Monthly Archives: April 2013

Self Serializing Base Class

This class can be used as a base for any class that needs to serialize and deserialize itself.

Imports System.Xml.Serialization
Imports System.Xml
Imports System.IO
''' <summary>
''' Base class for any object that can serialize itself either normally or cleanly. i.e. without the xml declaration thus making it useful for insertion into other xml.
''' </summary>
''' <remarks>Note that self deserialization is not possible</remarks>
Public MustInherit Class SelfSerializer
''' <summary>
''' This class can serialize itself with namespace and xml declaration.
''' </summary>
''' <returns></returns>
''' <remarks></remarks>
<System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2202:Do not dispose objects multiple times")>
Public Function Serialize() As String
Dim serializer As New XmlSerializer(Me.GetType)
'Need to serialize without namespaces to keep it clean and tidy
Dim emptyNS As New XmlSerializerNamespaces({XmlQualifiedName.Empty})
Using stream As New StringWriter(), writer As XmlWriter = XmlWriter.Create(stream)
'Serialize the item to the stream using the namespace supplied
serializer.Serialize(writer, Me)
'Read the stream and return it as a string
Return stream.ToString
End Using
End Function
''' <summary>
''' This class can serialize itself without namespace or xml declaration.
''' </summary>
''' <returns></returns>
''' <remarks></remarks>
<System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2202:Do not dispose objects multiple times")>
Public Function SerializeAsElement() As String
Dim serializer As New XmlSerializer(Me.GetType)
'Need to serialize without namespaces to keep it clean and tidy
Dim emptyNS As New XmlSerializerNamespaces({XmlQualifiedName.Empty})
'Need to remove xml declaration as we will use this as part of a larger xml file
Dim settings As New XmlWriterSettings()
settings.OmitXmlDeclaration = True
settings.NewLineHandling = NewLineHandling.Entitize
settings.Indent = True
settings.IndentChars = (ControlChars.Tab)
Using stream As New StringWriter(), writer As XmlWriter = XmlWriter.Create(stream, settings)
'Serialize the item to the stream using the namespace supplied
serializer.Serialize(writer, Me, emptyNS)
'Read the stream and return it as a string
Return stream.ToString
End Using
End Function

#Region "Self deserialization"

