Unable to expose more than one Service - Spring WebServiceExporter - asp.net

Hi I am still fairly new to Spring in general. I have been using WebServiceExporter to expose my WebServices. However, when I tried to add another WebService to my Web.xml I get the following error:
[ArgumentException: Duplicate type name within an assembly.]
System.Reflection.Emit.ModuleBuilder.CheckTypeNameConflict(String strTypeName, Type enclosingType) +14200621
System.Reflection.Emit.AssemblyBuilderData.CheckTypeNameConflict(String strTypeName, TypeBuilder enclosingType) +91
System.Reflection.Emit.TypeBuilder.Init(String fullname, TypeAttributes attr, Type parent, Type[] interfaces, ModuleBuilder module, PackingSize iPackingSize, Int32 iTypeSize, TypeBuilder enclosingType) +161
System.Reflection.Emit.ModuleBuilder.DefineTypeNoLock(String name, TypeAttributes attr, Type parent, Type[] interfaces, PackingSize packingSize, Int32 typesize) +103
System.Reflection.Emit.ModuleBuilder.DefineType(String name, TypeAttributes attr, Type parent) +289
Spring.Proxy.DynamicProxyManager.CreateTypeBuilder(String typeName, Type baseType) +145
[ArgumentException: Proxy already registered for "UserWebService" as Type "UserWebService".]
Spring.Proxy.DynamicProxyManager.CreateTypeBuilder(String typeName, Type baseType) +353
Spring.Proxy.CompositionProxyTypeBuilder.BuildProxyType() +149
Spring.Web.Services.WebServiceExporter.GenerateProxy() +333
Spring.Objects.Factory.Support.AbstractAutowireCapableObjectFactory.InvokeInitMethods(Object target, String name, IConfigurableObjectDefinition definition) +269
Spring.Objects.Factory.Support.AbstractAutowireCapableObjectFactory.ConfigureObject(String name, RootObjectDefinition definition, IObjectWrapper wrapper) +660
Spring.Objects.Factory.Support.WebObjectFactory.ConfigureObject(String name, RootObjectDefinition definition, IObjectWrapper wrapper) +135
Spring.Objects.Factory.Support.AbstractAutowireCapableObjectFactory.InstantiateObject(String name, RootObjectDefinition definition, Object[] arguments, Boolean allowEagerCaching, Boolean suppressConfigure) +933
[ObjectCreationException: Error creating object with name 'UserWebService' defined in 'file [C:\CODE\Kupla\Kupla\Web.xml] line 13' : Initialization of object failed : Proxy already registered for "UserWebService" as Type "UserWebService".]
Spring.Objects.Factory.Support.AbstractAutowireCapableObjectFactory.InstantiateObject(String name, RootObjectDefinition definition, Object[] arguments, Boolean allowEagerCaching, Boolean suppressConfigure) +1419
Spring.Objects.Factory.Support.AbstractObjectFactory.CreateAndCacheSingletonInstance(String objectName, RootObjectDefinition objectDefinition, Object[] arguments) +389
Spring.Objects.Factory.Support.AbstractObjectFactory.GetObjectInternal(String name, Type requiredType, Object[] arguments, Boolean suppressConfigure) +2103
Spring.Objects.Factory.Support.DefaultListableObjectFactory.PreInstantiateSingletons() +875
Spring.Context.Support.AbstractApplicationContext.Refresh() +1225
Spring.Context.Support.WebApplicationContext..ctor(WebApplicationContextArgs args) +179
_dynamic_Spring.Context.Support.WebApplicationContext..ctor(Object[] ) +252
Spring.Context.Support.RootContextInstantiator.InvokeContextConstructor(ConstructorInfo ctor) +168
Spring.Context.Support.ContextHandler.InstantiateContext(IApplicationContext parentContext, Object configContext, String contextName, Type contextType, Boolean caseSensitive, String[] resources) +192
Spring.Context.Support.WebContextHandler.InstantiateContext(IApplicationContext parent, Object configContext, String contextName, Type contextType, Boolean caseSensitive, String[] resources) +413
Spring.Context.Support.ContextHandler.Create(Object parent, Object configContext, XmlNode section) +520
[ConfigurationErrorsException: Error creating context 'spring.root': Duplicate type name within an assembly.]
System.Configuration.BaseConfigurationRecord.EvaluateOne(String[] keys, SectionInput input, Boolean isTrusted, FactoryRecord factoryRecord, SectionRecord sectionRecord, Object parentResult) +347
System.Configuration.BaseConfigurationRecord.Evaluate(FactoryRecord factoryRecord, SectionRecord sectionRecord, Object parentResult, Boolean getLkg, Boolean getRuntimeObject, Object& result, Object& resultRuntimeObject) +2277
System.Configuration.BaseConfigurationRecord.GetSectionRecursive(String configKey, Boolean getLkg, Boolean checkPermission, Boolean getRuntimeObject, Boolean requestIsHere, Object& result, Object& resultRuntimeObject) +1849
System.Configuration.BaseConfigurationRecord.GetSection(String configKey) +69
Spring.Util.ConfigurationUtils.GetSection(String sectionName) +270
Spring.Context.Support.WebApplicationContext.GetContextInternal(String virtualPath) +1663
Spring.Context.Support.WebSupportModule.Init(HttpApplication app) +665
System.Web.HttpApplication.InitModulesCommon() +192
System.Web.HttpApplication.InitInternal(HttpContext context, HttpApplicationState state, MethodInfo[] handlers) +1678
System.Web.HttpApplicationFactory.GetNormalApplicationInstance(HttpContext context) +390
System.Web.HttpApplicationFactory.GetApplicationInstance(HttpContext context) +194
System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) +293
Has anyone else experienced this with Spring before, I am really struggling to see what is wrong. My web.xml contains:
<?xml version="1.0" encoding="utf-8" ?>
<objects xmlns="http://www.springframework.net">
<object type="default.aspx">
<property name="SessionObjectHolder" ref="SessionObjectHolder"/>
</object>
<object type="home.aspx">
<property name="UserBLL" ref="UserBLL"/>
<property name="SessionObjectHolder" ref="SessionObjectHolder"/>
</object>
<object id="UserWebService" type="Spring.Web.Services.WebServiceExporter, Spring.Web">
<property name="TargetName" value="UserWebServiceDTO"/>
<property name="Namespace" value="http://test.co.uk"/>
<property name="Description" value="This is User Web Service"/>
<property name="TypeAttributes">
<list>
<object type="System.Web.Script.Services.ScriptServiceAttribute, System.Web.Extensions"/>
</list>
</property>
</object>
<object id="UserWebServiceDTO" type="Kupla.ServiceLayer.UserWebService, Kupla.ServiceLayer">
<property name="UserBLL" ref="UserBLL" />
</object>
<object id="SessionObjectHolderWebService" type="Spring.Web.Services.WebServiceExporter, Spring.Web">
<property name="TargetName" value="SessionObjectHolderWebServiceDTO"/>
<property name="Namespace" value="http://test.co.uk"/>
<property name="Description" value="This is the session object holder web service"/>
<property name="TypeAttributes">
<list>
<object type="System.Web.Script.Services.ScriptServiceAttribute, System.Web.Extensions"/>
</list>
</property>
</object>
<object id="SessionObjectHolderWebServiceDTO" type="Kupla.ServiceLayer.SessionObjectHolderWebService, Kupla.ServiceLayer">
<property name="UserBLL" ref="UserBLL" />
</object>
</objects>
Many many thanks in advance.

