Welcome

Hello, Welcome to my blog. If you like feel free to refer others

Friday 20 January 2012

Search LDAP and Database users prefixtext using AutoCompleteExtender

I will describe this step by step:
Step 1:
Below mentioned function which will search distinct users from LDAP as well as from Database. First of all to use LDAP we need reference of these 3 dll's. So add the reference of the 3 dll's in the project.

1) System.DirectoryServices
2) System.DirectoryServices.Protocols
3) System.DirectoryServices.AccountManagement

Function: This function will return a List of ResourceBE class, so need to create the ResourceBE class.

public static List<ResourceBE> getSerchedLDAPUsers(string domainName, string strLdapPath, string prefixText)
        {
            try
            {
                bool resourceNameValue=false;
                bool resourceEmailValue = false;
                string ResourceEmail=string.Empty;
                string ResourceFirstName=string.Empty;
                string ResourceLastName = string.Empty;

                DataTable dtLDAPUsers = new DataTable();
                DataRow dr = null;
                dtLDAPUsers.Columns.Add(new DataColumn("ResourceName", typeof(string)));
                dtLDAPUsers.Columns.Add(new DataColumn("Email", typeof(string)));

                List<ResourceBE> lstResource = new List<ResourceBE>();               
                DirectoryEntry directory = new DirectoryEntry(strLdapPath);

                
                //Set the filter condition just like SQL
                string filter = "(&(samAccountName=" + prefixText + "*)(objectClass=person))";

                //Define the properties to select from LDAP
                string[] strCats = { "samAccountName", "mail", "givenName", "sn" };
               
                DirectorySearcher dirComp = new DirectorySearcher(directory, filter, strCats, System.DirectoryServices.SearchScope.Subtree);
                SearchResultCollection results = dirComp.FindAll();
               
                foreach (SearchResult result in results)
                {
                    foreach (DictionaryEntry prop in result.Properties)
                    {
                        System.Collections.IEnumerable propsEnum = prop.Value as System.Collections.IEnumerable;
                        if (prop.Key.Equals("givenname"))
                        {
                            foreach (object individualValue in propsEnum)
                            {
                                ResourceFirstName = individualValue.ToString();
                                resourceNameValue = true;
                            }
                        }

                        if (prop.Key.Equals("sn"))
                        {
                            foreach (object individualValue in propsEnum)
                            {
                                ResourceLastName = individualValue.ToString();                               
                            }
                        }

                        if (prop.Key.Equals("mail"))
                        {
                            foreach (object individualValue in propsEnum)
                            {
                                ResourceEmail = individualValue.ToString();
                                resourceEmailValue = true;
                            }
                        }
                    }

                    if (resourceEmailValue && resourceNameValue)
                    {
                        dr = dtLDAPUsers.NewRow();
                        dr["ResourceName"] = ResourceFirstName + " " + ResourceLastName;
                        dr["Email"] = ResourceEmail;

                        dtLDAPUsers.Rows.Add(dr);
                    }
                }

                //Add DataBase User with LDAPUsers
                List<ResourceBE> lstDataBaseResource = new List<ResourceBE>();
                lstDataBaseResource = resourceManager.GetResourcesByResourceNamePrefix(prefixText);
                foreach (var item in lstDataBaseResource)
                {
                    dr = dtLDAPUsers.NewRow();
                    dr["ResourceName"] = item.ResourceName;
                    dr["Email"] = item.Email;

                    dtLDAPUsers.Rows.Add(dr);
                }

                //To get the distinct users

                string[] cols = { "ResourceName", "Email" };
                dtLDAPUsers = dtLDAPUsers.DefaultView.ToTable(true, cols);

                for (int i = 0; i < dtLDAPUsers.Rows.Count; i++)
                {
                    ResourceBE rbe = new ResourceBE();
                    rbe.ResourceName = dtLDAPUsers.Rows[i]["ResourceName"].ToString();
                    rbe.Email = dtLDAPUsers.Rows[i]["Email"].ToString();
                    lstResource.Add(rbe);
                }

               
                return lstResource;
            }
            catch (System.DirectoryServices.DirectoryServicesCOMException ex)
            {
                throw ex;
            }
            catch (Exception ex)
            {
                throw new Exception("Error while getting the users. <br />" + ex.Message, ex);
            }

        }


Step2 : Add the CSS in the page


<style type="text/css">
       .AutoExtender
       {
           position: relative;                   
           font-family: Verdana, Helvetica, sans-serif;
           font-size: .8em;
           font-weight: normal;
           border: solid 1px #006699;
           line-height: 20px;
           width: 100%;
           padding: 15px;
           background-color: White;
           margin-left: 0px;
           height:200px;          
           overflow-y:scroll;
       }
       .AutoExtenderList
       {
           vertical-align: bottom;
           border-bottom: dotted 1px #006699;
           cursor: pointer;
           color: Maroon;
           width: 100%;          
       }
       .AutoExtenderHighlight
       {
           color: White;
           background-color: #006699;
           cursor: pointer;
           width: 100%;
       }           
   </style>



Step 3 : 

Add the extender to particular textbox. To add extender you need to register AjaxControlToolkit on the page directive. It will be look like this : 
Syntax will be: <%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>


<asp:TextBox ID="txtNameSearch" runat="server" CssClass="textbox" ToolTip="Please enter atleast 3 character to autocomplete" Width="95%"></asp:TextBox>

<asp:AutoCompleteExtender ServiceMethod="SearchCustomers"
        MinimumPrefixLength="3" CompletionInterval="20" EnableCaching="false" CompletionSetCount="10"
        TargetControlID="txtNameSearch" ID="AutoCompleteExtender1" runat="server" FirstRowSelected="false" CompletionListCssClass="AutoExtender" CompletionListItemCssClass="AutoExtenderList"
                                CompletionListHighlightedItemCssClass="AutoExtenderHighlight" >



Note: Here I have added ServiceMethod = "SearchCustomers" so next step will be you need to create a webmethod on the page with same name.


Step 4 : 
Create a webmethod with same name which mentioned above and parameter should be exactly same and method should be static :


        [System.Web.Script.Services.ScriptMethod()]
        [System.Web.Services.WebMethod]
        public static List<string> SearchCustomers(string prefixText, int count)
        {
            List<ResourceBE> lstLDAPResource = new List<ResourceBE>();
            

            //Here you need to pass domain and path of LDAP
            lstLDAPResource = LDAPManager.getSerchedLDAPUsers(LDAPManager.GetLDAPDomain, LDAPManager.GetLDAPPath, prefixText);

            //return lstLDAPResource;
            List<string> customers = new List<string>();
            foreach (var item in lstLDAPResource)
            {
                customers.Add(item.ResourceName + " (" + item.Email + ")");
            }

            return customers;
        }





Hope this will help you.... :)




Happy Learning............

No comments:

Post a Comment