Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

Need a C# Expert to review code: I want to delete a single Wkstn obj from AD.

Posted on 2008-06-20
9
Medium Priority
?
256 Views
Last Modified: 2013-12-16
I'm relatively new to C# Programming and I've created a small Windows App to delete single and multiple workstation objects from Active Directory. I want to make sure the program is written correctly before I test. I certainly don't want to delete the wrong objects and get terminate from my Job. I need a C# Expert to evaluate.
With utmost gratitude,
WD
if (radioSingleObj.Checked)
            {
                if (textBoxSingle.Text == "")
                {
                    MessageBox.Show("You need to enter a workstation name", "Input Required", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                }
                else
                {
                    string objectName = textBoxSingle.Text;
                    MessageBox.Show(objectName);
 
                    string strPath = "LDAP://OU=Workstations,OU=BAND,DC=Corp,DC=BankofAmerica,DC=Com";
                    DirectoryEntry entry = null;
                    entry = new DirectoryEntry(strPath);
                    DirectorySearcher wkstnSearcher = new DirectorySearcher(entry);
                    wkstnSearcher.Filter = "(&(objectClass=computer)(|(cn=" + objectName + ")))";
                    wkstnSearcher.ClientTimeout.Seconds.Equals(30);
                    SearchResult searchWkstn = wkstnSearcher.FindOne();
                    if (wkstnSearcher.CacheResults)
                    {
                        labelWkstnObjStatus.Text = "Workstation object was located";
                        entry.Properties["cn"].Remove(objectName);
                        entry.CommitChanges();
                        entry.Close();
                    }
                    else
                    {
                        labelWkstnObjStatus.Text = "Unabled to locate Workstation object";
                    }
                }
            }

Open in new window

0
Comment
Question by:wally_davis
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 5
  • 4
9 Comments
 
LVL 96

Expert Comment

by:Bob Learned
ID: 21837270
First, are you able to create dummy entries that you can test code against?
0
 

Author Comment

by:wally_davis
ID: 21839585
Unfortunately I am not. But, we a good number of Disabled workstations in our immense AD Database and was able to run a test on a couple. I did attempt to test it and here's the problem I ran into:

I can delete a Wkstn object from Active Directory Computer and Users tool but not my C# app. When it hits the line of code "entry.CommitChanges();, it gives me the following error:

UnAuthorizedAccessException was unhandled; General Access denied error".

I've both passed in the Username/Password credentials/parameters and have also removed the passing in of the USERNAME and Password Parameters and I get the same results.
I don't have rights/permissions to mange our AD environment and the NTDSUTIL as someone suggested is not an option.
I figured since AD Users and Computers tool allows me to delete a Wkstn object that I'm probably just missing something within my code or could be overlooking. However, if there is something in AD that could prevent my code from deleting the object, I'm all EARS and would appreciate any insight.

0
 
LVL 96

Expert Comment

by:Bob Learned
ID: 21839605
>>I've both passed in the Username/Password credentials/parameters
I can't see how you attempt this.  What did you use to specify the credentials?  Is it a user that has access to delete ActiveDirectory entities?
0
What is a Denial of Service (DoS)?

A DoS is a malicious attempt to prevent the normal operation of a computer system. You may frequently see the terms 'DDoS' (Distributed Denial of Service) and 'DoS' used interchangeably, but there are some subtle differences.

 

Author Comment

by:wally_davis
ID: 21839621
yes. I passed in both my Username and Password (to the line of code below, p.s. see another excerpt of code below) as I have access to move, edit and delete Wkstn objects.

entry = new DirectoryEntry(strPath2, "USERNAME", "PASSWORD");
//string strPath = "LDAP://OU=AACOUNT,OU=FISHSUP,DC=HOLLY,DC=CREEK,DC=com";
                    string strPath2 = "LDAP://OU=FISHSUP,DC=HOLLY,DC=CREEK,DC=com";
                    DirectoryEntry entry = null;
                    entry = new DirectoryEntry(strPath2, "USERNAME", "PASSWORD");
                    DirectorySearcher wkstnSearcher = new DirectorySearcher(entry);
                    wkstnSearcher.Filter = "(&(objectClass=computer)(|(cn=" + objectName + ")))";
                    wkstnSearcher.ClientTimeout.Seconds.Equals(30);
                    SearchResult searchWkstn = wkstnSearcher.FindOne();
                    if (wkstnSearcher.CacheResults)
                    {
                        labelWkstnObjStatus.Text = "Workstation object was located";
                        entry.Properties["cn"].Remove(objectName);
                        entry.CommitChanges();
                        entry.Close();
                    }
                    else
                    {
                        labelWkstnObjStatus.Text = "Unabled to locate Workstation object";
                    }
 

Open in new window

0
 
LVL 96

Expert Comment

by:Bob Learned
ID: 21840461
Small, unimportant note:

All reference instances inherit from System.Object, which gives you Equals.  It returns a boolean, which you are ignoring in this case:

 wkstnSearcher.ClientTimeout.Seconds.Equals(30);

Try this:

 wkstnSearcher.ClientTimeout.Seconds = 30;
0
 
LVL 96

Expert Comment

by:Bob Learned
ID: 21840463
I don't see anything on the surface--you have an LDAP path (I assume it is valid, and the one that has the computers), and you have user credentials that has rights to manage objects.  Do you have the correct user credentials?  At first glance, it doesn't look like it from the exception that you are getting.
0
 

Author Comment

by:wally_davis
ID: 21846423
TheLearnedOne,
I changed the line of code to this, --> wkstnSearcher.ClientTimeout.Seconds = 30; and it gives me this error, "Error      1, Property or indexer 'System.TimeSpan.Seconds' cannot be assigned to -- it is read only".

Second, I discovered that there is a third parameter I could pass in to the line of code --> "entry = new DirectoryEntry(strPath2, "USERNAME", "PASSWORD", AuthenticationTypes authentication type);
It's a Bitwise value but I wouldn't know what to enter in so I'm going to see if I can find the values defined somewhere on the Internet. I know I'm using the correct credentials because I have deleted some Workstation objects from AD using the Active Directorys Users and Computers MMC Tool. Any further help would be appreciated. I feel like we're close on this one with the AuthenticationTypes.
0
 

Author Comment

by:wally_davis
ID: 21846792
TheLearnedOne,

Here's something I found on the Experts-Exchange website that pretty much indicates I'm not passing in my user credentials correctly. I already have one search Filter. Is it possible to have a second? If not, since I'm new to C#, would you be able to show me how I could add or use this code to replace what I have already in order to authenticate my user credentials properly to allow me to delete the computer object properly??
Well, in that case it should be correct. To however authenticate a user, you can't use the code without modification. Firstly, you need to specify more detail on the query filter
 
mySearcher.Filter = String.Format("(&(objectClass=user)(objectCategory=person)(cn={0}))", userId);
 
Secondly , use FindOne instead of FindAll
 
SearchResult result = searcher.FindOne();
if ( result != null )
{
     String userPath = "LDAP://LDAPServer/" + (String) result.Properties["distinguishedName"][0];
     DirectoryEntry user = new DirectoryEntry( userPath, userId, password );
     try
     {
          user.RefreshCache();
     }
     catch (ComException ex)
     {
         // exception is thrown when password is wrong
         // check the error number
     }
     finally
     {
         if ( user != null ) { user.Close(); user.Disposed(); }
     }
}

Open in new window

0
 

Accepted Solution

by:
wally_davis earned 0 total points
ID: 21858010
Appears that Active Directory support team may have restricted some permissions to manage certain objects. I'm investigating now. Appears that code I've written will work but just failes on the Entry.CommitChanges(); method/line of code. Please have this question removed.
0

Featured Post

How to Use the Help Bell

Need to boost the visibility of your question for solutions? Use the Experts Exchange Help Bell to confirm priority levels and contact subject-matter experts for question attention.  Check out this how-to article for more information.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Flash (http://en.wikipedia.org/wiki/Adobe_Flash) has evolved over the years to where it has become a masterful tool for displaying content screen.  It has excellent layout placement, UI precision as well as rendering capabilities. This, along with t…
Many of us here at EE write code. Many of us write exceptional code; just as many of us write exception-prone code. As we all should know, exceptions are a mechanism for handling errors which are typically out of our control. From database errors, t…
Do you want to know how to make a graph with Microsoft Access? First, create a query with the data for the chart. Then make a blank form and add a chart control. This video also shows how to change what data is displayed on the graph as well as form…
Visualize your data even better in Access queries. Given a date and a value, this lesson shows how to compare that value with the previous value, calculate the difference, and display a circle if the value is the same, an up triangle if it increased…

688 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question