Thursday, October 23, 2014

SharePoint 2013 User Profile Synchronization connection- Get account name from code

When SharePoint User Profile service application connects to Active Directory to synchronize user profiles, it uses user account provided in Connection Setting page in Central Administration, Manage Profile Service page. This account requires special permissions: http://technet.microsoft.com/en-us/library/hh296982.aspx


The next code shows how to get  this account name from your code:


SPServiceContext serviceContext = SPServiceContext.GetContext(currentWeb.Site);
UserProfileConfigManager config = new UserProfileConfigManager(serviceContext);
DirectoryServiceConnection conn = config.ConnectionManager.OfType<DirectoryServiceConnection>().FirstOrDefault(x => x.DisplayName == "Connection Name");

if (conn!=null)
{
    string accountName = conn.AccountUsername;
}