Home / Articles / Adobe ColdFusion / My Favorite Features in ColdFusion 10

My Favorite Features in ColdFusion 10

Article Description

Are you a ColdFusion user who hasn't upgraded to ColdFusion 10? Or perhaps you have, but still haven't really dug into what's new. In this article, Adobe evangelist Raymond Camden introduces you to some of his favorite new features in the latest version of ColdFusion.

With every new release of ColdFusion, developers find numerous new features added to the program. The ColdFusion team typically works with two to three main areas or themes when adding new features. This drives the “spirit” and direction of most of the high level features for the product. While the ColdFusion engineers certainly have their idea of what’s the most important updates in ColdFusion 10, I share what I think are the most important updates. While it’s certainly a personal list, I hope this list excites existing ColdFusion developers who haven’t made the leap to 10 yet, as well as others looking for a new way to build their back-end applications. Ready? Let’s go!

Security Enhancements

The unfortunate truth is that—for many—security is an afterthought of their web application. An average user will build his or her site and then look it over for possible security problems. If it isn’t obvious by now, this is an incredibly bad idea. Security is something that has to be in your mind before, during, and after the development of your application. ColdFusion has always tried its best to help developers build more secure applications. ColdFusion 10 is no exception to this.

One of the first things you will notice about ColdFusion 10 is that the installer itself prompts you to lock down your server. The new “Secure Profile” option available during installation will preset multiple settings in your server to help lock down and prevent common problems (see Figure 1).

To be clear, this isn’t a replacement for properly locking down your server, but it goes a long way in preparing your server to be more secure immediately after installation. Many options are configured when this setting is enabled, but some of the more important ones are:

  • Custom templates appear for both missing CFM files as well as a site-wide error handler.
  • Datasource connections are set so that Create, Drop, Alter, Grant, Revoke, and Stored Procedures are disabled.
  • Robust exceptions are disabled.

That last item in particular is one that many users forget about when setting up a production server. Robust exceptions are great for debugging, but on a live website, they can be disastrous due to the amount of information they reveal publicly.

Currently there is no way to re-run the secure profile after installation, but you have a few options. First, I’ve released an open-source ColdFusion Administrator extension that reports on the same settings used by the secure profile. This extension gives you a one-page report on these settings and if they are in a secure state or not. You can download that extension. Another option is the incredibly detailed ColdFusion 10 Lockdown Guide (PDF), written by Pete Freitag.

Another area where ColdFusion 10 improves security is in enhanced XSS protection. XSS, or cross-site scripting, is one of the most common vectors for attack on a website. For a long time now, ColdFusion has provided the htmlEditFormat and htmlCodeFormat functions as a simple way to prevent XSS. Both of these functions would escape < and > characters, and were (typically) enough to get the job done.

ColdFusion 10 expands upon this by adding six new functions:

  • encodeForCSS
  • encodeForHTML
  • encodeForHTMLAttribute
  • encodeForJavaScript
  • encodeforURL
  • encodeForXML

As you can guess, each of these functions helps prevent XSS attacks, but they are specifically tailored to how you intend to use the result. Let’s say you have a bit of user-provided input that will be used inside an HTML tag’s attribute. You would use the encodeForHTMLAttribute function. Now let’s say you have another bit of input that will help drive some dynamic CSS. As you can guess, you would use encodeForCSS. Here is a simple example:

<cfparam name=”url.class” default=””>
<cfoutput>
<div id=”content” class=”#encodeForHTMLAttribute(url.class)#”>
Some content with a dynamic class applied to it.
</div>
</cfoutput>

That’s a pretty trivial example, but you get the idea. Instead of one global function that may not properly handle where the output is being used, you now have six very specific handlers for your dynamic web pages.

Syntax Sugar

Syntax Sugar

Syntax Sugar, or language enhancements, is one of these things that don’t often get a lot of attention, but can make the life of a developer a heck of a lot easier. Some of my favorite aspects of ColdFusion 10 are the small little changes made to the syntax.

As an example, for a few versions now ColdFusion has support implicit notation for arrays and structs. So instead of doing:

