search

Active Directory with C#

Sep 03, 2024 pm 03:33 PM
c#c# tutorial

Active Directory with C# is first and foremost to organize computers, company users, and so on. The essential thing is a user management system which is generally used by enterprise networks and for business purposes. A company admin will use to organize the company’s entire history from the computers belongs to the network, the profile and access permissions, and so on. Active directory is a type of database like Oracle and SQL it has its own query type language and set of rules based on LDAP.

Syntax:

To access the DirectoryEntry object we required the Active Directory username, password, and server address. The server address contains the IP address or the path of LDAP looks like as the syntax as follows,

LDAP://domain_name.com/DC=domain_name,DC=com

How Active Directory works in C#?

Active Directory really helps for IT admin which helps to organize their company users, desktops and more it has entire hierarchical structure belong to which network and what the profile picture shows and who accessing the storages and so on. Most of the businesses progress their applications from desktop to web applications holding the form-based LDAP authentication. On occasion .NET applications interact with Microsoft Active Directory (AD) to retrieve the user’s list, to search out groups, to authenticate the users, and also to verify which users are in which Active Directory group. By using some approaches, we can retrieve the information from the AD database within our domain.

There are various approaches one is to make use of the LDAP (Lightweight Directory Access Protocol) it contains the classes DirectoryEntry and DirectorySearch belong to the namespace System.DirectoryServices. One more approach is to make use of the entire set of class wrappers in Active Directory (AD) under the namespace System.DirectoryServices.AccountManagement. By using the LDAP queries we can get the information from AD database. This class allows accessing the entire AD but the wrapper class allows retrieving the users, computer objects, groups in AD. The classes DirectoryEntry and DirectorySearch objects are quicker than the object System.DirectoryServices.AccountManagement.

The basic thing for Active Directory with C# includes the System.DirectoryService library, it helps to query with AD library routines. Active directory communicates through the objects of DirectoryEntry. Those objects are the most important connections to the LDAP database which we can query for additional objects and folders. To access the DirectoryEntry object we required the Active Directory username, password, and server address. The server address contains the IP address or the path of LDAP looks like as follows,

LDAP://domain_name.com/DC=domain_name,DC=com

Examples of Active Directory with C#

To connect with Active Directory for objects of DirectoryEntry, for we need to create the user of secure authenticate type which indicates the secure authenticated connection to the Active Directory. When connecting with an account of the admin we can perform the admin Active Directory functions such as creating new users, to update users, to deleting the users, and so on.

Get the DirectoryEntry of Directory object

private DirectoryEntry Reterieve_DirectoryObject( )
{
DirectoryEntry Obj_de;
Obj_de=new DirectoryEntry("LDAP://IP_Address", "admin","password", AuthenticationTypes Secure);
return _de;
}

Get the user from Active Directory in C#

Once connecting with Active Directory we need to query for an object like getting user as follows below,

private DirectoryEntry Reterieve_User(string User_Name)
{
DirectoryEntry obj_de = Reterieve_DirectoryObject( );
DirectorySearcher obj_deSearch = new DirectorySearcher();
obj_deSearch.SearchRoot = obj_de;
obj_deSearch.Filter = "(&(objectClass=user)(JOHNAccountName=" + User_Name + "))";
obj_deSearch.SearchScope = SearchScope.Subtree;
SearchResult getPath = obj_deSearch.FindOne();
if (!(getPath == null))
{
obj_de = new DirectoryEntry(getPath.Path, "administrator", "password", AuthenticationTypes.Secure);
return obj_de;
}
else
{
return null;
}
}

The above code explains how to retrieve the user from the Active Directory depends on their login credentials. We need to use a particular Active Directory query language included with parenthesis it contains the name like “JohnAccountName” and username as like in Active Directory. Once finding the DirectoryEntry next to code the new DirectoryEntry object which links to the result and to use the admin’s login details in the connection.

Create an authenticate user

To create an authenticated user for Active Directory we need to pass the valid LDAP path string to the DirectoryEntry class constructor, it follows the format of LDAP://Doamin_name. Let’s see the following method,

private bool AuthenticateUser(string domain_name, string user_name, string password)
{
bool result = false;
try
{
DirectoryEntry obj_de = new DirectoryEntry("LDAP://" + domainName, userName, password);
DirectorySearcher obj_dsearch = new DirectorySearcher(obj_de);
SearchResult _sResult = null;
sResult = obj_dsearch.FindOne();
result = true;
}
catch
{
result = false;
}
return result;
}

Alter the user details in Active Directory in C#

To alter the properties of an object of Active Directory in C# is just simple in C#, firstly to access the DirectoryEntry property fields and to alter the values as required before that to check whether it’s null or not and then finally call the function ComminChanges to execute and save the changes done. Let’s see the code below which shows that alters the user’s name property,

DirectoryEntry obj_de = Reterieve_User ("smith.rio");
if (obj_de!= null)
{
if (obj_de.Properties["displayName"] != null && obj_de.Properties["displayName"].Value != null)
{
de.Properties["displayName"].Value = "Smith, Rio (Welcome)";
de.CommitChanges();
}
}

The above code describes the CommitChanges(), which will save the changes made in the Active Directory. The most important thing is that whatever changes are made will not be immediately visible in the applications of Active Directory like users of Active Directory and computers in the control panel it takes around 5-30 minutes to visible during changes because it needs to synchronize over the servers all through the network.

Querying Multiple Users in Active Directory with C# ASP .NET

The code above explained was to query the single DirectoryEntry object, whereas if we required for the list of objects we need to use the type SearchResultCollection joined with obj_deSearch, to search out all the things instead of finding one,

SearchResultCollection findUsers = retrieve_allUsers();
if (findUsers!= null && findUsers.Count > 0)
{
foreach (SearchResult getUser in findUsers)
{
DirectoryEntry obj_de = getUser.GetDirectoryEntry();
}
}

Conclusion

In this article, I have explained about the Active Directory and how to retrieve details of users, system usage, groups, and also to authenticate the user. By using some classes, we can easily retrieve the details from the active directory (AD) database. Active Directory with C# is a foremost tool for enterprise networks and for businesses. When designing with web applications which suit for desktop applications to the web to make powerful organizations.

The above is the detailed content of Active Directory with C#. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
C# .NET: Exploring Core Concepts and Programming FundamentalsC# .NET: Exploring Core Concepts and Programming FundamentalsApr 10, 2025 am 09:32 AM

C# is a modern, object-oriented programming language developed by Microsoft and as part of the .NET framework. 1.C# supports object-oriented programming (OOP), including encapsulation, inheritance and polymorphism. 2. Asynchronous programming in C# is implemented through async and await keywords to improve application responsiveness. 3. Use LINQ to process data collections concisely. 4. Common errors include null reference exceptions and index out-of-range exceptions. Debugging skills include using a debugger and exception handling. 5. Performance optimization includes using StringBuilder and avoiding unnecessary packing and unboxing.

Testing C# .NET Applications: Unit, Integration, and End-to-End TestingTesting C# .NET Applications: Unit, Integration, and End-to-End TestingApr 09, 2025 am 12:04 AM

Testing strategies for C#.NET applications include unit testing, integration testing, and end-to-end testing. 1. Unit testing ensures that the minimum unit of the code works independently, using the MSTest, NUnit or xUnit framework. 2. Integrated tests verify the functions of multiple units combined, commonly used simulated data and external services. 3. End-to-end testing simulates the user's complete operation process, and Selenium is usually used for automated testing.

Advanced C# .NET Tutorial: Ace Your Next Senior Developer InterviewAdvanced C# .NET Tutorial: Ace Your Next Senior Developer InterviewApr 08, 2025 am 12:06 AM

Interview with C# senior developer requires mastering core knowledge such as asynchronous programming, LINQ, and internal working principles of .NET frameworks. 1. Asynchronous programming simplifies operations through async and await to improve application responsiveness. 2.LINQ operates data in SQL style and pay attention to performance. 3. The CLR of the NET framework manages memory, and garbage collection needs to be used with caution.

C# .NET Interview Questions & Answers: Level Up Your ExpertiseC# .NET Interview Questions & Answers: Level Up Your ExpertiseApr 07, 2025 am 12:01 AM

C#.NET interview questions and answers include basic knowledge, core concepts, and advanced usage. 1) Basic knowledge: C# is an object-oriented language developed by Microsoft and is mainly used in the .NET framework. 2) Core concepts: Delegation and events allow dynamic binding methods, and LINQ provides powerful query functions. 3) Advanced usage: Asynchronous programming improves responsiveness, and expression trees are used for dynamic code construction.

Building Microservices with C# .NET: A Practical Guide for ArchitectsBuilding Microservices with C# .NET: A Practical Guide for ArchitectsApr 06, 2025 am 12:08 AM

C#.NET is a popular choice for building microservices because of its strong ecosystem and rich support. 1) Create RESTfulAPI using ASP.NETCore to process order creation and query. 2) Use gRPC to achieve efficient communication between microservices, define and implement order services. 3) Simplify deployment and management through Docker containerized microservices.

C# .NET Security Best Practices: Preventing Common VulnerabilitiesC# .NET Security Best Practices: Preventing Common VulnerabilitiesApr 05, 2025 am 12:01 AM

Security best practices for C# and .NET include input verification, output encoding, exception handling, as well as authentication and authorization. 1) Use regular expressions or built-in methods to verify input to prevent malicious data from entering the system. 2) Output encoding to prevent XSS attacks, use the HttpUtility.HtmlEncode method. 3) Exception handling avoids information leakage, records errors but does not return detailed information to the user. 4) Use ASP.NETIdentity and Claims-based authorization to protect applications from unauthorized access.

In c language: What does it meanIn c language: What does it meanApr 03, 2025 pm 07:24 PM

The meaning of colon (':') in C language: conditional statement: separating conditional expressions and statement block loop statement: separating initialization, conditional and incremental expression macro definition: separating macro name and macro value single line comment: representing the content from colon to end of line as comment array dimension: specify the dimension of the array

What does a mean in C languageWhat does a mean in C languageApr 03, 2025 pm 07:21 PM

A in C language is a post-increase operator, and its operating mechanism includes: first obtaining the value of the variable a. Increase the value of a by 1. Returns the value of a after increasing.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)