• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 478
  • Last Modified:

Convert console to class library

Hi i have the below code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.DirectoryServices;

class Program
{
    static void Main()
    {

             
        
        DirectorySearcher searcher = new DirectorySearcher();
        searcher.Filter = "(&(objectCategory=person)(!(userAccountControl:1.2.840.113556.1.4.803:=2)))";
        foreach (SearchResult result in searcher.FindAll())
        Console.WriteLine(result.GetDirectoryEntry().Properties["sAMAccountName"].Value);
        Console.ReadLine();
        
    }
}


I wanna fire this event when i click the button in windows application.

some how i couldn't able to return the value

Open in new window

0
Sha1395
Asked:
Sha1395
  • 4
  • 4
2 Solutions
 
crysallusCommented:
If you're putting this code into a windows forms app, then you don't want to write output to the console.

You'll need to create some GUI element that will display the data in the right form for you. The easiest option would be to just add a textbox, and then assign everything you are writing to the console to the Text property of the textbox. That's the easiest method, but it probably won't be the best looking.

Is that what you mean by not being able to return the value?

If you need more help to set this up, just let us know.
0
 
anarki_jimbelCommented:
I'd have a method that searchs directories and returns a result as a string (or, may be, as string array, ir FileInfo etc)

Something like below:

private void button2_Click(object sender, EventArgs e)
        {
            MessageBox.Show(runDirSeacher());
        }

        private string runDirSeacher()
        {
            DirectorySearcher searcher = new DirectorySearcher();
            searcher.Filter = "(&(objectCategory=person)(!(userAccountControl:1.2.840.113556.1.4.803:=2)))";

            StringBuilder sb = new StringBuilder();

            foreach (SearchResult result in searcher.FindAll())
            {
                sb.AppendLine(result.GetDirectoryEntry().Properties["sAMAccountName"].Value);
            }

            return sb.ToString();
        }

Open in new window

0
 
Sha1395Author Commented:
thanks for your suggesting and code,the reason i want to convert this.

Already i have DLL file,i wanna add this one of my method in my existing file

this is the code,i have to include this method in that code


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.DirectoryServices;

namespace ActiveDir
{
    public class Employee
    {
        // instance variables 
        public String name, loginname, firstname;
        public String surname;
        public string title;
        public string company, Org;
        public string email, useraccountcontrol;
        public string mobile, telephonenumber, pager;
        public string city, state, country, postalcode;

        //   ...
        // Constructors

        public String FullName()
        {
           
            return String.Format("{0}. {1}. {2}. {3}. {4}. {5}. {6}. {7}. {8}. {9}. {10}. {11}. {12}. {13}. {14}.{15} ", name, title, company, surname, email, pager, mobile, telephonenumber, city, state, postalcode, country, loginname, firstname, useraccountcontrol, Org).Trim();
           
        }
        public static implicit operator String(Employee value)
        {
            return value.ToString();
        }

        public Employee()
        {
        }
    }

    public class ActiveDirSearch
    {
        public ActiveDirSearch()
        { }

