You will be redirected in 30 seconds or close now.

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

Related Topics: ColdFusion

ColdFusion: Article

Creating Configuration Files

Make your work cleaner and easier to maintain

In their book Head First Design Patterns, the four coauthors lay out a series of key principles for creating robust software designs. One of the most important of these principles is "Find what varies and encapsulate it." In this article, let's apply this principle to the use of configuration files and explore the support for old-style .INI files and XML files.

"Find what varies and encapsulate it" is what most of us do for a living. The heart of any programming language is a variable - a name/value pair. Although we programmers are so used to a variable that it seems the most natural of things, people without a programming background don't find it natural at all.

What Exactly Is a Variable?

I learned this several years ago when my son was working on a presentation he would have to give to his fifth-grade class. At the time, he was working with a video game called "RPG Maker" (a devilishly clever introduction to computer programming that masquerades as a game) and he decided that he would explain the very basic underpinnings of computer programming languages.

"Hey, Dad - how would you explain a variable?"

"A variable? Well, that's simple. A variable is something whose actual value may change over time. Take, for example, the notion of where you live - a notion we might call homeAddress. Now, the value of homeAddress may change (if you move from one house to another) but the idea of homeAddress is permanent.

And that's a variable."

Sometimes, I just have a way of making hard things seem simple. It's a gift.

Our son tried out his presentation on my wife. Susie isn't a programmer, but she works for IBM and so some computer basics must have worked its way into her, right?

She stared blankly at our son trying to explain how the idea of your homeAddress is the same even though it may change - your home address, the value, not the idea (which stays the same). Or something.

I went to hear his presentation to his classmates and it was pretty clear that the idea of variables wasn't having any better success with them than it had with his mom.

And there's an epilogue to this story. Some time later, Steve Nelson (of Fusebox fame) and I were discussing some Fusebox-related matters and I happened to tell him the story of how my "homeAddress" example crashed and burned. As you would expect of a friend, Steve was properly sympathetic.

"Hal, you're an idiot," he began. "Don't use abstract terms when trying to explain things to people. Give them something they can touch and see."

"Like what?" I asked.

Steve was drinking a Coke at the time in a clear plastic bottle. "You see this bottle? That's the variable. See the Coke inside it? That's the value."

He poured out the remaining liquid and dropped a pencil into the bottle. "Same variable, but different value."

Hmmm...in his obviously simplistic way, which left out many important nuances, he did seem to have a point. Now, it was my job to crush Steve's argument underfoot so that I would emerge victorious!

"All right, smart guy," I said. "How would you explain - an array?"

Steve stopped. It seemed that victory was mine. "An array?" he said. "Well...that's a six-pack!"

Variables in Applications

This month, I want to apply the "find what varies and encapsulate it" principle within a broader context - that of entire applications.

Almost every application of moderate size or more has certain pieces of information that the code relies on. Here are some examples:

  • dsn
  • log_file_path
  • expiration_date
  • banner_image
  • verbose_messages
  • required_score
  • admin_email
  • company_name
In each of these cases, the data is specific to a particular installation, so that the only thing different about installation A from installation B is that the dsn or the company_name or the decision to turn verbose messages on or off (etc.) is different. We have, in other words, a variable.

But where should this information be stored? It might be stored in a database. Sometimes, though, this isn't a good option. It may be that there is no login that would identify a particular user. Or it may be that the information needs to be maintained by non-programmers and no user-friendly interface to a database exists. And If the needed information is so simple that a database isn't required - or so complex that modeling in a database is difficult - a better solution may be a configuration file.

Two types of configuration file have found widespread acceptance in the programming world. The first is a bit of "old school" - the INI file. First popularized by Microsoft, the ini file has a specific, simple format:

keyname=value, value, value ;used when a keyname has multiple values

Section- and keynames cannot contain spaces and are case-insensitive. So, a sample INI file might look like this:

company_name =Widget Masters
verbose_messages = true

Notice the slight inconsistencies of treatment of spaces by the equal sign. Part of the INI specification is that parsers should be liberal in their application of rules.

