I am using Microsoft.WindowsAzure.Storage.dll version 6.0.0 for working with Azure table storage. While adding a new entry in the table, I am getting following error.
Line of code throwing error:
var operation = TableOperation.InsertOrReplace(entity);
await this.CloudTable.ExecuteAsync(operation).ConfigureAwait(false); -> // Throws error
where entity is of type TableEntity
I have referenced following assemblies:
<package id="Microsoft.Azure.KeyVault.Core" version="1.0.0" targetFramework="net451" />
<package id="Microsoft.Data.Edm" version="5.6.4" targetFramework="net451" />
<package id="Microsoft.Data.OData" version="5.6.4" targetFramework="net451" />
<package id="Microsoft.Data.Services.Client" version="5.6.4" targetFramework="net451" />
<package id="Newtonsoft.Json" version="6.0.8" targetFramework="net45" />
<package id="System.Spatial" version="5.6.4" targetFramework="net451" />
<package id="WindowsAzure.Storage" version="6.0.0" targetFramework="net451" />
Note: The code execute fine when run on my local machine, but throws above exception when run on a different environment which we don't own. (Different set of machines hosted somewhere else, and also we don't have access to these machines)
Error:
Error: System.EntryPointNotFoundException: Entry point was not
found.#R##N# at
Microsoft.WindowsAzure.Storage.Table.ITableEntity.get_PartitionKey()#R##N#
at
Microsoft.WindowsAzure.Storage.Table.TableOperation.GenerateCMDForOperation(CloudTableClient
client, CloudTable table, TableRequestOptions modifiedOptions)#R##N#
at
Microsoft.WindowsAzure.Storage.Table.TableOperation.BeginExecute(CloudTableClient
client, CloudTable table, TableRequestOptions requestOptions,
OperationContext operationContext, AsyncCallback callback, Object
state)#R##N# at
Microsoft.WindowsAzure.Storage.Table.CloudTable.BeginExecute(TableOperation
operation, TableRequestOptions requestOptions, OperationContext
operationContext, AsyncCallback callback, Object state)#R##N# at
Microsoft.WindowsAzure.Storage.Table.CloudTable.BeginExecute(TableOperation
operation, AsyncCallback callback, Object state)#R##N# at
Microsoft.WindowsAzure.Storage.Core.Util.AsyncExtensions.TaskFromApm[T1,TResult](Func 4
beginMethod, Func 2 endMethod, T1 arg1, CancellationToken
cancellationToken)#R##N# at
Microsoft.WindowsAzure.Storage.Table.CloudTable.ExecuteAsync(TableOperation
operation, CancellationToken cancellationToken)#R##N# at
Microsoft.WindowsAzure.Storage.Table.CloudTable.ExecuteAsync(TableOperation
operation)#R##N# at
Microsoft.OnlinePublishing.Retry.TaskRetryer 2.DoAction()#R##N#--- End
of stack trace from previous location where exception was thrown
---#R##N# at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
task)#R##N# at
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task)#R##N# at
System.Runtime.CompilerServices.ConfiguredTaskAwaitable 1.ConfiguredTaskAwaiter.GetResult()#R##N#
at
Microsoft.OnlinePublishing.Ingestion.Common.Cache.CloudTableManager.d__6 1.MoveNext()
This exception indicates that there is a version mismatch of reference assembly "Microsoft.WindowsAzure.Storage.dll" between the assembly that defines your TableEntity type and the assembly that is operating on it.
Which version of "Microsoft.WindowsAzure.Storage.dll" is referenced by the assembly where your TableEntity type is defined?
Related
I have an ASP NET MVC project which uses Ninject for IoC. Have added a Serilog logger
public class LoggingModule : BaseModule
{
public override void Load()
{
var fileName = "c:\path\file.log";
var loggerConfiguration = new LoggerConfiguration()
.WriteTo.RollingFile(fileName, LogEventLevel.Debug)
.MinimumLevel.Verbose();
var logger = loggerConfiguration.CreateLogger();
Log.Logger = logger;
Bind<ILogger>().ToConstant(logger);
}
}
And am injecting this into a Controller.
When I exercise the code that uses it to log it will log once and then never again until I restart the web app.
I'm using the same configuration code (without ninject) in a windows service which works fine.
Versions installed are
<package id="Serilog" version="2.3.0" targetFramework="net45" />
<package id="Serilog.Sinks.File" version="3.1.0" targetFramework="net45" />
<package id="Serilog.Sinks.RollingFile" version="3.2.0" targetFramework="net45" />
<package id="Ninject" version="3.2.2.0" targetFramework="net45" />
<package id="Ninject.MVC3" version="3.2.1.0" targetFramework="net45" />
<package id="Ninject.Web.Common" version="3.2.3.0" targetFramework="net45" />
<package id="Ninject.Web.Common.WebHost" version="3.2.3.0" targetFramework="net45" />
<package id="Microsoft.AspNet.Mvc" version="5.2.3" targetFramework="net45" />
Update:
Following on from Caio's answer. I added in the SelfLog and see...
2016-11-22T14:29:25.6317957Z Caught exception while emitting to sink Serilog.Core.Sinks.RestrictedSink: System.ObjectDisposedException: Cannot access a disposed object.
Object name: 'The rolling log file has been disposed.'.
at Serilog.Sinks.RollingFile.RollingFileSink.Emit(LogEvent logEvent)
at Serilog.Core.Sinks.SafeAggregateSink.Emit(LogEvent logEvent)
Update 2:
This turned out to be a bug in the way that IDependencyResolver had been implemented in our project. IDependencyResolver implements IDisposable and our implementation called dispose on the kernel. (Un?)luckily this had just never caused an issue before.
I've marked Caio's answer as the answer because him pointing me to the SelfLog gave me the tool to unwind what was happening. Thanks to all the helped though!
Have you tried checking the output from Serilog's self log, to see if there's any error occurring internally?
e.g.
Serilog.Debugging.SelfLog.Enable(msg => Console.WriteLine(msg));
https://github.com/serilog/serilog/wiki/Debugging-and-Diagnostics
First question: Are you using one of the Ninject.MVC packages? If not, I'd try this first as they plug the Ninject container into the MVC pipeline correctly.
https://www.nuget.org/packages/Ninject.MVC5/
Also:
You can sometimes have an order-of-operations problem with DI containers. For this reason I find that it's unsafe to do much setup logic directly in the NinjectModule. I'd try something like this instead:
Bind<ILogger>().ToMethod(context => {
var fileName = "c:\path\file.log";
var loggerConfiguration = new LoggerConfiguration()
.WriteTo.RollingFile(fileName, LogEventLevel.Debug)
.MinimumLevel.Verbose();
var logger = loggerConfiguration.CreateLogger();
Log.Logger = logger;
}).In <whatever> Scope()
When I deploy (using web deploy) my asp.net Web API project, I get the following error (see stack trace below)
Server Error in '/images.mysite.com' Application.
Could not load file or assembly 'Magick.NET-x64.DLL' or one of its dependencies. The specified module could not be found.
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 'Magick.NET-x64.DLL' or one of its dependencies. The specified module could not be found.
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.
Stack Trace:
[FileNotFoundException: Could not load file or assembly 'Magick.NET-x64.DLL' or one of its dependencies. The specified module could not be found.]
System.Reflection.RuntimeAssembly._nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks) +0
System.Reflection.RuntimeAssembly.InternalLoadAssemblyName(AssemblyName assemblyRef, Evidence assemblySecurity, RuntimeAssembly reqAssembly, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks) +210
System.Reflection.RuntimeAssembly.InternalLoad(String assemblyString, Evidence assemblySecurity, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean forIntrospection) +242
System.Reflection.RuntimeAssembly.InternalLoad(String assemblyString, Evidence assemblySecurity, StackCrawlMark& stackMark, Boolean forIntrospection) +17
System.Reflection.Assembly.Load(String assemblyString) +35
System.Web.Configuration.CompilationSection.LoadAssemblyHelper(String assemblyName, Boolean starDirective) +122
[ConfigurationErrorsException: Could not load file or assembly 'Magick.NET-x64.DLL' or one of its dependencies. The specified module could not be found.]
System.Web.Configuration.CompilationSection.LoadAssemblyHelper(String assemblyName, Boolean starDirective) +12762790
System.Web.Configuration.CompilationSection.LoadAllAssembliesFromAppDomainBinDirectory() +503
System.Web.Configuration.AssemblyInfo.get_AssemblyInternal() +142
System.Web.Compilation.BuildManager.GetReferencedAssemblies(CompilationSection compConfig) +334
System.Web.Compilation.BuildManager.CallPreStartInitMethods(String preStartInitListPath) +203
System.Web.Compilation.BuildManager.ExecutePreAppStart() +152
System.Web.Hosting.HostingEnvironment.Initialize(ApplicationManager appManager, IApplicationHost appHost, IConfigMapPathFactory configMapPathFactory, HostingEnvironmentParameters hostingParameters, PolicyLevel policyLevel, Exception appDomainCreationException) +1151
[HttpException (0x80004005): Could not load file or assembly 'Magick.NET-x64.DLL' or one of its dependencies. The specified module could not be found.]
System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +12883252
System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +159
System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) +12724313
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.17929
My server is windows server 2008 r2 standard
Running IIS : Windows server 2008 r2 standard
My project properties are:
Configuration: Active(Debug)
Platform:Active(x64)
Platform target: x64
warning level: 4
output pasth: bin\
treat warnings as errors : none
generate seriealization assembly: auto
On a side note, when I DO publish he project I’ve noticed that “ImageMagick (Magick.NET-x64)” is not showing up in the package manifest. Strange? What the hell?
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="EntityFramework" version="5.0.0" targetFramework="net45" />
<package id="EtsTraceLogger" version="1.0.0" targetFramework="net45" />
<package id="Microsoft.AspNet.Mvc" version="4.0.20710.0" targetFramework="net45" />
<package id="Microsoft.AspNet.Razor" version="2.0.20710.0" targetFramework="net45" />
<package id="Microsoft.AspNet.Web.Optimization" version="1.0.0" targetFramework="net45" />
<package id="Microsoft.AspNet.WebApi" version="4.0.20710.0" targetFramework="net45" />
<package id="Microsoft.AspNet.WebApi.Client" version="4.0.20710.0" targetFramework="net45" />
<package id="Microsoft.AspNet.WebApi.Core" version="4.0.30506.0" targetFramework="net45" />
<package id="Microsoft.AspNet.WebApi.OData" version="4.0.30506" targetFramework="net45" />
<package id="Microsoft.AspNet.WebApi.WebHost" version="4.0.20710.0" targetFramework="net45" />
<package id="Microsoft.AspNet.WebPages" version="2.0.20710.0" targetFramework="net45" />
<package id="Microsoft.Data.Edm" version="5.2.0" targetFramework="net45" />
<package id="Microsoft.Data.OData" version="5.2.0" targetFramework="net45" />
<package id="Microsoft.Net.Http" version="2.0.20710.0" targetFramework="net45" />
<package id="Microsoft.Web.Infrastructure" version="1.0.0.0" targetFramework="net45" />
<package id="Newtonsoft.Json" version="4.5.6" targetFramework="net45" />
<package id="System.Spatial" version="5.2.0" targetFramework="net45" />
<package id="WebGrease" version="1.1.0" targetFramework="net45" />
</packages>
Any help in the deployment of an Magick.NET-x64 based application would greatly be appreciated.
Oh...
I fixed this by installing the following,
http://www.microsoft.com/en-us/download/details.aspx?id=30679
Hope that helps!
Magick.NET Needs VC 2012 Runtime to be installed. (Visual C++ Redistributable for Visual Studio 2012)
Also once Visual C++ Redistributable for Visual Studio 2012 is installed on the server, it requires a restart.
I have an NServiceBus saga that is trying to schedule a timeout using the Raven timeout persister but when it tries it gets this error:
NServiceBus.Unicast.Transport.Transactional.TransactionalTransport [(null)] <(null)> - Failed raising 'transport message received' event for message with ID=90dadfbd-9eb6-4558-96ec-37edb642330a\17275422
System.InvalidOperationException: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd">
<HTML><HEAD><TITLE>Bad Request</TITLE>
<META HTTP-EQUIV="Content-Type" Content="text/html; charset=us-ascii"></HEAD>
<BODY><h2>Bad Request - Request Too Long</h2>
<hr><p>HTTP Error 400. The size of the request headers is too long.</p>
</BODY></HTML>
---> System.Net.WebException: The remote server returned an error: (400) Bad Request.
at System.Net.HttpWebRequest.GetResponse()
at Raven.Client.Connection.HttpJsonRequest.ReadStringInternal(Func`1 getResponse)
--- End of inner exception stack trace ---
at Raven.Client.Connection.HttpJsonRequest.ReadStringInternal(Func`1 getResponse)
at Raven.Client.Connection.HttpJsonRequest.ReadResponseString()
at Raven.Client.Connection.HttpJsonRequest.ReadResponseJson()
at Raven.Client.Connection.ServerClient.DirectPut(RavenJObject metadata, String key, Nullable`1 etag, RavenJObject document, String operationUrl)
at Raven.Client.Connection.ServerClient.<>c__DisplayClass10.<Put>b__f(String u)
at Raven.Client.Connection.ServerClient.TryOperation[T](Func`2 operation, String operationUrl, Boolean avoidThrowing, T& result)
at Raven.Client.Connection.ServerClient.ExecuteWithReplication[T](String method, Func`2 operation)
at Raven.Client.Connection.ServerClient.Put(String key, Nullable`1 etag, RavenJObject document, RavenJObject metadata)
at Raven.Client.Document.HiLoKeyGenerator.PutDocument(JsonDocument document)
at Raven.Client.Document.HiLoKeyGenerator.GetNextMax()
at Raven.Client.Document.HiLoKeyGenerator.NextId()
at Raven.Client.Document.HiLoKeyGenerator.GenerateDocumentKey(DocumentConvention convention, Object entity)
at Raven.Client.Document.MultiTypeHiLoKeyGenerator.GenerateDocumentKey(DocumentConvention conventions, Object entity)
at Raven.Client.Document.DocumentStore.<>c__DisplayClass1.<Initialize>b__0(Object entity)
at Raven.Client.Document.InMemoryDocumentSessionOperations.GetOrGenerateDocumentKey(Object entity)
at Raven.Client.Document.InMemoryDocumentSessionOperations.StoreInternal(Object entity, Nullable`1 etag, String id)
at Raven.Client.Document.InMemoryDocumentSessionOperations.Store(Object entity)
at NServiceBus.Timeout.Hosting.Windows.Persistence.RavenTimeoutPersistence.Add(TimeoutData timeout)
at NServiceBus.Timeout.Core.TimeoutTransportMessageHandler.Handle(TransportMessage message)
at NServiceBus.Unicast.Transport.Transactional.TransactionalTransport.OnTransportMessageReceived(TransportMessage msg)
I have restarted the Raven service & the nservicebus host. I've tried recreating this saga again but it still happens.
The timeout status message that is being scheduled is tiny:
<Messages xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://tempuri.net/Invoicing.Service">
<IPartPaymentTimeout>
<Amount>10.00</Amount>
<OriginalTransactionTimeUtc>2013-01-14T05:49:04.8180938Z</OriginalTransactionTimeUtc>
<PaymentNumber>7</PaymentNumber>
<Id>123456</Id>
<InvoiceNumber>1234567/34567</InvoiceNumber>
</IPartPaymentTimeout>
</Messages>
This was resolved in my case by stopping New Relic from instumenting custom applications. It looks like there is a bug in New Relic where it appends a request header X-NewRelic-ID, which gets appended with the same data until it grows too long:
X-NewRelic-ID: <hash>, <samehash>, <samehash>,.....<samehash>
Disabling instrumentation of NServiceBus.Host in the NewRelic.xml file prevents the header being sent.
In NewRelic.xml, you might also disable crossApplicationTracingEnabled.
To detect this, use tracing from System.Diagnostics:
<system.diagnostics>
<trace autoflush="true" />
<sources>
<source name="System.Net" maxdatasize="1024">
<listeners>
<add name="MyTraceFile"/>
</listeners>
</source>
</sources>
<sharedListeners>
<add
name="MyTraceFile"
type="System.Diagnostics.TextWriterTraceListener"
initializeData="System.Net.trace.log"
/>
</sharedListeners>
<switches>
<add name="System.Net" value="Verbose" />
</switches>
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.
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);
}
}
}