locked
How to get the Windows username of the currently logged-in user to pass to Active Directory in C# RRS feed

  • Question

  • User-1491118713 posted
    Hello to all,

    It's hard to explain this but I will do my best.

    I am building an Intranet application which needs to authenticate users off Active Directory
    after identifying them through their Windows login username. Below are the series of events that need to happen:

    1. User logs onto their Windows desktop within the company.

    2. The user pulls up a web browser and enters the Intranet app URL e.g. http://companyintranet

    3. As soon as the user hits the app the authentication module kicks in to work out who they are.
    This is where the business logic should work out the current user's Windows login username. When it's
    got the user's Windows login username it can then use that information to fetch more information
    about that user such as their email addresss, home adddress etc from AD.


    Active Directory is already set up and operational. I have already written a C# Active Directory
    wrapper class which I can use to pull out the the data from AD.

    Anyone has a clue how I can sort this puzzle out? And what happens if they access the app from outside teh company...
    and to add to the confusion what happens when they access it using a Linux box or even Apple Mac?


    Thanks in advance.

    Ernest
    Thursday, November 16, 2006 8:08 AM

Answers

  • User-1491118713 posted

    Hi zullu,

    In my authentication class I have this method

     

    1    /// <summary>
    2    		/// Gets the windows login for the currently logged in user in the client computer i.e
    3    		/// the person requesting the page
    4    		/// </summary>
    5    		/// <returns>The username of the user requesting the page, might contain domain</returns>
    6    		public string GetCurrentUserWindowsLogin()
    7    		{				
    8    
    9    			string windowsLogin = Page.User.Identity.Name;			
    10   			//Normally if the domain is present you get a string like DOMAINNAME\username, remove the domain
    11   			int hasDomain = windowsLogin.IndexOf(@"\");
    12   			if (hasDomain > 0)
    13   			{
    14   				windowsLogin = windowsLogin.Remove(0, hasDomain + 1);
    15   			} //end if			
    16   			return windowsLogin;
    17   		} //end GetCurrentUserWindowsLogin
    

     

    The method above gets me the user's AD SAMAccountName which I can then use to pass on to AD to query for more data.

    I then wrote the class below which allowed me to get people's information fropm AD based on their Windows login e.g. zullu
    This class can also be run as a standalone DOS application when compiled into an EXE. I test my classes this way ;) The AD connection details were kept in the Web.Config file which means you will need to give the program the correct values for "ldap_path" , "ldap_login_username", and "ldap_login_password"  . Give it a go and I hope it helps:

     

    1    using System;
    2    using System.Configuration;
    3    using System.DirectoryServices;
    4    using System.Security;
    5    using System.Security.Principal;
    6    using System.Globalization;
    7    
    8    namespace DataAccess
    9    {
    10   	/// <summary>
    11   	/// This class provides functionality to query Microsoft Active Directory 
    12   	/// for USER Objects information. It then makes that information available
    13   	/// to the calling client using a public encapsulated struct. 
    14   	/// </summary>
    15   	/// <remarks>
    16   	/// Instead of maintaining several properties for the USER data a public 
    17   	/// struct is used to expose the Active Directory USER Object data. 
    18   	/// This makes maintanance of the class very easy
    19   	/// </remarks>
    20   	/// <author>Ernest M. Fakudze</author>
    21   	/// <date_written>14 Nov 2006</date_written>
    22   	/// <version>1.0</version>
    23   	/// <last_update>27 Nov 2006</last_update>
    24       
    25   	public sealed class ActiveDirectoryWrapper
    26   	{
    27   		#region class members
    28   
    29   		#region internal fields
    30   
    31   		private string errorMessage;
    32   		private string lDAPConnectionString;
    33   		private string lDAPServerLoginUsername;
    34   		private string lDAPServerLoginPassword;
    35   		private string userToLookup;
    36   		public ApplicationUserData userData;        
    37   
    38   		#endregion
    39   
    40   		#region constructors
    41   
    42   		/// <summary>
    43   		/// Default constructor - initialises some members.
    44   		/// </summary>
    45   		public ActiveDirectoryWrapper()
    46   		{
    47   			errorMessage = string.Empty;
    48   			userData = new ApplicationUserData();
    49   			InitUserDetails();            
    50   			
    51   			lDAPConnectionString = ConfigurationSettings.AppSettings["ldap_path"];
    52   		} //end default constructors
    53   
    54   		#endregion
    55   
    56   		#region implementation
    57           
    58   		/// <summary>
    59   		/// Attempts to get user details from Active directory based on the user's Active Directory login username 
    60   		/// </summary>
    61   		/// <param name="loginUserName">the Active Directory username for the user.</param>
    62   		/// <returns>a DirectoryEntry object containing the user details, null if we could not get the details</returns>
    63   		public SearchResult GetUserDirectoryEntryDetails(string loginUserName)
    64   		{		
    65   			string userToFind = loginUserName;
    66               
    67   			try
    68   			{
    69   				DirectoryEntry de = new DirectoryEntry(lDAPConnectionString,
    70   					@ConfigurationSettings.AppSettings["ldap_login_username"],
    71   					ConfigurationSettings.AppSettings["ldap_login_password"]);
    72   				de.AuthenticationType = AuthenticationTypes.Secure;
    73                   
    74   				DirectorySearcher deSearch = new DirectorySearcher();
    75   				deSearch.SearchRoot = de;
    76   				//SearchResultCollection results;
    77   				SearchResult results;
    78   
    79   				//Search the USER object in the hierachy			
    80   				deSearch.Filter = "(&(objectClass=user)(SAMAccountName=" + loginUserName + "))";
    81   
    82   				deSearch.SearchScope = SearchScope.Subtree;
    83   
    84   				//Add the attributes which we want to return to the search result          
    85                   
    86   				results = deSearch.FindOne();           
    87                   
    88   				if ((results != null))
    89   				{
    90   					return results;
    91   				}
    92   				else
    93   				{
    94   					return null;
    95   				} //end if          
    96   			}
    97   			catch (Exception ex)
    98   			{
    99   				//Console.WriteLine("ERROR: " + ex.Message  );
    100  				//ApplicationContext.CurrentHTTPResponse.Write(ex.Message + "<br /><br />");
    101  
    102  				while (ex.InnerException != null)
    103  				{
    104  					errorMessage +=   ex.InnerException.Message.ToString() ;
    105  					//ApplicationContext.CurrentHTTPResponse.Write( ex.InnerException.Message.ToString() + "<br /><br />");
    106  				} //end while
    107  				Console.WriteLine(errorMessage);
    108  				return null;
    109  			} //end try/catch
    110  		} //end GetUserDirectoryEntryDetails.
    111  
    112          
    113  		/// <summary>
    114  		/// Populate the encapsualted struct with the data from the Search results
    115  		/// </summary>
    116  		/// <param name="theSearchResult">the SearchResult object which contains the data from Active Directory</param>
    117  		public void PopulateUserDataStruct(SearchResult theSearchResult)
    118  		{
    119  			if (theSearchResult != null)
    120  			{
    121  				ResultPropertyCollection myResultPropColl;
    122  				myResultPropColl = theSearchResult.Properties;
    123  
    124  				/**
    125  				* The code below is usefull for printing out the whole list of attributes from the current user node.
    126  				 * 
    127  				 
    128  				foreach (string myKey in myResultPropColl.PropertyNames)
    129  				{
    130  					string tab = "    ";
    131  					Console.WriteLine(myKey + " = ");
    132  					foreach (Object myCollection in myResultPropColl[myKey])
    133  					{
    134  						Console.WriteLine(tab + myCollection);
    135  					}//end foreach
    136  				} //end foreach
    137                */
    138  
    139  				//Add first name to search result if it exists
    140  				if (myResultPropColl.Contains("givenName"))
    141  				{
    142  					userData.personFirstName = theSearchResult.Properties["givenName"][0].ToString();                    
    143  				} //end if
    144  
    145  				//Add surname to search result if it exists
    146  				if (myResultPropColl.Contains("sn"))
    147  				{
    148  					userData.personSurname = theSearchResult.Properties["sn"][0].ToString();        
    149  				} //end if
    150  
    151  				//Add email to search result if it exists
    152  				if (myResultPropColl.Contains("mail"))
    153  				{
    154  					userData.personEmail = theSearchResult.Properties["mail"][0].ToString();                    
    155  				} //end if
    156                  
    157  				//Add the job title to search results if it exists
    158  				if (myResultPropColl.Contains("title"))
    159  				{
    160  					userData.personJobTitle = theSearchResult.Properties["title"][0].ToString();
    161  				} //end if          
    162  
    163  				//Add the person's job description to the search results if it exists
    164  				if (myResultPropColl.Contains("info"))
    165  				{
    166  					userData.personDepartment =   theSearchResult.Properties["info"][0].ToString();		
    167  					
    168  				} //end if
    169  
    170  				//Add the person's county to the search results if it exists
    171  				if (myResultPropColl.Contains("st"))
    172  				{
    173  					userData.personCounty =   theSearchResult.Properties["st"][0].ToString();		
    174  					
    175  				} //end if
    176  
    177  				//Add the person's mobile phone number to the search results if it exists
    178  				if (myResultPropColl.Contains("mobile"))
    179  				{
    180  					userData.personMobileNumber =   theSearchResult.Properties["mobile"][0].ToString();		
    181  					
    182  				} //end if
    183  
    184  				//Add the person's telephone number to the search results if it exists
    185  				if (myResultPropColl.Contains("telephoneNumber"))
    186  				{
    187  					userData.personTelephone =   theSearchResult.Properties["telephoneNumber"][0].ToString();		
    188  					
    189  				} //end if
    190  
    191  				//Add the person's post code to the search results if it exists
    192  				if (myResultPropColl.Contains("postalCode"))
    193  				{
    194  					userData.personPostCode =   theSearchResult.Properties["postalCode"][0].ToString();		
    195  					
    196  				} //end if
    197  
    198  				//Add the person's team (department) to the search results if it exists
    199  				if (myResultPropColl.Contains("department"))
    200  				{
    201  					userData.personDepartment =   theSearchResult.Properties["department"][0].ToString();		
    202  					
    203  				} //end if
    204  
    205  				//Add the person's street address to the search results if it exists
    206  				if (myResultPropColl.Contains("streetAddress"))
    207  				{
    208  					userData.personAddress1 =   theSearchResult.Properties["streetAddress"][0].ToString();		
    209  					
    210  				} //end if				
    211  
    212  				//Add the person's town to the search results if it exists
    213  				if (myResultPropColl.Contains("l"))
    214  				{
    215  					userData.personTown =   theSearchResult.Properties["l"][0].ToString();		
    216  					
    217  				} //end if				
    218  
    219  				//Add the person's xx to the search results if it exists
    220  				if (myResultPropColl.Contains("physicalDeliveryOfficeName"))
    221  				{
    222  					userData.personLocation =   theSearchResult.Properties["physicalDeliveryOfficeName"][0].ToString();		
    223  					
    224  				} //end if				
    225  			}
    226  			else
    227  			{
    228  				errorMessage += "User does not exist.";
    229  			} //end if
    230  		} //end PopulateUserDataStruct
    231  
    232  
    233  		#endregion
    234  
    235  		#region class properties
    236  
    237  		/// <summary>
    238  		/// LDAP connection string property.
    239  		/// </summary>
    240  		public string LDAPConnectionString
    241  		{
    242  			get { return lDAPConnectionString; }
    243  			set { lDAPConnectionString = value; }
    244  		} //end LDAPConnectionString property
    245  
    246  		/// <summary>
    247  		/// LDAP server login username property
    248  		/// </summary>
    249  		public string LDAPServerLoginUsername
    250  		{
    251  			get { return lDAPServerLoginUsername; }
    252  			set { lDAPServerLoginUsername = value; }
    253  		} //end LDAPServerLoginUsername property
    254  
    255  		/// <summary>
    256  		/// LDAP server login password property
    257  		/// </summary>
    258  		public string LDAPServerLoginPassword
    259  		{
    260  			get { return lDAPServerLoginPassword; }
    261  			set { lDAPServerLoginPassword = value; }
    262  		} //end LDAPServerLoginPassword property
    263          
    264  		/// <summary>
    265  		/// Error message property. Manages any errors that may occur when an instance
    266  		/// of this class is being used.
    267  		/// </summary>
    268  		public string ErrorMessage
    269  		{
    270  			get { return errorMessage;}
    271  			set { errorMessage = value; }
    272  		} //end ErrorMessage property
    273  
    274  		public string TheUserToLookup
    275  		{
    276  			set{ userToLookup = value;}
    277  			get { return userToLookup ;}
    278  		}
    279  
    280          
    281  		#endregion
    282  
    283  		#region init user details
    284  
    285  		/// <summary>
    286  		/// Initialise the user data struct to non-null values - very safe!!
    287  		/// </summary>
    288  		private void InitUserDetails()
    289  		{         
    290  			userData.personFirstName = string.Empty;
    291  			userData.personSurname = string.Empty;
    292  			userData.personJobTitle = string.Empty;
    293  			userData.personJobDescription = string.Empty;	
    294  			userData.personAddress1 = string.Empty;
    295  			userData.personTown = string.Empty;
    296  			userData.personCounty = string.Empty;
    297  			userData.personPostCode = string.Empty;
    298  			userData.personLocation = string.Empty;
    299  			userData.personTelephone = string.Empty;
    300  			userData.personMobileNumber = string.Empty;
    301  			userData.personEmail = string.Empty;
    302  			userData.personDepartment = string.Empty;
    303  		} //end InitUserDetails
    304  
    305  		#endregion
    306  
    307  		#region user data structure
    308  
    309  		/// <summary>
    310  		/// Convinient structure to hold LDAP users information
    311  		/// Simply contains fields
    312  		/// </summary>
    313  		public struct ApplicationUserData
    314  		{
    315  			public string personFirstName; //givenName
    316  			public string personSurname; //sn			
    317  			public string personJobTitle; //title
    318  			public string personJobDescription; //info			
    319  			public string personAddress1; //streetAddress
    320  			public string personTown; //l
    321  			public string personCounty; //st
    322  			public string personPostCode;//postalCode
    323  			public string personLocation; //physicalDeliveryOfficeName 
    324  			public string personTelephone; //telephoneNumber
    325  			public string personMobileNumber; //mobile
    326  			public string personEmail; //mail
    327  			public string personDepartment; //department
    328  		} //end ApplicationUserData struct.
    329  
    330  		#endregion
    331  
    332  		#region unit testing
    333  
    334  
    335  		/// <summary>
    336  		///  Main method for testing. You need to compile this class into an EXE first and then
    337  		/// invoke that EXE from a command-line in order to run the tests. 
    338  		/// </summary>		
    339  		public static void Main(string[] args)
    340  		{
    341  			ActiveDirectoryWrapper adWrapper = new ActiveDirectoryWrapper();
    342              
    343  			//optionally pass in parameters from the command line
    344  			if (args.Length != 0)
    345  			{
    346  				//assing them to properties as you see fit
    347  			} //end if
    348  
    349              adWrapper.PopulateUserDataStruct(adWrapper.GetUserDirectoryEntryDetails("zullu"));
    350  
    351  			Console.WriteLine("\n\nPerson name is  " + adWrapper.userData.personFirstName);
    352  			Console.WriteLine("Surname is " + adWrapper.userData.personSurname);
    353  			Console.WriteLine("Email is " + adWrapper.userData.personEmail);
    354  			Console.WriteLine("Person job title is " + adWrapper.userData.personJobTitle);
    355  
    356  
    357  			if (adWrapper.ErrorMessage != string.Empty)
    358  			{
    359  				Console.WriteLine(adWrapper.ErrorMessage);
    360  			}//end if
    361  
    362  		} //end main
    363  
    364  
    365  		#endregion
    366  
    367  		#endregion
    368  
    369  	} //end class
    370  } //end namespace
    371  
    
     

    Kind regards,
    Ernest

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, June 19, 2007 4:22 PM
  • User-1491118713 posted

    Hello Zullu,

    I'm glad you are making progress. Unfortunately I have never used InfoPath and I don't know what it is. Maybe ignorance on my part ;) However, I would say that all you would need to do is create an instance of my class in your event handler and then call the appropriate methods. All you would do is declare the line

    1    ActiveDirectoryWrapper adWrapper = new ActiveDirectoryWrapper();
    
    in your code. If you are not comfortable doing this I suggest you read up on the basics of Object Oriented Programming so that you are comfortable 
    with creating classes and using instances of those classes.
    I hope that helps,
    Kind regards,
    Ernest
    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, June 21, 2007 4:12 PM

