none
Get user by UserPrincipalName RRS feed

  • Question

  • Hi All

    I need  your help with code. I find this at the codeplex and running as part of my solution. https://adimageloader.codeplex.com/SourceControl/latest#1493139 .

    This solution is matching image name with user name in AD and send image to AD. This solution is using sAMAccountName property to match name.

    Is it possible to make this solution to look for userPrincipalName and push images to AD based on userPrincipalName.

    In our case userPrincipalNameis different than sAMAccountName , and images I am getting are coming with name that’s in userPrincipalName.

    I try to change this part of the code but can’t make it work

    // Get the LDAP Distinguished Name from the SAM / username

                string dn = GetUserDistinguishedName(userName);

               

     any help ,

    Full code is

    using System;

    using System.Collections.Generic;

    using System.Linq;

    using System.Text;

     

    using System.IO;

    using System.DirectoryServices;

    using System.DirectoryServices.AccountManagement;

     

    namespace AD_ImageLoader

    {

        class Program

        {

            static void Main(string[] args)

            {

                Console.WriteLine("\nImport Photos to Active Directory");

                Console.WriteLine("---------------------------------");

                Console.WriteLine("USAGE:");

                Console.WriteLine("AD_ImageLoader.exe [-s]");

                Console.WriteLine("-s : Supresses the pause at the end of processing.");

                Console.WriteLine("---------------------------------");

     

                // Get the current location of the EXE

                string location = System.Reflection.Assembly.GetExecutingAssembly().Location;

     

                // Get the folder location

                var asmLocation = new System.IO.DirectoryInfo(location);

                var dirLocation = asmLocation.Parent;

                //var dirLocation = new DirectoryInfo(@"C:\Test3");

     

                // Create folders for the photos (if req.) and set a reference.

                var processedLocation = dirLocation.CreateSubdirectory("Processed");

                var sourceLocation = dirLocation.CreateSubdirectory("Source");

     

                // Process each photo in the Source folder.

                foreach (FileInfo file in sourceLocation.EnumerateFiles())

                {

                    Console.WriteLine(string.Format("Photo: {0}", file.ToString()));

                   

                    // Extract the username from the file name.

                    // ie. jkent.jpg = jkent

                    var userName = (file.ToString().Replace(file.Extension, ""));

                    var fileName = file.FullName;

     

                    Console.WriteLine(string.Format("Username: {0}", userName));

     

                    // Load the Image into Active Directory

                    var ret = LoadImageIntoAD(userName, fileName);

     

                    // If successful, move the file into the Processed folder

                    if (ret == true)

                    {

                        try

                        {

                            file.CopyTo(processedLocation.FullName + @"\" + file.Name, true);

                            file.Delete();

                        }

                        catch (UnauthorizedAccessException)

                        {

                            Console.WriteLine("ERROR: You do not have permission to move images into the Processed folder.");

                        }

                    }

                    else

                        Console.WriteLine("Import Failed");

     

                    Console.WriteLine("---------------------------------");

                }

     

                if (args.Length == 0)

                {

                    Console.WriteLine("\nPress any key to continue...");

                    Console.Read();

                }

     

                return;

            }

     

            static bool LoadImageIntoAD(string userName, string fileName)

            {

                // Determine the current domain

                string domain = System.DirectoryServices.ActiveDirectory.Domain.GetCurrentDomain().Name;

     

                // Get the LDAP Distinguished Name from the SAM / username

                string dn = GetUserDistinguishedName(userName);

               

               

                Console.WriteLine(string.Format("Distinguished Name: {0}", dn));

     

                if (dn != null)

                {

                    // Load the photo into memory

                    byte[] data = File.ReadAllBytes(fileName);

     

                    // Get the user object from AD

                    var de = new DirectoryEntry("LDAP://" + domain + "/" + dn);

     

                    if (de != null)

                    {

                        Console.WriteLine("Directory Entry: Found");

     

                        // Clear any existing photos

                        de.Properties["jpegPhoto"].Clear();

                        de.Properties["thumbnailPhoto"].Clear();

     

                        // Add the photo to the user AD object.

                        de.Properties["jpegPhoto"].Add(data);

                        de.Properties["thumbnailPhoto"].Add(data);

     

                        // Update AD

                        de.CommitChanges();

     

                        Console.WriteLine("Directory Entry: Updated");

     

                        return true;

                    }

                    else

                        Console.WriteLine("Directory Entry: Not Found");

                }

                else

                    Console.WriteLine("Distinguished Name: Not Found");

     

                return false;

            }

     

            static string GetUserDistinguishedName(string userName)

            {

                // Get the Domain Pricipal

                PrincipalContext insPrincipalContext = new PrincipalContext(ContextType.Domain);

     

                // Get the User Principal and filter it by SAM / username

                UserPrincipal insUserPrincipal = new UserPrincipal(insPrincipalContext);

                insUserPrincipal.SamAccountName = userName;

     

                // Execute search.

                PrincipalSearcher insPrincipalSearcher = new PrincipalSearcher();

                insPrincipalSearcher.QueryFilter = insUserPrincipal;

                PrincipalSearchResult<Principal> results = insPrincipalSearcher.FindAll();

     

                foreach (Principal p in results)

                {

                    // Return the first record.

                    return p.DistinguishedName;

                   

                }

     

                return null;

            }

        }

    }

     

     

     

    Friday, May 31, 2013 7:53 PM

Answers

  • Greetings,

     

    The GetUserDistinguishedName method above uses a concept called query by example.  More information on using query by example can be found at the following MSDN link:

    http://msdn.microsoft.com/en-us/subscriptions/bb384384(v=vs.90)

    Modifiying the GetUserDistinguishedName method is straight forward.  I added the domain name and a container to the method call so that the base container for the query could be set to something other than the Users container.    Below is the new GetUserDistinguishedName that does a query by example searching for the userprincipalname.

            static string GetUserDistinguishedName(string userName, string container, string domain)
            {
                // Get the Domain Pricipal
                PrincipalContext insPrincipalContext = new PrincipalContext(ContextType.Domain, domain, container);
                // Get the User Principal and filter it by SAM / username
                UserPrincipal insUserPrincipal = new UserPrincipal(insPrincipalContext);
                insUserPrincipal.UserPrincipalName = userName;
                // Execute search.
                PrincipalSearcher insPrincipalSearcher = new PrincipalSearcher();
                insPrincipalSearcher.QueryFilter = insUserPrincipal;
                PrincipalSearchResult<Principal> results = insPrincipalSearcher.FindAll();
                foreach (Principal p in results)
                {
                    // Return the first record.
                    return p.DistinguishedName;
                }
                return null;
            }
    Enjoy.


          


    Monday, June 17, 2013 1:51 PM

All replies

  • Hi UMAR_USNT,

    I'm trying to involve some senior engineers into this issue and it will take some time. Your patience will be greatly appreciated.


    Bob Shen
    MSDN Community Support | Feedback to us
    Develop and promote your apps in Windows Store
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    Monday, June 3, 2013 7:47 AM
  • Greetings,

     

    The GetUserDistinguishedName method above uses a concept called query by example.  More information on using query by example can be found at the following MSDN link:

    http://msdn.microsoft.com/en-us/subscriptions/bb384384(v=vs.90)

    Modifiying the GetUserDistinguishedName method is straight forward.  I added the domain name and a container to the method call so that the base container for the query could be set to something other than the Users container.    Below is the new GetUserDistinguishedName that does a query by example searching for the userprincipalname.

            static string GetUserDistinguishedName(string userName, string container, string domain)
            {
                // Get the Domain Pricipal
                PrincipalContext insPrincipalContext = new PrincipalContext(ContextType.Domain, domain, container);
                // Get the User Principal and filter it by SAM / username
                UserPrincipal insUserPrincipal = new UserPrincipal(insPrincipalContext);
                insUserPrincipal.UserPrincipalName = userName;
                // Execute search.
                PrincipalSearcher insPrincipalSearcher = new PrincipalSearcher();
                insPrincipalSearcher.QueryFilter = insUserPrincipal;
                PrincipalSearchResult<Principal> results = insPrincipalSearcher.FindAll();
                foreach (Principal p in results)
                {
                    // Return the first record.
                    return p.DistinguishedName;
                }
                return null;
            }
    Enjoy.


          


    Monday, June 17, 2013 1:51 PM