Blue Theme Orange Theme Green Theme Red Theme
 
6 Months Free & No Setup Fees ASP.NET Hosting!
Home | Forums | ASP.NET 2.0 Tutorials | Web Services | How Do I...? | Class Browser | WPF Quick Starts | Advertise with Us
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
Team Foundation Server Hosting
Search :       Advanced Search »
Home » ASP.NET » Accessing Global Address List via System.DirectoryServices namespace

Accessing Global Address List via System.DirectoryServices namespace

This is a how-to article to access the GAL from ASP.NET, using the DropDownList ASP.NET server control as the UI. To accomplish this the article will illustrate by utilizing ADSI technology from a C# assembly returning an ArralList in order to bind to the DropDownList.

Page Views : 17407
Downloads : 0
Rating :
 Rate it
Level : Intermediate
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
 
Team Foundation Server Hosting
Become a Sponsor
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 

The System.DirectoryServices namespace provides easy access to Active Directory from managed code. The namespace contains two component classes, DirectoryEntry and DirectorySearcher, which use the Active Directory Services Interfaces (ADSI) technology. ADSI is the set of interfaces that Microsoft provides as a flexible tool for working with a variety of network providers.

This is a how-to article to access the GAL from ASP.NET, using the DropDownList ASP.NET server control as the UI. To accomplish this the article will illustrate by utilizing ADSI technology from a C# assembly returning an ArralList in order to bind to the DropDownList.

1) Open Microsoft Visual Studio .NET.

2) Click New Project. Select the Visual C# Projects Item in the Project Types panel on the left. Select Class Library in the Templates panel on the right. Name the project 'gal' or any name you choose in the Name text box and state the location of the project in the Location text box. And click OK to complete the project description.

3) In the Solution explorer right-click the References item and click Add Reference in the pop-up menu. The Add Reference dialog will be displayed. Select the .NET tab and highlight the System.DirectoryServices.dll, then click the Select button on the right to accept and click OK to add the reference to the Solution.

You will now see the added reference to the project.

4) Add to the using declaration section at the top just below the 'using System;' declaration the following two lines.

using System.DirectoryServices;
using System.Collections;

These using declarations are needed in order to access the classes of both namespaces, the DirectoryServices namespace to create the DirectorySearcher and DirectoryEntry objects, and the Collections namespace to create the ArrayList object.

You may want to click the link below as a reference to view the methods and properties in this namespace while building the solution.

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfsystemdirectoryservices.asp

Note the Default Global Address List Properties from the Exchange Server below. Its default Filter rules are shown.

Note the 'Users' property in the Canonical name of object definition below. We will use this property in our filter query.

(objectClass=user)

In this example I will shorten the filter rules to the following for simplicity sake:

(& (mailnickname=*)(objectClass=user))

shown below in the code.

The (mailnickname=*) filter applies the filter to every object that has a mailNickname attribute (that is, every object that is mail-enabled). The '&' is the equivalent to 'And' in T-Sql syntax. Exchange filter rules' order are not as intuitive as T-Sql as one can see. So the filter in the code means every object that is mail-enabled and every object that is defined as user.

5) Copy and Paste the following code in the class below the default constructor.

public ArrayList returngal()
{
DirectorySearcher objsearch =
new
DirectorySearcher();
string
strrootdse = objsearch.SearchRoot.Path ;
DirectoryEntry objdirentry =
new
DirectoryEntry(strrootdse);
objsearch.Filter = "(& (mailnickname=*)(objectClass=user))";
objsearch.SearchScope = System.DirectoryServices.SearchScope.Subtree;
objsearch.PropertiesToLoad.Add("cn");
objsearch.PropertyNamesOnly =
true
;
objsearch.Sort.Direction = System.DirectoryServices.SortDirection.Ascending;
objsearch.Sort.PropertyName = "cn";
SearchResultCollection colresults = objsearch.FindAll() ;
ArrayList arrGal =
new
ArrayList();
foreach(SearchResult objresult in
colresults)
{
arrGal.Add(objresult.GetDirectoryEntry().Properties["cn"].Value);
}
objsearch.Dispose();
return
arrGal ;
}

6) Click on the 'Build' menu item, then click on 'Build Solution' in the pop-up menu.

You will see the following successful build message in the Output/Build pane.

7) Click on the 'File' menu item, then click on 'Save gal.sln' in the pop-up menu to save the project solution.

