SqlConnection() parameterless exception - c#

I get this error trying to initialize SqlConnection instance.
First I tried with ConnectionString parameter, now I see it occurs even without it in the constructor. The code used to work, but fails after I changed my PC, so I suppose it has something to do with windows settings (windows 7) or user rights
My code:
using (SqlConnection conn = new SqlConnection())
{
SqlConnectionStringBuilder builder =
new SqlConnectionStringBuilder("Server=server1;Integrated Security=SSPI;Initial Catalog=db1");
conn.ConnectionString = builder.ConnectionString;
}
I already tried switching target framework back and forth as some suggest with no result (using 4.5.2 at the moment)
update
The exception thrown on the using line:
System.TypeInitializationException occurred HResult=0x80131534
Message=The type initializer for 'System.Data.SqlClient.SqlConnection'
threw an exception. Source=
StackTrace: at System.Data.SqlClient.SqlConnection..ctor() at
Reg_CB_Report.Program.GetSql(String ExecText) in
H:\MY\code\c#\Reg_CB_Report\Reg_CB_Report\Program.cs:line 228 at
Reg_CB_Report.Program.Main(String[] args) in
H:\MY\code\c#\Reg_CB_Report\Reg_CB_Report\Program.cs:line 83
Inner Exception 1: ArgumentException: The parameter is incorrect.
(Exception from HRESULT: 0x80070057 (E_INVALIDARG))
update2
App.config:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2"/>
</startup>
</configuration>
tried recreating it - no result
StackTrace:
StackTrace " at System.Security.Policy.PEFileEvidenceFactory.GetLocationEvidence(SafePEFileHandle peFile, SecurityZone& zone, StringHandleOnStack retUrl)\r\n at System.Security.Policy.PEFileEvidenceFactory.GenerateLocationEvidence()\r\n at System.Security.Policy.PEFileEvidenceFactory.GenerateEvidence(Type evidenceType)\r\n at System.Security.Policy.AssemblyEvidenceFactory.GenerateEvidence(Type evidenceType)\r\n at System.Security.Policy.Evidence.GetHostEvidenceNoLock(Type type)\r\n at System.Security.Policy.Evidence.GetHostEvidence(Type type, Boolean markDelayEvaluatedEvidenceUsed)\r\n at System.Security.Policy.AppDomainEvidenceFactory.GenerateEvidence(Type evidenceType)\r\n at System.Security.Policy.Evidence.GetHostEvidenceNoLock(Type type)\r\n at System.Security.Policy.Evidence.RawEvidenceEnumerator.MoveNext()\r\n at System.Security.Policy.Evidence.EvidenceEnumerator.MoveNext()\r\n at System.Configuration.ClientConfigPaths.GetEvidenceInfo(AppDomain appDomain, String exePath, String& typeName)\r\n at System.Configuration.ClientConfigPaths.GetTypeAndHashSuffix(AppDomain appDomain, String exePath)\r\n at System.Configuration.ClientConfigPaths..ctor(String exePath, Boolean includeUserConfig)\r\n at System.Configuration.ClientConfigPaths.GetPaths(String exePath, Boolean includeUserConfig)\r\n at System.Configuration.ClientConfigurationHost.RequireCompleteInit(IInternalConfigRecord record)\r\n at System.Configuration.BaseConfigurationRecord.GetSectionRecursive(String configKey, Boolean getLkg, Boolean checkPermission, Boolean getRuntimeObject, Boolean requestIsHere, Object& result, Object& resultRuntimeObject)\r\n at System.Configuration.BaseConfigurationRecord.GetSection(String configKey)\r\n at System.Data.SqlClient.SqlConnection..cctor()" string

It looks like you're trying to use the latest version of the SqlClient NuGet package (4.6) on the oldest supported runtime. A missing security update may be involved as well.
The type initializer mentioned in the exception is the static constructor which tries to load the SqlColumnEncryptionEnclaveProviders configuration section. I've never encountered that section either.
One option is to go back to an earlier SqlClient package that works. Another option is target .NET 4.7.2 and later. Finally, you can add the missing section yourself, as the link to the SharePoint bug shows :
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<configSections>
<section name="SqlColumnEncryptionEnclaveProviders"
type="System.Data.SqlClient.SqlColumnEncryptionEnclaveProviderConfigurationSection, System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
</configSections>
</configuration>
This isn't the only bug introduced by SqlClient 4.6. There was another one, again involving the parameterless constructor.

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/

