Strange exception coming out of OdbcConnection.Open() - c#

Bashing our heads against the wall here
We are an ISV and have hundreds of companies using our software with no problems. The software is Winforms/C# on .NET 2.0.
One of our clients has installed our software and it crashes on startup on all of their machines, apart from on one guy's laptop where it works fine.
On calling OdbcConnection.Open(), we get the following exception:
The type initializer for 'System.Transactions.Diagnostics.DiagnosticTrace' threw an exception.
at System.Transactions.Diagnostics.DiagnosticTrace.get_Verbose()
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 OurCompany.OurForm.connectionTestWorker_DoWork(Object sender)
This has an InnerException:
Configuration system failed to initialize
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()
Google just says "app.config is syntactically incorrect, rebuild it" yet the same app.config works fine on hundreds of other machines.
Here's app.config, as requested:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
<section name="OurApp.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</sectionGroup>
</configSections>
<system.diagnostics>
</system.diagnostics>
<applicationSettings>
<OurApp.Properties.Settings>
<setting name="OurApp_WebServices_OurServiceName" serializeAs="String">
<value>http://ourdomain.com/OurService.asmx</value>
</setting>
</OurApp.Properties.Settings>
</applicationSettings>
<appSettings>
<add key="WorkflowEngine" value="old" />
<add key="ProductID" value="3" />
<add key="EnableMigrationWizard" value="false" />
<add key="UseAlternativeFtpPort" value="true" />
<add key="FeedbackWhileConnecting" value="true" />
</appSettings>
</configuration>
A repair of the .NET Framework hasn't fixed this. I'm at a total loss. Any ideas?

Check machine.config and user.config. Along with app.config, those are the 3 that make up the config sections.
Reflector shows EnsureInit has 2 exception paths:
catch (Exception exception) {
this._initError = new ConfigurationErrorsException(SR.GetString("Config_client_config_init_error"), exception);
throw this._initError;
} catch {
this._initError = new ConfigurationErrorsException(SR.GetString("Config_client_config_init_error"));
throw this._initError;
}
Since the 2nd would only handle a non-CLS exception, I'd guess that you're hitting the first one. If that's the case, you probably need to recursively go through InnerException to get the full details.

Just for anyone's future reference, I had this problem with a local app that I was developing on my desktop and found that the problem was simply that I had the case wrong in . Once that was fixed it worked like a charm again.

Solved this by overwriting machine.config with a known working copy from another machine at the same SP/patch level.

I had this exact same error occur when trying to open an OLE DB connection with ASP/VB.NET 3.5 SP1. If I add my URL to the list of trusted sites in IE, then the error goes away and the connection opens successfully. I don't know if this will fix things in other browsers.

Related

C# Program wont start unless Mysql database is Online

My program used to start even though Mysql is offline, it will open but give an indicator that the program is not connected to the database, which is what i want. I want it to start even if the database is offline and just give an indicator that its not connected
I set a connection indicator like this:
public void connStatus()
{
MySqlConnection myConn = new MySqlConnection("SERVER = localhost; user id = root; password =; database = mpdb");
try
{
myConn.Open();
dbconsign.Visible = true;
dbnotconsign.Visible = false;
}
catch (Exception ex)
{
MetroMessageBox.Show(this, ex.Message , "NOTIFICATION", MessageBoxButtons.OK, MessageBoxIcon.Hand);
dbconsign.Visible = false;
dbnotconsign.Visible = true;
}
finally
{
if (myConn.State == ConnectionState.Open)
{
myConn.Close();
}
}
}
(I know that my code above is not the best one for checking server connections, but i just needed something to indicate if the database is online or offline, im new to programming and im not very good at it yet.)
now, after I added some dll's and went on with my little program, the program will only start if Mysql is Online. It won't start at all and will give messages like this:
Could not find schema information for the element 'setting'.
Could not find schema information for the element 'value'.
so i figured out something is wrong at the App.Config,
and the problem is I only have little knowledge on XML and i don't understand whats going on with the one on my project.
Can someone please tell me why is this happening? and how do i fix it?
Any suggestions and corrections are highly appreciated.
this is the App.config of my project:
<?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="cpsfmV2._0.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.2" />
</startup>
<userSettings>
<cpsfmV2._0.Properties.Settings>
<setting name="CurrentDate" serializeAs="String">
<value />
</setting>
</cpsfmV2._0.Properties.Settings>
</userSettings>
<system.data>
<DbProviderFactories>
<remove invariant="MySql.Data.MySqlClient" />
<add name="MySQL Data Provider" invariant="MySql.Data.MySqlClient" description=".Net Framework Data Provider for MySQL" type="MySql.Data.MySqlClient.MySqlClientFactory, MySql.Data, Version=6.9.12.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d" />
</DbProviderFactories>
</system.data>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="MySql.Data" publicKeyToken="c5687fc88969c44d" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-6.9.12.0" newVersion="6.9.12.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>
I am so happy i learned something new today,i just learned about proper debugging today thanks to google and stackoverflow.
I tried to google stuff related to NullReference Exception i found a very helpful guide from this post, not exactly the answer but the guy on the post explained it in easily understandable terms for newbies like me.
What is a NullReferenceException, and how do I fix it?
though the error says:
'System.NullReferenceException' occurred in MetroFramework.dll Additional information: Object reference not set to an instance of an object.
which got me confused as a beginner, i read on the post linked above that you need to check for the InnerException,
which i did and led me to my other mistake which says
System.TypeInitializationException
and it turns out its all because of a variable i declared from another class.
someone whos a newbie like me might get the same problem so i'll share the posts that helped me.
how to solve System.TypeInitializationException was unhandled exception in vb.net?
Field xxx is never assigned to, and will always have its default value null
and the final solution to my problem was i turned this:
private AuditTrail audittrail = new AuditTrail();
private void loginbtn_Click(object sender, EventArgs e)
{
//some code here
audittrail.RecordLogin();
}
into this:
private AuditTrail audittrail;
private void loginbtn_Click(object sender, EventArgs e)
{
audittrail = new AuditTrail();
//some code here
audittrail.RecordLogin();
}
and now its working :) Thanks to the helpful posts above.

