YOUR FEEDBACK
ASP.NET
mark bosley wrote: Good article. Please post the code or send it to me. It ...
AJAXWorld RIA Conference
$300 Savings Expire July 25
Register Today and SAVE!


2007 West
GOLD SPONSORS:
Active Endpoints
Your SOA Needs BPEL for Orchestration
BEA
Virtualized SOA: Adaptive Infrastructure for Demanding Applications
Nexaweb
Overcoming Bandwidth Challenges with Nexaweb
TIBCO
What is Service Virtualization?
SILVER SPONSORS:
WSO2
Using Web Services Technologies and FOSS Solutions
Click For 2007 East
Event Webcasts

2008 East
PLATINUM SPONSORS:
Appcelerator
Think Fast: Accelerate AJAX Development with Appcelerator
GOLD SPONSORS:
DreamFace Interactive
The Ultimate Framework for Creating Personalized Web 2.0 Mashups
ICEsoft
AJAX and Social Computing for the Enterprise
Kaazing
Enterprise Comet: Real–Time, Real–Time, or Real–Time Web 2.0?
Nexaweb
Now Playing: Desktop Apps in the Browser!
Sun
jMaki as an AJAX Mashup Framework
POWER PANELS:
The Business Value
of RIAs
What Lies Beyond AJAX?
KEYNOTES:
Douglas Crockford
Can We Fix the Web?
Anthony Franco
2008: The Year of the RIA
Click For 2007 Event Webcasts
SYS-CON.TV
TOP COLDFUSION LINKS


Creating Configuration Files
Make your work cleaner and easier to maintain

Digg This!

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)

About Hal Helms
Hal Helms is a well-known speaker/writer/strategist on software development issues. His monthly column in CFDJ contains his Musings on Software Development and he has written and contributed to several books. Hal holds training sessions on Java, ColdFusion, and software development processes. He authors a popular monthly newsletter series. For more information, contact him at hal@halhelms.com or see his website, www.halhelms.com.

CFDJ LATEST STORIES . . .
Adobe's Kevin Lynch and Microsoft's Scott Guthrie to Keynote AJAX World RIA Conference & Expo
Two of the biggest launches in Rich Internet Application history took place in 2007/2008 when Adobe launched AIR 1.0 in February '08 and Microsoft launched Silverlight (September '07). At the 6th International AJAXWorld RIA Conference & Expo in October SYS-CON Events is delighted to be
Voyager Offers Android, .NET CF, Java Runtime Support
Recursion Software released a private beta version of their Voyager mobile platform, with powerful interoperability for Android, Microsoft .NET and Compact Framework (CF), all Java editions (JME CDC, JSE and JEE), and more than 15 embedded operating systems. The Voyager platform is a p
AJAX and Enterprise RIA Tools - JSF, Flex, and JavaFX
2008 is going to be an important year for Rich Internet Applications. Most organizations are delivering or planning to deliver Rich Internet Applications; however, at the same time, most IT managers are facing a dilemma: which Rich Internet Application technology and platform to use? T
CFDynamics Announces Renewed Agreement with SmarterTools
CFDynamics, a ColdFusion web host, has renewed an agreement with SmarterTools that will allow them to pass on immediate value to their customers. When a customers signs up for a dedicated hosting account they will now receive $750 worth of features including SmarterMail, SmarterStats a
Microsoft's Virtualization Chief Mike Neil To Keynote SYS-CON's Virtualization Conference & Expo
Mike Neil is general manager for virtualization strategy in the Windows Server Division at Microsoft. Mike is focused on the delivery of the Windows virtualization technology, including Windows Server 2008 Hyper-V, Microsoft Hyper-V Server and Virtual PC 2007. Mike also directs the tec
SYS-CON's Virtualization Conference & Expo: Themes & Topics
From Application Virtualization to Xen, a round-up of the virtualization themes & topics being discussed in NYC June 23-24, 2008 by the world-class speaker faculty at the 3rd International Virtualization Conference & Expo being held by SYS-CON Events in The Roosevelt Hotel, in midtown
SUBSCRIBE TO THE WORLD'S MOST POWERFUL NEWSLETTERS
SUBSCRIBE TO OUR RSS FEEDS & GET YOUR SYS-CON NEWS LIVE!
Click to Add our RSS Feeds to the Service of Your Choice:
Google Reader or Homepage Add to My Yahoo! Subscribe with Bloglines Subscribe in NewsGator Online
myFeedster Add to My AOL Subscribe in Rojo Add 'Hugg' to Newsburst from CNET News.com Kinja Digest View Additional SYS-CON Feeds
Publish Your Article! Please send it to editorial(at)sys-con.com!

Advertise on this site! Contact advertising(at)sys-con.com! 201 802-3021

SYS-CON FEATURED WHITEPAPERS

ADS BY GOOGLE