Problem with SQL Connection exception on creating object - c#

I created a SQL Server database in Visual Studio 2013.
I have a problem when I am trying to create a new SqlConnection object. The same code worked yesterday, but now I have some problem. I also added the SQLException but I can't reach this code
try
{
string connectionString = ConfigurationManager.ConnectionStrings["MyKey"].ConnectionString;
SqlConnection sqlConnection = new SqlConnection(connectionString);
sqlConnection.Open();
}
catch (System.Data.SqlClient.SqlException sqlException)
{
System.Windows.Forms.MessageBox.Show(sqlException.Message);
}
Application.Run(new LoginForm());
SqlConnection did not work. This is the exception. I don't know what it is wrong because it did work before
System.TypeInitializationException was unhandled
HResult=-2146233036
Message=The type initializer for 'System.Data.SqlClient.SqlConnection' threw an exception.
Source=System.Data
TypeName=System.Data.SqlClient.SqlConnection
StackTrace:
at System.Data.SqlClient.SqlConnection..ctor(String connectionString)
InnerException: System.InvalidOperationException
HResult=-2146233079
Message=Failed to read the configuration section for enclave providers. Make sure the section is correctly formatted in your application configuration file.
Error Message: Configuration system failed to initialize
Source=System.Data
StackTrace:
at System.Data.SqlClient.SqlConnection..cctor()
InnerException: System.Configuration.ConfigurationErrorsException
HResult=-2146232062
Message=Configuration system failed to initialize
Source=System.Configuration
BareMessage=Configuration system failed to initialize
Line=0
InnerException: System.Configuration.ConfigurationErrorsException
HResult=-2146232062
Message=Root element is missing.
Source=System.Configuration
BareMessage=Root element is missing.
Line=0
InnerException: System.Xml.XmlException
HResult=-2146232000
Message=Root element is missing.
Source=System.Xml
app.config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<sectionGroup name="userSettings" type="System.Configuration.UserSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
<section name="MercazApp.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" allowExeDefinition="MachineToLocalUser" requirePermission="false" />
</sectionGroup>
</configSections>
<connectionStrings>
<add name="MyKey"
connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=D:\Taekwon-Do\MercazApp\DB\LoginDb.mdf;Integrated Security=True;"
providerName="System.Data.SqlClient"/>
</connectionStrings>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<userSettings>
<MercazApp.Properties.Settings>
<setting name="username" serializeAs="String">
<value />
</setting>
<setting name="password" serializeAs="String">
<value />
</setting>
<setting name="name" serializeAs="String">
<value />
</setting>
</MercazApp.Properties.Settings>
</userSettings>
</configuration>

Root element is missing. (C:\Users\alexs\AppData\Local\MercazApp\MercazApp.exe_Url_ka1yz14eyfxx0cttxywliv5ag3ke50uk\1.0.0.0\user.config)
seems relevant. Likely, that file changed to something bad. Inspect it.
I can't believe you! I renamed that folder to old and after building it was created again and now it works!! I spent 4 hours with that. Where did you see the error and why it caused?
I simply read the exception in full. Exceptions contain a lot of information. It is worth acquiring a habit to fully read, understand and interpret it.

try putting the connection string directly into the code in place of the line that says:
string connectionString = ConfigurationManager.ConnectionStrings["MyKey"].ConnectionString;
This will tell you whether it's a web.config issue. Since it started playing up suddenly, its quite likely that some config change in IIS triggered the web config to be updated.
also worth checking whther there are any other .config files in different folders (including app_data) if you find one with no content, just delete it.

Related

Why is sqlconnection.open nosing around in my config file?

