Tuesday, 28 April 2015

Active Directory User Details in JSON Format

In the past I have posted series of Active Directory reading and writing operations. Below is a sample query that you can use to get an idea on how to read from an Active Directory group and output into JSON format. I used Group Principal to read from Active Directory Group. I have posted my extended class in one of my previous post which I reuse here as Extended Principal User to read Tel, Fax etc… Otherwise I use principal user to read from active directory. I have created a data table with the column names which I want to print and added Active Directory Group members into this data table.


To create JSON output I used JavaScriptSerializer. I created a new List type Dictionary and added Active Directory members details along with the header. To write into txt file I have used “WriteAllText” with Replace method to replace Unicode character “\u0026”  to “&”. Because any character may be encoded using the unicode escape in JSON and any valid JSON parsing library must be able to interpret those escapes. There are many workarounds available including regex. I have used Replace method in this example.

using System.Runtime.Serialization.Json;
using System.Web.Script.Serialization;
using Newtonsoft.Json.Linq;

       public void Read_ActiveDirectory(string filelocation,string ADgroupname)
        {
            string filepath = filelocation;
            string grpname = ADgroupname;
            ctx = new PrincipalContext(ContextType.Domain);
            group = GroupPrincipal.FindByIdentity(ctx, IdentityType.Name, grpname);
            exprUser = new ExtendedPrincipalUser(ctx);
            prinUser = new UserPrincipal(ctx);
            srch = new PrincipalSearcher(prinUser);

            DataSet dsADCloud = new DataSet("AD");
            DataTable dtUsers = new DataTable("Users");
            dtUsers.Columns.Add("DisplayName");
            dtUsers.Columns.Add("Surname");
            dtUsers.Columns.Add("First_Name");
            dtUsers.Columns.Add("JobTitle");
            dtUsers.Columns.Add("Position");
            dtUsers.Columns.Add("Phone");
            dtUsers.Columns.Add("Mobile");
            dtUsers.Columns.Add("EmailAddress");
            dtUsers.Columns.Add("Department");
            dtUsers.Constraints.Add("UniqueUserId", dtUsers.Columns["UserName"], true);

            if (group != null)
            {
                foreach (Principal p in group.GetMembers(true))
                {
                    prinUser = UserPrincipal.FindByIdentity(ctx, IdentityType.SamAccountName, p.SamAccountName);
                    exprUser = ExtendedPrincipalUser.FindByIdentity(ctx, IdentityType.SamAccountName, p.SamAccountName);
                    DataRow drUser = dtUsers.NewRow();
                    if (prinUser.Enabled != false)
                    {
                        try { drUser["DisplayName"] = prinUser.DisplayName.ToString().Trim();  }
                        catch { drUser["DisplayName"] = null; }
                        try { drUser["Surname"] = prinUser.Surname.ToString().Trim();  }
                        catch { drUser["Surname"] = null; }
                        try { drUser["First_Name"] = prinUser.GivenName.ToString().Trim(); }
                        catch { drUser["First_Name"] = null; }
                        try { drUser["JobTitle"] = prinUser.Description.ToString().Trim(); }
                        catch { drUser["JobTitle"] = null; }
                        try { drUser["Position"] = exprUser.jobTitle.ToString().Trim(); }
                        catch { drUser["Position"] = null; }
                        try {drUser["Phone"] = exprUser.VoiceTelephoneNumber.Trim();}
                        catch { drUser["Phone"] = null; }
                        try { drUser["Mobile"] =  exprUser.mobile.ToString().Trim() ; }
                        catch { drUser["Mobile"] = null; }
                        try { drUser["EmailAddress"] = prinUser.EmailAddress.ToString().Trim(); }
                        catch { drUser["EmailAddress"] = null; }
                        try { drUser["Department"] = exprUser.department.ToString().Trim(); }
                        catch { drUser["Department"] = null; }

                        dtUsers.Rows.Add(drUser);
                    }
                }
            }
            dsADCloud.Tables.Add(dtUsers);

            string strExcelPath = System.Configuration.ConfigurationManager.ConnectionStrings[filepath].ConnectionString;
            System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();

            List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();    
                    Dictionary<string, object> row;


                    foreach (DataRow dr in dtUsers.Rows)
                    {
                        row = new Dictionary<string, object>();
                        foreach (DataColumn col in dtUsers.Columns)
                        {
                            row.Add(col.ColumnName, dr[col]);
                        }
                        rows.Add(row);
                    }

                    System.IO.File.WriteAllText(strExcelPath, serializer.Serialize(rows).ToString().Replace(@"\u0026", @"&"));
        }



Sample Output:

[{
"DisplayName":"ABC DEF","Surname":"DEF","First_Name":"ABC","JobTitle":"Manager","Position":"Manager","Phone":"123456789","Mobile":"147258369","EmailAddress":"ABCDEF@sampleemail.com","Department":"TEST DEPARTMENT 1"}, {"DisplayName":"GHI JKL","Surname":"JKL","First_Name":"GHI","JobTitle":"Coordinator","Position":"Coordinator","Phone":"012345678","Mobile":null,"EmailAddress":"GHI.JKL@sampleemail.com","Department":"TEST DEPARTMENT 2"}]

No comments:

Post a Comment