本文整理汇总了C#中System.DirectoryServices.AccountManagement.UserPrincipal.Save方法的典型用法代码示例。如果您正苦于以下问题:C# UserPrincipal.Save方法的具体用法?C# UserPrincipal.Save怎么用?C# UserPrincipal.Save使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.DirectoryServices.AccountManagement.UserPrincipal
的用法示例。
在下文中一共展示了UserPrincipal.Save方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: createUsers
public static void createUsers(string domain, string ou, int numOfUsers)
{
ContextType contextType = ContextType.Domain;
using (PrincipalContext ctx = new PrincipalContext(contextType, domain, ou))
{
for(int i=0; i<numOfUsers; i++)
{
try
{
UserPrincipal userPrincipal = new UserPrincipal(ctx);
userPrincipal.Surname = SampleData.GetSampleValueRandom(SampleData.LastNames);
userPrincipal.GivenName = SampleData.GetSampleValueRandom(SampleData.FirstNames); ;
userPrincipal.SamAccountName = userPrincipal.GivenName.ToLower() + "." + userPrincipal.Surname.ToLower();
userPrincipal.Name = userPrincipal.GivenName + " " + userPrincipal.Surname;
userPrincipal.DisplayName = userPrincipal.GivenName + " " + userPrincipal.Surname;
string pwdOfNewlyCreatedUser = "Acce1234!";
userPrincipal.SetPassword(pwdOfNewlyCreatedUser);
userPrincipal.Enabled = true;
userPrincipal.PasswordNeverExpires = true;
userPrincipal.Save();
}
catch (Exception ex)
{
Errors.Log(ex);
}
}
}
}
示例2: AddUser
public static void AddUser(SBSUser user)
{
UserPrincipal userPrincipal = new UserPrincipal(Context);
//if (lastName != null && lastName.Length > 0)
userPrincipal.Surname = user.UserName;
//if (firstName != null && firstName.Length > 0)
userPrincipal.GivenName = user.UserName;
//if (employeeID != null && employeeID.Length > 0)
// userPrincipal.EmployeeId = employeeID;
//if (emailAddress != null && emailAddress.Length > 0)
userPrincipal.EmailAddress = user.Email;
//if (telephone != null && telephone.Length > 0)
// userPrincipal.VoiceTelephoneNumber = telephone;
//if (userLogonName != null && userLogonName.Length > 0)
userPrincipal.SamAccountName = user.UserName;
string pwdOfNewlyCreatedUser = user.PassWord;
userPrincipal.SetPassword(pwdOfNewlyCreatedUser);
userPrincipal.Enabled = true;
userPrincipal.ExpirePasswordNow();
userPrincipal.Save();
}
示例3: When_Creating_Home_Directory__Then_It_Should_Have_The_Appropriate_Rights
public void When_Creating_Home_Directory__Then_It_Should_Have_The_Appropriate_Rights()
{
var username = string.Format("testUser{0}", DateTime.Now.Millisecond);
var administration = new AdministrationService();
var context = new PrincipalContext(ContextType.Machine);
var user = new UserPrincipal(context)
{
Name = username,
UserCannotChangePassword = false,
PasswordNeverExpires = true,
};
user.SetPassword("!Password123");
user.Save();
GroupPrincipal grp = GroupPrincipal.FindByIdentity(context, "IIS_IUSRS");
if (grp != null)
{
grp.Members.Add(user);
grp.Save();
}
Assert.IsNotNull(grp);
string dir = Path.Combine(ConfigurationManager.AppSettings["HomeDirectory"], username);
administration.MkDir(username, dir);
bool exists = Directory.Exists(dir);
Assert.IsTrue(exists);
Directory.Delete(dir);
user.Delete();
}
示例4: CreateLocalUser
/// <summary>
/// Create a local user on the machine
/// </summary>
/// <param name="userName"></param>
/// <param name="password"></param>
/// <remarks>Has to be run as an Admin</remarks>
public static void CreateLocalUser(string userName, string password)
{
DeleteLocalUser(userName);
UserPrincipal newUser = new UserPrincipal(new PrincipalContext(ContextType.Machine));
newUser.SetPassword(password);
newUser.Name = userName;
newUser.Description = "New test User";
newUser.UserCannotChangePassword = true;
newUser.PasswordNeverExpires = false;
newUser.Save();
}
示例5: UserAuthenticatorFixture
public UserAuthenticatorFixture()
{
var identity = UserPrincipal.FindByIdentity(new PrincipalContext(ContextType.Machine), IdentityType.SamAccountName, "adtest");
if (identity == null)
{
var principal = new UserPrincipal(new PrincipalContext(ContextType.Machine));
principal.SamAccountName = "adtest";
principal.DisplayName = "ad test";
principal.Save();
principal.SetPassword("password");
}
}
示例6: CreateUser
public LocalPrincipalData CreateUser(string userName)
{
string rvUserName = null;
string rvPassword = null;
LocalPrincipalData rv = null;
using (var context = new PrincipalContext(ContextType.Machine))
{
bool userSaved = false;
ushort tries = 0;
UserPrincipal user = null;
do
{
try
{
rvPassword = Membership.GeneratePassword(8, 2).ToLowerInvariant() + Membership.GeneratePassword(8, 2).ToUpperInvariant();
user = new UserPrincipal(context, userName, rvPassword, true);
user.DisplayName = "Warden User " + userName;
user.Save();
userSaved = true;
}
catch (PasswordException ex)
{
log.DebugException(ex);
}
++tries;
}
while (userSaved == false && tries < 5);
if (userSaved)
{
rvUserName = user.SamAccountName;
var groupQuery = new GroupPrincipal(context, IIS_IUSRS_NAME);
var searcher = new PrincipalSearcher(groupQuery);
var iisUsersGroup = searcher.FindOne() as GroupPrincipal;
iisUsersGroup.Members.Add(user);
iisUsersGroup.Save();
rv = new LocalPrincipalData(rvUserName, rvPassword);
}
}
return rv;
}
示例7: Create
/// <summary>
/// Создать пользователя, с указанным именем и паролем.
/// </summary>
/// <param name="username">Имя пользователя</param>
/// <param name="password">Пароль</param>
public void Create(string username, string password)
{
using (UserPrincipal user = new UserPrincipal(new PrincipalContext(ContextType.Machine)))
{
user.SamAccountName = username;
if (password.Length == 0)
{
user.PasswordNotRequired = true;
}
else
{
user.SetPassword(password);
user.PasswordNeverExpires = true;
}
user.Enabled = true;
user.Save();
}
}
示例8: CreateLocalWindowsAccount
public void CreateLocalWindowsAccount(string username, string password, string displayName, string description, bool disablePWChange, bool pwdNeverExpires, UserPrincipal user)
{
try
{
user.SetPassword(password);
user.DisplayName = displayName;
user.Name = username;
user.Description = description;
user.UserCannotChangePassword = disablePWChange;
user.PasswordNeverExpires = pwdNeverExpires;
user.Save();
BatchState.State = UserProcessState.WIN_USER_OK;
}
catch (Exception)
{
BatchState.State = UserProcessState.WIN_USER_ERROR;
throw;
}
}
示例9: ChangePassword
// Adapted from http://www.snippetdirectory.com/csharp/changing-password-of-a-local-or-domain-user/
public bool ChangePassword(string username, string oldpass, string newpass)
{
PrincipalContext insPrincipalContext = null;
if (this.options.Keys.Contains("location") && this.options["location"] == "local")
{
insPrincipalContext = new PrincipalContext(ContextType.Machine);//Connecting to local computer.
}
else if (this.options.Keys.Contains("location") && this.options["location"] == "domain")
{
insPrincipalContext = new PrincipalContext(ContextType.Domain, this.options["domain"], this.options["ads"]);//Connecting to Active Directory
}
UserPrincipal insUserPrincipal = new UserPrincipal(insPrincipalContext);
insUserPrincipal.Name = username;
PrincipalSearcher insPrincipalSearcher = new PrincipalSearcher();
insUserPrincipal = insPrincipalSearcher.FindOne() as UserPrincipal;
insUserPrincipal.SetPassword(newpass);
insUserPrincipal.Save();
insUserPrincipal.Dispose();
return true;
}
示例10: 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))
{
UserPrincipal newUser = new UserPrincipal(context, userName, password, true);
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();
}
}
示例11: CopyUser
/// <summary>
/// Copies a user account to the specified location. A random password will be assigned to the user
/// and the account will be disabbled. Before the account can be used it will need to be
/// unlocked and have its password reset.
///
/// The following attributes are copied from the template:
/// description, co, company, countryCode, department, l, physicalDeliveryOfficeName, postalCode,
/// profilePath (modified for the new user), st, streetAddress.
///
/// It also copies the group membership of the template.
/// </summary>
/// <param name="firstName">The givenName of the new user.</param>
/// <param name="lastName">The surName (sn) of the new user.</param>
/// <param name="samAccountName">The new logon name. This must be unique or this method will fail.</param>
/// <param name="location">The distinguishedName of the OU where the new user should be created.</param>
/// <param name="templateSamAccountName"></param>
/// <returns>The UserPrincipal object of the new user.</returns>
public static UserPrincipal CopyUser(string firstName, string lastName, string samAccountName, string location, string templateSamAccountName)
{
// Get the template principal object and create a new user principal object
UserPrincipal template = UserPrincipal.FindByIdentity(GetPrincipalContext(), templateSamAccountName);
UserPrincipal newUser = new UserPrincipal(GetPrincipalContext(location), samAccountName, GetRandomPassword(), false);
// create some attribute values for later
string displayName = string.Format("{0}, {1}", lastName, firstName);
string profilePath = GetProperty(template, "profilePath").Replace(templateSamAccountName, samAccountName);
// some easy settings that are in the UserPrincipal object
newUser.Description = template.Description;
newUser.DisplayName = displayName;
newUser.GivenName = firstName;
newUser.Name = displayName;
newUser.Surname = lastName;
newUser.UserCannotChangePassword = false;
newUser.UserPrincipalName = string.Format("{0}@{1}", samAccountName, GetCurrentDomain());
newUser.Save();
// some attributes must be set the old way
SetProperty(newUser, "co", GetProperty(template, "co"));
SetProperty(newUser, "company", GetProperty(template, "company"));
SetProperty(newUser, "countryCode", "0");
SetProperty(newUser, "department", GetProperty(template, "department"));
SetProperty(newUser, "l", GetProperty(template, "l"));
SetProperty(newUser, "physicalDeliveryOfficeName", GetProperty(template, "physicalDeliveryOfficeName"));
SetProperty(newUser, "postalCode", GetProperty(template, "postalCode"));
SetProperty(newUser, "profilePath", profilePath);
SetProperty(newUser, "st", GetProperty(template, "st"));
SetProperty(newUser, "streetAddress", GetProperty(template, "streetAddress"));
// copy the group membership of the template
foreach (GroupPrincipal group in template.GetGroups())
{
AddMember(samAccountName, group.SamAccountName);
}
return newUser;
}
示例12: createUser
/// <summary>
/// Creates an Active Directory user using a firstName.lastName convention in the default Users container for the domain
/// </summary>
/// <param name="firstName"></param>
/// <param name="lastName"></param>
/// <returns>UserPrincipal</returns>
public static UserPrincipal createUser(string firstName, string lastName, string password)
{
try
{
PrincipalContext domainContext = new PrincipalContext(ContextType.Domain, Properties.Settings.Default.domain, Properties.Settings.Default.domainLDAPbase);
UserPrincipal newUser = new UserPrincipal(domainContext);
newUser.GivenName = new CultureInfo("en-US").TextInfo.ToTitleCase(firstName);
newUser.Surname = new CultureInfo("en-US").TextInfo.ToTitleCase(lastName);
string display = new CultureInfo("en-US").TextInfo.ToTitleCase(firstName + " " + lastName);
newUser.Name = display;
newUser.DisplayName = display;
newUser.SamAccountName = firstName.ToLowerInvariant() + "." + lastName.ToLowerInvariant();
newUser.Save();
newUser.SetPassword(password);
newUser.ExpirePasswordNow();
newUser.Enabled = true;
return newUser;
}
catch (System.DirectoryServices.DirectoryServicesCOMException ex)
{
throw ex;
}
}
示例13: When_Creating_New_Site__It_Should_Be_Present_In_IIS
public void When_Creating_New_Site__It_Should_Be_Present_In_IIS()
{
var username = string.Format("testUser{0}", DateTime.Now.Millisecond);
const string password = "!Password123";
var administration = new AdministrationService();
var context = new PrincipalContext(ContextType.Machine);
var user = new UserPrincipal(context) {
Name = username,
UserCannotChangePassword = false,
PasswordNeverExpires = true,
};
user.SetPassword(password);
user.Save();
var grp = GroupPrincipal.FindByIdentity(context, "IIS_IUSRS");
if (grp != null)
{
grp.Members.Add(user);
grp.Save();
}
Assert.IsNotNull(grp);
var dir = Path.Combine(ConfigurationManager.AppSettings["HomeDirectory"], username);
var info = Directory.CreateDirectory(dir);
var security = info.GetAccessControl();
security.AddAccessRule(new FileSystemAccessRule(username,
FileSystemRights.Read |
FileSystemRights.Write |
FileSystemRights.Modify |
FileSystemRights.CreateDirectories |
FileSystemRights.CreateFiles |
FileSystemRights.ReadAndExecute,
InheritanceFlags.ContainerInherit |
InheritanceFlags.ObjectInherit,
PropagationFlags.None,
AccessControlType.Allow));
info.SetAccessControl(security);
var server = new IisServer();
// In order to make this work, you will have to add an entry to your host file or dns...
const string fqdn = "www.test.com";
server.AddWebSite(username, password, fqdn, dir, "http", string.Format("*:80:{0}", fqdn));
using (var serverManager = new ServerManager())
{
var site = serverManager.Sites.FirstOrDefault(x => x.Name == fqdn);
Assert.IsNotNull(site);
var app = site.Applications.FirstOrDefault();
Assert.IsNotNull(app);
var pool = serverManager.ApplicationPools.FirstOrDefault(x => x.Name == fqdn);
Assert.IsNotNull(pool);
// Cleaning up...
app.Delete();
site.Delete();
pool.Delete();
serverManager.CommitChanges();
}
// Cleaning up...
Directory.Delete(dir, true);
user.Delete();
}
示例14: CreateUser
public override MembershipUser CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out MembershipCreateStatus status)
{
UserPrincipal user = GetUser(username) ?? null;
if (user == null)
{
user = new UserPrincipal(GetPrincipalContext());
//User Log on Name
user.SamAccountName = username;
user.SetPassword(password);
user.Enabled = true;
user.UserPrincipalName = username;
user.GivenName = username;
user.Surname = username;
user.EmailAddress = email;
user.UserCannotChangePassword = false;
user.DisplayName = username;
try
{
user.Save();
MembershipUser msUser = new MembershipUser("ActiveDirectoryMembershipProvider", user.SamAccountName, providerUserKey, user.EmailAddress, string.Empty, string.Empty, true, user.IsAccountLockedOut(), DateTime.MinValue, user.LastLogon ?? DateTime.Now, user.LastBadPasswordAttempt ?? DateTime.Now, user.LastPasswordSet ?? DateTime.Now, user.AccountLockoutTime ?? DateTime.Now);
// Nos conectamos via SSH hacia el servidor de Zimbra
SshExec exec = new SshExec("mail.dxstudio.net", "alex");
exec.Password = "admin123";
exec.Connect();
// Una vez conectados al servidor de Zimbra
// estructuramos y armamos el comando Linux
// necesario crear el MailBox
string strCommand = string.Empty;
strCommand = "/opt/zimbra/bin/./zmprov -a admin -p Admin1234 ca " + user.SamAccountName + "@dxstudio.net SoyUnPassword";
// Ejecutamos el comando Linux para crear el MailBox
strCommand = exec.RunCommand(strCommand);
// Cerreamos la Conexion SSH
exec.Close();
// Enviamos Mensaje de bienvenida
SenMail(user.SamAccountName);
status = MembershipCreateStatus.Success;
return msUser;
}
catch (Exception ex)
{
// verificamos que efectivamente no se cree el usuario
var usr = GetUser(username) ?? null;
if (usr != null)
usr.Delete();
status = MembershipCreateStatus.UserRejected;
return null;
}
}
else
{
MembershipUser msUser = new MembershipUser("ActiveDirectoryMembershipProvider", user.SamAccountName, providerUserKey, user.EmailAddress, string.Empty, string.Empty, true, user.IsAccountLockedOut(), DateTime.MinValue, user.LastLogon ?? DateTime.Now, user.LastBadPasswordAttempt ?? DateTime.Now, user.LastPasswordSet ?? DateTime.Now, user.AccountLockoutTime ?? DateTime.Now);
status = MembershipCreateStatus.DuplicateUserName;
return msUser;
}
}
示例15: CreateAdUser
/*
* Edit funcations
*/
private string CreateAdUser(AdUser adUser, string container, List<string> securityGroups)
{
string loginId, manager = string.Empty;
// find the supervisor
if (!string.IsNullOrEmpty(adUser.ManagerKerb))
{
var supervisor = GetUserByEmployeeId(adUser.ManagerKerb);
if (supervisor != null) manager = supervisor.DistinguishedName;
}
using (var upc = new PrincipalContext(ContextType.Domain, Site.ActiveDirectoryServer, container, UserName, Password))
{
loginId = CheckForExistingUser(adUser.FirstName, adUser.LastName, upc);
if (loginId == null)
{
throw new DuplicateNameException("Unable to determine a valid userid for the requested user.");
}
var user = new UserPrincipal(upc);
AutoMapper.Mapper.Map(adUser, user);
user.SamAccountName = loginId;
user.UserPrincipalName = string.Format("{0}@caesdo.caes.ucdavis.edu", loginId);
user.Enabled = true;
if (adUser.LastName.ToLower() != loginId)
{
user.Name = string.Format("{0}, {1} ({2})", adUser.LastName, adUser.FirstName, loginId);
}
user.SetPassword(GeneratePassword(16));
//if (adUser.NeedsEmail)
//{
// user.EmailAddress = string.Format("{0}@caes.ucdavis.edu", loginId);
//}
user.Save();
foreach (var groupId in securityGroups)
{
AddToGroup(user, groupId);
}
}
// assign attributes that must be done after saving
using (var ad = new PrincipalContext(ContextType.Domain, Site.ActiveDirectoryServer, container, UserName, Password))
{
var user = UserPrincipal.FindByIdentity(ad, loginId);
// set the extended properties that cannot be done before first save
user.OfficeLocation(adUser.OfficeLocation);
user.Manager(manager);
user.Save();
}
return loginId;
}