Just a short blog post today to touch on a couple of useful helper methods that Sitecore provides that are easily overlooked.

You have likely used the following method for reading out a setting from a Sitecore configuration file:

Sitecore.Configuration.Settings.GetSetting("StringSetting", "defaultValue");

It’s worth knowing that you usually don’t need to manually parse values from configuration settings, as there’s a few other methods here that will do that for you:

Sitecore.Configuration.Settings.GetBoolSetting("BoolSetting", true);
Sitecore.Configuration.Settings.GetIntSetting("IntSetting", 5);
Sitecore.Configuration.Settings.GetDoubleSetting("DoubleSetting", 5.00m);
Sitecore.Configuration.Settings.GetLongSetting("LongSetting", 5);

These are just small wrappers around some simple parsing logic, but they’re handy nonetheless. Each variant allows you to specify a correctly-typed default value that will be returned if the setting doesn’t exist, or if it fails to parse.

As well as these, there’s a more interesting option! Have you ever needed to store a time-based setting in configuration? Did you end up storing it as a numeric value and calling your setting TimeoutSeconds or DelayInMinutes? Well thanks to the following method, you can have a little more flexibility in values that represent spans of time:

Sitecore.Configuration.Settings.GetTimeSpanSetting("TimeSpanSetting", TimeSpan.FromMinutes(5))

This method makes use of DateUtils.ParseTimeSpan to parse the string value as a TimeSpan, allowing for you to have a more varied and readable string. Here are some example values you can use:

d.hh:mm:ss
0.00:00:30 - 30 seconds
0.00:01:30 - 1 minute, 30 seconds
0.10:01:30 - 10 hours, 1 minute, 30 seconds
3.10:01:30 - 3 days, 10 hours, 1 minute, 30 seconds

Very helpful!

There’s also GetFileSetting, which simply reads the value as a string and feeds the result into FileUtil.MapPath to map the relative path to an absolute path on the server.

Finally, though there isn’t a GetSetting wrapper for it, there’s a useful string parsing helper that you can combine with the regular GetSetting method, and that’s StringUtil.ParseSizeString. This takes a string representing a file size, and returns the value as a long representing the same size as a number of bytes. Here are some examples:

StringUtil.ParseSizeString("100KB") // = 102400 bytes
StringUtil.ParseSizeString("100MB") // = 104857600 bytes
StringUtil.ParseSizeString("100GB") // = 107374182400 bytes

Like with GetTimeSpanSetting, this lets you store your configuration values as more flexible and readable strings. After all, it’s much quicker to read 100MB than 104857600 and know what the resulting file size will be.