FluentNhibernate Mapping Using References Index Out of Range When Adding new Object - nhibernate

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.

Related

Add-Migration error: Object reference not set to an instance of an object

I'm using code-first concept and just tried adding a new class to the Models folder in hope to create a new table in SQL server database. i've added
Public Overridable Property Diagnosis As DbSet(Of Diagnosis)
in the DBContext.vb.
Then in the package manager console, i entered Add-Migration Diagnosis. But below error comes out. Why is this? Can anyone help me out please?
Object reference not set to an instance of an object.
Full error in Package Manager Console:
System.NullReferenceException: Object reference not set to an instance of an object.
at System.Web.UI.ParseChildrenAttribute.GetHashCode()
at System.Collections.Generic.ObjectEqualityComparer`1.GetHashCode(T obj)
at System.Linq.Set`1.InternalGetHashCode(TElement value)
at System.Linq.Set`1.Find(TElement value, Boolean add)
at System.Linq.Enumerable.<ExceptIterator>d__72`1.MoveNext()
at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
at System.Data.Entity.ModelConfiguration.Utilities.AttributeProvider.<GetAttributes>b__3(PropertyInfo pi)
at System.Collections.Concurrent.ConcurrentDictionary`2.GetOrAdd(TKey key, Func`2 valueFactory)
at System.Data.Entity.ModelConfiguration.Utilities.AttributeProvider.GetAttributes(PropertyInfo propertyInfo)
at System.Data.Entity.ModelConfiguration.Conventions.PropertyAttributeConfigurationConvention`1.<.ctor>b__0(ConventionTypeConfiguration ec)
at System.Data.Entity.ModelConfiguration.Conventions.TypeConvention.ApplyCore(Type memberInfo, ModelConfiguration modelConfiguration)
at System.Data.Entity.ModelConfiguration.Conventions.TypeConventionBase.Apply(Type memberInfo, ModelConfiguration modelConfiguration)
at System.Data.Entity.ModelConfiguration.Configuration.ConventionsConfiguration.ApplyModelConfiguration(Type type, ModelConfiguration modelConfiguration)
at System.Data.Entity.ModelConfiguration.Conventions.Convention.ApplyModelConfiguration(Type type, ModelConfiguration modelConfiguration)
at System.Data.Entity.ModelConfiguration.Configuration.ConventionsConfiguration.ApplyModelConfiguration(Type type, ModelConfiguration modelConfiguration)
at System.Data.Entity.ModelConfiguration.Mappers.TypeMapper.MapComplexType(Type type, Boolean discoverNested)
at System.Data.Entity.ModelConfiguration.Mappers.PropertyMapper.MapPrimitiveOrComplexOrEnumProperty(PropertyInfo propertyInfo, Func`1 structuralTypeConfiguration, Boolean discoverComplexTypes)
at System.Data.Entity.ModelConfiguration.Mappers.PropertyMapper.MapIfNotNavigationProperty(PropertyInfo propertyInfo, EntityType entityType, Func`1 entityTypeConfiguration)
at System.Data.Entity.ModelConfiguration.Mappers.TypeMapper.<>c__DisplayClass14.<MapEntityType>b__e(PropertyMapper m, PropertyInfo p)
at System.Data.Entity.ModelConfiguration.Mappers.TypeMapper.MapStructuralElements[TStructuralTypeConfiguration](Type type, ICollection`1 annotations, Action`2 propertyMappingAction, Func`1 structuralTypeConfiguration)
at System.Data.Entity.ModelConfiguration.Mappers.TypeMapper.MapEntityType(Type type)
at System.Data.Entity.ModelConfiguration.Mappers.NavigationPropertyMapper.Map(PropertyInfo propertyInfo, EntityType entityType, Func`1 entityTypeConfiguration)
at System.Data.Entity.ModelConfiguration.Mappers.TypeMapper.MapEntityType(Type type)
at System.Data.Entity.DbModelBuilder.MapTypes(EdmModel model)
at System.Data.Entity.DbModelBuilder.Build(DbProviderManifest providerManifest, DbProviderInfo providerInfo)
at System.Data.Entity.DbModelBuilder.Build(DbConnection providerConnection)
at System.Data.Entity.Internal.LazyInternalContext.CreateModel(LazyInternalContext internalContext)
at System.Data.Entity.Internal.RetryLazy`2.GetValue(TInput input)
at System.Data.Entity.Internal.LazyInternalContext.InitializeContext()
at System.Data.Entity.Internal.LazyInternalContext.get_ModelBeingInitialized()
at System.Data.Entity.Infrastructure.EdmxWriter.WriteEdmx(DbContext context, XmlWriter writer)
at System.Data.Entity.Utilities.DbContextExtensions.<>c__DisplayClass1.<GetModel>b__0(XmlWriter w)
at System.Data.Entity.Utilities.DbContextExtensions.GetModel(Action`1 writeXml)
at System.Data.Entity.Utilities.DbContextExtensions.GetModel(DbContext context)
at System.Data.Entity.Migrations.DbMigrator..ctor(DbMigrationsConfiguration configuration, DbContext usersContext, DatabaseExistenceState existenceState, Boolean calledByCreateDatabase)
at System.Data.Entity.Migrations.DbMigrator..ctor(DbMigrationsConfiguration configuration)
at System.Data.Entity.Migrations.Design.MigrationScaffolder..ctor(DbMigrationsConfiguration migrationsConfiguration)
at System.Data.Entity.Migrations.Design.ToolingFacade.ScaffoldRunner.Run()
at System.AppDomain.DoCallBack(CrossAppDomainDelegate callBackDelegate)
at System.AppDomain.DoCallBack(CrossAppDomainDelegate callBackDelegate)
at System.Data.Entity.Migrations.Design.ToolingFacade.Run(BaseRunner runner)
at System.Data.Entity.Migrations.Design.ToolingFacade.Scaffold(String migrationName, String language, String rootNamespace, Boolean ignoreChanges)
at System.Data.Entity.Migrations.AddMigrationCommand.Execute(String name, Boolean force, Boolean ignoreChanges)
at System.Data.Entity.Migrations.AddMigrationCommand.<>c__DisplayClass2.<.ctor>b__0()
at System.Data.Entity.Migrations.MigrationsDomainCommand.Execute(Action command)
Object reference not set to an instance of an object.
I don't know if this is relevant or not, but in my web.config, there is a Default Connection that is already pre-set when i first created my project. When i first did Enable-Migrations i had to specify which connection it was. I've removed that line but it still doesn't work.
Previously when i did the add-migration, it didn't work because i simply created a class and added declaration of the respective strings, integer, etc. as variables like this:
Public Property id As String
Now it suddenly popped into my mind that i had to give a more elaborate description on each of the variables such as below:
<Key>
<StringLength(20)>
Public Property id As String
Now it works =')

Ajax POST to MVC4 with special characters '&#' does not work [duplicate]

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.

NHibernate Image Storage - The length of the byte[] value exceeds the length configured

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"/>

How to debug serialization error in tombstoned WP7 app

I am handling the current state of my WP7 app in the OnNavigatedFrom and To events so that if the app is tombstoned OR they navigate to a different page it saves the state to the inbuilt PhoneApplicationService state.
I have a simple ViewModel which I dump to the state to make life easier. When navigate to a different page within my app, the state is stored fine and restores fine (ie. I assume it is serializing at this point). However, when I tombstone the app (i.e. Start button) I am getting an unhandled error with serialization and the stacktrace is not giving me any clues as to why it is failing.
I have tried wrapping the actual call in a try catch block to try and see what is wrong but it doesn't help - it's something that the runtime is doing different on tombstoning with my object than when it just stores it between pages.
Here is my code:
protected override void OnNavigatedFrom(NavigationEventArgs args)
{
appService.State["TournamentViewModel"] = tournamentViewModel;
base.OnNavigatedFrom(args);
}
protected override void OnNavigatedTo(NavigationEventArgs args)
{
if (appService.State.ContainsKey("TournamentViewModel"))
{
tournamentViewModel = (TournamentViewModel)appService.State["TournamentViewModel"];
}
base.OnNavigatedTo(args);
}
This is the error that is generated - I really can't figure out where the problem is - how can I debug this better?
Exception Info:
Message: "SecurityException"
InnerException: "Could not evaluate expression"
StackTrace:
at System.Runtime.Serialization.DataContract.DataContractCriticalHelper.CreateGetOnlyCollectionDataContract(Int32 id, RuntimeTypeHandle typeHandle, Type type)
at System.Runtime.Serialization.DataContract.DataContractCriticalHelper.GetGetOnlyCollectionDataContractSkipValidation(Int32 id, RuntimeTypeHandle typeHandle, Type type)
at System.Runtime.Serialization.DataContract.GetGetOnlyCollectionDataContractSkipValidation(Int32 id, RuntimeTypeHandle typeHandle, Type type)
at System.Runtime.Serialization.XmlObjectSerializerContext.GetDataContractSkipValidation(Int32 typeId, RuntimeTypeHandle typeHandle, Type type)
at System.Runtime.Serialization.XmlObjectSerializerWriteContext.SerializeWithXsiType(XmlWriterDelegator xmlWriter, Object obj, RuntimeTypeHandle objectTypeHandle, Type objectType, Int32 declaredTypeID, RuntimeTypeHandle declaredTypeHandle, Type declaredType)
at System.Runtime.Serialization.XmlObjectSerializerWriteContext.InternalSerialize(XmlWriterDelegator xmlWriter, Object obj, Boolean isDeclaredType, Boolean writeXsiType, Int32 declaredTypeID, RuntimeTypeHandle declaredTypeHandle)
at System.Runtime.Serialization.XmlObjectSerializerWriteContext.InternalSerializeReference(XmlWriterDelegator xmlWriter, Object obj, Boolean isDeclaredType, Boolean writeXsiType, Int32 declaredTypeID, RuntimeTypeHandle declaredTypeHandle)
at System.Reflection.RuntimeMethodInfo.InternalInvoke(RuntimeMethodInfo rtmi, Object obj, BindingFlags invokeAttr, Binder binder, Object parameters, CultureInfo culture, Boolean isBinderDefault, Assembly caller, Boolean verifyAccess, StackCrawlMark& stackMark)
at System.Reflection.RuntimeMethodInfo.InternalInvoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, StackCrawlMark& stackMark)
at System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters)
at System.Runtime.Serialization.XmlFormatWriter.InternalSerialize(MethodInfo methodInfo, Object memberValue, Type memberType, Boolean writeXsiType, XmlObjectSerializerWriteContext context, XmlWriterDelegator xmlWriter)
at System.Runtime.Serialization.XmlFormatWriter.WriteValue(Type memberType, Object memberValue, Boolean writeXsiType, XmlObjectSerializerWriteContext context, XmlWriterDelegator xmlWriter)
at System.Runtime.Serialization.XmlFormatWriter.WriteMember(SerializingObject serObj, Int32 memberIndex, ClassDataContract derivedMostClassContract)
at System.Runtime.Serialization.XmlFormatWriter.WriteClass(CallStackElement`1 callStackElement)
at System.Runtime.Serialization.XmlFormatWriter.Serialize(XmlObjectSerializerWriteContext context)
at System.Runtime.Serialization.XmlFormatWriter.InitializeCallStack(XmlWriterDelegator xmlWriterDel, Object obj, XmlObjectSerializerWriteContext writeContext, DataContract contract)
at System.Runtime.Serialization.CollectionDataContract.WriteXmlValue(XmlWriterDelegator xmlWriter, Object obj, XmlObjectSerializerWriteContext context)
at System.Runtime.Serialization.XmlObjectSerializerWriteContext.WriteDataContractValue(DataContract dataContract, XmlWriterDelegator xmlWriter, Object obj, RuntimeTypeHandle declaredTypeHandle)
at System.Runtime.Serialization.XmlObjectSerializerWriteContext.SerializeWithoutXsiType(DataContract dataContract, XmlWriterDelegator xmlWriter, Object obj, RuntimeTypeHandle declaredTypeHandle)
at System.Runtime.Serialization.DataContractSerializer.InternalWriteObjectContent(XmlWriterDelegator writer, Object graph)
at System.Runtime.Serialization.DataContractSerializer.InternalWriteObject(XmlWriterDelegator writer, Object graph)
at System.Runtime.Serialization.XmlObjectSerializer.WriteObjectHandleExceptions(XmlWriterDelegator writer, Object graph)
at System.Runtime.Serialization.XmlObjectSerializer.WriteObject(XmlDictionaryWriter writer, Object graph)
at System.Runtime.Serialization.XmlObjectSerializer.WriteObject(Stream stream, Object graph)
at Microsoft.Phone.Shell.StreamPersister.Serialize(IDictionary`2 dictionary, IEnumerable`1 knownTypes)
at Microsoft.Phone.Shell.StreamPersister.Save(ShellPageManager shellPageManager, String key, IDictionary`2 dictionary, IEnumerable`1 knownTypes)
at Microsoft.Phone.Shell.PhoneApplicationService.FireDeactivated()
at Microsoft.Phone.Execution.NativeEmInterop.FireOnPause()
Update: By trial and error I found the problem to be the AppBar, which does not seem to be serializable. I marked it with [IgnoreDataMember] and it now throws a more meaningful error on a different problem. I would still like to know if there are any easy ways of catching this info...
Rodney,
My understanding is that when you put an object in one of the two State Dictionaries (the one off of PhoneApplicationPage and the other off of PhoneApplicationServices) it does not immediately serialize or deserialize.
If you use the Page.State to store data, it serializes your state bag when you leave the page, and deserializes when you return to the page (rather than when you add or read an object from the state bag).
If you use the PhoneApplicationService.State, serialization happens when you tombstone and deserialization when the application is re-activated (though I'm not sure if this is tied to the PhoneApplicationService.Activated event or not).
Page.State, by the way, doesn't allow sharing data between pages. Saving to PhoneApplicationService.State does allow you to do so.
IsolatedStorage.AppSettings seems to handle deserialization problems silently, so I'm not sure when that happens. Serialization, however, occurs when you call Save().
James
Well, how does your ViewModel express the way in which it's serializable? Personally I tend to try to steer clear of potentially-intricate serialization: one fairly simple option is to give your ViewModel the ability to explicitly convert itself to/from XML, and then perform that step manually yourself, saving an XDocument (or its string representation) in the application state. That way it's easy to debug the serialization step, see the exact XML being generated etc.
Of course, the use of XML here is incidental - if you can easily put everything in a CSV string, that would be fine too. Anything that you can easily inspect in terms of the serialized form before putting in application state.
I realise this is side-stepping some of the supposed benefits of the "automatic" serialization, but I've run into enough hard-to-diagnose problems with automatic serialization of arbitrary objects that I don't think the benefits outweigh the drawbacks.

IIS7 + NHibernate: Illegal operation attempted on a registry key that has been marked for deletion

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