Christian Studer
Christian Studer

Reputation: 25597

How do I dump the values of all members of a VB.Net module?

I am refactoring a legacy application which uses a huge module (static class) to store it's global state in approx. 400 different member variables:

Public Module GlobalState

Public Variable1 As Single
Public Variable2 As Single
...
Public Variable400 As Single

How can I dump the values of all these variables to a disk on file in a human readable format (XML, JSON..., not a binary dump)?

The commonly used object loggers require an instance of the class, but in this case everything is static.

Upvotes: 3

Views: 724

Answers (1)

If I understand you correctly, this can be done with reflection:

Imports System.Reflection
Imports System.Xml.Serialization
Imports System.IO

Private Sub Create()

    Dim list As New List(Of GlobalStateItem)

    For Each m As FieldInfo In GetType(GlobalState).GetFields(BindingFlags.Public Or BindingFlags.Instance Or BindingFlags.Static Or BindingFlags.DeclaredOnly)
        list.Add(New GlobalStateItem(m.Name, m.GetValue(Nothing)))
    Next

    Dim serializer As New XmlSerializer(GetType(List(Of GlobalStateItem)))

    Using stream As New StreamWriter("path")
        serializer.Serialize(stream, list)
    End Using

End Sub

<Serializable()>
Public Structure GlobalStateItem
    Public Sub New(name As String, value As Object)
        Me.Name = name
        Me.Value = value
    End Sub
    Public Name As String
    Public Value As Object
End Structure

Public Module GlobalState
    Public Variable1 As Single = 1.0!
    Public Variable2 As Single = 2.0!
    Public Variable400 As Single = 400.0!
End Module

Output:

<?xml version="1.0" encoding="utf-8"?>
<ArrayOfGlobalStateItem xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <GlobalStateItem>
    <Name>Variable1</Name>
    <Value xsi:type="xsd:float">1</Value>
  </GlobalStateItem>
  <GlobalStateItem>
    <Name>Variable2</Name>
    <Value xsi:type="xsd:float">2</Value>
  </GlobalStateItem>
  <GlobalStateItem>
    <Name>Variable400</Name>
    <Value xsi:type="xsd:float">400</Value>
  </GlobalStateItem>
</ArrayOfGlobalStateItem>

Upvotes: 2

Related Questions