Welcome!

ColdFusion Authors: Yakov Fain, Maureen O'Gara, Nancy Y. Nee, Tad Anderson, Daniel Kaar

Related Topics: ColdFusion, SOA & WOA, .NET

ColdFusion: Article

Crossing the .NET Divide: CFMX, Web Services, and .NET

ColdFusion Web service interoperability with .NET

Like it or not, .NET is proving a powerful force in the software industry. As a ColdFusion developer, you'll probably need to interact with it at some point in time.

One of the promises of .NET is that it can provide this interoperability through Web services. Although it's easy to send simple data to and from .NET Web services, a little bit of extra work on our end can make arrays, structures, and even queries work across the two platforms.

Quick Review: ColdFusion Web Services
This article is about ColdFusion Web service interoperability with .NET. It assumes a basic knowledge of how to create and consume Web services in ColdFusion. A brief review may help everyone get on the same page.

Web services use XML to provide remote procedure calls, or services, in a platform- and language-agnostic environment. By using the XML document Web Services Definition Language (WSDL), they describe how they work in a common, agreed-on format. When they communicate, data is sent in another XML format called Simple Object Access Protocol (SOAP).

Although WSDL and SOAP are both fairly complicated, creating and consuming Web services in ColdFusion couldn't be easier! To create a service, create a ColdFusion component (CFC) file in a Web-accessible directory. Give it at least one function (or method), being sure to specify its return type and that its access attribute is set to remote. If the method has arguments, you must also specify the data type of those arguments. The following code shows a very simple ColdFusion Web service that returns a simple string:


<cfcomponent>
  <cffunction name="getString"
    returntype="string"
    access="remote">
    <cfreturn "Hello, world!">
  </cffunction>
</cfcomponent>

After creating your CFC, it will be available as a Web service at http://<servername>/<path>/<filename>?WSDL. For example, if the code from the previous example was in "sampleService.cfc" under the root on your local machine, it would be available as a Web service at http://localhost/sampleService.cfc?WSDL.

Consuming a Web service from ColdFusion is just as simple. In fact, it only takes one line of code. The following code shows how to consume and then display the results of our CFC from the previous example. In this example, we use the CFInvoke tag to both instantiate and call a method of our sample Web service. We then output the result in a standard CFOutput block:


<cfinvoke
  webservice="http://localhost/
    sampleService.cfc?WSDL"
	method="getString"
	returnvariable="result">
<cfoutput>#result#</cfoutput>

Now that we've reviewed creating and consuming Web services in ColdFusion, let's move on to creating Web services that can be consumed by .NET clients.

Providing Data to .NET Through Web Services
When you build a Web service in ColdFusion, the "returnType" attribute of the CFFunction tag states what type of data the Web service will be returning. The language Web services uses to communicate (SOAP), describes these return types using XML. ColdFusion automatically creates this XML when your CFC is accessed as a Web service. It is up to the client software to interpret this XML and create variables it can "understand" from the data returned by your Web service.

Sending Simple Values to .NET
ColdFusion is considered a typeless language, and simple values are the variables that fall into this "typeless" category. An easy way to think of simple values is that they can be directly printed to a page using a CFOutput block. For example, you can directly output a date inside a CFOutput tag, but not a query: A date is a simple value, but a query is not.

Lucky for us, .NET understands all of the simple ColdFusion return types without a hitch. This means that any Web service method returning these types can be understood by .NET without any changes. Table 1 shows the .NET data types that the results of your ColdFusion Web services will be translated into.

You'll notice that three of the most powerful ColdFusion data types aren't listed in Table 1: arrays, structures, and queries. These are three of the complex data types available in ColdFusion. It's when we use ColdFusion Web services to send complex data types to .NET that we begin to encounter trouble.

Sending Simple Arrays to .NET
ColdFusion arrays and .NET arrays are very different, and the technical details of these differences are beyond the scope of this article. What is relevant, however, is that .NET does not translate a ColdFusion array sent over a Web service back into a native .NET array. Instead, .NET interprets them as its generic "object" type.

As long as your array contains simple values, you're in the clear. A .NET developer can easily loop over your result in the .NET equivalent of a collection-based CFLoop to extract the data. The following example shows the VB.NET code to do this:


For Each i In CFArrayResult
	Response.Write("i: " & i)
Next

We'll tackle complex arrays, such as arrays of structures, after we've first taken a look at how a structure can be sent to .NET

