Create User In Active Directory and Maill Box in Exchange Server

Hello Dear Frinez,

                                        Here is the blog  how to create a Active directory users and how to create the mail box for the Active directory users on Exchange Server 2007. It also explains how to disable the mail box for a user and  how to remove a user from the mail box as well in the Active Directory Using C# Coding.



using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using ActiveDs;
using System.DirectoryServices;
using System.EnterpriseServices;
using System.Runtime.InteropServices;
using System.Management.Instrumentation;
using System.Management;
using System.Management.Automation.Runspaces;
using System.Management.Automation.Host;
using Microsoft.PowerShell.Commands;
using System.Management.Automation;
using System.Security;
using System.Collections.ObjectModel;
using System.Collections;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            string sLDAP = ConfigurationManager.AppSettings["LDAP"].ToString();
            ArrayList arr = new ArrayList();
            arr = GetAllADDomainUsers(sLDAP);
            DropDownList1.DataSource = arr;
            DropDownList1.DataBind();
        }
      
    }
    protected void butCreateUser_Click(object sender, EventArgs e)
    {
        string sLDAP= ConfigurationManager.AppSettings["LDAP"].ToString();
      
       
        CreateUser(txtDispName.Text,txtFname.Text, txtLname.Text, sLDAP);
    }

    private void CreateUser(string sSamName, string sFistName, string sLast_Name, string sBaseContainer)
    {

        string sUserName = ConfigurationManager.AppSettings["Ser_UserName"].ToString();
        string sPass = ConfigurationManager.AppSettings["Ser_Password"].ToString();
     

        string sError = "";

        try
        {

            DirectoryEntry user, oCont;



            oCont = new DirectoryEntry(sBaseContainer, sUserName, sPass, AuthenticationTypes.Secure); //, null, null, AuthenticationTypes.Secure);

            IADsContainer oDSCont = null;

            IADsUser oUser = null;

            user = oCont.Children.Add("cn=" + sFistName, "user");

            oDSCont = oCont.NativeObject as IADsContainer;

            oUser = oDSCont.Create("user", string.Format("CN={0} {1}", sFistName, sLast_Name)) as IADsUser;

            oUser.Put("sn", sLast_Name);

            oUser.Put("givenname", sFistName);

            oUser.Put("samaccountname", sSamName);

            oUser.Put("description", "Sample Test Description");

            oUser.Put("displayname", sSamName);

            oUser.Put("userPrincipalName", sFistName + "@cgxchange.net");

            oUser.SetInfo();

            oUser.AccountDisabled = false;

            oUser.SetInfo();

            Response.Write("User Created Successfully!!!");







        }

        catch (Exception ex)
        {
            sError = ex.Message;

            Response.Write("Failed to create user");

            Response.Write(ex.Message);
        }
        finally
        {
            ArrayList arr = new ArrayList();
            arr = GetAllADDomainUsers(sBaseContainer);
            DropDownList1.DataSource = arr;
            DropDownList1.DataBind();
        }
   }



   public ArrayList GetAllADDomainUsers(string domainpath)
    {
        ArrayList allUsers = new ArrayList();
        string sUserName = ConfigurationManager.AppSettings["Ser_UserName"].ToString();
        string sPass = ConfigurationManager.AppSettings["Ser_Password"].ToString();
        DirectoryEntry searchRoot = new DirectoryEntry(domainpath,sUserName,sPass,AuthenticationTypes.Secure);
        DirectorySearcher search = new DirectorySearcher(searchRoot);
        search.Filter = "(&(objectClass=user)(objectCategory=person))";
        search.PropertiesToLoad.Add("displayname");

        SearchResult result;
        SearchResultCollection resultCol = search.FindAll();
        if (resultCol != null)
        {
            for (int counter = 0; counter < resultCol.Count; counter++)
            {
                result = resultCol[counter];
                if (result.Properties.Contains("displayname"))
                {
                    allUsers.Add((String)result.Properties["displayname"][0]);
                }
            }
        }
        return allUsers;
    }










    protected void butCreateMailBox_Click(object sender, EventArgs e)
    {
        try
        {
            //Create a Runespace and add commands
            RunspaceConfiguration runspaceConfig = RunspaceConfiguration.Create();
            PSSnapInException snapEX = null;
            System.Management.Automation.PSSnapInInfo snampInfo = runspaceConfig.AddPSSnapIn("Microsoft.Exchange.Management.PowerShell.Admin", out snapEX);
            Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfig);
            runspace.Open();

            //Creates a pipeline
            Pipeline pipeLine = runspace.CreatePipeline();

            using (pipeLine)
            {

                //creates a  command
                Command createMailbox = new Command("Enable-Mailbox");
                createMailbox.Parameters.Add("Identity", Session["User"].ToString());

                // now you must pass secure string
                string pword = "CGvak123";
                char[] passwordChars = pword.ToCharArray();
                SecureString password = new SecureString();
                foreach (char c in passwordChars)
                {
                    password.AppendChar(c);
                }

              
                createMailbox.Parameters.Add("Database", "CGVAK-XCHANGE\\First Storage Group\\Mailbox Database");

                //set other mailbox parameters here

                pipeLine.Commands.Add(createMailbox);

                Collection<PSObject> result = pipeLine.Invoke();


            }

            //closes connections
            pipeLine = null;
            runspace.Close();
            runspace = null;
            Response.Write("Mail Box Created Successfully!!!");
        }

        catch (Exception E)
        {
            Response.Write(E.ToString());
        }



    }




    protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
    {
        Session["User"] = DropDownList1.SelectedItem.Text;
    }
    protected void butRemoveMaiBox_Click(object sender, EventArgs e)
    {
        try
        {
            //Create a Runespace and add commands
            RunspaceConfiguration runspaceConfig = RunspaceConfiguration.Create();
            PSSnapInException snapEX = null;
            System.Management.Automation.PSSnapInInfo snampInfo = runspaceConfig.AddPSSnapIn("Microsoft.Exchange.Management.PowerShell.Admin", out snapEX);
            Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfig);
            runspace.Open();

            //Creates a pipeline
            Pipeline pipeLine = runspace.CreatePipeline();

            using (pipeLine)
            {

                //creates a  command
                Command createMailbox = new Command("Disable-Mailbox");
                createMailbox.Parameters.Add("Identity", Session["User"].ToString());
                createMailbox.Parameters.Add("Confirm", false);

                pipeLine.Commands.Add(createMailbox);

                Collection<PSObject> result = pipeLine.Invoke();


            }

            //closes connections
            pipeLine = null;
            runspace.Close();
            runspace = null;
            Response.Write("Mail Box Removed Successfully!!!");
        }

        catch (Exception E)
        {
            Response.Write(E.ToString());
        }

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        try
        {
            //Create a Runespace and add commands
            RunspaceConfiguration runspaceConfig = RunspaceConfiguration.Create();
            PSSnapInException snapEX = null;
            System.Management.Automation.PSSnapInInfo snampInfo = runspaceConfig.AddPSSnapIn("Microsoft.Exchange.Management.PowerShell.Admin", out snapEX);
            Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfig);
            runspace.Open();

            //Creates a pipeline
            Pipeline pipeLine = runspace.CreatePipeline();

            using (pipeLine)
            {

                //creates a  command
                Command createMailbox = new Command("Remove-Mailbox");
                createMailbox.Parameters.Add("Identity", Session["User"].ToString());
                createMailbox.Parameters.Add("Confirm", false);

                pipeLine.Commands.Add(createMailbox);

                Collection<PSObject> result = pipeLine.Invoke();


            }

            //closes connections
            pipeLine = null;
            runspace.Close();
            runspace = null;
            Response.Write("User Removed Successfully from Active Directory!!!");
        }

        catch (Exception E)
        {
            Response.Write(E.ToString());
        }

    }
}


Thanks,


D.Kannan MCAD.,MCT.