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

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.

Related

Dynamics CRM 2016 PluginProfiler System.TypeLoadException

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.

Serialization in Sitecore

I have a custom module in Sitecore which works fine if app pool session state is set to In process. When I change it to SQL Server I get error message saying that it is Unable to serialize the session state. All my classes I am using are serializable. My code is triggered by custom ribbon button and this error is thrown when I click on it. It is supposed to display dialog form but it shows error message instead. I thought it has sth to do with Sitecore DialogForm class which my class inherits, but it turned out that this is not the case.
When I debug the code error is thrown once Run(TranslateArgs args) method has finished executing - it is called from public override void Execute(CommandContext context) and is supposed to display dialog by calling SheerResponse.ShowModalDialog(str4.ToString(), true);
I also thought that it was because I used ClientPipelineArgs in Run method, but after creating custom class (and making it serializable) that inherits ClientPipelineArgs error didn't go away.
Any ideas what might be causing it?
Stack Trace:
[SerializationException: Type 'Sitecore.Data.Database' in Assembly 'Sitecore.Kernel, Version=7.0.0.0, Culture=neutral, PublicKeyToken=null' is not marked as serializable.]
System.Runtime.Serialization.FormatterServices.InternalGetSerializableMembers(RuntimeType type) +14210117
System.Runtime.Serialization.FormatterServices.GetSerializableMembers(Type type, StreamingContext context) +408
System.Runtime.Serialization.Formatters.Binary.WriteObjectInfo.InitMemberInfo() +420
System.Runtime.Serialization.Formatters.Binary.WriteObjectInfo.InitSerialize(Object obj, ISurrogateSelector surrogateSelector, StreamingContext context, SerObjectInfoInit serObjectInfoInit, IFormatterConverter converter, ObjectWriter objectWriter, SerializationBinder binder) +532
System.Runtime.Serialization.Formatters.Binary.ObjectWriter.Write(WriteObjectInfo objectInfo, NameInfo memberNameInfo, NameInfo typeNameInfo) +969
System.Runtime.Serialization.Formatters.Binary.ObjectWriter.Serialize(Object graph, Header[] inHeaders, __BinaryWriter serWriter, Boolean fCheck) +633
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Serialize(Stream serializationStream, Object graph, Header[] headers, Boolean fCheck) +322
System.Web.Util.AltSerialization.WriteValueToStream(Object value, BinaryWriter writer) +1487
[HttpException (0x80004005): Unable to serialize the session state. In 'StateServer' and 'SQLServer' mode, ASP.NET will serialize the session state objects, and as a result non-serializable objects or MarshalByRef objects are not permitted. The same restriction applies if similar serialization is done by the custom session state store in 'Custom' mode.]
System.Web.Util.AltSerialization.WriteValueToStream(Object value, BinaryWriter writer) +2252727
System.Web.SessionState.SessionStateItemCollection.WriteValueToStreamWithAssert(Object value, BinaryWriter writer) +49
System.Web.SessionState.SessionStateItemCollection.Serialize(BinaryWriter writer) +729
System.Web.SessionState.SessionStateUtility.Serialize(SessionStateStoreData item, Stream stream) +336
System.Web.SessionState.SessionStateUtility.SerializeStoreData(SessionStateStoreData item, Int32 initialStreamSize, Byte[]& buf, Int32& length, Boolean compressionEnabled) +99
System.Web.SessionState.SqlSessionStateStore.SetAndReleaseItemExclusive(HttpContext context, String id, SessionStateStoreData item, Object lockId, Boolean newItem) +3538900
System.Web.SessionState.SessionStateModule.OnReleaseState(Object source, EventArgs eventArgs) +1021
System.Web.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +92
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +165
Well the stack trace tells us, that some code is trying to put a Sitecore.Data.Database onto SessionState, and that won't work. It has no public constructor, but that is the very least of the problems. It can happen if trying to put an instantiated Item onto SessionState as well.
The stack trace appears to be incomplete. It should show you, which line of code in your Run method, is the root source of the exception.
What isn't clear to me; which exact version of Sitecore are you on?
Currently out-of-process session state mode is experimental feature in Sitecore. InProc is the best option for the Client. Find more details here.
If you still think that out-of-process is the right way to go, make sure you set it in accordance with this article.
[Update] Out-of-process session states are not supported on Content Management instance anymore. Link.

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...

Serialize ASPX page?

I am in the sitaution where I need to use an external session state server, which requires all my sessions to be serialized. I have been trying to make all the classes I store in sessions serializable, by using the [Serializeable()] attribute.
However, I keep getting the following error:
Unable to serialize the session state.
In StateServer and SQLServer mode, ASP.NET will serialize the session state objects, and as a result non-serializable objects or MarshalByRef objects are not permitted. The same restriction applies if similar serialization is done by the custom session state store in 'Custom' mode.
More interesting is however the stack trace:
[SerializationException: Type 'ASP.useroverview_aspx' in Assembly 'App_Web_pwonykbc, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' is not marked as serializable.]
System.Runtime.Serialization.FormatterServices.InternalGetSerializableMembers(RuntimeType type) +9452985
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.Web.Util.AltSerialization.WriteValueToStream(Object value, BinaryWriter writer) +1708
The Type ASP.useroverview_aspx is as far as I know an ASPX page. The page I load is Useroverview.aspx. However, I don't try to store this page in a session. So this error makes me wonder quite a lot.
I tried to do the following in the code-behind:
[Serializable()]
public partial class UserOverview : Page
{
private static readonly int TimerInterval = HttpContext.Current.IsDebuggingEnabled ? 2000 : 750;
// ...
}
This did not help at all!
So I wonder if one could serialize an ASPX page? This don't know if this would make sense. I doubt it!
Thanks...
I found the answer.. And you guys were right: One of my objects had a reference to the page.
I had an object Player, which had a list of events. One of these events had the current page as a target, which let to the problem.
I gave the event the following non serializable attribute:
[field: NonSerialized]
Then everything worked fine. And they all lived happily ever after!

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

Categories

Resources