PHP User Warning: fetch_template() calls should be replaced by the vB_Template class. Template name: bbcode_highlight in ..../includes/functions.php on line 4197

PHP User Warning: fetch_template() calls should be replaced by the vB_Template class. Template name: bbcode_highlight in ..../includes/functions.php on line 4197
VS 2013 Saving Structures Within Binary Files-VBForums
Results 1 to 24 of 24

Thread: Saving Structures Within Binary Files

  1. #1

    Thread Starter
    Android OpenGL ES Guru Jacob Roman's Avatar
    Join Date
    Aug 2004
    Location
    Miami Beach, FL
    Posts
    5,256

    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:
    1. Private Structure Question_Type
    2.         <VBFixedString(256)> Dim Answer As String
    3.         <VBFixedString(256)> Dim Rnd_Answer() As String
    4.         Public Sub Initialize()
    5.             ReDim Rnd_Answer(2)
    6.         End Sub
    7.     End Structure
    8.  
    9.     Private Structure Chapter_Type
    10.         Dim Question() As Question_Type
    11.         Dim Number_of_Questions As Integer
    12.         Public Sub Initialize()
    13.             ReDim Question(Number_of_Questions)
    14.         End Sub
    15.     End Structure
    16.  
    17.     Private Structure Subject_Type
    18.         Dim Chapter() As Chapter_Type
    19.         Dim Number_Of_Chapters As Integer
    20.         Public Sub Initialize()
    21.             ReDim Chapter(Number_Of_Chapters)
    22.         End Sub
    23.     End Structure
    24.  
    25.     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

    vb.net Code:
    1. Try
    2.             Binary_Writer = New BinaryWriter(New FileStream(Application.StartupPath & "\Test.bin", FileMode.Create))
    3.         Catch err As IOException
    4.             MessageBox.Show(err.Message + "\n Cannot create file.", "", MessageBoxButtons.OK, MessageBoxIcon.Error)
    5.         End Try
    6.  
    7.         'Subject > Chapter > Questions
    8.  
    9.         'Don't know how I am gonna save this
    10.         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.

  2. #2
    .NUT jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    103,892

    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?

  3. #3
    PowerPoster Evil_Giraffe's Avatar
    Join Date
    Aug 2002
    Location
    Suffolk, UK
    Posts
    2,555

    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.

  4. #4

    Thread Starter
    Android OpenGL ES Guru Jacob Roman's Avatar
    Join Date
    Aug 2004
    Location
    Miami Beach, FL
    Posts
    5,256

    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.

  5. #5
    Addicted Member
    Join Date
    Oct 2012
    Location
    Springfield, IL
    Posts
    142

    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.

  6. #6
    MS SQL Powerposter szlamany's Avatar
    Join Date
    Mar 2004
    Location
    CT
    Posts
    17,866

    Re: Saving Structures Within Binary Files

    This thread shows me working through this exact issue

    http://www.vbforums.com/showthread.p...t=serializable

    *** Read the sticky in the DB forum about how to get your question answered quickly!! ***

    Please remember to rate posts! Rate any post you find helpful - even in old threads! Use the link to the left - "Rate this Post".

    Some Informative Links:
    [ SQL Rules to Live By ] [ Reserved SQL keywords ] [ When to use INDEX HINTS! ] [ Passing Multi-item Parameters to STORED PROCEDURES ]
    [ Solution to non-domain Windows Authentication ] [ Crazy things we do to shrink log files ] [ SQL 2005 Features ] [ Loading Pictures from DB ]

    MS MVP 2006, 2007, 2008

  7. #7
    PowerPoster dunfiddlin's Avatar
    Join Date
    Jun 2012
    Posts
    8,242

    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?
    As the 6-dimensional mathematics professor said to the brain surgeon, "It ain't Rocket Science!"

    Reviews: "dunfiddlin likes his DataTables" - jmcilhinney

    Please be aware that whilst I will read private messages (one day!) I am unlikely to reply to anything that does not contain offers of cash, fame or marriage!

  8. #8
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    34,558

    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.
    My usual boring signature: Nothing

  9. #9
    PowerPoster dunfiddlin's Avatar
    Join Date
    Jun 2012
    Posts
    8,242

    Re: Saving Structures Within Binary Files

    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!
    As the 6-dimensional mathematics professor said to the brain surgeon, "It ain't Rocket Science!"

    Reviews: "dunfiddlin likes his DataTables" - jmcilhinney

    Please be aware that whilst I will read private messages (one day!) I am unlikely to reply to anything that does not contain offers of cash, fame or marriage!

  10. #10
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    34,558

    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.
    My usual boring signature: Nothing

  11. #11
    Frenzied Member dolot's Avatar
    Join Date
    Nov 2007
    Location
    Music city, U.S.A.
    Posts
    1,248

    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.
    I always add to the reputation of those whose post are helpful, and even occasionally to those whose posts aren't helpful but who obviously put forth a valiant effort. That is, when the system will allow it.
    My war with a browser-redirect trojan

  12. #12
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    34,558

    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.
    My usual boring signature: Nothing

  13. #13
    Frenzied Member dolot's Avatar
    Join Date
    Nov 2007
    Location
    Music city, U.S.A.
    Posts
    1,248

    Re: Saving Structures Within Binary Files

    Guess I wasn't paying much attention to those serialization articles I found.
    I always add to the reputation of those whose post are helpful, and even occasionally to those whose posts aren't helpful but who obviously put forth a valiant effort. That is, when the system will allow it.
    My war with a browser-redirect trojan

  14. #14
    Addicted Member
    Join Date
    Sep 2009
    Posts
    190

    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
    Last edited by nime; Jan 21st, 2014 at 02:14 AM.

  15. #15
    PowerPoster dunfiddlin's Avatar
    Join Date
    Jun 2012
    Posts
    8,242

    Re: Saving Structures Within Binary Files

    (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?
    As the 6-dimensional mathematics professor said to the brain surgeon, "It ain't Rocket Science!"

    Reviews: "dunfiddlin likes his DataTables" - jmcilhinney

    Please be aware that whilst I will read private messages (one day!) I am unlikely to reply to anything that does not contain offers of cash, fame or marriage!

  16. #16
    Addicted Member
    Join Date
    Sep 2009
    Posts
    190

    Re: Saving Structures Within Binary Files

    Quote Originally Posted by dunfiddlin View Post
    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.

  17. #17

    Thread Starter
    Android OpenGL ES Guru Jacob Roman's Avatar
    Join Date
    Aug 2004
    Location
    Miami Beach, FL
    Posts
    5,256

    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.

  18. #18
    Still learning kebo's Avatar
    Join Date
    Apr 2004
    Location
    Gardnerville,nv
    Posts
    3,708

    Re: Saving Structures Within Binary Files

    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
    Process control doesn't give you good quality, it gives you consistent quality.
    Good quality comes from consistently doing the right things.

    Vague general questions have vague general answers.
    A $100 donation is required for me to help you if you PM me asking for help. Instructions for donating to one of our local charities will be provided.

    ______________________________
    Last edited by kebo : Now. Reason: superfluous typo's

  19. #19

    Thread Starter
    Android OpenGL ES Guru Jacob Roman's Avatar
    Join Date
    Aug 2004
    Location
    Miami Beach, FL
    Posts
    5,256

    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

  20. #20
    Still learning kebo's Avatar
    Join Date
    Apr 2004
    Location
    Gardnerville,nv
    Posts
    3,708

    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>
    Last edited by kebo; Jan 21st, 2014 at 11:46 PM.
    Process control doesn't give you good quality, it gives you consistent quality.
    Good quality comes from consistently doing the right things.

    Vague general questions have vague general answers.
    A $100 donation is required for me to help you if you PM me asking for help. Instructions for donating to one of our local charities will be provided.

    ______________________________
    Last edited by kebo : Now. Reason: superfluous typo's

  21. #21

    Thread Starter
    Android OpenGL ES Guru Jacob Roman's Avatar
    Join Date
    Aug 2004
    Location
    Miami Beach, FL
    Posts
    5,256

    Re: Saving Structures Within Binary Files

    But.....is it possible without having to use a treeview? That is the question.

  22. #22
    Still learning kebo's Avatar
    Join Date
    Apr 2004
    Location
    Gardnerville,nv
    Posts
    3,708

    Re: Saving Structures Within Binary Files

    Quote Originally Posted by Jacob Roman View Post
    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?
    Process control doesn't give you good quality, it gives you consistent quality.
    Good quality comes from consistently doing the right things.

    Vague general questions have vague general answers.
    A $100 donation is required for me to help you if you PM me asking for help. Instructions for donating to one of our local charities will be provided.

    ______________________________
    Last edited by kebo : Now. Reason: superfluous typo's

  23. #23

    Thread Starter
    Android OpenGL ES Guru Jacob Roman's Avatar
    Join Date
    Aug 2004
    Location
    Miami Beach, FL
    Posts
    5,256

    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.

  24. #24
    Still learning kebo's Avatar
    Join Date
    Apr 2004
    Location
    Gardnerville,nv
    Posts
    3,708

    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
    Process control doesn't give you good quality, it gives you consistent quality.
    Good quality comes from consistently doing the right things.

    Vague general questions have vague general answers.
    A $100 donation is required for me to help you if you PM me asking for help. Instructions for donating to one of our local charities will be provided.

    ______________________________
    Last edited by kebo : Now. Reason: superfluous typo's

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Featured


Click Here to Expand Forum to Full Width