CMS2002: Quick and Easy Random "Factoid" Control
A recent request came through to allow our CMS users to add a random “fact of the moment” or “factoid” to the homepage. The tool would need to cycle through 5-10 random facts that include a title and heading.
My initial reaction was to simply create a database table and let it read from the database table. How much more simple can you get? Three or four columns, depending on how detailed you wanted to get (title, body, date, boolean for display) and a simple dataset. On the other hand, what about the user? How would s/he update it? That requires creating an admin page for that control–something that I wasn’t sure I wanted to do or maintain long-term.
So, what’s another option? What’s easily dropped into a dataset and readable? Well, XML!
- The code is extremely simplistic.
- The user maintenance is fairly short and mundane–anyone, with a bit of training, can update the XML file as long as it’s easy to read.
- Breaking the XML file will break the control unless proper safeguards are in place.
- How do we secure the file to keep it safe? Where do we put it?
In CMS, I opted to simply create a custom user control (TextRotator.ascx, for this example) with the code in a separate file (TextRotator.ascx.cs).
The user control itself contains, for this example, simply two label controls–the header and body. In the HTML, I’m assigning the lblHeader label the CssClass of “rotatingHeader” and the lblBody label the CssClass of “rotatingBody”. These are then added to our base CSS file that is called by all pages in our CSS project. You can also style these separately within the control.
Now, on to the code-behind.
The user control needs to:
- Create an empty Dataset and populate it with values from our XML file.
- Choose a random value to display.
- Set the header and body approprately to the chosen random value.
Before we start coding, let’s layout our XML file first.
For this example, we’re going to just have a title and a body. As additional nodes are added, additional “factoids” are rotated through–at least that’s the plan!
<?xml version=”1.0″ encoding=”utf-8″ ?>
<title>Did you know…?</title>
<body>Wichita Public Schools is the largest district between the Mississippi River and Denver, and Dallas and the Canadian border.</body>
Step 1 is easily completed by using the built-in methods of a DataSet.
// Create a new dataset and drop the rotating.xml file into it.
DataSet ds = new DataSet();
The DataSet.ReadXml method provides “a way to read either data only, or both data and schema into a DAtaSet from an XML document.” That’s exactly what we want to do here. The XML file is located in the root directory of our website for easy access and, in production, be located anywhere the developer desires.
Step 2 is completed by two steps. First, we must determine how many records exist in our dataset and, from there, we can generate a random number between 0 and our total records.
// Find the total number of objects (factoids to rotate).
int totalObjects = ds.Tables.Rows.Count;
// Generate a random number between 0 and the total factoids.
// We don’t want to always show the same factoid.
Random rnd = new Random();
int pickedObject = rnd.Next(totalObjects);
The Random.Next(Int32) method provides a random number between 0 and the number provided by our Rows.Count. It’s most important to remember that if you have eight entries, they are returned as 0 to 7.
Step 3 requires us to capture our new random number and use it to access the DataSet and display our results.
// Set the header and body to the picked objects.
lblHeader.Text = ds.Tables.Rows[pickedObject][“title”].ToString();
lblBody.Text = ds.Tables.Rows[pickedObject][“body”].ToString();
The DataSet.Tables.Rows[pickedObject] ensures that the random number generated above is picked out of our DataSet along with the proper column name (matching our XML file’s schema).
Finally, I suggest surrounding everything with the proper try/catch statements to ensure that, in the event that the XML file is not found, the entire CMS site does not collapse.
That’s it! From here, we save and compile to generate our user control and we’re ready to drop it on our CMS templates for consumption.