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.
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 have a small programm in which i copy paste stuff from A to B on the PC. The directory paths are written in the config, and when i (in the application) change the directory in the textbox it is updating the config file. I checked it, the value is immediatlely rewritten at the appropriate key. When i close the app and reopen it, it is updatet to the previously changed directory path, but i dont want to have to close the application and reopen is. I have a combobox and i want it to update as soon as the combobox reselect event triggers. But during the runtime (altough it is already changed in the config) it will not update the directory path shown in the app.
I read through and tried everything i found online and sadly nothing helped. Not every every kind of
ConfigurationManager.RefreshSection("appSettings");
THis is my config:
<appSettings file="">
<clear />
<add key="SourcepathClient" value="D:\xxx" />
<add key="SourcepathWin32" value="D:\xxx" />
<add key="DestinationpathUpdatePackages" value="D:\xxx" />
<add key="DestinationpathClient" value="D:\xxx" />
<add key="5_9_0-DestinationpathClient" value="D:\xxxt" />
<add key="5_9_0-DestinationpathUpdatePackages" value="D:\xxx" />
<add key="5_9_1-DestinationpathClient" value="D:\xxx" />
<add key="5_9_1-DestinationpathUpdatePackages" value="D:xxx" />
<add key="5_9_2-DestinationpathClient" value="D:\xxx" />
<add key="5_9_2-DestinationpathUpdatePackages" value="D:\xxx" />
</appSettings>
and this the code:
Configuration config = ConfigurationManager.OpenExeConfiguration(System.IO.Path.Combine(Directory.GetCurrentDirectory(), "UpdatePackager.exe"));
config.AppSettings.Settings[ComboBoxVersion.Text + "-DestinationpathClient"].Value = TextBoxDestinationpathClient.Text;
config.AppSettings.Settings[ComboBoxVersion.Text + "-DestinationpathUpdatePackages"].Value = TextBoxDestinationpathUpdatePackage.Text;
config.AppSettings.SectionInformation.ForceSave = true;
config.Save(ConfigurationSaveMode.Full);
ConfigurationManager.RefreshSection("appSettings");
I hope someone can help me.
Regards
i think there is no issue with code it issue related your access, it makes a difference if you run your application in IIS and run your test sample from Visual Studio. The ASP.NET process identity is the IIS account, ASPNET or NETWORK SERVICES (depending on IIS version).
Might need to grant ASPNET or NETWORK SERVICES Modify access on the folder where web.config resides.
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>
I have following code to start my server:
private static IXSocketServerContainer server = null;
public SocketServer()
{
server = XSockets.Plugin.Framework.Composable.GetExport<IXSocketServerContainer>();
}
this worked fine for me under WinXP and Win7, with exactly the same set of dll and exe files, but now I deployed my system under WinServer 2008 and I get following error:
clsSocketIntHandler|new , startin
servers|0|0||0||TypeInitializationException: ; The type initializer
for 'XSockets.Plugin.Framework.Composable' threw an exception. ; The
module was expected to contain an assembly manifest. (Exception from
HRESULT: 0x80131018)
Do you have any idea why could this be happening? What can be missing on my deployment machine? Can you please recommend me an alternative configuration to avoid this kind of dynamic loading?
My configuration now is as follows:
<appSettings>
<add key="XSockets.PluginCatalog" value="" />
<add key="XSockets.PluginFilter" value="*.dll,*.exe" />
</appSettings>
I answer this question only for completion and to help anyone that may face this problem. There are tow things you can do:
First: Upgrade to plug-in framework 1.3, (XSockets 3.0.3), this is mandatory
Second: try to limit the dll to load in case that you have a lot of libraries in the bin folder:
<appSettings>
<add key="XSockets.PluginCatalog" value="" />
<add key="XSockets.PluginFilter" value="XSockets.*,your.dlls.*" />
<!--
<add key="SocketServer.StartServers.Location" value="ws://localhost:3232" />
-->
</appSettings>
Uffe, thanks for your help!!
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.