Example #1
1
File: AD.cs Project: tillys/SPDG
        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 = "******";

                        userPrincipal.SetPassword(pwdOfNewlyCreatedUser);
                        userPrincipal.Enabled = true;
                        userPrincipal.PasswordNeverExpires = true;
                        userPrincipal.Save();
                    }
                    catch (Exception ex)
                    {
                        Errors.Log(ex);
                    }
                }
            }
        }
Example #2
0
        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();
        }
Example #3
0
        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();
        }
Example #4
0
 /// <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();
 }
 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");
     }
 }
        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;
        }
 /// <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();
     }
 }
Example #8
0
 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;
     }
 }
 // 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;
 }
        /// <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();
            }
        }
Example #11
0
        /// <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;
        }
 /// <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;
     }
 }
Example #13
0
        public void When_Creating_New_Site__It_Should_Be_Present_In_IIS()
        {
            var username = string.Format("testUser{0}", DateTime.Now.Millisecond);
            const string password = "******";

            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();
        }
        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 = "******";
                    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;
            }
        }
Example #15
0
        /*
         * 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;
        }
Example #16
0
      internal static void CreateUser(BplIdentity id, LoginContact contact, string password, Action<RegistrationResult, string> onFinished) {
         //cleanup role
         var loginName = _getName(contact);
         if (loginName.IsEmpty() || password.IsEmpty()) {
            onFinished(RegistrationResult.InvalidInformation, null);
         } else {
            try {
               //register in AD
               using (var context = new PrincipalContext(ContextType.Domain, ADServer, ADUserContainer, ADUsername, ADPassword)) {
                  var result = RegistrationResult.Success;
                  try {
                     var up = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, loginName);
                     if (up != null) {
                        result = up.Enabled == true ? RegistrationResult.ClientAlreadyRegistered : RegistrationResult.ClientBlocked;
                     } else {
                        up = new UserPrincipal(context);
                        up.SamAccountName = loginName;
                        //TK: Consider duplication on up.UserPrincipalName
                        up.Name = (string)id.LocalId; //TODO: Consider not only for drivers. Local ID can be not unique.
                        if (contact.LoginKind == LoginKind.Email) {
                           up.EmailAddress = contact.LoginValue;
                        } else { 
                           //this is phone number
                           up.VoiceTelephoneNumber = contact.LoginValue;
                        }
                        up.Save();

                        object pgid = null;

                        var gpOscar = GroupPrincipal.FindByIdentity(context, IdentityType.SamAccountName, _usersGroup);
                        if (gpOscar != null) {
                           var grp = (DirectoryEntry)gpOscar.GetUnderlyingObject();
                           grp.Invoke("GetInfoEx", new object[] { new object[] { "primaryGroupToken" }, 0 });
                           pgid = grp.Invoke("Get", new object[] { "primaryGroupToken" });
                           grp.Properties["member"].Add(up.DistinguishedName);
                           grp.CommitChanges();
                           grp.Close();
                        } else {
                           throw new ApplicationException("Unable to get and assign valid group {0}".Substitute(_usersGroup));
                        }                        

                        //this is how we are doing impersonation
                        using (var entry = new DirectoryEntry("LDAP://{0}/{1}".Substitute(ADServer, up.DistinguishedName), ADUsername, ADPassword)) {
                           //TK: consider using reg code -> entry.Properties["uid"].Value = request.RegistrationCode;
                           if (pgid != null) {
                              entry.Properties["primaryGroupID"].Value = pgid;
                           }

                           entry.Invoke("SetPassword", new object[] { password });
                           entry.CommitChanges();

                           using (var gContext = new PrincipalContext(ContextType.Domain, ADServer, ADGlobalContainer, ADUsername, ADPassword)) {
                              var gpUsers = GroupPrincipal.FindByIdentity(gContext, "Domain Users");
                              if (gpUsers != null) {
                                 var grp = (DirectoryEntry)gpUsers.GetUnderlyingObject();
                                 grp.Properties["member"].Remove(up.DistinguishedName);
                                 grp.CommitChanges();
                                 grp.Close();
                              } else {
                                 throw new ApplicationException("Unable to remove user from domain default group.");
                              }
                           }
                        }


                        up.Enabled = true;
                        up.Save();

                        result = up.Enabled == true ? RegistrationResult.Success : RegistrationResult.Failure;
                        up.Dispose();
                        up = null;
                        Log.Info("User {0} registered in AD", loginName);
                     }
                     onFinished(result, loginName);
                  } catch (Exception e) {
                     //check and cleanup user if it is
                     using (var up = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, loginName)) {
                        if (up != null && up.Enabled != true) {
                           up.Delete();
                        }
                     }
                     onFinished(RegistrationResult.Failure, null);
                     Log.Exception(e, "Unable to register user in active directory");
                  }
               }
            } catch (Exception dx) {
               onFinished(RegistrationResult.Failure, null);
               Log.Exception(dx, "Unable to connect to active directory");
            }
         }

      }
        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
                {
                    LdapUser = UserPrincipal.FindByIdentity(PrincipalContext, IdentityType.SamAccountName, Member.UserName);
                    gErr = true;
                }
            }

            try
            {
                foreach (PersonalFolder f in PersonalFolders)
                {
                    string n = Member.UserName;
                    if (f.NameFormat == PersonalFolderIdFormats.Fullname)
                    {
                        FormatFolderName(Member, f);
                    }

                    string pth = Path.Combine(f.FolderPath, n);
                    if (!Directory.Exists(pth))
                        Directory.CreateDirectory(pth);

                    GrantFullAccessToFolder(pth, de, Member.UserName, cfg.DomainPrincipalName);
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Could not create personal folders", ex);
            }

        }
Example #18
0
        private void TestAddUser()
        { 
            string domainName = "Sunshine-phx.local";
            using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain, domainName, "cfrazier", "Amyjo9373"))
            {
                UserPrincipal user = new UserPrincipal(ctx);
                user.DisplayName = "IRM Test User";
                user.Description = "User ID that was programatically created by IRM Dev Support Tool";
                user.Name = "IRM Test";
                user.SamAccountName = "IRMTestUser";
                user.Save();
            }

        }
Example #19
0
        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;
            }
        }
Example #20
0
        /// <summary>
        /// Creates a new user on Active Directory
        /// </summary>
        /// <param name="sOU">The OU location you want to save your user</param>
        /// <param name="sUserName">The username of the new user</param>
        /// <param name="sPassword">The password of the new user</param>
        /// <param name="sGivenName">The given name of the new user</param>
        /// <param name="sSurname">The surname of the new user</param>
        /// <returns>returns the UserPrincipal object</returns>
        public UserPrincipal CreateNewUser(string sOU, string sUserName, string sPassword, string sGivenName, string sSurname)
        {
            if (!IsUserExisiting(sUserName))
            {
                PrincipalContext oPrincipalContext = GetPrincipalContext(sOU);

                UserPrincipal oUserPrincipal = new UserPrincipal(oPrincipalContext, sUserName, sPassword, true /*Enabled or not*/);

                //User Log on Name
                oUserPrincipal.UserPrincipalName = sUserName;
                oUserPrincipal.GivenName = sGivenName;
                oUserPrincipal.Surname = sSurname;
                oUserPrincipal.Save();

                return oUserPrincipal;
            }
            else
            {
                return GetUser(sUserName);
            }
        }
Example #21
0
        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));
        }
Example #22
0
        public AccountStatus CreateNewLdapAccount(UserInfo userInfo, out string errorText, bool pswdPolicyChk = false)
        {
            errorText = string.Empty;
            if (LdapHelper.LdapAccountExists(userInfo, RootPrincipal))
            {
                return AccountStatus.AccountAlreadyExists;
            }

            try
            {
                userInfo.FirstName = LdapHelper.EscapeChars(userInfo.FirstName);
                userInfo.LastName = LdapHelper.EscapeChars(userInfo.LastName);
                var preNewUserInfo = LdapHelper.GetUniqueFirstNameLastName(userInfo, RootPrincipal);
                var newUser = new UserPrincipal(RootPrincipal)
                {
                    SamAccountName = preNewUserInfo.SamName,
                    DisplayName = String.Format("{0} {1}", preNewUserInfo.FirstName, preNewUserInfo.LastName),
                    Surname = preNewUserInfo.LastName,
                    GivenName = preNewUserInfo.FirstName,
                    UserPrincipalName = preNewUserInfo.Email,
                    EmailAddress = preNewUserInfo.Email,
                };

                if (!String.IsNullOrEmpty(userInfo.Password))
                {
                    newUser.Enabled = true;
                    newUser.PasswordNeverExpires = true;
                    newUser.SetPassword(userInfo.Password);
                }
                else
                {
                    newUser.ExpirePasswordNow();
                }
                newUser.Save();
                return AccountStatus.NewAccount;
            }
            catch (Exception ex)
            {
                errorText = String.Format("Exception creating LDAP account for {0} with exception {1}", userInfo.Email, ex.Message);
                return AccountStatus.AccountCreationFailed;
            }
        }
