Useful Sitecore configuration methods
You have likely used the following method for reading out a setting from a Sitecore configuration file:
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:
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
DelayInMinutes? Well thanks to the following method, you can have a little more flexibility in values that represent spans of time:
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:
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
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
GetTimeSpanSetting, this lets you store your configuration values as more flexible and readable strings. After all, it’s much quicker to read
104857600 and know what the resulting file size will be.