Blue Theme Orange Theme Green Theme Red Theme
 
Nevron Chart
Home | Forums | Videos | Advertise | Certifications | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
6 Months Free & No Setup Fees ASP.NET Hosting!
Search :       Advanced Search »
Home » Active Directory C# » Accessing the Active Directory from Microsoft .NET

Accessing the Active Directory from Microsoft .NET

This article is intended to explain the architecture design of one application querying information to Microsoft Active Directory. Microsoft Active Directory is a directory service that provides the foundation for distributed networks built on Windows.

Author Rank :
Page Views : 59385
Downloads : 0
Rating :
 Rate it
Level : Advanced
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
 
Discover the top 5 tips for understanding .NET Interop
Become a Sponsor
Team Foundation Server Hosting
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 

Introduction:

Some days ago, I saw in the CSharpCorner community's forum one question about how to access the Active Directory (AD) from Microsoft.NET. So, this article is intended to explain the architecture design of one application querying information to AD.

Microsoft Active Directory is a directory service that provides the foundation for distributed networks built on Windows. The Active Directory APIs provide access to the data stored in this directory. It is a programming model very easy to understand and use.

Active Directory Architecture:

The directory system agent (DSA) is the process that provides access to the store. The store is the physical store of directory information located on a hard disk. Clients access the directory using one of the following mechanisms supported by the DSA:

  • LDAP clients connect to the DSA using the LDAP protocol. LDAP is an acronym for Lightweight Directory Access Protocol. Active Directory supports LDAP 3.0, defined by RFC 2251, and LDAP 2.0, defined by RFC 1777. 

  • MAPI clients such as Microsoft Exchange connect to the DSA using the MAPI remote procedure call interface. 

  • Windows clients that use a previous version of Windows NT connect to the DSA using the Security Account Manager (SAM) interface. 

  • Active Directory DSA's connect to each other to perform replication using a proprietary remote procedure call interface.

Active Directory data model is derived from the X.500 data model. The directory holds objects that represent things of various sorts, described by attributes. The universe of objects that can be stored in the directory is defined in the schema. For each object class, the schema defines what attributes an instance of the class must have, what additional attributes it may have, and what object class can be a parent of the current object class.

Active Directory schema is implemented as a set of object class instances stored in the directory. This is very different than many directories that have a schema but store it as a text file read at startup. Storing the schema in the directory has many advantages. For example, user applications can read it to discover what objects and properties are available.

Active Directory can consist of many partitions or naming contexts. The distinguished name (DN) of an object includes enough information to locate a replica of the partition that holds the object. Many times however, the user or application does not know the DN of the target object or which partition might contain the object. The global catalog (GC) allows users and applications to find objects in an Active Directory domain tree, given one or more attributes of the target object. The global catalog contains a partial replica of every naming context in the directory. It contains the schema and configuration naming contexts as well. This means the GC holds a replica of every object in Active Directory but with only a small number of their attributes.

The global catalog is built automatically by Active Directory replication system. The replication topology for the global catalog is generated automatically. The properties replicated into the global catalog include a base set defined by Microsoft. Administrators can specify additional properties to meet the needs of their installation.

Interfaces for accessing the Active Directory:

  1. LDPA: The Lightweight Directory Access Protocol (LDAP) is a directory service protocol that runs on a layer above the TCP/IP stack, and provides a mechanism for connecting to, searching, and modifying Internet directories. The LDAP directory service is based on a client-server model. The function of LDAP is to allow access to an existing directory. The data model (data and namespace) of LDAP is similar to that of the X.500 OSI directory service, but with lower resource requirements due to its streamlined features. The associated LDAP API simplifies writing Internet directory service applications.

  2. ADSI: Active Directory Service Interfaces (ADSI) is a set of COM interfaces used to access the capabilities of directory services from different network providers in a distributed computing environment, to present a single set of directory service interfaces for managing network resources. Administrators and developers can use ADSI services to enumerate and manage the resources in a directory service, regardless of the network environment that contains the resource.

  3. System.DirectoryServices: System.DirectoryServices is a namespace in the .NET Framework that provides simple programming access to LDAP directories such as Active Directory. System.DirectoryServices is built on the Active Directory Service Interfaces (ADSI) API.

Using System.DirectoryServices namespace:

This article will emphasize in the benefits of using the namespace System.DirectoryServices, such as:

  • Designed completely within common language runtime parameters. System.DirectoryServices leverages common language runtime features, such as garbage collection, custom indexer, and dictionaries (hashtables). It also offers other common language runtime features such as automatic memory management, efficient deployment, an object-oriented framework, evidence-based security and exception handling. 

  • Simple to use. Although ADSI scripting was effective for many tasks, C++ applications for ADSI are sometimes difficult to develop. System.DirectoryServices implements some basic ADSI tasks to enable more efficient and effective application development.

System administrators can use System.DirectoryServices to automate tasks to manage network resources in the directory, such as users and computers and also to build applications that search, create, or modify objects in a directory.

You can develop a lot of business objects for accessing the Active Directory, leveraging any application which needs the platform as its main database and for publishing objects in enterprise network.

In listing 1, it's illustrated an example of the definition of a business object whose behavior is interacting with the AD and change the password for a particular user. The contract is specified in the IADPasswdManager interface and the implementation resides in the ADPasswdManager class.

As you can see in the code the AD is Transaction Processing System, the operation runs atomically as logic unit of work, and if everything is OK, you commit the changes otherwise roll back to the previous consistent state. See the method CommitChanges in highlighted silver.

Listing 1:

using System;

using System.DirectoryServices;

 

namespace OLAActiveDirectory.Management

{

    public interface IADPasswdManager

    {

        void ChangePassword(IADUser objUser, string strOldPasswd, string strNewPasswd);

        void SetPassword(IADUser objUser, string strPasswd);

    }

    public class ADPasswdManager : IADPasswdManager

    {

        public ADPasswdManager()

        {

        }

        public void SetPassword(IADUser objUser, string strPasswd)

        {

            DirectoryEntry objLoginEntry = objUser.DirectoryEntry;

            if (objLoginEntry != null)

            {

                objLoginEntry.Invoke("SetPassword", new object[] { strPasswd });

                objLoginEntry.CommitChanges();

            }

        }

        public void ChangePassword(IADUser objUser, string strOldPasswd, string strNewPasswd)

        {

            DirectoryEntry objLoginEntry = objUser.DirectoryEntry;

            if (objLoginEntry != null)

            {

                objLoginEntry.Invoke("ChangePassword", new object[] { strOldPasswd, strNewPasswd });

                objLoginEntry.CommitChanges();

            }

        }

    }
}

Then, a business entity must be defined to represent the users in the directory. It holds the information of a particular user in the directory knowing its Distinguished Name (DN). It's defined an interface IADUser and the implementation is realized in the class ADUser as shown in the Listing 2.

Listing 2:

using System;

using System.DirectoryServices;

using System.Collections;

 

namespace OLAActiveDirectory.Management

{

    public interface IADUser

    {

        DirectoryEntry DirectoryEntry { get;}

        bool IsUser { get;}

        PropertyValueCollection this[string strKey] { get;}

    }

 

    public class ADUser : IADUser

    {

        private readonly DirectoryEntry m_objUserEntry;

 

        public ADUser(string strLogin, string strRootPath)

        {

            DirectoryEntry objRootEntry = new DirectoryEntry(strRootPath);

            DirectorySearcher objADSearcher = new DirectorySearcher(objRootEntry);

 

            objADSearcher.Filter = "(&(objectClass=user)(anr=" + strLogin + "))";

            SearchResult objResult = objADSearcher.FindOne();

 

            this.m_objUserEntry = (objResult != null) ? objResult.GetDirectoryEntry() : null;

        }

        public DirectoryEntry DirectoryEntry

        {

            get

            {

                return this.m_objUserEntry;

            }

        }

        public PropertyValueCollection this[string strKey]

        {

            get

            {

                return this.m_objUserEntry.Properties[strKey];

            }

        }

        public bool IsUser

        {

            get

            {

                return this.m_objUserEntry != null;

            }

        }

    }
}

And finally, we define the helper class ADUserInfoShower and its underlying interface IADUserInfoShower whose role is to create an information label for a specific queried user. This object can be instantiated in the presentation layer and is independent of the technology used for showing the user information as illustrated in Listing 3. That is, this label can be rendered in a Web Browser, a Windows Client and a Mobile Device.


Listing 3:

using System;

 

namespace OLAActiveDirectory.Management

{

    public interface IADUserInfoShower

    {

        string GetInformation(IADUser objUser, string strSep);

    }

 

    public class ADUserInfoShower : IADUserInfoShower

    {

        private string prvInfoBuilder(IADUser objUser, string strSep)

        {

            string strResult;

 

            strResult = "Fullname:" + objUser["givenName"].Value + " " + objUser["sn"].Value;

            strResult += strSep + "Mail:" + objUser["mail"].Value;

            strResult += strSep + "Telephone(s):" + objUser["telephoneNumber"].Value;

            foreach (string strPhone in objUser["otherTelephone"])

                strResult += strSep + strPhone;

 

            return strResult;

        }

