472,801 Members | 1,101 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,801 software developers and data experts.

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>Maximized</WindowState>
<SplitPosition>335</SplitPosition>
<ShowStatusBar>true</ShowStatusBar>
<Connections>
<Connection>
<Database>MyFirstDatabase</Database>
<DataSource>MyServer</DataSource>
<IntegratedSecurity>true</IntegratedSecurity>
<ConnectionName>MyFirstConnection</ConnectionName>
</Connection>
<Connection>
<Database>MySecondDatabase</Database>
<DataSource>MyServer</DataSource>
<Password>mypassword</Password>
<UserName>mylogin</UserName>
<ConnectionName>MySecondConnection</ConnectionName>
</Connection>
<Connection>
<Database>C:\Reports.mdb</Database>
<DataSource>C:\Reports.mdb</DataSource>
<Provider>Access</Provider>
<ConnectionName>LOCALACCESS_C:\REPORTS.MDB</ConnectionName>
</Connection>
</Connections>
</Settings>
(Actually it looks exactly like that. :-) )

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

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

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

Option Explicit On
Option Strict On

Imports System.IO
Imports System.Xml.Serialization
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_fwsWindowState As FormWindowState
Private m_iSplitPosition As Integer
Private m_bShowStatusBar As Boolean
Private m_Connections As optConnectionCollection

' Some variables we need to start processing
Private Shared m_strXMLFileName 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 XmlAttributeOverrides = New XmlAttributeOverrides
Dim oAttributes As XmlAttributes
Dim sAttr As XmlElementAttribute

If (XMLFileName.Length > 0) Then
m_strXMLFileName = XMLFileName
Else
Throw New ArgumentException("Empty filename is not legal." & Environment.NewLine & "Parameter name: XMLFileName", "XMLFileName")
End If

' --- I'VE TRIED THIS BUT COMMENTED IT OUT, DOESN'T SEEM TO MATTER ----
'sAttr = New XmlElementAttribute("Connections")
'sAttr.Type = GetType(optConnectionCollection)

'oAttributes = New XmlAttributes
'oAttributes.XmlElements.Add(sAttr)
'oOverrides.Add(GetType(Settings), "Connections", oAttributes)

' Create the XmlSerializer using the XmlAttributeOverrides.
Try
m_oSerializer = New XmlSerializer(GetType(Settings), oOverrides)

Dim fs As New FileStream(m_strXMLFileName, FileMode.Open)

Return CType(m_oSerializer.Deserialize(fs), Settings)
Catch ex As Exception
MsgBox(ex.Message)
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.Length > 0) Then
m_strXMLFileName = XMLFileName
End If

If (m_strXMLFileName.Length = 0) Then
' No filename given; cannot save
Else
oWriter = New StreamWriter(m_strXMLFileName)
m_oSerializer.Serialize(oWriter, Me)
oWriter.Close()
End If

End Sub
Public Property Connections() As optConnectionCollection
Get
Return m_Connections
End Get
Set(ByVal Value As optConnectionCollection)
m_Connections = Value
End Set
End Property
Public ReadOnly Property XMLFileName() As String
Get
Return m_strXMLFileName
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_bShowStatusBar
End Get

Set(ByVal Value As Boolean)
m_bShowStatusBar = Value
End Set
End Property

Public Property WindowState() As FormWindowState
Get
Return m_fwsWindowState
End Get

Set(ByVal Value As FormWindowState)
m_fwsWindowState = Value
End Set
End Property

Public Property SplitPosition() As Integer
Get
Return m_iSplitPosition
End Get

Set(ByVal Value As Integer)
m_iSplitPosition = Value
End Set
End Property

End Class

'<FILE clsConnection.vb>
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_szConnectionString As String
Private m_iConnectionTimeout As Integer
Private m_szDataSource As String
Private m_szDatabase As String
Private m_bIntegratedSecurity As Boolean
Private m_szPassword As String
Private m_iProvider As eProvider = eProvider.SQLServer
Private m_szServerVersion As String
Private m_szUserName As String
Private m_ConnectionName As String
Public Sub New()
MyBase.New()
End Sub