        public Employee SearchUser(string username)
        {

            Employee employee = new Employee();


            try
            {
                DirectoryEntry entry = new DirectoryEntry("GC://Test", "Test\\Test", "Ld@Test", AuthenticationTypes.Secure);
                System.DirectoryServices.DirectorySearcher search = new System.DirectoryServices.DirectorySearcher(entry);
                
                if (username.Contains("."))
                {
                    string Fname = username.Substring(0, username.IndexOf("."));
                    Fname = Fname.Replace(" ", "");

                    string[] splitString = username.Split(new char[] { '.' });
                    username = splitString[splitString.Length - 1];

                    string email = Fname + "." + username;


                    search.Filter = "(mail=" + email + "*" + ")";

                }


                //--------If condition for Space and Dot search Filter---------------------------------------

                if (username.IndexOf(" ") > 0)

                    search.Filter = "(cn=" + username + ")";


                SearchResult result = search.FindOne();


                if (result != null)
                {

                    // user exists, cycle through LDAP fields (cn, telephonenumber etc.)

                    ResultPropertyCollection fields = result.Properties;

                    foreach (String ldapField in fields.PropertyNames)
                    {
                        // cycle through objects in each field e.g. group membership
                        // (for many fields there will only be one object such as name)                        
                        foreach (Object myCollection in fields[ldapField])
                        {
                            if (ldapField == "name")
                                employee.name = myCollection.ToString();
                            if (ldapField == "sn")
                                employee.surname = myCollection.ToString();
                            if (ldapField == "title")
                                employee.title = myCollection.ToString();
                            if (ldapField == "company")
                                employee.company = myCollection.ToString();
                            if (ldapField == "mobile")
                                employee.mobile = myCollection.ToString();
                            if (ldapField == "postalcode")
                                employee.postalcode = myCollection.ToString();
                            if (ldapField == "telephonenumber")
                                employee.telephonenumber = myCollection.ToString();
                            if (ldapField == "l")
                                employee.city = myCollection.ToString();
                            if (ldapField == "st")
                                employee.state = myCollection.ToString();
                            if (ldapField == "co")
                                employee.country = myCollection.ToString();
                            if (ldapField == "mail")
                                employee.email = myCollection.ToString();
                            if (ldapField == "otherpager")
                                employee.pager = myCollection.ToString();
                            if (ldapField == "co")
                                employee.country = myCollection.ToString();
                            if (ldapField == "cn")
                                employee.loginname = myCollection.ToString();
                            if (ldapField == "givenname")
                                employee.firstname = myCollection.ToString();
                            if (ldapField == "useraccountcontrol")
                                employee.useraccountcontrol = myCollection.ToString();
                            if (ldapField == "objectClass")
                                employee.Org = myCollection.ToString();
                        }
                    }

                }

                else
                {
                    return null;
                }
            }

            catch (Exception e)
            {
                throw e;
            }

            return employee;
        }
    }
}

Open in new window


Any suggestion,bcoz you might seen in the code,we are passing string and retrieve particular user info,if user click the button in the windows application then am going to call the method(already you provide the code).

So am i good to include the class in my exsisting file ?
0
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 
Sha1395Author Commented:
Hi Anarki,

I embedded your code in to  the class file,but its throwing error  at

sb.AppendLine(result.GetDirectoryEntry().Properties["sAMAccountName"].Value);

Error:The best overload method match for"system.Text.stringBuilder.AppendLine(String) has some invalid argument

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.DirectoryServices;

namespace ActiveDir
{
    public class Employee
{
    // instance variables 
    public String name,loginname,firstname;
    public String surname;
    public string title;
    public string company, Org;
    public string email,useraccountcontrol;
    public string mobile, telephonenumber,pager;
    public string city, state, country, postalcode;
    
        //   ...
    // Constructors

    public String FullName()
    {
      
        return String.Format("{0}. {1}. {2}. {3}. {4}. {5}. {6}. {7}. {8}. {9}. {10}. {11}. {12}. {13}. {14}.{15} ", name, title, company, surname, email, pager, mobile, telephonenumber, city, state, postalcode, country, loginname, firstname, useraccountcontrol,Org).Trim();
      
    }
    public static implicit operator String(Employee value)
    {
        return value.ToString();
    }

    public Employee()
    {
    }
}

    //***********************Class for Active user******************************

    public class ActiveUser
    {
        private string runDirSeacher()
        {
            DirectorySearcher searcher = new DirectorySearcher();
            searcher.Filter = "(&(objectCategory=person)(!(userAccountControl:1.2.840.113556.1.4.803:=2)))";

            StringBuilder sb = new StringBuilder();

            foreach (SearchResult result in searcher.FindAll())
            {
                sb.AppendLine(result.GetDirectoryEntry().Properties["sAMAccountName"].Value);
            }

            return sb.ToString();
        }

    }

    //***************************Code Ends Here**********************************

    public class ActiveDirSearch
    {
        public ActiveDirSearch()
        { }