Do your asmx or svc files exist? They should be removed when creating services by Spring, because one instance is created by Spring and second by IIS/.NET.
Edit
I haven't found this earlier, but WebServiceExporter registers type of object's name - UserWebService and SessionObjectHolderWebService in your case. But these types already exists (created by yourself), you call those objects with DTO suffix. Try to add suffix Exporter to objects created by WebServiceExporter.
The reason why you get different error while swapping services in config file is because Spring only returns the very first error. It can be quite painful in large projects.

Related

AWS SSO with Sustainsys/Saml2

While configuring AWS SSO SAML 2.0 application by default it does not include and NameIdFormat and if we go with this default metadata for our Service Provider, Sustainsys/Saml2 giving error like below.
Which configuration we can use to make it working without any defined NameIdFormat ?
MetaData provided by Identity Provider
Please note <md:NameIDFormat /> in metadata
<?xml version="1.0" encoding="UTF-8"?>
<md:EntityDescriptor xmlns:md="urn:oasis:names:tc:SAML:2.0:metadata" entityID="https://portal.sso.us-east-2.amazonaws.com/saml/assertion/REMOVED_FOR_BREVITY">
<md:IDPSSODescriptor WantAuthnRequestsSigned="false" protocolSupportEnumeration="urn:oasis:names:tc:SAML:2.0:protocol">
<md:KeyDescriptor use="signing">
<ds:KeyInfo xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
<ds:X509Data>
<ds:X509Certificate>REMOVED_FOR_BREVITY</ds:X509Certificate>
</ds:X509Data>
</ds:KeyInfo>
</md:KeyDescriptor>
<md:SingleLogoutService Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST" Location="https://portal.sso.us-east-2.amazonaws.com/saml/logout/REMOVED_FOR_BREVITY" />
<md:SingleLogoutService Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect" Location="https://portal.sso.us-east-2.amazonaws.com/saml/logout/REMOVED_FOR_BREVITY" />
<md:NameIDFormat />
<md:SingleSignOnService Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST" Location="https://portal.sso.us-east-2.amazonaws.com/saml/assertion/REMOVED_FOR_BREVITY" />
<md:SingleSignOnService Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect" Location="https://portal.sso.us-east-2.amazonaws.com/saml/assertion/REMOVED_FOR_BREVITY" />
</md:IDPSSODescriptor>
</md:EntityDescriptor>
Error return by Sustainsys/Saml2
Sustainsys.Saml2.Metadata.MetadataSerializationException: NameIDFormat element with no uri
at Sustainsys.Saml2.Metadata.MetadataSerializer.ReadNameIDFormat(XmlReader reader)
at Sustainsys.Saml2.Metadata.MetadataSerializer.ReadSsoDescriptorElement(XmlReader reader, SsoDescriptor descriptor)
at Sustainsys.Saml2.Metadata.MetadataSerializer.<>c__DisplayClass119_0.<ReadIdpSsoDescriptor>b__0()
at Sustainsys.Saml2.Metadata.MetadataSerializer.ReadChildren(XmlReader reader, Func`1 childAction)
at Sustainsys.Saml2.Metadata.MetadataSerializer.ReadIdpSsoDescriptor(XmlReader reader)
at Sustainsys.Saml2.Metadata.MetadataSerializer.<>c__DisplayClass118_0.<ReadEntityDescriptor>b__0()
at Sustainsys.Saml2.Metadata.MetadataSerializer.ReadChildren(XmlReader reader, Func`1 childAction)
at Sustainsys.Saml2.Metadata.MetadataSerializer.ReadEntityDescriptor(XmlReader reader, SecurityTokenResolver tokenResolver)
at Sustainsys.Saml2.Metadata.MetadataLoader.Load(XmlDictionaryReader reader)
at Sustainsys.Saml2.Metadata.MetadataLoader.Load(String metadataLocation, IEnumerable`1 signingKeys, Boolean validateCertificate, String minIncomingSigningAlgorithm)
at Sustainsys.Saml2.Metadata.MetadataLoader.LoadIdp(String metadataLocation, Boolean unpackEntitiesDescriptor)
at Sustainsys.Saml2.IdentityProvider.DoLoadMetadata()
at Sustainsys.Saml2.IdentityProvider.set_LoadMetadata(Boolean value)......

System.Web.HttpValueCollection.ThrowIfMaxHttpCollectionKeysExceeded() +2725318

i am getting an error while page reload on a dropdownlist option chang
[InvalidOperationException: Operation is not valid due to the current state of the object.]
System.Web.HttpValueCollection.ThrowIfMaxHttpCollectionKeysExceeded() +2725318
System.Web.HttpValueCollection.FillFromEncodedBytes(Byte[] bytes, Encoding encoding) +61
System.Web.HttpRequest.FillInFormCollection() +148
[HttpException (0x80004005): The URL-encoded form data is not valid.]
System.Web.HttpRequest.FillInFormCollection() +206
System.Web.HttpRequest.get_Form() +68
System.Web.HttpRequest.get_HasForm() +8807191
System.Web.UI.Page.GetCollectionBasedOnMethod(Boolean dontReturnNull) +97
System.Web.UI.Page.DeterminePostBackMode() +63
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +133
I had found some articles saying if you increase the value of MaxHttpCollectionKeys in the app setting it will work but it doesn't seem to work for me
I have tried various different values extending to the below value but none work of
<add key="aspnet:MaxHttpCollectionKeys" value="900000000000000000000000000000" />
you help is most appreciated

Having a hard time tracking down a process that is crashing my app pool

So I have an app that keeps crashing out and it's not leaving any application logs. When I finally went and looked in the event viewer for that server (a server 2003 box), I found this error (The even source was ASP.NET 4.0.30319.0)
An unhandled exception occurred and the process was terminated.
Application ID: /LM/W3SVC/2053196604/Root
Process ID: 24428
Exception: System.IO.FileLoadException
Message: Could not load file or assembly
'Microsoft.Practices.EnterpriseLibrary.Validation, Version=5.0.505.0,
Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its
dependencies. The located assembly's manifest definition does not
match the assembly reference. (Exception from HRESULT: 0x80131040)
StackTrace: Server stack trace: at
System.RuntimeTypeHandle.GetTypeByName(String name, Boolean
throwOnError, Boolean ignoreCase, Boolean reflectionOnly,
StackCrawlMarkHandle stackMark, Boolean loadTypeFromPartialName,
ObjectHandleOnStack type) at
System.RuntimeTypeHandle.GetTypeByName(String name, Boolean
throwOnError, Boolean ignoreCase, Boolean reflectionOnly,
StackCrawlMark& stackMark, Boolean loadTypeFromPartialName) at
System.RuntimeType.GetType(String typeName, Boolean throwOnError,
Boolean ignoreCase, Boolean reflectionOnly, StackCrawlMark& stackMark)
at System.Type.GetType(String typeName) at
Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ContainerModel.Unity.UnityContainerConfigurator.AddValidationExtension()
at
Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ContainerModel.Unity.UnityContainerConfigurator..ctor(IUnityContainer
container) at
Microsoft.Practices.EnterpriseLibrary.Common.Configuration.EnterpriseLibraryContainer.CreateDefaultContainer(IConfigurationSource
configurationSource) at
Microsoft.Practices.EnterpriseLibrary.Common.Configuration.EnterpriseLibraryContainer.SetCurrentContainerIfNotSet()
at Microsoft.Practices.EnterpriseLibrary.Logging.Logger.get_Writer()
at Apriva.WebApi.Shared.Logging.DefaultLogWriter.Log(Object message,
TraceEventType severity, LogEntry& entry, String category, HttpContext
context) at
Apriva.WebApi.Shared.Logging.DefaultLogWriter.Info(Object message,
String category, HttpContext context) at
System.Runtime.Remoting.Messaging.StackBuilderSink._PrivateProcessMessage(IntPtr
md, Object[] args, Object server, Int32 methodPtr, Boolean
fExecuteInContext, Object[]& outArgs) at
System.Runtime.Remoting.Messaging.StackBuilderSink.AsyncProcessMessage(IMessage
msg, IMessageSink replySink)
Exception rethrown at [0]: at
System.Runtime.Remoting.Proxies.RealProxy.EndInvokeHelper(Message
reqMsg, Boolean bProxyCase) at
System.Runtime.Remoting.Proxies.RemotingProxy.Invoke(Object NotUsed,
MessageData& msgData) at
Apriva.WebApi.Shared.Logging.Logger.LogDelegate.EndInvoke(IAsyncResult
result) at
Apriva.WebApi.Shared.Logging.Logger.LogAsyncComplete(IAsyncResult ar)
at
System.Runtime.Remoting.Messaging.AsyncResult.SyncProcessMessage(IMessage
msg) at
System.Runtime.Remoting.Messaging.StackBuilderSink.AsyncProcessMessage(IMessage
msg, IMessageSink replySink) at
System.Runtime.Remoting.Proxies.AgileAsyncWorkerItem.DoAsyncCall()
at
System.Runtime.Remoting.Proxies.AgileAsyncWorkerItem.ThreadPoolCallBack(Object
o) at
System.Threading.QueueUserWorkItemCallback.WaitCallback_Context(Object
state) at System.Threading.ExecutionContext.Run(ExecutionContext
executionContext, ContextCallback callback, Object state, Boolean
ignoreSyncCtx) at
System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem()
at System.Threading.ThreadPoolWorkQueue.Dispatch() at
System.Threading._ThreadPoolWaitCallback.PerformWaitCallback()
For more information, see Help and Support Center at
When I check the processes in the task manager, this PID isn't present. I figure it's because it is a w3wp process. So I go to command prompt and run iisapp.vbs and it returns a single process with a different PID.
The error seems to imply that there is a config reference to a different version of the enterprise library for validation when the version that was found was v5.0.505.0 and while my projects have plenty of references to the enterprise library, none refer to the validation package.
So my question is -- does anyone have any insight into where I should look next? I was trying to use the PID to at least see which application was causing the error, but that doesn't seem to be getting me anywhere.
Analysis:
From stack trace its clear that reference chain is:
Apriva.WebApi.Shared.Logging.DefaultLogWriter => Microsoft.Practices.EnterpriseLibrary.Logging.Logger => Microsoft.Practices.EnterpriseLibrary.Common.Configuration.EnterpriseLibraryContainer => Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ContainerModel.Unity.UnityContainerConfigurator.
Method "AddValidationExtension" of type Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ContainerModel.Unity.UnityContainerConfigurator needs type from 'Microsoft.Practices.EnterpriseLibrary.Validation assembly with signature
Possible steps find out root cause:
Open solution in visual studio.
Go to Edit Menu-> Find and Replace->Find in Files
Search for Microsoft.Practices.EnterpriseLibrary.Validation with Find options->Look at these file types -> *.csproj You will get list of project referencing this assembly.
Open all those project files in notepad and find out which one has different assembly signature than Version=5.0.505.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'
Most probably you should get culprit with above steps.
I will also recommend to check assembly cache and check signature of Microsoft.Practices.EnterpriseLibrary.Validation assembly and if it matches Version=5.0.505.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'

"Unable to validate data" Exception in my Event Log

I had moved my asp.net2 web-forms website to IIS8 base on windows server 2012 and i found in my event log many of the next warning :
- <Event xmlns="http://schemas.microsoft.com/win/2004/08/events/event">
- <System>
<Provider Name="ASP.NET 2.0.50727.0" />
<EventID Qualifiers="32768">1309</EventID>
<Level>3</Level>
<Task>3</Task>
<Keywords>0x80000000000000</Keywords>
<TimeCreated SystemTime="2014-01-02T20:44:47.000000000Z" />
<EventRecordID>2716</EventRecordID>
<Channel>Application</Channel>
<Computer>WIN-6GSFHL7R9M0</Computer>
<Security />
</System>
- <EventData>
<Data>3005</Data>
<Data>An unhandled exception has occurred.</Data>
<Data>02/01/2014 22:44:47</Data>
<Data>02/01/2014 20:44:47</Data>
<Data>8ba10465853a48c2a3a0ffc833750679</Data>
<Data>7</Data>
<Data>1</Data>
<Data>0</Data>
<Data>/LM/W3SVC/12/ROOT-2-130331688695275608</Data>
<Data>Full</Data>
<Data>/</Data>
<Data>C:\Inetpub\vhosts\domain.com\httpdocs\</Data>
<Data>WIN-6GSFHL7R9M0</Data>
<Data />
<Data>5216</Data>
<Data>w3wp.exe</Data>
<Data>WIN-6GSFHL7R9M0\IWPD_6(domain)</Data>
<Data>HttpException</Data>
<Data>Unable to validate data.</Data>
<Data>http://www.domain.com/ScriptResource.axd?d=neQR-vF3_EGwaDvBqhWT03ESuzxtn9v9XFCS44TLY3AvlJgJaiF16o8T3xF9JpxAa4aVdi8FBtTu_aoQwDJm1er-TLBDOoBFHQOWr7lHPFlEhPXZ5Y_wPNlfd8wmC4SLUpFTqQ2&t=635240882914102167</Data>
<Data>/ScriptResource.axd</Data>
<Data>157.55.35.41</Data>
<Data />
<Data>False</Data>
<Data />
<Data>WIN-6GSFHL7R9M0\IWPD_6(domain)</Data>
<Data>5</Data>
<Data>WIN-6GSFHL7R9M0\IWPD_6(domain)</Data>
<Data>False</Data>
<Data>at System.Web.Configuration.MachineKeySection.EncryptOrDecryptData(Boolean fEncrypt, Byte[] buf, Byte[] modifier, Int32 start, Int32 length, IVType ivType, Boolean useValidationSymAlgo, Boolean signData) at System.Web.Configuration.MachineKeySection.EncryptOrDecryptData(Boolean fEncrypt, Byte[] buf, Byte[] modifier, Int32 start, Int32 length, IVType ivType, Boolean useValidationSymAlgo) at System.Web.UI.Page.DecryptStringWithIV(String s, IVType ivType) at System.Web.UI.Page.DecryptString(String s)</Data>
</EventData>
</Event>
I have tried the following things :
Use of specifying machine key
Add renderAllHiddenFieldsAtTopOfForm="true"
I saw many posts suggesting EnableViewStateMAC=false, but it's sound stupid and dangers
Is this exception dangers? what i'm missing ?
I wouldn't worry about it.
The most likely explanation is that a search crawler / indexer has cached the old URLs and is checking them again to make sure they're still valid. Since ScriptResource.axd returns 404 for these now-incorrect URLs, the search crawler will eventually flush them from its cache, and over time you'll see these errors disappear.

NHibernate Configuration Error - Connection String?

I am getting this error:
------ Test started: Assembly: ECEHire.Test.dll ------
Test 'ECEHire.Test.Tests.GenerateSchema_Fixture.Can_generate_schema' failed: NHibernate.HibernateException : Format of the initialization string does not conform to specification starting at index 49.
----> System.ArgumentException : Format of the initialization string does not conform to specification starting at index 49.
at NHibernate.Tool.hbm2ddl.SchemaExport.Execute(Action1 scriptAction, Boolean export, Boolean justDrop)
at NHibernate.Tool.hbm2ddl.SchemaExport.Execute(Boolean script, Boolean export, Boolean justDrop)
GenerateSchema_Fixture.vb(18,0): at ECEHire.Test.Tests.GenerateSchema_Fixture.Can_generate_schema()
--ArgumentException
at System.Data.Common.DbConnectionOptions.GetKeyValuePair(String connectionString, Int32 currentPosition, StringBuilder buffer, Boolean useOdbcRules, String& keyname, String& keyvalue)
at System.Data.Common.DbConnectionOptions.ParseInternal(Hashtable parsetable, String connectionString, Boolean buildChain, Hashtable synonyms, Boolean firstKey)
at System.Data.Common.DbConnectionOptions..ctor(String connectionString, Hashtable synonyms, Boolean useOdbcRules)
at System.Data.SqlClient.SqlConnectionString..ctor(String connectionString)
at System.Data.SqlClient.SqlConnectionFactory.CreateConnectionOptions(String connectionString, DbConnectionOptions previous)
at System.Data.ProviderBase.DbConnectionFactory.GetConnectionPoolGroup(String connectionString, DbConnectionPoolGroupOptions poolOptions, DbConnectionOptions& userConnectionOptions)
at System.Data.SqlClient.SqlConnection.ConnectionString_Set(String value)
at System.Data.SqlClient.SqlConnection.set_ConnectionString(String value)
at NHibernate.Connection.DriverConnectionProvider.GetConnection()
at NHibernate.Tool.hbm2ddl.SchemaExport.Execute(Action1 scriptAction, Boolean export, Boolean justDrop)
0 passed, 1 failed, 0 skipped, took 3.23 seconds (NUnit 2.5.10).
When I try to test my NHibernate configuration file.
The configuration file is:
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
<session-factory>
<property name="dialect">NHibernate.Dialect.MsSql2005Dialect</property>
<property name="connection.connection_string">Data Source=MyServerName;initial catalog=MyDatabaseName;Integrated Security=SSPI</property>
<property name="connection.isolation">ReadCommitted</property>
<property name="proxyfactory.factory_class">NHibernate.ByteCode.LinFu.ProxyFactoryFactory, NHibernate.ByteCode.LinFu</property>
</session-factory>
</hibernate-configuration>
The test that I am running is:
<Test()> _
Public Sub Can_generate_schema()
Dim cfg = New Configuration()
cfg.Configure()
cfg.AddAssembly(GetType(Question).Assembly)
Dim exp As NHibernate.Tool.hbm2ddl.SchemaExport = New NHibernate.Tool.hbm2ddl.SchemaExport(cfg)
exp.Execute(False, True, False)
End Sub
I believe that this is a connection string error, but the connection string works as part of the web.config file for querying the database via ADO.
A few things to try:-
Could it be something as simple as adding a ; (semi colon) e.g. Integrated Security=SSPI;
Or try changing to Integrated Security=True;
Or drop connection.connection_string and use connection.connection_string_name
In web.config
<connectionStrings>
<add name="db" connectionString="Data Source=MyServerName;initial catalog=MyDatabaseName;Integrated Security=SSPI;"/>
</connectionStrings>
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
<session-factory>
...
<property name="connection.connection_string_name">db</property>
...
</session-factory>
</hibernate-configuration>
Edit The next thing to try is to make sure that the configuration file is being used in your test so try this:-
cfg.Configure(#"c:\hibernate.cfg.xml");
Making sure that the path IS totally correct, If this fails then put a break point at this line:-
cfg.AddAssembly(GetType(Question).Assembly)
and then add this watch cfg.Properties and make sure that the connection string is present as a key value pair
Edit2
For unit testing you would need to copy local true and get path from executing assembly OR create an app.config and use:-
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="hibernate-configuration"
type="NHibernate.Cfg.ConfigurationSectionHandler, NHibernate" />
</configSections>
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
<session-factory>
<property ../>
</session-factory>
</hibernate-configuration>
</configuration>
For a web site you could do:-
cfg.Configure(HttpContext.Current.Server.MapPath("~/hibernate.cfg.xml"));
To be honest there are lots of options and this is really another question!

Resources