-
Saving Structures Within Binary Files
Hey guys. I'm currently making a program as a self study guide for my coarses in college. Basically it allows me to add potential multiple choice test questions for any coarse I choose and save it to a file in binary format. And it allows me to test myself by randomly displaying the questions after loading it from file. Well....I'm stuck on figuring out how I can save it.
Basically how I have my structures is like this. I have a number of subjects, which are my coarses in college. Each subject has chapters, which is another structure. And each chapter has questions to that chapter, with possible random answers related to the right answer but will be the wrong answer:
vb.net Code:
Private Structure Question_Type
<VBFixedString(256)> Dim Answer As String
<VBFixedString(256)> Dim Rnd_Answer() As String
Public Sub Initialize()
ReDim Rnd_Answer(2)
End Sub
End Structure
Private Structure Chapter_Type
Dim Question() As Question_Type
Dim Number_of_Questions As Integer
Public Sub Initialize()
ReDim Question(Number_of_Questions)
End Sub
End Structure
Private Structure Subject_Type
Dim Chapter() As Chapter_Type
Dim Number_Of_Chapters As Integer
Public Sub Initialize()
ReDim Chapter(Number_Of_Chapters)
End Sub
End Structure
Private Subject(2) As Subject_Type
And if I were to save it as a binary file, I haven't the slightest clue on how I'm gonna do it :eek2:
vb.net Code:
Try
Binary_Writer = New BinaryWriter(New FileStream(Application.StartupPath & "\Test.bin", FileMode.Create))
Catch err As IOException
MessageBox.Show(err.Message + "\n Cannot create file.", "", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
'Subject > Chapter > Questions
'Don't know how I am gonna save this
Binary_Writer.Write(???)
Without having to save multiple files cause I only wanna work with one file that holds everything, I need to be able to save the questions with the random wrong answers with the associated chapters and subjects, and be able to load it from whatever subject and chapter of my choosing, and get the random questions to test myself associated with that chapter and subject. I know its 2 in the morning but I'm stumpt. Maybe I need some sleep to think about it but if anyone has any bright ideas, I would appreciate it. Thanks in advance. :bigyello:
-
Re: Saving Structures Within Binary Files
May I ask why you're using structures and the VBFixedString attribute? Are you using unmanaged code that you haven't shown us?
-
Re: Saving Structures Within Binary Files
Also, why must it be saved as binary not text? Why must it be a file rather than some other data store such as a database?
If I was going to save a set of data to a binary file, I'd probably stick the data in a data transfer object and pass it to a binary serializer.
-
Re: Saving Structures Within Binary Files
I dunno, its just my style to save stuff in binary format. I've been doing it for years. I'm just confused as to how im gonna save the questions for each subject for each class. Even if it were to be in text format, its still gonna be confusing. I'm just trying to make the program to where I can create my own questions and test myself so I'm ready for any test they toss at me. And I limited it so the files I save it as arent ending up gigantic in size. There wont be more than 255 characters anyways.
-
Re: Saving Structures Within Binary Files
You need to mark your class/structures with the <Serializable()> attribute. Then you need use the BinaryFormatter to serialize and deserialize your items. You might need to wrap all the items you're saving in another serializable class or structure or collection so you can combine it all in one place.
Also, don't worry about the size of your strings because .Net will only write as much has it has to and not waste any space.
-
Re: Saving Structures Within Binary Files
This thread shows me working through this exact issue
http://www.vbforums.com/showthread.p...t=serializable
-
Re: Saving Structures Within Binary Files
I must say it's screaming database at me but at least get out of that VB6 way of thinking. Structures and arrays are so ... well ... last century when it comes to data storage. Classes give you instant serializability. Lists give you easy nesting in a tree structure which is what you obviously need here. Why make things harder than they need to be?
-
Re: Saving Structures Within Binary Files
Classes or structures can both be serialized, but I believe that neither one gives you quite 'instant' serializability. I believe that you have to add the <Serializable()> attribute to either one, as OICU812 stated. I would be inclined to keep them in a list, though, rather than an array, since it seems unlikely that the number won't be changing. Other than that, I'm totally in favor of binary serialization. If the link that szlamany posted isn't sufficient for you, you could search on my name and Binary Serialization, as I've posted a pair of methods that I've used to serialize to and from a Base64 encoded string...which I think is a slight modification of some code that JMC gave me, so it's like a giant circle. Somewhere around here I also have some code that I use to serialize to a memory stream from a robot project. I have long since forgotten where I got that from, but it was here, I think. They are all pretty similar. Serializing to a stream doesn't care so much what kind of stream you are using.
By the way, coarse is rather rough. The word you were looking for is, of course, course. You might consider that to be a coarse course correction.
-
Re: Saving Structures Within Binary Files
Quote:
neither one gives you quite 'instant' serializability
I'm sorry. I 'av a cold! [Waits for reference to be plucked from cultural soup]
(Looks like it's gonna be a stinker too, dagnabbit!)
You know what I meant. I might even have known myself at one point!
-
Re: Saving Structures Within Binary Files
I find that cultural soup is good for a cold. If you get enough cultural soup you are sure to get a cold. I tried occultural soup once, but found the ectoplasm to be thicker than egg drop, at which point an upholstrygeist levitated the bowl, resurfaced my table in some kind of velvet, then dumped the bowl on my head and laughed at my furniture. It was unsettling.
By the way, here are the two methods for serialization:
Code:
Private Function SerializeTheme() As String
If mConfiguration IsNot Nothing AndAlso mConfiguration.ThemeID <> -1 Then
Try
Dim bf As New System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
Dim mStream As New System.IO.MemoryStream
Dim bReader As New System.IO.BinaryReader(mStream)
bf.Serialize(mStream, mConfiguration)
mStream.Position = 0
Return Convert.ToBase64String(bReader.ReadBytes(CInt(mStream.Length)))
Catch ex As Exception
Windows.Forms.MessageBox.Show("Failed while saving the theme. The default will be used next time. The error message was: " & Environment.NewLine & Environment.NewLine & ex.Message, "Serial Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
Return String.Empty
End Try
Else
Return String.Empty
End If
End Function
Private Shared Function DeSerializeTheme(ByVal themeAsString As String) As ThemeWrapper
Dim bf As New System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
Dim mStream As New System.IO.MemoryStream
Dim bWriter As New System.IO.BinaryWriter(mStream)
If themeAsString = String.Empty Then
Return Nothing
End If
Try
bWriter.Write(Convert.FromBase64String(themeAsString))
mStream.Position = 0
Return DirectCast(bf.Deserialize(mStream), ThemeWrapper)
Catch ex As Exception
Return Nothing
End Try
End Function
In this example, I'm serializing/deserializing a class called ThemeWrapper, but that's unimportant. The more important part is the ease of serializing to a stream...which in this case is a memorystream, but others can be used.
-
Re: Saving Structures Within Binary Files
I've been doing some class serialization lately and I haven't had to do anything to my classes to get them to serialize. Maybe that's just because I've been serializing to xml files on disk? The only serialization attributes I had to add were to the generic list I serialize - so it will know what the inherited classes that I add to the list look like. But the classes that I added have no attributes related to serialization.
-
Re: Saving Structures Within Binary Files
XML serialization is not the same as binary serialization. There are pluses and minuses to each, and different requirements for each. For example, binary serialization includes information about the assembly that did the serialization, whereas XML serialization does not, which makes XML serialization more generic, which it might as well be, since it can be read and manipulated by any text editor.
-
Re: Saving Structures Within Binary Files
Guess I wasn't paying much attention to those serialization articles I found. :eek:
-
Re: Saving Structures Within Binary Files
@dolot, If you have fixed length strings you don't need any serialization.
Simple data types still have fixed lengths, but something different from VB6.
I was doing many of that kind binary operations and I can tell you for sure what will happen.
> You will change your technic of work to some more modern level
OR
> You will abandon .NET as UNUSABLE for that kind of work with data
BECAUSE
> (among other problems) .NET is horribly slow with that, say more than 100x slower than VB6!
Why don't you try with database?
It is even simpler than work with random access or pure binary files.
Yet much more powerful.
If you still think you would use that see this:
Code:
Public Sub RListRec(ByVal GetPut As Integer, ByVal Record As Integer, ByVal RList As RListStruct, ByVal MaxR as Integer)
Dim FrL As Integer = FreeFile()
FileOpen(FrL, fFilePath, OpenMode.Random, OpenAccess.ReadWrite, OpenShare.Shared, Len(RList))
MaxR = CInt(LOF(FrL) / Len(RList))
If GetPut = 1 Then
FilePut(FrL, RList, Record)
Else
'' See this :)
Dim temp As ValueType = CType(New RList, ValueType)
FileGet(FrL, temp, Record)
RList = CType(temp, RList)
End If
FileClose(FrL)
End Sub
-
Re: Saving Structures Within Binary Files
Quote:
(among other problems) .NET is horribly slow with that, say more than 100x slower than VB6!
100x, eh? So what takes 1 second in VB6 takes 1 minute and 40 seconds in VB.Net?
-
Re: Saving Structures Within Binary Files
Quote:
Originally Posted by
dunfiddlin
100x, eh? So what takes 1 second in VB6 takes 1 minute and 40 seconds in VB.Net?
I don't measure strictly but it is possible so.
In short words, work with binary files like data files is quite unusable slow.
Especially for us which know how (fast and easy) that was in VB6.
Here is critical part in often opening and accessing files for read/write/seek and so...
Loading large chunk of binary data IS fast enough.
-
Re: Saving Structures Within Binary Files
Thanks for the info guys but I'm still stuck as to how I'm gonna save it to file due to the fact that is data that is part of a structure that is part of another structure (yes like a tree.) And I dont wanna make it a class because it is pointless to do so because im not doing any inheriting, properties, and methods. Just simple variables and arrays. Heck I don't even use classes in my game programming o.O. And I know of the <Serializable()> command but I never really worked with it before except maybe one time due to copy and pasting source code. Don't know how it works in depth.
So how can I save and load the data thats tree'ed within a structure in a binary file correctly?
If I were to break it down again you have a number of subjects to choose from, so lets say C++ class, VB class, and Speech class. Each class has a book that has a number of chapters. And each chapter has a number of questions in multiple choice, with 4 choices. One being the correct answer. And I wish to save it all within one file, if its possible. The file will need to save the particular subject with the number of questions regarding that subject with the actual questions and possible answers to them questions. I'm also making it to where I can add more and more questions to that particular chapter to the subject.
It's boggling my mind on how I can save it in this manner because of the fact that its tree'ed. Even if I did make it a class, it wouldnt matter because I would run into the same problem on saving it and loading it as a tree.
-
Re: Saving Structures Within Binary Files
Quote:
So how can I save and load the data thats tree'ed within a structure in a binary file correctly?
In the end if the serialization class won't work, do it by manually. Correctness is then a matter of being able to read what you write without consuming too many resources.
As I understand it, you have a structure with multiple instances saved in a way that can be modeled with a tree view. Am I correct?
If so create a virtual directory of structures using 2 data tables; 1 to hold the structures and 1 to hold the tree. Both table can be written to xml using the WriteXML method. I'm not really sure if this would address your problem, because admittedly, I didn't read the entire thread. If you need details, let me know.
kevin
-
Re: Saving Structures Within Binary Files
Well I'm not using a tree view nor working with xml. The data is saved in such a way that it is tree'ed, only as structures within structures. Its quite challenging yet the answer seems so simple but its not o.o
-
Re: Saving Structures Within Binary Files
No, I understand you are not working with a tree, but if done properly anything that can be organized in to a tree view can be written to a file using 2 tables. Whether you write them in in XML or text or any other method is up to you.
<zen>If the answer is simple then let it be so, for if you do not, the answer will only complicate itself</zen>
-
Re: Saving Structures Within Binary Files
But.....is it possible without having to use a treeview? That is the question.
-
Re: Saving Structures Within Binary Files
Quote:
Originally Posted by
Jacob Roman
But.....is it possible without having to use a treeview? That is the question.
yea. A tree view is only a representation of data that is stored somewhere. Think of it like a virtual directory of structures (files) much like windows explorer, except the only files you have are your structures. Does that fit your bill?
-
Re: Saving Structures Within Binary Files
Only if I'm able to figure out how to do it. I know how I want it saved, but not quite sure how it should be coded. How can a file be saved in binary format in such a way that its tree'ed? I can Binary_Writer.Write() all I want but there doesn't seem to be a way to organize it within the file itself as writing to lets say the answers to questions to a chapter to a subject. My brain is pulsating on the very idea.
-
Re: Saving Structures Within Binary Files
I don't use the binary writer, but if you can use it to write a data table, then yea, it can be done. pm me and I can send you some code if you'd like