473,786 Members | 2,462 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

GetType of passed object

I have a nice little Sub that saves data in a class "mySettings " to an XML
file.
I call it like so:
Dim mySettings As mySettings = New mySettings
mySettings.valu e1 = "someText"
mySettings.valu e2 = "otherText"
xmlSave("C:\fol der\file.xml", mySettings)

Here is the sub:
Public Shared Sub xmlSave(ByVal path As String, ByVal config As
mySettings)
Dim xs As XmlSerializer = New XmlSerializer(G etType(mySettin gs))
Dim fs As FileStream = New FileStream(path , FileMode.Create )
xs.Serialize(fs , config)
fs.Close()
End Sub

I thought this worked well, but now I want to save another XML class with
the xmlSave function.
I tried the following, but there is a problem in the code:
Public Shared Sub xmlSave(ByVal path As String, ByVal config As object)
Dim xs As XmlSerializer = New XmlSerializer(G etType(config))
'the line above has an error: Type 'config' is not defined.
Dim fs As FileStream = New FileStream(path , FileMode.Create )
xs.Serialize(fs , config)
fs.Close()
End Sub

Any suggestions?

Matthew
Nov 21 '05 #1
5 2267
Try:

Dim xs As XmlSerializer = New XmlSerializer(c onfig.GetType)
P.S.
Make sure the object & sub objects are marked as Serializable.
Schneider

"Matthew" <tu************ *@alltel.net> wrote in message
news:%2******** ********@TK2MSF TNGP11.phx.gbl. ..
I have a nice little Sub that saves data in a class "mySettings " to an XML
file.
I call it like so:
Dim mySettings As mySettings = New mySettings
mySettings.valu e1 = "someText"
mySettings.valu e2 = "otherText"
xmlSave("C:\fol der\file.xml", mySettings)

Here is the sub:
Public Shared Sub xmlSave(ByVal path As String, ByVal config As
mySettings)
Dim xs As XmlSerializer = New XmlSerializer(G etType(mySettin gs))
Dim fs As FileStream = New FileStream(path , FileMode.Create )
xs.Serialize(fs , config)
fs.Close()
End Sub

I thought this worked well, but now I want to save another XML class with
the xmlSave function.
I tried the following, but there is a problem in the code:
Public Shared Sub xmlSave(ByVal path As String, ByVal config As object) Dim xs As XmlSerializer = New XmlSerializer(G etType(config))
'the line above has an error: Type 'config' is not defined.
Dim fs As FileStream = New FileStream(path , FileMode.Create )
xs.Serialize(fs , config)
fs.Close()
End Sub

Any suggestions?

Matthew

Nov 21 '05 #2
> Dim xs As XmlSerializer = New XmlSerializer(c onfig.GetType)

Schneider, that's exactly what I wanted!
Thanks a million!

Matthew
Nov 21 '05 #3
I thought I was done, but there is one more twist.

Public Function xmlLoad(ByVal path As String, _
ByVal xmlClass As Object)
Dim myObject As New mySettings
Dim xs As System.Xml.Seri alization.XmlSe rializer = _
New System.Xml.Seri alization.XmlSe rializer(xmlCla ss.GetType)
Dim sr As New System.IO.Strea mReader(path)
' Calls the Deserialize method and casts to the object type.
myObject = CType(xs.Deseri alize(sr), mySettings)
sr.Close()
Return myObject
End Function

I want to remove any mention of mySettings from the above.

Any ideas?

Matthew
Nov 21 '05 #4
Well you should seperate the Serialize and DeSerialize into different
functions.

Other tips:

Always use (Unless not possible):
Option Explicit On
Option Strict On

User DirectCast instead of Ctype when possible.

Here's some samples below (See SerializeToFile )
I also have some more advanced demos on www.CodeProject.com
Jusr look in the XML section

'Copyright © 2004 Eric Schneider

Option Explicit On
Option Strict On

Imports System
Imports System.Xml
Imports System.IO

Public NotInheritable Class PersistenceBase

''' ------------------------------------------------------------------------
-----
''' <summary>
''' Serializes an object to a string.
''' </summary>
''' <param name="value">Ob ject.</param>
''' <returns>System .String</returns>
''' <remarks>
''' </remarks>
''' <history>
''' [ESCHNEIDER0] 9/19/2004 Created
''' </history>
''' ------------------------------------------------------------------------
-----
Public Shared Function SerializeObject ToString(ByVal value As Object) As
System.String

Dim StringWriter As New System.IO.Strin gWriter

Try
Dim XmlSerializer As New
System.XML.Seri alization.XmlSe rializer(value. GetType)
XmlSerializer.S erialize(String Writer, value)

Return StringWriter.To String

Catch ex As Exception
Throw ex
Finally
StringWriter.Cl ose()
End Try
End Function

''' ------------------------------------------------------------------------
-----
''' <summary>
''' Serializes an object to a string.
''' </summary>
''' <param name="value">Ob ject.</param>
''' <param name="extraType s">System.Ty pe array.</param>
''' <returns>System .String</returns>
''' <remarks>
''' </remarks>
''' <history>
''' [ESCHNEIDER0] 9/19/2004 Created
''' </history>
''' ------------------------------------------------------------------------
-----
Public Shared Function SerializeObject ToString(ByVal value As Object,
ByVal extraTypes() As System.Type) As System.String

Dim StringWriter As New System.IO.Strin gWriter

Try
Dim XmlSerializer As New
System.XML.Seri alization.XmlSe rializer(value. GetType, extraTypes)
XmlSerializer.S erialize(String Writer, value)

Return StringWriter.To String

Catch ex As Exception
Throw ex
Finally
StringWriter.Cl ose()
End Try
End Function

''' ------------------------------------------------------------------------
-----
''' <summary>
''' Serializes a object to a file.
''' </summary>
''' <param name="fileName" >String. File name and path.</param>
''' <param name="value">Ob ject. The object to serialize.</param>
''' <param name="extraType s">System.Ty pe array.</param>
''' <remarks>
''' </remarks>
''' <history>
''' [ESCHNEIDER0] 9/19/2004 Created
''' </history>
''' ------------------------------------------------------------------------
-----
Public Shared Sub SerializeObject ToFile(ByVal fileName As String, ByVal
value As Object, ByVal extraTypes() As System.Type)

Dim writer As New StreamWriter(fi leName)

Try
' Create a new XmlSerializer instance.
Dim s As New Xml.Serializati on.XmlSerialize r(value.GetType , extraTypes)

' Serialize the object, and close the StreamWriter.
s.Serialize(wri ter, value)

Catch x As System.InvalidO perationExcepti on
Throw x
Finally
writer.Close()
End Try
End Sub

''' ------------------------------------------------------------------------
-----
''' <summary>
''' Serializes a object to a file.
''' </summary>
''' <param name="fileName" >String. File name and path.</param>
''' <param name="value">Ob ject. The object to serialize.</param>
''' <remarks>
''' </remarks>
''' <history>
''' [ESCHNEIDER0] 9/19/2004 Created
''' </history>
''' ------------------------------------------------------------------------
-----
Public Shared Sub SerializeObject ToFile(ByVal fileName As String, ByVal
value As Object)

Dim writer As New StreamWriter(fi leName)

Try
' Create a new XmlSerializer instance.
Dim s As New Xml.Serializati on.XmlSerialize r(value.GetType )

' Serialize the object, and close the StreamWriter.
s.Serialize(wri ter, value)

Catch x As System.InvalidO perationExcepti on
Throw x
Finally
writer.Close()
End Try
End Sub

''' ------------------------------------------------------------------------
-----
''' <summary>
''' Deserializes a file into a object.
''' </summary>
''' <param name="fileName" >String. File name and path.</param>
''' <param name="extraType s">System.Ty pe array.</param>
''' <returns>Object .</returns>
''' <remarks>
''' </remarks>
''' <history>
''' [ESCHNEIDER0] 9/19/2004 Created
''' </history>
''' ------------------------------------------------------------------------
-----
Public Shared Function DeserializeObje ctFromFile(ByVa l fileName As String,
ByVal value As Object, ByVal extraTypes() As System.Type) As Object

Dim fs As New IO.FileStream(f ileName, FileMode.Open)

Try
Dim w As New Xml.Serializati on.XmlSerialize r(value.GetType , extraTypes)
Dim g As Object = w.Deserialize(f s)

Return g

Catch x As Exception
Throw x
Finally
fs.Close()
End Try
End Function

''' ------------------------------------------------------------------------
-----
''' <summary>
''' Deserializes a file into a object.
''' </summary>
''' <param name="fileName" >String. File name and path.</param>
''' <returns>Object .</returns>
''' <remarks>
''' </remarks>
''' <history>
''' [ESCHNEIDER0] 9/19/2004 Created
''' </history>
''' ------------------------------------------------------------------------
-----
Public Shared Function DeserializeObje ctFromFile(ByVa l fileName As String,
ByVal value As Object) As Object

Dim fs As New IO.FileStream(f ileName, FileMode.Open)

Try
Dim w As New Xml.Serializati on.XmlSerialize r(value.GetType )
Dim g As Object = w.Deserialize(f s)

Return g

Catch x As Exception
Throw x
Finally
fs.Close()
End Try
End Function

''' ------------------------------------------------------------------------
-----
''' <summary>
''' Deserializes a String into a object.
''' </summary>
''' <param name="value">St ring.</param>
''' <param name="type">Obj ect.</param>
''' <returns>Object .</returns>
''' <remarks>
''' </remarks>
''' <history>
''' [ESCHNEIDER0] 9/30/2004 Created
''' </history>
''' ------------------------------------------------------------------------
-----
Public Shared Function DeserializeObje ctFromString(By Val value As String,
ByVal type As Object) As Object

Dim fs As New IO.StringReader (value)

Try
Dim w As New Xml.Serializati on.XmlSerialize r(type.GetType)
Dim g As Object = w.Deserialize(f s)

Return g

Catch x As Exception
Throw x
Finally
fs.Close()
End Try
End Function

