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
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...
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...
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...
P2P RTC will impact the landscape of communications, shifting from traditional telephony style communications models to OTT (Over-The-Top) cloud assisted & PaaS (Platform as a Service) communication services. The P2P shift will impact many areas of our lives, from mobile communication, human interactive web services, RTC and telephony infrastructure, user federation, security and privacy implications, business costs, and scalability. In his session at Internet of @ThingsExpo, Robin Raymond, Chief Architect at Hookflash Inc., will walk through the shifting landscape of traditional telephone a...
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.
BSQUARE is a global leader of embedded software solutions. We enable smart connected systems at the device level and beyond that millions use every day and provide actionable data solutions for the growing Internet of Things (IoT) market. We empower our world-class customers with our products, services and solutions to achieve innovation and success. For more information, visit www.bsquare.com.
How do APIs and IoT relate? The answer is not as simple as merely adding an API on top of a dumb device, but rather about understanding the architectural patterns for implementing an IoT fabric. There are typically two or three trends: Exposing the device to a management framework Exposing that management framework to a business centric logic • Exposing that business layer and data to end users. This last trend is the IoT stack, which involves a new shift in the separation of what stuff happens, where data lives and where the interface lies. For instance, it’s a mix of architectural style...
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 SOA Software, an API management leader, 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. SOA Software is a leading provider of API Management and SOA Governance products that equip business to deliver APIs and SOA together to drive their company to meet its business strategy quickly and effectively. SOA Software’s technology helps businesses to accelerate their digital channels with APIs, drive partner adoption, monetize their assets, and achieve a...
SYS-CON Events announced today that Utimaco 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. Utimaco is a leading manufacturer of hardware based security solutions that provide the root of trust to keep cryptographic keys safe, secure critical digital infrastructures and protect high value data assets. Only Utimaco delivers a general-purpose hardware security module (HSM) as a customizable platform to easily integrate into existing software solutions, embed business logic and build s...
Connected devices are changing the way we go about our everyday life, from wearables to driverless cars, to smart grids and entire industries revolutionizing business opportunities through smart objects, capable of two-way communication. But what happens when objects are given an IP-address, and we rely on that connection, sometimes with our lives? How do we secure those vast data infrastructures and safe-keep the privacy of sensitive information? This session will outline how each and every connected device can uphold a core root of trust via a unique cryptographic signature – a “bir...
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...
Almost everyone sees the potential of Internet of Things but how can businesses truly unlock that potential. The key will be in the ability to discover business insight in the midst of an ocean of Big Data generated from billions of embedded devices via Systems of Discover. Businesses will also need to ensure that they can sustain that insight by leveraging the cloud for global reach, scale and elasticity.
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...