Why won't my object serialize? - asp.net-web-api2

I have a class. It implements IXmlSerializable. I can't get Web API 2 to serialize it.
Here is my class:
public class MyType: IXmlSerializable
{
public XmlSchema GetSchema()
{
return null;
}
public void WriteXml(XmlWriter writer)
{
// some code
}
public void ReadXml(XmlReader reader)
{
throw new NotImplementedException();
}
}
Here is the response:
<Error>
<Message>An error has occurred.</Message>
<ExceptionMessage>
The 'ObjectContent`1' type failed to serialize the response body for content type 'text/xml; charset=utf-8'.
</ExceptionMessage>
<ExceptionType>System.InvalidOperationException</ExceptionType>
<StackTrace />
<InnerException>
<Message>An error has occurred.</Message>
<ExceptionMessage>Type 'MyType' with data contract name 'XmlConverter:http://schemas.datacontract.org/2004/07/MyNamespace' is not expected. Consider using a DataContractResolver or add any types not known statically to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding them to the list of known types passed to DataContractSerializer.</ExceptionMessage>
<ExceptionType>System.Runtime.Serialization.SerializationException</ExceptionType>
<StackTrace>
at System.Runtime.Serialization.XmlObjectSerializerWriteContext.SerializeAndVerifyType(DataContract dataContract, XmlWriterDelegator xmlWriter, Object obj, Boolean verifyKnownType, RuntimeTypeHandle declaredTypeHandle, Type declaredType)
at System.Runtime.Serialization.XmlObjectSerializerWriteContext.SerializeWithXsiTypeAtTopLevel(DataContract dataContract, XmlWriterDelegator xmlWriter, Object obj, RuntimeTypeHandle originalDeclaredTypeHandle, Type graphType)
at System.Runtime.Serialization.DataContractSerializer.InternalWriteObjectContent(XmlWriterDelegator writer, Object graph, DataContractResolver dataContractResolver)
at System.Runtime.Serialization.DataContractSerializer.InternalWriteObject(XmlWriterDelegator writer, Object graph, DataContractResolver dataContractResolver)
at System.Runtime.Serialization.XmlObjectSerializer.WriteObjectHandleExceptions(XmlWriterDelegator writer, Object graph, DataContractResolver dataContractResolver)
at System.Runtime.Serialization.DataContractSerializer.WriteObject(XmlWriter writer, Object graph)
at System.Net.Http.Formatting.XmlMediaTypeFormatter.WriteToStream(Type type, Object value, Stream writeStream, HttpContent content)
at System.Net.Http.Formatting.XmlMediaTypeFormatter.WriteToStreamAsync(Type type, Object value, Stream writeStream, HttpContent content, TransportContext transportContext, CancellationToken cancellationToken)
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Web.Http.WebHost.HttpControllerHandler.<WriteBufferedResponseContentAsync>d__1b.MoveNext()
</StackTrace>
</InnerException>
</Error>
I've tried [DataContract]. That changes the 'Type 'MyNamespace.MyType' cannot be IXmlSerializable and have DataContractAttribute attribute.' I've tried using [XmlSchemaProvider("Method", IsAny = true)], with Method returning null, which gives me the original error again. DataContractSerializer is supposed to be able to serialize IXmlSerializables. What gives?
P.S.: WriteXml is not being called at all.

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 =')

WCF Read data issue from service

