天天看點

Introduction to System.DirectoryServices.Protocols (S.DS.P) 系統目錄服務協定類庫——部分翻譯Introduction to System.DirectoryServices.Protocols (S.DS.P)介紹系統目錄服務協定類庫

Introduction to System.DirectoryServices.Protocols (S.DS.P)介紹系統目錄服務協定類庫

Establishing an LDAP Connection(建立一個LDAP連接配接)

Request and Response Classes(請求響應類)

A fundamental part of interacting withadirectory service via LDAP is creating and sending requests andreceivingresponses. The synchronous S.DS.P method for sending a request is SendRequest.A directory server thenreturns a response that you can cast into theappropriate response object.

通過LDAP與目錄服務互動的一個基本組成部分是建立、發送請求和接收響應。同步S.DS.P方法是SendRequest發送請求。目錄伺服器傳回的響應,你可以丢在适當的響應對象。

When you call the SendRequest methodofan LdapConnection, the method ships an LDAP operation to adirectoryserver and the server returns aDirectoryResponseobject. Theobject returned aligns in structure with the type of request. Forexample, ifyou supply the SendRequest method with an AddRequest object,the directory serverreturns a DirectoryResponse objectthat isstructurally equivalent to an AddResponseobject. You must then castthe returned DirectoryResponse base classinto an AddResponse objectbeforeyou inspect the response. The pattern for this is: 

當你調用LdapConnection的SendRequest方法,該方法對目錄服務運作一個Ldap操作并且這個服務傳回一個DirectoryResponse的對象。傳回的對象與其請求的類型在結構上是一緻的。例如,如果你提供帶有AddRequest對象的SendRequest方法,目錄服務傳回一個DirectoryResponse對象,在結構上相當于一個AddResponse對象。在你檢查響應之前,你必須把傳回的DirectoryResponse基類投射到一個AddResponse對象。該模式是:

DirectoryRequestType request = new DirectoryRequestType(parameters…);
DirectoryResponseType response = (DirectoryResponseType)connection.SendRequest(request);

           

The following code snippet demonstrates how to implement this pattern using the AddRequest and AddResponse objects. The values of the dn and dirClassType are defined elsewhere and are not shown here to avoid obscuring the pattern:

下面的代碼片斷示範了如何使用AddRequest和AddResponse對象實作這種模式。dn和dirClassType的值定義在其他地方,這裡沒有顯示,以避免混淆模式:

// build an addrequest object 建立一個 AddRequest對象
AddRequest addRequest = new AddRequest(dn, dirClassType);
                
// cast the response into an AddResponse object to get the response 把響應變成一個AddResponse對象來擷取響應
AddResponse addResponse = (AddResponse)connection.SendRequest(addRequest);


           

The following request classes map to the listed response classes appearing in Table 1:

以下請求類映射到出現在表1中的列出的響應類:

Table 1. DirectoryRequest and Corresponding DirectoryResponse Classes

表1: 目錄請求類與對應的目錄響應類

Introduction to System.DirectoryServices.Protocols (S.DS.P) 系統目錄服務協定類庫——部分翻譯Introduction to System.DirectoryServices.Protocols (S.DS.P)介紹系統目錄服務協定類庫

The .NET Framework SDK Class Library Reference describes the purpose of each request and response class. In addition, I demonstrate how to use all of these request objects except the last two DSML request objects. For more information on S.DS.P architecture, see "System.DirectoryServices.Protocols Architecture" at http://msdn2.microsoft.com/en-us/library/ms257187.aspx.

這個.NET 架構 SDk類庫參考描述每個請求和響應的目的類。此外,我将示範如何使用所有這些請求的對象,除了最後兩個DSML請求對象。對于S.DS.P架構的更多資訊,請參閱“系統目錄服務協定體系結構”http://msdn2.microsoft.com/en-us/library/ms257187.aspx.

Management Tasks 管理任務

Common directory services management tasks include creating, adding, moving, modifying and deleting directory objects. While S.DS provides all of these capabilities, S.DS.P allows you to use common LDAP programming constructs to perform the same tasks. S.DS is easier for these code tasks, but seeing how to complete these familiar tasks with S.DS.P is a great way to introduce key members of this namespace.

常見的目錄服務管理任務包括建立,增加,移動,修改,删除目錄對象。雖然S.DS 提供所有這些功能,S.DS.P允許你使用常見的LDSP程式設計構造來執行相同的任務。S.DS更容易進行這些代碼的任務,但是現在看看,如果用S.DS.P完成這些類似的任務,S.DS.P是強大的途徑來介紹這些命名空間的關鍵成員。

LDAP Directory Management Tasks LDAP目錄管理任務

Code examples in this section will build on one another to familiarize you with the common patterns. For instance, the first example will show you how to create 100 user accounts in just a few lines of code by using the AddRequest object, but it won't show you how to get a response back about the task from a directory server. The next example returns to the essence of the first create users task by demonstrating how to add any valid object to the directory, and it also shows how to get a response back about the task. A later example introduces you to the ModifyRequest object for managing an attribute, but it doesn't demonstrate how to get a response back about whether the attribute was successfully modified. Immediately following that example, I introduce the ModifyResponse object. This incremental approach, I believe, will help you better understand how to build on the examples to create more complex and useful code.

本節中的代碼示例将建立在彼此熟悉的常見模式。例如,第一個例子将告訴你,如何在短短的幾行代碼中,使用AddRequest對象建立100個使用者帳号,但是它不會告訴你如何從目錄伺服器的任務得到響應。下一個例子傳回第一次建立使用者任務的本質,通過示範如何增加一些有效的對象目錄,這也說明了如何得到響應的任務。後面的例子向您介紹ModifyRequest對象的屬性管理,但這并不說明如何得到一個響應傳回的屬性是否被成功修改。緊跟着,示例中,我将介紹ModifyResponse對象。我相信,這種循序漸進的方式,将會幫助你更好的了解如何建構示例來建立更複雜和有用的代碼。

Creating Users Accounts  建立使用者帳号

A classic initial demonstration of directory services programming techniques often involves generating many user accounts with only a few lines of code. As S.DS.P is arguably the most radical departure from traditional directory services coding in the .NET Framework, I think a multi-user creation example is a good starting point. I think you would agree that it's more useful than writing Hello World to an attribute!

一個經典的初始目錄服務程式設計技術示範通常包括生成許多使用者帳戶,隻需要幾行代碼。由于S.DS.P從傳統的編碼。NET架構中的目錄服務可以說是最根本的出發,我認為一個多使用者建立的例子是一個很好的起點。我想你會同意,這比編寫Hello World的屬性更有用!

The following code example demonstrates how to create 100 user accounts in just a few lines of code:

下面的代碼示例示範了如何建立100個使用者賬戶在短短幾行代碼:

  1. Establish an LDAP connection to a directory server.

    建立LDAP連接配接到目錄伺服器 

    In an Active Directory domain, the Locator service provides the host name of a domain controller in the specified domain for the connection.

    在ActiveDirectory域,定位器服務提供的連接配接在指定的域的域控制器的主機名。

  2. Declare and initialize the dn variable with the distinguishedName value of each user account to create.

    聲明并初始化distinguishedName值,每個使用者帳戶建立的DN變量。

  3. Call the SendRequest method of the connection object to transport each request to a directory server.

    調用SendRequest連接配接對象的方法,運送到目錄伺服器的每個請求。

    You pass a directory request (in this case an AddRequest) to the SendRequest method. TheSendRequest method then automatically binds to a domain controller in the targeted domain using the current user's credentials.  

    你傳遞一個目錄請求(在這種情況下,一個AddRequest)的SendRequest方法。SendRequest方法自動綁定到在目标域使用目前使用者憑證的域控制器。

Example 1. Creating 100 user accounts

示例1.建立100個使用者帳戶。

LdapConnection connection = new LdapConnection("fabrikam.com");
for (int i = 1; i <= 101; i++)
{
    string dn = "cn=user" + i + ",ou=UserAccounts,dc=fabrikam,dc=com";
    connection.SendRequest(new AddRequest(dn, "user"));
}

           

If you were to run this code, you wouldn't get any return results and the user accounts created in the fabrikam.com Active Directory domain would be disabled. Obviously, this is a pedantic example, but it effectively demonstrates that even a namespace as sophisticated as S.DS.P provides a simple and elegant model to complete significant directory management tasks.

如果你要運作此代碼,你不會得到任何傳回結果和使用者帳戶将被禁用在fabrikam.com的Active Directory域的建立。很顯然,這是個迂腐的例子,但是它有效地表明,即使是一個複雜的S.DS.P的命名空間,也提供了一個簡單而優雅的模型,來完成重要的目錄管理任務。

Adding an Object to a Directory将對象添加到目錄

As you saw in the previous create user example, when you call the SendRequest method, you pass the method an AddRequest object to create a user by the specified name. The second parameter in the AddRequest can either be an array of attributes to assign to the object or the lDAPDisplayName of the class schema object from which the object should be derived.

正如你看到的在前面建立的使用者的例子,當你調用SendRequest方法,你給方法傳遞一個AddRequest對象來建立一個使用者指定的名稱。AddRequest的第二個參數可以是一個屬性數組配置設定的對象或者對象應得的類架構對象LdapDisplayName.

In order to get a response from a directory server about the success or failure of the requested operation, you cast the returned DirectoryResponse base class into the proper response type based on the type of DirectoryRequest object you pass to theSendRequest method.

為了得到響應從目錄伺服器所請求的操作是成功還是失敗,你投遞的傳回到适當的響應類型的類型的DirectoryResponse對象傳遞給SendRequest方法的基礎上DirectoryResponse基類.

The following code example demonstrates how to add a directory object named Seasoned derived from the organizationalUnit class schema object to the directory below the techwriters ou in the fabrikam.com domain:

下面的代碼示例示範了如何增加一個目錄對象,命名為經驗豐富的organizationalUnit類架構對象目錄下面的techwriters fabrikam.com域中的OU:

  1. Declare and initialize some string variables used later in the example.

    聲明和初始化在本例中使用的一些字元串變量。

    The corresponding code download allows you to pass these and other values in as command line arguments.

    下載下傳相應的代碼,使您可以通過這些和其他值作為指令行參數。

  2. Create an LdapConnection object for connecting to a domain controller in the fabrikam.com domain.

    建立一個連接配接到fabrikam.com域中的域控制器的LdapConnection對象。

    Because a specific domain controller was not declared for the hostordomainName variable, the Active Directory Locator will find an available domain controller for the binding operation. This is referred to as serverless binding.

    由于特定的域控制器沒有聲明hostordomainName變量。Active Directory定位器将找到一個可用的域控制器綁定操作。這是被稱為伺服器綁定。

  3. Create an AddRequest object and pass it the distinguished name stored in the dn variable and the lDAPDisplayName of the class schema object to instantiate.

    建立一個AddRequest的對象并将其傳遞的可分辨名稱存儲在dn變量,并執行個體化一個類結構對象LdapDisplayName,

  4. Call the SendRequest method of the connection object and cast the returned DirectoryResponse as an AddResponse object.

    調用連接配接對象的SendRequest方法并投射傳回DirectoryResponse 作為AddResponse對象。

    An implicit bind occurs here.

    這裡出現隐式綁定。

  5. Display information about the request. The response from the directory server is contained in theResultCode property of the addResponse object.

    顯示有關請求的資訊。從目錄伺服器的響應包含在AddResponse對象的ResultCode屬性中。

    The AddResponse class contains an ErrorMessage response property that you can display for more information on any error that might be returned from the directory server.   

    AddResponse類包含一個錯誤資訊的響應屬性,您也許能從目錄伺服器傳回更多的關于錯誤資訊。

Example 2. Adding an OrganizationalUnit object 

示例2. 添加OrganizationalUnit對象

string hostOrDomainName = "fabrikam.com";
string dn = "ou=Seasoned,ou=techwriters,dc=fabrikam,dc=com";
string dirClasstype = "organizationalUnit";

// establish a connection to the directory 建立一個連接配接到該目錄
LdapConnection connection = new LdapConnection(hostOrDomainName);

try
{
    // create an addrequest object  建立一個addrequest對象
    AddRequest addRequest = new AddRequest(dn, dirClassType);

    // cast the returned DirectoryResponse as an AddResponse object
    //将傳回DirectoryResponse作為一個AddResponse對象
    AddResponse addResponse = (AddResponse)connection.SendRequest(addRequest);

    Console.WriteLine("A {0} with a dn of\n {1} was added successfully " + 
       "The server response was {2}",
        dirClassType, dn, addResponse.ResultCode);
}
catch (Exception e)
{    Console.WriteLine("\nUnexpected exception occured:\n\t{0}: {1}",
                      eGetType().Name, e.Message);
}


           

Adding an Object to a Directory Using a Different AddRequest Constructor 

 使用不同的AddRequest 的構造函數,将一個對象添加到一個目錄中

Before delving into another code example, let's step back for a moment and consider how the definition of class schema objects plays an important role in directory object creation. This is essential to understand before you try to use the alternative AddRequest constructor to create directory objects.

深究另一個代碼示例之前,讓我們回顧一下,并考慮如何定義的類架構對象起着重要的作用在目錄中建立對象。這是必須了解的,在你試圖使用替代AddRequest的構造函數來建立目錄對象之前。

The attributes of a class schema object define the object. A key part of that definition is the attributes that the object must or may contain. When you instantiate a directory object from a class schema object, you or the directory service must provide values for any attributes that the directory object must contain (mandatory attributes) when it is created. 

一個類架構對象的屬性定義的對象。該定義的一個關鍵部分是對象的屬性必須或者可能包含。當你從一個類架構對象執行個體化一個目錄對象,你必須提供目錄伺服器建立時必須包含的屬性值(強制屬性)。

In the prior code example (Example 2), I demonstrate how to add an OrganizationalUnit object to the directory by using the AddRequest constructor. In that case, the constructor takes the distinguishedName of the object to create and the type of object class from which the object is derived. If you take a close look at the organizationalUnit class schema object in an Active Directory or ADAM schema, you will see that theinstanceType,objectCategory,nTSecurityDescriptor,objectClass andou attributes must be defined for the object in order for it to be created. TheorganizationalUnit class inherits from theTop schema class object, which defines the first four of those attributes as mandatory and theorganizationalUnit class defines theou attribute as mandatory. You must provide values for theou attribute and theobjectClass attribute, and directory services takes care of providing the other values.

在之前的代碼示例(例2)中,我示範了如何用AddRequest構造函數增加一個OrganizationalUnit對象到目錄中。 既然這樣,構造函數将distinguishedName對象的建立和對象類的類型,從該對象派生。如果你仔細看organizationalUnit類模式對象在Active

Directory或ADAM模式,你将會看到instanceType, objectCategory, nTSecurityDescriptor, objectClass and ou 屬性必須被定義的對象,以便它被建立。organizationalUnit類繼承自Top模式類對象,它定義的前四的屬性是強制的并且organizationalUnit類定義的ou屬性也是必須的。你必須提供ou屬性值和objectClass屬性值,并且目錄服務負責提供其他值。

Now that you know the mandatory attributes and who has to set what, you can make use of the AddRequest constructor that takes the distinguished name of the object you want to create and an array of DirectoryAttribute objects. The array of objects must include values for any mandatory attributes that directory services will not set for you or that are not defined as part of the distinguished name of the new object. Considering the previous organizationalUnit example, the following code snippet shows how you can define the one required directory attribute (objectClass) by creating a DirectoryAttribute object:

現在,你已經了解了強制屬性,你可以使用AddRequest構造函數來設定它。該函數接收你想建立的對象的可辨識名稱和 目錄屬性對象數組。該對象的數組必須包含強制屬性的值,目錄伺服器不會對你或者沒有定義的 新對象的可辨識名稱的一部分的設定。考慮前面示例organizationalUnit,下面代碼片段示範了如何定義一個所需的目錄屬性(對象類)建立一個DirectoryAttribute對象:

DirectoryAttribute objectClass =  new DirectoryAttribute("objectClass", "organizationalUnit");

           

You can then pass that to the AddRequest object, like so:

然後,你可以通過這樣到AddRequest對象,像這樣:

addRequest = new AddRequest(dn, objectClass);

           

You might notice that this doesn't add much to the prior code example ( Error! Reference source not found.). It gets more interesting when you encounter a directory object that contains more mandatory attributes, such as an object derived from the User class schema object, which also requires other mandatory attributes (i.e., sAMAccountName), or you want to add additional optional attributes to an object when it's created. In the following code snippet I define two optional attributes, the city (" l") directory attribute and description directory attribute, and pass those along with the objectClass mandatory directory attribute when I call the AddRequest constructor to create an OU:

你也許會注意到,沒有增加太多的事先的代碼示例(錯誤!未找到引用源。)。它變得更加有趣,當你遇到了一個目錄對象,它包含更多的強制屬性, 例如一個對象來自User  Class 模式對象,這也需要其他的強制性屬性(如,sAMAccountName),或者你想添加額外的可選屬性來建立一個對象的時候。在下面的代碼片段,我定義了兩個可選屬性,城市("l")目錄屬性和描述目錄屬性,并沿用objectClass強制目錄屬性 ,當我調用 AddRequest構造函數建立一個OU:

DirectoryAttribute l = 
    new DirectoryAttribute("l", "Redmond");

DirectoryAttribute description = 
    new DirectoryAttribute("description", "Writers with 3 years of experience");

