Dynamics CRM 2016 PluginProfiler System.TypeLoadException - c#

I'm having problems debugging my assembly using the PluginProfiler supplied with the PluginRegistrationTool. Once I mark the step as profiling and trigger it (Create an account) it shows the following error message:
Unhandled Exception:
System.ServiceModel.FaultException`1[[Microsoft.Xrm.Sdk.OrganizationServiceFault, Microsoft.Xrm.Sdk, Version=8.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35]]: Unexpected Exception in the Plug-in ProfilerDetail:
<OrganizationServiceFault xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.microsoft.com/xrm/2011/Contracts">
<ErrorCode>-2147220891</ErrorCode>
<ErrorDetails xmlns:d2p1="http://schemas.datacontract.org/2004/07/System.Collections.Generic">
<KeyValuePairOfstringanyType>
<d2p1:key>CallStack</d2p1:key>
<d2p1:value xmlns:d4p1="http://www.w3.org/2001/XMLSchema" i:type="d4p1:string"> at PluginProfiler.Plugins.ProfilerBase`1.InitializeProfiler(Dictionary`2 services, T operationContext, ProfilerPluginContext& context)
at PluginProfiler.Plugins.ProfilerPlugin.Execute(IServiceProvider serviceProvider)
at Microsoft.Crm.Sandbox.SandboxAppDomainHelper.<>c__DisplayClass8.<Execute>b__1()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at Microsoft.Crm.Sandbox.SandboxAppDomainHelper.Execute(IOrganizationServiceFactory organizationServiceFactory, Dictionary`2 sandboxServices, String pluginTypeName, String pluginConfiguration, String pluginSecureConfig, IPluginExecutionContext requestContext, Boolean enablePluginStackTrace, Boolean chaosFailAppDomain)
at Microsoft.Crm.Sandbox.SandboxAppDomainHelper.Execute(IOrganizationServiceFactory organizationServiceFactory, Dictionary`2 sandboxServices, String pluginTypeName, String pluginConfiguration, String pluginSecureConfig, IPluginExecutionContext requestContext, Boolean enablePluginStackTrace, Boolean chaosFailAppDomain)
at Microsoft.Crm.Sandbox.SandboxWorker.Execute(SandboxCallInfo callInfo, SandboxPluginExecutionContext requestContext, Guid pluginAssemblyId, Int32 sourceHash, String assemblyName, Guid pluginTypeId, String pluginTypeName, String pluginConfiguration, String pluginSecureConfig, SandboxRequestCounter& workerCounter, Boolean returnTraceInfo)</d2p1:value>
</KeyValuePairOfstringanyType>
<KeyValuePairOfstringanyType>
<d2p1:key>OperationStatus</d2p1:key>
<d2p1:value xmlns:d4p1="http://www.w3.org/2001/XMLSchema" i:type="d4p1:string">3</d2p1:value>
</KeyValuePairOfstringanyType>
<KeyValuePairOfstringanyType>
<d2p1:key>SubErrorCode</d2p1:key>
<d2p1:value xmlns:d4p1="http://www.w3.org/2001/XMLSchema" i:type="d4p1:string">-2146233088</d2p1:value>
</KeyValuePairOfstringanyType>
</ErrorDetails>
<Message>Unexpected Exception in the Plug-in Profiler</Message>
<Timestamp>2017-09-20T11:11:16.7252255Z</Timestamp>
<ExceptionRetriable>false</ExceptionRetriable>
<ExceptionSource i:nil="true" />
<InnerFault i:nil="true" />
<OriginalException i:nil="true" />
<TraceText>
[PluginProfiler.Plugins: PluginProfiler.Plugins.ProfilerPlugin]
[585cb523-f29d-e711-81b0-000d3a22c45c: XXXXXXXX.Xrm.Plugins.BasicEntryPoints.GenericPlugin: Create of account (Profiler)]
An exception occurred during the initialization of the Plug-in Profiler.
Unhandled Exception: System.TypeLoadException: Inheritance security rules violated while overriding member: 'Castle.DynamicProxy.ProxyGenerationOptions.GetObjectData(System.Runtime.Serialization.SerializationInfo, System.Runtime.Serialization.StreamingContext)'. Security accessibility of the overriding method must match the security accessibility of the method being overriden.
at System.Reflection.RuntimeAssembly.GetExportedTypes(RuntimeAssembly assembly, ObjectHandleOnStack retTypes)
at System.Reflection.RuntimeAssembly.GetExportedTypes()
at Microsoft.Xrm.Sdk.KnownTypesProvider.get_KnownOrganizationRequestResponseTypes()
at Microsoft.Xrm.Sdk.KnownTypesResolver.ResolveName(String typeName, String typeNamespace, Type declaredType, DataContractResolver knownTypeResolver)
at System.Runtime.Serialization.XmlObjectSerializerContext.ResolveDataContractFromDataContractResolver(XmlQualifiedName typeName, Type declaredType)
at System.Runtime.Serialization.XmlObjectSerializerContext.ResolveDataContractFromKnownTypes(String typeName, String typeNs, DataContract memberTypeContract, Type declaredType)
at System.Runtime.Serialization.XmlObjectSerializerContext.IsKnownType(DataContract dataContract, Type declaredType)
at System.Runtime.Serialization.XmlObjectSerializerContext.IsKnownType(DataContract dataContract, Dictionary`2 knownDataContracts, Type declaredType)
at System.Runtime.Serialization.KnownTypeDataContractResolver.TryResolveType(Type type, Type declaredType, DataContractResolver knownTypeResolver, XmlDictionaryString& typeName, XmlDictionaryString& typeNamespace)
at Microsoft.Xrm.Sdk.KnownTypesResolver.TryResolveType(Type type, Type declaredType, DataContractResolver knownTypeResolver, XmlDictionaryString& typeName, XmlDictionaryString& typeNamespace)
at System.Runtime.Serialization.XmlObjectSerializerWriteContext.ResolveType(Type objectType, Type declaredType, XmlDictionaryString& typeName, XmlDictionaryString& typeNamespace)
at System.Runtime.Serialization.XmlObjectSerializerWriteContext.WriteTypeInfo(XmlWriterDelegator writer, DataContract contract, DataContract declaredContract)
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.WriteObject(XmlDictionaryWriter writer, Object graph)
at Microsoft.Crm.Sandbox.SandboxUtility.SerializeDataContract[T](T dataContract, Assembly proxyTypesAssembly)
at Microsoft.Crm.Sandbox.SandboxOrganizationServiceWrapper.ExecuteInternal(OrganizationRequest request)
at Microsoft.Crm.Sandbox.SandboxOrganizationServiceWrapper.RetrieveInternal(String entityName, Guid id, ColumnSet columnSet)
at Microsoft.Crm.Sandbox.SandboxOrganizationServiceWrapper.Retrieve(String entityName, Guid entityId, ColumnSet columnSet)
at PluginProfiler.Plugins.PluginLoaderUtility.RefreshAssembly(IOrganizationService service, ProfilerConfiguration config, PluginInitializationContext context)
at PluginProfiler.Plugins.PluginLoaderUtility.RefreshPluginInitializationContext(IOrganizationServiceFactory factory, ProfilerConfiguration config, PluginInitializationContext currentContext)
at PluginProfiler.Plugins.ProfilerBase`1.InitializeProfiler(Dictionary`2 services, T operationContext, ProfilerPluginContext& context)
</TraceText>
</OrganizationServiceFault>
I'm using StructureMap as IoC container and StructureMap.AutoFactory, which requires Castle.Core. I'm using ILMerge to merge all assemblies into a single on. I'm using the following arguments to execute ILMerge:
/target:library
/out:"$outPath"
/log:"$logFile"
/keyfile:"${keyFile}"
/copyattrs
/wildcards
/targetplatform:"v4,${Env:ProgramFiles(x86)}\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.5.2"
and the following assemblies (left out my dlls):
"${targetDir}StructureMap.dll"
"${targetDir}StructureMap.AutoFactory.dll"
"${targetDir}Castle.Core.dll"
I'm really out of ideas and it would be great if someone finds the time to help me. Thanks in advance!

As per this article the Sandboxed environment in which plugins run prohibits the use of Reflection to access internal members. I'm not familiar with dynamics proxying per se, but it looks like creating types on the fly and potentially using reflection in the process may not be possible in the sandbox.
If you have an on-prem dev environment you could register the plugin outside the sandbox and see what happens.

Related

how to deploy a Webapi project (coupled with EF & LocalDb) to Azure

Quickly to get a feeling on azure, I created a webapi project which uses EF and Local DB and it has some crud operations.
Then I signed up to Azure, created a WebApp and then downloaded the publish profile.
Using VS 2013, deployed the application to Azure. Navigated to index.html everything is working fine.
The problem is when I try to execute a simple HttpGet (which returns the value from the LocalDB), I am getting the below stack trace.
<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>
Format of the initialization string does not conform to specification starting at index 0.
</ExceptionMessage>
<ExceptionType>System.ArgumentException</ExceptionType>
<StackTrace>
at System.Data.Common.DbConnectionOptions.GetKeyValuePair(String connectionString, Int32 currentPosition, StringBuilder buffer, Boolean useOdbcRules, String& keyname, String& keyvalue) at System.Data.Common.DbConnectionOptions.ParseInternal(Hashtable parsetable, String connectionString, Boolean buildChain, Hashtable synonyms, Boolean firstKey) at System.Data.Common.DbConnectionOptions..ctor(String connectionString, Hashtable synonyms, Boolean useOdbcRules) at System.Data.SqlClient.SqlConnectionString..ctor(String connectionString) at System.Data.SqlClient.SqlConnectionFactory.CreateConnectionOptions(String connectionString, DbConnectionOptions previous) at System.Data.ProviderBase.DbConnectionFactory.GetConnectionPoolGroup(DbConnectionPoolKey key, DbConnectionPoolGroupOptions poolOptions, DbConnectionOptions& userConnectionOptions) at System.Data.SqlClient.SqlConnection.ConnectionString_Set(DbConnectionPoolKey key) at System.Data.SqlClient.SqlConnection.set_ConnectionString(String value) at System.Data.Entity.Infrastructure.Interception.DbConnectionDispatcher.<SetConnectionString>b__18(DbConnection t, DbConnectionPropertyInterceptionContext`1 c) at System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch[TTarget,TInterceptionContext](TTarget target, Action`2 operation, TInterceptionContext interceptionContext, Action`3 executing, Action`3 executed) at System.Data.Entity.Infrastructure.Interception.DbConnectionDispatcher.SetConnectionString(DbConnection connection, DbConnectionPropertyInterceptionContext`1 interceptionContext) at System.Data.Entity.Internal.LazyInternalConnection.InitializeFromConnectionStringSetting(ConnectionStringSettings appConfigConnection) at System.Data.Entity.Internal.LazyInternalConnection.Initialize() at System.Data.Entity.Internal.LazyInternalConnection.get_Connection() at System.Data.Entity.Internal.LazyInternalContext.get_Connection() at System.Data.Entity.Infrastructure.DbContextInfo..ctor(Type contextType, DbProviderInfo modelProviderInfo, AppConfig config, DbConnectionInfo connectionInfo, Func`1 resolver) at System.Data.Entity.Migrations.DbMigrator..ctor(DbMigrationsConfiguration configuration, DbContext usersContext, DatabaseExistenceState existenceState, Boolean calledByCreateDatabase) at System.Data.Entity.MigrateDatabaseToLatestVersion`2.InitializeDatabase(TContext context) at System.Data.Entity.Internal.InternalContext.<>c__DisplayClassf`1.<CreateInitializationAction>b__e() at System.Data.Entity.Internal.InternalContext.PerformInitializationAction(Action action) at System.Data.Entity.Internal.InternalContext.PerformDatabaseInitialization() at System.Data.Entity.Internal.LazyInternalContext.<InitializeDatabase>b__4(InternalContext c) at System.Data.Entity.Internal.RetryAction`1.PerformAction(TInput input) at System.Data.Entity.Internal.LazyInternalContext.InitializeDatabaseAction(Action`1 action) at System.Data.Entity.Internal.LazyInternalContext.InitializeDatabase() at System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType) at System.Data.Entity.Internal.Linq.InternalSet`1.Initialize() at System.Data.Entity.Internal.Linq.InternalSet`1.GetEnumerator() at System.Data.Entity.Infrastructure.DbQuery`1.System.Collections.Generic.IEnumerable<TResult>.GetEnumerator() at WriteArrayOfBankModelToXml(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.SerializeWithoutXsiType(DataContract dataContract, XmlWriterDelegator xmlWriter, Object obj, RuntimeTypeHandle declaredTypeHandle) 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 also see there are no options to create a LocalDb in Azure Website.
I initially guessed since I am using CodeFirst approach, Azure will automatically create the database for me.
EDIT: I have seeded the database and added some sample data to the localdb. The api works just fine in my local machine.
Any inputs on this please ?
You should use Azure SQL Database instead of local DB.
You will still use CodeFirst.
Here is how to do it :
Enable Migrations, create the database, add sample data and a data initializer
https://azure.microsoft.com/en-us/documentation/articles/web-sites-dotnet-rest-service-aspnet-api-sql-database/#enable-migrations-create-the-database-add-sample-data-and-a-data-initializer
If needed, you can jump to the top of the page to see the complete tuto starting from the Web API...

AppFabric Caching Serialization exception

I'm running with problems with AppFabric Caching 1.1. Try google it but nothing came up (or using the wrong keywords)
There is the follow scenario:
We have the cluster with 2 hosts up and running
We have our dev server using the appfabric cluster with no problem
We do night builds to a testing server (with no problems, all the configs are right) and here the appfabric have problems
We have one cache for dev and another to test
The object that we have problems is a list of classes A, and the class A have some properties and a list of class B. Both classes have serialize attribute and datacontract plus datamember.
In dev everything work as expected. We store/retrieve/delete from cache.
In test we store, but when try to retrieve have an exception.
The exception is:
Error Message: Object reference not set to an instance of an object.
Stack Trace: at
System.Runtime.Serialization.TypeName.LoadTypeWithPartialName(ITypeName
typeNameInfo, Assembly initialAssembly, String fullTypeName) at
System.Runtime.Serialization.TypeName.LoadTypeWithPartialName(ITypeName
typeNameInfo, Assembly initialAssembly, String fullTypeName) at
System.Runtime.Serialization.TypeName.GetType(Assembly
initialAssembly, String fullTypeName) at
System.Runtime.Serialization.XmlObjectSerializerReadContextComplex.ResolveDataContractTypeInSharedTypeMode(String
assemblyName, String typeName, Assembly& assembly) at
System.Runtime.Serialization.XmlObjectSerializerReadContextComplex.ResolveDataContractInSharedTypeMode(String
assemblyName, String typeName, Assembly& assembly, Type& type) at
System.Runtime.Serialization.XmlObjectSerializerReadContextComplex.InternalDeserializeInSharedTypeMode(XmlReaderDelegator
xmlReader, Int32 declaredTypeID, Type declaredType, String name,
String ns) at
System.Runtime.Serialization.XmlObjectSerializerReadContextComplex.InternalDeserialize(XmlReaderDelegator
xmlReader, Type declaredType, String name, String ns) at
System.Runtime.Serialization.NetDataContractSerializer.InternalReadObject(XmlReaderDelegator
xmlReader, Boolean verifyObjectName) at
System.Runtime.Serialization.XmlObjectSerializer.ReadObjectHandleExceptions(XmlReaderDelegator
reader, Boolean verifyObjectName) at
Microsoft.ApplicationServer.Caching.Utility.Deserialize(Byte[][]
buffers, Boolean checkTypeToLoad, Object context, IEnumerable1
knownTypes) at
Microsoft.ApplicationServer.Caching.Utility.Deserialize(Byte[][]
buffers, Boolean checkTypeToLoad) at
Microsoft.ApplicationServer.Caching.RoutingClient.SendMsgAndWait(RequestBody
reqMsg, IRequestTracker& tracker) at
Microsoft.ApplicationServer.Caching.DataCache.SendReceive(RequestBody
reqMsg, IMonitoringListener listener) at
Microsoft.ApplicationServer.Caching.DataCache.InternalGet(String key,
DataCacheItemVersion& version, String region, IMonitoringListener
listener) at
Microsoft.ApplicationServer.Caching.DataCache.<>c__DisplayClass49.b__48()
at
Microsoft.ApplicationServer.Caching.MonitoringListenerFactory.EmptyListener.Microsoft.ApplicationServer.Caching.IMonitoringListener.Listen[TResult](Func`1
innerDelegate) at
Microsoft.ApplicationServer.Caching.DataCache.Get(String key)
EDIT:
The classes are decorate with Serialize and DataContract attributes. The properties are decorated with DataMember attribute
To sort it I use the Protocol Buffer and do the serialization myself.
When I open the dll's, I discover the AppFabric bypass if it is a byte array.

