This document is archived and information here might be outdated.  Recommended version.


Connecting to geodatabases and databases (ArcObjects .NET 10.5 SDK)

Connecting to geodatabases and databases


Summary
This topic demonstrates how to connect to each type of geodatabase and to various types of relational databases that do not have the enterprise geodatabase schema installed.

In this topic


About workspaces

A workspace is a container of spatial and non-spatial datasets, such as feature classes, raster datasets, and tables. Workspaces provide methods to access existing datasets and to create datasets.
The following are the three types of workspaces (represented by values in the esriWorkspaceType enumeration):
  • Shapefile workspaces and ArcInfo workspaces—Are examples of file-based workspaces (esriFileSystemWorkspace).
  • Personal and file geodatabases—Are examples of local database workspaces (esriLocalDatabaseWorkspace).
  • Databases and enterprise geodatabases—Stored in a relational database management system (RDBMS) such as Oracle, DB2, SQL Server, Informix, or PostgreSQL is a remote database workspace (esriRemoteDatabaseWorkspace). Databases without the enterprise geodatabase schema can also be connected to in ArcGIS. When connected to, they return the (esriRemoteDatabaseWorkspace) type in the esriWorkspaceType enumeration.   
There are several methods that can be used to open a workspace, each with its own purpose. This topic reviews these methods for different types of workspaces and discusses when one can offer advantages over another.
To open a workspace, an appropriate workspace factory must be created. Each workspace type has its own workspace factory.
A workspace factory is a dispenser of workspaces and allows a client to connect to a workspace specified by a set of connection properties. A workspace factory is a co-creatable singleton object. For more information, see Interacting with singleton objects. A singleton object can only be instantiated once in a process. Workspace factory classes for geodatabases are located in the DataSourcesGDB library.

Methods for connecting to a workspace

The following are the three different methods to open a workspace from an appropriate workspace factory:
  • IWorkspaceFactory.Open—The Open method takes as input a set of connection properties that specify the workspace with which to establish a connection.
  • IWorkspaceFactory.OpenFromFile—The OpenFromFile method takes the path name of a file or directory that represents a file-based workspace, a local geodatabase workspace, or an ArcSDE connection file and returns the appropriate workspace.
  • IWorkspaceFactory2.OpenFromString—The OpenFromString method on the IWorkspaceFactory2 interface was added to allow the opening of a workspace using a connection string that describes the connection properties for the workspace. The connection string is a collection of name-value pairs separated by semicolons (;).
Each workspace factory maintains a pool of currently connected, active workspaces that are referenced by the application. When any of the previously listed Open* methods are called, the workspace factory verifies if a workspace has previously been opened with a matching set of properties. If so, a reference to the existing instance is returned.
In the case of enterprise geodatabases, when an application connects to a workspace but omits some connection properties (such as user name and password), the workspace factory checks a set of "core" properties (DBCLIENT, DATABASE_CONNECTION_PROPERTIES and AUTHENTICATION_MODE) to verify they match any open workspaces. If so, the workspace factory returns a reference to the matching workspace.

Connecting to file geodatabases

The required workspace factory used to connect to a file geodatabase is the FileGDBWorkspaceFactory class. Typically, the OpenFromFile method is used to connect to a file geodatabase. The following code example shows how to call this method:
[C#]
// For example, path=@"C:\myData\myfGDB.gdb".
public static IWorkspace FileGdbWorkspaceFromPath(String path)
{
    Type factoryType=Type.GetTypeFromProgID(
        "esriDataSourcesGDB.FileGDBWorkspaceFactory");
    IWorkspaceFactory workspaceFactory=(IWorkspaceFactory)Activator.CreateInstance
        (factoryType);
    return workspaceFactory.OpenFromFile(path, 0);
}
[VB.NET]
' For example, path="C:\myData\myfGDB.gdb".
Public Shared Function FileGdbWorkspaceFromPath(ByVal Path As String) As IWorkspace
Dim factoryType As Type=Type.GetTypeFromProgID("esriDataSourcesGDB.FileGDBWorkspaceFactory")
Dim workspaceFactory As IWorkspaceFactory=CType(Activator.CreateInstance(factoryType), IWorkspaceFactory)
Return workspaceFactory.OpenFromFile(Path, 0)
End Function

Connecting to personal geodatabases

The required workspace factory used to connect to a personal geodatabase is the AccessWorkspaceFactory class. Typically, the OpenFromFile method is used to connect to a file geodatabase. The following code example shows how to call this method:
[C#]
// For example, path=@"C:\myData\mypGDB.mdb".
public static IWorkspace AccessWorkspaceFromPath(String path)
{
    Type factoryType=Type.GetTypeFromProgID(
        "esriDataSourcesGDB.AccessWorkspaceFactory");
    IWorkspaceFactory workspaceFactory=(IWorkspaceFactory)Activator.CreateInstance
        (factoryType);
    return workspaceFactory.OpenFromFile(path, 0);
}
[VB.NET]
' For example, path="C:\myData\mypGDB.mdb".
Public Shared Function AccessWorkspaceFromPath(ByVal Path As String) As IWorkspace
Dim factoryType As Type=Type.GetTypeFromProgID("esriDataSourcesGDB.AccessWorkspaceFactory")
Dim workspaceFactory As IWorkspaceFactory=CType(Activator.CreateInstance(factoryType), IWorkspaceFactory)
Return workspaceFactory.OpenFromFile(Path, 0)
End Function

Connecting to enterprise geodatabases

The workspace factory to use to connect to an enterprise geodatabase is SdeWorkspaceFactory. The connection properties specify the server and instance to connect to and can be saved in a connection file (.sde) on the file system.
The properties can include the following connection properties of the database being connected to:
  • INSTANCE—The instance being connected to. This is an optional property that remains in the connection properties for legacy reasons. It is not necessary to set this parameter when making a connection to an enterprise geodatabase.
  • DATABASE—The database being connected to if the specific DBMS supports databases.
  • USER—The connected user.
  • PASSWORD—The connected user's password.
  • DBCLIENT—The type of database management system (DBMS) for which the connection is being made. For example, if connecting to an Oracle database, the string "oracle" should be used for this parameter.   
  • DB_CONNECTION_PROPERTIES—The aspect of the connection that uniquely identifies the database server. For Oracle connections, this can be either a string identifying an entry in the TNSNames.ora file or an Oracle Easy Connect string. For databases that support Open Database Connectivity (ODBC) connections, this can be an ODBC string or an identifier, which will help the connecting machine look up the data source name if configured. Internet Protocol version 6 (IPv6)-style identifiers are also supported by this parameter if the database server is configured to use this protocol for identification.    
  • AUTHENTICATION_MODE—The credential authentication mode of the connection. Acceptable values are the operating system authentication (OSA) and DBMS. The default is DBMS. If the AUTHENTICATION_MODE is OSA, the USER and PASSWORD properties are not required. OSA uses the operating system credentials to establish a connection with the database.
  • VERSION—The transactional version to connect to. The acceptable value is a string that represents a transaction version name. If no version is passed in, the default version will be connected to.
  • HISTORICAL_NAME—The historical version to connect to. The acceptable value is a string that represents a historical marker name.
  • HISTORICAL_TIMESTAMP—The moment in history to establish a historical version connection. The acceptable value is a date object containing a date time that represents a moment time stamp. The formatting of the date is DBMS specific (for example, SQLServer="1/1/2006 12:00:01 AM").
Only one of the version properties (that is, VERSION, HISTORICAL_NAME, or HISTORICAL_TIMESTAMP) should be used since the workspace connection can only represent one version.
If any of the Open methods for a workspace are called with insufficient properties, a Connection dialog box appears requesting the required properties. This can be used with esriRemoteDatabaseWorkspace type workspaces to allow the user to connect with specific credentials (for example, prompting them to enter a specific user name or password).

Connecting to a transactional version

In the following code example, a property set is populated from supplied strings to make a connection to an enterprise geodatabase workspace with a transactional version. The property set is then used by the Open method to return a workspace. This approach involves the most code; however, it can be customized into a general function for connecting to enterprise geodatabases based on supplied parameters from the user.
[C#]
public static IWorkspace ConnectToTransactionalVersion(String dbclient, String
    dbConnProp, String user, String password, String database, String version,
    String authentication)
{
    IPropertySet propertySet=new PropertySet();
    propertySet.SetProperty("DBCLIENT", dbclient);
    propertySet.SetProperty("DB_CONNECTION_PROPERTIES", dbConnProp);
    propertySet.SetProperty("DATABASE", database);
    propertySet.SetProperty("USER", user);
    propertySet.SetProperty("PASSWORD", password);
    propertySet.SetProperty("VERSION", version);
    propertySet.SetProperty("AUTHENTICATION_MODE", authentication);
    Type factoryType=Type.GetTypeFromProgID(
        "esriDataSourcesGDB.SdeWorkspaceFactory");
    IWorkspaceFactory workspaceFactory=(IWorkspaceFactory)Activator.CreateInstance
        (factoryType);
    return workspaceFactory.Open(propertySet, 0);
}
[VB.NET]
Public Shared Function ConnectToTransactionalVersion(ByVal dbclient As String,
ByVal dbConnProp As String, ByVal user As String, ByVal password As String,
ByVal database As String, ByVal Version As String, ByVal authentication As String) As IWorkspace
Dim propertySet As IPropertySet=New PropertySetClass()

propertySet.SetProperty("DBCLIENT", dbclient)

    propertySet.SetProperty("DB_CONNECTION_PROPERTIES", dbConnProp)

        propertySet.SetProperty("DATABASE", database)

            propertySet.SetProperty("USER", user)

                propertySet.SetProperty("PASSWORD", password)

                    propertySet.SetProperty("VERSION", Version)

                        propertySet.SetProperty("AUTHENTICATION_MODE", authentication)
                            Dim factoryType As Type=Type.GetTypeFromProgID("esriDataSourcesGDB.SdeWorkspaceFactory")
                            Dim workspaceFactory As IWorkspaceFactory=CType(Activator.CreateInstance(factoryTpe))
                            Return workspaceFactory.Open(propertySet, 0)
                        End Function

Connecting to a historical marker name

If archiving is enabled on data in an enterprise geodatabase, a historical version can be specified when connecting to the geodatabase. It is possible to create a named marker at some point. These markers are created with IHistoricalWorkspace and can be used to make a connection to this specific time.
To connect to a historical marker, augment the property set and replace the VERSION property with a HISTORICAL_NAME property. In the following code example, the name of the historical marker is Year End 2006:
[C#]
// For example, DBConnProp="Kona".
// database="sde" or "" if Oracle.
// instance="5151".
// user="vtest".
// password="go".
// historicalName="Year End 2006".
public static IWorkspace ConnectoToHistoricalVersion(String DBConnProp, String
    dbclient, String user, String password, String database, String historicalName)
{
    IPropertySet propertySet=new PropertySet();
    propertySet.SetProperty("DBCLIENT", dbclient);
    propertySet.SetProperty("DB_CONNECTION_PROPERTIES", DBConnProp);
    propertySet.SetProperty("DATABASE", database);
    propertySet.SetProperty("USER", user);
    propertySet.SetProperty("PASSWORD", password);
    propertySet.SetProperty("HISTORICAL_NAME", historicalName);

    Type factoryType=Type.GetTypeFromProgID(
        "esriDataSourcesGDB.SdeWorkspaceFactory");
    IWorkspaceFactory workspaceFactory=(IWorkspaceFactory)Activator.CreateInstance
        (factoryType);
    return workspaceFactory.Open(propertySet, 0);
}
[VB.NET]
' For example, DBConnProp="Kona".
' database="sde" or "" if Oracle.
' instance="5151".
' user="vtest".
' password="go".
' historicalName="Year End 2006".
Public Shared Function ConnectoToHistoricalVersion(ByVal server As String, ByVal instance As String, _
                                                   ByVal user As String, ByVal password As String, ByVal database As String, ByVal historicalName As String) As IWorkspace
Dim propertySet As IPropertySet=New PropertySetClass()

propertySet.SetProperty("DB_CONNECTION_PROPERTIES", DBConnProp)

    propertySet.SetProperty("DATABASE", database)

        propertySet.SetProperty("USER", user)

            propertySet.SetProperty("PASSWORD", password)

                propertySet.SetProperty("HISTORICAL_NAME", historicalName)
                    
                    Dim factoryType As Type=Type.GetTypeFromProgID("esriDataSourcesGDB.SdeWorkspaceFactory")
                    Dim workspaceFactory As IWorkspaceFactory=CType(Activator.CreateInstance(factoryType), IWorkspaceFactory)
                    Return workspaceFactory.Open(propertySet, 0)
                End Function

Connecting to a historical time stamp

It is also possible to connect at any time with the historical time stamp property. The following code example replaces the Historical_Name property with Historical_Timestamp to connect to an enterprise geodatabase. Convert a string representing a date to a date object when using it throughout the archiving application programming interface (API). This allows any date conversion errors to be handled before they are used to connect to a workspace.
[C#]
// For example, server="Kona".
// database="sde".
// instance="5151".
// user="vtest".
// password="go".
// timestamp="1/1/2006 12:00:01 AM".
public static IWorkspace ConnectToHistoricalTimestamp(String DBConnProp, String
    dbclient, String user, String password, String database, String timestamp)
{
    IPropertySet propertySet=new PropertySetClass();
    propertySet.SetProperty("DBCLIENT", dbclient);
    propertySet.SetProperty("DB_CONNECTION_PROPERTIES", DBConnProp);
    propertySet.SetProperty("DATABASE", database);
    propertySet.SetProperty("USER", user);
    propertySet.SetProperty("PASSWORD", password);

    // Convert a string representing a date to a date object when using it 
    // throughout the archiving API.
    DateTime dateTime=Convert.ToDateTime(timestamp);
    propertySet.SetProperty("HISTORICAL_TIMESTAMP", dateTime);

    Type factoryType=Type.GetTypeFromProgID(
        "esriDataSourcesGDB.SdeWorkspaceFactory");
    IWorkspaceFactory workspaceFactory=(IWorkspaceFactory)Activator.CreateInstance
        (factoryType);
    return workspaceFactory.Open(propertySet, 0);
}
[VB.NET]
' For example, DBConnProp="Kona".
' database="sde".
' instance="5151".
' user="vtest".
' password="go".
' timestamp="1/1/2006 12:00:01 AM".
Public Shared Function ConnectToHistoricalTimestamp(ByVal server As String, ByVal instance As String, _
                                                    ByVal user As String, ByVal password As String, ByVal database As String, ByVal timestamp As String) As IWorkspace
Dim propertySet As IPropertySet=New PropertySetClass()

propertySet.SetProperty("DB_CONNECTION_PROPERTIES", DBConnProp)

    propertySet.SetProperty("DATABASE", database)

        propertySet.SetProperty("USER", user)

            propertySet.SetProperty("PASSWORD", password)
                
                ' Convert a string representing a date to a date object when using it
                ' throughout the archiving API.
                Dim dateTime As DateTime=Convert.ToDateTime(timestamp)

                propertySet.SetProperty("HISTORICAL_TIMESTAMP", dateTime)
                    
                    Dim factoryType As Type=Type.GetTypeFromProgID("esriDataSourcesGDB.SdeWorkspaceFactory")
                    Dim workspaceFactory As IWorkspaceFactory=CType(Activator.CreateInstance(factoryType), IWorkspaceFactory)
                    Return workspaceFactory.Open(propertySet, 0)
                End Function
If an ArcSDE connection file created in ArcCatalog (or created programmatically with IWorkspaceFactory.Create) is used to organize and distribute the connection information for an enterprise geodatabase, the OpenFromFile method can be used to connect to the workspace.
In the following code example, the path to the .sde connection file stored on disk is used to create the connection with the OpenFromFile method:
[C#]
// For example, connectionFile=@"C:\myData\Connection to Kona.sde".
public static IWorkspace ArcSdeWorkspaceFromFile(String connectionFile)
{
    Type factoryType=Type.GetTypeFromProgID(
        "esriDataSourcesGDB.SdeWorkspaceFactory");
    IWorkspaceFactory workspaceFactory=(IWorkspaceFactory)Activator.CreateInstance
        (factoryType);
    return workspaceFactory.OpenFromFile(connectionFile, 0);
}
[VB.NET]
' For example, connectionFile="C:\myData\Connection to Kona.sde".
Public Shared Function ArcSdeWorkspaceFromFile(ByVal connectionFile As String) As IWorkspace
Dim factoryType As Type=Type.GetTypeFromProgID("esriDataSourcesGDB.SdeWorkspaceFactory")
Dim workspaceFactory As IWorkspaceFactory=CType(Activator.CreateInstance(factoryType), IWorkspaceFactory)
Return workspaceFactory.OpenFromFile(connectionFile, 0)
End Function
The OpenFromString method is most commonly used for convenience. An example of this is when a specific application accesses an enterprise geodatabase with well-known connection properties. In this case, creating a string of the name-value pairs might be easier than creating a property set for the same parameters.
In the following code example, connection is made to the same ArcSDE instance as in the Open method example, except as a different user:
[C#]
// For example, connectionString="DB_CONNECTION_PROPERTIES=Kona;DATABASE=sde;USER=Editor;PASSWORD=Editor;VERSION=sde.DEFAULT".
public static IWorkspace ArcSdeWorkspaceFromString(String connectionString)
{
    Type factoryType=Type.GetTypeFromProgID(
        "esriDataSourcesGDB.SdeWorkspaceFactory");
    IWorkspaceFactory2 workspaceFactory2=(IWorkspaceFactory2)
        Activator.CreateInstance(factoryType);
    return workspaceFactory2.OpenFromString(connectionString, 0);
}
[VB.NET]
' For example, connectionString="DB_CONNECTION_PROPERTIES=Kona;DATABASE=sde;USER=Editor;PASSWORD=Editor;VERSION=sde.DEFAULT".
Public Shared Function ArcSdeWorkspaceFromString(ByVal connectionString As String) As IWorkspace
Dim factoryType As Type=Type.GetTypeFromProgID("esriDataSourcesGDB.SdeWorkspaceFactory")
Dim workspaceFactory2 As IWorkspaceFactory2=CType(Activator.CreateInstance(factoryType), IWorkspaceFactory2)
Return workspaceFactory2.OpenFromString(connectionString, 0)
End Function

Connecting to enterprise geodatabases on SQL Server Express

Enterprise geodatabases on SQL Server Express are remote database workspaces and use the SdeWorkspaceFactory to make a connection to the workspace.

Using the workspace factory

Personal and workgroup ArcSDE geodatabases can be connected to using the same code. The code for both is also very similar to that of an enterprise ArcSDE geodatabase. Personal and workgroup ArcSDE geodatabases only support connections using direct connect and do not support the three-tier connections that an enterprise ArcSDE does.
Additionally, connections can only be made using OSA, where the user's operating system credentials are used for the user name and password. The geodatabases in a personal and workgroup ArcSDE are always owned by the database owner (dbo) user. The version names are prefixed by dbo.
The following code example contains minor differences from the code used to connect to an enterprise geodatabase. The direct connection is set up in the instance property. In this code example, the AUTHENTICATION_MODE property is also introduced. This property defaults to DBMS, which means that the DBMS will be used to authenticate the user's credentials. The authentication mode has been set to OSA instead of passing in the user name and password.
[C#]
// For example, for direct connect with OSA authentication.
// DBConnProp="tivo_sqlexpress".
// Instance="sde:sqlserver:tivo\\sqlexpress".
// Database="sewer".
// Authentication_mode="OSA".
// Version="dbo.DEFAULT".
public static IWorkspace WorkgroupArcSdeWorkspaceFromPropertySet(String server,
    String instance, String authenticationMode, String database, String version)
{
    IPropertySet propertySet=new PropertySetClass();
    propertySet.SetProperty("DB_CONNECTION_PROPERTIES", DBConnProp);
    propertySet.SetProperty("DATABASE", database);
    propertySet.SetProperty("AUTHENTICATION_MODE", authenticationMode);
    propertySet.SetProperty("VERSION", version);

    Type factoryType=Type.GetTypeFromProgID(
        "esriDataSourcesGDB.SdeWorkspaceFactory");
    IWorkspaceFactory workspaceFactory=(IWorkspaceFactory)Activator.CreateInstance
        (factoryType);
    return workspaceFactory.Open(propertySet, 0);
}
[VB.NET]
' For example, for direct connect with OSA authentication.
' DBConnProp="tivo_sqlexpress".
' Database="sewer".
' Authentication_mode="OSA".
' Version="dbo.DEFAULT".
Public Shared Function WorkgroupArcSdeWorkspaceFromPropertySet(ByVal server As String, ByVal instance As String, _
                                                               ByVal authenticationMode As String, ByVal database As String, ByVal Version As String) As IWorkspace
Dim propertySet As IPropertySet=New PropertySetClass()

propertySet.SetProperty("SERVER", server)

    propertySet.SetProperty("DB_CONNECTION_PROPERTIES", DBConnProp)

        propertySet.SetProperty("DATABASE", database)

            propertySet.SetProperty("AUTHENTICATION_MODE", authenticationMode)

                propertySet.SetProperty("VERSION", Version)
                    
                    Dim factoryType As Type=Type.GetTypeFromProgID("esriDataSourcesGDB.SdeWorkspaceFactory")
                    Dim workspaceFactory As IWorkspaceFactory=CType(Activator.CreateInstance(factoryType), IWorkspaceFactory)
                    Return workspaceFactory.Open(propertySet, 0)
                End Function
The OpenFromFile method can also be used to connect to an enterprise geodatabase on SQL Server Express. The connection files are then used in the OpenFromFile method as shown in the following code example:
[C#]
// For example, connectionFile=@"C:\myData\Connection to tivo.sde".
public static IWorkspace WorkgroupArcSdeWorkspaceFromFile(String connectionFile)
{
    Type factoryType=Type.GetTypeFromProgID(
        "esriDataSourcesGDB.SdeWorkspaceFactory");
    IWorkspaceFactory workspaceFactory=(IWorkspaceFactory)Activator.CreateInstance
        (factoryType);
    return workspaceFactory.OpenFromFile(connectionFile, 0);
}
[VB.NET]
' For example, connectionFile="C:\myData\Connection to tivo.sde".
Public Shared Function WorkgroupArcSdeWorkspaceFromFile(ByVal connectionFile As String) As IWorkspace
Dim factoryType As Type=Type.GetTypeFromProgID("esriDataSourcesGDB.SdeWorkspaceFactory")
Dim workspaceFactory As IWorkspaceFactory=CType(Activator.CreateInstance(factoryType), IWorkspaceFactory)
Return workspaceFactory.OpenFromFile(connectionFile, 0)
End Function
Using the OpenFromString method to open an enterprise geodatabase on SQL Server Express only differs from opening an enterprise geodatabase because of the string that is passed in. Ensure that OSA is set and that direct connect is used for the instance property value pair. See the following code example:
[C#]
// For example, connectionString="SERVER=tivo_sqlexpress;DATABASE=sewer;INSTANCE=sde:sqlserver:tivo\\sqlexpress;AUTHENTICATION_MODE=OSA;VERSION=dbo.DEFAULT".
public IWorkspace WorkgroupArcSdeWorkspaceFromString(String connectionString)
{
    Type factoryType=Type.GetTypeFromProgID(
        "esriDataSourcesGDB.SdeWorkspaceFactory");
    IWorkspaceFactory2 workspaceFactory2=(IWorkspaceFactory2)
        Activator.CreateInstance(factoryType);
    return workspaceFactory2.OpenFromString(connectionString, 0);
}
[VB.NET]
' For example, connectionString="DB_CONNECTION_PROPERTIES=tivo_sqlexpress;DATABASE=sewer;AUTHENTICATION_MODE=OSA;VERSION=dbo.DEFAULT".

Public Function WorkgroupArcSdeWorkspaceFromString(ByVal connectionString As String) As IWorkspace
    Dim factoryType As Type=Type.GetTypeFromProgID("esriDataSourcesGDB.SdeWorkspaceFactory")
    Dim workspaceFactory2 As IWorkspaceFactory2=CType(Activator.CreateInstance(factoryType), IWorkspaceFactory2)
    Return workspaceFactory2.OpenFromString(connectionString, 0)
End Function

Using the DataServerManager

The DataServerManager class is used to access and administer one or more enterprise geodatabases stored on a data server. A connection can be opened to each geodatabase in a data server through name objects returned by the CreateWorkspaceName method. Unlike an enterprise geodatabase, opening a connection to an enterprise geodatabase on SQL Server Express does not require a set of properties. Instead, the geodatabase name, version type, and version specifier are used.
The following are the three version types that can be used to connect to the geodatabase:
  • VERSION—Transactional version to connect to. The acceptable value is a string that represents a transaction version name.
  • HISTORICAL_NAME—Historical version to connect to. The acceptable value is a string that represents a historical marker name.
  • HISTORICAL_TIMESTAMP—Moment in history to establish a historical version connection. The acceptable value is a date object containing a date time that represents a moment time stamp.
The specified version must correspond to the version type (for example, if VERSION is specified, the version name must be listed as the version specified). Also, since  the workspace connection can only represent one version, use only one of the three version properties (that is, VERSION, HISTORICAL_NAME, or HISTORICAL_TIMESTAMP).
The following code example shows how to connect to a transactional version of a enterprise geodatabase on SQL Server Express using the DataServerManager:
[C#]
// For example, serverName="tivo\\sqlexpress".
// gdbName="sewer".
// versionPropName="VERSION".
// versionName="dbo.DEFAULT".
public static IWorkspace WorkgroupArcSdeWorkspaceFromDSM(String serverName, String
    gdbName, String versionPropName, String versionName)
{
    // Create a Data Server Manager object.
    IDataServerManager dataServerManager=new DataServerManagerClass();

    // Set the server name and connect to the server.
    dataServerManager.ServerName=serverName;
    dataServerManager.Connect();

    // Open one of the geodatabases in the database server.
    IDataServerManagerAdmin dataServerManagerAdmin=(IDataServerManagerAdmin)
        dataServerManager;
    IWorkspaceName workspaceName=dataServerManagerAdmin.CreateWorkspaceName
        (gdbName, versionPropName, versionName);

    // Cast from the workspace name to utilize the Open method.
    IName name=(IName)workspaceName;
    IWorkspace workspace=(IWorkspace)name.Open();
    return workspace;
}
[VB.NET]
' For example, serverName="tivo\sqlexpress".
' gdbName="sewer".
' versionPropName="VERSION".
' versionName="dbo.DEFAULT".
Public Shared Function WorkgroupArcSdeWorkspaceFromDSM(ByVal serverName As String, ByVal gdbName As String, _
                                                       ByVal versionPropName As String, ByVal versionName As String) As IWorkspace
' Create a Data Server Manager object.
Dim dataServerManager As IDataServerManager=New DataServerManagerClass()

' Set the server name and connect to the server.
dataServerManager.ServerName=serverName
dataServerManager.Connect()

' Open one of the geodatabases in the database server.
Dim dataServerManagerAdmin As IDataServerManagerAdmin=CType(dataServerManager, IDataServerManagerAdmin)
Dim workspaceName As IWorkspaceName=dataServerManagerAdmin.CreateWorkspaceName(gdbName, versionPropName, versionName)

' Cast from the workspace name to utilize the Open method.
Dim Name As IName=CType(workspaceName, IName)
Dim workspace As IWorkspace=CType(Name.Open(), IWorkspace)
Return workspace
End Function

Connecting to databases

ArcGIS can work with both enterprise geodatabases and data stored in a database without the enterprise geodatabase schema. The SdeWorkspaceFactory should be used to connect to both databases and geodatabases.
The properties can include the following connection properties of the database being connected to:
  • DATABASE—The database being connected to if the specific DBMS supports databases.
  • USER—The connected user.
  • PASSWORD—The connected user's password.
  • DBCLIENT—The type of database client that is installed on the machine making the connection to the database. For example, if connecting to an Oracle database, the string "oracle" should be used for this parameter.
  • DB_CONNECTION_PROPERTIES The aspect of the connection that uniquely identifies the database server. For Oracle connections, this can be either a string identifying an entry in the TNSNames.ora file or an Oracle Easy Connect string. For databases that support ODBC connections, this can be an ODBC string or an identifier that will help the connecting machine look up the data source name if configured. IPv6-style identifiers are also supported by this parameter if the database server is configured to use this protocol for identification.
  • AUTHENTICATION_MODE—The credential authentication mode of the connection. Acceptable values are the OSA and DBMS. The default is DBMS. If the AUTHENTICATION_MODE is OSA, the USER and PASSWORD properties are not required. OSA uses the operating system credentials to establish a connection with the database.

Dealing with partial connection parameters

If connection parameters, such as version, username, and password, are missing from the propertyset when open is called, the caller will be prompted to enter the missing connection parameters. This might not be desirable behavior for all applications. Because of this, it is possible to provide the missing connection parameters programmatically using the members of the ISetDefaultConnectionInfo interface.
The following code example shows how to use this API to suppress the Connection dialog box in the event of missing connection parameters:
[C#]
Type sdeWorkspaceFactoryType=Type.GetTypeFromProgID(
    "esriDataSourcesGDB.SdeWorkspaceFactory");
IWorkspaceFactory2 sdeWorkspaceFactory=(IWorkspaceFactory2)
    Activator.CreateInstance(sdeWorkspaceFactoryType);
ISetDefaultConnectionInfo3 setDefaultConnectionInfo3=(ISetDefaultConnectionInfo3)
    sdeWorkspaceFactory;

string user="dave";
string database="testruns";
string password="dave";
string versionName="sde.DEFAULT";
string authenticationMode="DBMS";

setDefaultConnectionInfo3.SetParameters(server, instance, user, password,
    versionName);
setDefaultConnectionInfo3.SetParameters3(server, instance, authenticationMode, user,
    password, versionName, null);

//Set the Server and Instance properties. For non-Oracle DBMSs, include the DATABASE property
//to allow the connection. For DB2 and Informix, this is the DataSource name of the locally
//cataloged database; for SQL Server and PostgreSQL, it is the name of the database.
IPropertySet connProps=new PropertySet();
connProps.SetProperty("SERVER", server);
connProps.SetProperty("INSTANCE", instance);
connProps.SetProperty("DATABASE", database);

IWorkspace sdeWorkspace=sdeWorkspaceFactory.Open(connProps, 0);

setDefaultConnectionInfo3.ClearParameters(server, instance);
setDefaultConnectionInfo3.ClearParameters3(server, instance, authenticationMode);

try
{
    //This connection fails, the connection parameters have been cleared from the cache, 
    //there will be no user/password information. This will fail, you catch the exception, 
    //and output a message to the user.
    sdeWorkspace=sdeWorkspaceFactory.Open(connProps, 0);
}

catch (Exception exc)
{
    COMException ce=exc as COMException;
    if (ce != null)
    {
        Console.WriteLine(String.Format("{0} : {1} : {2}", ce.Message, ce.ErrorCode,
            ((fdoError)ce.ErrorCode).ToString()));
    }
    else
    {
        Console.WriteLine(String.Format("{0}", exc.Message));
    }
}
[VB.NET]
Dim sdeWorkspaceFactoryType As System.Type
Dim sdeWorkspaceFactory As ESRI.ArcGIS.Geodatabase.IWorkspaceFactory2
Dim setDefaultConnectionInfo3 As ESRI.ArcGIS.Geodatabase.ISetDefaultConnectionInfo3

Dim server As String
Dim instance As String
Dim database As String
Dim user As String
Dim password As String
Dim versionName As String
Dim authenticationMode As String

Dim connProps As ESRI.ArcGIS.esriSystem.PropertySet

Dim sdeWorkspace As ESRI.ArcGIS.Geodatabase.IWorkspace

sdeWorkspaceFactoryType=Type.GetTypeFromProgID("esriDataSourcesGDB.SdeWorkspaceFactory")
sdeWorkspaceFactory=Activator.CreateInstance(sdeWorkspaceFactoryType)
setDefaultConnectionInfo3=sdeWorkspaceFactory

server="bort"
instance="sde:postgresql:bort"
user="dave"
database="testruns"
password="dave"
versionName="sde.DEFAULT"
authenticationMode="DBMS"

'setDefaultConnectionInfo3.SetParameters(server, instance, user, password, versionName);
setDefaultConnectionInfo3.SetParameters3(server, instance, authenticationMode, user, password, versionName, Nothing)

'Set the Server and Instance properties. For non-Oracle DBMSs, include the DATABASE property
'to allow the connection. For DB2 and Informix, this is the DataSource name of the locally
'cataloged database; for SQL Server and PostgreSQL, it is the name of the database.
connProps=New ESRI.ArcGIS.esriSystem.PropertySet()
connProps.SetProperty("SERVER", server)
connProps.SetProperty("INSTANCE", instance)
connProps.SetProperty("DATABASE", database)

sdeWorkspace=sdeWorkspaceFactory.Open(connProps, 0)
System.Runtime.InteropServices.Marshal.ReleaseComObject(sdeWorkspace)

'setDefaultConnectionInfo3.ClearParameters(server, instance);
setDefaultConnectionInfo3.ClearParameters3(server, instance, authenticationMode)

Try
'This connection fails, the connection parameters have been cleared from the cache,
'there will be no user/password information. This will fail, you catch the exception,
'and output a message to the user.
sdeWorkspace=sdeWorkspaceFactory.Open(connProps, 0)

Catch exc As System.Exception
Dim ce As System.Runtime.InteropServices.COMException
ce=exc
If (ce.ErrorCode <> Nothing) Then
    
    Console.WriteLine(String.Format("{0} : {1}", ce.Message, ce.ErrorCode))
Else
    
    Console.WriteLine(String.Format("{0}", exc.Message))
End If
End Try






To use the code in this topic, reference the following assemblies in your Visual Studio project. In the code files, you will need using (C#) or Imports (VB .NET) directives for the corresponding namespaces (given in parenthesis below if different from the assembly name):

Development licensing Deployment licensing
ArcGIS Desktop Basic ArcGIS Desktop Basic
ArcGIS Desktop Standard ArcGIS Desktop Standard
ArcGIS Desktop Advanced ArcGIS Desktop Advanced
Engine Developer Kit Engine