Solved

Convert console application to dll class library file

Posted on 2011-02-22
24
1,439 Views
Last Modified: 2012-08-14
Hi ,

Below is my code ,when i was written the whole code in console application.now i have to change the whole console application in to .dll class library file,in that case am going to create an windows application(call this class library file) and pass the string and retrieve the user information from AD.

HEre is my code (Credit goes to lot of people esp:Dhaest)

using System;
using System.Text;
using System.DirectoryServices;

namespace activeDirectoryLdapExamples
{
    class Program
    {
        static void Main(string[] args)
        {
           
            Console.Write("Enter user: ");
            String username = Console.ReadLine();
           
          if (username.Contains("."))
           
         {            
           // username = username.Replace(".", " ");
           //   string updateuser=username.Substring(0,username.IndexOf("."));

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

            username = splitString[splitString.Length - 1];
             
              //string surname = splitString[splitString.Length-1];
            // username = username.Split(".");)
            // string updateUser1 = user1.Substring(0, user1.IndexOf("."));
            Console.WriteLine(username);
           
         
          }
         
       //   elseif (username.Contains(" ")
       //     {
       // //-- Do nothing here. This is how we want it.
       //      }
       //   else
       //   {
       //// Neither "John.Doe" or "John Doe" were encountered. Handle this however you want.
       //   }


            try
            {
                // create LDAP connection object

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

                // create search object which operates on LDAP connection object
                // and set search object to only find the user specified

               // DirectorySearcher search = new DirectorySearcher(myLdapConnection);
                System.DirectoryServices.DirectorySearcher search = new System.DirectoryServices.DirectorySearcher(entry);
              //  search.Filter = "(cn=" + username + ")";
             
                if (username.IndexOf(" ") > 0)
                    search.Filter = "(cn=" + username + ")";
                else
                    search.Filter = "(sn=" + username + ")";
               
 // create results objects from search object

                  //  search.Filter = "(sn=" + username + ")";
                    // create results objects from search object
           
                    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])
                        Console.WriteLine(String.Format("{0,-20} : {1}", ldapField, myCollection.ToString()));
                   
                    }
                }

                else
                {

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

                    //ResultPropertyCollection fields = result.Properties;
                    //foreach (string ldapfield in fields.PropertyNames)
                    //{
                    //    foreach (Object myCollection in fields
                    //        Console.WriteLine(String.Format("{0,-20} : {1}", ldapField, myCollection.ToString()));
                    //}
                    // user does not exist
                    Console.WriteLine("User not found!");
                }
            }

            catch (Exception e)
            {
                Console.WriteLine("Exception caught:\n\n" + e.ToString());
            }
        }


    }
}
0
Comment
Question by:Sha1395
  • 15
  • 9
24 Comments
 
LVL 53

Accepted Solution

by:
Dhaest earned 500 total points
ID: 34950362
You can easily transform this into a class, function that you can call.
What do you want to return if you found, not found the user ?

Example: code in your console-app (add a reference to the dll-project)

using System;
using System.Text;


namespace activeDirectoryLdapExamples
{
    class Program
    {
        static void Main(string[] args)
        {

            Console.Write("Enter user: ");
            String username = Console.ReadLine();

            ActiveDir.ActiveDirSearch search = new ActiveDir.ActiveDirSearch();

            string output = search.SearchUser(username);

        }


    }
}


Below you find the class in your dll-project

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

namespace ActiveDir
{
    public class ActiveDirSearch
    {
        public ActiveDirSearch()
        { }

        public string SearchUser(string username)
        {
            string returnString = "";

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


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

                // DirectorySearcher search = new DirectorySearcher(myLdapConnection);
                System.DirectoryServices.DirectorySearcher search = new System.DirectoryServices.DirectorySearcher(entry);
                //  search.Filter = "(cn=" + username + ")";

                if (username.IndexOf(" ") > 0)
                    search.Filter = "(cn=" + username + ")";
                else
                    search.Filter = "(sn=" + 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])
                            returnString += String.Format("{0,-20} : {1}", ldapField, myCollection.ToString());

                    }

                }

                else
                {


                    returnString =  "User not found!";
                }
            }

            catch (Exception e)
            {
                throw e;
            }

            return returnString;
        }
    }
}