Sending Structures to .NET
Presently, ColdFusion structures do not translate to .NET. If you send a structure to .NET through a ColdFusion Web service, the .NET developer receives nothing but an empty object. However, Macromedia has provided a solution to this through CFCs.

To return a structure to .NET, you create a "definition" CFC that will represent the structure and its data. Each member of the structure needs a corresponding CFProperty tag in the definition CFC.

Instead of returning a structure, you first create an instance of the CFC. Then, use CFSet tags to set its properties to their corresponding values in your structure. Last, you return the instance of the CFC instead of your structure. It's important to note that you need to change the returntype of your CFFunction tag from "structure" to the (package) name of the CFC you're returning.

In Listing 1, we take a look at how to do this. It first shows our definition CFC (employee.cfc) that represents an "employee" structure. Then, we have a Web service (employeeService.cfc) that creates the structure, translates it into the employee CFC, and returns the CFC.

When the definition CFC is returned to .NET, .NET sees it as a type named after the interface component. In other words, the employee CFC returned in Listing 1 would be seen as an "Employee" object having directly accessible properties named EmployeeId, Firstname, and Lastname. On the .NET side, if the result was stored in a variable called "myEmployee," the employee's first name would be accessible as "myEmployee.Firstname." This is exactly as it would be in a ColdFusion structure.

Combining Arrays and Structures
By combining what we've seen of sending arrays and structures to .NET, it's simple to send more complex arrays or structures to .NET. For example, if you want to send an array of structures back to .NET, you first create an array and then populate it with CFC instances that hold the structure data. In Listing 2, an array named "result" is created, and each member of this array is an instance of our employee CFC. We then return the entire array.

On the .NET side, we first store the result in an object named "employees." Then, we loop over the members of the employee object with each being an instance of an employee. Knowing that the individual employee's data is stored in directly accessible properties, we can then print it out using simple "dot-syntax."

Queries: XML to the Rescue!
After covering arrays and structures, it should be easy enough to send queries to .NET. We could represent the entire query as an array, with each row using a facade CFC. Believe it or not, we can do better by returning ColdFusion queries in a format .NET already understands.

First, let me give you some background. The .NET equivalent of a ColdFusion query is called a DataSet. It's part of ADO.NET, which is the portion of .NET that deals with databases. DataSets are XML representations of database schemas. They can hold multiple queries, maintain relationships between the queries, and perform a slew of automated database tasks.

From a ColdFusion perspective, what's great about DataSets is that we can easily create XML that a .NET client can turn into a DataSet. Listing 3 shows an example of XML that can be used to create a .NET data set. You'll see that it's fairly simple. A root-level tag defines a "table" named books, with each "book" node describing a row in that table. Inside each book node, we describe each column. In this case, the columns are the "author" and "title" nodes.

Using ColdFusion MX's XML support, we can easily turn a query into this type of XML and return it to .NET as a string. To help out, I've created a user-defined function (UDF) that transforms queries into exactly this format of XML. This UDF is part of a utility CFC I've created called QueryTool, available on www.CFCZone.org or my site at: www.clearsoftware.net/client/queryTool.cfm. Listing 4 shows an entire solution for creating a query, transforming it to XML using this UDF, returning the XML, and finally the VB.NET client code for creating a DataSet from the result.

Compatibility and Performance
I imagine some of you are wondering how these changes to your ColdFusion Web services affect both performance and compatibility with existing ColdFusion-based clients. Tasks such as translating queries to XML are costly, and they should be performed only when necessary.

In my own applications, I'm using a two-tier approach to provide data to both ColdFusion and .NET clients. The first tier consists of a CFC with no modifications for .NET compatibility. ColdFusion applications can then call this component and its Web services with no changes. The second tier is also a CFC, used solely to provide data to .NET. It does this by instantiating the first-tier CFC as a component, calling the appropriate method, and then performing any necessary .NET-specific translations on the result. This way, any performance drains such as translating queries to XML only impact .NET clients, and I maintain compatibility with existing ColdFusion clients.

Consuming Data from .NET Web Services
Similar to ColdFusion, .NET makes it very easy to create Web services. Also similar to ColdFusion, it has no reservations about returning data in its own proprietary formats, like the DataSet.

Because of these differences in architecture, consuming .NET Web services is more difficult than consuming native ColdFusion Web services. In this section, we'll take a look at how to consume the various types of data returned by .NET Web services.

Consuming Simple Types
Again, ColdFusion and .NET see eye to eye on simple data types. The .NET string type, its various numeric types, and its date type all translate to their ColdFusion equivalents automatically. This means that consuming a .NET Web service that returns a simple value is no different than consuming an equivalent ColdFusion Web service.

Consuming .NET Arrays
When dealing with arrays, things get a little more complicated. Before we look at how to consume a .NET array, we need to understand a fundamental difference between .NET and ColdFusion. ColdFusion is typeless, whereas .NET is a typed, object oriented environment. This means that every .NET variable is of a specific type, and all of those types inherit from a root "object" class.

For ColdFusion, this means that any complex data type sent over a .NET Web service will not be automatically translated into its ColdFusion equivalent. Instead, it will be translated into a Java object. This Java object will have various properties and methods, just like a CFC or COM object. You can CFDump the resultant object at any time to get a list of its properties and methods. If any of you have ever returned a CFC from a Web service, this should look very familiar.

Now that you know this, if you're calling a .NET Web service that you think returns an array, don't be surprised when your result is an object. Unlike ColdFusion arrays, .NET arrays are of a specific type, meaning that each element of the array is of the same type. Simple arrays can be arrays of strings, numbers, or even raw bytes. Elements in more complex arrays can contain any type of object.

If you CFDump the result of a .NET Web service returning an array, the object you receive will contain a method called "Get<type>()." In this, "<type>" is replaced by the name of the type of array you're expecting, such as "GetString()." If you call this method, the result is the native ColdFusion array you'd expect from a ColdFusion-based Web service. For a more complex example, if you expected a .NET Web service to return an array of our employee structures/objects, you'd look for a method called "GetEmployee()." This is because you're looking for an array of the employee type.

Consuming .NET Structures
Now that we know that complex data returned by .NET will be represented as Java objects, we can explore how to consume .NET's equivalent of a structure. It's actually very easy. If you've ever used a ColdFusion Web service that returns a CFC, it should be familiar territory. When you CFDump the result of a .NET Web service that returns an enumeration or other similar class, you'll see a number of "get" and "set" methods. These work like their equivalents in a ColdFusion Web service returning a CFC instance. As we're concerned with consuming, it's the "get" methods we're interested in.

If we consume the .NET equivalent of our ColdFusion GetEmployee Web service, we'd see a Java object with methods named "GetFirstname," "GetLastname," and "GetEmployeeId." Calling these would then return the Firstname, Lastname, and EmployeeId values or "properties" of this object. If we stored our result in a variable named "employee" and wanted to print out the employee's first name, we could reference it as #employee.GetFirstname()#.

Consuming .NET DataSets
.NET's database interaction library, ADO.NET, uses what is called a DataSet. A DataSet is more than a query. It's an in-memory representation of a database schema. A DataSet can contain multiple tables and maintain relations between those tables. Each one of those tables can be thought of as an individual query.

What makes DataSets interoperable is that .NET uses XML to represent them. When calling a .NET Web service that returns a DataSet, exploration of the result leads to the discovery of a getAny() method. This method returns an array of objects representing the schema and data contained in a DataSet. These objects, in turn, have methods that expose their underlying XML. With a little bit of work, we can use ColdFusion MX's native XML support to translate this XML into ColdFusion queries.

Again, I've created a UDF for dealing with .NET DataSets. Listing 5 shows both the UDF and an example of its use. This UDF can be downloaded from my Web site: www.clearsoftware.net/client/convertDotNetDataset.cfm. Because DataSets can contain multiple queries, my implementation returns a structure. Each member of the structure is a query named after the table's name in the .NET DataSet.

Conclusion
As more software development moves toward Service-Oriented Architecture (SOA), it's important to ensure that ColdFusion is interoperable with other development platforms. Although some things are out of our control (e.g., the changing Web service standards), I hope this article has shown you that it's fairly easy to move data between ColdFusion and .NET via Web services. ColdFusion can be an important player in your service-oriented application, both as a client and service provider.

Supplemental Code
A complete example of interoperable ColdFusion MX and .NET Web services, along with client code, is available at: www.sys-con.com/coldfusion/sourcec.cfm

More Stories By Joe Rinehart

Joe Rinehart is a Flex, ColdFusion, and J2EE developer. You can find his blog at Firemoss.com.

Comments (6)

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.


@ThingsExpo Stories
Samsung VP Jacopo Lenzi, who headed the company's recent SmartThings acquisition under the auspices of Samsung's Open Innovaction Center (OIC), answered a few questions we had about the deal. This interview was in conjunction with our interview with SmartThings CEO Alex Hawkinson. IoT Journal: SmartThings was developed in an open, standards-agnostic platform, and will now be part of Samsung's Open Innovation Center. Can you elaborate on your commitment to keep the platform open? Jacopo Lenzi: Samsung recognizes that true, accelerated innovation cannot be driven from one source, but requires a...
The Internet of Things will greatly expand the opportunities for data collection and new business models driven off of that data. In her session at Internet of @ThingsExpo, Esmeralda Swartz, CMO of MetraTech, will discuss how for this to be effective you not only need to have infrastructure and operational models capable of utilizing this new phenomenon, but increasingly service providers will need to convince a skeptical public to participate. Get ready to show them the money! Speaker Bio: Esmeralda Swartz, CMO of MetraTech, has spent 16 years as a marketing, product management, and busin...
SYS-CON Events announced today that TeleStax, the main sponsor of Mobicents, will exhibit at Internet of @ThingsExpo, which will take place on November 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. TeleStax provides Open Source Communications software and services that facilitate the shift from legacy SS7 based IN networks to IP based LTE and IMS networks hosted on private (on-premise), hybrid or public clouds. TeleStax products include Restcomm, JSLEE, SMSC Gateway, USSD Gateway, SS7 Resource Adaptors, SIP Servlets, Rich Multimedia Services, Presence Services/RCS, Diame...
Things are being built upon cloud foundations to transform organizations. This CEO Power Panel at 15th Cloud Expo, moderated by Roger Strukhoff, Cloud Expo and @ThingsExpo conference chair, will address the big issues involving these technologies and, more important, the results they will achieve. How important are public, private, and hybrid cloud to the enterprise? How does one define Big Data? And how is the IoT tying all this together?
We certainly live in interesting technological times. And no more interesting than the current competing IoT standards for connectivity. Various standards bodies, approaches, and ecosystems are vying for mindshare and positioning for a competitive edge. It is clear that when the dust settles, we will have new protocols, evolved protocols, that will change the way we interact with devices and infrastructure. We will also have evolved web protocols, like HTTP/2, that will be changing the very core of our infrastructures. At the same time, we have old approaches made new again like micro-services...
The only place to be June 9-11 is Cloud Expo & @ThingsExpo 2015 East at the Javits Center in New York City. Join us there as delegates from all over the world come to listen to and engage with speakers & sponsors from the leading Cloud Computing, IoT & Big Data companies. Cloud Expo & @ThingsExpo are the leading events covering the booming market of Cloud Computing, IoT & Big Data for the enterprise. Speakers from all over the world will be hand-picked for their ability to explore the economic strategies that utility/cloud computing provides. Whether public, private, or in a hybrid form, clo...
SYS-CON Events announces a new pavilion on the Cloud Expo floor where WebRTC converges with the Internet of Things. Pavilion will showcase WebRTC and the Internet of Things. The Internet of Things (IoT) is the most profound change in personal and enterprise IT since the creation of the Worldwide Web more than 20 years ago. All major researchers estimate there will be tens of billions devices--computers, smartphones, tablets, and sensors – connected to the Internet by 2020. This number will continue to grow at a rapid pace for the next several decades.
SYS-CON Events announced today that Gridstore™, the leader in software-defined storage (SDS) purpose-built for Windows Servers and Hyper-V, will exhibit at SYS-CON's 15th International Cloud Expo®, which will take place on November 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. Gridstore™ is the leader in software-defined storage purpose built for virtualization that is designed to accelerate applications in virtualized environments. Using its patented Server-Side Virtual Controller™ Technology (SVCT) to eliminate the I/O blender effect and accelerate applications Gridsto...
SYS-CON Events announced today that Red Hat, the world's leading provider of open source solutions, will exhibit at Internet of @ThingsExpo, which will take place on November 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. Red Hat is the world's leading provider of open source software solutions, using a community-powered approach to reliable and high-performing cloud, Linux, middleware, storage and virtualization technologies. Red Hat also offers award-winning support, training, and consulting services. As the connective hub in a global network of enterprises, partners, a...
As the Internet of Things unfolds, mobile and wearable devices are blurring the line between physical and digital, integrating ever more closely with our interests, our routines, our daily lives. Contextual computing and smart, sensor-equipped spaces bring the potential to walk through a world that recognizes us and responds accordingly. We become continuous transmitters and receivers of data. In his session at Internet of @ThingsExpo, Andrew Bolwell, Director of Innovation for HP’s Printing and Personal Systems Group, will discuss how key attributes of mobile technology – touch input, senso...
The Internet of Things (IoT) is making everything it touches smarter – smart devices, smart cars and smart cities. And lucky us, we’re just beginning to reap the benefits as we work toward a networked society. However, this technology-driven innovation is impacting more than just individuals. The IoT has an environmental impact as well, which brings us to the theme of this month’s #IoTuesday Twitter chat. The ability to remove inefficiencies through connected objects is driving change throughout every sector, including waste management. BigBelly Solar, located just outside of Boston, is trans...
Connected devices and the Internet of Things are getting significant momentum in 2014. In his session at Internet of @ThingsExpo, Jim Hunter, Chief Scientist & Technology Evangelist at Greenwave Systems, will examine three key elements that together will drive mass adoption of the IoT before the end of 2015. The first element is the recent advent of robust open source protocols (like AllJoyn and WebRTC) that facilitate M2M communication. The second is broad availability of flexible, cost-effective storage designed to handle the massive surge in back-end data in a world where timely analytics...
Internet of @ThingsExpo Silicon Valley announced on Thursday its first 12 all-star speakers and sessions for its upcoming event, which will take place November 4-6, 2014, at the Santa Clara Convention Center in California. @ThingsExpo, the first and largest IoT event in the world, debuted at the Javits Center in New York City in June 10-12, 2014 with over 6,000 delegates attending the conference. Among the first 12 announced world class speakers, IBM will present two highly popular IoT sessions, which will take place November 4-6, 2014 at the Santa Clara Convention Center in Santa Clara, Calif...
The Internet of Things (IoT) promises to evolve the way the world does business; however, understanding how to apply it to your company can be a mystery. Most people struggle with understanding the potential business uses or tend to get caught up in the technology, resulting in solutions that fail to meet even minimum business goals. In his session at Internet of @ThingsExpo, Jesse Shiah, CEO / President / Co-Founder of AgilePoint Inc., will show what is needed to leverage the IoT to transform your business. He will discuss opportunities and challenges ahead for the IoT from a market and tec...
From a software development perspective IoT is about programming "things," about connecting them with each other or integrating them with existing applications. In his session at @ThingsExpo, Yakov Fain, co-founder of Farata Systems and SuranceBay, will show you how small IoT-enabled devices from multiple manufacturers can be integrated into the workflow of an enterprise application. This is a practical demo of building a framework and components in HTML/Java/Mobile technologies to serve as a platform that can integrate new devices as they become available on the market.
SYS-CON Events announced today that O'Reilly Media has been named “Media Sponsor” of SYS-CON's 15th International Cloud Expo®, which will take place on November 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. O'Reilly Media spreads the knowledge of innovators through its books, online services, magazines, and conferences. Since 1978, O'Reilly Media has been a chronicler and catalyst of cutting-edge development, homing in on the technology trends that really matter and spurring their adoption by amplifying "faint signals" from the alpha geeks who are creating the future. An...
The Transparent Cloud-computing Consortium (abbreviation: T-Cloud Consortium) will conduct research activities into changes in the computing model as a result of collaboration between "device" and "cloud" and the creation of new value and markets through organic data processing High speed and high quality networks, and dramatic improvements in computer processing capabilities, have greatly changed the nature of applications and made the storing and processing of data on the network commonplace.
SYS-CON Events announced today that Aria Systems, the recurring revenue expert, has been named "Bronze Sponsor" of SYS-CON's 15th International Cloud Expo®, which will take place on November 4-6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. Aria Systems helps leading businesses connect their customers with the products and services they love. Industry leaders like Pitney Bowes, Experian, AAA NCNU, VMware, HootSuite and many others choose Aria to power their recurring revenue business and deliver exceptional experiences to their customers.
The Internet of Things (IoT) is going to require a new way of thinking and of developing software for speed, security and innovation. This requires IT leaders to balance business as usual while anticipating for the next market and technology trends. Cloud provides the right IT asset portfolio to help today’s IT leaders manage the old and prepare for the new. Today the cloud conversation is evolving from private and public to hybrid. This session will provide use cases and insights to reinforce the value of the network in helping organizations to maximize their company’s cloud experience.
As a disruptive technology, Web Real-Time Communication (WebRTC), which is an emerging standard of web communications, is redefining how brands and consumers communicate in real time. The on-going narrative around WebRTC has largely been around incorporating video, audio and chat functions to apps. In his session at Internet of @ThingsExpo, Alex Gouaillard, Founder and CTO of Temasys Communications, will look at a fourth element – data channels – and talk about its potential to move WebRTC beyond browsers and into the Internet of Things.