Browse Active Directory Users Using PivotViewer

    More recently, a wonderful control for Silverlight came out - PivotViewer. Let's try to use it to view Active Directory users. For ease of understanding, we will use the finished project provided by the creators of Pivot.

    To work, we need:


    Let's go:

    Open the downloaded PivotJitServer project in Visual Studio 2010. We find the CollectionFactories project and add a new class there, call it ActiveDirectoryFactory and inherit it from CollectionFactoryBase.

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

      namespace CollectionFactories
      {
        public class ActiveDirectoryFactory : CollectionFactoryBase
        {
          public ActiveDirectoryFactory()
          {
            this.Summary = "ActiveDirectory collection";
          }
        }
      }

    * This source code was highlighted with Source Code Highlighter.


    Next, add the assembly reference System.DirectoryServices to the CollectionFactories project and add “using System.DirectoryServices;” to our class.

    Let's create an auxiliary class ActiveDirectoryUser, which will contain the parameters we need. For convenience, a Dictionary is used in the class to store the parameter-value bindings Code (comments inside):

        public class ActiveDirectoryUser
        {
          // конструктор, передаем в качестве параметра результат поиска в ActiveDirectory
          public ActiveDirectoryUser(SearchResult entry)
          {
            _Parameters = new Dictionary();
            
            // Заполняем все найденные параметры объекта AD в параметры нашего класса
            foreach (string propertyName in entry.Properties.PropertyNames)
            {
              _Parameters.Add(propertyName, entry.Properties[propertyName][0]);
            }
          }

          private Dictionary _Parameters;
          public Dictionary Parameters
          {
            get { return _Parameters; }
          }
        }

    * This source code was highlighted with Source Code Highlighter.


    To create a collection of elements in the CollectionFactoryBase class, there is a MakeCollection method that returns PivotServerTools.Collection (a collection of elements to display). We need to change it in order to fill the collection with our elements in it.

          public override Collection MakeCollection(CollectionRequestContext context)
          {
            Collection collection = new Collection(); // новая коллекция
            collection.Name = "ActiveDirectory database"; // название коллекции
            List users = GetObjects("LDAP://servad", "(&(objectClass=user)(objectCategory=person))"); // фильтр для получения объектов из AD

            // перебираем все найденные объекты и добавляем их в коллекцию
            foreach (ActiveDirectoryUser user in users)
            {
               ItemImage itemImage = null; // картинка при показе, можно использовать картинку из AD, или взять картинку по http

              // добавляем объект в коллекцию, с проверкой есть ли параметр у найденного объекта, если нет, то в качестве данных используем String.Empty
              collection.AddItem(
                user.Parameters.ContainsKey("displayname") ? user.Parameters["displayname"].ToString() : user.Parameters["samaccountname"].ToString(),
                null, null, itemImage,
                user.Parameters.ContainsKey("samaccountname") ? new Facet("Account Name", FacetType.Text, user.Parameters["samaccountname"].ToString()) : new Facet("Account Name", FacetType.Text, String.Empty),
                user.Parameters.ContainsKey("lastlogon") ? new Facet("Last Logon", FacetType.DateTime, DateTime.FromFileTime((long)user.Parameters["lastlogon"])) : new Facet("Last Logon", FacetType.DateTime, new DateTime()),
                user.Parameters.ContainsKey("company") ? new Facet("Company", FacetType.Text, user.Parameters["company"].ToString()) : new Facet("Company", String.Empty),
                user.Parameters.ContainsKey("department") ? new Facet("Department", FacetType.Text, user.Parameters["department"].ToString()) : new Facet("Department", String.Empty),
                user.Parameters.ContainsKey("title") ? new Facet("Title", FacetType.Text, user.Parameters["title"].ToString()) : new Facet("Title", String.Empty)
                );
            }

            collection.SetFacetDisplay("Account Name", false, true, false); // не отображать фильтр по именам, но показать его в свойстве объекта
            collection.SetFacetFormat("Last Logon", "dd-MM-yyyy hh:mm:ss"); // формат последней даты входа пользователя

            return collection;
          }

    * This source code was highlighted with Source Code Highlighter.


    SetFacetDisplay allows you not to display the specified parameter in the filter, but to show it in the properties when the selected object in Pivot.
    SetFacetFormat allows you to set the date format. In our case, the date format of the last user login is set.

    And the code to search for objects in ActiveDirectory

    private List GetObjects(String domainpath, String filter)
    {
      List allUsers = new List();

      DirectoryEntry searchRoot = new DirectoryEntry(domainpath);
      DirectorySearcher search = new DirectorySearcher(searchRoot);
      search.PageSize = 1000;
      search.Filter = filter;
      search.PropertiesToLoad.Add("displayName");
      search.PropertiesToLoad.Add("samaccountname");
      search.PropertiesToLoad.Add("department");
      search.PropertiesToLoad.Add("company");
      search.PropertiesToLoad.Add("lastlogon");
      search.PropertiesToLoad.Add("title");

      SearchResult result;
      SearchResultCollection resultCol = search.FindAll();
      if (resultCol != null)
      {
        for (int counter = 0; counter < resultCol.Count; counter++)
        {
          result = resultCol[counter];
          ActiveDirectoryUser adObject = new ActiveDirectoryUser(result);

          allUsers.Add(adObject);
        }
      }
      return allUsers;
    }

    * This source code was highlighted with Source Code Highlighter.

    Here an important parameter is PageSize; if it is not set, then the search will return no more than 1000 results.

    All is ready. We launch the web project and select on the page "Click here to view the samples in a Silverlight application using the PivotViewer control". As the sample collection, select ActiveDirectoryFactory.cs, after which data will begin filling in and you will see the entire list of users with the ability to sort by company, department, position ...

    Personally, I immediately found a bunch of typos in the user’s parameters, starting from the company to the position. Simple and convenient viewing, instead of dsquery.

    Since it is not very convenient to show on a small screen, here is a link to the pictures

    Also popular now: