Tuesday, 23 December 2008

Converting DMO to SMO

SQL 2008 no longer supports DMO. Below is some VB.NET Code for creating a database in VB.NET using DMO


Imports SQLDMO

..

Public Function CREATE_DATABASE(ByVal NewDatabaseName As String, ByVal MDFPath As String, ByVal LDFPath As String, ByRef Message As String) As Boolean

REM Create an SQLDMO application
Dim sqlApp As New SQLDMO.ApplicationClass()

REM Create an Server, which resembles to your actual server
Dim srv As New SQLDMO.SQLServerClass()

REM Create Database
Dim nDatabase As New SQLDMO.Database()

REM Create Data Files
Dim nDBFileData As New SQLDMO.DBFile()

REM Create Log Files
Dim nLogFile As New SQLDMO.LogFile()

Try
REM Assign a name to database
nDatabase.Name = NewDatabaseName

REM Assign a name to datafile
nDBFileData.Name = NewDatabaseName
nDBFileData.PhysicalName = MDFPath
nDBFileData.PrimaryFile = True
nDBFileData.Size = 2
nDBFileData.FileGrowthType = SQLDMO.SQLDMO_GROWTH_TYPE.SQLDMOGrowth_MB
nDBFileData.FileGrowth = 1

REM Add the DBFile object
nDatabase.FileGroups.Item("PRIMARY").DBFiles.Add(nDBFileData)
REM Assign name to Log files
nLogFile.Name = NewDatabaseName + "_Log"
nLogFile.PhysicalName = LDFPath
nLogFile.Size = 2
nDatabase.TransactionLog.LogFiles.Add(nLogFile)
srv.LoginSecure = True
srv.Connect(_SourceDatabaseServer)
srv.Databases.Add(nDatabase)
srv.DisConnect()
srv = Nothing
Return True

Catch ex As Exception
Message = ex.Message
Return False
End Try

End Function


To do the same thing in SMO


Imports Microsoft.SqlServer.Management.Smo
Imports Microsoft.SqlServer.Management.Common

...

Public Function CREATE_DATABASE(ByVal NewDatabaseName As String, ByVal MDFPath As String, ByVal LDFPath As String, ByRef Message As String) As Boolean

Try
'Server server = new Server("localhost");
Dim iServer As New Server(_SourceDatabaseServer)

'Database database = new Database(server, "TESTDATABASE");
Dim iDB As New Database(iServer, NewDatabaseName)

'FileGroup fileGroup = new FileGroup(database, "PRIMARY");
Dim iFileGroup As New FileGroup(iDB, "PRIMARY")

'DataFile dataFile = new DataFile(fileGroup, "TESTDTABASE_DATA", "c:
'\\TESTDATABASE_DATA.mdf");
Dim iDataFile As New DataFile(iFileGroup, NewDatabaseName + "_Data", MDFPath)

'dataFile.GrowthType = FileGrowthType.Percent;
'dataFile.Growth = 10;
'dataFile.Size = 4000;
'fileGroup.Files.Add(dataFile);

iFileGroup.Files.Add(iDataFile)
'database.FileGroups.Add(fileGroup);

iDB.FileGroups.Add(iFileGroup)
'LogFile logFile = new LogFile(database, "TESTDATABASE_LOG", "c:
'\\TESTDATABASE_LOG.ldf");
Dim iLogFile As New LogFile(iDB, NewDatabaseName + "_Log", LDFPath)

iLogFile.GrowthType = FileGrowthType.Percent

'logFile.Growth = 10;
iLogFile.Size = 2

'database.LogFiles.Add(logFile);
iDB.LogFiles.Add(iLogFile)

'database.Create(false);
iDB.Create(False)

Return True

Catch ex As Exception
Message = ex.Message
Return False
End Try

End Function