Open in new window

0
 

Author Comment

by:Sha1395
ID: 34950403
Wow ! awesome Dhaest.

If i found the user in the AD,then i will return ("first name,"last name","email id" and telephone number),the return value should store as an object,so any one can create an windows application and call my dll to retrieve the user info.

this is the actual plan i have right now.

Thanks and thanks a lot for your great help
0
 
LVL 53

Expert Comment

by:Dhaest
ID: 34950414
>> the return value should store as an object

Just replace the type in the call to the procedure
fe: public string SearchUser(string username)
will be
public Employee SearchUser(string username)
0
 

Author Comment

by:Sha1395
ID: 34950481
Oh my god ! Genius

Changed the code based on your suggestion.Am going to create a class file then i will call this class file thru console application (The code you provided already).


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

namespace ActiveDir
{
    public class ActiveDirSearch
    {
        public ActiveDirSearch()
        { }

        public Employee string SearchUser(string username)
        {
            string returnString = "";

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


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

                // DirectorySearcher search = new DirectorySearcher(myLdapConnection);
                System.DirectoryServices.DirectorySearcher search = new System.DirectoryServices.DirectorySearcher(entry);
                //  search.Filter = "(cn=" + username + ")";

                if (username.IndexOf(" ") > 0)
                    search.Filter = "(cn=" + username + ")";
                else
                    search.Filter = "(sn=" + 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])
                            returnString += String.Format("{0,-20} : {1}", ldapField, myCollection.ToString());

                    }

                }

                else
                {


                    returnString =  "User not found!";
                }
            }

            catch (Exception e)
            {
                throw e;
            }

            return returnString;
        }
    }
}
0
 

Author Closing Comment

by:Sha1395
ID: 34950499
Only one thing DHAEST Rocks
0
 
LVL 53

Expert Comment

by:Dhaest
ID: 34950516
Still need to make some changes, because you want to return an object ...
Remember to create a class, employee, which will be used for passing

Another remark: in your calling of the procedure, if you get the return, check if the employee object is filled or not (because you can return a null-value if no object has been found)

Also how are you filling the employee-object ?

foreach (Object myCollection in fields[ldapField])
                            returnString += String.Format("{0,-20} : {1}", ldapField, myCollection.ToString());

--> probably you want something dynamic ... depending of the ldapField (and do you want them all ?)
foreach (Object myCollection in fields[ldapField])
{
     if (ldapField == "name") employee.Name = myCollection.ToString());
     if (ldapField == "surname") employee.surname = myCollection.ToString());
      ....
}
public Employee string SearchUser(string username)
        {
            
            Employee employee = new Employee();

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


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

                // DirectorySearcher search = new DirectorySearcher(myLdapConnection);
                System.DirectoryServices.DirectorySearcher search = new System.DirectoryServices.DirectorySearcher(entry);
                //  search.Filter = "(cn=" + username + ")";

                if (username.IndexOf(" ") > 0)
                    search.Filter = "(cn=" + username + ")";
                else
                    search.Filter = "(sn=" + 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 == "surname") employee.surname = myCollection.ToString());
      ....
}
                    }

                }

                else
                {
                   return null;
               }
            }

            catch (Exception e)
            {
                throw e;
            }

            return employee ;
        }

Open in new window

0
 

Author Comment

by:Sha1395
ID: 34950556
Yes i want to most of them,like name,phone no,employee id etc. can i add something

if (ldapField == "Telephone") employee.Telephone= myCollection.ToString());


is that the only change i need to do ?
0
 
LVL 53

Expert Comment

by:Dhaest
ID: 34950581
I think so. Try to create the code like you want it and just let me know if you still have a problem somewhere ...
0
 

Author Comment

by:Sha1395
ID: 34950583
is it possible rather than passing null value ,pass constant string ("no user found") ? to employee object

Also how are you filling the employee-object ?

I thought the below code will return the whole value

   returnString += String.Format("{0,-20} : {1}", ldapField, myCollection.ToString());

so you are suggesting to return the value like this

 if (ldapField == "name") employee.Name = myCollection.ToString());
     if (ldapField == "surname") employee.surname = myCollection.ToString());
      ....

0
 
LVL 53

Expert Comment

by:Dhaest
ID: 34950648
1. I thought the below code will return the whole value
   returnString += String.Format("{0,-20} : {1}", ldapField, myCollection.ToString());

-->  Yes it will, but as a string, not as an object.

2. possible rather than passing null value ,pass constant string ("no user found") ?

Yes you can, if you add fe a property on the employee object, fe boolean bFound. In the code that receives the object, you can check if this is true or false ...
0
 

Author Comment

by:Sha1395
ID: 34950655
Okie created class library file and add your code,i don't know it shows error

//Invalid token String in Class

//Type or name space Employee could not found

// if (ldapField == "name") employee.Name = myCollection.ToString()); "Throws error,so no point add more field there.do i miss something here ?

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

namespace ActiveDir
{
    public class ActiveDirSearch
    {
        public ActiveDirSearch()
        { }

        public Employee string SearchUser(string username) //Invalid token String in Class
        {
           
            Employee employee = new Employee(); //Type or name space Employee could not found

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


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

                // DirectorySearcher search = new DirectorySearcher(myLdapConnection);
                System.DirectoryServices.DirectorySearcher search = new System.DirectoryServices.DirectorySearcher(entry);
                //  search.Filter = "(cn=" + username + ")";

                if (username.IndexOf(" ") > 0)
                    search.Filter = "(cn=" + username + ")";
                else
                    search.Filter = "(sn=" + 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 == "surname") employee.surname = myCollection.ToString());
   
}
                    }

                }

                else
                {
                   return null;
               }
            }

            catch (Exception e)
            {
                throw e;
            }

            return employee ;
        }
0
 
LVL 53

Expert Comment

by:Dhaest
ID: 34950666
Did you create a employee-class ?
public class Employee
{
    // instance variables 
     public String name;
    public String surname;
           ...
    // Constructors
    public Employee()
    {
    }
}

Open in new window

0
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 

Author Comment

by:Sha1395
ID: 34950703
Ooh do i need to create an employee class in my class library file  ?but why,sorry to bother you but am trying to understand the code.

0
 

Author Comment

by:Sha1395
ID: 34950834
Okie i got it now

Please have a look at my code ,still showing an error "
//Invalid token String in Class

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;
    public String surname;
     public string title;
        //   ...
    // Constructors
    public Employee()
    {
    }
}

    public class ActiveDirSearch
    {
        public ActiveDirSearch()
        { }

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

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


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

                // DirectorySearcher search = new DirectorySearcher(myLdapConnection);
                System.DirectoryServices.DirectorySearcher search = new System.DirectoryServices.DirectorySearcher(entry);
                //  search.Filter = "(cn=" + username + ")";

                if (username.IndexOf(" ") > 0)
                    search.Filter = "(cn=" + username + ")";
                else
                    search.Filter = "(sn=" + 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 == "surname")
         employee.surname = myCollection.ToString();
    if(ldapField=="title")
        employee.title=myCollection.ToString();
   
}
                    }

                }

                else
                {
                   return null;
               }
            }

            catch (Exception e)
            {
                throw e;
            }

            return employee ;
        }
    }
}


0
 
LVL 53

Expert Comment

by:Dhaest
ID: 34950888
Where do you get the error ?
0
 

Author Comment

by:Sha1395
ID: 34950896
public Employee string SearchUser(string username)

Invalid token string in class
0
 
LVL 53

Expert Comment

by:Dhaest
ID: 34950901
public Employee string SearchUser(string username)

Must be

public Employee SearchUser(string username)
0
 

Author Comment

by:Sha1395
ID: 34950956
Thanks a lot Dhaest.
0
 

Author Comment

by:Sha1395
ID: 34950999
Tomorrow i will consolidate the Console application file as well as the class library file.In that way it will handy to some one to use your code
0
 

Author Comment

by:Sha1395
ID: 34955854
hi Dhaest,

i wrote a console app (the code you gave me earlier),throwing an error message at

 string output = search.SearchUser(username);

