How to move connectionString from App.config to code in C#? - c#

I want to remove connectionString from App.config and add it to code. I'm using WinForms(C#) and .Net Framework 4.8. I have textBoxes and a datagridview on my form. I'm using Microsoft Access Database (.mdb). I want to do this because database's password is visible in App.config. Is there any way to do that
Here is my app.config XML code :
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
</configSections>
<connectionStrings>
<add name="Locker.Properties.Settings.pw_dbConnectionString"
connectionString="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\files\pw_db.mdb;Persist Security Info=True;Jet OLEDB:Database Password=XYZ"
providerName="System.Data.OleDb" />
</connectionStrings>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.8" />
</startup>
</configuration>

I would suggest you not to define the connection string in code, better you can encrypt it in the app.config file.
Please follow the following steps:
Rename app.config to web.config
Open command prompt and type:
%windir%\Microsoft.NET\Framework\v2.0.50727\aspnet_regiis -pef
"connectionStrings" path of the web.config>
Rename web.config back to app.config
If you open the file in notepad, you will see the encrypted value and you can continue using it as you were using before.

Related

How to define and encrypt a connection string in app config file

I have created a application with c#. I define a connection string in app config file. Here is my app config file code:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<startup useLegacyV2RuntimeActivationPolicy="True">
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
</startup>
<appSettings>
<add key="con" value="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\myFolder\Mydb.mdb;Persist Security Info=True;Jet OLEDB:Database Password=bd1234" />
</appSettings>
</configuration>
I want to create that code to this following format and encrypted password value.
<?xml version="1.0"?>
<configuration>
<configSections>
</configSections>
<appSettings>
<add key="ServerName" value="user"/>
<add key="Provider" value="Microsoft.Jet.OLEDB.4.0"/>
<add key="Data Source" value="C:\myFolder\Mydb.mdb"/>
<add key="Persist Security Info" value="True"/>
<add key="Jet OLEDB:Database Password" value="*******"/>
</appSettings>
<startup useLegacyV2RuntimeActivationPolicy="true">
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
</startup>
</configuration>
How can i do that?
Good question.
Ideally, if you can use windows authentication, this will solve your issue without having to protect your config file.
Try adding the following:
<add key="con" value="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\myFolder\Mydb.mdb;Persist Security Info=False;Integrated Security=SSPI;Jet OLEDB:Database" />
Here is an MSDN doc with more details:
https://learn.microsoft.com/en-us/visualstudio/ide/managing-application-settings-dotnet?view=vs-2017
If you do need to protect your app config, you can use the .NET famework "ProtectSection" function which will encrypt your config file (using machine.config key), and your application will be able to access the config details, but it is not easily visible.
Given the security implications it is worth having a detailed look of how it works:
https://learn.microsoft.com/en-us/dotnet/framework/data/adonet/connection-strings-and-configuration-files
Have you tried below?
string value = System.Configuration.ConfigurationManager.AppSettings[key];
Requires add reference System.Configuration
if you know that how you will do the encryption then you can save the encrypted password following this way
How to update app settings key value pair dynamically on app.config file in c# winforms
To do the encryption and save the app settings follow the link of #ksdev
Encrypt password in App.config

configuration system failed to initialize in visual studio 2010 windows form

I'm currently facing this error while running my c# program:
configuration system failed to initialize
here is my app.config file:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<add name="FastConnection"
connectionString="DataSource=.\SQLEXPRESS;AttachDbFilename=C:\Users\mustiondb.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True" />
</configSections>
</configuration>
I believe there is probably information lacking in this app.config file. However, I'm not sure what information. When I created an app config file from my windows form (visual studio 2010), the only information in the app config file was this:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
</configuration>
I tried searching for information to add in, but i'm not sure what and where to find these information.
If you want to use connection string use <connectionStrings> not <Configurations>
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="FastConnection" connectionString="DataSource=.\SQLEXPRESS;AttachDbFilename=C:\Users\mustiondb.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True" />
</connectionStrings>
</configuration>
If you need to add custom application settings
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="Key0" value="0" />
<add key="Key1" value="1" />
<add key="Key2" value="2" />
</appSettings>
</configuration>
I faced the same issue. I had an & in one of the strings of app.Config and somehow Visual Studio didn't show the error while building. After replacing & with & it worked fine.

