Friday, September 16, 2011

Getting all objects from AD

// for getting  ou contents//
public class RecursiveTraversal
{ public string obj;
public void traverse(DirectoryEntry entry,int x)
{ // Check  it is a n ou
if( entry.SchemaClassName=="organizationalUnit" )
{
x++;
obj = obj + " <Node Object_name=\"" + entry.Name.ToString().Substring(3).Replace("&", "&")+"\"" ;
obj = obj + " Object_type=\"" + entry.Name.ToString().Substring(0, 2) + "\"";
obj = obj + " Object_path=\"" + entry.Path.ToString().Replace("&", "&") + "\"";
obj = obj + " Object_level=\"" + Convert.ToString(x).Replace("&", "&") + "\"";
obj = obj + " ";
DirectoryEntry nw =new DirectoryEntry(entry.Path.ToString());
IEnumerator ie = entry.Children.GetEnumerator();
// Ensure that the list is not null
if (ie.MoveNext())
{ obj = obj + ">";
foreach (DirectoryEntry di in nw.Children)
{ traverse(di, x); }
obj = obj + " </Node>";
}
else
{
obj = obj + ">";
obj = obj + " </Node>";
}
}
}
}
//for getting the AD object list .. this is using the RecursiveTraversal class //
[WebMethod]
public XmlDocument get_Activedirectory_object_list(string type)
{
RecursiveTraversal rt = new RecursiveTraversal();
xmlhelp = new Xml_Helper();
if (type == "1")
{
try
{
DirectoryEntry entryRoot = new DirectoryEntry("LDAP://RootDSE");
string dmain = entryRoot.Properties["defaultNamingContext"][0].ToString();
string entry = "<Data StatusText=\"Success\" Count=\"1\" TotalCount=\"1\" ><Row><Object_name>Domain</Object_name> <Object_type>DC</Object_type> <Object_path>LDAP://" + dmain + "</Object_path> <Object_level>0</Object_level></Row></Data> ";
doc.InnerXml = entry;
}
catch (Exception exp)
{
doc = xmlhelp.Get_XML_Document(eh.Call_Exception(exp));
return doc;
}
}
else
{
try
{
DirectoryEntry entryRoot = new DirectoryEntry("LDAP://RootDSE");
string dmain = entryRoot.Properties["defaultNamingContext"][0].ToString();
DirectoryEntry entry = new DirectoryEntry("LDAP://" + dmain);
foreach (DirectoryEntry cd in entry.Children)
{
rt.traverse(cd, 0);
}
DataSet ds1 = new DataSet();
ds1.Tables.Add("ADUsers");
ds1.Tables["ADUsers"].Columns.Add("Components");
DataRow row = ds1.Tables["ADUsers"].NewRow();
ds1.Tables[0].Rows.Add(row);
ds1.Tables[0].Rows[0]["Components"] = rt.obj;
doc = xmlhelp.Get_XML_Document(ds1);
}
catch (Exception ex)
{
doc = xmlhelp.Get_XML_Document(eh.Call_Exception(ex));
return doc;
}
}
return doc;
}

No comments:

Post a Comment