Incorrect reading data from .bin file - c#

I have two programs: one is test that students take and second is for teachers(teachers create some variants of test and add questions to it); Teacher program creates .bin files with tests and then student's open and take those tests. Data structure(class Question) are similiar in both programs;
Teacher's program class code:
[Serializable]
public class Question
{
public Question(string q_text, Dictionary<string, bool> ans, Image img)
{
text = q_text;
answers = ans;
image = img;
isAnswered = false;
}
public string text { get; set; }
public Dictionary<string, bool> answers { get; set; }
public Image image { get; set; }
public bool isAnswered;
public static void PersistObject(Dictionary<int, Question> q, Stream stream)
{
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(stream, q);
stream.Close();
}
public static Dictionary<int, Question> LoadObject(Stream stream)
{
try
{
BinaryFormatter formatter = new BinaryFormatter();
Dictionary<int, Question> deserializedObject = (Dictionary<int, Question>)formatter.Deserialize(stream);
stream.Close();
return deserializedObject;
}
catch
{
return null;
}
}
}
}
and student's program class code:
[Serializable]
class Question
{
public Question(string text, Image img, Dictionary<string, bool> ans)
{
question_text = text;
image = img;
answers = ans;
isAnswered = false;
}
public string question_text { get; set; }
public Dictionary<string, bool> answers { get; set; }
public Image image { get; set; }
public bool isAnswered;
public static Dictionary<int, Question> LoadObject(Stream stream)
{
try
{
BinaryFormatter formatter = new BinaryFormatter();
Dictionary<int, Question> deserializedObject = (Dictionary<int, Question>)formatter.Deserialize(stream);
stream.Close();
return deserializedObject;
}
catch
{
return null;
}
}
}
But when I try to read some test in student program:
string file = path + test_number + ".bin";
Stream myStream = File.Open(file, FileMode.Open);
questions = Question.LoadObject(myStream);
it sets questions to null. But when I read those files in teachers program then it's OK.(perhaps, it's OK, because I create those files in teachers mode too). Type of questions is Dictionary<int,Question> .What's the problem?

Related

How to Serialize Object to Xml

The class I want to store:
[Serializable]
public class Storagee
{
int tabCount;
List<string> tabNames;
List<EachItemListHolder> eachItemsHolder;
public void PreSetting(int count, List<string> strings, List<EachItemListHolder> items)
{
tabCount = count;
tabNames = strings;
eachItemsHolder = items;
}
public void PreSetting(int count ) //debug purpose
{
tabCount = count;
}
public int GetTabCount() { return tabCount; }
public List<string> GetTabNames() { return tabNames; }
public List<EachItemListHolder> GetListEachItemListHolder() { return eachItemsHolder; }
}
Serializing class:
namespace Book
{
class SaveAndLoad
{
public void SaveAll(Storagee str)
{
var path = #"C:\Temp\myserializationtest.xml";
using (FileStream fs = new FileStream(path, FileMode.Create))
{
XmlSerializer xSer = new XmlSerializer(typeof(Storagee));
xSer.Serialize(fs, str);
}
}
public Storagee LoadAll()
{
var path = #"C:\Temp\myserializationtest.xml";
using (FileStream fs = new FileStream(path, FileMode.Open)) //double
{
XmlSerializer _xSer = new XmlSerializer(typeof(Storagee));
var myObject = _xSer.Deserialize(fs);
return (Storagee)myObject;
}
}
}
}
Main method (Window form):
class Book
{
List<EachTab> eachTabs;
Storagee storagee;
SaveAndLoad saveAndLoad;
eachTabs = new List<EachTab>();
storagee = new Storagee();
saveAndLoad = new SaveAndLoad();
void Saving()
{
int count = UserTab.TabCount; // tab counts
storagee.PreSetting(count);
saveAndLoad.SaveAll(storagee);
}
}
It makes xml file but doesn't save data.
I tried the serializing code in different project and it worked.
but it doesn't in this solution
since I'm kind of new to coding I don't know what the problem is
especially serializing part.
serializing codes are copied and pasted with little tweak
It makes xml file but doesn't save data.
It doesn't save any data because your class does not provide any data that it can serialize. XmlSerializer only serializes public fields and properties and the Storagee class doesn't have any.
You could, for example, change your public getter methods to public properties:
public int TabCount { get; set; }
public List<string> TabNames { get; set; }
public List<string> EachItemsHolder { get; set; }
Alternatively, if using public properties is not an option, you could also look into using custom serialization by implementing IXmlSerializable.

How to export a class in a binary file

I need to export into a binary file an observable collection. This file will be parsed by an embeded software.
This is my class of Led configuration :
[XmlRoot("ConfLed")]
public class LedVals
{
#region Properties
[XmlAttribute]
public int ID { get; set; }
[XmlAttribute]
public string Type { get; set; } = "Trigger";
[XmlAttribute]
public string Binding { get; set; } = "OFF";
[XmlAttribute]
public int Trigger1 { get; set; } = 0;
[XmlAttribute]
public int Trigger2 { get; set; } = 0;
[XmlAttribute]
public string ColorT0 { get; set; } = "#000000";
[XmlAttribute]
public string ColorT1 { get; set; } = "#000000";
[XmlAttribute]
public string ColorT2 { get; set; } = "#000000";
#endregion
public LedVals()
{
}
public LedVals(int idParam, string typeParam, string bindingParam, int trig1Param, int trig2Param, string c0Param, string c1Param, string c2Param)
{
this.ID = idParam;
this.Type = typeParam;
this.Binding = bindingParam;
this.Trigger1 = trig1Param;
this.Trigger2 = trig2Param;
this.ColorT0 = c0Param;
this.ColorT1 = c1Param;
this.ColorT2 = c2Param;
}
}
And this is my serialize function for the observable collection of LedVals class (ListeLedTable) that I need to export:
public void SerializeLedTable(string filePathParam)
{
try
{
using (Stream mstream = File.Open(filePathParam + ".bin", FileMode.Create))
{
BinaryFormatter bin = new BinaryFormatter();
bin.Serialize(mstream, ListeLedTable);
}
}
}
The result is a file with binary values of the class properties and text description of the observable collection structure.
Is there a way to export properties values of a class like this ?
I can use a binaryWriter to write each property of my class in a loop, but I thought there might a simpler solution.
Thank you !
Use Marshal Techniques :
class Program
{
static void Main(string[] args)
{
LedVals ledVals = new LedVals();
int size = Marshal.SizeOf(ledVals); ;
IntPtr ptr = Marshal.AllocHGlobal(size);
byte[] buffer = new byte[Marshal.SizeOf(ledVals)];
Marshal.StructureToPtr(ledVals, ptr, true);
Marshal.Copy(ptr, buffer, 0, Marshal.SizeOf(ledVals));
Marshal.FreeHGlobal(ptr);
FileStream stream = File.OpenWrite("FILENAME");
BinaryWriter bWriter = new BinaryWriter(stream, Encoding.UTF8);
bWriter.Write(buffer);
}
}
[StructLayout(LayoutKind.Sequential)]
public class LedVals
{
public int ID { get; set; }
}
Using .NET binary serialization for any interop is a bad idea.
XML might be a better choice, but embedded devices usually lack the required horsepower to do any XML processing. I don't know what your embedded platform is, but there's a chance you could use Protocol Buffers (Protocol Buffers) to transfer binary data back and forth.

Deserialisation unable to list data

