How to capitalize the first letter of each word in a string

By Alan S. at July 23, 2010 12:43
Filed Under: Web / Software Development

This is going to be the shortest post on this board, and one of the most embarrassing!

 

I ‘inherited’ a file full of string values that contained over 10,000 entries. Problem was, they were all lower case. I wasn’t about to sit there and manually capitalize the first letter of each word in the list so I thought, “Hey… just write a quick function in the program that does it for you. It should only take a few lines, right?” Well, not for me.

 

I started working on a function that read in each line, searched for the first character and capitalized it. But how would you account for some words that should not be capitalized like ‘de’ as in “Cul de Sac” or initials or abbreviations? The more I thought about it, the more complex the function got. I started worrying that I was missing something… Well, I was.

 

Like I said, it’s kind of embarrassing, but while Googling to try and make sure I covered all my bases, I came across this gem on the MSDN site:

 

myString = System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase( myString );

 

I couldn't believe it. It takes care of all automatic capitalization of the first letter of a word or string of words... Ugh! Oh well, I hope at least it saves some developer an hour of headaches!

Bookmark and Share DotnetKicks dotnetshoutout

How to populate a TreeView control using XML with NO root

By Alan S. at July 14, 2010 11:09
Filed Under: Web / Software Development

For our latest software venture, we needed to create a tree view listing of all the countries that we were going to support. Naturally, we created an XML input file that was formed like this:

   1: <?xml version="1.0" encoding="utf-8" ?>
   2: <Countries>
   3:   <Country Name="Argentina" value="http://buenosaires.en.craigslist.org">
   4:   </Country>
   5:   <Country Name="Australia" value="http://sydney.craigslist.com.au">
   6:       <Region Name="Adelaide" value="http://adelaide.craigslist.com.au" />
   7:       <Region Name="Brisbane" value="http://brisbane.craigslist.com.au" />
   8:       <Region Name="Cairns" value="http://cairns.craigslist.com.au" />
   9:       <Region Name="Canberra" value="http://canberra.craigslist.com.au" />
  10:       <Region Name="Darwin" value="http://darwin.craigslist.com.au" />
  11:       <Region Name="Gold Coast" value="http://goldcoast.craigslist.com.au" />
  12:       <Region Name="Melbourne" value="http://melbourne.craigslist.com.au" />
  13:       <Region Name="Newcastle" value="http://ntl.craigslist.com.au" />
  14:       <Region Name="Perth" value="http://perth.craigslist.com.au" />
  15:       <Region Name="Sydney" value="http://sydney.craigslist.com.au" />
  16:       <Region Name="Tasmania" value="http://hobart.craigslist.com.au" />
  17:       <Region Name="Wollongong" value="http://wollongong.craigslist.com.au" />
  18:   </Country>
  19:   <Country Name="Austria" value="http://vienna.en.craigslist.at">
  20:   </Country>
  21: ... and so on...

The problem was that XML requires a root element (in this case, Countries). This meant that just blindly loading the XML left us with a single root node (Countries) with all the individual country information (Country) listed below that. We wanted to start our TreeView with the Country listings as root elements.

 

The solution was to create a reader function that would skip the root element found in traditional reader samples, like the example on Microsoft’s MSDN site. We created a function here that does just that.

   1: private void OnFormLoad(object sender, EventArgs e)
   2: {
   3:     try
   4:     {
   5:         XmlDocument dom = new XmlDocument();
   6:         dom.Load("CountryList.xml"); 
   7:         treeView1.Nodes.Clear();
   8:         AddTreeViewChildNodes(treeView1.Nodes, dom.DocumentElement);
   9:         treeView1.Refresh();
  10:         treeView1.CollapseAll();
  11:     }
  12:     catch (XmlException xmlEx)
  13:     {
  14:         MessageBox.Show(xmlEx.Message);
  15:     }
  16:     catch (Exception ex)
  17:     {
  18:         MessageBox.Show(ex.Message);
  19:     }
  20: }
  21:  
  22: private void AddTreeViewChildNodes(TreeNodeCollection parent_nodes, XmlNode xml_node)
  23: {
  24:     foreach (XmlNode child_node in xml_node.ChildNodes)
  25:     {
  26:         // Make the new TreeView node.
  27:         TreeNode new_node = parent_nodes.Add(child_node.Attributes["Name"].Value);
  28:         // Recursively make this node's descendants.
  29:         AddTreeViewChildNodes(new_node.Nodes, child_node);
  30:         // If this is a leaf node, make sure it's visible.
  31:         if (new_node.Nodes.Count == 0) new_node.EnsureVisible();
  32:     }
  33: }

The code is deceptively simple… It’s only 3 lines of recursive C#. You can always change the text that is displayed by manipulating the child_node.Attributes["Name"].Value line. It’s important to call treeView1.Refresh() when the function is complete to ensure all of the boxes and nodes are fully drawn.

 

imageWhat we’re left with is a nice TreeView control that has each country listed as a root element, despite what the XML says.

 

BTW: If your wondering how we did the 3 state checkbox, that information will be provided in a later post.

Bookmark and Share DotnetKicks dotnetshoutout

Singleton Class – C#’s MVP

By Alan S. at January 20, 2010 16:15
Filed Under: Web / Software Development

What is a singleton class? Well basically it's a class that can only be instantiated ONE TIME within the confines of an applications space. Why is this useful? Well, it's a great place for creating and managing single point code logging functions or holding global data that requires a bit to retrieve.

 

For example, I wrote a program for a user that read data from an Access database. When the program started, I instantiate a singleton and run a query to get the version of the data (within a table / row). This value is stored in the singleton upon startup. Now, when the dozens of custom reports are run, this information is printed on the header by simply referencing the singleton variable as opposed to running this query every time that value is needed.

In the example below, I am going to create a singleton class that contains one of my most used functions, WriteToLog.

 

First, lets create a singleton class in Visual Studio by right clicking the project name in the "Solution Explorer" pane and selecting "Add New Item." Select "Class" and type in a name for your new singleton class (example: LocalEnv). Enter this in the source code window:

   1: using System; 
   2: public class LocalEnv 
   3: { 
   4:     private static LocalEnv instance = null;
   5:     private LocalEnv() {}
   6:     public static LocalEnv Instance 
   7:     {
   8:         get
   9:         {
  10:             if (instance == null)
  11:             {
  12:                 instance = new LocalEnv();
  13:             }
  14:             return instance;
  15:         } 
  16:     } 
  17: }

Notice how the constructor is private? This means that the class can only be instantiated internally by using the "new" command and referencing it through the instance variable. If an instance of this class already exists in memory, it will simply return the already instantiated instance. If not, it creates a new instance of the class. Be sure to note the differences in the Instance variable and the instance variable (upper and lowercase 'i' versions). They are two seperate things.

 

Next, we'll need to create a function within our LocalEnv class that will write a message to a log file. In this example, I will assume that this is a website and that we want to write all of our logs to a subdirectory under the App_Data directory (or wherever you want) and that the log filename will be the date the event occurred.

   1: public void WriteToLog(string sBaseDir, string sText)
   2: {
   3:     string sLogFilename = sBaseDir + "/MyWebLogs/" + 
   4:         string.Format("{0:d}{1:d2}{2:d2}.log", DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day);
   5:     StreamWriter myStream = null;
   6:     sText = DateTime.Now.ToShortDateString() + " "+DateTime.Now.ToShortTimeString() + ": " + sText;
   7:     using (myStream = new StreamWriter(sLogFilename, true))
   8:     {
   9:         myStream.WriteLine(sText);
  10:     }
  11: }

Now, in our .aspx file, we can write any message to the generic text log as follows:

   1: LocalEnv.Instance().WriteToLog(Request.MapPath("~/App_Data"), "A new user was added");

Whenever we call the function, it will write a single line to the log file in the directory we specify. It will write all log entries into a single file for the day. The result in our log file file (example: c:\inetpub\wwwroot\App_Data\MyWebLogs\20100114.log) will look like:

01/14/2010 17:54:14: A new user was added

Bookmark and Share DotnetKicks dotnetshoutout


   

eMail Scraper
Generate email lists in seconds!


eSource Development presents the ultimate tool for email lead generation! They have decided to release the hottest email list generation tool that allows you to get hundreds (even THOUSANDS) of specific email addresses for any genre, niche, or geographical area.

Internet marketing companies and professionals have been using this tool for years. Now, it has been re-engineered, updated, and released to the public. This 'insider only' software was a closely guarded industry secret until recently.



Watch the Demo

NEW! Trial version available!

DOWNLOAD FOR FREE




  


Dr. Torgo's PC
System Inventory v2.0


Dr. Torgo's PC System Inventory offers a full range of system query options and powerful reporting tools. This software quickly generates reports on several dozen hives of system information including disks, CPU, memory, motherboard, users, ports, services, software, and MORE.

Read more here!

NEW! Trial version available!
DOWNLOAD FOR FREE


Help us out by visiting our sponsors!

iBuyPower







Recent Comments

Comment RSS

What We're Playing





Who's Watchin' Me?