Welcome!

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:


[SectionName]
keyname=value
;comment
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:


[Configuration]
dsn=WegotWidgets
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.


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

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) />

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

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:


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

			<testing>
				<dsn name="TestInventory" />
				<db type="msaccess" />
			</testing>
			<production>
				<dsn name="GlobalInventory" security="SSPI" />
				<db type="sqlserver" />
			</production>
		</database>
	</settings>
</configuration>

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--->
</cfquery>

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 Dasher Technologies will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 - Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Dasher Technologies, Inc. ® is a premier IT solution provider that delivers expert technical resources along with trusted account executives to architect and deliver complete IT solutions and services to help our clients execute their goals, plans and objectives. Since 1999, we'v...
SYS-CON Events announced today that TidalScale, a leading provider of systems and services, will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 - Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. TidalScale has been involved in shaping the computing landscape. They've designed, developed and deployed some of the most important and successful systems and services in the history of the computing industry - internet, Ethernet, operating s...
Enterprises have taken advantage of IoT to achieve important revenue and cost advantages. What is less apparent is how incumbent enterprises operating at scale have, following success with IoT, built analytic, operations management and software development capabilities – ranging from autonomous vehicles to manageable robotics installations. They have embraced these capabilities as if they were Silicon Valley startups. As a result, many firms employ new business models that place enormous impor...
Coca-Cola’s Google powered digital signage system lays the groundwork for a more valuable connection between Coke and its customers. Digital signs pair software with high-resolution displays so that a message can be changed instantly based on what the operator wants to communicate or sell. In their Day 3 Keynote at 21st Cloud Expo, Greg Chambers, Global Group Director, Digital Innovation, Coca-Cola, and Vidya Nagarajan, a Senior Product Manager at Google, will discuss how from store operations...
Nordstrom is transforming the way that they do business and the cloud is the key to enabling speed and hyper personalized customer experiences. In his session at 21st Cloud Expo, Ken Schow, VP of Engineering at Nordstrom, will discuss some of the key learnings and common pitfalls of large enterprises moving to the cloud. This includes strategies around choosing a cloud provider(s), architecture, and lessons learned. In addition, he’ll go over some of the best practices for structured team migrat...
SYS-CON Events announced today that Taica will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Taica manufacturers Alpha-GEL brand silicone components and materials, which maintain outstanding performance over a wide temperature range -40C to +200C. For more information, visit http://www.taica.co.jp/english/.
SYS-CON Events announced today that MIRAI Inc. will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. MIRAI Inc. are IT consultants from the public sector whose mission is to solve social issues by technology and innovation and to create a meaningful future for people.
Recently, REAN Cloud built a digital concierge for a North Carolina hospital that had observed that most patient call button questions were repetitive. In addition, the paper-based process used to measure patient health metrics was laborious, not in real-time and sometimes error-prone. In their session at 21st Cloud Expo, Sean Finnerty, Executive Director, Practice Lead, Health Care & Life Science at REAN Cloud, and Dr. S.P.T. Krishnan, Principal Architect at REAN Cloud, will discuss how they bu...
As hybrid cloud becomes the de-facto standard mode of operation for most enterprises, new challenges arise on how to efficiently and economically share data across environments. In his session at 21st Cloud Expo, Dr. Allon Cohen, VP of Product at Elastifile, will explore new techniques and best practices that help enterprise IT benefit from the advantages of hybrid cloud environments by enabling data availability for both legacy enterprise and cloud-native mission critical applications. By rev...
Join IBM November 1 at 21st Cloud Expo at the Santa Clara Convention Center in Santa Clara, CA, and learn how IBM Watson can bring cognitive services and AI to intelligent, unmanned systems. Cognitive analysis impacts today’s systems with unparalleled ability that were previously available only to manned, back-end operations. Thanks to cloud processing, IBM Watson can bring cognitive services and AI to intelligent, unmanned systems. Imagine a robot vacuum that becomes your personal assistant tha...
With major technology companies and startups seriously embracing Cloud strategies, now is the perfect time to attend 21st Cloud Expo October 31 - November 2, 2017, at the Santa Clara Convention Center, CA, and June 12-14, 2018, at the Javits Center in New York City, NY, and learn what is going on, contribute to the discussions, and ensure that your enterprise is on the right path to Digital Transformation.
SYS-CON Events announced today that Datera will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Datera offers a radically new approach to data management, where innovative software makes data infrastructure invisible, elastic and able to perform at the highest level. It eliminates hardware lock-in and gives IT organizations the choice to source x86 server nodes, with business model option...
Infoblox delivers Actionable Network Intelligence to enterprise, government, and service provider customers around the world. They are the industry leader in DNS, DHCP, and IP address management, the category known as DDI. We empower thousands of organizations to control and secure their networks from the core-enabling them to increase efficiency and visibility, improve customer service, and meet compliance requirements.
Digital transformation is changing the face of business. The IDC predicts that enterprises will commit to a massive new scale of digital transformation, to stake out leadership positions in the "digital transformation economy." Accordingly, attendees at the upcoming Cloud Expo | @ThingsExpo at the Santa Clara Convention Center in Santa Clara, CA, Oct 31-Nov 2, will find fresh new content in a new track called Enterprise Cloud & Digital Transformation.
SYS-CON Events announced today that N3N will exhibit at SYS-CON's @ThingsExpo, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. N3N’s solutions increase the effectiveness of operations and control centers, increase the value of IoT investments, and facilitate real-time operational decision making. N3N enables operations teams with a four dimensional digital “big board” that consolidates real-time live video feeds alongside IoT sensor data a...
SYS-CON Events announced today that NetApp has been named “Bronze Sponsor” of SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. NetApp is the data authority for hybrid cloud. NetApp provides a full range of hybrid cloud data services that simplify management of applications and data across cloud and on-premises environments to accelerate digital transformation. Together with their partners, NetApp emp...
Smart cities have the potential to change our lives at so many levels for citizens: less pollution, reduced parking obstacles, better health, education and more energy savings. Real-time data streaming and the Internet of Things (IoT) possess the power to turn this vision into a reality. However, most organizations today are building their data infrastructure to focus solely on addressing immediate business needs vs. a platform capable of quickly adapting emerging technologies to address future ...
SYS-CON Events announced today that Avere Systems, a leading provider of hybrid cloud enablement solutions, will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Avere Systems was created by file systems experts determined to reinvent storage by changing the way enterprises thought about and bought storage resources. With decades of experience behind the company’s founders, Avere got its ...
SYS-CON Events announced today that Avere Systems, a leading provider of enterprise storage for the hybrid cloud, will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 - Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Avere delivers a more modern architectural approach to storage that doesn't require the overprovisioning of storage capacity to achieve performance, overspending on expensive storage media for inactive data or the overbui...
SYS-CON Events announced today that IBM has been named “Diamond Sponsor” of SYS-CON's 21st Cloud Expo, which will take place on October 31 through November 2nd 2017 at the Santa Clara Convention Center in Santa Clara, California.