        public Employee SearchUser(string username)
        {
            
            Employee employee = new Employee();

           
                



            try
            {
                DirectoryEntry entry = new DirectoryEntry("GC://Test", "Test\\Test", "Ld@Test", AuthenticationTypes.Secure);
               
                System.DirectoryServices.DirectorySearcher search = new System.DirectoryServices.DirectorySearcher(entry);
               
                if (username.Contains("."))
                {
                    string Fname = username.Substring(0, username.IndexOf("."));
                    Fname = Fname.Replace(" ", "");
                    
                    string[] splitString = username.Split(new char[] { '.' });
                    username = splitString[splitString.Length - 1];
                                                         
               
                    string email = Fname + "." + username ;
                   
                     search.Filter = "(mail=" + email + "*"+ ")";
               
                  
                   
                }


                //--------If condition for Space and Dot search Filter---------------------------------------

                if (username.IndexOf(" ") > 0)

                    search.Filter = "(cn=" + username + ")";

                  

                //-----------------------------------------Code Ends Here-------------------------------------

                SearchResult result = search.FindOne();


                if (result != null)
                {

                    // user exists, cycle through LDAP fields (cn, telephonenumber etc.)

                    ResultPropertyCollection fields = result.Properties;

                    foreach (String ldapField in fields.PropertyNames)
                    {
                        // cycle through objects in each field e.g. group membership
                        // (for many fields there will only be one object such as name)                        
                        foreach (Object myCollection in fields[ldapField])
                            {
                                 if (ldapField == "name") 
                                     employee.name = myCollection.ToString();
                                 if (ldapField == "sn")
                                     employee.surname = myCollection.ToString();
                                 if(ldapField=="title")
                                     employee.title=myCollection.ToString();
                                 if (ldapField == "company")
                                     employee.company = myCollection.ToString();
                                 if (ldapField == "mobile")
                                     employee.mobile = myCollection.ToString();
                                 if (ldapField == "postalcode")
                                     employee.postalcode = myCollection.ToString();
                                 if (ldapField == "telephonenumber")
                                     employee.telephonenumber = myCollection.ToString();
                                 if (ldapField == "l")
                                     employee.city = myCollection.ToString();
                                 if (ldapField == "st")
                                     employee.state = myCollection.ToString();
                                 if (ldapField == "co")
                                     employee.country = myCollection.ToString();
                                 if (ldapField == "mail")
                                     employee.email = myCollection.ToString();
                                 if (ldapField == "otherpager")
                                     employee.pager = myCollection.ToString();
                                 if (ldapField == "co")
                                     employee.country = myCollection.ToString();
                                 if (ldapField == "cn")
                                     employee.loginname = myCollection.ToString();
                                 if (ldapField == "givenname")
                                     employee.firstname = myCollection.ToString();
                                 if (ldapField == "useraccountcontrol")
                                     employee.useraccountcontrol = myCollection.ToString();
                                 if (ldapField == "objectClass")
                                     employee.Org = myCollection.ToString();
                            }
                      }

                 }

                         else
                        {
                   return null;
                      }
            }

            catch (Exception e)
            {
                throw e;
            }

            return employee ;
        }
    }
}

Open in new window

0
 
crysallusCommented:
Try:

sb.AppendLine(result.GetDirectoryEntry().Properties["sAMAccountName"].Value.ToString());

Open in new window

0
 
crysallusCommented:
You'll also need to make runDirSearcher public if you wish to call it from anywhere outside that class.
0
 
Sha1395Author Commented:
Thanks Crysallus for your help.

Yep based on your suggestion changed the code,as far now its builds with out error.

I didn't see your earlier post.sorry for that. I have answer for your question

"If you're putting this code into a windows forms app, then you don't want to write output to the console."

Yep you are right,that's why am saving the result in an object,so more than one app is calling my dll they will get the result as an object they can use it.

Please suggest or advice whatever i did so far ,is that make sense ?

here is my code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.DirectoryServices;

namespace ActiveDir
{
    public class Employee
    {
        // instance variables 
        public String name, loginname, firstname;
        public String surname;
        public string title;
        public string company, Org;
        public string email, useraccountcontrol;
        public string mobile, telephonenumber, pager;
        public string city, state, country, postalcode;

        //   ...
        // Constructors

        public String FullName()
        {

            return String.Format("{0}. {1}. {2}. {3}. {4}. {5}. {6}. {7}. {8}. {9}. {10}. {11}. {12}. {13}. {14}.{15} ", name, title, company, surname, email, pager, mobile, telephonenumber, city, state, postalcode, country, loginname, firstname, useraccountcontrol, Org).Trim();

        }
        public static implicit operator String(Employee value)
        {
            return value.ToString();
        }

        public Employee()
        {
        }
    }

    //***********************Class for Active user******************************

    public class ActiveUser
    {
        public string runDirSeacher()
        {
            DirectorySearcher searcher = new DirectorySearcher();
            searcher.Filter = "(&(objectCategory=person)(!(userAccountControl:1.2.840.113556.1.4.803:=2)))";

            StringBuilder sb = new StringBuilder();

            foreach (SearchResult result in searcher.FindAll())
            {
                
                sb.AppendLine(result.GetDirectoryEntry().Properties["sAMAccountName"].Value.ToString());
            }

            return sb.ToString();
        }

    }

    //***************************Code Ends Here**********************************

    public class ActiveDirSearch
    {
        public ActiveDirSearch()
        { }

        public Employee SearchUser(string username)
        {

            Employee employee = new Employee();

            
            try
            {
                DirectoryEntry entry = new DirectoryEntry("GC://Test", "Test\\Test", "Ld@Test", AuthenticationTypes.Secure);

                System.DirectoryServices.DirectorySearcher search = new System.DirectoryServices.DirectorySearcher(entry);

                if (username.Contains("."))
                {
                    string Fname = username.Substring(0, username.IndexOf("."));
                    Fname = Fname.Replace(" ", "");

                    string[] splitString = username.Split(new char[] { '.' });
                    username = splitString[splitString.Length - 1];


                    string email = Fname + "." + username;

                    search.Filter = "(mail=" + email + "*" + ")";



                }


                //--------If condition for Space and Dot search Filter---------------------------------------

                if (username.IndexOf(" ") > 0)

                    search.Filter = "(cn=" + username + ")";



                //-----------------------------------------Code Ends Here-------------------------------------

                SearchResult result = search.FindOne();


                if (result != null)
                {

                    // user exists, cycle through LDAP fields (cn, telephonenumber etc.)

                    ResultPropertyCollection fields = result.Properties;

                    foreach (String ldapField in fields.PropertyNames)
                    {
                        // cycle through objects in each field e.g. group membership
                        // (for many fields there will only be one object such as name)                        
                        foreach (Object myCollection in fields[ldapField])
                        {
                            if (ldapField == "name")
                                employee.name = myCollection.ToString();
                            if (ldapField == "sn")
                                employee.surname = myCollection.ToString();
                            if (ldapField == "title")
                                employee.title = myCollection.ToString();
                            if (ldapField == "company")
                                employee.company = myCollection.ToString();
                            if (ldapField == "mobile")
                                employee.mobile = myCollection.ToString();
                            if (ldapField == "postalcode")
                                employee.postalcode = myCollection.ToString();
                            if (ldapField == "telephonenumber")
                                employee.telephonenumber = myCollection.ToString();
                            if (ldapField == "l")
                                employee.city = myCollection.ToString();
                            if (ldapField == "st")
                                employee.state = myCollection.ToString();
                            if (ldapField == "co")
                                employee.country = myCollection.ToString();
                            if (ldapField == "mail")
                                employee.email = myCollection.ToString();
                            if (ldapField == "otherpager")
                                employee.pager = myCollection.ToString();
                            if (ldapField == "co")
                                employee.country = myCollection.ToString();
                            if (ldapField == "cn")
                                employee.loginname = myCollection.ToString();
                            if (ldapField == "givenname")
                                employee.firstname = myCollection.ToString();
                            if (ldapField == "useraccountcontrol")
                                employee.useraccountcontrol = myCollection.ToString();
                            if (ldapField == "objectClass")
                                employee.Org = myCollection.ToString();
                        }
                    }

                }

                else
                {
                    return null;
                }
            }

            catch (Exception e)
            {
                throw e;
            }

            return employee;
        }
    }
}

Open in new window

0
 
crysallusCommented:
Your code should work, though I could suggest a few improvements design-wise, such as:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.DirectoryServices;

namespace DirectoryServicesSearcher
{
	public class Employee
	{
		// instance variables 
		public String name, loginname, firstname;
		public String surname;
		public string title;
		public string company, Org;
		public string email, useraccountcontrol;
		public string mobile, telephonenumber, pager;
		public string city, state, country, postalcode;

		//   ...
		// Constructors

		public String FullName()
		{

			return String.Format("{0}. {1}. {2}. {3}. {4}. {5}. {6}. {7}. {8}. {9}. {10}. {11}. {12}. {13}. {14}.{15} ", name, title, company, surname, email, pager, mobile, telephonenumber, city, state, postalcode, country, loginname, firstname, useraccountcontrol, Org).Trim();

		}
		public static implicit operator String(Employee value)
		{
			return value.ToString();
		}

