CODE DIGEST
Skip Navigation LinksHome » Article » .Netframework Article » Active Directories in .Net   You are not logged in.
Search
 

Technologies
 

CodeDigest Navigation
 

Technology News
Read more..

Read more..

Read more..

 

Community News
Read more..

Read more..

 
Active Directories in .Net
By Satheesh Babu
Posted On Feb 24,2008
Article Rating: (Login)
Be first to rate
this article.
No of Comments: 22
Category:
Print this article.

Active Directories in .Net

 

Active directory are similar to database that are used in windows environment to store information’s about networks, users, domains and assets like printers, etc. Like database we can query, update active directory for business purposes. With this information we will move forward and see how active directories are accessed, updated using .net through simple example. Throughout this article I use LDAP to connect to active directory.

 

How to access AD through .Net?

.Netframework has packed set of classes in System.DirectoryServices namespace which facilitates us to gain access to AD. We have to add reference to this namespace before proceeding it further.

 

In the next section we will see how to retrieve the whole information about a user in AD with the help of System.DirectoryServices namespace.

 

Get user information from AD:

The below code will help us to retrieve all the information of a particular user by giving his/her userid. For executing this code you need to change the below LDAP string according to your infrastructure name.

 

        DirectoryEntry dir = new DirectoryEntry();

        dir.Path = "LDAP://YourDomainController ";        

        DirectorySearcher sea = new DirectorySearcher(dir);

        sea.Filter = "(sAMAccountName=satheesb)";

        SearchResult seares = sea.FindOne();      

        StringBuilder str = new StringBuilder();

        System.DirectoryServices.ResultPropertyCollection prop = seares.Properties;

        ICollection coll = prop.PropertyNames;

        IEnumerator enu = coll.GetEnumerator(); 

            while (enu.MoveNext())

            {

                str.Append(enu.Current + " = " + seares.Properties[enu.Current.ToString()][0] + "\n");

            }

           txtSummary.Text = str.ToString();

 

If you see the above code we are restricting the search by giving a filter to retrieve only a particular user, “satheesb” in our case. We can extend this query and narrow down the search according to our need. Multiple conditions can be given in the format,

(&(Attribute1=value)(Attribute2=value)(Attribute2=value))

The above query uses AND condition so all the conditions have to be satisfied. We can use OR with the help of “|” symbol and we can use the symbol “!” for NOT. For security purposes not every user id in an enterprise will have rights to update AD. DirectoryEntry class have UserName and Password property that will get the service account informations in case of ASP.Net application.

 

dir.Username = txtServiceUID.Text;

dir.Password = txtServicePwd.Text;

 

Update Active Directory in .Net:

We will see a simple example that will update the AD in this section. For making the understanding simple we will search for user with surname “babu” and update their country to India. Updations to a attribute in AD can be done through DirectoryEntry class by,

DirectoryEntry.Property[“PropertyName”].Value=”new Value”;

For example:

                dir.Properties["mobile"].Value = "9901999337";

 

Implementation:

 

    try

        {

            DirectoryEntry dir = new DirectoryEntry();

            dir.Path = "LDAP://YourDomainController ";        

            DirectorySearcher sea = new DirectorySearcher(dir);

            sea.Filter = "(sn=Babu)";

            SearchResultCollection seacoll = sea.FindAll();

            Response.Write(seacoll.Count.ToString());

            StringBuilder str = new StringBuilder();

            for (int i = 0; i < seacoll.Count; i++)

            {

                DirectoryEntry d = new DirectoryEntry();

                d.Path = seacoll[i].Path;

 

                d.Properties["co"].Value = "India";

 

                d.CommitChanges();

                if (d.Properties.Contains("sAMAccountName"))

                {

                    str.Append("sAMAccountName =" + d.Properties["sAMAccountName"].Value + "\n");

                }

                if (d.Properties.Contains("co"))

                {

                    str.Append("Country =" + d.Properties["co"].Value + "\n");                   

                }

                str.Append("---------" + "\n");

            }

            txtSummary.Text = str.ToString();

            Response.Write("Completed with " + seacoll.Count.ToString() + " Row(s)");

        }

        catch (Exception ex)

        {

            Response.Write(ex.Message);

        }

After updating make sure to call CommitChanges() method which saves the updated data to the underlying store. One thing we have to note when we are working with active directory is it is very slow and thus we should make our search query very narrow as much as possible. We can get the entire attribute names in AD using the code listed in “Get user information from AD” section. Download the source code attached with article and change the LDAP string to see AD in action.

Download Source:

Download source
Article Feedback
Title  
Submitted By  
Comment  
Comments
Retuiaid
magic story very thanks hotels cheap beachfront puerto penasco hotels that are beautiful 9083
Wcdmsqpt
Very interesting tale germany las vegas and cheap hotels =-(
Gfztrqvl
It's serious in orange beach cheap hotels in cnetral london >:-OO
Nqwpsrqe
Punk not dead shanghai san fransisco and cheap hotels =-(
Mqbxqmke
Good crew it's cool :) hotel near osu cheap hotels oahu 976219
Vhvtmtzq
I'm happy very good site windsor cheap hotels in solvang 784402
Dhrixdjo
I love this site http://groups.google.jp/group/worldwide-hotel-room cheap hotels in pendleton :))
Yegqgwgs
Thanks funny site thailand cheap hotels in miami florida msj
Laouqdye
Excellent work, Nice Design heathrow hotel in london cleveland cheap hotels %-[[
Lwwbxqan
Very funny pictures in new philadelphia oh cheap hotels flagstaff 428701
Gjzmjgnj
It's funny goodluck hotel room in miami hotel dublin cheap ujpan
Jhnfzdfd
Hello good day vegas luxury las vegas hotels lowest rates cheap hotel discount qczwj
Zxeyyxlq
i'm fine good work hotels cheapest 735568
Sbownsrw
Cool site goodluck :) hotel new york city cheap hotel and tickets to new york roudbq
Xzexqpcf
Gloomy tales http://groups.google.jp/group/hotel-guides cheap hotel deals in lisbon >:-O
Xqrldzcz
real beauty page time square cheap hotels in death valley 72182
Mbzvnclr
I love this site hotel cheap flights hotels canada com 66565
Jyqugkpt
Cool site goodluck :) in denmark cheap :OO
Dmqqvjrm
Very interesting tale http://groups.google.jp/group/Hotels-Cheap-provides cheap hotels com %PP
Xxtsrmmd
Jonny was here vegas cheap hotels in near kij
Bspbilho
Punk not dead cheap cheap hotels in montego bay 667
Octjiial
i'm fine good work http://groups.google.jp/group/l-cheaphotels cheap hotels >:DDD