Monday, December 06, 2010

SharePoint-Active Directory Synchronize


Please do not follow the logic that retrieving user details from the Active Directory mentioned here, please visit my TechNet article for alternate approaches

Last week,I prepared the small SharePoint utility to retrieving the Active Directory users and synchronize with SharePoint List.



public string LDAPUsers()
        {
            string listD = "";
            string strResult = "";
            string strRes = "";
            DirectoryEntry entry = new DirectoryEntry("LDAP://domainName", "userid", "pAsSwrd");
            DirectorySearcher mySearcher = new DirectorySearcher(entry);
            mySearcher.Filter = "((objectCategory=Person))";

            foreach (SearchResult resEnt in mySearcher.FindAll())
            {
                listD = listD + resEnt.GetDirectoryEntry().Name + ",";


            }
            string[] test = listD.Split('=');
            for (int i = 0; i < test.Length; i++)
            {
                strResult = strResult + test[i].ToString();
            }

            string[] test1 = strResult.Split(',');
            for (int j = 0; j < test1.Length; j++)
            {
                strRes = strRes + test1[j] + ",";
            }
            return strRes.Replace("CN", ""); ;
        }
Below code pushing the string array values in to SharePoint List.
SPSite site = new SPSite("http://moss:4100");
        SPWeb web = site.OpenWeb();
        SPList list = web.Lists["LDAP User"];
        string[] names = LDAPUsers().Split(',');
        for (int j = 0; j < names.Length; j++)
        {
            SPListItem item = list.Items.Add();
            web.AllowUnsafeUpdates = true;
            item["Title"] = names[j].ToString();
            web.AllowUnsafeUpdates = true;
            item.Update();
            web.AllowUnsafeUpdates = false;
        }