How to remove a ConnectionString using Config Transformations - c#

I have a Web.config with several ConnectionStrings
<connectionStrings>
<add name="connStr1" connectionString="...
<add name="ConnStr2" connectionString="...
<add name="connStr3" connectionString="...
Is there a way using config transformations to remove a specific connectionstring? Something Like:
<connectionStrings>
<xdt:Remove connStr2?
Obviously no where near the correct syntax, but you get my drift...

This will remove a specific connection string based on its name.
<configuration>
<connectionStrings>
<add name="ConnStr2" xdt:Transform="Remove" xdt:Locator="Match(name)" connectionString=" " />
</connectionStrings>
</configuration>
Note that the connectionString value is not empty string, but is instead a space. Any non-empty value would do.

From the MSDN documentation on the subject:
<configuration xmlns:xdt="...">
<connectionStrings>
<add xdt:Transform="Remove" />
</connectionStrings>
</configuration>
The Transform="Remove" is the magic you're looking for. There is also a Transform="RemoveAll" which you might be able to use in conjunction with a specific add(s).
EDIT
On second thought you may also be able to combine the Locator attribute with the Remove defined above to limit which elements you actually want to delete.
More definitively:
<configuration xmlns:xdt="...">
<connectionStrings>
<add xdt:Transform="Remove" xdt:Locator="XPath(configuration/connectionStrings[#name='ConnStr2'])" />
</connectionStrings>
</configuration>
Or similar should work.

Related

App.config transformation is not working based on environment

I have a console application and I need to separate app.config for diff. env in order to use different connection strings.
I right-clicked on App.config -> Add config transforms and got two files:
App.Debug.config
App.Release.config
Those files are following:
<?xml version="1.0"?>
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-
Transform">
<connectionStrings>
<add name="SqlCpaConnectionString"
connectionString="blahblah"
providerName="System.Data.SqlClient"/>
<add name="AzureStorageConnectionString"
connectionString="blahblah"
providerName="Microsoft.WindowsAzure.Storage"/>
When getting the settings like:
ConfigurationManager.ConnectionStrings["AzureStorageConnectionString"].ConnectionString
I get null ref ex on both of envs...
See following answer. This will also work with console apps: How do I use Web.Config transform on my connection strings?
Set the connection string transform:
<connectionStrings>
<add name="local" connectionString="Data Source=IPAddress,Port;Initial Catalog=SomeOtherDB;User ID=TopSecretUsername;Password=SecurePassword"
xdt:Transform="SetAttributes" xdt:Locator="Match(name)"/>
</connectionStrings>

In C#, how do i cope with XmlException: 'xdt' is an undeclared prefix. when trying to set new password in connectionString?

I am trying to set a new password in my app.config files. I tried to do this using code below. Exception is thrown here because of the xdt:Transform in the connectionString:
configuration.ConnectionStrings.ConnectionStrings["DbContext"].ConnectionString
= string.Format("Data Source=x ;Initial Catalog=x ;User='sa';Password='{0}';",
textBox1.Text);
Reason: "System.Configuration.ConfigurationErrorsException: ''xdt' is an undeclared prefix. "
This is a transformed config file and hence contains "xdt:Transform"
Here is the connectionstring I want to change:
<connectionStrings>
<add name="DbContext" connectionString="Data Source=x;Initial
Catalog=x;User='sa';Password='x';"
xdt:Transform="Replace" xdt:Locator="Match(name)"/>
</connectionStrings>
Is there any possibility to somehow parse a connectionString part of the xml file? Thank you in advance!
The xdt namespace should be defined. In the a web.release.config file (*), this is done like this:
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
<!--
in the example below, the "SetAttributes" transform will change the value of a connectionstring
-->
<connectionStrings>
<add name="MyConnectionString" connectionString="some value" xdt:Transform="SetAttributes" xdt:Locator="Match(name)" />
</connectionStrings>
</configuration>
*) I must admit that these transformations are normally used for web.config files rather than app.config files. However, it can be done for app.config also, but this is another topic.

Can't read connection string from web.config