		public Employee()
		{
		}
	}

	public class Searcher
	{
		public Searcher()
		{ }

		public Employee FindUser(string username)
		{
			Employee employee = null;

			try
			{
				DirectoryEntry entry = new DirectoryEntry("GC://Test", "Test\\Test", "Ld@Test", AuthenticationTypes.Secure);

				System.DirectoryServices.DirectorySearcher search = new System.DirectoryServices.DirectorySearcher(entry);

				if (username.Contains("."))
				{
					string Fname = username.Substring(0, username.IndexOf("."));
					Fname = Fname.Replace(" ", "");

					string[] splitString = username.Split(new char[] { '.' });
					username = splitString[splitString.Length - 1];

					string email = Fname + "." + username;

					search.Filter = "(mail=" + email + "*" + ")";
				}

				//--------If condition for Space and Dot search Filter---------------------------------------
				if (username.IndexOf(" ") > 0)
					search.Filter = "(cn=" + username + ")";

				SearchResult result = search.FindOne();

				if (result != null)
				{
					employee = CreateEmployeeData(result);
				}
			}
			catch (Exception e)
			{
				throw e;
			}

			return employee;
		}

		public List<Employee> FindAllActiveUsers()
		{
			List<Employee> activeUsers = new List<Employee>();
			DirectorySearcher searcher = new DirectorySearcher();

			try
			{
				searcher.Filter = "(&(objectCategory=person)(!(userAccountControl:1.2.840.113556.1.4.803:=2)))";

				foreach (SearchResult result in searcher.FindAll())
				{
					activeUsers.Add(CreateEmployeeData(result));
				}
			}
			catch (Exception e)
			{
				throw e;
			}

			return activeUsers;
		}

		private Employee CreateEmployeeData(SearchResult result)
		{
			Employee employee = new Employee();

			if (result != null)
			{
				ResultPropertyCollection fields = result.Properties;

				foreach (String ldapField in fields.PropertyNames)
				{
					// cycle through objects in each field e.g. group membership
					// (for many fields there will only be one object such as name)                        
					foreach (Object myCollection in fields[ldapField])
					{
						if (ldapField == "name")
							employee.name = myCollection.ToString();
						if (ldapField == "sn")
							employee.surname = myCollection.ToString();
						if (ldapField == "title")
							employee.title = myCollection.ToString();
						if (ldapField == "company")
							employee.company = myCollection.ToString();
						if (ldapField == "mobile")
							employee.mobile = myCollection.ToString();
						if (ldapField == "postalcode")
							employee.postalcode = myCollection.ToString();
						if (ldapField == "telephonenumber")
							employee.telephonenumber = myCollection.ToString();
						if (ldapField == "l")
							employee.city = myCollection.ToString();
						if (ldapField == "st")
							employee.state = myCollection.ToString();
						if (ldapField == "co")
							employee.country = myCollection.ToString();
						if (ldapField == "mail")
							employee.email = myCollection.ToString();
						if (ldapField == "otherpager")
							employee.pager = myCollection.ToString();
						if (ldapField == "co")
							employee.country = myCollection.ToString();
						if (ldapField == "cn")
							employee.loginname = myCollection.ToString();
						if (ldapField == "givenname")
							employee.firstname = myCollection.ToString();
						if (ldapField == "useraccountcontrol")
							employee.useraccountcontrol = myCollection.ToString();
						if (ldapField == "objectClass")
							employee.Org = myCollection.ToString();
					}
				}
			}

			return employee;
		}
	}
}

Open in new window

This compiles, though I haven't tested it. The main changes I made was to put both searching methods into the one class, which, at least to me, makes more sense. Also, I changed some method names, and the method that finds all active users now returns a list full of employee objects for all the active users, rather than simply putting all that data into a single string, which is very limiting when it comes to outputting that data in the GUI. With the list of all active user's employee objects, that gives you far more flexibility when it comes to displaying that information on the GUI form.

Just a suggestion or 2... you don't have to go with this approach of course.
0
 
Sha1395Author Commented:
Om God !Thanks a lot for your very very kind answers.

Am gonna user yours anyway.i have add two more methods,first i will come up with some code for that,hope fully i will get help from you guys again to consolidate the whole code.

Thank you so much Crysallus
0

Featured Post

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 4
  • 4
Tackle projects and never again get stuck behind a technical roadblock.
Join Now