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
WebRTC defines no default signaling protocol, causing fragmentation between WebRTC silos. SIP and XMPP provide possibilities, but come with considerable complexity and are not designed for use in a web environment. In his session at Internet of @ThingsExpo, Matthew Hodgson, technical co-founder of the Matrix.org, will discuss how Matrix is a new non-profit Open Source Project that defines both a new HTTP-based standard for VoIP & IM signaling and provides reference implementations.

SUNNYVALE, Calif., Oct. 20, 2014 /PRNewswire/ -- Spansion Inc. (NYSE: CODE), a global leader in embedded systems, today added 96 new products to the Spansion® FM4 Family of flexible microcontrollers (MCUs). Based on the ARM® Cortex®-M4F core, the new MCUs boast a 200 MHz operating frequency and support a diverse set of on-chip peripherals for enhanced human machine interfaces (HMIs) and machine-to-machine (M2M) communications. The rich set of periphera...

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.
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...
SYS-CON Events announced today that Matrix.org has been named “Silver Sponsor” of Internet of @ThingsExpo, which will take place on November 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. Matrix is an ambitious new open standard for open, distributed, real-time communication over IP. It defines a new approach for interoperable Instant Messaging and VoIP based on pragmatic HTTP APIs and WebRTC, and provides open source reference implementations to showcase and bootstrap the new standard. Our focus is on simplicity, security, and supporting the fullest feature set.
Predicted by Gartner to add $1.9 trillion to the global economy by 2020, the Internet of Everything (IoE) is based on the idea that devices, systems and services will connect in simple, transparent ways, enabling seamless interactions among devices across brands and sectors. As this vision unfolds, it is clear that no single company can accomplish the level of interoperability required to support the horizontal aspects of the IoE. The AllSeen Alliance, announced in December 2013, was formed with the goal to advance IoE adoption and innovation in the connected home, healthcare, education, aut...
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...
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...
Software AG helps organizations transform into Digital Enterprises, so they can differentiate from competitors and better engage customers, partners and employees. Using the Software AG Suite, companies can close the gap between business and IT to create digital systems of differentiation that drive front-line agility. We offer four on-ramps to the Digital Enterprise: alignment through collaborative process analysis; transformation through portfolio management; agility through process automation and integration; and visibility through intelligent business operations and big data.
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.
Be Among the First 100 to Attend & Receive a Smart Beacon. The Physical Web is an open web project within the Chrome team at Google. Scott Jenson leads a team that is working to leverage the scalability and openness of the web to talk to smart devices. The Physical Web uses bluetooth low energy beacons to broadcast an URL wirelessly using an open protocol. Nearby devices can find all URLs in the room, rank them and let the user pick one from a list. Each device is, in effect, a gateway to a web page. This unlocks entirely new use cases so devices can offer tiny bits of information or simple i...
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?
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.
TechCrunch reported that "Berlin-based relayr, maker of the WunderBar, an Internet of Things (IoT) hardware dev kit which resembles a chunky chocolate bar, has closed a $2.3 million seed round, from unnamed U.S. and Switzerland-based investors. The startup had previously raised a €250,000 friend and family round, and had been on track to close a €500,000 seed earlier this year — but received a higher funding offer from a different set of investors, which is the $2.3M round it’s reporting."
The Industrial Internet revolution is now underway, enabled by connected machines and billions of devices that communicate and collaborate. The massive amounts of Big Data requiring real-time analysis is flooding legacy IT systems and giving way to cloud environments that can handle the unpredictable workloads. Yet many barriers remain until we can fully realize the opportunities and benefits from the convergence of machines and devices with Big Data and the cloud, including interoperability, data security and privacy.
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. Over the summer Gartner released its much anticipated annual Hype Cycle report and the big news is that Internet of Things has now replaced Big Data as the most hyped technology. Indeed, we're hearing more and more about this fascinating new technological paradigm. Every other IT news item seems to be about IoT and its implications on the future of digital busines...
Cultural, regulatory, environmental, political and economic (CREPE) conditions over the past decade are creating cross-industry solution spaces that require processes and technologies from both the Internet of Things (IoT), and Data Management and Analytics (DMA). These solution spaces are evolving into Sensor Analytics Ecosystems (SAE) that represent significant new opportunities for organizations of all types. Public Utilities throughout the world, providing electricity, natural gas and water, are pursuing SmartGrid initiatives that represent one of the more mature examples of SAE. We have s...
The Internet of Things needs an entirely new security model, or does it? Can we save some old and tested controls for the latest emerging and different technology environments? In his session at Internet of @ThingsExpo, Davi Ottenheimer, EMC Senior Director of Trust, will review hands-on lessons with IoT devices and reveal privacy options and a new risk balance you might not expect.
IoT is still a vague buzzword for many people. In his session at Internet of @ThingsExpo, Mike Kavis, Vice President & Principal Cloud Architect at Cloud Technology Partners, will discuss the business value of IoT that goes far beyond the general public's perception that IoT is all about wearables and home consumer services. The presentation will also discuss how IoT is perceived by investors and how venture capitalist access this space. Other topics to discuss are barriers to success, what is new, what is old, and what the future may hold.