Today I thought, Oh, I'll just add some SQL logging to a C# SFTP custom (console) program we have. I didn't write it, and it has perhaps an odd configuration file. It looks like the SQL Performance Counters require a well conformed config file? Add the catch for TypeInitializationException gave some more specific and useful info.
So I am getting the connection string from the app.config file, but to show why I'm frustrated, I hard-coded the connection string below. If I'm providing a full connection string, why would it go to the config file. Apparently SqlPerformanceCounters is picky about these things???
if (!String.IsNullOrWhiteSpace(SqlConnectionString))
{
try
{
WriteLogConsole("SqlConnectionObj - about to open with SqlConnectionString='" +
SqlConnectionString + "'");
//SqlConnection SqlConnectionObj = new SqlConnection(SqlConnectionString);
// Even using a hard-coded connection string I have this issue!
SqlConnection SqlConnectionObj = new SqlConnection("Server=abc;Database=MyDBName;Trusted_Connection=true");
SqlConnectionObj.Open();
WriteLogConsole("SqlConnectionObj - opened successfully");
}
catch (TypeInitializationException ex)
{
WriteLogConsole("TypeInitializationException=" + ex.ToString());
// don't stop, keep going. Logging is nice, but not critical
}
catch (SqlException ex)
{
WriteLogConsole("SqlException=" + ex.ToString());
// don't stop, keep going. Logging is nice, but not critical
}
catch (Exception ex)
{
WriteLogConsole("System.Exception=" + ex.Message);
// don't stop, keep going. Logging is nice, but not critical
}
}
The short version of the error thrown is this:
Unrecognized configuration section
CustomAppSettings/LogExceptionsToFile
Full exception:
SqlConnectionObj - about to open with SqlConnectionString='Server=abc;Database=MyDBName;Trusted_Connection=true'
Exception thrown: 'System.TypeInitializationException' in System.Data.dll
TypeInitializationException=System.TypeInitializationException: The type initializer for 'System.Data.SqlClient.SqlConnection' threw an exception. ---> System.TypeInitializationException: The type initializer for 'System.Data.SqlClient.SqlConnectionFactory' threw an exception. ---> System.TypeInitializationException: The type initializer for 'System.Data.SqlClient.SqlPerformanceCounters' threw an exception. ---> System.Configuration.ConfigurationErrorsException: Configuration system failed to initialize ---> System.Configuration.ConfigurationErrorsException: Unrecognized configuration section CustomAppSettings/LogExceptionsToFile
at System.Configuration.ConfigurationSchemaErrors.ThrowIfErrors(Boolean ignoreLocal)
at System.Configuration.BaseConfigurationRecord.ThrowIfParseErrors(ConfigurationSchemaErrors schemaErrors)
at System.Configuration.BaseConfigurationRecord.ThrowIfInitErrors()
at System.Configuration.ClientConfigurationSystem.EnsureInit(String configKey)
--- End of inner exception stack trace ---
at System.Configuration.ConfigurationManager.PrepareConfigSystem()
at System.Configuration.ConfigurationManager.GetSection(String sectionName)
at System.Configuration.PrivilegedConfigurationManager.GetSection(String sectionName)
at System.Diagnostics.DiagnosticsConfiguration.GetConfigSection()
at System.Diagnostics.DiagnosticsConfiguration.Initialize()
at System.Diagnostics.DiagnosticsConfiguration.get_SwitchSettings()
at System.Diagnostics.Switch.InitializeConfigSettings()
at System.Diagnostics.Switch.InitializeWithStatus()
at System.Diagnostics.Switch.get_SwitchSetting()
at System.Data.ProviderBase.DbConnectionPoolCounters..ctor(String categoryName, String categoryHelp)
at System.Data.SqlClient.SqlPerformanceCounters..ctor()
at System.Data.SqlClient.SqlPerformanceCounters..cctor()
--- End of inner exception stack trace ---
at System.Data.SqlClient.SqlConnectionFactory..cctor()
--- End of inner exception stack trace ---
at System.Data.SqlClient.SqlConnection..cctor()
--- End of inner exception stack trace ---
at System.Data.SqlClient.SqlConnection..ctor(String connectionString)
at WinSCPWrapperGet.Program.Main(String[] args)
I think it's related to something like this.
What do I have to change to make it happy? I saw other posts about using but I don't have a group. I added everything below in as an attempt to fix the issue. The rest of the program runs fine and uses the config file as desired.
<configuration>
<configSections> <!-- this was not here when I first got the error,
me thinks I need something like to fix this issue -->
<sectionGroup name="CustomAppSettings" type="System.Configuration.UserSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<section name="MyApp.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" allowExeDefinition="MachineToLocalUser" requirePermission="false"/>
</sectionGroup>
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6"/>
</startup>
<CustomAppSettings>
<!-- we have many more parms, but here is an example;
each SFTP site can have about 10 config parms -->
<Site1>
<add key="HostName" value="sftp.somesite1.com"/>
<add key="HostPort" value=""/>
</Site1>
<Site2>
<add key="HostName" value="sftp.somesite1.com"/>
<add key="HostPort" value=""/>
</Site2>
... etc...
NOTE: This is in production now, and I am enhancing it. We have maybe a few dozen config files in different scheduled tasks, so I would hate to change all of them, even if they are not designed perfectly.
Found this: https://learn.microsoft.com/en-us/dotnet/framework/data/adonet/performance-counters
It tells us that we can tune the performance counters in the config file:
<system.diagnostics>
<switches>
<add name="ConnectionPoolPerformanceCounterDetail"
value="4"/>
</switches>
</system.diagnostics>
So bottom line, I just need to know how to make my config file work with SQL, even though the connection string in the config is not the issue.
The group is not needed, so far the following has got around the original issue:
<configuration>
<configSections>
<section name="CustomAppSettings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" allowExeDefinition="MachineToLocalUser" requirePermission="false"/>
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6"/>
</startup>
<CustomAppSettings>
etc...
Reference: https://blog.ivankahl.com/creating-custom-configuration-sections-in-app-config/