I am tying to get the generic List of user List<User> object from my web service to my web application. probably this is common issue. i searched a lot but got different remedies with each link. so finally i decide to ask to chaps over here... anyways
I am using console application for fetching the data from my hosted wcf web service. where as my WCf web service having the Entity framework 4.1. am using objects from its model class. when i tried to add service reference to my web application , it typically generates the proxy in web app. i am able to post data means i could create user. but while getusers which is returning List , getting following exceptions...:
Exception:
An error occurred while receiving the HTTP response to
http://myserver/AdminService/MyAdminService.svc. This could be due to
the service endpoint binding not using the HTTP protocol. This could
also be due to an HTTP request context being aborted by the server
(possibly due to the service shutting down). See server logs for more
details.
Inner Exception is :
The underlying connection was closed: An unexpected error occurred
on a receive
and inner-inner exception is : Unable to read data from the
transport connection: An existing connection was forcibly closed by
the remote host.
with message : An existing connection was forcibly closed by the
remote host
Error Code :10054
Where as Event log saying :
A message was not logged.
Exception: System.ServiceModel.CommunicationException: There was
an error while trying to serialize parameter
http://tempuri.org/:getUsersResult. The InnerException message was
'Type
'System.Data.Entity.DynamicProxies.User_00DEC686D7E21DB0D84B595F647A03FFB4943938F76E8C3DBBE0F77F8BC29A1D'
with data contract name
'User_00DEC686D7E21DB0D84B595F647A03FFB4943938F76E8C3DBBE0F77F8BC29A1D:http://schemas.datacontract.org/2004/07/System.Data.Entity.DynamicProxies'
is not expected. Consider using a DataContractResolver or add any
types not known statically to the list of known types - for example,
by using the KnownTypeAttribute attribute or by adding them to the
list of known types passed to DataContractSerializer.'. Please see
InnerException for more details. --->
System.Runtime.Serialization.SerializationException: Type
'System.Data.Entity.DynamicProxies.User_00DEC686D7E21DB0D84B595F647A03FFB4943938F76E8C3DBBE0F77F8BC29A1D'
with data contract name
'User_00DEC686D7E21DB0D84B595F647A03FFB4943938F76E8C3DBBE0F77F8BC29A1D:http://schemas.datacontract.org/2004/07/System.Data.Entity.DynamicProxies'
is not expected. Consider using a DataContractResolver or add any
types not known statically to the list of known types - for example,
by using the KnownTypeAttribute attribute or by adding them to the
list of known types passed to DataContractSerializer.
at
System.Runtime.Serialization.XmlObjectSerializerWriteContext.SerializeAndVerifyType(DataContract
dataContract, XmlWriterDelegator xmlWriter, Object obj, Boolean
verifyKnownType, RuntimeTypeHandle declaredTypeHandle, Type
declaredType)
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 WriteArrayOfUserToXml(XmlWriterDelegator , Object ,
XmlObjectSerializerWriteContext , CollectionDataContract )
at
System.Runtime.Serialization.CollectionDataContract.WriteXmlValue(XmlWriterDelegator
xmlWriter, Object obj, XmlObjectSerializerWriteContext context)
at
System.Runtime.Serialization.DataContractSerializer.InternalWriteObjectContent(XmlWriterDelegator
writer, Object graph, DataContractResolver dataContractResolver)
at
System.Runtime.Serialization.DataContractSerializer.InternalWriteObject(XmlWriterDelegator
writer, Object graph, DataContractResolver dataContractResolver)
at
System.Runtime.Serialization.XmlObjectSerializer.WriteObjectHandleExceptions(XmlWriterDelegator
writer, Object graph, DataContractResolver dataContractResolver)
at
System.Runtime.Serialization.XmlObjectSerializer.WriteObject(XmlDictionaryWriter
writer, Object graph)
at
System.ServiceModel.Dispatcher.DataContractSerializerOperationFormatter.SerializeParameterPart(XmlDictionaryWriter
writer, PartInfo part, Object graph)
--- End of inner exception stack trace ---
at
System.ServiceModel.Dispatcher.DataContractSerializerOperationFormatter.SerializeParameterPart(XmlDictionaryWriter
writer, PartInfo part, Object graph)
at
System.ServiceModel.Dispatcher.DataContractSerializerOperationFormatter.SerializeParameter(XmlDictionaryWriter
writer, PartInfo part, Object graph)
at
System.ServiceModel.Dispatcher.DataContractSerializerOperationFormatter.SerializeBody(XmlDictionaryWriter
writer, MessageVersion version, String action, MessageDescription
messageDescription, Object returnValue, Object[] parameters, Boolean
isRequest)
at
System.ServiceModel.Dispatcher.OperationFormatter.OperationFormatterMessage.OperationFormatterBodyWriter.OnWriteBodyContents(XmlDictionaryWriter
writer)
at
System.ServiceModel.Channels.BodyWriter.WriteBodyContents(XmlDictionaryWriter
writer)
at
System.ServiceModel.Channels.Message.ToString(XmlDictionaryWriter
writer)
at
System.ServiceModel.Diagnostics.MessageLogTraceRecord.WriteTo(XmlWriter
writer)
at
System.ServiceModel.Diagnostics.MessageLogger.LogInternal(MessageLogTraceRecord
record)
at
System.ServiceModel.Diagnostics.MessageLogger.LogMessageImpl(Message&
message, XmlReader reader, MessageLoggingSource source)
at
System.ServiceModel.Diagnostics.MessageLogger.LogMessage(Message&
message, XmlReader reader, MessageLoggingSource source)
Process Name: w3wp
Process ID: 5928
What should be this issue. me and team searching for this since 3 days. but unfortunately not overcome so far...
I tried lot of stuffs like add serializable attribute, endpoint modifications ... i can not recollect all :) ... probably you may give us right directions...
The reason is that EF classes are by default proxied at runtime to support lazy loading and dynamic change tracking. So you don't serialize User class but class derived from User at runtime. WCF doesn't like that. Turn off proxy creation on your context.
context.Configuration.ProxyCreationEnabled = false;

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.

