C# and Sun One Directory Server : Retrieve Domain Group Members

If you have already worked on the Sun One Directory Server product, you might already know that SunONE Directory Server is a robust, scalable server designed to manage an enterprise-wide directory of users and resources. This is something like the Active Directory Microsoft has built for windows.

When working with the Sun One directory using C# & the .Net 2.0/Above, most of the developers find it difficult to get the Members of a group within a domain programmatically. This post should help few of those developers to resolve the problem. You can easily query the directory to get all the members of a group using c#.

Now, how do we get the members?
No more hitting the bush. Lets write code. Create a console/web/windows application using Visual Studio. In my case,  have used a console application for making the things quick.

First, create a entity which can hold the details of a group user like Id, Full Name of the user, email id of user, path where he resides. Create a class CLDAPUser with the below code.

class CLDAPUser
        private string m_sUId = string.Empty;
        private string m_sFullName = string.Empty;
        private string m_sEmailId = string.Empty;
        private string m_sPath = string.Empty;

        public string Uid
            { return m_sUId; }
            { m_sUId = value;}

        public string FullName
            {return m_sFullName;}
            {m_sFullName = value;}

        public string EmailId
            {return m_sEmailId;}
            {m_sEmailId = value;}

        public string Path
            {return m_sPath;}
            {m_sPath = value;}

Now, let us write the function to retrieve the Sun One Users of a Group. I have added comments inside which gives the explanation

//Include the below namespaces.
using System.Collections.Generic;
using System.DirectoryServices;

private static List<CLDAPUser> SunOne_GetGroupMembers(string i_sGroup, string i_sADsPath,  string i_sDomainName, string i_sPath)
            string sFName = string.Empty;
            string sLName = string.Empty;
            string sFullName = string.Empty;
            string sMail = string.Empty;
            string sADsPath = string.Empty;
            string sPath = string.Empty;

            List<CLDAPUser> objLdapUserList = new List<CLDAPUser>();
                DirectoryEntry oRoot = new DirectoryEntry();
                oRoot.Path = i_sADsPath;
                oRoot.AuthenticationType = AuthenticationTypes.ServerBind;
                oRoot.Username = m_sUserName;
                oRoot.Password = m_sPassword;

                sADsPath = i_sADsPath.Substring(0, i_sADsPath.LastIndexOfAny("/".ToCharArray()));
                DirectorySearcher oDSSearcher = new DirectorySearcher(oRoot);

                //The very important step. CN = Group Name & uniqueMember=* is a filter which returns all members from Sun One
                oDSSearcher.Filter = "(&(CN=" + i_sGroup + ")(uniqueMember=*))";

                SearchResultCollection oSRC = oDSSearcher.FindAll();
                foreach (SearchResult oSResult in oSRC)
                    ResultPropertyCollection resultPropColl = oSResult.Properties;

                    //Loop to iterate for each sun one user of the group and get the details further
                    foreach (object oMemberColl in resultPropColl["uniqueMember"])
                        DirectoryEntry ogpMemberEntry = new DirectoryEntry(sADsPath + "/" + oMemberColl.ToString());
                        ogpMemberEntry.AuthenticationType = AuthenticationTypes.ServerBind;
                        ogpMemberEntry.Username = m_sUserName;
                        ogpMemberEntry.Password = m_sPassword;

                        System.DirectoryServices.PropertyCollection oUserProps = ogpMemberEntry.Properties;
                        string sID = oUserProps["uid"].Value.ToString();

                        if (sID != "")
                                //givenname is the property name to get the First Name of Sun One User
                                sFName = oUserProps["givenname"].Value.ToString();
                            catch (Exception ex) { /*Do Some Error Logging*/ sFName = "N/A"; }

                                //sn is the property name to get the Last Name of Sun One User
                                sLName = oUserProps["sn"].Value.ToString();

                            catch (Exception ex) { /*Do Some Error Logging*/ sLName = "N/A"; }

                            sFullName = sFName + " " + sLName;

                                //mail is the property name to get the email address of Sun One User
                                sMail = oUserProps["mail"].Value.ToString();
                            catch (Exception ex) { /*Do Some Error Logging*/ sMail = "N/A"; }

                                sPath = oMemberColl.ToString();
                            catch (Exception ex) { /*Do Some Error Logging*/ sPath = "N/A"; }

                            //Store the details
                            CLDAPUser objLdapUser = new CLDAPUser();
                            objLdapUser.Uid = sID;
                            objLdapUser.FullName = sFullName;
                            objLdapUser.EmailId = sMail;
                            objLdapUser.Path = sPath;

                            //Add this user detail to the list

            catch (Exception ex) { /*Do Some Error Logging*/}

            //The List contains all the users/members of the group!
            return objLdapUserList;

Now, we need to call the above function with required parameters. Here we go. Write it in Main() of your console application

    //This is the Group for which we need to Retrieve the Users from Sun One
     string sGroup = "Accounting Managers";

     //Port the Sun One Server is Listening at
     int iPort = 30291;

      string sServername = "";

      //Domain String 
      string sDomainstr = "dc=yoursun1,dc=local";

      //Create LDAP Path based on above credentials
      string sAdsPath = "LDAP://" + sServername + ":" + iPort + "/" + sDomainstr;

      //I dont have a user name password required to connect to Sun One so let me make it null.
       m_sUserName = null;
       m_sPassword = null;

       //Create a list to Hold Sun One Users
       List<CLDAPUser> objLdapUserList = new List<CLDAPUser>();
       //Finally, Get the Sun One users for the Group by calling the function
       objLdapUserList = SunOne_GetGroupMembers(sGroup, sAdsPath,  sDomainstr, sDomainstr);

And thats it!!, pass any Group name and you get the users within it. Easy. Isnt it?

Lets do programming together. You can follow me on twitter @MSGuyTweets or find me on Facebook at Facebook.com/MysoreGuy

Popular posts from this blog

Facebook Javascript API : Feed and Share Dialog for Beginners

Real time Push Notifications with SignalR & PNotify (Pines Notify)

What's new and expected in .NET Framework 4.5