16. グループ取得サンプルコード(VB)
Public Shared Function GetGroups(
Of T As {DirectoryObject, IGroup}) As IList(Of T)
Dim groups As New List(Of T)()
Using root = GetRootEntry() ’ルートのDirectoryEntryを取得
Dim filter = String.Format("(objectCategory={0})", CategoryType.Group)
Using searcher As New DirectorySearcher(root, filter)
Using results = searcher.FindAll()
For Each res As SearchResult In results
groups.Add(DirectCast(CreateInstance(res.GetDirectoryEntry()),
T))
Next
End Using
End Using
End Using
Return groups
End Function
※root は一般的には New DirectoryEntry(LDAPのルートパス) をセット
※CreateInstance メソッドは DirectoryEntry から DirectoryObject を作成
16
17. グループ取得サンプルコード(C#)
public static IList<T> GetGroups<T>()
where T : DirectoryObject, IGroup {
var grous = new List<T>();
using (var root = GetRootEntry()) { //ルートのDirectoryEntryを取得
var filter = String.Format("(objectCategory={0})", CategoryType.Group);
using (var searcher = new DirectorySearcher(root, filter)) {
using (var results = searcher.FindAll()) {
foreach (SearchResult res in results) {
groups.Add((T)CreateInstance(res.GetDirectoryEntry()));
}
}
}
}
return groups;
}
※root は一般的には new DirectoryEntry(LDAPのルートパス) をセット
※CreateInstance メソッドは DirectoryEntry から DirectoryObject を作成
17
20. メンバ名の取得サンプルコード(VB)
対象グループを group As IADsGroup とすると
For Each member As IADs In group.Members()
Dim objectType = DirectCast([Enum].Parse(GetType(CategoryType),
member.Class, True), CategoryType) 'ディレクトリ オブジェクトの種類
'外部のセキュリティプリンシパルの時
If objectType = CategoryType.ForeignSecurityPrincipal Then
Dim objectSid = DirectCast(member.Get("objectSid"), Byte())
Dim sid = New SecurityIdentifier(objectSid, 0) 'SID
'アカウントに変換
Dim account = DirectCast(
sid.Translate(GetType(NTAccount)), NTAccount)
'account.Value または account.ToString() でメンバ名を取得
Else '外部のセキュリティプリンシパル以外の時
'member.Get(”cn”).ToString() でメンバ名を取得
End If
Next
20
21. メンバ名の取得サンプルコード(C#)
対象グループを IADsGroup group とすると
foreach (IADs member in group.Members()) {
var objectType = (CategoryType)Enum.Parse(typeof(CategoryType),
member.Class, true); //ディレクトリ オブジェクトの種類
//外部のセキュリティプリンシパルの時
if (objectType == CategoryType.ForeignSecurityPrincipal) {
var objectSid = (byte[])member.Get("objectSid");
var sid = new SecurityIdentifier(objectSid, 0); //SID
//アカウントに変換
var account = (NTAccount)sid.Translate(typeof(NTAccount));
//account.Value または account.ToString() でメンバ名を取得
} else { //外部のセキュリティプリンシパル以外の時
//member.Get(”cn”).ToString() でメンバ名を取得
}
}
21
23. 所属するグループの取得サンプルコード
対象グループを group(DirectoryEntry 型)とすると
VB
For Each groupPath As String In group.Properties.Item("memberOf")
name = DirectoryAccess.PathToCn(groupPath) '名前を取得
path = DirectoryAccess.GetBelongPath(groupPath) '所属パスを取得
Next
C#
foreach (string groupPath in group.Properties["memberOf"]) {
name = DirectoryAccess.PathToCn(groupPath); //名前を取得
path = DirectoryAccess.GetBelongPath(groupPath); //所属パスを取得
}
23