I am trying to create an application that can both serialise and deserialise data, i can serialise the information however when i try to read the information i am left with an empty list and i do not know why.
My Serialization class
[Serializable()]
public class FileSerilizeObject
{
public static string FileName { get; set; }
public static string Extension { get; set; }
public static string Base64 { get; set; }
public FileSerilizeObject(string filename, string extension, string base64vaulue)
{
FileName = filename;
Extension = extension;
Base64 = base64vaulue;
}
}
}
My serialization/deserialization methods
public void Serialize(List<FileSerilizeObject> List)
{
using (Stream stream = File.Open(savepath, FileMode.OpenOrCreate))
{
BinaryFormatter bin = new BinaryFormatter();
bin.Serialize(stream, List);
stream.Close();
}
}
public List<FileSerilizeObject> Deserialised(string OpenPath)
{
List<FileSerilizeObject> defo;
using(Stream stream = File.Open(OpenPath, FileMode.Open))
{
BinaryFormatter bin = new BinaryFormatter();
defo = (List<FileSerilizeObject>)bin.Deserialize(stream);
}
return defo;
}
I have checked to insure that the file paths are correct and that the file itself is not empty.Everything is fine however the "defo" list is always empty so i can only assume the issue is with the defo = (List<FileSerilizeObject>)bin.Deserialize(stream);Line however i do not know why.
You need to remove the static from your properties
[Serializable]
public class FileSerializeObject
{
public string FileName { get; set; }
public string Extension { get; set; }
public string Base64 { get; set; }
public FileSerializeObject(string filename, string extension, string base64vaulue)
{
FileName = filename;
Extension = extension;
Base64 = base64vaulue;
}
}
Try to set the [Serializable()] attribute for each property.
So it would look like this:
[Serializable()]
public class FileSerilizeObject
{
[Serializable()]
public string FileName { get; set; }
[Serializable()]
public string Extension { get; set; }
[Serializable()]
public string Base64 { get; set; }
public FileSerilizeObject(string filename, string extension, string base64vaulue)
{
FileName = filename;
Extension = extension;
Base64 = base64vaulue;
}
}
}
EDIT: Removed static keyword from properties.
I tested your code into a console application and it is working for me, I tested with VS 2013 but I used the same code that you wrote above.
Some details:
1. I removed the word static form the "FileSerilizeObject"
The class FileSerilizeObject
[Serializable()]
public class FileSerilizeObject
{
public string FileName { get; set; }
public string Extension { get; set; }
public string Base64 { get; set; }
public FileSerilizeObject(string filename, string extension, string base64vaulue)
{
FileName = filename;
Extension = extension;
Base64 = base64vaulue;
}
}
Functions
public static void Serialize(List<FileSerilizeObject> List)
{
using (Stream stream = File.Open(#"C:\Users\ttest\Desktop\folder1\data.bin", FileMode.OpenOrCreate))
{
BinaryFormatter bin = new BinaryFormatter();
bin.Serialize(stream, List);
stream.Close();
}
}
public static List<FileSerilizeObject> Deserialised(string OpenPath)
{
List<FileSerilizeObject> defo;
using (Stream stream = File.Open(OpenPath, FileMode.Open))
{
BinaryFormatter bin = new BinaryFormatter();
defo = (List<FileSerilizeObject>)bin.Deserialize(stream);
}
return defo;
}
Main
var bytes = Encoding.UTF8.GetBytes("dffesdbcdef==");
var base64 = Convert.ToBase64String(bytes);
FileSerilizeObject f1 = new FileSerilizeObject("test", "jpg", base64);
bytes = Encoding.UTF8.GetBytes("ggasddbcdef==");
base64 = Convert.ToBase64String(bytes);
FileSerilizeObject f2 = new FileSerilizeObject("test2", "png", base64);
bytes = Encoding.UTF8.GetBytes("asddffasdasdasdesdbcdef==");
base64 = Convert.ToBase64String(bytes);
FileSerilizeObject f3 = new FileSerilizeObject("test3", "doc", base64);
List<FileSerilizeObject> lFiles = new List<FileSerilizeObject>();
lFiles.Add(f1);
lFiles.Add(f2);
lFiles.Add(f3);
Serialize(lFiles);
Deserialised(#"C:\Users\rjimen4x\Desktop\tutoriales\data.bin");

Serialization of two Dictionaries at once

I have two classes as below and I'm using them in two separate Dictionaries. How can I Serialize these two Dictionaries to a single file? my Serialization implementation for a single Dictionary can be found at this link:
Serialize a Dictionary<string, object>
[Serializable]
class Beam
{
public string Name { get; set; }
public double Width { get; set; }
}
[Serializable]
class Column
{
public string Name { get; set; }
public double Width { get; set; }
}
Here are my Dictionaries:
var Dic1 = new Dictionary<string, Beam>
{
{"Beam1", new Beam{Name = "B1", Width = 10}},
{"Beam2", new Beam{Name = "B2", Width = 5}},
};
var Dic2 = new Dictionary<string, Column>
{
{"Column1", new Column{Name = "C1", Width = 10}},
{"Column2", new Column{Name = "C2", Width = 5}},
};
Here is the complete code I've written so far but I'm getting an exception:
[Serializable]
public static class Building
{
public static Dictionary<string, Beam> Beams;
public static Dictionary<string, Column> Columns;
}
[Serializable]
public class Beam
{
public string Name { get; set; }
}
[Serializable]
public class Column
{
public string Name { get; set; }
}
static class Program
{
static void Main()
{
Building.Beams.Add("Beam1", new Beam { Name = "B1"});
Building.Columns.Add("Column1", new Column { Name = "C1" });
Serialize();
}
static void Serialize()
{
var fs = new FileStream("DataFile.dat", FileMode.Create);
var formatter = new BinaryFormatter();
try
{
// I'm getting an excepting here:
// 'Savef.Building' is a 'type' but is used like a 'variable'
formatter.Serialize(fs, Building);
}
catch (SerializationException e)
{
Console.WriteLine("Failed to serialize. Reason: " + e.Message);
throw;
}
finally
{
fs.Close();
}
}
}
Create a class marked with the Serializable attribute, containing instances of these two dictionaries:
[Serializable]
public class Building
{
public static Building Instance = new Building();
public readonly Dictionary<string, Beam> Beams = new Dictionary<string, Beam>();
public readonly Dictionary<string, Column> Columns = new Dictionary<string, Column>();
public static Dictionary<string, Beam> AllBeams
{
get { return Instance.Beams; }
}
}
EDIT
A Singleton pattern used to avoid the exception.
In the other parts of the code use Building.Instance to access the dictionaries.
EDIT2
A static property introduced: Building.AllBeams. You can use it as shorthand.

Derived Class Deserialization

I have a problem with deserialization with my logic simulation program.
Here are my element classes:
public class AndGateData : TwoInputGateData
{
}
public class TwoInputGateData : GateData
{
public TwoInputGateData()
{
Input2 = new InputData();
Input1 = new InputData();
}
public InputData Input1 { get; set; }
public InputData Input2 { get; set; }
}
public class GateData : ElementData
{
public GateData()
{
OutputData = new OutputData();
}
public OutputData OutputData { get; set; }
}
public class ElementData
{
public int Delay { get; set; }
public Guid Id { get; set; }
}
And here are classes responsible for sockets:
public class InputData : SocketData
{
}
public class SocketData
{
public Guid Id { get; set; }
public SignalData SignalData { get; set; }
}
SignalData is not important here. So, I won't write it (in order to keep this question clean) here unless somebody says it is necessary.
CircuitData is very important:
[XmlRoot("Circuit")]
public class CircuitData
{
[XmlElement(typeof(AndGateData))]
[XmlElement(typeof(OrGateData))]
public List<ElementData> elements = new List<ElementData>();
public List<WireData> wires = new List<WireData>();
public void AddElement(ElementData element)
{
elements.Add(element);
}
public void AddWire(WireData wire)
{
wires.Add(wire);
}
}
Wires are not important right now.
Now, I have written some Serialization:
public class CircuitDataWriter
{
public static void Write(object obj, string fileName)
{
var xmlFormat = new XmlSerializer(typeof(CircuitData));
using(Stream fStream = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None) )
{
xmlFormat.Serialize(fStream,obj);
}
Console.WriteLine("Circuit saved in XML format.");
}
}
It works just like I wanted, it produces that xml document:
<?xml version="1.0"?>
-<Circuit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
-<AndGateData>
<Delay>10</Delay>
<Id>bfee6dd7-5946-4b7b-9d0b-15d5cf60e2bf</Id>
-<OutputData> <Id>00000000-0000-0000-0000-000000000000</Id> </OutputData>
-<Input1> <Id>7c767caf-79a9-4c94-9e39-5c38ec946d1a</Id> <SignalData xsi:type="SignalDataOn"/> </Input1>
-<Input2> <Id>d2cad8f8-8528-4db3-9534-9baadb6a2a14</Id> <SignalData xsi:type="SignalDataOff"/> </Input2>
</AndGateData>
<wires/>
</Circuit>
But I have problem with my DESERIALIZATION. Here is the code:
public static CircuitData Read()
{
var reader = new XmlSerializer(typeof(CircuitData));
StreamReader file = new StreamReader("Circuit.xml");
var returnCircuitData = new CircuitData();
returnCircuitData = (CircuitData) reader.Deserialize(file);
return returnCircuitData;
}
Now, it deserializes my Circuit.xml to object, but this object only contains Id and Delay, it does not contain Input1, Input2 or Output. So, it is treated like Element, not like AndGate. I tried to solve it out for a day but it seems that no one has that kind of problem.
I have a suggestion for you, make the Write method generic like this and create the serializer using objectToSerialize.GetType():
public static void Write<T>(T objectToSerialize, string fileName)
{
var xmlSerializer = new XmlSerializer(objectToSerialize.GetType());
...
}
The XmlSerializer.Deserialize() method returns object, you can make your Read method generic like this:
public static T Read<T>(string fileName)
{
var serializer = new XmlSerializer(typeof(T));
using (StreamReader file = new StreamReader(fileName))
{
return (T)serializer.Deserialize(file);
}
}
Other than that you might want to read about:
XmlInclude that is used when you serialize derived classes.
XmlArray and XmlArrayItem that are used for controlling serialization of arrays

Categories

Resources