        public ADUserInfoShower()

        {

        }

        public string GetInformation(IADUser objUser, string strSep)

        {

            return this.prvInfoBuilder(objUser, strSep);

        }

    }

}

Conclusion:

This article illustrates how you can interact with the Active Directory for querying information using Microsoft.NET technologies.

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate this article
 
 About the author
 
John Charles Olamendy
He’s a senior Integration Solutions Architect and Consultant. His primary area of involvement is in Object-Oriented Analysis and Design, Database design , Enterprise Application Integration, Unified Modeling Language, Design Patterns and Software Development Process. He has knowledge and extensive experience in the development of Enterprise Applications using Microsoft.NET and J2EE technologies and standards. He is proficient with distributed systems programming; and business-process integration and messaging using the principles of the Services Oriented Architecture (SOA) and related technologies such as Microsoft BizTalk Server, Web Services (Windows Communication Foundation, WSE, BEA WebLogic, Oracle AS and Axis) through multiple implementations of loosely-coupled system. He’s a prolific blogger contributing to .NET and J2EE communities and actively writes articles on subjects relating to integration of applications, business intelligence, and enterprise applications development. He holds a Master’s degree in Business Informatics at Otto Von Guericke University, Magdeburg, Germany. He was recently awarded as MVP. He currently works in the telecommunication industry and delivers integration solutions for this industry. He harbors a true passion for the technology.
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Discover the Top 5 .NET Memory Management Fundamentals
To write the best .NET code, you need to know exactly how the .NET framework really manages memory. Ricky Leeks presents the Top 5 fundamental facts of .NET memory management. Learn more.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
Nevron Chart
Become a Sponsor
 Comments
why does your code use Interfaces? by Pete On August 9, 2007
Hi, Could you tell me as to why does your code use interfaces for each class? What advantage would that give your class? e.g. your ADPasswdManager class uses IADPasswdManager interface. Couldn't your ADPasswdManager class have regular methods like SetPassword and ChangePassword? Why use the interface? I mean I know what interfaces are and why they are used but why in this case? Thank you... Regards...
Reply | Email | Modify 
Re: why does your code use Interfaces? by John Charles On August 23, 2007

The interface is the abstraction of the class.  Thus there is a separation between what you see and how it is implemented. Casses realize interfaces. A class may realize several interface, therefore one instance of the class has several faces which are provided to other objects for message exchange purposes.

I always use interface in my designs to separe the communication mechanisms from implementation so the application is more loosely coupled.

For example one client needs to access to a directory service, the service exposes an interface for communication and message exchange to the client, it is transparent to the client if the service is Active Directory, UDDI or other service, the face is the same, but if the client needs other form of directory service, the only thing to do is realize the interface and implement the business logic in the class, the create an instance of the class and reference this object using the interface defintion.

This is a very loosely coupled approach useful for the development any form of modular artifacts such as components, Web services, etc.

Reply | Email | Modify 
Non Login User Group/Role Membership by Louis On January 30, 2008

Is there an easy way to merely find out if a specified username is in a specified AD Group/Role? I am not talking about the login user, but a user that I can specify. For example, say JSmith is logged in, but wants to find out if JDoe is in an AD group called "LabAdmin". I tried ADUser above, but that crashes on the .FindOne line and am not even sure that that would be the code to use anyway.

I can get the first level, but if there are groups within groups within the group, I cannot drill down.

Reply | Email | Modify 
Re: Non Login User Group/Role Membership by Alan On February 14, 2008
You must change FindOne to FindAll because find one will return only the first instance found, findall will return all of them.
Reply | Email | Modify 
Login User Group/Role Membership by Cherise On October 9, 2008
I am looking for something similiar to Louis. In my case user will be logged into Windows and have access to parts of the web program based on them being in a specific user group. I am not sure where to start with the code, would you be able to point me in the right direction? Using ASP.NET 2.0, VB.Net, ADO.Net, Active Directory for Windows & SQL Server Enterprise Manager. Thanks in advance.
Reply | Email | Modify 
Requirements to Access Active Directory using C# by Moses On September 14, 2009

Hi,

Teh project I am working on requires me to write a C# class to read the username / lognid of the all the users in our active directory.  What information do i need from our Network infrastructure team so i can do this task?  DO i need the root path of the AD, or do i need some account and password to access the Active directory usernames?

Chees,
Moses 

Reply | Email | Modify 

 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.