简体   繁体   中英

SqlConnection throws an exception when running without debugging

I have an exception every time I try to run my program without debugging (Ctrl+F5). The code seems to run fine with debugging. I have tried creating a temp project with just the essentials. I have reinstalled Visual Studio. The problem still occurs. There is already a post about this but not a clear answer.

My Connection String:

"Data Source=(localdb)\\ProjectsV12;Initial Catalog=gatdb;Integrated Security=False;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False;Trusted_Connection=False;"

The Exception occurs here:

(SqlConnection connection = new SqlConnection(connectionString))

This is the exception:

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()
       at System.Data.SqlClient.SqlConnection..ctor(String connectionString, SqlCredential credential)
       at System.Data.SqlClient.SqlConnection..ctor(String connectionString)
       at GatHunter.Sql.IsServerConnected(String connectionString) in c:\users\kold\documents\visual studio 2015\Projects\ScatteredGats\GatHunter\Sql.cs:line 14
       at GatHunter.Program.Main(String[] args) in c:\users\kold\documents\visual studio 2015\Projects\ScatteredGats\GatHunter\Program.cs:line 14
  InnerException: 
       HResult=-2146233036
       Message=The type initializer for 'System.Data.SqlClient.SqlConnectionFactory' threw an exception.
       Source=System.Data
       TypeName=System.Data.SqlClient.SqlConnectionFactory
       StackTrace:
            at System.Data.SqlClient.SqlConnection..cctor()
       InnerException: 
            HResult=-2146233036
            Message=The type initializer for 'System.Data.SqlClient.SqlPerformanceCounters' threw an exception.
            Source=System.Data
            TypeName=System.Data.SqlClient.SqlPerformanceCounters
            StackTrace:
                 at System.Data.SqlClient.SqlConnectionFactory..ctor()
                 at System.Data.SqlClient.SqlConnectionFactory..cctor()
            InnerException: 
                 BareMessage=Configuration system failed to initialize
                 HResult=-2146232062
                 Line=0
                 Message=Configuration system failed to initialize
                 Source=System.Configuration
                 StackTrace:
                      at System.Configuration.ConfigurationManager.EnsureConfigurationSystem()
                      at System.Configuration.ConfigurationManager.PrepareConfigSystem()
                      at System.Configuration.ConfigurationManager.GetSection(String sectionName)
                      at System.Configuration.PrivilegedConfigurationManager.GetSection(String sectionName)
                      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()
                 InnerException: 
                      HResult=-2146233036
                      Message=The type initializer for 'System.Uri' threw an exception.
                      Source=System.Configuration
                      TypeName=System.Uri
                      StackTrace:
                           at System.Configuration.ClientConfigurationSystem..ctor()
                           at System.Configuration.ConfigurationManager.EnsureConfigurationSystem()
                      InnerException: 
                           HResult=-2146233036
                           Message=The type initializer for 'System.UriParser' threw an exception.
                           Source=System
                           TypeName=System.UriParser
                           StackTrace:
                                at System.Uri..cctor()
                           InnerException: 
                                HResult=-2146233036
                                Message=The type initializer for 'System.Runtime.Versioning.BinaryCompatibility' threw an exception.
                                Source=mscorlib
                                TypeName=System.Runtime.Versioning.BinaryCompatibility
                                StackTrace:
                                     at System.Runtime.Versioning.BinaryCompatibility.get_TargetsAtLeast_Desktop_V4_5()
                                     at System.UriParser..cctor()
                                InnerException: 
                                     HResult=-2146233033
                                     Message=Input string was not in a correct format.
                                     Source=mscorlib
                                     StackTrace:
                                          at System.Version.VersionResult.SetFailure(ParseFailureKind failure, String argument)
                                          at System.Version.TryParseComponent(String component, String componentName, VersionResult& result, Int32& parsedComponent)
                                          at System.Version.TryParseVersion(String version, VersionResult& result)
                                          at System.Version.Parse(String input)
                                          at System.Version..ctor(String version)
                                          at System.Runtime.Versioning.BinaryCompatibility.ParseFrameworkName(String frameworkName, String& identifier, Int32& version, String& profile)
                                          at System.Runtime.Versioning.BinaryCompatibility.ParseTargetFrameworkMonikerIntoEnum(String targetFrameworkMoniker, TargetFrameworkId& targetFramework, Int32& targetFrameworkVersion)
                                          at System.Runtime.Versioning.BinaryCompatibility.ReadTargetFrameworkId()
                                          at System.Runtime.Versioning.BinaryCompatibility.get_AppWasBuiltForFramework()
                                          at System.Runtime.Versioning.BinaryCompatibility.BinaryCompatibilityMap..ctor()
                                          at System.Runtime.Versioning.BinaryCompatibility..cctor()
                                     InnerException: 

In your connection string Integrated Security is set to False .

User ID = ****; Password = **** User ID = ****; Password = **** missing in your connection string.

If you would like to connect using Windows Authentication use

Integrated Security=SSPI; instead of Integrated Security=true;

If you try to use Integrated Security=true/false/yes/no with OleDb provider, you will get an exception during connection.

I want to thank everybody for their advise. I do not know why but what fixed this issue for me (even though I created an entirely new project and didn't touch the app.config) was this.

  1. delete app.config
  2. re-create via add->new item-> app.config
  3. switch the target framework from 4.6.1 to 4.0 then back to 4.6.1 again.

Initially I wanted to see what the reaction was when I switched to the 4.0 framework and to my surprise it suddenly started working. I know this sounds strange and I have no explanation for it.

This mostly due an error in your app.config file, Check for badly formed XML or unexpected elements.

Also double check you connectionstring .

Try simplifying the connection string to;

string str="Data Source=(localdb)\\ProjectsV12;Initial Catalog=gatdb;Integrated Security=False;User ID=sa;Password=sa;";
SqlConnection connection = new SqlConnection(str);

and try again.

Do the following steps.

  1. Create "xyz.udl" file on desktop.
  2. Double click on that file.
  3. Select appropriate provider
  4. Select server
  5. Set user / password and allow to save password
  6. Select database and hit test connection.
  7. Click on Ok button.
  8. Open that "xyz.udl" file in notepad.

Copy your connection string and use that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM