本文整理匯總了C#中System.DirectoryServices.AccountManagement.UserPrincipal.SetPassword方法的典型用法代碼示例。如果您正苦於以下問題:C# UserPrincipal.SetPassword方法的具體用法?C# UserPrincipal.SetPassword怎麽用?C# UserPrincipal.SetPassword使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類System.DirectoryServices.AccountManagement.UserPrincipal
的用法示例。
在下文中一共展示了UserPrincipal.SetPassword方法的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: CreateUser
/// <summary>
/// To Create users
/// </summary>
/// <param name="txt">textbox to warnings</param>
/// <param name="userLogonName">username</param>
/// <param name="userPassword"></param>
/// <param name="datetime">account expiration date</param>
/// <returns>true if users if deleted sucessfully </returns>
public void CreateUser(StringBuilder sb, string userLogonName, string userPassword)
{
// Creating the PrincipalContext
PrincipalContext principalContext = null;
principalContext = context;
// Check if user object already exists in the store
UserPrincipal usr = UserPrincipal.FindByIdentity(principalContext, userLogonName);
if (usr == null){
// Create the new UserPrincipal object
UserPrincipal userPrincipal = new UserPrincipal(context);
// username
userPrincipal.SamAccountName = userLogonName;
// Expiring date
// userPrincipal.AccountExpirationDate = datetime;
//Password
userPrincipal.SetPassword(userPassword);
//Activate the account
userPrincipal.Enabled = true;
//cant change the password
userPrincipal.UserCannotChangePassword = true;
userPrincipal.Save();
}
}
示例3: 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();
}
示例4: 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();
}
示例5: 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();
}
示例6: 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");
}
}
示例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 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;
}
}
示例11: CreateUserIfNotPresent
private void CreateUserIfNotPresent()
{
using (var context = new PrincipalContext(ContextType.Machine, Localhost))
{
if (UserPrincipal.FindByIdentity(context, IdentityType.Name, NLogTestUser) != null)
return;
var user = new UserPrincipal(context);
user.SetPassword(NLogTestUserPassword);
user.Name = NLogTestUser;
user.Save();
var group = GroupPrincipal.FindByIdentity(context, "Users");
group.Members.Add(user);
group.Save();
}
}
示例12: crearEstudiante2
//BASARSE EN ESTO PARA ARREGLAR TODO LO QUE SEA CON EL AD
//Una mejor manera de hacerlo http://johnbarquin.wordpress.com/2008/06/12/servicios-de-directorio-en-net-35/
/// <summary>
/// Método que se encarga de crear un usuario estudiante en Active Directory
/// </summary>
/// <param name="estudiante">
/// Los datos del estudiante (en un tipo Usuario) por ingresar a Active Directory
/// </param>
public Boolean crearEstudiante2(Usuario estudiante)
{
String nombre_completo = estudiante.Carnet + " " + estudiante.Nombre + " " + estudiante.Apellidos + " " + estudiante.Carrera;
try {
PrincipalContext contextoDominio = new PrincipalContext(ContextType.Domain, Constantes.DOM, Constantes.AD_USER, Constantes.AD_PASS);
UserPrincipal usuario = new UserPrincipal(contextoDominio, estudiante.UID, estudiante.Contrasena, true);
usuario.SamAccountName = estudiante.UID;// LEGACY: Cuenta de estudiante Pre-Win2000
usuario.UserPrincipalName = estudiante.UID + Constantes.DOMINIO;//Debe de contener el dominio
usuario.GivenName = estudiante.Nombre;
usuario.Surname = estudiante.Apellidos;
usuario.DisplayName = nombre_completo;
usuario.Description = "Estudiante";
usuario.HomeDirectory = getHomeDirectoryAD(estudiante);
usuario.EmailAddress = estudiante.Correo;
usuario.HomeDrive = "M";
usuario.PasswordNeverExpires = true;
usuario.Save();
usuario.SetPassword(estudiante.Contrasena);
usuario.Save();
return true;
}
catch (Exception e)
{
_conexionBD = new ManejoBD();
_conexionBD.insertarBitacoraError(e.ToString(), "");
return false;
}
}
示例13: CreateSimpleAdUser
public static string CreateSimpleAdUser(string username, string password, string name, string description, string adPath = "OU=Users,OU=UNIT,DC=UN1T,DC=GROUP")
{
using (WindowsImpersonationContextFacade impersonationContext
= new WindowsImpersonationContextFacade(
nc))
{
bool userIsExist = false;
DirectoryEntry directoryEntry = new DirectoryEntry(DomainPath);
using (directoryEntry)
{
//Если пользователь существует
DirectorySearcher search = new DirectorySearcher(directoryEntry);
search.Filter = String.Format("(&(objectClass=user)(sAMAccountName={0}))", username);
SearchResult resultUser = search.FindOne();
userIsExist = resultUser != null && resultUser.Properties.Contains("sAMAccountName");
}
if (!userIsExist)
{
//Создаем аккаунт в AD
using (
var pc = new PrincipalContext(ContextType.Domain, "UN1T", adPath))
{
using (var up = new UserPrincipal(pc))
{
up.SamAccountName = username;
up.UserPrincipalName = username + "@unitgroup.ru";
up.SetPassword(password);
up.Enabled = true;
up.PasswordNeverExpires = true;
up.UserCannotChangePassword = true;
up.Description = description;
//up.DistinguishedName = "DC=unitgroup.ru";
try
{
up.Save();
}
catch (PrincipalOperationException ex)
{
}
up.UnlockAccount();
}
}
}
directoryEntry = new DirectoryEntry(DomainPath);
using (directoryEntry)
{
//DirectoryEntry user = directoryEntry.Children.Add("CN=" + username, "user");
DirectorySearcher search = new DirectorySearcher(directoryEntry);
search.Filter = String.Format("(&(objectClass=user)(sAMAccountName={0}))", username);
search.PropertiesToLoad.Add("objectsid");
search.PropertiesToLoad.Add("samaccountname");
search.PropertiesToLoad.Add("userPrincipalName");
search.PropertiesToLoad.Add("mail");
search.PropertiesToLoad.Add("usergroup");
search.PropertiesToLoad.Add("displayname");
search.PropertiesToLoad.Add("givenName");
search.PropertiesToLoad.Add("sn");
search.PropertiesToLoad.Add("title");
search.PropertiesToLoad.Add("telephonenumber");
search.PropertiesToLoad.Add("homephone");
search.PropertiesToLoad.Add("mobile");
search.PropertiesToLoad.Add("manager");
search.PropertiesToLoad.Add("l");
search.PropertiesToLoad.Add("company");
search.PropertiesToLoad.Add("department");
SearchResult resultUser = search.FindOne();
if (resultUser == null) return String.Empty;
DirectoryEntry user = resultUser.GetDirectoryEntry();
//SetProp(ref user, ref resultUser, "mail", mail);
SetProp(ref user, ref resultUser, "displayname", name);
SetProp(ref user, ref resultUser, "givenName", username);
SetProp(ref user, ref resultUser, "sn", name);
SetProp(ref user, ref resultUser, "title", description);
//SetProp(ref user, ref resultUser, "telephonenumber", workNum);
//SetProp(ref user, ref resultUser, "mobile", mobilNum);
SetProp(ref user, ref resultUser, "l", description);
SetProp(ref user, ref resultUser, "company", name);
SetProp(ref user, ref resultUser, "department", "-");
//SetProp(ref user, ref resultUser, "manager", "");
//user.Properties["jpegPhoto"].Clear();
//SetProp(ref user, ref resultUser, "jpegPhoto", photo);
user.CommitChanges();
SecurityIdentifier sid = new SecurityIdentifier((byte[])resultUser.Properties["objectsid"][0],
0);
return sid.Value;
}
return String.Empty;
}
//.........這裏部分代碼省略.........
示例14: SaveUser
//public static void GetEmployeeManager(Employee emp, out string managerUsername)
//{
// managerUsername = String.Empty;
// if (emp.Department == null) return;
// if (!Department.CheckUserIsChief(emp.Department.Id, emp.Id))
// {
// managerUsername = emp.Manager != null ? GetLoginFromEmail(emp.Manager.Email) : String.Empty;
// }
// if (String.IsNullOrEmpty(managerUsername))
// {
// Department currDep = new Department(emp.Department.Id);
// GetParentDepChief(currDep, out managerUsername);
// }
//}
//public static void GetParentDepChief(Department dep, out string managerUsername)
//{
// managerUsername = String.Empty;
// if (dep.ParentDepartment != null && dep.ParentDepartment.Id > 0)
// {
// var parentDep = new Department(dep.ParentDepartment.Id);
// var overManager = new Employee(parentDep.Chief.Id);
// managerUsername = GetLoginFromEmail(overManager.Email);
// if (String.IsNullOrEmpty(managerUsername))
// {
// GetParentDepChief(parentDep, out managerUsername);
// }
// }
//}
public static string SaveUser(Employee emp)
{
if (!emp.HasAdAccount) return String.Empty;
using (WindowsImpersonationContextFacade impersonationContext
= new WindowsImpersonationContextFacade(
nc))
{
string username = String.IsNullOrEmpty(emp.AdLogin) ? GetLoginFromEmail(emp.Email) : StringHelper.Trim(emp.AdLogin);
if (String.IsNullOrEmpty(username.Trim())) return string.Empty;
string mail = StringHelper.Trim(emp.Email);
string fullName = StringHelper.Trim(emp.FullName);
string surname = StringHelper.Trim(emp.Surname);
string name = StringHelper.Trim(emp.Name);
string position = emp.Position != null ? emp.Position.Id > 0 && String.IsNullOrEmpty(emp.Position.Name) ? new Position(emp.Position.Id).Name : emp.Position.Name : String.Empty;
string workNum = StringHelper.Trim(emp.WorkNum);
string mobilNum = StringHelper.Trim(emp.MobilNum);
string city = emp.City != null ? StringHelper.Trim(emp.City.Name) : String.Empty;
string org = emp.Organization != null ? emp.Organization.Id > 0 && String.IsNullOrEmpty(emp.Organization.Name) ? new Organization(emp.Organization.Id).Name : emp.Organization.Name : String.Empty;
string dep = emp.Department != null ? emp.Department.Id > 0 && String.IsNullOrEmpty(emp.Department.Name) ? new Department(emp.Department.Id).Name : emp.Department.Name : String.Empty;
var photo = emp.Photo != null && emp.Photo.Length > 0 ? emp.Photo : null;
Employee manager = new Employee(emp.Manager.Id);
string managerUsername = String.IsNullOrEmpty(manager.AdLogin)
? GetLoginFromEmail(manager.Email)
: manager.AdLogin;
//GetEmployeeManager(emp, out managerUsername);
string managerName = String.Empty;
bool userIsExist = false;
DirectoryEntry directoryEntry = new DirectoryEntry(DomainPath);
using (directoryEntry)
{
//Если пользователь существует
DirectorySearcher search = new DirectorySearcher(directoryEntry);
search.Filter = String.Format("(&(objectClass=user)(sAMAccountName={0}))", username);
SearchResult resultUser = search.FindOne();
userIsExist = resultUser != null && resultUser.Properties.Contains("sAMAccountName");
}
if (!String.IsNullOrEmpty(managerUsername.Trim()))
{
using (directoryEntry)
{
DirectorySearcher search = new DirectorySearcher(directoryEntry);
search.Filter = String.Format("(&(objectClass=user)(sAMAccountName={0}))", managerUsername);
search.PropertiesToLoad.Add("DistinguishedName");
SearchResult resultManager = search.FindOne();
if (resultManager != null)
managerName = (string)resultManager.Properties["DistinguishedName"][0];
}
}
if (!userIsExist)
{
//Создаем аккаунт в AD
using (
var pc = new PrincipalContext(ContextType.Domain, "UN1T", "OU=Users,OU=UNIT,DC=UN1T,DC=GROUP"))
{
using (var up = new UserPrincipal(pc))
{
up.SamAccountName = username;
up.UserPrincipalName = username + "@unitgroup.ru";
up.SetPassword("z-123456");
up.Enabled = true;
up.ExpirePasswordNow();
try
{
up.Save();
}
catch (PrincipalOperationException ex)
//.........這裏部分代碼省略.........
示例15: CreateOrGetUserPrincipal
private UserPrincipal CreateOrGetUserPrincipal(UserInformation userInfo)
{
UserPrincipal user = null;
if ( ! LocalAccount.UserExists(userInfo.Username) )
{
// See note about MS bug in CreateOrGetGroupPrincipal to understand the mix of DE/Principal here:
using (user = new UserPrincipal(m_machinePrincipal))
{
user.Name = userInfo.Username;
user.SetPassword(userInfo.Password);
user.Save();
// Sync via DE
SyncUserPrincipalInfo(user, userInfo);
// We have to re-fetch to get changes made via underlying DE
return GetUserPrincipal(user.Name);
}
}
user = GetUserPrincipal(userInfo.Username);
if (user != null)
return user;
else
throw new Exception(
String.Format("Unable to get user principal for account that apparently exists: {0}", userInfo.Username));
}