NHibernate: Collection was modified; enumeration operation may not execute

I'm currently struggling with this "Collection was modified; enumeration operation may not execute" issue.
I have searched about this error message, and it's all related to the foreach statement. I do have the some foreach statements, but they are just simply representing the data. I did not using any remove or add inside the foreach statement.
NOTE:
The error randomly happens (about 4-5 times a day).
The application is the MVC website.
There are about 5 users operate this applications (about 150 orders a day). Could it be some another users modified the collection, and then occur this error?
I have log4net setup and the settings can be found here
Make sure that the controller has a parameterless public constructor I do have parameterless public constructor in AdminProductController
Does anyone know why this happen and how to resolve this issue?
A friend (Oskar) mentioned that
"Theory: Maybe the problem is that
your configuration and session factory
is initialized on the first request
after application restart. If a second
request comes in before the first
request is finished, maybe it will
also try to initialize and then
triggering this problem somehow."
Many thanks.
Daoming
Here is the error message:
System.InvalidOperationException
Collection was modified; enumeration operation may not execute.
System.InvalidOperationException: An error occurred when trying to create a controller of type 'WebController.Controllers.Admin.AdminProductController'. Make sure that the controller has a parameterless public constructor. ---> System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> NHibernate.MappingException: Could not configure datastore from input stream DomainModel.Entities.Mappings.OrderProductVariant.hbm.xml ---> System.InvalidOperationException: Collection was modified; enumeration operation may not execute.
at System.Collections.ArrayList.ArrayListEnumeratorSimple.MoveNext()
at System.Xml.Schema.XmlSchemaSet.AddSchemaToSet(XmlSchema schema)
at System.Xml.Schema.XmlSchemaSet.Add(String targetNamespace, XmlSchema schema)
at System.Xml.Schema.XmlSchemaSet.Add(XmlSchema schema)
at NHibernate.Cfg.Configuration.LoadMappingDocument(XmlReader hbmReader, String name)
at NHibernate.Cfg.Configuration.AddInputStream(Stream xmlInputStream, String name)
--- End of inner exception stack trace ---
at NHibernate.Cfg.Configuration.LogAndThrow(Exception exception)
at NHibernate.Cfg.Configuration.AddInputStream(Stream xmlInputStream, String name)
at NHibernate.Cfg.Configuration.AddResource(String path, Assembly assembly)
at NHibernate.Cfg.Configuration.AddAssembly(Assembly assembly)
at DomainModel.RepositoryBase..ctor()
at WebController.Controllers._baseController..ctor()
at WebController.Controllers.Admin.AdminProductController..ctor()
at System.RuntimeType.CreateInstanceImpl(Boolean publicOnly, Boolean skipVisibilityChecks, Boolean fillCache)
--- End of inner exception stack trace ---
at System.RuntimeType.CreateInstanceImpl(Boolean publicOnly, Boolean skipVisibilityChecks, Boolean fillCache)
at System.Activator.CreateInstance(Type type, Boolean nonPublic)
at System.Web.Mvc.DefaultControllerFactory.GetControllerInstance(RequestContext requestContext, Type controllerType)
--- End of inner exception stack trace ---
at System.Web.Mvc.DefaultControllerFactory.GetControllerInstance(RequestContext requestContext, Type controllerType)
at System.Web.Mvc.DefaultControllerFactory.CreateController(RequestContext requestContext, String controllerName)
at System.Web.Mvc.MvcHandler.ProcessRequestInit(HttpContextBase httpContext, IController& controller, IControllerFactory& factory)
at System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state)
at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
Oskar is right. Two separate threads are trying to initialize the session factory at the same time. Suggest you put some locking around the initialization code, perhaps just using the lock keyword and a suitable synchronization object. We've used a pattern like this, using one of the locks from the Wintellect PowerThreading library:
using (_lock.WaitToRead())
{
if (Factory != null) return Factory;
}
using (_lock.WaitToWrite())
{
if (Factory != null) return Factory;
Factory = ConfigureFactory();
return Factory;
}
You could more simply just use the lock keyword and a double-check locking pattern like so:
class NestedSessionManager
{
internal static SessionManager _sessionManager;
private static readonly object _syncRoot = new object();
internal static SessionManager sessionManager
{
get
{
if (_sessionManager != null) return _sessionManager;
lock (_syncRoot)
{
if (_sessionManager != null) return _sessionManager;
_sessionManager = new SessionManager();
return _sessionManager;
}
}
}
}

NHibernate Not Compile on my Window Server

