porting gadfly to c

Wed, Aug 19, 2009

Initially I didn’t think I had time to delve into C# when writing the ActiveDirectory stuff to manage users programatically, so I stuck with C++/COM as I knew how to work that way, at least once I’d scraped the rust off those parts of my COM brain. Anyway, after the hassle of dealing with XML and JMS topics from C++ I decided to look into it a bit more and after literally half a day of research/coding and while dealing with other major issues at the same time (who says we don’t multitask?!), I ported GADfly to C#. I must say, I am astounded, completely and utterly. Basically, C++/COM has more or less been “updated” with C#/.NET but you can still get to the underlying COM functionality but not in the messy way VB used to let you. C# has native support for ADSI as well as incredibly simple remote IO support. So how do you create a user, their home directory and give them ownership/full rights in ActiveDirectory using C#? Have a gander at this. No VARIANT, allocing, releasing or anything grubby like that. Behold! But remember to run it inside the domain to allow the admin user access to the remote filesystem.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.DirectoryServices;
using System.Runtime.InteropServices;
using System.Management;
using System.IO;
using System.Security.AccessControl;
using System.Security.Principal;

namespace gadfly_cs { class gadfly { static void Main(string[] args) { try { DirectoryEntry admin = new DirectoryEntry(); admin.Path = “LDAP://domain/ou=testou,dc=testdc,dc=local”; admin.Username = “domain\adminuser”; admin.Password = “adminpasswd”;

    DirectoryEntry newUser = admin.Children.Add("cn=testuser", "user");
    newUser.Properties["samAccountName"].Value = "testuser";
    newUser.Properties["userPrincipalName"].Value = "testuser";
    newUser.Properties["givenName"].Value = "Test";
    newUser.Properties["sn"].Value = "User";
    newUser.Properties["mail"].Value = "test@test.com";
    newUser.Properties["displayName"].Value = "Test User    ";
    newUser.Properties["homeDirectory"].Value = "\\\\domain\\Share\\testuserdir";
    newUser.Properties["homeDrive"].Value = "Z:";
    newUser.Invoke("SetPassword", new object[] {"testuserpasswd"});
    newUser.Properties["userAccountControl"].Value = 0x200;

    string folderName = "\\\\domain\\Share\\testuserdir";
    DirectoryInfo dInfo = new DirectoryInfo("\\\\domain\\Share\\testuserdir");
    DirectorySecurity dSecurity = dInfo.GetAccessControl();
    dSecurity.AddAccessRule(new FileSystemAccessRule("domain\\testuser", FileSystemRights.FullControl, AccessControlType.Allow));
    NTAccount adUser = new System.Security.Principal.NTAccount("domain\\testuser");
  catch(COMException ce) {

} }


comments powered by Disqus