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.

IoT & Smart Cities Stories
Moroccanoil®, the global leader in oil-infused beauty, is thrilled to announce the NEW Moroccanoil Color Depositing Masks, a collection of dual-benefit hair masks that deposit pure pigments while providing the treatment benefits of a deep conditioning mask. The collection consists of seven curated shades for commitment-free, beautifully-colored hair that looks and feels healthy.
The textured-hair category is inarguably the hottest in the haircare space today. This has been driven by the proliferation of founder brands started by curly and coily consumers and savvy consumers who increasingly want products specifically for their texture type. This trend is underscored by the latest insights from NaturallyCurly's 2018 TextureTrends report, released today. According to the 2018 TextureTrends Report, more than 80 percent of women with curly and coily hair say they purcha...
The textured-hair category is inarguably the hottest in the haircare space today. This has been driven by the proliferation of founder brands started by curly and coily consumers and savvy consumers who increasingly want products specifically for their texture type. This trend is underscored by the latest insights from NaturallyCurly's 2018 TextureTrends report, released today. According to the 2018 TextureTrends Report, more than 80 percent of women with curly and coily hair say they purcha...
We all love the many benefits of natural plant oils, used as a deap treatment before shampooing, at home or at the beach, but is there an all-in-one solution for everyday intensive nutrition and modern styling?I am passionate about the benefits of natural extracts with tried-and-tested results, which I have used to develop my own brand (lemon for its acid ph, wheat germ for its fortifying action…). I wanted a product which combined caring and styling effects, and which could be used after shampo...
The platform combines the strengths of Singtel's extensive, intelligent network capabilities with Microsoft's cloud expertise to create a unique solution that sets new standards for IoT applications," said Mr Diomedes Kastanis, Head of IoT at Singtel. "Our solution provides speed, transparency and flexibility, paving the way for a more pervasive use of IoT to accelerate enterprises' digitalisation efforts. AI-powered intelligent connectivity over Microsoft Azure will be the fastest connected pat...
There are many examples of disruption in consumer space – Uber disrupting the cab industry, Airbnb disrupting the hospitality industry and so on; but have you wondered who is disrupting support and operations? AISERA helps make businesses and customers successful by offering consumer-like user experience for support and operations. We have built the world’s first AI-driven IT / HR / Cloud / Customer Support and Operations solution.
Codete accelerates their clients growth through technological expertise and experience. Codite team works with organizations to meet the challenges that digitalization presents. Their clients include digital start-ups as well as established enterprises in the IT industry. To stay competitive in a highly innovative IT industry, strong R&D departments and bold spin-off initiatives is a must. Codete Data Science and Software Architects teams help corporate clients to stay up to date with the mod...
At CloudEXPO Silicon Valley, June 24-26, 2019, Digital Transformation (DX) is a major focus with expanded DevOpsSUMMIT and FinTechEXPO programs within the DXWorldEXPO agenda. Successful transformation requires a laser focus on being data-driven and on using all the tools available that enable transformation if they plan to survive over the long term. A total of 88% of Fortune 500 companies from a generation ago are now out of business. Only 12% still survive. Similar percentages are found throug...
Druva is the global leader in Cloud Data Protection and Management, delivering the industry's first data management-as-a-service solution that aggregates data from endpoints, servers and cloud applications and leverages the public cloud to offer a single pane of glass to enable data protection, governance and intelligence-dramatically increasing the availability and visibility of business critical information, while reducing the risk, cost and complexity of managing and protecting it. Druva's...
BMC has unmatched experience in IT management, supporting 92 of the Forbes Global 100, and earning recognition as an ITSM Gartner Magic Quadrant Leader for five years running. Our solutions offer speed, agility, and efficiency to tackle business challenges in the areas of service management, automation, operations, and the mainframe.