Solved

Retrieve active user from Active Directory using C#

Posted on 2011-02-24
7
538 Views
Last Modified: 2012-06-21
So far i change "DHAEST" code to modifed based on my need.

Class Library File

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.DirectoryServices;

namespace ActiveDir
{
    public class Employee
    {
        // instance variables 
        public String useraccountcontrol;
        //   ...
        // Constructors

        public String FullName()
        {

            return String.Format("{0} ", useraccountcontrol).Trim();
           
        }
        public static implicit operator String(Employee value)
        {
            return value.ToString();
        }

        public Employee()
        {
        }
    }

  

    public class ActiveDirSearch
    {
        public ActiveDirSearch()
        { }

        public Employee SearchUser()
        {

            Employee employee = new Employee();


            try
            {
             
                
               DirectoryEntry entry = new DirectoryEntry("GC://Test", "Test\\Test", "Ld@Test", AuthenticationTypes.Secure);


                
                System.DirectoryServices.DirectorySearcher search = new System.DirectoryServices.DirectorySearcher(entry);
                search.Filter = "(useraccountcontrol=" + "512" + ")";
                SearchResult result = search.FindOne();


                if (result != null)
                {

                    // user exists, cycle through LDAP fields (cn, telephonenumber etc.)

                    ResultPropertyCollection fields = result.Properties;

                    foreach (String ldapField in fields.PropertyNames)
                    {
                        // cycle through objects in each field e.g. group membership
                        // (for many fields there will only be one object such as name)                        
                        foreach (Object myCollection in fields[ldapField])
                        {
                           
                            if (ldapField == "cn")
                                employee.useraccountcontrol = myCollection.ToString();

                        }
                    }

                }

                else
                {
                    return null;
                }
            }

            catch (Exception e)
            {
                throw e;
            }

            return employee;
        }
    }
}

Open in new window


Am not yet tested this one but i have a doubt while return the output,bcoz am going to return bunch of active users.

Does this code will return the value of all the users ?
0
Comment
Question by:Sha1395
[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
  • 4
  • 2
7 Comments
 
LVL 11

Expert Comment

by:azarc3
ID: 34968970
As written you're only going to get one user.
0
 

Author Comment

by:Sha1395
ID: 34969053
Exactly that's what i think so,so i have to use "Find All()" right ?
0
 
LVL 33

Accepted Solution

by:
Todd Gerbert earned 500 total points
ID: 34971406
I think you're wanting something like this (note that UserAccountControl is a set of flags, and I believe simply specifying 512 as a search parameter won't quite work correctly):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.DirectoryServices;

class Program
{
	static void Main()
	{
		DirectorySearcher searcher = new DirectorySearcher();
		searcher.Filter = "(&(objectCategory=person)(!(userAccountControl:1.2.840.113556.1.4.803:=2)))";

		Console.WriteLine("Active users:");

		foreach (SearchResult result in searcher.FindAll())
			Console.WriteLine(result.GetDirectoryEntry().Properties["sAMAccountName"].Value);

		Console.ReadKey();
	}
}

Open in new window

0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

Author Comment

by:Sha1395
ID: 34975018
Hi,

If you could explain little bit about this will help me to understand

(userAccountControl:1.2.840.113556.1.4.803:=2)))


thanks
0
 

Author Comment

by:Sha1395
ID: 34975298
No i got it thru MSDN article ,please ignore my previous question.

How can i return the result as an object and am going to call from Windows Application thru button click.
0
 
LVL 33

Expert Comment

by:Todd Gerbert
ID: 34979783
Put the directory searching code in it's own method, call that method from your button click event handler.  Easy thing to do would be to simply return the SearchResultCollection:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.DirectoryServices;

public partial class Form1 : Form
{
	public Form1()
	{
		InitializeComponent();
	}

	private void button1_Click(object sender, EventArgs e)
	{
		SearchResultCollection activeUsers = GetActiveUsers();

		activeUserseTextBox.Clear();

		if (activeUsers == null)
			MessageBox.Show("No Active Users Found");
		else
		{
			foreach (SearchResult user in activeUsers)
			{
				activeUserseTextBox.AppendText(user.GetDirectoryEntry().Properties["sAMAccountName"].Value.ToString() + "\r\n");
			}
		}
	}

	private SearchResultCollection GetActiveUsers()
	{
		SearchResultCollection searchResults = null;

		using (DirectorySearcher searcher = new DirectorySearcher())
		{
			searcher.Filter = "(&(objectCategory=person)(sAMAccountName=*)(!(userAccountControl:1.2.840.113556.1.4.803:=2)))";

			searchResults = searcher.FindAll();
		}

		if (searchResults.Count > 0)
			return searchResults;
		else
			return null;
	}
}

Open in new window



Or, you can return an array of strings that has the user names:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.DirectoryServices;

public partial class Form1 : Form
{
	public Form1()
	{
		InitializeComponent();
	}

	private void button1_Click(object sender, EventArgs e)
	{
		string[] activeUsers = GetActiveUsers();

		activeUserseTextBox.Clear();

		if (activeUsers == null)
			MessageBox.Show("No Active Users Found");
		else
		{
			foreach (string user in activeUsers)
				activeUserseTextBox.AppendText(user + Environment.NewLine);
		}
	}

	private string[] GetActiveUsers()
	{
		string[] userList = null;

		using (DirectorySearcher searcher = new DirectorySearcher())
		{
			searcher.Filter = "(&(objectCategory=person)(sAMAccountName=*)(!(userAccountControl:1.2.840.113556.1.4.803:=2)))";

			SearchResultCollection searchResults = searcher.FindAll();

			if (searchResults.Count > 0)
			{
				userList = new string[searchResults.Count];
				for (int i = 0; i < userList.Length; i++)
					userList[i] = searchResults[i].GetDirectoryEntry().Properties["sAMAccountName"].Value.ToString();
			}
		}

		return userList;

	}
}

Open in new window

0
 

Author Comment

by:Sha1395
ID: 34983898
Thanks a lot tgerbert.
0

Featured Post

Salesforce Made Easy to Use

On-screen guidance at the moment of need enables you & your employees to focus on the core, you can now boost your adoption rates swiftly and simply with one easy tool.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
.NET: How to pass typed serialize using JavaScriptSerializer ==> Deserialize in C# 6 61
Selenium and Xpath 4 70
Put File 6 38
Pdf not loading 2 41
Introduction Although it is an old technology, serial ports are still being used by many hardware manufacturers. If you develop applications in C#, Microsoft .NET framework has SerialPort class to communicate with the serial ports.  I needed to…
We all know that functional code is the leg that any good program stands on when it comes right down to it, however, if your program lacks a good user interface your product may not have the appeal needed to keep your customers happy. This issue can…
In a recent question (https://www.experts-exchange.com/questions/29004105/Run-AutoHotkey-script-directly-from-Notepad.html) here at Experts Exchange, a member asked how to run an AutoHotkey script (.AHK) directly from Notepad++ (aka NPP). This video…
I've attached the XLSM Excel spreadsheet I used in the video and also text files containing the macros used below. https://filedb.experts-exchange.com/incoming/2017/03_w12/1151775/Permutations.txt https://filedb.experts-exchange.com/incoming/201…

752 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