the connection information through the Server object properties, passing the SQL Server instance name to the Server object constructor function, or using the ServerConnection object to p
Trang 112 Developing with SMO
IN THIS CHAPTER
Using SMO SMO Hierarchy Building the SMO Sample Application
Copyright © 2006 by The McGraw-Hill Companies Click here for terms of use
Trang 2In this chapter, you learn how you can manage SQL Server programmatically
from VB.NET by taking advantage of SQL Management Objects (SMO) Like its predecessor, Distributed Management Objects (SQL-DMO), SMO enables you to develop custom SQL Server management applications that you can tailor to your environment Using SMO with VB.NET or any other Net language, you can create custom SQL Server management interfaces that let you perform all the functions SQL Server’s Management Studio provides In fact, SMO is the foundation for SQL Server’s Management Studio Using SMO, you can list databases and tables; add logins; control replication; import and export data; and perform backups, restores, and many other administrative tasks SMO opens up SQL Server to a number of custom programs that can both display and manipulate SQL Server and all of its databases and objects
In this chapter, you get an overview of SMO, as well as a look at its underlying architecture Then, you see how to use SMO from VB.NET In this section, you see how to add the SMO object library to the Visual Basic Integrated Development Environment (IDE) You also see how to perform some common tasks with SMO Finally, this chapter finishes by presenting a sample SQL Server management utility that’s built using VB.NET and SMO
Using SMO
To get programmatic access to management functions of other database platforms, you might need to master low-level networking and system interfaces—if it’s available at all However, SMO provides a NET framework solution that makes SQL Server’s database management functions easy to access The hierarchy for the SMO objects used in the NET framework is discussed in the next section of this chapter SQL Server’s SMO functions can be used by a programming language that
is supported by the Common Language Runtime (CLR), such as Visual Basic.NET and Visual C#.NET
To use SMO from VB.NET, follow these basic steps:
1. Add a reference to the SMO assemblies and then import the namespaces that are required so that your program can recognize the SMO types
2. Create an instance of the Server object
3. Establish a connection to the instance of the Server object to SQL Server
4. Use the Server object
5. Disconnect from SQL Server
Trang 3The following section of the chapter walks you through the basic steps needed
to build a project using SMO The project presented is a Winforms project built
in Visual Basic, but you can follow these steps to build an ASP project or even
a command-line project
Adding SMO Objects to Visual Studio
Before you can begin to use the SMO objects in Visual Basic’s development
environment, you need to incorporate the SMO assemblies into your Visual Basic
project The files that provide the basic support for SMO are copied to your client
system when you first install the SQL Server client However, you still need to set
a reference to them in Visual Studio’s development environment to enable their use
from your applications To add the SMO references to your Visual Studio project,
you must select the Add Reference option from the Project menu This action displays
the References dialog box you can see in Figure 12-1
Select the NET tab and scroll through the References dialog box until you see the
SMO assemblies: Microsoft.SqlServer.ConnectionInfo, Microsoft.SqlServer
.Smo, Microsoft.SqlServer.SmoEnum, and Microsoft.SqlServer.SqlEnum Selecting
these items and then clicking OK adds the references to Visual Basic’s Interactive
Figure 12-1 Adding references to SMO
Trang 4Development Environment (IDE) To see the SMO properties and methods, you must use Visual Basic’s Object Browser, shown in Figure 12-2
Creating the Server Object
Before you can use any of the SMO methods, you must first specify an import directive for the Microsoft.SqlServer.Management.Smo Namespace in your project The Microsoft.SqlServer.Management.Smo Namespace contains all of the related SQL Server connection and data access classes To add an import directive for the Microsoft.SqlServer.Management.Smo to a VB.NET project, you would add the following code to the declaration section of your source file:
Imports Microsoft.SqlServer.Management.Smo
Next, you must create an instance of the Server object, which is the most basic object in the SMO set You can create an instance of the Server object and establish
a connection to the SQL Server instance in three different ways: explicitly setting
Figure 12-2 Viewing an SMO assembly from the Object Browser
Trang 5the connection information through the Server object properties, passing the
SQL Server instance name to the Server object constructor function, or using the
ServerConnection object to provide the connection information
To explicitly set the connection information through the Server object properties,
you simply declare the Server object variable using the default constructor If you do
not set any of the Server object’s properties, the Server object attempts to connect
to the local instance of SQL Server with the default connection settings To connect
to a remote or named instance of SQL Server, set the name property and any other
properties that affect the connection settings, such as authentication mode, logins,
and passwords, as shown here:
Dim oSQLServer As New Server()
oSQLServer.ConnectionContext.LoginSecure = false
oSQLServer.ConnectionContext.Login = "username"
oSQLServer.ConnectionContext.Password = "password"
To pass the SQL Server instance name to the Server object, you first declare the
Server object variable and pass the SQL Server instance name as a string parameter
in the constructor, as shown here:
Dim oSQLServer As Server = New Server("SQL2005")
To use the ServerConnection object, you need to specify an import directive for
the Microsoft.SqlServer.Management.Common namespace The import directive for
Microsoft.SqlServer.Management.Common is added to the declaration section of
your source file:
Imports Microsoft.SqlServer.Management.Common
In order to use the ServerConnection object to provide the connection information to
the Server object, you declare a ServerConnection object variable and set the connection
information, such as the SQL Server instance name and the authentication mode into its
properties You then pass the ServerConnection object as a parameter to the Server object
constructor Here is an example of this method:
Dim oServerConn As ServerConnection = New ServerConnection()
oServerConn.ServerInstance = "SQL2005"
oServerConn.LoginSecure = True
Dim oSQLServer As New Server(oServerConn)
Trang 6One advantage to using the ServerConnection object is that the connection information can be reused SMO removes the association between the application object and the Server object, allowing you to release the application state In other words, you can instantiate a Server object by reusing an existing connection, perform your application processes, and then release the reference
to the Server object This lets you write a program that use memory efficiently by controlling when you want to release an object’s state.
Using SMO Properties
A SQLServer object has more than 1000 different properties that can be accessed from your application The SMO hierarchy section later in this chapter will show some of the most common SMO objects The SQL Server Books Online help file lists all the SMO object properties and notes whether they are read-only or read/write
TIP
You can use the Object Browser to list the properties for each SQLServer object from Visual Studio’s IDE.
Getting Property Values
You can retrieve the property values for all the properties that are standard data types using the Visual Basic assignment operator (“=”), as shown here:
Dim sInstanceName As String
sInstanceName = oSQLServer.InstanceName
Here, you can see that a string named sInstanceName is first declared using the Visual Basic Dim statement Then the Visual Basic assignment operator is used
to fill the sInstanceName string variable with the contents of the oSQLServer
.InstanceName property This technique works for all the standard Visual Basic data types, including String, Long, and Integer Object properties are treated a little differently, however, as you can see in following example:
Dim oJobServer As Microsoft.SqlServer.Management.Smo.Agent.JobServer oJobServer = oSQLServer.JobServer
To retrieve the contents of SMO object properties, you assign an object reference
to a variable In this case, the Dim statement is used to declare an object of the Smo Agent.JobServer data type named oJobServer Then you assign the contents of the oSQLServer.JobServer object to the oJobServer object
Trang 7Setting Property Values
You can set the value of SMO read/write properties from Visual Basic by using the
assignment operator (“=”) The following example shows how to set the SQLServer
object’s ApplicationName property:
Dim boolDefaultTextMode As Boolean
boolDefaultTextMode = True
oSQLServer.DefaultTextMode = boolDefaultTextMode
In this example, you can see the oSQLServer.DefaultTextMode property is set using
the Visual Basic assignment operator to the value of “True”, which is contained in the
boolDefaultTextMode Boolean variable
TIP
While you can set only properties that use standard data types—such as String, Boolean, or
Long—you cannot set any of the SMO properties that are object data types Object properties are
always read-only.
SMO Property Collections
SMO’s core object hierarchy makes extensive use of object collections, which are
basically groups of related objects For instance, the Databases collection in the
Server object is a collection of Database objects
TIP
Collection objects typically end with an s For instance, Databases indicates a collection of Database
objects.
Table 12-1 lists the object collections that are part of the Server object
Like objects, collections are all contained within a parent object In the case of
the object collections shown in Table 12-1, all the object collections belong to the
SQLServer core object
A collection object is actually an object that has its own set of properties and
methods The following list shows the different properties and methods contained in
the Databases collection:
Count property
IsSynchronized property
Item property
Trang 8ItemByID method Parent property Refresh method You can see that the properties and methods of the Databases collection objects are all oriented toward working with the group of databases For instance, the Count property reports on the number of Database objects contained in the collection, while the ItemByID method returns a specific Database object in the Databases collections Because all collection objects contain and manage multiple objects, the properties and methods for all collections are similar
In contrast, the following list shows a selection of some of the primary properties
of an individual Database object:
CreateDate property DataSpaceUsage property Defaults collection Drop method FileGroups collection
Table 12-1 SMO Server Object Collections
SMO Server Object Collection Description
BackupDevices Listing of backup devices available
Credentials Listing of credential objects
Endpoints Listing of endpoints defined
Languages Listing of supported languages
LinkedServers Listing of registered linked servers
Roles Listing of roles defined on SQL Server
SystemDataTypes Listing of system data types defined
SystemMessages Listing of system messages
UserDefinedMessages Listing of user-defined messages
Trang 9Name property
Owner property
Rename method
SpaceAvailable property
StoredProcedures collection
Tables collection
Views collection
You can see that the properties and methods of the Database object are all directly
related to a SQL Server database For instance, the Drop method drops the database
from the server, while the Owner property contains the name of the database owner
Notice that some of the Database object properties are also other Collection objects
For instance, the StoredProcedures property is a collection of the stored procedures
in the database Likewise, the Tables property is a collection of the tables contained
in the database
Iterating Through Collections
To use SMO effectively, one of the first things you should know is how to work with
the collection objects Iterating through a collection can be accomplished using the
following code:
Dim oServerConn As ServerConnection = New ServerConnection()
oServerConn.ServerInstance = "SQL2005"
oServerConn.LoginSecure = True
Dim oSQLServer As New Server(oServerConn)
For Each oDatabase As Database In oSQLServer.Databases
Debug.Print (oDatabase.Name)
Next
Visual Basic’s For Each statement automatically loops through all the objects in
a collection This example prints a list of all the database names contained in the
Databases collection of the oSQLServer object The code within the For Each block
refers to the current object in the collection
Getting a Specific Collection Object
You also need to understand how to reference a specific object in a collection You
can refer to individual objects within a collection either by the object name or by
Trang 10the ordinal value within the collection For example, to refer to a Database object by name, you could use the following:
Dim oServerConn As ServerConnection = New ServerConnection()
oServerConn.ServerInstance = "SQL2005"
oServerConn.LoginSecure = True
Dim oSQLServer As New Server(oServerConn)
oSQLServer.Databases("SMOSample")
or
Dim oServerConn As ServerConnection = New ServerConnection()
oServerConn.ServerInstance = "SQL2005"
oServerConn.LoginSecure = True
Dim oSQLServer As New Server(oServerConn)
oSQLServer.Databases.Item("SMOSample")
or
Dim oServerConn As ServerConnection = New ServerConnection()
oServerConn.ServerInstance = "SQL2005"
oServerConn.LoginSecure = True
Dim oSQLServer As New Server(oServerConn)
Dim sDatabaseName As String
sDatabaseName = "SMOSample"
oSQLServer.Databases.Item(sDatabaseName)
All these examples are equivalent In each case, they reference the database named “SMOSample” in the oSQLServer object Because the Item method is the default, you can optionally omit the use of the “Item” method In other words, to reference an individual collection object by name, you pass the Item method a string containing the object’s name
NOTE
This code implicitly uses the Item method of the collection object The Item method is the default method
in a collection; therefore, you needn’t explicitly code oSQLServer.Databases.Item(“SMOSample”) The Item method can accept either a string or an ordinal number.
Trang 11To refer to the first database object by ordinal number, you use the following code:
Dim oServerConn As ServerConnection = New ServerConnection()
oServerConn.ServerInstance = "SQL2005"
oServerConn.LoginSecure = True
Dim oSQLServer As New Server(oServerConn)
oSQLServer.Databases(0)
Again, this code implicitly uses the Item method of the Databases collections
In this case, the Item method is passed the first ordinal value, instead of a string
containing the name of the database The ordinal value of 0 returns the first database
in the oSQLServer object Similarly, the ordinal value of 1 returns the second database,
and so on
SMO Hierarchy
The SMO object model extends and supplants its predecessor, the SQL-DMO object
model Unlike the SQL-DMO object framework, which was based on COM, the
newer SMO object model is based on the NET framework This means that SMO
requires the NET framework to be installed on the systems that are used to run SMO
management applications SMO can be used to manage SQL Server 7 and SQL Server
2000, as well as SQL Server 2005, allowing you to easily manage a multiversion
environment SQL-DMO will also continue to be supported by SQL Server 2005,
allowing backward compatibility for your applications, but SQL-DMO has not been
enhanced to include the new features found in the new release In other words,
SQL-DMO is limited to supporting only those features that were found in the previous
releases of SQL Server The new SMO object framework contains over 150 new
classes, enabling your custom management application to take advantage of the new
features found in SQL Server 2005
The SMO object model consists of a hierarchy of objects contained in several
namespaces and dll files The different SMO namespaces represent different areas
of functionality within SMO Table 12-2 lists the namespaces and their relative
functionality
The core SMO namespace, Microsoft.SqlServer.Management.Smo, is implemented
as a NET assembly This means that the Common Language Runtime (CLR) must be
installed before using the SMO objects The main SMO namespace contains classes
that are divided into two categories: instance classes and utility classes.