Syed Jahanzaib Personal Blog to Share Knowledge !

March 30, 2017

C# Active Directory Management using custom built App!

Filed under: Programming — Tags: , , , , , — Syed Jahanzaib / Pinochio~:) @ 11:01 AM

c

This is just another reference example post, on how you can use C# code to connect with active directory in order to perform some basic tasks , using one window operation approach. It’s simple, fast, and works well enough to cater the OP requirements. You can add your own functions in it as required. You can use use/modify/redistribute this code freely. no obligations.

stackoverflow


Task:

A simple program which can display all Active Directory users in a Drop down List menu, and based on the selection, it can perform various actions like

  • Check Status of User
  • Disable Account
  • Enable Account
  • While preventing any access to Admin account(s)

Something like below …

logo

Requirements:

  • Target framework is 4.x. [Latest is good because of its extensive support for various  enormous operations.]
  • Reference of Active Directory Modules

To add refrence to proect, Goto PROJECTS > ADD REFERENCE  > FRAMEWORK

Add following …

  • System.DirectoryServices
  • System.DirectoryServices.ActiveDirectory
  • System.DirectoryServices.AccountManagement

reference.PNG

The program must be run via Administrator account or account with admin privileges

CODE:

Here is the full code. Based on this code, we can add many other functions, this is just for example purposes.

Form1.cs


// C# code to manage Active Directory functions
// like enable/disable user account via drop down menu list
// Syed Jahanzaib / aacable at hotmail dot com
// March, 2017
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.DirectoryServices;
using System.DirectoryServices.ActiveDirectory;
using System.DirectoryServices.AccountManagement;
using System.Configuration;
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
new ToolTip().SetToolTip(comboBox1, "Click here to see user list");
}
private void button1_Click(object sender, EventArgs e)
{
String _ADUserName = comboBox1.Text; // <-- The textbox you enter your username?
if (string.IsNullOrEmpty(comboBox1.Text) || comboBox1.Text == "0")
{
this.StatusTextBox.AppendText("\r\n" + _ADUserName + " - Please Enter Username!\n\r");
return;
}
PrincipalContext context = new PrincipalContext(ContextType.Domain);
UserPrincipal user = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, comboBox1.Text.Trim());
if (comboBox1.Text == "ADMIN1" | comboBox1.Text == "ADMIN2")
{
this.StatusTextBox.AppendText("\r\n" + _ADUserName + " - Dont get over smart. You are 'NOT' authorized to change admin accounts state!\n\r");
return;
}
if (user == null)
{
this.StatusTextBox.AppendText("\r\n" + _ADUserName + " - not found in AD!\n\r");
return;
}
if (user.Enabled == false)
{
this.StatusTextBox.AppendText("\r\n" + _ADUserName + " - User is already DISABLED.\n\r");
return;
}
if (user.Enabled == true)
DiableADUserUsingUserPrincipal(_ADUserName);
this.StatusTextBox.AppendText("\r\n" + _ADUserName + " - is now DISABLED.\n\r");
}
private static bool DiableADUserUsingUserPrincipal(string username)
{
try
{
PrincipalContext principalContext = new PrincipalContext(ContextType.Domain);
UserPrincipal userPrincipal = UserPrincipal.FindByIdentity
(principalContext, username);
userPrincipal.Enabled = false;
userPrincipal.Save();
return true;
}
catch (Exception ex)
{
//Console.WriteLine(ex.Message);
}
return false;
}
private static bool EnableADUserUsingUserPrincipal(string username)
{
try
{
PrincipalContext principalContext = new PrincipalContext(ContextType.Domain);
UserPrincipal userPrincipal = UserPrincipal.FindByIdentity
(principalContext, username);
userPrincipal.Enabled = true;
userPrincipal.Save();
return true;
}
catch (Exception ex)
{
//Console.WriteLine(ex.Message);
}
return false;
}
private void button2_Click(object sender, EventArgs e)
{
{
String _ADUserName = comboBox1.Text; // <-- The textbox you enter your username?
if (string.IsNullOrEmpty(comboBox1.Text) || comboBox1.Text == "0")
{
this.StatusTextBox.AppendText("\r\n" + _ADUserName + " - Please Enter Username!\n\r");
return;
}
PrincipalContext context = new PrincipalContext(ContextType.Domain);
UserPrincipal user = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, comboBox1.Text.Trim());

if (comboBox1.Text == "ADMIN1" | comboBox1.Text == "ADMIN2")
{
this.StatusTextBox.AppendText("\r\n" + _ADUserName + " - Dont get over smart. You are 'NOT' authorized to change admin accounts state!\n\r");
return;
}
if (user == null)
{
this.StatusTextBox.AppendText("\r\n" + _ADUserName + " - not found in AD!\n\r");
return;
}
if (user.Enabled == true)
{
this.StatusTextBox.AppendText("\r\n" + _ADUserName + " - User is already ENABLED.\n\r");
return;
}
if (user.Enabled == false)
EnableADUserUsingUserPrincipal(_ADUserName);
this.StatusTextBox.AppendText("\r\n" + _ADUserName + " - is now ENABLED.\n\r");
}
}
private void UserStatusButton_Click(object sender, EventArgs e)

