воскресенье, 26 августа 2012 г.

VB.NET and Novell eDirectory: read, modify. Читаем и пишем в Novell eDirectory с VB.NET

Использую следующие скрипты в SSIS в качестве Script Source и Destination components:


Поиск и чтение атрибутов:

Imports System
Imports System.Data
Imports System.Math
Imports System.Security.Cryptography.X509Certificates
Imports System.DirectoryServices.Protocols
Imports Microsoft.SqlServer.Dts.Pipeline.Wrapper
Imports Microsoft.SqlServer.Dts.Runtime.Wrapper

_
_
Public Class ScriptMain
    Inherits UserComponent

    Public Overrides Sub PreExecute()
        MyBase.PreExecute()
        '
        ' Add your code here for preprocessing or remove if not needed
        '
    End Sub

    Public Overrides Sub PostExecute()
        MyBase.PostExecute()
        '
        ' Add your code here for postprocessing or remove if not needed
        ' You can set read/write variables here, for example:
        ' Me.Variables.MyIntVar = 100
        '
    End Sub

    Public Overrides Sub CreateNewOutputRows()
        '
        ' Add rows by calling the AddRow method on the member variable named "Buffer".
        ' For example, call MyOutputBuffer.AddRow() if your output was named "MyOutput".

        Dim con As New LdapConnection(New LdapDirectoryIdentifier("ipaddress:636")) ' подключение у нас через SSL, поэтому такой порт
        con.SessionOptions.SecureSocketLayer = True ' туда же
        con.SessionOptions.VerifyServerCertificate = AddressOf ServerCallback ' поскольку self-signed certificate, надо использовать этот способ, чтобы его игнорировать
        Dim credential As New System.Net.NetworkCredential("cn=login,o=services", "password")
        con.AuthType = AuthType.Basic
        con.Credential = credential

        Using con
            Dim attributesToReturn As String() = New String() {"sNum", "cn", "login", "givenName", "sn", "dioceseEmail", "dioceseEmailAlias"}
            Dim request As New SearchRequest("ou=Users,ou=Sydney,o=COMMUNITIES", "(&(objectClass=user)(login=*)(sNum=*)(!dioceseEmail=*))", SearchScope.Subtree, attributesToReturn)
            Dim response As SearchResponse = DirectCast(con.SendRequest(request, New TimeSpan(1, 0, 0, 0, 0)), SearchResponse)
  
            If response.Entries.Count > 0 Then
                Dim counter As Integer = 0
                For Each entry As SearchResultEntry In response.Entries
                    Output0Buffer.AddRow()
                    Output0Buffer.login = entry.Attributes.Item("login").Item(0).ToString
                    Output0Buffer.sNum = entry.Attributes.Item("sNum").Item(0).ToString
                Next
            End If
        End Using
        '
        'Dts.TaskResult = ScriptResults.Success
    End Sub
    Function ServerCallback(ByVal connection As LdapConnection, ByVal certificate As X509Certificate) As Boolean ' вот эта часть занимается проверкой (точнее, игнорированием) сертификата
        Return True
    End Function
End Class

Поиск и модификация атрибутов:

' Microsoft SQL Server Integration Services Script Component
' Write scripts using Microsoft Visual Basic 2008.
' ScriptMain is the entry point class of the script.

Imports System
Imports System.Data
Imports System.Math
Imports System.Security.Cryptography.X509Certificates
Imports System.DirectoryServices.Protocols
Imports System.Data.SqlClient ' это мне для лога ошибок и успехов
Imports Microsoft.SqlServer.Dts.Pipeline.Wrapper
Imports Microsoft.SqlServer.Dts.Runtime.Wrapper

_
_
Public Class ScriptMain
    Inherits UserComponent

    Public Overrides Sub PreExecute()
        MyBase.PreExecute()
        '
        ' Add your code here for preprocessing or remove if not needed
        '
    End Sub

    Public Overrides Sub PostExecute()
        MyBase.PostExecute()
        '
        ' Add your code here for postprocessing or remove if not needed
        ' You can set read/write variables here, for example:
        ' Me.Variables.MyIntVar = 100
        '
    End Sub

    Public Overrides Sub Input0_ProcessInputRow(ByVal Row As Input0Buffer)
        Dim sNum As String, login As String, dioceseEmail As String, dioceseEmailAlias As String
        sNum = Row.sNum
        login = Row.login
        dioceseEmail = Row.dioceseEmail
        dioceseEmailAlias = Row.dioceseEmailAlias
        '
        Dim con As New LdapConnection(New LdapDirectoryIdentifier("ipaddress:636"))
        con.SessionOptions.SecureSocketLayer = True
        con.SessionOptions.VerifyServerCertificate = AddressOf ServerCallback
        Dim credential As New System.Net.NetworkCredential("cn=login,o=services", "password")
        con.AuthType = AuthType.Basic
        con.Credential = credential

        Using con
            Dim attributesToReturn As String() = New String() {"sNum"}
            Dim request As New SearchRequest("ou=Users,ou=Sydney,o=COMMUNITIES", "(&(objectClass=user)(login=" & login & ")(sNum=" & sNum & " )(!dioceseEmail=*))", System.DirectoryServices.Protocols.SearchScope.Subtree, attributesToReturn)
            Dim response As SearchResponse = DirectCast(con.SendRequest(request, New TimeSpan(1, 0, 0, 0, 0)), SearchResponse)
            If response.Entries.Count > 0 Then
                Dim counter As Integer = 0
            
                For Each entry As SearchResultEntry In response.Entries
                 
                    Dim modifyUserDioceseEmail As New DirectoryAttributeModification()
                    modifyUserDioceseEmail.Operation = DirectoryAttributeOperation.Replace
                    modifyUserDioceseEmail.Name = "dioceseEmail"
                    modifyUserDioceseEmail.Add(dioceseEmail)

                    Dim modifyUserDioceseEmailAlias As New DirectoryAttributeModification()
                    modifyUserDioceseEmailAlias.Operation = DirectoryAttributeOperation.Replace
                    modifyUserDioceseEmailAlias.Name = "dioceseEmailAlias"
                    modifyUserDioceseEmailAlias.Add(dioceseEmailAlias)

                    Dim modifyRequest As New ModifyRequest(entry.DistinguishedName, modifyUserDioceseEmail)
                    Dim response2 As DirectoryResponse = con.SendRequest(modifyRequest)
                    Dim modifyRequest2 As New ModifyRequest(entry.DistinguishedName, modifyUserDioceseEmailAlias)
                    Dim response3 As DirectoryResponse = con.SendRequest(modifyRequest2)

                    Dim connMgr As ConnectionManagerAdoNet
                    Dim sqlConn As SqlConnection
                    connMgr = Me.Connections.SNWDConnection
                    sqlConn = CType(connMgr.AcquireConnection(Nothing), SqlConnection)
                    'подхватили соединение
                    Dim sqlCmd As New SqlCommand("UPDATE idm.IDVEmails set timestamp=getdate() where sNum='" & sNum & "' and login='" & login & "'") ' записали результат
                    sqlCmd.Connection = sqlConn
                    sqlCmd.ExecuteNonQuery()
                    connMgr.ReleaseConnection(sqlConn)

                Next
            End If
        End Using
        '
        ' Dts.TaskResult = ScriptResults.Success
    End Sub
    Function ServerCallback(ByVal connection As LdapConnection, ByVal certificate As X509Certificate) As Boolean
        Return True
    End Function
End Class

Удаление объектов:


' Microsoft SQL Server Integration Services Script Component
' Write scripts using Microsoft Visual Basic 2008.
' ScriptMain is the entry point class of the script.

Imports System
Imports System.Data
Imports System.Math
Imports System.Security.Cryptography.X509Certificates
Imports System.DirectoryServices.Protocols
Imports Microsoft.SqlServer.Dts.Pipeline.Wrapper
Imports Microsoft.SqlServer.Dts.Runtime.Wrapper

_
_
Public Class ScriptMain
    Inherits UserComponent

    Public Overrides Sub PreExecute()
        MyBase.PreExecute()
        '
        ' Add your code here for preprocessing or remove if not needed
        '
    End Sub

    Public Overrides Sub PostExecute()
        MyBase.PostExecute()
        '
        ' Add your code here for postprocessing or remove if not needed
        ' You can set read/write variables here, for example:
        ' Me.Variables.MyIntVar = 100
        '
    End Sub

    Public Overrides Sub Input0_ProcessInputRow(ByVal Row As Input0Buffer)
        '
        Dim con As New LdapConnection(New LdapDirectoryIdentifier("10.80.2.100:636"))
        con.SessionOptions.SecureSocketLayer = True
        con.SessionOptions.VerifyServerCertificate = AddressOf ServerCallback
        Dim credential As New System.Net.NetworkCredential("cn=login,o=services", "password")
        con.AuthType = AuthType.Basic
        con.Credential = credential

        Using con
            'Dim attributesToReturn As String() = New String() {"workforceID", "cn", "uniqueID", "givenName", "sn", "fullName", "mail", "loginDisabled"}
            Dim attributesToReturn As String() = New String() {"sNum", "cn", "login", "givenName", "sn", "dioceseEmail", "dioceseEmailAlias"}
            Dim request As New SearchRequest("ou=Sydney,o=COMMUNITIES", Row.SearchFilter, System.DirectoryServices.Protocols.SearchScope.Subtree, attributesToReturn)
            Dim response As SearchResponse = DirectCast(con.SendRequest(request, New TimeSpan(1, 0, 0, 0, 0)), SearchResponse)
            'con.Bind()
            If response.Entries.Count > 0 Then
                For Each entry As SearchResultEntry In response.Entries
                    Dim deleteRequest As New DeleteRequest(entry.DistinguishedName)
                    Dim response2 As DirectoryResponse = con.SendRequest(deleteRequest)
                Next
            End If
        End Using
        '
    End Sub
    Function ServerCallback(ByVal connection As LdapConnection, ByVal certificate As X509Certificate) As Boolean
        Return True
    End Function
End Class



Источники:

Комментариев нет: