I have an entry in my <appSettings> section which contains my connection string. By default, it looks for the file on the root of the C: drive.
<appSettings>
<add key="EnvironmentFile" value="C:\environment.extension" />
</appSettings>
I need to modify the value of the entry programmatically since the app will be deployed to a different server (Appharbor), which I don't have access to the C drive. I moved the environment file to the root of the app directory which means I need to modify the appSettings value for EnvironmentFile. Here's what I have tried so far, I have resorted to the following since I can't put relative values on web.config such as
value="~/environment.extension"
Default.aspx:
protected void Page_Load(object sender, EventArgs e)
{
if(ConfigurationManager.AppSettings["EnvironmentFile"] == null)
{
Configuration config = WebConfigurationManager.OpenWebConfiguration("~");
config.AppSettings.Settings.Add("EnvironmentFile", AppDomain.CurrentDomain.BaseDirectory + #"environment.extension");
config.Save(ConfigurationSaveMode.Minimal);
ConfigurationManager.RefreshSection("appSettings");
}
if (IsPostBack == false)
{
//--some business logic here that gets data from the database
}
}
In debug mode, it does modify my web.config but throws an exception since it is already executing the code on my if block. Are there other ways to do this such that I have different configuration for debug and release?
Yes, there is another way of doing this.
If you right click on your Web.Config in Visual Studio you'll see an option to 'Add Config Transform'. This allows you to create transformations for your various configurations. The newly added Web.XXX.config files will have some examples of how to transform your entries, but a simple example would be:
In your base Web.Config:
<appSettings>
<add key="Mode" value="Development" />
</appSettings>
And then in a WebConfig.LiveRelease.config file you might have this:
<appSettings>
<add key="Mode" value="Live" xdt:Transform="SetAttributes" xdt:Locator="Match(key)"/>
</appSettings>
Related
I am developing a WPF application which runs well in visual studio v.2022 very well. My problem is when I deploy the application to another computer for testing it does not seem to be updating app.config data. When I change the ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None) to NONE it works well in both debug and release mode in Visual Studio but throws an error when deployed to another computer. The error I am getting is "System configuration.configuration error exception - An error ocurred while loading the the configuration file myApp.dll.config. Access denied "
I gather that the user has no write privileges on the Program Files folder where the app.config is stored. However, when I change the user level to either Roaming or Roaming and local, then nothing happens as the configuration file is not located and if at all the changes are made then they are not persisting. Here is my app.config file
<configuration>
<appSettings>
<add key="Server" value=""/>
<add key="Port" value=""/>
<add key="Database" value=""/>
<add key="User" value=""/>
<add key="Pwd" value=""/>
<add key="Code" value=""/>
<add key="Access" value=""/>
<add key="Status" value=""/>
<add key="EndDate" value=""/>
</appSettings>
</configuration>
Here is my method for updating the the app.config
public static void UpdateSetting(string key, string value)
{
Configuration roaming = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();
fileMap.ExeConfigFilename = roaming.FilePath;
Configuration configuration = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
var appSettings = configuration.AppSettings;
foreach (var keys in appSettings.Settings.AllKeys.Where(x => x.StartsWith(key)))
{
appSettings.Settings[keys].Value = value;
}
configuration.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("appSettings");
}
and here is an example of how the method is called Settings.UpdateSetting("Code", _Code);
Any help will be much appreciated
Following #Joe's comment it occurred to me that it was not possible to write to config application data at runtime. I opted to create a new section in the config file in the Properties.Settings folder in my solution and assigned the scope to User and not application since the user is able to update the data at runtime. Double click on the settings.Settings file to open in designer view and literally entered the settings names to be stored.
The stored settings can be saved and retrieved using the methods below.Properties.Settings.Default.yourSetting. to get the settings.
And to store/save the settings
Properties.Settings.Default.yourSetting= val;`
Properties.Settings.Default.Save();`
That solved my problem.
I need to read web.config file, outside the application's folder (located in any other directory).
I tried this code:
string filePath = #"C:\Users\Idrees\Downloads\New folder\Web.config";
Configuration c1 = ConfigurationManager.OpenExeConfiguration(filePath);
var value1 = c1.AppSettings.Settings["Key1"].Value;
But it is giving me the error:
Object reference not set to an instance of an object.
Because here, c1.AppSettings is an object, but c1.AppSettings.Settings contains not items (hence 0 Count). It is not really loading the AppSettings keys. When trying to read any Key from Settings collection, it gives this error.
Is there any way how to load AppSettings keys from a web.config file outside the application folder.
If I put same file within application folder, then it reads the keys successfully.
This is my sample config file's content:
<?xml version="1.0" encoding="utf-8"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=169433
-->
<configuration>
<connectionStrings>
<!--here goes my connection strings-->
</connectionStrings>
<appSettings>
<add key="Key1" value="Value1" />
<add key="Key2" value="Value2" />
<add key="Key3" value="Value3" />
</appSettings>
</configuration>
I have a web application already running on my server. And I need to develop a small utility which has to do some job in database, and I don't want to write db credentials or connection string(and some other additional app-settings) in each application, I want it to read same thing from web.config.
You can using ConfigurationManager to read arbitrary configuration files by opening a mapped exe configuration as follows:
var filePath = #"C:\Users\Idrees\Downloads\New folder\Web.config";
var fileMap = new ExeConfigurationFileMap { ExeConfigFilename = filePath };
var configuration = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
var value = configuration.AppSettings.Settings["Key1"].Value;
As I understand from your comment you want some kind of shared configuration accross multiple app on the same computer. You may consider using external file like this :
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<connectionStrings configSource="config\connString01.config"/>
<appSettings file="config\config01.config">
<add key="Var3" value="Var3 value from main config file"/>
</appSettings>
in above .config example connectionStrings is sourced from an other file. Below an example what can be such an external config file:
<connectionStrings>
<add name="SQLConnectionString01" connectionString="Data Source=sourcename01;Initial Catalog=cat01;Persist Security Info=True;Integrated Security=true;"/>
</connectionStrings>
Read documentation: ConfigurationManager.OpenExeConfiguration on MSDN
public static Configuration OpenExeConfiguration(
string exePath
)
This is EXE path
I use app.config to store some info. My file looks like this:
<?xml version="1.0"?>
<configuration>
<appSettings>
<add key="używajDomyślnie" value="false" />
<add key="sInicjały" value="ŁM" />
<add key="nPrzedstawiciel" value="Łukasz Motyczka" />
<add key="nPozycja" value="Przedstawiciel Naukowo-Handlowy" />
<add key="nTelefon" value="+48 784 567 670" />
<add key="nEmail" value="motyczka.lukasz#bmgrp.pl" />
<add key="dataoferty" value="" />
<add key="ostatniNrOferty" value="" />
</appSettings>
<connectionStrings>
<add name="Oferty_BMGRP.Properties.Settings.BazaDanychConnectionString" connectionString="Data Source=|DataDirectory|\BazaDanych.sdf" providerName="Microsoft.SqlServerCe.Client.3.5" />
</connectionStrings>
<system.windows.forms jitDebugging = "true"/>
</configuration>
The snippet that throws a NullexceptionError is:
if(checkBox1.CheckState == CheckState.Checked)
{
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
AppSettingsSection app = config.AppSettings;
//app.Settings.Clear();
//app.Settings.Add("używajDomyślnie", "true");
//app.Settings.Add("sInicjały", sInicjaly.ToString());
//app.Settings.Add("nPrzedstawiciel", nPrzedstawiciel.ToString());
//app.Settings.Add("nPozycja", nPozycja.ToString());
//app.Settings.Add("nTelefon", nTelefon.ToString());
//app.Settings.Add("nEmail", nEmail.ToString());
config.AppSettings.Settings["używajDomyślnie"].Value = "true"; //<- THIS LINE GIVES ME AN ERROR
config.AppSettings.Settings["sInicjały"].Value = sInicjaly.ToString();
config.AppSettings.Settings["nPrzedstawiciel"].Value = nPrzedstawiciel.ToString();
config.AppSettings.Settings["nPozycja"].Value = nPozycja.ToString();
config.AppSettings.Settings["nTelefon"].Value = nTelefon.ToString();
config.AppSettings.Settings["nEmail"].Value = nEmail.ToString();
config.Save(ConfigurationSaveMode.Modified);
form1.checkBox1.CheckState = CheckState.Checked;
}
When I debug it or build release in VS it works fine. Also it works on my laptop. But on every other machine I have null exception error. Also it worked until I tried to make a setup project (which works but meesed up this one). Whatmore the jit Debugging does not work, I still have a .net error (continue or exit).
Also I did notice that on my computer and some other laptop I was using, when error occurs it shows:
System.NullReferenceException: Odwołanie do obiektu nie zostało ustawione na wystąpienie obiektu.
w Oferty_BMGRP.Form3.button1_Click(Object sender, EventArgs e) w C:\Users\user\Documents\Visual Studio 2010\Projects\BMGRP\Oferty BMGRP\OfertyBMGRP\Form3.cs:wiersz 282
Sorry for polish, but what I want to point is that on both machines it shows path to same folder, which exists only on one of them.
Please help :)
EDIT!
I just found out that if I build the release. Run application and make th above code run, it creates MyApplication.exe.config file, and then app works fine on every computer. How can I make it to work as setup project, where .exe.config is not created, only app.config?
You're trying to set the Value property of a null object. Settings["blah"] is returning null before you even have a chance to set the value.
Try this instead:
config.AppSettings.Add("key", "value");
Or maybe will a null check:
if(config.AppSettings.Settings["key"] == null)
{
config.AppSettings.Add("key", "value");
}
MyApplication.exe.config is app.config, and you shouldn't mess with that paradigm. It's how .net applications are intended to work.
If you want to do your configuration differently than that, than you can either do your own file IO or find another external configuration library.
I use System.Configuration.ConfigurationManager.AppSettings["key1"] in settings.designer.cs file. It's working fine in the development but after I moved all the .dll files into production it is not working.
In web.config file I added app settings in development and production both. What is the problem?
Code from settings.designer.cs file
get
{
return WebConfigurationManager.AppSettings["ConnectionString"];
//return (AppSettings["ConnectionString"]);
//return ((string)(this["ConnectionString"]));
}
I tried all three return statements. 3rd return is working fine in both dev & prod but it is not rendering from web.config.
Code in web.config
<add key="ConnectionString" value="connection string values are given here">
Don't use WebConfigurationManager.
Use System.Configuration.ConfigurationManager.AppSettings["key"] instead to read key-value pair kept in Web.config, e.g.:
<configuration>
<appSetttings>
<add key="key1" value="value1" />
</appSetttings>
</configuration>
and System.Configuration.ConfigurationManager.ConnectionStrings["name"].ConnectionString to read connection string, e.g.:
<configuration>
<connectionStrings>
<add name="name" connectionString="value1" />
</connectionStrings>
</configuration>
You have to add configuration setting (connectionstring) to last execution program config file.
Create app.config in wpf (c#)
<?xml version="1.0"?>
<configuration>
<connectionStrings>
<clear />
<add name="Name"
providerName="MySql.Data"
connectionString="Server=.net;Uid=;Pwd=H;Database=;charset=utf8;Allow Zero Datetime=true;" />
</connectionStrings>
</configuration>
used code C#:
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
ConnectionStringsSection conStr = config.ConnectionStrings;
if (!conStr.SectionInformation.IsProtected)
{
conStr.SectionInformation.ProtectSection("RSAProtectedConfigurationProvider");
conStr.SectionInformation.ForceSave = true;
config.Save();
}
else
{
foreach (ConnectionStringSettings ss in conStr.ConnectionStrings)
Console.WriteLine(ss);
Console.Read();
}
config.Save(); - causes exception:
{"Failed to encrypt the section 'connectionStrings' using provider
'RsaProtectedConfigurationProvider'. The error message from the
provider: Object already exists .\r\n"}
I was getting the same exception on Save. By running the application as an Administrator, I was able to get around this.
I added an app.manifest file to my project, and changed the execution level like so: requestedExecutionLevel level="requireAdministrator" uiAccess="false"
This way, I always run as admin, and have permissions to save the encrypted section.
Check the SectionInformation.ProtectSection Method
also check here
You could look at using the aspnet_regiis.exe to perform encryption for you. Refer to this
MSDN Link
This way you could perform encryption without writing code.