Unrecognized configuration section userSettings but Debug works fine

My app is working fine when debugging but when I'm trying to run it outside visual studio it just keeps crashing and all what I can find is this in event viewer:
Framework Version: v4.0.30319
Description: The process was terminated due to an unhandled exception.
Exception Info: System.Configuration.ConfigurationErrorsException
at System.Configuration.ConfigurationSchemaErrors.ThrowIfErrors(Boolean)
at System.Configuration.BaseConfigurationRecord.ThrowIfParseErrors(System.Configuration.ConfigurationSchemaErrors)
at System.Configuration.BaseConfigurationRecord.ThrowIfInitErrors()
at System.Configuration.ClientConfigurationSystem.OnConfigRemoved(System.Object, System.Configuration.Internal.InternalConfigEventArgs)
Exception Info: System.Configuration.ConfigurationErrorsException
at System.Configuration.ConfigurationManager.PrepareConfigSystem()
at System.Configuration.ConfigurationManager.RefreshSection(System.String)
at System.Configuration.ClientSettingsStore.ReadSettings(System.String, Boolean)
at System.Configuration.LocalFileSettingsProvider.GetPropertyValues(System.Configuration.SettingsContext, System.Configuration.SettingsPropertyCollection)
at System.Configuration.SettingsBase.GetPropertiesFromProvider(System.Configuration.SettingsProvider)
at System.Configuration.SettingsBase.GetPropertyValueByName(System.String)
at System.Configuration.SettingsBase.get_Item(System.String)
at System.Configuration.ApplicationSettingsBase.GetPropertyValue(System.String)
at System.Configuration.ApplicationSettingsBase.get_Item(System.String)
at LeagueFPSBoost.Properties.Settings.get_UpgradeRequired()
at LeagueFPSBoost.Program.CreateConfigIfNotExists()
at LeagueFPSBoost.Program.Startup(System.String[])
at LeagueFPSBoost.Program.Main(System.String[])
It was working fine, i just dont know what happened to it. Here is more info:
static void CreateConfigIfNotExists()
{
var configFile = $"{Application.ExecutablePath}.config";
if (!File.Exists(configFile))
{
File.WriteAllText(configFile, Resources.App_Config);
}
var configDir = Path.Combine(leagueConfigDirPath, #"LeagueFPSBoost\");
if (!Directory.Exists(configDir))
{
Directory.CreateDirectory(configDir);
}
if (!File.Exists(Path.Combine(configDir, "App.config")))
{
File.WriteAllText(Path.Combine(configDir, "App.config"), Resources.App_Config);
}
AppConfig.Change(Path.Combine(configDir, "App.config"));
if (File.Exists(configFile))
{
File.Delete(configFile);
}
if (Settings.Default.UpgradeRequired) //Exception Thrown Here
{
Settings.Default.Upgrade();
Settings.Default.UpgradeRequired = false;
Settings.Default.Save();
}
}
And this is from Settings.Desinger.cs:
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("True")]
public bool UpgradeRequired {
get {
return ((bool)(this["UpgradeRequired"]));
}
set {
this["UpgradeRequired"] = value;
}
}
Here is App.config:
<?xml version="1.0" encoding="utf-8"?>
<!-- User settings like theme and etc are stored in ...\AppData\Local\LeagueFPSBoost\... -->
<configuration>
<configSections>
<sectionGroup name="userSettings" type="System.Configuration.UserSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
<section name="LeagueFPSBoost.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" allowExeDefinition="MachineToLocalUser" requirePermission="false" />
</sectionGroup>
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System" publicKeyToken="b77a5c561934e089" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.0.0.0" newVersion="4.0.0.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
<userSettings>
<LeagueFPSBoost.Properties.Settings>
<setting name="ThemeStyle" serializeAs="String">
<value>Light</value>
</setting>
<setting name="ColorStyle" serializeAs="String">
<value>Blue</value>
</setting>
<setting name="Notifications" serializeAs="String">
<value>True</value>
</setting>
<setting name="Log" serializeAs="String">
<value>True</value>
</setting>
<setting name="UpgradeRequired" serializeAs="String">
<value>True</value>
</setting>
</LeagueFPSBoost.Properties.Settings>
</userSettings>
</configuration>
When application starts from Visual Studio in debug mode everything works fine every time. Problem is when I run application by clicking on exe it works first time (if user.config doesn't exist in roaming/local/appname.. folder). One I run application for second time by clicking on exe I just get the same error every time. But when I delete user.config file it starts again normally but it just wont start with user.config being there....
This is user.config:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<userSettings>
<LeagueFPSBoost.Properties.Settings>
<setting name="ThemeStyle" serializeAs="String">
<value>Dark</value>
</setting>
<setting name="ColorStyle" serializeAs="String">
<value>Red</value>
</setting>
<setting name="Notifications" serializeAs="String">
<value>True</value>
</setting>
<setting name="Log" serializeAs="String">
<value>True</value>
</setting>
<setting name="UpgradeRequired" serializeAs="String">
<value>False</value>
</setting>
</LeagueFPSBoost.Properties.Settings>
</userSettings>
</configuration>
Sometimes I'm also getting this exception:
System.Configuration.ConfigurationErrorsException: Unrecognized configuration section userSettings
(C:\Users\...\AppData\Local\LeagueFPSBoost\LeagueFPSBoost.exe_Url_10kxs4....xzo1\2.8.0.0\user.config line 3)
I tried incrementing 2.8.0.0 to 2.9.0.0 but I still got same problem.
It was working fine before, I don't know what happened to it.
Edit: I found out where exception is thrown by attacking debugger to process but still I don't know why?
Edit 2: I found out that adding:
<configSections>
<sectionGroup name="userSettings" type="System.Configuration.UserSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
<section name="LeagueFPSBoost.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" allowExeDefinition="MachineToLocalUser" requirePermission="false" />
</sectionGroup>
</configSections>
to the user.config fixes the problem but why is it missing in there in first place?
I've found answer here.
I have modified a code a bit so that its universal:
/// <summary>
/// Corrects the roaming settings file if needed because sometimes the node "configSections" is missing in the settings file.
/// Correct this by taking this node out of the default config file.
/// </summary>
private static void CorrectRoamingSettingsFileIfNeeded()
{
const string NODE_NAME_CONFIGURATION = "configuration";
const string NODE_NAME_CONFIGSECTIONS = "configSections";
const string NODE_NAME_USERSETTINGS = "userSettings";
//Exit if no romaing config (file) to correct...
var configRoaming = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoamingAndLocal);
if (configRoaming == null) return;
if (!configRoaming.HasFile) return;
//Check for the <sectionGroup> with name="userSettings"
//Note: Used ugly iteration because "configRoaming.GetSectionGroup(sectionGroupName)" throws ArgumentException.
ConfigurationSectionGroup sectionGroupUserSettings = null;
foreach (ConfigurationSectionGroup sectionGroup in configRoaming.SectionGroups)
{
if (sectionGroup.Name.Equals(NODE_NAME_USERSETTINGS))
{
sectionGroupUserSettings = sectionGroup;
break;
}
}
//Exit if the needed section group is found...
if (sectionGroupUserSettings != null && sectionGroupUserSettings.IsDeclared) return;
//Do correction actions...
var xDoc = XDocument.Load(configRoaming.FilePath);
var userSettingsNode = xDoc.Element(NODE_NAME_CONFIGURATION).Element(NODE_NAME_USERSETTINGS);
var ConfigFullFilename = Assembly.GetEntryAssembly().Location;
var configDefault = ConfigurationManager.OpenExeConfiguration(ConfigFullFilename);
var xDocDefault = XDocument.Load(configDefault.FilePath);
var configSectionsNode = xDocDefault.Element(NODE_NAME_CONFIGURATION).Element(NODE_NAME_CONFIGSECTIONS);
userSettingsNode.AddBeforeSelf(configSectionsNode);
xDoc.Save(configRoaming.FilePath);
}
That was confusing as hell....
While this is not directly related to the OP, this is the post users are sent to when searching for this error, so it is worth pointing out here as it is related.
This error occurs in .Net Core when adding an app.config using system.Configuration.ConfigurationManager 4.7.0:
ConfigurationErrorsException: Unrecognized configuration section add. (C:\Source\Repos\SFTP_Application\SFTP_Application\SFTP_Application_Console\bin\Debug\netcoreapp3.1\SFTP_Application_Console.dll.config line 3)
Unrecognized configuration section add means: it is missing a "section" and it thinks that <add> is a section.
In .Net Core's case, it is originally built to run off .json, but not everyone likes running their site off .json alone. So, you can add a .config file, but out of the box that file is missing an <appSettings> section. Put your keys in that, and your good to go.
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="ApplicationId" value="0" />
<!--SqlConnections-->
<add key="sql_Con_String" value="mydsstring" />
</appSettings>
</configuration>