An unhandled exception of type 'System.TypeInitializationException' occurred in EntityFramework.dll

I was trying to learn Entity Framework and SQLite using this tutorial. However, I get an error.
The error thrown is:
An unhandled exception of type 'System.TypeInitializationException' occurred in EntityFramework.dll
Additional information: The type initializer for 'System.Data.Entity.Internal.AppConfig' threw an exception.
Here is the full error trace:
System.TypeInitializationException: The type initializer for 'System.Data.Entity.Internal.AppConfig' threw an exception. ---> System.Configuration.Configuration
ErrorsException: 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. (C:\Users\Ankur\Documents\Visual Studio 2012\Projects\ConsoleApplication1\ConsoleApplication1\bin\Debug\ConsoleApplication1.vshost.exe.config line 11)
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.get_ConnectionStrings()
at System.Data.Entity.Internal.AppConfig..ctor()
at System.Data.Entity.Internal.AppConfig..cctor()
--- End of inner exception stack trace ---
at System.Data.Entity.Internal.AppConfig.get_DefaultInstance()
at System.Data.Entity.Internal.LazyInternalConnection..ctor(String nameOrConnectionString)
at System.Data.Entity.DbContext..ctor()
at ConsoleApplication1.ChinookContext..ctor()
at ConsoleApplication1.Program.Main(String[] args) in c:\Users\Ankur\Documents\Visual Studio 2012\Projects\ConsoleApplication1\ConsoleApplication1\Program.cs
:line 16
Here is the C# code:
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
using (var context = new ChinookContext()) //error comes on this line
{
}
}
}
class ChinookContext : DbContext
{
}
}
Here is file App.config:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.data>
<DbProviderFactories>
<add name="SQLite Data Provider" invariant="System.Data.SQLite" description="Data Provider for SQLite" type="System.Data.SQLite.SQLiteFactory, System.Data.SQLite" />
</DbProviderFactories>
</system.data>
<connectionStrings>
<add name="ChinookContext" connectionString="Data Source=|DataDirectory|Chinook_Sqlite_AutoIncrementPKs.sqlite" providerName="System.Data.SQLite" />
</connectionStrings>
<configSections>
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="v11.0" />
</parameters>
</defaultConnectionFactory>
</entityFramework>
</configuration>
Here is file packages.config:
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="EntityFramework" version="5.0.0" targetFramework="net45" />
<package id="System.Data.SQLite.x86" version="1.0.86.0" targetFramework="net45" />
</packages>
Read the message:
Only one <configSections> element allowed per
config file and if present must be the first child of the root <configuration> element.
Move the configSections element to the top - just above where system.data is currently.
Check which version of Entity Framework reference you have in your References and make sure that it matches with your configSections node in Web.config file. In my case it was pointing to version 5.0.0.0 in my configSections and my reference was 6.0.0.0. I just changed it and it worked...
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false"/>
Just go to Web.Config from Main folder, not the one in Views Folder:
configSections
section name="entityFramework" type="System.Data. .....,Version=" <strong>5</strong>.0.0.0"..
<..>
ADJUST THE VERSION OF EntityFramework you have installed, ex. like Version 6.0.0.0"
Check that right version is referenced in your project. E.g. the dll it is complaining about, could be from an older version and that's why there could be a version mismatch.
I had this issue when i refereed a library project from a console application, and the library project was using a nuget package which is not refereed in the console application. Referring the same package in the console application helped to resolve this issue.
Seeing the Inner exception can help.
In static class,
if you are getting information from xml or reg, class tries to initialize all properties. therefore, you should control if the config variable is there otherwise properties will not initialize so the class.
Check xml referance variable is there,
Check reg referance variable is is there,
Make sure you handle if they are not there.

