Solved

Convert console to class library

Posted on 2011-02-24
9
467 Views
Last Modified: 2012-05-11
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
Comment
Question by:Sha1395
  • 4
  • 4
9 Comments
 
LVL 8

Accepted Solution

by:
crysallus earned 250 total points
Comment Utility
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
 
LVL 29

Assisted Solution

by:anarki_jimbel
anarki_jimbel earned 250 total points
Comment Utility
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
 

Author Comment

by:Sha1395
Comment Utility
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
 

Author Comment

by:Sha1395
Comment Utility
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
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
LVL 8

Expert Comment

by:crysallus
Comment Utility
Try:

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

Open in new window

0
 
LVL 8

Expert Comment

by:crysallus
Comment Utility
You'll also need to make runDirSearcher public if you wish to call it from anywhere outside that class.
0
 

Author Comment

by:Sha1395
Comment Utility
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
 
LVL 8

Expert Comment

by:crysallus
Comment Utility
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
 

Author Comment

by:Sha1395
Comment Utility
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

Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

Join & Write a Comment

It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
Illustrator's Shape Builder tool will let you combine shapes visually and interactively. This video shows the Mac version, but the tool works the same way in Windows. To follow along with this video, you can draw your own shapes or download the file…
You have products, that come in variants and want to set different prices for them? Watch this micro tutorial that describes how to configure prices for Magento super attributes. Assigning simple products to configurable: We assigned simple products…

728 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

Need Help in Real-Time?

Connect with top rated Experts

8 Experts available now in Live!

Get 1:1 Help Now