XML Serialization Error In Nhibernate with MVC4 Web API - asp.net-mvc

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.

Related

FormatException: Input string was not in a correct format. - Changed ASP.net Core Identity PK to int

I've been working on this for the last 3 hours and haven't found a good resource or solution to this problem. I've followed the directions found in Microsoft's documentation to change my ASP.net Privatekey from a string to an int. Since then, I have been presented with the following error:
FormatException: Input string was not in a correct format.
The app will not load past this method in the program.cs class:
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
I have hit a roadblock and any help with this issue would be appreciated.
Asp.net Error Stack:
FormatException: Input string was not in a correct format.
System.Number.ThrowOverflowOrFormatException(ParsingStatus status, TypeCode type)
ArgumentException: 4c3ccce2-61cd-4315-9cf2-99933f6797ed is not a valid value for Int32. (Parameter 'value')
System.ComponentModel.BaseNumberConverter.ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
Stack Query Cookies Headers Routing
FormatException: Input string was not in a correct format.
System.Number.ThrowOverflowOrFormatException(ParsingStatus status, TypeCode type)
int.Parse(string s, NumberStyles style, IFormatProvider provider)
System.ComponentModel.Int32Converter.FromString(string value, NumberFormatInfo formatInfo)
System.ComponentModel.BaseNumberConverter.ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
Show raw exception details
System.FormatException: Input string was not in a correct format.
at System.Number.ThrowOverflowOrFormatException(ParsingStatus status, TypeCode type)
at System.Int32.Parse(String s, NumberStyles style, IFormatProvider provider)
at System.ComponentModel.Int32Converter.FromString(String value, NumberFormatInfo formatInfo)
at System.ComponentModel.BaseNumberConverter.ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, Object value)
ArgumentException: 4c3ccce2-61cd-4315-9cf2-99933f6797ed is not a valid value for Int32. (Parameter 'value')
System.ComponentModel.BaseNumberConverter.ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
System.ComponentModel.TypeConverter.ConvertFromInvariantString(string text)
Microsoft.AspNetCore.Identity.UserStoreBase<TUser, TKey, TUserClaim, TUserLogin, TUserToken>.ConvertIdFromString(string id)
Microsoft.AspNetCore.Identity.EntityFrameworkCore.UserStore<TUser, TRole, TContext, TKey, TUserClaim, TUserRole, TUserLogin, TUserToken, TRoleClaim>.FindByIdAsync(string userId, CancellationToken cancellationToken)
Microsoft.AspNetCore.Identity.UserManager.FindByIdAsync(string userId)
Microsoft.AspNetCore.Identity.UserManager.GetUserAsync(ClaimsPrincipal principal)
Microsoft.AspNetCore.Identity.SignInManager.ValidateSecurityStampAsync(ClaimsPrincipal principal)
Microsoft.AspNetCore.Identity.SecurityStampValidator.ValidateAsync(CookieValidatePrincipalContext context)
Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationHandler.HandleAuthenticateAsync()
Microsoft.AspNetCore.Authentication.AuthenticationHandler.AuthenticateAsync()
Microsoft.AspNetCore.Authentication.AuthenticationService.AuthenticateAsync(HttpContext context, string scheme)
Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
Show raw exception details
System.ArgumentException: 4c3ccce2-61cd-4315-9cf2-99933f6797ed is not a valid value for Int32. (Parameter 'value')
---> System.FormatException: Input string was not in a correct format.
at System.Number.ThrowOverflowOrFormatException(ParsingStatus status, TypeCode type)
at System.Int32.Parse(String s, NumberStyles style, IFormatProvider provider)
at System.ComponentModel.Int32Converter.FromString(String value, NumberFormatInfo formatInfo)
at System.ComponentModel.BaseNumberConverter.ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, Object value)
--- End of inner exception stack trace ---
at System.ComponentModel.BaseNumberConverter.ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, Object value)
at System.ComponentModel.TypeConverter.ConvertFromInvariantString(String text)
at Microsoft.AspNetCore.Identity.UserStoreBase5.ConvertIdFromString(String id) at Microsoft.AspNetCore.Identity.EntityFrameworkCore.UserStore9.FindByIdAsync(String userId, CancellationToken cancellationToken)
at Microsoft.AspNetCore.Identity.UserManager1.FindByIdAsync(String userId) at Microsoft.AspNetCore.Identity.UserManager1.GetUserAsync(ClaimsPrincipal principal)
at Microsoft.AspNetCore.Identity.SignInManager1.ValidateSecurityStampAsync(ClaimsPrincipal principal) at Microsoft.AspNetCore.Identity.SecurityStampValidator1.ValidateAsync(CookieValidatePrincipalContext context)
at Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationHandler.HandleAuthenticateAsync()
at Microsoft.AspNetCore.Authentication.AuthenticationHandler`1.AuthenticateAsync()
at Microsoft.AspNetCore.Authentication.AuthenticationService.AuthenticateAsync(HttpContext context, String scheme)
at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context
I think the problem may be that the login of your previous user may be completed when the ID is a string.
You now change it to int, so now it no longer knows what to do with the string.
I think the simplest solution is that you should delete the cookie, log out and log in again (use int instead).

Catel UIVisualizerService issue with Syncfusion sfDatagrid

I have created a project that makes use of Catel, Entity Framework 6 and Syncfusion Community Edition. Specifically I am using the sfDataGrid from Syncfusion.
I have come across an issue that has me completely stumped, maybe someone out there could point me in the right direction.
I have a Catel UserControl with a sfDataGrid in it. The ViewModel has an ObservableCollection (Catel Property) of the data I am using as the ItemsSource for the sfDataGrid. I have filtering enabled on the sfDataGrid. Here is the code for the sfDataGrid:
<sync:SfDataGrid
x:Name="ItemsDataGrid"
ItemsSource="{Binding MyItems, Mode=OneWay}"
SelectedItem="{Binding MyItem, Mode=TwoWay}"
AutoGenerateColumns="False"
AllowFiltering="True"
AllowResizingColumns="True"
GridCopyOption="IncludeHeaders"
GridPasteOption="None"
ShowGroupDropArea="True"
ShowRowHeader="True"
DataFetchSize="50">
<!-- Columns -->
</sync:SfDataGrid>
I add a new Item to the collection on a different view and then I save it to the datacontext and refresh the list:
private async void OnNewMyItemExecute()
{
MyItem= new MyItem();
MyItemsRepository.Add(MyItem);
var myItemsViewModel = TypeFactory
.Default
.CreateInstanceWithParametersAndAutoCompletion<myItemsViewModel >(MyItem); //the construction has parameters for IUIVisualizerService, IPleaseWaitService, etc.
if (await _UIVisualizerService.ShowDialogAsync(myItemsViewModel) ?? true)
{
var myItem= myItemsViewModel.MyItem;
await InitializeAsync();
MyItem = myItem;
}
else
{
_UnitOfWorkService.Rollback(); //just undo some changes
MyItem = null;
}
UnitOfWork.SaveChanges();
}
Creating a new Item is not a problem at all, the thing that is weird is that after I created a new Item and then attempt to filter grid on any column of the sfDataGrid (click the filter button in the column header, a filter popup opens, enter a value in the criteria textbox and click 'OK'), I get this:
MyProject.vshost.exe Warning: 0 : 17:57:49:075 => [WARNING]
[Catel.Services.UIVisualizerService] [8] An error occurred, returning
null since we don't know the result | [TargetInvocationException]
System.Reflection.TargetInvocationException: Exception has been thrown
by the target of an invocation. --->
System.Reflection.TargetInvocationException: Exception has been thrown
by the target of an invocation. ---> System.InvalidCastException:
Unable to cast object of type 'MyProject.Domain.MyItem' to type
'System.Data.Entity.DynamicProxies.MyItem_4CA6F59AB53174892ED9EFBC1D3CC07B862579FC3C5733C6CF4DE857907CFF9C'.
at lambda_method(Closure , MyItem ) --- End of inner exception
stack trace --- at System.RuntimeMethodHandle.InvokeMethod(Object
target, Object[] arguments, Signature sig, Boolean constructor) at
System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj,
Object[] parameters, Object[] arguments) at
System.Delegate.DynamicInvokeImpl(Object[] args) at
System.Delegate.DynamicInvoke(Object[] args) at
Syncfusion.Data.QueryableCollectionView.<>c__DisplayClass3.b__1(Object
o) at Syncfusion.Data.QueryableCollectionView.FilterRecord(Object
record) at
Syncfusion.Data.EnumerableRecordsWrapper..ctor(IEnumerable source,
CollectionViewAdv view) at
Syncfusion.Data.EnumerableRecordsWrapper.CreateNew(IEnumerable source,
CollectionViewAdv view) at
Syncfusion.Data.QueryableCollectionView.CreateRecords() at
Syncfusion.Data.CollectionViewAdv.EnsureInitialized() at
Syncfusion.Data.CollectionViewAdv.get_Records() at
Syncfusion.Data.CollectionViewAdv.EnsureRecordsInitialized() at
Syncfusion.Data.CollectionViewAdv.Refresh() at
Syncfusion.Data.QueryableCollectionView.RefreshFilter() at
Syncfusion.Data.CollectionViewAdv.ApplyFilters() at
Syncfusion.Data.CollectionViewAdv.set_FilterPredicates(ObservableCollection1
value) at Syncfusion.UI.Xaml.Grid.GridModel.FilterColumn(GridColumn
column, List1 filterPredicates) at
Syncfusion.UI.Xaml.Grid.GridFilterControl.RefreshFilter() at
Syncfusion.UI.Xaml.Grid.GridFilterControl.b__10(Object
s, RunWorkerCompletedEventArgs e) at
System.ComponentModel.BackgroundWorker.OnRunWorkerCompleted(RunWorkerCompletedEventArgs
e) at
System.ComponentModel.BackgroundWorker.AsyncOperationCompleted(Object
arg) at
System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate
callback, Object args, Int32 numArgs) at
System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source,
Delegate callback, Object args, Int32 numArgs, Delegate catchHandler)
at System.Windows.Threading.DispatcherOperation.InvokeImpl() at
System.Windows.Threading.DispatcherOperation.InvokeInSecurityContext(Object
state) at
System.Threading.ExecutionContext.RunInternal(ExecutionContext
executionContext, ContextCallback callback, Object state, Boolean
preserveSyncCtx) at
System.Threading.ExecutionContext.Run(ExecutionContext
executionContext, ContextCallback callback, Object state, Boolean
preserveSyncCtx) at
System.Threading.ExecutionContext.Run(ExecutionContext
executionContext, ContextCallback callback, Object state) at
System.Windows.Threading.DispatcherOperation.Invoke() at
System.Windows.Threading.Dispatcher.ProcessQueue() at
System.Windows.Threading.Dispatcher.WndProcHook(IntPtr hwnd, Int32
msg, IntPtr wParam, IntPtr lParam, Boolean& handled) at
MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam,
IntPtr lParam, Boolean& handled) at
MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o) at
System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate
callback, Object args, Int32 numArgs) at
System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source,
Delegate callback, Object args, Int32 numArgs, Delegate catchHandler)
at
System.Windows.Threading.Dispatcher.LegacyInvokeImpl(DispatcherPriority
priority, TimeSpan timeout, Delegate method, Object args, Int32
numArgs) at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd,
Int32 msg, IntPtr wParam, IntPtr lParam) at
MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg) at
System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame
frame) at
System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame frame)
at System.Windows.Window.ShowHelper(Object booleanBox) at
System.Windows.Window.Show() at System.Windows.Window.ShowDialog()
--- End of inner exception stack trace --- at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[]
arguments, Signature sig, Boolean constructor) at
System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj,
Object[] parameters, Object[] arguments) 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
Catel.Services.UIVisualizerService.<>c__DisplayClass23_0.b__0()
in
C:\CI_WS\Ws\86058\Source\Catel\src\Catel.MVVM\Catel.MVVM.Shared\Services\UIVisualizerService.cs:line
499
This is the method of UIVisualizerService with Line 499:
protected virtual bool? ShowWindow(FrameworkElement window, bool showModal)
{
if (showModal)
{
var showDialogMethodInfo = window.GetType().GetMethodEx("ShowDialog");
if (showDialogMethodInfo != null)
{
// Child window does not have a ShowDialog, so not null is allowed
bool? result = null;
window.Dispatcher.InvokeIfRequired(() =>
{
// Safety net to prevent crashes when this is the main window
try
{
result = showDialogMethodInfo.Invoke(window, null) as bool?; //Line 499
}
catch (Exception ex)
{
Log.Warning(ex, "An error occurred, returning null since we don't know the result");
}
});
return result;
}
Log.Warning("Method 'ShowDialog' not found on '{0}', falling back to 'Show'", window.GetType().Name);
}
I have tried opening MyItemsView with .ShowAsync(), .ShowDialogAsync() and before I upgraded to Catel 4.4 I also used .ShowDialog(), but it made no difference. I could turn Proxy Creation off in EF, but that would cause a lot of changes I have to make in my project (no more lazy loading for me, and that is not an option). I do believe the problem being the new Item I add not being a Dynamic Proxy, and getting it to be a Dynamic Proxy would probably solve the issue, but I have tried loading all the data from the DbContext again, but it also does not solve the problem.
Any advice would be appreciated.
The issue is this:
System.InvalidCastException: Unable to cast object of type 'MyProject.Domain.MyItem' to type 'System.Data.Entity.DynamicProxies.MyItem_4CA6F59AB53174892ED9EFBC1D3CC07B862579FC3C5733C6CF4DE857907CFF9C'.
The reason is, of course, that you are trying to cast a base type to a derived type (which it simply isn't). That this eventually results in the window closing is because an exception happens, but that isn't the real problem.
This exception occurs in the FilterRecord method of the grid. I am not sure if that is something you have written yourself or something that is inside syncfusion, but that is the place to look.
The reason you have generated proxies is because you enabled (or it's enabled by default) the proxy generation of the Entity Framework DbContext.

Xamarin 4 issue: iOS AOT problems which are not present in Xamarin 3. What is the solution?

I have built the very same code base with the latest Xamarin 4 tools (Xamarin Studio 5.10.1, Xamarin iOS 9.2.1, Mono MDK 4.2.1) on Mac and the latest Xamarin 3 (Xamarin Studio 5.9.8.0, Xamarin.iOS 9.1.0.31, Mono MDK 4.0.5.1) tools.
The Xamarin 3 builds work just fine, the Xamarin 4 do not. Here is the AOT problem produced by the MS ADAL library:
System.ExecutionEngineException: Attempting to JIT compile method
'(wrapper runtime-invoke) <Module>:runtime_invoke_bool_Nullable`1<DateTimeOffset> (object,intptr,intptr,intptr)'
while running with --aot-only.
See http://docs.xamarin.com/ios/about/limitations for more information.
And the complete stacktrace:
System.Reflection.MonoMethod.Invoke(object obj, BindingFlags invokeAttr, Binder binder, object[] parameters, CultureInfo culture)
System.Reflection.MethodBase.Invoke(object obj, object[] parameters)
System.Runtime.Serialization.Json.JsonFormatWriterInterpreter.UnwrapNullableObject(Func<_> memberValue, ref Type memberType, ref bool isNull)
System.Runtime.Serialization.Json.JsonFormatWriterInterpreter.WriteValue(Type memberType, object memberValue)
System.Runtime.Serialization.Json.JsonFormatWriterInterpreter.WriteMembers(ClassDataContract classContract, ExtensionDataObject extensionData, ClassDataContract derivedMostClassContract)
System.Runtime.Serialization.Json.JsonFormatWriterInterpreter.WriteClass(ClassDataContract classContract)
System.Runtime.Serialization.Json.JsonFormatWriterInterpreter.WriteToJson(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContextComplexJson context, ClassDataContract dataContract, XmlDictionaryString[] memberNames)
System.Runtime.Serialization.Json.JsonFormatWriterGenerator.CriticalHelper.<GenerateClassWriter>c__AnonStorey0.<>m__0(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContextComplexJson context, ClassDataContract dataContract, XmlDictionaryString[] memberNames)
System.Runtime.Serialization.Json.JsonClassDataContract.WriteJsonValueCore(XmlWriterDelegator jsonWriter, object obj, XmlObjectSerializerWriteContextComplexJson context, RuntimeTypeHandle declaredTypeHandle)
System.Runtime.Serialization.Json.JsonDataContract.WriteJsonValue(XmlWriterDelegator jsonWriter, object obj, XmlObjectSerializerWriteContextComplexJson context, RuntimeTypeHandle declaredTypeHandle)
System.Runtime.Serialization.Json.DataContractJsonSerializer.WriteJsonValue(JsonDataContract contract, XmlWriterDelegator writer, object graph, XmlObjectSerializerWriteContextComplexJson context, RuntimeTypeHandle declaredTypeHandle)
System.Runtime.Serialization.Json.XmlObjectSerializerWriteContextComplexJson.WriteDataContractValue(DataContract dataContract, XmlWriterDelegator xmlWriter, object obj, RuntimeTypeHandle declaredTypeHandle)
System.Runtime.Serialization.XmlObjectSerializerWriteContext.SerializeWithoutXsiType(DataContract dataContract, XmlWriterDelegator xmlWriter, object obj, RuntimeTypeHandle declaredTypeHandle)
System.Runtime.Serialization.XmlObjectSerializerWriteContext.InternalSerialize(XmlWriterDelegator xmlWriter, object obj, bool isDeclaredType, bool writeXsiType, int declaredTypeID, RuntimeTypeHandle declaredTypeHandle)
System.Runtime.Serialization.XmlObjectSerializerWriteContextComplex.InternalSerialize(XmlWriterDelegator xmlWriter, object obj, bool isDeclaredType, bool writeXsiType, int declaredTypeID, RuntimeTypeHandle declaredTypeHandle)
System.Runtime.Serialization.XmlObjectSerializerWriteContext.InternalSerializeReference(XmlWriterDelegator xmlWriter, object obj, bool isDeclaredType, bool writeXsiType, int declaredTypeID, RuntimeTypeHandle declaredTypeHandle)
System.Reflection.MonoMethod.InternalInvoke(MonoMethod, object, object[], ref Exception)(wrapper managed-to-native)
System.Reflection.MonoMethod.Invoke(object obj, BindingFlags invokeAttr, Binder binder, object[] parameters, CultureInfo culture)
Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext.<AcquireTokenCommonAsync>d__68.MoveNext()
Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext.<AcquireTokenAsync>d__4b.MoveNext()
I would appreciate any constructive explanation of what has changed and why this this thing is no longer working.
Is this related to some Mono implementation change or some weird mtouch behaviour?
Solution: Please file a bug report, on http://bugzilla.xamarin.com, along with a test case. There very little probability that anyone on stackoverflow can help with such specific issues.
As to why ? it's likely the move from Mono code (mono 4.0 was used in XI 9.1) to the MS RS code (open sourced .NET BCL used in mono 4.2 and XI 9.2) that hits a case that the AOT compiler does not handle.
A test case will help us identify and fix that code. More importantly it also makes great addition to our unit tests (to ensure further changes won't break this again).
I had the same problem. After lots of time spending, I found that app.config was missing from my project file. Adding that file to my project solved that issue. Let me know if this works!

automapper error collection was modified when multiple users are creating a user

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

Unable to serialize RelationshipManager with JSON.NET

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.

Resources