{
String _ADUserName = comboBox1.Text; // <-- The textbox you enter your username?
if (string.IsNullOrEmpty(comboBox1.Text) || comboBox1.Text == "0")
{
this.StatusTextBox.AppendText("\r\n" + _ADUserName + " - Please Enter Username!\n\r");
return;
}
PrincipalContext context = new PrincipalContext(ContextType.Domain);
UserPrincipal user = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, comboBox1.Text.Trim());

if (comboBox1.Text == "ADMIN1" | comboBox1.Text == "ADMIN2")
{
this.StatusTextBox.AppendText("\r\n" + _ADUserName + " - Dont get over smart. You are 'NOT' authorized to change admin accounts state!\n\r");
return;
}
if (user.Enabled == true) this.StatusTextBox.AppendText("\r\n" + _ADUserName + " - Status is ENABLED.\n\r");
else this.StatusTextBox.AppendText("\r\n" + _ADUserName + " - Status is DISABLED.\n\r"); ;
}
private void Form1_Load(object sender, EventArgs e)
{
PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
UserPrincipal qbeUser = new UserPrincipal(ctx);
PrincipalSearcher srch = new PrincipalSearcher(qbeUser);
foreach (var found in srch.FindAll())
{
UserPrincipal foundUser = found as UserPrincipal;
if (foundUser != null)
{
comboBox1.Items.Add(foundUser.SamAccountName);
}
}
}
private void linkLabel1_Click(object sender, EventArgs e)
{
System.Diagnostics.Process.Start("https://aacable.wordpress.com");
}

private void comboBox1_MouseHover(object sender, EventArgs e)
{
//ToolTip tt = new ToolTip();
//tt.Show("Click here to see user list", this.comboBox1, 2000);
}
}
}
// Code Ends Here. Take Care

Form1.Designer.cs