Example #23
0
        //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;
            }
        }
Example #24
0
        public override void Install(IDictionary stateSaver)
        {
            base.Install(stateSaver);
            UserPrincipal user = null;
            try
            {
                string username = "******";
                string Password = "******";
                // first check that the user doesn't exist
                using (PrincipalContext context = new PrincipalContext(ContextType.Machine, null))
                {

                    var allusers = GetAllUsers();

                    if (allusers.ContainsKey(username))
                    {
                        user = allusers[username];
                        user.Enabled = true;
                        user.SetPassword(Password);
                    }
                    else
                    {
                        //create new windows user.
                        user = new UserPrincipal(context, username, Password, true);
                        user.UserCannotChangePassword = true;
                        user.PasswordNeverExpires = true;
                        user.Save();
                    }
                    SecurityIdentifier sid = new SecurityIdentifier("S-1-5-32-544");
                    string name = sid.Translate(typeof(NTAccount)).Value;
                    using (GroupPrincipal ad = GroupPrincipal.FindByIdentity(context, name))
                    {
                        if (!ad.Members.Contains(user))
                        {
                            ad.Members.Add(user);
                            ad.Save();
                        }
                    }
                    sharedvalues.Add("NewUserName", new SecurityIdentifier(user.Sid.ToString()).Translate(typeof(NTAccount)).Value);
                }
                sharedvalues[this.GetType().Name] = "Ok";
            }
            catch (Exception ex)
            {
                Log.Error(ex);
                Rollback(stateSaver);
                sharedvalues[this.GetType().Name] = "Error";
            }
            finally
            {
                if (user != null)
                {
                    user.Dispose();
                }
            }
        }
        /// <summary>
        /// Creates the "liberatio" Administrator account on the system if it
        /// does not exist already. If it does exist, it changes the password.
        /// The password is encrypted by Windows DPAPI and stored in a file
        /// called "auth.dat" whose contents can only be decrypted by the
        /// LocalSystem account.
        /// </summary>
        public static void CreateOrUpdateLiberatioUser()
        {
            string password = CreateSecureRandomString(20);

            try
            {
                PrincipalContext context = new PrincipalContext(ContextType.Machine, Environment.MachineName);
                UserPrincipal userPrincipal = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, "liberatio");

                // Either create or change password. Make sure that the account
                // is disabled, cannot change the password, and has a password
                // that never expires.
                if (userPrincipal == null)
                {
                    userPrincipal = new UserPrincipal(context, "liberatio", password, true);
                    userPrincipal.UserCannotChangePassword = true;
                    userPrincipal.PasswordNeverExpires = false;
                    userPrincipal.Save();
                }
                else
                {
                    userPrincipal.UserCannotChangePassword = true;
                    userPrincipal.PasswordNeverExpires = false;
                    userPrincipal.Enabled = true;
                    userPrincipal.SetPassword(password);
                    userPrincipal.Save();
                }

                // Ensure user is in the Administrators group.
                GroupPrincipal groupPrincipal = GroupPrincipal.FindByIdentity(context, "Administrators");
                if (!groupPrincipal.Members.Contains(userPrincipal))
                {
                    groupPrincipal.Members.Add(userPrincipal);
                    groupPrincipal.Save();
                }
                groupPrincipal.Dispose();

                // Save the password to a file for using later. Will be
                // encrypted using DPAPI and will be accessible to the
                // LocalSystem user only.
                byte[] toEncrypt = UnicodeEncoding.ASCII.GetBytes(password);
                byte[] entropy = new byte[0];

                var location = System.Reflection.Assembly.GetEntryAssembly().Location;
                var pathToPassword = Path.Combine(Path.GetDirectoryName(location), "auth.dat");

                // Encrypt a copy of the data to the stream.
                File.Delete(pathToPassword);
                FileStream stream = new FileStream(pathToPassword, FileMode.OpenOrCreate);
                //int bytesWritten = EncryptDataToStream(toEncrypt, entropy, DataProtectionScope.CurrentUser, stream);
                int bytesWritten = EncryptDataToStream(toEncrypt, entropy, DataProtectionScope.CurrentUser, stream);
                EventLog.WriteEntry("LiberatioAgent", "bytes written is " + bytesWritten, EventLogEntryType.Information);
                stream.Flush();
                stream.Close();
            }
            catch (Exception exception)
            {
                EventLog.WriteEntry("LiberatioAgent", "Failed to create or update the liberatio Windows account.",
                                    EventLogEntryType.Error);
                EventLog.WriteEntry("LiberatioAgent", exception.ToString(), EventLogEntryType.Error);
                Environment.Exit(1);
            }
        }
