Steve said:
Hello all,
I need to find all the distribution lists/groups a user is a member of
using
Active Directory when they request an INTRANET webpage. Impersonation is
DISABLED on this site.
I have a ASP.NET webpage written in VB.NET where when a user loads the
page
it get's their network user name by processing:
Request.ServerVariables("LOGON_USER") and now I need to find out what
email
distribution lists they are a member of.
Can anyone give me a code snippet that accepts a username and returns a
string with the Distribution Groups/Lists they are a member of? I am
using
Visual Studio 2003.
Does this help:
public ArrayList GetGroupsForUser(string domain, string uid, string pwd)
{
SearchResult sr = GetUserSearchResult(domain, uid, pwd);
ArrayList al = new ArrayList();
if (sr == null)
{
return null;
}
DirectorySearcher search = new DirectorySearcher(sr.Path);
search.Filter = "(cn=" + sr.Properties["cn"][0] + ")";
search.PropertiesToLoad.Add("memberOf");
try
{
sr = search.FindOne();
int propertyCount = sr.Properties["memberOf"].Count;
if (propertyCount == 0)
{
return null;
}
string dn;
int equalsNdx;
int commandX;
for (int i = 0; i < propertyCount; i++)
{
dn = sr.Properties["memberOf"]
.ToString();
equalsNdx = dn.IndexOf("=", 1);
commandX = dn.IndexOf(",", 1);
if (equalsNdx == -1)
{
return null;
}
al.Add(dn.Substring((equalsNdx + 1), (commandX - equalsNdx) -
1));
}
}
catch (Exception ex)
{
//-- Create the EventLog if it does not already exist.
if (!EventLog.SourceExists("ActiveDirectoryRemoteObject"))
{
EventLog.CreateEventSource("ActiveDirectoryRemoteObject",
"ActiveDirectoryRemoteObjectLog");
}
//-- Create an EventLog instance and assign its source.
EventLog myLog = new EventLog();
myLog.Source = "ActiveDirectoryRemoteObject";
//-- Write the custom error message to the event log.
myLog.WriteEntry("GetGroupsForUser : " + ex.Message);
return null;
}
return al;
} //-- End of GetGroupForUser()
public SearchResult GetUserSearchResult(string domain, string uid, string
pwd)
{
string domainAndUserName = domain + "\\" + uid;
DirectoryEntry entry = new DirectoryEntry(LdapHomePath,
domainAndUserName, pwd);
try
{
DirectorySearcher search = new DirectorySearcher(entry);
search.Filter = "(sAMAccountName=" + uid + ")";
search.PropertiesToLoad.Add("cn");
return search.FindOne();
}
catch (Exception ex)
{
//-- Create the EventLog if it does not already exist.
if (!EventLog.SourceExists("ActiveDirectoryRemoteObject"))
{
EventLog.CreateEventSource("ActiveDirectoryRemoteObject",
"ActiveDirectoryRemoteObjectLog");
}
//-- Create an EventLog instance and assign its source.
EventLog myLog = new EventLog();
myLog.Source = "ActiveDirectoryRemoteObject";
//-- Write the custom error message to the event log.
myLog.WriteEntry("GetUserSearchResult - " + LdapHomePath + " " +
defaultDomain + " " + uid + " : " + ex.Message);
return null;
}
} //-- End GetUserSearchResult() method.
Best of luck
Peter