Private myState As Object = Me
''' <summary>
''' Deserialize
''' </summary>
''' <param name="xml"></param>
''' <remarks>This is a shallow copy so won't read any nested objects.</remarks>
Public Sub Deserialize(xml As String)
Dim newMe As Object 'We don't know our own type so we have to use an object here
'Read text
Dim newSerializer As New XmlSerializer(Me.GetType)
Using newReader As New StringReader(xml)
newMe = newSerializer.Deserialize(newReader)
myState = newMe
End Using
For Each propinfo In myState.GetType.GetProperties()
Dim name = propinfo.Name
Dim realProp = (From p In Me.GetType.GetProperties
Where p.Name = name And p.MemberType = Reflection.MemberTypes.Property).Take(1)(0)
realProp.SetValue(Me, propinfo.GetValue(myState, Nothing), Nothing)
Next
End Sub

#End Region
End Class

Get the Current Directory

I hate trying to remember this so here are various options.

If you are writing an application:

Return Application.StartupPath

'or

Dim uri As String = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase)
Dim local As String = New Uri(uri).LocalPath
Return local

If you are writing a class library:

Return My.Application.Info.DirectoryPath

If you are writing an ASPX page:

Dim serverfilepath As String = Server.MapPath(filepath)

Include a namespace prefix when serializing or deserializing

In order to include a namespace prefix when serializing a class we must add an xmlns property of type XmlNamespaceDeclaration to the class and then add a prefix in the class constructor.

Imports System.Xml.Serialization

    <Serializable(), XmlRoot("navigation", Namespace:="<a href="http://www.tla.com/">http://www.tla.com</a>")>
    Public Class Navigation
        ''' <summary>
        ''' Add a namespace declaration so that we can use a prefix for this class.
        ''' </summary>
        ''' <remarks>
        ''' See <a href="http://msdn.microsoft.com/en-us/library/vstudio/system.xml.serialization.xmlnamespacedeclarationsattribute(v=vs.90).aspx">http://msdn.microsoft.com/en-us/library/vstudio/system.xml.serialization.xmlnamespacedeclarationsattribute(v=vs.90).aspx</a>
        ''' and <a href="http://stackoverflow.com/questions/1254544/how-do-i-specify-xml-serialization-attributes-to-support-namespace-prefixes-duri">http://stackoverflow.com/questions/1254544/how-do-i-specify-xml-serialization-attributes-to-support-namespace-prefixes-duri</a> </remarks>
        <XmlNamespaceDeclarations> Public xmlns As New XmlSerializerNamespaces

        Public Sub New()
            'Add thenamespace prefix
            xmlns.Add("tla", "<a href="http://www.tla.com/">http://www.tla.com</a>")
        End Sub

    End Class

    <XmlType("heading")>
    Public Class Heading

        Public Sub New()
   'Default constructor
        End Sub

        Private myQuestions As List(Of Question)
        ''' <summary>
        ''' Flat sequence of questions.
        ''' </summary>
        ''' <value></value>
        ''' <returns></returns>
        ''' <remarks>Using the XmlElementAttribute markup renders the list as a flat sequence.</remarks>
        <XmlElementAttribute("question", GetType(Question))>
        Public Property Questions() As List(Of Question)
            Get
                If myQuestions Is Nothing Then myQuestions = New List(Of Question) 'Lazy loading
                Return Me.myQuestions
            End Get
            Set(value As List(Of Question))
                Me.myQuestions = value
            End Set
        End Property
  
    End Class

    <XmlType("question")>
    Public Class Question
 
        <XmlAttribute()> Public Property id() As String
  
    End Class

 

 

Get the application directory

Dim path As String 
path = System.IO.Path.GetDirectoryName( _
   System.Reflection.Assembly.GetExecutingAssembly().Location)

Utilising a .NET DLL with a .config file in VB6

This isn’t great practice but it’s sometimes necessary to use a config file for a DLL developed in .NET that then needs to be called from VB6.

To debug a VB6 app/exe that uses a .NET dll with a .config file you must create a vb6.exe.config file in the same folder as the VB6 executable. Typically this is C:\Program Files\Microsoft Visual Studio\VB98.

When the VB6 dll/exe is compiled the config file must be named the same as the dll/exe with a .config extension and be placed in the same location as the dll/exe. e.g. MyVB6Program.exe.config

The .NET DLL can use code like this to retrieve, for instance, connection strings:

'Fetch the connection string from the app.config file
Dim settings As ConnectionStringSettings = ConfigurationManager.ConnectionStrings(name)
If settings IsNot Nothing Then
' Retrieve the partial connection string.
Dim connectString As String = settings.ConnectionString
' Create a new SqlConnectionStringBuilder based on the partial connection string retrieved from the config file.
Dim builder As DbConnectionStringBuilder
'We need to act differently depending on wether we are using Access or SQL
If settings.ProviderName.ToUpper = "SYSTEM.DATA.ODBC" Then
builder = New OdbcConnectionStringBuilder(connectString)
' Supply the additional values.
builder.Add("Uid", "USER_NAME_HERE")
builder.Add("Pwd", "PASSWORD_HERE")
'This is a bit of a hack but we can check the odbc connection string to see if it contains the phrase 'SQL Server'
'as all sql server odbc connection strings up to and including version 11 will contain this phrase
If settings.ConnectionString.IndexOf("SQL Server", 0, StringComparison.CurrentCultureIgnoreCase) &lt;&gt; -1 Then
useSQLServer = True 'Set the useSQLServer flag
Else
Throw New Exception("Provider '" &amp; settings.ProviderName &amp; "' is not allowed.")
End If
Return builder.ConnectionString
Else
Throw New Exception("Unable to retrieve app.config connectionstrings.")
End If