I am trying to create an AppFabric cache client which is a console application. But receives the error Error in client configuration file while creating new instance of DataCacheFactory. Connection settings are provided in App.Config file as described in msdn.
Code
static void Main(string[] args)
{
try
{
DataCacheFactory dFact = new DataCacheFactory();
DataCache myCache = dFact.GetCache("default");
myCache.Remove("pValue");
myCache.Add("pValue", "Test Cache Value");
Console.WriteLine(string.Format("{0}", "Added to cache. Press any key to read...."));
Console.ReadLine();
Console.WriteLine(string.Format("{0}", myCache.Get("pValue").ToString()));
Console.ReadLine();
}
catch (Exception Ex)
{
throw new System.Exception(Ex.ToString());
}
}
}
App.Config file
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<configSections>
<section name="dataCacheClient"
type="Microsoft.ApplicationServer.Caching.DataCacheClientSection,
Microsoft.ApplicationServer.Caching.Core,Version=1.0.0.0,Culture=neutral,
PublicKeyToken=31bf3856ad364e35"
allowLocation="true"
allowDefinition="Everywhere" />
</configSections>
<dataCacheClient>
<hosts>
<host name="localhost" cachePort="22233"/>
</hosts>
</dataCacheClient>
</configuration>
Exception
Microsoft.ApplicationServer.Caching.DataCacheException:
ErrorCode<ERRCMC0003>:SubStatus<ES0001>:Error in client configuration file. --->
System.Configuration.ConfigurationErrorsException: Configuration system failed to
initialize --->
System.Configuration.ConfigurationErrorsException:
Only one <configSections> element allowed per config file
and if present must be the first child of the root <configuration> element.
(DistributedInMemory.vshost.exe.Config line 7)
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.ClientConfigurationSystem.EnsureInit(String configKey)
at System.Configuration.ClientConfigurationSystem.PrepareClientConfigSystem(String sectionName)
at
System.Configuration.ClientConfigurationSystem.System.Configuration.Internal.IInternalConfigSystem.GetSection(String sectionName)
at System.Configuration.ConfigurationManager.GetSection(String sectionName)
at Microsoft.ApplicationServer.Caching.ClientConfigReader..ctor()
at Microsoft.ApplicationServer.Caching.DataCacheFactoryConfiguration.Initialize(String path)
--- End of inner exception stack trace ---
at Microsoft.ApplicationServer.Caching.ConfigFile.ThrowException(Int32 errorCode, Exception e)
at Microsoft.ApplicationServer.Caching.DataCacheFactoryConfiguration.Initialize(String path)
at Microsoft.ApplicationServer.Caching.DataCacheFactory..ctor()
at DistributedInMemory.Program.Main(String[] args) in DistributedInMemory\Program.cs:line 16
Any idea why this error happening....Thanks.
You need to put the configSections element immediately after configuration element.
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<!-- Put config sections here -->
<configSections>
<!-- Put dataCache client section first -->
<section name="dataCacheClient" type="Microsoft.ApplicationServer.Caching.DataCacheClientSection, Microsoft.ApplicationServer.Caching.Core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" allowLocation="true" allowDefinition="Everywhere" />
<!-- Then other sections... -->
</configSections>
Related
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/
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.
I get this error:
Failure:
System.TypeInitializationException: The type initializer for 'System.Transactions.Diagnostics.DiagnosticTrace' threw an exception. ---> System.Configuration.ConfigurationErrorsException: Configuration system failed to initialize ---> System.Configuration.ConfigurationErrorsException: Unrecognized configuration section ServiceSettings/TycheConnectionString. (C:\KR_workspace\Alpha\Tyche\Applications\KPlusSynchronizer\KPlusSynchronizer\KPlusSynchronizerConsole\bin\Debug\KPlusSynchronizerConsole.vshost.exe.config line 17)
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.ClientConfigurationSystem.EnsureInit(String configKey)
at System.Configuration.ClientConfigurationSystem.PrepareClientConfigSystem(String sectionName)
at System.Configuration.ClientConfigurationSystem.System.Configuration.Internal.IInternalConfigSystem.GetSection(String sectionName)
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_Sources()
at System.Diagnostics.TraceSource.Initialize()
at System.Diagnostics.TraceSource.get_Switch()
at System.Transactions.Diagnostics.DiagnosticTrace..cctor()
--- End of inner exception stack trace ---
at System.Transactions.Transaction.get_Current()
at System.Data.Common.ADP.IsSysTxEqualSysEsTransaction()
at System.Data.Common.ADP.NeedManualEnlistment()
at System.Data.Odbc.OdbcConnection.Open()
at KPlusSynchronizer.Kplus.GetDataFromKplus(String kplusConnection, String sp) in c:\KR_workspace\Alpha\Tyche\Applications\KPlusSynchronizer\KPlusSynchronizer\KPlusSynchronizer\KPlus\Kplus.cs:line 24
at KPlusSynchronizer.Kplus..ctor(String kplusConnection, String sp) in c:\KR_workspace\Alpha\Tyche\Applications\KPlusSynchronizer\KPlusSynchronizer\KPlusSynchronizer\KPlus\Kplus.cs:line 16
at KPlusSynchronizer.Synchronizer.Synchronize(String tycheTable, String tycheSp, String kplusSp) in c:\KR_workspace\Alpha\Tyche\Applications\KPlusSynchronizer\KPlusSynchronizer\KPlusSynchronizer\KPlusSynchronizer.cs:line 34:
when I'm running my application. This is my app config:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<sectionGroup name="ServiceSettings" type="System.Configuration.UserSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
<section name="KPlusSynchronizerConsole.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" allowExeDefinition="MachineToLocalUser" requirePermission="false" />
</sectionGroup>
<sectionGroup name="TablesToSynchronize" type="System.Configuration.UserSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
<section name="KPlusSynchronizerConsole.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>
<ServiceSettings>
<TycheConnectionString value="Data Source=xxxxx;Initial Catalog=xxxxxx;Integrated Security=True" />
<KplusConnectionString value="Driver={Adaptive Server Enterprise};UID=xxxxx;PWD=xxxxx;Database=xxxxxx;Server=xxxxx;Port=4130;" />
<LogFiles value="true" />
</ServiceSettings>
<TablesToSynchronize>
<Table name="Table1" tycheSp="xxxxx" kplusSp="xxxx"/>
<Table name="Table2" tycheSp="xxxxx" kplusSp="xxxx"/>
<Table name="Table3" tycheSp="xxxxx" kplusSp="xxxx"/>
</TablesToSynchronize>
</configuration>
So the error is thrown when I'm opening connection to a DB using the connectionstring. I would like some help how to set this up. Do I need both configSections? Is this even possible?
I would like to use this kind om format instead of appSettings
Try
<ServiceSettings>
<KPlusSynchronizerConsole.Properties.Settings>
<TycheConnectionString value="Data Source=xxxxx;Initial Catalog=xxxxxx;Integrated Security=True" />
<KplusConnectionString value="Driver={Adaptive Server Enterprise};UID=xxxxx;PWD=xxxxx;Database=xxxxxx;Server=xxxxx;Port=4130;" />
<LogFiles value="true" />
</KPlusSynchronizerConsole.Properties.Settings>
</ServiceSettings>
if you look at your spec:
<sectionGroup name="ServiceSettings" type="System.Configuration.UserSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
<section name="KPlusSynchronizerConsole.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" allowExeDefinition="MachineToLocalUser" requirePermission="false" />
</sectionGroup>
it should be clear that you are telling it to expect a section named "KPlusSynchronizerConsole.Properties.Settings" and thus you should have one!
You need to do that same to
<TablesToSynchronize>...
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.
I cannot get the IApplication context for my console app
I get an exception with this detail:
The type initializer for 'Spring.Context.Support.ContextRegistry' threw an exception.
With inner exception:
Could not configure Common.Logging from configuration section 'common/logging
There's clearly something basic I've not hooked up, but I'm not sure what.
using Spring.Context;
using Spring.Context.Support;
namespace ConsoleApplication4
{
class Program
{
static void Main(string[] args)
{
IApplicationContext ctx = ContextRegistry.GetContext();
}
}
}
And my app.config looks like this:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<sectionGroup name="spring">
<section name="context" type="Spring.Context.Support.ContextHandler, Spring.Core"/>
<section name="objects" type="Spring.Context.Support.DefaultSectionHandler, Spring.Core" />
</sectionGroup>
</configSections>
<spring>
<context>
<resource uri="config://spring/objects"/>
</context>
<objects xmlns="http://www.springframework.net">
<description>An example that demonstrates simple IoC features. </description>
</objects>
</spring>
</configuration>
Spring.Net uses Common Logging as facility for logging, you have to add the logging configuration to your app.config and the proper library to the referenced assemblies.
<configuration>
<configSections>
<sectionGroup name="common">
<section name="logging" type="Common.Logging.ConfigurationSectionHandler, Common.Logging" />
</sectionGroup>
</configSections>
<common>
<logging>
<factoryAdapter type="Common.Logging.Simple.ConsoleOutLoggerFactoryAdapter, Common.Logging">
<arg key="level" value="DEBUG" />
<arg key="showLogName" value="true" />
<arg key="showDataTime" value="true" />
<arg key="dateTimeFormat" value="yyyy/MM/dd HH:mm:ss:fff" />
</factoryAdapter>
</logging>
</common>
</configuration>
http://netcommon.sourceforge.net/docs/1.2.0/reference/html/logging.html#logging-declarative-config
The type initializer for 'Spring.Context.Support.ContextRegistry'
threw an exception
This is valueable information and Spring.net is really good at providing additional information. Whenever Spring.net throws something, be sure to read the InnerException.
WHen I edit my config I get the messages: Could not find schema
information for the attribute #. for # = 'uri', 'context', 'resource'
and 'spring'
This is normal if you didn't install the schemas. You can download the schemas at their site and find additional information in their docs. Please note that this is optional and spring runs without those schemas.