How to fix 'System.ServiceModel.ExceptionDetail' is not marked as serializable

I have a WCF web service called by an ASP .Net web site. In my web method I deliberately don't catch exceptions, as I want them to be handled by the client web site. The web service is purely an internal application, and I want it to behave like a standard library which expects the caller to handle exceptions. I have includeExceptionDetailInFaults="true" in the service web.config. When my service throws an exception I get this error:
Log Name: Application
Source: ASP.NET 2.0.50727.0
Date: 24/05/2012 09:13:52
Event ID: 1334
Task Category: None
Level: Error
Keywords: Classic
User: N/A
Description:
An unhandled exception occurred and the process was terminated.
Application ID: DefaultDomain
Process ID: 2628
Exception: System.Runtime.Serialization.SerializationException
Message: Type 'System.ServiceModel.ExceptionDetail' in Assembly 'System.ServiceModel, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' is not marked as serializable.
StackTrace: at System.Runtime.Serialization.FormatterServices.InternalGetSerializableMembers(RuntimeType type)
at System.Runtime.Serialization.FormatterServices.GetSerializableMembers(Type type, StreamingContext context)
at System.Runtime.Serialization.Formatters.Binary.WriteObjectInfo.InitMemberInfo()
at System.Runtime.Serialization.Formatters.Binary.WriteObjectInfo.InitSerialize(Object obj, ISurrogateSelector surrogateSelector, StreamingContext context, SerObjectInfoInit serObjectInfoInit, IFormatterConverter converter, ObjectWriter objectWriter)
at System.Runtime.Serialization.Formatters.Binary.WriteObjectInfo.Serialize(Object obj, ISurrogateSelector surrogateSelector, StreamingContext context, SerObjectInfoInit serObjectInfoInit, IFormatterConverter converter, ObjectWriter objectWriter)
at System.Runtime.Serialization.Formatters.Binary.ObjectWriter.Write(WriteObjectInfo objectInfo, NameInfo memberNameInfo, NameInfo typeNameInfo)
at System.Runtime.Serialization.Formatters.Binary.ObjectWriter.Serialize(Object graph, Header[] inHeaders, __BinaryWriter serWriter, Boolean fCheck)
at System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Serialize(Stream serializationStream, Object graph, Header[] headers, Boolean fCheck)
at System.Runtime.Remoting.Channels.CrossAppDomainSerializer.SerializeObject(Object obj, MemoryStream stm)
at System.AppDomain.Serialize(Object o)
at System.AppDomain.MarshalObject(Object o)
How to fix this so my client is able to catch exceptions thrown by the service?
I found the cause of the problem - the exception was being thrown in a worker thread (System.Threading.ThreadPool.QueueUserWorkItem) within my web service, so of course was not being handled. Fixed by adding an exception handler and logging to the worker thread.

Type 'Tamir.SharpSsh.jsch.JSchException' is not marked as serializable

I have a .NET 3.5 MVC2 web app that runs fine from Visual Studio 2008 but when I publish to a remote site, I get an error in a certain function.
Any idea what I should be looking for here?
Event Type: Error
Event Source: ASP.NET 2.0.50727.0
Event Category: None
Event ID: 1334
Date: 24/08/2010
Time: 13:58:55
User: N/A
Computer: MSVSC01-G124NW
Description:
An unhandled exception occurred and the process was terminated.
Application ID: DefaultDomain
Process ID: 17048
Exception: System.Runtime.Serialization.SerializationException
Message: Type 'Tamir.SharpSsh.jsch.JSchException' in Assembly 'Tamir.SharpSSH, Version=1.1.1.13, Culture=neutral, PublicKeyToken=null' is not marked as serializable.
StackTrace: at System.Runtime.Serialization.Formatters.Binary.WriteObjectInfo.InitSerialize(Object obj, ISurrogateSelector surrogateSelector, StreamingContext context, SerObjectInfoInit serObjectInfoInit, IFormatterConverter converter, ObjectWriter objectWriter)
at System.Runtime.Serialization.Formatters.Binary.WriteObjectInfo.Serialize(Object obj, ISurrogateSelector surrogateSelector, StreamingContext context, SerObjectInfoInit serObjectInfoInit, IFormatterConverter converter, ObjectWriter objectWriter)
at System.Runtime.Serialization.Formatters.Binary.ObjectWriter.Serialize(Object graph, Header[] inHeaders, __BinaryWriter serWriter, Boolean fCheck)
at System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Serialize(Stream serializationStream, Object graph, Header[] headers, Boolean fCheck)
at System.Runtime.Remoting.Channels.CrossAppDomainSerializer.SerializeObject(Object obj, MemoryStream stm)
at System.AppDomain.Serialize(Object o)
at System.AppDomain.MarshalObject(Object o)
For more information, see Help and Support Center at http://go.microsoft.com/fwlink/events.asp.
Well.. is your exception class marked as serializable?
Aop is right, you have to put [Serializable()] before your class. This tells the compiler this class can be serialized.
[Serializable()]
public class TestSimpleObject { ... }
More info about attributes and serialization :
http://www.csharpfriends.com/Articles/getArticle.aspx?articleID=94
http://msdn.microsoft.com/en-us/library/z0w1kczw.aspx
http://msdn.microsoft.com/en-us/library/system.serializableattribute(VS.71).aspx
Are you using that class in a member of another class that is serializable? if so, you may need to add these attributes to that variable
[XmlIgnore][field: NonSerialized] private JSch _jsch
I hope that helps

