Wednesday, August 15, 2012

One may get a list of domains from an Active Directory forest in C#. This post shows how.

I am learning to work with Active Directory. Typically, I've done nothing greater than sniff a user's LAN alias in assigning System.Web.HttpContext.Current.User.Identity.Name to a string, but beyond this hat trick lies a large wealth of capabilities in the System.DirectoryServices and System.DirectoryServices.ActiveDirectory namespaces. An Active Directory has a "forest" which may contain numerous domains within it. This allows some boundaries and breakup for a large organization. It is also quicker to search a particular domain than to search the whole of the forest.

I am building a dummy app in the name of experimentation and learning the System.DirectoryServices and System.DirectoryServices.ActiveDirectory namespaces. My About action below shows how to find the forest and get a list of its domains out of it.

using System.Collections.Generic;
using System.Web.Mvc;
using System.Linq;
using System.DirectoryServices.ActiveDirectory;
namespace ActiveDirectoryStuff.Controllers
{
   public class HomeController : Controller
   {
      public ActionResult Index()
      {
         
//the following line requires: <authentication mode="Windows"/> in Web.config
         string name = System.Web.HttpContext.Current.User.Identity.Name;
         ViewBag.Message = name;
         return View();
      }
      
      public ActionResult About(string id)
      {
         string name = id.Replace('@', '\\');
         Forest forest = Forest.GetCurrentForest();
         List<string> domainNames = new List<string>(){};
         domainNames.AddRange (from Domain domain in forest.Domains select
               domain.Name);
         return View(domainNames);
      }
   }
}

 
 

The view for the About action:

@model List<string>
@{
   ViewBag.Title = "Domains";
}
<h2>Domains</h2>
@foreach (string domainName in Model)
{
   @domainName<br />
}

 
 

My Index view is not really related to this posting, yet here it is. I use System.Web.HttpContext.Current.User.Identity.Name to find who the user is (, and, yes, this requires <authentication mode="Windows"/> in the Web.config file). After that, I create a link to the About action and pass it the Active Directory id, but I am not doing anything with this information yet. Forgive the noise.

@{
   ViewBag.Title = "Home Page";
}
<h2>Your Active Directory Account!</h2>
<p>
   <a href="/Home/About/@ViewBag.Message.Replace('\\', '@')/">Click here</a> to learn
         more about: @ViewBag.Message
</p>

No comments:

Post a Comment