DirectoryAttribute objectClass =
    new DirectoryAttribute("objectClass", "organizationalUnit");

// create a DirectoryAttribute array and pass in three directory attributes
//建立DirectoryAttribute 數組并且指派這3個目錄屬性
DirectoryAttribute[] dirAttribs = new DirectoryAttribute[3];
dirAttribs[0] = l;
dirAttribs[1] = description;
dirAttribs[2] = objectClass;

// create an addrequest object
//建立一個addrequest對象
addRequest = new AddRequest(dn, dirAttribs);


           

Note that there is not a corresponding code sample with the code download for this variation on creating an AddRequest object. Start with the AddObject method in the code sample and this information to create a method that uses this AddRequest constructor.

請注意,沒有這種變化,建立一個AddRequest對象的代碼下載下傳相應的代碼示例。開始AddObject方法中的代碼示例和資訊,以建立一個方法使用這個AddRequest構造函數。

Adding an Attribute to a Directory Object

将屬性添加到目錄對象

After creating an object in a directory, you might want to add optional attributes to it. For all attributes that an object may contain (optional attributes), you can add them using the ModifyRequest object. 

在目錄中建立一個對象後,你也許想要給它增加一個可選屬性。對于一個對象也許包含所有的屬性(可選屬性),你能将它們添加使用ModifyRequest對象。

To add an attribute to an existing directory object, create a ModifyRequest object and in that object specify the distinguished name of the object you want to modify along with the Add value of theDirectoryAttributeOperation enumeration, the attribute name and value to add.

要添加到現有目錄對象的屬性,建立一個ModifyRequest對象,該對象中指定的可辨識名稱的對象,你想要修改伴随着增加DirectoryAttributeOperation枚舉的值,增加屬性名稱和值

The DirectoryAttributeOperation enumeration contains three values: Add, Delete and Replace. If an attribute already exists in an object, specifying anAdd DirectoryAttributeOperation will throw a DirectoryOperationException error. Therefore, if you want to update an existing attribute, use theReplace DirectoryAttributeOperation value instead.

DirectoryAttributeOperation枚舉包含三個值:增加,删除和替換。如果一個屬性在對象中已經存在,指定一個增加DirectoryAttributeOperation将會抛出一個DirectoryOperationException錯誤。是以,如果你想要更新一個已經存在的屬性,使用Replace DirectoryAttributeOperation 值代替。

The following code sample demonstrates how to add a department attribute and value of Human Resources to a user account object named John Doe in the TechWriters OU of the fabrikam.com domain:

下面的代碼示例示範了如何增加一個部門人力資源的屬性和值的使用者帳戶對象名為John Doe在fabrikam.com域中的TechWriters  OU:

  1. Create an LdapConnection object for connecting to a domain controller in the fabrikam.com domain.

    建立一個連接配接到fabrikam.com域中的域控制器的LdapConnection對象 

  2. Create a ModifyRequest object and pass it the distinguished name stored in the dn variable, the Add value of theDirectoryAttributeOperation enumeration, thelDAPDisplayName of the attribute to add and the value to assign the attribute.

    建立一個ModifyRequest對象,并把它傳遞的可辨識名稱存儲在dn變量中,添加DirectoryAttributeOperation枚舉值,添加lDAPDisplayName的屬性和價值配置設定屬性。

  3. Call the SendRequest method of the connection object and pass it the modRequest object.

    調用連接配接對象的SendRequest方法,并傳遞modRequest對象。

    If the attribute has not been assigned to the user account, the send request will succeed. Otherwise, a DirectoryOperationException will be thrown.

    如果屬性沒有被配置設定過給使用者帳戶,發送請求會成功。否則,将會抛出一個DirectoryOperationException.

  4. If a DirectoryOperationException occurs, it might be because the attribute has already been assigned to the object. Therefore, create a new ModifyRequest object and leave all parameters the same except call the Replace value of theDirectoryAttributeOperation enumeration.

    如果DirectoryOperationException出現,它可能是因為該屬性已經被配置設定給該對象。是以,建立一個新的ModifyRequest對象,并保留所有參數相同,除非調用了替換DirectoryAttributeOperation枚舉值。

    An additional try catch block appears inside the request to modify an existing attribute in case this attempt also throws a DirectoryOperationException error.

    一個額外的try catch塊出現在請求修改存在的屬性,假如這個嘗試也會抛出DirectoryOperationException異常。

  5. If no errors are thrown, report that the operation was successful.

    如果沒有抛出異常,說明操作會成功。

    This result might not be correct, as the code does not consult the server to verify that the LDAP operation was successful or not. The next section explores how to get a response back from a directory server. 

    這個結果可能不正确,因為這個代碼并不會驗證LDAP 操作服務是否成功。下一節将探讨如何從目錄伺服器得到響應。

Example 3. Adding or replacing the department attribute of a user account

示例3. 添加或者替換使用者帳戶的部分屬性

string hostOrDomainName = "fabrikam.com";
string dn = "cn=john doe,ou=techwriters,dc=fabrikam,dc=com";
string attributeName = "department";
string attributeValue = "Accounting";

// establish a connection to the directory
//建立一個連接配接到該目錄
LdapConnection connection = new LdapConnection(hostOrDomainName);

try
{
    ModifyRequest modRequest = new ModifyRequest(
            dn, DirectoryAttributeOperation.Add,
            attributeName, attributeValue);
    
    // example of modifyrequest not using the response object...
    //modifyrequest例子不使用響應對象.... 
    connection.SendRequest(modRequest);
    Console.WriteLine("{0} of {1} added successfully.", 
        attributeName, attributeValue);
}
catch (DirectoryOperationException)
{
    try
    {
        ModifyRequest modRequest = new ModifyRequest(
                dn, DirectoryAttributeOperation.Replace,
                attributeName, attributeValue);

        connection.SendRequest(modRequest);
        Console.WriteLine("The {0} attribute in:\n{1}\nreplaced " +
            "successfully with a value of {2}",
            attributeName, dn, attributeValue);
    }
    catch (DirectoryOperationException e)
    {
        Console.WriteLine("\nUnexpected exception occured:\n\t{0}: {1}",
                          e.GetType().Name, e.Message);
    }

}

catch (Exception e)
{
    Console.WriteLine("\nUnexpected exception occured:\n\t{0}: {1}",
                      e.GetType().Name, e.Message);
}
           

Important Consider using the code example appearing next (Example 4) as a starting point for building robust code for adding or replacing attributes. That example uses the directory response object to determine if the attribute has already been set and to check if the directory operation was successful.

重要 考慮下一個示例(示例4)會使用此代碼作為出發點,為建構健壯的代碼,添加或替換屬性。這個例子使用目錄響應對象,以确定是否這個屬性已經被設定,并且檢查目錄操作是否成功。

Getting Feedback from a Directory Server from an Object Modify Request

從目錄伺服器的一個對象修改請求得到回報

The example appearing in Example 3 does not demonstrate the pairing of the ModifyRequest and ModifyResponse classes or how you can leverage theDirectoryOperationException class to determine more about an error response. While the code catches errors, it doesn't directly display responses from a directory server as a result of modifying an object. The pattern for using a ModifyResponse object to properly cast a returned directory response from a ModifyRequest is identical to the pattern I demonstrated for casting a directory response from an AddRequest into an AddResponse. The code download with this article contains theAddAttribute2 method so that you have a complete example using theModifyRequest andModifyResponse classes. The following code snippet shows how you use the ModifyResponse object in an example similar to Example 3:

例3中出現的例子并不表明ModifyRequest和ModifyResponse是配對的類,或者你可以利用DirectoryOperationException類擷取更多的錯誤的響應。雖然這段代碼捕獲異常,它并不能直接從目錄伺服器得到響應,作為一個修改對象的結果。使用ModifyResponse對象正确轉換一個傳回目錄從ModifyRequest響應中,相同的模型,我示範了對鑄造一個目錄響應從AddRequest 到AddResponse。本文的代碼下載下傳包含方法,以便讓你有一個完整的例子使用ModifyRequest和ModifyResponse類。下面的代碼片段顯示了,你如何使用這個ModifyResponse對象在類似例3的例子中:

// build a modifyrequest object 
//建立一個modifyrequest對象
ModifyRequest  modRequest =
        new ModifyRequest(dn, DirectoryAttributeOperation.Add,
        attributeName, attributeValue);

// cast the returned directory response into a ModifyResponse type named modResponse
//将傳回的目錄響應到一個類名為modifyResponse的ModifyResponse類型中
ModifyResponse modResponse = (ModifyResponse)connection.SendRequest(modRequest);

Console.WriteLine("The {0} attribute in {1} added successfully " +
        "with a value of {2}. The server response was {3}",
        attributeName, dn, attributeValue, modResponse.ResultCode);

           

When an add operation fails, you can determine why by examining the server's directory response more closely. TheSendRequest method throws a DirectoryOperationException if the directory server returns a DirectoryResponse object containing an error. This directory response is packaged in theResponse property of the exception.

當增加操作失敗,你可以通過檢查伺服器的目錄中響應更加緊密來确定為什麼。SendRequest方法抛出了一個DirectoryOperationException,如果目錄伺服器傳回一個包含一個錯誤的DirectoryResponse對象。此目錄響應被包裝在異常的響應屬性。

The ResultCode of the directory response returns a value contained in the ResultCode enumeration. This enumeration is rich with a plethora of error values. For example, an error equivalent to the AttributeOrValueExists value is returned if an attribute is assigned to an object.

目錄伺服器響應傳回的結果代碼值包含在ResultCode 枚舉中,這個枚舉是富含大量的誤內插補點。例如,一個錯誤相當于AttributeOrValueExists值傳回如果屬性被配置設定到一個對象。

The following code example demonstrates how to use the ModifyResponse class to verify a directory object modification and how to use a directory response object containing an error code to handle a DirectoryOperationException. This code sample is similar to Error! Reference source not found., but provides a better starting point for building code that adds or replaces an attribute value:

下面的代碼示例示範如何使用ModifyResponse類來驗證目錄對象修改和如何使用一個目錄響應對象,它包含一個錯誤代碼來處理一個DirectoryOperationException。下面的代碼示例類似錯誤!未找到引用源。但提供一個更好的起點,為建構代碼。添加或者替換屬性值。

  1. Create an LdapConnection object for connecting to a domain controller in the fabrikam.com domain.

    建立一個連接配接到fabrikam.com域中的域控制器的LdapConnection對象 .

  2. Declare the ModifyRequest and ModifyResponse objects and name them modRequest and modResponse respectively.

    聲明ModifyRequest和ModifyResponse對象,并用名字mofRequest和modResponse區分。

    These two objects are declared here because they could be used within two try catch blocks. This is more efficient than the code example appearing inError! Reference source not found. where there is a potential of creating two ModifyRequest objects, one for the attempted add operation and another for the replace operation.

    這兩個對象都在這裡聲明,因為他們可以用在兩個try catch代碼塊。這是更有效的代碼示例中出現的

    錯誤!未找到引用源。那裡是一個潛在的,建立兩個ModifyRequest對象。一個企圖添加操作,另一個用于替換操作。

  3. Initialize modRequest by passing it the distinguished name stored in the dn variable, the Add value of theDirectoryAttributeOperation enumeration, thelDAPDisplayName of the attribute to add and the value to assign the attribute.

    初始化modRequest 通過它的可分辨名稱存儲在dn變量,DirectoryAttributeOperation枚舉增加的值,要添加的屬性和屬性值配置設定的LDAPDisplayName.

  4. Cast the returned directory response object into a ModifyResponse object named modResponse.

    If the attribute has not been assigned to the user account, the send request will succeed. Otherwise, the SendRequest throws a DirectoryOperationException.

    将傳回的目錄響應對象,命名為modResponse到一個ModifyResponse對象。

    如果這個屬性沒有被配置設定到使用者帳戶,發送請求會成功的。否則,SendRequest抛出一個DirectoryOperationException.

  5. Catch the DirectoryOperationException and name the returned object doe.

    抓住DirectoryOperationException,并用doe命名傳回的對象

  6. Check the ResultCode property of the directory response object. If the result code is equivalent to the AttributeOrValueExists value in theResultCode enumeration, then attempt to replace the attribute value.

    The Response property of the DirectoryOperationException object named doe contains the directory response object.

    檢查目錄響應對象的ResultCode屬性。如果結果代碼與ResultCode枚舉的AttributeOrValueExists值相同,然後嘗試替換屬性值。

    doe命名的 DirectoryOperationException對象的Response屬性包含目錄響應對象。

  7. Create a new ModifyRequest object and leave all parameters the same except call the Replace value of theDirectoryAttributeOperation enumeration.

    建立一個新的ModifyRequest對象,并将所有相同的屬性替換為DirectoryAttributeOperation枚舉值。

    An additional try catch block appears inside the request to modify an existing attribute in case other errors are thrown. However, you can more elegantly handle errors using other values of theResultCode enumeration. For example, if the object specified, cn=john doe,ou=techwriters,dc=fabrikam,dc=com in this example does not exist, the directory response will be equivalent to the NoSuchObject value of theResultCode enumeration. 

    另外一個catch塊出現在請求修改一個現有屬性,以防其他也會抛出錯誤。但是,你可以使用ResultCode列舉的其他值更優雅的處理錯誤。例如,如果指定的對象,cn=john doe,ou=techwrites,dc=fabrikam,dc=com 在這個例子中不存在,目錄響應的ResultCode枚舉的NoSuchObject值是相等的。

