473,762 Members | 8,598 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

DeSerialize/Serialize CollectionBase Object

Long Post, thanks for your patience...

I have and XML file that looks something like this:
<?xml version="1.0" encoding="utf-8" ?>
<Settings>
<Location>
<X>30</X>
<Y>40</Y>
</Location>
<Size>
<Width>140</Width>
<Height>56</Height>
</Size>
<WindowState>Ma ximized</WindowState>
<SplitPosition> 335</SplitPosition>
<ShowStatusBar> true</ShowStatusBar>
<Connections>
<Connection>
<Database>MyFir stDatabase</Database>
<DataSource>MyS erver</DataSource>
<IntegratedSecu rity>true</IntegratedSecur ity>
<ConnectionName >MyFirstConnect ion</ConnectionName>
</Connection>
<Connection>
<Database>MySec ondDatabase</Database>
<DataSource>MyS erver</DataSource>
<Password>mypas sword</Password>
<UserName>mylog in</UserName>
<ConnectionName >MySecondConnec tion</ConnectionName>
</Connection>
<Connection>
<Database>C:\Re ports.mdb</Database>
<DataSource>C:\ Reports.mdb</DataSource>
<Provider>Acces s</Provider>
<ConnectionName >LOCALACCESS_C: \REPORTS.MDB</ConnectionName>
</Connection>
</Connections>
</Settings>
(Actually it looks exactly like that. :-) )

I have a class Settings, optConnection, optConnectionCo llection (Code Below).

When I call the subroutine to open the XML file (In the Settings Class) and thus Deserialize into the objects, my connectioncolle ction does not contain any connections. What have I missed here?

--------------------------------

Option Explicit On
Option Strict On

Imports System.IO
Imports System.Xml.Seri alization
Imports System.Drawing
Imports System.Windows. Forms
Public Class Settings

Private m_ptLocation As Point = Point.Empty
Private m_sizeSize As Size = Size.Empty
Private m_fwsWindowStat e As FormWindowState
Private m_iSplitPositio n As Integer
Private m_bShowStatusBa r As Boolean
Private m_Connections As optConnectionCo llection

' Some variables we need to start processing
Private Shared m_strXMLFileNam e As String = ""
Private Shared m_oSerializer As XmlSerializer = Nothing

Public Sub New()

End Sub

' Open = Deserialize the XML file to the Objects
Public Shared Function Open(ByVal XMLFileName As String) As Settings

Dim oOverrides As XmlAttributeOve rrides = New XmlAttributeOve rrides
Dim oAttributes As XmlAttributes
Dim sAttr As XmlElementAttri bute

If (XMLFileName.Le ngth > 0) Then
m_strXMLFileNam e = XMLFileName
Else
Throw New ArgumentExcepti on("Empty filename is not legal." & Environment.New Line & "Parameter name: XMLFileName", "XMLFileNam e")
End If

' --- I'VE TRIED THIS BUT COMMENTED IT OUT, DOESN'T SEEM TO MATTER ----
'sAttr = New XmlElementAttri bute("Connectio ns")
'sAttr.Type = GetType(optConn ectionCollectio n)

'oAttributes = New XmlAttributes
'oAttributes.Xm lElements.Add(s Attr)
'oOverrides.Add (GetType(Settin gs), "Connection s", oAttributes)

' Create the XmlSerializer using the XmlAttributeOve rrides.
Try
m_oSerializer = New XmlSerializer(G etType(Settings ), oOverrides)

Dim fs As New FileStream(m_st rXMLFileName, FileMode.Open)

Return CType(m_oSerial izer.Deserializ e(fs), Settings)
Catch ex As Exception
MsgBox(ex.Messa ge)
End Try
End Function

' Close = Serialize the Objects to the XML File
Public Sub Close(Optional ByVal XMLFileName As String = "")

Dim oWriter As StreamWriter

If (XMLFileName.Le ngth > 0) Then
m_strXMLFileNam e = XMLFileName
End If