When are settings from app.config actually read?

When are settings from app.config actually read by application?
Suppose I have a windows service and some app settings for it. In code I have a method where some setting is used. Method is being called in every iteration, not just once during all the time. If I change the setting value through the configuration file should I restart the service for it to be "refreshed" inside or will it be accepted the next time without any interaction from my side?
You need to call ConfigurationManager.RefreshSection method to get the latest values read directly from disk. Here's a simple way to test and provide answer to your question:
static void Main(string[] args)
{
while (true)
{
// There is no need to restart you application to get latest values.
// Calling this method forces the reading of the setting directly from the config.
ConfigurationManager.RefreshSection("appSettings");
Console.WriteLine(ConfigurationManager.AppSettings["myKey"]);
// Or if you're using the Settings class.
Properties.Settings.Default.Reload();
Console.WriteLine(Properties.Settings.Default.MyTestSetting);
// Sleep to have time to change the setting and verify.
Thread.Sleep(10000);
}
}
My app.config containing:
<?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="ConsoleApplication2.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" allowExeDefinition="MachineToLocalUser" requirePermission="false" />
</sectionGroup>
</configSections>
<appSettings>
<add key="myKey" value="Original Value"/>
</appSettings>
<userSettings>
<ConsoleApplication2.Properties.Settings>
<setting name="MyTestSetting" serializeAs="String">
<value>Original Value</value>
</setting>
</ConsoleApplication2.Properties.Settings>
</userSettings>
</configuration>
After you start the application, open the app.config within the build folder, and change the value of the appSetting "myKey". You'll see the new value printed out to the console.
To answer the question, yes they are cached on the first time they are each read I think, and to force the read straight from the disk, you need to refresh the section.
Either when you load it up via the configuration manager (ConfigurationManager.GetSection("x/y");) or when you try to access the properties.
There is a slight grey area here because when you get the configuration out via the config manager:
var config = (MyConfigSection)ConfigurationManager.GetSection("MyConfigSection");
You get a configuration object back if you have provided the configuration section type in the configurationSections element at the top of the config file. If you do not actually provide the actual config you will still get an object back.
However if you have a required field that is not set it will not throw an exception till you call the property. I have worked this out whilst trying to unit test my custom configuration sections.

Windows Services Error in C#

I using c#. At this time I using Windows 7.My question is ; When I running my code,
that's gives me errors etc 193:0xc1 error , Services started but after stopped , 1053 services errors.
Here is my code.
public RupdaterService()
{
InitializeComponent();
this.timer1.Elapsed += new System.Timers.ElapsedEventHandler(this.timer1_Elapsed);
}
protected override void OnStart (string[] args)
{
timer1.Enabled=true;
this.DBEntry("Service Started");
}
protected override void OnStop()
{
this.timer1.Enabled = false;
this.DBEntry("Service Stopped");
}
private void timer1_Elapsed(object sender,System.Timers.ElapsedEventArgs e)
{
this.DBEntry("Service Running");
}
Here 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=b77a5c5***9" >
<section name="HedefliRUpdater.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5***9" requirePermission="false" />
</sectionGroup>
</configSections>
<system.serviceModel>
</system.serviceModel>
<applicationSettings>
<HedefliRUpdater.Properties.Settings>
<setting name="HedefliRUpdater_srvHedefli_wsrvHermesHedefliMesaj"
serializeAs="String">
<value>http://***.com/hedefli/srvHedefli.asmx</value>
</setting>
</HedefliRUpdater.Properties.Settings>
</applicationSettings>
Thanks in advance,
Some things to check. These happened to me, off the top of my head:
Is there anything in the Event Logs? They can sometimes give you a clue.
Is the Event Log full? If Windows can't write to it, it won't start the service. Try clearing the Application event log and see if it starts.
Are there any syntax errors in the .config file? We once had a problem with an .msi installer that put an <endpoint> tag after the end of </configuration>
It looks like you're writing to a database. Does the user that the service runs under have access to that database?
Try putting Debugger.Break() at the beginning of your OnStart() to prompt Windows to connect an instance of Visual Studio when it starts up. At the very least, it'll tell you if the fault is happening before it gets to your OnStart, or after.
Do you have more than one <endpoint> specified in the app.config/web.config file that matches the same contract? Try removing the superfluous endpoint
I don't know what your problem is, but this question Easier way to debug a Windows service provides excellent tips to allow you to debug the startup of your service.
I had a similar issue and found the following link to be useful:
http://support.microsoft.com/default.aspx?scid=kb;en-us;Q325680
In my case the exe was in C:\Documents ans Settings.... and there was a file named C:\Documents. Deleting this file helped, but I am still looking for a way to solve this programatically.

