I am trying to get user from active directory in my webpart but i am sruck somewhere please help me my code is as below.
using System; using System.Runtime.InteropServices; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Xml.Serialization; using System.DirectoryServices; using Microsoft.SharePoint; using Microsoft.SharePoint.WebControls; using Microsoft.SharePoint.WebPartPages; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.Collections;
namespace LdapTest2008 { [Guid("028042d8-7f77-4674-8b19-61b282e5ddf8")] public class LdapTest2008 : System.Web.UI.WebControls.WebParts.WebPart { public LdapTest2008() { }
Label lblUsers = new Label();
protected override void CreateChildControls()
{
base.CreateChildControls();
// TODO: add custom rendering code here.
// Label label = new Label();
// label.Text = "Hello World";
// this.Controls.Add(label);
}
public override void RenderControl(HtmlTextWriter writer)
{
base.RenderControl(writer);
StringCollection StrCollectionReturn = new StringCollection();
string strGroup = "My Group";
StrCollectionReturn= GetGroupMembers(strGroup);
lblUsers.Text = StrCollectionReturn.ToString();
this.Controls.Add(lblUsers);
writer.Write(lblUsers.Text);
}
//Query Active Directory to get users from Active Directory Groups
public StringCollection GetGroupMembers(string strGroup)
{
string domain = "LDAP://Domain.COM";
string domainAndUsername = "Domain.COM\\username";
string passWord = "password";
StringCollection groupMemebers = new StringCollection();
try
{
DirectoryEntry ent = new DirectoryEntry(domain,domainAndUsername,passWord);
DirectorySearcher srch = new DirectorySearcher("(CN=" + strGroup + ")");
srch.SizeLimit = 0;
srch.PageSize = 1000;
SearchResultCollection coll = srch.FindAll();
foreach (SearchResult rs in coll)
{
ResultPropertyCollection resultPropColl = default(ResultPropertyCollection);
resultPropColl = rs.Properties;
foreach (Object memberColl in resultPropColl["member"])
{
DirectoryEntry gpMemberEntry = new DirectoryEntry("LDAP://"+ memberColl);
System.DirectoryServices.PropertyCollection userProps = gpMemberEntry.Properties;
//getting user properties from AD
object obVal = userProps["displayName"].Value;
object obAcc = userProps["sAMAccountName"].Value;
if (null != obVal)
{
groupMemebers.Add("User Name:" + obAcc.ToString() + ", User login name:" + obVal.ToString() + "<br>");
}
}
}
}
catch (Exception ex)
{
ex.GetBaseException();
// writer.Write(ex.Message);
}
return groupMemebers;
}
}
}
When debug this code i stuck here DirectorySearcher srch = new DirectorySearcher("(CN=" + strGroup + ")"); it give me error found null value.
What i am doing wrong please help on this.
Thank you.