Archive for the 'Active Directory' Category

15
Sep
08

Active Directory User Selective Inductive Field Control

My project manager ask me to do the Active Directory User Selective inductive method to seperate out the active directory users from the telephone extension list users who were binded in their Display Name with the Active Directory, the following is a small module for our companies sharepoint protal management server to maintain all the resources in a centeral station as repository for that we have developed a list contains the extension list of all employees…
the list does has two field types, column named <Employee Name> and <Extension Number>

Note : <Employee Name> Field maps with the Display Name of the Active Directory Users List…

the following xCode.GetADUser.Field.cs

namespace xCode.GetADUser
{
using System;
using System.Runtime.InteropServices;
using System.Security.Permissions;

using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.Security;

    [CLSCompliant(false)]
    [Guid("d3fee3ce-4e3a-4990-8bde-3b52d3596be4")]
    public class ADUserField : SPFieldText
    {
        /// <summary>
        ///
        /// </summary>
        /// <param name="fields"></param>
        /// <param name="fieldName"></param>
        public GetADUserField(SPFieldCollection fields, string fieldName)
            : base(fields, fieldName)
        {
        }
       
        /// <summary>
        ///
        /// </summary>
        /// <param name="fields"></param>
        /// <param name="typeName"></param>
        /// <param name="displayName"></param>
        public GetADUserField(SPFieldCollection fields, string typeName, string displayName)
            : base(fields, typeName, displayName)
        {
        }

        /// <summary>
        ///
        /// </summary>
        public override BaseFieldControl FieldRenderingControl
        {
            [SharePointPermission(SecurityAction.LinkDemand, ObjectModel = true)]
            get
            {
                BaseFieldControl fieldControl = new GetADUserFieldControl();
                fieldControl.FieldName = this.InternalName;

                return fieldControl;
            }
        }
    }
}

the below code describes the functionality for the get Active directory Users…

lets take two asp.net controls for the following functionality, where the dropdownlist list up all the users from the active directory irregardless any condition except the object.filter by user…

 // Golbal variables for the Get Active Directory Userfield control.
        private DropDownList ddlRemainADUsers;
        private Label lblADUser;

the above DropDownList list will visible only on the Newform.aspx and Editform.aspx whereas the Label control will visible only for an alternate form (Dispform.aspx)

 /// <summary>
        /// CreateChildControls() will be called by the PreRender stage
        /// </summary>
        protected override void CreateChildControls()
        {
            base.CreateChildControls();

            //Filtering the ControlMode for field in both Newform.aspx as well as Editform.aspx
            if (this.ControlMode == SPControlMode.Edit ||
                this.ControlMode == SPControlMode.New) 
            {
                // Initialize the ddlRemainADUsers DropDownList with new instance
                this.ddlRemainADUsers = new DropDownList();

                // Gets the current site from the SPContext
                SPSite objSite = SPContext.GetContext(this.Context).Site;

                // Binding all Active directory Users into the AdUsersList ArrayList Control.
                // return all users from the Active Directory.
                ArrayList AdUsersList = getADUsers();

                // ArrayList to be subtracted to the AdUsersList ArrayList...
                ArrayList UserList = new ArrayList();

                // Remained Users after the Seperation done...
                ArrayList RemainList = new ArrayList();
                SPWeb objWeb = objSite.OpenWeb();

                // validating the List Item Count not set to be 0 or less than that...
                if (web.Lists[<listName>].ItemCount > 0) {                   
                    SPListItemCollection objListItemColl = objWeb.Lists[<listName>].Items;
                    // Iterating through each ListItem from the respective list <listName>
                    foreach (SPListItem objListItem in objListItemColl) {
                        if (objListItem[<EmployeeNameField>] == null) {
                            UserList.Add(""); // Adding the empty string.Empty when the field value set to be null...
                        }
                        else {
                            UserList.Add(_Item[<EmployeeNameField>].ToString()); // else addnig the field value
                        }
                    }

                    // Here the Magic code.
                    int Count = AdUsersList.Count;
                    if (!(UserList.Count <= 0)) {
                        for (int inr = 0; inr < Count; inr++) {
                            // if Active Directory Users were not found to be in the UserList ArrayList then add those users into the RemainList ArrayList
                            if (!UserList.Contains(AdUsersList[inr]))
                                RemainList.Add(AdUsersList[inr].ToString());
                        }
                    }
                    else {
                        for (int inr = 0; inr < Count; inr++) {
                            RemainList.Add(AdUsersList[inr].ToString());
                        }
                    }
                }
                else {
                    int Count = AdUsersList.Count;
                    for (int inr = 0; inr < Count; inr++) {
                        RemainList.Add(AdUsersList[inr].ToString());
                    }
                }

                // Sorting the ArrayList if needed
                RemainList.Sort();

                // Binds the RemainList Users to the ddlRemainADUsers DropDownList         
                this.ddlRemainADUsers.DataSource = RemainList;
                this.ddlRemainADUsers.DataBind(); // Call a Simple DataBind()

                // Get the current value of the field.
                string currentValue = (string)this.ItemFieldValue;

                if (!string.IsNullOrEmpty(currentValue)) { // Checks or Validates the currentValue
                    this.ddlRemainADUsers.SelectedValue = currentValue;
                }
                else if (this.ddlRemainADUsers.Items.Count > 0) {
                    this.ddlRemainADUsers.SelectedIndex = 0;
                }

                // Add an Attributes for "onchange" event for the ddlRemainADUsers DropDownList
                this.ddlRemainADUsers.Attributes["onchange"] = "this.options[this.selectedIndex].value;";
                base.Controls.Add(ddlRemainADUsers);
            }         

            string text = null;
            object textObject = this.ItemFieldValue;

            if (textObject != null) {
                // ReBinds the textObject Value to the textbox for the View Mode
                text = (string)textObject;
            }

            if (text == null || text == string.Empty) {
                text = this.ddlRemainADUsers.SelectedValue;
            }

            //Filtering the ControlMode for field in both Dispform.aspx
            if (this.ControlMode == SPControlMode.Display) {
                lblADUser = new Label();
                lblADUser.Text = text.ToString();
                base.Controls.Add(lblADUser);
            }           
        }

        /// <summary>
        /// Updates the Field Value with from the ddlRemainADUsers.SelectedValue to the ItemFieldValue.Value
        /// from where we rebind the ItemFieldValue to the textObject Value
        /// </summary>
        public override void UpdateFieldValueInItem()
        {

            this.EnsureChildControls();
            try {
                this.Value = this.ddlRemainADUsers.SelectedValue;
                this.ItemFieldValue = this.Value;
            }
            catch {
                ;
            }
        }

        /// <summary>
        /// Render the xCode.GetADUser
        /// </summary>
        /// <param name="output"></param>
        protected override void Render(HtmlTextWriter output)
        {
            if (this.ControlMode == SPControlMode.Edit ||
                this.ControlMode == SPControlMode.New) {               
                this.ddlRemainADUsers.RenderControl(output);
            }
            if (this.ControlMode == SPControlMode.Display) {
                this.lblADUser.RenderControl(output);
            }
        }

}

might thing this helps a lot for the comparing as well as subtracting the Active Directory Users with the Desired List Column…
Cheers !!!
Happy Coding…

15
Sep
08

LightWeight Active Directory – Change User’s Password Webpart

AD Password Changer allows users to change their Active Directory password. AD Password Changer has a simple user interface and provides descriptive responses to users whose new passwords may not meet minimum requirements.
Here i have exposed the logical part of my code, instead not the complete solution pack… i would rather arrange for that in future as a downloadable code in *.zip format…

One of the most common functions to perform in Active Directory from a SharePoint application or C# ASP .NET application is resetting user passwords.
However, by following a few important logical webpart redesign, you can have your webpart easily resetting user passwords in Active Directory not more with rendering the controls and bind to the page control…

By remembering the security rules of .NET, Windows, and IIS, manipulating passwords can be a straight forward process. Always remember to enclose all Active Directory functions within a try catch block in order to handle errors.

namespace xCode.ChangeMyPassword
{

 [DefaultProperty("LabelLoggedOn"), ToolboxData("<{0}:ChangeMyPassword runat=server></{0}:ChangeMyPassword>"), XmlRoot(Namespace="xCode.ChangeMyPassword")]
 public class ChangeMyPassword : WebPart, IDesignTimeHtmlProvider
 {

       /// Reduced code for complete explanation
        private TextBox _txtNewPw;
        private TextBox _txtNewRPw;
        private TextBox _txtOldPw;

        /// <summary>
        ///  Method handles the Change Password button click event...
        /// </summary> 
        private void btnChangePw_Click(object sender, EventArgs e)
        {
            Label label;
            if (this._txtNewPw.Text.Length >= 0)
            {
                if (this._txtNewPw.Text.Equals(this._txtNewRPw.Text))
                {
                    DirectoryEntry entry;
                    string[] strArray = this.Context.User.Identity.Name.Split(new char[] { '\\' });
                    if (this.isLocalAccount())
                    {
                        try
                        {
       // Connect to Active Directory and get the DirectoryEntry object.
       // Note, ADPath is an Active Directory path pointing to a user.

                            entry = new DirectoryEntry("WinNT://" + strArray[0] + "/" + strArray[1], this.Context.User.Identity.Name, this._txtOldPw.Text, AuthenticationTypes.Secure);
                        }
                        catch (Exception exception1)
                        {
                            Exception ex1 = exception1;
                            label = this._lblError;
                            label.Text = label.Text + this.ex1.Message.ToString();
       return;
                        }
                        try
                        {
                            object objectValue = RuntimeHelpers.GetObjectValue(entry.Invoke("ChangePassword", new object[] { this._txtOldPw.Text, this._txtNewPw.Text }));
                        }
                        catch (Exception exception5)
                        {
                            Exception ex2 = exception5;
                            label = this._lblError;
                            label.Text = label.Text + this.ex2.Message.ToString();
       return;
                        }
                    }
                    else
                    {
                        try
                        {
                            string[] propertiesToLoad = new string[] { "sAMAccountName", "cn" };
                            DirectorySearcher searcher = new DirectorySearcher("(sAMAccountName=" + strArray[1] + ")", propertiesToLoad);
                            searcher.SearchRoot.Username = this.Context.User.Identity.Name;
                            searcher.SearchRoot.Password = this._txtOldPw.Text;

       // You would have created this which searches AD for the specified user
       // and returns its DirectoryEntry object or path. See here.
                            SearchResult result = searcher.FindOne();
                            if (result == null)
                            {
                                label = this._lblError;
                                label.Text = label.Text + "The User was not found in the Active Directory";
                            }
                            entry = new DirectoryEntry(result.Path, this.Context.User.Identity.Name, this._txtOldPw.Text);
                            entry.RefreshCache();
                        }
                        catch (Exception exception6)
                        {
                            Exception ex3 = exception6;
                            label = this._lblError;
                            label.Text = label.Text + this.ex3.Message.ToString();
                            return;
                        }
                        try
                        {
       // Impersonate a user with administrative rights.
       // Reset the password.

                            entry.Invoke("ChangePassword", new object[] { this._txtOldPw.Text, this._txtNewPw.Text });
                        }
                        catch (Exception exception7)
                        {
                            Exception ex4 = exception7;
                            label = this._lblError;
                            label.Text = label.Text  + this.ex4.Message.ToString();
                            return;
                        }
                    }
                    label = this._lblError;
                    label.Text = label.Text + this.SuccessMessage;
                }
                else
                {
                    label = this._lblError;
                    label.Text = label.Text + this.ErrorMessagePasswordMatch;
                }
            }
            else
            {
                label = this._lblError;
                label.Text = label.Text + "Password doesn't match requirements.";
            }
        }

 /// <summary>
 ///  Boolean method returns the Account of the User previliage as local or gobal...
 /// </summary> 
 /// <return>bool</return>
 private bool isLocalAccount()
        {
            return (this.Context.Server.MachineName.ToUpper() == this.Context.User.Identity.Name.Split(new char[] { '\\' })[0]);
        }
   }
}

Cheers !!!

Happy Coding…




Calendar

June 2012
M T W T F S S
« Feb    
 123
45678910
11121314151617
18192021222324
252627282930  

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 1 other follower


Follow

Get every new post delivered to your Inbox.