EF and Webservice Error "System.InvalidOperationException" - c#

I started a new project. Created a class library added EF item to it under a DB namespace and then create a class(Stripped down) for each entity that i can expose in WS. I ref the CL in a windows test app to see if everything was working and it was.So i created a WS add reference addedd the connectionstring for EF and then created a webmethod that retruns the object i created for each entity.
so my namspaces looks like this
[projectName].CL.Item - created object
[projectName].CL.DB.Item - Ef Item
[projectName].WS - Webservice namespace
So i ran the ws and tested it. and i get this lovely little exception.
System.InvalidOperationException: Unable to generate a temporary class (result=1).
error CS0012: The type 'System.Data.Objects.DataClasses.EntityObject' is defined in an assembly that is not referenced. You must add a reference to assembly 'System.Data.Entity, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'.
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.FromMappings(XmlMapping[] mappings, Evidence evidence)
at System.Web.Services.Protocols.XmlReturn.GetInitializers(LogicalMethodInfo[] methodInfos)
at System.Web.Services.Protocols.XmlReturnWriter.GetInitializers(LogicalMethodInfo[] methodInfos)
at System.Web.Services.Protocols.MimeFormatter.GetInitializers(Type type, LogicalMethodInfo[] methodInfos)
at System.Web.Services.Protocols.HttpServerType..ctor(Type type)
at System.Web.Services.Protocols.HttpServerProtocol.Initialize()
at System.Web.Services.Protocols.ServerProtocol.SetContext(Type type, HttpContext context, HttpRequest request, HttpResponse response)
at System.Web.Services.Protocols.ServerProtocolFactory.Create(Type type, HttpContext context, HttpRequest request, HttpResponse response, Boolean& abortProc
Now this tells me it need reference to data.entity so i added still thinking to myself this is weird never had to do this and i am not return entity object i am returning the created onces but i did it. still the same error
then i saw that no matter what webmethod i select it does this i commented the webmethod out and made a helloworld and it worked.
I looked on google some people suggestthat you add
<add assembly="System.Data.Entity, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/>
to the webconfig i did and still same error. i am dumbfounded i do this sort of thing like daily and i never got a error like this. And the EF structure is nothing special 5 tables with foreignkeys.
i even deleted the WS/CL project and recreated it.
pls help

Found the problem...
I have in each POCO class this
namespace CL
{
public class Item
{
public static implicit operator Item(DB.Item db)
{
return new Item
{
Created = db.Created,
Id = db.ItemId
};
}
}
}
that basically converts the DB item into a POCO item.
So if i do this instead
namespace CL.DB
{
public partial class Item
{
public static implicit operator CL.Item(Item db)
{
return new CL.Item
{
Created = db.Created,
Id = db.ItemId
};
}
}
}
it works fine. WTF

Related

Dapper unable to cast object of type 'Microsoft.SqlServer.Types.SqlGeography' to type 'System.Data.Entity.Spatial.DbGeography'

I have EF configured with a Location field on my User table:
public DbGeography Location { get; set; }
However when I query my User table with:
user = connection.Query<User>("update [User] set LastOnline = #lastOnline output INSERTED.* where Username = #un",
new { lastOnline = DateTime.UtcNow, un = username }).First();
I get the following error:
Message=Error parsing column 122 (Location=POINT (-118.2436849
34.0522342) - Object) Source=Dapper StackTrace:
at Dapper.SqlMapper.ThrowDataException(Exception ex, Int32 index, IDataReader reader, Object value) in
d:\Dev\dapper-dot-net\Dapper NET40\SqlMapper.cs:line 4045
at Deserialize4650b5f0-d037-49ad-802e-8a9be95e8496(IDataReader )
at Dapper.SqlMapper.d__111.MoveNext() in d:\Dev\dapper-dot-net\Dapper NET40\SqlMapper.cs:line 1572
at System.Collections.Generic.List1..ctor(IEnumerable1 collection)
at System.Linq.Enumerable.ToList[TSource](IEnumerable1 source)
at Dapper.SqlMapper.Query[T](IDbConnection cnn, String sql, Object param, IDbTransaction transaction, Boolean buffered, Nullable1
commandTimeout, Nullable1 commandType) in
d:\Dev\dapper-dot-net\Dapper NET40\SqlMapper.cs:line 1443
at App.Services.BrowseService.GetProfiles(ProfileSearchDto query, String username, Boolean isAdmin) in
c:\PROJECTS\App\App-MAIN\App\Services\BrowseService.cs:line 330
InnerException: System.InvalidCastException
HResult=-2147467262
Message=Unable to cast object of type 'Microsoft.SqlServer.Types.SqlGeography' to type
'System.Data.Entity.Spatial.DbGeography'.
What is causing this?
Update
Just for kicks, I tried using EF:
db.Database.SqlQuery<User>("bla bla")
And I get a different error:
Message=No mapping exists from object type
<>f__AnonymousTypef`2[[System.DateTime, mscorlib, Version=4.0.0.0,
Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.String,
mscorlib, Version=4.0.0.0, Culture=neutral,
PublicKeyToken=b77a5c561934e089]] to a known managed provider native
type. Source=System.Data
goes bald
Conclusion
My app needs to search by radius and currently uses a naive lat/long boxed query. I was trying to upgrade my implementation to use spatial types, but it looks like my tooling doesn't support this scenario. Back to being naive I go.
Dapper doesn't support Entity Framework types in the core library, to reduce the number of dependencies. However, it has an extensible type-handler model, and bindings for DbGeography are included in the Dapper.EntityFramework package. Once you have added that, you need to call:
Dapper.EntityFramework.Handlers.Register();
to ask the add-in to register itself. And then it should work. If you get assembly mismatch exceptions, you should be able to resolve it with assembly binding redirects. This applies in particular to the underlying SqlGeography type, where the metadata that SQL Server returns is a different version to the metadata in the Microsoft.SqlServer.Types package. But an assembly-binding redirect works fine.

Error when (de)serializing derived types with Json.Net

I'm trying to (de)serialize a class with this simple piece of code:-
var settings = new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.All };
// Serialize
var json = JsonConvert.SerializeObject(obj, settings);
// Deseralize - this is where it fails
var test = JsonConvert.DeserializeObject<MyObject>(json, settings);
DeseralizeObject() fails with a JsonSerializationException:-
Error resolving type specified in JSON 'Xxx.Common.MyObject, Xxx.Common'. Path '$type', line 1, position 110
Inner exception: JsonSerializationException, message "Could not load assembly 'Xxx.Common".
I don't understand why it can't load the assembly - it's being referenced by this project!
It works if I don't use the JsonSerializerSettings, however I need this because the class being serialized will eventually have a List<SomeBaseClass> property that will contain derived types.
Any thoughts? I'm using Json.Net v6.0.
Edit:
I just tried adding TypeNameAssemblyFormat = FormatterAssemblyStyle.Full to my serializer settings, which resulted in this different (and confusing) exception message:-
Type specified in JSON 'Xxx.Common.MyObject, Xxx.Common, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' is not compatible with 'Xxx.Common.MyObject, Xxx.Common, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'. Path '$type', line 1, position 165.
Edit2:
To clarify things, the above code is a complete repro of the problem, and resides in a larger WPF application, while MyObject resides in a different project ("Xxx.Common") in the same solution, and is referenced by the WPF application project - I've simply replaced our company namespace with "Xxx" for this post.
MyObject is a simple POCO that I've created to rule out any issues that may be due to complex types, and consists of a few string and double properties, i.e.
public class MyObject
{
public string Name {get;set;}
public double Foo {get;set;}
...
}
The serialized JSON looks like this (again company NS replaced) - the pertinent part (i.e. the "$type") appears to be correct:-
{"$type":"Xxx.Common.MyObject, Xxx.Common","Name":null,"Foo":0.0,"StepSize":0.0,"Convergence":0.0,"Cutoff":0.0}

ResolutionFailedException with Unity

I'm using Patterns and Practices' Unity to inject dependencies into my objects and have hit a weird (to me, anyway) issue. Here's my class definitions:
public class ImageManager : IImageManager
{
IImageFileManager fileManager;
public ImageManager(IImageFileManager fileMgr)
{
this.fileManager = fileMgr;
}
}
public class ImageFileManager : IImageFileManager
{
public ImageFileManager(string folder)
{
FileFolder = folder;
}
}
And here's the code to register my classes
container.RegisterInstance<MainWindowViewModel>(new MainWindowViewModel())
.RegisterType<IPieceImageManager, PieceImageManager>(
new InjectionConstructor(typeof(string)))
.RegisterType<IImageFileManager, ImageFileManager>()
.RegisterType<IImageManager, ImageManager>(
new InjectionConstructor(typeof(IImageFileManager)));
I originally resolved this in the code behind (I know, it defeats the purpose. Bear with me.) of the XAML file like this
IImageManager imageManager = MvvmViewModelLocator.Container.Resolve<IImageManager>(
new ParameterOverride("folder", "/images"));
And it worked. But I created a view model for my main view and when I copied the same line into it, I get an exception. Here are the two most inner exceptions:
InnerException: Microsoft.Practices.Unity.ResolutionFailedException
HResult=-2146233088
Message=Resolution of the dependency failed, type = "SwapPuzzleApp.Model.IImageManager", name = "(none)".
Exception occurred while: while resolving.
Exception is: InvalidOperationException - The type IImageManager does not have an accessible constructor.
At the time of the exception, the container was:
Resolving SwapPuzzleApp.Model.IImageManager,(none)
Source=Microsoft.Practices.Unity
TypeRequested=IImageManager
StackTrace:
at Microsoft.Practices.Unity.UnityContainer.DoBuildUp(Type t, Object existing, String name, IEnumerable`1 resolverOverrides)
at Microsoft.Practices.Unity.UnityContainer.DoBuildUp(Type t, String name, IEnumerable`1 resolverOverrides)
at Microsoft.Practices.Unity.UnityContainer.Resolve(Type t, String name, ResolverOverride[] resolverOverrides)
at Microsoft.Practices.Unity.UnityContainerExtensions.Resolve[T](IUnityContainer container, ResolverOverride[] overrides)
at SwapPuzzleApp.ViewModel.MainWindowViewModel..ctor() in c:\Users\Carole\Documents\Visual Studio 2012\Projects\SwapPuzzle\SwapPuzzle\ViewModel\MainWindowViewModel.cs:line 17
at SwapPuzzleApp.ViewModel.MvvmViewModelLocator..cctor() in c:\Users\Carole\Documents\Visual Studio 2012\Projects\SwapPuzzle\SwapPuzzle\ViewModel\MvvmViewModelLocator.cs:line 51
InnerException: System.InvalidOperationException
HResult=-2146233079
Message=The type IImageManager does not have an accessible constructor.
Source=Microsoft.Practices.Unity
StackTrace:
StackTrace:
at Microsoft.Practices.ObjectBuilder2.DynamicMethodConstructorStrategy.ThrowForNullExistingObject(IBuilderContext context)
at lambda_method(Closure , IBuilderContext )
at Microsoft.Practices.ObjectBuilder2.DynamicBuildPlanGenerationContext.<>c__DisplayClass1.<GetBuildMethod>b__0(IBuilderContext context)
at Microsoft.Practices.ObjectBuilder2.DynamicMethodBuildPlan.BuildUp(IBuilderContext context)
at Microsoft.Practices.ObjectBuilder2.BuildPlanStrategy.PreBuildUp(IBuilderContext context)
at Microsoft.Practices.ObjectBuilder2.StrategyChain.ExecuteBuildUp(IBuilderContext context)
at Microsoft.Practices.Unity.UnityContainer.DoBuildUp(Type t, Object existing, String name, IEnumerable`1 resolverOverrides)
InnerException:
I'm not sure what the problem is, as ImageManager clearly has a public constructor. I thought it might be due to an invalid path, but if I concretely instantiate the object, everything works.
// this line has no problems
IImageManager imageManager = new ImageManager(new ImageFileManager("/images"));
I also wondered if I needed to pass in new InjectionConstructor(typeof(string)) when I register IImageManager, but it doesn't seem to help and why would it be needed now and not before? So I'm stumped. This is my first attempt at using Dependency Injection, so it's probably something basic. I'm just not seeing what, though.
Look very closely at the error message. Notice this part:
Message=The type IImageManager does not have an accessible constructor.
Notice the type name is IImageManager, not ImageManager. Somewhere along the line you lost your type mapping.
Your registration of FileImageManager has a problem as well, since you don't specify the folder parameter in the registration, so Unity has no idea what string to pass.
I was using the examples in this article as my guide. Either the examples in there are way too advanced for an introduction, or there's misinformation in that topic.
After consulting other sources (mainly PluarlSight), I came up with a much simpler and more logical solution.
container.RegisterInstance<TimerViewModel>(new TimerViewModel());
container.RegisterType<IPieceImageManager, PieceImageManager>();
container.RegisterType<IImageFileManager, ImageFileManager>
(new InjectionConstructor("/images"));
container.RegisterType<IImageManager, ImageManager>();
I ran into a similar issue with this error tied directly to a Mock (using automoq) that I was doing for an operation. In this case it turned out that because there were a number of member methods that get called with the object being mocked, that I had to define all of those in the automoq chain to get it to resolve properly
I realize this is an example in instance code, but it could occur in Moqs also. So if you read this and are wondering about an example related to Moqs, look into that first.

Exceptions for Entity Framework Code First Migrations

I'm getting several unhandled exceptions while using Code First Migrations of Entity Framework 4.3.
The database context:
public class MyAppContext : DbContext
{
public DbSet<Branch> Branches { get; set; }
public MyAppContext()
{ }
}
The entity:
public class Branch : IEntity<Guid>
{
public Guid Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public bool Active { get; set; }
}
The database initializer:
public class MyAppInitializer : CreateDatabaseIfNotExists<MyAppContext>
{
protected override void Seed(MyAppContext context)
{
context.Branches.Add(new Branch() { Id = branchId, Name = "Acme", Description = "Acme", Active = true });
context.SaveChanges();
}
}
I installed Entity Framework 4.3 to my DAL project and MVC project using:
Install-Package EntityFramework
I have set the MVC project as the startup project and executed the following command to the DAL project with the database context and initializer:
PM> Enable-Migrations -Verbose
Using NuGet project 'Ckms.KeyManagement.Managers'.
Error while searching for context type (specify -Verbose to see exception details).
System.Data.Entity.Migrations.Design.ToolingException: Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information. at
System.Data.Entity.Migrations.Design.ToolingFacade.Run(BaseRunner
runner) at
System.Data.Entity.Migrations.Design.ToolingFacade.GetContextTypes()
at
System.Data.Entity.Migrations.MigrationsCommands.FindContextToEnable()
Edit the generated Configuration class to specify the context to
enable migrations for.
Code First Migrations enabled for project Ckms.KeyManagement.Managers.
A DbMigrationsConfiguration child class is added to the DAL project. If I add the type of the DbContext manually and enable Automatic Migrations:
internal sealed class Configuration : DbMigrationsConfiguration<MyAppContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = true;
}
protected override void Seed(MyAppContext context)
{ }
}
These exceptions are thrown for the Add-Migration and Update-Database commands:
PM> Add-Migration TestEFMigrationsColumn -Verbose
Using NuGet project
'Ckms.KeyManagement.Managers'. Using StartUp project ''.
System.Reflection.TargetInvocationException: Exception has been thrown
by the target of an invocation. ---> System.ArgumentException: The
parameter is incorrect. (Exception from HRESULT: 0x80070057
(E_INVALIDARG)) --- End of inner exception stack trace --- at
System.RuntimeType.InvokeDispMethod(String name, BindingFlags
invokeAttr, Object target, Object[] args, Boolean[] byrefModifiers,
Int32 culture, String[] namedParameters) at
System.RuntimeType.InvokeMember(String name, BindingFlags
bindingFlags, Binder binder, Object target, Object[] providedArgs,
ParameterModifier[] modifiers, CultureInfo culture, String[]
namedParams) at
System.Management.Automation.ComMethod.InvokeMethod(PSMethod method,
Object[] arguments) Exception has been thrown by the target of an
invocation.
Update-Database:
PM> Update-Database -Verbose
Using NuGet project
'Ckms.KeyManagement.Managers'. Using StartUp project ''.
System.Reflection.TargetInvocationException: Exception has been thrown
by the target of an invocation. ---> System.ArgumentException: The
parameter is incorrect. (Exception from HRESULT: 0x80070057
(E_INVALIDARG)) --- End of inner exception stack trace --- at
System.RuntimeType.InvokeDispMethod(String name, BindingFlags
invokeAttr, Object target, Object[] args, Boolean[] byrefModifiers,
Int32 culture, String[] namedParameters) at
System.RuntimeType.InvokeMember(String name, BindingFlags
bindingFlags, Binder binder, Object target, Object[] providedArgs,
ParameterModifier[] modifiers, CultureInfo culture, String[]
namedParams) at
System.Management.Automation.ComMethod.InvokeMethod(PSMethod method,
Object[] arguments) Exception has been thrown by the target of an
invocation.
Any ideas? The error messages are not really helpful. I have tried the Nuget commands with and without an existing database.
If you are using separate library for data access you need to provide it name when running query:
Add-Migration -StartUpProjectName "Your DAL Project" MyNewMigration
Update-Database -StartUpProjectName "Your DAL Project" -Verbose
add-migration -Name First -ProjectName DbSet.Framework -StartUpProjectName CodeFirstConsole
First: Name of Migration
Dbset.Framework: Project where dbContext and other classes
CodeFirstConsole: Start Up project (could be your web, windows or console app)
For System.ArgumentException: The parameter is incorrect. (Exception from HRESULT: 0x80070057 (E_INVALIDARG)) adding -projectname and startupprojectname did not help.
Setting the PackageManager Console's "Default Project" Dropdown to point to the Library (in my case) where I wanted the "Migration folder" and its expected contents to be was the only way to get this running from a multiproject solution.
I also had the same issue. Found out that if anything is wrong with the config files this error comes up. I had duplicate tags in web.config and removing these solved my issue.
I had solve this problem only by changing the name used in connection string.
<add name="abcd" providerName="System.Data.SqlClient" connectionString="Data Source=.\SQLEXPRESS;AttachDbFileName=|DataDirectory|\DatabaseFileName.mdf;Integrated Security=True;User Instance=True;MultipleActiveResultSets=True" />
And I use connectionStrings after closing tag of the
appSettings
and just before starting tag of
system.web
Make sure that name that you use in connectionString not used in other connections.
Ran into the same problem , solved by removing <globalization> from web.config.
You must be having two connection strings in your web. Config files. Just delete one