How do we make use of INI files? We'll need to be able to both read and write to these files and ColdFusion makes it easy to do both of these. Let's first take the case of reading an INI file. We'll use the one shown above as our example. To read one of the name/value pairs - say, company_name - we'll use ColdFusion's GetProfileString function.

	<h2>Welcome to #GetProfileString(ExpandPath('Sample.ini'), 'Configuration',

How do we get the value of "Widget Masters" into the INI file? Usually, these files are edited by hand, but ColdFusion allows you to edit them programatically. In this example, I'll add a new name/value pair to Sample.ini.

<cfset SetProfileString(ExpandPath('Sample.ini'), 'Configuration', 'required_score', 90) />

	<cfif variables.score LT GetProfileString(ExpandPath('Sample.ini'), 'Configuration',
		Have you considered a career in the arts?
		OK, now you can receive the secret Java decoder ring.

If you're wondering why you would need to set an INI file programatically, consider that this file can be used to determine the next numbered item in a sequence - an order number or customer number for example. To do this, you get, then immediately set, the number stored in the INI file.

<cfset invoice = GetProfileString(ExpandPath('Sample.ini'), 'Configuration', 'last_invoice') />
<cfset SetProfileString(ExpandPath('Sample.ini'), 'Configuration', 'last_invoice', invoice + 1) />

Invoice No: #invoice#

Some configuration information is more complex and is a poor fit for the simple nature of the INI file. In such cases, XML can be the ideal solution. Here is a sample XML-based configuration file:

		<!-- database use = testing|production-->
		<database use="testing">

				<dsn name="TestInventory" />
				<db type="msaccess" />
				<dsn name="GlobalInventory" security="SSPI" />
				<db type="sqlserver" />

The idea with this configuration file is that the application may be in one of two modes: testing or production. Each mode uses a separate datasource. When the "use" attribute of the "database" element is set to testing, we want to use the datasource defined in the "testing" element; in production mode, we want to use the datasource defined in the "production" element. Here is the code that reads and process the configuration file shown above:

<cffile action="READ" file="#ExpandPath('Sample.xml')#" variable="aFile" />
<cfset xml = XmlParse(aFile) />

<cfset databaseInfo = XmlSearch(xml, '//database') />
<cfset use = databaseInfo[1].xmlAttributes['use'] />
<cfset testingInfo = XmlSearch(xml, '//testing/dsn') />
<cfset productionInfo = XmlSearch(xml, '//production/dsn') />
<cfset testing = testingInfo[1].xmlAttributes['name'] />
<cfset production = productionInfo[1].xmlAttributes['name'] />

<cfset dsn = Evaluate(use) />

<cfquery datasource="#dsn#" name="myQ">
	<!---sql here--->

ColdFusion offers several XML tags and functions for dealing with XML. In this case, I've used only two: XMLParse and XMLSearch. The XMLParse function converts valid XML text into an XML object. Without this step, the XML text is unavailable for further processing.

The XMLSearch function provides an interface to the tremendous power of XPath, the XML-specific language for querying XML objects. For developers steeped in SQL queries, XPath may be initially hard to digest, but there are some excellent resources to help you.

Nate Weiss wrote a fine tutorial on working with ColdFusion's XML tags and functions, available at www.macromedia.com/devnet/mx/coldfusion/articles/xmlxslt.pdf. For in-depth examples of working with XPath, the tutorials at www.zvon.org/xxl/XPathTutorial/General/examples.html are invaluable.

Configuration files are very specific tools, but understanding how to use them can make your work cleaner and easier to maintain.

Further References Head First Design Patterns
By Elisabeth & Eric Freeman, Bert Bates, Kathy Sierra (O'Reilly)

More Stories By Hal Helms

Hal Helms is a well-known speaker/writer/strategist on software development issues. He holds training sessions on Java, ColdFusion, and software development processes. He authors a popular monthly newsletter series. For more information, contact him at hal (at) halhelms.com or see his website, www.halhelms.com.

Comments (0)

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
SYS-CON Events announced today that Technologic Systems Inc., an embedded systems solutions company, will exhibit at SYS-CON's @ThingsExpo, which will take place on June 6-8, 2017, at the Javits Center in New York City, NY. Technologic Systems is an embedded systems company with headquarters in Fountain Hills, Arizona. They have been in business for 32 years, helping more than 8,000 OEM customers and building over a hundred COTS products that have never been discontinued. Technologic Systems’ pr...
SYS-CON Events announced today that Auditwerx will exhibit at SYS-CON's 20th International Cloud Expo®, which will take place on June 6-8, 2017, at the Javits Center in New York City, NY. Auditwerx specializes in SOC 1, SOC 2, and SOC 3 attestation services throughout the U.S. and Canada. As a division of Carr, Riggs & Ingram (CRI), one of the top 20 largest CPA firms nationally, you can expect the resources, skills, and experience of a much larger firm combined with the accessibility and attent...
SYS-CON Events announced today that CA Technologies has been named “Platinum Sponsor” of SYS-CON's 20th International Cloud Expo®, which will take place on June 6-8, 2017, at the Javits Center in New York City, NY, and the 21st International Cloud Expo®, which will take place October 31-November 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. CA Technologies helps customers succeed in a future where every business – from apparel to energy – is being rewritten by software. From ...
SYS-CON Events announced today that HTBase will exhibit at SYS-CON's 20th International Cloud Expo®, which will take place on June 6-8, 2017, at the Javits Center in New York City, NY. HTBase (Gartner 2016 Cool Vendor) delivers a Composable IT infrastructure solution architected for agility and increased efficiency. It turns compute, storage, and fabric into fluid pools of resources that are easily composed and re-composed to meet each application’s needs. With HTBase, companies can quickly prov...
SYS-CON Events announced today that Loom Systems will exhibit at SYS-CON's 20th International Cloud Expo®, which will take place on June 6-8, 2017, at the Javits Center in New York City, NY. Founded in 2015, Loom Systems delivers an advanced AI solution to predict and prevent problems in the digital business. Loom stands alone in the industry as an AI analysis platform requiring no prior math knowledge from operators, leveraging the existing staff to succeed in the digital era. With offices in S...
Buzzword alert: Microservices and IoT at a DevOps conference? What could possibly go wrong? In this Power Panel at DevOps Summit, moderated by Jason Bloomberg, the leading expert on architecting agility for the enterprise and president of Intellyx, panelists peeled away the buzz and discuss the important architectural principles behind implementing IoT solutions for the enterprise. As remote IoT devices and sensors become increasingly intelligent, they become part of our distributed cloud enviro...
SYS-CON Events announced today that T-Mobile will exhibit at SYS-CON's 20th International Cloud Expo®, which will take place on June 6-8, 2017, at the Javits Center in New York City, NY. As America's Un-carrier, T-Mobile US, Inc., is redefining the way consumers and businesses buy wireless services through leading product and service innovation. The Company's advanced nationwide 4G LTE network delivers outstanding wireless experiences to 67.4 million customers who are unwilling to compromise on ...
SYS-CON Events announced today that Infranics will exhibit at SYS-CON's 20th International Cloud Expo®, which will take place on June 6-8, 2017, at the Javits Center in New York City, NY. Since 2000, Infranics has developed SysMaster Suite, which is required for the stable and efficient management of ICT infrastructure. The ICT management solution developed and provided by Infranics continues to add intelligence to the ICT infrastructure through the IMC (Infra Management Cycle) based on mathemat...
SYS-CON Events announced today that Interoute, owner-operator of one of Europe's largest networks and a global cloud services platform, has been named “Bronze Sponsor” of SYS-CON's 20th Cloud Expo, which will take place on June 6-8, 2017 at the Javits Center in New York, New York. Interoute is the owner-operator of one of Europe's largest networks and a global cloud services platform which encompasses 12 data centers, 14 virtual data centers and 31 colocation centers, with connections to 195 add...
SYS-CON Events announced today that Cloudistics, an on-premises cloud computing company, has been named “Bronze Sponsor” of SYS-CON's 20th International Cloud Expo®, which will take place on June 6-8, 2017, at the Javits Center in New York City, NY. Cloudistics delivers a complete public cloud experience with composable on-premises infrastructures to medium and large enterprises. Its software-defined technology natively converges network, storage, compute, virtualization, and management into a ...
In his session at @ThingsExpo, Eric Lachapelle, CEO of the Professional Evaluation and Certification Board (PECB), will provide an overview of various initiatives to certifiy the security of connected devices and future trends in ensuring public trust of IoT. Eric Lachapelle is the Chief Executive Officer of the Professional Evaluation and Certification Board (PECB), an international certification body. His role is to help companies and individuals to achieve professional, accredited and worldw...
In his General Session at 16th Cloud Expo, David Shacochis, host of The Hybrid IT Files podcast and Vice President at CenturyLink, investigated three key trends of the “gigabit economy" though the story of a Fortune 500 communications company in transformation. Narrating how multi-modal hybrid IT, service automation, and agile delivery all intersect, he will cover the role of storytelling and empathy in achieving strategic alignment between the enterprise and its information technology.
Microservices are a very exciting architectural approach that many organizations are looking to as a way to accelerate innovation. Microservices promise to allow teams to move away from monolithic "ball of mud" systems, but the reality is that, in the vast majority of organizations, different projects and technologies will continue to be developed at different speeds. How to handle the dependencies between these disparate systems with different iteration cycles? Consider the "canoncial problem" ...
The Internet of Things is clearly many things: data collection and analytics, wearables, Smart Grids and Smart Cities, the Industrial Internet, and more. Cool platforms like Arduino, Raspberry Pi, Intel's Galileo and Edison, and a diverse world of sensors are making the IoT a great toy box for developers in all these areas. In this Power Panel at @ThingsExpo, moderated by Conference Chair Roger Strukhoff, panelists discussed what things are the most important, which will have the most profound e...
Keeping pace with advancements in software delivery processes and tooling is taxing even for the most proficient organizations. Point tools, platforms, open source and the increasing adoption of private and public cloud services requires strong engineering rigor - all in the face of developer demands to use the tools of choice. As Agile has settled in as a mainstream practice, now DevOps has emerged as the next wave to improve software delivery speed and output. To make DevOps work, organization...
My team embarked on building a data lake for our sales and marketing data to better understand customer journeys. This required building a hybrid data pipeline to connect our cloud CRM with the new Hadoop Data Lake. One challenge is that IT was not in a position to provide support until we proved value and marketing did not have the experience, so we embarked on the journey ourselves within the product marketing team for our line of business within Progress. In his session at @BigDataExpo, Sum...
Web Real-Time Communication APIs have quickly revolutionized what browsers are capable of. In addition to video and audio streams, we can now bi-directionally send arbitrary data over WebRTC's PeerConnection Data Channels. With the advent of Progressive Web Apps and new hardware APIs such as WebBluetooh and WebUSB, we can finally enable users to stitch together the Internet of Things directly from their browsers while communicating privately and securely in a decentralized way.
DevOps is often described as a combination of technology and culture. Without both, DevOps isn't complete. However, applying the culture to outdated technology is a recipe for disaster; as response times grow and connections between teams are delayed by technology, the culture will die. A Nutanix Enterprise Cloud has many benefits that provide the needed base for a true DevOps paradigm.
What sort of WebRTC based applications can we expect to see over the next year and beyond? One way to predict development trends is to see what sorts of applications startups are building. In his session at @ThingsExpo, Arin Sime, founder of WebRTC.ventures, will discuss the current and likely future trends in WebRTC application development based on real requests for custom applications from real customers, as well as other public sources of information,
In his General Session at 17th Cloud Expo, Bruce Swann, Senior Product Marketing Manager for Adobe Campaign, explored the key ingredients of cross-channel marketing in a digital world. Learn how the Adobe Marketing Cloud can help marketers embrace opportunities for personalized, relevant and real-time customer engagement across offline (direct mail, point of sale, call center) and digital (email, website, SMS, mobile apps, social networks, connected objects).