Now we have a .NET assembly ready to use in our web page.

8) On the chosen web server create a new folder, name it 'gal', under the wwwroot directory.

9) Create a virtual directory on the chosen web server using the Virtual Directory Creation Wizard to input the Alias, name it 'gal', the Directory, choose the newly created folder 'gal', and the Access Permissions(check the Read and Run Scripts at least) properties.

10) Open upon notepad and copy and paste the following code into the editor. Now save the file as 'gal.aspx' into the gal directory on the web server.

 <%@ Page Language="c#" Debug="true" %>
<html>
<script language="c#" runat="server">
void Page_Load(object sender, EventArgs e)
{
gal.Class1 s = new gal.Class1();
gal.DataSource = s.returngal();
gal.DataBind();
gal.Items.Insert( 0, new ListItem("GAL") );
}
</script>
<body>
GAL
<form id="Form" runat="server">
<br>
<ASP:DropDownList id="gal" runat="server" />
</form>
</body>
</html>

11) Copy and paste the following code into the editor. Now save the file as 'web.config' into the gal directory on the web server.

<?xml version="1.0" encoding="utf-8" ?>
<
configuration>

<system.web>

<customErrors mode="Off" />

<authentication mode="None" />

</system.web
>
</
configuration>

12) Create a new folder, name it 'bin', under the gal directory of the web server. Now copy the 'gal.dll' from the Debug folder which is under the bin folder in the project folder 'gal' and paste this gal.dll into the 'bin' folder of the web server.

Copy from the folder below.

Paste it into the folder below.

13) Type the path to the gal.aspx in the browser and see results below.

If error messages appear, there may be problems with ASP.NET Base Account
See the following article at

http://support.microsoft.com/default.aspx?scid=kb;en-us;329986

The web.config file may need some changes and the security of the virtual directory may need some adjusting. The article above should lend some light on the issue.

A possible solution could be the following:

Edit the web.config file.

<authentication mode="Windows" />
<identity impersonate="true" />

And change the virtual directory security setting. Clear the Anonymous Authentication check box and check the Integrated Windows Authentication property.

There may be an issue with the performance of the page on request due to the size of the GAL. You may have to implement some caching into your gal.aspx page similar to the following.

ArrayList arrGal = new ArrayList();
arrGal = (ArrayList)Cache["arrGal"];
if ( arrGal == null
)
{
gal.Class1 s =
new
gal.Class1();
arrGal = s.returngal();
Cache["arrGal"] = arrGal ;
}
gal.DataSource = arrGal ;
gal.DataBind();
gal.Items.Insert( 0,
new ListItem("GAL") );

This will greatly affect the page's performance and enhance the user's experience.

You may want to use a cache dependency like the following:

Cache.Insert("arrGal ", arrGal, null, DateTime.Now.AddMinutes(2), NoSlidingExpiration);

There may be an issue with the number of objects returned from the objsearch.FindAll() method. By default it will only return a maximum of 1000 objects in the SearchResultCollection. So you might have to do a little coding here. A possible solution is to have more than one implementation of FindAll() in the code, using a property to limit the searches eventually grabbing all the objects. I will use the 'cn' property to illustrate. The cn property is short for the common name attribute.

objsearch.Filter = "(& (mailnickname=*)(objectClass=user) (cn<=M))";

for one search and

objsearch.Filter = "(& (mailnickname=*)(objectClass=user) (cn>=M))";

for the second search, effectively using two, or more if needed, searches to select all the objects resulting in two or more SearchResultCollection objects to loop through.

foreach(SearchResult objresult in colresults)
{
arrGal.Add(objresult.GetDirectoryEntry().Properties["cn"].Value);
}
foreach(SearchResult objresult2 in
colresults2)
{
arrGal.Add(objresult2.GetDirectoryEntry().Properties["cn"].Value);
}

A url link which may be helpful to access search attributes is:

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
 
Frank Gutierrez
Frank Gutierrez has been a developer for seven years in the Health Care Industry. He has a Masters degree from the University of Southern California.
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.
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 Gauge for SharePoint
Become a Sponsor
 Comments
hi by srividya On October 19, 2007
hi i get the following error when i run the aspx file "The specified domain either does not exist or could not be contacted.\r\n in the following line string strrootdse = objsearch.SearchRoot.Path; with regards sri
Reply | Email | Modify 
Team Foundation Server Hosting
 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.