namespace WindowsFormsApplication2
{
partial class Form1
{
///
<summary>
/// Required designer variable.
/// </summary>

private System.ComponentModel.IContainer components = null;

///
<summary>
/// Clean up any resources being used.
/// </summary>

/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}

#region Windows Form Designer generated code

///
<summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>

private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Form1));
this.button1 = new System.Windows.Forms.Button();
this.button2 = new System.Windows.Forms.Button();
this.StatusTextBox = new System.Windows.Forms.TextBox();
this.UserStatusButton = new System.Windows.Forms.Button();
this.comboBox1 = new System.Windows.Forms.ComboBox();
this.linkLabel1 = new System.Windows.Forms.LinkLabel();
this.pictureBox1 = new System.Windows.Forms.PictureBox();
this.toolTip1 = new System.Windows.Forms.ToolTip(this.components);
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit();
this.SuspendLayout();
//
// button1
//
this.button1.Location = new System.Drawing.Point(157, 70);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(88, 23);
this.button1.TabIndex = 0;
this.button1.Text = "Disable User";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// button2
//
this.button2.Location = new System.Drawing.Point(157, 41);
this.button2.Name = "button2";
this.button2.Size = new System.Drawing.Size(88, 23);
this.button2.TabIndex = 2;
this.button2.Text = "Enable User";
this.button2.UseVisualStyleBackColor = true;
this.button2.Click += new System.EventHandler(this.button2_Click);
//
// StatusTextBox
//
this.StatusTextBox.BackColor = System.Drawing.Color.Black;
this.StatusTextBox.Cursor = System.Windows.Forms.Cursors.Arrow;
this.StatusTextBox.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.StatusTextBox.ForeColor = System.Drawing.SystemColors.Window;
this.StatusTextBox.Location = new System.Drawing.Point(263, 12);
this.StatusTextBox.Margin = new System.Windows.Forms.Padding(1);
this.StatusTextBox.Multiline = true;
this.StatusTextBox.Name = "StatusTextBox";
this.StatusTextBox.ReadOnly = true;
this.StatusTextBox.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
this.StatusTextBox.Size = new System.Drawing.Size(276, 216);
this.StatusTextBox.TabIndex = 3;
this.StatusTextBox.Text = "Status Box ...";
//
// UserStatusButton
//
this.UserStatusButton.Location = new System.Drawing.Point(157, 12);
this.UserStatusButton.Name = "UserStatusButton";
this.UserStatusButton.Size = new System.Drawing.Size(88, 23);
this.UserStatusButton.TabIndex = 4;
this.UserStatusButton.Text = "Check Status";
this.UserStatusButton.UseVisualStyleBackColor = true;
this.UserStatusButton.Click += new System.EventHandler(this.UserStatusButton_Click);
//
// comboBox1
//
this.comboBox1.AllowDrop = true;
this.comboBox1.BackColor = System.Drawing.SystemColors.Info;
this.comboBox1.DropDownHeight = 215;
this.comboBox1.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.comboBox1.ForeColor = System.Drawing.Color.Black;
this.comboBox1.FormattingEnabled = true;
this.comboBox1.IntegralHeight = false;
this.comboBox1.ItemHeight = 13;
this.comboBox1.Location = new System.Drawing.Point(6, 12);
this.comboBox1.Name = "comboBox1";
this.comboBox1.Size = new System.Drawing.Size(136, 21);
this.comboBox1.Sorted = true;
this.comboBox1.TabIndex = 5;
this.comboBox1.MouseHover += new System.EventHandler(this.comboBox1_MouseHover);
//
// linkLabel1
//
this.linkLabel1.AutoSize = true;
this.linkLabel1.Location = new System.Drawing.Point(260, 232);
this.linkLabel1.Name = "linkLabel1";
this.linkLabel1.Size = new System.Drawing.Size(279, 13);
this.linkLabel1.TabIndex = 7;
this.linkLabel1.TabStop = true;
this.linkLabel1.Text = "Management of Active Directory in C# by Syed.Jahanzaib";
this.linkLabel1.Click += new System.EventHandler(this.linkLabel1_Click);
//
// pictureBox1
//
this.pictureBox1.Image = ((System.Drawing.Image)(resources.GetObject("pictureBox1.Image")));
this.pictureBox1.Location = new System.Drawing.Point(6, 156);
this.pictureBox1.Name = "pictureBox1";
this.pictureBox1.Size = new System.Drawing.Size(239, 72);
this.pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
this.pictureBox1.TabIndex = 6;
this.pictureBox1.TabStop = false;
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(544, 248);
this.Controls.Add(this.linkLabel1);
this.Controls.Add(this.pictureBox1);
this.Controls.Add(this.comboBox1);
this.Controls.Add(this.UserStatusButton);
this.Controls.Add(this.StatusTextBox);
this.Controls.Add(this.button2);
this.Controls.Add(this.button1);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.Fixed3D;
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "Form1";
this.Text = "Active Directory Management Panel !";
this.Load += new System.EventHandler(this.Form1_Load);
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();

}

#endregion

private System.Windows.Forms.Button button1;
private System.Windows.Forms.Button button2;
private System.Windows.Forms.TextBox StatusTextBox;
private System.Windows.Forms.Button UserStatusButton;
private System.Windows.Forms.ComboBox comboBox1;
private System.Windows.Forms.LinkLabel linkLabel1;
private System.Windows.Forms.PictureBox pictureBox1;
private System.Windows.Forms.ToolTip toolTip1;
}
}


0fb310fdff985ec27edf24c236b1e2f3

Regard’s
Syed Jahanzaib


Contact !

 

Advertisements

Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: