How to obtain app.config of a different application and modify it - c#

I have two windows application. eg ., FormA and FormB
The app.config of FormA is as below
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="company" value="DSRC"/>
</appSettings>
<connectionStrings>
<add name="test" connectionString="Testing Connection String"/>
</connectionStrings>
</configuration>
Now I have another application named as Form B.
I want to retrieve both appsettings and connectionstrings of Form A into Form B.
Further I should be able to modify both of these appsettings and connection strings and save it into the Form A.
I know how to retrieve the appsettings , and connection strings of the same application and modify.
But how do I obtain of some other application and modify the same.
Kindly do let me know.
Actually I have 4 windows services running under one setup., one webservice and one wcf service and one application.
All these have different app.configs, comprising of different appsettings and different connection strings.
I am supposed to create a windows application that will retrieve each of these settings and then save it accordingly.
I tried upto this level
ExeConfigurationFileMap filename= new ExeConfigurationFileMap();
fileMap.ExeConfigFilename = #"D:\Home\FormA\FormA\bin\Debug\FormA.exe.config";
Configuration config =
ConfigurationManager.OpenMappedExeConfiguration(filename,
ConfigurationUserLevel.None);
But then just got struck, I just do not know how to proceed further (Sounds dumb right !)
Can anyone help me proceed down the way.
Regards
cmrhema

Basically, you need to open the configuration for that other executable something like this:
// full path to other EXE, including EXE extension - but *NOT* .config !!
string otherExePath = #"C:\........\OtherApp\bin\Debug\OtherApp.exe";
Configuration otherConfig =
ConfigurationManager.OpenExeConfiguration(otherExePath);
and then you can access all the settings on the new otherConfig configuration:
string otherSetting = otherConfig.AppSettings.Settings["TestSetting1"].Value;
and you can also save it back (provided you have the necessary permissions to that directory).
otherConfig.Save():

ExeConfigurationFileMap fileMap2
= new ExeConfigurationFileMap();
fileMap2.ExeConfigFilename = #"OtherFile";
Configuration config2 =
ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
ConnectionStringSettings newSettings =
config.ConnectionStrings.ConnectionStrings["oldSConString"];
ConnectionStringsSection csSection
= config2.ConnectionStrings;
csSection.ConnectionStrings.Add(newSettings);
config2.Save(ConfigurationSaveMode.Modified);
VS2005 C# Programmatically change connection string contained in app.config

Related

How do I get a list of all connection strings in app.config

In need to create an small console app, that takes two arguments:
File location for app.config file.
passkey
My problem is that the console app needs to read the connectionStrings and Encrypt it and then save the encrypted text to the config file. I have looked, but have not found any solution for it.
My app.config file could look like this:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<connectionStrings>
<add name="Conn1" connectionString="Data Source=Database1;Initial Catalog=DB12;User ID=User1234;Password=Qwerty123" providerName="System.Data.SqlClient" />
<add name="Conn2" connectionString="Data Source=Database2;Initial Catalog=DB12;User ID=User1234;Password=Qwerty123" providerName="System.Data.SqlClient" />
</connectionStrings>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
</startup>
</configuration>
I have the encryption part are done. I just need to in this example to read those two connectionstrings and encrypt them each. Please note that the name of the connectStrings are different every time, since the console app are triggered by TFS build server.
Basically you don't really need the name of the Connection String but the connection itself. I believe you just need to go thru them with foreach and for each iteration you can get the connectionString till the last one in the app.config.
foreach (System.Configuration.ConnectionStringSettings css in System.Configuration.ConfigurationManager.ConnectionStrings)
{
string connectionString = css.ConnectionString;
// encryption part
// rewriting the connectionString in the app.config or however you want ot be done
}
You mentioned you got the encryption part done and all you need is reading the strings.
Hope it helps!
If you donĀ“t know the name of the connection string, you could try it like this:
ConnectionStringSettingsCollection connections = ConfigurationManager.ConnectionStrings;
if (connections.Count != 0)
{
//go trough all available ConnectionStrings in app.config
foreach (ConnectionStringSettings connection in connections)
{
//reading the ConnectionString
string conString = ConfigurationManager.ConnectionStrings[connection.Name].ConnectionString;
//writing the ConnectionString
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.ConnectionStrings.ConnectionStrings[connection.Name].ConnectionString = EncryptConfig(conString); //just call your Encryption part here instead of "EncryptConfig()"
config.Save(ConfigurationSaveMode.Modified, true);
ConfigurationManager.RefreshSection("connectionStrings");
}
}
Use ConfigurationManager class like
ConfigurationManager.ConnectionStrings["Conn2"].ConnectionString
came up with this to work with both app and web, note i did also need to change the values and save them to disk so couldn't just loop through
var appConfig = System.Web.HttpContext.Current == null
? ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None)
: System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
var needsToSave = false;
foreach (var appCon in appConfig.ConnectionStrings.ConnectionStrings.Cast<ConnectionStringSettings>())
{
//do stuff
}

