The following is a presentation I gave at the Milwaukee SItecore Developer meetup. The presentation was sort of a back to basics...
Setting Values in Sitecore Config FilesDerek Dysart
I was reminded this morning of an often overlooked part of Sitecore’s config file patching system. By now we all should be familiar with the
patch:before– inserts the element before the specified element.
patch:after– inserts the element after the specified element.
patch:attribute– defines or replaces the specified attribute of the element. You can achieve the same effect using the set namespace.
patch:delete– removes the specified element.
patch:instead– replaces the specified element.
But if you look closely, Sitecore also has you register a
set namespace, but then doesn’t really tell you what that does. Let’s look at a common scenario.
You have a new server and you need to configure the connection to a SMTP server so Sitecore can send emails (lost password, etc.). The setting Sitecore uses is in the
/sitecore/settings/ section of the configuration, specifically
<setting name="MailServer" value="localhost" />. You could go ahead and open the file
Sitecore.config and replace
localhost with the correct value, but editing the stock config files is frowned upon. So you decide to create a patch file. Without the
set namespace, that would look something like:
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/"> <sitecore> <settings> <setting name="MailServer"> <patch:attribute name="value"> smtp.organization.com </patch:attribute> </setting> </settings> </sitecore> </configuration>
This gets the job done, but the whole
patch:attribute name="value" is a little ugly, plus it assumes the setting
MailServer was created earlier in the configuration files, which is a safe assumption for system settings, but what if you’re a module author or you have application specific settings? If the setting wasn’t specified earier in the config file chain, you’ll get an error when the AppPool starts. We can simplify the config file and in the process set the setting if our config is the first instance of it, or override it if it is not. This is where the
set namespace comes in:
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/" xmlns:set="http://www.sitecore.net/xmlconfig/set/"> <sitecore> <settings> <setting name="MailServer" set:value="smtp.organization.com" /> </setting> </settings> </sitecore> </configuration>
IMO, this is much cleaner. If for some reason, the
MailServer setting wasn’t specified earlier it now is, and if it was specified, it’s now overridden. Keep in mind, patch file ordering is still in effect, so depending on the version of Sitecore you need to be aware of how your patch files are applied (see the version specific documentation for more information)