How did My Object Get into ASP.NET Page State?

I know what this error is, how to fix it, etc.
My question is that I don't know why my current page I am developing is throwing this error when I am not using the foo class directly in any way, nor am I setting anything to the viewstate. I am using postbacks alot, but like I said, I am not storing anything in the viewstate etc one integer.
I am using nhibernate if that is relevant.
Any idea why I need to mark this classes as serializable that arent being used? Where should I start investigating?
[SerializationException: Type 'FlexiCommerce.Persistence.NH.ContentPersister' in Assembly 'FlexiCommerce.Persistence.NH, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' is not marked as serializable.]
System.Runtime.Serialization.FormatterServices.InternalGetSerializableMembers(RuntimeType type) +9434541
System.Runtime.Serialization.FormatterServices.GetSerializableMembers(Type type, StreamingContext context) +247
System.Runtime.Serialization.Formatters.Binary.WriteObjectInfo.InitMemberInfo() +160
System.Runtime.Serialization.Formatters.Binary.WriteObjectInfo.InitSerialize(Object obj, ISurrogateSelector surrogateSelector, StreamingContext context, SerObjectInfoInit serObjectInfoInit, IFormatterConverter converter, ObjectWriter objectWriter, SerializationBinder binder) +218
System.Runtime.Serialization.Formatters.Binary.ObjectWriter.Write(WriteObjectInfo objectInfo, NameInfo memberNameInfo, NameInfo typeNameInfo) +388
System.Runtime.Serialization.Formatters.Binary.ObjectWriter.Serialize(Object graph, Header[] inHeaders, __BinaryWriter serWriter, Boolean fCheck) +444
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Serialize(Stream serializationStream, Object graph, Header[] headers, Boolean fCheck) +133
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Serialize(Stream serializationStream, Object graph) +13
System.Web.UI.ObjectStateFormatter.SerializeValue(SerializerBinaryWriter writer, Object value) +2937
[ArgumentException: Error serializing value 'Music#2' of type 'FlexiCommerce.Components.Category.']
System.Web.UI.ObjectStateFormatter.SerializeValue(SerializerBinaryWriter writer, Object value) +3252
System.Web.UI.ObjectStateFormatter.SerializeValue(SerializerBinaryWriter writer, Object value) +2276
[ArgumentException: Error serializing value 'System.Object[]' of type 'System.Object[].']
System.Web.UI.ObjectStateFormatter.SerializeValue(SerializerBinaryWriter writer, Object value) +3252
System.Web.UI.ObjectStateFormatter.Serialize(Stream outputStream, Object stateGraph) +116
System.Web.UI.ObjectStateFormatter.Serialize(Object stateGraph) +57
System.Web.UI.ObjectStateFormatter.System.Web.UI.IStateFormatter.Serialize(Object state) +4
System.Web.UI.Util.SerializeWithAssert(IStateFormatter formatter, Object stateGraph) +37
System.Web.UI.HiddenFieldPageStatePersister.Save() +79
System.Web.UI.Page.SavePageStateToPersistenceMedium(Object state) +108
System.Web.UI.Page.SaveAllState() +315
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +2492
Are you perhaps databinding objects of this kind? It's clearly gotten into page state somehow.
I would assume you have enabled some of the caching elements either for query caching, or enabled actual object graph caching of NHibernate (if so probably using the SysCacheProvider which is just HttpRuntime.Cache).
I would recommend regardless of caching usage or not to mark every Domain object as serializable as it's very reasonable at some point that it will either go over the wire or just into a ViewState/Session container.

Categories

Resources