If (m_strXMLFileNa me.Length = 0) Then
' No filename given; cannot save
Else
oWriter = New StreamWriter(m_ strXMLFileName)
m_oSerializer.S erialize(oWrite r, Me)
oWriter.Close()
End If

End Sub
Public Property Connections() As optConnectionCo llection
Get
Return m_Connections
End Get
Set(ByVal Value As optConnectionCo llection)
m_Connections = Value
End Set
End Property
Public ReadOnly Property XMLFileName() As String
Get
Return m_strXMLFileNam e
End Get
End Property

Public Property Location() As Point
Get
Return m_ptLocation
End Get

Set(ByVal Value As Point)
m_ptLocation = Value
End Set

End Property

Public Property Size() As Size
Get
Return m_sizeSize
End Get

Set(ByVal Value As Size)
m_sizeSize = Value
End Set
End Property

Public Property ShowStatusBar() As Boolean
Get
Return m_bShowStatusBa r
End Get

Set(ByVal Value As Boolean)
m_bShowStatusBa r = Value
End Set
End Property

Public Property WindowState() As FormWindowState
Get
Return m_fwsWindowStat e
End Get

Set(ByVal Value As FormWindowState )
m_fwsWindowStat e = Value
End Set
End Property

Public Property SplitPosition() As Integer
Get
Return m_iSplitPositio n
End Get

Set(ByVal Value As Integer)
m_iSplitPositio n = Value
End Set
End Property

End Class

'<FILE clsConnection.v b>
Option Explicit On
Option Strict On

Public Class optConnection

Implements IDbConnection

Public Enum eProvider
SQLServer = 0
Access = 1
FileDSN = 2
SystemDSN = 3
UserDSN = 4
End Enum

Private Const ACCESS_PROVIDER As String = "Microsoft.Jet. OLEDB.4.0"

Private m_szConnectionS tring As String
Private m_iConnectionTi meout As Integer
Private m_szDataSource As String
Private m_szDatabase As String
Private m_bIntegratedSe curity As Boolean
Private m_szPassword As String
Private m_iProvider As eProvider = eProvider.SQLSe rver
Private m_szServerVersi on As String
Private m_szUserName As String
Private m_ConnectionNam e As String
Public Sub New()
MyBase.New()
End Sub

Public Overridable Property ConnectionName( ) As String
Get
Return m_ConnectionNam e
End Get

Set(ByVal Value As String)
m_ConnectionNam e = Value
End Set

End Property

Public Overridable Property DataSource() As String
Get
Return m_szDataSource
End Get

Set(ByVal szDataSource As String)
If (State <> ConnectionState .Closed) Then
Throw New InvalidOperatio nException("The 'DataSource' property may only be changed while the connection is closed. The current state of the connection is " & State.ToString( ) & ".")
End If

If (szDataSource Is Nothing) Then
m_szDataSource = ""
Else
m_szDataSource = szDataSource
End If

End Set
End Property
Public Overridable Property IntegratedSecur ity() As Boolean
Get
Return m_bIntegratedSe curity
End Get

Set(ByVal bIntegratedSecu rity As Boolean)
If (State <> ConnectionState .Closed) Then
Throw New InvalidOperatio nException("The 'IntegratedSecu rity' property may only be changed while the connection is closed. The current state of the connection is " & State.ToString( ) & ".")
End If

m_bIntegratedSe curity = bIntegratedSecu rity

End Set
End Property
Public Overridable Property Password() As String
Get
Return m_szPassword
End Get

Set(ByVal szPassword As String)
If (State <> ConnectionState .Closed) Then
Throw New InvalidOperatio nException("The 'Password' property may only be changed while the connection is closed. The current state of the connection is " & State.ToString( ) & ".")
End If

If (szPassword Is Nothing) Then
m_szPassword = ""
Else
m_szPassword = szPassword
End If

End Set
End Property

Public Property Provider() As eProvider
Get
Return m_iProvider
End Get

Set(ByVal iProvider As eProvider)
If (State <> ConnectionState .Closed) Then
Throw New InvalidOperatio nException("The 'Provider' property may only be changed while the connection is closed. The current state of the connection is " & State.ToString( ) & ".")
End If

