In this exercise we are going to make a connection to Active Directory and create some new Organisational Units ready for us to place some users in. You will also use your first loop mechanism to create these organisational units (feel free to rename and add to these to make them more relevant to you).
You will also learn about try-catch blocks and use these to handle errors that may occur during any of the processing that takes place.
In this exercise you will be required to Power On and connect to the following servers from your Practice-Lab application:
Domain Controller
Domain Member
If this is the first time you are accessing a Practice-Lab why not take a few minutes to watch our video on getting started, or if you are still having difficulty connecting to your Practice-Lab device please refer to our help pages.
Connecting to Active Directory
Before we make use of our new User class we are going to create a few organisational units. To do this, we need to some information about the Active Directory server so that we can connect to it.
Here is the Active Directory information that is valid in our lab that we need to build our connection string (if you are not using a lab then you will need to change some of the settings in the code below):
- Domain name: PRACTICELABS
- Domain Controller: PLABDC01
- User name: Administrator
- Password: Passw0rd
Note: In real life you wouldnt be using the Administrator account to do these tasks!
To create the function that will create an OU move your cursor to below the static void main block and type the following:
public static void CreateOU(string ou)
{
try
{
if (!DirectoryEntry.Exists("LDAP://PLABDC01/ou=" + ou + ",dc=PRACTICELABS,dc=COM"))
{
try
{
DirectoryEntry ActiveDirectory = new DirectoryEntry("LDAP://PLABDC01/dc=PRACTICELABS,dc=COM", "Administrator", "Passw0rd");
DirectoryEntry NewOU = ActiveDirectory.Children.Add("OU=" + ou, "OrganizationalUnit");
NewOU.CommitChanges();
ActiveDirectory.CommitChanges();
Console.WriteLine("Created OU:{0}", ou);
}
catch (Exception error)
{
Console.WriteLine("An error occured while creating group:{0} :\n{1}", ou, error.Message);
}
}
else
{
Console.WriteLine("OU already exists");
}
}
catch (Exception error)
{
Console.WriteLine("We couldnt connect to AD! Is the server powered on?. Exception generated was\n{0}", error.Message);
}
}
Lets go through these lines one by one:
public static void CreateOU(string ou)
This line declares the function, we return nothing to the caller ( void ), its static meaning we dont have to generate a new instance of a class to use it (dont worry too much about this), the function name is CreateOU and finally, when we call the function we need to pass it the OU name (as a string) that we are going to create.
try
{
}
catch (Exception error)
{
}
These lines within the code catch any exceptions (errors/crashes if you like) that could occur. Its a really good idea to use these wherever you feel that an error could occur. A typical example is when you are dealing with external processes such as connecting to Active Directory, SQL Server, Exchange Server or just reading a plain text file that might not exist.
Code that is present within the try block will execute until a failure occurs, if one occurs then the exception message is passed to the catch block giving you the opportunity to do anything you need to do when an error occurs. You can have the optional finally {} block too which will execute whether a crash occurs or not, this is a great way to clean up (we are not covering dispose() or using() in this tutorial, but you can use dispose to help free up resources). If you added a finally statement, it would look like this:
try
{
}
catch (Exception error)
{
}
finally
{
}
if (!DirectoryEntry.Exists("LDAP://PLABDC01/ou=" + ou + ",dc=PRACTICELABS,dc=COM"))
This line attempts to connect to Active Directory and determine if our OU exists (please note that we are only checking in the root of the tree!). If the OU does NOT exist the exclamation mark ! means not i.e:
if(1 != 2)
{
//this is true;
}
DirectoryEntry Directory = new DirectoryEntry("LDAP://PLABDC01/dc=PRACTICELABS,dc=COM", "Administrator", "Passw0rd");
DirectoryEntry NewOU = Directory.Children.Add("OU=" + ou, "OrganizationalUnit");
NewOU.CommitChanges();
Directory.CommitChanges();
Console.WriteLine("Created OU:{0}", ou);
Thee 5 lines of code (they may appear wrapped) achieve the following:
Create a new connection to Active Directory, setting the context to the root (PRACTICELABS.COM), and specifying a username and password to connect with.
Create a new directory Organisational Unit object.
Commit the changes to the NewOU.
Commit the changes to Directory.
The last statement I will explain is this one:
Console.WriteLine("An error occured while creating group:{0} :\n{1}", ou, error.Message);
This statement writes an error message to the console, however the reason I wanted to explain it is because of the use of the \n and {0} commands. A \n is a carriage return, and the curly braces specifies that we are going to insert the values at the end of the command. You will see , ou followed by , error.Message . This means {0} will be populated with the value of ou which we originally passed in to the function, and {1} will be on a new line and populated with the value of error.Message (you could also display the contents of error.InnerException too which may help diagnosing issues).
Creating the OUs
OK So we have our OU creation code. So now we need to call it.
Finally we will add some meaningful code in the static void main section of our project where the entry point in to the program is (i.e. when I press run, the code inside this block will execute).
string[] Departments = { "Marketing", "Sales", "Human Resources" };
foreach (string dept in Departments)
{
CreateOU(dept);
}
This block of code does the following:
string[] Departments = { "Marketing", "Sales", "Human Resources" }; //Creates a string Array with the specified values.
foreach (string dept in Departments)
{
CreateOU(dept);
}
These commands iterate (loop) over each value in our string array passing in a variable called dept . We then call the CreateOU function and pass it the value of dept . Basically CreateOU is called with each of the values in our Department array.
We could have easily done:
CreateOU("Marketing");
CreateOU("Sales");
CreateOU("Human Resources");
But I wanted to show you a string array and an iteration statement using foreach.
This will create our OUs in sequence, to verify if you run the application now (press the green play button in the toolbar at the top of the Visual C# Express application). After it runs, connect to the Active Directory server, then open Active Directory Users and Computers, you should see your new OUs!
Before:
After:
Summary
In this exercise you created your first function which took a parameter that created an Organisational Unit in Active Directory. You used a string[] array to iterate through to pass the value of the array through to the OU create function.