2011-11-14 14 views
4

私はActive Directoryからいくつかのものを読み込むためにクエリを実行しました。 結果には、ある種の「ResultPropertyCollection」がプロパティとしてあります。 本文は全部知っています。どのようにリストに変換できますか?PropertyValueCollectionをList C#に変換する方法は? (ResultPropertyCollection、SearchResult、LDAP)

DirectoryEntry de = new DirectoryEntry("LDAP://" + this.rootLDAP); 
    DirectorySearcher ds = new DirectorySearcher(de, "(& (objectcategory=Group))"); 

    ds.PropertiesToLoad.Add("samaccountname"); 
    ds.PropertiesToLoad.Add("memberof"); 
    ds.PropertiesToLoad.Add("samaccounttype"); 
    ds.PropertiesToLoad.Add("grouptype"); 
    ds.PropertiesToLoad.Add("member"); 
    ds.PropertiesToLoad.Add("objectcategory"); 

    var r = (from SearchResult sr in ds.FindAll() select sr) .ToArray(); 

おかげ Farzad

答えて

7

あなたがすることはできません - 少なくともない非常に簡単。

var r = ds.FindAll(); 

List<SearchResult> results = new List<SearchResult>(); 

foreach (SearchResult sr in r) 
{ 
    results.Add(sr); 
} 

をしかし、あなたは検索結果から実際の値をしたい場合、あなたは多くの作業を実行する必要があります。

あなたは単にSearchResultタイプのリストを持っているしたい場合は、使用することができます。

基本的に、そのコレクションには、検索用に定義したすべてのプロパティが含まれています。少なくとも、値を含む限りです。

本当に、これらの値を保持するクラスを作成する必要があります。二つの要素がmemberOfあるとmember自体が複数の値を含めることができます(彼らはしている「複数値は、」ADの属性) - あなたはこれらの文字列のリスト必要があります:あなたが持っていると、次に

public class YourType 
{ 
    public string SamAccountName { get; set; } 
    public int SamAccountType { get; set; } 
    public int GroupType { get; set; } 
    public string ObjectCategory { get; set; } 
    public List<string> MemberOf { get; set; } 
    public List<string> Member { get; set; } 
} 

を検索結果には、結果を反復処理し、各検索結果のためのYourTypeの新しいインスタンスを作成し、List<YourType>にそれらを固執する必要があります。

foreach(SearchResult sr in ds.FindAll()) 
{ 
    YourType newRecord = ConvertToYourType(sr); 
} 

、その方法では、あなたはそれぞれの.Propertiesコレクションを検査する必要があります値とそれを抽出:

public YourType ConvertToYourType(SearchResult result) 
{ 
    YourType returnValue = new YourType(); 
    returnValue.MemberOf = new List<string>(); 
    returnValue.Member = new List<string>(); 

    if(result.Properties["samAccountName"] != null && result.Properties["samAccountName"].Count > 0) 
    { 
     returnValue.SamAccountName = result.Properties["samAccountName"][0].ToString(); 
    } 

    // ..... and so on for each of your values you need to extracxt 

    return returnValue; 
} 
+0

+1、私は必要な特定の値を取得する方法を理解できませんでした。ありがとう! – Cody

0

これは完全な解決策ではないかもしれません。以下 は

SearchResultCollection rc = ds.FindAll(); 

List<SearchResult> resultList = rc.Cast<SearchResult>().ToList(); 

// Now loop through the list 
foreach(SearchResult sr in resultList) 
{ 
    //.. get properties here 
} 
0

は、我々はこのようなものを使用することはできませんSearchResultCollectionListに変換する唯一のソリューションですか?

ds.FindAll().Cast<SearchResult>().Select(result => new Address(result.GetDirectoryEntry())).ToList(); 