ConfigurationManager.AppSettings[key] not accessible within class library

I am unable to access CloudfigurationManager from within an method. The code was originally a klass library and I added a configuration file (App.config) where I am simply adding the values for a hard coded test for Azure SDK.
OpenSessionWithAzure()
private void OpenSessionWithAzure()
{
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(ConfigurationManager.AppSetting["APP_SETTINGS"])// Visual Studio is unable to identify ConfigurationManager
}
App.config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="StorageConnectionString" connectionString="DefaultEndpointsProtocol=https;AccountName=userName;AccountKey=Key"/>
<add name="SasPolicyName" connectionString="myPolicy"/>
</connectionStrings>
</configuration>
Is there a reason why I am unable to access the ConfigurationManager within my application or a known workaround?
The reason for this error was due to the fact that I did not:
Have a reference to System.Configuration.dll in my class library.
Did not have the using System.Configuration
After adding performing the steps above I am not able to access ConfigurationManager.AppSettings["APP_SETTINGS"]
You need to add reference to System.Configuration and then add key-value pair in appSettings section
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="SasPolicyName" value="myPolicy" />
<add key="APP_SETTINGS" value="MySetting" />
</appSettings>
<connectionStrings>
<add name="StorageConnectionString" connectionString="DefaultEndpointsProtocol=https;AccountName=userName;AccountKey=Key"/>
</connectionStrings>
</configuration>
Then use like below,
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(ConfigurationManager.AppSetting["APP_SETTINGS"])
The method signature you use must be consistent with the setting in your App.config.
With the setting below,
<configuration>
<appSettings>
<add key="StorageConnectionString" value="XXXXXXXXX"/>
</appSettings>
</configuration>
use System.Configuration.ConfigurationManager.AppSettings["StorageConnectionString"].
And System.Configuration.ConfigurationManager.ConnectionStrings["StorageConnectionString"] for
<configuration>
<connectionStrings>
<add name ="StorageConnectionString" connectionString="XXXXXXXXXX"/>
</connectionStrings>
</configuration>
When you attempt to read from appSettings, it reads from the .config file of the executing application. So in the simplest implementation you'd just need to add those configuration settings to that application's .config file (app.config or web.config.) There are other ways to approach it if you absolutely need the library to have its own .config file, but adding it to the executing application's .config is what's done most commonly.

'Dynamic' connection string for ms-access C#

I have an access database connected to my code via a connection string as shown:
connection = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Me\Documents\Visual Studio 2013\Projects\Computing Project\Database.accdb;
Persist Security Info=False;");
However I would like this app to be able to be installed on other devices, so I'm guessing the connection string has to be dynamic and change on each system. How would I use this in my code?
Add an App.config to the solution with following content
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.1" />
</startup>
<connectionStrings>
<add name="MyCon" connectionString="Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Me\Documents\Visual Studio 2013\Projects\Computing Project\Database.accdb; Persist Security Info=False;"/ >
</connectionStrings>
</configuration>
Then in code,
connection = new OleDbConnection(ConfigurationManager.ConnectionStrings["MyCon"].ToString());
PS: ConfigurationManager class is in assembly System.Configuration.
So please add a reference of this assembly before using it.

A Visual Studio 2008 automated tests project can read a configuration file like app.config? (C# .NET)

I have an app.config file inside my TestProject, but when I try to read it using ConfigurationManager it reads from somewhere else and it's none of my app.config's. How to correct this?
Current config:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="Production" connectionString="Server=127.0.0.1,2345;Uid=user;Pwd=password;Initial Catalog=DATABASE_DATA"/>
</connectionStrings>
</configuration>
Current code:
ConfigurationManager.ConnectionStrings[0].ConnectionString
Expected output:
"Server=127.0.0.1,2345;Uid=user;Pwd=password;Initial Catalog=DATABASE_DATA"
Actual output:
"data source=.\\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true"
Try Referencing it by name.
ConfigurationManager.ConnectionStrings["Production"].ConnectionString
The config files automatically integrate machine.config which has that SQLEXPRESS connection string by default.

Categories

Resources