Search Results

Search found 54 results on 3 pages for 'iserializable'.

Page 1/3 | 1 2 3  | Next Page >

  • Resolving Circular References for Objects Implementing ISerializable

    - by Chris
    I'm writing my own IFormatter implementation and I cannot think of a way to resolve circular references between two types that both implement ISerializable. Here's the usual pattern: [Serializable] class Foo : ISerializable { private Bar m_bar; public Foo(Bar bar) { m_bar = bar; m_bar.Foo = this; } public Bar Bar { get { return m_bar; } } protected Foo(SerializationInfo info, StreamingContext context) { m_bar = (Bar)info.GetValue("1", typeof(Bar)); } public void GetObjectData(SerializationInfo info, StreamingContext context) { info.AddValue("1", m_bar); } } [Serializable] class Bar : ISerializable { private Foo m_foo; public Foo Foo { get { return m_foo; } set { m_foo = value; } } public Bar() { } protected Bar(SerializationInfo info, StreamingContext context) { m_foo = (Foo)info.GetValue("1", typeof(Foo)); } public void GetObjectData(SerializationInfo info, StreamingContext context) { info.AddValue("1", m_foo); } } I then do this: Bar b = new Bar(); Foo f = new Foo(b); bool equal = ReferenceEquals(b, b.Foo.Bar); // true // Serialise and deserialise b equal = ReferenceEquals(b, b.Foo.Bar); If I use an out-of-the-box BinaryFormatter to serialise and deserialise b, the above test for reference-equality returns true as one would expect. But I cannot conceive of a way to achieve this in my custom IFormatter. In a non-ISerializable situation I can simply revisit "pending" object fields using reflection once the target references have been resolved. But for objects implementing ISerializable it is not possible to inject new data using SerializationInfo. Can anyone point me in the right direction?

    Read the article

  • ISerializable and backward compatibility

    - by pierusch
    hello I have to work an an old application that used binaryFormatter to serialize application data into filestream (say in a file named "data.oldformat") without any optimizazion the main class has been marked with attribute <serializable()>public MainClass ....... end class and the serialization code dim b as new binaryformatter b.serialize(mystream,mymainclass) In an attempt to optimize the serialization/deserialization process I simply made the class implement the ISerializable interface and wrote some optimized serialization routines <serializable()>public MainClass implements ISerializable ....... end class The optimization works really well but I MUST find a way to reatrive the data inside the old files for backward compatibility. How can I do that?? Pierluigi

    Read the article

  • C# ISerializable question

    - by 5YrsLaterDBA
    I am planning to use serialization to do clone. I have to make my class ISerializable. But how about its super classes and all referenced variable classes? do I need to make them all ISerializable? If I use ISerializable. I have to implement the GetObjectData(), what I should put inside that method? leave it empty is ok?

    Read the article

  • Iserializable to serialize readonly methods to be sent through webservice

    - by george9170
    I am sending an object through a webservice with readonly methods. I am using the Iserializable interface, assuming that I would no longer need a parameterless constructor. This is not true and I still cannot send my object over the wire. public class Foo: ISerializable { public boolean IsBusy { get; private set;} protected Foo(SerializationInfo info, StreamingContext context) { this.IsBusy = info.GetBoolean("IsBusy"); } void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { .AddValue("IsBusy", this.IsBusy); }

    Read the article

  • How to mock ISerializable classes with Moq?

    - by asmois
    Hi there, I'm completly new to Moq and now trying to create a mock for System.Assembly class. I'm using this code: var mockAssembly = new Mock<Assembly>(); mockAssembly.Setup( x => x.GetTypes() ).Returns( new Type[] { typeof( Type1 ), typeof( Type2 ) } ); But when I run tests I get next exception: System.ArgumentException : The type System.Reflection.Assembly implements ISerializable, but failed to provide a deserialization constructor Stack Trace: at Castle.DynamicProxy.Generators.BaseProxyGenerator.VerifyIfBaseImplementsGet­ObjectData(Type baseType) at Castle.DynamicProxy.Generators.ClassProxyGenerator.GenerateCode(Type[] interfaces, ProxyGenerationOptions options) at Castle.DynamicProxy.DefaultProxyBuilder.CreateClassProxy(Type classToProxy, Type[] additionalInterfacesToProxy, ProxyGenerationOptions options) at Castle.DynamicProxy.ProxyGenerator.CreateClassProxy(Type classToProxy, Type[] additionalInterfacesToProxy, ProxyGenerationOptions options, Object[] constructorArguments, IInterceptor[] interceptors) at Moq.Proxy.CastleProxyFactory.CreateProxy[T](ICallInterceptor interceptor, Type[] interfaces, Object[] arguments) at Moq.Mock`1.<InitializeInstance>b__0() at Moq.PexProtector.Invoke(Action action) at Moq.Mock`1.InitializeInstance() at Moq.Mock`1.OnGetObject() at Moq.Mock`1.get_Object() Could you reccomend me the right way to mock ISerializable classes (like System.Assembly) with Moq. Thanks in advance!

    Read the article

  • Json.Net Issues: StackOverflowException is thrown when serialising circular dependent ISerializable object with ReferenceLoopHandling.Ignore

    - by keyr
    I have a legacy application that used binary serialisation to persist the data. Now we wanted to use Json.net 4.5 to serialise the data without much changes to the existing classes. Things were working nice till we hit a circular dependent class. Is there any workaround to solve this problem? Sample code as shown below [Serializable] class Department : ISerializable { public Employee Manager { get; set; } public string Name { get; set; } public Department() { } public Department( SerializationInfo info, StreamingContext context ) { Manager = ( Employee )info.GetValue( "Manager", typeof( Employee ) ); Name = ( string )info.GetValue( "Name", typeof( string ) ); } public void GetObjectData( SerializationInfo info, StreamingContext context ) { info.AddValue( "Manager", Manager ); info.AddValue( "Name", Name ); } } [Serializable] class Employee : ISerializable { [NonSerialized] //This does not work [XmlIgnore]//This does not work private Department mDepartment; public Department Department { get { return mDepartment; } set { mDepartment = value; } } public string Name { get; set; } public Employee() { } public Employee( SerializationInfo info, StreamingContext context ) { Department = ( Department )info.GetValue( "Department", typeof( Department ) ); Name = ( string )info.GetValue( "Name", typeof( string ) ); } public void GetObjectData( SerializationInfo info, StreamingContext context ) { info.AddValue( "Department", Department ); info.AddValue( "Name", Name ); } } And the test code Department department = new Department(); department.Name = "Dept1"; Employee emp1 = new Employee { Name = "Emp1", Department = department }; department.Manager = emp1; Employee emp2 = new Employee() { Name = "Emp2", Department = department }; IList<Employee> employees = new List<Employee>(); employees.Add( emp1 ); employees.Add( emp2 ); var memoryStream = new MemoryStream(); var formatter = new BinaryFormatter(); formatter.Serialize( memoryStream, employees ); memoryStream.Seek( 0, SeekOrigin.Begin ); IList<Employee> deserialisedEmployees = formatter.Deserialize( memoryStream ) as IList<Employee>; //Works nicely JsonSerializerSettings jsonSS= new JsonSerializerSettings(); jsonSS.TypeNameHandling = TypeNameHandling.Objects; jsonSS.TypeNameAssemblyFormat = FormatterAssemblyStyle.Full; jsonSS.Formatting = Formatting.Indented; jsonSS.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; //This is not working!! //jsonSS.ReferenceLoopHandling = ReferenceLoopHandling.Serialize; //This is also not working!! jsonSS.PreserveReferencesHandling = PreserveReferencesHandling.All; string jsonAll = JsonConvert.SerializeObject( employees, jsonSS ); //Throws stackoverflow exception Edit1: The issue has been reported to Json (http://json.codeplex.com/workitem/23668)

    Read the article

  • Using my ISerializable implementation instead of DataContractSerializer

    - by mpm
    My WCF client and server exchange objects whose types are defined on a class library shared by both, the server and the client. These objects implement custom serialization via ISerializable. However, my custom serialization is not being used. DataContractSerializer is being used, instead. How do I force my custom serialization to be used? The reason why I need to use my own serialization is because I do trasfer some big object graphs and my serialization algorithm does a good job in compressing/speeding up things.

    Read the article

  • .NET binary serialization conditionally without ISerializable

    - by SillyWhy
    I got 2 classes, for example: public class A { private B b; ... } public class B { ... } I need to serialize an object A using BinaryFormatter. When remoting it shall include the field b, but not when serialize to file. Here is what I added: [Serializable] public class A : MarshalByRefObject { private B b; [OnSerializing] private void OnSerializing(StreamingContext context) { if (context.State == StreamingContextStates.File) { this.b = null; } } ... } [Serializable] public class B : MarshalByRefObject { ... } I think this is a bad design because if another class C also contains B, in class C we must add the duplicate OnSerializing() logic as in A. Class B should decide what to do, not class A or C. I don't want to use ISerializable interface because there are too many variables in class B have to be added to SerializationInfo. I can create a SerializationSurrogate for class B, which perform nothing in GetObjectData() & SetObjectData(), then use it when serializing to file. However the same maintenance issue because whoever modify class B can't notice what going to happen during serialization & the existence of SerializationSurrogate. Is there a better alternative?

    Read the article

  • Why can't I use WCF DataContract and ISerializable on the same class?

    - by Dave
    Hi all, I have a class that I need to be able to serialize to a SQLServer session variable and be available over a WCF Service. I have declared it as follows namespace MyNM { [Serializable] [DataContract(Name = "Foo", Namespace = "http://www.mydomain.co.uk")] public class Foo : IEntity, ISafeCopy<Foo> { [DataMember(Order = 0)] public virtual Guid Id { get; set; } [DataMember(Order = 1)] public virtual string a { get; set; } DataMember(Order = 2)] public virtual Bar c { get; set; } /* ISafeCopy implementation */ } [Serializable] [DataContract(Name = "Bar ", Namespace = "http://www.mydomain.co.uk")] public class Bar : IEntity, ISafeCopy<Bar> { #region Implementation of IEntity DataMember(Order = 0)] public virtual Guid Id { get; set; } [DataMember(Order = 1)] public virtual Baz y { get; set; } #endregion /* ISafeCopy implementation*/ } [Serializable] [DataContract] public enum Baz { [EnumMember(Value = "one")] one, [EnumMember(Value = "two")] two, [EnumMember(Value = "three")] three } But when I try and call this service, I get the following error in the trace log. "System.Runtime.Serialization.InvalidDataContractException: Type 'BarProxybcb100e8617f40ceaa832fe4bb94533c' cannot be ISerializable and have DataContractAttribute attribute." If I take out the Serializable attribute, the WCF service works, but when the object can't be serialized to session. If I remove the DataContract attribute from class Bar, the WCF service fails saying Type 'BarProxy3bb05a31167f4ba492909ec941a54533' with data contract name 'BarProxy3bb05a31167f4ba492909ec941a54533:http://schemas.datacontract.org/2004/07/' is not expected. Add any types not known statically to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding them to the list of known types passed to DataContractSerializer I've tried adding a KnownType attribute to the foo class [KnownType(typeof(Bar))] But I still get the same error. Can anyone help me out with this? Many thanks Dave

    Read the article

  • Cant' cast a class with multiple inheritance

    - by Jay S.
    I am trying to refactor some code while leaving existing functionality in tact. I'm having trouble casting a pointer to an object into a base interface and then getting the derived class out later. The program uses a factory object to create instances of these objects in certain cases. Here are some examples of the classes I'm working with. // This is the one I'm working with now that is causing all the trouble. // Some, but not all methods in NewAbstract and OldAbstract overlap, so I // used virtual inheritance. class MyObject : virtual public NewAbstract, virtual public OldAbstract { ... } // This is what it looked like before class MyObject : public OldAbstract { ... } // This is an example of most other classes that use the base interface class NormalObject : public ISerializable // The two abstract classes. They inherit from the same object. class NewAbstract : public ISerializable { ... } class OldAbstract : public ISerializable { ... } // A factory object used to create instances of ISerializable objects. template<class T> class Factory { public: ... virtual ISerializable* createObject() const { return static_cast<ISerializable*>(new T()); // current factory code } ... } This question has good information on what the different types of casting do, but it's not helping me figure out this situation. Using static_cast and regular casting give me error C2594: 'static_cast': ambiguous conversions from 'MyObject *' to 'ISerializable *'. Using dynamic_cast causes createObject() to return NULL. The NormalObject style classes and the old version of MyObject work with the existing static_cast in the factory. Is there a way to make this cast work? It seems like it should be possible.

    Read the article

  • Anatomy of a serialization killer

    - by Brian Donahue
    As I had mentioned last month, I have been working on a project to create an easy-to-use managed debugger. It's still an internal tool that we use at Red Gate as part of product support to analyze application errors on customer's computers, and as such, should be easy to use and not require installation. Since the project has got rather large and important, I had decided to use SmartAssembly to protect all of my hard work. This was trivial for the most part, but the loading and saving of results was broken by SA after using the obfuscation, rendering the loading and saving of XML results basically useless, although the merging and error reporting was an absolute godsend and definitely worth the price of admission. (Well, I get my Red Gate licenses for free, but you know what I mean!)My initial reaction was to simply exclude the serializable results class and all of its' members from obfuscation, and that was just dandy, but a few weeks on I decided to look into exactly why serialization had broken and change the code to work with SA so I could write any new code to be compatible with SmartAssembly and save me some additional testing and changes to the SA project.In simple terms, SA does all that it can to prevent serialization problems, for instance, it will not obfuscate public members of a DLL and it will exclude any types with the Serializable attribute from obfuscation. This prevents public members and properties from being made private and having the name changed. If the serialization is done inside the executable, however, public members have the access changed to private and are renamed. That was my first problem, because my types were in the executable assembly and implemented ISerializable, but did not have the Serializable attribute set on them!public class RedFlagResults : ISerializable        {        }The second problem caused by the pruning feature. Although RedFlagResults had public members, they were not truly properties, and used the GetObjectData() method of ISerializable to serialize the members. For that reason, SA could not exclude these members from pruning and further broke the serialization. public class RedFlagResults : ISerializable        {                public List<RedFlag.Exception> Exceptions;                 #region ISerializable Members                 public void GetObjectData(SerializationInfo info, StreamingContext context)                {                                info.AddValue("Exceptions", Exceptions);                }                 #endregionSo to fix this, it was necessary to make Exceptions a proper property by implementing get and set on it. Also, I added the Serializable attribute so that I don't have to exclude the class from obfuscation in the SA project any more. The DoNotPrune attribute means I do not need to exclude the class from pruning.[Serializable, SmartAssembly.Attributes.DoNotPrune]        public class RedFlagResults        {                public List<RedFlag.Exception> Exceptions {get;set;}        }Similarly, the Exception class gets the Serializable and DoNotPrune attributes applied so all of its' properties are excluded from obfuscation.Now my project has some protection from prying eyes by scrambling up the code so it's harder to reverse-engineer, without breaking anything. SmartAssembly has also provided the benefit of merging so that the end-user doesn't need to extract all of the DLL files needed by RedFlag into a directory, and can be run directly from the .zip archive. When an error occurs (hey, I'm only human!), an exception report can be sent to me so I can see what went wrong without having to, er, debug the debugger.

    Read the article

  • Storing Interface type in ASP.NET Profile

    - by NathanD
    In my ASP.NET website all calls into the data layer return entities as interfaces and the website does not need to know what the concrete type is. This works fine, but I have run into a problem when trying to store one of those types into the user Profile. My interface implements ISerializable, like the following: public interface IInsured : IPerson, IEntity, ISerializable and the concrete type in the datalayer does implement ISerializable. My Profile property in web.config is: <add name="ActiveInsured" type="FacadeInterfaces.IInsured" serializeAs="Binary" defaultValue="[null]"/> It compiles just fine, but I get a runtime error on Profile.Save() saying that the interface cannot be serialized. I have also tried it with serializeAs="Xml". I thought that if my interface implemented ISerializable it would work. Anybody had this problem before or know of a workaround?

    Read the article

  • In VB.NET how do you specify Inherits/implements on a generic class with multi-constraints

    - by Romel Evans
    When I write the following statement in VB.Net (C# is my normal language), I get an "end of statement expected" referring to the "Implements" statement. <Serializable()> _ <XmlSchemaProvider("EtgSchema")> _ Public Class SerializeableEntity(Of T As {Class, ISerializable, New}) _ Implements IXmlSerializable, ISerializable ... End Class The C# version that I'm trying to emulate is: [Serializable] [XmlSchemaProvider("MySchema")] public class SerializableEntity<T> : IXmlSerializable, ISerializable where T : class, new() { .... } Sometimes I feel like I have 5 thumbs with VB.NET :)

    Read the article

  • Why Isn't My .Net Object Serializable?

    - by Rob P.
    I've got a 'MyDataTable' class that inherits from System.Data.DataTable I've implemented ISerializable in my class and have a 'Public Overrides Sub GetObjectData...' But when I try to serialize the an object of 'MyDataTable' I get an error saying that 'MyDataTable' is not marked as serializable. If I used a DataTable instead - my code serializes correctly. If I add a serializable attribute to the 'MyDataTable' class - it serializes correctly, but I'm told that is unnecessary if I implement ISerializable. Can someone point me in the right direction?

    Read the article

  • .NET Remoting Exception not handled Client-Side

    - by DanJo519
    I checked the rest of the remoting questions, and this specific case did not seem to be addressed. I have a .NET Remoting server/client set up. On the server side I have an object with a method that can throw an exception, and a client which will try to call that method. Server: public bool MyEquals(Guid myGuid, string a, string b) { if (CheckAuthentication(myGuid)) { logger.Debug("Request for \"" + a + "\".Equals(\"" + b + "\")"); return a.Equals(b); } else { throw new AuthenticationException(UserRegistryService.USER_NOT_REGISTERED_EXCEPTION_TEXT); } } Client: try { bool result = RemotedObject.MyEquals(myGuid, "cat", "dog"); } catch (Services.Exceptions.AuthenticationException e) { Console.WriteLine("You do not have permission to execute that action"); } When I call MyEquals with a Guid which causes CheckAuthentication to return false, .NET tries to throw the exception and says the AuthenticationException was unhandled. This happens server side. The exception is never marshaled over to the client-side, and I cannot figure out why. All of the questions I have looked at address the issue of an exception being handled client-side, but it isn't the custom exception but a base type. In my case, I can't even get any exception to cross the remoting boundary to the client. Here is a copy of AuthenticationException. It is in the shared library between both server and client. [Serializable] public class AuthenticationException : ApplicationException, ISerializable { public AuthenticationException(string message) : base(message) { } public AuthenticationException(SerializationInfo info, StreamingContext context) : base(info, context) { } #region ISerializable Members void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { base.GetObjectData(info, context); } #endregion }

    Read the article

  • Fluent NHibernate mapping List<Point> as value to single column

    - by Paja
    I have this class: public class MyEntity { public virtual int Id { get; set; } public virtual List<Point> Vectors { get; set; } } How can I map the Vectors in Fluent NHibernate to a single column (as value)? I was thinking of this: public class Vectors : ISerializable { public List<Point> Vectors { get; set; } /* Here goes ISerializable implementation */ } public class MyEntity { public virtual int Id { get; set; } public virtual Vectors Vectors { get; set; } } Is it possible to map the Vectors like this, hoping that Fluent NHibernate will initialize Vectors class as standard ISerializable? Or how else could I map List<Point> to a single column? I guess I will have to write the serialization/deserialization routines myself, which is not a problem, I just need to tell FNH to use those routines. I guess I should use IUserType or ICompositeUserType, but I have no idea how to implement them, and how to tell FNH to cooperate.

    Read the article

  • DataContractJsonSerializer produces list of hashes instead of hash

    - by Jacques
    I would expect a Dictionary object of the form: Dictionary<string,string> dict = new Dictionary<string,string>() {["blah", "bob"], ["blahagain", "bob"]}; to serialize into JSON in the form of: { "blah": "bob", "blahagain": "bob" } NOT [ { "key": "blah", "value": "bob" }, { "key": "blahagain", "value": "bob"}] What is the reason for what appears to be a monstrosity of a generic attempt at serializing collections? The DataContractJsonSerializer uses the ISerializable interface to produce this thing. It seems to me as though somebody has taken the XML output from ISerializable and mangled this thing out of it. Is there a way to override the default serialization used by .Net here? Could I just derive from Dictionary and override the Serialization methods? Posting to hear of any caveats or suggestions people might have.

    Read the article

  • How can I run code in a C# class definition each time any instance of the class is deserialized?

    - by Ben
    I am trying to derive a class from ObservableCollection and I need to run just a single line of code each and every time any instance of this class is deserialized. My thought was to do this: [Serializable] public class ObservableCollection2<T> : ObservableCollection<T>, ISerializable { public ObservableCollection2() : base() { } public ObservableCollection2(SerializationInfo info, StreamingContext context) : base(info, context) { // Put additional code here. } void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { base.GetObjectData(info, context); } } But I don't have access to those base methods related to serialization. Am I forced to re-write all of the serialization manually?

    Read the article

  • .NET: Serializing object to a file from a 3rd party assembly

    - by MacGyver
    Below is a link that describes how to serialize an object. But it requires you implement from ISerializable for the object you are serializing. What I'd like to do is serialize an object that I did not define--an object based on a class in a 3rd party assembly (from a project reference) that is not implementing ISerializable. Is that possible? How can this be done? http://www.switchonthecode.com/tutorials/csharp-tutorial-serialize-objects-to-a-file Property (IWebDriver = interface type): private IWebDriver driver; Object Instance (FireFoxDriver is a class type): driver = new FirefoxDriver(firefoxProfile); ================ 3/21/2012 update after answer posted Why would this throw an error? It doesn't like this line: serializedObject.DriverInstance = (FirefoxDriver)driver; ... Error: Cannot implicitly convert type 'OpenQA.Selenium.IWebDriver' to 'OpenQA.Selenium.Firefox.FirefoxDriver'. An explicit conversion exists (are you missing a cast?) Here is the code: FirefoxDriverSerialized serializedObject = new FirefoxDriverSerialized(); Serializer serializer = new Serializer(); serializedObject = serializer.DeSerializeObject(@"C:\firefoxDriver.qa"); driver = serializedObject.DriverInstance; if (driver == null) { driver = new FirefoxDriver(firefoxProfile); serializedObject.DriverInstance = (FirefoxDriverSerialized)driver; serializer.SerializeObject(@"C:\firefoxDriver.qa", serializedObject); } Here are the two Serializer classes I built: public class Serializer { public Serializer() { } public void SerializeObject(string filename, FirefoxDriverSerialized objectToSerialize) { Stream stream = File.Open(filename, FileMode.Create); BinaryFormatter bFormatter = new BinaryFormatter(); bFormatter.Serialize(stream, objectToSerialize); stream.Close(); } public FirefoxDriverSerialized DeSerializeObject(string filename) { FirefoxDriverSerialized objectToSerialize; Stream stream = File.Open(filename, FileMode.Open); BinaryFormatter bFormatter = new BinaryFormatter(); objectToSerialize = (FirefoxDriverSerialized)bFormatter.Deserialize(stream); stream.Close(); return objectToSerialize; } } [Serializable()] public class FirefoxDriverSerialized : FirefoxDriver, ISerializable { private FirefoxDriver driverInstance; public FirefoxDriver DriverInstance { get { return this.driverInstance; } set { this.driverInstance = value; } } public FirefoxDriverSerialized() { } public FirefoxDriverSerialized(SerializationInfo info, StreamingContext ctxt) { this.driverInstance = (FirefoxDriver)info.GetValue("DriverInstance", typeof(FirefoxDriver)); } public void GetObjectData(SerializationInfo info, StreamingContext ctxt) { info.AddValue("DriverInstance", this.driverInstance); } } ================= 3/23/2012 update #2 - fixed serialization/de-serialization, but having another issue (might be relevant for new question) This fixed the calling code. Because we're deleting the *.qa file when we call the WebDriver.Quit() because that's when we chose to close the browser. This will kill off our cached driver as well. So if we start with a new browser window, we'll hit the catch block and create a new instance and save it to our *.qa file (in the serialized form). FirefoxDriverSerialized serializedObject = new FirefoxDriverSerialized(); Serializer serializer = new Serializer(); try { serializedObject = serializer.DeSerializeObject(@"C:\firefoxDriver.qa"); driver = serializedObject.DriverInstance; } catch { driver = new FirefoxDriver(firefoxProfile); serializedObject = new FirefoxDriverSerialized(); serializedObject.DriverInstance = (FirefoxDriver)driver; serializer.SerializeObject(@"C:\firefoxDriver.qa", serializedObject); } However, still getting this exception: Acu.QA.Main.Test_0055_GiftCertificate_UserCheckout: SetUp : System.Runtime.Serialization.SerializationException : Type 'OpenQA.Selenium.Firefox.FirefoxDriver' in Assembly 'WebDriver, Version=2.16.0.0, Culture=neutral, PublicKeyToken=1c2bd1631853048f' is not marked as serializable. TearDown : System.NullReferenceException : Object reference not set to an instance of an object. The 3rd line in this code block is throwing the exception: public void SerializeObject(string filename, FirefoxDriverSerialized objectToSerialize) { Stream stream = File.Open(filename, FileMode.Create); BinaryFormatter bFormatter = new BinaryFormatter(); bFormatter.Serialize(stream, objectToSerialize); // <=== this line stream.Close(); }

    Read the article

  • DeSerialization doesn't work though i Implement GetObjectData method and Constructor

    - by Punit Singhi
    Hi, I have a static generic dictionary in a class. As static memeber cannot serialized so i have implented ISerializable interface and method GetObjectData to serialize. I have a constructor which will also accept SerializationInfo and StreamingContext to deserliaze the dictionay. Now when i try to serialize and deserialize , it always return 1(thoug i added 2 entries). please find the pseduo code- [Serializable] public class MyClass : ISerializable { internal static Dictionary<long, string> dict = new Dictionary<long,string>(); public void GetObjectData(SerializationInfo info, StreamingContext context) { info.AddValue("static.dic", MyClass1.dict, typeof(Dictionary<long, string>)); } public MyClass(SerializationInfo info, StreamingContext context) { MyClass.dict= (Dictionary<long, string>)info.GetValue("static.dic", typeof(Dictionary<long, string>)); } public void Add() { dict.Add(21, "11"); } public MyClass() { dict.Add(21, "11"); } } public class MyClass { MyClass myClass = new MyClass(); public static void Main() { myClass.Add(); FileStream fileStream = new FileStream("test.binary", FileMode.Create); IFormatter bf = new BinaryFormatter(); bf.Serialize(fileStream, myClass); fileStream.Dispose(); fileStream.Close(); fileStream = new FileStream("test.binary", FileMode.Open); bf = new BinaryFormatter(); myClass = (MyClass1)bf.Deserialize(fileStream); } }

    Read the article

  • Serialize Forms into memory

    - by serhio
    Background: In a desktop MDI application we have a lot of forms. Task: Save the controls contents of closed forms(textbox texts, checkbox checks etc). Limitations: A saved form for (DB/Windows) user? For (DB/Windows) group of users? Both variants may be possible. Question: a) What is the best way? b) if I want do not use files, how to serialize the form into a MemoryStream and then recuperate it if the opening form was been once opened and serialized? StartingPoint: Implemented a form that implements ISerializable. Deserialize the form on opening, serialize onclosing: Public Sub GetObjectData(ByVal info As System.Runtime.Serialization.SerializationInfo, ByVal context As System.Runtime.Serialization.StreamingContext) Implements System.Runtime.Serialization.ISerializable.GetObjectData info.AddValue("tbxExportFolder", tbxExportFolder.Text, GetType(String)) info.AddValue("cbxCheckAliasUnicity", cbxCheckAliasUnicity.Checked, GetType(Boolean)) End Sub Public Sub New(ByVal info As SerializationInfo, ByVal context As StreamingContext) Me.New() Me.tbxExportFolder.Text = info.GetString("tbxExportFolder") Me.cbxCheckAliasUnicity.Checked = info.GetBoolean("cbxCheckAliasUnicity") End Sub Private Sub SerializeMe() Dim binFormatter As New Formatters.Binary.BinaryFormatter Dim fileStream As New FileStream(SerializedFilename, FileMode.Create) Try binFormatter.Serialize(fileStream, Me) Catch Throw Finally fileStream.Close() End Try End Sub Protected Overrides Sub OnClosing(ByVal e As System.ComponentModel.CancelEventArgs) SerializeMe() MyBase.OnClosing(e) End Sub

    Read the article

  • Should classes from the same namespace be kept in the same assembly?

    - by Dan Rasmussen
    For example, ISerializable and the Serializable Attribute are both in the System.Runtime.Serialization namespace, but not the assembly of the same name. On the other hand, DataContract attributes are in the namespace/assembly System.Runtime.Serialization. This causes confusion when a class can have using System.Runtime.Serialization but still not have reference to the System.Runtime.Serialization assembly, meaning DataContract cannot be found. Should this be avoided in practice, or is it common for namespaces to be split over multiple assemblies? What other issues should one be careful of when doing this?

    Read the article

  • Formatting dates when serialising an object in C# (2.0)

    - by zoman
    Hi, I'm xml-serializing a object with a large number of properties and I have two properties with DateTime types. I'd like to format the dates for the serialized output. I don't really want to implement the ISerializable interface and overwrite the serialization for every property. Is there any other way to achieve this? (I'm using C#, .NET 2) Thanks.

    Read the article

  • C# "Enum" Serialization - Deserialization to Static Instance

    - by Walt W
    Suppose you have the following class: class Test : ISerializable { public static Test Instance1 = new Test { Value1 = "Hello" ,Value2 = 86 }; public static Test Instance2 = new Test { Value1 = "World" ,Value2 = 26 }; public String Value1 { get; private set; } public int Value2 { get; private set; } public void GetObjectData(SerializationInfo info, StreamingContext context) { //Serialize an indicator of which instance we are - Currently //I am using the FieldInfo for the static reference. } } I was wondering if it is possible / elegant to deserialize to the static instances of the class? Since the deserialization routines (I'm using BinaryFormatter, though I'd imagine others would be similar) look for a constructor with the same argument list as GetObjectData(), it seems like this can't be done directly . . Which I would presume means that the most elegant solution would be to actually use an enum, and then provide some sort of translation mechanism for turning an enum value into an instance reference. How might one go about this?

    Read the article

1 2 3  | Next Page >