Saturday 27 March 2010

Who needs help with the Haddock!

Hello it's your friendly neighbourhood techhie again!
Well a passionate one at any rate.
So one of the issues which I am sure everyone who is a sys admin on AD hits at some point scripting in their life is that darn long LDAP address you need to modify objects.
Remind you of how annoying it is to take that entire object string from the AD Object in AD Users and Computers (or as I lovingly call it ADUC pron: Haddock without the 'H')
Well here is a tool you can write very simply using the wonderful Visual C# Express Edition 2009.
Now before you all go arrrrgggghhhhh progamming or the other word argh another programming language. Everyone just take a deep breath and quote the words from the "Hitchhikers Guide to the Galaxy." which is "Don't Panic!"
First things first, download and install the Visual C# Express Edition 2008 from the Microsoft site. Install it with all the typical settings.
Once this is done create a new project using Windows Form Application template and give it a name something like AD2LDAP.

This form will need two text boxes and two command buttons.
One of the Text boxes will be called Username where you will enter the username of the user.
The second Text Box will be called LDAPPathText which will display the full path of the user using the standard LDAP display format.

Now to start searching the Active Directory you need to add a reference to the DirectoryServices Assembly. You do this by clicking on Project...Add Reference.
So now you now have a form To look something like this. I have added some niceties to this like some labels but the application should work as long as you have the components listed above.
We now need to confirm that the “System.DirectoryServices” assembly has been added to the form for it to use the searching abilities.
You can do this by looking at the associated cs file for the form. The easiest way is to double click on any of the buttons we have on the form.
What you should see is the source code associated with the form.
Over here at the top you can see the line
using System.DirectoryServices;

This basically states that the Directory Services Assembly is now available for use in this application. If you do not see it there just go ahead and type it.
Now what we are going to do is to create a generic search function which checks if the object exists in the local Active Directory. We will call this function IsExistInAD which will return a boolen response (i.e yes or no, true or false) where it will take an normal string argument (i.e. a word, sentence, etc) and search for it in the local Active Directory structure and say yes it exists or no it doesn’t.
What I will show you a sample code here and then explain it in detail.
bool IsExistInAD(string loginName)
{
DirectorySearcher search = new DirectorySearcher();
search.Filter = String.Format("(SAMAccountName={0})", loginName);
search.PropertiesToLoad.Add("cn");
SearchResult result = search.FindOne();

if (result == null)
{
return false;
}

return true;
}

What you have to do is create a DirectorySearcher Component called search which will have all the characteristics and attributes of a DirectorySearcher component.
DirectorySearcher search = new DirectorySearcher();

We will then set it up to search for only the username object in Active Directory.
search.Filter = String.Format("(SAMAccountName={0})", loginName);
Out of it we only want it to return the canonical name (“cn”) of the object which in other words is the LDAP string we are after.
search.PropertiesToLoad.Add("cn");
We will then use the search function to locate the username and see if it exists in the current domain an return the result to an object of type SearchResult.
SearchResult result = search.FindOne();
We shall now see if the result of this has been successful in finding the canonical name of this user. If it hasn’t been successful then the SearchResult object result should be empty. If it is empty then the user has not been found so we can return a false result to say the user doesn’t exist.
if (result == null)
{
return false;
}

Otherwise in all other instances we can return the user exists.
return true;

So this allows us to test to see if the user exists in AD.
Let us now look at how we locate the LDAP path for the user using one of the buttons.
private void button1_Click(object sender, EventArgs e)
{

if (UserName.Text.Length > 0)
{
if (!IsExistInAD(UserName.Text.ToString()))
{
UserName.ForeColor = System.Drawing.Color.Red;
MessageBox.Show("User Not Found! Please enter the exact username of the user. ", "User Check");
}
else
{
UserName.ForeColor = System.Drawing.Color.Blue;
DirectorySearcher search = new DirectorySearcher();
search.Filter = String.Format("(SAMAccountName={0})", UserName.Text.ToString());
search.PropertiesToLoad.Add("cn");
SearchResult result = search.FindOne();
LDAPPathText.Text = result.Path.ToString();
}
}
else
{
MessageBox.Show("User Name not Entered! Please enter the exact username of the user. ", "User Check");
}
}

As before in the function to check if the user exists in AD we use the same method however we use the generic function IsExistInAD to check if the user exists before we continue to return LDAP Path in one of our text boxes to use.
if (!IsExistInAD(UserName.Text.ToString()))
{
UserName.ForeColor = System.Drawing.Color.Red;
MessageBox.Show("User Not Found! Please enter the exact username of the user. ", "User Check");
}

So in general what we want is for the application to return a error message if the user doesn’t exist and to validate for conditions when nothing is entered in the username text box and all other conditions before we perform the search.
So this is a simple form of searching for users. Of course this is not what you might call very secure in the sense of handling usernames and passwords, defining the domain to search etc. But it is a good platform to start writing your own applications using the power of Active Directory and c#

Here is the source code in case you need it.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.DirectoryServices;


namespace ADtoLDAP
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

bool IsExistInAD(string loginName)
{
DirectorySearcher search = new DirectorySearcher();
search.Filter = String.Format("(SAMAccountName={0})", loginName);
search.PropertiesToLoad.Add("cn");
SearchResult result = search.FindOne();

if (result == null)
{
return false;
}

return true;
}


private void button1_Click(object sender, EventArgs e)
{

if (UserName.Text.Length > 0)
{
if (!IsExistInAD(UserName.Text.ToString()))
{
UserName.ForeColor = System.Drawing.Color.Red;
MessageBox.Show("User Not Found! Please enter the exact username of the user. ", "User Check");
}
else
{
UserName.ForeColor = System.Drawing.Color.Blue;
DirectorySearcher search = new DirectorySearcher();
search.Filter = String.Format("(SAMAccountName={0})", UserName.Text.ToString());
search.PropertiesToLoad.Add("cn");
SearchResult result = search.FindOne();
LDAPPathText.Text = result.Path.ToString();
}
}
else
{
MessageBox.Show("User Name not Entered! Please enter the exact username of the user. ", "User Check");
}
}


private void button2_Click(object sender, EventArgs e)
{
Application.Exit();
}
}
}

No comments: