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

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()

Related

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

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

TravelItineraryReadService VB error

When trying to use the TravelItineraryReadService 3.8.0 service via VB i get the following error just by doing
Private service As TravelItineraryReadService
service = New TravelItineraryReadService
the error output:
at System.Xml.Serialization.Compiler.Compile(Assembly parent, String ns, XmlSerializerCompilerParameters xmlParameters, Evidence evidence)
at System.Xml.Serialization.TempAssembly.GenerateAssembly(XmlMapping[] xmlMappings, Type[] types, String defaultNamespace, Evidence evidence, XmlSerializerCompilerParameters parameters, Assembly assembly, Hashtable assemblies)
at System.Xml.Serialization.TempAssembly..ctor(XmlMapping[] xmlMappings, Type[] types, String defaultNamespace, String location, Evidence evidence)
at System.Xml.Serialization.XmlSerializer.GetSerializersFromCache(XmlMapping[] mappings, Type type)
at System.Xml.Serialization.XmlSerializer.FromMappings(XmlMapping[] mappings, Type type)
at System.Web.Services.Protocols.SoapClientType..ctor(Type type)
at System.Web.Services.Protocols.SoapHttpClientProtocol..ctor()
at PricingContingency.TravelItineraryRQ1.TravelItineraryReadService..ctor()
i am using visual studio 2015,
added the WSDL as
it doesn't matter if i add the header info or not. it always fails.
This is due to response object issue in generated web service proxy class.
Changed the following and works well for me.
1.
Private associatedDataField()() As TravelItineraryReadRSTravelItineraryItineraryInfoItineraryPricingPriceQuoteMiscInformationTicketingFeesFeeInformationAssociatedDataAssociatedDataItem
----change as below-- Private associatedDataField() As
TravelItineraryReadRSTravelItineraryItineraryInfoItineraryPricingPriceQuoteMiscInformationTicketingFeesFeeInformationAssociatedDataAssociatedDataItem
Public Property AssociatedData() As TravelItineraryReadRSTravelItineraryItineraryInfoItineraryPricingPriceQuoteMiscInformationTicketingFeesFeeInformationAssociatedDataAssociatedDataItem()()
----change as below--
Public Property AssociatedData() As TravelItineraryReadRSTravelItineraryItineraryInfoItineraryPricingPriceQuoteMiscInformationTicketingFeesFeeInformationAssociatedDataAssociatedDataItem()

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.

WCF Read data issue from service

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

How to debug serialization error in tombstoned WP7 app

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