This is the third part of the Sitefinity series. For your convenience you can find other parts in the table of contents in Sitefinity Part 1 — Capturing logs
Sitefinity stores its database connection string in App_data\Sitefinity\Configuration\DataConfig.config
so you can easily modify connection string there. But what if you want to extract the connection string in runtime? E.g., you want to read it from Azure Key Vault after application is started?
First, you need to execute some piece of code before actual Webapp executes. Add the following to AssemblyInfo.cs
:
1 2 |
// Override configuration files [assembly: PreApplicationStartMethod(typeof(DatabaseConfiguration), "OverrideConnectionString")] |
This will run your code before anything related to Sitefinity gets chance to work so you can override the connection string in the file:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
using System.Web.Hosting; using System.Xml.Linq; using System.IO; namespace Cms { public class DatabaseConfiguration { public static void OverrideConnectionString() { var configurationFilePath = HostingEnvironment.MapPath("~/App_Data/Sitefinity/Configuration/DataConfig.config"); var document = XDocument.Load(configurationFilePath); var element = document .Element("dataConfig") .Element("connectionStrings") .Element("add"); element.Attribute("connectionString").Value = "YOUR_CONNECTION_STRING"; element.Attribute("dbType").Value = "DB_TYPE_EG_MsSql"; File.WriteAllText(configurationFilePath, document.ToString()); } } } |
The file is modified before application reads it so changes are visible in the application without restart.
Tested with Sitefinity version: 10.0.6411.0.