ExportDbInfo Source Code

This code was downloaded from MOBZystems, Home of Tools. No license, use at will. And at your own risk!

Imports System.IO
Imports System.Text
  
Module MainModule
  
  Const ExeName As String = "ExportDbInfo"
  Const DefaultSourceFileName As String = "DbInfo.vb"
  
  
  ''' <summary>
  ''' Export the structure of an Access database to a VB.NET source file
  ''' 
  ''' Usage: ExportDbInfo database-file-name [source-file-name]
  ''' 
  ''' Args(0) is Access database name
  ''' Args(1) is VB.NET source file name (optional)
  ''' </summary>
  ''' <returns>0 if OK, 1 if error(s)</returns>
  Function Main(ByVal Args() As String) As Integer
    If Args.Length > 0 Then
      Dim DatabaseName As String = Args(0)
  
      Dim SourcefileName As String = DefaultSourceFileName
      If Args.Length > 1 Then
        SourcefileName = Args(1)
      End If
  
      If Args.Length > 2 Then
        ErrorMessage("Too many arguments")
        Return 1
      End If
  
      Try
        Return ExportDBStructure(DatabaseName, SourcefileName)
      Catch Ex As ApplicationException
        Console.Error.WriteLine(ExeName + ": " + Ex.Message)
        Return 1
      Catch Ex As Exception
        Console.Error.WriteLine(ExeName + ": Unexpected error: " + Ex.Message)
        Return 1
      End Try
    Else
      ErrorMessage("No arguments specified")
      Return 1
    End If
  End Function
  
  ''' <summary>
  ''' Print an error message to Console.Error, then report usage instructions
  ''' </summary>
  Private Sub ErrorMessage(ByVal Message As String)
    Console.Error.WriteLine( _
      ExeName + " v" + _
      My.Application.Info.Version.Major.ToString() + "." + _
      My.Application.Info.Version.Minor.ToString() + "." + _
      My.Application.Info.Version.Build.ToString() + _
      ": " + Message _
    )
    Console.Error.WriteLine()
    Console.Error.WriteLine("Usage:")
    Console.Error.WriteLine()
    Console.Error.WriteLine(ExeName + " database-name [source-file-name]")
    Console.Error.WriteLine()
    Console.Error.WriteLine("Writes table and column names of the specified Access database")
    Console.Error.WriteLine("to the specified VB.NET source file.")
    Console.Error.WriteLine("Default source file name is " + DefaultSourceFileName + " in the working directory.")
    Console.Error.WriteLine()
  End Sub
  
  ''' <summary>
  ''' Do the actual work: export the source file
  ''' </summary>
  ''' <param name="DatabaseName">File name of an Access database</param>
  ''' <param name="SourceFileName">Name of the VB.NET source file</param>
  Private Function ExportDBStructure(ByVal DatabaseName As String, ByVal SourceFileName As String) As Integer
    ' Set up an Access connection string
    Dim ConnectionString As String = String.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0}", DatabaseName)
  
    ' The schema information for this connection
    Dim SchemaInfo As DbSchemaInfo
  
    Using Connection As New OleDb.OleDbConnection(ConnectionString)
      Try
        Connection.Open()
        ' Get schema information for the connection
        SchemaInfo = New DbSchemaInfo(Connection)
      Catch Ex As Exception
        Throw New ApplicationException("Failed to open database '" + DatabaseName + "': " + Ex.Message, Ex)
      End Try
  
      Connection.Close()
    End Using
  
    Dim ErrorCount As Integer = 0
  
    ' First check validity of table and column names
    ' Report any errors to Console.Error
    For Each TableInfo As DbSchemaInfo.DbSchemaTableInfo In SchemaInfo.Tables
      Dim TableName As String = TableInfo.TableName
  
      If TableName.Contains(" ") Then
        Console.Error.WriteLine("Table name '{0}' contains spaces", TableName)
        ErrorCount += 1
      End If
      ' Create public shared constants for each column
      For Each ColumnName As String In TableInfo.ColumnNames
        If ColumnName.Contains(" ") Then
          Console.Error.WriteLine("Table '{0}': column name '{1}' contains spaces", TableName, ColumnName)
          ErrorCount += 1
        End If
      Next ColumnName
  
    Next TableInfo
  
    ' Abort here if we have errors:
    If ErrorCount > 0 Then
      Console.Error.WriteLine(String.Format("{0} Error(s)", ErrorCount))
      Return 1 ' Signal error
    Else
      ' Write all output to this string builder
      Dim Output As New StringBuilder
  
      ' Write out a header
      Dim N As DateTime = DateTime.Now
  
      Output.AppendLine("Imports System.ComponentModel")
      Output.AppendLine()
  
      Output.AppendLine("''' <summary>")
      Output.AppendLine("''' Generated by " + ExeName + " at " + N.ToString("yyyy\-MM\-dd HH\:mm\:ss"))
      Output.AppendLine("''' *** DO NOT MODIFY ***")
      Output.AppendLine("''' </summary>")
  
      ' Set up a class definition. Derive class name from file name
      Dim ClassName As String = Path.GetFileNameWithoutExtension(SourceFileName)
  
      Output.AppendLine("Public Class " + ClassName)
  
      ' Loop over tables to create class definitions for each
      For Each TableInfo As DbSchemaInfo.DbSchemaTableInfo In SchemaInfo.Tables
        Dim TableName As String = TableInfo.TableName
  
        ' Write out a class definition for the table
        Output.AppendLine(Chr(9) + String.Format("Public Class {0}", TableName))
  
        ' Create public shared constants for each column
        For Each ColumnName As String In TableInfo.ColumnNames
          Output.AppendLine(Chr(9) + Chr(9) + String.Format("Public Const {1} As String = ""{1}""", TableName, ColumnName))
        Next ColumnName
  
        Output.AppendLine(Chr(9) + String.Format("End Class ' {0}", TableName))
  
        Output.AppendLine()
  
      Next TableInfo
  
      ' Write out a shared member for each table
      For Each TableInfo As DbSchemaInfo.DbSchemaTableInfo In SchemaInfo.Tables
        Output.AppendLine(Chr(9) + String.Format("Public Const {0}Table As String = ""{0}""", TableInfo.TableName))
      Next TableInfo
  
      ' End outer class
      Output.AppendLine(String.Format("End Class ' {0}", ClassName))
  
      Try
        ' Write it all out to the specified source file
        File.WriteAllText(SourceFileName, Output.ToString())
      Catch Ex As Exception
        Throw New ApplicationException("Failed to write to source file '" + SourceFileName + "': " + Ex.Message, Ex)
      End Try
  
      Console.WriteLine(ExeName + ": Database '" + DatabaseName + "' sucessfully exported to '" + SourceFileName + "'.")
      Return 0 ' No error
    End If
  End Function
End Module