Activation error occured while trying to get instance of type LogWriter

I am trying to using the Logging Application block of Enterprise Library 5.0 to log simple message to the Windows event log on Win XP SP3 system using:
Logger.Write(msg);
I get the "Activation error occured while trying to get instance of type LogWriter" error message when trying to log.
Shown below is the config file used with MS Enterprise library
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="loggingConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.LoggingSettings, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="true" />
</configSections>
<loggingConfiguration name="" tracingEnabled="true" defaultCategory="General">
<listeners>
<add name="Event Log Listener" type="Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.FormattedEventLogTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.FormattedEventLogTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
source="Enterprise Library Logging" formatter="Text Formatter"
log="Application" machineName="." traceOutputOptions="None" />
</listeners>
<formatters>
<add type="Microsoft.Practices.EnterpriseLibrary.Logging.Formatters.TextFormatter, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
template="Timestamp: {timestamp}{newline}
Message: {message}{newline}
Category: {category}{newline}
Priority: {priority}{newline}
EventId: {eventid}{newline}
Severity: {severity}{newline}
Title:{title}{newline}
Machine: {localMachine}{newline}
App Domain: {localAppDomain}{newline}
ProcessId: {localProcessId}{newline}
Process Name: {localProcessName}{newline}
Thread Name: {threadName}{newline}
Win32 ThreadId:{win32ThreadId}{newline}
Extended Properties: {dictionary({key} - {value}{newline})}"
name="Text Formatter" />
</formatters>
<categorySources>
<add switchValue="All" name="General">
<listeners>
<add name="Event Log Listener" />
</listeners>
</add>
</categorySources>
<specialSources>
<allEvents switchValue="All" name="All Events" />
<notProcessed switchValue="All" name="Unprocessed Category" />
<errors switchValue="All" name="Logging Errors & Warnings">
<listeners>
<add name="Event Log Listener" />
</listeners>
</errors>
</specialSources>
</loggingConfiguration>
</configuration>
I just wanted to add this error may be caused by another configuration issue. Make sure to look at the inner exceptions for this error. In my case it was:
"The type Database cannot be constructed. You must configure the container to supply this value."
To resolve this I had to add a providerName to my database connection string in the web.config. So the final connection string node looked like this:
<add name="DBConn" connectionString="Data Source=ServerName;Initial Catalog=Logging;Persist Security Info=True;integrated security=True;" providerName="System.Data.SqlClient" />
I realized that I was trying to use Config file from within a DLL which does not work. I should be using FileConfigurationSource instead.
If I use the same App.Config from an application, it worked fine.
Reading the other answers to this question, and from my own experiences, in general it seems this error occurs when your application cannot read some required configuration for the Logging application block from a config file.
To add to the scenarios mentioned in previous answers, I've come across this error a couple of times:
1) In a unit test project, where I forgot to add an app.config file at all;
2) In a config file where I deleted a particular listener from the loggingConfiguration section but forgot to remove the name of the listener from the categorySource that referenced it.
It is missing DLL; pay attension when you place your DLL's at GAC you may need to add more DLL's to GAC . Common, Data, Logging, Logging.Database and ServiceLocation DLLS make sure they reside together in one directory
I've also seen this error when forgetting to add a reference to the EntLib DLL's.
I've had the same error when using a separate entlib config file.
In Web.config, enterpriseLibrary.ConfigurationSource pointed to EntLib.config. When I used the EnterpriseLibrary.Config tool to edit EntLib.config to set up the logging database details, it put everything in EntLib.config. I got this error until I moved the connetionStrings section to Web.config.
Additionally to examples of
Simon Tewsi
 I want to add my example, when logging configuration was located in a separate file but section descriptions were missed in app.config
   
<section name ="loggingConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.LoggingSettings, Microsoft.Practices.EnterpriseLibrary.Logging" />  
 <loggingConfiguration configSource="EnterpriseLibraryLogging.config" />

Categories