1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
|
using System;
using System.Collections.Generic;
using System.Text;
using System.DirectoryServices;
using System.Configuration;
namespace ActiveDirectory
{
public class ADActions
{
public static bool ExistEntry(UserDetails ud)
{
try
{
//create an instance of the DirectoryEntry
DirectoryEntry deEntry = new DirectoryEntry("LDAP://DC=rnd,DC=as", "Administrator", "Azerty123");
//GetDirectoryObject();
//create instance fo the direcory searcher
DirectorySearcher deSearch = new DirectorySearcher();
deSearch.SearchRoot = deEntry;
//set the search filter
deSearch.Filter = "(&(objectClass=user)(cn=" +
ud.GIVEN_NAME + " " +
ud.INITIALS + ". " +
ud.SN + "))";
deSearch.SearchScope = SearchScope.Subtree;
//find the first instance
SearchResult results = deSearch.FindOne();
if (results != null)
{
return true;
}
return false;
}
catch (Exception e)
{
throw new Exception("Error in existence:\r\n", e);
}
}//ExistEntry
public static void AddUserToActiveDirectory(UserDetails ud)
{
if (!ExistEntry(ud))
{
DirectoryEntry deEntry = new DirectoryEntry("LDAP://OU=" + ud.OU + ",DC=rnd,DC=as", "Administrator", "Azerty123");
DirectoryEntry newUser = deEntry.Children.Add("CN=" +
ud.GIVEN_NAME + " " +
ud.INITIALS + ". " +
ud.SN, "user");
try
{
newUser.Properties["sAMAccountName"].Add(ud.SAM_ACCOUNT_NAME);
newUser.Properties["sn"].Add(ud.SN);
newUser.Properties["givenName"].Add(ud.GIVEN_NAME);
// CommitChanges() permet de valider les données auprès du serveur.
newUser.CommitChanges();
}
catch (DirectoryServicesCOMException dcex)
{
throw new DirectoryServicesCOMException("Error while adding a new user", dcex);
}
catch (Exception ex)
{
throw new Exception("Error while adding a new user", ex);
}
try
{
//La deuxième phase consiste à affecter à lutilisateur un Mot de Passe et activer son compte.
newUser.Invoke("SetPassword", new object[] { ud.PASSWORD });
newUser.Properties["userAccountControl"].Value = 0x0200;
newUser.CommitChanges();
newUser.Close();
}
catch (DirectoryServicesCOMException dcex)
{
throw new DirectoryServicesCOMException("Error while adding a new user's password and activation", dcex);
}//catch
catch (Exception ex)
{
throw new Exception("Error while adding a new user's password and activation", ex);
}//catch
}//if
}//AddUserToActiveDirectory
}//class ADActions
}//namespace |
Partager