I have a problem with NServiceBus where I first get the error that NHibernate cannot map from an NHibernate specific Bag, and when I make this an IList, I get a message that NHibernate cannot find a concrete implementation for this IList. I am stumped.
This is the first error I got:
System.InvalidCastException: Unable to cast object of type
'NHibernate.Collection.Generic.PersistentGenericBag`1[CustomerDirect.Interfaces.Document.DocumentSubTemplate]'
to type
'System.Collections.Generic.List`1[CustomerDirect.Interfaces.Document.DocumentSubTemplate]'.
at (Object , Object[] , SetterCallback ) at
NHibernate.Event.Default.WrapVisitor.ProcessComponent(Object
component, IAbstractComponentType componentType) at
NHibernate.Event.Default.WrapVisitor.ProcessComponent(Object
component, IAbstractComponentType componentType) at
NHibernate.Event.Default.WrapVisitor.ProcessValue(Int32 i, Object[]
values, IType[] types) at
NHibernate.Event.Default.AbstractVisitor.ProcessEntityPropertyValues(Object[]
values, IType[] types) at
NHibernate.Event.Default.AbstractSaveEventListener.VisitCollectionsBeforeSave(Object
entity, Object id, Object[] values, IType[] types, IEventSource
source) at
NHibernate.Event.Default.AbstractSaveEventListener.PerformSaveOrReplicate(Object
entity, EntityKey key, IEntityPersister persister, Boolean
useIdentityColumn, Object anything, IEventSource source, Boolean
requiresImmediateIdAccess) at
NHibernate.Event.Default.AbstractSaveEventListener.SaveWithGeneratedId(Object
entity, String entityName, Object anything, IEventSource source,
Boolean requiresImmediateIdAccess) at
NHibernate.Event.Default.DefaultSaveOrUpdateEventListener.SaveWithGeneratedOrRequestedId(SaveOrUpdateEvent
event) at
NHibernate.Event.Default.DefaultSaveOrUpdateEventListener.EntityIsTransient(SaveOrUpdateEvent
event) at
NHibernate.Event.Default.DefaultSaveOrUpdateEventListener.OnSaveOrUpdate(SaveOrUpdateEvent
event) at NHibernate.Impl.SessionImpl.FireSave(SaveOrUpdateEvent
event) at NHibernate.Impl.SessionImpl.Save(Object obj) at
NServiceBus.Persistence.NHibernate.SharedConnectionStorageSessionProvider.ExecuteInTransaction(Action`1
operation) in
c:\BuildAgent\work\5135de308b2f3016\src\NServiceBus.NHibernate\SharedSession\SharedConnectionStorageSessionProvider.cs:line
60 at NServiceBus.SagaPersistenceBehavior.Invoke(IncomingContext
context, Action next) in
c:\BuildAgent\work\1b05a2fea6e4cd32\src\NServiceBus.Core\Sagas\SagaPersistenceBehavior.cs:line
116 at
ServiceControl.Plugin.SagaAudit.CaptureSagaStateBehavior.Invoke(IncomingContext
context, Action next) in
c:\BuildAgent\work\5d8e2b68f32aa08f\src\ServiceControl.Plugin.SagaAudit\CaptureSagaStateBehavior.cs:line
41 at
NServiceBus.Persistence.NHibernate.OpenNativeTransactionBehavior.Invoke(IncomingContext
context, Action next) in
c:\BuildAgent\work\5135de308b2f3016\src\NServiceBus.NHibernate\SharedSession\OpenNativeTransactionBehavior.cs:line
20 at
NServiceBus.Persistence.NHibernate.OpenSessionBehavior.InnerInvoke(BehaviorContext
context, Action next, Func`1 connectionRetriever) in
c:\BuildAgent\work\5135de308b2f3016\src\NServiceBus.NHibernate\SharedSession\OpenSessionBehavior.cs:line
73 at
NServiceBus.Persistence.NHibernate.OpenSessionBehavior.Invoke(IncomingContext
context, Action next) in
c:\BuildAgent\work\5135de308b2f3016\src\NServiceBus.NHibernate\SharedSession\OpenSessionBehavior.cs:line
35 at NServiceBus.DataBusReceiveBehavior.Invoke(IncomingContext
context, Action next) in
c:\BuildAgent\work\1b05a2fea6e4cd32\src\NServiceBus.Core\DataBus\DataBusReceiveBehavior.cs:line
60 at
NServiceBus.SetCurrentMessageBeingHandledBehavior.Invoke(IncomingContext
context, Action next) in
c:\BuildAgent\work\1b05a2fea6e4cd32\src\NServiceBus.Core\Unicast\Behaviors\SetCurrentMessageBeingHandledBehavior.cs:line
17 at NServiceBus.LoadHandlersBehavior.Invoke(IncomingContext
context, Action next) in
c:\BuildAgent\work\1b05a2fea6e4cd32\src\NServiceBus.Core\Unicast\Behaviors\LoadHandlersBehavior.cs:line
46 at
NServiceBus.ApplyIncomingMessageMutatorsBehavior.Invoke(IncomingContext
context, Action next) in
c:\BuildAgent\work\1b05a2fea6e4cd32\src\NServiceBus.Core\MessageMutator\ApplyIncomingMessageMutatorsBehavior.cs:line
23 at
NServiceBus.ExecuteLogicalMessagesBehavior.Invoke(IncomingContext
context, Action next) in
c:\BuildAgent\work\1b05a2fea6e4cd32\src\NServiceBus.Core\Unicast\Messages\ExecuteLogicalMessagesBehavior.cs:line
24 at NServiceBus.CallbackInvocationBehavior.Invoke(IncomingContext
context, Action next) in
c:\BuildAgent\work\1b05a2fea6e4cd32\src\NServiceBus.Core\Unicast\Behaviors\CallbackInvocationBehavior.cs:line
22 at
NServiceBus.DeserializeLogicalMessagesBehavior.Invoke(IncomingContext
context, Action next) in
c:\BuildAgent\work\1b05a2fea6e4cd32\src\NServiceBus.Core\Unicast\Messages\DeserializeLogicalMessagesBehavior.cs:line
47 at
NServiceBus.ApplyIncomingTransportMessageMutatorsBehavior.Invoke(IncomingContext
context, Action next) in
c:\BuildAgent\work\1b05a2fea6e4cd32\src\NServiceBus.Core\MessageMutator\ApplyIncomingTransportMessageMutatorsBehavior.cs:line
20 at
NServiceBus.SubscriptionReceiverBehavior.Invoke(IncomingContext
context, Action next) in
c:\BuildAgent\work\1b05a2fea6e4cd32\src\NServiceBus.Core\Unicast\Subscriptions\MessageDrivenSubscriptions\SubscriptionReceiverBehavior.cs:line
32 at NServiceBus.UnitOfWorkBehavior.Invoke(IncomingContext
context, Action next) in
c:\BuildAgent\work\1b05a2fea6e4cd32\src\NServiceBus.Core\UnitOfWork\UnitOfWorkBehavior.cs:line
42 at
NServiceBus.Persistence.NHibernate.OpenSqlConnectionBehavior.Invoke(IncomingContext
context, Action next) in
c:\BuildAgent\work\5135de308b2f3016\src\NServiceBus.NHibernate\SharedSession\OpenSqlConnectionBehavior.cs:line
38 at NServiceBus.ChildContainerBehavior.Invoke(IncomingContext
context, Action next) in
c:\BuildAgent\work\1b05a2fea6e4cd32\src\NServiceBus.Core\Unicast\Behaviors\ChildContainerBehavior.cs:line
17 at
NServiceBus.ProcessingStatisticsBehavior.Invoke(IncomingContext
context, Action next) in
c:\BuildAgent\work\1b05a2fea6e4cd32\src\NServiceBus.Core\Monitoring\ProcessingStatisticsBehavior.cs:line
23 at NServiceBus.AuditBehavior.Invoke(IncomingContext context,
Action next) in
c:\BuildAgent\work\1b05a2fea6e4cd32\src\NServiceBus.Core\Audit\AuditBehavior.cs:line
20 at
NServiceBus.Pipeline.PipelineExecutor.Execute[T](BehaviorChain`1
pipelineAction, T context) in
c:\BuildAgent\work\1b05a2fea6e4cd32\src\NServiceBus.Core\Pipeline\PipelineExecutor.cs:line
127 at
NServiceBus.Unicast.Transport.TransportReceiver.ProcessMessage(TransportMessage
message) in
c:\BuildAgent\work\1b05a2fea6e4cd32\src\NServiceBus.Core\Unicast\Transport\TransportReceiver.cs:line
344 at
NServiceBus.Unicast.Transport.TransportReceiver.TryProcess(TransportMessage
message) in
c:\BuildAgent\work\1b05a2fea6e4cd32\src\NServiceBus.Core\Unicast\Transport\TransportReceiver.cs:line
230 at NServiceBus.Transports.Msmq.MsmqDequeueStrategy.Action() in
c:\BuildAgent\work\1b05a2fea6e4cd32\src\NServiceBus.Core\Transports\Msmq\MsmqDequeueStrategy.cs:line
266
Then, when I made my property an IList, I got this:
Exception when starting endpoint.
NHibernate.MappingException: Could not determine type for:
System.Collections.Generic.IList`1[[CustomerDirect.Interfaces.Document.DocumentSubTemplate,
CustomerDirect.Interfaces, Version=1.0.0.0, Culture=neutral,
PublicKeyToken=null]], mscorlib, Version=4.0.0.0, Culture=neutral,
PublicKeyToken=b77a5c561934e089, for columns:
NHibernate.Mapping.Column(SubTemplates)
at NHibernate.Mapping.SimpleValue.get_Type()
at
NHibernate.Cfg.XmlHbmBinding.MappingLogExtensions.LogMapped(Property
property, IInternalLogger log)
at NHibernate.Cfg.XmlHbmBinding.PropertiesBinder.Bind(IEnumerable`1
properties, Table table, IDictionary`2 inheritedMetas, Action`1
modifier, Action`1 addToModelAction)
at
NHibernate.Cfg.XmlHbmBinding.CollectionBinder.BindCompositeElement(HbmCompositeElement
compositeElementMapping, Collection model, IDictionary`2
inheritedMetas)
at
NHibernate.Cfg.XmlHbmBinding.CollectionBinder.BindCollectionSecondPass(ICollectionPropertiesMapping
collectionMapping, Collection model, IDictionary`2 persistentClasses,
IDictionary`2 inheritedMetas)
at
NHibernate.Cfg.XmlHbmBinding.CollectionBinder.<>c__DisplayClass13.<AddCollectionSecondPass>b__12(IDictionary`2
persistentClasses)
at NHibernate.Cfg.Configuration.SecondPassCompile()
at NHibernate.Cfg.Configuration.BuildSessionFactory()
at
NServiceBus.Features.NHibernateStorageSession.Setup(FeatureConfigurationContext
context) in
c:\BuildAgent\work\5135de308b2f3016\src\NServiceBus.NHibernate\SharedSession\NHibernateStorageSession.cs:line
54
at
NServiceBus.Features.FeatureActivator.ActivateFeature(FeatureState
featureState, IEnumerable`1 featuresToActivate,
FeatureConfigurationContext context) in
c:\BuildAgent\work\1b05a2fea6e4cd32\src\NServiceBus.Core\Features\FeatureActivator.cs:line
235
at
NServiceBus.Features.FeatureActivator.SetupFeatures(FeatureConfigurationContext
context) in
c:\BuildAgent\work\1b05a2fea6e4cd32\src\NServiceBus.Core\Features\FeatureActivator.cs:line
116
at NServiceBus.Configure.Initialize() in
c:\BuildAgent\work\1b05a2fea6e4cd32\src\NServiceBus.Core\Configure.cs:line
115
at NServiceBus.GenericHost.PerformConfiguration(Action`1
moreConfiguration) in
c:\BuildAgent\work\a3de8759ee491634\src\NServiceBus.Hosting.Windows\GenericHost.cs:line
119
at NServiceBus.GenericHost.Start() in
c:\BuildAgent\work\a3de8759ee491634\src\NServiceBus.Hosting.Windows\GenericHost.cs:line
58
I made it work using NHibernate Loquacious mapping. Since we never query on our Saga data other than the ID of the saga itself, I went with having the complex properties as Json in nvarchar(max) fields. I used this gist to get it to work: https://gist.github.com/phillip-haydon/1936188
Related
This question already has answers here:
A potentially dangerous Request.Form value was detected from the client - ASP.NET MVC
(5 answers)
Closed 9 years ago.
Ajax POST data that contains '&#' characters causes MVC4 controller fails to decode. Following were my tests;
POST data contains 'MYNAMEIS&#XYZ' , result ERROR
POST data contains 'MYNAMEIS& #XYZ' (note the space), result SUCCESS
POST data contains 'MYNAMEIS#&XYZ' (note the order of special characters), result
SUCCESS
POST data contains 'Q&^%AA#####$%' (note bunch of special
characters), result SUCCESS
It doesn't work when # comes right after & in the POST request. I've verified that request encoding is set to UTF-8 in web.config, _layout.cshtml . But still no luck.
Please help how to resolve this issue.
Stack Trace from the exception;
<!--
[HttpRequestValidationException]: A potentially dangerous Request.Form value was detected from the client (Name="&#").
at System.Web.HttpRequest.ValidateString(String value, String collectionKey, RequestValidationSource requestCollection)
at System.Web.HttpRequest.<>c__DisplayClass5.<ValidateHttpValueCollection>b__3(String key, String value)
at System.Web.HttpValueCollection.EnsureKeyValidated(String key)
at System.Web.HttpValueCollection.GetValues(String name)
at System.Web.Mvc.NameValueCollectionValueProvider.ValueProviderResultPlaceholder.GetResultFromCollection(String key, NameValueCollection collection, CultureInfo culture)
at System.Web.Mvc.NameValueCollectionValueProvider.ValueProviderResultPlaceholder.<>c__DisplayClass8.<.ctor>b__4()
at System.Lazy`1.CreateValue()
at System.Lazy`1.LazyInitValue()
at System.Lazy`1.get_Value()
at System.Web.Mvc.NameValueCollectionValueProvider.GetValue(String key, Boolean skipValidation)
at System.Web.Mvc.ValueProviderCollection.GetValueFromProvider(IValueProvider provider, String key, Boolean skipValidation)
at System.Web.Mvc.ValueProviderCollection.<>c__DisplayClass9.<GetValue>b__4(IValueProvider provider)
at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext()
at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext()
at System.Linq.Enumerable.FirstOrDefault[TSource](IEnumerable`1 source)
at System.Web.Mvc.ValueProviderCollection.GetValue(String key, Boolean skipValidation)
at System.Web.Mvc.DefaultModelBinder.BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
at System.Web.Mvc.DefaultModelBinder.GetPropertyValue(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor, IModelBinder propertyBinder)
at System.Web.Mvc.DefaultModelBinder.BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor)
at System.Web.Mvc.DefaultModelBinder.BindProperties(ControllerContext controllerContext, ModelBindingContext bindingContext)
at System.Web.Mvc.DefaultModelBinder.BindComplexElementalModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Object model)
at System.Web.Mvc.DefaultModelBinder.BindComplexModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
at System.Web.Mvc.DefaultModelBinder.BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
at System.Web.Mvc.ControllerActionInvoker.GetParameterValue(ControllerContext controllerContext, ParameterDescriptor parameterDescriptor)
at System.Web.Mvc.ControllerActionInvoker.GetParameterValues(ControllerContext controllerContext, ActionDescriptor actionDescriptor)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass25.<BeginInvokeAction>b__1e(AsyncCallback asyncCallback, Object asyncState)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.BeginInvokeAction(ControllerContext controllerContext, String actionName, AsyncCallback callback, Object state)
at System.Web.Mvc.Controller.<>c__DisplayClass1d.<BeginExecuteCore>b__17(AsyncCallback asyncCallback, Object asyncState)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout)
at System.Web.Mvc.Controller.BeginExecuteCore(AsyncCallback callback, Object state)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout)
at System.Web.Mvc.Controller.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state)
at System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state)
at System.Web.Mvc.MvcHandler.<>c__DisplayClass8.<BeginProcessRequest>b__2(AsyncCallback asyncCallback, Object asyncState)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout)
at System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state)
at System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state)
at System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData)
at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
-->
Use the ValidateInput(false) attribute.
You can also encode the &# characters and then decode them on the server.
I am using Fluent NHibernate and am trying to store an image. Small images work, but larger images do not, and I receive this error when saving to the database (SQL Server):
Exception: Error dehydrating property value for CFC.Domain.Vehicle.Image
Inner Exception: The length of the byte[] value exceeds the length configured in the mapping/parameter.
Here is my mapping:
mapping.Table("Vehicle");
mapping.Id(x => x.Id, "VehicleID");
mapping.Map(x => x.Year).Not.Nullable();
mapping.Map(x => x.Image).CustomSqlType("VARBINARY(MAX)").Length(int.MaxValue);
The "Image" property is a byte[].
Note the CustomSqlType and the length, which creates the proper nvarchar(max) column in the database. I've read countless of other posts talking about similar issues, but none cover this specific error. It isn't that the data is being truncated and then saved, it just errors out before ever sending the SQL query.
The image I am testing with is just the standard Windows 7 sample images (Penguins.jpg of course) but an image around 1kb works fine.
I appreciate the help! Here is the beginning of the stack trace if it helps.
[HibernateException: The length of the byte[] value exceeds the length
configured in the mapping/parameter.]
NHibernate.Type.AbstractBinaryType.Set(IDbCommand cmd, Object value,
Int32 index) +207
NHibernate.Type.NullableType.NullSafeSet(IDbCommand cmd, Object value,
Int32 index) +397
NHibernate.Type.NullableType.NullSafeSet(IDbCommand st, Object value,
Int32 index, Boolean[] settable, ISessionImplementor session) +62
NHibernate.Persister.Entity.AbstractEntityPersister.Dehydrate(Object
id, Object[] fields, Object rowId, Boolean[] includeProperty,
Boolean[][] includeColumns, Int32 table, IDbCommand statement,
ISessionImplementor session, Int32 index) +350
[PropertyValueException: Error dehydrating property value for
CFC.Domain.Vehicle.Image]
NHibernate.Persister.Entity.AbstractEntityPersister.Dehydrate(Object
id, Object[] fields, Object rowId, Boolean[] includeProperty,
Boolean[][] includeColumns, Int32 table, IDbCommand statement,
ISessionImplementor session, Int32 index) +510
NHibernate.Persister.Entity.AbstractEntityPersister.Dehydrate(Object
id, Object[] fields, Boolean[] includeProperty, Boolean[][]
includeColumns, Int32 j, IDbCommand st, ISessionImplementor session)
+59 NHibernate.Persister.Entity.GeneratedIdentifierBinder.BindValues(IDbCommand
ps) +79
NHibernate.Id.Insert.AbstractReturningDelegate.PerformInsert(SqlCommandInfo
insertSQL, ISessionImplementor session, IBinder binder) +102
NHibernate.Persister.Entity.AbstractEntityPersister.Insert(Object[]
fields, Boolean[] notNull, SqlCommandInfo sql, Object obj,
ISessionImplementor session) +265
NHibernate.Persister.Entity.AbstractEntityPersister.Insert(Object[]
fields, Object obj, ISessionImplementor session) +358
NHibernate.Action.EntityIdentityInsertAction.Execute() +262
NHibernate.Engine.ActionQueue.Execute(IExecutable executable) +56
NHibernate.Event.Default.AbstractSaveEventListener.PerformSaveOrReplicate(Object
entity, EntityKey key, IEntityPersister persister, Boolean
useIdentityColumn, Object anything, IEventSource source, Boolean
requiresImmediateIdAccess) +811
NHibernate.Event.Default.AbstractSaveEventListener.PerformSave(Object
entity, Object id, IEntityPersister persister, Boolean
useIdentityColumn, Object anything, IEventSource source, Boolean
requiresImmediateIdAccess) +543
NHibernate.Event.Default.AbstractSaveEventListener.SaveWithGeneratedId(Object
entity, String entityName, Object anything, IEventSource source,
Boolean requiresImmediateIdAccess) +257
I know it's a little late to be posting a reply but I just came across this exact same error. Below was my resolution - hopefully it helps someone else in the future.
I changed:
Map(x => x.ByteArrayProperty);
to:
Map(x => x.ByteArrayProperty).Length(int.MaxValue);
Sigh, sometimes after 2 days of research you just have to post a question to StackOverflow to find the answer right after.
I'm not sure of the underlying reason, but specifying the property directly when mapping was the problem. To resolve the issue I ended up creating a new "BinaryLengthConvention" below.
public class BinaryColumnLengthConvention : IPropertyConvention, IPropertyConventionAcceptance
{
public void Accept(IAcceptanceCriteria<IPropertyInspector> criteria)
{
criteria.Expect(x => x.Property.PropertyType == typeof(byte[]));
}
public void Apply(IPropertyInstance instance)
{
instance.Length(2147483647);
instance.CustomSqlType("varbinary(MAX)");
}
}
Magically it all started working. Hopefully someone else that searches for that error message finds this useful.
I got the same error while storing the big images. I resolved by adding length attribute to image field as <property name="image" length="2147483647"/>
I have created an override that looks like this:
public class ProjectMappingOverride : IAutoMappingOverride<Project> {
public void Override(AutoMapping<Project> mapping) {
mapping.Component(p => p.OwnerNotifyReasons).ColumnPrefix("NotifyOwner");
mapping.Component(p => p.ContactNotifyReasons).ColumnPrefix("NotifyContacts");
}
}
However, this throws an exception:
System.InvalidOperationException: Tried to add component 'OwnerNotifyReasons' when already added.
d:\Development\FluentNHibernate\src\FluentNHibernate\MappingModel\MappedMembers.cs(134,0): at FluentNHibernate.MappingModel.MappedMembers.AddComponent(IComponentMapping componentMapping)
d:\Development\FluentNHibernate\src\FluentNHibernate\MappingModel\ClassBased\ClassMappingBase.cs(115,0): at FluentNHibernate.MappingModel.ClassBased.ClassMappingBase.AddComponent(IComponentMapping componentMapping)
d:\Development\FluentNHibernate\src\FluentNHibernate\Automapping\Steps\ComponentStep.cs(39,0): at FluentNHibernate.Automapping.Steps.ComponentStep.Map(ClassMappingBase classMap, Member member)
d:\Development\FluentNHibernate\src\FluentNHibernate\Automapping\AutoMapper.cs(161,0): at FluentNHibernate.Automapping.AutoMapper.TryMapProperty(ClassMappingBase mapping, Member member, IList`1 mappedMembers)
d:\Development\FluentNHibernate\src\FluentNHibernate\Automapping\AutoMapper.cs(149,0): at FluentNHibernate.Automapping.AutoMapper.<>c__DisplayClass13.<ProcessClass>b__12(Member x)
d:\Development\FluentNHibernate\src\FluentNHibernate\Utils\CollectionExtensions.cs(15,0): at FluentNHibernate.Utils.CollectionExtensions.Each[T](IEnumerable`1 enumerable, Action`1 each)
d:\Development\FluentNHibernate\src\FluentNHibernate\Automapping\AutoMapper.cs(147,0): at FluentNHibernate.Automapping.AutoMapper.ProcessClass(ClassMappingBase mapping, Type entityType, IList`1 mappedMembers)
d:\Development\FluentNHibernate\src\FluentNHibernate\Automapping\AutoMapper.cs(43,0): at FluentNHibernate.Automapping.AutoMapper.MergeMap(Type classType, ClassMappingBase mapping, IList`1 mappedMembers)
d:\Development\FluentNHibernate\src\FluentNHibernate\Automapping\AutoMapper.cs(176,0): at FluentNHibernate.Automapping.AutoMapper.Map(Type classType, List`1 types)
d:\Development\FluentNHibernate\src\FluentNHibernate\Automapping\AutoPersistenceModel.cs(185,0): at FluentNHibernate.Automapping.AutoPersistenceModel.AddMapping(Type type)
d:\Development\FluentNHibernate\src\FluentNHibernate\Automapping\AutoPersistenceModel.cs(153,0): at FluentNHibernate.Automapping.AutoPersistenceModel.CompileMappings()
d:\Development\FluentNHibernate\src\FluentNHibernate\Automapping\AutoPersistenceModel.cs(175,0): at FluentNHibernate.Automapping.AutoPersistenceModel.Configure(Configuration configuration)
d:\Development\FluentNHibernate\src\FluentNHibernate\Cfg\AutoMappingsContainer.cs(84,0): at FluentNHibernate.Cfg.AutoMappingsContainer.Apply(Configuration cfg)
d:\Development\FluentNHibernate\src\FluentNHibernate\Cfg\MappingConfiguration.cs(74,0): at FluentNHibernate.Cfg.MappingConfiguration.Apply(Configuration cfg)
d:\Development\FluentNHibernate\src\FluentNHibernate\Cfg\FluentConfiguration.cs(130,0): at FluentNHibernate.Cfg.FluentConfiguration.BuildConfiguration()
What am I doing wrong?
This is a bug in Fluent NHibernate. I'd written a fix, but it is not accepted yet.
The pull request is located here: http://github.com/jagregory/fluent-nhibernate/pull/106
I am trying to map a parent child relationship between a Person object and a Organization object in FluentNHibernate using References in the mapping file like this:
References(x => x.Organization);
The relationship is a Person object contains a OrganizationId column that corresponds to a record in the Organization table with the corresponding OrganizationId. Different Person records can belong to the same Organization.
When I retrieve a Person object it works properly. Person.Organization is populated. I can save a Person object and it works properly. However, when I attempt to add a new Person object I get a Index Out of Range exception from NHibernate. The exception occurs when calling session.SaveOrUpdate(person). I've tried changing the mapping to:
References(x => x.Organization).Cascade.None()
Still get the same error. I can't figure out what is causing the exception. The full exception is this:
System.IndexOutOfRangeException : Invalid index 22 for this SqlParameterCollection with Count=22.
at System.Data.SqlClient.SqlParameterCollection.RangeCheck(Int32 index)
at System.Data.SqlClient.SqlParameterCollection.GetParameter(Int32 index)
at System.Data.Common.DbParameterCollection.System.Collections.IList.get_Item(Int32 index)
at NHibernate.Type.NullableType.NullSafeSet(IDbCommand cmd, Object value, Int32 index)
at NHibernate.Type.ManyToOneType.NullSafeSet(IDbCommand st, Object value, Int32 index, Boolean[] settable, ISessionImplementor session)
at NHibernate.Persister.Entity.AbstractEntityPersister.Dehydrate(Object id, Object[] fields, Object rowId, Boolean[] includeProperty, Boolean[][] includeColumns, Int32 table, IDbCommand statement, ISessionImplementor session, Int32 index)
at NHibernate.Persister.Entity.AbstractEntityPersister.GeneratedIdentifierBinder.BindValues(IDbCommand ps)
at NHibernate.Id.Insert.AbstractReturningDelegate.PerformInsert(SqlCommandInfo insertSQL, ISessionImplementor session, IBinder binder)
at NHibernate.Persister.Entity.AbstractEntityPersister.Insert(Object[] fields, Boolean[] notNull, SqlCommandInfo sql, Object obj, ISessionImplementor session)
at NHibernate.Persister.Entity.AbstractEntityPersister.Insert(Object[] fields, Object obj, ISessionImplementor session)
at NHibernate.Action.EntityIdentityInsertAction.Execute()
at NHibernate.Engine.ActionQueue.Execute(IExecutable executable)
at NHibernate.Event.Default.AbstractSaveEventListener.PerformSaveOrReplicate(Object entity, EntityKey key, IEntityPersister persister, Boolean useIdentityColumn, Object anything, IEventSource source, Boolean requiresImmediateIdAccess)
at NHibernate.Event.Default.AbstractSaveEventListener.SaveWithGeneratedId(Object entity, String entityName, Object anything, IEventSource source, Boolean requiresImmediateIdAccess)
at NHibernate.Event.Default.DefaultSaveOrUpdateEventListener.SaveWithGeneratedOrRequestedId(SaveOrUpdateEvent event)
at NHibernate.Event.Default.DefaultSaveOrUpdateEventListener.EntityIsTransient(SaveOrUpdateEvent event)
at NHibernate.Event.Default.DefaultSaveOrUpdateEventListener.OnSaveOrUpdate(SaveOrUpdateEvent event)
at NHibernate.Impl.SessionImpl.FireSaveOrUpdate(SaveOrUpdateEvent event)
at NHibernate.Impl.SessionImpl.SaveOrUpdate(Object obj)
First of all the exception occurs because you map the same column twice in your class and that is not allowed.
check this
IndexOutOfRangeException Deep in the bowels of NHibernate
Secondly (and according to your latest comment) having an OrganizationId and an Organization property in your Person class is sort-of going against the grain. You don't need it. You can access it via per1.Organization.Id
If you already have an Organization in your db (say Id=5) and you map the Organization class to the Person class using the OrganizationId foreign key, then when you code
Organization theOrganizationWithId5 = nhSession.Get<Organization>(5);
per1.Organization = theOrganizationWithId5;
nhSession.Save(per1);
NHibernate will just set the value 5 on the OrganizationId column in your Person table.
You will not be populating Organization.
We have an asp.net MVC app using Fluent Nhibernate running on top of IIS7 & Windows Sever 2008. Frequently (although so far we have yet to consistently reproduce it) after a build we get a yellow screen of death with this exception:
[COMException (0x800703fa): Illegal operation attempted on a registry key that has been marked for deletion. (Exception from HRESULT: 0x800703FA)]
System.Reflection.Assembly._nDefineDynamicModule(Assembly containingAssembly, Boolean emitSymbolInfo, String filename, StackCrawlMark& stackMark) +0
System.Reflection.Emit.AssemblyBuilder.DefineDynamicModuleInternalNoLock(String name, Boolean emitSymbolInfo, StackCrawlMark& stackMark) +381
System.Reflection.Emit.AssemblyBuilder.DefineDynamicModuleInternal(String name, Boolean emitSymbolInfo, StackCrawlMark& stackMark) +105
System.Reflection.Emit.AssemblyBuilder.DefineDynamicModule(String name, Boolean emitSymbolInfo) +83
Castle.DynamicProxy.ModuleScope.CreateModule(Boolean signStrongName) +206
Castle.DynamicProxy.ModuleScope.ObtainDynamicModuleWithWeakName() +63
Castle.DynamicProxy.Generators.Emitters.ClassEmitter.CreateTypeBuilder(ModuleScope modulescope, String name, Type baseType, Type[] interfaces, TypeAttributes flags, Boolean forceUnsigned) +78
Castle.DynamicProxy.Generators.Emitters.ClassEmitter..ctor(ModuleScope modulescope, String name, Type baseType, Type[] interfaces, TypeAttributes flags, Boolean forceUnsigned) +69
Castle.DynamicProxy.Generators.Emitters.ClassEmitter..ctor(ModuleScope modulescope, String name, Type baseType, Type[] interfaces) +36
Castle.DynamicProxy.Generators.BaseProxyGenerator.BuildClassEmitter(String typeName, Type parentType, Type[] interfaces) +140
Castle.DynamicProxy.Generators.ClassProxyGenerator.GenerateCode(Type[] interfaces, ProxyGenerationOptions options) +648
Castle.DynamicProxy.ProxyGenerator.CreateClassProxy(Type classToProxy, Type[] additionalInterfacesToProxy, ProxyGenerationOptions options, Object[] constructorArguments, IInterceptor[] interceptors) +139
Castle.DynamicProxy.ProxyGenerator.CreateClassProxy(Type classToProxy, Type[] additionalInterfacesToProxy, IInterceptor[] interceptors) +39
NHibernate.ByteCode.Castle.ProxyFactory.GetProxy(Object id, ISessionImplementor session) +416
[HibernateException: Creating a proxy instance failed]
NHibernate.ByteCode.Castle.ProxyFactory.GetProxy(Object id, ISessionImplementor session) +642
NHibernate.Tuple.Entity.AbstractEntityTuplizer.CreateProxy(Object id, ISessionImplementor session) +49
NHibernate.Persister.Entity.AbstractEntityPersister.CreateProxy(Object id, ISessionImplementor session) +102
NHibernate.Event.Default.DefaultLoadEventListener.CreateProxyIfNecessary(LoadEvent event, IEntityPersister persister, EntityKey keyToLoad, LoadType options, IPersistenceContext persistenceContext) +255
NHibernate.Event.Default.DefaultLoadEventListener.ProxyOrLoad(LoadEvent event, IEntityPersister persister, EntityKey keyToLoad, LoadType options) +400
NHibernate.Event.Default.DefaultLoadEventListener.OnLoad(LoadEvent event, LoadType loadType) +923
NHibernate.Impl.SessionImpl.FireLoad(LoadEvent event, LoadType loadType) +169
NHibernate.Impl.SessionImpl.InternalLoad(String entityName, Object id, Boolean eager, Boolean isNullable) +310
NHibernate.Type.EntityType.ResolveIdentifier(Object id, ISessionImplementor session) +211
NHibernate.Engine.TwoPhaseLoad.InitializeEntity(Object entity, Boolean readOnly, ISessionImplementor session, PreLoadEvent preLoadEvent, PostLoadEvent postLoadEvent) +527
NHibernate.Loader.Loader.InitializeEntitiesAndCollections(IList hydratedObjects, Object resultSetId, ISessionImplementor session, Boolean readOnly) +544
NHibernate.Loader.Loader.DoQuery(ISessionImplementor session, QueryParameters queryParameters, Boolean returnProxies) +1158
NHibernate.Loader.Loader.DoQueryAndInitializeNonLazyCollections(ISessionImplementor session, QueryParameters queryParameters, Boolean returnProxies) +105
NHibernate.Loader.Loader.LoadEntity(ISessionImplementor session, Object id, IType identifierType, Object optionalObject, String optionalEntityName, Object optionalIdentifier, IEntityPersister persister) +472
NHibernate.Loader.Entity.AbstractEntityLoader.Load(ISessionImplementor session, Object id, Object optionalObject, Object optionalId) +77
NHibernate.Loader.Entity.AbstractEntityLoader.Load(Object id, Object optionalObject, ISessionImplementor session) +30
NHibernate.Persister.Entity.AbstractEntityPersister.Load(Object id, Object optionalObject, LockMode lockMode, ISessionImplementor session) +182
NHibernate.Event.Default.DefaultLoadEventListener.LoadFromDatasource(LoadEvent event, IEntityPersister persister, EntityKey keyToLoad, LoadType options) +174
NHibernate.Event.Default.DefaultLoadEventListener.Load(LoadEvent event, IEntityPersister persister, EntityKey keyToLoad, LoadType options) +194
NHibernate.Event.Default.DefaultLoadEventListener.OnLoad(LoadEvent event, LoadType loadType) +923
NHibernate.Impl.SessionImpl.FireLoad(LoadEvent event, LoadType loadType) +169
NHibernate.Impl.SessionImpl.Get(String entityName, Object id) +191
NHibernate.Impl.SessionImpl.Get(Type entityClass, Object id) +139
NHibernate.Impl.SessionImpl.Get(Object id) +136
Huddle.DataAccess.Persistence.Repository`1.FindById(Int32 id) +281
Huddle.WebSite.Global.GetWorkspace() +241
Huddle.WebSite.Global.Application_BeginRequest(Object sender, EventArgs e) +437
System.Web.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +80
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +171
It seems a few other people have found the same problem although no one seems to have a solution, any ideas?
This sounds like something I've seen with COM+ and MSMQ on Windows 2008. What happens is that Windows 2008 unloads the user registry hive as soon as the user is logged off, regardless of any remaining open handles. You should see entries in the event log that the hive was unloaded with processes still using it.
There is a GPO that can be set to prevent this from happening (DisableForceUnload)
More information here:
http://blogs.msdn.com/distributedservices/archive/2009/11/06/a-com-server-application-may-stop-working-on-windows-server-2008.aspx
This looks like a bug in the .NET framework itself.
Notice that the innermost method being called, does not specify it can throw a ComException.
I would suggest updating to the most recent version of Castle Dynamic Proxy (2.2 beta) to see if the problem persists.
If it does you may try using one of the other proxy providers.
And also report this issue to Microsoft Connect