为什么 sqlconnection.open 在我的配置文件中四处乱窜?

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

今天我想,哦,我将添加一些 SQL 日志记录到我们拥有的 C# SFTP 自定义(控制台)程序。我没有写它,它可能有一个奇怪的配置文件。看起来 SQL 性能计数器需要一个符合规范的配置文件?添加 TypeInitializationException 的捕获提供了一些更具体和有用的信息。

所以我从 app.config 文件中获取连接字符串,但为了说明我为什么感到沮丧,我在下面对连接字符串进行了硬编码。如果我提供完整的连接字符串,为什么它会转到配置文件。显然 SqlPerformanceCounters 对这些东西很挑剔???

            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 
                }

            }

抛出的错误的简短版本是这样的:

Unrecognized configuration section CustomAppSettings/LogExceptionsToFile

完全异常:

    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)

我认为这与 this.

之类的东西有关

我要改变什么才能让它开心?我看到其他关于使用的帖子,但我没有群组。我在下面添加了所有内容以尝试解决此问题。程序的其余部分运行良好,并根据需要使用配置文件。

<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...

注意:现在正在制作中,我正在对其进行改进。我们在不同的计划任务中可能有几十个配置文件,所以我不愿意更改所有这些文件,即使它们设计得不完美。

找到这个:https://docs.microsoft.com/en-us/dotnet/framework/data/adonet/performance-counters

它告诉我们可以在配置文件中调整性能计数器:

<system.diagnostics>
  <switches>
    <add name="ConnectionPoolPerformanceCounterDetail"
         value="4"/>
  </switches>
</system.diagnostics>

所以最重要的是,我只需要知道如何使我的配置文件与 SQL 一起工作,即使配置中的连接字符串不是问题。

不需要群,至此以下内容已经绕过原问题:

<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... 

参考:https://blog.ivankahl.com/creating-custom-configuration-sections-in-app-config/