Example 4. A more robust example demonstrating how to add or replace an attribute of a directory object

示例4。一個更強大的例子示範了如何添加或更換目錄對象的屬性

string hostOrDomainName = "fabrikam.com";
string dn = "cn=john doe,ou=techwriters,dc=fabrikam,dc=com";
string attributeName = "department";
string attributeValue = "Accounting";

// establish a connection to the directory
//建立一個目錄連接配接
LdapConnection connection = new LdapConnection(hostOrDomainName);

// declare the request and response objects here
//此處聲明request和response對象
// they are used in two blocks
//他們使用在兩個塊中
ModifyRequest modRequest;
ModifyResponse modResponse;

try
{
    // initialize the modRequest object 
    //初始化modRequest對象
    modRequest =
        new ModifyRequest(dn, DirectoryAttributeOperation.Add,
        attributeName, attributeValue);

    // cast the returned directory response into a ModifyResponse type 
    // named modResponse    
    //投擲傳回目錄請求到類名為modResponse的ModifyResponse
    modResponse =
        (ModifyResponse)connection.SendRequest(modRequest);

    Console.WriteLine("The {0} attribute of {1} added successfully " +
        "with a value of {2}. The server response was {3}",
        attributeName, dn, attributeValue, modResponse.ResultCode);

}

// if the code enters this catch block, it might be 
// caused by the presence of the specified attribute. 
// The DirectoryAttributeOperation.Add enumeration fails
// if the attribute is already present.

//如果代碼進入這個catch塊,也許是由于指定屬性已經存在。
//如果這個屬性已經存在
//DirectoryAttributeOperation.Add枚舉失敗
catch (DirectoryOperationException doe)
{
    // The resultcode from the error message states that 
    // the attribute already exists

    //resultcode為錯誤消息指出,屬性已經存在
    if (doe.Response.ResultCode == ResultCode.AttributeOrValueExists)
    {
        try
        {
            modRequest = new ModifyRequest(
                                dn,
                                DirectoryAttributeOperation.Replace,
                                attributeName,
                                attributeValue);

            modResponse =
                (ModifyResponse)connection.SendRequest(modRequest);

            Console.WriteLine("The {0} attribute of {1} replaced " +
                "successfully with a value of {2}. The server " +
                "response was {3}",
                attributeName, dn, attributeValue, modResponse.ResultCode);
        }
        // this catch block will handle other errors that you could
        // more elegantly handle with other values in the 
        // ResultCode enumeration.

        //這些catch塊将會處理其他錯誤.
        //你能更優雅的處理ResultCode枚舉中的其他值
        catch (Exception e)
        {
            Console.WriteLine("\nUnexpected exception occured:\n\t{0}: {1}",
              e.GetType().Name, e.Message);
        }
    }

}

catch (Exception e)
{
    Console.WriteLine("\nUnexpected exception occured:\n\t{0}: {1}",
                      e.GetType().Name, e.Message);
}


           

To keep the remaining code examples as simple as possible, I show just a few of the most common interrogations of the ResultCode property in a response object. In production code, you will want to examine many more result codes contained in a DirectoryOperationException. Use the examples I show as a starting point for handling other directory response result codes. Carefully review the ResultCode enumeration for other common directory responses.

為了讓剩餘的代碼例子盡可能簡單。我展示的隻是一些常見的 ResultCode屬性,在一個響應對象。在編寫代碼時,你将會檢查更多的結果代碼包含在一個DirectoryOperationException。使用展示的例子,我作為一個起點處理其他目錄響應結果代碼。請仔細閱讀ResultCode枚舉為其他常見目錄響應。

In addition, the prior code example can be simplified with the PermissiveModifyControl directory control, which is explored in the next section.

此外,現有的代碼示例可以簡化與PermissiveModifyControl 目錄控制,這是在下一節中探讨。

Adding Values to a Multi-Valued Attribute

To Be Continued。。。。

未完待續。。。。

小弟不才,翻譯的不是很好。如果有更好的翻譯,請大蝦們不吝賜教。那我将感激不盡。希望共同進步。

繼續閱讀