I receive this error when I am trying to serialise a entity framework class with a circular reference (POCO). It is unable to serialise the proxy class which contains a RelationshipManager.
I have tried to the 'ToList()' method listed here http://json.codeplex.com/discussions/214093, but still no luck. Any ideas?
Here is an example of the exception i am receiving.
System.Reflection.TargetInvocationException was unhandled by user code
Message=Exception has been thrown by the target of an invocation.
Source=mscorlib
StackTrace:
at System.RuntimeMethodHandle._InvokeMethodFast(IRuntimeMethodInfo method, Object target, Object[] arguments, SignatureStruct& sig, MethodAttributes methodAttributes, RuntimeType typeOwner)
at System.RuntimeMethodHandle.InvokeMethodFast(IRuntimeMethodInfo method, Object target, Object[] arguments, Signature sig, MethodAttributes methodAttributes, RuntimeType typeOwner)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters)
at Newtonsoft.Json.Serialization.JsonContract.InvokeOnSerializing(Object o, StreamingContext context) in d:\Development\Releases\Json\Working\Src\Newtonsoft.Json\Serialization\JsonContract.cs:line 111
at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject(JsonWriter writer, Object value, JsonObjectContract contract, JsonProperty member, JsonContract collectionValueContract) in d:\Development\Releases\Json\Working\Src\Newtonsoft.Json\Serialization\JsonSerializerInternalWriter.cs:line 293
at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, JsonContract collectionValueContract) in d:\Development\Releases\Json\Working\Src\Newtonsoft.Json\Serialization\JsonSerializerInternalWriter.cs:line 117
at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.WriteMemberInfoProperty(JsonWriter writer, Object memberValue, JsonProperty property, JsonContract contract) in d:\Development\Releases\Json\Working\Src\Newtonsoft.Json\Serialization\JsonSerializerInternalWriter.cs:line 204
at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject(JsonWriter writer, Object value, JsonObjectContract contract, JsonProperty member, JsonContract collectionValueContract) in d:\Development\Releases\Json\Working\Src\Newtonsoft.Json\Serialization\JsonSerializerInternalWriter.cs:line 328
at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, JsonContract collectionValueContract) in d:\Development\Releases\Json\Working\Src\Newtonsoft.Json\Serialization\JsonSerializerInternalWriter.cs:line 117
at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.WriteMemberInfoProperty(JsonWriter writer, Object memberValue, JsonProperty property, JsonContract contract) in d:\Development\Releases\Json\Working\Src\Newtonsoft.Json\Serialization\JsonSerializerInternalWriter.cs:line 204
at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject(JsonWriter writer, Object value, JsonObjectContract contract, JsonProperty member, JsonContract collectionValueContract) in d:\Development\Releases\Json\Working\Src\Newtonsoft.Json\Serialization\JsonSerializerInternalWriter.cs:line 328
at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, JsonContract collectionValueContract) in d:\Development\Releases\Json\Working\Src\Newtonsoft.Json\Serialization\JsonSerializerInternalWriter.cs:line 117
at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeList(JsonWriter writer, IWrappedCollection values, JsonArrayContract contract, JsonProperty member, JsonContract collectionValueContract) in d:\Development\Releases\Json\Working\Src\Newtonsoft.Json\Serialization\JsonSerializerInternalWriter.cs:line 429
at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, JsonContract collectionValueContract) in d:\Development\Releases\Json\Working\Src\Newtonsoft.Json\Serialization\JsonSerializerInternalWriter.cs:line 127
at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.Serialize(JsonWriter jsonWriter, Object value) in d:\Development\Releases\Json\Working\Src\Newtonsoft.Json\Serialization\JsonSerializerInternalWriter.cs:line 70
at Newtonsoft.Json.JsonSerializer.SerializeInternal(JsonWriter jsonWriter, Object value) in d:\Development\Releases\Json\Working\Src\Newtonsoft.Json\JsonSerializer.cs:line 451
at Newtonsoft.Json.JsonSerializer.Serialize(JsonWriter jsonWriter, Object value) in d:\Development\Releases\Json\Working\Src\Newtonsoft.Json\JsonSerializer.cs:line 443
at Newtonsoft.Json.JsonConvert.SerializeObject(Object value, Formatting formatting, JsonSerializerSettings settings) in d:\Development\Releases\Json\Working\Src\Newtonsoft.Json\JsonConvert.cs:line 591
at Route25.Events.API.Formatters.JsonPFormatter.OnWriteToStream(Type type, Object value, Stream stream, HttpContentHeaders contentHeaders, TransportContext context) in E:\Projects\Route25.Events\Route25.Events.API\Formatters\JsonPFormatter.cs:line 75
at Microsoft.ApplicationServer.Http.MediaTypeFormatter.WriteToStream(Type type, Object instance, Stream stream, HttpContentHeaders contentHeaders, TransportContext context)
at Microsoft.ApplicationServer.Http.ObjectContent.WriteToStreamInternal(Stream stream, TransportContext context)
at Microsoft.ApplicationServer.Http.ObjectContent.SerializeToStream(Stream stream, TransportContext context)
at System.Net.Http.HttpContent.CopyTo(Stream stream, TransportContext context)
at System.Net.Http.HttpContent.CopyTo(Stream stream)
at Microsoft.ApplicationServer.Http.Channels.HttpMessageEncoderFactory.HttpMessageEncoder.WriteMessage(Message message, Stream stream)
at Microsoft.ApplicationServer.Http.Channels.HttpMessageEncoderFactory.HttpMessageEncoder.WriteMessage(Message message, Int32 maxMessageSize, BufferManager bufferManager, Int32 messageOffset)
at System.ServiceModel.Channels.HttpOutput.SerializeBufferedMessage(Message message)
at System.ServiceModel.Channels.HttpOutput.SendAsyncResult.SendWithoutChannelBindingToken()
at System.ServiceModel.Channels.HttpOutput.SendAsyncResult.Send()
at System.ServiceModel.Channels.HttpOutput.SendAsyncResult..ctor(HttpOutput httpOutput, Boolean suppressEntityBody, TimeSpan timeout, AsyncCallback callback, Object state)
at System.ServiceModel.Channels.HttpOutput.BeginSend(TimeSpan timeout, AsyncCallback callback, Object state)
at System.ServiceModel.Channels.HttpRequestContext.ReplyAsyncResult.SendResponse()
at System.ServiceModel.Channels.HttpRequestContext.ReplyAsyncResult..ctor(HttpRequestContext context, Message message, TimeSpan timeout, AsyncCallback callback, Object state)
at System.ServiceModel.Channels.HttpRequestContext.OnBeginReply(Message message, TimeSpan timeout, AsyncCallback callback, Object state)
at System.ServiceModel.Activation.HostedHttpContext.OnBeginReply(Message message, TimeSpan timeout, AsyncCallback callback, Object state)
at System.ServiceModel.Channels.RequestContextBase.BeginReply(Message message, TimeSpan timeout, AsyncCallback callback, Object state)
at Microsoft.ApplicationServer.Http.Channels.HttpMessageEncodingRequestContext.BeginReply(Message message, TimeSpan timeout, AsyncCallback callback, Object state)
at Microsoft.ApplicationServer.Http.Channels.HttpMessageHandlerChannel.ReceiveAsyncResultBase.HttpMessageHandlerRequestContext.ReplyAsyncResult.ContinueReplyPath(HttpResponseMessage httpResponse)
InnerException: System.InvalidOperationException
Message=The RelationshipManager object could not be serialized. This type of object cannot be serialized when the RelationshipManager belongs to an entity object that does not implement IEntityWithRelationships.
Source=System.Data.Entity
StackTrace:
at System.Data.Objects.DataClasses.RelationshipManager.OnSerializing(StreamingContext context)
InnerException:
To replicate simply create two classes that reference each other and use the code-first dbcontext model.
If the problem really is in circular references check this thread for help. But you should not serialize your entities - if serializer tries to serialize RelationshipManager as well you should serialize custom objects instead of entities because RelationshipManager is "infrastructure" part of entity - it is not part of data you really need to serialize and most probably this part has no meaning for target system where you want to pass Json object.
Related
Not working Swagger Ui
500 : {"Message":"An error has occurred.","ExceptionMessage":"Invalid type owner for DynamicMethod.","ExceptionType":"System.ArgumentException","StackTrace":" at System.Reflection.Emit.DynamicMethod.Init(String name, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] signature, Type owner, Module m, Boolean skipVisibility, Boolean transparentMethod, StackCrawlMark& stackMark)\r\n at System.Reflection.Emit.DynamicMethod..ctor(String name, Type returnType, Type[] parameterTypes, Type owner, Boolean skipVisibility)\r\n at Newtonsoft.Json.Utilities.DynamicReflectionDelegateFactory.CreateDynamicMethod(String name, Type returnType, Type[] parameterTypes, Type owner)\r\n at Newtonsoft.Json.Utilities.DynamicReflectionDelegateFactory.CreateDefaultConstructor[T](Type type)\r\n at Newtonsoft.Json.Serialization.DefaultContractResolver.GetDefaultCreator(Type createdType)\r\n at Newtonsoft.Json.Serialization.DefaultContractResolver.InitializeContract(JsonContract contract)\r\n at Newtonsoft.Json.Serialization.DefaultContractResolver.CreateArrayContract(Type objectType)\r\n at Newtonsoft.Json.Serialization.DefaultContractResolver.CreateContract(Type objectType)\r\n at Newtonsoft.Json.Serialization.DefaultContractResolver.ResolveContract(Type type)\r\n at Swashbuckle.Swagger.SchemaRegistry.CreateInlineSchema(Type type)\r\n at Swashbuckle.Swagger.SchemaRegistry.GetOrRegister(Type type)\r\n at Swashbuckle.Swagger.SwaggerGenerator.CreateParameter(String location, ApiParameterDescription paramDesc, SchemaRegistry schemaRegistry)\r\n at Swashbuckle.Swagger.SwaggerGenerator.<>c__DisplayClass12.b__11(ApiParameterDescription paramDesc)\r\n at System.Linq.Enumerable.WhereSelectEnumerableIterator2.MoveNext()\r\n at System.Collections.Generic.List1..ctor(IEnumerable1 collection)\r\n at System.Linq.Enumerable.ToList[TSource](IEnumerable1 source)\r\n at Swashbuckle.Swagger.SwaggerGenerator.CreateOperation(ApiDescription apiDesc, SchemaRegistry schemaRegistry)\r\n at Swashbuckle.Swagger.SwaggerGenerator.CreatePathItem(IEnumerable1 apiDescriptions, SchemaRegistry schemaRegistry)\r\n at Swashbuckle.Swagger.SwaggerGenerator.<>c__DisplayClass7.<GetSwagger>b__4(IGrouping2 group)\r\n at System.Linq.Enumerable.ToDictionary[TSource,TKey,TElement](IEnumerable1 source, Func2 keySelector, Func2 elementSelector, IEqualityComparer1 comparer)\r\n at Swashbuckle.Swagger.SwaggerGenerator.GetSwagger(String rootUrl, String apiVersion)\r\n at Swashbuckle.Application.SwaggerDocsHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)\r\n at System.Net.Http.HttpMessageInvoker.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)\r\n at System.Web.Http.Dispatcher.HttpRoutingDispatcher.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)\r\n at System.Net.Http.DelegatingHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)\r\n at System.Web.Http.HttpServer.d__0.MoveNext()"} http://localhost:5352/swagger/docs/v1
When I got this error, it was because I had an error/omission in my ResponseType definition (WebApi). The compiler was fine with it, but Swagger wasn't.
Failed
[ResponseType(typeof(IEnumerable<>))]
Worked
[ResponseType(typeof(IEnumerable<string>))]
I am receiving following error and this error only comes up when multiple users are hitting the same button. Any help/ideas will be really appreciated:
System.InvalidOperationException: Collection was modified; enumeration
operation may not execute. Generated: Wed, 10 Jun 2015 07:29:06 GMT
AutoMapper.AutoMapperMappingException:
Mapping types: User -> User ApplicationSecurityManager.Service.User ->
ApplicationSecurityManager.Models.User
Destination path: User
Source value: ApplicationSecurityManager.Service.User --->
System.InvalidOperationException: Collection was modified; enumeration
operation may not execute. at
System.Collections.Generic.List1.Enumerator.MoveNextRare() at
AutoMapper.TypeMap.<get_AfterMap>b__1(Object src, Object dest) at
AutoMapper.Mappers.TypeMapObjectMapperRegistry.PropertyMapMappingStrategy.Map(ResolutionContext
context, IMappingEngineRunner mapper) at
AutoMapper.Mappers.TypeMapMapper.Map(ResolutionContext context,
IMappingEngineRunner mapper) at
AutoMapper.MappingEngine.AutoMapper.IMappingEngineRunner.Map(ResolutionContext
context) --- End of inner exception stack trace --- at
AutoMapper.MappingEngine.AutoMapper.IMappingEngineRunner.Map(ResolutionContext
context) at AutoMapper.MappingEngine.Map[TDestination](Object
source, Action1 opts) at
ApplicationSecurityManager.UserManager.LoadUser(String username) at
ApplicationSecurityManager.UserManager.get_AuthenticatedUser() at
ApplicationSecurityManager.UserManager.IsAuthenticated() at
ApplicationSecurityManager.Infrastructure.ApplicationSecurityAttribute.OnAuthorization(AuthorizationContext
filterContext) at
System.Web.Mvc.ControllerActionInvoker.InvokeAuthorizationFilters(ControllerContext
controllerContext, IList1 filters, ActionDescriptor actionDescriptor)
at
System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass25.<BeginInvokeAction>b__1e(AsyncCallback
asyncCallback, Object asyncState) at
System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult1.Begin(AsyncCallback
callback, Object state, Int32 timeout) at
System.Web.Mvc.Async.AsyncResultWrapper.Begin[TResult](AsyncCallback
callback, Object state, BeginInvokeDelegate beginDelegate,
EndInvokeDelegate1 endDelegate, Object tag, Int32 timeout) at
System.Web.Mvc.Async.AsyncResultWrapper.Begin[TResult](AsyncCallback
callback, Object state, BeginInvokeDelegate beginDelegate,
EndInvokeDelegate1 endDelegate, Object tag) at
System.Web.Mvc.Controller.<>c__DisplayClass1d.b__17(AsyncCallback
asyncCallback, Object asyncState) at
System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult1.Begin(AsyncCallback
callback, Object state, Int32 timeout) at
System.Web.Mvc.Async.AsyncResultWrapper.Begin[TResult](AsyncCallback
callback, Object state, BeginInvokeDelegate beginDelegate,
EndInvokeDelegate1 endDelegate, Object tag, Int32 timeout) at
System.Web.Mvc.Controller.BeginExecuteCore(AsyncCallback callback,
Object state) at
System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult1.Begin(AsyncCallback
callback, Object state, Int32 timeout) at
System.Web.Mvc.Async.AsyncResultWrapper.Begin[TResult](AsyncCallback
callback, Object state, BeginInvokeDelegate beginDelegate,
EndInvokeDelegate1 endDelegate, Object tag, Int32 timeout) at
System.Web.Mvc.Async.AsyncResultWrapper.Begin(AsyncCallback callback,
Object state, BeginInvokeDelegate beginDelegate, EndInvokeDelegate
endDelegate, Object tag) at
System.Web.Mvc.Controller.BeginExecute(RequestContext requestContext,
AsyncCallback callback, Object state) at
System.Web.Mvc.MvcHandler.<>c__DisplayClass8.b__2(AsyncCallback
asyncCallback, Object asyncState) at
System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult1.Begin(AsyncCallback
callback, Object state, Int32 timeout) at
System.Web.Mvc.Async.AsyncResultWrapper.Begin[TResult](AsyncCallback
callback, Object state, BeginInvokeDelegate beginDelegate,
EndInvokeDelegate1 endDelegate, Object tag, Int32 timeout) at
System.Web.Mvc.Async.AsyncResultWrapper.Begin(AsyncCallback callback,
Object state, BeginInvokeDelegate beginDelegate, EndInvokeDelegate
endDelegate, Object tag) 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)
This is the constructor where i think the aftermap is the problem but when debugging i don't receive the error.
Public Sub New(environmentCode As String, applicationCode As String)
MyBase.New(environmentCode, applicationCode)
SOBaseUrl = System.Configuration.ConfigurationManager.AppSettings(Enums.AppSettingKeys.SOBaseUrl.ToString())
If Not String.IsNullOrEmpty(SOBaseUrl) Then
SOBaseUrl = SOBaseUrl.TrimEnd("/")
End If
'Setup mapping.
Mapper.CreateMap(Of Service.User, Models.User)() _
.ForMember(Function(dest As Models.User) dest.ENumber, Sub(opt) opt.MapFrom(Function(src As Service.User) src.INumber)) _
.AfterMap(Sub(src As Service.User, dest As Models.User)
dest.Groups = New List(Of String)
Using service = ApplicationSecurityManager.Service.Factory.GetService()
Dim applicationPermissions = service.LoadPermissionsForUser(dest.Username, MyBase.EnvironmentCode)
If (Not applicationPermissions Is Nothing AndAlso applicationPermissions.Any(Function(x) x.Code = MyBase.ApplicationCode)) Then
dest.Groups = applicationPermissions.Single(Function(x) x.Code = MyBase.ApplicationCode).GroupNames.ToList()
End If
End Using
End Sub)
Depenendency Injection Mapping:
container.RegisterType(Of IUserManager, UserManager)(New PerThreadLifetimeManager(),
New InjectionConstructor(
ConfigurationManager.AppSettings(Common.Enums.AppSettingKeys.Environment.ToString()),
ConfigurationManager.AppSettings(Common.Enums.AppSettingKeys.ApplicationCode.ToString()))
)
In the saveUserResponse, the error is getting thrown.
Public Function Create(user As Common.Models.User, approve As Boolean) As SO.Common.Models.User Implements IUserProvider.Save
Dim saveUserResponse = UserManager.SaveUser(Mapper.Map(Of ApplicationSecurityManager.Service.User)(user))
If Not String.IsNullOrEmpty(saveUserResponse.ErrorMessage) Then
'The Security system returned an error.
Throw New Exception("Security Service returned error: " & saveUserResponse.ErrorMessage)
End If
'Return the username.
Return Mapper.Map(Of Common.Models.User)(saveUserResponse.User)
End Function
This is caused when multiple users modify the same user.Groups collection in the AfterMap() method of your mapping. To avoid this, lock the code that is processing the collection. For example:
'class level object
private object _myLock = New object()
'Setup mapping.
Mapper.CreateMap(Of Service.User, Models.User)() _
.ForMember(Function(dest As Models.User) dest.ENumber, Sub(opt) opt.MapFrom(Function(src As Service.User) src.INumber)) _
.AfterMap(Sub(src As Service.User, dest As Models.User)
SyncLock _myLock
dest.Groups = New List(Of String)
Using service = ApplicationSecurityManager.Service.Factory.GetService()
Dim applicationPermissions = service.LoadPermissionsForUser(dest.Username, MyBase.EnvironmentCode)
If (Not applicationPermissions Is Nothing AndAlso applicationPermissions.Any(Function(x) x.Code = MyBase.ApplicationCode)) Then
dest.Groups = applicationPermissions.Single(Function(x) x.Code = MyBase.ApplicationCode).GroupNames.ToList()
End If
End Using
End SyncLock
End Sub)
This is pretty common mistake modifying a collection while iterating it. Is it possible you are leaving something out here we can't see? Anyway's in the code that you have provided there is not any such scenario from what I can see. This means that you might be calling this in a multi-threaded environment and the collection is being modified in some other thread.
What can you try?
Look into locking your enumeration so only one thread at a time can be accessed. It's possible that it's being accessed multiple time's when user's are clicking on the button.
Here's a good link to help you out: http://weblogs.asp.net/leftslipper/mvc-locking-the-routecollection
I'm trying to create a Facebook app using default Facebook Template for Asp.Net MVC. I'm registered in developers.facebook.com and created an app.
I've created the ASP.NET based MVC webpage using following steps:
I've enabled the SSL property to True.
Copied the SSL URL (in my case it was localhost:44301).
In Solution Explorer, right clicked the MvcFBTestApp and select Properties.
Select the Web tab. Paste the SSL URL into the Project Url box, then click Create Virtual
Directory.
I've used the App ID/App Secret and Namespace of facebook App and configured the web.config file of my MVCApp with these settings.
Saved the project and Run the project.
Now if I run the app it request for Facebook login and logs in to facebook. But after that it generates following error instead of showing default MVC webpage. Appreciate if anyone can give me guidance.
Server Error in '/' Application.
Could not convert string to integer: public_profile. Path 'data[0].permission', line 1, position 39.
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: Newtonsoft.Json.JsonReaderException: Could not convert string to integer: public_profile. Path 'data[0].permission', line 1, position 39.
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:
[JsonReaderException: Could not convert string to integer: public_profile. Path 'data[0].permission', line 1, position 39.]
Newtonsoft.Json.JsonReader.ReadAsInt32Internal() +921
Newtonsoft.Json.JsonTextReader.ReadAsInt32() +39
Newtonsoft.Json.Serialization.JsonSerializerInternalReader.ReadForType(JsonReader reader, JsonContract contract, Boolean hasConverter) +228
Newtonsoft.Json.Serialization.JsonSerializerInternalReader.PopulateDictionary(IWrappedDictionary wrappedDictionary, JsonReader reader, JsonDictionaryContract contract, JsonProperty containerProperty, String id) +1469
Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateObject(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, Object existingValue) +866
Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateValueInternal(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, Object existingValue) +184
Newtonsoft.Json.Serialization.JsonSerializerInternalReader.PopulateList(IWrappedCollection wrappedList, JsonReader reader, JsonArrayContract contract, JsonProperty containerProperty, String id) +1180
Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateList(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, Object existingValue, String id) +698
Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateValueInternal(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, Object existingValue) +233
Newtonsoft.Json.Serialization.JsonSerializerInternalReader.SetPropertyValue(JsonProperty property, JsonConverter propertyConverter, JsonContainerContract containerContract, JsonProperty containerProperty, JsonReader reader, Object target) +598
Newtonsoft.Json.Serialization.JsonSerializerInternalReader.PopulateObject(Object newObject, JsonReader reader, JsonObjectContract contract, JsonProperty member, String id) +1799
Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateObject(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, Object existingValue) +517
Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateValueInternal(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, Object existingValue) +184
Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize(JsonReader reader, Type objectType, Boolean checkAdditionalContent) +740
Newtonsoft.Json.JsonSerializer.DeserializeInternal(JsonReader reader, Type objectType) +1143
Newtonsoft.Json.JsonSerializer.Deserialize(JsonReader reader, Type objectType) +47
Newtonsoft.Json.JsonConvert.DeserializeObject(String value, Type type, JsonSerializerSettings settings) +193
Newtonsoft.Json.JsonConvert.DeserializeObject(String value, Type type) +44
Facebook.FacebookClient.ProcessResponse(HttpHelper httpHelper, String responseString, Type resultType, Boolean containsEtag, IList1 batchEtags) +2070
Facebook.FacebookClient.Api(HttpMethod httpMethod, String path, Object parameters, Type resultType) +1168
Facebook.FacebookClient.Get(String path, Object parameters, Type resultType) +52
Facebook.FacebookClient.Get(String path, Object parameters) +139
Facebook.FacebookClient.Get(String path) +100
Microsoft.AspNet.Mvc.Facebook.Client.FacebookClientExtensions.GetCurrentUserPermissions(FacebookClient client) +74
Microsoft.AspNet.Mvc.Facebook.Providers.DefaultFacebookPermissionService.GetUserPermissions(String userId, String accessToken) +217
Microsoft.AspNet.Mvc.Facebook.Authorization.FacebookAuthorizeFilter.OnAuthorization(AuthorizationContext filterContext) +5182
System.Web.Mvc.ControllerActionInvoker.InvokeAuthorizationFilters(ControllerContext controllerContext, IList1 filters, ActionDescriptor actionDescriptor) +143
System.Web.Mvc.Async.<>c__DisplayClass25.b__1e(AsyncCallback asyncCallback, Object asyncState) +978
System.Web.Mvc.Async.WrappedAsyncResult1.Begin(AsyncCallback callback, Object state, Int32 timeout) +161
System.Web.Mvc.Async.AsyncResultWrapper.Begin(AsyncCallback callback, Object state, BeginInvokeDelegate beginDelegate, EndInvokeDelegate1 endDelegate, Object tag, Int32 timeout) +92
System.Web.Mvc.Async.AsyncResultWrapper.Begin(AsyncCallback callback, Object state, BeginInvokeDelegate beginDelegate, EndInvokeDelegate1 endDelegate, Object tag) +53
System.Web.Mvc.Async.AsyncControllerActionInvoker.BeginInvokeAction(ControllerContext controllerContext, String actionName, AsyncCallback callback, Object state) +523
System.Web.Mvc.<>c__DisplayClass1d.<BeginExecuteCore>b__17(AsyncCallback asyncCallback, Object asyncState) +83
System.Web.Mvc.Async.WrappedAsyncResult1.Begin(AsyncCallback callback, Object state, Int32 timeout) +161
System.Web.Mvc.Async.AsyncResultWrapper.Begin(AsyncCallback callback, Object state, BeginInvokeDelegate beginDelegate, EndInvokeDelegate1 endDelegate, Object tag, Int32 timeout) +92
System.Web.Mvc.Async.AsyncResultWrapper.Begin(AsyncCallback callback, Object state, BeginInvokeDelegate beginDelegate, EndInvokeDelegate endDelegate, Object tag, Int32 timeout) +97
System.Web.Mvc.Async.AsyncResultWrapper.Begin(AsyncCallback callback, Object state, BeginInvokeDelegate beginDelegate, EndInvokeDelegate endDelegate, Object tag) +53
System.Web.Mvc.Controller.BeginExecuteCore(AsyncCallback callback, Object state) +501
System.Web.Mvc.Async.WrappedAsyncResult1.Begin(AsyncCallback callback, Object state, Int32 timeout) +161
System.Web.Mvc.Async.AsyncResultWrapper.Begin(AsyncCallback callback, Object state, BeginInvokeDelegate beginDelegate, EndInvokeDelegate1 endDelegate, Object tag, Int32 timeout) +92
System.Web.Mvc.Async.AsyncResultWrapper.Begin(AsyncCallback callback, Object state, BeginInvokeDelegate beginDelegate, EndInvokeDelegate endDelegate, Object tag, Int32 timeout) +97
System.Web.Mvc.Async.AsyncResultWrapper.Begin(AsyncCallback callback, Object state, BeginInvokeDelegate beginDelegate, EndInvokeDelegate endDelegate, Object tag) +53
System.Web.Mvc.Controller.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state) +417
System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state) +49
System.Web.Mvc.<>c__DisplayClass8.<BeginProcessRequest>b__2(AsyncCallback asyncCallback, Object asyncState) +127
System.Web.Mvc.Async.WrappedAsyncResult1.Begin(AsyncCallback callback, Object state, Int32 timeout) +161
System.Web.Mvc.Async.AsyncResultWrapper.Begin(AsyncCallback callback, Object state, BeginInvokeDelegate beginDelegate, EndInvokeDelegate`1 endDelegate, Object tag, Int32 timeout) +92
System.Web.Mvc.Async.AsyncResultWrapper.Begin(AsyncCallback callback, Object state, BeginInvokeDelegate beginDelegate, EndInvokeDelegate endDelegate, Object tag, Int32 timeout) +97
System.Web.Mvc.Async.AsyncResultWrapper.Begin(AsyncCallback callback, Object state, BeginInvokeDelegate beginDelegate, EndInvokeDelegate endDelegate, Object tag) +53
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) +373
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state) +88
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData) +50
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +301
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155
Thanks & BR,
Ahmed
This a parsing problem inside the Newtonsoft.Json library. Some string can't be parsed into an integer.
Try to ensure that you are installing the latest updated version of the Newtonsoft.Json library.
Hello we are creating a web API in MVC4 with NHibernate. But when we are calling the web API it throws us the Error. Here is the Error.
<Error><Message>An error has occurred.</Message><ExceptionMessage>The 'ObjectContent`1' type failed to serialize the response body for content type 'application/xml; charset=utf-8'.</ExceptionMessage><ExceptionType>System.InvalidOperationException</ExceptionType><StackTrace/><InnerException><Message>An error has occurred.</Message><ExceptionMessage>Type 'NHibernate.Collection.Generic.PersistentGenericSet`1[[MvcAngular.Models.BankAccount, MvcAngular, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]' with data contract name 'ArrayOfBankAccount:http://schemas.datacontract.org/2004/07/MvcAngular.Models' 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.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 WriteCustomerInfoToXml(XmlWriterDelegator , Object , XmlObjectSerializerWriteContext , ClassDataContract )
at System.Runtime.Serialization.ClassDataContract.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.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 WriteArrayOfCustomerInfoToXml(XmlWriterDelegator , Object , XmlObjectSerializerWriteContext , CollectionDataContract )
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.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.XmlObjectSerializer.WriteObjectHandleExceptions(XmlWriterDelegator writer, Object graph)
at System.Runtime.Serialization.DataContractSerializer.WriteObject(XmlWriter writer, Object graph)
at System.Net.Http.Formatting.XmlMediaTypeFormatter.<>c__DisplayClass7.<WriteToStreamAsync>b__6()
at System.Threading.Tasks.TaskHelpers.RunSynchronously(Action action, CancellationToken token)</StackTrace></InnerException></Error>
We are successfully getting the Result in the WebApi. here is the schema of the Classess. we have Used ISET int the parent class
public class CustomerInfo
{
int _CustomerId;
public virtual int CustomerId
{
get { return _CustomerId; }
set { _CustomerId = value; }
}
string _Name;
[Required]
public virtual string Name
{
get { return _Name; }
set { _Name = value; }
}
public virtual ISet<BankAccount> BankAccounts { get; set; }
public virtual void SetBankAccount(ISet<BankAccount> bankact)
{
this.BankAccounts = bankact;
}
public virtual ISet<BankAccount> GetBankAccounts()
{
return this.BankAccounts;
}
}
AND This is the Get Method of Web API
public IList<CustomerInfo> Get()
{
CustomerInfoDAL cd = new CustomerInfoDAL();
var lst = cd.GetCustomer();
return lst;
}
We are successfully getting the Result in lst. but while showing that through Web api it shows us this Error.
Actually Nhibernate ISET<> is not supported by serialization. we have to fetch that though JSON. ie you can use Fiddler to see the result.
I asked before a question here, and I read this question/answers about multi-threading and I know those solutions. But today I get a new problem. When we are using commands (or where we can access the original code to manage and modify it) the async-decorator that suggested in above answers works. But when MVC creates a new thread itself, what can we do? e.g. I have a custom role provider (works with DbContext), and I get this error:
The operation cannot be completed because the DbContext has been disposed.
And here is stack trace:
[InvalidOperationException: The operation cannot be completed because the DbContext has been disposed.]
System.Data.Entity.Internal.InternalContext.CheckContextNotDisposed() +67
System.Data.Entity.Internal.LazyInternalContext.InitializeContext() +34
System.Data.Entity.Internal.Linq.DbQueryProvider.Execute(Expression expression) +22
System.Linq.Queryable.Any(IQueryable1 source, Expression1 predicate) +265
MyProject.MyRoleProvider.IsUserInRole(String username, String roleName) in ...
System.Web.Security.Roles.IsUserInRole(String username, String roleName) +263
MyProject.MyPrincipal.IsInRole(String role) in ...
System.Linq.Enumerable.Any(IEnumerable1 source, Func2 predicate) +146
System.Web.Mvc.AuthorizeAttribute.AuthorizeCore(HttpContextBase httpContext) +200
System.Web.Mvc.AuthorizeAttribute.OnAuthorization(AuthorizationContext filterContext) +159
System.Web.Mvc.ControllerActionInvoker.InvokeAuthorizationFilters(ControllerContext controllerContext, IList`1 filters, ActionDescriptor actionDescriptor) +96
System.Web.Mvc.Async.<>c__DisplayClass25.b__1e(AsyncCallback asyncCallback, Object asyncState) +446
System.Web.Mvc.Async.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +130
System.Web.Mvc.Async.AsyncControllerActionInvoker.BeginInvokeAction(ControllerContext controllerContext, String actionName, AsyncCallback callback, Object state) +302
System.Web.Mvc.<>c__DisplayClass1d.b__17(AsyncCallback asyncCallback, Object asyncState) +30
System.Web.Mvc.Async.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +130
System.Web.Mvc.Controller.BeginExecuteCore(AsyncCallback callback, Object state) +382
System.Web.Mvc.Async.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +130
System.Web.Mvc.Controller.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state) +317
System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state) +15
System.Web.Mvc.<>c__DisplayClass8.b__2(AsyncCallback asyncCallback, Object asyncState) +71
System.Web.Mvc.Async.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +130
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) +249
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state) +50
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData) +16
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +301
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155
As you can see, MyProject.MyRoleProvider.IsUserInRole invoked asynchronously, which I did not start it and its invoking async by MVC itself. So I have not any control on it. My provider ctor is:
public MyRoleProvider() {
_context = MyIoCWrapper.GetService();
}
It seems when MyRoleProvider instantiated, HttpContext is not null, and when IsInRole called, HttpContext is null.
If I want to start a new life scope, it will be used just once, and if MVC starts a new thread, I will have a new DbContext too. I confused to finding a solution. Have you any one?
How can I start a new life scope for all background threads -I start them or MVC starts them?
Your problem is in fact unrelated to running controllers asynchronously, but is a general problem of controlling the lifetime of objects.
You probably registered your MyRoleProvider in the web.config of the application, or perhaps registered it through code. Eitherway, the MyRoleProvider is a singleton, there is just a single instance of that class during the lifetime of the application.
The MyRoleProvider however depends on a DbContext which has a lifestyle that is shorter (Per Web Request or hybrid in your case), which means you can't cache that DbContext during the lifetime of your MyRoleProver, since that would 'promote' the lifestyle of that DbContext to singleton as well. The _context = MyIoCWrapper.GetService(); line seems to indicate that you are caching that DbContext.
In this case you will have to resolve the DbContext instance on each method call. So instead, your IsUserInRole would look something like this:
public bool IsUserInRole(String username, String roleName)
{
var context = MyIoCWrapper.GetService();
return context.Roles
.Any(r => r.Name == roleName && r.User.Name == username);
}