"can't implictly convert type 'ActiveDir.employee to string"
0
 

Author Comment

by:Sha1395
ID: 34956027
Here is the consolidated code for console and class files



I got an error on my console application

"can't implictly convert type 'ActiveDir.employee to string"

Console Application code :

Collapse

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

namespace activeDirectoryLdapExamples
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("Enter user: ");
            String username = Console.ReadLine();
            ActiveDir.ActiveDirSearch search = new ActiveDir.ActiveDirSearch();
            string output = search.SearchUser(username);

        }

    }
}

Class File Code:

Collapse

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;
    public String surname;
     public string title;
        //   ...
    // Constructors
    public Employee()
    {
    }
}

    public class ActiveDirSearch
    {
        public ActiveDirSearch()
        { }

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

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


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

                // DirectorySearcher search = new DirectorySearcher(myLdapConnection);
                System.DirectoryServices.DirectorySearcher search = new System.DirectoryServices.DirectorySearcher(entry);
                //  search.Filter = "(cn=" + username + ")";

                if (username.IndexOf(" ") > 0)
                    search.Filter = "(cn=" + username + ")";
                else
                    search.Filter = "(sn=" + 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 == "surname")
         employee.surname = myCollection.ToString();
    if(ldapField=="title")
        employee.title=myCollection.ToString();
   
}
                    }

                }

                else
                {
                   return null;
               }
            }

            catch (Exception e)
            {
                throw e;
            }

            return employee ;
        }
    }
}

did i miss something here ?
0
 
LVL 53

Expert Comment

by:Dhaest
ID: 34958616
You are returning an employee object. So in your console-application you need something like this:


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

namespace activeDirectoryLdapExamples
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("Enter user: ");
            String username = Console.ReadLine();
            ActiveDir.ActiveDirSearch search = new ActiveDir.ActiveDirSearch();
            ActiveDir.Employee output = search.SearchUser(username);
            Console.Output output.name;
        }

    }
}

Open in new window

0
 

Author Comment

by:Sha1395
ID: 34960041
Thanks for that Dhaest, i was modified the code in class library file ,using string format in the empolyee class and return the value to console appliaction.

Tested it and it works,i will post the code soon.


0
 

Author Comment

by:Sha1395
ID: 34960127
i have one more question here,please pardon me,

i was trying to do like this in my search filter but its throwing error.
if (username.Contains(".")) //what am trying to achieve here is  

//([quote]if user name comes like Joe(space)wil.smith,then i will split the string based on  dot like First Name :Joe(space)will and Lastname:Smith,then remove space in the first name: JoeWill.
Then use the first and last name in the search filter to compare against in AD.)[/quote]

            {
                string Fname = username.Substring(0, username.IndexOf("."));
                Fname = Fname.Replace("", " ");
                string[] splitString = username.Split(new char[] { '.' });
                username = splitString[splitString.Length - 1];
               
            }

  if (username.IndexOf(" ") > 0)
                    search.Filter = "(cn=" + username + ")";
                else
                    search.Filter = "(sn=" + username + ")" & "(givenname=" + Fname + "));

Open in new window

in this case,if i pass a string like Joe will.smith

then

My first name should be : Joewill (it should eliminate the space,if space is there,if not leave it as it is)
lastname=smith

then i will use the search filter against "sn" and "givenname" retrieve the user info.

Please correct my mistakes,its throwing an error.
0

Featured Post

Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
How to get a file from SqlServer DB 4 29
C# Problem Solving Execerscise 5 43
Create XML 5 34
c# if statement weird reaction 3 30
Article by: Najam
Having new technologies does not mean they will completely replace old components.  Recently I had to create WCF that will be called by VB6 component.  Here I will describe what steps one should follow while doing so, please feel free to post any qu…
Entity Framework is a powerful tool to help you interact with the DataBase but still doesn't help much when we have a Stored Procedure that returns more than one resultset. The solution takes some of out-of-the-box thinking; read on!
This video explains how to create simple products associated to Magento configurable product and offers fast way of their generation with Store Manager for Magento tool.
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…

747 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

10 Experts available now in Live!

Get 1:1 Help Now