SharePoint 2010 - Webpart - Get SQL Server + Instance Name
-
Tuesday, May 01, 2012 4:35 PM
We are creating and using some custom databases for our solution. The location of these databases is going to be the same as SharePoint 2010 Config Database. We are required to create the connection strings programmatically without using web.config entries. (Integrated security is being used for SQL Connection strings.)
Can you please tell me how I can get the SQL Server Instance Name programatically. Tried the following code, but I'm only getting the server name and not the instance name.
SPSite site = SPContext.Current.Site; SPProcessIdentity pi = site.WebApplication.Farm.TimerService.ProcessIdentity; string userName = pi.Username; object configDB = pi.GetType().GetProperty("ConfigurationDatabase", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(pi, null); SPServer server = (SPServer)configDB.GetType().GetProperty("Server").GetValue(configDB, null); string serverName = server.Name;Thanks in advance for the help,
prashant
All Replies
-
Tuesday, May 01, 2012 5:55 PMHave you tried SPContext.Current.Site.ContentDatabase.NormalizedDataSource ? This appears to return the server instance name.
Blog | SharePoint Field Notes Dev Tool | ClassMaster
-
Tuesday, May 01, 2012 6:06 PM
Thanks Steve. I'll try that.
Also, what if the Content Databases and Config Database are on different SQL Servers?
-
Tuesday, May 01, 2012 6:55 PM
I guess it is possible the two could be different. You can use the following code to get the instance name from the DefaultDatabaseInstance.Name property of the Administration service. This is the default instance where all new content databases will be created for the this service. It is very unlikely this would ever be different than the instance for the configuration database. You need to be a farm admin to access this code.
public static string GetConfigInstanceName() { SPWebService admService = SPWebService.AdministrationService; return admService.DefaultDatabaseInstance.Name; }Blog | SharePoint Field Notes Dev Tool | ClassMaster
- Marked As Answer by prashantFR Thursday, May 03, 2012 4:12 PM
-
Thursday, May 03, 2012 4:12 PMThanks so much, Steve. It worked.

