WCF Read data issue from service - wcf

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;

Related

.net API throwing exception "JSON integer is too large or small for an Int32. Path 'item_id', line 1, position 1486"

I'm using the .net client library, v1.5.9 which is the latest version, and am receiving the following error when attempting to add a new item on the ItemService:
Newtonsoft.Json.JsonReaderException: JSON integer 2151368024 is too large or small for an Int32. Path 'item_id', line 1, position 1486.
at Newtonsoft.Json.JsonTextReader.ParseReadNumber(ReadType readType, Char firstChar, Int32 initialPosition)
at Newtonsoft.Json.JsonTextReader.ParseNumber(ReadType readType)
at Newtonsoft.Json.JsonTextReader.ReadNumberValue(ReadType readType)
at Newtonsoft.Json.JsonTextReader.ReadAsInt32()
at Newtonsoft.Json.JsonReader.ReadForType(JsonContract contract, Boolean hasConverter)
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.PopulateObject(Object newObject, JsonReader reader, JsonObjectContract contract, JsonProperty member, String id)
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateObject(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, Object existingValue)
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateValueInternal(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, Object existingValue)
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize(JsonReader reader, Type objectType, Boolean checkAdditionalContent)
at Newtonsoft.Json.JsonSerializer.DeserializeInternal(JsonReader reader, Type objectType)
at Newtonsoft.Json.JsonConvert.DeserializeObject(String value, Type type, JsonSerializerSettings settings)
at Newtonsoft.Json.JsonConvert.DeserializeObject(String value, Type type, JsonConverter[] converters)
at Newtonsoft.Json.JsonConvert.DeserializeObject[T](String value, JsonConverter[] converters)
at PodioAPI.Utils.JSONSerializer.Deserilaize[T](String json)
at PodioAPI.Podio.Request[T](RequestMethod requestMethod, String url, Object requestData, Object options)
at PodioAPI.Podio.Post[T](String url, Object requestData, Object options)
at PodioAPI.Services.ItemService.AddNewItem(Int32 appId, Item item, Nullable`1 spaceId, Boolean silent, Boolean hook)
This is because the ItemId property is an int instead of long.
The client library hasn't been updated in years and it's been marked as archived now so I can't PR a fix.
Is there a way around this issue or do I have to replace the client library in my code with my own implementation?
I fixed this issue by downloading the source code of the library, add the local reference and change the data type from int to long.
https://github.com/podio/podio-dotnet
But it seems there is only asynchronous version available (even the Podio .NET project is async), you may need to change the way you call the functions a bit.
I have exectly the same issue with podio.ItemService.FilterItems()

How to call Dot NET method with parameters by MULE DotNet connector?

I am trying to call .Net method from my ESB Mule project.
I created the following class in VS 2013:
namespace NicePerform.ESBDataResolver
{
public class DataResolver
{
public Object InitInfrastructure(string sysAdminURL, string delimiter, int refreshIntervalInMin)
{
/// do something
}
}
}
In the Mule project I configured DotNet connector.
<dotnet:config name="DotNet_Connector" assemblyType="NicePerform.ESBDataResolver.DataResolver, NicePerform.ESBDataResolver" assemblyPath="D:\tfs\NGA\Splash\ESB\Debug\NicePerform.ESBDataResolver.dll" scope="Singleton" doc:name="DotNet Connector"/>
<dotnet:execute config-ref="DotNet_Connector" methodName="InitInfrastructure(System.String sysAdminURL, System.String delimiter, System.Int32 refreshIntervalInMin)" doc:name="DotNet Connector"/>
I am filling the payload:
{"sysAdminURL":"${sysAdmin}","delimiter":"${delimiter}","refreshIntervalInMin":"${userAdminRefreshInterval}"}
But on call .net method I am failing with the following exception:
System.Exception: Error looking for method named InitInfrastructure(System.String sysAdminURL, System.String delimiter, System.Int32 refreshIntervalInMin) : The method name InitInfrastructure(System.String sysAdminURL, System.String delimiter, System.Int32 refreshIntervalInMin) doesn't exist
Server stack trace:
at Org.Mule.Api.Component.ComponentLoader.MethodLookUp(Object component, String methodName, MuleMessage message)
at Org.Mule.Api.Component.ComponentLoader.ExecuteComponent(String assembly, String type, String methodName, MuleMessage message, Boolean isSingleton)
at System.Runtime.Remoting.Messaging.StackBuilderSink._PrivateProcessMessage(IntPtr md, Object[] args, Object server, Object[]& outArgs)
at System.Runtime.Remoting.Messaging.StackBuilderSink.SyncProcessMessage(IMessage msg)
Exception rethrown at [0]:
at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
at Org.Mule.Api.Component.ComponentLoader.ExecuteComponent(String assembly, String type, String methodName, MuleMessage message, Boolean isSingleton)
at Org.Mule.Api.Component.ComponentManager.Execute(String assembly, String typeName, String methodName, MuleMessage message, Boolean isSingleton)
at Org.Mule.Api.Routing.Router.Process(ProcessRequest request)
at Org.Mule.Api.Routing.__Router.Process0(IntPtr __envp, JniLocalHandle __obj, JniLocalHandle request)
I try to set namespace together with method name with no success. If I am changing calling method signature to receive single string parameter - it works. What I am doing wrong?
Everything looks correct to me, but I dont have examplecode setup for it.
You mention that you have tested with setting the namespace with the method name. have you also tested the Classname together with the method name or both?
In C# int is equal to System.Int32, and I assume this doesnt cause the issue, but it might be related.
In the example files with the connector they use a slightly different notation for the methodName field: . Since we cant find an issue in your code, you could just as well try a few other ways of calling it.

Why won't my object serialize?

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.

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;
}
}
}
}