<cfset arr = arrayNew(1)>
<cfset arr[1] = “Stroz”>
<cfset arr[2] = “Sharp”>
<cfset arr[3] = “Ferguson”>
<cfset beer = structNew()>
<cfset beer.isGood = “heck yes”>

you can do this:

<cfset arr = [“Stroz”, “Sharp”, “Ferguson”]>
<cfset beer = {isGood = “heck yes”}

While this was really nice, you may notice that the implicit struct notation doesn’t follow the typical JSON-like format that the array example did. Instead of key:value, we have key=value. Now you can use either format in ColdFusion 10:

<cfset beer = {isGood:”heck yes”}>

And obviously this works in script-notation as well:

beer = {isGood:”heck yes”};

If you find yourself writing a lot of JavaScript, then you’ve probably used the colon by mistake before. Now you don’t need to worry about it.

Speaking of script notation, you can now use the cfsetting and cfinclude tags directly in your script-based code. For example:

component {
  setting showdebugoutput=”false”;
  include “settings.inc”;
}

While we’re talking about cfinclude, you can also use the new runonce attribute to ensure a particular file is only included one time:

<cfinclude template=”something.cfm” runonce=”true”>

Another simple addition may have limited used in production, but is extremely helpful during testing and experimenting. For years now, developers have been able to create a query object by hand, rather than by SQL, by using queryNew and queryAddRow. This could be useful for times when you need to make a database query to a server you do not have access to yet. While powerful, it was very verbose. Here is a simple example:

<cfset teams = queryNew(“id,name”,”integer,varchar”)>
<cfset queryAddRow(teams, 1)>
<cfset querySetCell(teams, “id”, 1, 1)>
<cfset querySetCell(teams, “name”, “Saints”, 1)>
<cfset queryAddRow(teams, 1)>
<cfset querySetCell(teams, “id”, 1, 2)>
<cfset querySetCell(teams, “name”, “Giants”, 2)>

In ColdFusion 10, both queryNew and queryAddRow have been modified to let you specify data immediately, using implicit array and struct notation. Here’s the same code using the new feature:

