Search Results

Search found 75 results on 3 pages for 'binaryformatter'.

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

  • BinaryFormatter with MemoryStream Question

    - by Changeling
    I am testing BinaryFormatter to see how it will work for me and I have a simple question: When using it with the string HELLO, and I convert the MemoryStream to an array, it gives me 29 dimensions, with five of them being the actual data towards the end of the dimensions: BinaryFormatter bf = new BinaryFormatter(); MemoryStream ms = new MemoryStream(); byte[] bytes; string originalData = "HELLO"; bf.Serialize(ms, originalData); ms.Seek(0, 0); bytes = ms.ToArray(); returns - bytes {Dimensions:[29]} byte[] [0] 0 byte [1] 1 byte [2] 0 byte [3] 0 byte [4] 0 byte [5] 255 byte [6] 255 byte [7] 255 byte [8] 255 byte [9] 1 byte [10] 0 byte [11] 0 byte [12] 0 byte [13] 0 byte [14] 0 byte [15] 0 byte [16] 0 byte [17] 6 byte [18] 1 byte [19] 0 byte [20] 0 byte [21] 0 byte [22] 5 byte [23] 72 byte [24] 69 byte [25] 76 byte [26] 76 byte [27] 79 byte [28] 11 byte Is there a way to only return the data encoded as bytes without all the extraneous information?

    Read the article

  • Deserialization error using Runtime Serialization with the Binary Formatter

    - by Lily
    When I am deserializing a hierarchy I get the following error The input stream is not a valid binary format. The starting contents (in bytes) are The input stream is not a valid binary format. The starting contents (in bytes) are: 20-01-20-20-20-FF-FF-FF-FF-01-20-20-20-20-20-20-20 ..." Any help please? Extra info: public void Serialize(ISyntacticNode person) { Stream stream = File.Open(fileName, FileMode.OpenOrCreate); try { BinaryFormatter binary = new BinaryFormatter(); pList.Add(person); binary.Serialize(stream, pList); stream.Close(); } catch { stream.Close(); } } public List<ISyntacticNode> Deserialize() { Stream stream = File.Open(fileName, FileMode.OpenOrCreate); BinaryFormatter binary = new BinaryFormatter(); try { pList = (List<ISyntacticNode>)binary.Deserialize(stream); binary.Serialize(stream, pList); stream.Close(); } catch { pList = new List<ISyntacticNode>(); binary.Serialize(stream, pList); stream.Close(); } return pList; } I am Serializing a hierarchy which is of type Proxem.Antelope.Parsing.ISyntacticNode Now I have gotten this error System.Runtime.Serialization.SerializationException: Binary stream '116' does not contain a valid BinaryHeader. Possible causes are invalid stream or object version change between serialization and deserialization. i'm using a different instance. How may I avoid this error please

    Read the article

  • Sending large serialized objects over sockets is failing only when trying to grow the byte Array, bu

    - by FinancialRadDeveloper
    I have code where I am trying to grow the byte array while receiving the data over my socket. This is erroring out. public bool ReceiveObject2(ref Object objRec, ref string sErrMsg) { try { byte[] buffer = new byte[1024]; byte[] byArrAll = new byte[0]; bool bAllBytesRead = false; int iRecLoop = 0; // grow the byte array to match the size of the object, so we can put whatever we // like through the socket as long as the object serialises and is binary formatted while (!bAllBytesRead) { if (m_socClient.Receive(buffer) > 0) { byArrAll = Combine(byArrAll, buffer); iRecLoop++; } else { m_socClient.Close(); bAllBytesRead = true; } } MemoryStream ms = new MemoryStream(buffer); BinaryFormatter bf1 = new BinaryFormatter(); ms.Position = 0; Object obj = bf1.Deserialize(ms); objRec = obj; return true; } catch (System.Runtime.Serialization.SerializationException se) { objRec = null; sErrMsg += "SocketClient.ReceiveObject " + "Source " + se.Source + "Error : " + se.Message; return false; } catch (Exception e) { objRec = null; sErrMsg += "SocketClient.ReceiveObject " + "Source " + e.Source + "Error : " + e.Message; return false; } } private byte[] Combine(byte[] first, byte[] second) { byte[] ret = new byte[first.Length + second.Length]; Buffer.BlockCopy(first, 0, ret, 0, first.Length); Buffer.BlockCopy(second, 0, ret, first.Length, second.Length); return ret; } Error: mscorlibError : The input stream is not a valid binary format. The starting contents (in bytes) are: 68-61-73-43-68-61-6E-67-65-73-3D-22-69-6E-73-65-72 ... Yet when I just cheat and use a MASSIVE buffer size its fine. public bool ReceiveObject(ref Object objRec, ref string sErrMsg) { try { byte[] buffer = new byte[5000000]; m_socClient.Receive(buffer); MemoryStream ms = new MemoryStream(buffer); BinaryFormatter bf1 = new BinaryFormatter(); ms.Position = 0; Object obj = bf1.Deserialize(ms); objRec = obj; return true; } catch (Exception e) { objRec = null; sErrMsg += "SocketClient.ReceiveObject " + "Source " + e.Source + "Error : " + e.Message; return false; } } This is really killing me. I don't know why its not working. I have lifted the Combine from a suggestion on here too, so I am pretty sure this is not doing the wrong thing? I hope someone can point out where I am going wrong

    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

  • Binary stream 'NN' does not contain a valid BinaryHeader. Possible causes are invalid stream or obje

    - by FinancialRadDeveloper
    I am passing user defined classes over sockets. The SendObject code is below. It works on my local machine, but when I publish to the WebServer which is then communicating with the App Server on my own machine it fails. public bool SendObject(Object obj, ref string sErrMsg) { try { MemoryStream ms = new MemoryStream(); BinaryFormatter bf1 = new BinaryFormatter(); bf1.Serialize(ms, obj); byte[] byArr = ms.ToArray(); int len = byArr.Length; m_socClient.Send(byArr); return true; } catch (Exception e) { sErrMsg = "SendObject Error: " + e.Message; return false; } } I can do this fine if it is one class in my tools project and the other class about UserData just doesn't want to know. Frustrating! Ohh. I think its because the UserData class has a DataSet inside it. Funnily enough I have seen this work, but then after 1 request it goes loopy and I can't get it to work again. Anyone know why this might be? I have looked at comparing the dlls to make sure they are the same on the WebServer and on my local machine and they look to be so as I have turned on versioning in the AssemblyInfo.cs to double check. Edit: Ok it seems that the problem is with size. If I keep it under 1024 byes ( I am guessing here) it works on the web server and doesnt if it has a DataSet inside it.k In fact this is so puzzling I converted the DataSet to a string using ds.GetXml() and this also causes it to blow up. :( So it seems that across the network something with my sockets is wrong and doesn't want to read in the data. JonSkeet where are you. ha ha. I would offer Rep but I don't have any. Grr

    Read the article

  • deserialize system.outofmemoryexception

    - by clanier9
    I've got a serializeable class called Cereal with several public fields shown here <Serializable> Public Class Cereal Public id As Integer Public cardType As Type Public attacker As String Public defender As String Public placedOn As String Public attack As Boolean Public placed As Boolean Public played As Boolean Public text As String Public Sub New() End Sub End Class My client computer is sending a new Cereal to the host by serializing it shown here 'sends data to host stream (c1) Private Sub cSendText(ByVal Data As String) Dim bf As New BinaryFormatter Dim c As New Cereal c.text = Data bf.Serialize(mobjClient.GetStream, c) End Sub The host listens to the stream for activity and when something gets put on it, it is supposed to deserialize it to a new Cereal shown here 'accepts data sent from the client, raised when data on host stream (c2) Private Sub DoReceive(ByVal ar As IAsyncResult) Dim intCount As Integer Try 'find how many byte is data SyncLock mobjClient.GetStream intCount = mobjClient.GetStream.EndRead(ar) End SyncLock 'if none, we are disconnected If intCount < 1 Then RaiseEvent Disconnected(Me) Exit Sub End If Dim bf As New BinaryFormatter Dim c As New Cereal c = CType(bf.Deserialize(mobjClient.GetStream), Cereal) If c.text.Length > 0 Then RaiseEvent LineReceived(Me, c.text) Else RaiseEvent CardReceived(Me, c) End If 'starts listening for action on stream again SyncLock mobjClient.GetStream mobjClient.GetStream.BeginRead(arData, 0, 1024, AddressOf DoReceive, Nothing) End SyncLock Catch e As Exception RaiseEvent Disconnected(Me) End Try End Sub when the following line executes, I get a System.OutOfMemoryException and I cannot figure out why this isn't working. c = CType(bf.Deserialize(mobjClient.GetStream), Cereal) The stream is a TCPClient stream. I'm new to serialization/deserialization and using visual studio 11

    Read the article

  • deserializing multiple types from a stream

    - by clanier9
    I have a card game program, and so far, the chat works great back and forth over the TCPClient streams between host and client. I want to make it do this with serializing and deserializing so that I can also pass cards between host and client. I tried to create a separate TCPClient stream for the passing of cards but it didn't work and figured it may be easier to keep one TCPClient stream that gets the text messages as well as cards. So I created a class, called cereal, which has the properties for the cards that will help me rebuild the card from an embedded database of cards on the other end. Is there a way to make my program figure out whether a card has been put in the stream or if it's just text in the stream so I can properly deserialize it to a string or to a cereal? Or should I add a string property to my cereal class and when that property is filled in after deserializing to the cereal, i'll know it's just text (if that field is empty after deserializing i'll know it's a card)? I'm thinking a try catch, where it tries to deserialize to a string, and if it fails it will catch and cast as a cereal. Or am I just way off base with this and should choose another route? I'm using visual studio 2011, am using a binaryformatter, and am new to serializing/deserializing.

    Read the article

  • What is the best way to deserialize generics written with a different version of a signed assembly?

    - by Rick Minerich
    In other cases it has been suggested that you simply add a SerializationBinder which removes the version from the assembly type. However, when using generic collections of a type found in a signed assembly, that type is strictly versioned based on its assembly. Here is what I've found works. internal class WeaklyNamedAssemblyBinder : SerializationBinder { public override Type BindToType(string assemblyName, string typeName) { ResolveEventHandler handler = new ResolveEventHandler(CurrentDomain_AssemblyResolve); AppDomain.CurrentDomain.AssemblyResolve += handler; Type returnedType; try { AssemblyName asmName = new AssemblyName(assemblyName); var assembly = Assembly.Load(asmName); returnedType = assembly.GetType(typeName); } catch { returnedType = null; } finally { AppDomain.CurrentDomain.AssemblyResolve -= handler; } return returnedType; } Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args) { string truncatedAssemblyName = args.Name.Split(',')[0]; Assembly assembly = Assembly.Load(truncatedAssemblyName); return assembly; } } However, causing the binding process to change globally seems rather dangerous to me. Strange things could happen if serialization was happening in multiple threads. Perhaps a better solution is to do some regex manipulation of the typeName? What do you think?

    Read the article

  • BinaryFormatter in C# a good way to read files?

    - by mr-pac
    I want to read a binary file which was created outside of my program. One obvious way in C# to read a binary file is to define class representing the file and then use a BinaryReader and read from the file via the Read* methods and assign the return values to the class properties. What I don't like with the approach is that I manually have to write code that reads the file, although the defined structure represents how the file is stored. I also have to keep the order correct when I read. After looking a bit around I came across the BinaryFormatter which can automatically serialize and deserialze object in binary format. One great advantage would be that I can read and also write the file without creating additional code. However I wonder if this approach is good for files created from other programs on not just serialized .NET objects. Take for example a graphics format file like BMP. Would it be a good idea to read the file with a BinaryFormatter or is it better to manually and write via BinaryReader and BinaryWriter? Or are there any other approaches which suit better? I'am not looking for concrete examples but just for an advice what is the best way to implement that.

    Read the article

  • Deserialize Stream to List<T> or any other type

    - by Sam
    Attempting to deserialize a stream to List<T> (or any other type) and am failing with the error: The type arguments for method 'Foo.Deserialize<T>(System.IO.Stream)' cannot be inferred from the usage. Try specifying the type arguments explicitly. This fails: public static T Deserialize<T>(this Stream stream) { BinaryFormatter bin = new BinaryFormatter(); return (T)bin.Deserialize(stream); } But this works: public static List<MyClass.MyStruct> Deserialize(this Stream stream) { BinaryFormatter bin = new BinaryFormatter(); return (List<MyClass.MyStruct>)bin.Deserialize(stream); } or: public static object Deserialize(this Stream stream) { BinaryFormatter bin = new BinaryFormatter(); return bin.Deserialize(stream); } Is it possible to do this without casting, e.g. (List<MyStruct>)stream.Deserialize()?

    Read the article

  • C#: The input stream is not a valid binary format.

    - by Mcoroklo
    I have a problem with deserializing in C#/ASP.NET, which gives the exact error: The input stream is not a valid binary format. The starting contents (in bytes) are: 41-41-45-41-41-41-44-2F-2F-2F-2F-2F-41-51-41-41-41 ... What I am trying to do I have a structure with 3 classes. I have a class A which is a base class, and then class B and C which are derived from A. I am trying to store random types of B and C in the database using LINQ to SQL, in a column with the type VARCHAR(MAX). I cannot use BINARY as the length is around 15.000. My code... Error is in the LAST codeblock C# Code in Business layer- Storing a record private void AddTraceToDatabase(FightTrace trace) { MemoryStream recieverStream = new MemoryStream(); MemoryStream firedStream = new MemoryStream(); MemoryStream moveStream = new MemoryStream(); BinaryFormatter binaryFormatter = new BinaryFormatter(); binaryFormatter.Serialize(recieverStream,trace.Reciever); binaryFormatter.Serialize(firedStream,trace.FiredBy); binaryFormatter.Serialize(moveStream,trace.Move); string reciever = Convert.ToBase64String(recieverStream.ToArray()); string fired = Convert.ToBase64String(firedStream.ToArray()); string move = Convert.ToBase64String(moveStream.ToArray()); this.dataAccess.AddFightTrace(trace.TraceType.ToString(),reciever,move,fired,trace.DateTime,this.FightId); } C# Code in Data access layer - Storing a record public void AddFightTrace(string type, string reciever, string Move, string firedBy, DateTime firedAt, int fightid) { GameDataContext db = new GameDataContext(); dbFightTrace trace = new dbFightTrace(); trace.TraceType = type; trace.Reciever = reciever; trace.Move = Move; trace.FiredBy = firedBy; trace.FiredAt = firedAt; trace.FightId = fightid; db.dbFightTraces.InsertOnSubmit(trace); db.SubmitChanges(); } C# Code getting the entry in the database public List<dbFightTrace> GetNewTraces(int fightid, DateTime lastUpdate) { GameDataContext db = new GameDataContext(); var data = from d in db.dbFightTraces where d.FightId==fightid && d.FiredAt > lastUpdate select d; return data.ToList(); } C# Factory, converting from LINQ to SQL class to my objects THIS IS HERE THE ERROR COMES public FightTrace CreateTrace(dbFightTrace trace) { TraceType traceType = (TraceType) Enum.Parse(typeof(TraceType), trace.TraceType); BinaryFormatter formatter = new BinaryFormatter(); System.Text.UTF8Encoding enc = new System.Text.UTF8Encoding(); MemoryStream recieverStream = new MemoryStream(enc.GetBytes(trace.Reciever)); recieverStream.Position = 0; MemoryStream firedStream = new MemoryStream(enc.GetBytes(trace.FiredBy)); firedStream.Position = 0; MemoryStream movedStream = new MemoryStream(enc.GetBytes(trace.Move)); movedStream.Position = 0; // THE NEXT LINE HERE CAUSES THE ERROR NPC reciever = formatter.Deserialize(recieverStream) as NPC; Player fired = formatter.Deserialize(firedStream) as Player; BaseAttack attack = formatter.Deserialize(movedStream) as BaseAttack; FightTrace t = new FightTrace(traceType,reciever,attack,fired); t.TraceId = trace.FightTraceId; t.DateTime = trace.FiredAt; return t; } So the error happends when the first Deserialize method is run, with the above error. I have tried several things but I am quite lost on this one.. Thanks! :-)

    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

  • Binary serialization and deserialization without creating files (via strings)

    - by the_V
    Hi, I'm trying to create a class that will contain functions for serializing/deserializing objects to/from string. That's what it looks like now: public class BinarySerialization { public static string SerializeObject(object o) { string result = ""; if ((o.GetType().Attributes & TypeAttributes.Serializable) == TypeAttributes.Serializable) { BinaryFormatter f = new BinaryFormatter(); using (MemoryStream str = new MemoryStream()) { f.Serialize(str, o); str.Position = 0; StreamReader reader = new StreamReader(str); result = reader.ReadToEnd(); } } return result; } public static object DeserializeObject(string str) { object result = null; byte[] bytes = System.Text.Encoding.ASCII.GetBytes(str); using (MemoryStream stream = new MemoryStream(bytes)) { BinaryFormatter bf = new BinaryFormatter(); result = bf.Deserialize(stream); } return result; } } SerializeObject method works well, but DeserializeObject does not. I always get an exception with message "End of Stream encountered before parsing was completed". What may be wrong here?

    Read the article

  • Concurrent connections in C# socket

    - by Chu Mai
    There are three apps run at the same time, 2 clients and 1 server. The whole system should function as following: The client sends an serialized object to server then server receives that object as a stream, finally the another client get that stream from server and deserialize it. This is the sender: TcpClient tcpClient = new TcpClient(); tcpClient.Connect("127.0.0.1", 8888); Stream stream = tcpClient.GetStream(); BinaryFormatter binaryFormatter = new BinaryFormatter(); binaryFormatter.Serialize(stream, event); // Event is the sending object tcpClient.Close(); Server code: TcpListener listener = new TcpListener(IPAddress.Parse("127.0.0.1"), 8888); listener.Start(); Console.WriteLine("Server is running at localhost port 8888 "); while (true) { Socket socket = listener.AcceptSocket(); try { Stream stream = new NetworkStream(socket); // Typically there should be something to write the stream // But I don't knwo exactly what should the stream write } catch (Exception e) { Console.WriteLine("Exception: " + e.Message); Console.WriteLine("Disconnected: {0}", socket.RemoteEndPoint); } } The receiver: TcpClient client = new TcpClient(); // Connect the client to the localhost with port 8888 client.Connect("127.0.0.1", 8888); Stream stream = client.GetStream(); Console.WriteLine(stream); when I run only the sender and server, and check the server, server receives correctly the data. The problem is when I run the receiver, everything is just disconnected. So where is my problem ? Could anyone point me out ? Thanks

    Read the article

  • How to analyse contents of binary serialization stream?

    - by Tao
    I'm using binary serialization (BinaryFormatter) as a temporary mechanism to store state information in a file for a relatively complex (game) object structure; the files are coming out much larger than I expect, and my data structure includes recursive references - so I'm wondering whether the BinaryFormatter is actually storing multiple copies of the same objects, or whether my basic "number of objects and values I should have" arithmentic is way off-base, or where else the excessive size is coming from. Searching on stack overflow I was able to find the specification for Microsoft's binary remoting format: http://msdn.microsoft.com/en-us/library/cc236844(PROT.10).aspx What I can't find is any existing viewer that enables you to "peek" into the contents of a binaryformatter output file - get object counts and total bytes for different object types in the file, etc; I feel like this must be my "google-fu" failing me (what little I have) - can anyone help? This must have been done before, right??

    Read the article

  • ASP.NET ViewState Tips and Tricks #2

    - by João Angelo
    If you need to store complex types in ViewState DO implement IStateManager to control view state persistence and reduce its size. By default a serializable object will be fully stored in view state using BinaryFormatter. A quick comparison for a complex type with two integers and one string property produces the following results measured using ASP.NET tracing: BinaryFormatter: 328 bytes in view state IStateManager: 28 bytes in view state BinaryFormatter sample code: // DO NOT [Serializable] public class Info { public int Id { get; set; } public string Name { get; set; } public int Age { get; set; } } public class ExampleControl : WebControl { protected override void OnLoad(EventArgs e) { base.OnLoad(e); if (!this.Page.IsPostBack) { this.User = new Info { Id = 1, Name = "John Doe", Age = 27 }; } } public Info User { get { object o = this.ViewState["Example_User"]; if (o == null) return null; return (Info)o; } set { this.ViewState["Example_User"] = value; } } } IStateManager sample code: // DO public class Info : IStateManager { public int Id { get; set; } public string Name { get; set; } public int Age { get; set; } private bool isTrackingViewState; bool IStateManager.IsTrackingViewState { get { return this.isTrackingViewState; } } void IStateManager.LoadViewState(object state) { var triplet = (Triplet)state; this.Id = (int)triplet.First; this.Name = (string)triplet.Second; this.Age = (int)triplet.Third; } object IStateManager.SaveViewState() { return new Triplet(this.Id, this.Name, this.Age); } void IStateManager.TrackViewState() { this.isTrackingViewState = true; } } public class ExampleControl : WebControl { protected override void OnLoad(EventArgs e) { base.OnLoad(e); if (!this.Page.IsPostBack) { this.User = new Info { Id = 1, Name = "John Doe", Age = 27 }; } } public Info User { get; set; } protected override object SaveViewState() { return new Pair( ((IStateManager)this.User).SaveViewState(), base.SaveViewState()); } protected override void LoadViewState(object savedState) { if (savedState != null) { var pair = (Pair)savedState; this.User = new Info(); ((IStateManager)this.User).LoadViewState(pair.First); base.LoadViewState(pair.Second); } } }

    Read the article

  • changing the serialization procedure for a graph of objects (.net framework)

    - by pierusch
    Hello I'm developing a scientific application using .net framework. The application depends heavily upon a large data structure (a tree like structure) that has been serialized using a standard binaryformatter object. The graph structure looks like this: <serializable()>Public class BigObjet inherits list(of smallObject) end class <serializable()>public class smallObject inherits list(of otherSmallerObjects) end class ... The binaryFormatter object does a nice job but it's not optimized at all and the entire data structure reaches around 100Mb on my filesystem. Deserialization works too but it's pretty slow (around 30seconds on my quad core). I've found a nice .dll on codeproject (see "optimizing serialization...") so I wrote a modified version of the classes above overriding the default serialization/deserialization procedure reaching very good results. The problem is this: I can't lose the data previosly serialized with the old version and I'd like to be able to use the new serialization/deserialization method. I have some ideas but I'm pretty sure someone will be able to give me a proper and better advice ! use an "helper" graph of objects who takes care of the entire serialization/deserialization procedure reading data from the old format and converting them into the classes I nedd. This could work but the binaryformatter "needs" to know the types being serialized so........ :( modify the "old" graph to include a modified version of serialization procedure...so I'll be able to deserialize old file and save them with the new format......this doesn't sound too good imho. well any help will be higly highly appreciated :)

    Read the article

  • Reference to the Main Form whilst trying to Serialize objects in C#

    - by Paul Matthews
    I have a button on my main form which calls a method to serialize some objects to disk. I am trying to add these objects to an ArrayList and then serialize them using a BinaryFormatter and a FileStream. public void SerializeGAToDisk(string GenAlgName) { // Let's make a list that includes all the objects we // need to store a GA instance ArrayList GAContents = new ArrayList(); GAContents.Add(GenAlgInstances[GenAlgName]); // Structure and info for a GA GAContents.Add(RunningGAs[GenAlgName]); // There may be several running GA's using (FileStream fStream = new FileStream(GenAlgName + ".ga", FileMode.Create, FileAccess.Write, FileShare.None)) { BinaryFormatter binFormat = new BinaryFormatter(); binFormat.Serialize(fStream, GAContents); } } When running the above code I get the following exception: System.Runtime.Serialization.SerializationException was unhandled Message=Type 'WindowsFormsApplication1.Form1' in Assembly 'GeneticAlgApp, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' is not marked as serializable. So that means that somewhere in the objects I'm trying to save there must be a reference to the main form. The only possible references I can see are 3 delegates which all point to methods in the main form code. Do delegates get serialized as well? I can't seem to apply the [NonSerialized] attribute to them. Is there anything else I might be missing? Even better, is there a quick method to find the reference(s) that are causing the problem?

    Read the article

  • ASP.NET Session Management

    - by geekrutherford
    Great article (a little old but still relevant) about the inner workings of session management in ASP.NET: Underpinnings of the Session State Management Implementation in ASP.NET.   Using StateServer and the BinaryFormatter serialization occuring caused me quite the headache over the last few days. Curiously, it appears the w3wp.exe process actually consumes more memory when utilizing StateServer and storing somewhat large and complex data types in session.   Users began experiencing Out Of Memory exceptions in the production environment. Looking at the stack trace it related to serialization using the BinaryFormatter. Using remote debugging against our QA server I noted that the code in the application functioned without issue. The exception occured outside the context of the application itself when the request had completed and the web server was trying to serialize session state into the StateServer.   The short term solution is switching back to the InProc method. Thus far this has proven to consume considerably less memory and has caused no issues. Long term the complex object stored in session will be off-loaded into a web service used to access the information directly from the database outside the context of the object used to encapsulate it.

    Read the article

  • How do I save my whole program?

    - by user1444829
    What argument should be in this missing part of formatter.Serliaze to get the program to save just the program as a .exe? Ignore the Openfiles. class FileOption { OpenFileDialog openDialog = new OpenFileDialog(); SaveFileDialog saveDialog = new SaveFileDialog(); BinaryFormatter formatter = new BinaryFormatter(); public void Open() { } public void Save() { if (saveDialog.ShowDialog() == DialogResult.OK) { FileStream file = new FileStream(saveDialog.FileName, FileMode.Create); formatter.Serialize(file, x); // x means that i havent set anything there yet// file.Close(); } } }

    Read the article

  • difference between DataContract attribute and Serializable attribute in .net

    - by samar
    I am trying to create a deep clone of an object using the following method. public static T DeepClone<T>(this T target) { using (MemoryStream stream = new MemoryStream()) { BinaryFormatter formatter = new BinaryFormatter(); formatter.Serialize(stream, target); stream.Position = 0; return (T)formatter.Deserialize(stream); } } This method requires an object which is Serialized i.e. an object of a class who is having an attribute "Serializable" on it. I have a class which is having attribute "DataContract" on it but the method is not working with this attribute. I think "DataContract" is also a type of serializer but maybe different than that of "Serializable". Can anyone please give me the difference between the two? Also please let me know if it is possible to create a deepclone of an object with just 1 attribute which does the work of both "DataContract" and "Serializable" attribute or maybe a different way of creating a deepclone? Please help!

    Read the article

  • protobuf-net NOT faster than binary serialization?

    - by Ashish Gupta
    I wrote a program to serialize a 'Person' class using XMLSerializer, BinaryFormatter and ProtoBuf. I thought protobuf-net should be faster than the other two. Protobuf serialization was faster than XMLSerialization but much slower than the binary serialization. Is my understanding incorrect? Please make me understand this. Thank you for the help. Following is the output:- Person got created using protocol buffer in 347 milliseconds Person got created using XML in 1462 milliseconds Person got created using binary in 2 milliseconds Code below using System; using System.Collections.Generic; using System.Linq; using System.Text; using ProtoBuf; using System.IO; using System.Diagnostics; using System.Runtime.Serialization.Formatters.Binary; namespace ProtocolBuffers { class Program { static void Main(string[] args) { string XMLSerializedFileName = "PersonXMLSerialized.xml"; string ProtocolBufferFileName = "PersonProtocalBuffer.bin"; string BinarySerializedFileName = "PersonBinary.bin"; var person = new Person { Id = 12345, Name = "Fred", Address = new Address { Line1 = "Flat 1", Line2 = "The Meadows" } }; Stopwatch watch = Stopwatch.StartNew(); watch.Start(); using (var file = File.Create(ProtocolBufferFileName)) { Serializer.Serialize(file, person); } watch.Stop(); Console.WriteLine(watch.ElapsedMilliseconds.ToString()); Console.WriteLine("Person got created using protocol buffer in " + watch.ElapsedMilliseconds.ToString() + " milliseconds " ); watch.Reset(); watch.Start(); System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(person.GetType()); using (TextWriter w = new StreamWriter(XMLSerializedFileName)) { x.Serialize(w, person); } watch.Stop(); Console.WriteLine(watch.ElapsedMilliseconds.ToString()); Console.WriteLine("Person got created using XML in " + watch.ElapsedMilliseconds.ToString() + " milliseconds"); watch.Reset(); watch.Start(); using (Stream stream = File.Open(BinarySerializedFileName, FileMode.Create)) { BinaryFormatter bformatter = new BinaryFormatter(); //Console.WriteLine("Writing Employee Information"); bformatter.Serialize(stream, person); } watch.Stop(); Console.WriteLine(watch.ElapsedMilliseconds.ToString()); Console.WriteLine("Person got created using binary in " + watch.ElapsedMilliseconds.ToString() + " milliseconds"); Console.ReadLine(); } } [ProtoContract] [Serializable] public class Person { [ProtoMember(1)] public int Id {get;set;} [ProtoMember(2)] public string Name { get; set; } [ProtoMember(3)] public Address Address {get;set;} } [ProtoContract] [Serializable] public class Address { [ProtoMember(1)] public string Line1 {get;set;} [ProtoMember(2)] public string Line2 {get;set;} } }

    Read the article

  • Faster way to clone.

    - by AngryHacker
    I am trying to optimize a piece of code that clones an object: #region ICloneable public object Clone() { MemoryStream buffer = new MemoryStream(); BinaryFormatter formatter = new BinaryFormatter(); formatter.Serialize(buffer, this); // takes 3.2 seconds buffer.Position = 0; return formatter.Deserialize(buffer); // takes 2.1 seconds } #endregion Pretty standard stuff. The problem is that the object is pretty beefy and it takes 5.4 seconds (according ANTS Profiler - I am sure there is the profiler overhead, but still). Is there a better and faster way to clone?

    Read the article

  • packing fields of a class into a byte array in c#

    - by alex
    Hi all: I am trying to create a fast way to convert c# classes into byte array. I thought of serializing the class directly to a byte array using an example I found: // Convert an object to a byte array private byte[] ObjectToByteArray(Object obj) { if(obj == null) return null; BinaryFormatter bf = new BinaryFormatter(); MemoryStream ms = new MemoryStream(); bf.Serialize(ms, obj); return ms.ToArray(); } But the byte array I got contains some other information that are not related to the fields in the class. I guess it is also converting the Properties of the class. Is there a way to serialize only the fields of the class to a byte array? Thanks

    Read the article

1 2 3  | Next Page >