System.ArgumentException: 'Keyword not supported: 'metadata

What is this Error.
System.ArgumentException: 'Keyword not supported: 'metadata'.'
Line of follow is my app.config.
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
<section name="Foroush.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</sectionGroup>
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5"/>
</startup>
<connectionStrings>
<add name="ForoushEntities" connectionString="metadata=res://*/DataModel.csdl|res://*/DataModel.ssdl|res://*/DataModel.msl;provider=System.Data.SqlClient;provider connection string="data source=.;initial catalog=Foroush;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient"/>
</connectionStrings>
<applicationSettings>
<Foroush.Properties.Settings>
<setting name="Foroush_SmsWebService_SendReceive" serializeAs="String">
<value>http://ip.sms.ir/ws/SendReceive.asmx</value>
</setting>
</Foroush.Properties.Settings>
</applicationSettings>
</configuration>
For Example
In the screenshot I see you alter the connection string by replacing an important part with "" in an attempt to create a Sql Connection String instead of an Entity Framework Connection String.
There are build-in methods for that like:
var entityConnectionStringBuilder = new EntityConnectionStringBuilder(MyConnectionString);
string sqlConnectionString = entityConnectionStringBuilder.ProviderConnectionString;
return new System.Data.SqlClient.SqlConnectionStringBuilder(sqlConnectionString).UserId);
In the screenshot code you probably wanted to use ConnectionStringNewFormat as an argument in the SqlConnectionStringBuilder instead of MyConnectionString (which is the original Entity Framework Connection String. But please, do not use string manipulation but use the code provided to you by the Entity Framework as demonstrated above.

Read settings added manually to app.config after compile

I developed a Windows service. It uses a MyService.exe.config file for configuration, that looks like this (simplified with just one setting, Prop1):
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
<section name="MyNamespace.MyService.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</sectionGroup>
</configSections>
<applicationSettings>
<MyNamespace.MyService.Properties.Settings>
<setting name="Prop1" serializeAs="String">
<value>Foo</value>
</setting>
</MyNamespace.MyService.Properties.Settings>
</applicationSettings>
</configuration>
When I deploy to a customer production environment I need to add more settings manually on the config file, for instance Prop2:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
<section name="MyNamespace.MyService.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</sectionGroup>
</configSections>
<applicationSettings>
<MyNamespace.MyService.Properties.Settings>
<setting name="Prop1" serializeAs="String">
<value>Foo</value>
</setting>
<setting name="Prop2" serializeAs="String">
<value>Bar</value>
</setting>
</MyNamespace.MyService.Properties.Settings>
</applicationSettings>
</configuration>
Now if I start the service this lines of code:
log.Debug(Properties.Settings.Default["Prop1"].ToString());
log.Debug(Properties.Settings.Default["Prop2"].ToString());
produce following output:
Foo
Impossibile trovare la proprietà di impostazione 'Prop2'.
in System.Configuration.SettingsBase.GetPropertyValueByName(String propertyName)
in System.Configuration.SettingsBase.get_Item(String propertyName)
in System.Configuration.ApplicationSettingsBase.GetPropertyValue(String propertyName)
in System.Configuration.ApplicationSettingsBase.get_Item(String propertyName)
in ...
The error in Italian means "Cannot find settings property 'Prop2'".
How can I read settings added to app.config after compile time?
I'm wondering whether it is not possible to add new settings to app.config when the application is already deployed, because every setting must be compiled and made available statically in Properties.Settings.Default. So to achieve what I want should I use a settings file managed by me, like re-inventing the wheel?
Well, I had posted an idea I thought would work but went back and tested myself and it didn't. D***.
So here's a suggestion I do use when the regular Settings stuff doesn't work.
Create an XML file structured as DataSet (the easiest way to do this is write a short program that creates a DatSet, populates it, and saves it as XML.
DataSet mydataset = new DataSet("myDataSet");
DataTable mydatatable = new DataTable("myDataTable");
mydatatable.Columns.Add(new DataColumn("myColumn1"));
DataRow newrow = mydatatable.NewRow();
newrow["myColumn1"] = "somedata";
mydatatable.Rows.Add(newrow);
mydataset.Tables.Add(mydatatable);
mydataset.WriteXML(#"C:\mydataset.xml", XmlWriteMode.WriteSchema);
This creates your basic XML file.
Very Important!!!!! To serialize a DataSet and/or DataTable you MUST give them names when you create them:
new DataSet("mydataset")
Then, as long as you don't violate the integrity of the XML structure, you can add rows (and even columns) to you XML file any time you wish using your favorite text editor.
In your application you simply read the XML file back into a DataSet and iterate through your DataTable rows (and through each DataTable if you created more than one) and process accordingly.
DataSet myDataSet = new DataSet("mydataset");
myDataSet.ReadXml(#"C:\mydataset.xml")
foreach (DataTable t in myDataSet.Tables)
{
foreach (DataRow r in t.Rows)
{
//process here
}
}
Very Important!!!!! To process the data you MUST use the names for the DataSet and DataTable from the XML file.
Hope this helps. It has worked for me many times when I couldn't use or couldn't access the built-in settings handler. It does add a little bit more time to your coding but....
John

"Configuration system failed to initialize" error

I'm getting this exception when using the code:
var appSettings = ConfigurationManager.AppSettings; //Exception here
string result = appSettings["ILFSsqlServer"] ?? "Not Found"; //trying to get to this point
I'm not really sure why and from previous answers to this question I think I'm doing exactly what they suggest but to no avail.
My app.config is:
<?xml version="1.0"?>
<configuration>
<configSections>
<sectionGroup name="userSettings"
type="System.Configuration.UserSettingsGroup, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
</sectionGroup>
</configSections>
<AppSettings>
<add key="ILFSsqlServer" value="ODBC;DSN=sql server copycloas;Trusted_Connection=Yes;APP=Microsoft Office 2010;DATABASE=ILFSView;"/>
</AppSettings>
</configuration>
On your app.config you should write appSettings, lowercase A.

Categories

Resources