Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

Query AD for Group Membership

Posted on 2013-05-16
1
Medium Priority
?
215 Views
Last Modified: 2013-05-16
I am trying to query AD for the groups of users.  For some reason, my group count is coming back as the true count less 1 (ie I can see the user is a member of 6 groups, but my count is coming back as only 5).

Anyone see my issue here?

using System;
using System.Collections.Generic;
using System.Text;
using System.DirectoryServices;
using System.Collections.ObjectModel;
using System.IO;
using System.Data;
using Microsoft.SqlServer.Server;
using System.Data.SqlTypes;
using System.Data.SqlClient;
using System.Collections.Specialized;
public class LDAPGroupChecks
{
    [Microsoft.SqlServer.Server.SqlProcedure]
    public static int LDAPGroupCheck(string str_Domain, string str_UserName, string str_Group)
    {
        // variable declaration
        string str_ErrorDescription = "";                               // returned error description
        string str_LoginName = str_Domain + @"\" + str_UserName; // build our full login name
        StringBuilder stb_GroupList = new StringBuilder();              // holds a list of all groups this user is a member of
        int int_ReturnValue = 0;                                // default our return value to 0


        // attempt to grab the details for this account
        try
        {
            // Bind to the native AdsObject			
            DirectoryEntry ptr_DirectoryEntry = new DirectoryEntry("LDAP://" + str_Domain);
            Object ptr_Object = ptr_DirectoryEntry.NativeObject;
            DirectorySearcher ptr_DirectorySearcher = new DirectorySearcher(ptr_DirectoryEntry);

            // generate our LDAP search parameters
            ptr_DirectorySearcher.Filter = "(SAMAccountName=" + str_UserName + ")";
            ptr_DirectorySearcher.PropertiesToLoad.Add("memberof");

            // run the search and grab our result
            SearchResult ptr_SearchResult = ptr_DirectorySearcher.FindOne();


            // check our result
            if (null == ptr_SearchResult)
            {
                // if the search failed return false because the account doesn't exist
                int_ReturnValue = 0;
                SqlContext.Pipe.Send(int_ReturnValue.ToString());

            

                return int_ReturnValue;
            }

            // populate our variables with the user information from AD
            int int_GroupCount = ptr_SearchResult.Properties["memberOf"].Count;

            

            // loop through all the groups and append to our string
            for (int int_Counter = 0; int_Counter < int_GroupCount ; int_Counter++)
            {
                stb_GroupList.Append((string)ptr_SearchResult.Properties["memberOf"][int_Counter]);
                stb_GroupList.Append("|");
                

            }
            stb_GroupList.Length -= 1; //remove the last '|' symbol


            

            // figure out if our given group is in the group list
            if (stb_GroupList.ToString().ToLower().Contains("cn=" + str_Group.ToLower() + ","))
                int_ReturnValue = 1;
            else
                int_ReturnValue = 0;
        }
        catch (Exception ptr_Exception)
        {


            /*********************************************************************/

            string fError = "f:\\production\\DotNetAssemblies\\udb_PasswordKeeper\\Error.txt";

            using (FileStream fs2 = new FileStream(fError, FileMode.Append))
            {
                Byte[] info = new UTF8Encoding(true).GetBytes(ptr_Exception.ToString());
                // Add some information to the file.
                fs2.Write(info, 0, info.Length);
                fs2.Close();

            }

            /*********************************************************************/


            int_ReturnValue = 3;
            str_ErrorDescription = "Error accessing user information. " + ptr_Exception.Message;
            return int_ReturnValue;
        }
     
        // return our status
        SqlContext.Pipe.Send(stb_GroupList.ToString());
        return int_ReturnValue;
    }
}

Open in new window

0
Comment
Question by:gdspeare
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
1 Comment
 

Accepted Solution

by:
gdspeare earned 0 total points
ID: 39173088
The issue is that the primary group assigned to the user is not pulled back by default.

http://social.msdn.microsoft.com/Forums/en-US/Vsexpressvb/thread/88656999-bf53-481b-83d0-ed6f7d1cba16
0

Featured Post

How to Create Failover DNS Record Sets in Route 53

Route 53 has the ability to easily configure DNS record sets specifically for failover scenarios. These failover record sets can be configured to failover to full-blown deployments in other regions or to a static HTML page that informs your customers of the issue.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In my previous article (http://www.experts-exchange.com/Programming/Languages/.NET/.NET_Framework_3.x/A_4362-Serialization-in-NET-1.html) we saw the basics of serialization and how types/objects can be serialized to Binary format. In this blog we wi…
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
Add bar graphs to Access queries using Unicode block characters. Graphs appear on every record in the color you want. Give life to numbers. Hopes this gives you ideas on visualizing your data in new ways ~ Create a calculated field in a query: …
In response to a need for security and privacy, and to continue fostering an environment members can turn to for support, solutions, and education, Experts Exchange has created anonymous question capabilities. This new feature is available to our Pr…

721 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question