''' ------------------------------------------------------------------------
-----
''' <summary>
''' Deserializes a String into a object.
''' </summary>
''' <param name="value">St ring.</param>
''' <param name="type">Obj ect.</param>
''' <param name="extraType s">System.Ty pe array.</param>
''' <returns>Object .</returns>
''' <remarks>
''' </remarks>
''' <history>
''' [ESCHNEIDER0] 9/30/2004 Created
''' </history>
''' ------------------------------------------------------------------------
-----
Public Shared Function DeserializeObje ctFromString(By Val value As String,
ByVal type As Object, ByVal extraTypes() As System.Type) As Object

Dim fs As New IO.StringReader (value)

Try
Dim w As New Xml.Serializati on.XmlSerialize r(type.GetType, extraTypes)
Dim g As Object = w.Deserialize(f s)

Return g

Catch x As Exception
Throw x
Finally
fs.Close()
End Try
End Function

Private Sub New()

End Sub

End Class

"Matthew" <tu************ *@alltel.net> wrote in message
news:ui******** ******@tk2msftn gp13.phx.gbl...
I thought I was done, but there is one more twist.

Public Function xmlLoad(ByVal path As String, _
ByVal xmlClass As Object)
Dim myObject As New mySettings
Dim xs As System.Xml.Seri alization.XmlSe rializer = _
New System.Xml.Seri alization.XmlSe rializer(xmlCla ss.GetType)
Dim sr As New System.IO.Strea mReader(path)
' Calls the Deserialize method and casts to the object type.
myObject = CType(xs.Deseri alize(sr), mySettings)
sr.Close()
Return myObject
End Function

I want to remove any mention of mySettings from the above.

Any ideas?

Matthew

Nov 21 '05 #5
Schneider, thanks for the examples. They helped solve my problem.

Matthew
Nov 21 '05 #6

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

Similar topics

6
2189
by: Marco | last post by:
Hi. I am trying to get a type object using GetType. For this, I use: Type type = Type.GetType("System.Windows.Forms.TextBox"); But after this line, when I check, type is null. What am I doing wrong ? How to do it right ?
10
11801
by: Bob | last post by:
This has been bugging me for a while now. GetType isn't availble for variables decalred as interface types, I have to DirectCast(somevariable, Object). In example: Sub SomeSub(ByVal Dictionary as IDictionary) If Dictionary is Nothing Then Return Dim o as Object = DirectCast(Dictionary, Object)
4
2870
by: Howard Kaikow | last post by:
For the code below, for both appWord and gappWord, I get the error "Public member 'GetType' on type 'ApplicationClass' not found" I realize the test for appWord is superflous as the parameter is passed in as a known type, but gappWord is has a scope of the class, so a test of the type is valid (making believe the sub does not know the pre-ordained type). TypeOf returns Word.Application. TypeName returns ApplicationClass.
1
1495
by: dcs | last post by:
Hi, Can someone please help. I have a class that contains the following Structure (called MyStructure) and sub (called MainSub). And this 1st class inherits a 2nd class that contains a sub called Get_Values_From_MyStructure. My problem is in sub Get_Values_From_MyStructure. Since Get_Values_From_MyStructure is inherited by many different classes, its parameter i_obj_Structure will contain various Structure definitions. And thats a problem...
6
1461
by: Paul | last post by:
I have two projects in one solution. One is called Frontier and holds all my base user controls, classes, etc. that are used over multiple applications. The second is my application project (OCFU) which holds the forms and code that the users run. I need to instantiate a new form only given the form's name in a string. In the calling form in the OCFU project I used the following code: Dim objNewForm As Object =...
3
2521
by: Ron M. Newman | last post by:
Hi, I have a certain assembly that needs to create instances of objects where the object class is passed as a string (e.g. "System.Drawing.Bitmap"). I have found that calling "GetType" on this string, returns null. Naturally, I suspect that because the this assembly doesn't reference the assembly containing "System.Drawing.Bitmap", the type cannot be found and thus I'm getting null in the GetType.
1
962
by: Kristian Frost | last post by:
Hello, Sorry for polluting the VB newsgroup with curly brackets, but I couldn't think how to get that question onto one line otherwise. Anyway, I'm trying to write a Sub, or Function which takes an object as an input and then creates a new object of the same type using that class' constructor. VB isn't currently liking any of my attempts, but the general idea is to have: Private Function NewInterfaceObjectArray(ByVal...
4
9484
by: Steph | last post by:
hello, i want to find the type from a generic... like : public static john<T>(object obj, T myControl) { ((myControl.getType())myControl).OnClientClick ="code"; } because my generic var can be a Button, LinkButton, ... with "OnClientClick " event. and i dont want use :
2
2520
by: Carlos Rodriguez | last post by:
I have the following function in C#public void Undo(IDesignerHost host) { if (!this.componentName.Equals(string.Empty) && (this.member != null)) { IContainer container1 = (IContainer) host.GetService(typeof(IContainer)); IComponent component1 = container1.Components; PropertyInfo info1 = component1.GetType().GetProperty(this.member.Name);
0
9647
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
9496
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10363
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
10164
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10110
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8989
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...
0
6745
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
5534
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2894
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.