本文整理汇总了C#中System.DirectoryServices.AccountManagement.UserPrincipal.GetUnderlyingObject方法的典型用法代码示例。如果您正苦于以下问题:C# UserPrincipal.GetUnderlyingObject方法的具体用法?C# UserPrincipal.GetUnderlyingObject怎么用?C# UserPrincipal.GetUnderlyingObject使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.DirectoryServices.AccountManagement.UserPrincipal
的用法示例。
在下文中一共展示了UserPrincipal.GetUnderlyingObject方法的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: CreateUser
/// <summary>
/// Creates a Windows user.
/// </summary>
/// <param name="userName">Name of the user.</param>
/// <param name="password">The password.</param>
/// <param name="description">The description for the user.</param>
public static void CreateUser(string userName, string password, string description)
{
using (var context = new PrincipalContext(ContextType.Machine))
{
using (UserPrincipal newUser = new UserPrincipal(context, userName, password, true))
{
newUser.HomeDirectory = string.Format(CultureInfo.InvariantCulture, @"c:\users\{0}", userName);
newUser.Save();
DirectoryEntry de = newUser.GetUnderlyingObject() as DirectoryEntry;
if (!string.IsNullOrEmpty(description))
{
de.Properties["Description"].Add(description);
}
de.Invoke("Put", new object[] { "UserFlags", 0x10000 }); // 0x10000 is DONT_EXPIRE_PASSWORD
de.Invoke("SetPassword", password);
newUser.Save();
}
}
}
示例2: CreateLdapAccount
public void CreateLdapAccount(LdapConfig cfg, bool allowPasswordChange)
{
string pwd = ldapContext.LdapConfigs.Decryptpassword(cfg);
DirectoryEntry ou = new DirectoryEntry("LDAP://" + OuAssignment.OuDistinguishedName, cfg.UserName, pwd);
string fn = Regex.Replace(Member.GivenName, @"[^A-Za-z0-9]+", "");
string mn = null;
if(Member.MiddleName != null)
mn = Regex.Replace(Member.MiddleName, @"[^A-Za-z0-9]+", "");
string ln = Regex.Replace(Member.Surname, @"[^A-Za-z0-9]+", "");
string name = Lcps.DivisionDirectory.Members.DirectoryMemberRepository.GetName(DirectoryMemberNameFormats.Full | DirectoryMemberNameFormats.Sort, ln, fn, mn);
string dn = string.Format("CN={0} ({1})", name.Replace(",", "\\,"), Member.UserName);
var principalContext = new PrincipalContext(ContextType.Domain, cfg.DomainPrincipalName, cfg.UserName, pwd);
string memberPw = Member.DecryptPassword();
bool enabled = false;
if ((Member.MembershipScope & Convert.ToInt64(MembershipScopeReserved.Active)) == Convert.ToInt64(MembershipScopeReserved.Active))
enabled = true;
if ((Member.MembershipScope & Convert.ToInt64(MembershipScopeReserved.Inactive)) == Convert.ToInt64(MembershipScopeReserved.Inactive))
enabled = false;
LdapUser = new UserPrincipal(principalContext, Member.UserName, memberPw, enabled);
string scope = this.dirContext.MembershipScopes.GetCaptionLabel(Member.MembershipScope);
LdapUser.Description = scope;
LdapUser.DisplayName = Lcps.DivisionDirectory.Members.DirectoryMemberRepository.GetName(Member, DirectoryMemberNameFormats.Short | DirectoryMemberNameFormats.Sort);
LdapUser.UserCannotChangePassword = (!allowPasswordChange);
LdapUser.Surname = Member.Surname;
LdapUser.GivenName = Member.GivenName;
LdapUser.UserPrincipalName = Member.UserName + "@" + cfg.DomainPrincipalName;
LdapUser.PasswordNeverExpires = true;
LdapUser.EmployeeId = Member.InternalId;
LdapUser.EmailAddress = Member.Email;
try
{
LdapUser.Save();
}
catch (Exception ex)
{
throw new Exception("Could not create user", ex);
}
ou.RefreshCache();
DirectoryEntry de = null;
try
{
de = (DirectoryEntry)LdapUser.GetUnderlyingObject();
de.InvokeSet("division", pwd);
de.InvokeSet("comment", DateTime.Now.ToString());
de.MoveTo(ou, dn);
de.CommitChanges();
de.RefreshCache();
ou.RefreshCache();
LdapUser = UserPrincipal.FindByIdentity(PrincipalContext, IdentityType.SamAccountName, Member.UserName);
}
catch (Exception ex)
{
throw new Exception(string.Format("Could not move user {0} to OU", dn), ex);
}
SyncGroupMemberships(false);
bool gErr = true;
int x = 1;
while(gErr == true)
{
try
{
x++;
DirectoryEntry thisU = (DirectoryEntry)LdapUser.GetUnderlyingObject();
thisU.CommitChanges();
ou.RefreshCache();
thisU.RefreshCache();
foreach(GroupPrincipal g in LdapUser.GetGroups())
{
string n = g.Name;
}
gErr = false;
}
catch
//.........这里部分代码省略.........
示例3: GetEmails
IEnumerable<string> GetEmails(UserPrincipal user)
{
// Add the "mail" entry
yield return user.EmailAddress;
// Add the "proxyaddresses" entries.
PropertyCollection properties = ((DirectoryEntry) user.GetUnderlyingObject()).Properties;
foreach (object property in properties["proxyaddresses"])
yield return property.ToString();
yield return user.UserPrincipalName;
}
示例4: ToDomainUser
private static DomainUser ToDomainUser(UserPrincipal principal)
{
if (principal == null)
{
return new DomainUser();
}
var directoryEntry = principal.GetUnderlyingObject() as DirectoryEntry;
return new DomainUser
{
Login = principal.SamAccountName,
FullName = principal.DisplayName,
Guid = principal.Guid.ToString(),
Email = principal.EmailAddress,
Phone = directoryEntry.GetPhone(),
PhoneAdditional = principal.VoiceTelephoneNumber,
PhysicalDeliveryOfficeName = directoryEntry.GetOffice(),
Post = directoryEntry.GetPost(),
SubdivisionIdentifiers = directoryEntry.GetSubdivisionIdentifiers()
};
}
示例5: ADUser
/// <summary>
/// Create an AD User from the given connection and UserPrincipal
/// </summary>
/// <param name="connection">The AD connection</param>
/// <param name="user">An existing UserPrincipal object</param>
public ADUser(ActiveDirectory connection, UserPrincipal user)
{
if (connection == null || user == null)
{
throw new NullReferenceException();
}
_sourceUser = user;
_connection = connection;
mapper = new DEMapper();
DEFields.Add("manager");
this.UserState = UserStates.Existing;
foreach (System.Reflection.PropertyInfo property in this.GetType().GetProperties())
{
DEFieldAttribute tag= property.GetCustomAttributes(typeof(DEFieldAttribute),true).FirstOrDefault() as DEFieldAttribute;
if (tag != null)
{
DEFields.Add(tag.Name!=null?tag.Name:property.Name);
}
}
if (user.Name != null)
{
_groups = new List<string>(_sourceUser.GetGroups(connection.GlobalContext).Select(item => item.Name));
}
this.Initialize(_sourceUser);
if (_sourceUser.DisplayName != null)
{
directoryEntry = _sourceUser.GetUnderlyingObject() as DirectoryEntry;
directoryEntry.RefreshCache(DEFields.ToArray<string>());
mapper.Copy(directoryEntry, this);
}
string ldap=String.Format("LDAP://{0}/{1}", connection.Name, connection.Container);
parent = new DirectoryEntry(ldap, connection.User, connection.Password);
}
示例6: Save
/// <summary>
/// Save the local ADUser data to the remote server
/// </summary>
public void Save()
{
if (isSaveable)
{
//Set password
if (passwordChanged)
{
_sourceUser.SetPassword(_password);
passwordChanged = false;
}
if (_sourceUser.Name == null || _sourceUser.DisplayName == null)
{
_sourceUser.Name = GivenName + " " + Surname;
_sourceUser.DisplayName = _sourceUser.Name;
}
Boolean wasNewUser = _isNewUser;
try
{
_sourceUser.Save();
//Save data to AD
if (_isNewUser)
{
directoryEntry = _sourceUser.GetUnderlyingObject() as DirectoryEntry;
}
_isNewUser = false;
}
catch (PrincipalExistsException ex)
{
throw new DuplicateUser(ex.Message);
}
Sync_Groups();
//Have to reload the UserPrincipal to get the DirectoryEntry
UserPrincipal newSourceUser = _connection.GetUserBySid(_sourceUser.Sid);
//if (wasNewUser)
//{
if (newSourceUser == null)
{
string msg = "Couldn't reload user: " + _sourceUser.DisplayName;
throw new InvalidOperationException(msg);
}
_sourceUser = newSourceUser;
//}
if (directoryEntry != null)
{
directoryEntry.Close();
}
directoryEntry = _sourceUser.GetUnderlyingObject() as DirectoryEntry;
directoryEntry.Options.SecurityMasks = SecurityMasks.Dacl;
//Copy local attributes to directory entry
//directoryEntry.RefreshCache(DEFields.ToArray<string>());
mapper.Copy(this, directoryEntry);
if ((this.Manager != null) && (!this.Manager.DistinguishedName.Equals(directoryEntry.Properties["manager"].Value)))
{
if (directoryEntry.Properties.Contains("manager"))
{
directoryEntry.Properties["manager"].Value = this.Manager.DistinguishedName;
}
else
{
directoryEntry.Properties["manager"].Add(this.Manager.DistinguishedName);
}
}
if (DisplayName != directoryEntry.Properties["cn"].Value as string)
{
directoryEntry.Rename("CN=" + DisplayName);
}
try
{
directoryEntry.CommitChanges();
}
catch (DirectoryServicesCOMException ex)
{
System.Diagnostics.Debug.Write(ex.Message + " - " + ex.StackTrace);
throw new ADException(String.Format("DirectoryServicesCOMException {0}", ex.Message), ex);
}
if (this.HideFromAddressLists)
{
try
{
if (!directoryEntry.Properties.Contains("msExchHideFromAddressLists"))
//.........这里部分代码省略.........
示例7: SetUserProperties
private void SetUserProperties(UserPrincipal user, Dictionary<string, object> properties)
{
if (user == null)
{
throw new ArgumentNullException("user", "Null refference object");
}
if (properties != null)
{
var _userObject = user.GetUnderlyingObject();
if (_userObject != null)
{
SetProperties((DirectoryEntry)_userObject, properties);
}
}
}
示例8: AddADUser
/// <summary>
/// Create AD User in a container
/// </summary>
/// <param name="userinfo">ADUser object</param>
/// <returns></returns>
public ResponseMessage AddADUser( RequestUserCreate userinfo )
{
ResponseMessage status = new ResponseMessage();
status.IsSuccessful = false;
status.Message = string.Empty;
Session stat = ValidateSession( userinfo.DomainInfo.SessionKey );
if ( stat.IsAuthenticated == true )
{
PrincipalContext principalContext = null;
string uri = FixADURI( userinfo.DomainInfo.ADHost , userinfo.DomainInfo.ContainerPath );
if ( string.IsNullOrWhiteSpace( uri ) )
{
status.Message = status.Message = "AD Host is not allowed to be empty, kindly provide the AD Host";
return status;
}
bool isAllowWite = CheckWriteOermission( uri , userinfo.DomainInfo.BindingUserName , userinfo.DomainInfo.BindingUserPassword );
try
{
UserPrincipal usr = FindADUser( userinfo.UserLogonName , userinfo.DomainInfo );
if ( usr != null )
{
status.Message = " user already exists. Please use a different User Logon Name";
return status;
}
else
{
principalContext = new PrincipalContext( ContextType.Domain , userinfo.DomainInfo.DomainName , userinfo.DomainInfo.ContainerPath , userinfo.DomainInfo.BindingUserName , userinfo.DomainInfo.BindingUserPassword );
}
}
catch ( Exception ex )
{
status.Message = @"Failed to create PrincipalContext: " + ex;
return status;
}
// Create the new UserPrincipal object
UserPrincipal userPrincipal = new UserPrincipal( principalContext );
if ( !string.IsNullOrWhiteSpace( userinfo.LastName ) )
userPrincipal.Surname = userinfo.LastName;
if ( !string.IsNullOrWhiteSpace( userinfo.FirstName ) )
userPrincipal.GivenName = userinfo.FirstName;
if ( !string.IsNullOrWhiteSpace( userinfo.LastName ) && !string.IsNullOrWhiteSpace( userinfo.FirstName ) )
userPrincipal.DisplayName = userinfo.FirstName + " " + userinfo.LastName;
if ( !string.IsNullOrWhiteSpace( userinfo.Description ) )
userPrincipal.Description = userinfo.Description;
if ( !string.IsNullOrWhiteSpace( userinfo.EmployeeID ) )
userPrincipal.EmployeeId = userinfo.EmployeeID;
if ( !string.IsNullOrWhiteSpace( userinfo.EmailAddress ) )
userPrincipal.EmailAddress = userinfo.EmailAddress;
if ( !string.IsNullOrWhiteSpace( userinfo.Telephone ) )
userPrincipal.VoiceTelephoneNumber = userinfo.Telephone;
if ( !string.IsNullOrWhiteSpace( userinfo.UserLogonName ) )
userPrincipal.SamAccountName = userinfo.UserLogonName;
if ( !string.IsNullOrWhiteSpace( userinfo.Password ) )
userPrincipal.SetPassword( userinfo.Password );
userPrincipal.Enabled = true;
userPrincipal.ExpirePasswordNow();
try
{
userPrincipal.Save();
DirectoryEntry de = (DirectoryEntry)userPrincipal.GetUnderlyingObject();
FillUserExtraAttributes( ref de , userinfo );
de.CommitChanges();
status.Message = "Account has been created successfuly";
status.IsSuccessful = true;
}
catch ( Exception ex )
{
status.Message = "Exception creating user object. " + ex;
status.IsSuccessful = false;
return status;
}
//.........这里部分代码省略.........
示例9: createNewUserBackgroundWorker_DoWork
private void createNewUserBackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
try
{
using (var principalContext = new PrincipalContext(ContextType.Domain, domainDnsName, cnDnDictionary[createInComboBox.Text]))
{
using (var checkForExistingUser = UserPrincipal.FindByIdentity(principalContext, sAMAccountNameTextBox.Text))
{
if (checkForExistingUser != null)
{
AddActivityItem(sAMAccountNameTextBox.Text + " already exists. Use a different sAMAccountName.");
activityListBox.BackColor = Color.Pink;
return;
}
}
using (var newUser = new UserPrincipal(principalContext))
{
newUser.SamAccountName = sAMAccountNameTextBox.Text;
if (givenNameTextBox.Text.Length > 0)
newUser.GivenName = givenNameTextBox.Text;
if (middleNameTextBox.Text.Length > 0)
newUser.MiddleName = middleNameTextBox.Text;
if (surnameTextBox.Text.Length > 0)
newUser.Surname = surnameTextBox.Text;
if (displayNameTextBox.Text.Length > 0)
newUser.DisplayName = displayNameTextBox.Text;
if (emailTextBox.Text.Length > 0)
newUser.EmailAddress = emailTextBox.Text;
if (employeeIDTextBox.Text.Length > 0)
newUser.EmployeeId = employeeIDTextBox.Text;
if (descriptionTextBox.Text.Length > 0)
newUser.Description = descriptionTextBox.Text;
if (userPrincipalNameTextBox.Text.Length > 0)
newUser.UserPrincipalName = userPrincipalNameTextBox.Text;
newUser.SetPassword(passwordTextBox.Text);
if (userEnabledCheckBox.Checked)
newUser.Enabled = true;
if (changePasswordCheckBox.Checked)
newUser.ExpirePasswordNow();
if (passwordNeverExpiresCheckBox.Checked)
newUser.PasswordNeverExpires = true;
newUser.Save();
if (!string.IsNullOrEmpty(copyFromComboBox.Text))
{
using (PrincipalSearchResult<Principal> newUsersExistingGroupMemberships = newUser.GetAuthorizationGroups())
using (var userToCopyFrom = UserPrincipal.FindByIdentity(principalContext, copyFromComboBox.Text))
{
using (PrincipalSearchResult<Principal> groups = userToCopyFrom.GetAuthorizationGroups())
{
foreach (GroupPrincipal groupPrincipal in groups)
{
bool newUserIsAlreadyAMember = false;
foreach (GroupPrincipal existingGroupMembership in newUsersExistingGroupMemberships)
{
if (existingGroupMembership.Name == groupPrincipal.Name)
newUserIsAlreadyAMember = true;
}
if (newUserIsAlreadyAMember == false)
{
groupPrincipal.Members.Add(newUser);
groupPrincipal.Save();
AddActivityItem("User added to group: " + groupPrincipal.Name);
}
}
}
}
}
else
{
AddActivityItem("No group memberships were copied.");
}
// To set additional attributes beyond those provided by UserPrincipal, we must drop down to the underlying object.
using (DirectoryEntry newUserEntry = (DirectoryEntry)newUser.GetUnderlyingObject())
{
if (initialsTextBox.Text.Length > 0)
newUserEntry.Properties["initials"].Value = initialsTextBox.Text;
if (employeeNumberTextBox.Text.Length > 0)
newUserEntry.Properties["employeeNumber"].Value = employeeNumberTextBox.Text;
if (telephoneNumberTextBox.Text.Length > 0)
newUserEntry.Properties["telephoneNumber"].Value = telephoneNumberTextBox.Text;
newUserEntry.CommitChanges();
}
AddActivityItem("User " + newUser.SamAccountName + " created successfully.");
//.........这里部分代码省略.........