Imports Microsoft.SqlServer.Management.Smo

Public Class Form1

  Private Sub Log(ByVal Msg As String)
    txtOutput.AppendText(Msg & vbCrLf)
  End Sub

  Private Sub ListDatabases(ByVal SRV As Server)
    Log("")
    For Each DB As Database In SRV.Databases
      Log(DB.Name)
    Next
  End Sub

  ' Click event

  Private Sub btnTest_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnTest.Click

    ' Connect and basics

    Dim SRV As New Server(Environment.MachineName)
    Log(SRV.Name)
    Log(SRV.Information.Edition)
    Log(SRV.Information.VersionString)

    ' List Databases

    Log("")
    Log(SRV.Databases.Count)
    Log("")
    ListDatabases(SRV)

    ' Create a Database

    Try
      Dim newDB As Database
      newDB = New Database(SRV, "VSLive")
      newDB.Create()
    Catch Ex As Exception
      MessageBox.Show(Ex.Message, "Error")
    End Try
    ListDatabases(SRV)

    ' Drop Database

    'SRV.Databases("VSLive").Drop()

    ' Request table properties

    Dim TBL As Table
    TBL = SRV.Databases("AdventureWorks").Tables.Item("Contact", "Person")
    Log("")
    Log(TBL.Name) ' lightweight property
    Log(TBL.Schema) ' lightweight property
    Log(TBL.CreateDate) ' must fully instantiate first
    Log(TBL.DataSpaceUsed) ' expensive property

    'Dim SRV As New Server(Environment.MachineName)
    Dim SCR As New Scripter(SRV)
    SCR.Options.FileName = "c:\projects\script.txt"
    SCR.Options.AppendToFile = True
    SCR.Options.IncludeHeaders = True

    ' URNCollection is a new collection used by SMO

    Dim LST As New UrnCollection
    ' XPath style syntax for reference DB objects
    LST.Add(New Urn("Server[@Name = '" & _
       Environment.MachineName & "']/" & _
       "Database[@Name = 'Northwind']/" & _
       "Table[@Name = 'Customers']"))
    LST.Add(New Urn("Server[@Name = '" & _
       Environment.MachineName & "']/" & _
       "Database[@Name = 'Northwind']/" & _
       "Table[@Name = 'Products']"))

    ' Execute

    SCR.Script(LST)
    Log("Scripting complete")

    Dim SRV As New Server(Environment.MachineName)
    Dim CON As Microsoft.SqlServer.Management.Common.ServerConnection = SRV.ConnectionContext

    CON.ServerInstance = Environment.MachineName
    CON.SqlExecutionModes = Microsoft.SqlServer.Management.Common.SqlExecutionModes.ExecuteSql

    CON.Connect()

    Log("")
    Log("Executing:")
    Log(CON.ExecuteScalar("SELECT @@Version"))

    Log("")
    Log("Captured:")
    For Each S As String In CON.CapturedSql.Text
      Log(S)
    Next

    CON.Disconnect()

  End Sub

End Class
