Serialization in Sitecore - c#

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.

Related

Unable to serialize the session state using stateserver

I m getting following error and wondering if we can make System.Data.Linq.EntitySet serializable
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.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Web.HttpException: 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.
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[SerializationException: Type 'System.Data.Linq.EntitySet`1[[NES.HiLo.Data.DAO.UserResource, NES.HiLo.Data, Version=1.0.5012.39381, Culture=neutral, PublicKeyToken=null]]' in Assembly 'System.Data.Linq, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' is not marked as serializable.]
System.Runtime.Serialization.FormatterServices.InternalGetSerializableMembers(RuntimeType type) +7738715
System.Runtime.Serialization.FormatterServices.GetSerializableMembers(Type type, StreamingContext context) +258
System.Runtime.Serialization.Formatters.Binary.WriteObjectInfo.InitMemberInfo() +111
System.Runtime.Serialization.Formatters.Binary.WriteObjectInfo.InitSerialize(Object obj, ISurrogateSelector surrogateSelector, StreamingContext context, SerObjectInfoInit serObjectInfoInit, IFormatterConverter converter, ObjectWriter objectWriter) +422
System.Runtime.Serialization.Formatters.Binary.WriteObjectInfo.Serialize(Object obj, ISurrogateSelector surrogateSelector, StreamingContext context, SerObjectInfoInit serObjectInfoInit, IFormatterConverter converter, ObjectWriter objectWriter) +51
System.Runtime.Serialization.Formatters.Binary.ObjectWriter.Write(WriteObjectInfo objectInfo, NameInfo memberNameInfo, NameInfo typeNameInfo) +7636088
System.Runtime.Serialization.Formatters.Binary.ObjectWriter.Serialize(Object graph, Header[] inHeaders, __BinaryWriter serWriter, Boolean fCheck) +461
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Serialize(Stream serializationStream, Object graph, Header[] headers, Boolean fCheck) +134
System.Web.Util.AltSerialization.WriteValueToStream(Object value, BinaryWriter writer) +1577
The exception actually tells you already what the issue is, EntitySet is not serializeable. Therefore it cannot be stored in session state if you use the session DB feature.
EntitySet does not implement/support this. Therefore to store it in the session state, you would have to read the data into your own objects and then save it for example.
Or simply do not try to use session state to "persist" those kind of objects because usually you don't want to do this (no best practice).
One easiest & one of the best solution is to use Json.NET library.
This library allows you to do bidirectional transformation of LINQ objects to their JSON representation.
For example, you can store the product in the view state , with just few lines of code:
Product product = new Product();
product.Name = "Apple";
product.Expiry = new DateTime(2008, 12, 28);
product.Price = 3.99M;
string json = JsonConvert.SerializeObject(product);
ViewState["product"] = json ;
and retrieve it back too :
product = JsonConvert.DeserializeObject<Product>(ViewState["product"] as string);
Refer these 2 links for more:
1.) http://james.newtonking.com/projects/json-net.aspx
2.) http://www.codeplex.com/json/
if your application is using in-process state management, you'll be able to store LINQ objects in Session, Application and Cache. However you won't be able to store them in the view state.
The reason is that the data stored in the view state is serialized using a binary formatter.
Therefore one more solution is to make the LINQ class serializable, you'll need to mark all System.Data.Linq.EntitySet and System.Data.Linq.EntityRef fields with NonSerialized attribute and to mark with Serializable attribute the LINQ class.
And yet another solution is to manually extract data from the LINQ objects, store it to some intermediate format (class, struct,... etc.) and later manually transform it back.

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.

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

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