Could not create the driver from NHibernate.Driver.SQLiteDriver - nhibernate

I am sorry I am posting this question again. I googled for it and found many posts and threads on stackoverflow and other ones, but none wokred for me.
I get this error message when I run my Windows Forms Application.
Here is my App.config file:
<?xml version="1.0"?>
<configuration>
<configSections>
<section name="hibernate-configuration" type="NHibernate.Cfg.ConfigurationSectionHandler, NHibernate"/>
</configSections>
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
<session-factory name="NHibernate.Test">
<property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property>
<property name="connection.driver_class">NHibernate.Driver.SQLiteDriver</property>
<property name="connection.connection_string">
Data Source=nhibernate.db;Version=3;New=True;
</property>
<property name="dialect">NHibernate.Dialect.SQLiteDialect</property>
<property name="query.substitutions">true=1;false=0</property>
<property name="proxyfactory.factory_class">
NHibernate.ByteCode.LinFu.ProxyFactoryFactory,NHibernate.ByteCode.LinFu
</property>
</session-factory>
</hibernate-configuration>
<startup useLegacyV2RuntimeActivationPolicy="true">
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
</startup>
</configuration>
I am using Visual Studio 2010, on Windows Server 2008 R2 64 Bit.
My project configuration is X86, and I tried the x86, x64 and ManagedOnly versions of the System.Data.SQLite.dll file, but none seemed to work.
Can anyone please help me with this?
P.S: I know there are similar threads to this one, but please don't close this thread because none of the solutions have worked for me.
Thanks.