I have the following in my web.config located at the root of my project:
<configuration>
<connectionStrings>
<clear />
<add name="Default" providerName="System.Data.SqlClient" connectionString="Server=tcp:whoops;Encrypt=True;TrustServerCertificate=False;Connection Timeout=3000;" />
</connectionStrings>
<appSettings>
<add key="ConnectionString" value="test"/>
</appSettings>
....
I read from Startup.cs (this is an asp.net core web app):
string connection = ConfigurationManager.ConnectionStrings["Default"].ConnectionString;
However when I break on this, ConfigurationManager.ConnectionStrings and ConfigurationManager.AppSettings are empty (well, the first has some default connection string that is not the one in web.config).
What's going on here?
You will have to migrate the config to the new file appsettings.json
https://learn.microsoft.com/en-us/aspnet/core/migration/configuration?view=aspnetcore-2.1
Not saying this is how you should do it, but you can do the following...
In ASP.Net Core 2.2, you should be able to add an XML configuration to IConfigurationBuilder using
configBuilder.AddXmlFile("app.config");
Contents is pretty much the same as above...
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<connectionStrings configSource="connectionStrings.config" />
<appSettings>
<add key="Test" value="TestValue" />
</appSettings>
</configuration>
You should then be able to access AppSettings/ConnectionStrings using...
ConfigurationManager.ConnectionStrings
ConfigurationManager.AppSettings.AllKeys
{string[1]}
[0]: "Test"
ConfigurationManager.AppSettings.Get("Test")
"TestValue"

Is it possible to reference the same connection string in multiple places in a config file?

<?xml version="1.0" encoding="utf-8"?>
<configuration>
<connectionStrings>
<add name="DefaultConnection" connectionString="Server=test.com,1234;" providerName="System.Data.SqlClient" />
</connectionStrings>
<appSettings>
<add key="serilog:write-to:MSSqlServer.connectionString" value="here reference the DefaultConnection connection string." />
</appSettings>
</configuration>
Same connection strings needs to be referenced in multiple places. For typo mistakes I would like to be able to reference a single connection string in the same file.
Is this possible?

Is there anything wrong with ConfigurationManager in C#?

I read many topics related to configuration manager but could not resolve the issue. I just want to read the connection string as well some appsetting keys from a CLASS LIBRARY in the web application.
I have reference to System.Configuration Class.
This is my code:
using System.Configuration;
...
string constr = ConfigurationManager.ConnectionStrings["cbuddydb"].ConnectionString;
string strUserName = ConfigurationManager.AppSettings["username"];
string strPwd = ConfigurationManager.AppSettings["password"];
But it seems reading from a different config file. not from the web.config in my project. Because the value read is wrong.
My web.config is below:
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0" />
</system.web>
<system.data>
<connectionStrings>
<clear />
<add name="cbuddydb" connectionstring=
"Driver={MySQL ODBC 5.1 Driver};Server=localhost;Database=myDataBase;Persist Security Info=True;
User=#username;Password=#password;Option=3" providerName="MySql.Data.MySqlClient" password=""/>
</connectionStrings>
<appSettings >
<clear />
<add key="username" value ="6/0RUNnSmUBsbdNoCg+9Sw=="/>
<add key="password" value =""/>
</appSettings>
</system.data>
</configuration>
The reason for this is because of configuration file inheritance. The connection string at index 0 may not be in your config file, but it may have been inherited from machine.config etc. Have a look at ASP.Net config file hierarchy and inheritance: http://msdn.microsoft.com/en-us/library/ms178685.aspx
You could clear the inherited connection strings by specifying the following in your web.config
<connectionStrings>
<clear />
<add name=”MyConnString” connectionString=“Whatever“ />
</connectionStrings>
EDIT: In your config, place your connectionStrings and appSettings tags directly below the configuration element. They should not be within the system.data element. They are direct children of the configuration element. And remove the extra password attribute after the providerName. I can't validate your connection string, since I don't know how you're using it.
<configuration>
<connectionStrings>
<clear />
<add name="cbuddydb" connectionString=
"Driver={MySQL ODBC 5.1 Driver};Server=localhost;Database=myDataBase;Persist Security Info=True;
User=#username;Password=#password;Option=3" providerName="MySql.Data.MySqlClient"/>
</connectionStrings>
<appSettings >
<add key="username" value ="6/0RUNnSmUBsbdNoCg+9Sw=="/>
<add key="password" value =""/>
</appSettings>
<system.data>
....
You should consider encrypting sensitive information in your config file, like passwords.

Categories