Why is Entity Framework 6.1.3 throwing a "Could not load type 'System.Data.Entity.Infrastructure.TableExistenceChecker'"

Brand new project and entity framework will not start due to the exception being thrown as soon as the context instance is created.
Entity framework throws the following exception:
Could not load type 'System.Data.Entity.Infrastructure.TableExistenceChecker' from assembly 'EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'.
References:
EntityFramework
EntityFramework.SqLServer
Via the nuget package manager:
Install-Package entityframework
Very simple context and entity:
public class TextDbContext : DbContext
{
public TextDbContext()
: base("Test")
{
}
public DbSet<TestEntity> TestEntity { get; set; }
}
public class TestEntity
{
public int Id { get; set; }
public string Name { get; set; }
}
static void Main(string[] args)
{
var test = ConfigurationManager.ConnectionStrings["Test"].ConnectionString;
using (var conn = new SqlConnection(test))
{
conn.Open();
var cmd = new SqlCommand("Select * from testtable", conn);
var result = cmd.ExecuteReader();
}
//exception thrown on this line is the same as the one in the context
var instance = SqlProviderServices.Instance;
using (var db = new TextDbContext())
{
var item = new TestEntity
{
Name = "xyz"
};
db.TestEntity.Add(item);
db.SaveChanges();
}
}
Here is the current app.config file:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<connectionStrings>
<add name="Test" connectionString="server=localhost;database=Test;Data Source=localhost;Integrated Security=True;Pooling=True" providerName="System.Data.SqlClient" />
</connectionStrings>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
</configuration>
Stack trace is as follows:
at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at System.Reflection.RuntimePropertyInfo.GetValue(Object obj, BindingFlags invokeAttr, Binder binder, Object[] index, CultureInfo culture)
at System.Reflection.RuntimePropertyInfo.GetValue(Object obj, Object[] index)
at System.Data.Entity.Utilities.MemberInfoExtensions.GetValue(MemberInfo memberInfo)
at System.Data.Entity.Infrastructure.DependencyResolution.ProviderServicesFactory.GetInstance(Type providerType)
at System.Data.Entity.Infrastructure.DependencyResolution.ProviderServicesFactory.GetInstance(String providerTypeName, String providerInvariantName)
at System.Data.Entity.Internal.AppConfig.<.ctor>b__2(ProviderElement e)
at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext()
at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
at System.Data.Entity.Internal.AppConfig.<.ctor>b__1()
at System.Lazy`1.CreateValue()
at System.Lazy`1.LazyInitValue()
at System.Lazy`1.get_Value()
at System.Data.Entity.Internal.AppConfig.get_DbProviderServices()
at System.Data.Entity.Infrastructure.DependencyResolution.AppConfigDependencyResolver.RegisterDbProviderServices()
at System.Data.Entity.Infrastructure.DependencyResolution.AppConfigDependencyResolver.GetServiceFactory(Type type, String name)
at System.Data.Entity.Infrastructure.DependencyResolution.AppConfigDependencyResolver.<>c__DisplayClass1.<GetService>b__0(Tuple`2 t)
at System.Collections.Concurrent.ConcurrentDictionary`2.GetOrAdd(TKey key, Func`2 valueFactory)
at System.Data.Entity.Infrastructure.DependencyResolution.AppConfigDependencyResolver.GetService(Type type, Object key)
at System.Data.Entity.Infrastructure.DependencyResolution.DbDependencyResolverExtensions.GetServiceAsServices(IDbDependencyResolver resolver, Type type, Object key)
at System.Data.Entity.Infrastructure.DependencyResolution.AppConfigDependencyResolver.GetServices(Type type, Object key)
at System.Data.Entity.Infrastructure.DependencyResolution.ResolverChain.<>c__DisplayClass6.<GetServices>b__5(IDbDependencyResolver r)
at System.Linq.Enumerable.<SelectManyIterator>d__14`2.MoveNext()
at System.Linq.Enumerable.<ConcatIterator>d__71`1.MoveNext()
at System.Linq.Enumerable.<OfTypeIterator>d__aa`1.MoveNext()
at System.Data.Entity.Utilities.IEnumerableExtensions.Each[T](IEnumerable`1 ts, Action`1 action)
at System.Data.Entity.Infrastructure.DependencyResolution.InternalConfiguration.Lock()
at System.Data.Entity.Infrastructure.DependencyResolution.DbConfigurationManager.<.ctor>b__1()
at System.Lazy`1.CreateValue()
at System.Lazy`1.LazyInitValue()
at System.Lazy`1.get_Value()
at System.Data.Entity.Infrastructure.DependencyResolution.DbConfigurationManager.GetConfiguration()
at System.Data.Entity.DbContext.InitializeLazyInternalContext(IInternalConnection internalConnection, DbCompiledModel model)
at System.Data.Entity.DbContext..ctor(String nameOrConnectionString)
at test2.TextDbContext..ctor() in \\srv\users\carl.tierney\Documents\Visual Studio 2013\Projects\test2\test2\test2context.cs:line 13
at test2.Program.Main(String[] args) in \\srv\users\carl.tierney\Documents\Visual Studio 2013\Projects\test2\test2\Program.cs:line 13
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state
at System.Threading.ThreadHelper.ThreadStart()
If you find as I did that EF is not installed in the Gac then the next step is to uninstall it AFTER you note the version of your package. I use NuGet so I went to Tools...Library Package Manager...Package Manager Console. I tried the GUI first but uninstalling failed and as of this writing you can only install the latest version of the package.
Open your solution and go to Tools...Library Package Manager...Package Manager Console
Select the project that uses EF and is having the problem
Type Uninstall-package EntityFramework
You should be prompted to restart Visual Studio so close and reopen VS and your solution
Open Package Manager Console with Tools...Library Package Manager...Package Manager Console
Type Install-package EntityFramework (add -Version x.x.x if you're installing an older version)
You should be good to go
I had the exact same problem in my unit test project. After a couple of hours of troubleshooting I noticed that the .csproj-file still had reference to my previous version of EF:
<Reference Include="EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\packages\EntityFramework.6.1.1\lib\net45\EntityFramework.dll</HintPath>
</Reference>
I simply changed the version to 6.1.3 and all tests ran fine again.
Apparently if there is a reference to entity framework in the GAC and it is not the same as the one you have referenced via Nuget you get this error. In my case it was 6.0.0 in the GAC.
Solution:
Launch the developer command prompt for visual studio then:
gacutil -u EntityFramework
In my case when I got this error, I was not able to find EF in GAC. So nothing was to unistall.
However, after investigating all EF references in all projects of the solution it was found that one of the project referenced EF 6.1.1 and all others 6.1.3. Answer by michaelhawkins helped in this case, I removed all EF from all projects and then installed the same latest version back.
Just leaving it here, because in all cases this exception most probably is due to conflict of versions of EF, but where specifically you need to look to resolve the conflict may depend on various factors.
In my case I had to remove the EntityFramework.dll from this folder:
C:\Windows\Microsoft.NET\assembly\GAC_MSIL\EntityFramework
The same problem happened to me
Open Visual Studio --> Tools --> Extensions and Updates
Check Updates first if any update related with Nuget Package Manager Console update it.
Select All tab in Extensions and Updates be sure your Nuget Package Manager Console version
Open your project folder --> Packages then delete everything about entityframework
If there is a file like entityframework.deleteme --> delete it and restart Visual Studio
For future reference in my case removing EntityFramework.SqlServer from GAC fixed this error. The assembly was exactly same version than the one referenced in my application (6.0.0.0 for both EntityFramework.dll and EntityFramework.SqlServer.dll). However, I didn't have EntityFramework in GAC when this exception occurred.
I had installed the EntityFramework references to my application with SQLite Core (x86/x64) using NuGet. Also I had dabbled with GAC a bit previously and most likely added the assembly there myself.
Do you have EntityFramework.SqlServer referenced? This should come automatically with entity framework. If not try add it as a reference, or via Nuget.
Ofcourse that is if you are usign SqlServer provider. if not, you need to add your specific provider.
Just update the package.config file to match the EF version your using
In this case, it is "6.1.3".
Another simple bypass is to use :
EntityFramework\Add-Migration
instead
Add-Migration
I was getting this same error after installing Visual Studio 2015 (VS 2015) when running unit tests that use SQL CE. My connection factory is SqlCeConnectionFactory and provider is System.Data.Entity.SqlServerCompact.SqlCeProviderServices, EntityFramework.SqlServerCompact.
The solution for me was to add the path to EntityFramework.SqlServerCompact.dll to the deployment list in my .testsettings file. The line I added looks like this:
<DeploymentItem filename="packages\EntityFramework.SqlServerCompact.6.1.1\lib\net45\EntityFramework.SqlServerCompact.dll" />
Changing connectionstring value from
"data source=.;initial catalog=[dbname];integrated security=True"
To
"Server=.;Database=[dbname];integrated security=True"
In my case i work in two different project with two different version of EF when i switch between them the problem occurred .restarting VS2017 solved the problem .

ConfigurationErrorsException/SecurityException/FileIOPermission reading application .config file during NLog instantiation

I'm getting a weird exception when trying to initialize NLog instance as a static class member (update: this is happening in a desktop app which is targeting .NET 4.0).
The problem is, I'm getting it only on one specific client machine, and can't reproduce on any of my development configurations. Can someone point me in a direction, what should I look for?
PS: User tried to run the app with administrator rights as well, getting same exception.
System.Configuration.ConfigurationErrorsException: An error occurred creating the configuration section handler for nlog: Request for permission of type "System.Security.Permissions.FileIOPermission, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" failed. (C:\Users\XXX\Desktop\Test.exe.Config line 9) ---> System.Security.SecurityException: Request for permission of type "System.Security.Permissions.FileIOPermission, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" failed.
in System.Security.CodeAccessSecurityEngine.Check(Object demand, StackCrawlMark& stackMark, Boolean isPermSet)
in System.Security.CodeAccessPermission.Demand()
in System.AppDomainSetup.VerifyDir(String dir, Boolean normalize)
in NLog.Internal.Fakeables.AppDomainWrapper..ctor(AppDomain appDomain)
in NLog.Internal.Fakeables.AppDomainWrapper.get_CurrentDomain()
in NLog.Config.ConfigSectionHandler.System.Configuration.IConfigurationSectionHandler.Create(Object parent, Object configContext, XmlNode section)
in System.Configuration.RuntimeConfigurationRecord.RuntimeConfigurationFactory.CreateSectionImpl(RuntimeConfigurationRecord configRecord, FactoryRecord factoryRecord, SectionRecord sectionRecord, Object parentConfig, ConfigXmlReader reader)
in System.Configuration.RuntimeConfigurationRecord.RuntimeConfigurationFactory.CreateSectionWithRestrictedPermissions(RuntimeConfigurationRecord configRecord, FactoryRecord factoryRecord, SectionRecord sectionRecord, Object parentConfig, ConfigXmlReader reader)
in System.Configuration.RuntimeConfigurationRecord.CreateSection(Boolean inputIsTrusted, FactoryRecord factoryRecord, SectionRecord sectionRecord, Object parentConfig, ConfigXmlReader reader)
in System.Configuration.BaseConfigurationRecord.CallCreateSection(Boolean inputIsTrusted, FactoryRecord factoryRecord, SectionRecord sectionRecord, Object parentConfig, ConfigXmlReader reader, String filename, Int32 line)
--- End of inner exception stack trace ---
in System.Configuration.BaseConfigurationRecord.EvaluateOne(String[] keys, SectionInput input, Boolean isTrusted, FactoryRecord factoryRecord, SectionRecord sectionRecord, Object parentResult)
in System.Configuration.BaseConfigurationRecord.Evaluate(FactoryRecord factoryRecord, SectionRecord sectionRecord, Object parentResult, Boolean getLkg, Boolean getRuntimeObject, Object& result, Object& resultRuntimeObject)
in System.Configuration.BaseConfigurationRecord.GetSectionRecursive(String configKey, Boolean getLkg, Boolean checkPermission, Boolean getRuntimeObject, Boolean requestIsHere, Object& result, Object& resultRuntimeObject)
in System.Configuration.BaseConfigurationRecord.GetSectionRecursive(String configKey, Boolean getLkg, Boolean checkPermission, Boolean getRuntimeObject, Boolean requestIsHere, Object& result, Object& resultRuntimeObject)
in System.Configuration.BaseConfigurationRecord.GetSectionRecursive(String configKey, Boolean getLkg, Boolean checkPermission, Boolean getRuntimeObject, Boolean requestIsHere, Object& result, Object& resultRuntimeObject)
in System.Configuration.BaseConfigurationRecord.GetSection(String configKey)
in System.Configuration.ConfigurationManager.GetSection(String sectionName)
in NLog.Config.XmlLoggingConfiguration.get_AppConfig()
in NLog.LogFactory.get_Configuration()
in NLog.LogFactory.GetLogger(LoggerCacheKey cacheKey)
in NLog.LogFactory.GetLogger(String name)
in NLog.LogManager.GetCurrentClassLogger()
Update (config file)
<?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="Test.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</sectionGroup>
<section name="nlog" type="NLog.Config.ConfigSectionHandler, NLog"/>
</configSections>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<targets>
<target name="logfile" xsi:type="File" fileName="log-${machinename}.txt" layout="${longdate} ${level:uppercase=True} ${logger} ${message} ${exception:format=ToString,StackTrace}" />
</targets>
<rules>
<logger name="*" minlevel="Debug" writeTo="logfile" />
</rules>
</nlog>
<applicationSettings>
<Test.Properties.Settings>
<setting name="servers" serializeAs="Xml">
<value>
<ArrayOfString xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<string>111</string>
<string>222</string>
</ArrayOfString>
</value>
</setting>
</Test.Properties.Settings>
</applicationSettings>
</configuration>
NLog is instantiated this way (static field on a class):
private static NLog.Logger _logger = NLog.LogManager.GetCurrentClassLogger();
SOLUTION is to remove "untrusted origin" flag from application .config file using "unblock" button in file properties, or Sysinternals Streams tool
Thanks to #giammin who pointed me in right direction (trust level)!
Stupid me. It turns out that the cause of the problem was pretty obvious: it was result of Attachment Manager work. "Untrusted origin" flag (Zone.Identifier alternate data stream) was set on downloaded archive which contained app files.
What was unexpected for me in this, is that:
I thought that only IE implements this "protective measure". Turns out, I was wrong - user downloaded the file via Chrome, which also sets this flag. Firefox doesn't set it (I checked on the latest versions to date).
Flag was copied to files from archive (zip) after extraction. This happened, I believe, because user extracted files using built-in Windows archive tool.
The direct cause of this problem was not a flag on assembly or executable files, but rather a flag on .config file itself. Once it was removed, problem disappeared. Flags on .exe/.dll files do not contribute to the problem in any way.
I'm still not sure why this only happens on .net 4.0, and disappears when .net 4.5 is installed (application files are exactly the same).
to debug nlog you can use its internal logging:
<nlog autoReload="true" throwExceptions="true" internalLogFile="c:\log.txt" internalLogLevel="Trace">
---UPDATE---
Another check could be to move the config to an external file:
<configSections>
...
<section name="nlog" type="NLog.Config.ConfigSectionHandler, NLog"/>
</configSections>
<nlog configSource="NLog.config" />
NLog.config:
<?xml version="1.0"?>
<nlog autoReload="true" throwExceptions="true" internalLogFile="c:\log.txt" internalLogLevel="Trace">
...
</nlog>
Anyway It seems that the application is not running in FullTrust.
----UPDATE2----
Try to add this requirePermission="false" in
<section name="nlog" type="NLog.Config.ConfigSectionHandler, NLog" requirePermission="false"/>

Error only occurs after publishing: "Unable to connect to any of the specified MySQL hosts."

During development the program runs fine, but once published I noticed my elements weren't populating properly. I thought at first it was a problem with the update panels, but someone told me to use Firebug, and this is the error I see being thrown.
Again:
"Unable to connect to any of the specified MySQL hosts."
My code(This part is from the web.config):
<connectionStrings>
<add name="MySQLConnection" connectionString="[myServer];[myDatabase];UID= [myID];PWD=[myPassword];"
providerName="MySql.Data.SqlClient" />
</connectionStrings>
In C#, I call the connection string thusly:
string connstring = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["MySQLConnection"].ConnectionString;
MySqlConnection myConnection = new MySqlConnection(connstring);
Any input on why this isn't working, or why it works in development and not once published, would be greatly appreciated.
Thanks.
EDIT: New information
Oh my god, this is maddening.
So my program had a second web.config file, and I had previously put a connection string in that one with incorrect data. When the program ran that's what it was trying to use, and that's why it wasn't working. Or so I thought.
I found this out, of course, after thinking it was the same file, and simply trying to update it. Finally I removed the connection string from the old file altogether, and what do you know, I now know that it's using the proper connection string.
Hoo-ray for me, right? Nope.
I now know that it is using the correct connection string, and yet it is still somehow not working.
That being said, I added some better troubleshooting in, so now I have this:
MySql.Data.MySqlClient.MySqlException (0x80004005): Unable to connect to any of the specified MySQL hosts. ---> System.Security.SecurityException: Request for the permission of type 'System.Net.SocketPermission, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.
at System.Security.CodeAccessSecurityEngine.Check(Obj ect demand, StackCrawlMark& stackMark, Boolean isPermSet)
at System.Security.CodeAccessSecurityEngine.Check(Cod eAccessPermission cap, StackCrawlMark& stackMark)
at System.Security.CodeAccessPermission.Demand()
at System.Net.Sockets.Socket.CheckCacheRemote(EndPoin t& remoteEP, Boolean isOverwrite)
at System.Net.Sockets.Socket.BeginConnectEx(EndPoint remoteEP, Boolean flowContext, AsyncCallback callback, Object state)
at System.Net.Sockets.Socket.BeginConnect(EndPoint remoteEP, AsyncCallback callback, Object state)
at MySql.Data.Common.StreamCreator.CreateSocketStream (IPAddress ip, Boolean unix)
at MySql.Data.Common.StreamCreator.GetStream(UInt32 timeout)
at MySql.Data.MySqlClient.NativeDriver.Open()
The action that failed was:
Demand
The type of the first permission that failed was:
System.Net.SocketPermission
The Zone of the assembly that failed was:
MyComputer
at MySql.Data.MySqlClient.NativeDriver.Open()
at MySql.Data.MySqlClient.Driver.Create(MySqlConnecti onStringBuilder settings)
at MySql.Data.MySqlClient.MySqlPool.GetPooledConnecti on()
at MySql.Data.MySqlClient.MySqlPool.TryToGetDriver()
at MySql.Data.MySqlClient.MySqlPool.GetConnection()
at MySql.Data.MySqlClient.MySqlConnection.Open()
at WordsOfPower.testing.update_words() in C:\Users\AJ\documents\visual studio 2010\Projects\WordsOfPower\WordsOfPower\WordsOfPow er.aspx.cs:line 39
Final Edit: I updated my web.config to use full trust.
http://support.winhost.com/KB/a657/changing-the-default-aspnet-trust-level.aspx
Make sure the connection string in the web.config file is correct
<add name="STRING_CONNECTION" connectionString="Server=[SERVER];Database=[DATA BASE NAME];Uid=[USER];Pwd=[PASSWORD];" providerName="MySql.Data.MySqlClient"/>
That is a trust issue.
See http://www.marthijnvandenheuvel.com/2011/04/14/fix-net-4-socketpermission-for-mysql-driver-in-medium-trust/

Activation error occured while trying to get instance of type ICacheManager, key "Cache Manager"

I seem to have hit a wall here and would appreciate some help from anyone who is able to on this one. I am not exactly sure what the error message below means. I am using the Caching Block of Enterprise Pattern Services but I keep running in to the problem below. I downloaded the latest version and tried stepping through to the issue but I can't seem to pin the exact problem and I need help please. Thanks in advance
Test method WorldBank.Service.Business.UnitTest.TopicsManagerTest.Call_Children_out_of_schoolTest threw exception:
Microsoft.Practices.ServiceLocation.ActivationException: Activation error occured while trying to get instance of type ICacheManager, key "Cache Manager" ---> Microsoft.Practices.Unity.ResolutionFailedException: Resolution of the dependency failed, type = "Microsoft.Practices.EnterpriseLibrary.Caching.ICacheManager", name = "Cache Manager".
Exception occurred while: while resolving.
Exception is: InvalidOperationException - The current type, Microsoft.Practices.EnterpriseLibrary.Caching.ICacheManager, is an interface and cannot be constructed. Are you missing a type mapping?
-----------------------------------------------
At the time of the exception, the container was:
Resolving Microsoft.Practices.EnterpriseLibrary.Caching.ICacheManager,WuCache
---> System.InvalidOperationException: The current type, Microsoft.Practices.EnterpriseLibrary.Caching.ICacheManager, is an interface and cannot be constructed. Are you missing a type mapping?
Microsoft.Practices.ObjectBuilder2.DynamicMethodConstructorStrategy.ThrowForAttemptingToConstructInterface(IBuilderContext context) in e:\Builds\Unity\UnityTemp\Compile\Unity\Unity\Src\ObjectBuilder\Strategies\BuildPlan\DynamicMethod\Creation\DynamicMethodConstructorStrategy.cs: line 209
BuildUp_Microsoft.Practices.EnterpriseLibrary.Caching.ICacheManager(IBuilderContext )
Microsoft.Practices.ObjectBuilder2.DynamicMethodBuildPlan.BuildUp(IBuilderContext context) in e:\Builds\Unity\UnityTemp\Compile\Unity\Unity\Src\ObjectBuilder\Strategies\BuildPlan\DynamicMethod\DynamicMethodBuildPlan.cs: line 37
Microsoft.Practices.ObjectBuilder2.BuildPlanStrategy.PreBuildUp(IBuilderContext context) in e:\Builds\Unity\UnityTemp\Compile\Unity\Unity\Src\ObjectBuilder\Strategies\BuildPlan\BuildPlanStrategy.cs: line 43
Microsoft.Practices.ObjectBuilder2.StrategyChain.ExecuteBuildUp(IBuilderContext context) in e:\Builds\Unity\UnityTemp\Compile\Unity\Unity\Src\ObjectBuilder\Strategies\StrategyChain.cs: line 110
Microsoft.Practices.Unity.UnityContainer.DoBuildUp(Type t, Object existing, String name, IEnumerable`1 resolverOverrides) in e:\Builds\Unity\UnityTemp\Compile\Unity\Unity\Src\UnityContainer.cs: line 511
Microsoft.Practices.Unity.UnityContainer.DoBuildUp(Type t, Object existing, String name, IEnumerable`1 resolverOverrides) in e:\Builds\Unity\UnityTemp\Compile\Unity\Unity\Src\UnityContainer.cs: line 515
Microsoft.Practices.Unity.UnityContainer.Resolve(Type t, String name, ResolverOverride[] resolverOverrides) in e:\Builds\Unity\UnityTemp\Compile\Unity\Unity\Src\UnityContainer.cs: line 173
Microsoft.Practices.Unity.UnityServiceLocator.DoGetInstance(Type serviceType, String key) in e:\Builds\Unity\UnityTemp\Compile\Unity\Unity\Src\UnityServiceLocator.cs: line 64
Microsoft.Practices.ServiceLocation.ServiceLocatorImplBase.GetInstance(Type serviceType, String key) in c:\Home\Chris\Projects\CommonServiceLocator\main\Microsoft.Practices.ServiceLocation\ServiceLocatorImplBase.cs: line 49
Microsoft.Practices.ServiceLocation.ServiceLocatorImplBase.GetInstance(Type serviceType, String key) in c:\Home\Chris\Projects\CommonServiceLocator\main\Microsoft.Practices.ServiceLocation\ServiceLocatorImplBase.cs: line 53
Microsoft.Practices.ServiceLocation.ServiceLocatorImplBase.GetInstance[TService](String key) in c:\Home\Chris\Projects\CommonServiceLocator\main\Microsoft.Practices.ServiceLocation\ServiceLocatorImplBase.cs: line 103
Microsoft.Practices.EnterpriseLibrary.Caching.CacheFactory.InnerGetCacheManager(String cacheManagerName) in e:\Builds\EntLib\Latest\Source\Blocks\Caching\Src\Caching\CacheFactory.cs: line 66
Microsoft.Practices.EnterpriseLibrary.Caching.CacheFactory.GetCacheManager(String cacheManagerName) in e:\Builds\EntLib\Latest\Source\Blocks\Caching\Src\Caching\CacheFactory.cs: line 53
WorldBank.Service.Business.ResponseManager.Get_w_Utility() in C:\SOOfficialPiece\WorldBank.Service.Business\ResponseManager.cs: line 42
WorldBank.Service.Business.ResponseManager..ctor() in C:\SOOfficialPiece\WorldBank.Service.Business\ResponseManager.cs: line 34
WorldBank.Service.Business.ResponseManager.getResponseObjectJSON(Int32 perpage, Object results, Boolean doDeepRetrieval) in C:\SOOfficialPiece\WorldBank.Service.Business\ResponseManager.cs: line 68
System.Dynamic.UpdateDelegates.UpdateAndExecute4[T0,T1,T2,T3,TRet](CallSite site, T0 arg0, T1 arg1, T2 arg2, T3 arg3)
WorldBankBusiness.Topics.TopicsManager.Call_Children_out_of_school(PersonType persontype, EnrollmentType enrollmenttype, String countrycode) in C:\SOOfficialPiece\WorldBank.Service.Business\TopicsManager.cs: line 39
WorldBank.Service.Business.UnitTest.TopicsManagerTest.Call_Children_out_of_schoolTest() in C:\SOOfficialPiece\WorldBank.Service.Business.UnitTest\TopicsManagerTest.cs: line 88
The Caching Application Block requires some configuration information to be present in the app/web.config before it can be used (AFAIK, unfortunately it is tough to find documentation stating otherwise). Without that configuration info, the following code will cause that same exception to be thrown as you are seeing:
var cm = CacheFactory.GetCacheManager("MyCacheManager");
In order to get a CacheManager, you need to define the CacheManager in your app.config or web.config:
<configuration>
<configSections>
<section name="cachingConfiguration"
type="Microsoft.Practices.EnterpriseLibrary.Caching.Configuration.CacheManagerSettings, Microsoft.Practices.EnterpriseLibrary.Caching, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="true" />
</configSections>
<cachingConfiguration defaultCacheManager="MyCacheManager">
<cacheManagers>
<add name="MyCacheManager" type="Microsoft.Practices.EnterpriseLibrary.Caching.CacheManager, Microsoft.Practices.EnterpriseLibrary.Caching, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
expirationPollFrequencyInSeconds="60"
maximumElementsInCacheBeforeScavenging="50000"
numberToRemoveWhenScavenging="1000"
backingStoreName="NullBackingStore" />
</cacheManagers>
<backingStores>
<add type="Microsoft.Practices.EnterpriseLibrary.Caching.BackingStoreImplementations.NullBackingStore, Microsoft.Practices.EnterpriseLibrary.Caching, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
name="NullBackingStore" />
</backingStores>
</cachingConfiguration>
</configuration>
Once you add the configuration values, you should be able to get a valid CacheManager from the CacheFactory. The post also has some more information that might help you.
It is worth noting that if you are using .NET 4.0, for non web apps you can use MemoryCache (in the System.Runtime.Caching namespace) which provides similar functionality but does not require all of this configuration. And for web apps you can of course use the Cache class in System.Web.Caching.

Categories

Resources