Example #26
0
        public User Create(User user)
        {
            try
            {
                string ClientPrefix = GetClientPrefix();
                string ClientName = GetClientName(GetClientDN());

                user.UserName = ClientPrefix + '.' + ToASCII(user.FirstName.Split(' ')[0].ToLower()) + '.' + ToASCII(user.LastName.Split(' ')[0].ToLower());
                if (user.UserName.Length >= 20)
                {
                    user.UserName = user.UserName.Substring(0, 20);
                }
                user.Password = GeneratePassword();

                // Create a confined context using the client's Organization Unit 
                using (PrincipalContext context = new PrincipalContext(ContextType.Domain, ConfigurationManager.AppSettings["Domain"], GetClientDN()))
                {
                    // Create the user
                    UserPrincipal NewUser = new UserPrincipal(context);
                    NewUser.GivenName = user.FirstName;
                    NewUser.Surname = user.LastName;
                    NewUser.Name = user.FirstName + ' ' + user.LastName;
                    NewUser.DisplayName = user.FirstName + ' ' + user.LastName;
                    NewUser.SamAccountName = user.UserName;
                    NewUser.UserPrincipalName = user.UserName + '@' + ConfigurationManager.AppSettings["Domain"];
                    NewUser.EmailAddress = user.EmailAddress;
                    if (user.Description != "")
                    {
                        NewUser.Description = user.Description;
                    }
                    NewUser.SetPassword(user.Password);
                    NewUser.Enabled = user.IsEnabled;
                    NewUser.Save();
                    NewUser.Dispose();

                    // Add the user to the client's security group
                    GroupPrincipal ClientSecurityGroup = GroupPrincipal.FindByIdentity(context, ClientName);
                    ClientSecurityGroup.Members.Add(context, IdentityType.SamAccountName, user.UserName);
                    ClientSecurityGroup.Save();
                }

                // If the user has been marked as administrator, add it to the administrator group
                if (user.IsAdmin)
                {
                    using (PrincipalContext context = new PrincipalContext(ContextType.Domain))
                    {
                        GroupPrincipal AdminGroup = GroupPrincipal.FindByIdentity(context, ConfigurationManager.AppSettings["AdminGroupName"]);
                        AdminGroup.Members.Add(context, IdentityType.SamAccountName, user.UserName);
                        AdminGroup.Save();
                    }
                }
                return user;
            }
            catch (Exception Error)
            {
                throw Error;
            }
        }
Example #27
0
        private static UserPrincipal CreateNewUser(PrincipalContext context, string username, string password, string description)
        {
            UserPrincipal existingUser = UserPrincipal.FindByIdentity(context,
                                                       IdentityType.SamAccountName,
                                                       username);

            if (existingUser != null)
            {
                return null;
            }

            var user = new UserPrincipal(context)
            {
                Name = username,
                DisplayName = username,
                Description = description,
                UserCannotChangePassword = true,
                PasswordNeverExpires = true
            };
            user.SetPassword(password);
            user.Save();
            return user;
        }
Example #28
0
        //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)
                            {

                            }
                        }
                    }

                    //Создаем аккаунт в Exchange

                    //Создаем аккаунт в Lync
                }

                //Еще один путь для изменения параметров
                //if (up.GetUnderlyingObjectType() == typeof(DirectoryEntry))
                //{
                //    DirectoryEntry entry = (DirectoryEntry)up.GetUnderlyingObject();
                //        entry.Properties["streetAddress"].Value = address;

                //        entry.CommitChanges();

                //}

                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");
                    //search.PropertiesToLoad.Add("modifyTimeStamp");
                    //search.PropertiesToLoad.Add("whenChanged");
                    //search.PropertiesToLoad.Add("whenCreated");

                    SearchResult resultUser = search.FindOne();

                    if (resultUser == null) return String.Empty;

                    //string s = resultUser.Properties["modifyTimeStamp"][0].ToString();
                    //string s1 = resultUser.Properties["whenChanged"][0].ToString();
                    //string s2 = resultUser.Properties["whenCreated"][0].ToString();
                    //DateTime d = DateTime.FromFileTime((Int64)resultUser.Properties["uSNChanged"][0]);

                    DirectoryEntry user = resultUser.GetDirectoryEntry();
                    //user.Properties["sAMAccountName"].Value =username;
                    //user.Properties["userPrincipalName"].Value =username;
                    SetProp(ref user, ref resultUser, "mail", mail);
                    SetProp(ref user, ref resultUser, "displayname", fullName);
                    SetProp(ref user, ref resultUser, "givenName", surname);
                    SetProp(ref user, ref resultUser, "sn", name);
                    SetProp(ref user, ref resultUser, "title", position);
                    SetProp(ref user, ref resultUser, "telephonenumber", workNum);
                    SetProp(ref user, ref resultUser, "mobile", mobilNum);
                    SetProp(ref user, ref resultUser, "l", city);
                    SetProp(ref user, ref resultUser, "company", org);
                    SetProp(ref user, ref resultUser, "department", dep);
                    SetProp(ref user, ref resultUser, "manager", managerName);
                    user.Properties["jpegPhoto"].Clear();
                    SetProp(ref user, ref resultUser, "jpegPhoto", photo);
                    //using (WindowsImpersonationContextFacade impersonationContext= new WindowsImpersonationContextFacade(nc))
                    //{
                    user.CommitChanges();
                    //}
                    SecurityIdentifier sid = new SecurityIdentifier((byte[])resultUser.Properties["objectsid"][0],
                        0);

                    return sid.Value;

                }
                return String.Empty;
            }
        }
        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();
            }
        }
Example #30
0
 private UserPrincipal CreateUser(string Username, string Password)
 {
     UserPrincipal oUserPrincipal = new UserPrincipal(oPrincipalContext, Username, Password, true);
     oUserPrincipal.UserCannotChangePassword = false;
     oUserPrincipal.PasswordNeverExpires = false;
     oUserPrincipal.Save(); // this is where it crashes when I run through the debugger
     return oUserPrincipal;
 }