public class Address 
{ 
    internal Address(DirectoryEntry entry) 
    { 
     // 
     // You can get one or more of the following properties: 
     // 
     // 
     // objectClass 
     // cn 
     // description 
     // givenName 
     // distinguishedName 
     // instanceType 
     // whenCreated 
     // whenChanged 
     // displayName 
     // uSNCreated 
     // memberOf 
     // uSNChanged 
     // homeMTA 
     // proxyAddresses 
     // homeMDB 
     // mDBUseDefaults 
     // mailNickname 
     // protocolSettings 
     // name 
     // objectGUID 
     // userAccountControl 
     // badPwdCount 
     // codePage 
     // countryCode 
     // badPasswordTime 
     // lastLogon 
     // pwdLastSet 
     // primaryGroupID 
     // objectSid 
     // accountExpires 
     // logonCount 
     // sAMAccountName 
     // sAMAccountType 
     // showInAddressBook 
     // legacyExchangeDN 
     // userPrincipalName 
     // lockoutTime 
     // objectCategory 
     // dSCorePropagationData 
     // lastLogonTimestamp 
     // textEncodedORAddress 
     // mail 
     // msExchPoliciesExcluded 
     // msExchMailboxTemplateLink 
     // msExchRecipientDisplayType 
     // msExchUserCulture 
     // msExchVersion 
     // msExchRecipientTypeDetails 
     // msExchHomeServerName 
     // msExchALObjectVersion 
     // msExchMailboxSecurityDescriptor 
     // msExchUserAccountControl 
     // msExchMailboxGuid 
     // nTSecurityDescriptor 

     // As an example we get only two properties 
     this.DisplayName = (string)entry.Properties["displayName"].Value; 
     this.Mail = (string)entry.Properties["mail"].Value; 
     Manager = (string)entry.Properties["manager"].Value; 
    } 

    public string DisplayName 
    { 
     get; 
     private set; 
    } 

    public string Manager 
    { 
     get; 
     private set; 
    } 

    public string Mail 
    { 
     get; 
     private set; 
    } 
} 
0

私も最初は混乱していた(私は現在、それを使用していたよう)が、それはプロパティコレクションアイテムの種類を取得するすべての問題でした。プロパティーアイテムのタイプがSystem.Collections.DictionaryEntryであり、値がResultPropertyValueCollectionアイテムから作られたコレクションであることが分かったら、単純な繰り返しが可能でした。

 bool attemptResult = false; 
     string ldap = "LDAP:<Your A.D. specific connection string>"; 
     DirectoryEntry entry = new DirectoryEntry(ldap, username, password, AuthenticationTypes.Secure); 

     try 
     { 
      DirectorySearcher searcher = new DirectorySearcher(entry); 
      searcher.Filter = "(&(objectClass=User)(sAMAccountName=" + username + "))"; 
      SearchResult one = searcher.FindOne(); 
      attemptResult = true; 
      string properties = ""; 
      string userData = JsonConvert.SerializeObject(one.Properties); 
      foreach (System.Collections.DictionaryEntry de in one.Properties) { 
       properties += (properties.Length > 0 ? ",\n" : ""); 
       properties += "\"" + de.Key + "\": ["; 
       ResultPropertyValueCollection vc = ((ResultPropertyValueCollection)de.Value); 
       foreach (var val in vc) { 
        properties += "{\"type\": \"" + val.GetType().Name + "\", \"value\"; \"" + val.ToString() + "\"}"; 
       } 
       properties += "]"; 
      } 
      properties = properties.Replace("}{", "},{"); 

      string displayName = one.Properties["displayname"][0].ToString(); 
      string givenName = one.Properties["givenname"][0].ToString(); 
      string lastname = one.Properties["sn"][0].ToString(); 
     } 
     catch (Exception e) { 
      //log the error; 
     }    
     return attemptResult; 

お知らせJsonConvert.SerializeObjectを使用して文字列に迅速かつ簡単に変換:ここ

は私がなってしまったものです。これはワンステップ変換です。

私はまた、foreach反復を使用して文字列にパーソナライズされた変換を実行しました。これは、名前付きプロパティの値を取得した後で、それを得ると、プロパティをゼロ、1つ以上の値があるかどうか調べ、必要に応じてオブジェクトの型を検証することもできます。

文字列変数、プロパティ、およびuserDataの両方で取得された値です(プライバシーのために削除された項目もあります)。

/* Value of userData Obtained with Json serializator*/ 

{"givenname":["First Name"],"samaccountname":["User.Name"],"cn":["First Name Last Name"],"pwdlastset":[131641282827115142],"whencreated":["2017-10-12T22:16:43"],"badpwdcount":[0],"displayname":["First Name Last Name"],"lastlogon":[131648243091569908],"samaccounttype":[805306368],"countrycode":[0],"objectguid":["SOMETHINGBASE64LIKE=="],"usnchanged":[52144153],"manager":["CN=The Name Of A Person,OU=Department Name,OU=City,OU=GroupName ,DC=Domain,DC=com"],"whenchanged":["2018-03-02T23:21:54"],"name":["First Name Last Name"],"objectsid":["SOMETHINGBASE64LIKE=="],"lastlogoff":[0],"lockouttime":[0],"badpasswordtime":[131647632246625185],"instancetype":[4],"primarygroupid":[513],"objectcategory":["CN=Person,CN=Schema,CN=Configuration,DC=Domain,DC=com"],"logoncount":[1073],"useraccountcontrol":[512],"description":["Some text"],"dscorepropagationdata":["1601-01-01T00:00:00"],"distinguishedname":["CN=First Name Last Name,OU=Department Name,OU=City,OU=GroupName ,DC=Domain,DC=com"],"objectclass":["top","person","organizationalPerson","user"],"adspath":["LDAP://Server/CN=First Name Last Name,OU=Department Name,OU=City,OU=GroupName ,DC=Domain,DC=com"],"usncreated":[39705915],"lastlogontimestamp":[131643676396776065],"userprincipalname":["[email protected]"],"employeeid":["99999"],"accountexpires":[9223372036854775807],"department":["DepartmentName"],"codepage":[0],"sn":["Last Name"]} 

/* value of properties, the string I concatenated */ 
"givenname": [{"type": "String", "value"; "First Name"}], 
"samaccountname": [{"type": "String", "value"; "User.Name"}], 
"cn": [{"type": "String", "value"; "First Name Last name"}], 
"pwdlastset": [{"type": "Int64", "value"; "131641282827115142"}], 
"whencreated": [{"type": "DateTime", "value"; "12/10/2017 10:16:43 p. m."}], 
"badpwdcount": [{"type": "Int32", "value"; "0"}], 
"displayname": [{"type": "String", "value"; "First Name Last name"}], 
"lastlogon": [{"type": "Int64", "value"; "131648243091569908"}], 
"samaccounttype": [{"type": "Int32", "value"; "805306368"}], 
"countrycode": [{"type": "Int32", "value"; "0"}], 
"objectguid": [{"type": "Byte[]", "value"; "System.Byte[]"}], 
"usnchanged": [{"type": "Int64", "value"; "52144153"}], 
"manager": [{"type": "String", "value"; "CN=Some Person Name,OU=Department name,OU=City,OU=Group Name,DC=Domain,DC=com"}], 
"whenchanged": [{"type": "DateTime", "value"; "2/3/2018 11:21:54 p. m."}], 
"name": [{"type": "String", "value"; "First Name Last name"}], 
"objectsid": [{"type": "Byte[]", "value"; "System.Byte[]"}], 
"lastlogoff": [{"type": "Int64", "value"; "0"}], 
"lockouttime": [{"type": "Int64", "value"; "0"}], 
"badpasswordtime": [{"type": "Int64", "value"; "131647632246625185"}], 
"instancetype": [{"type": "Int32", "value"; "4"}], 
"primarygroupid": [{"type": "Int32", "value"; "513"}], 
"objectcategory": [{"type": "String", "value"; "CN=Person,CN=Schema,CN=Configuration,DC=Domain,DC=com"}], 
"logoncount": [{"type": "Int32", "value"; "1073"}], 
"useraccountcontrol": [{"type": "Int32", "value"; "512"}], 
"description": [{"type": "String", "value"; "13065, PROGRAMADOR SENIOR"}], 
"dscorepropagationdata": [{"type": "DateTime", "value"; "1/1/1601 12:00:00 a. m."}], 
"distinguishedname": [{"type": "String", "value"; "CN=First Name Last name,OU=Department name,OU=City,OU=Group Name,DC=Domain,DC=com"}], 
"objectclass": [{"type": "String", "value"; "top"},{"type": "String", "value"; "person"},{"type": "String", "value"; "organizationalPerson"},{"type": "String", "value"; "user"}], 
"adspath": [{"type": "String", "value"; "LDAP://SERVERNAME/CN=First Name Last name,OU=Department name,OU=City,OU=Group Name,DC=Domain,DC=com"}], 
"usncreated": [{"type": "Int64", "value"; "39705915"}], 
"lastlogontimestamp": [{"type": "Int64", "value"; "131643676396776065"}], 
"userprincipalname": [{"type": "String", "value"; "[email protected]"}], 
"employeeid": [{"type": "String", "value"; "13065"}], 
"accountexpires": [{"type": "Int64", "value"; "9223372036854775807"}], 
"department": [{"type": "String", "value"; "IT"}], 
"codepage": [{"type": "Int32", "value"; "0"}], 
"sn": [{"type": "String", "value"; "Last name"}] 

ご覧のとおり、一部のプロパティには複数の値があります。したがって、単純な汎用プロパティリストを取得するには、複数値プロパティを使用して何を行うかを決定する必要があります。おそらく、すべての値を文字列として扱いたいので、適切なセパレータを使用して複数の値を連結することができます。

関連する問題