Serialization Exception in compiled dll

I've inherited an ecommerce ASP.NET (c# code behind) web application. We've recently moved servers and it's proving somewhat troublesome. I have very little experience with IIS server configuration and dealing with large projects like this. Most of the problems have now been fixed, but we're experiencing problems with a crucial part, as a customer attempts to make a payment.
As the customer confirms payment, the application encounters 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.
Stack Trace:
[SerializationException: Type 'PayerAuthentication.PayerAuthenticationServicePost' in Assembly 'PayerAuthentication, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' is not marked as serializable.]
System.Runtime.Serialization.FormatterServices.InternalGetSerializableMembers(RuntimeType type) +7733643
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) +161
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.Serialize(Object graph, Header[] inHeaders, __BinaryWriter serWriter, Boolean fCheck) +410
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
Google search results indicate I should add [Serializable] to the class declaration affected, but this is in a compiled dll to which I do not have the csproj.
The code was working fine on the previous server and I do not believe any changes have been made to the code, only to web.config - what can I do?
The sessionstate section of web.config reads <sessionState mode="StateServer" />
UPDATE1: Using Reflector, I exported the class above, made it serializable, recompiled and replaced the dll. The order process went one step further, wherepon I encountered the same error for another dll-compiled class. Once again I was able to use Reflector to see the code, and then export it, edit and recompile.
Now I have the same error occurring in:
SerializationException: Type 'System.Runtime.Remoting.Messaging.AsyncResult' in Assembly 'mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' is not marked as serializable.]
I'm not sure I can do anything about this, as this must be part of the .net system files! Any further ideas?
UPDATE2: Ha, well I've subsequently discovered it's processing the payments correctly, but then throwing the above Unable to serialize the session state error on System.Runtime.Remoting.Messaging.AsyncResult before the user gets receipt of the transaction. Not good. Unsure how to move forward now...
UPDATE3: I tried creating a copy of the System.Runtime.Remoting.Messaging.AsyncResult class, and making it serializable but this is then leading to inconsistent accessibility problems.
using System;
using System.Runtime.InteropServices;
using System.Threading;
using System.Security.Permissions;
using System.Runtime.Remoting.Messaging;
[Serializable, ComVisible(true)]
public class myAsyncResult : IAsyncResult, IMessageSink
{
// Fields
private AsyncCallback _acbd;
private Delegate _asyncDelegate;
private object _asyncState;
private ManualResetEvent _AsyncWaitHandle;
private bool _endInvokeCalled;
private bool _isCompleted;
private IMessageCtrl _mc;
private IMessage _replyMsg;
// Methods
internal myAsyncResult(Message m);
//[SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.Infrastructure)]
public virtual IMessageCtrl AsyncProcessMessage(IMessage msg, IMessageSink replySink);
private void FaultInWaitHandle();
public virtual IMessage GetReplyMessage();
public virtual void SetMessageCtrl(IMessageCtrl mc);
//[SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.Infrastructure)]
public virtual IMessage SyncProcessMessage(IMessage msg);
// Properties
public virtual object AsyncDelegate { get; }
public virtual object AsyncState { get; }
public virtual WaitHandle AsyncWaitHandle { get; }
public virtual bool CompletedSynchronously { get; }
public bool EndInvokeCalled { get; set; }
public virtual bool IsCompleted { get; }
public IMessageSink NextSink { [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.Infrastructure)] get; }
}
Specifically, that error CS0122: 'System.Runtime.Remoting.Messaging.Message' is inaccessible due to its protection level. I can see this is because Message is an internal class. But surely I can't change the accessibility level of it as it is part of the System.Runtime namespace. And making a copy and renaming it is going to cuase the same problem again, surely?
Can anyone help me now?
FINAL UPDATE
Looks like, after all this, that it was the SSL certificate (see my answer below)
If you really wanted the code, you could try using Reflector's Class View. At the very least, it could help you verify whether or not [Serializable] was part of the problem class definition or not.
You'll need to find out if the new server is a later version than the old, or an older one. If it's an older version, then upgrade it to the newer version, and things should work.
If it's newer, then is it your code (that you have source to) that puts these non-serializable objects into session state? If so, then you can maybe create your own class to mirror the properties of the old class. Make your class serializable and put an instance of your class into session state. Make an instance of the old class when you take yours out of session state.
I now believe that this problem arose when we installed a new SSL certificate.
The new certificate had Postcode extensions which our payment merchant HSBC doesn't accept over it's CPI payment gateway.
Getting the correct SSL certificate installed seems to have finally solved this problem.
If the code was previously using just the in-memory state provider, then this could be... tricky. It is a pain point that the serialization process (via BinaryFormatter, which the database state provider uses) requires the [Serializable] attribute when the default provider doesn't.
How much of the code can you edit? Any of it? For example, can you change the code that puts things into/out-of state? You could perhaps use a separate (serializable) DTO with the necessary properties and translate between them with your own code.
Other options:
go back to the in-memory provider (and wave goodbye to a cluster)
write a provider that doesn't use BinaryFormatter
I have some thoughts on the latter, but I doubt it would be trivial
If the question is just how to make the application run without this error, the fast solution is to set the mode attribute of the sessionState element to "InProc".

Categories