m_iProvider = iProvider

End Set
End Property
Public Overridable Property ServerVersion() As String
Get
Return m_szServerVersi on
End Get
Set(ByVal Value As String)
m_szServerVersi on = Value
End Set
End Property

Public Overridable Property UserName() As String
Get
Return m_szUserName
End Get

Set(ByVal szUserName As String)

If (szUserName Is Nothing) Then
m_szUserName = ""
Else
m_szUserName = szUserName
End If

End Set
End Property
Public Overloads Function BeginTransactio n() As System.Data.IDb Transaction Implements System.Data.IDb Connection.Begi nTransaction

End Function

Public Overloads Function BeginTransactio n1(ByVal il As System.Data.Iso lationLevel) As System.Data.IDb Transaction Implements System.Data.IDb Connection.Begi nTransaction

End Function

Public Sub ChangeDatabase( ByVal databaseName As String) Implements System.Data.IDb Connection.Chan geDatabase

End Sub

Public Sub Close() Implements System.Data.IDb Connection.Clos e

End Sub
Public ReadOnly Property ConnectionTimeo ut() As Integer Implements System.Data.IDb Connection.Conn ectionTimeout
Get

End Get
End Property

Public Function CreateCommand() As System.Data.IDb Command Implements System.Data.IDb Connection.Crea teCommand

End Function
Public Sub Open() Implements System.Data.IDb Connection.Open

End Sub

Public ReadOnly Property State() As System.Data.Con nectionState Implements System.Data.IDb Connection.Stat e
Get

End Get
End Property
Public Overridable Property ConnectionStrin g() As String Implements System.Data.IDb Connection.Conn ectionString
Get
Return m_szConnectionS tring
End Get

Set(ByVal szConnectionStr ing As String)
If (State <> ConnectionState .Closed) Then
Throw New InvalidOperatio nException("The 'ConnectionStri ng' property may only be changed while the connection is closed. The current state of the connection is " & State.ToString( ) & ".")
End If

If (szConnectionSt ring Is Nothing) Then
m_szConnectionS tring = ""
Else
m_szConnectionS tring = szConnectionStr ing
End If

End Set
End Property

Public Overridable ReadOnly Property Database() As String Implements System.Data.IDb Connection.Data base
Get
Return m_szDatabase
End Get

End Property

Public Sub Dispose() Implements System.IDisposa ble.Dispose

End Sub
End Class

'<FILE clsConnectionCo llection.vb >

Option Explicit On
Option Strict On

Public Class optConnectionCo llection
Inherits CollectionBase

Public Sub New()
MyBase.New()
End Sub

Public Sub New(ByVal oConnections As ICollection)
MyBase.New()

AddRange(oConne ctions)
End Sub

Default Public Overloads Property Item(ByVal iIndex As Integer) As optConnection
Get
Return CType(List.Item (iIndex), optConnection)
End Get

Set(ByVal Value As optConnection)
Add(Value)
End Set
End Property
Public Function Add(ByVal oConnection As optConnection) As Integer
Return List.Add(oConne ction)
End Function

Public Sub AddRange(ByVal oConnections As ICollection)
Dim oEntry As DictionaryEntry
Dim oValue As Object

If (TypeOf oConnections Is IDictionary) Then
For Each oEntry In CType(oConnecti ons, IDictionary)
List.Add(oEntry .Value)
Next oEntry
Else
For Each oValue In oConnections
List.Add(oValue )
Next oValue
End If
End Sub

Public Overloads Sub Remove(ByVal szName As String)
Dim i As Integer
Dim oConnection As optConnection

For i = 0 To List.Count - 1
oConnection = CType(List(i), optConnection)
If (oConnection.Co nnectionName = szName) Then
List.RemoveAt(i )
Return
End If
Next i

' Connection was not found in the collection
' TODO: Throw an appropriate exception
Throw New Exception
End Sub

Public Overloads Sub Remove(ByVal oConnection As optConnection)
List.Remove(oCo nnection)
End Sub

End Class

<FILE - Form1.vb - Simple form to open/close the file>

Imports Settings_Class

Public Class Form1
Inherits System.Windows. Forms.Form

Private m_Settings As Settings

Private Sub Button1_Click(B yVal sender As System.Object, ByVal e As System.EventArg s) Handles Button1.Click

m_Settings = m_Settings.Open ("XMLFIlE3.xml" )

End Sub
Private Sub Button2_Click(B yVal sender As System.Object, ByVal e As System.EventArg s) Handles Button2.Click
m_Settings.Clos e("XMLFilE4.xml ")
m_Settings = Nothing

End Sub
End Class

Thanks for any help.
From: John Manion

-----------------------
Posted by a user from .NET 247 (http://www.dotnet247.com/)

<Id>i0oFZ6jppEO cTC58KQwXlA==</Id>
Nov 21 '05 #1
0 2070

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

7
5830
by: Ian Tompsett | last post by:
H I was wondering if it possible for an object to serialize/deserialize itself from XML. I'd be guessing that it would need to use the XmlSerializer class, but that seems to want to create a brand new object when deserializing. In my case I have an existing object that I'd like to pass some XML to for the object to repopulate its member variables. Similarly I'd like it to be able to populate an XML string from the values of its member...
0
2174
by: Mike Pollett | last post by:
Hi, I have used the ISerializable interface before and the code below worked fine. Until I derived it from CollectionBase. The code will still serialize and deserialize the properties in this class and properties derived from this class but will not serialize or deserialize the properties in CollectionBase. Like InnerList, which is a read only property of CollectionBase. How can I serialize and deserialize the InnerList property of...
1
7090
by: Mike Pollett | last post by:
Hi, I have used the ISerializable interface before and the code below worked fine. Until I derived it from CollectionBase. The code will still serialize and deserialize the properties in this class and properties derived from this class but will not serialize or deserialize the properties in CollectionBase. Like InnerList, which is a read only property of CollectionBase. How can I serialize and deserialize the InnerList property of...
3
5881
by: Amsteel | last post by:
I got something like this in VB.Net <Serializable()> Public Class YQProfileC Inherits CollectionBase Public Sub Save2File(ByVal FileName As String) Dim IFormatter As New BinaryFormatter() Dim FS As FileStream = New FileStream(FileName, FileMode.Create, FileAccess.Write, FileShare.None) IFormatter.Serialize(FS, Me) FS.Close()
2
6073
by: PCH | last post by:
I have 2 functions, one to serialize an object, and one to deserialize it. I can serialize just fine, the problem is when I try to deserialize it later... I get an error: {"Invalid BinaryFormatter stream. " } I looked at the serialized string vs whats passed into the deserialize
2
2427
by: alexandre martins | last post by:
Every time i try to make Deserialize the computer gives me the folowing error: "End of Stream encountered before parsing was complete" the code that i'm running is simple and is based on an MSDN example. The CODE is BELOW this lines. If you see something wrong or missing please answer. Class declaration:
4
3309
by: George Addison | last post by:
I understand this might not be the optimal method of deserialization, but how can I deserialize a class to itself? Something like: Public Sub New(Optional ByVal filename as string = Nothing) If Not IsNothing(filename) then fs = New System.IO.FileStream(filename, System.IO.FileMode.Open) Dim sf As New
3
4805
by: Jeff Richardson | last post by:
This is a repost from the InfoPath news group. Hi, I am writing a SharePoint application that works with InfoPath forms. When a user submits a completed InfoPath form to a forms library my code processes the posted xml file by reading the data into a C# class object that was generated by XSD.EXE. The class was generated from the myschema.xsd file that is contained in the InfoPath solution with a command line like:
1
3667
by: davebaranas | last post by:
I am able to serialize this but I get a null exception when I try to deserialize it back Even if I don't make any child classes it throws "Object reference not set to an instance of an object." I must be missing something here Private Sub cmdLoad_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdLoad.Click
0
9554
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10137
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9812
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8814
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7360
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6640
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5405
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
3510
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2788
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.