app.config exception SqlConnection without connection string

Here is my problem: I have a simple C# console app and I open my connection with
SqlConnection conn = new SqlConnection("Data Source=server;" + "Initial Catalog=database;" + "User id=sa;" + "Password=pass;timeout=60;");
That works fine. I added the app.config with some keys in the AppSettings. That works fine too.
But if I add a new tag to the config, the previous code gives me exception...why?!
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="template" value="value"/>
<add key="saveas" value="value"/>
</appSettings>
<tag>
</tag>
</configuration>
You cannot just add a random tag to your config file. The config file is parsed by the runtime and the runtime has to understand it.
If you want to do something with your custom tag, it might be helpful to ask a question about that (make sure you search existing questions before you do), because there are different ways to reach what you want (for example custom configuration sections). But until then, the quickest solution to make your problem go away is to simply delete the tag tag from your configuration file.
I'm not sure how you plug your connection string into your data handler. If you are using Linq, your project should have updated with the connection settings in the app.config automatically. I update my app.config during publication.
Here is a sample of what my config looks like. perhaps it will give you what you need. You can see how I added my own "tag" called ConnectivityDatabase and SysDatabase.

Dynamically Provide Username and password to Connection String

I am using C# winform application using MySql as back-end database. Using App.config file, application read connection string to connect database as follows:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionstring>
<addkey="MySQL.DB"value="server=localhost;database=mysqldbname;user=username;password=12345678;">
</add>
</connectionstring>
</configuration>
Is there any way that we can provide username and password not from App.config but from user of application, by entering username and password? so that we are able to protect sensitive data. Other information are ok to read from app.config like database name, server etc.
Ahmed
you can have appSettings
<appSettings>
<add key="ConFormat" value="server=localhost;database=mysqldbname;user={0};password={1};"/>
</appSettings>
read it and set the values
var formatString = ConfigurationManager.AppSettings["ConFormat"].ToString();
var conString = string.Format(formatString , SecureUserName, SecurePW);
If you're using raw ADO.NET then you can use a connection string builder, presumably a MySqlConnectionStringBuilder in your case. Create a new instance with the connection string from the config file, set the appropriate properties and then get the result from the ConnectionString property.
By the way, you can store passwords and other sensitive data in the config file using Protected Configuration to encrypt it.
Change the code in app.config like this
<add key="MySQL.DB"value="server=localhost;database=mysqldbname;user=&usernamefromuser;password=&passfromuser;">
Add a button for connecting and 2 textboxes for username and password
Buttons code :
//other code for mysql variables ...
string connectionStr= connStrFrom_App_Config.Replace("&usernamefromuser",texBox1.Text).Replace("&passfromuser",textBox2.Text);
//other code for connecting

load config from app.config if available

Im new to C# .net programming and sorry if I ask stupid question.
I have setup my programs to load setting from database instead off app.config.
However, I want it to replace the setting from app.config if only the setting available in it.
For example, the setting that will load from database is
IP_address = 192.168.0.111
folder_path = /share
pc_name = pc_dev
username = developer
password = developer123
then in app.config I will insert this value
IP_address = 192.168.0.222
the program will then change the IP_address value that it load from database to the value that I insert in app.config
is there anyway to do this?
Thank you
Easiest way is to use your app.config's appSettings. Add a reference to System.Configuration.
Then your app config should look like this:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="ipAddress" value="192.168.0.222"/>
</appSettings>
</configuration>
Then in your code, get the value from the config by using this:
string ipAddFromConfig = System.Configuration.ConfigurationManager.AppSettings["ipAddress"]; // get the value from the appsettings.
Then you can replace the value that you got from your DB.

Object reference not set to an instance of an object. - App.config

I receiving the error and in the local window I am seeing for both conSettings and connectionString value of null. I am right to say ConfigurationManager is null and I need to create a new object. Maybe I am using Access and perhaps I have missed something in App.config file. Can someone help me on how to solve this problem, please. Thanks in advance.
App.config file...
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="MyDBConnectionString" value="Provider=Microsoft.Jet.OLEDB.4.0;Data
Source=E:\...\Database1.mdb"/>
</appSettings>
</configuration>
Form.cs file...
private void btnShow_Click(object sender, EventArgs e)
{
ConnectionStringSettings conSettings = ConfigurationManager.ConnectionStrings["MyDBConnectionString"];
string connectionString = ConfigurationManager.ConnectionStrings["MyDBConnectionString"].ConnectionString; // error points here
try
{
con = new OleDbConnection(connectionString);
con.Open();
cmd = new OleDbCommand("SELECT * FROM Table1", con);
objReader = cmd.ExecuteReader();
while (objReader.Read())
{
txtID.Text = ds.Tables[0].Rows[rno][0].ToString();
CBAgeGroup.Text = ds.Tables[0].Rows[rno][1].ToString();
CBGender.Text = ds.Tables[0].Rows[rno][2].ToString();
CBCrimOffen.Text = ds.Tables[0].Rows[rno][3].ToString();
if (ds.Tables[0].Rows[rno][4] != System.DBNull.Value)
{
photo_aray = (byte[])ds.Tables[0].Rows[rno][4];
MemoryStream ms = new MemoryStream(photo_aray);
pictureBox1.Image = Image.FromStream(ms);
}
txtCV.Text = ds.Tables[0].Rows[rno][5].ToString();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
con.Close();
}
}
I have been advised to use App.config.
VS 2010 C#
MS Access 2003
UPDATE 1
My App.config now looks like this...
<configuration>
<ConnectionString>
<add key="MyDBConnectionString" value="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Raj\Education\C_Sharp\Test1\Database1.mdb"/>
</ConnectionString>
I am now receiving error of..."Configuration system failed to initialize". I am looking at it now on Google.
Update 2
Tried...
<configuration>
<connectionStrings>
<add name="MyDBConnectionString" connectionString="Provider=Microsoft.Jet.OLEDB.4.0;Data
Source=E:\...\Database1.mdb"/>
</connectionStrings>
</configuration>
Receiving error of "Object reference not set to an instance of an object" Googling again
Update 3
<configuration>
<connectionStrings>
<clear />
<add name="MyDBConnectionString"
providerName="System.Data.OleDb" connectionString="Provider=Microsoft.Jet.OLEDB.4.0; Source=\Database1.mdb" />
</connectionStrings>
With the update 3 I am receiving error the same error. I have included the Add reference System. Configuration and I have referenced using System.Configuration;
Conclusion
Perhaps it maybe there is a technical gitch between VS 2010 and Access 2003. I shall not use App.config this time round. I know there will be no problem with SQL Server. So I will leave it that. Thanks Damith and Clint for your time.
you need to read AppSettings key as below ,
string connectionString =
ConfigurationSettings.AppSettings["MyDBConnectionString"];
still you receive empty value, try below steps
Select the App.Config file in the solution explorer
In the property window select Copy to Output Directory to Copy
Always.
Now Build the application and try again.
to access like below you need to add connectionStrings section in app config
string connectionString =
ConfigurationManager.ConnectionStrings["MyDBConnectionString"].ConnectionString; // error points here
sample app config
<?xml version="1.0"?>
<configuration>
<connectionStrings>
<add name="MyDBConnectionString"
connectionString="Provider=Microsoft.Jet.OLEDB.4.0;Data
Source=E:\...\Database1.mdb"/>
</connectionStrings>
</configuration>
Check if you have put the app.config file under your startup project or not. In my case, I just had to put the app.config file under my startup project, and problem was solved.
This happened to me in class library with a console app set to run for debugging.
It is necessary to add the connection to the app.config in the console app, as it will not find it in your library if you're starting it from an outside process.
This:
string connectionString = ConfigurationManager.ConnectionStrings["MyDBConnectionString"].ConnectionString;
is your problem.
You're accessing ConfigurationManager.ConnectionStrings to get to your configuration item, but in the App.Config file you've put it under appSettings which is a different section of the config file than ConnectionStrings
You could either put your connection string in the relevant ConnectionStrings section of the app.config (accessible with ConfigurationManager.ConnectionStrings, or access it against the appSettings section.
See:
http://msdn.microsoft.com/en-us/library/ms254494(v=vs.80).aspx
For MSDN guidelines on storing connection strings.
I too faced the same problem even after multiple scrutinizing the app.config files and my code for error, but i didn't found any errors in my code. Eventually i found a silly mistake that my compiler had by default taken the application configuration file name as 'app1.config', and when i changed it to 'app.config' every thing just worked fine for me.
Hope it will help.
I bumped into this problem when I added app.config file by Project -> Add -> New Item... -> Application Configuration File to an old, tiny C# library that had been originaly written in .NET Framework 4.5 and later updated to 4.7.2. After many attempts I decided to load config file just as a XML file. If everything else failed you may consider using this workaround.
App.settings
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="MyDBConnectionString"
providerName="System.Data.OleDb" connectionString="Provider=Microsoft.Jet.OLEDB.4.0; Source=\Database1.mdb" />
</connectionStrings>
</configuration>
Code behind
using System;
using System.IO;
using System.Reflection;
using System.Xml;
XmlDocument doc = new XmlDocument();
string path = Path.GetDirectoryName(new Uri(Assembly.GetExecutingAssembly().CodeBase).LocalPath) + "\\YourProjectName.exe.config";
doc.Load(path);
XmlNode node = doc.SelectSingleNode("//connectionStrings");
XmlElement value = (XmlElement)node.SelectSingleNode("//add[#name='MyDBConnectionString']");
string connectionString = value.Attributes["connectionString"].Value;
The effect should be similar to:
string connectionString = ConfigurationManager.ConnectionStrings["MyDBConnectionString"].ToString();
OR
string connectionString = ConfigurationManager.ConnectionStrings["MyDBConnectionString"].ConnectionString;
Hope that someone will find this useful.

Categories

Resources