This library is designed to allow the modification of configuration files via the Microsoft.Web.Xdt library. It uses the transform syntax that we all know and love. You can utilize this library in memory with no need to access any files, but you can do that as well.
You can install this package via Nuget under the package id of RimDev.Automation.Transform.
PM> Install-Package RimDev.Automation.Transform
Next step is to have a source and a transform file ready. Please read the transformation documentation before attempting to use this library.
When you have your files ready, you can perform a transformation with the following code.
using (var transformer = new ConfigurationTransformer()) {
var result
= transformer
.SetSourceFromFile("web.config")
.SetTransformFromFile("web.debug.config")
.Apply("web.transformed.config");
}
You get a few methods that allow you to construct transformations programatically.
- InsertAppSetting
- ReplaceAppSetting
- InsertSqlConnectionString
- ReplaceSqlConnectionString
- InsertConnectionString
- ReplaceConnectionString
- InsertCustomErrorSetting
- ReplaceCustomErrorSetting
- InsertSmtpSetting
- ReplaceSmtpSetting
using (var transformer = new ConfigurationTransformer()) {
transformer
.SetSourceFromFile("web.config")
.Transform.InsertAppSetting("hello", "world");
var result = transformer.Apply("web.transformed.config");
}
The methods utilize the transform syntax, and append it to your transformation config. You can load an existing transform while still appending additional programatic values.
using (var transformer = new ConfigurationTransformer()) {
transformer
.SetSourceFromFile("web.config")
.Transform
.InsertCustomErrorsSetting("ON", "~/error", customErrors =>
{
customErrors.AddError(400, "~/error/400");
customErrors.AddError(500, "~/error/500");
})
.InsertSmtpSetting(smtpDeliveryMethod: SmtpDeliveryMethod.SpecifiedPickupDirectory,
from: "[email protected]",
smtpBuilder: smtpBuilder =>
{
smtpBuilder.AddSpecifiedPickupDirectory(@"c:\email");
smtpBuilder.AddNetwork(host: "localhost");
});
var result = transformer.Apply("web.transformed.config");
}
The CustomError and Smtp setting methods allow you to pass an Action to specify the child elements of the respective parent elements.
Thanks to Ritter IM for supporting OSS.