<cfset teams = queryNew(“id,name”,”integer,varchar”,[{id:1,name:”Saints”}, {id:2,name:”Giants”}]>

Appending another row is also easier:

<cfset queryAddRow(teams, {id:3, name:”Texans”})>

While it’s not something you may use every day, it’s still an incredibly helpful addition.

The final language enhancements I’ll mention are closures and inline functions. For folks used to writing JavaScript code, this will be intimately familiar. Your ColdFusion code can now create closures and return functions as proper first-class citizens in the language. Multiple existing functions have also been updated to allow for inline functions as well. Because this is where most folks will make use of this feature, let’s look at an example now. Imagine you need to iterate over an array. This is how you would typically do it:

for(var i=1; i<arrayLen(someArray); i++) {
  writeoutput(“lets do something with “ & someArray[i] & “<br/>”);
}

Not too hard, but ColdFusion 10 adds a new arrayEach function that simplifies this a bit:

arrayEach(someArray, function(i) {
    writeoutput(“lets do something with “ & i & “<br/>”);
});

The end result is the same, but depending on your personal preference, you may find the inline version much easier to use. Obviously, you could also define those functions ahead of time and pass them in as well:

function printer(x) {
  writeoutput(“lets do something with “ & i & “<br/>”);
}
arrayEach(someArray, printer);

Another useful version of this is the ability to filter arrays. Imagine an array of teams:

<cfset teams = [{name:”Saints”,wins:9}, {name:”Giants”,wins:12}, {name:”Cowboys”,wins:3}]>

I want to filter this array using business logic to determine who is going to the playoffs. The logic is simple: You must have had at least 10 wins or your name must be the Saints. (Sorry, I may be a bit biased.) Here is how you could do this using the new arrayFilter function:

goingToFinals = arrayFilter(teams, function(t) {
  return t.wins >= 10 || t.name eq “Saints”;
});

This would return an array consisting of the Saints and the Giants (see Figure 2).

You can find similar enhancements for ColdFusion structs and lists as well!

WebSockets

WebSockets

I’ve spent the last few years working hard to improve my client-side chops. While I’ve mainly been focused on getting better at JavaScript in general, I’ve also been interested in data handling in the abstract—both the storage of data on the client side as well as the ways in which we can send data back and forth. One of the things I learned early on is that AJAX is not a silver bullet for applications. (I learned that the hard way when I thought it would be ok to send 700KB of XML data back and forth on every request. Spoiler alert—it wasn’t.)

As one of the most interesting features that fall under the HTML5 umbrella, WebSockets provide a way for your applications to share data in a much more real-time format then traditional “polling” style AJAX-applications.

In the past, if you wanted to inform the user that something has happened of importance on the server, your code needed to ping the server constantly, asking it if it had new data. With WebSockets, you can now create an “open channel” between the client and the server, allowing for instantaneous updates.

Of course, not all browsers support this hip new technology. The good news is that the WebSocket implementation in ColdFusion 10 is backwards-compatible with Flash. If you hit a ColdFusion 10 web application making use of WebSockets with an incompatible browser, then you will be served up a version with Flash. What’s nice is that your code doesn’t have to change at all. You can also gracefully handle people who don’t support WebSockets or Flash by at least providing them with a message.

In general, WebSockets in ColdFusion is added to a page by making use of the <cfwebsocket> tag. This handles setting up some initial JavaScript libraries and (possibly) initializing a connection for you. To begin, though, you first enable a WebSocket channel in your Application.cfc file:

component {
  this.name = “somedemo”;
  this.wschannels = [{name:”chat”}];
}

You can name your WebSocket channels as you wish, and obviously have as many as you would like as well. Now that you’ve enabled WebSockets, let’s look at a simple example of a chat application. There’s a bit of code here, so just try to take it slow and I’ll explain it in parts.

<cfwebsocket name="mywebsocket" onMessage="msgHandler" subScribeTo="chat">
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script>
var chatblock;
$(document).ready(function() {
	chatblock = $("#chatblock");
	$("#sendBtn").on("click", function(e) {
		e.preventDefault();
		var msg = $("#message").val();
		mywebsocket.publish("chat", msg);
	});
});
function msgHandler(msg){
	if(msg.type === "data") {
		chatblock.append(msg.data + "<br/>");
	}
}
</script>
</head>
<body>
<input type="text" id="message"> 
<input type="button" value="Send Msg" id="sendBtn">
<div id="chatblock"></div>
</body>
</html>

Starting at the top, the <cfwebsocket> tag does a few things. First, it flags ColdFusion to automatically include WebSocket-related JavaScript files in the response. Secondly, it creates a top-level JavaScript variable I can use to interact with the WebSocket. Next, it defines the name of a handler that will receive messages. Finally, it automatically subscribes to a channel. All of this can be tweaked, and there are more options available to the tag.

In essence, the tag is simply handling the initial JavaScript setup. The rest of the code is entirely client-side. I’ve built an incredibly simple, and ugly, chat demo. You’ve got a text field and a button. Entering text into the field and clicking the button will send the message. You can see this in the following API call:

mywebsocket.publish(“chat”, msg);

In case you’re curious, your messages are not limited to simple strings. Anything that JavaScript can encode with JSON can be sent.

The message handler is used to report chats from other users. Now, one thing you discover right away with ColdFusion WebSockets is that many messages are sent. For example, you get a message when you successfully subscribe to a channel. So I’ve got a bit of code there that inspects the object and only considers some messages as, well, messages I want to display.

The result is that you, and any other user of the app, can enter messages and they will appear in all browsers, instantaneously! While it’s clearly a simple demo, I hope you can see the power that this provides for client-side applications. You can also use server-side handlers to help with security and message formatting as well.

Conclusion

Conclusion

I hope that this short list of ColdFusion 10 features has gotten you excited about the update. There is a heck of a lot more to ColdFusion 10. I encourage you to download the server today (it costs nothing to run in development) at adobe.com/go/coldfusion.