Code to pull a user's manager into a workflow in SharePoint:
public void SetManagerFields(object sender, EventArgs e)
{
try
{
SearchSuccessful = false;
//Set up the AD objects
DirectoryEntry dirEntry = new DirectoryEntry("GC:");
if (null == dirEntry)
{
Outcome = "Could not connect to Directory";
return;
}
System.Collections.IEnumerator gcChildrenEnum = dirEntry.Children.GetEnumerator();
gcChildrenEnum.MoveNext();
//Search for Manager of AccountName
DirectorySearcher searcher = new DirectorySearcher((DirectoryEntry)gcChildrenEnum.Current);
string filterString = "(samAccountName= " + AccountName.Substring(AccountName.IndexOf("\\") + 1) + ")";
searcher.Filter = filterString;
SearchResult result = searcher.FindOne();
if (result == null)
{
Outcome = "Could not find user account.";
return;
}
if (result.Properties.Contains("manager"))
{
//Parse manager display name from search result
ManagerDisplayName = result.Properties["manager"][0].ToString();
int index;
int indexComma = ManagerDisplayName.IndexOf(',');
int indexSlash = ManagerDisplayName.IndexOf('\\');
//If a comma is escaped, grab the second comma to get the full display name
if (indexSlash != -1 && indexComma > indexSlash)
index = ManagerDisplayName.IndexOf(',', indexComma + 1);
else
index = indexComma;
ManagerDisplayName = ManagerDisplayName.Substring(3, index - 3);
//If there's a slash, remove it (.Replace("\\", "") doesn't work)
if (indexSlash != -1)
{
//Find it again cause it moved
indexSlash = ManagerDisplayName.IndexOf('\\');
indexComma = ManagerDisplayName.IndexOf(',');
ManagerDisplayName = ManagerDisplayName.Substring(0, indexSlash) +
ManagerDisplayName.Substring(indexComma);
}
searcher.Filter = "(displayName= " + ManagerDisplayName + ")";
result = searcher.FindOne();
if (result == null)
{
Outcome = "Could not find manager " + ManagerDisplayName + ".";
return;
}
//Propagate data to the promoted properties
if (result.Properties.Contains("samaccountname"))
ManagerAccountName = result.Properties["samaccountname"][0].ToString();
if (result.Properties.Contains("mail"))
ManagerEmailAddress = result.Properties["