Here is the error:
NHibernate.HibernateException: Could not create the driver from NHibernate.Driver.SQLiteDriver. ---> System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> NHibernate.HibernateException: The IDbCommand and IDbConnection implementation in the assembly SQLite.NET could not be found. Ensure that the assembly SQLite.NET is located in the application directory or in the Global Assembly Cache. If the assembly is in the GAC, use <qualifyAssembly/> element in the application configuration file to specify the full name of the assembly.
at NHibernate.Driver.ReflectionBasedDriver..ctor(String driverAssemblyName, String connectionTypeName, String commandTypeName)
at NHibernate.Driver.SQLiteDriver..ctor()
--- End of inner exception stack trace ---
at System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck)
at System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache)
at System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipVisibilityChecks, Boolean skipCheckThis, Boolean fillCache)
at System.Activator.CreateInstance(Type type, Boolean nonPublic)
at NHibernate.Bytecode.ActivatorObjectsFactory.CreateInstance(Type type)
at NHibernate.Connection.ConnectionProvider.ConfigureDriver(IDictionary`2 settings)
--- End of inner exception stack trace ---
at NHibernate.Connection.ConnectionProvider.ConfigureDriver(IDictionary`2 settings)
at NHibernate.Connection.ConnectionProvider.Configure(IDictionary`2 settings)
at NHibernate.Connection.ConnectionProviderFactory.NewConnectionProvider(IDictionary`2 settings)
at NHibernate.Cfg.SettingsFactory.BuildSettings(IDictionary`2 properties)
at NHibernate.Cfg.Configuration.BuildSettings()
at NHibernate.Cfg.Configuration.BuildSessionFactory()
at Employee.App.SessionProvider.get_Session() in C:\Users\Ako\documents\visual studio 2010\Projects\Employee\Employee.App\SessionProvider.cs:line 28
at Employee.App.EmployeeManager.get_Session() in C:\Users\Ako\documents\visual studio 2010\Projects\Employee\Employee.App\EmployeeManager.cs:line 14
at Employee.App.EmployeeManager.Save(Employee employee) in C:\Users\Ako\documents\visual studio 2010\Projects\Employee\Employee.App\EmployeeManager.cs:line 56
at Employee.App.frmMain.frmMain_Load(Object sender, EventArgs e) in C:\Users\Ako\documents\visual studio 2010\Projects\Employee\Employee.App\frmMain.cs:line 23
at System.Windows.Forms.Form.OnLoad(EventArgs e)
at System.Windows.Forms.Form.OnCreateControl()
at System.Windows.Forms.Control.CreateControl(Boolean fIgnoreVisible)
at System.Windows.Forms.Control.CreateControl()
at System.Windows.Forms.Control.WmShowWindow(Message& m)
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.ScrollableControl.WndProc(Message& m)
at System.Windows.Forms.Form.WmShowWindow(Message& m)
at System.Windows.Forms.Form.WndProc(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)

The error appears to be with the driver creation, this suggests to me that the driver is not installed on your system correctly. I've just tested this and it works for me (ok I'm using monodevelop, not VS), I installed the Sqlite driver from here:
ADO.NET 2.0 Provider for SQLite
I then used this in my app.config file:
<session-factory>
<property name="dialect">NHibernate.Dialect.SQLiteDialect</property>
<property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property>
<property name="connection.driver_class">NHibernate.Driver.SQLiteDriver</property>
<property name="connection.connection_string">Data Source=SimpleExample.sqlite;Version=3</property>
<property name="proxyfactory.factory_class">NHibernate.ByteCode.LinFu.ProxyFactoryFactory, NHibernate.ByteCode.LinFu</property>
<mapping assembly="SimpleExample" />
</session-factory>

it appears that the SQLite assembly is not loaded hence the error:
Could not create the driver from NHibernate.Driver.SQLiteDriver. ---> System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> NHibernate.HibernateException: The IDbCommand and IDbConnection implementation in the assembly SQLite.NET could not be found. Ensure that the assembly SQLite.NET is located in the application directory or in the Global Assembly Cache. If the assembly is in the GAC, use element in the application configuration file to specify the full name of the assembly.
you could preload the assembly using:
PreLoadAssembliesFromPath(AppDomain.CurrentDomain.BaseDirectory);
private static void PreLoadAssembliesFromPath(string p)
{
//S.O. NOTE: ELIDED - ALL EXCEPTION HANDLING FOR BREVITY
//get all .dll files from the specified path and load the lot
FileInfo[] files = null;
//you might not want recursion - handy for localised assemblies
//though especially.
files = new DirectoryInfo(p).GetFiles("*.dll",SearchOption.AllDirectories);
AssemblyName a = null;
string s = null;
foreach (var fi in files)
{
s = fi.FullName;
//now get the name of the assembly you've found, without loading it
//though (assuming .Net 2+ of course).
a = AssemblyName.GetAssemblyName(s);
//sanity check - make sure we don't already have an assembly loaded
//that, if this assembly name was passed to the loaded, would actually
//be resolved as that assembly. Might be unnecessary - but makes me
//happy :)
if (!AppDomain.CurrentDomain.GetAssemblies().Any(assembly =>
AssemblyName.ReferenceMatchesDefinition(a, assembly.GetName())))
{
//crucial - USE THE ASSEMBLY NAME.
//in a web app, this assembly will automatically be bound from the
//Asp.Net Temporary folder from where the site actually runs.
Assembly.Load(a);
}
}
}

Related

DbProviderFactory CreateConnection Fails for System.Data.SqlClient

Here is the code to test with. Create a new Form, add a button and put this code in the button.
Dim dbf As Data.Common.DbProviderFactory
'
' uncomment one of the below dbf =
'
'this fails
'dbf = Data.Common.DbProviderFactories.GetFactory("System.Data.SqlClient")
'these work
'dbf = Data.Common.DbProviderFactories.GetFactory("System.Data.Odbc")
'dbf = Data.Common.DbProviderFactories.GetFactory("System.Data.OleDb")
Dim conn As Data.Common.DbConnection
conn = dbf.CreateConnection
The create connection only fails for SqlClient. The error is
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.SqlClientFactory.CreateConnection()
at WindowsApplication1.Form1.Button1_Click(Object sender, EventArgs e) in C:\Users\dewayne.basnett\AppData\Local\Temporary Projects\WindowsApplication1\Form1.vb:line 19
at System.Windows.Forms.Control.OnClick(EventArgs e)
at System.Windows.Forms.Button.OnClick(EventArgs e)
at System.Windows.Forms.Button.PerformClick()
at System.Windows.Forms.Form.ProcessDialogKey(Keys keyData)
at System.Windows.Forms.Control.ProcessDialogKey(Keys keyData)
at System.Windows.Forms.Control.PreProcessMessage(Message& msg)
at System.Windows.Forms.Control.PreProcessControlMessageInternal(Control target, Message& msg)
at System.Windows.Forms.Application.ThreadContext.PreTranslateMessage(MSG& msg)
at System.Windows.Forms.Application.ThreadContext.System.Windows.Forms.UnsafeNativeMethods.IMsoComponent.FPreTranslateMessage(MSG& msg)
at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.OnRun()
at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.DoApplicationModel()
at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.Run(String[] commandLine)
at WindowsApplication1.My.MyApplication.Main(String[] Args) in 17d14f5c-a337-4978-8281-53493378c1071.vb:line 81
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()
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
BareMessage=Configuration system failed to initialize
HResult=-2146232062
Line=0
Message=Configuration system failed to initialize
Source=System.Configuration
StackTrace:
at System.Configuration.ClientConfigurationSystem.OnConfigRemoved(Object sender, InternalConfigEventArgs e)
at System.Configuration.Internal.InternalConfigRoot.OnConfigRemoved(InternalConfigEventArgs e)
at System.Configuration.Internal.InternalConfigRoot.RemoveConfigImpl(String configPath, BaseConfigurationRecord configRecord)
at System.Configuration.BaseConfigurationRecord.GetSectionRecursive(String configKey, Boolean getLkg, Boolean checkPermission, Boolean getRuntimeObject, Boolean requestIsHere, Object& result, Object& resultRuntimeObject)
at System.Configuration.BaseConfigurationRecord.GetSection(String configKey)
at System.Configuration.ClientConfigurationSystem.System.Configuration.Internal.IInternalConfigSystem.GetSection(String sectionName)
at System.Data.SqlClient.SqlConnection..cctor()
InnerException: System.Configuration.ConfigurationErrorsException
BareMessage=Unrecognized configuration section userSettings.
Filename=C:\Users\dewayne.basnett\AppData\Local\WindowsApplication1\WindowsApplication1.vshos_Url_odwpvb4iq0tpdwxwwhwkttkzifz10zja\1.0.0.0\user.config
HResult=-2146232062
Line=3
Message=Unrecognized configuration section userSettings. (C:\Users\dewayne.basnett\AppData\Local\WindowsApplication1\WindowsApplication1.vshos_Url_odwpvb4iq0tpdwxwwhwkttkzifz10zja\1.0.0.0\user.config line 3)
Source=System.Configuration
StackTrace:
at System.Configuration.ConfigurationSchemaErrors.ThrowIfErrors(Boolean ignoreLocal)
at System.Configuration.BaseConfigurationRecord.ThrowIfParseErrors(ConfigurationSchemaErrors schemaErrors)
at System.Configuration.BaseConfigurationRecord.ThrowIfInitErrors()
at System.Configuration.ClientConfigurationSystem.OnConfigRemoved(Object sender, InternalConfigEventArgs e)
InnerException:
EDIT: The config file is created by the IDE, but FWIW here it is
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<userSettings>
<WindowsApplication1.My.MySettings>
<setting name="AutoIncrement" serializeAs="String">
<value>False</value>
</setting>
</WindowsApplication1.My.MySettings>
</userSettings>
</configuration>
App.config contents
'FAILING
'<?xml version="1.0" encoding="utf-8"?>
'<configuration>
' <startup>
' <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5"/>
' </startup>
'</configuration>
'WORKING
'<?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="WindowsApplication1.My.MySettings" 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>
' <userSettings>
' <WindowsApplication1.My.MySettings>
' <setting name="foo" serializeAs="String">
' <value/>
' </setting>
' </WindowsApplication1.My.MySettings>
' </userSettings>
'</configuration>
The answer, and I am not sure of the mechanics behind this, is...
Yesterday a user in another domain was trying to install one of my apps and setup was throwing an error. It looked like a permission problem but they insisted it was not. One of their programmers suggested that I change the properties of a code file from Do not copy to Copy always. I didn't think it would help, but they insisted. Eventually I figured out that it was how they were mapping to the install directory.
They had it as \fileserver.mo.gov\install. Changing it to \fileserver\install fixed the problem. I did not change the code file back.
As this problem became more bizarre I thought of what happened yesterday and remembered the change. I set it back to Do not copy, republished the app, and the above problem went away. As I said I don't understand the mechanics behind this, but my issue is resolved.

Could not load file or assembly 'MvcSiteMapProvider

I added the provider via nuget console Install-Package MvcSiteMapProvider.MVC4.
The install looked good:
Successfully added 'MvcSiteMapProvider.MVC4 4.6.22' to XYZ.
When I execute the application I get this error message any suggestions on troubling shooting?
Server Error in '/XYZ' Application.
Could not load file or assembly 'MvcSiteMapProvider, Version=4.6.22.0, Culture=neutral, PublicKeyToken=1923abe4657913cc' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.IO.FileLoadException: Could not load file or assembly 'MvcSiteMapProvider, Version=4.6.22.0, Culture=neutral, PublicKeyToken=1923abe4657913cc' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Assembly Load Trace: The following information can be helpful to determine why the assembly 'MvcSiteMapProvider, Version=4.6.22.0, Culture=neutral, PublicKeyToken=1923abe4657913cc' could not be loaded.
WRN: Assembly binding logging is turned OFF.
To enable assembly bind failure logging, set the registry value [HKLM\Software\Microsoft\Fusion!EnableLog] (DWORD) to 1.
Note: There is some performance penalty associated with assembly bind failure logging.
To turn this feature off, remove the registry value [HKLM\Software\Microsoft\Fusion!EnableLog].
Stack Trace:
[FileLoadException: Could not load file or assembly 'MvcSiteMapProvider, Version=4.6.22.0, Culture=neutral, PublicKeyToken=1923abe4657913cc' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)]
System.Reflection.CustomAttribute._CreateCaObject(RuntimeModule pModule, IRuntimeMethodInfo pCtor, Byte** ppBlob, Byte* pEndBlob, Int32* pcNamedArgs) +0
System.Reflection.CustomAttribute.CreateCaObject(RuntimeModule module, IRuntimeMethodInfo ctor, IntPtr& blob, IntPtr blobEnd, Int32& namedArgs) +38
System.Reflection.CustomAttribute.GetCustomAttributes(RuntimeModule decoratedModule, Int32 decoratedMetadataToken, Int32 pcaCount, RuntimeType attributeFilterType, Boolean mustBeInheritable, IList derivedAttributes, Boolean isDecoratedTargetSecurityTransparent) +571
System.Reflection.CustomAttribute.GetCustomAttributes(RuntimeAssembly assembly, RuntimeType caType) +103
System.Reflection.RuntimeAssembly.GetCustomAttributes(Boolean inherit) +37
Owin.Loader.DefaultLoader.SearchForStartupAttribute(String friendlyName, IList1 errors, Boolean& conflict) +106
Owin.Loader.DefaultLoader.GetDefaultConfiguration(String friendlyName, IList1 errors) +46
Owin.Loader.DefaultLoader.LoadImplementation(String startupName, IList1 errorDetails) +75
Owin.Loader.DefaultLoader.Load(String startupName, IList1 errorDetails) +21
Microsoft.Owin.Host.SystemWeb.OwinBuilder.GetAppStartup() +115
Microsoft.Owin.Host.SystemWeb.OwinHttpModule.InitializeBlueprint() +28
System.Threading.LazyInitializer.EnsureInitializedCore(T& target, Boolean& initialized, Object& syncLock, Func`1 valueFactory) +115
Microsoft.Owin.Host.SystemWeb.OwinHttpModule.Init(HttpApplication context) +106
System.Web.HttpApplication.RegisterEventSubscriptionsWithIIS(IntPtr appContext, HttpContext context, MethodInfo[] handlers) +534
System.Web.HttpApplication.InitSpecial(HttpApplicationState state, MethodInfo[] handlers, IntPtr appContext, HttpContext context) +172
System.Web.HttpApplicationFactory.GetSpecialApplicationInstance(IntPtr appContext, HttpContext context) +352
System.Web.Hosting.PipelineRuntime.InitializeApplication(IntPtr appContext) +296
[HttpException (0x80004005): Could not load file or assembly 'MvcSiteMapProvider, Version=4.6.22.0, Culture=neutral, PublicKeyToken=1923abe4657913cc' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)]
System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +9947380
System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +101
System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) +261
Assuming you actually have the Nuget package installed, that error is most usually an issue with binding redirects in your Web.config. You can try to resolve the issue manually, by finding the appropriate binding redirect and making sure the version numbers are correct. I find it easier to just force remove the package and reinstall it. That will usually fix the problem:
> uninstall-package MvcSiteMapProvider.MVC4 -Force
> install-package MvcSiteMapProvider.MVC4
Make sure your Web.config is not open in your documents pane, or if it is, that you allow it to reload. If you save over it without refreshing from the filesystem after installing a Nuget package, you'll often bork things like binding redirects, leading to this issue.

NServiceBus + Common.Logging + NLog

I'm trying to figure out how to use NServiceBus in combination withCommon.Logging. I just can not get it running. I try to develop a small demo application just for educational purpose.
What I did was:
1) Create a simple console application and imported Common.Logging and Common,Logging.NLog, added some Info messages and added an App.Config file:
<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>
That worked just fine. But when I include NServiceBus:
var bus = Configure.With().DefaultBuilder()
.XmlSerializer()
.MsmqTransport()
.IsTransactional( true )
.UnicastBus()
.MsmqSubscriptionStorage()
.CreateBus()
.Start( () => Configure.Instance.ForInstallationOn<NServiceBus.Installation.Environments.Windows>().Install() );
I get this exception:
System.TypeInitializationException was unhandled
Message=The type initializer for 'NServiceBus.Configure' threw an exception.
Source=NServiceBus.Core
TypeName=NServiceBus.Configure
StackTrace:
at NServiceBus.Configure.With()
at ConsoleApplication1.Program.Main(String[] args) in D:\Development\katas\ConsoleApplication1\ConsoleApplication1\Program.cs:line 17
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.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException: Common.Logging.ConfigurationException
Message=ConfigurationReader Common.Logging.Configuration.DefaultConfigurationReader returned unknown settings instance of type Common.Logging.Configuration.LogSetting
Source=NServiceBus.Core
StackTrace:
at Common.Logging.Configuration.ArgUtils.Guard[T](Function`1 function, String messageFormat, Object[] args)
at Common.Logging.Configuration.ArgUtils.Guard(Action action, String messageFormat, Object[] args)
at Common.Logging.LogManager.BuildLoggerFactoryAdapter()
at Common.Logging.LogManager.get_Adapter()
at Common.Logging.LogManager.GetLogger(String name)
at NServiceBus.Configure..cctor()
InnerException: System.ArgumentOutOfRangeException
Message=Type 'Common.Logging.Configuration.LogSetting, Common.Logging, Version=2.0.0.0, Culture=neutral, PublicKeyToken=af08829b84f0328e' of parameter 'sectionResult' is not assignable to target type 'Common.Logging.Configuration.LogSetting, NServiceBus.Core, Version=3.2.0.0, Culture=neutral, PublicKeyToken=9fc386479f8a226c'
Parameter name: sectionResult
Actual value was Common.Logging.Configuration.LogSetting.
Source=NServiceBus.Core
ParamName=sectionResult
StackTrace:
at Common.Logging.Configuration.ArgUtils.AssertIsAssignable[T](String paramName, Type valType, String messageFormat, Object[] args)
at Common.Logging.Configuration.ArgUtils.AssertIsAssignable[T](String paramName, Type valType)
at Common.Logging.LogManager.<>c__DisplayClass3.<BuildLoggerFactoryAdapter>b__1()
at Common.Logging.Configuration.ArgUtils.<>c__DisplayClass13.<Guard>b__12()
at Common.Logging.Configuration.ArgUtils.Guard[T](Function`1 function, String messageFormat, Object[] args)
InnerException:
I've already tried several things suggested in StackOverflow and other groups, but I just can't get it working. Can anyone offer some advice on how to approach this? Or provide a simple example?
This setup shouldn't be to fancy, right? I don't even need logging for the NServiceBus part for now.
Thanks!
NServiceBus has it's own version of Common.Logging that is ilmerged and internalized into the Core dll, that it uses to configure it's own logging (using log4net). When it starts up it discovers the configuration section in your app.config and tries to load it. However, your configuration section (called "logging") points to the external Common.Logging dll:
<section name="logging" type="Common.Logging.ConfigurationSectionHandler, Common.Logging" />
Where NSB wants it to look like:
<section name="logging" type="Common.Logging.ConfigurationSectionHandler, NServiceBus.Core" />
Because of this, NSB throws an error. This is most certainly a bug in NSB. I suggest you create an issue on their github project.
While maybe not the most optimal solution in your case, the quickest way to work around it is to delete the logging section in app.config and configure Common.Logging in code. Or, skip using Common.Logging altogether and use NLog directly.
I might add that this problem will go away in NSB 4.0 where Common.Logging is not used anymore.

