Monthly Archives: January 2005

Get SharePoints Database names and connection strings.

C Sharp source code for grabbing database details in sharepoint

Using Sharepoint’s internal mechanisms, it is possible to retrieve the database name and connection string for the content databases that power a site. The code in the attached file uses the following methodology.

1) create a new topology object.
2) loop through objTopology.Databases
3) test whether the returned DB is a profile, Site or Server database
4) allow access to string[] objects that contain the database name and connection string for each type of database.

Simple*.

* It is a little bit hacky, though. I can’t find any methods that tell me database-X functions as the profiles database, or that database-Y is the Sites database. To do this, I have had to resort to running queries against the database in question to determine whether a distinctive table exists. Not ideal, but until I find a better way, it will have to do.

**UPDATE**

The original version will fail if you try to get database details on a host with multiple portals. To get around this, you need to instantiate the object by passing in the site id.

for example:

// find the base url for this portal site.
string PortalUrl = Page.Request.Url.ToString().Replace(Page.Request.RawUrl.ToString(),”/”);
// Create a SPSite object
SPSite mySite = new SPSite(PortalUrl);
// Create a sharepointInfo object to get the databases back from
InTechnology.InTranet.SharepointInfo.Information myInfo = new InTechnology.InTranet.SharepointInfo.Information(mySite.ID.ToString());
profileConnectionString = myInfo.profilesDatabase()[1];

Again, I’m sure there is an easier way to get the site ID, but I don’t know it.

Conditional methods

To create methods that will only be called in a debug build of your application, you can use the following syntax :

[Conditional( “DEBUG” )]
private void SetDebugVariables()
{
connect
ionString = “datasource=developmentDB;SSPI=true;initial catalog=development”;
Trace.WriteLine(“Called in debug build”);
}

One use is to override release build settings to allow you to reference a local data store instead of the production data.

private function setVariables(){ connectionString = "datasource=productionDB;SSPI=true;initial catalog=production"; SetDebugVariables(); } [Conditional( "DEBUG" )] private void SetDebugVariables() { connectionString = "datasource=developmentDB;SSPI=true;initial catalog=development"; Trace.WriteLine("Called in debug build"); }

In a debug build, the method SetDebugVariables() is called, and will therefore override the default (reslease) settings. In a release build, the call to SetDebugVariables() is never made. This is because the compiler recognises the Conditional nature of the method, and simply ignores calls to it in a release build.