조치 확약 후크 예제

확약 후크는 레코드가 데이터베이스에 확약되기 전에 추가 조치를 수행합니다.

다음 예제는 결함에 중복("dups")이 있는지 확인합니다. 원본 결함이 "tested"로 표시되면 후크에서는 중복을 "dupdone"으로 표시함으로써 중복을 다시 평가하여 수정되어야 함을 나타냅니다. 이러한 업데이트 중 하나를 확약하는 데 실패한 경우 이 후크가 속한 것을 포함하여 모든 데이터베이스 트랜잭션이 롤백됩니다.
주: 또한 유효성 검증 또는 알림 후크에서 추가 조치를 수행할 수도 있습니다. ValidateCommit 메소드를 호출할 때는 코드가 예외 및 리턴 메시지 문자열을 검사하는지 확인하십시오. 이 섹션의 예제는 오류 및 예외 핸들의 예를 제공합니다. 자세한 정보는 오류 검사 및 유효성 검증을 참조하십시오. 또한 Entity 오브젝트의 IsEditable 메소드를 사용하여 예외 핸들의 일부로 확약 오퍼레이션을 되돌려야 하는지 판단할 수 있습니다. 모든 유효성 검증 실패를 되돌릴 필요는 없을 수 있습니다. 성공적인 확약 후에는 Revert 메소드를 호출해도 동작하지 않습니다(Entity가 이미 데이터베이스에 확약되었기 때문에 사후 알림 경고를 리턴하는 경우에도).

VBScript

Sub swbug_Commit(actionname, actiontype)

    ' actionname As String
    ' actiontype As Long
    ' action = tested
    Dim dups  ' Array of all direct duplicates of this defect
    Dim dupsvar ' Variant containing link to a duplicate
    Dim dupsobj ' The same link, but as an object rather than a variant
    Dim record  ' The record extracted from the link
    Dim  session
    Dim parent_id ' The display name of this defect
    Dim RetVal

    ' Make an API to call to see if this record has duplicates
    If HasDuplicates() Then
      Set session = GetSession 
      dups = GetDuplicates 
      parent_id = GetDisplayName 

      For Each dupvar In dups
        Set dupobj = dupvar 
        Set entity = dupobj.GetChildEntity 
        session.EditEntity entity, "dupdone" 
        entity.SetFieldValue "action_reason", "Original " & parent_id & " is tested"

       ' validate and commit, with exception and error handling
       On Error Resume Next
       Err.Clear
       'RetVal is empty on success else it holds an error message string on failure
       RetVal = entity.Validate  
       if  Err.Number <> 0  then       
      ' An exception occurred
      ' Err.description holds the error message 
      ' This example prints the error details and reverts the record to
      ' its previous state.
       StdOut "Validation exception:" & vbCrLf &_
        "    Error number: " & Err.Number & vbCrLf &_
        "    Error description: '" & Err.Description & vbCrLf
     entity.Revert 

elseif RetVal <> "" then 
    ' An error message string was returned.indicating that validation failed, 
    ' possibly due to one or more fields having unacceptable values. You can
    ' attempt to resolve this problem by determining which fields
    ' have unacceptable values, give them acceptable values, and retry the
    ' call to entity.Validate. This code example prints the error
    ' details and then reverts the record to its original state.
    StdOut "Validation error: " & RetVal & vbCrLf  
    entity.Revert 

else
    ' Validate was successful. You can proceed and Commit the change.
    StdOut "Validation was successful." & vbCrLf
    Err.Clear
    RetVal = entity.Commit  
    if  Err.Number <> 0  then       
        ' An exception occurred (this indicates that an error occurred before
        ' the values were written to the database). This example code prints the
        ' error details and reverts the record to its previous state.
        StdOut "Commit exception:" & vbCrLf &_
            "    Error number: " & Err.Number & vbCrLf &_
            "    Error description: '" & Err.Description & vbCrLf
        entity.Revert 

    elseif RetVal <> "" then 
        ' An error message string value was returned. This indicates that an 
        ' error occurred after the values were written to the database (for 
        ' example, a failure in an action notification hook). You can handle 
        ' the error by correcting the failure and trying  to commit again or 
        ' revert. This example code prints the error message details.
        StdOut "Commit error (after committing changes): " & RetVal & vbCrLf

    else
        ' No exception or returned error message value
        StdOut "Commit was successful." & vbCrLf
    end if
end if

' Clear the error handler
Err.Clear

      Next
    end if
End Sub

Perl

sub swbug_Commit {

    my($actionname, $actiontype) = @_; 

    # $actionname As string scalar
    # $actiontype as long scalar 
    # action is Submit 
    # This hook is fired during the "commit" step of an
    # entity update. It is the appropriate place to put an
    # activity which should be bundled into the same
    # transaction as the commit, such as subactions
    # or updates of external data storage.

    my ($RetVal);
    my ($dups, # Array of all direct duplicates of this defect
    $record,   # The record extracted from the link
    $parent_id, # The display name of this defect 
    $session, 
    $locEntity,
    $dupobj
    );

    # Make an API to call to see if this record has duplicates
    if ($entity->HasDuplicates()) {
      $session=$entity->GetSession();      $dups = $entity->GetDuplicates();
      $parent_id = $entity->GetDisplayName();
      my $count = $dups->Count();
      my $i = 0;
      for ($i=0;$i<$count;$i++){
        $dupobj = $dups->Item($i);
        $locEntity = $dupobj->GetChildEntity();
        $session->EditEntity($locEntity, "dupdone");
        $locEntity->SetFieldValue("action_reason", "Original " 
              . $parent_id . " is tested");

    # validate and commit, with exception and error handling
      eval {$RetVal = $locEntity->Validate(); };
      if ($@){
           	print "Exception: '$@'\n";
           	$locEntity->Revert();
      }
      elsif ($RetVal ne "") { 
          	 $session->OutputDebugString ("validation error: $RetVal\n"); 
          	          # correct whatever failed validation and then try validate again or revert
          }    
      else {
            eval {$RetVal = $locEntity->Commit(); };         
            if ($@){
                    	print "Exception: '$@'\n";
                    	$locEntity->Revert();
                     }
            elsif ($RetVal ne "") { 
            			$session->OutputDebugString ("commit error: $RetVal\n"); 
            			         # handle error - correct whatever failed and try again or revert  
                }
        # commit successful
            }
    }
   } 
}

피드백