NHibernate 3.0 configuration with ODP.NET

I just setup NHibernate for the first time. My platform and config settings as follows:
Database: Oracle 11.1g
ODP.NET Version: 4.112.1.2 (Installed from ODTWithODAC112012, which is a 1 release above my Oracle db installation)
NHibernate Version 3.0
I created a test MVC app with a test project. Then, to test for NHibernate connection, I use the following test fixture:
using IBCService.Models;
using NHibernate.Cfg;
using NHibernate.Tool.hbm2ddl;
using NUnit.Framework;
namespace IBCService.Tests
{
[TestFixture]
public class GenerateSchema_Fixture
{
[Test]
public void Can_generate_schema()
{
var cfg = new Configuration();
cfg.Configure();
cfg.AddAssembly(typeof(Product).Assembly);
new SchemaExport(cfg).Execute(false, true, false);
}
}
The Nhibernate config file:
<?xml version="1.0" encoding="utf-8"?>
<!-- This config use Oracle Data Provider (ODP.NET) -->
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2" >
<session-factory name="NHibernate.Test">
<property name="connection.driver_class">NHibernate.Driver.OracleDataClientDriver</property>
<property name="connection.connection_string">
User ID=TEST;Password=******;Data Source=//RAND
</property>
<property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property>
<property name="show_sql">false</property>
<property name="dialect">NHibernate.Dialect.Oracle10gDialect</property>
<property name="query.substitutions">true 1, false 0, yes 'Y', no 'N'</property>
<property name="proxyfactory.factory_class">NHibernate.ByteCode.LinFu.ProxyFactoryFactory, NHibernate.ByteCode.LinFu</property>
</session-factory>
</hibernate-configuration>
On test, I get the following exception stack trace:
NHibernate.HibernateException was unhandled by user code
Message=Could not create the driver from NHibernate.Driver.OracleDataClientDriver.
Source=NHibernate
StackTrace:
at NHibernate.Connection.ConnectionProvider.ConfigureDriver(IDictionary`2 settings) in d:\CSharp\NH\nhibernate\src\NHibernate\Connection\ConnectionProvider.cs:line 113
at NHibernate.Connection.ConnectionProvider.Configure(IDictionary`2 settings) in d:\CSharp\NH\nhibernate\src\NHibernate\Connection\ConnectionProvider.cs:line 64
at NHibernate.Connection.ConnectionProviderFactory.NewConnectionProvider(IDictionary`2 settings) in d:\CSharp\NH\nhibernate\src\NHibernate\Connection\ConnectionProviderFactory.cs:line 50
at NHibernate.Tool.hbm2ddl.SchemaExport.Execute(Action`1 scriptAction, Boolean export, Boolean justDrop) in d:\CSharp\NH\nhibernate\src\NHibernate\Tool\hbm2ddl\SchemaExport.cs:line 333
at NHibernate.Tool.hbm2ddl.SchemaExport.Execute(Boolean script, Boolean export, Boolean justDrop) in d:\CSharp\NH\nhibernate\src\NHibernate\Tool\hbm2ddl\SchemaExport.cs:line 290
at IBCService.Tests.GenerateSchema_Fixture.Can_generate_schema() in D:\APPS\VS2010\IBanking\CustomerService\IBCService.Tests\GenerateSchema_Fixture.cs:line 21
InnerException: System.Reflection.TargetInvocationException
Message=Exception has been thrown by the target of an invocation.
Source=mscorlib
StackTrace:
at System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck)
at System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache)
at System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipVisibilityChecks, Boolean skipCheckThis, Boolean fillCache)
at System.Activator.CreateInstance(Type type, Boolean nonPublic)
at System.Activator.CreateInstance(Type type)
at NHibernate.Bytecode.ActivatorObjectsFactory.CreateInstance(Type type) in d:\CSharp\NH\nhibernate\src\NHibernate\Bytecode\ActivatorObjectsFactory.cs:line 9
at NHibernate.Connection.ConnectionProvider.ConfigureDriver(IDictionary`2 settings) in d:\CSharp\NH\nhibernate\src\NHibernate\Connection\ConnectionProvider.cs:line 107
InnerException: System.NullReferenceException
Message=Object reference not set to an instance of an object.
Source=NHibernate
StackTrace:
at NHibernate.Driver.OracleDataClientDriver..ctor() in d:\CSharp\NH\nhibernate\src\NHibernate\Driver\OracleDataClientDriver.cs:line 42
InnerException:
If I change NHibernate.Driver.OracleDataClientDriver to NHibernate.Driver.OracleClientDriver (MS provider for Oracle), the test succeed. Can someone tell me what I'm doing wrong?
Hi
I think the error happens, because Nhibernate is not loading the driver from the GAC with Assembly.LoadWithPartialName(), but with Assembly.Load(). Try to place Oracle.DataAccess.dll in the bin directory or use qualifyAssembly section into your app.config or web.config.
Example:
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<qualifyAssembly partialName="Oracle.DataAccess"
fullName="Oracle.DataAccess, Version=2.102.2.20, Culture=neutral, PublicKeyToken=89b483f429c47342" />
</assemblyBinding>
</runtime>
#PerlDev: I think that you have a "ODP.NET 32 bit binary" installed and you are compiling your app with platform "AnyCPU". If so, try to change to x86 (this is what I did, and worked).
If you want to compile as x64 I think you must install the "ODP.NET 64 bit binary" (I didnĀ“t do it yet).
This worked for me.
Go Build / Configuration Manager in Visual Studio. Check the platform column. I changed debug from Any CPU to x64

After upgrading to .Net 4.0, I'm getting the exception "Could not load file or assembly 'System.Windows, Version=2.0.5.0'"

We recently upgraded our web app from 3.5 to 4.0. Now after I login and load a page with Microsoft ScriptManager on it, I get:
Could not load file or assembly 'System.Windows, Version=2.0.5.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e' or one of its dependencies. The system cannot find the file specified.
It only happens the first time, reload the page and everything works.
UPDATE: We have all Silverlight v4 projects.I found the System.Windows.dll in the C:\Program Files\Reference Assemblies\Microsoft\Framework\Silverlight\v4.0 directory. Why would it look for version 2.0?
Here's the entire exception (edited and removed folder paths)
Server Error in '/test' Application.
Could not load file or assembly 'System.Windows, Version=2.0.5.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e' or one of its dependencies. The system cannot find the file specified.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.IO.FileNotFoundException: Could not load file or assembly 'System.Windows, Version=2.0.5.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e' or one of its dependencies. The system cannot find the file specified.
Source Error:
Line 450: <UC5:PageTitle ID="PageTitle" runat="server" />
Line 451: <UC2:PageTabs ID="testPageTabs" runat="server" />
Line 452: <asp:ScriptManager ID="ScriptManager1" runat="server"/>
Line 453: <div id="step1Div" style="padding-top: 10px; padding-left: 10px" runat="server">
Line 454: <asp:ValidationSummary ID="displayValidationSummary" ValidationGroup="displayCreateEditValidationGroup" runat="server" />
Source File: c:{directories}\Pages\Administration\DisplayCreateEdit.aspx Line: 452
Assembly Load Trace: The following information can be helpful to determine why the assembly 'System.Windows, Version=2.0.5.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e' could not be loaded.
WRN: Assembly binding logging is turned OFF.
To enable assembly bind failure logging, set the registry value [HKLM\Software\Microsoft\Fusion!EnableLog] (DWORD) to 1.
Note: There is some performance penalty associated with assembly bind failure logging.
To turn this feature off, remove the registry value [HKLM\Software\Microsoft\Fusion!EnableLog].
Stack Trace:
[FileNotFoundException: Could not load file or assembly 'System.Windows, Version=2.0.5.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e' or one of its dependencies. The system cannot find the file specified.]
System.ModuleHandle.ResolveType(RuntimeModule module, Int32 typeToken, IntPtr* typeInstArgs, Int32 typeInstCount, IntPtr* methodInstArgs, Int32 methodInstCount, ObjectHandleOnStack type) +0
System.ModuleHandle.ResolveTypeHandleInternal(RuntimeModule module, Int32 typeToken, RuntimeTypeHandle[] typeInstantiationContext, RuntimeTypeHandle[] methodInstantiationContext) +180
System.Reflection.RuntimeModule.ResolveType(Int32 metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments) +192
System.Reflection.CustomAttribute.FilterCustomAttributeRecord(CustomAttributeRecord caRecord, MetadataImport scope, Assembly& lastAptcaOkAssembly, RuntimeModule decoratedModule, MetadataToken decoratedToken, RuntimeType attributeFilterType, Boolean mustBeInheritable, Object[] attributes, IList derivedAttributes, RuntimeType& attributeType, IRuntimeMethodInfo& ctor, Boolean& ctorHasParameters, Boolean& isVarArg) +115
System.Reflection.CustomAttribute.GetCustomAttributes(RuntimeModule decoratedModule, Int32 decoratedMetadataToken, Int32 pcaCount, RuntimeType attributeFilterType, Boolean mustBeInheritable, IList derivedAttributes, Boolean isDecoratedTargetSecurityTransparent) +426
System.Reflection.CustomAttribute.GetCustomAttributes(RuntimeAssembly assembly, RuntimeType caType) +103
System.Reflection.RuntimeAssembly.GetCustomAttributes(Boolean inherit) +33
System.Web.UI.AssemblyCache.GetAjaxFrameworkAssemblyAttribute(Assembly assembly) +76
System.Web.UI.ScriptManager.get_DefaultAjaxFrameworkAssembly() +388
System.Web.UI.ScriptManager..ctor() +26
ASP.pages_administration_displaycreateedit_aspx.__BuildControlScriptManager1() in c:{directories}\Pages\Administration\DisplayCreateEdit.aspx:452
ASP.pages_administration_displaycreateedit_aspx.__BuildControlContent1(Control __ctrl) in c:{directories}\Pages\Administration\DisplayCreateEdit.aspx:9
System.Web.UI.CompiledTemplateBuilder.InstantiateIn(Control container) +12
System.Web.UI.MasterPage.InstantiateInContentPlaceHolder(Control contentPlaceHolder, ITemplate template) +87
ASP.master_master.__BuildControlContentPlaceHolder1() in c:{directories}\Master.master:28
ASP.master_master.__BuildControlmasterForm() in c:{directories}\Master.master:13
ASP.master_master.__BuildControlTree(master_master __ctrl) in c:{directories}\Master.master:1
ASP.master_master.FrameworkInitialize() in c:\WINDOWS\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\zoning\dff1a5fe\99aa3a7f\App_Web_shgw15qp.4.cs:0
System.Web.UI.UserControl.InitializeAsUserControlInternal() +35
System.Web.UI.MasterPage.CreateMaster(TemplateControl owner, HttpContext context, VirtualPath masterPageFile, IDictionary contentTemplateCollection) +8832342
System.Web.UI.Page.get_Master() +54
System.Web.UI.Page.ApplyMasterPage() +15
System.Web.UI.Page.PerformPreInit() +45
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +328
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.1
And the system.web of our web.config:
<system.web>
<pages validateRequest="false" buffer="true" theme="Summer" controlRenderingCompatibilityVersion="3.5" clientIDMode="AutoID">
<controls>
<add namespace="AjaxControlToolkit" assembly="AjaxControlToolkit" tagPrefix="ajaxToolkit"/>
</controls>
<tagMapping>
<add tagType="System.Web.UI.WebControls.TextBox" mappedTagType="CleanTextBox"/>
<add tagType="System.Web.UI.HtmlControls.HtmlTextArea" mappedTagType="CleanTextArea"/>
</tagMapping>
</pages>
<compilation debug="true" targetFramework="4.0">
<assemblies>
</assemblies>
</compilation>
<authentication mode="Forms">
<forms requireSSL="false" cookieless="UseDeviceProfile" loginUrl="~/Pages/Authentication/Login.aspx" timeout="60" defaultUrl="~/Pages/Authentication/AccountHome.aspx" slidingExpiration="true" name="sqlAuthCookie" protection="All"/>
</authentication>
<sessionState timeout="60" mode="StateServer" stateConnectionString="tcpip=localhost" stateNetworkTimeout="60" cookieless="false"/>
<customErrors mode="RemoteOnly" defaultRedirect="~/Pages/Global/DefaultError.aspx">
<error statusCode="404" redirect="~/Pages/Global/404.htm"/>
<error statusCode="403" redirect="~/Pages/Global/403.htm"/>
</customErrors>
<httpHandlers>
<add path="*js.axd" verb="*" type="ScriptCompressorHandler"/>
<add path="*css.axd" verb="*" type="CssCompressorHandler"/>
<add path="*css" verb="*" type="CssCompressorHandler"/>
<add verb="*" path="Reserved.ReportViewerWebControl.axd" type="Microsoft.Reporting.WebForms.HttpHandler, Microsoft.ReportViewer.WebForms, Version=9.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>
</httpHandlers>
<httpModules>
<remove name="WindowsAuthentication"/>
<remove name="PassportAuthentication"/>
<remove name="AnonymousIdentification"/>
<remove name="RoleManager"/>
<remove name="Profile"/>
<remove name="ErrorHandlerModule"/>
<add type="ScriptCompressorModule" name="ScriptCompressorModule"/>
<add type="CssCompressorModule" name="CssCompressorModule"/>
</httpModules>
<machineKey validationKey="{key}" decryptionKey="{key}" validation="SHA1"/>
<httpRuntime maxRequestLength="1048576" executionTimeout="3600" requestValidationMode="2.0"/>
</system.web>
See the same problem here and Microsoft Feedback/Bug report
Edit: I'm running VS 2010, XP with IIS 5.0 (I miss Win 7 at work every day :-)). We have the web app running under the local IIS instance, not Cassini. We deployed it to a test server and I did not see the exception. After I installed the C:\Program Files\Reference Assemblies\Microsoft\Framework\Silverlight\v4.0\System.windows.dll to the GAC and then removed it and haven't seen the same exception, though my colleague hasn't done this and still sees it occasionally. I think it only happens when the app is restarted (which happens every time we rebuild the app when developing locally).
Sounds like one of the projects in your solution is referencing the v2 system assemblies. Make sure that all of your projects and application pools are set to use 4.0. You can set this in the project properties in Visual Studio.
(Note that you'll have to rebuild your solution with the new settings if you haven't already).
I have been having the same issues for a long time, but just found some old Silverlight Assemblies in my bin folder, removed those and voila.. error gone
Adding reference to AjaxControlToolkit.dll and adding the header
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>
to the aspx that contains the script manager solved the problem for me.