I metodi seguenti possono essere aggiunti al Web Service usabile con InfoPath e permettono di recuperare alcune informazioni da un dominio Active Directory (AD).
I metodi sono:
  • ADGetUserInfo passando un nome utente (userName), ritorna il valore della proprietà indicata (propertyName). Ritorna una stringa.
  • ADGetUserInfo_DisplayName come ADGetUserInfo solo che ritorna direttamente il DisplayName
  • ADGetUserInfo_Mail come ADGetUserInfo solo che ritorna direttamente la Mail
  • ADEnumMembers enumera i membri del gruppo passato (groupName) facendo ricorsione sui gruppi, infine elimina gli utenti duplicati e ordina il risultato. Riritorna un DataSet

C#

#region ActiveDirectory get Info

  /// <summary>
  /// Get AD user DisplayName 
  /// </summary>
  /// <param name="userName">AD user name</param>
  [WebMethod]
  public string ADGetUserInfo_DisplayName(string userName)
  {
    return ADGetUserInfo(userName, "displayname");
  }

  /// <summary>
  /// Get AD user Mail
  /// </summary>
  /// <param name="userName">AD user name</param>
  [WebMethod]
  public string ADGetUserInfo_Mail(string userName)
  {
    return ADGetUserInfo(userName, "mail");
  }

  /// <summary>
  /// Get specific AD property of user
  /// </summary>
  /// <param name="userName">AD user name</param>
  /// <param name="propertyName">name of property to get user name</param>
  [WebMethod]
  public string ADGetUserInfo(string userName, string propertyName)
  {
    //read connection info
    string adServer = string.Format("LDAP://{0}", System.Configuration.ConfigurationSettings.AppSettings["ADServer"]);
    string user = System.Configuration.ConfigurationSettings.AppSettings["ADUser"];
    string password = System.Configuration.ConfigurationSettings.AppSettings["ADPassword"];

    DirectoryEntry ADentry = new DirectoryEntry(adServer, user, password);
    DirectorySearcher searcher = new DirectorySearcher(ADentry);
    searcher.Filter = String.Format("(&(objectClass=user)(objectCategory=person)(sAMAccountName={0}))", userName);
    searcher.SearchScope = SearchScope.Subtree;
    searcher.PropertiesToLoad.Add(propertyName);
    SearchResult result = searcher.FindOne();
    return result.Properties[propertyName][0].ToString();
  }


  /// <summary>
  /// Enum members of AD
  /// </summary>
  /// <param name="groupName">AD group name</param>
  [WebMethod]
  public DataSet ADEnumMembers(string groupName)
  {
    //creo la tabella che verrà restituita ad infopath, con le relative colonne
    DataSet ds = new DataSet("SelectTable");
    DataTable tbl = new DataTable("Users");
    ds.Tables.Add(tbl);
    tbl.Columns.Add("DisplayName", Type.GetType("System.String"));
    tbl.Columns.Add("Mail", Type.GetType("System.String"));
    tbl.Columns.Add("AccountName", Type.GetType("System.String"));

    DataTable tblTmp = new DataTable("Users1");
    ds.Tables.Add(tblTmp);
    tblTmp.Columns.Add("DisplayName", Type.GetType("System.String"));
    tblTmp.Columns.Add("Mail", Type.GetType("System.String"));
    tblTmp.Columns.Add("AccountName", Type.GetType("System.String"));

    //read connection info
    string adServer = string.Format("LDAP://{0}", System.Configuration.ConfigurationSettings.AppSettings["ADServer"]);
    string user = System.Configuration.ConfigurationSettings.AppSettings["ADUser"];
    string password = System.Configuration.ConfigurationSettings.AppSettings["ADPassword"];

    ADEnumMembersRecursive(adServer, groupName, tblTmp, user, password);

    //reorder list and remove duplicate
    List<string> duplicati = new List<string>();
    tblTmp.DefaultView.Sort = "DisplayName";
    foreach (DataRowView rowTmp in tblTmp.DefaultView)
    {
      string s1 = rowTmp["DisplayName"].ToString();
      string s2 = rowTmp["Mail"].ToString();
      string s3 = rowTmp["AccountName"].ToString();

      if (duplicati.Contains(s1) == false)
      {
        duplicati.Add(s1);
        DataRow row = tbl.NewRow();
        row["DisplayName"] = s1;
        row["Mail"] = s2;
        row["AccountName"] = s3;
        tbl.Rows.Add(row);
      }
    }

    ds.Tables.Remove("Users1");
    return ds;
  }

  private void ADEnumMembersRecursive(string cnn, string groupName, DataTable tbl, string user, string password)
  {
    if (string.IsNullOrEmpty(groupName) == true) return;
    DirectoryEntry ADentry = new DirectoryEntry(cnn, user, password);
    DirectorySearcher ADsearch = new DirectorySearcher(ADentry);
    ADsearch.Filter = string.Format("(CN={0})", groupName);
    ADsearch.SearchScope = SearchScope.Subtree;
    SearchResultCollection searchResults = ADsearch.FindAll();

    foreach (SearchResult rs in searchResults)
    {
      ResultPropertyCollection resultPropColl = rs.Properties;
      foreach (Object memberColl in resultPropColl["member"])
      {
        DirectoryEntry gpMemberEntry = new DirectoryEntry("LDAP://" + memberColl);
        System.DirectoryServices.PropertyCollection userProps = gpMemberEntry.Properties;
        string displayName = userProps["DisplayName"].Value == null ? "" : userProps["DisplayName"].Value.ToString();
        if (userProps["objectClass"][1].ToString() == "group")
        {
          ADEnumMembersRecursive(cnn, displayName, tbl, user, password);
        }
        else
        {
          string sAMAccountName = userProps["sAMAccountName"].Value == null ? "" : userProps["sAMAccountName"].Value.ToString();
          string mail = userProps["mail"].Value == null ? "" : userProps["mail"].Value.ToString();
          DataRow row = tbl.NewRow();
          row["DisplayName"] = displayName;
          row["Mail"] = mail;
          row["AccountName"] = sAMAccountName;
          tbl.Rows.Add(row);
        }
      }
    }
  }
  #endregion
Il web.config con i parametri di configurazione da aggiungere

XML

<?xml version="1.0"?>
<configuration>
  <appSettings>
    <add key="ADServer" value="DC=sgart,DC=local" />
    <add key="ADUser" value="SGART\administrator" />
    <add key="ADPassword" value="passworduser" />
  </appSettings>
  <system.web>
    <compilation debug="true">
      <assemblies>
        <add assembly="System.DirectoryServices, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/>
      </assemblies>
    </compilation>
  </system.web>
</configuration>
Tags:
C#236 Esempi225 InfoPath9 SharePoint498
Potrebbe interessarti anche: