HOWTO: [ADSI] Pinvoke the Wizard for a new Active Directory object0 Reacties

Wouldn't it be fun to create new active directory objects, while you even don't startup the MMC for active directory? No, don't be afraid that everybody including ‘nobody’ on your network -now- can do this

If the code below does not run on a domain controller, you first should install the adminpak.msi (or register dsadmin.dll and dsa.mcs) for on Windows 2003 that also can be installed on Windows XP.

And of course, Active Directory is -really- secure. If the calling code is not executed by someone with sufficient rights, it will fail.

So here we go and make yourself really -see- active directory!

(ps: I like writing unique code, as far as I can see, nobody did it yet, hey, don't forget to visit www.adccure.nl !)

static void Main()

{

IDsAdminCreateObject co = new DsAdminCreateObject() as IDsAdminCreateObject;
object nativedsObject = new DirectoryEntry("LDAP://cn=users,dc=yourdomain,dc=local").NativeObject;
co.Initialize(nativedsObject, null, "user");
object newObject = co.CreateModal(DsAdminCreateObject.GetDeskTopWindow());

}

[ComImport, Guid("53554A38-F902-11d2-82B9-00C04F68928B"),

InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]

public interface IDsAdminCreateObject

{

///


/// Need to initialize before popping up the new object wizard
///

/// initialized dir object Container object eg: cn=users,DC=domain,dc=local
///
can be null, specifies original object if you want a copy!

/// contains "User", "group", "contact", "inetOrgPerson" etc
void Initialize( [MarshalAs(UnmanagedType.IDispatch)] object ADsContainerObj,
[MarshalAs(UnmanagedType.IDispatch), Optional(), DefaultParameterValue(null)] object ADsCopySource,
[MarshalAs(UnmanagedType.LPWStr)] string ClassName);

///


/// Returns native ActiveDirectory object
///

/// handle to parent window, specify 0 (mostly)
[return: MarshalAs(UnmanagedType.IDispatch)]
object CreateModal(IntPtr hwndParent);

}

 

///

/// Have our CLSID_DsAdminCreateObject be imported by .NET
///


[ComImport, Guid("E301A009-F901-11d2-82B9-00C04F68928B")]
public class DsAdminCreateObject

{

/// we just needed a pointer to a window, if you run this code within a Windows Form, you can fetch a handle to it and hand it over to CreateModal!
[DllImport("user32", EntryPoint = "GetDesktopWindow", ExactSpelling = true, SetLastError = false)]
public static extern IntPtr GetDeskTopWindow();
}