本文整理汇总了C#中System.DirectoryServices.AccountManagement.PrincipalContext.Dispose方法的典型用法代码示例。如果您正苦于以下问题:C# PrincipalContext.Dispose方法的具体用法?C# PrincipalContext.Dispose怎么用?C# PrincipalContext.Dispose使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.DirectoryServices.AccountManagement.PrincipalContext
的用法示例。
在下文中一共展示了PrincipalContext.Dispose方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: IsGroupMember
private static bool IsGroupMember(string userName, string Group)
{
#if DEBUG
return true;
//PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "reckner.com", "fmedvedik", "(manos)3k");
//PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "10.0.0.2", "fmedvedik", "(manos)3k");
// PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
// PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "reckner.com");
#else
PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "reckner.com");
var findByIdentity = UserPrincipal.FindByIdentity(ctx, userName);
bool retVal = false;
if (findByIdentity != null)
{
List<string> result;
using (var src = findByIdentity.GetGroups(ctx))
{
result = new List<string>();
src.ToList().ForEach(sr => result.Add(sr.SamAccountName));
}
var l = result.FirstOrDefault(s => s.Equals(Group));
retVal = (l != null);
}
ctx.Dispose();
return retVal;
#endif
}
示例2: Execute
public StringBuilder Execute(Dictionary<string, StringBuilder> values, IWorkspace theWorkspace)
{
string domain = null;
string username = null;
string password = null;
StringBuilder tmp;
values.TryGetValue("Domain", out tmp);
if(tmp != null)
{
domain = tmp.ToString();
}
values.TryGetValue("Username", out tmp);
if(tmp != null)
{
username = tmp.ToString();
}
values.TryGetValue("Password", out tmp);
if(tmp != null)
{
password = tmp.ToString();
}
if(string.IsNullOrEmpty(domain) || string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password))
{
throw new InvalidDataContractException("Domain or Username or Password is missing");
}
var result = new ExecuteMessage { HasError = false };
try
{
if(domain.Equals("."))
{
domain = Environment.UserDomainName;
}
bool isValid;
using(var context = new PrincipalContext(ContextType.Domain, domain))
{
isValid = context.ValidateCredentials(username, password);
context.Dispose();
}
result.SetMessage(isValid ? "<result>Connection successful!</result>" : "<result>Connection failed. Ensure your username and password are valid</result>");
}
catch
{
result.SetMessage("<result>Connection failed. Ensure your username and password are valid</result>");
}
Dev2JsonSerializer serializer = new Dev2JsonSerializer();
return serializer.SerializeToBuilder(result);
}
示例3: DisposeConnection
public static void DisposeConnection(PrincipalContext context)
{
lock (Sync)
{
context.Dispose();
Connections.Remove(context);
}
}
示例4: accManDisconnect
public static void accManDisconnect(PrincipalContext ctx)
{
try
{
ctx.Dispose();
}
catch (Exception)
{
}
}
示例5: aPasswordResetButton_Click
private void aPasswordResetButton_Click(object sender, EventArgs e)
{
string SamAccountName = SD.SamAccountName;
PrincipalContext principalContext = new PrincipalContext(ContextType.Domain, mainClass.selectedDomainController);
UserPrincipal user = UserPrincipal.FindByIdentity(principalContext, IdentityType.SamAccountName, SamAccountName);
userNewPassword = mainClass.RandomPasswordGenerator();
user.SetPassword(userNewPassword);
if (userMustChangePasswordAtNextLogin)
{
user.ExpirePasswordNow();
}
//GetUserDetails();
user.Dispose();
principalContext.Dispose();
sendEmailWithTheNewPassword();
this.Close();
}
示例6: IsGroupMember
private static bool IsGroupMember(string userName, string Group)
{
var ctx = new PrincipalContext(ContextType.Domain, "reckner.com");
var findByIdentity = UserPrincipal.FindByIdentity(ctx, userName);
var retVal = false;
if (findByIdentity != null)
{
List<string> result;
using (var src = findByIdentity.GetGroups(ctx))
{
result = new List<string>();
src.ToList().ForEach(sr => result.Add(sr.SamAccountName));
}
var l = result.FirstOrDefault(s => s.Equals(Group));
retVal = (l != null);
}
ctx.Dispose();
return retVal;
}
示例7: GetRecipientsFromAdGroup
public static MailAddress[] GetRecipientsFromAdGroup(AdGroup group)
{
var list = new List<MailAddress>();
using (WindowsImpersonationContextFacade impersonationContext
= new WindowsImpersonationContextFacade(
nc))
{
string sid = AdUserGroup.GetSidByAdGroup(group);
PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
GroupPrincipal grp = GroupPrincipal.FindByIdentity(ctx, IdentityType.Sid, sid);
if (grp != null)
{
foreach (Principal p in grp.GetMembers(true))
{
string email = new Employee(p.Sid.Value).Email;
if (String.IsNullOrEmpty(email)) continue;
list.Add(new MailAddress(email));
}
grp.Dispose();
}
ctx.Dispose();
return list.ToArray();
}
}
示例8: UpdateUser
/// <summary>
/// Updates a user in Active Directory
/// </summary>
/// <param name="user"></param>
/// <param name="isUsingDisplayNameAsNameAttribute"></param>
public void UpdateUser(UsersObject user, bool isUsingDisplayNameAsNameAttribute)
{
PrincipalContext pc = null;
UserPrincipalExt up = null;
try
{
pc = new PrincipalContext(ContextType.Domain, this.domainController, this.username, this.password);
logger.Debug("Finding user in Active Directory: " + user.UserPrincipalName);
up = UserPrincipalExt.FindByIdentity(pc, IdentityType.UserPrincipalName, user.UserPrincipalName);
if (up == null)
throw new Exception("USER IS UNKNOWN");
else
{
up.GivenName = user.Firstname;
up.DisplayName = user.DisplayName;
up.Enabled = user.IsEnabled;
if (!string.IsNullOrEmpty(user.Middlename))
up.MiddleName = user.Middlename;
else
up.MiddleName = null;
if (!string.IsNullOrEmpty(user.Lastname))
up.LastName = user.Lastname;
else
up.LastName = null;
if (!string.IsNullOrEmpty(user.Department))
up.Department = user.Department;
else
up.Department = null;
if (isUsingDisplayNameAsNameAttribute)
up.Name = user.DisplayName;
// Save changes
up.Save();
}
}
catch (Exception ex)
{
this.logger.Error("Error updating user " + user.UserPrincipalName, ex);
throw;
}
finally
{
if (up != null)
up.Dispose();
if (pc != null)
pc.Dispose();
}
}
示例9: NewUser
/// <summary>
/// Creates a new user
/// </summary>
/// <param name="user"></param>
/// <param name="baseOrganizationalUnit"></param>
/// <param name="isUsingDisplayNameAsNameAttribute"></param>
public UsersObject NewUser(UsersObject user, string companyUsersPath, bool isUsingDisplayNameAsNameAttribute)
{
PrincipalContext pc = null;
UserPrincipalExt up = null;
try
{
pc = new PrincipalContext(ContextType.Domain, this.domainController, companyUsersPath, this.username, this.password);
logger.Debug("Looking to see if user already exists: " + user.UserPrincipalName);
bool doesExist = DoesUserPrincipalNameExist(user.UserPrincipalName);
if (doesExist)
throw new Exception("User already exists");
else
{
// Find an available sAMAccountName
user.sAMAccountName = GetAvailableSamAccountName(user.UserPrincipalName);
// User was not found so lets create the new user
up = new UserPrincipalExt(pc, user.sAMAccountName, user.Password, true);
up.UserPrincipalName = user.UserPrincipalName;
up.DisplayName = user.DisplayName;
up.PasswordNeverExpires = user.PasswordNeverExpires;
if (isUsingDisplayNameAsNameAttribute)
up.Name = user.DisplayName;
else
up.Name = user.UserPrincipalName;
if (!string.IsNullOrEmpty(user.Firstname))
up.GivenName = user.Firstname;
if (!string.IsNullOrEmpty(user.Middlename))
up.MiddleName = user.Middlename;
if (!string.IsNullOrEmpty(user.Lastname))
up.LastName = user.Lastname;
if (!string.IsNullOrEmpty(up.Department))
up.Department = user.Department;
up.Save();
// Get the user's GUID
user.UserGuid = (Guid)up.Guid;
// Get the user's distinguished name
user.DistinguishedName = up.DistinguishedName;
// Return the user with the information
return user;
}
}
catch (Exception ex)
{
this.logger.Error("Error creating new user " + user.UserPrincipalName, ex);
throw;
}
finally
{
if (up != null)
up.Dispose();
if (pc != null)
pc.Dispose();
}
}
示例10: Create
/// <summary>
/// Creates a new security group
/// </summary>
/// <param name="oupath"></param>
/// <param name="groupname"></param>
/// <param name="description"></param>
/// <param name="isSecurityGroup"></param>
/// <param name="isUniversal"></param>
public void Create(string oupath, string groupname, string description, bool isSecurityGroup, bool isUniversal)
{
PrincipalContext pc = null;
GroupPrincipal gp = null;
try
{
// Remove all whitespaces
groupname = groupname.Replace(" ", string.Empty);
this.logger.Debug("Attempting to create new group named " + groupname + " on path " + oupath);
pc = new PrincipalContext(ContextType.Domain, this.domainController, oupath, this.username, this.password);
gp = GroupPrincipal.FindByIdentity(pc, IdentityType.Name, groupname);
if (gp == null)
{
this.logger.Debug("Group " + groupname + " does not exist... so we can continue...");
gp = new GroupPrincipal(pc, groupname);
gp.IsSecurityGroup = isSecurityGroup;
gp.GroupScope = isUniversal ? GroupScope.Universal : GroupScope.Global;
gp.Save();
this.logger.Info("Successfully created new group " + groupname);
}
else
throw new Exception("Group " + groupname + " already exists. Please delete this group before continuing.");
}
catch (Exception ex)
{
this.logger.Error("Error creating new group " + groupname, ex);
throw;
}
finally
{
if (gp != null)
gp.Dispose();
if (pc != null)
pc.Dispose();
}
}
示例11: Create
public SecurityGroup Create(string parentOU, SecurityGroup group)
{
PrincipalContext ctx = null;
GroupPrincipal grp = null;
try
{
log.DebugFormat("Creating a new group {0}", group.Name);
if (string.IsNullOrEmpty(parentOU))
throw new MissingFieldException("Create", "parentOU");
if (string.IsNullOrEmpty(group.Name))
throw new MissingFieldException("SecurityGroup", "Name");
if (string.IsNullOrEmpty(group.SamAccountName))
throw new MissingFieldException("SecurityGroup", "SamAccountName");
if (group.SamAccountName.Length > 19)
throw new ArgumentOutOfRangeException(group.SamAccountName);
ctx = new PrincipalContext(ContextType.Domain, _domainController, parentOU, _username, _password);
grp = new GroupPrincipal(ctx, group.SamAccountName);
grp.Name = group.Name;
grp.IsSecurityGroup = true;
if (!string.IsNullOrEmpty(group.Description))
grp.Description = group.Description;
if (!string.IsNullOrEmpty(group.DisplayName))
grp.DisplayName = group.DisplayName;
grp.Save();
log.DebugFormat("Successfully created new group {0}", group.Name);
// Update the values
group.DistinguishedName = grp.DistinguishedName;
group.ObjectGUID = (Guid)grp.Guid;
return group;
}
catch (Exception ex)
{
log.ErrorFormat("Error creating new group {0}. Exception: {1}", group.Name, ex.ToString());
throw;
}
finally
{
if (grp != null)
grp.Dispose();
if (ctx != null)
ctx.Dispose();
}
}
示例12: btn_createPC_Click
private void btn_createPC_Click(object sender, RoutedEventArgs e)
{
if (currentPC == null || currentBranch == null)
{
MessageBox.Show("Before createing new PC, you must select Current Branch and generate free PC name!", "Error", MessageBoxButton.OK, MessageBoxImage.Stop);
return;
}
MessageBoxResult mbr = MessageBox.Show(String.Format("Create new PC with name {0} in OU {1}", currentPC, currentBranch), "Agree or disagree?", MessageBoxButton.YesNo,
MessageBoxImage.Question);
if (mbr == MessageBoxResult.No) return;
if (mbr == MessageBoxResult.Yes)
{
try
{
pcx = new PrincipalContext(ContextType.Domain, "bin.bank", String.Format("OU={0},OU=BIN BRANCHES,DC=BIN,DC=BANK", currentBranch), username, password);
ComputerPrincipal comp = new ComputerPrincipal(pcx, currentPC, "", true);
if (ckbx_description.IsChecked == true)
{
string diskrip = Interaction.InputBox("Input a description if needed.", "Description for " + currentPC, "Иванов И. В.");
comp.Description = (diskrip == "") ? null : diskrip;
}
comp.Save();
MessageBox.Show("Successfully!", "Information", MessageBoxButton.OK, MessageBoxImage.Information);
}
catch (Exception ex) { MessageBox.Show(ex.Message); }
finally { pcx.Dispose(); }
}
}
示例13: ActiveDirectorySetup
public void ActiveDirectorySetup(bool overwrite)
{
const string ftpDetails = "OU=Users,OU=";
const string iisDetails = "OU=";
String[] siteTypes = { iisDetails, ftpDetails };
foreach (String type in siteTypes)
{
String siteConnection = type;
String siteUsername;
String sitePassword;
if (type == iisDetails)
{
siteUsername = IISusername;
sitePassword = IISpassword;
}
else
{
siteUsername = FTPusername;
sitePassword = FTPpassword;
}
using (var de = new DirectoryEntry(getConfigSections("ADServer") + "/" + siteConnection + ",DC= " + loginUserName.Text.Split('\\')[0] + ",DC=net", loginUserName.Text, loginPassword.Text))
{
bool creatingNewUser = false;
try
{
using (var dirSearch = new DirectorySearcher(de, "(&(objectClass=user)(name=" + siteUsername + "))", new[] { "cn" }))
{
de.RefreshCache();
SearchResult result = dirSearch.FindOne();
if (result != null && !overwrite)
{
WriteOut("User with that name already exists. Please enter a unique domain name. If you want to override the existing entries, select the Override checkbox.");
}
else if (overwrite)
{
WriteOut("Overwriting existing user.");
creatingNewUser = true;
}
else
{
WriteOut("No user with that name.");
creatingNewUser = true;
}
}
}
catch (Exception e)
{
WriteOut("Failed because of: " + e);
creatingNewUser = false;
}
if (creatingNewUser)
{
try
{
if (overwrite)
{
DirectoryEntry oldUser = de.Children.Find("CN=" + siteUsername, "user");
de.Children.Remove(oldUser);
WriteOut("Removed existing user entry.");
}
DirectoryEntry user = de.Children.Add("CN=" + siteUsername, "user");
user.Properties["sAMAccountName"].Add(siteUsername);
user.Properties["userPrincipalName"].Value = siteUsername + "@" + loginUserName.Text.Split('\\')[0] + ".com";
user.CommitChanges();
WriteOut("Added new user.");
user.Invoke("SetPassword", new Object[] { sitePassword });
user.Properties["userAccountControl"].Value = 0x10240; //Password never expires (0x10000) and normal account (0x200) + can't change password (0x40)
user.CommitChanges();
WriteOut("Set user password and password never expires flag.");
de.CommitChanges();
//REDO TO USE THE DIRECTORY SERVICES ACCOUNT MANAGEMENT STUFF
using (var pc = new PrincipalContext(ContextType.Domain, "servername." + loginUserName.Text.Split('\\')[0] + ".net", "OU=,DC=" + loginUserName.Text.Split('\\')[0] + ",DC=net", loginUserName.Text, loginPassword.Text))
{
GroupPrincipal group = GroupPrincipal.FindByIdentity(pc, "WWWRoot-" + folderGroup);
PrincipalContext mainContext = new PrincipalContext(ContextType.Domain, "servername." + loginUserName.Text.Split('\\')[0] + ".com", siteConnection + ",DC=" + loginUserName.Text.Split('\\')[0] + ",DC=com", loginUserName.Text, loginPassword.Text);
group.Members.Add(mainContext, IdentityType.UserPrincipalName, siteUsername + "@" + loginUserName.Text.Split('\\')[0] + ".com");
group.Save();
mainContext.Dispose();
}
//USER CAN'T CHANGE PASSWORD FLAG NOT SETTING
ActiveDirectorySecurity adSec = de.ObjectSecurity;
var securityDescriptor = adSec.GetSecurityDescriptorSddlForm(AccessControlSections.Access);
var testSD = adSec.GetSecurityDescriptorBinaryForm();
var sid = new SecurityIdentifier(WellKnownSidType.SelfSid, null);
//TxtOutput.Text += "SDDL: " + securityDescriptor + "| Binary: " + testSD;
Guid changePasswordGuid = new Guid("{ab721a53-1e2f-11d0-9819-00aa0040529b}");
RawSecurityDescriptor rawSecDes = new RawSecurityDescriptor(securityDescriptor);
var rawAcl = rawSecDes.DiscretionaryAcl;
DiscretionaryAcl discACL = new DiscretionaryAcl(false, true, rawAcl);
discACL.SetAccess(AccessControlType.Deny, sid, 0x10000000, InheritanceFlags.None, PropagationFlags.None, ObjectAceFlags.ObjectAceTypePresent, changePasswordGuid, changePasswordGuid);
//.........这里部分代码省略.........
示例14: AddGPOAccessRights
/// <summary>
/// Grants the group red and list object rights but denies list content
/// </summary>
/// <param name="ouPath"></param>
/// <param name="groupName"></param>
public void AddGPOAccessRights(string ouPath, string groupName)
{
DirectoryEntry de = null;
PrincipalContext pc = null;
GroupPrincipal gp = null;
try
{
de = new DirectoryEntry("LDAP://" + this.domainController + "/" + ouPath, this.username, this.password);
pc = new PrincipalContext(ContextType.Domain, this.domainController, this.username, this.password);
// Find the group
gp = GroupPrincipal.FindByIdentity(pc, IdentityType.Name, groupName.Replace(" ", string.Empty));
if (gp == null)
throw new Exception("Unable to find the group " + groupName + " in Active Directory");
else
{
// Add Read Property
de.ObjectSecurity.AddAccessRule(new ActiveDirectoryAccessRule(gp.Sid, ActiveDirectoryRights.ReadProperty, AccessControlType.Allow));
// Add List Object
de.ObjectSecurity.AddAccessRule(new ActiveDirectoryAccessRule(gp.Sid, ActiveDirectoryRights.ListObject, AccessControlType.Allow));
// Deny List Content
de.ObjectSecurity.AddAccessRule(new ActiveDirectoryAccessRule(gp.Sid, ActiveDirectoryRights.ListChildren, AccessControlType.Deny));
de.CommitChanges();
}
}
catch (Exception)
{
throw;
}
finally
{
if (gp != null)
gp.Dispose();
if (pc != null)
pc.Dispose();
if (de != null)
de.Dispose();
}
}
示例15: DeleteUser
/// <summary>
/// Deletes a user from the system
/// </summary>
/// <param name="userPrincipalName"></param>
public void DeleteUser(string userPrincipalName)
{
PrincipalContext pc = null;
UserPrincipal up = null;
try
{
pc = new PrincipalContext(ContextType.Domain, this.domainController, this.username, this.password);
logger.Debug("Looking to see if user already exists: " + userPrincipalName);
up = UserPrincipal.FindByIdentity(pc, IdentityType.UserPrincipalName, userPrincipalName);
if (up != null)
{
up.Delete();
logger.Info("Deleted user " + userPrincipalName);
}
}
catch (Exception ex)
{
this.logger.Error("Error deleting user " + userPrincipalName, ex);
throw;
}
finally
{
if (up != null)
up.Dispose();
if (pc != null)
pc.Dispose();
}
}