Public Overridable Property ConnectionName() As String
Get
Return m_ConnectionName
End Get

Set(ByVal Value As String)
m_ConnectionName = 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 InvalidOperationException("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 IntegratedSecurity() As Boolean
Get
Return m_bIntegratedSecurity
End Get

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

m_bIntegratedSecurity = bIntegratedSecurity

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 InvalidOperationException("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 InvalidOperationException("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_szServerVersion
End Get
Set(ByVal Value As String)
m_szServerVersion = 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 BeginTransaction() As System.Data.IDbTransaction Implements System.Data.IDbConnection.BeginTransaction

End Function

Public Overloads Function BeginTransaction1(ByVal il As System.Data.IsolationLevel) As System.Data.IDbTransaction Implements System.Data.IDbConnection.BeginTransaction

End Function

Public Sub ChangeDatabase(ByVal databaseName As String) Implements System.Data.IDbConnection.ChangeDatabase

End Sub

Public Sub Close() Implements System.Data.IDbConnection.Close

End Sub
Public ReadOnly Property ConnectionTimeout() As Integer Implements System.Data.IDbConnection.ConnectionTimeout
Get

End Get
End Property

Public Function CreateCommand() As System.Data.IDbCommand Implements System.Data.IDbConnection.CreateCommand

End Function
Public Sub Open() Implements System.Data.IDbConnection.Open

End Sub

Public ReadOnly Property State() As System.Data.ConnectionState Implements System.Data.IDbConnection.State
Get

End Get
End Property
Public Overridable Property ConnectionString() As String Implements System.Data.IDbConnection.ConnectionString
Get
Return m_szConnectionString
End Get

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

If (szConnectionString Is Nothing) Then
m_szConnectionString = ""
Else
m_szConnectionString = szConnectionString
End If

End Set
End Property

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

End Property

Public Sub Dispose() Implements System.IDisposable.Dispose

End Sub
End Class

'<FILE clsConnectionCollection.vb >

Option Explicit On
Option Strict On

Public Class optConnectionCollection
Inherits CollectionBase

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

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

AddRange(oConnections)
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(oConnection)
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(oConnections, 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.ConnectionName = 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(oConnection)
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(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

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

End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
m_Settings.Close("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>i0oFZ6jppEOcTC58KQwXlA==</Id>
Nov 21 '05 #1
0 2008

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

Similar topics

7
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...
0
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...
1
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...
3
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...
2
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...
2
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...
4
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)...
3
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...
1
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."...
0
linyimin
by: linyimin | last post by:
Spring Startup Analyzer generates an interactive Spring application startup report that lets you understand what contributes to the application startup time and helps to optimize it. Support for...
0
by: erikbower65 | last post by:
Here's a concise step-by-step guide for manually installing IntelliJ IDEA: 1. Download: Visit the official JetBrains website and download the IntelliJ IDEA Community or Ultimate edition based on...
0
by: kcodez | last post by:
As a H5 game development enthusiast, I recently wrote a very interesting little game - Toy Claw ((http://claw.kjeek.com/))。Here I will summarize and share the development experience here, and hope it...
0
by: Taofi | last post by:
I try to insert a new record but the error message says the number of query names and destination fields are not the same This are my field names ID, Budgeted, Actual, Status and Differences ...
14
DJRhino1175
by: DJRhino1175 | last post by:
When I run this code I get an error, its Run-time error# 424 Object required...This is my first attempt at doing something like this. I test the entire code and it worked until I added this - If...
0
by: Rina0 | last post by:
I am looking for a Python code to find the longest common subsequence of two strings. I found this blog post that describes the length of longest common subsequence problem and provides a solution in...
5
by: DJRhino | last post by:
Private Sub CboDrawingID_BeforeUpdate(Cancel As Integer) If = 310029923 Or 310030138 Or 310030152 Or 310030346 Or 310030348 Or _ 310030356 Or 310030359 Or 310030362 Or...
0
by: lllomh | last post by:
Define the method first this.state = { buttonBackgroundColor: 'green', isBlinking: false, // A new status is added to identify whether the button is blinking or not } autoStart=()=>{
0
by: lllomh | last post by:
How does React native implement an English player?

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.