All replies

  • User-130167459 posted

    User.Identity.Name will tell you the username for the currently logged in user. Im assuming you are using Active Directory Membership provider and have Basic Authenication and deny anonymous users in your IIS. Everything should work fine if so no matter what browser you are using, you still have to authenticate when you connect to the website and you login info is stored in your session.

    Thursday, November 23, 2006 1:26 AM
  • User-1491118713 posted

    Thanks areddic,

    I have already used User.Identity.Name and disabled annonymous login in IIS. It appears to be working fine at the moment.

    Thanks for spending some of your precious time to help me.

    Kind regards

    Ernest 

    Wednesday, November 29, 2006 3:52 PM
  • User-406496242 posted

    Hi Ernest ,

    Can you please let me know how to get the current logged in user from the AD.

    I even need to pull the user's manager (name, emailid) at the same time.

    Any Help!

    Thanks in advance

    zullu

    Tuesday, June 19, 2007 11:03 AM
  • User-1491118713 posted

    Hi zullu,

    In my authentication class I have this method

     

    1    /// <summary>
    2    		/// Gets the windows login for the currently logged in user in the client computer i.e
    3    		/// the person requesting the page
    4    		/// </summary>
    5    		/// <returns>The username of the user requesting the page, might contain domain</returns>
    6    		public string GetCurrentUserWindowsLogin()
    7    		{				
    8    
    9    			string windowsLogin = Page.User.Identity.Name;			
    10   			//Normally if the domain is present you get a string like DOMAINNAME\username, remove the domain
    11   			int hasDomain = windowsLogin.IndexOf(@"\");
    12   			if (hasDomain > 0)
    13   			{
    14   				windowsLogin = windowsLogin.Remove(0, hasDomain + 1);
    15   			} //end if			
    16   			return windowsLogin;
    17   		} //end GetCurrentUserWindowsLogin
    

     

    The method above gets me the user's AD SAMAccountName which I can then use to pass on to AD to query for more data.

    I then wrote the class below which allowed me to get people's information fropm AD based on their Windows login e.g. zullu
    This class can also be run as a standalone DOS application when compiled into an EXE. I test my classes this way ;) The AD connection details were kept in the Web.Config file which means you will need to give the program the correct values for "ldap_path" , "ldap_login_username", and "ldap_login_password"  . Give it a go and I hope it helps:

     

    1    using System;
    2    using System.Configuration;
    3    using System.DirectoryServices;
    4    using System.Security;
    5    using System.Security.Principal;
    6    using System.Globalization;
    7    
    8    namespace DataAccess
    9    {
    10   	/// <summary>
    11   	/// This class provides functionality to query Microsoft Active Directory 
    12   	/// for USER Objects information. It then makes that information available
    13   	/// to the calling client using a public encapsulated struct. 
    14   	/// </summary>
    15   	/// <remarks>
    16   	/// Instead of maintaining several properties for the USER data a public 
    17   	/// struct is used to expose the Active Directory USER Object data. 
    18   	/// This makes maintanance of the class very easy
    19   	/// </remarks>
    20   	/// <author>Ernest M. Fakudze</author>
    21   	/// <date_written>14 Nov 2006</date_written>
    22   	/// <version>1.0</version>
    23   	/// <last_update>27 Nov 2006</last_update>
    24       
    25   	public sealed class ActiveDirectoryWrapper
    26   	{
    27   		#region class members
    28   
    29   		#region internal fields
    30   
    31   		private string errorMessage;
    32   		private string lDAPConnectionString;
    33   		private string lDAPServerLoginUsername;
    34   		private string lDAPServerLoginPassword;
    35   		private string userToLookup;
    36   		public ApplicationUserData userData;        
    37   
    38   		#endregion
    39   
    40   		#region constructors
    41   
    42   		/// <summary>
    43   		/// Default constructor - initialises some members.
    44   		/// </summary>
    45   		public ActiveDirectoryWrapper()
    46   		{
    47   			errorMessage = string.Empty;
    48   			userData = new ApplicationUserData();
    49   			InitUserDetails();            
    50   			
    51   			lDAPConnectionString = ConfigurationSettings.AppSettings["ldap_path"];
    52   		} //end default constructors
    53   
    54   		#endregion
    55   
    56   		#region implementation
    57           
    58   		/// <summary>
    59   		/// Attempts to get user details from Active directory based on the user's Active Directory login username 
    60   		/// </summary>
    61   		/// <param name="loginUserName">the Active Directory username for the user.</param>
    62   		/// <returns>a DirectoryEntry object containing the user details, null if we could not get the details</returns>
    63   		public SearchResult GetUserDirectoryEntryDetails(string loginUserName)
    64   		{		
    65   			string userToFind = loginUserName;
    66               
    67   			try
    68   			{
    69   				DirectoryEntry de = new DirectoryEntry(lDAPConnectionString,
    70   					@ConfigurationSettings.AppSettings["ldap_login_username"],
    71   					ConfigurationSettings.AppSettings["ldap_login_password"]);
    72   				de.AuthenticationType = AuthenticationTypes.Secure;
    73                   
    74   				DirectorySearcher deSearch = new DirectorySearcher();
    75   				deSearch.SearchRoot = de;
    76   				//SearchResultCollection results;
    77   				SearchResult results;
    78   
    79   				//Search the USER object in the hierachy			
    80   				deSearch.Filter = "(&(objectClass=user)(SAMAccountName=" + loginUserName + "))";
    81   
    82   				deSearch.SearchScope = SearchScope.Subtree;
    83   
    84   				//Add the attributes which we want to return to the search result          
    85                   
    86   				results = deSearch.FindOne();           
    87                   
    88   				if ((results != null))
    89   				{
    90   					return results;
    91   				}
    92   				else
    93   				{
    94   					return null;
    95   				} //end if          
    96   			}
    97   			catch (Exception ex)
    98   			{
    99   				//Console.WriteLine("ERROR: " + ex.Message  );
    100  				//ApplicationContext.CurrentHTTPResponse.Write(ex.Message + "<br /><br />");
    101  
    102  				while (ex.InnerException != null)
    103  				{
    104  					errorMessage +=   ex.InnerException.Message.ToString() ;
    105  					//ApplicationContext.CurrentHTTPResponse.Write( ex.InnerException.Message.ToString() + "<br /><br />");
    106  				} //end while
    107  				Console.WriteLine(errorMessage);
    108  				return null;
    109  			} //end try/catch
    110  		} //end GetUserDirectoryEntryDetails.
    111  
    112          
    113  		/// <summary>
    114  		/// Populate the encapsualted struct with the data from the Search results
    115  		/// </summary>
    116  		/// <param name="theSearchResult">the SearchResult object which contains the data from Active Directory</param>
    117  		public void PopulateUserDataStruct(SearchResult theSearchResult)
    118  		{
    119  			if (theSearchResult != null)
    120  			{
    121  				ResultPropertyCollection myResultPropColl;
    122  				myResultPropColl = theSearchResult.Properties;
    123  
    124  				/**
    125  				* The code below is usefull for printing out the whole list of attributes from the current user node.
    126  				 * 
    127  				 
    128  				foreach (string myKey in myResultPropColl.PropertyNames)
    129  				{
    130  					string tab = "    ";
    131  					Console.WriteLine(myKey + " = ");
    132  					foreach (Object myCollection in myResultPropColl[myKey])
    133  					{
    134  						Console.WriteLine(tab + myCollection);
    135  					}//end foreach
    136  				} //end foreach
    137                */
    138  
    139  				//Add first name to search result if it exists
    140  				if (myResultPropColl.Contains("givenName"))
    141  				{
    142  					userData.personFirstName = theSearchResult.Properties["givenName"][0].ToString();                    
    143  				} //end if
    144  
    145  				//Add surname to search result if it exists
    146  				if (myResultPropColl.Contains("sn"))
    147  				{
    148  					userData.personSurname = theSearchResult.Properties["sn"][0].ToString();        
    149  				} //end if
    150  
    151  				//Add email to search result if it exists
    152  				if (myResultPropColl.Contains("mail"))
    153  				{
    154  					userData.personEmail = theSearchResult.Properties["mail"][0].ToString();                    
    155  				} //end if
    156                  
    157  				//Add the job title to search results if it exists
    158  				if (myResultPropColl.Contains("title"))
    159  				{
    160  					userData.personJobTitle = theSearchResult.Properties["title"][0].ToString();
    161  				} //end if          
    162  
    163  				//Add the person's job description to the search results if it exists
    164  				if (myResultPropColl.Contains("info"))
    165  				{
    166  					userData.personDepartment =   theSearchResult.Properties["info"][0].ToString();		
    167  					
    168  				} //end if
    169  
    170  				//Add the person's county to the search results if it exists
    171  				if (myResultPropColl.Contains("st"))
    172  				{
    173  					userData.personCounty =   theSearchResult.Properties["st"][0].ToString();		
    174  					
    175  				} //end if
    176  
    177  				//Add the person's mobile phone number to the search results if it exists
    178  				if (myResultPropColl.Contains("mobile"))
    179  				{
    180  					userData.personMobileNumber =   theSearchResult.Properties["mobile"][0].ToString();		
    181  					
    182  				} //end if
    183  
    184  				//Add the person's telephone number to the search results if it exists
    185  				if (myResultPropColl.Contains("telephoneNumber"))
    186  				{
    187  					userData.personTelephone =   theSearchResult.Properties["telephoneNumber"][0].ToString();		
    188  					
    189  				} //end if
    190  
    191  				//Add the person's post code to the search results if it exists
    192  				if (myResultPropColl.Contains("postalCode"))
    193  				{
    194  					userData.personPostCode =   theSearchResult.Properties["postalCode"][0].ToString();		
    195  					
    196  				} //end if
    197  
    198  				//Add the person's team (department) to the search results if it exists
    199  				if (myResultPropColl.Contains("department"))
    200  				{
    201  					userData.personDepartment =   theSearchResult.Properties["department"][0].ToString();		
    202  					
    203  				} //end if
    204  
    205  				//Add the person's street address to the search results if it exists
    206  				if (myResultPropColl.Contains("streetAddress"))
    207  				{
    208  					userData.personAddress1 =   theSearchResult.Properties["streetAddress"][0].ToString();		
    209  					
    210  				} //end if				
    211  
    212  				//Add the person's town to the search results if it exists
    213  				if (myResultPropColl.Contains("l"))
    214  				{
    215  					userData.personTown =   theSearchResult.Properties["l"][0].ToString();		
    216  					
    217  				} //end if				
    218  
    219  				//Add the person's xx to the search results if it exists
    220  				if (myResultPropColl.Contains("physicalDeliveryOfficeName"))
    221  				{
    222  					userData.personLocation =   theSearchResult.Properties["physicalDeliveryOfficeName"][0].ToString();		
    223  					
    224  				} //end if				
    225  			}
    226  			else
    227  			{
    228  				errorMessage += "User does not exist.";
    229  			} //end if
    230  		} //end PopulateUserDataStruct
    231  
    232  
    233  		#endregion
    234  
    235  		#region class properties
    236  
    237  		/// <summary>
    238  		/// LDAP connection string property.
    239  		/// </summary>
    240  		public string LDAPConnectionString
    241  		{
    242  			get { return lDAPConnectionString; }
    243  			set { lDAPConnectionString = value; }
    244  		} //end LDAPConnectionString property
    245  
    246  		/// <summary>
    247  		/// LDAP server login username property
    248  		/// </summary>
    249  		public string LDAPServerLoginUsername
    250  		{
    251  			get { return lDAPServerLoginUsername; }
    252  			set { lDAPServerLoginUsername = value; }
    253  		} //end LDAPServerLoginUsername property
    254  
    255  		/// <summary>
    256  		/// LDAP server login password property
    257  		/// </summary>
    258  		public string LDAPServerLoginPassword
    259  		{
    260  			get { return lDAPServerLoginPassword; }
    261  			set { lDAPServerLoginPassword = value; }
    262  		} //end LDAPServerLoginPassword property
    263          
    264  		/// <summary>
    265  		/// Error message property. Manages any errors that may occur when an instance
    266  		/// of this class is being used.
    267  		/// </summary>
    268  		public string ErrorMessage
    269  		{
    270  			get { return errorMessage;}
    271  			set { errorMessage = value; }
    272  		} //end ErrorMessage property
    273  
    274  		public string TheUserToLookup
    275  		{
    276  			set{ userToLookup = value;}
    277  			get { return userToLookup ;}
    278  		}
    279  
    280          
    281  		#endregion
    282  
    283  		#region init user details
    284  
    285  		/// <summary>
    286  		/// Initialise the user data struct to non-null values - very safe!!
    287  		/// </summary>
    288  		private void InitUserDetails()
    289  		{         
    290  			userData.personFirstName = string.Empty;
    291  			userData.personSurname = string.Empty;
    292  			userData.personJobTitle = string.Empty;
    293  			userData.personJobDescription = string.Empty;	
    294  			userData.personAddress1 = string.Empty;
    295  			userData.personTown = string.Empty;
    296  			userData.personCounty = string.Empty;
    297  			userData.personPostCode = string.Empty;
    298  			userData.personLocation = string.Empty;
    299  			userData.personTelephone = string.Empty;
    300  			userData.personMobileNumber = string.Empty;
    301  			userData.personEmail = string.Empty;
    302  			userData.personDepartment = string.Empty;
    303  		} //end InitUserDetails
    304  
    305  		#endregion
    306  
    307  		#region user data structure
    308  
    309  		/// <summary>
    310  		/// Convinient structure to hold LDAP users information
    311  		/// Simply contains fields
    312  		/// </summary>
    313  		public struct ApplicationUserData
    314  		{
    315  			public string personFirstName; //givenName
    316  			public string personSurname; //sn			
    317  			public string personJobTitle; //title
    318  			public string personJobDescription; //info			
    319  			public string personAddress1; //streetAddress
    320  			public string personTown; //l
    321  			public string personCounty; //st
    322  			public string personPostCode;//postalCode
    323  			public string personLocation; //physicalDeliveryOfficeName 
    324  			public string personTelephone; //telephoneNumber
    325  			public string personMobileNumber; //mobile
    326  			public string personEmail; //mail
    327  			public string personDepartment; //department
    328  		} //end ApplicationUserData struct.
    329  
    330  		#endregion
    331  
    332  		#region unit testing
    333  
    334  
    335  		/// <summary>
    336  		///  Main method for testing. You need to compile this class into an EXE first and then
    337  		/// invoke that EXE from a command-line in order to run the tests. 
    338  		/// </summary>		
    339  		public static void Main(string[] args)
    340  		{
    341  			ActiveDirectoryWrapper adWrapper = new ActiveDirectoryWrapper();
    342              
    343  			//optionally pass in parameters from the command line
    344  			if (args.Length != 0)
    345  			{
    346  				//assing them to properties as you see fit
    347  			} //end if
    348  
    349              adWrapper.PopulateUserDataStruct(adWrapper.GetUserDirectoryEntryDetails("zullu"));
    350  
    351  			Console.WriteLine("\n\nPerson name is  " + adWrapper.userData.personFirstName);
    352  			Console.WriteLine("Surname is " + adWrapper.userData.personSurname);
    353  			Console.WriteLine("Email is " + adWrapper.userData.personEmail);
    354  			Console.WriteLine("Person job title is " + adWrapper.userData.personJobTitle);
    355  
    356  
    357  			if (adWrapper.ErrorMessage != string.Empty)
    358  			{
    359  				Console.WriteLine(adWrapper.ErrorMessage);
    360  			}//end if
    361  
    362  		} //end main
    363  
    364  
    365  		#endregion
    366  
    367  		#endregion
    368  
    369  	} //end class
    370  } //end namespace
    371  
    
     

    Kind regards,
    Ernest

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, June 19, 2007 4:22 PM
  • User-406496242 posted

    Wow !!

    This looks awesome. I am not very good at these lines of codes which you have posted. I apologize for that :-).

    But I guess I am very close to getting my things work out.

    Just few more thing to understand before I get to start doing this.

    To let you know: 

    I have a Development server with MOSS 2007 where I am developing this infopath 2003 form. The Active Directory is sitting on a different Production server where finally the InfoPath 2003 form would be published to a document library as default template.

    Now while developing this form, when I open the form from the dev server, the code need to hit the prod server having AD and get the userdetails.

    Any further idea as to how to implement your piece of code here.

    Can I do this without writing any web service. Or is it required to have this code in a web service.

    Thanks Many Many, I have found a ray of hope in you. :-)

    zullu

     

    Wednesday, June 20, 2007 1:07 AM
  • User-406496242 posted

    Hi Ernest,

     Hey I could do that now. U R a gr8 man. [:)]

    Full Cheers to you!!!

    Now as usual, my next question.

    I am now trying to incorporate the same into my InfoPath 2003 form.

    To do this, I have created a InfoPath 2003 C# project in Visual Studio 2005.

    I am trying to modfy the starting point of the function "public static void Main(string[] args)".

    Instead of execution starting from this "MAIN", I need to execute the whole thing on the InfoPath form's OnLoad event.

    There are two textboxes "CurrentUser" and "ManagerEmail" on my form. I need to pull the data and display them when the form loads.

    I am not sure how do I achieve this.

    Can You help me to do this.

    Thanks from the core of my heart !! [:)]

    zullu

     

    Thursday, June 21, 2007 2:47 PM
  • User-406496242 posted

    Hi Ernest,

     Can I write VBSricpt code in my InfoPath 2003 form instead of using Visual Studio 2005 and using C# ?

    If so how?

    Sorry for troubling you too much :-)

     zullu

    Thursday, June 21, 2007 3:58 PM
  • User-1491118713 posted

    Hello Zullu,

    I'm glad you are making progress. Unfortunately I have never used InfoPath and I don't know what it is. Maybe ignorance on my part ;) However, I would say that all you would need to do is create an instance of my class in your event handler and then call the appropriate methods. All you would do is declare the line

    1    ActiveDirectoryWrapper adWrapper = new ActiveDirectoryWrapper();
    
    in your code. If you are not comfortable doing this I suggest you read up on the basics of Object Oriented Programming so that you are comfortable 
    with creating classes and using instances of those classes.
    I hope that helps,
    Kind regards,
    Ernest
    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, June 21, 2007 4:12 PM
  • User-406496242 posted

    Thanks Ernest,

    I'll try to figure this out.

    :-)

     

    Friday, June 22, 2007 2:58 PM
  • User-1039807434 posted

    That's coool! But... How to get user data from AD without storing login and password in Web.config, i.e. is this possible if in my web site I use a impersonalisation.

    Tuesday, August 21, 2007 8:04 AM
  • User-704323373 posted

    Hi Ernest,

    I was trying to see how your class works and it seems toio me that it does not contain a definition for the type SearchResult. Could you add that?

     

    Thank you,

     Adrian

    Wednesday, August 29, 2007 10:36 AM
  • User-704323373 posted

    Sorry, my mistake: I added the reference to System.DirectoryServices and the code compiled.

    Wednesday, August 29, 2007 10:51 AM
  • User-747691116 posted

    Hi Ernie,

    This is a great post!  Thanks for posting your code. I hope you are still active on this forum!

    I would like to use his code, but I am learning VB.Net.  Can someone help me convert this or rewrite C# code into VB.Net?

    Thank you very much in advance...

    Monday, April 6, 2009 5:09 PM