Friday, May 30, 2014

SharePoint 2013/2010: Management of Active Directory users via SharePoint List and Event Receivers (C#.Net).

Context: Customer wants to manage Active Directory User Accounts directly in SharePoint. That means I need a custom SharePoint list to add, modify and delete user accounts. The list has to contain the following fields: Firstname, Lastname, Username, E-Mail and Password.

Solution: I used 'System.DirectoryServices.AccountManagement' API for adding, updating and deleting the active directory users. SharePoint event recievers were used to capture the events when the user of the list wants to delete, update and add an active directory user.

The following code I wrote to achieve this task;


PrincipalContext principalContext = null;
        UserPrincipal _userPrincipal = null;
        String _email = null;
        String _firstName = null;
        String _lastName = null;
        String _userName = null;
        String _password = null;

        /// 
        /// An user is being added in the active directory.
        /// 
        public override void ItemAdding(SPItemEventProperties properties)
        {
            try
            {
                _email = (String)properties.AfterProperties["EMail"];
                _firstName = (String)properties.AfterProperties["FirstName"];
                _lastName = (String)properties.AfterProperties["LastName"];
                _userName = (String)properties.AfterProperties["Username"];
                _password = (String)properties.AfterProperties["Password"];

                Validator _validator = new Validator();
                if (!_validator.IsValidEmail(_email)) // If it is not valid, cancel the current operation
                {
                    properties.Cancel = true;
                    properties.ErrorMessage = "Invalid email value!";
                }
                else
                {                    
                    principalContext = getPrincipalContext();
                    _userPrincipal = new UserPrincipal(principalContext, _userName, _password, true);

                    //User Information
                    _userPrincipal.Name = _firstName + " " + _lastName;
                    _userPrincipal.Description = "This is the user account created from SharePoint list";
                    _userPrincipal.EmailAddress = _email;
                    _userPrincipal.SetPassword(_password);
                    try { _userPrincipal.Save(); }
                    catch (Exception) { }
                    base.ItemAdding(properties);
                }
            }
            catch (Exception ex)
            {
                properties.Cancel = true;
                properties.ErrorMessage = ex.Message;
            }
            finally
            {
                if (principalContext != null)
                    principalContext.Dispose();
                if (_userPrincipal != null)
                    _userPrincipal.Dispose();
            }
        }

        /// 
        /// An user is being updated in the active directory..
        /// 
        public override void ItemUpdating(SPItemEventProperties properties)
        {
            try
            {
                _userName = (String)properties.ListItem["Username"];
                if ((String)properties.AfterProperties["EMail"] != null)
                    _email = (String)properties.AfterProperties["EMail"];
                else
                    _email = (String)properties.ListItem["EMail"];

                if ((String)properties.AfterProperties["FirstName"] != null)
                    _firstName = (String)properties.AfterProperties["FirstName"];
                else
                    _firstName = (String)properties.ListItem["FirstName"];


                if ((String)properties.AfterProperties["LastName"] != null)
                    _lastName = (String)properties.AfterProperties["LastName"];
                else
                    _lastName = (String)properties.ListItem["LastName"];

                if ((String)properties.AfterProperties["Password"] != null)
                    _password = (String)properties.AfterProperties["Password"];
                else
                    _password = (String)properties.ListItem["Password"];

                
                principalContext = getPrincipalContext();
                _userPrincipal = UserPrincipal.FindByIdentity(principalContext, IdentityType.SamAccountName, _userName);
                _userPrincipal.Delete();
                _userPrincipal.Dispose();
                _userPrincipal = new UserPrincipal(principalContext, _userName, _password, true);
                _userPrincipal.Name = _firstName + " " + _lastName;
                _userPrincipal.Description = "This is the user account created from SharePoint list";
                _userPrincipal.EmailAddress = _email;
                _userPrincipal.SetPassword(_password);
                try { _userPrincipal.Save(); }
                catch (Exception) { }
                base.ItemUpdating(properties);
            }
            catch (Exception ex)
            {
                properties.Cancel = true;
                properties.ErrorMessage = ex.InnerException.Message;
            }
            finally
            {
                if (principalContext != null)
                    principalContext.Dispose();
                if (_userPrincipal != null)
                    _userPrincipal.Dispose();
            }
        }

        /// 
        /// An user is being deleted in the active directory..
        /// 
        public override void ItemDeleting(SPItemEventProperties properties)
        {
            try
            {
                _userName = (String)properties.ListItem["Username"];
                principalContext = getPrincipalContext();
                _userPrincipal = UserPrincipal.FindByIdentity(principalContext, IdentityType.SamAccountName, _userName);
                _userPrincipal.Delete();
                base.ItemDeleting(properties);
            }
            catch (Exception ex)
            {
                properties.Cancel = true;
                properties.ErrorMessage = ex.InnerException.Message;
            }
            finally
            {
                if (principalContext != null)
                    principalContext.Dispose();
                if (_userPrincipal != null)
                    _userPrincipal.Dispose();
            }

        }

        // Please change username and Password that is allowed to create users in Active Directory
        private PrincipalContext getPrincipalContext()
        {
            string _domainName = getDomainName();
            PrincipalContext principalContext = new PrincipalContext(ContextType.Domain, _domainName,
                        "CN=Users,DC=Contoso,DC=com", ContextOptions.SimpleBind, "salman@contoso.com", "Dev#123");

            return principalContext;
        }

        //Get Domain Name
        private string getDomainName()
        {
            return System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties().DomainName;
        }


No comments:

Post a Comment