Monday, 20 June 2011

Program to Create Active Directory user

1. Add refereces 
2. Create One Organization Unit in Active Directory Named Web Users
My Domain Name is CGSTAGE

using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.DirectoryServices;

namespace Custom_New_User.VisualWebPart1
{
    public partial class VisualWebPart1UserControl : UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
          {
           }

        protected void btnSubmit_Click(object sender, EventArgs e)
        {

            try
            {
                DirectoryEntry parent = new DirectoryEntry("LDAP://OU= Web                 Users,DC=CGSTAGE,DC=com", null, null, AuthenticationTypes.Secure);
                DirectoryEntry user = parent.Children.Add("CN="+txtUName.Text, "user");
                using (user)
                {
                    //sAMAccountName is required for W2k AD, we would not use
                    //this for ADAM, however.
                    user.Properties["sAMAccountName"].Value = txtUName.Text;

                    //userPrincipalName is not required, but recommended
                    //for ADAM. AD also contains this, so we can use it.
                    user.Properties["userPrincipalName"].Value = txtUName.Text;
                    user.Properties["givenName"].Value = txtFName.Text;
                    user.Properties["sn"].Value = txtLName.Text;                  
                    user.CommitChanges();
                    //To Activate the User
                    int val = (int)user.Properties["userAccountControl"].Value;
                    user.Properties["userAccountControl"].Value = val & ~0x2;
                    user.Invoke("SetPassword", new object[] { txtPassword.Text });
                    user.CommitChanges();
                }

            }

            catch (Exception e1)
            {
                Label1.Text = e1.Message;
            }

        }
     }

    }