My Apps was developed with NHibernate Working fine on my system but giving this error on the host Server
Index was outside the bounds of the array.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.IndexOutOfRangeException: Index was outside the bounds of the array.
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[IndexOutOfRangeException: Index was outside the bounds of the array.]
NHibernate.Dialect.Dialect.IsQuoted(String name) +84
NHibernate.Dialect.Dialect.QuoteForSchemaName(String schemaName) +20
NHibernate.Cfg.HbmBinder.MakeIdentifier(XmlNode node, SimpleValue model, Mappings mappings) +228
NHibernate.Cfg.HbmBinder.BindRootClass(XmlNode node, RootClass model, Mappings mappings) +1223
NHibernate.Cfg.HbmBinder.BindRoot(XmlDocument doc, Mappings mappings) +398
NHibernate.Cfg.Configuration.AddValidatedDocument(XmlDocument doc, String name) +69
[MappingException: Could not compile the mapping document: CMS.Common.Mapping.CMS.Common.Data.AccountPeriod.hbm.xml]
NHibernate.Cfg.Configuration.LogAndThrow(MappingException me) +40
NHibernate.Cfg.Configuration.AddValidatedDocument(XmlDocument doc, String name) +137
NHibernate.Cfg.Configuration.AddXmlReader(XmlTextReader hbmReader, String name) +29
NHibernate.Cfg.Configuration.AddInputStream(Stream xmlInputStream, String name) +109
NHibernate.Cfg.Configuration.AddResource(String path, Assembly assembly) +185
NHibernate.Cfg.Configuration.AddResources(Assembly assembly, IList resources, Boolean skipOrdering) +166
NHibernate.Cfg.Configuration.AddAssembly(Assembly assembly, Boolean skipOrdering) +32
NHibernate.Cfg.Configuration.AddAssembly(String assemblyName) +150
NHibernate.Cfg.Configuration.DoConfigure(XmlDocument doc) +644
NHibernate.Cfg.Configuration.Configure(XmlTextReader reader) +304
NHibernate.Cfg.Configuration.Configure(XmlNode node) +81
NHibernate.Cfg.Configuration.Configure() +35
ProjectBase.Data.NHibernateSessionManager.InitSessionFactory() +60
ProjectBase.Data.NHibernateSessionManager..ctor() +39
ProjectBase.Data.Nested..cctor() +39
[TypeInitializationException: The type initializer for 'Nested' threw an exception.]
ProjectBase.Data.NHibernateSessionManager.get_Instance() +38
CMS.Facade.CoreSystem.BuildSession() in C:\Users\Oladapo\Documents\Visual Studio 2008\Projects\Property Manager\CMS.Facade\CoreSystem.cs:440
CMS.Facade.AdvertSystem.RetrieveAllAdvert() in C:\Users\Oladapo\Documents\Visual Studio 2008\Projects\Property Manager\CMS.Facade\AdvertSystem.cs:16
[TargetInvocationException: Exception has been thrown by the target of an invocation.]
System.RuntimeMethodHandle._InvokeMethodFast(Object target, Object[] arguments, SignatureStruct& sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner) +0
System.RuntimeMethodHandle.InvokeMethodFast(Object target, Object[] arguments, Signature sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner) +71
System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks) +350
System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) +29
System.Web.UI.WebControls.ObjectDataSourceView.InvokeMethod(ObjectDataSourceMethod method, Boolean disposeInstance, Object& instance) +488
System.Web.UI.WebControls.ObjectDataSourceView.ExecuteSelect(DataSourceSelectArguments arguments) +1247
System.Web.UI.WebControls.BaseDataList.GetData() +38
System.Web.UI.WebControls.DataList.CreateControlHierarchy(Boolean useDataSource) +153
System.Web.UI.WebControls.BaseDataList.OnDataBinding(EventArgs e) +54
System.Web.UI.WebControls.BaseDataList.DataBind() +55
System.Web.UI.WebControls.BaseDataList.EnsureDataBound() +60
System.Web.UI.WebControls.BaseDataList.CreateChildControls() +69
System.Web.UI.Control.EnsureChildControls() +87
System.Web.UI.Control.PreRenderRecursiveInternal() +44
System.Web.UI.Control.PreRenderRecursiveInternal() +171
System.Web.UI.Control.PreRenderRecursiveInternal() +171
System.Web.UI.Control.PreRenderRecursiveInternal() +171
System.Web.UI.Control.PreRenderRecursiveInternal() +171
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +842
After adding some NHibernate goodness to a project, I had similar problems deploying because I forgot to update the web.config file on production. Once I defined the hibernate-configuration section, everything worked.
Also happened to me when I had an empty enum defined.
That you have a MappingException included in your stack trace is key. This implies either a problem with your class mappings, or your NHibernate configuration. It could also be that your database does not contain tables or fields defined in your class mappings.
To be more specific, you would need to provide additional information.