Virtual Business Card


A Jack of all trades is a master of integration, as such an individual who knows enough from many learned trades and skills to be able to bring their disciplines together in a practical manner, and is not a specialist but can be an expert in many fields. Such a person is known as a polymath or a renaissance man; a typical example is someone like Leonardo da Vinci.

Friday, June 22, 2012

Recursively get all users in a group in Active Directory C#



   1:  using System;
   2:  using System.Collections.Generic;
   3:  using System.ComponentModel;
   4:  using System.Data;
   5:  using System.Drawing;
   6:  using System.Linq;
   7:  using System.Text;
   8:  using System.Windows.Forms;
   9:  using System;
  10:  using System.DirectoryServices;
  11:  using System.Collections.Generic;
  12:  using System.DirectoryServices.AccountManagement;
  13:   
  14:  namespace RecurseUsersInGroups
  15:  {
  16:      public partial class FormGroups : Form
  17:      {
  18:   
  19:          StringBuilder _builder = new StringBuilder();
  20:   
  21:          public FormGroups()
  22:          {
  23:              InitializeComponent();
  24:          }
  25:   
  26:          private void buttonGetAllUsers_Click(object sender, EventArgs e)
  27:          {
  28:              try
  29:              {
  30:                  textBoxUsers.Clear();
  31:                  _builder.Clear();
  32:   
  33:                  PrincipalContext ctx = new PrincipalContext(ContextType.Domain, textBoxDomain.Text);
  34:                  GroupPrincipal grp = GroupPrincipal.FindByIdentity(ctx, IdentityType.Name, textBoxADGroup.Text);
  35:   
  36:                  if (grp != null)
  37:                  {
  38:                      foreach (Principal p in grp.GetMembers(true))
  39:                      {
  40:   
  41:                          if (!_builder.ToString().Contains(p.SamAccountName))
  42:                          {
  43:                              _builder.Append(p.SamAccountName);
  44:                              _builder.Append("; ");
  45:                          }
  46:                      }
  47:   
  48:                      textBoxUsers.Text = _builder.ToString();
  49:   
  50:                      grp.Dispose();
  51:                      ctx.Dispose();
  52:   
  53:                  }
  54:                  else
  55:                  {
  56:                      MessageBox.Show("\nWe did not find that group in that domain, perhaps the group resides in a different domain?");
  57:                  }
  58:              }
  59:              catch (System.Exception)
  60:              {
  61:   
  62:                  MessageBox.Show("\nWe did not find that group in that domain, perhaps the group resides in a different domain?");
  63:              }
  64:             
  65:   
  66:   
  67:          }
  68:   
  69:   
  70:   
  71:      }
  72:  }

No comments:

Post a Comment