# m_actiondef

description:
Makes a previous duplicated Defect back to it's original state


description:
This action is restricted to Super User profiles.


# m_fielddef

description:
the replica site where this record can be modified


description:
the replica site where this record was last re-keyed


description:
This field is used for importing other data into the default schema.


description:
A unique name used to identify a project. A project might be a product, code shared across products or a component of a product.


description:
An explanation or description of this project.


description:
Path to the Rational Administrator project


description:
Select a project name. A project might be a product, code shared across products or a component of a product.


description:
The name used to identify the e-mail rule.  This name must be unique.


description:
Enter a list of fields upon which ClearQuest should check to determine whether to trigger this e-mail rule.  If any field is changed, this e-mail rule will be triggered.


description:
Enter the fields to display in the e-mail message body.


description:
Select a record to which this rule applies.


description:
Check this box to include all the record's fields in the e-mail message body.


description:
Select a public query to use as an additional e-mail trigger.


description:
Check this box to show the field's previous values.  This is done against the list of fields selected in the Fields to Display control or for all fields, if the Include Entire Defect is checked.


description:
Check this box if you want the modifier of the record to receive an e-mail notification.


description:
Select one or more ClearQuest users as recipient(s) of the e-mail.  These user(s) must have their e-mail address defined in their user information.


description:
Select one or more ClearQuest users as additional recipient(s) of the e-mail.  These user(s) must have their e-mail address defined in their user information.


description:
Select one or more ClearQuest groups as recipient(s) of the e-mail.  The users in these group(s) must have their e-mail address defined in their user information.


description:
Select one or more ClearQuest groups as additional recipient(s) of the e-mail.  The users in these group(s) must have their e-mail address defined in their user information.


description:
You can select recipient(s) based on field values.  These fields must contain a full e-mail address (e.g. name@company.com).


description:
You can select additional recipient(s) based on field values.  These fields must contain a full e-mail address (e.g. name@company.com).


description:
Enter the full e-mail address to send e-mail to a specific address that may not necessarily belong to a ClearQuest user.


description:
Select the fields you wish to appear on the subject line of the e-mail.


description:
Uncheck this box if you would like to disable this e-mail rule.


description:
Select one or more actions upon which ClearQuest should run the e-mail rule.  If one or more of the chosen actions was used to modify the record, then the e-mail rule will trigger.


description:
Select one or more action types upon which ClearQuest should run the e-mail rule.  If one or more of the selected action types was used to modify the record, then the e-mail rule will trigger.


description:
Select one or more states upon which ClearQuest should run the e-mail rule.  If one or more of the selected source states was the original state of the record, then the e-mail rule will trigger.


description:
Select one or more destination states upon which ClearQuest should run the e-mail rule.  If one or more of the selected destination states was the resulting state of the record, then the e-mail rule will trigger.


description:
This specifies whether or not you want to do an AND or an OR operation between Fields to Check for Change and the parameters on the Action Controls tab.


description:
Name of the CleaQuest Database in which you want to be able to create associations to requirements.


description:
Full name of the CleaQuest Database file (including the path) in which you want to be able to create associations.


description:
ClearQuest Record Type Name you want to be able to create associations with.


description:
ClearQuest EntityDef field name that stores the references to associated requirements. This field must be of type Reference_List and reference the'Requirement' EntityDef.


description:
Back reference field name defined for CQReqListAttName. This field will automatically store the references of ClearQuest record associated with a requirement.


description:
ClearQuest EntityDef field name that stores the Repository Project that contains the requirements you want to associate with the current ClearQuest record. This field must be of type Reference and reference the 'repoproject' EntityDef.


description:
Name of an action of type MODIFY that operates on the CQEntityDefName.


description:
Title of the association dialog box that appears when the integration is called from RequisitePro. This title can mention for example the EntityDef name of the ClearQuest records expected to be associated with the selected requirement(s).


description:
Name of the ReqiusitePro project in which you want to be able to create associations to ClearQuest records.


description:
Full name of the RequisitePro project file (including the path) in which you want to be able to create associations.


description:
Full name (including the path) of the Help file used by both association dialog boxes (either called from RequisitePro or ClearQuest) in which you want to be able to create associations.


description:
Context ID in the help file that is called when pressing the help button from  the association dialog box that appears when the integration is called from ClearQuest.


description:
Context ID in the help file that is called when pressing the help button from  the association dialog box that appears when the integration is called from RequisitePro.


description:
GUID of the Requirement Type you want to associate requirements to CQEntityDefName.


description:
GUID of the Attribute Field Type in which the list of associated ClearQuest record IDs is stored.


description:
Type or select the build in which the defect was found. 
If you create a defect from Rational LogViewer, this is automatically entered. 
To display general information, specifications, and statistics about a build, click Properties.


description:
Type or select the name of the log containing the results of the Robot script in which a defect was found. If you create a defect from Rational LogViewer, this is automatically entered.
To display the properties of this log, click Properties.


description:
Type or select the name of the script containing the defect. If you create a defect from Rational LogViewer, this is automatically entered.
To open the script in Robot, click Open. 
To display the properties of this script, click Properties.


description:
Displays the name of a verification point. If you create a defect from Rational LogViewer, this is automatically entered. 
To open the appropriate Comparator, click Open. 
To display the properties of this verification point, click Properties.


description:
Type the name of the company that reported the defect.


description:
Type or select the hardware platform that was in use when the defect was found.


description:
Type the name of the computer in which the defect was found. If you create a defect from Rational LogViewer, LogViewer fills in the Computer box with information from the Rational Administrator.


description:
Type or select the operating system software that was in use when the defect was found.


description:
Type or select the build in which a defect was fixed. 
To display general information, specifications, and statistics about a build, click Properties.


description:
Type the name of the person that reported the defect. If you create a defect from LogViewer, LogViewer fills in the Contact box with the name of the user logged into the repository.


description:
Type or select the log folder containing the defect. If you create a defect from Rational LogViewer, LogViewer fills in the Log Folder box with information from Robot.


description:
Type additional information about a defect, such as the cause of a defect, or how it was fixed.


description:
Specify any other information that may be relevant to the software testing environment. You can enter a short statement or enter the name of a text file that contains detailed information in the Attachments tab. You can enter up to 40 characters.


description:
Click to select a custom field to describe a defect. You can assign additional information about a defect using your own terminology by customizing the label for this field.


description:
Type text to describe a defect. You can assign additional information about a defect using your own terminology by customizing the label for this field.


description:
To associate a requirement with this defect:
1.  Click the Select button to display the requirements hierarchy. 
2.  Select the type of requirement you want.
3.  Click the particular requirement you want to associate with this defect and click OK.


description:
Select the associated Test Case with this record


description:
This field is a string representing a hash of the call stack.


description:
This field is used to contain the call stack.


description:
This field contains the name of the tool in which this defect was found.  You may select one of the Rational product names or enter the name of the tool used.


description:
This field contains the name of the program under test.


description:
This field contains the name of the tool against which this defect can be verified.  You may select one of the Rational product names or enter the name of the tool used.


description:
This field contains the command line necessary to reproduce this defect.


description:
When this check box is enabled,  the  UCM_ChkBeforeDeliver global script will be run before any activity in this project is delivered. The script determines if the current user has permission to do the deliver.


description:
When this check box is enabled, the  UCM_ChkBeforeWorkOn global script will be run before a WorkOn action is done for any activity in this UCM_Project. The script determines if the current user has permission to work on the activity.


description:
When this check box is enabled,  the  UCM_CQActAfterDeliver global script will be run after any activity in this project is delivered. The script can execute a corresponding ClearQuest action.


description:
When this check box is enabled, mastership of ClearQuest activity records is checked before UCM delivery. If target stream is remote, the record is remastered to the remote site.


description:
The person responsible for carrying out the activity.


description:
This is a display-only field which shows the ClearCase stream where this entity has been worked on (if it has been worked on already).


description:
This is a display-only field which shows the ClearCase view where this entity is being worked on (if there is one).


description:
This should be set to the UCM_Project entity which corresponds to the ClearCase project where this entity will be worked on.


# m_property

name:
Applied Package Form Tab Names_Project_1


name:
Applied Package Form Tab Names_Customer_4


name:
Applied Package Form Tab Names_Resolution_4


name:
Applied Package Form Tab Names_Attachments_2


name:
Applied Package Form Tab Names_History_2


name:
Applied Package Form Tab Names_Repository_5


name:
Applied Package Form Tab Names_TeamTest_5


name:
Applied Package Form Tab Names_EnhancementRequest_4


name:
Applied Package Form Tab Names_RequisitePro_15


name:
Applied Package Form Tab Names_UnifiedChangeManagement_9

data:
SUBMITTABNAMES=Unified Change Management;RECORDTABNAMES=Unified Change Management


name:
Applied Package Form Tab Names_AMStateTypes_1


name:
Applied Package Form Tab Names_JazzInterop_7


# m_scriptdef

program:
REM Nobody has permission to submit this kind of entitydef
   REM Only system internals can do this
   users_AccessControl = FALSE


program:
# Nobody has permission to submit this kind of entitydef
    # Only system internals can do this
    return 0;


program:
REM Nobody has permission to submit this kind of entitydef
   REM Only system internals can do this
   groups_AccessControl = FALSE


program:
REM Nobody has permission to submit this kind of entitydef
   REM Only system internals can do this
   attachments_AccessControl = FALSE


program:
REM Nobody has permission to submit this kind of entitydef
   REM Only system internals can do this
   ratl_replicas_AccessControl = FALSE


program:
REM Nobody has permission to submit this kind of entitydef
   REM Only system internals can do this
   history_AccessControl = FALSE


program:
# Nobody has permission to submit this kind of entitydef
   # Only system internals can do this
   return 0;


program:
1-Resolve Immediately
2-Give High Attention
3-Normal Queue
4-Low Priority


program:
1-Critical
2-Major
3-Average
4-Minor
5-Enhancement


program:
'  DO_NOT_REMOVE SCRIPT_SETTING EXECUTION_MODE=2
REM  *** Do not modify the predefined prologue above this line ***

REM  ***TO DO: Add your code here ***

    DIM session
    DIM username
    
    set session = GetSession
    username = session.GetUserLoginName
    SetFieldValue fieldname, username

REM  *** Do not modify the predefined epilogue below this line ***


program:
#  DO_NOT_REMOVE SCRIPT_SETTING EXECUTION_MODE=2


    my $session;
    my $username;
    
    $session = $entity->GetSession();
    $username = $session->GetUserLoginName();
    $entity->SetFieldValue($fieldname, $username);


program:
'  DO_NOT_REMOVE SCRIPT_SETTING EXECUTION_MODE=2
REM  *** Do not modify the predefined prologue above this line ***

REM  ***TO DO: Add your code here ***

    SetFieldValue fieldname, Date

REM  *** Do not modify the predefined epilogue below this line ***


program:
#  DO_NOT_REMOVE SCRIPT_SETTING EXECUTION_MODE=2

    $entity->SetFieldValue($fieldname, GetCurrentDate());


program:
Keywords 1
Keywords 2
Keywords 3
Keywords 4
Keywords 5


program:
Cosmetic Flaw
Data Corruption
Data Loss
Documentation Issue
Incorrect Operation
Installation Problem
Missing Feature
Slow Performance
System Crash
Unexpected Behavior
Unfriendly Behavior


program:
# TODO -- put your perl script code here
sub GetCurrentDate {
    my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $time) = localtime();
    return sprintf("%4d-%2.2d-%2.2d %2.2d:%2.2d:%2.2d", $year + 1900, $mon + 1, $mday,  $hour, $min, $sec);
}


program:
# do any setup for the action here
	$session = $entity->GetSession();

	$session->OutputDebugString ("Email_Maintenance: Initialization\n");
	$fldObj = $entity->GetFieldValue ("Operator_Value");
	if ($fldObj->GetValueStatus == $CQPerlExt::CQ_HAS_VALUE) {
		$fldValue = $fldObj->GetValue();
		$session->OutputDebugString ("Operator has value; it's $fldValue\n");
	} else {
		$session->OutputDebugString ("Operator does NOT have a value, setting it to 0");
		$entity->SetFieldValue ("Operator_Value", "0");
	}


program:
function RSEM_CheckAccess (UserName)

	 dim Sess
	 dim ResultSet
	 dim CurrUser

	 On Error Resume Next

	 set Sess = GetSession

	 'Get current user logged in
	 'CurrUser = Sess.GetUserLoginName	 'OR
	 CurrUser = UserName

	 'Get a list of Super Users and Schema Designers
	 set ResultSet = Sess.BuildSQLQuery("select login_name from users where is_superuser = 1 or is_appbuilder = 1")
	 ResultSet.Execute

	 'Check to see if current user is a super user or a schema designer
	 while (ResultSet.MoveNext = AD_SUCCESS)
		 if (ResultSet.GetColumnValue(1) = CurrUser) then
			 RSEM_CheckAccess = TRUE
			 exit function
		 end if
	 wend

	 RSEM_CheckAccess = FALSE
end function

sub RSEM_FieldsChoices (Choices)
	'Choices as ChoiceList
	Dim Sess
	Dim EntDef
	Dim fields
	Dim entDefName

	On Error Resume Next

	set Sess = GetSession
	entDefName = GetFieldValue("Entity_Def").GetValue
	if entDefName = "" then exit sub
	set EntDef = Sess.GetEntityDef(entDefName)
	fields = EntDef.GetFieldDefNames

	for idx = LBound(fields) to Ubound(fields)
		'put logic here to restrict fields based on
		'	system fields (or some of)
		'	non-addr fields (for some fields)
		Choices.AddItem fields(idx)
	next

	Choices.Sort

end sub

sub RSEM_ActionsChoices (Choices)
	'Choices as ChoiceList
	Dim Sess
	Dim EntDef
	Dim actions
	Dim ActionType
	Dim entDefName

	On Error Resume Next

	set Sess = GetSession
	entDefName = GetFieldValue("Entity_Def").GetValue
	if entDefName = "" then exit sub
	set EntDef = Sess.GetEntityDef(entDefName)
	actions = EntDef.GetActionDefNames

	for idx = LBound(actions) to Ubound(actions)
		ActionType = EntDef.GetActionDefType (actions(idx))
		if ActionType <> AD_BASE And ActionType <> AD_RECORD_SCRIPT_ALIAS And ActionType <> AD_CQCOPY Then
			Choices.AddItem actions(idx)
		end if
	next

	Choices.Sort

end sub

sub RSEM_ActionTypesChoices (Choices)
	'Choices as ChoiceList
	Dim Sess						'session object
	Dim EntDef					'entity def object
	Dim Actions					'list of actions defined in entity
	Dim ActionType		  'action type for an action
	Dim ActionTypesList()	'temp list of action types added to choice list
	Dim cnt						'index for ActionTypesList array
	Dim ActionTypeAdded		'flag to indicate whether the action type was added to choice list
	Dim entDefName
	On Error Resume Next

	'Get Action names defined for the entity
	set Sess = GetSession
	entDefName = GetFieldValue("Entity_Def").GetValue
	if entDefName = "" then exit sub
	set EntDef = Sess.GetEntityDef(entDefName)
	Actions = EntDef.GetActionDefNames

	cnt = 0

	'Cycle through the list of available actions to determine the action types.
	for idx = LBound(Actions) to Ubound(Actions)

		ActionType = EntDef.GetActionDefType (Actions(idx))
		ActionTypeAdded = 0
		i = 0

		'check to see if action type has already been added to the choice list to avoid dups.
		if cnt <> 0 then
			for i = LBound(ActionTypesList) to UBound(ActionTypesList)
				if ActionType = ActionTypesList(i)then
					'this action type has been added to the list
					ActionTypeAdded = 1
					Exit For
				end if
			next
		end if

		'If not already added, then add to choice list.
		if ActionTypeAdded = 0 then
			if ActionType <> AD_BASE And ActionType <> AD_RECORD_SCRIPT_ALIAS And ActionType <> AD_CQCOPY Then
					Choices.AddItem RSEM_GetActionTypeName(EntDef, ActionType)
					Redim Preserve  ActionTypesList(cnt+1)
					ActionTypesList(cnt) = ActionType
					cnt = cnt + 1
			end if
		end if
	next

	Choices.Sort

end sub


function RSEM_GetActionTypeName(EntDef, ActionTypeEnum)
	Dim actionTypeName
	actionTypeName = ""
	On Error Resume Next

	' Use EntDef.GetActionTypeName(ActionTypeEnum) if it exists (was added in 7.0.1)
	actionTypeName = EntDef.GetActionTypeName(ActionTypeEnum)

	' If actionTypeName is undefined, fall back to old method
	if actionTypeName = "" then
		actionTypeName = RSEM_GetActionTypeString(ActionTypeEnum)
	end if

	RSEM_GetActionTypeName = actionTypeName
end function



function RSEM_GetActionTypeString (ActionTypeEnum)
	' Note: This function is effectively obsolete; see RSEM_GetActionTypeName

	'These strings match what's in the dll.
	select case ActionTypeEnum
		case AD_SUBMIT
			RSEM_GetActionTypeString = "SUBMIT"
		case AD_MODIFY
			RSEM_GetActionTypeString = "MODIFY"
		case AD_CHANGE_STATE
			RSEM_GetActionTypeString = "CHANGE_STATE"
		case AD_DUPLICATE
			RSEM_GetActionTypeString = "DUPLICATE"
		case AD_UNDUPLICATE
			RSEM_GetActionTypeString = "UNDUPLICATE"
		case AD_IMPORT
			RSEM_GetActionTypeString = "IMPORT"
		case AD_DELETE
			RSEM_GetActionTypeString = "DELETE"
		case AD_BASE
			RSEM_GetActionTypeString = "BASE"
		case AD_RECORD_SCRIPT_ALIAS
			RSEM_GetActionTypeString = "RECORD_SCRIPT_ALIAS"
		case else
			RSEM_GetActionTypeString = ""
	end select

end function

sub RSEM_StatesChoices (Choices)
	'Choices as ChoiceList
	Dim Sess
	Dim EntDef
	Dim states
	Dim entDefName

	On Error Resume Next

	set Sess = GetSession
	entDefName = GetFieldValue("Entity_Def").GetValue
	if entDefName = "" then exit sub
	set EntDef = Sess.GetEntityDef(entDefName)
	if EntDef.GetType() <> AD_AUX_ENTITY then
		states = EntDef.GetStateDefNames
	end if
	for idx = LBound(states) to Ubound(states)
		Choices.AddItem states(idx)
	next

	Choices.Sort

end sub

Function RSEM_GetEmailObject
	dim em
	dim sess
	dim key

	On Error Resume Next

	key = "_RSEM_EmailObject"
	disableCacheKey = "_RSEM_No_EmailRules_Cache"

	set sess = GetSession

	if sess.HasValue (key) then
		set em = sess.NameValue(key)
		em.SetSession sess
	else
		set em = CreateObject("ClearQuest_Email.Email_Rules")

		if not IsObject(em) or em Is Nothing then
			sess.OutputDebugString "!!! RSEM_GetEmailObject: Object 'em' is invalid" & vbcrlf
			exit function
		end if

		em.SetSession sess
		if not sess.HasValue (disableCacheKey) then
						set sess.NameValue(key) = em
		end if
	end if

	set RSEM_GetEmailObject = em

end function

sub RSEM_ProcessEmailRules (ent)
	'ent and Entity
	Dim em
	Dim sess


	'stop
	set em = RSEM_GetEmailObject
	set sess= GetSession

	If not IsObject(em) or em Is Nothing then
		sess.OutputDebugString "!!! RSEM_ProcessemailRules: Object 'em' is invalid" & vbcrlf
		exit sub
	end if

	em.ProcessEmailRules (ent)
	em.ClearSession

end sub

sub RSEM_ResetCache
	dim em
	dim sess

	On Error Resume Next

	'stop
	set em = RSEM_GetEmailObject
	set sess= GetSession

	If not IsObject(em) or em Is Nothing then
		sess.OutputDebugString "!!! RSEM_ResetCache: Object 'em' is invalid" & vbcrlf
		exit sub
	end if

	em.ResetCache
	em.ClearSession

end sub


program:
sub RSEM_CheckAccess
{
	my ($currUser) = @_;
	my $session = $entity->GetSession();

	# Get current user logged in
	# $currUser = $session->GetUserLoginName();

	# Get a list of Super Users and Schema Designers
	my $resultSet = $session->BuildSQLQuery("select login_name from users where is_superuser = 1 or is_appbuilder = 1");
	$resultSet->Execute();

	# Check to see if current user is a super user or a schema designer
	while ($resultSet->MoveNext() == $CQPerlExt::CQ_SUCCESS) {
		if ($resultSet->GetColumnValue(1) eq $currUser) {
			return 1;
		}
	}

	return 0;
}

sub RSEM_FieldsChoices {
	my @choices;

	my $session = $entity->GetSession();
	my $entDefName = $entity->GetFieldValue("entity_def")->GetValue();
	if ($entDefName eq ""){
		return @choices;
	}
	my $entDef = $session->GetEntityDef($entDefName);
	my $fields = $entDef->GetFieldDefNames();
	if ($fields){
		@choices = @$fields;
		@choices = sort(@choices);
	}
	return @choices;
}

sub RSEM_ProcessEmailRules
{
	my ($myEntity) = @_;
	my $session = $entity->GetSession();
	my $eMail = CQEmailRules::Build();

	if (!defined($eMail) || ref($eMail) ne 'CQEmailRules') {
		$session->OutputDebugString("!!! RSEM_ProcessEmailRules: Object eMail is invalid\n");
		return (-1);
	}

	$eMail->SetSession($session);
	$eMail->ProcessEmailRules($myEntity);
	# $email->ClearSession();
}

sub RSEM_ActionsChoices {
	my @choices;

	my $session = $entity->GetSession();
	my $entDefName = $entity->GetFieldValue("entity_def")->GetValue();
	if ($entDefName eq ""){
		# @choices is null
		return @choices;
	}
	my $entDef = $session->GetEntityDef($entDefName);
	my $actionNames = $entDef->GetActionDefNames();

	foreach my $actionName (@$actionNames) {
		my $actionType = $entDef->GetActionDefType($actionName);
		if ($actionType != $CQPerlExt::CQ_BASE &&
			$actionType != $CQPerlExt::CQ_RECORD_SCRIPT_ALIAS &&
			$actionType != $CQPerlExt::CQ_CQCOPY) {
			push(@choices, $actionName);
		}
	}
	@choices = sort(@choices);
	return @choices;
}

sub RSEM_ActionTypesChoices {
	my @choices;

	my $session = $entity->GetSession();
	my $entDefName = $entity->GetFieldValue("entity_def")->GetValue();
	if ($entDefName eq ""){
		# @choices is null
		return @choices;
	}
	my $entDef = $session->GetEntityDef($entDefName);
	my $actionNames = $entDef->GetActionDefNames();

	foreach my $actionName (@$actionNames) {
		my $actionType = $entDef->GetActionDefType($actionName);
		if ($actionType != $CQPerlExt::CQ_BASE &&
			$actionType != $CQPerlExt::CQ_RECORD_SCRIPT_ALIAS &&
			$actionType != $CQPerlExt::CQ_CQCOPY) {
			my $locActionTypeName = RSEM_GetActionTypeName($entDef, $actionType);
			if (!RSEM_InArray($locActionTypeName, @choices)) {
				push(@choices, $locActionTypeName);
			}
		}
	}
	@choices = sort(@choices);
	return @choices;
}

sub RSEM_InArray {
	my ($item, @array) = @_;

	foreach my $locItem (@array) {
		if ($locItem eq $item) {
			return 1;
		}
	}
	return 0;
}

sub RSEM_GetActionTypeName {
	my ($entDef, $actionType) = @_;

	my $locActionTypeName = "";
	eval {
		# Use $entDef->GetActionTypeName, if it exists (it's defined in 7.0.1)
		$locActionTypeName = $entDef->GetActionTypeName($actionType);
	};

	if ($locActionTypeName ne "") {
		return $locActionTypeName;
	}

	# If we get here, it means $entDef->GetActionTypeName is not defined.
	# Fall back to using a hard-coded list of names, as we did prior to 7.0.1
	my @actionTypeNames = ("SUBMIT", "MODIFY", "CHANGE_STATE", "DUPLICATE",
		"UNDUPLICATE", "IMPORT", "DELETE", "BASE", "RECORD_SCRIPT_ALIAS");

	$locActionTypeName = $actionTypeNames[$actionType - 1];
	return $locActionTypeName;
}

sub RSEM_StatesChoices {
	my @choices;

	my $states;

	my $session = $entity->GetSession();
	my $entDefName = $entity->GetFieldValue("entity_def")->GetValue();
	if ($entDefName eq ""){
		# @choices is null
		return @choices;
	}
	my $entDef = $session->GetEntityDef($entDefName);
	if ($entDef->GetType() != $CQPerlExt::CQ_AUX_ENTITY){
		$states = $entDef->GetStateDefNames();
	}
	# could be a stateless entity
	if ($states){
		@choices = @$states;
		@choices = sort(@choices);
	}
	return @choices;
}

sub RSEM_ResetCache
{
	# no op for now
}


program:
sub NoteEntryInit { 
    my ($fieldName) = @_;
    # Clear out the notes entry field
    $entity->SetFieldValue($fieldName, "");
}

sub SetLog  {

    # noteEntryField As String
    # notesLogField As String
    my ($noteEntryField, $notesLogField) = @_;

    my $primaryActionType = $entity->GetActionType();
    if ($primaryActionType eq $CQPerlExt::CQ_IMPORT) {
        # We don't modify the existing log record during an Import
        return;
    }

    my $oldNotes = $entity->GetFieldOriginalValue($notesLogField)->GetValue();
    my $thisNoteInfo = $entity->GetFieldValue($noteEntryField);

	#  hash of months and their corresponding strings in English
	%month_string = (
		"1" => "January",
		"2" => "February",
		"3" => "March",
		"4" => "April",
		"5" => "May",
		"6" => "June",
		"7" => "July",
		"8" => "August",
		"9" => "September",
		"10" => "October",
		"11" => "November",
		"12" => "December",
	);

    if ($thisNoteInfo->GetValueStatus() eq $CQPerlExt::CQ_HAS_VALUE) {
        my $thisNote = $thisNoteInfo->GetValue();
        my $session = $entity->GetSession();
        my $crLf = "\x0d\x0a";

        my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $time) = localtime();
        my $now = sprintf("%2.2d %s %4d %2.2d:%2.2d:%2.2d", $mday, $month_string{$mon + 1} ,$year + 1900, $hour, $min, $sec);

        my $myName = $session->GetUserLoginName();

        # Get the state, if it exists.  (The record type may be stateless; we use an eval
        # block to catch any error that's thrown in that case.)
        my $stateBanner = "";
        eval {
            # If there's no state, then just ignore the resulting error.
            $stateBanner = "State: " . $entity->GetFieldValue("State")->GetValue();
        };
        my $banner = $crLf . "==== " . $stateBanner . " by: " . $myName . " on " . $now . " ====" . $crLf;
        my $newNotes = $banner . $crLf . $thisNote . $crLf . $oldNotes;
        $entity->SetFieldValue($notesLogField, $newNotes);
    } else {
        # Value changed back to empty string; undo any change we have made to the notes log.
        $entity->SetFieldValue($notesLogField, $oldNotes);
    }
}


program:
REM return one of AD_MANDATORY, AD_OPTIONAL, AD_READONLY.  Example:
    REM   If username = "pat" Then
    REM      raprojectname_Permission = AD_READONLY
    REM   Else
    REM      raprojectname_Permission = AD_OPTIONAL
    REM   End If
	
	dim ac_sIntegrationVar
	dim oSession
	dim a_sVal

	ac_sIntegrationVar = "CQI_Integration"

	raprojectname_Permission = AD_READONLY

	set oSession = GetSession
	If oSession.HasValue(ac_sIntegrationVar) Then
		a_sVal = oSession.NameValue(ac_sIntegrationVar)
		if a_sVal = "Running" then
			raprojectname_Permission = AD_OPTIONAL
		end if	
	end if
	
	set oSession = nothing


program:
REM return one of AD_MANDATORY, AD_OPTIONAL, AD_READONLY.  Example:
    REM   If username = "pat" Then
    REM      revision_date_1_Permission = AD_READONLY
    REM   Else
    REM      revision_date_1_Permission = AD_OPTIONAL
    REM   End If
	
	dim ac_sIntegrationVar
	dim oSession
	dim a_sVal

	ac_sIntegrationVar = "CQI_Integration"

	revision_date_Permission = AD_READONLY

	set oSession = GetSession
	If oSession.HasValue(ac_sIntegrationVar) Then
		a_sVal = oSession.NameValue(ac_sIntegrationVar)
		if a_sVal = "Running" then
			revision_date_Permission = AD_OPTIONAL
		end if	
	end if
	
	set oSession = nothing


program:
REM return TRUE if the user has permission to perform this action

	Dim a_bIsRunningIntegration

	Requirement_AccessControl = FALSE

	a_bIsRunningIntegration = CQI_IsRunningIntegration()
	if a_bIsRunningIntegration then
		Requirement_AccessControl = TRUE
	end if


program:
REM return TRUE if the user has permission to perform this action

    Dim a_bIsRunningIntegration

	Requirement_AccessControl = FALSE

	a_bIsRunningIntegration = CQI_IsRunningIntegration()
	if a_bIsRunningIntegration then
		Requirement_AccessControl = TRUE
	end if


program:
REM return TRUE if the user has permission to perform this action

	Dim a_bIsRPAssociateDlg

	Requirement_AccessControl = TRUE

	a_bIsRPAssociateDlg = CQI_CheckAssociateDlg()
	if a_bIsRPAssociateDlg Then
		Requirement_AccessControl = FALSE
	end if


program:
REM return TRUE if the user has permission to perform this action. Example:
    REM   If username = "pat" Then
    REM      Requirement_AccessControl = TRUE
    REM   Else
    REM      Requirement_AccessControl = FALSE
    REM   End If
	Dim a_bIsRunningIntegration
	Dim a_bIsRPAssociateDlg

	a_bIsRunningIntegration = CQI_IsRunningIntegration()
	if a_bIsRunningIntegration then
		Requirement_AccessControl = FALSE
    else
	    Requirement_AccessControl = TRUE

		a_bIsRPAssociateDlg = CQI_CheckAssociateDlg()
		if a_bIsRPAssociateDlg Then
			Requirement_AccessControl = FALSE
		end if
	end if


program:
REM do any setup for the action here

	Dim a_bIsRunningIntegration			'Contains a boolean indicating if the integration is already in progress, to prevent reccurence
	Dim a_oCQSession							'Current CQ session
	Dim a_bEmpty								'Boolean indicationg wether or not a Req Proxy is selected in the CQ List Box
	Dim a_oReqProTool							'Reference to a ASCQIIntegration.RefreshTool instance
	Dim a_sError								'Error message sent back by integration in case of a failure 	dim bWeb

	Dim ac_sRequirement_GUID					' Requirement GUID field name

	ac_sRequirement_GUID = "Req_GUID"

	bWeb = Check_Web()
	
	' Check for valid RA Project and Mastership of RP project at current site
	if not CQI_CheckRPProjectMaster(GetFieldValue("RAProjectName").GetValue(), a_sError) then
		if bWeb then
			Err.Raise 1, "Rational RequisitePro/ClearQuest Integration", a_sError
		else
 			msgbox a_sError, vbOKOnly + vbCritical, "Rational RequisitePro/ClearQuest Integration"
		end if
 		exit sub
 	end if

	if len(GetFieldValue(ac_sRequirement_GUID).GetValue) <> 0 then 
		a_bIsRunningIntegration = CQI_IsRunningIntegration()
		if not a_bIsRunningIntegration then
		 	Set a_oCQSession = GetSession
			if not a_oCQSession is nothing then
				Dim sRAProjectName
				Dim sRPProjectPath
				Dim sUserName 
				Dim sPassWord
				Dim sRequirementGUID
				Dim bRet

				sRAProjectName = me.GetFieldValue("RAProjectName").GetValue
				sRPProjectPath = CQI_GetRPProjectFromRA(sRAProjectName)

				sRequirementGUID = GetFieldValue(ac_sRequirement_GUID).GetValue
				set a_oReqProTool = CQI_GetNewReqProTool()

				if a_oReqProTool is nothing then
 					if bWeb then
 						Err.Raise 1, "Rational RequisitePro/ClearQuest Integration", "ClearQuest could not connect to the Integration Server." + vbcrlf + "Please contact your Administrator."
 						exit sub
 					end if
					msgbox "ClearQuest could not connect to the Integration Server." + vbcrlf + "Please contact your Administrator.", vbOKOnly + vbCritical, "Rational RequisitePro/ClearQuest Integration"
				else
					' Get RP username password
					dim bGotLogonInfo

					bGotLogonInfo = CQI_RPlogon(sRPProjectPath, sUserName, sPassword)
					if bGotLogonInfo then					
						bRet = a_oReqProTool.RefreshRequirementFromCQ(me, sRPProjectPath, sUserName, sPassWord, sRequirementGUID, a_sError)
					end if
				end if

			end if	'a_oCQSession
		end if ' a_bIsRunningIntegration
	end if	' Req_GUID Not empty
	
	if not a_oReqProTool is nothing then
		if not a_oReqProTool.Unload(a_sError) then
			Msgbox a_sError, vbOKOnly + vbCritical, "Rational RequisitePro/ClearQuest Integration"
		end if
		set a_oReqProTool = nothing
	end if
	set a_oCQSession = nothing


program:
REM add your hook code here

REM Launch RequisitePro Properties dialog box for the selected Requirement in the CQ list box, and pass its DBID 
REM if return of call is ePrp_OK
REM	Nothing is done
REM if return of call is ePrp_Removed
REM	then the requirement is removed fromlist of requirement associated with current CQ record

	On Error resume next	'handle ListSelection empty
	err.clear

	Dim ePrp_Empty
	Dim ePrp_OK
	Dim ePrp_Error
	Dim ePrp_Removed
	Dim a_bWeb									'Web or not
	Dim a_bIsRunningIntegration			'Contains a boolean indicating if the integration is already in progress, to prevent reccurence
	Dim a_oCQSession							'Current CQ session
	Dim a_sDBID									'DBID of the Req Proxy selected in the CQ List Box
	Dim a_bEmpty								'Boolean indicationg wether or not a Req Proxy is selected in the CQ List Box
	Dim a_oRequisiteProTool					'Reference to a ASCQIIntegration.RequisiteProTool instance
	Dim a_eRet									'Contains value returned by the call to integration
	Dim a_sError								'Error message sent back by integration in case of a failure
	Dim a_sFail									'Return value of the deletion of the association in ClearQuest between current CQ record and the Req Proxy

	Dim ac_sRequirement_GUID					' Requirement GUID field name

	ac_sRequirement_GUID = "Req_GUID"
	ePrp_Empty = 0
	ePrp_OK = 1
	ePrp_Error = 2
	ePrp_Removed = 3

	a_bWeb = Check_Web()
   'This script must not be launched through the web	
	'We also test if the record is editable

	If (NOT a_bWeb) Then
 		' Checks for valid RA Project and Mastership of RP project at current site
 		if not CQI_CheckRPProjectMaster(GetFieldValue("RAProjectName").GetValue(), a_sError) then
 			msgbox a_sError, vbOKOnly + vbCritical, "Rational RequisitePro/ClearQuest Integration"
 			exit function
 		end if

		if len(GetFieldValue(ac_sRequirement_GUID).GetValue) <> 0 then 
			a_bIsRunningIntegration = CQI_IsRunningIntegration()
			if not a_bIsRunningIntegration then
			 	Set a_oCQSession = GetSession
				if not a_oCQSession is nothing then 					
					dim sRAProjectName
					dim sRPProjectPath
					dim sUserName 
					dim sPassWord
	                dim sRequirementGUID
					dim sDBID

					sRAProjectName = me.GetFieldValue("RAProjectName").GetValue
			
					sRPProjectPath = CQI_GetRPProjectFromRA(sRAProjectName)

					sRequirementGUID = me.GetFieldValue(ac_sRequirement_GUID).GetValue
					sDBID = me.GetFieldValue("dbid").GetValue

					set a_oRequisiteProTool = CQI_GetNewReqProTool()
					a_oCQSession.OutputDebugString "Got the ReqProTool" 

					if a_oRequisiteProTool is nothing then
						msgbox "ClearQuest could not connect to the Integration Server." + vbcrlf + "Please contact your Administrator.", vbOKOnly + vbCritical, "Rational RequisitePro/ClearQuest Integration"
					else
						' Get RP username password
						dim bGotLogonInfo

						bGotLogonInfo = CQI_RPlogon(sRPProjectPath, sUserName, sPassword)
						if bGotLogonInfo then
							a_eRet = a_oRequisiteProTool.GetProperties2( sRPProjectPath, _
																		 sUserName, _
																		 sPassWord, _
																		 sRequirementGUID, _
																		 sDBID, _
																		 a_sError)
							a_oCQSession.OutputDebugString "executing switch statement" 
							select case a_eRet
								case ePrp_OK
									'Nothing to do
								case ePrp_Removed
									if me.IsEditable() then
										' View button is clicked from the Requirement record form.
										MsgBox "The requirement has been deleted in Rational RequisitePro.", _
														vbOKOnly + vbInformation, _
														"Rational RequisitePro/ClearQuest Integration"
									else
										' This hook is fired from a placeholder record.
										Requirement_CQI_Properties_Req = "DELETED"
									end if
									' MsgBox "This requirement doesn't exist anymore. The association is going to be removed.", vbOKOnly + vbInformation, "Rational RequisitePro/ClearQuest Integration"
									' a_sFail = me.DeleteFieldValue(ac_sRequirement_GUID, sRequirementGUID)

								case else
									msgbox a_sError, vbOKOnly + vbCritical, "Rational RequisitePro/ClearQuest Integration" 
							end select
						end if
					end if
				end if 	'a_oCQSession
			else								  
				msgbox "Modification (or viewing) of Requirement properties cannot be done at this point, as the Clearquest information is currently displayed from RequisitePro. Please access the Requirement Properties dialog from RequisitePro.", vbOKOnly + vbInformation, "Rational RequisitePro/ClearQuest Integration" 
			end if	'a_bIsRunningIntegration
		else								  
			msgbox "This ClearQuest/RequisitePro integration operation is not supported. This ClearQuest record is associated with a Rational project that is not accessible from your local area network.", vbOKOnly + vbInformation, "Rational RequisitePro/ClearQuest Integration" 
		end if	' Req_GUID Not empty

	end if	'a_bWeb
	
	if not a_oRequisiteProTool is nothing then
		if not a_oRequisiteProTool.Unload(a_sError) then
			Msgbox a_sError, vbOKOnly + vbCritical, "Rational RequisitePro/ClearQuest Integration"
		end if
		set a_oRequisiteProTool = nothing
	end if

	set a_oCQSession = nothing


program:
REM add your hook code here

  	Requirement_CQI_Web_RPLogon = CQI_Web_ValidateRPLogon()


program:
REM Set the initial value of the field here.  Example:
    REM   SetFieldValue fieldname, 12345

	 dim session
	 dim userName

	 set session = GetSession
	 userName = session.GetUserLoginName

	 SetFieldValue fieldname, userName


program:
REM Set the initial value of the field here.  Example:
    REM   SetFieldValue fieldname, 12345

	 SetFieldValue fieldname, now


program:
If GetFieldValue("Resolution_Statetype").GetValue() = "Resolved" then
        Resolution_Permission = AD_MANDATORY
    else
       Resolution_Permission = AD_OPTIONAL
    End if


program:
if ($entity->GetFieldValue("Resolution_Statetype")->GetValue() eq "Resolved") {
        $result = $CQPerlExt::CQ_MANDATORY;
    } else {
        $result = $CQPerlExt::CQ_OPTIONAL;
    }


program:
Duplicate
Enhancement Request
Fixed
Fixed Indirectly
Functions as Designed


program:
REM return one of AD_MANDATORY, AD_OPTIONAL, AD_READONLY.  Example:
    REM   If username = "pat" Then
    REM      repoproject_Permission = AD_READONLY
    REM   Else
    REM      repoproject_Permission = AD_OPTIONAL
    REM   End If





 	Dim ac_sCQIRepoVar
    Dim a_oCQSession			   

    ac_sCQIRepoVar = "CQICurrentRepo" 

    Set a_oCQSession = GetSession
    if not a_oCQSession is nothing then
       a_oCQSession.NameValue(ac_sCQIRepoVar) = GetFieldValue(fieldname).GetValue
    end if
	 RepoProject_Permission = AD_OPTIONAL


program:
REM This hook will be run each time the field's value
  REM changes.  This hook is run before
  REM the new value is validated
  REM so be aware the new value may not be valid.
  REM Example:
  REM   Dim op_sys
  REM   op_sys = GetFieldValue(fieldname).GetValue()
  REM   If op_sys = "windows" Then
  REM      SetFieldValue "os_version", "NT 4.x"
  REM  <etc.>
  REM   End If
	On Error resume next
	err.clear

	Dim ac_sCQReqListAttName    
	Dim ac_sCQIRepoVar
	Dim a_oCQSession
	Dim a_sSavedRepo
	Dim a_vTableDBIDs
	Dim a_sFail
	Dim bWeb

	dim oRAPrj

   ac_sCQReqListAttName= "Requirements_List"
   ac_sCQIRepoVar = "CQICurrentRepo"  


	bWeb = Check_Web()
  
   Set a_oCQSession = GetSession
   if not a_oCQSession is nothing then
	' RATLC00772237 - Check for TMS COM Server available in advance
	' to suppress error message boxes when TeamTest components are not installed
	Dim tmsServerChecked
	Dim oSQARepo
	tmsServerChecked = "TMSSERVERCHECKED"

	if NOT a_oCQSession.HasValue(tmsServerChecked) then
		Set oSQARepo = CreateObject("TMSServer.TMSServer")
		if err.number <> 0 OR oSQARepo is nothing then
		 	a_oCQSession.NameValue("REPOVALID") = True
			a_oCQSession.NameValue(tmsServerChecked) = False
		else
			a_oCQSession.NameValue(tmsServerChecked) = True			
		end if
		set oSQARepo = nothing
	end if

   	if GetFieldValue("RAProject").GetValue() = "" then

      a_sSavedRepo = a_oCQSession.NameValue(ac_sCQIRepoVar)

	  a_vTableDBIDs = GetFieldValue(ac_sCQReqListAttName).GetValueAsList
      if IsEmpty(a_vTableDBIDs) then

	  	a_oCQSession.NameValue(ac_sCQIRepoVar) = GetFieldValue(fieldname).GetValue
		ChangeTTProject
      else

	  	if a_sSavedRepo <> GetFieldValue(fieldname).GetValue then
			if not bWeb then
           		msgbox "Once requirements are associated with a ClearQuest record, you can't change its Rational Project." + vbcrlf + "Please first remove existing associations.", vbOKOnly + vbInformation, "Rational RequisitePro/ClearQuest Integration" 
			end if
			' for Web just revert back the value. Raising an error does not do anything
           a_sFail = SetFieldValue(fieldname, a_sSavedRepo)
        end if
	  end if    'a_vTableDBIDs

	else

	  	set oRAPrj = a_oCQSession.GetEntity("RAProject", GetFieldValue("RAProject").GetValue()) 

		if not oRAPrj is nothing then

'		   	if oRAPrj.SiteHasMastership then
		      a_sSavedRepo = a_oCQSession.NameValue(ac_sCQIRepoVar)

			  a_vTableDBIDs = GetFieldValue(ac_sCQReqListAttName).GetValueAsList
		      if IsEmpty(a_vTableDBIDs) then

			  	a_oCQSession.NameValue(ac_sCQIRepoVar) = GetFieldValue(fieldname).GetValue
				ChangeTTProject
		      else
				' Allows RA project to change from Blank to Valid value.
			  	if len(a_sSavedRepo) = 0 then
					a_oCQSession.NameValue(ac_sCQIRepoVar) = GetFieldValue(fieldname).GetValue
					SetTTProject
				elseif a_sSavedRepo <> GetFieldValue(fieldname).GetValue then
					if not bWeb then
		           		msgbox "Once requirements are associated with a ClearQuest record, you can't change its Rational Project." + vbcrlf + "Please first remove existing associations.", vbOKOnly + vbInformation, "Rational RequisitePro/ClearQuest Integration" 
					end if
					' for Web just revert back the value. Raising an error does not do anything
		           a_sFail = SetFieldValue(fieldname, a_sSavedRepo)
		        end if
			  end if    'a_vTableDBIDs

'			else
'				'RATLC00014772 Modified the message and added code to reset the value to what it was before the selection
'				if not bWeb then
'		        	msgbox "You cannot associate ClearQuest records with a Rational project if the ownership of the Rational project does not belong to your local ClearQuest MultiSite database." , vbOKOnly + vbInformation, "Rational RequisitePro/ClearQuest Integration" 
'				end if
'				' for Web just revert back the value. Raising an error does not do anything
'				a_sFail = SetFieldValue(fieldname, a_sSavedRepo)
'			end if 'oRAPrj.SiteHasMastership

		end if	'oRAPrj

     end if 'GetFieldValue("RAProject").GetValue()
   end if 'a_oCQSession


program:
REM Return a non-empty string explaining why the
   REM field's current value is not permitted.
   REM Or, if it is valid, return an empty string value.
   REM Example: 
   REM    Dim value_info
   REM    Set value_info = GetFieldValue(fieldname)
   REM    If Len(value_info.GetValue()) < 10 Then
   REM        requirements_list_Validation = "Must be at least 10 chars long"
   REM    End If
	Dim oSession
 	Dim sRAProjectName
 	Dim bWeb
 	Dim a_vTableDBIDs				'List of DBIDs of Req proxies associated to the current CQ record
 	Dim a_oCurReq
 	Dim sError
 	Dim ac_sCQReqListAttName
 	Dim ac_sRequirement
 	Dim ac_sRAProjectField
 	Dim ac_sRAProjectNameField
 	Dim ac_sTagField
 	Dim ac_sNameField
 	Dim ac_sRequirementField
 	Dim lCount
 	dim a_lIndex
 	 	
	ac_sRequirement = "Requirement"
 	ac_sCQReqListAttName = "Requirements_List"
 	ac_sRAProjectField  = "RAProject"
 	ac_sRAProjectNameField = "RAProjectName"
 	ac_sTagField = "Tag"
 	ac_sNameField = "Name"
 	ac_sRequirementField = "Requirement"
		
 	set oSession = GetSession
 	if oSession is nothing then
 		exit function
 	end if
  	sError = vbNullString
 	lCount = 0
 	
 	sRAProjectName = GetFieldValue(ac_sRAProjectField).GetValue
 	
 	if len(sRAProjectName) <> 0 then
 		a_vTableDBIDs = getfieldValue(fieldname).GetValueAsList
 		if not IsEmpty(a_vTableDBIDs) then
 			if (LBound(a_vTableDBIDs) <= UBound(a_vTableDBIDs)) Then
 				For a_lIndex = LBound(a_vTableDBIDs) To UBound(a_vTableDBIDs)
 					set a_oCurReq = oSession.GetEntity(ac_sRequirement, cstr(a_vTableDBIDs(a_lIndex)))
 					if a_oCurReq.GetFieldValue(ac_sRAProjectNameField).GetValue <> sRAProjectName then
 						dim sName
 						dim sText
 						sName = a_oCurReq.GetFieldValue(ac_sNameField).GetValue
 						sText = a_oCurReq.GetFieldValue(ac_sRequirementField).GetValue
 						sError = sError + vbcrlf + "Tag: " + a_oCurReq.GetFieldValue(ac_sTagField).GetValue
 						
						if len(sName) = 0 then
 							sError = sError + ", Name: "
 						elseif len(sName) > 33 then
 							sError = sError + ", Name: " + left(sName, 30) + "..."
 						else
 							sError = sError + ", Name: " + sName
 						end if

						if len(sText) = 0 then
 							sError = sError + ", Text: "
 						elseif len(sText) > 33 then
 							sError = sError + ", Text: " + left(sText, 30) + "..."
 						else
 							sError = sError + ", Text: " + sText
 						end if

 						lCount = lCount + 1
 					end if
 				next
 			end if
 		end if
 		 
		if lCount = 1 then
 			requirements_list_Validation = "Requirements must belong to RAProject: " + sRAProjectName + _
 				". The following Requirement belongs to a different RAProject:" + sError
 		elseif lCount > 1 then
 			requirements_list_Validation = "Requirements must belong to RAProject: " + sRAProjectName + _
 				". The following Requirements belong to different RAProject:" + sError
 		end if
	else
		a_vTableDBIDs = getfieldValue(ac_sCQReqListAttName).GetValueAsList
 		if not IsEmpty(a_vTableDBIDs) then
 			if (LBound(a_vTableDBIDs) <= UBound(a_vTableDBIDs)) Then
 				requirements_list_Validation = "Please select an RA Project in order to create associations to Requirement records."
 			end if
 		end if
 	end if
 	
 	set oSession = nothing
 	set a_ocurReq = nothing


program:
# Do not initialize Note_Entry field if the action type is
    # duplicate, unduplicate, or delete.

    my $primaryActionType = $entity->GetActionType();
    if ($primaryActionType ne $CQPerlExt::CQ_DUPLICATE &&
        $primaryActionType ne $CQPerlExt::CQ_UNDUPLICATE && 
        $primaryActionType ne $CQPerlExt::CQ_DELETE) {
        NoteEntryInit("Note_Entry");
    }


program:
# Return a non-empty string explaining why the action cannot commit
    # with its current values. If it is valid, return an empty string.
    # Example:
    #    my $value_info = $entity->GetFieldValue("some field");
    #    if (length($value_info->GetValue()) < 10) {
    #        $result = "Must be at least 10 chars long";
    #    }

	# Ensure that the log is updated correctly if we were editing multiple
	# records in batch mode (see RATLC00453464.)

	SetLog("Note_Entry", "Notes_Log");


program:
Dim Primary_Action_Type
	Dim session

	Primary_Action_Type = GetActionType
	Set session = GetSession

	if Primary_Action_Type <> AD_IMPORT And session.IsEmailEnabled then
		RSEM_ProcessEmailRules (BaseEntity)
	end if


program:
my $primaryActionType = $entity->GetActionType();
	my $session = $entity->GetSession();

	if ($primaryActionType != $CQPerlExt::CQ_IMPORT &&
		$session->IsEmailEnabled()) {
		RSEM_ProcessEmailRules($entity);
	}


program:
Dim CurrentAction
  CurrentAction = GetActionType()
  ' Check to see what the current action is.  If it is a
  ' Modify_State or Change_State type action, then attempt
  ' the repository connection.  This is unnecessary for other
  ' action types.  For newly submitted defects, there is no
  ' context for the project, so this is done with the project
  ' fields OnChange hook

  If ((CurrentAction <> AD_IMPORT) And (CurrentAction <> AD_DUPLICATE) And  _
     (CurrentAction <> AD_UNDUPLICATE) And (CurrentAction <> AD_DELETE) And _
	  (CurrentAction <> AD_SUBMIT)) Then
	  		SetTTProject
  End If


program:
REM do any setup for the action here

REM Stores in global variable called "CQIReqs", the list of Req Proxy DBIDs, the current CQ record is currently associated to
REM Position state of state machine to "INIT"

	Dim a_CurrentActionType					'Action type of the action that initiated the execution of this script
	Dim ac_sCQReqListAttName				'Name of the global variable containing the name of the field of the CQ record that stores associations
	Dim ac_sCQIStateVar						'Name of the global variable containing the current state of the state machine
	Dim ac_sCQIListReqsVar					'Name of the global variable containing the list of Proxy Req DBIDs associated to the current CQ record
	Dim ac_sCQIdbidSeparator				'Character used to separate dbids in string list 
	Dim a_bWeb									'Web or not
	Dim a_bIsRunningIntegration			'Contains a boolean indicating if the integration is already in progress, to prevent reccurence
	Dim a_oCQSession							'Current CQ session
	Dim a_sListDBIDs							'List of Req proxy DBIDs associated to the current CQ record
	Dim a_vTableDBIDs							'Table of Req proxy DBIDs associated to the current CQ record

	a_CurrentActionType = GetActionType()

	'Check to see if the real action is an import action or delete action.
	'If so exit.
	if a_CurrentActionType = AD_IMPORT or a_CurrentActionType = AD_DELETE then
		exit sub
	end if

	ac_sCQReqListAttName = "Requirements_List"		 
	ac_sCQIStateVar = "CQIState"
	ac_sCQIListReqsVar = "CQIReqs"
	ac_sCQIdbidSeparator = ","

	a_bWeb = Check_Web()
	'This script must no be launched through the web
	'We also test if the record is editable, it should be as we are in an initialization hook
	If (IsEditable AND NOT a_bWeb) Then
		a_bIsRunningIntegration = CQI_IsRunningIntegration()
		if not a_bIsRunningIntegration then
		 	Set a_oCQSession = GetSession
			if not a_oCQSession is nothing then
				'Systematically set Sate to INIT
				a_oCQSession.NameValue(ac_sCQIStateVar)= "INIT"
				'Get the list of DBIDs of the Req proxies associated to current CQ record
				a_vTableDBIDs = getfieldValue(ac_sCQReqListAttName).GetValueAsList
				if not IsEmpty(a_vTableDBIDs) then
					if CQI_GetListFromDBIDTable(a_vTableDBIDs, ac_sCQIdbidSeparator, a_sListDBIDs) then
						'Stores the list in global variable
						a_oCQSession.NameValue(ac_sCQIListReqsVar) = a_sListDBIDs
					end if
				end if	'a_vTableDBIDs
			end if	'a_oCQSession
		end if	'a_bIsRunningIntegration
	end if	'a_bWeb

	set a_oCQSession = nothing


program:
REM Return a non-empty string explaining why the action
   REM cannot commit with the current values.
   REM Or, if it is valid, return an empty string value.
   REM Example: 
   REM    Dim value_info
   REM    Set value_info = GetFieldValue("some field")
   REM    If Len(value_info.GetValue()) < 10 Then
   REM        EnhancementRequest_Validation = "Must be at least 10 chars long"
   REM    End If

REM Checks if associations still exist with current CQ record when user tries to delete it
REM if none, deletion completed
REM if some, deletion canceled

	Dim a_CurrentActionType					'Action type of the action that initiated the execution of this script

	a_CurrentActionType = GetActionType()
   'Check to see if the real action is a delete action.
	'If not exit.
	if a_CurrentActionType = AD_DELETE then
		'Don't allow user to delete the current record unless no requirements are
		'associated with it
		Dim ac_sCQReqListAttName				'Name of the global variable containing the name of the field of the CQ record that stores associations
		Dim a_vTableDBIDs							'List of DBIDs of Req proxies associated to the current CQ record
	
		ac_sCQReqListAttName= "Requirements_List"
' RATLC00015495 
'		a_vTableReqIds = GetFieldValue(ac_sCQReqListAttName).GetValueAsList		
        a_vTableDBIDs = GetFieldValue(ac_sCQReqListAttName).GetValueAsList
		if IsEmpty(a_vTableDBIDs) then
'			EnhancementRequest_Validation = vbNullString		
		EnhancementRequest_Validation = vbNullString		
		else
'			EnhancementRequest_Validation = "Rational RequisitePro/ClearQuest Integration: You have to remove all associations with RequisitePro requirements before you can delete the current ClearQuest record."	    	
			EnhancementRequest_Validation = "Rational RequisitePro/ClearQuest Integration: You have to remove all associations with RequisitePro requirements before you can delete the current ClearQuest record."
		end if
	end if	'a_CurrentActionType


program:
REM This hook is fired during the "commit" step of an
  REM entity update, so it is the appropriate place to put
  REM activity which should be bundled into the same
  REM transaction as the commit, such as subactions
  REM or updates of external data storage.

REM Empty global variable called "CQIReqs" that stores the list of Req Proxy DBIDs, the current CQ record is currently associated to
REM If state of state machine is "MODIFIED", then call integration to commit changes on RequisitePro side
REM Reset state of state machine to "NOTHING"

	Dim a_CurrentActionType					'Action type of the action that initiated the execution of this script
	Dim ac_sCQIStateVar						'Name of the global variable containing the current state of the state machine
	Dim ac_sCQIListReqsVar					'Name of the global variable containing the list of Proxy Req DBIDs associated to the current CQ record
	Dim a_bWeb									'Web or not
	Dim a_bIsRunningIntegration			'Contains a boolean indicating if the integration is already in progress, to prevent reccurence
	Dim a_oCQSession							'Current CQ session
	Dim a_oRequisiteProTool					'Reference to a ASCQIIntegration.RequsiteProTool instance
	Dim a_sError								'Error message sent back by integration in case of a failure to commit modifications
 
	a_CurrentActionType = GetActionType()

	'Check to see if the real action is an import action or delete action.
	'If so exit.
	if a_CurrentActionType = AD_IMPORT or a_CurrentActionType = AD_DELETE then
		exit sub
	end if

	ac_sCQIStateVar = "CQIState"
	ac_sCQIListReqsVar = "CQIReqs"

	a_bWeb = Check_Web()
   'This script must no be launched through the web
	'We also test if the record is editable, it should be as we are in a commit hook
	If (IsEditable AND NOT a_bWeb) Then
		a_bIsRunningIntegration = CQI_IsRunningIntegration()
		if not a_bIsRunningIntegration then
		 	Set a_oCQSession = GetSession
			if not a_oCQSession is nothing then
				if a_oCQSession.NameValue(ac_sCQIStateVar)= "MODIFIED" then
					set a_oRequisiteProTool = CQI_GetRequisiteProTool()	
					if a_oRequisiteProTool is nothing then
						msgbox "Could not connect to the integration server.", vbOKOnly + vbCritical, "Rational RequisitePro/ClearQuest Integration"
					else
						if not a_oRequisiteProTool.Commit(Me, a_sError) then
							msgbox a_sError ,vbOKOnly + vbCritical, "Rational RequisitePro/ClearQuest Integration"
						end if
					end if
				else	'ac_sCQIStateVar
					'No modification made through CQ/RP integration
				end if
				a_oCQSession.NameValue(ac_sCQIStateVar)= "NOTHING"
				a_oCQSession.NameValue(ac_sCQIListReqsVar) = vbNullString
				call CQI_UnloadRequisiteProTool()
			end if	'a_oCQSession
		end if	'a_bIsRunningIntegration
	end if	'a_bWeb
 
	set a_oRequisiteProTool = nothing
	set a_oCQSession = nothing


program:
REM Check the requirement type for its type guid
   REM Check the type of the current record type
   REM pull up a requirement map for this record type
   REM see if the requirement type guid is the same as the guid 
   REM for the requirement that is being added.
	
	' Get all the requirement types that this artifact can be associated to
	Dim session, reqList, listItem, tempReq, recordType
	
	EnhancementRequest_Validation = ""
	Set session = GetSession
	recordType = GetEntityDefName

	Dim queryDef, queryField, operator, filterNode, resultSet
	Dim ac_sTagField
	Dim ac_sNameField
	
	ac_sTagField = "Tag"
	ac_sNameField = "Name"

	Set queryDef = session.BuildQuery("RequirementMap")
	If Not queryDef is Nothing then
	' Building the query
		queryField = queryDef.BuildField("RPReqTypeGUID")
		Set operator = queryDef.BuildFilterOperator(AD_COMP_OP_EQ)
		operator.BuildFilter "CQEntityDefName",	AD_COMP_OP_EQ, recordType
		Set resultSet = session.BuildResultSet(queryDef)
		resultSet.Execute()

		Dim found, tempGUID, counter, status, GUIDs

		Set GUIDs = CreateObject("Scripting.dictionary")

		found = False
		counter = 0
		status = resultSet.MoveNext
	'	build the requirement types GUIDs array
		Do While status = AD_SUCCESS 
			tempGUID = resultSet.GetColumnValue(1)
			GUIDs.Add counter, tempGUID
			counter = counter + 1
		 	status = resultSet.MoveNext
		 Loop 

	'	Retrieve all the requirements that are associated to the current artifact
		Dim tempReqList
		tempReqList = GetFieldValue("Requirements_List").GetValue	

		If tempReqList <> "" then
		'	Break the string of line feed separated requirement ids in to an array
			Dim array ' array of requirements
			Dim u ' number of elements in the array
			Dim result
			result = ""
		'	Splitting it
		  	array = Split(Cstr(tempReqList),vbLF)
			u = UBound(array)
			Dim ReqId, requirement, reqTypeGUID
		'	Check if the requirement's type is in the list of allowed requirement GUIDs list
			For i = 0 To u
				found = False
				ReqId = array(i)
			'	Get the requirement
				Set requirement = session.GetEntity("Requirement", ReqId)
				If Not requirement Is Nothing Then
					Dim fieldDef 
				'	Get the requirement type
					reqTypeGUID = requirement.GetFieldValue("Type_GUID").GetValue
				'	Check to see if the GUID is matching with the existing list
					For j = 0 to GUIDs.count
						If GUIDs.Item(j) <> "" Then
							If GUIDs.Item(j) = reqTypeGUID Then
							'	Found it so dont need to loop anymore
								found = True
								Exit For
							End If
						Else
							'	Valid guid's are done so skip
							Exit For
						End If
					Next

				End If
			'	Create the erroneous list of requirements

				If Not found Then
					Dim sReq
					Dim sName
					
					sName = requirement.GetFieldValue(ac_sNameField).GetValue
					sReq = requirement.GetFieldValue(ac_sTagField).GetValue
					' Limiting the name length to about 30 characters for display
					if len(sName) = 0 then
						result = result & vbLF & sReq
					elseif len(sText) > 33 then
						result = result & vbLF & sReq & ": " & left(sName, 30) + "..."
					else
						result = result & vbLF & sReq & ": " & sName
					end if
				end if				
			Next
			'	Check to see if the erroneous list of requirements is empty or not
			If result <> "" Then
			'	if the list is not empty create the error message.
				EnhancementRequest_Validation = "The following Requirements types dont match " & result
			End If
		End If

	End If


program:
REM add your hook code here

REM Launch RequisitePro Association dialog box, with list of Req Proxy DBIDs of Requirements already associated to current CQ record
REM if return of call is OK
REM	Position state of state machine to "MODIFIED"
REM if return of call is Cancel


	Dim eRet_Empty
	Dim eRet_OK
	Dim eRet_Cancel
	Dim eRet_Error
	Dim ac_sCQReqListAttName				'Name of the global variable containing the name of the field of the CQ record that stores associations
	Dim ac_sCQIStateVar						'Name of the global variable containing the current state of the state machine
	Dim ac_sCQIListReqsVar					'Name of the global variable containing the list of Proxy Req DBIDs associated to the current CQ record
	Dim ac_sCQIdbidSeparator				'Character used to separate dbids in string list 
	Dim a_bWeb									'Web or not
	Dim a_bIsRunningIntegration			'Contains a boolean indicating if the integration is already in progress, to prevent reccurence
	Dim a_bProjectSet							'Contains a boolean indicating if a Rational Project has been selected for the current CQ record
	Dim a_oCQSession							'Current CQ session
	Dim a_oRequisiteProTool					'Reference to a ASCQIIntegration.RequisiteProTool instance
	Dim a_sListReqDBIDs						'List of Req Proxy DBIDs associated to the current CQ record
	Dim a_eRet									'Contains value returned by the call to integration
	Dim a_sError								'Error message sent back by integration in case of a failure
	Dim a_vTableDBIDs							'List of DBIDs of Req proxies associated to the current CQ record
	Dim a_lIndex
	Dim a_sFail									'Return value of the creation of the association in ClearQuest between current CQ record and the Req Proxy

	eRet_Empty = 0
	eRet_OK = 1
	eRet_Cancel = 2
	eRet_Error = 3	

	ac_sCQReqListAttName= "Requirements_List"	
	ac_sCQIStateVar = "CQIState"
	ac_sCQIListReqsVar = "CQIReqs"
	ac_sCQIdbidSeparator = ","
	
	a_bWeb = Check_Web()

	' RATLC01009865 - Display message for non-functional button in CQWeb
	if a_bWeb then
		' Need this Error handler otherwise it does not work from CQWeb.
		On Error resume next
	 	err.clear

		EnhancementRequest_CQI_Select_Req = "This operation is not available in the Web client."
		return
	end if	


   'This script must no be launched through the web
	'We also test if the record is editable
	If (IsEditable AND NOT a_bWeb) Then

		if Check_RAProjectMaster then
			a_bIsRunningIntegration = CQI_IsRunningIntegration()
			if not a_bIsRunningIntegration then
				a_bProjectSet = Check_Project()
				if a_bProjectSet then
				 	Set a_oCQSession = GetSession
					if not a_oCQSession is nothing then
						set a_oRequisiteProTool = CQI_GetRequisiteProTool()	
						if a_oRequisiteProTool is nothing then
							msgbox "ClearQuest could not connect to the Integration Server." + vbcrlf + "Please contact your Administrator.", vbOKOnly + vbCritical, "Rational RequisitePro/ClearQuest Integration"
						else
							' RATLC01201983 - Do not use list of requirements when beginning to modify the record.
							' instead use the current list of requirements
							' a_sListReqDBIDs = a_oCQSession.NameValue(ac_sCQIListReqsVar)
							a_vTableDBIDs = getfieldValue(ac_sCQReqListAttName).GetValueAsList
							if not IsEmpty(a_vTableDBIDs) then
								CQI_GetListFromDBIDTable a_vTableDBIDs, ac_sCQIdbidSeparator, a_sListReqDBIDs
							end if   ' a_vTableDBIDs

							a_eRet = a_oRequisiteProTool.AssociateFromClearQuest(me, ac_sCQReqListAttName, a_sListReqDBIDs, a_sError)
							Select Case a_eRet
							   	Case eRet_OK
									a_oCQSession.NameValue(ac_sCQIStateVar)= "MODIFIED" 
									if a_sListReqDBIDs <> vbNullString then
										a_vTableDBIDs = empty
										if CQI_GetTableFromDBIDList(a_sListReqDBIDs, ac_sCQIdbidSeparator, a_vTableDBIDs) then
											if not IsEmpty(a_vTableDBIDs) then
												for a_lIndex = LBound(a_vTableDBIDs) to UBound(a_vTableDBIDs)
											        a_sFail = AddFieldValue(ac_sCQReqListAttName, cstr(a_vTableDBIDs(a_lIndex)))
													if a_sFail = vbNullString then
														call CQI_AddDBIDToList(cstr(a_vTableDBIDs(a_lIndex)), ac_sCQIdbidSeparator)
													end if	'a_sFail
												next
											end if
										end if
									end if
				
						      Case eRet_Cancel

								Case Else		
									msgbox a_sError ,vbOKOnly + vbCritical, "Rational RequisitePro/ClearQuest Integration"
				
							End Select
						end if	'a_oRequisiteProTool
					end if	'a_oCQSession
				else
					if GetEntityDefName = "EnhancementRequest" and GetActionType = AD_SUBMIT then
						msgbox "In order to associate a requirement, you must first submit the EnhancementRequest record.", vbOKOnly + vbInformation, "Rational RequisitePro/ClearQuest Integration"
					else 						
						MsgBox "A valid RAProject must be selected.", vbOKOnly + vbInformation, "Rational RequisitePro/ClearQuest Integration"
					end if
				end if	'a_bProjectSet
			else								  
				msgbox "Modification (or viewing) of Requirement properties cannot be done at this point, as the Clearquest information is currently displayed from RequisitePro. Please access the Requirement Properties dialog from RequisitePro.", vbOKOnly + vbInformation, "Rational RequisitePro/ClearQuest Integration" 
			end if	'a_bIsRunningIntegration

		else								  
			msgbox "This ClearQuest/RequisitePro integration operation is not supported. This ClearQuest record is associated with a Rational project that is not accessible from your local area network.", vbOKOnly + vbInformation, "Rational RequisitePro/ClearQuest Integration" 
		end if	'Check_RAProjectMaster
	end if	'a_bWeb

	set a_oRequisiteProTool = nothing
	set a_oCQSession = nothing


program:
REM add your hook code here

REM Launch RequisitePro Properties dialog box for the selected Requirement in the CQ list box, and pass its DBID 
REM if return of call is ePrp_OK
REM	Nothing is done
REM if return of call is ePrp_Removed
REM	then the requirement is removed fromlist of requirement associated with current CQ record

	On Error resume next	'handle ListSelection empty
	err.clear

	Dim a_bWeb									'Web or not
	Dim a_bIsRunningIntegration			'Contains a boolean indicating if the integration is already in progress, to prevent reccurence
	Dim a_oCQSession							'Current CQ session
	Dim a_lNumberSel							'Number of Requirements currently selected in the CQ List Box
	Dim a_sStrElm								'CQ Key of the Req Proxy selected in the CQ List Box (currently dbid)
	Dim a_sDBID									'DBID of the Req Proxy selected in the CQ List Box
	Dim a_bEmpty								'Boolean indicationg wether or not a Req Proxy is selected in the CQ List Box
	Dim a_sError								'Error message sent back by integration in case of a failure
	Dim a_sFail									'Return value of the deletion of the association in ClearQuest between current CQ record and the Req Proxy
 	dim a_oReq									' selected Requirement record
	Dim vRet									' Generic return value
	Dim ac_sCQReqListAttName
	
	ac_sCQReqListAttName= "Requirements_List"

	a_bWeb = Check_Web()

	' RATLC01009865 - Display message for non-functional button in CQWeb
	if a_bWeb then
		EnhancementRequest_CQI_Properties_Req = "You cannot view a requirement from this record in the Web client. Open the requirement record and select View."
		return
	end if	

   'This script must not be launched through the web
	'We also test if the record is editable
	If (IsEditable AND NOT a_bWeb) Then
		a_bIsRunningIntegration = CQI_IsRunningIntegration()
		if not a_bIsRunningIntegration then
		 	Set a_oCQSession = GetSession
			if not a_oCQSession is nothing then
				if Check_Eclipse() then
					' Handle the selection differently for CQ Eclipse.
					' param = string of selected DBIDs separated by Line Feed.
					Dim sParam 
					Dim bGotOne

					sParam = cstr(param)
					bGotOne = false
					' There is an extra LF added at the end of every DBID 
					' even for one selection. The code below handles both the 
					' cases, with and without the last LF.
					if len(sParam) > 1 then
					    If InStrRev(sParam, vbLf) = Len(sParam) Then
					    	If InStrRev(Left(sParam, Len(sParam) - 1), vbLf) = 0 Then
					            ' There is an extra LF at the end of the string
					            a_sDBID = Left(sParam, Len(sParam) - 1)
					            bGotOne = True
					        End If
					    Else
					        If InStrRev(sParam, vbLf) = 0 Then
					            a_sDBID = sParam
					            bGotOne = True
					        End If
					    End If
					End If

					if bGotOne then
						set a_oReq = a_oCQSession.GetEntity("Requirement", a_sDBID)
						if not a_oReq is nothing then
							vRet = a_oReq.FireNamedHook("CQI_Properties_Req", "")
							set a_oReq = nothing
						end if
					else
						MsgBox "Please select one requirement in the list view to get the properties.", vbOKOnly + vbInformation, "Rational RequisitePro/ClearQuest Integration"
					end if
				else
					a_lNumberSel = 0
					For Each a_sStrElm In param.ListSelection
						a_sDBID = a_sStrElm
						a_lNumberSel = a_lNumberSel + 1
					Next
					a_bEmpty = IsNull(a_sDBID) or IsEmpty(a_sDBID)
					if a_bEmpty then
						'Nothing to do
						MsgBox "Please select one requirement in the list view to get the properties.", vbOKOnly + vbInformation, "Rational RequisitePro/ClearQuest Integration"
					else
		on error goto 0
						if a_lNumberSel = 1 then
	 						set a_oReq = a_oCQSession.GetEntity("Requirement", a_sDBID)
	 						if not a_oReq is nothing then
	 							vRet = a_oReq.FireNamedHook("CQI_Properties_Req", "")
	 						end if
	 				   	else
							MsgBox "Please select one requirement in the list view to get the properties.", vbOKOnly + vbInformation, "Rational RequisitePro/ClearQuest Integration"
						end if
					end if	'a_bEmpty
				end if ' Check_Eclipse()

				' RATLC01011263 - If the Requirement is deleted from RP. Prompt user to remove the association 
				if vRet = "DELETED" then
					vRet = Msgbox ("The requirement has been deleted in Rational RequisitePro." _
									+ vbcrlf+ "Do you want to remove the association?", _
									vbYesNo + vbQuestion, _
									"Rational RequisitePro/ClearQuest Integration")
					if vRet = vbYes then
						DeleteFieldValue ac_sCQReqListAttName, a_sDBID
					end if
				end if

			end if	'a_oCQSession
		else								  
			msgbox "Modification (or viewing) of Requirement properties cannot be done at this point, as the Clearquest information is currently displayed from RequisitePro. Please access the Requirement Properties dialog from RequisitePro.", vbOKOnly + vbInformation, "Rational RequisitePro/ClearQuest Integration" 
		end if	'a_bIsRunningIntegration
	end if	'a_bWeb

	set a_oReq = nothing
	set a_oCQSession = nothing


program:
REM add your hook code here

REM Revert the modifications made on the RequisitePro side to stay in sync with revert done on ClearQuest side
REM The purpose of the state machine managed in the hooks is to trap this event: Revert in CQ

	Dim ac_sCQIStateVar						'Name of the global variable containing the current state of the state machine
	Dim ac_sCQIListReqsVar					'Name of the global variable containing the list of Proxy Req DBIDs associated to the current CQ record
	Dim a_bWeb									'Web or not
	Dim a_oCQSession							'Current CQ session
	Dim a_sCurrentState						'State ths state machine is currently in
	Dim a_oRequisiteProTool					'Reference to a ASCQIIntegration.RequisiteProTool instance
	Dim a_sError								'Error message sent back by integration in case of a failure

	ac_sCQIStateVar = "CQIState"
	ac_sCQIListReqsVar = "CQIReqs"

	a_bWeb = Check_Web()
   'This script must no be launched through the web
	'Don't test if the record is editable, it is not the case when user clicked Revert and then we have work to do
	If (NOT a_bWeb) Then

		'if Check_RAProjectMaster then
		 	Set a_oCQSession = GetSession
			if not a_oCQSession is nothing then
				if a_oCQSession.HasValue(ac_sCQIStateVar) then	
					a_sCurrentState = a_oCQSession.NameValue(ac_sCQIStateVar)
					if a_sCurrentState = "NOTHING" then
						'Nothing to do
					else
						if a_sCurrentState = "INIT" then
							a_oCQSession.NameValue(ac_sCQIStateVar) = "REVERT"
						else
							if a_sCurrentState = "COMMIT" then
								'Nothing to do	
								'An error occurred, set it back to NOTHING
								a_oCQSession.NameValue(ac_sCQIStateVar) = "NOTHING"
							else
								if a_sCurrentState = "MODIFIED" then
									set a_oRequisiteProTool = CQI_GetRequisiteProTool()	
									if a_oRequisiteProTool is nothing then
										msgbox "ClearQuest could not connect to the Integration Server." + vbcrlf + "Please contact your Administrator.", vbOKOnly + vbCritical, "Rational RequisitePro/ClearQuest Integration"
									else
										if not a_oRequisiteProTool.Rollback(Me, a_sError) then
											msgbox a_sError ,vbOKOnly + vbCritical, "Rational RequisitePro/ClearQuest Integration"
										end if
									end if
								else
									'No modification by CQ/RP integration
								end if	'a_sCurrentState = "MODIFIED"
								a_oCQSession.NameValue(ac_sCQIStateVar) = "NOTHING"
							end if	'a_sCurrentState = "COMMIT"
							a_oCQSession.NameValue(ac_sCQIListReqsVar) = vbnullstring
							call CQI_UnloadRequisiteProTool()
						end if	'a_sCurrentState = "INIT"
					end if	'a_sCurrentState = "NOTHING"
				else
					a_oCQSession.NameValue(ac_sCQIStateVar) = "NOTHING"
				end if	'a_sCQIStateVar
			end if	'a_oCQSession

		'else

			'msgbox "This ClearQuest/RequisitePro integration operation is not supported. This ClearQuest record is associated with a Rational project that is not accessible from your local area network.", vbOKOnly + vbInformation, "Rational RequisitePro/ClearQuest Integration" 
		'end if	'Check_RAProjectMaster
	end if	'a_bWeb

	set a_oRequisiteProTool = nothing
	set a_oCQSession = nothing


program:
REM add your hook code here

REM Removes the association for the selected Requirement in the CQ list box, and pass its DBID 
REM Position state of state machine to "MODIFIED"

 	On Error resume next	'handle ListSelection empty
	err.clear

	Dim ac_sCQReqListAttName				'Name of the global variable containing the name of the field of the CQ record that stores associations
	Dim ac_sCQIStateVar						'Name of the global variable containing the current state of the state machine
	Dim ac_sCQIListReqsVar					'Name of the global variable containing the list of Proxy Req DBIDs associated to the current CQ record
	Dim ac_sCQIdbidSeparator				'Character used to separate dbids in string list 
	Dim a_bWeb									'Web or not
	Dim a_bIsRunningIntegration			'Contains a boolean indicating if the integration is already in progress, to prevent reccurence
	Dim a_oCQSession							'Current CQ session
	Dim a_lNumberSel							'Number of Requirements currently selected in the CQ List Box
	Dim a_sStrElm								'CQ Key of the Req Proxy selected in the CQ List Box (currently dbid)
	Dim a_sDBID									'DBID of the Req Proxy selected in the CQ List Box
	Dim a_bEmpty								'Boolean indicationg wether or not a Req Proxy is selected in the CQ List Box
	Dim a_oRequisiteProTool					'Reference to a ASCQIIntegration.RequisiteProTool instance
	Dim a_sListReqDBIDs						'List of Req Proxy DBIDs associated to the current CQ record
	Dim a_eRet									'Contains value returned by the call to integration
	Dim a_sError								'Error message sent back by integration in case of a failure
	Dim a_vTableDBIDs							'List of DBIDs of Req proxies associated to the current CQ record
	Dim a_lIndex
	Dim a_sFail									'Return value of the creation of the association in ClearQuest between current CQ record and the Req Proxy

	ac_sCQReqListAttName= "Requirements_List"	
	ac_sCQIStateVar = "CQIState"
	ac_sCQIListReqsVar = "CQIReqs"
	ac_sCQIdbidSeparator = ","

	a_bWeb = Check_Web()
   'This script must no be launched through the web
	'We also test if the record is editable
	If (IsEditable AND NOT a_bWeb) Then

		if Check_RAProjectMaster then
			a_bIsRunningIntegration = CQI_IsRunningIntegration()
			if not a_bIsRunningIntegration then
			 	Set a_oCQSession = GetSession
				if not a_oCQSession is nothing then
					a_lNumberSel = 0
					For Each a_sStrElm In param.ListSelection
						a_sDBID = a_sStrElm
						a_lNumberSel = a_lNumberSel + 1
						a_bEmpty = IsNull(a_sDBID) or IsEmpty(a_sDBID)
						if not a_bEmpty then
		on error goto 0
							set a_oRequisiteProTool = CQI_GetRequisiteProTool()
							if a_oRequisiteProTool is nothing then
								msgbox "ClearQuest could not connect to the Integration Server." + vbcrlf + "Please contact your Administrator.", vbOKOnly + vbCritical, "Rational RequisitePro/ClearQuest Integration"
							else
								if a_oRequisiteProTool.RemoveRequirement(Me, ac_sCQReqListAttName, a_sDBID, a_sError) then
									a_sFail = DeleteFieldValue(ac_sCQReqListAttName, a_sDBID)
									if a_sFail <> vbnullstring then
										msgbox "Unable to remove the selected association on the ClearQuest side:" + vbcrlf + a_sFail, vbOKOnly + vbCritical, "Rational RequisitePro/ClearQuest Integration"
									else
										call CQI_RemoveDBIDFromList(a_sDBID, ac_sCQIdbidSeparator)
									end if	'a_sFail
									a_oCQSession.NameValue(ac_sCQIStateVar)= "MODIFIED"
								else
									msgbox a_sError ,vbOKOnly + vbCritical, "Rational RequisitePro/ClearQuest Integration"
								end if	'RemoveRequirement
							end if	'a_oRequisiteProTool
						else
							MsgBox "Please select one requirement in the list view to remove.", vbOKOnly + vbInformation, "Rational RequisitePro/ClearQuest Integration"
					   end if	'a_bEmpty
					Next		'a_sStrElm
				end if	'a_oCQSession
			else								  
				msgbox "Modification (or viewing) of Requirement properties cannot be done at this point, as the Clearquest information is currently displayed from RequisitePro. Please access the Requirement Properties dialog from RequisitePro.", vbOKOnly + vbInformation, "Rational RequisitePro/ClearQuest Integration" 
			end if	'a_bIsRunningIntegration

		else

			msgbox "This ClearQuest/RequisitePro integration operation is not supported. This ClearQuest record is associated with a Rational project that is not accessible from your local area network.", vbOKOnly + vbInformation, "Rational RequisitePro/ClearQuest Integration" 
		end if	'Check_RAProjectMaster
	end if	'a_bWeb

	set a_oRequisiteProTool = nothing
	set a_oCQSession = nothing


program:
REM add your hook code here

REM Refreshes the Requirement proxies of associated Requirements in the CQ list box
 	On Error resume next
 	err.clear

	Dim ac_sCQReqListAttName				'Name of the global variable containing the name of the field of the CQ record that stores associations
	Dim ac_sCQIdbidSeparator				'Character used to separate dbids in string list 
	Dim a_bWeb								'Web or not
	Dim a_bIsRunningIntegration				'Contains a boolean indicating if the integration is already in progress, to prevent reccurence
	Dim a_oCQSession						'Current CQ session
	Dim a_oRequisiteProTool					'Reference to a ASCQIIntegration.RequisiteProTool instance
	Dim a_sListReqDBIDs						'List of Req Proxy DBIDs associated to the current CQ record
	Dim a_vTableDBIDs						'List of DBIDs of Req proxies associated to the current CQ record
	Dim a_sError							'Error message sent back by integration in case of a failure
	Dim a_sDBIDtoRemove						'List of DBIDs of Req proxies associated to the current CQ record to remove because they don't exist anymore
	Dim a_sDBID								'DBIDs to remove
 	Dim a_oCurReq
	 dim ac_sRequirement
 	Dim ac_sReqRefreshAction
	ac_sRequirement = "Requirement" 
	ac_sReqRefreshAction = "Refresh"					  

	ac_sCQReqListAttName= "Requirements_List"	
	ac_sCQIdbidSeparator = ","

	a_bWeb = Check_Web()

	' RATLC01009865 - Display message for non-functional button in CQWeb
	if a_bWeb then
		EnhancementRequest_CQI_Refresh_Req = "You cannot refresh requirements from this record in the Web client. Open the requirement record and select Refresh."
		return
	end if	

   'This script must no be launched through the web
	'We also test if the record is editable, it should be as we are in an initialization hook
	If (IsEditable AND NOT a_bWeb) Then
		if Check_RAProjectMaster then
			a_bIsRunningIntegration = CQI_IsRunningIntegration()
			if not a_bIsRunningIntegration then
			 	Set a_oCQSession = GetSession
				if not a_oCQSession is nothing then
					set a_oRequisiteProTool = CQI_GetNewReqProTool()
					if a_oRequisiteProTool is nothing then
						msgbox "ClearQuest could not connect to the Integration Server." + vbcrlf + "Please contact your Administrator.", vbOKOnly + vbCritical, "Rational RequisitePro/ClearQuest Integration"
					else
						a_sError = me.Validate
						if a_sError <> vbNullString then
							MsgBox a_sError, vbOKOnly + vbInformation, _
									"Rational RequisitePro/ClearQuest Integration"
							
							if not a_oRequisiteProTool.Unload(a_sError) then
								Msgbox a_sError, vbOKOnly + vbCritical, "Rational RequisitePro/ClearQuest Integration"
	 						end if
							
							exit function
						end if

						a_vTableDBIDs = getfieldValue(ac_sCQReqListAttName).GetValueAsList
						if not IsEmpty(a_vTableDBIDs) then
 							Dim sRAProjectName
							Dim sRPProjectPath
							Dim sUserName 
							Dim sPassWord
							Dim sRequirementGUID
							dim bGotLogonInfo

							sRAProjectName = me.GetFieldValue("RAProject").GetValue
							sRPProjectPath = CQI_GetRPProjectFromRA(sRAProjectName)
							bGotLogonInfo = CQI_RPlogon(sRPProjectPath, sUserName, sPassword)
							if not bGotLogonInfo then
								if not a_oRequisiteProTool.Unload(a_sError) then
									Msgbox a_sError, vbOKOnly + vbCritical, "Rational RequisitePro/ClearQuest Integration"
		 						end if
								set a_oCQSession = nothing
							 	set a_oCurReq = nothing
							 	set a_oRequisiteProTool = nothing
								exit function
							end if

							if (LBound(a_vTableDBIDs) <= UBound(a_vTableDBIDs)) Then
								For a_lIndex = LBound(a_vTableDBIDs) To UBound(a_vTableDBIDs)
									bRefreshed = a_oRequisiteProTool.RefreshReqFromPlaceholder (GetSession(), _
															cstr(a_vTableDBIDs(a_lIndex)), _
															sRPProjectPath, _
															sUserName, _
															sPassword, _
															a_sError)
									if len (a_sError) <> 0 then
									 	MsgBox "Could not Refresh Requirement - " + a_oCurReq.GetFieldValue("Tag").GetValue + ":" + a_oCurReq.GetFieldValue("Name").GetValue + _
													vbcrlf + "Error: " + vbcrlf + a_sError, _
													vbOKOnly + vbInformation, _
													"Rational RequisitePro/ClearQuest Integration"
										err.clear	
									end if
	
								Next
							end if	'Bound vTable()
 						end if	'a_vTableDBIDs

						if not a_oRequisiteProTool.Unload(a_sError) then
							Msgbox a_sError, vbOKOnly + vbCritical, "Rational RequisitePro/ClearQuest Integration"
 						end if
					end if	'a_oRequisiteProTool
				end if	'a_oCQSession
			end if	'a_bIsRunningIntegration
		else

			msgbox "This ClearQuest/RequisitePro integration operation is not supported. This ClearQuest record is associated with a Rational project that is not accessible from your local area network.", vbOKOnly + vbInformation, "Rational RequisitePro/ClearQuest Integration" 
		end if	'Check_RAProjectMaster

	end if	'a_bWeb

	set a_oCQSession = nothing
 	set a_oCurReq = nothing
 	set a_oRequisiteProTool = nothing


program:
REM return TRUE if the user has permission to perform this action

	Dim a_oSession
	Dim a_oUser
	
	set a_oSession = GetSession
	if not a_oSession is nothing then
		set a_oUser = a_oSession.GetEntity("users", username)
		if not a_oUser is nothing then
			RequirementMap_AccessControl = a_oUser.GetFieldValue("is_superuser").GetValue
	  end if
	end if


program:
REM  *** Do not modify the predefined prologue above this line ***
On Error resume next	'handle repository login errors
err.clear

REM  *** Check to make sure that we have mastership locally before filling
REM  *** in the choice list
If NOT Check_RAProjectMaster Then
	choices.AddItem(GetFieldValue(fieldname).GetValue)
	exit sub
End If

if Valid_Project() Then
	Dim CQSession
	Dim SQASessionVar
	Dim TMSServer
	Set CQSession = GetSession
	SQASessionVar = "SQAREPO"

	Set TMSServer = CQSession.NameValue(SQASessionVar)

	Dim BuildList
	Set BuildList = TMSServer.Builds

	If (err.number <> 0) Then
		msgbox( "Could not access the TMS Build objects.")
		msgbox err.number
		Exit Sub
	End If	

	If (BuildList.Count > 0) Then
		Dim BuildArray()
		ReDim BuildArray( BuildList.Count )

		For i = 1 To BuildList.Count
			 BuildArray(i-1) = BuildList.Name(i)
		Next

		choices.AddItems(BuildArray)
	End If

End If
REM  *** Do not modify the predefined epilogue below this line ***


program:
REM  *** Do not modify the predefined prologue above this line ***

	If Check_Web() Then
		dim BuildValue
		BuildValue = GetFieldValue("Build").GetValue
		If (GetFieldValue("Build").GetValueStatus() <> AD_HAS_NO_VALUE) Then
			SetFieldValue "Log_Folder", ""
			InvalidateFieldChoiceList( "Log_Folder" )
			SetFieldValue "Log", ""
			InvalidateFieldChoiceList( "Log" )
		End If
	Else
		SetFieldValue "Log_Folder", ""
		InvalidateFieldChoiceList( "Log_Folder" )
		SetFieldValue "Log", ""
		InvalidateFieldChoiceList( "Log" )
	End If

REM  *** Do not modify the predefined epilogue below this line ***


program:
REM  *** Do not modify the predefined prologue above this line ***
On Error resume next	'handle repository login errors
err.clear

REM  *** Check to make sure that we have mastership locally before filling
REM  *** in the choice list
If NOT Check_RAProjectMaster Then
	choices.AddItem(GetFieldValue(fieldname).GetValue)
	exit sub
End If

if Valid_Project() Then
	Dim SelBuild
	Dim LogColPtr
	Dim LogFolderPtr
	Dim BuildPtr
	Dim SQAVar
	Dim SQASessionVar
	Dim TMSServer
	SQASessionVar = "SQAREPO"
	Set CQSession = GetSession
	' SetTTProject
	Set TMSServer = CQSession.NameValue(SQASessionVar)
	If (err.number <> 0) Then
		Exit Sub
	End If	

	Dim BuildField
	Dim BuildValue
	Dim LogFolderField
	Dim LogFolderValue
	Dim LogFolderColPtr
	
	Set BuildField = GetFieldValue("Build")
	BuildValue = BuildField.GetValue()
	Set LogFolderField = GetFieldValue("Log_Folder")
	LogFolderValue = LogFolderField.GetValue()
	
	If BuildField.GetValueStatus() = AD_HAS_VALUE Then
	   If LogFolderField.GetValueStatus() = AD_HAS_VALUE Then
	      Set BuildPtr = TMSServer.CreateBuild
		  Set BuildPtr = TMSServer.GetBuildByName( BuildValue )
	
		  Set LogFolderColPtr = BuildPtr.GetLogFolders
	      Set LogFolderPtr = BuildPtr.CreateLogFolder
	      Set LogFolderPtr = BuildPtr.GetLogFolder( LogFolderValue )
	      Set LogColPtr = LogFolderPtr.GetLogs
	
			If (LogColPtr.Count > 0) Then
				Dim LogArray()
				ReDim LogArray( LogColPtr.Count )
		
				For i = 1 To LogColPtr.Count
					 LogArray(i-1) = LogColPtr.Name(i)
				Next
		
				choices.AddItems(LogArray)
			End If

	   End If
	End If
End If
REM  *** Do not modify the predefined epilogue below this line ***


program:
'Test to see if this was entered via LogViewer;  If so, then allow the
  'field to be set.  Otherwise it is a readonly field.
 
 	dim CQSession
	Set CQSession = GetSession
	If ( CQSession.HasValue("_LogViewer_Mode") ) Then
	   	Test_Script_Permission = AD_OPTIONAL
    	Else								 
    		Test_Script_Permission = AD_READONLY
   End If


program:
REM  *** Do not modify the predefined prologue above this line ***
	'TestScript hook no longer being used
REM  *** Do not modify the predefined epilogue below this line ***


program:
REM  *** Do not modify the predefined prologue above this line ***

Dim CQSession
Dim VPValue

VPVar = "VPVAR"
Set CQSession = GetSession
If CQSession.HasValue(VPVar) Then
	VPValue = CQSession.NameValue(VPVar)
	SetFieldValue "Verification_Point",  VPValue
Else
	SetFieldValue "Verification_Point", ""
End If

REM  *** Do not modify the predefined epilogue below this line ***


program:
386 IBM PC Clone
486 IBM PC Clone
Pentium


program:
REM  *** Do not modify the predefined prologue above this line ***
On Error resume next	'handle repository login errors
err.clear

REM  *** Check to make sure that we have mastership locally before filling
REM  *** in the choice list
If NOT Check_RAProjectMaster Then
	choices.AddItem(GetFieldValue(fieldname).GetValue)
	exit sub
End If

if Valid_Project() Then
	Dim CQSession
	Dim SQASessionVar
	Dim TMSServer
	Set CQSession = GetSession
	SQASessionVar = "SQAREPO"

	Set TMSServer = CQSession.NameValue(SQASessionVar)

	Dim ComputerList
	Set ComputerList = TMSServer.Computers

	If (err.number <> 0) Then
		msgbox( "Could not access the TMS Computer objects")
		msgbox err.number
		Exit Sub
	End If	

	If (ComputerList.Count > 0) Then
		Dim ComputerArray()
		ReDim ComputerArray( ComputerList.Count )

		For i = 1 To ComputerList.Count
			 ComputerArray(i-1) = ComputerList.Name(i)
		Next

		choices.AddItems(ComputerArray)
	End If

End If
REM  *** Do not modify the predefined epilogue below this line ***


program:
Windows NT 4.0
Windows 2000
Solaris
HP-UX
AIX
Linux
Windows Millenium
Windows NT 3.51
Windows 95
Windows 98


program:
REM  *** Do not modify the predefined prologue above this line ***
On Error resume next	'handle repository login errors
err.clear

REM  *** Check to make sure that we have mastership locally before filling
REM  *** in the choice list
If NOT Check_RAProjectMaster Then
	choices.AddItem(GetFieldValue(fieldname).GetValue)
	exit sub
End If

if Valid_Project() Then
	Dim LogFolderColPtr
	Dim BuildPtr
	Dim SQAVar
	Dim SQASessionVar
	Dim TMSServer
	SQASessionVar = "SQAREPO"
	
	Set CQSession = GetSession
'	SetTTProject
	Set TMSServer = CQSession.NameValue(SQASessionVar)
	
	Dim BuildField
	Dim BuildValue
	
	Set BuildField = GetFieldValue("Build")
	BuildValue = BuildField.GetValue()
	
	If BuildField.GetValueStatus() = AD_HAS_VALUE Then
		Set BuildPtr = TMSServer.CreateBuild
		If (err.number <> 0) Then
			Exit Sub
		End If

		Set BuildPtr = TMSServer.GetBuildByName( BuildValue )
		Set LogFolderColPtr = BuildPtr.GetLogFolders

		If (LogFolderColPtr.Count > 0) Then
			Dim LogFolderArray()
			ReDim LogFolderArray( LogFolderColPtr.Count )
	
			For i = 1 To LogFolderColPtr.Count
				 LogFolderArray(i-1) = LogFolderColPtr.Name(i)
			Next
			choices.AddItems(LogFolderArray)
		End If

	End If
End If
REM  *** Do not modify the predefined epilogue below this line ***


program:
REM  *** Do not modify the predefined prologue above this line ***

	If Check_Web() Then
		dim LogFldValue
		LogFldValue = GetFieldValue("Log_Folder").GetValue
		If (GetFieldValue("Log_Folder").GetValueStatus() <> AD_HAS_NO_VALUE) Then	
			SetFieldValue "Log", ""
			InvalidateFieldChoiceList( "Log" )
		End If
	Else
		SetFieldValue "Log", ""
		InvalidateFieldChoiceList( "Log" )
	End If

REM  *** Do not modify the predefined epilogue below this line ***


program:
REM Return a non-empty string explaining why the action
   REM cannot commit with the current values.
   REM Or, if it is valid, return an empty string value.
   REM Example: 
   REM    Dim value_info
   REM    Set value_info = GetFieldValue("some field")
   REM    If Len(value_info.GetValue()) < 10 Then
   REM        Defect_Validation = "Must be at least 10 chars long"
   REM    End If

REM Checks if associations still exist with current CQ record when user tries to delete it
REM if none, deletion completed
REM if some, deletion canceled

	Dim a_CurrentActionType					'Action type of the action that initiated the execution of this script

	a_CurrentActionType = GetActionType()
   'Check to see if the real action is a delete action.
	'If not exit.
	if a_CurrentActionType = AD_DELETE then
		'Don't allow user to delete the current record unless no requirements are
		'associated with it
		Dim ac_sCQReqListAttName				'Name of the global variable containing the name of the field of the CQ record that stores associations
		Dim a_vTableDBIDs							'List of DBIDs of Req proxies associated to the current CQ record
	
		ac_sCQReqListAttName= "Requirements_List"
' RATLC00015495 
'		a_vTableReqIds = GetFieldValue(ac_sCQReqListAttName).GetValueAsList		
        a_vTableDBIDs = GetFieldValue(ac_sCQReqListAttName).GetValueAsList
		if IsEmpty(a_vTableDBIDs) then
'			EnhancementRequest_Validation = vbNullString		
		Defect_Validation = vbNullString		
		else
'			EnhancementRequest_Validation = "Rational RequisitePro/ClearQuest Integration: You have to remove all associations with RequisitePro requirements before you can delete the current ClearQuest record."	    	
			Defect_Validation = "Rational RequisitePro/ClearQuest Integration: You have to remove all associations with RequisitePro requirements before you can delete the current ClearQuest record."
		end if
	end if	'a_CurrentActionType


program:
REM Check the requirement type for its type guid
   REM Check the type of the current record type
   REM pull up a requirement map for this record type
   REM see if the requirement type guid is the same as the guid 
   REM for the requirement that is being added.
	
	' Get all the requirement types that this artifact can be associated to
	Dim session, reqList, listItem, tempReq, recordType
	
	Defect_Validation = ""
	Set session = GetSession
	recordType = GetEntityDefName

	Dim queryDef, queryField, operator, filterNode, resultSet
	Dim ac_sTagField
	Dim ac_sNameField
	
	ac_sTagField = "Tag"
	ac_sNameField = "Name"

	Set queryDef = session.BuildQuery("RequirementMap")
	If Not queryDef is Nothing then
	' Building the query
		queryField = queryDef.BuildField("RPReqTypeGUID")
		Set operator = queryDef.BuildFilterOperator(AD_COMP_OP_EQ)
		operator.BuildFilter "CQEntityDefName",	AD_COMP_OP_EQ, recordType
		Set resultSet = session.BuildResultSet(queryDef)
		resultSet.Execute()

		Dim found, tempGUID, counter, status, GUIDs

		Set GUIDs = CreateObject("Scripting.dictionary")

		found = False
		counter = 0
		status = resultSet.MoveNext
	'	build the requirement types GUIDs array
		Do While status = AD_SUCCESS 
			tempGUID = resultSet.GetColumnValue(1)
			GUIDs.Add counter, tempGUID
			counter = counter + 1
		 	status = resultSet.MoveNext
		 Loop 

	'	Retrieve all the requirements that are associated to the current artifact
		Dim tempReqList
		tempReqList = GetFieldValue("Requirements_List").GetValue	

		If tempReqList <> "" then
		'	Break the string of line feed separated requirement ids in to an array
			Dim array ' array of requirements
			Dim u ' number of elements in the array
			Dim result
			result = ""
		'	Splitting it
		  	array = Split(Cstr(tempReqList),vbLF)
			u = UBound(array)
			Dim ReqId, requirement, reqTypeGUID
		'	Check if the requirement's type is in the list of allowed requirement GUIDs list
			For i = 0 To u
				found = False
				ReqId = array(i)
			'	Get the requirement
				Set requirement = session.GetEntity("Requirement", ReqId)
				If Not requirement Is Nothing Then
					Dim fieldDef 
				'	Get the requirement type
					reqTypeGUID = requirement.GetFieldValue("Type_GUID").GetValue
				'	Check to see if the GUID is matching with the existing list
					For j = 0 to GUIDs.count
						If GUIDs.Item(j) <> "" Then
							If GUIDs.Item(j) = reqTypeGUID Then
							'	Found it so dont need to loop anymore
								found = True
								Exit For
							End If
						Else
							'	Valid guid's are done so skip
							Exit For
						End If
					Next

				End If
			'	Create the erroneous list of requirements

				If Not found Then
					Dim sReq
					Dim sName
					
					sName = requirement.GetFieldValue(ac_sNameField).GetValue
					sReq = requirement.GetFieldValue(ac_sTagField).GetValue
					' Limiting the name length to about 30 characters for display
					if len(sName) = 0 then
						result = result & vbLF & sReq
					elseif len(sText) > 33 then
						result = result & vbLF & sReq & ": " & left(sName, 30) + "..."
					else
						result = result & vbLF & sReq & ": " & sName
					end if
				end if				
			Next
			'	Check to see if the erroneous list of requirements is empty or not
			If result <> "" Then
			'	if the list is not empty create the error message.
				Defect_Validation = "The following Requirements types dont match " & result
			End If
		End If

	End If


program:
dim bProjExists
	dim bWeb

	On Error resume next	' handle repository login errors
	err.clear
    bWeb = Check_Web()
	bProjExists = Valid_Project()

	' *** Do not perform any operations if we do not have branch mastership.
	if (NOT Check_RAProjectMaster AND NOT bWeb) then
		Defect_Build_Properties = "Mastership Failure - This operation is not currently available at this site."
		exit Function
	end if

	' Do not continue unless a project has been selected and the defect is editable
	If (bProjExists AND IsEditable AND NOT bWeb) Then
		Dim CQSession
		Dim TMSSServer
		Dim SQASessionVar
		Dim AssetEditorPtr
		SQASessionVar = "SQAREPO"
		AssetEditorVar = "ASSETEDITOR"

		Set CQSession = GetSession
		' SetTTProject
		Set TMSServer = CQSession.NameValue(SQASessionVar)

		Dim SelectedBuild
		Dim BuildField
		Dim BuildPtr
		
		Set BuildField = GetFieldValue("Build")	

		If BuildField.GetValueStatus() = AD_HAS_VALUE Then
			SetAssetEditor
			Set AssetEditorPtr = CQSession.NameValue(AssetEditorVar)
			err.clear
			Set BuildPtr = TMSServer.CreateBuild
			' Invalid repo connection?  Just drop outta here
			If (err.number <> 0) Then
				msgbox "Create Build Failed!"
				Exit Function
			End If
			SelectedBuild = BuildField.GetValue()

			Set BuildPtr = TMSServer.GetBuildByName( SelectedBuild )
			If err.number = 0 Then
				dim ret_sts
				dim BuildPropSheet
				Set BuildPropSheet = AssetEditorPtr.CreateBuildPropertySheet()
				BuildPropSheet.Caption = "Build Properties"
				BuildPropSheet.ParentWindow = 0
				ret_sts = BuildPropSheet.Show(BuildPtr, TMSServer)

				InvalidateFieldChoiceList( "Log_Folder" )	' User could have added new values
			Else
				err.clear
				Defect_Build_Properties = "This is an invalid build name.  Cannot display properties."
			End If
		End If
  	End If


program:
On Error resume next	'handle repository login errors
	err.clear

	dim bProjExists
	dim bWeb
	bWeb = Check_Web()
	bProjExists = Valid_Project()

	' *** Do not perform any operations if we do not have branch mastership.
	if (NOT Check_RAProjectMaster AND NOT bWeb) then
		Defect_Comparator = "Mastership Failure - This operation is not currently available at this site."
		exit Function
	end if

	' Do not continue unless a project has been selected and the defect is editable
	If (bProjExists AND IsEditable AND NOT bWeb) Then 
	 	Dim DefectID
		Dim DefectField
		Dim CQSession
		Dim TMSServer
		Dim AssetEditorPtr
		Dim SQASessionVar
		SQASessionVar = "SQAREPO"
		AssetEditorVar = "ASSETEDITOR"
		
		Set CQSession = GetSession
		Set TMSServer = CQSession.NameValue(SQASessionVar)
		If (err.number <> 0) Then
			Exit Function
		End If
		SetAssetEditor
		Set AssetEditorPtr = CQSession.NameValue(AssetEditorVar)
				
		DefectID = GetFieldValue("id").GetValue()
		call AssetEditorPtr.ViewVerificationPointFromDefect(DefectID, TMSServer)
	End If


program:
dim bProjExists
	dim bWeb

	On Error resume next	'handle repository login errors
	err.clear
    bWeb = Check_Web()
	bProjExists = Valid_Project()

	' *** Do not perform any operations if we do not have branch mastership.
	if (NOT Check_RAProjectMaster AND NOT bWeb) then
		Defect_Fixed_Build_Properties = "Mastership Failure - This operation is not currently available at this site."
		exit Function
	end if

	' Do not continue unless a project has been selected and the defect is editable
	If (bProjExists AND IsEditable AND NOT bWeb) Then
		Dim CQSession
		Dim TMSSServer
		Dim SQASessionVar
		Dim AssetEditorPtr
		SQASessionVar = "SQAREPO"
		AssetEditorVar = "ASSETEDITOR"

		Set CQSession = GetSession
		' SetTTProject
		Set TMSServer = CQSession.NameValue(SQASessionVar)

		Dim SelectedBuild
		Dim BuildField
		Dim BuildPtr
		
		Set BuildField = GetFieldValue("Fixed_In_Build")	
		If BuildField.GetValueStatus() = AD_HAS_VALUE Then
			SetAssetEditor
			Set AssetEditorPtr = CQSession.NameValue(AssetEditorVar)
			err.clear
			Set BuildPtr = TMSServer.CreateBuild
			' Invalid repo connection?  Just drop outta here
			If (err.number <> 0) Then
				msgbox "Create Build Failed!"
				Exit Function
			End If
			SelectedBuild = BuildField.GetValue()

			Set BuildPtr = TMSServer.GetBuildByName( SelectedBuild )
			If err.number = 0 Then
				dim ret_sts
				dim BuildPropSheet
				Set BuildPropSheet = AssetEditorPtr.CreateBuildPropertySheet()
				BuildPropSheet.Caption = "Fixed in Build Properties"
				BuildPropSheet.ParentWindow = 0
				ret_sts = BuildPropSheet.Show(BuildPtr, TMSServer)
			Else
				err.clear
				Defect_Fixed_Build_Properties = "This is an invalid build name.  Cannot display properties."
			End If
		End If
  	End If


program:
on error resume next
  	RSEM_FieldsChoices choices


program:
on error resume next
	RSEM_FieldsChoices choices


program:
Dim session
	Dim entity_names

	on error resume next

 	set session = GetSession
	
	' The choice list should include all entity types that have
	' been enabled for any version of the Email package.

	Set packages = session.GetEnabledPackageRevs
	For each pack in packages
		pkgName = pack.PackageName()
		pkgRev = pack.RevString()
		if pkgName = "Email" Then
	 		Set pkgRevs = session.GetEnabledEntityDefs(pkgName, pkgRev)
			For each entityDef in pkgRevs
				choices.AddItem(entityDef.GetName)
			Next
		End If
	Next

	choices.sort


program:
my $session = $entity->GetSession();

	# The choice list should include all entity types that have
	# been enabled for any version of the Email package.
	my $packagerevs = $session->GetEnabledPackageRevs();
	for (my $x=0; $x < $packagerevs->Count(); $x++){
		  my $pack = $packagerevs->Item($x);
		  my $packageName = $pack->GetPackageName();
		  next unless ($packageName eq "Email");

		  my $revString = $pack->GetRevString();

		  my $edefs = $session->GetEnabledEntityDefs($packageName, $revString);

		  for (my $y=0; $y < $edefs->Count(); $y++){
		    my $edef = $edefs->Item($y);
		    my $name = $edef->GetName();
		    push(@choices, $name);
		}
	}

	 @choices = sort(@choices);


program:
Dim session, allReqEntities, ruleRecordType
	Set session = GetSession

    SetFieldValue "Change_Fields",""
    SetFieldValue "Display_Fields",""
	SetFieldValue "Subject_Fields",""

	 allReqEntities = session.GetReqEntityDefNames
	 ruleRecordType = GetFieldValue("Entity_Def").GetValue()
	 for each req in allReqEntities
			If req = ruleRecordType Then
				SetFieldValue "Subject_Fields", "id"
			End If
	Next


program:
my $session, $ruleRecordType, $lastEnt, $eptr, $i;
	$session = $entity->GetSession();

	$entity->SetFieldValue("Change_Fields", "");
    $entity->SetFieldValue("Display_Fields", "");
	$entity->SetFieldValue("Subject_Fields", "");

	$eptr = $session->GetReqEntityDefNames();
	$lastEnt = $$eptr[-1];  # last entity in the array
	$ruleRecordType = $entity->GetFieldValue("Entity_Def")->GetValue();
	$i = 0;
	do {
		 if($$eptr[$i] eq $ruleRecordType) {
			 $entity->SetFieldValue("Subject_Fields", "id");
		 }
	} until($$eptr[$i++] eq $lastEnt);


program:
Dim Value

	on error resume next
	Value = GetFieldValue(fieldname).GetValue()

	if Value = 1 then
		SetFieldRequirednessForCurrentAction "Display_Fields", AD_READONLY
	else
		SetFieldRequirednessForCurrentAction "Display_Fields", AD_OPTIONAL
	end if


program:
my $value;

	 $value = $entity->GetFieldValue($fieldname)->GetValue();

	 if ($value == 1) {
		 $entity->SetFieldRequirednessForCurrentAction("Display_Fields", $CQPerlExt::CQ_READONLY);
	 } else {
		 $entity->SetFieldRequirednessForCurrentAction("Display_Fields", $CQPerlExt::CQ_OPTIONAL);
	 }


program:
dim values	
	dim sess
	dim ws

	On Error Resume Next

	set sess = GetSession

	set ws = sess.GetWorkSpace
	values = ws.GetUneditedQueries(1)

	if IsArray(values) then
		for idx = lbound(values) to ubound(values)
			choices.additem values(idx)
		next
	end if


program:
my $eMail;
	 my $values;
	 my $session = $entity->GetSession();
	
	 $eMail = CQEmailRules::Build(); 
    if (!defined($eMail) || ref($eMail) ne 'CQEmailRules') {
	   $session->OutputDebugMessage ("!!! Filter_Query_Choicelist: Object eMail is invalid");
		return (-1);
 	 }

	 $eMail->SetSession($session);	
	 $values = $eMail->GetPublicQueries();
 	 if ($values){
	 	@choices =  @$values;
	}


program:
on error resume next
	RSEM_ActionsChoices choices


program:
on error resume next
	RSEM_ActionTypesChoices choices


program:
on error resume next
	RSEM_StatesChoices choices


program:
'Only Super Users and Schema Designers are allowed this action
	  Email_Rule_AccessControl = RSEM_CheckAccess(username)


program:
# Only Super Users and Schema Designers are allowed this action
	  return RSEM_CheckAccess($username);


program:
REM do any setup for the action here
	set	session = GetSession
	session.OutputDebugString "Email_Maintenance: Initialization" & vbcrlf
	set fldObj = GetFieldValue ("Operator_Value")
	if fldObj.GetValueStatus = AD_HAS_VALUE then
		session.OutputDebugString "Operator has value; it's " & fldObj.GetValue & vbcrlf
	else
		session.OutputDebugString "Operator does NOT have a value, setting it to 0" & vbcrlf
		SetFieldValue "Operator_Value", 0
	end if


program:
On Error resume next	'handle repository login errors
	err.clear

	dim bProjExists
	dim bWeb 
	bProjExists = Valid_Project()
	bWeb = Check_Web()

	' *** Do not perform any operations if we do not have branch mastership.
	if (NOT Check_RAProjectMaster AND NOT bWeb) then
		Defect_Log_Properties = "Mastership Failure - This operation is not currently available at this site."
		exit Function
	end if

	' Do not continue unless a project has been selected and the defect is editable
	If (bProjExists AND IsEditable AND NOT bWeb) Then
		Dim CQSession
		Dim TMSServer
		Dim SQASessionVar
		Dim AssetEditorPtr
		Dim LogFolderPtr
		Dim LogPtr
		Dim BuildPtr
	
		SQASessionVar = "SQAREPO"
		AssetEditorVar = "ASSETEDITOR"
		
		Set CQSession = GetSession
		' SetTTProject
		Set TMSServer = CQSession.NameValue(SQASessionVar)
		
		Dim SelectedBuild
		Dim BuildField
		Dim SelectedLogFolder
		Dim LogFolderField
		Dim SelectedLog
		Dim LogField
		
		Set BuildField = GetFieldValue("Build")
		Set LogFolderField = GetFieldValue("Log_Folder")
		Set LogField = GetFieldValue("Log")
	
		If BuildField.GetValueStatus() = AD_HAS_VALUE Then
			If LogFolderField.GetValueStatus() = AD_HAS_VALUE Then
				If LogField.GetValueStatus() = AD_HAS_VALUE Then
					SetAssetEditor
					Set AssetEditorPtr = CQSession.NameValue(AssetEditorVar)
					SelectedBuild = BuildField.GetValue()
					SelectedLogFolder = LogFolderField.GetValue()
					SelectedLog = LogField.GetValue()
	
					Set BuildPtr = TMSServer.CreateBuild
					' Invalid repo connection?  Just drop outta here
					If (err.number <> 0) Then
						Exit Function
					End If
					Set BuildPtr = TMSServer.GetBuildByName(SelectedBuild)
					If err.number <> 0 Then
						err.clear
						Defect_Log_Properties = "This is an invalid build name.  Cannot display properties."
						Exit Function
					Else	
						Set LogFolderPtr = BuildPtr.CreateLogFolder
	     				Set LogFolderPtr = BuildPtr.GetLogFolder( SelectedLogFolder )

						If err.number <> 0 Then
							err.clear
							Defect_Log_Properties = "This is an invalid log folder name.  Cannot display properties."			
							Exit Function
						Else			
							Set LogPtr = LogFolderPtr.CreateLog
							Set LogPtr = LogFolderPtr.GetLog( SelectedLog )
							If err.number = 0 Then
								dim ret_sts
								dim LogPropSheet
								Set LogPropSheet = AssetEditorPtr.CreateLogPropertySheet()
								LogPropSheet.Caption = "Log Properties"
								LogPropSheet.ParentWindow = 0
								ret_sts = LogPropSheet.Show(LogPtr, TMSServer)
							Else
								err.clear
								Defect_Log_Properties = "This is an invalid log name.  Cannot display properties."
							End If	
						End If
					End If
			   End If	
			End If
		End If
	End If


program:
On Error resume next	'handle repository login errors
	err.clear
	
	dim bProjExists
	dim bWeb
	bWeb = Check_Web()
	bProjExists = Valid_Project()

	' *** Do not perform any operations if we do not have branch mastership.
	if (NOT Check_RAProjectMaster AND NOT bWeb) then
		Defect_Open_Script = "Mastership Failure - This operation is not currently available at this site."
		exit Function
	end if

	' Do not continue unless a project has been selected and the defect is editable
	If (bProjExists AND IsEditable AND NOT bWeb) Then
		Dim CQSessiom
		Dim TMSServer
		Dim SQASessionVar
		Dim AssetEditorPtr
		SQASessionVar = "SQAREPO"
		AssetEditorVar = "ASSETEDITOR"
		
		Dim Test_Script_ID_Field
		Set Test_Script_ID_Field = GetFieldValue("Test_Script_ID")	
		If (Test_Script_ID_Field.GetValueStatus() = AD_HAS_VALUE  AND Valid_Project()) Then

			Set CQSession = GetSession
			Set TMSServer = CQSession.NameValue(SQASessionVar)
		
			Dim SelectedScript
			Dim ScriptField

			Dim ScriptID
			Dim Script_SourceUID
		
			Set ScriptID = GetFieldValue("Test_Script_ID")
			Script_SourceUID = GetFieldValue("Test_Source_UID").GetValue()
		
			If ScriptID.GetValueStatus() = AD_HAS_VALUE Then
				SetAssetEditor
				Set AssetEditorPtr = CQSession.NameValue(AssetEditorVar)
				SelectedScript = ScriptID.GetValue()
				call AssetEditorPtr.OpenTestScript( SelectedScript, Script_SourceUID, TMSServer)

				If (err.number <> 0) Then
					Defect_Open_Script = "This is an invalid script name.  Cannot open this script."
				End If				
			End If ' ScriptID.GetValueStatus() = AD_HAS_VALUE

		End If ' (Test_Script_ID.GetValueStatus() = AD_HAS_VALUE  AND Valid_Project())

	End If ' (bProjExists AND IsEditable AND NOT bWeb)


program:
On Error resume next	'handle repository login errors
	err.clear
	
	dim bProjExists
	dim bWeb
	bWeb = Check_Web()
	bProjExists = Valid_Project()

	' *** Do not perform any operations if we do not have branch mastership.
	if (NOT Check_RAProjectMaster AND NOT bWeb) then
		Defect_Script_Properties = "Mastership Failure - This operation is not currently available at this site."
		exit Function
	end if

	' Do not continue unless a project has been selected and the defect is editable
	If (bProjExists AND IsEditable AND NOT bWeb) Then
		Dim CQSessiom
		Dim TMSServer
		Dim SQASessionVar
		Dim AssetEditorPtr
		SQASessionVar = "SQAREPO"
		AssetEditorVar = "ASSETEDITOR"
		
		Set CQSession = GetSession
		Set TMSServer = CQSession.NameValue(SQASessionVar)
		
		Dim SelectedScript
		Dim ScriptField

		Dim ScriptID
		Dim Script_SourceUID
		
		Set ScriptID = GetFieldValue("Test_Script_ID")
		Script_SourceUID = GetFieldValue("Test_Source_UID").GetValue()
		
		If ScriptID.GetValueStatus() = AD_HAS_VALUE Then
			SetAssetEditor
			Set AssetEditorPtr = CQSession.NameValue(AssetEditorVar)
			SelectedScript = ScriptID.GetValue()
			call AssetEditorPtr.ShowTestScriptProperties( SelectedScript, Script_SourceUID, TMSServer )

			If (err.number <> 0) Then
				Defect_Script_Properties = "This is an invalid script name.  Cannot display test script properties."
				msgbox err.number
			End If				
		End If
	End If


program:
On Error resume next	' handle repository login errors
	err.clear

	dim bProjExists
	dim bWeb
	bProjExists = Valid_Project()
	bWeb = Check_Web()

	' *** Do not perform any operations if we do not have branch mastership.
	if (NOT Check_RAProjectMaster AND NOT bWeb) then
		Defect_VP_Properties = "Mastership Failure - This operation is not currently available at this site."
		exit Function
	end if

	' Do not continue unless a project has been selected and the defect is editable
	If (bProjExists AND IsEditable AND NOT bWeb) Then
		Dim DefectID
		Dim DefectField
		Dim CQSession
		Dim TMSServer
		Dim AssetEditorPtr
		Dim SQASessionVar
		SQASessionVar = "SQAREPO"
		AssetEditorVar = "ASSETEDITOR"
		
		Set CQSession = GetSession
		' SetTTProject
		Set TMSServer = CQSession.NameValue(SQASessionVar)	
		SetAssetEditor
		Set AssetEditorPtr = CQSession.NameValue(AssetEditorVar)
				
		DefectID = GetFieldValue("id").GetValue()
		call AssetEditorPtr.ViewVPPropertiesFromDefect(DefectID, TMSServer)
		If (err.number <> 0) Then
			Exit Function
		End If
	End If


program:
On Error resume next	' handle repository login errors
	err.clear
	
	dim bProjExists
	dim bDisplayProperties
	bDisplayProperties = TRUE	' Assume TRUE unless otherwise set
	dim bWeb
	bWeb = Check_Web()
	bProjExists = Valid_Project()

	' *** Do not perform any operations if we do not have branch mastership.
	if (NOT Check_RAProjectMaster AND NOT bWeb) then
		Defect_Test_Input_Properties = "Mastership Failure - This operation is not currently available at this site."
		exit Function
	end if

	' Do not continue unless a project has been selected and the defect is editable
	If (bProjExists AND IsEditable AND NOT bWeb) Then
		Dim CQSessiom
		Dim TMSServer
		Dim SQASessionVar
		Dim AssetEditorPtr
		SQASessionVar = "SQAREPO"
		AssetEditorVar = "ASSETEDITOR"
		
		Set CQSession = GetSession
		Set TMSServer = CQSession.NameValue(SQASessionVar)
		
		Dim SelectedNode
		Dim SourceUID
		Dim StrElm
		Dim TestInputDBID
		Dim EntityPtr

		For Each StrElm in Param.ListSelection
			TestInputDBID = StrElm
		Next

		If (NOT IsNull(TestInputDBID) ) AND (NOT IsEmpty( TestInputDBID)) Then
			Set EntityPtr = CQSession.GetEntitybyDBid("TestInput", TestInputDBID)
			SelectedNode = EntityPtr.GetFieldValue("Test_Input_ID").GetValue()
			SourceUID = EntityPtr.GetFieldValue("Source_UID").GetValue()

			SetAssetEditor
			Set AssetEditorPtr = CQSession.NameValue(AssetEditorVar)
			call AssetEditorPtr.ShowTestInputProperties( SelectedNode, SourceUID, TMSServer)
		Else
			bDisplayProperties = FALSE
		End If

		If (NOT bDisplayProperties) Then
			Defect_Test_Input_Properties = "There are no test inputs selected.  Cannot display properties."
		End If				
	End If


program:
dim bWeb

	On Error resume next	' handle repository login errors
	err.clear
    bWeb = Check_Web()

	' *** Do not perform any operations if we do not have branch mastership.
	if (NOT Check_RAProjectMaster AND NOT bWeb) then
		Defect_Test_Input_Selector = "Mastership Failure - This operation is not currently available at this site."
		exit Function
	end if

	' Do not continue unless a project has been selected and the defect is editable
	If (IsEditable AND (NOT bWeb) AND Valid_Project()) Then
		Dim CQSession
		Dim TMSServer
		Dim SQASessionVar
		Dim AssetSelectorPtr
		SQASessionVar = "SQAREPO"
		AssetSelectorVar = "ASSETSELECT"

		If Valid_Project Then

			Set CQSession = GetSession
			' SetTTProject
			Set TMSServer = CQSession.NameValue(SQASessionVar)


			SetAssetSelector
			Set AssetSelectorPtr = CQSession.NameValue(AssetSelectorVar)
			err.clear
			dim TestCaseDlgPtr
			Set TestCaseDlgPtr = AssetSelectorPtr.CreateTestInputSelectionDialog

			If err.number = 0 Then
				dim ret_sts
				dim TestInputCount
				TestCaseDlgPtr.Caption = "TestCase Input Selection"
				TestCaseDlgPtr.ParentWindow = 0
				ret_sts = TestCaseDlgPtr.Show(TMSServer)

				TestInputCount = TestCaseDlgPtr.GetSelCount			
				If TestInputCount > 0 Then
					dim TestInputObject
					dim TestInputKey
					dim TestInputsCol
					Set TestInputsCol = TestCaseDlgPtr.GetSelTestInputs()
					If TestInputsCol.Count > 0 Then

						dim Item
						Set Item  = TestInputsCol.Item(1)
						dim TheName
						dim TheNode
						dim TheUID
						TheName = Item.Name
						TheNode = Item.NodeID
						TheUID = Item.SourceUID

						set TestInputObject = CQSession.BuildEntity("TestInput")
						TestInputObject.SetFieldValue "Test_Input_Name", TheName
						TestInputObject.SetFieldValue "Test_Input_ID", THENode
						TestInputObject.SetFieldValue "Source_UID", THEUID
						TestInputKey = TestInputObject.GetFieldValue("dbid").GetValue()

						ret_sts = TestInputObject.Validate
						ret_sts = TestInputObject.Commit
						Set TestInputObject = Nothing
						AddFieldValue "Test_Input_List", TestInputKey
					End If
				End If

			Else
				err.clear
				Defect_Test_Input_Selector = "Cannot display Test Input Selection Dialog."
			End If
		End If ' Project is valid
  	End If ' (IsEditable AND NOT bWeb)


program:
REM add your hook code here
	Dim bWeb
	Dim bConfigured
	On Error resume next	'handle repository login errors
	err.clear
    bWeb = Check_Web()
	bConfigured = FALSE ' Assume non-configured test case first

	' *** Do not perform any operations if we do not have branch mastership.
	if (NOT Check_RAProjectMaster AND NOT bWeb) then
		Defect_TestCase_Properties = "Mastership Failure - This operation is not currently available at this site."
		exit Function
	end if

	' Do not continue unless a project has been selected and the defect is editable
	If (IsEditable AND NOT bWeb) Then
		Dim CQSession
		Dim TMSSServer
		Dim SQASessionVar
		Dim AssetEditorPtr
		SQASessionVar = "SQAREPO"
		AssetEditorVar = "ASSETEDITOR"

		Dim TC_UID_Field
		Set TC_UID_Field = GetFieldValue("Test_Case_UID")	
		If (TC_UID_Field.GetValueStatus() = AD_HAS_VALUE  AND Valid_Project()) Then
			Set CQSession = GetSession
			Set TMSServer = CQSession.NameValue(SQASessionVar)

			SetAssetEditor
			Set AssetEditorPtr = CQSession.NameValue(AssetEditorVar)
			err.clear
			dim AssetPtr

			dim ret_sts
			dim TestCasePropSheet
			dim TC_UID
			TC_UID = GetFieldValue("Test_Case_UID").GetValue()

			Set AssetPtr = TMSServer.GetTestCase(TC_UID)

			If (err.number <> 0) Then
				err.clear	' Assume error because this is a configured test case
				bConfigured = TRUE
				Set AssetPtr = TMSServer.GetConfiguredTestCase(TC_UID)
				Set TestCasePropSheet = AssetEditorPtr.CreateConfiguredTestCasePropertySheet
			Else
				Set TestCasePropSheet = AssetEditorPtr.CreateTestCasePropertySheet
			End If

			' Invalid repo connection?  Just drop outta here
			If (err.number <> 0) Then
				msgbox "Could not access this test case."
				Exit Function
			End If

	
			TestCasePropSheet.Caption = "TestCase Properties"
			TestCasePropSheet.ParentWindow = 0
			ret_sts = TestCasePropSheet.Show( AssetPtr, TMSServer)

			if (err.number <> 0) Then
				Defect_TestCase_Properties = "This is an invalid test asset.  Cannot display properties."
			End If

		End If ' TC_UID_Field is not blank
	
	End If   ' (IsEditable AND NOT bWeb)


program:
REM add your hook code here
	dim bWeb

	On Error resume next	' handle repository login errors

	err.clear
    bWeb = Check_Web()

	' *** Do not perform any operations if we do not have branch mastership.
	if (NOT Check_RAProjectMaster AND NOT bWeb) then
		Defect_TestCase_Selector = "Mastership Failure - This operation is not currently available at this site."
		exit Function
	end if

	' Do not continue unless a project has been selected and the defect is editable
	If (IsEditable AND (NOT bWeb) AND Valid_Project()) Then
		Dim CQSession
		Dim TMSServer
		Dim SQASessionVar
		Dim AssetSelectorPtr
		SQASessionVar = "SQAREPO"
		AssetSelectorVar = "ASSETSELECT"
		
		If (Valid_Project) Then
			Set CQSession = GetSession
			Set TMSServer = CQSession.NameValue(SQASessionVar)

			SetAssetSelector
			Set AssetSelectorPtr = CQSession.NameValue(AssetSelectorVar)
			err.clear
			dim TestCaseDlgPtr
			Set TestCaseDlgPtr = AssetSelectorPtr.CreateTestCaseSelectionDialog

			If err.number = 0 Then
				dim ret_sts
				dim count
				TestCaseDlgPtr.Caption = "TestCase Selection"
				TestCaseDlgPtr.ParentWindow = 0
				ret_sts = TestCaseDlgPtr.SetAllowConfiguredTC( 1 )
				ret_sts = TestCaseDlgPtr.SetAllowTestCase( 1 )
				ret_sts = TestCaseDlgPtr.Show(TMSServer)
		
				If ret_sts = 1 Then
					Dim pTestCase 
					Set pTestCase = TestCaseDlgPtr.GetSelTestCases()

					Dim pAssetConfCol
					Set pAssetConfCol = TestCaseDlgPtr.GetSelConfiguredTestCases()

					Dim ItemUID
					Dim TMSObject
					Dim ItemName
					Dim ItemType

					If IsObject(pTestCase) Then
				    	If (pTestCase.count > 0) Then
				        	ItemUID = pTestCase.GetValue(1)
				        	Set TMSObject = TMSServer.GetTestCase(ItemUID)
				        	ItemName = TMSObject.Name
							SetFieldValue "Test_Case", ItemName
							SetFieldValue "Test_Case_UID", ItemUID         
				    	End If
					End If

					If IsObject(pAssetConfCol) Then
				    	If (pAssetConfCol.count > 0) Then
				    	    ItemUID = pAssetConfCol.GetValue(1)
	    	   	    	    Set TMSObject = TMSServer.GetConfiguredTestCase(ItemUID)
				    	    ItemName = TMSObject.Name
							SetFieldValue "Test_Case", ItemName
							SetFieldValue "Test_Case_UID", ItemUID
	       		    	End If
					End If
				End If	' Else Selection dialog canceled
			Else
				err.clear
				Defect_TestCase_Selector = "Cannot display TestCase Selection Dialog."
			End If
		End If  ' If (Valid_Project)
  	End If


program:
REM add your hook code here

REM Launch RequisitePro Association dialog box, with list of Req Proxy DBIDs of Requirements already associated to current CQ record
REM if return of call is OK
REM	Position state of state machine to "MODIFIED"
REM if return of call is Cancel


	Dim eRet_Empty
	Dim eRet_OK
	Dim eRet_Cancel
	Dim eRet_Error
	Dim ac_sCQReqListAttName				'Name of the global variable containing the name of the field of the CQ record that stores associations
	Dim ac_sCQIStateVar						'Name of the global variable containing the current state of the state machine
	Dim ac_sCQIListReqsVar					'Name of the global variable containing the list of Proxy Req DBIDs associated to the current CQ record
	Dim ac_sCQIdbidSeparator				'Character used to separate dbids in string list 
	Dim a_bWeb									'Web or not
	Dim a_bIsRunningIntegration			'Contains a boolean indicating if the integration is already in progress, to prevent reccurence
	Dim a_bProjectSet							'Contains a boolean indicating if a Rational Project has been selected for the current CQ record
	Dim a_oCQSession							'Current CQ session
	Dim a_oRequisiteProTool					'Reference to a ASCQIIntegration.RequisiteProTool instance
	Dim a_sListReqDBIDs						'List of Req Proxy DBIDs associated to the current CQ record
	Dim a_eRet									'Contains value returned by the call to integration
	Dim a_sError								'Error message sent back by integration in case of a failure
	Dim a_vTableDBIDs							'List of DBIDs of Req proxies associated to the current CQ record
	Dim a_lIndex
	Dim a_sFail									'Return value of the creation of the association in ClearQuest between current CQ record and the Req Proxy

	eRet_Empty = 0
	eRet_OK = 1
	eRet_Cancel = 2
	eRet_Error = 3	

	ac_sCQReqListAttName= "Requirements_List"	
	ac_sCQIStateVar = "CQIState"
	ac_sCQIListReqsVar = "CQIReqs"
	ac_sCQIdbidSeparator = ","
	
	a_bWeb = Check_Web()

	' RATLC01009865 - Display message for non-functional button in CQWeb
	if a_bWeb then
		' Need this Error handler otherwise it does not work from CQWeb.
		On Error resume next
	 	err.clear

		Defect_CQI_Select_Req = "This operation is not available in the Web client."
		return
	end if	


   'This script must no be launched through the web
	'We also test if the record is editable
	If (IsEditable AND NOT a_bWeb) Then

		if Check_RAProjectMaster then
			a_bIsRunningIntegration = CQI_IsRunningIntegration()
			if not a_bIsRunningIntegration then
				a_bProjectSet = Check_Project()
				if a_bProjectSet then
				 	Set a_oCQSession = GetSession
					if not a_oCQSession is nothing then
						set a_oRequisiteProTool = CQI_GetRequisiteProTool()	
						if a_oRequisiteProTool is nothing then
							msgbox "ClearQuest could not connect to the Integration Server." + vbcrlf + "Please contact your Administrator.", vbOKOnly + vbCritical, "Rational RequisitePro/ClearQuest Integration"
						else
							' RATLC01201983 - Do not use list of requirements when beginning to modify the record.
							' instead use the current list of requirements
							' a_sListReqDBIDs = a_oCQSession.NameValue(ac_sCQIListReqsVar)
							a_vTableDBIDs = getfieldValue(ac_sCQReqListAttName).GetValueAsList
							if not IsEmpty(a_vTableDBIDs) then
								CQI_GetListFromDBIDTable a_vTableDBIDs, ac_sCQIdbidSeparator, a_sListReqDBIDs
							end if   ' a_vTableDBIDs

							a_eRet = a_oRequisiteProTool.AssociateFromClearQuest(me, ac_sCQReqListAttName, a_sListReqDBIDs, a_sError)
							Select Case a_eRet
							   	Case eRet_OK
									a_oCQSession.NameValue(ac_sCQIStateVar)= "MODIFIED" 
									if a_sListReqDBIDs <> vbNullString then
										a_vTableDBIDs = empty
										if CQI_GetTableFromDBIDList(a_sListReqDBIDs, ac_sCQIdbidSeparator, a_vTableDBIDs) then
											if not IsEmpty(a_vTableDBIDs) then
												for a_lIndex = LBound(a_vTableDBIDs) to UBound(a_vTableDBIDs)
											        a_sFail = AddFieldValue(ac_sCQReqListAttName, cstr(a_vTableDBIDs(a_lIndex)))
													if a_sFail = vbNullString then
														call CQI_AddDBIDToList(cstr(a_vTableDBIDs(a_lIndex)), ac_sCQIdbidSeparator)
													end if	'a_sFail
												next
											end if
										end if
									end if
				
						      Case eRet_Cancel

								Case Else		
									msgbox a_sError ,vbOKOnly + vbCritical, "Rational RequisitePro/ClearQuest Integration"
				
							End Select
						end if	'a_oRequisiteProTool
					end if	'a_oCQSession
				else
					if GetEntityDefName = "EnhancementRequest" and GetActionType = AD_SUBMIT then
						msgbox "In order to associate a requirement, you must first submit the EnhancementRequest record.", vbOKOnly + vbInformation, "Rational RequisitePro/ClearQuest Integration"
					else 						
						MsgBox "A valid RAProject must be selected.", vbOKOnly + vbInformation, "Rational RequisitePro/ClearQuest Integration"
					end if
				end if	'a_bProjectSet
			else								  
				msgbox "Modification (or viewing) of Requirement properties cannot be done at this point, as the Clearquest information is currently displayed from RequisitePro. Please access the Requirement Properties dialog from RequisitePro.", vbOKOnly + vbInformation, "Rational RequisitePro/ClearQuest Integration" 
			end if	'a_bIsRunningIntegration

		else								  
			msgbox "This ClearQuest/RequisitePro integration operation is not supported. This ClearQuest record is associated with a Rational project that is not accessible from your local area network.", vbOKOnly + vbInformation, "Rational RequisitePro/ClearQuest Integration" 
		end if	'Check_RAProjectMaster
	end if	'a_bWeb

	set a_oRequisiteProTool = nothing
	set a_oCQSession = nothing


program:
REM add your hook code here

REM Launch RequisitePro Properties dialog box for the selected Requirement in the CQ list box, and pass its DBID 
REM if return of call is ePrp_OK
REM	Nothing is done
REM if return of call is ePrp_Removed
REM	then the requirement is removed fromlist of requirement associated with current CQ record

	On Error resume next	'handle ListSelection empty
	err.clear

	Dim a_bWeb									'Web or not
	Dim a_bIsRunningIntegration			'Contains a boolean indicating if the integration is already in progress, to prevent reccurence
	Dim a_oCQSession							'Current CQ session
	Dim a_lNumberSel							'Number of Requirements currently selected in the CQ List Box
	Dim a_sStrElm								'CQ Key of the Req Proxy selected in the CQ List Box (currently dbid)
	Dim a_sDBID									'DBID of the Req Proxy selected in the CQ List Box
	Dim a_bEmpty								'Boolean indicationg wether or not a Req Proxy is selected in the CQ List Box
	Dim a_sError								'Error message sent back by integration in case of a failure
	Dim a_sFail									'Return value of the deletion of the association in ClearQuest between current CQ record and the Req Proxy
 	dim a_oReq									' selected Requirement record
	Dim vRet									' Generic return value
	Dim ac_sCQReqListAttName
	
	ac_sCQReqListAttName= "Requirements_List"

	a_bWeb = Check_Web()

	' RATLC01009865 - Display message for non-functional button in CQWeb
	if a_bWeb then
		Defect_CQI_Properties_Req = "You cannot view a requirement from this record in the Web client. Open the requirement record and select View."
		return
	end if	

   'This script must not be launched through the web
	'We also test if the record is editable
	If (IsEditable AND NOT a_bWeb) Then
		a_bIsRunningIntegration = CQI_IsRunningIntegration()
		if not a_bIsRunningIntegration then
		 	Set a_oCQSession = GetSession
			if not a_oCQSession is nothing then
				if Check_Eclipse() then
					' Handle the selection differently for CQ Eclipse.
					' param = string of selected DBIDs separated by Line Feed.
					Dim sParam 
					Dim bGotOne

					sParam = cstr(param)
					bGotOne = false
					' There is an extra LF added at the end of every DBID 
					' even for one selection. The code below handles both the 
					' cases, with and without the last LF.
					if len(sParam) > 1 then
					    If InStrRev(sParam, vbLf) = Len(sParam) Then
					    	If InStrRev(Left(sParam, Len(sParam) - 1), vbLf) = 0 Then
					            ' There is an extra LF at the end of the string
					            a_sDBID = Left(sParam, Len(sParam) - 1)
					            bGotOne = True
					        End If
					    Else
					        If InStrRev(sParam, vbLf) = 0 Then
					            a_sDBID = sParam
					            bGotOne = True
					        End If
					    End If
					End If

					if bGotOne then
						set a_oReq = a_oCQSession.GetEntity("Requirement", a_sDBID)
						if not a_oReq is nothing then
							vRet = a_oReq.FireNamedHook("CQI_Properties_Req", "")
							set a_oReq = nothing
						end if
					else
						MsgBox "Please select one requirement in the list view to get the properties.", vbOKOnly + vbInformation, "Rational RequisitePro/ClearQuest Integration"
					end if
				else
					a_lNumberSel = 0
					For Each a_sStrElm In param.ListSelection
						a_sDBID = a_sStrElm
						a_lNumberSel = a_lNumberSel + 1
					Next
					a_bEmpty = IsNull(a_sDBID) or IsEmpty(a_sDBID)
					if a_bEmpty then
						'Nothing to do
						MsgBox "Please select one requirement in the list view to get the properties.", vbOKOnly + vbInformation, "Rational RequisitePro/ClearQuest Integration"
					else
		on error goto 0
						if a_lNumberSel = 1 then
	 						set a_oReq = a_oCQSession.GetEntity("Requirement", a_sDBID)
	 						if not a_oReq is nothing then
	 							vRet = a_oReq.FireNamedHook("CQI_Properties_Req", "")
	 						end if
	 				   	else
							MsgBox "Please select one requirement in the list view to get the properties.", vbOKOnly + vbInformation, "Rational RequisitePro/ClearQuest Integration"
						end if
					end if	'a_bEmpty
				end if ' Check_Eclipse()

				' RATLC01011263 - If the Requirement is deleted from RP. Prompt user to remove the association 
				if vRet = "DELETED" then
					vRet = Msgbox ("The requirement has been deleted in Rational RequisitePro." _
									+ vbcrlf+ "Do you want to remove the association?", _
									vbYesNo + vbQuestion, _
									"Rational RequisitePro/ClearQuest Integration")
					if vRet = vbYes then
						DeleteFieldValue ac_sCQReqListAttName, a_sDBID
					end if
				end if

			end if	'a_oCQSession
		else								  
			msgbox "Modification (or viewing) of Requirement properties cannot be done at this point, as the Clearquest information is currently displayed from RequisitePro. Please access the Requirement Properties dialog from RequisitePro.", vbOKOnly + vbInformation, "Rational RequisitePro/ClearQuest Integration" 
		end if	'a_bIsRunningIntegration
	end if	'a_bWeb

	set a_oReq = nothing
	set a_oCQSession = nothing


program:
REM add your hook code here

REM Refreshes the Requirement proxies of associated Requirements in the CQ list box
 	On Error resume next
 	err.clear

	Dim ac_sCQReqListAttName				'Name of the global variable containing the name of the field of the CQ record that stores associations
	Dim ac_sCQIdbidSeparator				'Character used to separate dbids in string list 
	Dim a_bWeb								'Web or not
	Dim a_bIsRunningIntegration				'Contains a boolean indicating if the integration is already in progress, to prevent reccurence
	Dim a_oCQSession						'Current CQ session
	Dim a_oRequisiteProTool					'Reference to a ASCQIIntegration.RequisiteProTool instance
	Dim a_sListReqDBIDs						'List of Req Proxy DBIDs associated to the current CQ record
	Dim a_vTableDBIDs						'List of DBIDs of Req proxies associated to the current CQ record
	Dim a_sError							'Error message sent back by integration in case of a failure
	Dim a_sDBIDtoRemove						'List of DBIDs of Req proxies associated to the current CQ record to remove because they don't exist anymore
	Dim a_sDBID								'DBIDs to remove
 	Dim a_oCurReq
	 dim ac_sRequirement
 	Dim ac_sReqRefreshAction
	ac_sRequirement = "Requirement" 
	ac_sReqRefreshAction = "Refresh"					  

	ac_sCQReqListAttName= "Requirements_List"	
	ac_sCQIdbidSeparator = ","

	a_bWeb = Check_Web()

	' RATLC01009865 - Display message for non-functional button in CQWeb
	if a_bWeb then
		Defect_CQI_Refresh_Req = "You cannot refresh requirements from this record in the Web client. Open the requirement record and select Refresh."
		return
	end if	

   'This script must no be launched through the web
	'We also test if the record is editable, it should be as we are in an initialization hook
	If (IsEditable AND NOT a_bWeb) Then
		if Check_RAProjectMaster then
			a_bIsRunningIntegration = CQI_IsRunningIntegration()
			if not a_bIsRunningIntegration then
			 	Set a_oCQSession = GetSession
				if not a_oCQSession is nothing then
					set a_oRequisiteProTool = CQI_GetNewReqProTool()
					if a_oRequisiteProTool is nothing then
						msgbox "ClearQuest could not connect to the Integration Server." + vbcrlf + "Please contact your Administrator.", vbOKOnly + vbCritical, "Rational RequisitePro/ClearQuest Integration"
					else
						a_sError = me.Validate
						if a_sError <> vbNullString then
							MsgBox a_sError, vbOKOnly + vbInformation, _
									"Rational RequisitePro/ClearQuest Integration"
							
							if not a_oRequisiteProTool.Unload(a_sError) then
								Msgbox a_sError, vbOKOnly + vbCritical, "Rational RequisitePro/ClearQuest Integration"
	 						end if
							
							exit function
						end if

						a_vTableDBIDs = getfieldValue(ac_sCQReqListAttName).GetValueAsList
						if not IsEmpty(a_vTableDBIDs) then
 							Dim sRAProjectName
							Dim sRPProjectPath
							Dim sUserName 
							Dim sPassWord
							Dim sRequirementGUID
							dim bGotLogonInfo

							sRAProjectName = me.GetFieldValue("RAProject").GetValue
							sRPProjectPath = CQI_GetRPProjectFromRA(sRAProjectName)
							bGotLogonInfo = CQI_RPlogon(sRPProjectPath, sUserName, sPassword)
							if not bGotLogonInfo then
								if not a_oRequisiteProTool.Unload(a_sError) then
									Msgbox a_sError, vbOKOnly + vbCritical, "Rational RequisitePro/ClearQuest Integration"
		 						end if
								set a_oCQSession = nothing
							 	set a_oCurReq = nothing
							 	set a_oRequisiteProTool = nothing
								exit function
							end if

							if (LBound(a_vTableDBIDs) <= UBound(a_vTableDBIDs)) Then
								For a_lIndex = LBound(a_vTableDBIDs) To UBound(a_vTableDBIDs)
									bRefreshed = a_oRequisiteProTool.RefreshReqFromPlaceholder (GetSession(), _
															cstr(a_vTableDBIDs(a_lIndex)), _
															sRPProjectPath, _
															sUserName, _
															sPassword, _
															a_sError)
									if len (a_sError) <> 0 then
									 	MsgBox "Could not Refresh Requirement - " + a_oCurReq.GetFieldValue("Tag").GetValue + ":" + a_oCurReq.GetFieldValue("Name").GetValue + _
													vbcrlf + "Error: " + vbcrlf + a_sError, _
													vbOKOnly + vbInformation, _
													"Rational RequisitePro/ClearQuest Integration"
										err.clear	
									end if
	
								Next
							end if	'Bound vTable()
 						end if	'a_vTableDBIDs

						if not a_oRequisiteProTool.Unload(a_sError) then
							Msgbox a_sError, vbOKOnly + vbCritical, "Rational RequisitePro/ClearQuest Integration"
 						end if
					end if	'a_oRequisiteProTool
				end if	'a_oCQSession
			end if	'a_bIsRunningIntegration
		else

			msgbox "This ClearQuest/RequisitePro integration operation is not supported. This ClearQuest record is associated with a Rational project that is not accessible from your local area network.", vbOKOnly + vbInformation, "Rational RequisitePro/ClearQuest Integration" 
		end if	'Check_RAProjectMaster

	end if	'a_bWeb

	set a_oCQSession = nothing
 	set a_oCurReq = nothing
 	set a_oRequisiteProTool = nothing


program:
Function CQI_GetRPProjectFromRA ( sRAProjectName  ) 'as string
	Dim oRAProject 
    	Dim a_oQueryFilterNode 
    	Dim a_oResultset 
	Dim oSession
	Dim sRPProjectPath
	Dim lRecords
	Dim lStatus
    
	CQI_GetRPProjectFromRA = ""

	Set oSession = GetSession
	set oRAProject = oSession.GetEntity("RAProject", sRAProjectName)
 	if not oRAProject is nothing then
 		CQI_GetRPProjectFromRA = oRAProject.GetFieldValue("RPProjectPath").GetValue
 	end if	
	
    Set oRAProject = Nothing
	Set oSession = Nothing
End Function


program:
Function CQI_GetRefreshTool() 'as ASCQIIntegration.RefreshTool
Dim a_oCQSession			        'Current CQ session
	dim a_oConnector					  'Reference to a ASCQIIntegration.Connector instance
	dim a_oIntegration				  'Reference to a ASCQIIntegration.Integration instance
	dim a_oRefreshTool	        'Reference to a ASCQIIntegration.RefreshTool instance
	dim ac_sRefreshToolVar     'Name of session variable containing the Tool that initiate the action						
	dim a_bGotIt

	ac_sRefreshToolVar = "CQIRefreshTool"

	set CQI_GetRefreshTool = nothing
	Set a_oCQSession = GetSession
	if not a_oCQSession is nothing then
		a_bGotIt = false
		
		If a_oCQSession.HasValue(ac_sRefreshToolVar) Then
			set CQI_GetRefreshTool = a_oCQSession.NameValue(ac_sRefreshToolVar)
			a_bGotIt = true
		end if	'ac_sRequisiteProToolVar
		
		if not a_bGotIt then
			Set a_oConnector = CreateObject("ASCQIIntegration.Connector")
			if a_oConnector is nothing then
				msgbox "ClearQuest could not connect to the Integration Server." + vbcrlf + "Please contact your Administrator.", vbOKOnly + vbCritical, "Rational RequisitePro/ClearQuest Integration"
			else
				Set a_oIntegration = a_oConnector.GetUniqueInstance
				if a_oIntegration is nothing then
					msgbox "ClearQuest could not connect to the Integration Server." + vbcrlf + "Please contact your Administrator.", vbOKOnly + vbCritical, "Rational RequisitePro/ClearQuest Integration"
				else
					set a_oRefreshTool = a_oIntegration.GetRefreshTool
					if a_oRefreshTool is nothing then
						msgbox "ClearQuest could not connect to the Integration Server." + vbcrlf + "Please contact your Administrator.", vbOKOnly + vbCritical, "Rational RequisitePro/ClearQuest Integration"
					else
						a_oCQSession.NameValue(ac_sRefreshToolVar) = a_oRefreshTool
						set CQI_GetRefreshTool = a_oRefreshTool
					end if	'a_oRefreshTool
				end if	'a_oIntegration
			end if	'a_oConnector
		end if	'a_bGotIt		
	end if	'a_oCQSession

	set a_oConnector = nothing
	set a_oIntegration = nothing
	set a_oRefreshTool = nothing
	set a_oCQSession = nothing
end function


program:
Sub SetTTProject()
	' Resets the SQA Repository Connection if the project has changed
	' This is the same as ChangeTTProject except that this does not clear
	' the integration fields after resetting the project.

	On Error resume next	'handle repository login errors
	err.clear	
	Dim ProjVar
	Dim RepoPathVar
	Dim Session
	Dim TTProject
	Dim TTRepo
	Dim SQAVar
	Dim SQARepo
	Dim bProject
	Dim DefectIDVar
	bProject = Check_Project()

	ProjVar = "TTPROJ"
	ProjValid = "PROJVALID"
	RepoPathVar = "TTREPOPATH"
	SQAVar = "SQAREPO"
	DefectIDVar = "DEFECTID"
	Set Session = GetSession
	Dim RepoValid
	RepoValid = "REPOVALID"
	Dim bValidRepo
	bValidRepo = Session.NameValue(RepoValid)
	

	If Session.HasValue(ProjVar) Then
		TTProject = Session.NameValue(ProjVar)
		TTRepo = Session.NameValue(RepoPathVar)
		Set SQARepo = Session.NameValue(SQAVar)
		Dim bsProject
		bsProject =  GetFieldValue("RAProject.Name").GetValue()

		Dim bsRepoPath
		bsRepoPath = GetFieldValue("RAProject.RA_Project_Path").GetValue()
		Session.NameValue(RepoPathVar) = bsRepoPath

		If (bsRepoPath = TTRepo) AND (bValidRepo = TRUE) Then
			' The user has selected the same repo so use cached info.
			InvalidateTTFields
		else
			If bProject Then	' Is a project selected
				If (Valid_Project()) Then
					call SQARepo.Logout()
				End If

				Session.NameValue(RepoValid) = False
				Session.NameValue(ProjValid) = False
				SetSQARepo
			else ' No project is selected
			 ' Do nothing (no project is selected - don't kill cached value)
			 ' Check_Project will not allow hook code to fire in this case.
			End If ' if (bProject)

		End If ' if Session.HasValue(ProjVar)

	Else	 ' First time through so just login
		Session.NameValue(ProjValid) = False
		SetSQARepo
		InvalidateTTFields
   End If
End Sub


program:
Sub SetSQARepo()
	' Sets the SQA Repository Global Variable if it hasn't been set
	On Error resume next	'handle repository login errors
	err.clear

	Dim SQAVar
	Dim Session
	Dim SQARepo
	Dim ProjVar
	Dim RepoPathVar
	Dim TTProject
	Dim TTRepo
	Dim RepoValid
	Dim bRepoExists
	
	ProjVar = "TTPROJ"
	RepoPathVar = "TTREPOPATH"
	SQAVar = "SQAREPO"
	RepoValid = "REPOVALID"
	Set Session = GetSession

	' RepoValid is set to False when changing to a new project into a new
	' repository.  This case is handled the same as the initial case 
	' where there is no repostitory set yet.
	bRepoExists = False
	If Session.HasValue(RepoValid) Then
 		If Session.NameValue(RepoValid) Then
			Set SQARepo = Session.NameValue(SQAVar)
			bRepoExists = True
		Else
			bRepoExists = False
		End If
	End If


	If bRepoExists = False Then
		' Ensure that there is a TT Repository before trying to connect
		dim ProjField	  
		dim ProjStatus
		Set ProjField = GetFieldValue("RAProject.RA_Project_Path")
		ProjStatus = ProjField.GetValueStatus()

		If ProjStatus = AD_HAS_VALUE Then
			Set SQARepo = nothing
			Session.NameValue(SQAVar) = ""

			Set SQARepo = CreateObject("TMSServer.TMSServer")
			if (err.number <> 0) Then
				msgbox "Cannot create the TMS COM Server" 
				msgbox err.number
				Exit Sub
			End If	

			Session.NameValue(SQAVar) = SQARepo

			Dim bsProject
			bsProject = GetFieldValue("RAProject.Name").GetValue()
	
			Dim bsRepoPath
			bsRepoPath = GetFieldValue("RAProject.RA_Project_Path").GetValue()
			Session.NameValue(RepoPathVar) = bsRepoPath
			Session.NameValue(ProjVar) = bsProject
			Dim bsUserID
			bsUserID = Session.GetUserLoginName
			Dim bsPasswordEncrypted
			bsPasswordEncrypted = Session.GetUserEncryptedPassword
			SetAssetEditor
	 		Dim AssetEditorPtr
			AssetEditorVar = "ASSETEDITOR"
			Set AssetEditorPtr = Session.NameValue(AssetEditorVar)		

			If Check_Web() Then
				call AssetEditorPtr.RSLoginFromClearQuestWeb(bsRepoPath, bsUserID, bsPasswordEncrypted, SQARepo)
			Else
				call AssetEditorPtr.RSLoginFromClearQuest(bsRepoPath, bsUserID, bsPasswordEncrypted, SQARepo)
			End If

			' Check to make sure that the project we just logged in to has
			' an associated datastore before enabling.
			dim bsDataPath
			bsDataPath = SQARepo.DatastorePath

			'If no problems with the login, then set the valid project global variable
			Dim ProjValid
			ProjValid = "PROJVALID"
			If (err.number = 0) AND NOT (bsDataPath = "") Then
				Session.NameValue(ProjValid) = True
				Session.NameValue(RepoValid) = True
			Else
				Session.NameValue(ProjValid) = False
				Session.NameValue(RepoValid) = False
			End If
		End If
	End If

End Sub


program:
Sub SetAssetSelector()
	'Sets the SQA Asset Selector if it hasn't already been set
	
	Dim AssetSelector
	Dim SelectorVar
	Dim Session

 	SelectorVar = "ASSETSELECT"
	Set Session = GetSession

	If Session.HasValue(SelectorVar) Then
		Set AssetSelector = Session.NameValue(SelectorVar)
	Else
		Set AssetSelector = CreateObject("tmsui.TMSAssetSelector")
		Session.NameValue(SelectorVar) = AssetSelector
	End If
End Sub


program:
Sub SetAssetEditor() 
	' Sets the SQA Asset Editor Global Variable if it hasn't been set 

Dim AssetEditor
Dim AssetVar
Dim Session

AssetVar = "ASSETEDITOR"
Set Session = GetSession

If Session.HasValue(AssetVar) Then
	Set AssetEditor = Session.NameValue(AssetVar)
Else
	Set AssetEditor = CreateObject("tmsui.TMSAssetEditor")
	Session.NameValue(AssetVar) = AssetEditor
End If

End Sub


program:
Sub ClearTTFields()
' Clear the values of the TeamTest Integration fields

	dim ProjValue
	dim bProjChanged
	ProjValue = GetFieldValue("RAProject").GetValue 

	' The following block is used to check to see whether the TeamTest or the 
	' RequisitePro packages have been installed by checking for particular fields
	' that they would have loaded.  This avoids accessing them if they do not exist.
	Dim NameList, bReqProPackage, bTTPackage
	NameList = GetFieldNames
	bReqProPackage = FALSE
	bTTPackage = FALSE
   For Each item In NameList
      If (item = "Requirements_List") Then
			bReqProPackage = TRUE
      End If
      If (item = "Build") Then
			bTTPackage = TRUE
      End If
   Next


	' For Web UI, make sure field really changed first!
	If Check_Web() Then
		If (GetFieldValue("RAProject").GetValueStatus() <> AD_HAS_NO_VALUE) Then
			If (bReqProPackage = TRUE) Then ' Clear the Requirements List
					SetFieldValue "Requirements_List", ""
			End If
			If (bTTPackage = TRUE) Then  ' Clear and Initialize TeamTest fields
				SetFieldValue "Build", ""
				SetFieldValue "Log_Folder", ""
				SetFieldValue "Log", ""
				SetFieldValue "Test_Script", ""
				SetFieldValue "Verification_Point", ""
				SetFieldValue "Hardware", ""
				SetFieldValue "Fixed_In_Build", ""
				SetFieldValue "Requirement", ""
				SetFieldValue "Requirement_ID", -1
				SetFieldValue "Test_Case", ""
				SetFieldValue "Operating_System", ""
				SetFieldValue "Computer", ""		 
				InvalidateTTFields
			End If
		End If
	Else 'Running from CQ Client
		If (bReqProPackage = TRUE) Then ' Clear the Requirements List
				SetFieldValue "Requirements_List", ""
		End If
		If (bTTPackage = TRUE) Then  ' Clear and Initialize TeamTest fields
			SetFieldValue "Build", ""
			SetFieldValue "Log_Folder", ""
			SetFieldValue "Log", ""
			SetFieldValue "Test_Script", ""
			SetFieldValue "Verification_Point", ""
			SetFieldValue "Hardware", ""
			SetFieldValue "Fixed_In_Build", ""
			SetFieldValue "Requirement", ""
			SetFieldValue "Requirement_ID", -1
			SetFieldValue "Test_Case", ""
			SetFieldValue "Operating_System", ""
			SetFieldValue "Computer", ""
			InvalidateTTFields
		End If
	End If

End Sub


program:
Function Check_Web
	dim Sess

	Set Sess = GetSession
	Check_Web = Sess.HasValue("_CQ_WEB_SESSION")
End Function


program:
Function Check_Project()
	'Checks to see if the project has been properly set
dim ProjField
dim ProjStatus
set ProjField = GetFieldValue("RAProject")
ProjStatus = ProjField.GetValueStatus()
If ProjStatus = AD_HAS_NO_VALUE Then
	Check_Project = FALSE
Else
	Check_Project = TRUE
End If

End Function


program:
Sub ChangeTTProject()
	' Resets the SQA Repository Connection if the project has changed
	'The only difference between this and SetTTProject is that this
	'routine clears the integration fields after changing the project 

	On Error resume next	' handle repository login errors
	err.clear
	Dim ProjVar
	Dim RepoPathVar
	Dim Session
	Dim TTProject
	Dim TTRepo
	Dim SQAVar
	Dim SQARepo
	Dim bProject
	Dim DefectIDVar
	bProject = Check_Project()	 


	ProjVar = "TTPROJ"
	ProjValid = "PROJVALID"
	RepoPathVar = "TTREPOPATH"
	SQAVar = "SQAREPO"
	DefectIDVar = "DEFECTID"
	Set Session = GetSession
	Dim RepoValid
	RepoValid = "REPOVALID"
	Dim bValidRepo
	bValidRepo = Session.NameValue(RepoValid)

	If Session.HasValue(ProjVar) Then
		TTProject = Session.NameValue(ProjVar)
		TTRepo = Session.NameValue(RepoPathVar)
		Set SQARepo = Session.NameValue(SQAVar)
		Dim bsProject
		bsProject =  GetFieldValue("RAProject.Name").GetValue()

		Dim bsRepoPath
		bsRepoPath = GetFieldValue("RAProject.RA_Project_Path").GetValue()
		Session.NameValue(RepoPathVar) = bsRepoPath

		If (bsRepoPath = TTRepo) AND (bValidRepo = TRUE) Then
			' The user has selected the same repo so use cached info.
			InvalidateTTFields
		else
			ClearTTFields

			If Valid_Project() Then
				call SQARepo.Logout()
			End If

			Session.NameValue(RepoValid) = False
			Session.NameValue(ProjValid) = False
			' Invalidate current Repo
			If bProject Then	' Don't get a new repo if they selected no project
				SetSQARepo
			End If
		End If
	Else	 ' First time through so just login
		Session.NameValue(ProjValid) = False
		SetSQARepo
		InvalidateTTFields
   End If

End Sub


program:
Function Valid_Project()
	' Checks to see if this project is a valid TeamTest Project

Set Session = GetSession
ProjValid = "PROJVALID"
Dim bValid
If Session.HasValue(ProjValid) Then
	bValid = Session.NameValue(ProjValid)
Else bValid = False
End If


If Check_Project() AND bValid Then
	Valid_Project = TRUE
Else
	Valid_Project = FALSE
End If

End Function


program:
Sub UpdateRequirement()
	On Error resume next	'handle repository login errors
	err.clear
	dim ProjectField
	dim ProjectStatus
	set ProjectField = GetFieldValue("RAProject")
	ProjectStatus = ProjectField.GetValueStatus()
	if ProjectStatus = AD_HAS_VALUE then
		
		Dim CQSession
		Dim SQASession
		Dim SQARepositoryRootPtr
		Dim SQASessionVar
		SQASessionVar = "SQAREPO"
		
		Set CQSession = GetSession
		Set SQASession = CQSession.NameValue(SQASessionVar)
		' Set SQARepositoryRootPtr = SQASession.SQARepositoryRoot
		
		Dim ReqIDField
		Dim ReqID
		
		Set ReqIDField = GetFieldValue("Requirement_ID")
		If ReqIDField.GetValueStatus() = AD_HAS_NO_VALUE Then
			ReqID = -1
		Else
			ReqID = ReqIDField.GetValue()
		End If
		'Needs to be rewritten to support the TMS Input Selection objects
		If ReqID > 0 Then
			Dim SQAProjectPtr
			Dim AssetEditorPtr
			Dim AssetEditorVar
			Dim ReqDescription
			AssetEditorVar = "ASSETEDITOR"
	
			Set SQAProjectPtr = SQARepositoryRootPtr.CurrentProject
			if (err.number <> 0) Then
				Exit Sub
			End If

			SetAssetEditor
			Set AssetEditorPtr = CQSession.NameValue(AssetEditorVar)
			ReqDescription = " "
			call AssetEditorPtr.GetRequirementFromDBKey( ReqID, SQAProjectPtr, ReqDescription)
			SetFieldValue "Requirement", Left(ReqDescription, 254)
		End If
	End If
End Sub


program:
Function CQI_RPLogon(sRPProject, sUsername, sPassword) 'as boolean
	Dim a_oCQSession			        'Current CQ session
	dim a_oRPLogonDlg	        	'Reference to a ASCQIIntegration.RefreshTool instance
	dim a_bGotIt
	dim bWeb

	dim ac_sRPProjectPrefix
	dim ac_sRPUsernamePrefix
	dim ac_sRPPasswordPrefix

	dim ac_lOK		' return code if RP Logon dlg OK button is pressed
	ac_lOK = 2

	ac_sUsernamePrefix = "CQI_RPUsernameVar_"
	ac_sPasswordPrefix = "CQI_RPPasswordVar_"

	CQI_RPLogon = false

	Set a_oCQSession = GetSession
	if not a_oCQSession is nothing then
		
		If a_oCQSession.HasValue(ac_sUsernamePrefix + sRPProject) and _
				a_oCQSession.HasValue(ac_sPasswordPrefix + sRPProject) Then
			sUsername = a_oCQSession.NameValue(ac_sUsernamePrefix + sRPProject)
			sPassword = a_oCQSession.NameValue(ac_sPasswordPrefix + sRPProject)
			CQI_RPLogon = true
		else 
			bWeb = Check_Web()
			if not bWeb then
				Set a_oRPLogonDlg = CQI_GetRPLogonDlg()
			
				a_oRPLogonDlg.ShowDialog (sRPProject)
			
				if a_oRPLogonDlg.ReturnCode = ac_lOK then
					sUsername = a_oRPLogonDlg.Username
					sPassword = a_oRPLogonDlg.Password
			
					' set the session variable to use next time
					a_oCQSession.NameValue(ac_sUsernamePrefix + sRPProject) = sUsername
					a_oCQSession.NameValue(ac_sPasswordPrefix + sRPProject) = sPassword
			
					CQI_RPLogon = true
				end if 
			end if    ' bWeb
		end if
	end if	'a_oCQSession

	set a_oRPLogonDlg = nothing
	set a_oCQSession = nothing
end function


program:
REM TODO -- put your script code here
function CQI_GetRPLogonDlg() 
	On Error resume next
	err.clear

	Dim a_oCQSession			        'Current CQ session
	dim a_oConnector					  'Reference to a ASCQIIntegration.Connector instance
	dim a_oIntegration				  'Reference to a ASCQIIntegration.Integration instance
	dim a_oRPLogonDlg	        'Reference to a ASCQIIntegration.RequisiteProTool instance
	dim ac_sRPLogonDlgVar     'Name of session variable containing the Tool that initiate the action						
	dim a_bGotIt
	Dim ac_StateCompVar
 	Dim bWeb

	ac_sRPLogonDlgVar = "CQI_RPLogonDlg"	

	set CQI_GetRPLogonDlg = nothing

	bWeb = Check_Web()
	
	Set a_oCQSession = GetSession
	if not a_oCQSession is nothing then
		a_bGotIt = false
		' Disable caching the instance due to problems in CQ Eclipse with sharing instances from diff threads
		' If a_oCQSession.HasValue(ac_sRPLogonDlgVar) Then
		' 	set CQI_GetRPLogonDlg = a_oCQSession.NameValue(ac_sRPLogonDlgVar)
		' 	a_bGotIt = true
		' end if	
		if not a_bGotIt then
			Set a_oConnector = CreateObject("ASCQIIntegration.Connector")
			if a_oConnector is nothing OR Err.Number <> 0 then
 				if bWeb then
 					Err.Raise 1, "Rational RequisitePro/ClearQuest Integration", "ClearQuest could not connect to the Integration Server." + vbcrlf + "Please contact your Administrator."
 					exit function
 				end if
				msgbox "ClearQuest could not connect to the Integration Server." + vbcrlf + "Please contact your Administrator.", vbOKOnly + vbCritical, "Rational RequisitePro/ClearQuest Integration"
			else
				Set a_oIntegration = a_oConnector.GetUniqueInstance
				if a_oIntegration is nothing OR Err.Number <> 0 then
 					if bWeb then
 						Err.Raise 1, "Rational RequisitePro/ClearQuest Integration", "ClearQuest could not connect to the Integration Server." + vbcrlf + "Please contact your Administrator."
 						exit function
 					end if
					msgbox "ClearQuest could not connect to the Integration Server." + vbcrlf + "Please contact your Administrator.", vbOKOnly + vbCritical, "Rational RequisitePro/ClearQuest Integration"
				else
					set a_oRPLogonDlg = a_oIntegration.GetRPLogonDlg
					if a_oRPLogonDlg is nothing OR Err.Number <> 0 then
 						if bWeb then
 							Err.Raise 1, "Rational RequisitePro/ClearQuest Integration", "ClearQuest could not connect to the Integration Server." + vbcrlf + "Please contact your Administrator."
 							exit function
 						end if
						msgbox "ClearQuest could not connect to the Integration Server." + vbcrlf + "Please contact your Administrator.", vbOKOnly + vbCritical, "Rational RequisitePro/ClearQuest Integration"
					else
						' Disable caching the instance due to problems in CQ Eclipse with sharing instances from diff threads
						' a_oCQSession.NameValue(ac_sRPLogonDlgVar) = a_oRPLogonDlg
						set CQI_GetRPLogonDlg = a_oRPLogonDlg
					end if	'a_oRPLogonDlg
				end if	'a_oIntegration
			end if	'a_oConnector
		end if	'a_bGotIt		
	end if	'a_oCQSession

	set a_oConnector = nothing
	set a_oIntegration = nothing
	set a_oRPLogonDlg = nothing
	set a_oCQSession = nothing

end function


program:
REM TODO -- put your script code here
function CQI_Web_ValidateRPLogon() ' as string on error 
	Dim a_oCQSession			        'Current CQ session
	dim a_oRPLogonDlg	        	'Reference to a ASCQIIntegration.RefreshTool instance

	dim ac_sCQiWebLogon_RPProjectPath
	dim ac_sCQiWebLogon_RPUsername
	dim ac_sCQiWebLogon_RPPassword

	dim sRPProjectPath
	dim sRPUsername
	dim sRPPassword

	dim ac_sRPProjectPrefix
	dim ac_sRPUsernamePrefix
	dim ac_sRPPasswordPrefix

	dim sError

	' Prefix used to cache username passwords
	ac_sUsernamePrefix = "CQI_RPUsernameVar_"
	ac_sPasswordPrefix = "CQI_RPPasswordVar_"

	Set a_oCQSession = GetSession
 	' sesssion variables used by CQ Web to store RP login information
	ac_sCQiWebLogon_RPProjectPath = "CQI_Web_RPProjectPath"
	ac_sCQiWebLogon_RPUsername = "CQI_Web_RPUsername"
	ac_sCQiWebLogon_RPPassword = "CQI_Web_RPPassword" 

	sRPProjectPath = a_oCQSession.NameValue(ac_sCQiWebLogon_RPProjectPath)
	sRPUsername = a_oCQSession.NameValue(ac_sCQiWebLogon_RPUsername)
	sRPPassword = a_oCQSession.NameValue(ac_sCQiWebLogon_RPPassword)

	if not a_oCQSession is nothing then
		Set a_oRPLogonDlg = CQI_Web_GetRPLogonDlg(sError)
		if a_oRPLogonDlg is nothing then
			CQI_Web_ValidateRPLogon = sError
		else
			if a_oRPLogonDlg.TestRPLogon_Silent( sRPProjectPath, sRPUsername, sRPPassword, sError) then
				' set the session variable to use next time
				a_oCQSession.NameValue(ac_sUsernamePrefix + sRPProjectPath) = sRPUsername
				a_oCQSession.NameValue(ac_sPasswordPrefix + sRPProjectPath) = sRPPassword
			else
				CQI_Web_ValidateRPLogon = sError
			end if
		end if
	end if	'a_oCQSession

	set a_oRPLogonDlg = nothing
	set a_oCQSession = nothing

end function


program:
REM Gets the RPLogonDlg for a web session. This does not display any msg box on error
function CQI_Web_GetRPLogonDlg(sError) 
	Dim a_oCQSession			        'Current CQ session
	dim a_oConnector					  'Reference to a ASCQIIntegration.Connector instance
	dim a_oIntegration				  'Reference to a ASCQIIntegration.Integration instance
	dim a_oRPLogonDlg	        'Reference to a ASCQIIntegration.RequisiteProTool instance
	dim ac_sRPLogonDlgVar     'Name of session variable containing the Tool that initiate the action						
	dim a_bGotIt
	Dim ac_StateCompVar

	ac_sRPLogonDlgVar = "CQI_RPLogonDlg"	

	set CQI_Web_GetRPLogonDlg = nothing
	 	Set a_oCQSession = GetSession
	if not a_oCQSession is nothing then
		a_bGotIt = false
		If a_oCQSession.HasValue(ac_sRPLogonDlgVar) Then
			set CQI_Web_GetRPLogonDlg = a_oCQSession.NameValue(ac_sRPLogonDlgVar)
			a_bGotIt = true
		end if	
		if not a_bGotIt then
			Set a_oConnector = CreateObject("ASCQIIntegration.Connector")
			if a_oConnector is nothing then
				sError = "ClearQuest could not connect to the Integration Server." + vbcrlf + "Please contact your Administrator."
			else
				Set a_oIntegration = a_oConnector.GetUniqueInstance
				if a_oIntegration is nothing then
					sError = "ClearQuest could not connect to the Integration Server." + vbcrlf + "Please contact your Administrator."
				else
					set a_oRPLogonDlg = a_oIntegration.GetRPLogonDlg
					if a_oRPLogonDlg is nothing then
						sError = "ClearQuest could not connect to the Integration Server." + vbcrlf + "Please contact your Administrator."
					else
						a_oCQSession.NameValue(ac_sRPLogonDlgVar) = a_oRPLogonDlg
						set CQI_Web_GetRPLogonDlg = a_oRPLogonDlg
					end if	'a_oRPLogonDlg
				end if	'a_oIntegration
			end if	'a_oConnector
		end if	'a_bGotIt		
	end if	'a_oCQSession

	set a_oConnector = nothing
	set a_oIntegration = nothing
	set a_oRPLogonDlg = nothing
	set a_oCQSession = nothing

end function


program:
REM TODO -- put your script code here
 REM - Meant to be called from a Requirement record to check for a valid RA Project
 REM and to make sure that the current site has mastership of the ReqPro project
 REM i.e check mastership of the RA Project (= mastership of RP Project)
 function CQI_CheckRPProjectMaster(sRAProjectName,  sError) ' as boolean
 	dim oRAPrj
	dim oSession
	Set oSession = GetSession  	
	CQI_CheckRPProjectMaster = false
  	if sRAProjectName <> vbNullString then

		Set oRAPrj = oSession.GetEntity("RAProject", sRAProjectName)
 		if not oRAPrj is nothing then
			CQI_CheckRPProjectMaster = oRAPrj.SiteHasMastership
 			if not CQI_CheckRPprojectMaster then
 				sError = "Cannot perform this action from the current site: the RequisitePro project is not mastered at this site."
 			end if
  		else
 			sError = "Cannot find the Rational Administrator project. Integration is disabled for this record."
 		End If
 	else
 		sError = "Record does not have a valid Rational Administrator project"
 	end if
  	set oSession = nothing
 	set oRAPrj = nothing
end function


program:
REM TODO -- put your script code here
Function Check_Eclipse
	dim Sess

	Set Sess = GetSession
	Check_Eclipse = Sess.HasValue("_CQ_ECLIPSE_SESSION")
End Function


program:
REM TODO -- put your script code here
function CQI_GetNewReqProTool()		 'as ASCQIIntegration.RequisiteProTool
	On Error resume next
	err.clear

	dim a_oConnector					  'Reference to a ASCQIIntegration.Connector instance
	dim a_oIntegration				  'Reference to a ASCQIIntegration.Integration instance
	dim a_oRequisiteProTool	        'Reference to a ASCQIIntegration.RequisiteProTool instance
	Dim bWeb

	set CQI_GetNewReqProTool = nothing

	bWeb = Check_Web()
	
	Set a_oConnector = CreateObject("ASCQIIntegration.Connector")
	if a_oConnector is nothing OR Err.Number <> 0 then
			if bWeb then
				Err.Raise 1, "Rational RequisitePro/ClearQuest Integration", "ClearQuest could not connect to the Integration Server." + vbcrlf + "Please contact your Administrator."
				exit function
			end if
		msgbox "ClearQuest could not connect to the Integration Server." + vbcrlf + "Please contact your Administrator.", vbOKOnly + vbCritical, "Rational RequisitePro/ClearQuest Integration"
	else
		Set a_oIntegration = a_oConnector.GetUniqueInstance
		if a_oIntegration is nothing OR Err.Number <> 0 then
				if bWeb then
					Err.Raise 1, "Rational RequisitePro/ClearQuest Integration", "ClearQuest could not connect to the Integration Server." + vbcrlf + "Please contact your Administrator."
					exit function
				end if
			msgbox "ClearQuest could not connect to the Integration Server." + vbcrlf + "Please contact your Administrator.", vbOKOnly + vbCritical, "Rational RequisitePro/ClearQuest Integration"
		else
			set a_oRequisiteProTool = a_oIntegration.GetRequisiteProTool
			if a_oRequisiteProTool is nothing OR Err.Number <> 0 then
					if bWeb then
						Err.Raise 1, "Rational RequisitePro/ClearQuest Integration", "ClearQuest could not connect to the Integration Server." + vbcrlf + "Please contact your Administrator."
						exit function
					end if
				msgbox "ClearQuest could not connect to the Integration Server." + vbcrlf + "Please contact your Administrator.", vbOKOnly + vbCritical, "Rational RequisitePro/ClearQuest Integration"
			else
				set CQI_GetNewReqProTool = a_oRequisiteProTool
			end if	'a_oRequisiteProTool
		end if	'a_oIntegration
	end if	'a_oConnector

	set a_oConnector = nothing
	set a_oIntegration = nothing
	set a_oRequisiteProTool = nothing

end function


program:
Function CQI_CheckAssociateDlg()
	Dim a_bIsRPAssociateDlg

    CQI_RPAssociateDlg = "CQI_RPAssociateDlg"

	CQI_CheckAssociateDlg = FALSE

	Set Session = GetSession

	If Session.HasValue(CQI_RPAssociateDlg) Then
		a_bIsRPAssociateDlg = Session.NameValue(CQI_RPAssociateDlg)
		If a_bIsRPAssociateDlg = "Running" then
			CQI_CheckAssociateDlg = TRUE
		End If
	End If
End Function


program:
Function Check_RAProjectMaster
	dim oRAPrj
	dim oSession
	Set oSession = GetSession
	If GetFieldValue("RAProject").GetValue() = "" then
		Check_RAProjectMaster = TRUE
		Exit Function
	End If
	Set oRAPrj = oSession.GetEntity("RAProject", GetFieldValue("RAProject").GetValue())
	Check_RAProjectMaster = oRAPrj.SiteHasMastership
End Function


program:
Sub InvalidateTTFields()
'Invalidate the values of the TeamTest Integration Choicelist fields
	InvalidateFieldChoiceList( "Build" )
	InvalidateFieldChoiceList( "Log_Folder" )
	InvalidateFieldChoiceList( "Log" )
	InvalidateFieldChoiceList( "Operating_System" )
	InvalidateFieldChoiceList( "Computer" )
	InvalidateFieldChoiceList( "Fixed_In_Build" )
End Sub


program:
REM TODO -- put your script code here

function CQI_IsRunningIntegration()  'as boolean
'Indicates if the user is in edition on a CQ record from the CQ association dialog box
'To avoid recursivity

	dim a_sCQI_IntegrationVar	
	dim a_oCQSession

	a_sCQI_IntegrationVar= "CQI_Integration"
	Set a_oCQSession = GetSession
	if not a_oCQSession is nothing then
		if a_oCQSession.NameValue(a_sCQI_IntegrationVar) = "Running" then
			CQI_IsRunningIntegration = true
		else
			CQI_IsRunningIntegration = false
		end if
	end if
	
end function


program:
REM TODO -- put your script code here

Function  CQI_GetListFromDBIDTable(vTable(), sCQidsSeparator, byref sText) 		  'as boolean

REM Return TRUE if could construct corresponding list of Req Proxy DBIDs for table of Req DBIDs
REM a_vTable: table containing Requirement records dbids
REM sCQidsSeparator: string inserted between each DBID returned in sText
REM sText: string returned, containing list of Requirement Proxy DBIDs, separated by string in sCQidsSeparator

	Dim a_lIndex
  
	CQI_GetListFromDBIDTable = False

	sText = vbNullString
	if (LBound(vTable) <= UBound(vTable)) Then
		For a_lIndex = LBound(vTable) To UBound(vTable)
			if sText <> vbNullString then
				sText = sText + sCQidsSeparator
			end if
			sText = sText + cstr(vTable(a_lIndex))
		Next
	end if	'Bound vTable()
	CQI_GetListFromDBIDTable = True

End Function


program:
REM TODO -- put your script code here

sub CQI_UnloadRequisiteProTool()
	Dim a_oCQSession			        'Current CQ session
	dim a_oRequisiteProTool	        'Reference to a ASCQIIntegration.RequisiteProTool instance
	dim ac_sRequisiteProToolVar      'Name of session variable containing the Tool that initiate the action			
	Dim a_sError		
	Dim ac_StateCompVar
	Dim a_sVal

	ac_StateCompVar = "CQIStateComp"
	ac_sRequisiteProToolVar = "CQI_RequisiteProTool"

	Set a_oCQSession = GetSession
	if not a_oCQSession is nothing then
		a_sVal = a_oCQSession.NameValue(ac_StateCompVar)
		if a_sVal = "LOADED" then
			set a_oRequisiteProTool = a_oCQSession.NameValue(ac_sRequisiteProToolVar)
			if not a_oRequisiteProTool is nothing then
				if not a_oRequisiteProTool.Unload(a_sError) then
 					if Check_Web() then
 						Err.Raise 1, "Rational RequisitePro/ClearQuest Integration", a_sError
 					else
						Msgbox a_sError, vbOKOnly + vbCritical, "Rational RequisitePro/ClearQuest Integration"
 					end if
				end if
			end if
			set a_oRequisiteProTool = nothing
			a_oCQSession.NameValue(ac_sRequisiteProToolVar) = ""
			a_oCQSession.NameValue(ac_StateCompVar) = "UNLOADED"
		end if
	end if	'a_oCQSession
	
	set a_oCQSession = nothing

end sub


program:
REM TODO -- put your script code here

sub CQI_AddDBIDToList(sDBID, sCQidsSeparator) 

REM Adds the sDBID passed as a parameter to the list of Req Proxy DBIDs associated to current CQ record
REM only if it is not already in the list
REM and separates existing dibds from new one by character contained in parameter sCQidsSeparator

	Dim ac_sCQIListReqsVar					'Name of the global variable containing the list of Req Proxy DBIDs associated to the current CQ record
	Dim a_oCQSession							'Current CQ session	
	Dim a_sListReqDBIDs						'List of Req Proxy DBIDs associated to the current CQ record
	Dim a_vTableDBIDs							'List of DBIDs of Req proxies associated to the current CQ record
	Dim a_bFound								'Boolean indicating wether the DBID has been found in the list or not
	Dim a_lIndex

 	ac_sCQIListReqsVar = "CQIReqs"

	Set a_oCQSession = GetSession
	if not a_oCQSession is nothing then
		a_sListReqDBIDs = a_oCQSession.NameValue(ac_sCQIListReqsVar)
		a_vTableDBIDs = empty

		a_vTableDBIDs = Split(a_sListReqGUIDs, sCQidsSeparator, -1, 1)
		'May be no value has been splitted
		'Then LBound(a_vTableDBIDs)==0 and UBound(a_vTableDBIDs)==-1
		If (LBound(a_vTableDBIDs) <= UBound(a_vTableDBIDs)) Then
			a_bFound = false
			for a_lIndex = LBound(a_vTableDBIDs) to UBound(a_vTableDBIDs)
   	      if sDBID = cstr(a_vTableDBIDs(a_lIndex)) then
					a_bFound = true
					exit for
				end if
			next
			if not a_bFound then
				a_sListReqDBIDs = a_sListReqDBIDs + sCQidsSeparator + sDBID
			end if
		else
			a_sListReqDBIDs = sDBID
		end if	'Bound a_vTableDBIDs

		a_oCQSession.NameValue(ac_sCQIListReqsVar) = a_sListReqDBIDs
		
	end if	'a_oCQSession

end sub


program:
REM TODO -- put your script code here

sub CQI_RemoveDBIDFromList(sDBID, sCQidsSeparator)

REM Removes the sDBID passed as a parameter from the list of Req Proxy DBIDs associated to current CQ record
REM and separates existing dibds by character contained in parameter sCQidsSeparator

	Dim ac_sCQIListReqsVar					'Name of the global variable containing the list of Req Proxy DBIDs associated to the current CQ record
	Dim a_oCQSession							'Current CQ session	
	Dim a_sListReqDBIDs						'List of Req Proxy DBIDs associated to the current CQ record
	Dim a_vTableDBIDs							'List of DBIDs of Req proxies associated to the current CQ record
	Dim a_lIndex

 	ac_sCQIListReqsVar = "CQIReqs"

	Set a_oCQSession = GetSession
	if not a_oCQSession is nothing then
		a_sListReqDBIDs = a_oCQSession.NameValue(ac_sCQIListReqsVar)
		a_vTableDBIDs = empty

		a_vTableDBIDs = Split(a_sListReqGUIDs, sCQidsSeparator, -1, 1)
		a_sListReqDBIDs = vbNullString
		'May be no value has been splitted
		'Then LBound(a_vTableDBIDs)==0 and UBound(a_vTableDBIDs)==-1
		If (LBound(a_vTableDBIDs) <= UBound(a_vTableDBIDs)) Then
			for a_lIndex = LBound(a_vTableDBIDs) to UBound(a_vTableDBIDs)
   	      if sDBID = cstr(a_vTableDBIDs(a_lIndex)) then
					'Nothing to do
				else
					if a_sListReqDBIDs = vbNullString then
						a_sListReqDBIDs = cstr(a_vTableDBIDs(a_lIndex))
					else
						a_sListReqDBIDs = a_sListReqDBIDs + sCQidsSeparator + cstr(a_vTableDBIDs(a_lIndex))
					end if
				end if
			next
		else
			'Nothing to do
		end if	'Bound a_vTableDBIDs

		a_oCQSession.NameValue(ac_sCQIListReqsVar) = a_sListReqDBIDs
		
	end if	'a_oCQSession

end sub


program:
REM TODO -- put your script code here

function CQI_GetRequisiteProTool()		 'as ASCQIIntegration.RequisiteProTool
	On Error resume next
	err.clear

	Dim a_oCQSession			        'Current CQ session
	dim a_oConnector					  'Reference to a ASCQIIntegration.Connector instance
	dim a_oIntegration				  'Reference to a ASCQIIntegration.Integration instance
	dim a_oRequisiteProTool	        'Reference to a ASCQIIntegration.RequisiteProTool instance
	dim ac_sRequisiteProToolVar     'Name of session variable containing the Tool that initiate the action						
	dim a_bGotIt
	dim a_sVal
	Dim ac_StateCompVar 	
	Dim bWeb

	ac_sRequisiteProToolVar = "CQI_RequisiteProTool"
	ac_StateCompVar = "CQIStateComp"

	set CQI_GetRequisiteProTool = nothing

	bWeb = Check_Web()
	
	Set a_oCQSession = GetSession
	if not a_oCQSession is nothing then
		a_bGotIt = false
		If a_oCQSession.HasValue(ac_sRequisiteProToolVar) Then
			a_sVal = a_oCQSession.NameValue(ac_StateCompVar)
			if a_sVal = "LOADED" then
				set CQI_GetRequisiteProTool = a_oCQSession.NameValue(ac_sRequisiteProToolVar)
				a_bGotIt = true
			end if	'vbnullstring
		end if	'ac_sRequisiteProToolVar
		if not a_bGotIt then
			Set a_oConnector = CreateObject("ASCQIIntegration.Connector")
			if a_oConnector is nothing OR Err.Number <> 0 then
 				if bWeb then
 					Err.Raise 1, "Rational RequisitePro/ClearQuest Integration", "ClearQuest could not connect to the Integration Server." + vbcrlf + "Please contact your Administrator."
 					exit function
 				end if
				msgbox "ClearQuest could not connect to the Integration Server." + vbcrlf + "Please contact your Administrator.", vbOKOnly + vbCritical, "Rational RequisitePro/ClearQuest Integration"
			else
				Set a_oIntegration = a_oConnector.GetUniqueInstance
				if a_oIntegration is nothing OR Err.Number <> 0 then
 					if bWeb then
 						Err.Raise 1, "Rational RequisitePro/ClearQuest Integration", "ClearQuest could not connect to the Integration Server." + vbcrlf + "Please contact your Administrator."
 						exit function
 					end if
					msgbox "ClearQuest could not connect to the Integration Server." + vbcrlf + "Please contact your Administrator.", vbOKOnly + vbCritical, "Rational RequisitePro/ClearQuest Integration"
				else
					set a_oRequisiteProTool = a_oIntegration.GetRequisiteProTool
					if a_oRequisiteProTool is nothing OR Err.Number <> 0 then
 						if bWeb then
 							Err.Raise 1, "Rational RequisitePro/ClearQuest Integration", "ClearQuest could not connect to the Integration Server." + vbcrlf + "Please contact your Administrator."
 							exit function
 						end if
						msgbox "ClearQuest could not connect to the Integration Server." + vbcrlf + "Please contact your Administrator.", vbOKOnly + vbCritical, "Rational RequisitePro/ClearQuest Integration"
					else
						a_oCQSession.NameValue(ac_sRequisiteProToolVar) = a_oRequisiteProTool
						a_oCQSession.NameValue(ac_StateCompVar) = "LOADED"
						set CQI_GetRequisiteProTool = a_oRequisiteProTool
					end if	'a_oRequisiteProTool
				end if	'a_oIntegration
			end if	'a_oConnector
		end if	'a_bGotIt		
	end if	'a_oCQSession
	set a_oConnector = nothing
	set a_oIntegration = nothing
	set a_oRequisiteProTool = nothing

	set a_oCQSession = nothing

end function


program:
REM TODO -- put your script code here

Function CQI_GetTableFromDBIDList(sText, sCQidsSeparator, byref vTable)		'as boolean 

REM Return TRUE if could construct corresponding table of Req Proxy DBIDs for list of Proxy DBIDs
REM sText: contains list of Requirement Proxy DBIDs, separated by string in sCQidsSeparator
REM sCQidsSeparator: string used to separate each DBID in sText
REM a_vTable: table returned that contains Requirement Proxy dbids which are stored in sText

	Dim a_vCQdbidsArray 
	Dim a_lIndex 

	CQI_GetTableFromDBIDList = False
  

	a_vCQdbidsArray = Split(sText, sCQidsSeparator, -1, 1)
	'May be no value has been splitted
	'Then LBound(a_vCQdbidsArray)==0 and UBound(a_vCQdbidsArray)==-1

	If (LBound(a_vCQdbidsArray) <= UBound(a_vCQdbidsArray)) Then
		'At least one CQ record id has to be processed
		ReDim vTable(UBound(a_vCQdbidsArray) - LBound(a_vCQdbidsArray))
		For a_lIndex = LBound(a_vCQdbidsArray) To UBound(a_vCQdbidsArray)
			vTable(a_lIndex - LBound(a_vCQdbidsArray)) = a_vCQdbidsArray(a_lIndex)
		Next
	else
		vTable = empty
	end If	'Bound a_vCQdbidsArray    

	CQI_GetTableFromDBIDList = True

End Function


program:
# Set default value to return
    $result = $CQPerlExt::CQ_OPTIONAL;
    
	# check if the session variable is defined
    my $variable_defined_flag = $session->HasValue("EDIT_CQACT_CTX_TYPE");
    if ( $variable_defined_flag ) {
	    my $edit_context_type = $session->GetNameValue("EDIT_CQACT_CTX_TYPE");
		if ( $edit_context_type eq "" ) {
			my $bound_vob_object = $entity->GetFieldValue("ucm_vob_object")->GetValue();
			if ( $bound_vob_object ne "" ) {
				$result = $CQPerlExt::CQ_READONLY;
			}			
        }
	}


program:
' The actiontype that we get as a parameter is just "BASE' which
  ' isn't very informative, so get the action type that started it all.
  real_actiontype = GetActionType

  ' Get args for calling methods
  Set this_session = GetSession()
  Set this_entity = BaseEntity

  If (real_actiontype <> AD_SUBMIT) Then
    ' For other actiontype's, check if entity is bound
    bound_vob_object = GetFieldValue("ucm_vob_object").GetValue

    If (bound_vob_object <> "") Then
      call_squid = 0	

      If (real_actiontype <> AD_DELETE) Then
        ' Get a list of the fields in this record type...
        fieldNameList = GetFieldNames

        ' Loop
        For Each FN in fieldNameList
          If (FN = "Headline") Then
            ' Get the field's original value
            OldFV = GetFieldOriginalValue(FN).GetValue
            ' Get the current value
            NewFV = GetFieldValue(FN).GetValue                
            If (OldFV <> NewFV) Then
              call_squid = 1	
              Exit For
            End If ' End of "OldFV <> NewFV"
          End If  ' End of "FN = Headline" 
        Next ' End of For loop 
   	  End If ' End of (real_actiontype <> AD_DELETE)

      If (call_squid = 1) Or (real_actiontype = AD_DELETE) Then      
        ' Entity is bound, attempt to create SquidServer COM server
        ' Set error handling to catch error from CreateObject
        On Error Resume Next
        Set squid_server = CreateObject("ClearCase.SquidServer.1")
        error_num  = Err.Number
        error_desc = Err.Description
        ' Reset error handling, so that SquidServer method errors are reported by CQ
        On Error Goto 0

        If error_num <> 0 Then
          ' Create Object failed, raise exception
          If error_num = 429 Then
            ' CreateObject failed because SquidServer was not found, assume ClearCase is not installed
            Err.Raise vbObjectError+1, "SquidServer", "Error: ClearCase may not be installed or configured correctly."
          Else
            ' CreateObject failed for another reason, report the error
            Err.Raise vbObjectError+2, "SquidServer", "Can not access SquidServer: CreateObject error=" & CStr(error_num) & " " & CStr(error_desc)
          End If ' End of "error_num = 429"
        Else
          ' CreateObject succeeded, call appropriate server method
          ' On error, these will throw an exception and abort the commit
          If (real_actiontype = AD_DELETE) Then
            Call squid_server.DeleteCommitCQActivity(this_session, this_entity)            
          Else
            Call squid_server.ModifyCommitCQActivity(this_session, this_entity)
          End If
        End If ' End of "CreateObject succeeded"      
      End If ' End of "call_squid"
    End If ' End of (bound_vob_object <> "")
  End If ' End of (real_actiontype <> AD_SUBMIT)


program:
# The actiontype that we get as a parameter is just "BASE' which
    # isn't very informative, so get the action type that started it all.
    my $real_actiontype = $entity->GetActionType();

    # Get args for calling methods
    my $session_id = $session->CQInt_Id();
    my $entity_id = $entity->CQInt_Id();
    
	my $call_squid = 0;        
    if ($real_actiontype != $CQPerlExt::CQ_SUBMIT) {
      # For other actiontypes, check if entity is bound
      my $field_info = $entity->GetFieldValue("ucm_vob_object");
      my $ucm_vob_object = $field_info->GetValue();

      if ($ucm_vob_object ne "") {
        # Entity is bound, check if calling SQUID is necessary
        if ($real_actiontype != $CQPerlExt::CQ_DELETE) {           
          # Get a list of the fields in this record type
          # (NOTE: GetFieldNames() returns a *REFERENCE* to an array)...
          my($FieldNamesRef) = $entity->GetFieldNames();

          # Loop through the fields               
          foreach $FN (@$FieldNamesRef) {
            if ( $FN eq "Headline" ) {
              # Get the field's original value...
              $OldFV = $entity->GetFieldOriginalValue($FN)->GetValue();
              # Get the field's new value...
              $NewFV = $entity->GetFieldValue($FN)->GetValue();

              # check if the OldValue equals the NewValue
              if ( $OldFV ne $NewFV ) {
                $call_squid = 1;
                last;
              }
            } # End of ( $FN eq "Headline" ) 
          } # End of foreach loop
        } # End of ($real_actiontype != $CQPerlExt::CQ_DELETE)

        if ( ( $call_squid == 1 ) || ($real_actiontype == $CQPerlExt::CQ_DELETE) ) {
          # Calling SQUID is necessary, get CQSquidLoad package
          require CQSquidLoad;
          my $squid = new CQSquidLoad;
          my $load_status = $squid->SquidLoadStatus();

          # Check whether CQSquidLoad package was able to load CQSquidLoad library
          if ($load_status == 2) {
            # CQSquidLoad library could not be loaded, assume ClearCase is not installed
            die "Error: ClearCase may not be installed or configured correctly.";
          }
          elsif ($load_status == 3) {
            # CQSquidLoad library loaded, but is wrong version
            die "Can not change this record, wrong version of ClearCase is installed.";
          }
          else {
            # Success, call package method to do the work.
            # On error, this will throw an exception and abort the commit
            if ($real_actiontype == $CQPerlExt::CQ_DELETE) {
              $squid->DeleteCommitCQActivity($session_id, $entity_id);
            }
            else {
              $squid->ModifyCommitCQActivity($session_id, $entity_id);
            }
          } # End of "load CQSquidLoad Package"
         } # End of "call_squid"
       } # End of ($ucm_vob_object ne "")
     } # End of "other actiontype's"


program:
' Get the Activity Change Set (ACS) ActiveX Control instance

  set acs_ctrl = param.ObjectItem

  ' Clear any existing items

  acs_ctrl.Clear

  ' Get the session and info about the record type

  Set session = GetSession
  Set entitydef = session.GetEntityDef(GetEntityDefname)

  ' If entitydef has (non-UCM) cc integration objects, populate list

  If entitydef.IsFieldDefName("cc_change_set") Then
    cset_ref = GetFieldValue("cc_change_set").GetValue
     If cset_ref <> "" Then
      Set cset_record = session.GetEntity("cc_change_set",cset_ref)
      object_ref_list = (cset_record.GetFieldValue("objects")).GetValueAsList
      If IsArray(object_ref_list) Then
        For Each object_ref In object_ref_list
          Set version_record = session.GetEntity("cc_vob_object",object_ref)
          VOBOid = version_record.GetFieldValue("vob_family_uuid").GetValue
          ObjOid = version_record.GetFieldValue("object_oid").GetValue
          Path = version_record.GetFieldValue("name").GetValue
          acs_ctrl.AddItemEx VOBOid,ObjOid,Path
        Next
        ' Exit Function
      End If ' cc_change_set has a list of cc_vob_objects
    End If ' cc_change_set field is non-empty
  End If ' has a cc_change_set field

  ' If entitydef has a UCM activity, use that to get the change set list

  If entitydef.IsFieldDefName("ucm_vob_object") Then
    acs_ref = GetFieldValue("ucm_vob_object").GetValue
    If acs_ref <> "" Then
      acs_ctrl.Activity = acs_ref
    End If
  End If


program:
' ***** UCM Package Rev = 4.0 07_12_2001 *****


   ' Attempt to create SquidServer COM server (should succeed if ClearCase is
   ' installed).   
   ' Set error handling to catch error from CreateObject
   On Error Resume Next
   Set squid_server = CreateObject("ClearCase.SquidServer.1")
   error_num  = Err.Number
   error_desc = Err.Description
   ' Reset error handling, so that SquidServer method errors are reported by CQ
   On Error Goto 0

   BaseCMActivity_UCM_WorkOn = ""
   If error_num <> 0 Then
	   ' Create Object failed, raise exception
      If error_num = 429 Then
         ' CreateObject failed because SquidServer was not found, assume ClearCase is not installed
         BaseCMActivity_UCM_WorkOn = "Error: ClearCase may not be installed or configured correctly."
      Else
         ' CreateObject failed for another reason, report the error
         BaseCMActivity_UCM_WorkOn = "Can not access SquidServer: CreateObject error=" & CStr(error_num) & " " & CStr(error_desc)
      End If
	Else
      ' CreateObject succeeded, call SquidServer's method
      Set this_session = GetSession()
      Set this_entity = BaseEntity
      BaseCMActivity_UCM_WorkOn = squid_server.StartWork(this_session, this_entity)
   End If


program:
# Get CQSquidLoad package
    require CQSquidLoad;
    my $squid = new CQSquidLoad;
    my $load_status = $squid->SquidLoadStatus(); 

    # Check whether CQSquidLoad package was able to load CQSquidLoad library
    if ($load_status == 2) {
        # CQSquidLoad library could not be loaded, assume ClearCase
        # is not installed
        die "Error: ClearCase may not be installed or configured correctly.";
    }
    elsif ($load_status == 3) {
        # CQSquidLoad library loaded, but is wrong version
        die "Can not Work On this record, wrong version of ClearCase is installed.";
    }
    else {
        # Success, call package method to do the work
        my $session_id = $session->CQInt_Id();
        my $entity_id = $entity->CQInt_Id();
        $result = $squid->StartWork($session_id, $entity_id);
    }

	 # Return error string


program:
' Get Session
  Set this_session = GetSession
  ' check if the session variable is defined
  edit_context_type = ""
  variable_definded_flag = this_session.HasValue("EDIT_CQACT_CTX_TYPE")

  If variable_definded_flag Then
    ' defined, get the value
  	edit_context_type = this_session.NameValue("EDIT_CQACT_CTX_TYPE")
  Else 
   	' not defined, calling from ClearQuest
  End If	

  If edit_context_type = "EDIT_ENTITY" Then
	ucm_stream_Permission = AD_OPTIONAL
  Else 
   	ucm_stream_Permission = AD_READONLY
  End If


program:
# Set default value to return
    $result = $CQPerlExt::CQ_READONLY;

    # check if the session variable is defined
    my $variable_defined_flag = $session->HasValue("EDIT_CQACT_CTX_TYPE");

    if ( $variable_defined_flag ) {
    	# defined, get the value
  		my $edit_context_type = $session->GetNameValue("EDIT_CQACT_CTX_TYPE");
		if ( $edit_context_type eq "EDIT_ENTITY" ) {
			$result = $CQPerlExt::CQ_OPTIONAL;
		}  		
    }


program:
' Get Session
  Set this_session = GetSession
  ' check if the session variable is defined
  edit_context_type = ""
  variable_definded_flag = this_session.HasValue("EDIT_CQACT_CTX_TYPE")

  If variable_definded_flag Then
    ' defined, get the value
  	edit_context_type = this_session.NameValue("EDIT_CQACT_CTX_TYPE")
  Else 
   	' not defined, calling from ClearQuest
  End If	

  If edit_context_type = "EDIT_ENTITY" Then
	ucm_view_Permission = AD_OPTIONAL
  Else 
   	ucm_view_Permission = AD_READONLY
  End If


program:
' Get Session
  Set this_session = GetSession
  ' check if the session variable is defined
  edit_context_type = ""

  variable_defined_flag = this_session.HasValue("EDIT_CQACT_CTX_TYPE")
  If variable_defined_flag Then
    ' defined, get the value
  	edit_context_type = this_session.NameValue("EDIT_CQACT_CTX_TYPE")
  Else 
   	' not defined, calling from ClearQuest
  End If 	

  If edit_context_type = "" Then
	' Default behavior is to be read-only if entity is bound, else can be changed
	bound_vob_object = GetFieldValue("ucm_vob_object").GetValue
  	If bound_vob_object <> "" Then
  		ucm_project_Permission = AD_READONLY
  	Else 
    	ucm_project_Permission = AD_OPTIONAL
  	End If
  Else
	' All other cases - make it non read-only
	ucm_project_Permission = AD_OPTIONAL	
  End If


program:
' Attempt to create SquidServer COM server (should succeed if ClearCase is
  ' installed).   
  ' Set error handling to catch error from CreateObject
  On Error Resume Next
  Set squid_server = CreateObject("ClearCase.SquidServer.1")
  error_num  = Err.Number
  error_desc = Err.Description
  ' Reset error handling, so that SquidServer method errors are reported by CQ
  On Error Goto 0

  UCMUtilityActivity_UCM_Contributors = ""
  If error_num <> 0 Then
  	' Create Object failed, raise exception
   	If error_num = 429 Then
    	' CreateObject failed because SquidServer was not found, assume ClearCase is not installed or configured correctly
        UCMUtilityActivity_UCM_Contributors = "Error: ClearCase may not be installed or configured correctly."
    Else
        ' CreateObject failed for another reason, report the error
        UCMUtilityActivity_UCM_Contributors = "Can not access SquidServer: CreateObject error=" & CStr(error_num) & " " & CStr(error_desc)
    End If
  Else
  	' CreateObject succeeded, call SquidServer's method
    Set this_session = GetSession()
    Set this_entity = BaseEntity
    UCMUtilityActivity_UCM_Contributors = squid_server.GetContributors(this_session, this_entity)
  End If


program:
# Get CQSquidLoad package
    require CQSquidLoad;
    my $squid = new CQSquidLoad;
    my $load_status = $squid->SquidLoadStatus(); 

    # Check whether CQSquidLoad package was able to load CQSquidLoad library
    if ($load_status == 2) {
        # CQSquidLoad library could not be loaded, assume ClearCase
        # is not installed
        die "Error: ClearCase may not be installed or configured correctly.";
    }
    elsif ($load_status == 3) {
        # CQSquidLoad library loaded, but is wrong version
        die "Error: wrong version of ClearCase is installed.";
    }
    else {
        # Success, call package method to do the work
        my $session_id = $session->CQInt_Id();
        my $entity_id = $entity->CQInt_Id();
        $result = $squid->GetContributors($session_id, $entity_id);
    }

	# Return error string


program:
' ***** UCM Package Rev = 4.0 07_12_2001 *****


   ' Attempt to create SquidServer COM server (should succeed if ClearCase is
   ' installed).   
   ' Set error handling to catch error from CreateObject
   On Error Resume Next
   Set squid_server = CreateObject("ClearCase.SquidServer.1")
   error_num  = Err.Number
   error_desc = Err.Description
   ' Reset error handling, so that SquidServer method errors are reported by CQ
   On Error Goto 0

   UCMUtilityActivity_UCM_WorkOn = ""
   If error_num <> 0 Then
	   ' Create Object failed, raise exception
      If error_num = 429 Then
         ' CreateObject failed because SquidServer was not found, assume ClearCase is not installed
         UCMUtilityActivity_UCM_WorkOn = "Error: ClearCase may not be installed or configured correctly."
      Else
         ' CreateObject failed for another reason, report the error
         UCMUtilityActivity_UCM_WorkOn = "Can not access SquidServer: CreateObject error=" & CStr(error_num) & " " & CStr(error_desc)
      End If
	Else
      ' CreateObject succeeded, call SquidServer's method
      Set this_session = GetSession()
      Set this_entity = BaseEntity
      UCMUtilityActivity_UCM_WorkOn = squid_server.StartWork(this_session, this_entity)
   End If


program:
' ***** UCM Package Rev = 4.0 07_12_2001 *****


   ' Attempt to create SquidServer COM server (should succeed if ClearCase is
   ' installed).   
   ' Set error handling to catch error from CreateObject
   On Error Resume Next
   Set squid_server = CreateObject("ClearCase.SquidServer.1")
   error_num  = Err.Number
   error_desc = Err.Description
   ' Reset error handling, so that SquidServer method errors are reported by CQ
   On Error Goto 0

   Defect_UCM_WorkOn = ""
   If error_num <> 0 Then
	   ' Create Object failed, raise exception
      If error_num = 429 Then
         ' CreateObject failed because SquidServer was not found, assume ClearCase is not installed
         Defect_UCM_WorkOn = "Error: ClearCase may not be installed or configured correctly."
      Else
         ' CreateObject failed for another reason, report the error
         Defect_UCM_WorkOn = "Can not access SquidServer: CreateObject error=" & CStr(error_num) & " " & CStr(error_desc)
      End If
	Else
      ' CreateObject succeeded, call SquidServer's method
      Set this_session = GetSession()
      Set this_entity = BaseEntity
      Defect_UCM_WorkOn = squid_server.StartWork(this_session, this_entity)
   End If


program:
Function UCM_ChkBeforeDeliver_Def (entity_type, entity_id)

  ' This implements the default behavior when the "Perform ClearQuest Action
  ' Before Delivery" policy is enabled: Default is to do the delivery
  ' for all activities
  '
  ' INPUT:
  '  - entity_type: type of entity being delivered
  '  - entity_id: id (e.g. "SAMPL0000001") of entity being delivered
  ' OUTPUT:
  '  - If the activity should be delivered, this should return an empty string
  '  - If the activity should not be delivered, this should return a string
  '    to be displayed as an error message. This will cause the delivery to
  '    be aborted.

  UCM_ChkBeforeDeliver_Def = "" 

End Function


program:
Function UCM_ChkBeforeWorkOn_Def (entity_type, entity_id)

  ' This implements the default behavior when the "Perform ClearQuest Action
  ' Before Work On" policy is enabled: It only allows user to work on the entity
  ' if it is assigned to them.
  '
  ' INPUT:
  '  - entity_type: type of entity being worked on
  '  - entity_id: id (e.g. "SAMPL0000001") of entity being worked on
  ' OUTPUT:
  '  - If the current user is permitted to work on this entity, this should
  '    return an empty string
  '  - If the current user is not permitted to work on this entity, this
  '    should return a string to be displayed as an error message. This
  '    will cause the Work On action to be aborted.

  ' Get hook's session context
  Set session = GetSession()

  ' Get the entity
  Set entity = session.GetEntity(entity_type, entity_id)

  ' Get the entity's assigned user
  assigned_user = entity.GetFieldValue("Owner").GetValue()

  ' Get current user from session
  current_user = session.GetUserLoginName()

  ' Check the assigned_user
  If assigned_user = current_user Then
      ' User is permitted to work on entity, return empty string
      UCM_ChkBeforeWorkOn_Def = ""
  ElseIf assigned_user = "" Then
      ' User is not permitted to work on un-assigned entity, return error string
      UCM_ChkBeforeWorkOn_Def = "You cannot work on this " + entity_type + " because it is not assigned to an Owner."
  Else
      ' User is not permitted to work on mis-assigned entity, return error string
      UCM_ChkBeforeWorkOn_Def = "You cannot work on this " + entity_type + " because its Owner is """ + assigned_user + """, not """ + current_user + """"
  End If

End Function


program:
dim ac_sIntegrationVar
	dim oSession
	dim a_sVal

	ac_sIntegrationVar = "CQI_Integration"

	req_id_Permission = AD_READONLY

	set oSession = GetSession
	If oSession.HasValue(ac_sIntegrationVar) Then
		a_sVal = oSession.NameValue(ac_sIntegrationVar)
		if a_sVal = "Running" then
			req_id_Permission = AD_OPTIONAL
		end if	
	end if
	
	set oSession = nothing


program:
dim ac_sIntegrationVar
	dim oSession
	dim a_sVal

	ac_sIntegrationVar = "CQI_Integration"

	requirement_Permission = AD_READONLY

	set oSession = GetSession
	If oSession.HasValue(ac_sIntegrationVar) Then
		a_sVal = oSession.NameValue(ac_sIntegrationVar)
		if a_sVal = "Running" then
			requirement_Permission = AD_OPTIONAL
		end if	
	end if
	
	set oSession = nothing


program:
dim ac_sIntegrationVar
	dim oSession
	dim a_sVal

	ac_sIntegrationVar = "CQI_Integration"

	tag_Permission = AD_READONLY

	set oSession = GetSession
	If oSession.HasValue(ac_sIntegrationVar) Then
		a_sVal = oSession.NameValue(ac_sIntegrationVar)
		if a_sVal = "Running" then
			tag_Permission = AD_OPTIONAL
		end if	
	end if
	
	set oSession = nothing


program:
REM return one of AD_MANDATORY, AD_OPTIONAL, AD_READONLY.  Example:
    REM   If username = "pat" Then
    REM      project_name_Permission = AD_READONLY
    REM   Else
    REM      project_name_Permission = AD_OPTIONAL
    REM   End If

	dim ac_sIntegrationVar
	dim oSession
	dim a_sVal

	ac_sIntegrationVar = "CQI_Integration"

	project_name_Permission = AD_READONLY

	set oSession = GetSession
	If oSession.HasValue(ac_sIntegrationVar) Then
		a_sVal = oSession.NameValue(ac_sIntegrationVar)
		if a_sVal = "Running" then
			project_name_Permission = AD_OPTIONAL
		end if	
	end if
	
	set oSession = nothing


program:
REM return one of AD_MANDATORY, AD_OPTIONAL, AD_READONLY.  Example:
    REM   If username = "pat" Then
    REM      req_guid_Permission = AD_READONLY
    REM   Else
    REM      req_guid_Permission = AD_OPTIONAL
    REM   End If
	dim ac_sIntegrationVar
	dim oSession
	dim a_sVal

	ac_sIntegrationVar = "CQI_Integration"

	req_guid_Permission = AD_READONLY

	set oSession = GetSession
	If oSession.HasValue(ac_sIntegrationVar) Then
		a_sVal = oSession.NameValue(ac_sIntegrationVar)
		if a_sVal = "Running" then
			req_guid_Permission = AD_OPTIONAL
		end if	
	end if
	
	set oSession = nothing


program:
REM return one of AD_MANDATORY, AD_OPTIONAL, AD_READONLY.  Example:
    REM   If username = "pat" Then
    REM      name_Permission = AD_READONLY
    REM   Else
    REM      name_Permission = AD_OPTIONAL
    REM   End If

	dim ac_sIntegrationVar
	dim oSession
	dim a_sVal

	ac_sIntegrationVar = "CQI_Integration"

	name_Permission = AD_READONLY

	set oSession = GetSession
	If oSession.HasValue(ac_sIntegrationVar) Then
		a_sVal = oSession.NameValue(ac_sIntegrationVar)
		if a_sVal = "Running" then
			name_Permission = AD_OPTIONAL
		end if	
	end if
	
	set oSession = nothing


program:
REM return one of AD_MANDATORY, AD_OPTIONAL, AD_READONLY.  Example:
    REM   If username = "pat" Then
    REM      fldcolumn_Permission = AD_READONLY
    REM   Else
    REM      fldcolumn_Permission = AD_OPTIONAL
    REM   End If

	dim ac_sIntegrationVar
	dim oSession
	dim a_sVal

	ac_sIntegrationVar = "CQI_Integration"

	fldcolumn_Permission = AD_READONLY

	set oSession = GetSession
	If oSession.HasValue(ac_sIntegrationVar) Then
		a_sVal = oSession.NameValue(ac_sIntegrationVar)
		if a_sVal = "Running" then
			fldcolumn_Permission = AD_OPTIONAL
		end if	
	end if
	
	set oSession = nothing


program:
REM return one of AD_MANDATORY, AD_OPTIONAL, AD_READONLY.  Example:
    REM   If username = "pat" Then
    REM      revision_Permission = AD_READONLY
    REM   Else
    REM      revision_Permission = AD_OPTIONAL
    REM   End If
		dim ac_sIntegrationVar
	dim oSession
	dim a_sVal

	ac_sIntegrationVar = "CQI_Integration"

	revision_Permission = AD_READONLY

	set oSession = GetSession
	If oSession.HasValue(ac_sIntegrationVar) Then
		a_sVal = oSession.NameValue(ac_sIntegrationVar)
		if a_sVal = "Running" then
			revision_Permission = AD_OPTIONAL
		end if	
	end if
	
	set oSession = nothing


program:
REM return one of AD_MANDATORY, AD_OPTIONAL, AD_READONLY.  Example:
    REM   If username = "pat" Then
    REM      type_guid_Permission = AD_READONLY
    REM   Else
    REM      type_guid_Permission = AD_OPTIONAL
    REM   End If
	
	dim ac_sIntegrationVar
	dim oSession
	dim a_sVal

	ac_sIntegrationVar = "CQI_Integration"

	type_guid_Permission = AD_READONLY

	set oSession = GetSession
	If oSession.HasValue(ac_sIntegrationVar) Then
		a_sVal = oSession.NameValue(ac_sIntegrationVar)
		if a_sVal = "Running" then
			type_guid_Permission = AD_OPTIONAL
		end if	
	end if
	
	set oSession = nothing


program:
Function UCM_CQActAfterDeliver_Def (entity_type, entity_id)

  ' This implements the default behavior when the "Perform ClearQuest Action
  ' After Deliver" policy is enabled: Default is to do the delivery
  ' for all activities
  '
  ' INPUT:
  '  - entity_type: type of entity being delivered
  '  - entity_id: id (e.g. "SAMPL0000001") of entity being delivered
  ' OUTPUT:
  '  - If the activity should be delivered, this should return an empty string
  '  - If the activity should not be delivered, this should return a string
  '    to be displayed as an error message. This will cause the delivery to
  '    be aborted.

  UCM_CQActAfterDeliver_Def = "" 

End Function


program:
sub UCU_ChkBeforeDeliver {

  # This is the script which implements the "Check Before ClearCase Delivery"
  # policy. When initially installed, it invokes a default script.
  # If users want to customize this policy, they should edit this script
  # to use their code rather than invoking the default script. The default
  # script code can be used as an example.
  #
  # INPUT:
  #  - entity_type: type of entity on which action will be executed
  #  - entity_id:   id (e.g. "SAMPL0000001") of entity on which action will be
  #                 executed
  #  - target_stream_selector: target stream selector
  #  - target_view_tag: target view tag
  #
  # OUTPUT:
  #  - If the action was successfully executed, this must return an empty
  #    string
  #  - If the action was not successfully executed, this must return a string
  #    to be displayed as an error message.

  my ($entity_type, $entity_id, $target_stream_selector, $target_view_tag) = @_;
  my $result;

  $result = UCU_ChkBeforeDeliver_Def($entity_type, $entity_id);

  return $result;
}


program:
Function UCM_CQActAfterDeliver (entity_type, entity_id, target_stream_selector, target_view_tag)

  ' This is the script which implements the "Do ClearQuest Action After 
  ' Delivery" policy. When initially installed, it invokes a default script.
  ' If users want to customize this policy, they should edit this script
  ' to use their code rather than invoking the default script. The default
  ' script code can be used as an example.
  '
  ' INPUT:
  '  - entity_type: type of entity on which action will be executed
  '  - entity_id:   id (e.g. "SAMPL0000001") of entity on which action will be
  '                 executed
  '  - target_stream_selector: target stream selector
  '  - target_view_tag: target view tag
  '
  ' OUTPUT:
  '  - If the action was successfully executed, this must return an empty
  '    string
  '  - If the action was not successfully executed, this must return a string
  '    to be displayed as an error message.
  '
  ' RULES: This script must be written such that, if it is called more than
  '        once for the same entity during the same deliver operation, it 
  '        handles it correctly. This case can arise if a deliver operation

  '        is aborted then resumed.
  '  
                      
  UCM_CQActAfterDeliver = UCM_CQActAfterDeliver_Def(entity_type, entity_id)
                        
End Function


program:
Function UCM_ChkBeforeWorkOn (entity_type, entity_id, stream)

  ' This is the script which implements the "Check Before Work On"
  ' policy. When initially installed, it invokes a default script.
  ' If users want to customize this policy, they should edit this script
  ' to use their code rather than invoking the default script. The default
  ' script code can be used as an example.
  '
  ' INPUT:
  '  - entity_type: type of entity on which action will be executed
  '  - entity_id:   id (e.g. "SAMPL0000001") of entity on which action will be
  '                 executed
  '  - stream:      stream on which the entity is being worked on
  ' OUTPUT:
  '  - If the action was successfully executed, this must return an empty
  '    string
  '  - If the action was not successfully executed, this must return a string
  '    to be displayed as an error message.
                      
  UCM_ChkBeforeWorkOn = UCM_ChkBeforeWorkOn_Def(entity_type, entity_id)
                        
End Function


program:
Function UCM_ChkBeforeDeliver (entity_type, entity_id, target_stream_selector, target_view_tag)

  ' This is the script which implements the "Check Before ClearCase Delivery"
  ' policy. When initially installed, it invokes a default script.
  ' If users want to customize this policy, they should edit this script
  ' to use their code rather than invoking the default script. The default
  ' script code can be used as an example.
  '
  ' INPUT:
  '  - entity_type: type of entity on which action will be executed
  '  - entity_id:   id (e.g. "SAMPL0000001") of entity on which action will be
  '                 executed
  '  - target_stream_selector: target stream selector
  '  - target_view_tag: target view tag
  '
  ' OUTPUT:
  '  - If the action was successfully executed, this must return an empty
  '    string
  '  - If the action was not successfully executed, this must return a string
  '    to be displayed as an error message.
                      
  UCM_ChkBeforeDeliver = UCM_ChkBeforeDeliver_Def(entity_type, entity_id)
                        
End Function


program:
sub UCU_CQActAfterChact {

  # This is the script which implements the "Perform Action After 
  # Changing Activity" policy. When initially installed, it invokes a default script.
  # If users want to customize this policy, they should edit this script
  # to use their code rather than invoking the default script. The default
  # script code can be used as an example.
  #
  # INPUT:
  #  - entity_type: type of entity on which action will be executed
  #  - entity_id:   id (e.g. "SAMPL0000001") of entity on which action will be
  #                 executed
  #  - project_info: "SIMPLE" if activity is in a single stream project, 
  #                  "DEFAULT" if activity is in a regular project
  #  - stream_info: "INT" if activity is in project's integration stream
  #                 "DEV" if activity is not in project's integration stream
  #         
  # OUTPUT:
  #  - If the action was successfully executed, this must return an empty
  #    string
  #  - If the action was not successfully executed, this must return a string
  #    to be displayed as an error message.
  #
  # RULES: This script must be written such that, if it is called more than
  #        once for the same entity during the same deliver operation, it 
  #        handles it correctly. This case can arise if a deliver operation
  #        is aborted then resumed.
  #  

  my ($entity_type, $entity_id, $project_info, $stream_info) = @_;
  my $result;

  $result = UCU_CQActAfterChact_Def($entity_type, $entity_id, $project_info, $stream_info);

  return $result;
}


program:
sub UCU_CQActBeforeChact {

  # This is the script which implements the "Perform Action Before
  # Changing Activity" policy. When initially installed, it invokes a default script.
  # If users want to customize this policy, they should edit this script
  # to use their code rather than invoking the default script. The default
  # script code can be used as an example.
  #
  # INPUT:
  #  - entity_type: type of entity on which action will be executed
  #  - entity_id:   id (e.g. "SAMPL0000001") of entity on which action will be
  #                 executed
  #  - project_info: "SIMPLE" if activity is in a single stream project, 
  #                  "DEFAULT" if activity is in a regular project
  #  - stream_info: "INT" if activity is in project's integration stream
  #                 "DEV" if activity is not in project's integration stream
  # OUTPUT:
  #  - If the action was successfully executed, this must return an empty
  #    string
  #  - If the action was not successfully executed, this must return a string
  #    to be displayed as an error message.
  #
  # RULES: This script must be written such that, if it is called more than
  #        once for the same entity during the same deliver operation, it 
  #        handles it correctly. This case can arise if a deliver operation
  #        is aborted then resumed.
  #  

  my ($entity_type, $entity_id, $project_info, $stream_info) = @_;
  my $result;

  $result = UCU_CQActBeforeChact_Def($entity_type, $entity_id, $project_info, $stream_info);

  return $result;
}


program:
Function UCM_CQActAfterChact (entity_type, entity_id, project_info, stream_info)

  ' This is the script which implements the "Perform Action After Changing Activity"
  ' policy. When initially installed, it invokes a default script.
  ' If users want to customize this policy, they should edit this script
  ' to use their code rather than invoking the default script. The default
  ' script code can be used as an example.
  '
  ' INPUT:
  '  - entity_type: type of entity on which action will be executed
  '  - entity_id:   id (e.g. "SAMPL0000001") of entity on which action will be
  '                 executed
  '  - project_info: "SIMPLE" if activity is in a single stream project, 
  '                  "DEFAULT" if activity is in a regular project
  '  - stream_info: "INT" if activity is in project's integration stream
  '                 "DEV" if activity is not in project's integration stream
  ' OUTPUT:
  '  - If the action was successfully executed, this must return an empty
  '    string
  '  - If the action was not successfully executed, this must return a string
  '    to be displayed as an error message.
                      
  UCM_CQActAfterChact = UCM_CQActAfterChact_Def(entity_type, entity_id, project_info, stream_info)
                        
End Function


program:
Function UCM_CQActBeforeChact (entity_type, entity_id, project_info, stream_info)

  ' This is the script which implements the "Perform Action Before Changing Activity"
  ' policy. When initially installed, it invokes a default script.
  ' If users want to customize this policy, they should edit this script
  ' to use their code rather than invoking the default script. The default
  ' script code can be used as an example.
  '
  ' INPUT:
  '  - entity_type: type of entity on which action will be executed
  '  - entity_id:   id (e.g. "SAMPL0000001") of entity on which action will be
  '                 executed
  '  - project_info: "SIMPLE" if activity is in a single stream project, 
  '                  "DEFAULT" if activity is in a regular project
  '  - stream_info: "INT" if activity is in project's integration stream
  '                 "DEV" if activity is not in project's integration stream
  ' OUTPUT:
  '  - If the action was successfully executed, this must return an empty
  '    string
  '  - If the action was not successfully executed, this must return a string
  '    to be displayed as an error message.
                      
  UCM_CQActBeforeChact = UCM_CQActBeforeChact_Def(entity_type, entity_id, project_info, stream_info)
                        
End Function


program:
sub UCU_CQActAfterDeliver {

  # This is the script which implements the "Do ClearQuest Action After 
  # Delivery" policy. When initially installed, it invokes a default script.
  # If users want to customize this policy, they should edit this script
  # to use their code rather than invoking the default script. The default
  # script code can be used as an example.
  #
  # INPUT:
  #  - entity_type: type of entity on which action will be executed
  #  - entity_id:   id (e.g. "SAMPL0000001") of entity on which action will be
  #                 executed
  #  - target_stream_selector: target stream selector
  #  - target_view_tag: target view tag
  #
  # OUTPUT:
  #  - If the action was successfully executed, this must return an empty
  #    string
  #  - If the action was not successfully executed, this must return a string
  #    to be displayed as an error message.
  #
  # RULES: This script must be written such that, if it is called more than
  #        once for the same entity during the same deliver operation, it 
  #        handles it correctly. This case can arise if a deliver operation
  #        is aborted then resumed.
  #  

  my ($entity_type, $entity_id, $target_stream_selector, $target_view_tag) = @_;
  my $result;

  $result = UCU_CQActAfterDeliver_Def($entity_type, $entity_id);

  return $result;
}


program:
sub UCU_ChkBeforeWorkOn {

  # This is the script which implements the "Check Before Work On"
  # policy. When initially installed, it invokes a default script.
  # If users want to customize this policy, they should edit this script
  # to use their code rather than invoking the default script. The default
  # script code can be used as an example.
  #
  # INPUT:
  #  - entity_type: type of entity on which action will be executed
  #  - entity_id:   id (e.g. "SAMPL0000001") of entity on which action will be
  #                 executed
  #  - stream:      stream on which the entity is being worked on
  # OUTPUT:
  #  - If the action was successfully executed, this must return an empty
  #    string
  #  - If the action was not successfully executed, this must return a string
  #    to be displayed as an error message.

  my ($entity_type, $entity_id, $stream) = @_;
  my $result;

  $result = UCU_ChkBeforeWorkOn_Def($entity_type, $entity_id);

  return $result;
}


program:
sub UCU_ChkBeforeDeliver_Def {

  # This implements the default behavior when the "Perform ClearQuest Action
  # Before Delivery" policy is enabled: Default is to do the delivery
  # for all activities
  #
  # INPUT:
  #  - entity_type: type of entity being delivered
  #  - entity_id: id (e.g. "SAMPL0000001") of entity being delivered
  # OUTPUT:
  #  - If the activity should be delivered, this should return an empty string
  #  - If the activity should not be delivered, this should return a string
  #    to be displayed as an error message. This will cause the delivery to
  #    be aborted.

  my $result = "";
  return $result;
}


program:
sub UCU_ChkBeforeWorkOn_Def {

  # This implements the default behavior when the "Perform ClearQuest Action
  # Before Work On" policy is enabled: It only allows user to work on the entity
  # if it is assigned to them.
  #
  # INPUT:
  #  - entity_type: type of entity being worked on
  #  - entity_id: id (e.g. "SAMPL0000001") of entity being worked on
  # OUTPUT:
  #  - If the current user is permitted to work on this entity, this should
  #    return an empty string
  #  - If the current user is not permitted to work on this entity, this
  #    should return a string to be displayed as an error message. This
  #    will cause the Work On action to be aborted.

  my ($entity_type, $entity_id) = @_;
  my $result;

  # Get the entity
  my $entity = $session->GetEntity($entity_type, $entity_id);

  # Get the entity's assigned user
  my $field_info = $entity->GetFieldValue("Owner");
  my $assigned_user = $field_info->GetValue();

  # Get current user from session
  my $current_user = $session->GetUserLoginName();
 
  # Check the assigned_user
  if ($assigned_user eq $current_user) {
      # User is permitted to work on entity, return empty string
      $result = "";
      }
  elsif ($assigned_user eq "") {
      # User is not permitted to work on un-assigned entity, return error string
      $result = "You cannot work on this $entity_type because it is not assigned to an Owner.";
      }
  else {
      # User is not permitted to work on mis-assigned entity, return error string      
      $result = "You cannot work on this $entity_type because its Owner is \"$assigned_user\", not \"$current_user\"";
      }

  return $result;
}


program:
sub UCU_CQActAfterDeliver_Def {

  # This implements the default behavior when the "Do ClearQuest Action
  # After ClearCase Delivery" policy is enabled: Default is to do the delivery
  # for all activities
  #
  # INPUT:
  #  - entity_type: type of entity being delivered
  #  - entity_id: id (e.g. "SAMPL0000001") of entity being delivered
  # OUTPUT:
  #  - If the activity should be delivered, this should return an empty string
  #  - If the activity should not be delivered, this should return a string
  #    to be displayed as an error message. This will cause the delivery to
  #    be aborted.

  my $result = "";
  return $result;
}


program:
Function UCM_CQActBeforeChact_Def (entity_type, entity_id, project_info, stream_info)

  ' This implements the default behavior when the "Perform ClearQuest Action
  ' Before Changing Activity" policy is enabled: Default is do chact
  ' for all activities
  '
  ' INPUT:
  '  - entity_type: type of entity being changed
  '  - entity_id: id (e.g. "SAMPL0000001") of entity being changed
  '  - project_info:
  '    "SIMPLE": this project is a single stream project
  '    "DEFAULT": this project is NOT a single stream project 
  '  - stream_info:
  '    "INT": this stream is project's integration stream
  '    "DEV": this stream is not project's integration stream
  ' OUTPUT:
  '  - If the activity should be changed, this should return an empty string
  '  - If the action should not be changed, this should return a string
  '    to be displayed as an error message. This will cause the chact to
  '    be aborted.
  UCM_CQActBeforeChact_Def = ""
  
End Function


program:
Function UCM_CQActAfterChact_Def (entity_type, entity_id, project_info, stream_info)

  ' This implements the default behavior when the "Perform ClearQuest Action
  ' After Changing Activity" policy is enabled: Default is do nothing
  ' for all activities
  '
  ' INPUT:
  '  - entity_type: type of entity being changed
  '  - entity_id: id (e.g. "SAMPL0000001") of entity being changed
  '  - project_info:
  '    "SIMPLE": this project is a single stream project
  '    "DEFAULT": this project is NOT a single stream project 
  '  - stream_info:
  '    "INT": this stream is project's integration stream
  '    "DEV": this stream is not project's integration stream
  ' OUTPUT:
  '  - If the action was successful, this should return an empty string
  '  - If the action was unsuccessful, this should return a string
  '    to be displayed as an error message. This will cause the chact to
  '    be aborted.

  if project_info = "SIMPLE" Then
      ' User is permitted to do the transition, policies allowing
	  UCM_CQActAfterChact_Def = ""
  ElseIf stream_info = "INT" Then
      ' User is permitted to do the transition, policies allowing
	  UCM_CQActAfterChact_Def = ""
  Else
      ' User is NOT permitted to do the transition
	  UCM_CQActAfterChact_Def = "You cannot complete " + entity_id + " because it is not in a single stream project or in a project's integration stream"
  End If

End Function


program:
sub UCU_CQActBeforeChact_Def {

  # This implements the default behavior when the "Perform ClearQuest Action
  # Before Changing Activity" policy is enabled: Default is to do the chact
  # for all activities
  #
  # INPUT:
  #  - entity_type: type of entity being changed
  #  - entity_id: id (e.g. "SAMPL0000001") of entity being changed
  #  - project_info:
  #    "SIMPLE": this project is a single stream project
  #    "DEFAULT": this project is NOT a single stream project 
  #  - stream_info:
  #    "INT": this stream is project's integration stream
  #    "DEV": this stream is not project's integration stream
  # OUTPUT:
  #  - If the activity should be changed, this should return an empty string
  #  - If the activity should not be changed, this should return a string
  #    to be displayed as an error message. This will cause the chact to
  #    be aborted.

  my $result = "";
  return $result;
}


program:
sub UCU_CQActAfterChact_Def {

  # This implements the default behavior when the "Perform ClearQuest Action
  # After Changing Activity" policy is enabled: Default is to do nothing
  # for all activities
  #
  # INPUT:
  #  - entity_type: type of entity being changed
  #  - entity_id: id (e.g. "SAMPL0000001") of entity being changed
  #  - project_info:
  #    "SIMPLE": this project is a single stream project
  #    "DEFAULT": this project is NOT a single stream project 
  #  - stream_info:
  #    "INT": this stream is project's integration stream
  #    "DEV": this stream is not project's integration stream
  # OUTPUT:
  #  - If the action was successful, this should return an empty string
  #  - If the action was not successful, this should return a string
  #    to be displayed as an error message. This will cause the chact to
  #    be aborted.
 
  my ($entity_type, $entity_id, $project_info, $stream_info) = @_;
  my $result = "";

  if ($project_info eq "SIMPLE") {
    # allow the UCM change activity
	$result = "";
  } 
  elsif ($stream_info eq "INT") {
    # allow the UCM change activity
	$result = "";
  }
  else {
    # dissallow UCM change activity
	$result = "You cannot complete " . $entity_id . "because it is not in a single stream project or in a project's integration stream";
  }

  return $result;
}


program:
# This hook will be run each time the field's value changes.
    # This hook runs before the new value is validated so be aware
    # the new value may not be valid.
    # Example:
    #   my $op_sys = $entity->GetFieldValue($fieldname)->GetValue();
    #   if ($op_sys eq "windows") {
    #      $entity->SetFieldValue("os_version", "NT 4.x");
    #      <etc.>
    #   }      
	 my $script = $entity->GetFieldValue($fieldname)->GetValue();
     if( $script eq NULL || $script eq "" ) {
        $entity->SetFieldValue("DefaultScriptOptions", "" );
        $entity->SetFieldValue("DefaultScriptType","" );
    }


program:
# Return a non-empty string explaining why the field's current
    # value is not valid. If it is valid, return an empty string.
	$scriptValue = $entity->GetFieldValue($fieldname)->GetValue();
	$testTypeValue = $entity->GetFieldValue("DefaultScriptType")->GetValue();

	# Since we're the only ones who ever set the default script type, we don't need to make it
	# mandatory.


program:
1 - Critical
2 - High
3 - Medium
4 - Low


program:
my $plan = $entity->GetFieldValue("ParentPlan")->GetValue();
    if (($plan eq "") || ($plan eq NULL)) {
	 	return $result;
	}



	my $assetRegistry = $session->GetEntity("TMTestPlan", $plan)->GetFieldValue("AssetRegistry")->GetValue();


    if (($assetRegistry eq "") || ($assetRegistry eq NULL)) {
        return $result;
     }


	 my $refFormIterations = $entity->GetFieldValue("Iterations")->GetValueAsList();

	 my $refAssetIterations = $session->GetEntity("TMAssetRegistry",$assetRegistry )->GetFieldValue("Iterations")->GetValueAsList();

	 my @assetIterations = @$refAssetIterations;
	 my @formIterations = @$refFormIterations;


	# can't have more form iterations than there are for the actual assetRegistry, 
	 if( $#assetIterations < $#formIterations) {

	 	$result = "Some Iterations do not belong to the Asset Registry";
	 }
	 else {
			# now see if all of the iterations are part of the asset registryf
			foreach  $formIt (@formIterations ) {

				my $found = 0;
				foreach $assetIt (@assetIterations) {

					if($assetIt eq $formIt ){
						$found = 1;
						last;
					}
				}

				if( $found < 1 ){
					$result = "Some Iterations do not belong to the Asset Registry";
					last;
				}
				$found = 0;
			}
	 }


program:
REM Return a non-empty string explaining why the action
   REM cannot commit with the current values.
   REM Or, if it is valid, return an empty string value.
   REM Example: 
   REM    Dim value_info
   REM    Set value_info = GetFieldValue("some field")
   REM    If Len(value_info.GetValue()) < 10 Then
   REM        TMTestCase_Validation = "Must be at least 10 chars long"
   REM    End If

REM Checks if associations still exist with current CQ record when user tries to delete it
REM if none, deletion completed
REM if some, deletion canceled

	Dim a_CurrentActionType					'Action type of the action that initiated the execution of this script

	a_CurrentActionType = GetActionType()
   'Check to see if the real action is a delete action.
	'If not exit.
	if a_CurrentActionType = AD_DELETE then
		'Don't allow user to delete the current record unless no requirements are
		'associated with it
		Dim ac_sCQReqListAttName				'Name of the global variable containing the name of the field of the CQ record that stores associations
		Dim a_vTableDBIDs							'List of DBIDs of Req proxies associated to the current CQ record
	
		ac_sCQReqListAttName= "Requirements_List"
' RATLC00015495 
'		a_vTableReqIds = GetFieldValue(ac_sCQReqListAttName).GetValueAsList		
        a_vTableDBIDs = GetFieldValue(ac_sCQReqListAttName).GetValueAsList
		if IsEmpty(a_vTableDBIDs) then
'			EnhancementRequest_Validation = vbNullString		
		TMTestCase_Validation = vbNullString		
		else
'			EnhancementRequest_Validation = "Rational RequisitePro/ClearQuest Integration: You have to remove all associations with RequisitePro requirements before you can delete the current ClearQuest record."	    	
			TMTestCase_Validation = "Rational RequisitePro/ClearQuest Integration: You have to remove all associations with RequisitePro requirements before you can delete the current ClearQuest record."
		end if
	end if	'a_CurrentActionType


program:
REM Check the requirement type for its type guid
   REM Check the type of the current record type
   REM pull up a requirement map for this record type
   REM see if the requirement type guid is the same as the guid 
   REM for the requirement that is being added.
	
	' Get all the requirement types that this artifact can be associated to
	Dim session, reqList, listItem, tempReq, recordType
	
	TMTestCase_Validation = ""
	Set session = GetSession
	recordType = GetEntityDefName

	Dim queryDef, queryField, operator, filterNode, resultSet
	Dim ac_sTagField
	Dim ac_sNameField
	
	ac_sTagField = "Tag"
	ac_sNameField = "Name"

	Set queryDef = session.BuildQuery("RequirementMap")
	If Not queryDef is Nothing then
	' Building the query
		queryField = queryDef.BuildField("RPReqTypeGUID")
		Set operator = queryDef.BuildFilterOperator(AD_COMP_OP_EQ)
		operator.BuildFilter "CQEntityDefName",	AD_COMP_OP_EQ, recordType
		Set resultSet = session.BuildResultSet(queryDef)
		resultSet.Execute()

		Dim found, tempGUID, counter, status, GUIDs

		Set GUIDs = CreateObject("Scripting.dictionary")

		found = False
		counter = 0
		status = resultSet.MoveNext
	'	build the requirement types GUIDs array
		Do While status = AD_SUCCESS 
			tempGUID = resultSet.GetColumnValue(1)
			GUIDs.Add counter, tempGUID
			counter = counter + 1
		 	status = resultSet.MoveNext
		 Loop 

	'	Retrieve all the requirements that are associated to the current artifact
		Dim tempReqList
		tempReqList = GetFieldValue("Requirements_List").GetValue	

		If tempReqList <> "" then
		'	Break the string of line feed separated requirement ids in to an array
			Dim array ' array of requirements
			Dim u ' number of elements in the array
			Dim result
			result = ""
		'	Splitting it
		  	array = Split(Cstr(tempReqList),vbLF)
			u = UBound(array)
			Dim ReqId, requirement, reqTypeGUID
		'	Check if the requirement's type is in the list of allowed requirement GUIDs list
			For i = 0 To u
				found = False
				ReqId = array(i)
			'	Get the requirement
				Set requirement = session.GetEntity("Requirement", ReqId)
				If Not requirement Is Nothing Then
					Dim fieldDef 
				'	Get the requirement type
					reqTypeGUID = requirement.GetFieldValue("Type_GUID").GetValue
				'	Check to see if the GUID is matching with the existing list
					For j = 0 to GUIDs.count
						If GUIDs.Item(j) <> "" Then
							If GUIDs.Item(j) = reqTypeGUID Then
							'	Found it so dont need to loop anymore
								found = True
								Exit For
							End If
						Else
							'	Valid guid's are done so skip
							Exit For
						End If
					Next

				End If
			'	Create the erroneous list of requirements

				If Not found Then
					Dim sReq
					Dim sName
					
					sName = requirement.GetFieldValue(ac_sNameField).GetValue
					sReq = requirement.GetFieldValue(ac_sTagField).GetValue
					' Limiting the name length to about 30 characters for display
					if len(sName) = 0 then
						result = result & vbLF & sReq
					elseif len(sText) > 33 then
						result = result & vbLF & sReq & ": " & left(sName, 30) + "..."
					else
						result = result & vbLF & sReq & ": " & sName
					end if
				end if				
			Next
			'	Check to see if the erroneous list of requirements is empty or not
			If result <> "" Then
			'	if the list is not empty create the error message.
				TMTestCase_Validation = "The following Requirements types dont match " & result
			End If
		End If

	End If


program:
$result = "This operation is not supported in this client.";


program:
REM add your hook code here

REM Launch RequisitePro Association dialog box, with list of Req Proxy DBIDs of Requirements already associated to current CQ record
REM if return of call is OK
REM	Position state of state machine to "MODIFIED"
REM if return of call is Cancel


	Dim eRet_Empty
	Dim eRet_OK
	Dim eRet_Cancel
	Dim eRet_Error
	Dim ac_sCQReqListAttName				'Name of the global variable containing the name of the field of the CQ record that stores associations
	Dim ac_sCQIStateVar						'Name of the global variable containing the current state of the state machine
	Dim ac_sCQIListReqsVar					'Name of the global variable containing the list of Proxy Req DBIDs associated to the current CQ record
	Dim ac_sCQIdbidSeparator				'Character used to separate dbids in string list 
	Dim a_bWeb									'Web or not
	Dim a_bIsRunningIntegration			'Contains a boolean indicating if the integration is already in progress, to prevent reccurence
	Dim a_bProjectSet							'Contains a boolean indicating if a Rational Project has been selected for the current CQ record
	Dim a_oCQSession							'Current CQ session
	Dim a_oRequisiteProTool					'Reference to a ASCQIIntegration.RequisiteProTool instance
	Dim a_sListReqDBIDs						'List of Req Proxy DBIDs associated to the current CQ record
	Dim a_eRet									'Contains value returned by the call to integration
	Dim a_sError								'Error message sent back by integration in case of a failure
	Dim a_vTableDBIDs							'List of DBIDs of Req proxies associated to the current CQ record
	Dim a_lIndex
	Dim a_sFail									'Return value of the creation of the association in ClearQuest between current CQ record and the Req Proxy

	eRet_Empty = 0
	eRet_OK = 1
	eRet_Cancel = 2
	eRet_Error = 3	

	ac_sCQReqListAttName= "Requirements_List"	
	ac_sCQIStateVar = "CQIState"
	ac_sCQIListReqsVar = "CQIReqs"
	ac_sCQIdbidSeparator = ","
	
	a_bWeb = Check_Web()

	' RATLC01009865 - Display message for non-functional button in CQWeb
	if a_bWeb then
		' Need this Error handler otherwise it does not work from CQWeb.
		On Error resume next
	 	err.clear

		TMTestCase_CQI_Select_Req = "This operation is not available in the Web client."
		return
	end if	


   'This script must no be launched through the web
	'We also test if the record is editable
	If (IsEditable AND NOT a_bWeb) Then

		if Check_RAProjectMaster then
			a_bIsRunningIntegration = CQI_IsRunningIntegration()
			if not a_bIsRunningIntegration then
				a_bProjectSet = Check_Project()
				if a_bProjectSet then
				 	Set a_oCQSession = GetSession
					if not a_oCQSession is nothing then
						set a_oRequisiteProTool = CQI_GetRequisiteProTool()	
						if a_oRequisiteProTool is nothing then
							msgbox "ClearQuest could not connect to the Integration Server." + vbcrlf + "Please contact your Administrator.", vbOKOnly + vbCritical, "Rational RequisitePro/ClearQuest Integration"
						else
							' RATLC01201983 - Do not use list of requirements when beginning to modify the record.
							' instead use the current list of requirements
							' a_sListReqDBIDs = a_oCQSession.NameValue(ac_sCQIListReqsVar)
							a_vTableDBIDs = getfieldValue(ac_sCQReqListAttName).GetValueAsList
							if not IsEmpty(a_vTableDBIDs) then
								CQI_GetListFromDBIDTable a_vTableDBIDs, ac_sCQIdbidSeparator, a_sListReqDBIDs
							end if   ' a_vTableDBIDs

							a_eRet = a_oRequisiteProTool.AssociateFromClearQuest(me, ac_sCQReqListAttName, a_sListReqDBIDs, a_sError)
							Select Case a_eRet
							   	Case eRet_OK
									a_oCQSession.NameValue(ac_sCQIStateVar)= "MODIFIED" 
									if a_sListReqDBIDs <> vbNullString then
										a_vTableDBIDs = empty
										if CQI_GetTableFromDBIDList(a_sListReqDBIDs, ac_sCQIdbidSeparator, a_vTableDBIDs) then
											if not IsEmpty(a_vTableDBIDs) then
												for a_lIndex = LBound(a_vTableDBIDs) to UBound(a_vTableDBIDs)
											        a_sFail = AddFieldValue(ac_sCQReqListAttName, cstr(a_vTableDBIDs(a_lIndex)))
													if a_sFail = vbNullString then
														call CQI_AddDBIDToList(cstr(a_vTableDBIDs(a_lIndex)), ac_sCQIdbidSeparator)
													end if	'a_sFail
												next
											end if
										end if
									end if
				
						      Case eRet_Cancel

								Case Else		
									msgbox a_sError ,vbOKOnly + vbCritical, "Rational RequisitePro/ClearQuest Integration"
				
							End Select
						end if	'a_oRequisiteProTool
					end if	'a_oCQSession
				else
					if GetEntityDefName = "EnhancementRequest" and GetActionType = AD_SUBMIT then
						msgbox "In order to associate a requirement, you must first submit the EnhancementRequest record.", vbOKOnly + vbInformation, "Rational RequisitePro/ClearQuest Integration"
					else 						
						MsgBox "A valid RAProject must be selected.", vbOKOnly + vbInformation, "Rational RequisitePro/ClearQuest Integration"
					end if
				end if	'a_bProjectSet
			else								  
				msgbox "Modification (or viewing) of Requirement properties cannot be done at this point, as the Clearquest information is currently displayed from RequisitePro. Please access the Requirement Properties dialog from RequisitePro.", vbOKOnly + vbInformation, "Rational RequisitePro/ClearQuest Integration" 
			end if	'a_bIsRunningIntegration

		else								  
			msgbox "This ClearQuest/RequisitePro integration operation is not supported. This ClearQuest record is associated with a Rational project that is not accessible from your local area network.", vbOKOnly + vbInformation, "Rational RequisitePro/ClearQuest Integration" 
		end if	'Check_RAProjectMaster
	end if	'a_bWeb

	set a_oRequisiteProTool = nothing
	set a_oCQSession = nothing


program:
REM add your hook code here

REM Launch RequisitePro Properties dialog box for the selected Requirement in the CQ list box, and pass its DBID 
REM if return of call is ePrp_OK
REM	Nothing is done
REM if return of call is ePrp_Removed
REM	then the requirement is removed fromlist of requirement associated with current CQ record

	On Error resume next	'handle ListSelection empty
	err.clear

	Dim a_bWeb									'Web or not
	Dim a_bIsRunningIntegration			'Contains a boolean indicating if the integration is already in progress, to prevent reccurence
	Dim a_oCQSession							'Current CQ session
	Dim a_lNumberSel							'Number of Requirements currently selected in the CQ List Box
	Dim a_sStrElm								'CQ Key of the Req Proxy selected in the CQ List Box (currently dbid)
	Dim a_sDBID									'DBID of the Req Proxy selected in the CQ List Box
	Dim a_bEmpty								'Boolean indicationg wether or not a Req Proxy is selected in the CQ List Box
	Dim a_sError								'Error message sent back by integration in case of a failure
	Dim a_sFail									'Return value of the deletion of the association in ClearQuest between current CQ record and the Req Proxy
 	dim a_oReq									' selected Requirement record
	Dim vRet									' Generic return value
	Dim ac_sCQReqListAttName
	
	ac_sCQReqListAttName= "Requirements_List"

	a_bWeb = Check_Web()

	' RATLC01009865 - Display message for non-functional button in CQWeb
	if a_bWeb then
		TMTestCase_CQI_Properties_Req = "You cannot view a requirement from this record in the Web client. Open the requirement record and select View."
		return
	end if	

   'This script must not be launched through the web
	'We also test if the record is editable
	If (IsEditable AND NOT a_bWeb) Then
		a_bIsRunningIntegration = CQI_IsRunningIntegration()
		if not a_bIsRunningIntegration then
		 	Set a_oCQSession = GetSession
			if not a_oCQSession is nothing then
				if Check_Eclipse() then
					' Handle the selection differently for CQ Eclipse.
					' param = string of selected DBIDs separated by Line Feed.
					Dim sParam 
					Dim bGotOne

					sParam = cstr(param)
					bGotOne = false
					' There is an extra LF added at the end of every DBID 
					' even for one selection. The code below handles both the 
					' cases, with and without the last LF.
					if len(sParam) > 1 then
					    If InStrRev(sParam, vbLf) = Len(sParam) Then
					    	If InStrRev(Left(sParam, Len(sParam) - 1), vbLf) = 0 Then
					            ' There is an extra LF at the end of the string
					            a_sDBID = Left(sParam, Len(sParam) - 1)
					            bGotOne = True
					        End If
					    Else
					        If InStrRev(sParam, vbLf) = 0 Then
					            a_sDBID = sParam
					            bGotOne = True
					        End If
					    End If
					End If

					if bGotOne then
						set a_oReq = a_oCQSession.GetEntity("Requirement", a_sDBID)
						if not a_oReq is nothing then
							vRet = a_oReq.FireNamedHook("CQI_Properties_Req", "")
							set a_oReq = nothing
						end if
					else
						MsgBox "Please select one requirement in the list view to get the properties.", vbOKOnly + vbInformation, "Rational RequisitePro/ClearQuest Integration"
					end if
				else
					a_lNumberSel = 0
					For Each a_sStrElm In param.ListSelection
						a_sDBID = a_sStrElm
						a_lNumberSel = a_lNumberSel + 1
					Next
					a_bEmpty = IsNull(a_sDBID) or IsEmpty(a_sDBID)
					if a_bEmpty then
						'Nothing to do
						MsgBox "Please select one requirement in the list view to get the properties.", vbOKOnly + vbInformation, "Rational RequisitePro/ClearQuest Integration"
					else
		on error goto 0
						if a_lNumberSel = 1 then
	 						set a_oReq = a_oCQSession.GetEntity("Requirement", a_sDBID)
	 						if not a_oReq is nothing then
	 							vRet = a_oReq.FireNamedHook("CQI_Properties_Req", "")
	 						end if
	 				   	else
							MsgBox "Please select one requirement in the list view to get the properties.", vbOKOnly + vbInformation, "Rational RequisitePro/ClearQuest Integration"
						end if
					end if	'a_bEmpty
				end if ' Check_Eclipse()

				' RATLC01011263 - If the Requirement is deleted from RP. Prompt user to remove the association 
				if vRet = "DELETED" then
					vRet = Msgbox ("The requirement has been deleted in Rational RequisitePro." _
									+ vbcrlf+ "Do you want to remove the association?", _
									vbYesNo + vbQuestion, _
									"Rational RequisitePro/ClearQuest Integration")
					if vRet = vbYes then
						DeleteFieldValue ac_sCQReqListAttName, a_sDBID
					end if
				end if

			end if	'a_oCQSession
		else								  
			msgbox "Modification (or viewing) of Requirement properties cannot be done at this point, as the Clearquest information is currently displayed from RequisitePro. Please access the Requirement Properties dialog from RequisitePro.", vbOKOnly + vbInformation, "Rational RequisitePro/ClearQuest Integration" 
		end if	'a_bIsRunningIntegration
	end if	'a_bWeb

	set a_oReq = nothing
	set a_oCQSession = nothing


program:
REM add your hook code here

REM Refreshes the Requirement proxies of associated Requirements in the CQ list box
 	On Error resume next
 	err.clear

	Dim ac_sCQReqListAttName				'Name of the global variable containing the name of the field of the CQ record that stores associations
	Dim ac_sCQIdbidSeparator				'Character used to separate dbids in string list 
	Dim a_bWeb								'Web or not
	Dim a_bIsRunningIntegration				'Contains a boolean indicating if the integration is already in progress, to prevent reccurence
	Dim a_oCQSession						'Current CQ session
	Dim a_oRequisiteProTool					'Reference to a ASCQIIntegration.RequisiteProTool instance
	Dim a_sListReqDBIDs						'List of Req Proxy DBIDs associated to the current CQ record
	Dim a_vTableDBIDs						'List of DBIDs of Req proxies associated to the current CQ record
	Dim a_sError							'Error message sent back by integration in case of a failure
	Dim a_sDBIDtoRemove						'List of DBIDs of Req proxies associated to the current CQ record to remove because they don't exist anymore
	Dim a_sDBID								'DBIDs to remove
 	Dim a_oCurReq
	 dim ac_sRequirement
 	Dim ac_sReqRefreshAction
	ac_sRequirement = "Requirement" 
	ac_sReqRefreshAction = "Refresh"					  

	ac_sCQReqListAttName= "Requirements_List"	
	ac_sCQIdbidSeparator = ","

	a_bWeb = Check_Web()

	' RATLC01009865 - Display message for non-functional button in CQWeb
	if a_bWeb then
		TMTestCase_CQI_Refresh_Req = "You cannot refresh requirements from this record in the Web client. Open the requirement record and select Refresh."
		return
	end if	

   'This script must no be launched through the web
	'We also test if the record is editable, it should be as we are in an initialization hook
	If (IsEditable AND NOT a_bWeb) Then
		if Check_RAProjectMaster then
			a_bIsRunningIntegration = CQI_IsRunningIntegration()
			if not a_bIsRunningIntegration then
			 	Set a_oCQSession = GetSession
				if not a_oCQSession is nothing then
					set a_oRequisiteProTool = CQI_GetNewReqProTool()
					if a_oRequisiteProTool is nothing then
						msgbox "ClearQuest could not connect to the Integration Server." + vbcrlf + "Please contact your Administrator.", vbOKOnly + vbCritical, "Rational RequisitePro/ClearQuest Integration"
					else
						a_sError = me.Validate
						if a_sError <> vbNullString then
							MsgBox a_sError, vbOKOnly + vbInformation, _
									"Rational RequisitePro/ClearQuest Integration"
							
							if not a_oRequisiteProTool.Unload(a_sError) then
								Msgbox a_sError, vbOKOnly + vbCritical, "Rational RequisitePro/ClearQuest Integration"
	 						end if
							
							exit function
						end if

						a_vTableDBIDs = getfieldValue(ac_sCQReqListAttName).GetValueAsList
						if not IsEmpty(a_vTableDBIDs) then
 							Dim sRAProjectName
							Dim sRPProjectPath
							Dim sUserName 
							Dim sPassWord
							Dim sRequirementGUID
							dim bGotLogonInfo

							sRAProjectName = me.GetFieldValue("RAProject").GetValue
							sRPProjectPath = CQI_GetRPProjectFromRA(sRAProjectName)
							bGotLogonInfo = CQI_RPlogon(sRPProjectPath, sUserName, sPassword)
							if not bGotLogonInfo then
								if not a_oRequisiteProTool.Unload(a_sError) then
									Msgbox a_sError, vbOKOnly + vbCritical, "Rational RequisitePro/ClearQuest Integration"
		 						end if
								set a_oCQSession = nothing
							 	set a_oCurReq = nothing
							 	set a_oRequisiteProTool = nothing
								exit function
							end if

							if (LBound(a_vTableDBIDs) <= UBound(a_vTableDBIDs)) Then
								For a_lIndex = LBound(a_vTableDBIDs) To UBound(a_vTableDBIDs)
									bRefreshed = a_oRequisiteProTool.RefreshReqFromPlaceholder (GetSession(), _
															cstr(a_vTableDBIDs(a_lIndex)), _
															sRPProjectPath, _
															sUserName, _
															sPassword, _
															a_sError)
									if len (a_sError) <> 0 then
									 	MsgBox "Could not Refresh Requirement - " + a_oCurReq.GetFieldValue("Tag").GetValue + ":" + a_oCurReq.GetFieldValue("Name").GetValue + _
													vbcrlf + "Error: " + vbcrlf + a_sError, _
													vbOKOnly + vbInformation, _
													"Rational RequisitePro/ClearQuest Integration"
										err.clear	
									end if
	
								Next
							end if	'Bound vTable()
 						end if	'a_vTableDBIDs

						if not a_oRequisiteProTool.Unload(a_sError) then
							Msgbox a_sError, vbOKOnly + vbCritical, "Rational RequisitePro/ClearQuest Integration"
 						end if
					end if	'a_oRequisiteProTool
				end if	'a_oCQSession
			end if	'a_bIsRunningIntegration
		else

			msgbox "This ClearQuest/RequisitePro integration operation is not supported. This ClearQuest record is associated with a Rational project that is not accessible from your local area network.", vbOKOnly + vbInformation, "Rational RequisitePro/ClearQuest Integration" 
		end if	'Check_RAProjectMaster

	end if	'a_bWeb

	set a_oCQSession = nothing
 	set a_oCurReq = nothing
 	set a_oRequisiteProTool = nothing


program:
$result = 0;
    my $createAllowed = $session->GetNameValue("ExternalFileCreation");
    if ($createAllowed eq "true") {
        $result = 1;
        $session->SetNameValue("ExternalFileCreation", "false");
    }


program:
# Return one of
    #   $CQPerlExt::CQ_MANDATORY
    #   $CQPerlExt::CQ_OPTIONAL
    #   $CQPerlExt::CQ_READONLY
    # Example:
    #   if ($username eq "pat") {
    #      $result = $CQPerlExt::CQ_READONLY; 
    #   } else {
    #      $result = $CQPerlExt::CQ_OPTIONAL;
    #   }

    $result = $CQPerlExt::CQ_READONLY;
    my $createAllowed = $session->GetNameValue("SuiteLogCreation");
    if ($createAllowed eq "true") {
        $result = $CQPerlExt::CQ_OPTIONAL;
    }


program:
# Set $result to 1 if the user has permission to perform
    # this action, otherwise set it to 0.
    $result = 0;
    my $createAllowed = $session->GetNameValue("SuiteLogCreation");
    if ($createAllowed eq "true") {
        $result = 1;
    # Commented out the disabling of creation so that the field
    # permission hooks can key off it.
    #    $session->SetNameValue("SuiteLogCreation", "false");
    }


program:
# build the query object
 	$sessionObj = $entity->GetSession();
 	$queryDefObj = $sessionObj->BuildQuery("TMSuiteLog");
  	# set the fields we are intested in
 	$queryDefObj->BuildField("dbid");
 	 	# get the ctc and the iteration for the filter
	# RJP TestSuite
	my @it;
	my $itOperator = $CQPerlExt::CQ_COMP_OP_IS_NULL;	
	my $itVal = $entity->GetFieldValue("Iteration")->GetValue();	
	if( ($itVal ne NULL) && ($itVal ne "" ) ) {		
		@it = $entity->GetFieldValue("Iteration")->GetValue();		
		$itOperator = $CQPerlExt::CQ_COMP_OP_EQ;	
	} 	 	@it = $entity->GetFieldValue("Iteration")->GetValue();

 	@suite = $entity->GetFieldValue("Suite")->GetValue();
 	@latest = "true";
 	# build the filter
 	$operator = $queryDefObj->BuildFilterOperator($CQPerlExt::CQ_BOOL_OP_AND);
  	$operator->BuildFilter("Iteration", $itOperator,\@it );
 	$operator->BuildFilter("Suite", $CQPerlExt::CQ_COMP_OP_EQ, \@suite );
 	$operator->BuildFilter("Latest", $CQPerlExt::CQ_COMP_OP_EQ,\@latest );
  	# execute the query
 	$resultSetObj = $sessionObj->BuildResultSet($queryDefObj);
 	$resultSetObj->Execute();
  	# loop and update any old records by changing the field value to reflect that they
 	# are not the latest
 	while ($resultSetObj->MoveNext == $CQPerlExt::CQ_SUCCESS) {
  		# get the ids of the records
 		$dbid = $resultSetObj->GetColumnValue(1);
 		$newDbid = $entity->GetDbId();
  		if( $newDbid ne $dbid ){
  			# get the entity of the current value in the record set
 			$OldEntity = $session->GetEntity("TMSuiteLog", $dbid);
  			# set the new value
  			eval {
 			$OldEntity->EditEntity("modify");
 			$OldEntity->SetFieldValue("Latest", "false");
  			# validate changes
 			$status = $OldEntity->Validate();
  			# commit changes
 			if ($status eq "") {
 				$OldEntity->Commit();
 			} else {
 				$OldEntity->Revert();
 			}
 			};
			if ($@) {
			    $session->OutputDebugString("Modify()/Commit()/Revert() threw: " . $@ . " when trying to clear the latest bit from TMSuiteLogs.\n");
			};

 		}
 	}


program:
# Return a non-empty string explaining why the action cannot commit
    # with its current values. If it is valid, return an empty string.
    # Example:
    #    my $value_info = $entity->GetFieldValue("some field");
    #    if (length($value_info->GetValue()) < 10) {
    #        $result = "Must be at least 10 chars long";
    #    }
	$sessionObj = $entity->GetSession();
	my $recordType = $entity->GetEntityDefName();
	my $origIt = $entity->GetFieldOriginalValue("Iteration")->GetValue();
	my $iter = $entity->GetFieldValue("Iteration")->GetValue();
	# we only really need to change the latest if we were latest
	if ($origIt ne $iter)
	{
		my $filter = "Suite";
		CQTM_SetLatestLogOrigIter($entity,$filter);
		CQTM_SetLatestLog($entity,$filter); 
	} # if iter has changed
	$result = "";


program:
# This hook is fired during the "commit" step of an entity update, so
    # it is the appropriate place to put activity which should be bundled
    # into the same transaction as the commit, such as subactions or an
    # update of external data storage.
if ($entity->GetFieldValue("Latest") eq "true")
{
	$queryDefObj = $sessionObj->BuildQuery("TMSuiteLog");
  	# set the fields we are intested in
 	$queryDefObj->BuildField("dbid");
	$queryDefObj->BuildField("StartTime");
	my $queryField = $queryDefObj->GetFieldByPosition(2);
	$queryField->SetSortOrder(1); 	
	$queryField->SetSortType($CQPerlExt::CQ_SORT_DESC);

 	# get the ctc and the iteration for the filter
 	my @ctc = $entity->GetFieldValue("ConfiguredTestCase")->GetValue();
 	my @it;	
	my $itOperator = $CQPerlExt::CQ_COMP_OP_IS_NULL;	
	my $itVal = $entity->GetFieldValue("Iteration")->GetValue();	
	if( ($itVal ne NULL) && ($itVal ne "" ) ) {		
		@it = $entity->GetFieldValue("Iteration")->GetValue();		
		$itOperator = $CQPerlExt::CQ_COMP_OP_EQ;	
	} 	
 	@latest = "true";
 	# build the filter
 	$operator = $queryDefObj->BuildFilterOperator($CQPerlExt::CQ_BOOL_OP_AND);
  	$operator->BuildFilter("Iteration", $itOperator, \@it );
 	$operator->BuildFilter("ConfiguredTestCase", $CQPerlExt::CQ_COMP_OP_EQ, \@ctc );
 	$operator->BuildFilter("Latest", $CQPerlExt::CQ_COMP_OP_NEQ,\@latest );
  	# execute the query
 	$resultSetObj = $sessionObj->BuildResultSet($queryDefObj);
 	$resultSetObj->Execute();


  	# loop and update any old records by changing the field value to reflect that they
 	# are not the latest
 	if($resultSetObj->MoveNext == $CQPerlExt::CQ_SUCCESS) {  		# get the ids of the records
 		$dbid = $resultSetObj->GetColumnValue(1);
 		$newDbid = $entity->GetDbId();
  		if( $newDbid ne $dbid ){
  			# get the entity of the current value in the record set
 			$OldEntity = $session->GetEntity("TMSuiteLog", $dbid);
  			# set the new value
			eval {
 			$OldEntity->EditEntity("modify");
 			$OldEntity->SetFieldValue("Latest", "true");
  			# validate changes
 			$status = $OldEntity->Validate();
  			# commit changes
 			if ($status eq "") {
 				$OldEntity->Commit();
 			} else {
 				$OldEntity->Revert();
 			}
			};
			if ($@) {
			    $session->OutputDebugString("Modify()/Commit()/Revert() threw: " . $@ . " when trying to set the latest bit from TMTestLogs.\n");
			};

 		}
 	}
} # if we're latest


program:
# sets the latest flag on the new (current) iteration 

	$sessionObj = $entity->GetSession();
	my $queryDefObj = $sessionObj->BuildQuery("TMSuiteLog");
  	# set the fields we are intested in
 	$queryDefObj->BuildField("dbid");
	$queryDefObj->BuildField("StartTime");
	my $queryField = $queryDefObj->GetFieldByPosition(2);
	$queryField->SetSortOrder(1); 	
	$queryField->SetSortType($CQPerlExt::CQ_SORT_DESC);

	my @latest = "true";
	my @ctc = $entity->GetFieldValue("ConfiguredTestCase")->GetValue();
	my @it;	
	my $itOperator = $CQPerlExt::CQ_COMP_OP_IS_NULL;	
	my $itVal = $entity->GetFieldValue("Iteration")->GetValue();	
	if( ($itVal ne NULL) && ($itVal ne "" ) ) {		
		@it = $entity->GetFieldValue("Iteration")->GetValue();		
		$itOperator = $CQPerlExt::CQ_COMP_OP_EQ;	
	} 
 	# build the filter
	
 	$operator = $queryDefObj->BuildFilterOperator($CQPerlExt::CQ_BOOL_OP_AND);
  	$operator->BuildFilter("Iteration", $itOperator, \@it );
 	$operator->BuildFilter("ConfiguredTestCase", $CQPerlExt::CQ_COMP_OP_EQ, \@ctc );
 	$operator2->BuildFilter("Latest", $CQPerlExt::CQ_COMP_OP_EQ,\@latest );
  	# execute the query
 	$resultSetObj = $sessionObj->BuildResultSet($queryDefObj);
 	$resultSetObj->Execute();
	my $amILatest = "false";
 	while($resultSetObj->MoveNext == $CQPerlExt::CQ_SUCCESS) 
	{  		
		$startTime = $resultSetObj->GetColumnValue(2);
		$myTime = $entity->GetFieldValue("StartTime");
  		if( $startTime lt $myTime )
		{
			$amILatest = "true";
		}
		if ($amILatest eq "true")
		{
			# get the ids of the records
	 		$dbid = $resultSetObj->GetColumnValue(1);

			# get the entity of the current value in the record set
			$OldEntity = $sessionObj->GetEntity("TMSuiteLog", $dbid);
			# set the new value
			eval 
			{
				$OldEntity->EditEntity("modify");
				$OldEntity->SetFieldValue("Latest", "false");
	 			# validate changes
				$status = $OldEntity->Validate();
	 			# commit changes
				if ($status eq "") {
					$OldEntity->Commit();
		
				} else {
					$OldEntity->Revert();
				}
			};
			if ($@) {
			    $session->OutputDebugString("Modify()/Commit()/Revert() threw: " . $@ . " when trying to set the latest bit from TMSuiteLog.\n");
			};
		} # if I'm latest


	}  # while resultset
	$entity->SetFieldValue("Latest", $amILatest);


program:
' The actiontype that we get as a parameter is just "BASE' which
  ' isn't very informative, so get the action type that started it all.
  real_actiontype = GetActionType

  ' Get args for calling methods
  Set this_session = GetSession()
  Set this_entity = BaseEntity

  If (real_actiontype <> AD_SUBMIT) Then
    ' For other actiontype's, check if entity is bound
    bound_vob_object = GetFieldValue("ucm_vob_object").GetValue

    If (bound_vob_object <> "") Then
      call_squid = 0

      If (real_actiontype <> AD_DELETE) Then
        ' Get a list of the fields in this record type...
        fieldNameList = this_entity.GetFieldNames

        ' Loop 
        For Each FN in fieldNameList
          If (FN="name")Or(FN= "ucm_chk_before_work_on")Or(FN="ucm_chk_before_deliver")Or(FN="ucm_chk_mstr_before_dlvr")Or(FN="ucm_cq_act_after_deliver")Or(FN="ucm_cq_trans_after_dlvr")Or(FN="ucm_chk_mstr_after_dlvr")Or(FN="ucm_cq_act_before_chact")Or(FN="ucm_cq_trans_after_chact")Or(FN="ucm_cq_act_after_chact") Then 
            ' Get the field's original value
            OldFV = this_entity.GetFieldOriginalValue(FN).GetValue
            ' Get the current value 
            NewFV = this_entity.GetFieldValue(FN).GetValue
					
            If OldFV <> NewFV Then
              call_squid = 1 
              Exit For			
            End If ' End of "OldFV <> NewFV"
          End If ' End of "FN = name" ...
        Next ' End of For Loop
      End If ' End of (real_actiontype <> AD_DELETE)

      If (call_squid = 1) Or (real_actiontype = AD_DELETE) Then		   
        ' Entity is bound, attempt to create SquidServer COM server
        ' Set error handling to catch error from CreateObject
        On Error Resume Next
        Set squid_server = CreateObject("ClearCase.SquidServer.1")
        error_num  = Err.Number
        error_desc = Err.Description
        ' Reset error handling, so that SquidServer method errors are reported by CQ
        On Error Goto 0

        If error_num <> 0 Then
          ' Create Object failed, raise exception
          If error_num = 429 Then
            ' CreateObject failed because SquidServer was not found, assume ClearCase is not installed
            Err.Raise vbObjectError+1, "SquidServer", "Error: ClearCase may not be installed or configured correctly."
          Else
            ' CreateObject failed for another reason, report the error
            Err.Raise vbObjectError+2, "SquidServer", "Can not access SquidServer: CreateObject error=" & CStr(error_num) & " " & CStr(error_desc)
          End If
        Else
          ' CreateObject succeeded, call appropriate server method
          ' On error, these will throw an exception and abort the commit		  
          If (real_actiontype = AD_DELETE) Then
            Call squid_server.DeleteCommitCQProject(this_session, this_entity)
          Else  		 	 	  
            Call squid_server.ModifyCommitCQProject(this_session, this_entity)		
          End If
        End If ' End of "CreateObject succeeded"		 
      End If ' End of "call squid"...
    End If ' End of (bound_vob_object <> "")
  End If ' End of (real_actiontype <> AD_SUBMIT)


program:
# The actiontype that we get as a parameter is just "BASE' which
    # isn't very informative, so get the action type that started it all.
    my $real_actiontype = $entity->GetActionType();

    # Get args for calling methods
    my $session_id = $session->CQInt_Id();
    my $entity_id = $entity->CQInt_Id();
    
    my $call_squid = 0;
    if ($real_actiontype != $CQPerlExt::CQ_SUBMIT) {    
      # For other actiontypes, check if entity is bound
      my $field_info = $entity->GetFieldValue("ucm_vob_object");
      my $ucm_vob_object = $field_info->GetValue();

      if ($ucm_vob_object ne "") {
        if ($real_actiontype != $CQPerlExt::CQ_DELETE) {
          # Get a list of the fields in this record type
          # (NOTE: GetFieldNames() returns a *REFERENCE* to an array)...
          my($FieldNamesRef) = $entity->GetFieldNames();

          # Loop through the fields
		  foreach $FN (@$FieldNamesRef) {
            if (($FN eq "name")||($FN eq "ucm_chk_before_work_on")||($FN="ucm_chk_before_deliver")||($FN="ucm_chk_mstr_before_dlvr")||(FN$ eq "ucm_cq_act_after_deliver")||(FN$ eq "ucm_cq_trans_after_dlvr")||(FN$ eq "ucm_chk_mstr_after_dlvr")||(FN$ eq "ucm_cq_act_before_chact")||(FN$ eq "ucm_cq_trans_after_chact")||(FN$ eq "ucm_cq_act_after_chact")) {
              # Get the field's original value...
              $OldFV = $entity->GetFieldOriginalValue($FN)->GetValue();
              # Get the field's new value...
              $NewFV = $entity->GetFieldValue($FN)->GetValue();

              # check if the OldValue equals the NewValue
              if ( $OldFV ne $NewFV ) {
                $call_squid = 1;
				last;
              }
            } # End of ($FN eq "name")
          } # End of Loop   
        } # End of ($real_actiontype != $CQPerlExt::CQ_DELETE)

        if (( $call_squid ==1 ) || ($real_actiontype == $CQPerlExt::CQ_DELETE)) {        
          # Call SQUID is necessary, get CQSquidLoad package
          require CQSquidLoad;
          my $squid = new CQSquidLoad;
          my $load_status = $squid->SquidLoadStatus(); 

          # Check whether CQSquidLoad package was able to load CQSquidLoad library
          if ($load_status == 2) {
            # CQSquidLoad library could not be loaded, assume ClearCase is not installed
            die "Error: ClearCase may not be installed or configured correctly.";
          }
          elsif ($load_status == 3) {
            # CQSquidLoad library loaded, but is wrong version
            die "Can not change this record, wrong version of ClearCase is installed.";
          }
          else {
            # Success, call package method to do the work.
            # On error, this will throw an exception and abort the commit
            if ($real_actiontype == $CQPerlExt::CQ_DELETE)  {
              $squid->DeleteCommitCQProject($session_id, $entity_id);
            }
            else {
              $squid->ModifyCommitCQProject($session_id, $entity_id);      
            }
          } # End of "Success" 
	    } # End of "call_squid"
      } # End of ($ucm_vob_object ne "")
    } # End of "other actiontype's"


program:
'---
  ' This record hook is invoked by SQUID to invoke the "Perform ClearQuest Action
  ' Before Delivery" policy. It ivokes the UCM_ChkBeforeDeliver
  ' global script (an initial version of this is installed via UCM package 
  ' installation, but it can be edited by the user).
  '
  ' INPUT:
  '  - Param must be a string with this format:
  '     "entity-type|entity-id|target_stream_selector|target_view_tag" 
  '     (vertical bars are delimeters)
  '     which represents the entity bound to the SUM_Project to be delivered
  ' OUTPUT:
  '  - If the SUM_Project should be delivered, this returns an empty string
  '  - If the SUM_Project should be delivered, this returns a string to be
  '    displayed as an error message. This will cause the delivery to be
  '    aborted.
  '---

      ' Parse the param string
      start = 1
      pos = 0

      pos = Instr(start, param, "|", vbBinaryCompare)
      entity_type = Mid (param, start, pos-start)
      start = pos + 1

      pos = Instr(start, param, "|", vbBinaryCompare)
      entity_id = Mid (param, start, pos-start)
      start = pos + 1

      pos = Instr(start, param, "|", vbBinaryCompare)
      target_stream_selector = Mid (param, start, pos-start)
      start = pos + 1

      pos = Instr(start, param, "|", vbBinaryCompare)
      target_view = Mid (param, start, pos-start)
      start = pos + 1

      ' Call the user-editable global script
      ucm_project_UCM_ChkBeforeDeliver = UCM_ChkBeforeDeliver(entity_type, entity_id, target_stream_selector, target_view)


program:
#---
    # This record hook is invoked by SQUID to invoke the "Perform ClearQuest Action
    # Before Delivery" policy. It ivokes the UCM_ChkBeforeDeliver
    # global script (an initial version of this is installed via UCM package 
    # installation, but it can be edited by the user).
    #
    # INPUT:
    # - Param must be a string with this format:
    #     "entity-type|entity-id|target_stream_selector|target_view_tag" 
    #     (vertical bars are delimeters)
    #     which represents the entity bound to the SUM_Project to be delivered
    # OUTPUT:
    #  - If the SUM_Project should be delivered, this returns an empty string
    #  - If the SUM_Project should be delivered, this returns a string to be
    #    displayed as an error message. This will cause the delivery to be
    #    aborted.
    #---

    # NOTE: Param is really a string type
    my ($param_string) = @_;

    # Parse the param string
    my $entity_type;
    my $entity_id;
	my $target_stream_selector;
	my $target_view_tag;
    ($entity_type, $entity_id, $target_stream_selector, $target_view_tag) = split ('\|', $param_string);

    # Call the user-editable global script
    $result = UCU_ChkBeforeDeliver($entity_type, $entity_id, $target_stream_selector, $target_view_tag);


program:
'---
  ' This record hook is invoked by SQUID to invoke the "Perform ClearQuest Action
  ' Before Work On" policy. It invokes the UCM_ChkBeforeWorkOn global script 
  ' (an initial version of this is installed via UCM package installation, 
  ' but it can be edited by the user).
  '
  ' INPUT:
  '  - Param must be a string with this format:
  '     "entity-type|entity-id|stream" (vertical bars are delimeters)
  '    which represents the entity to be worked on
  ' OUTPUT:
  '  - If the current user is permitted to work on this entity, this
  '    returns an empty string
  '  - If the current user is not permitted to work on this entity, this
  '    returns a string to be displayed as an error message. This will
  '    cause the Work On action to be aborted.
  '---

      ' Parse the param string
      start = 1
      pos = 0

      pos = Instr(start, param, "|", vbBinaryCompare)
      entity_type = Mid (param, start, pos-start)
      start = pos + 1

      pos = Instr(start, param, "|", vbBinaryCompare)
      entity_id = Mid (param, start, pos-start)
      start = pos + 1

      pos = Instr(start, param, "|", vbBinaryCompare)
      stream = Mid (param, start, pos-start)
      start = pos + 1

      ' Call the user-editable global script
      ucm_project_UCM_ChkBeforeWorkOn = UCM_ChkBeforeWorkOn(entity_type, entity_id, stream)


program:
#---
    # This record hook is invoked by SQUID to invoke the "Check Before
    # Work On" policy. It invokes the UCU_ChkBeforeWorkOn global script 
    # (an initial version of this is installed via UCM package installation, 
    # but it can be edited by the user).
    #
    # INPUT:
    #  - Param must be a string with this format:
    #     "entity-type|entity-id|stream" (vertical bars are delimeters)
    #    which represents the entity to be worked on
    # OUTPUT:
    #  - If the current user is permitted to work on this entity, this
    #    returns an empty string
    #  - If the current user is not permitted to work on this entity, this
    #    returns a string to be displayed as an error message. This will
    #    cause the Work On action to be aborted.
    #---

    # NOTE: Param is really a string type
    my ($param_string) = @_;

    # Parse the param string
    my $entity_type;
    my $entity_id;
	my $stream;
    ($entity_type, $entity_id, $stream) = split ('\|', $param_string);

    # Call the user-editable global script
    $result = UCU_ChkBeforeWorkOn($entity_type, $entity_id,$stream);


program:
'---
  ' This record hook is invoked by SQUID to invoke the "Perform ClearQuest
  ' Action After Delivery" policy. It invokes the UCM_CQActAfterDeliver
  ' global script (an initial version of this is installed via UCM package
  ' installation, but it can be edited by the user).
  '
  ' INPUT:
  '  - Param must be a string with this format:
  '     "entity-type|entity-id|target_stream_selector|target_view_tag" 
  '     (vertical bars are delimeters)
  '    which represents the entity bound to the SUM_Project which was
  '    delivered
  ' OUTPUT:
  '  - If the ClearQuest Action is OK, this returns an empty string
  '  - If the ClearQuest Action is NOYT OK, this returns a string
  '    to be displayed as an error message.
  '---

      ' Parse the param string
      start = 1
      pos = 0

      pos = Instr(start, param, "|", vbBinaryCompare)
      entity_type = Mid (param, start, pos-start)
      start = pos + 1

      pos = Instr(start, param, "|", vbBinaryCompare)
      entity_id = Mid (param, start, pos-start)
      start = pos + 1

      pos = Instr(start, param, "|", vbBinaryCompare)
      target_stream_selector = Mid (param, start, pos-start)
      start = pos + 1

      pos = Instr(start, param, "|", vbBinaryCompare)
      target_view = Mid (param, start, pos-start)
      start = pos + 1

      ' Call the user-editable global script
      ucm_project_UCM_CQActAfterDeliver = UCM_CQActAfterDeliver(entity_type, entity_id, target_stream_selector, target_view)


program:
#---
    # This record hook is invoked by SQUID to invoke the "Perform ClearQuest
    # Action After Delivery" policy. It invokes the UCU_CQActAfterDeliver
    # global script (an initial version of this is installed via UCM package
    # installation, but it can be edited by the user).
    #
    # INPUT:
    #  - Param must be a string with this format:
    #     "entity-type|entity-id|target_stream_selector|target_view_tag" 
    #     (vertical bars are delimeters)
    #    which represents the entity bound to the SUM_Project which was
    #    delivered
    # OUTPUT:
    #  - If the ClearQuest Action is OK, this returns an empty string
    #  - If the ClearQuest Action is NOYT OK, this returns a string
    #    to be displayed as an error message.
    #---

    # NOTE: Param is really a string type
    my ($param_string) = @_;

    # Parse the param string
    my $entity_type;
    my $entity_id;
	my $target_stream_selector;
	my $target_view_tag;
    ($entity_type, $entity_id, $target_stream_selector, $target_view_tag) = split ('\|', $param_string);

    # Call the user-editable global script
    $result = UCU_CQActAfterDeliver($entity_type, $entity_id, $target_stream_selector, $target_view_tag);


program:
'---
  ' This record hook is invoked by SQUID to invoke the "Perform ClearQuest
  ' Action Before Changing Activity" policy. 
  '
  ' INPUT:
  '  - Param must be a string with this format:
  '     "entity-type|entity-id|project_info|stream_info" (vertical bars are delimeters)
  ' OUTPUT:
  '  - If the entity is valid, this returns an empty string
  '  - If the entity is not valid, this returns a string
  '    to be displayed as an error message.
  '---

      ' Parse the param string
      start = 1
      pos = 0

      pos = Instr(start, param, "|", vbBinaryCompare)
      entity_type = Mid (param, start, pos-start)
      start = pos + 1

      pos = Instr(start, param, "|", vbBinaryCompare)
      entity_id = Mid (param, start, pos-start)
      start = pos + 1

	  pos = Instr(start, param, "|", vbBinaryCompare)
	  project_info = Mid (param, start, pos-start)
	  start = pos + 1

	  pos = Instr(start, param, "|", vbBinaryCompare)
	  stream_info = Mid (param, start, pos-start)
	  start = pos + 1

      ' Call the user-editable global script
      ucm_project_UCM_CQActBeforeChact = UCM_CQActBeforeChact(entity_type, entity_id, project_info, stream_info)


program:
#---
    # This record hook is invoked by SQUID to invoke the "Perform ClearQuest
    # Action Before Changing Activity" policy. 
    #
    # INPUT:
    #  - Param must be a string with this format:
    #     "entity-type|entity-id|project_info|stream_info" (vertical bars are delimeters)
    # 
    # OUTPUT:
    #  - If the entity is valid, this returns an empty string
    #  - If the entity is not valid, this returns a string
    #    to be displayed as an error message.
    #---

    # Parse the param string
	my $entity_type;
	my $entity_id;
	my $project_info;
	my $stream_info;
	($entity_type, $entity_id, $project_info, $stream_info) = split ('\|', $param);

    # Call the user-editable global script
    $result = UCU_CQActBeforeChact($entity_type, $entity_id, $project_info, $stream_info);


program:
'---
  ' This record hook is invoked by SQUID to invoke the "Perform ClearQuest Action
  ' After Changing Activity" policy. If the activity is not in
  ' a single stream project, or is not in the project's integration
  ' stream, the UCM change activity should fail.
  '
  ' INPUT:
  '  - Param must be a string with this format:
  '     "entity-type|entity-id|project_info|stream_info" (vertical bars are delimeters)
  '
  ' OUTPUT:
  '  - If the entity is valid, this returns an empty string
  '  - If the entity is not valid, this returns a string
  '    to be displayed as an error message.
  '---

      ' Parse the param string
      start = 1
      pos = 0

      pos = Instr(start, param, "|", vbBinaryCompare)
      entity_type = Mid (param, start, pos-start)
      start = pos + 1

      pos = Instr(start, param, "|", vbBinaryCompare)
      entity_id = Mid (param, start, pos-start)
      start = pos + 1

	  pos = Instr(start, param, "|", vbBinaryCompare)
	  project_info = Mid (param, start, pos-start)
	  start = pos + 1

	  pos = Instr(start, param, "|", vbBinaryCompare)
	  stream_info = Mid (param, start, pos-start)
	  start = pos + 1

      ' Call the user-editable global script
      ucm_project_UCM_CQActAfterChact = UCM_CQActAfterChact(entity_type, entity_id, project_info, stream_info)


program:
#---
    # This record hook is invoked by SQUID to invoke the "Perform ClearQuest Action
    # After Changing Activity" policy. If the activity is not in
    # a single stream project, or is not in the project's integration
    # stream, the UCM change activity should fail.
    #
    # INPUT:
    #  - Param must be a string with this format:
    #     "entity-type|entity-id|project_info|stream_info" (vertical bars are delimeters)
	#
    # OUTPUT:
    #  - If the entity is valid, this returns an empty string
    #  - If the entity is not valid, this returns a string
    #    to be displayed as an error message.
    #---
	
	# Parse the param string
	my $entity_type;
	my $entity_id;
	my $project_info;
	my $stream_info;
	($entity_type, $entity_id, $project_info, $stream_info) = split ('\|', $param);

	$result = UCU_CQActAfterChact($entity_type, $entity_id, $project_info, $stream_info);


program:
# Set $result to 1 if the user has permission to perform
    # this action, otherwise set it to 0.
    $result = 0;
    my $createAllowed = $session->GetNameValue("FileLocationCreation");
    if ($createAllowed eq "true") {
        $result = 1;
        $session->SetNameValue("FileLocationCreation", "false");
    }


program:
# Do any setup for the action here.

    $session->OutputDebugString("In Delete action for FileLocation.\n");

    my $externalFiles = $entity->GetFieldValue("ExternalFiles")->GetValueAsList();

    # Determine the name of the Delete action
	my $externalFileEntityDef = $session->GetEntityDef("TMExternalFile");
    my $actionDefList = $externalFileEntityDef->GetActionDefNames();
    my $deleteAction = "CQTM_NOT_FOUND";
    foreach $actionName (@$actionDefList) {
        if ($externalFileEntityDef->GetActionDefType($actionName) eq $CQPerlExt::CQ_DELETE) {
            $session->OutputDebugString("Delete action name: '" . $actionName . "'\n");
            $deleteAction = $actionName;
            last;
        }
    }    

    if ($deleteAction eq "CQTM_NOT_FOUND") {
        return;
    }

    my $externalFileEntity;
    foreach $externalFile (@$externalFiles) {

        $externalFileEntity = $session->GetEntity("TMExternalFile", $externalFile);
        $session->DeleteEntity($externalFileEntity, $deleteAction);

    }


program:
# Return a non-empty string explaining why the field's current
    # value is not valid. If it is valid, return an empty string.

    my $ARValue = $entity->GetFieldValue("AssetRegistry")->GetValue();

	my $refCases = $entity->GetFieldValue("TestCases")->GetValueAsList();

    my @cases = @$refCases;

	my $casePlan;
    my $caseAR;
    my $casePlanEntity;
    my $caseEntity;
    foreach $case (@cases) {
        $caseEntity = $session->GetEntity("TMTestCase", $case);
        $casePlan = $caseEntity->GetFieldValue("ParentPlan")->GetValue();
        $casePlanEntity = $session->GetEntity("TMTestPlan", $casePlan);
        $caseAR = $casePlanEntity->GetFieldValue("AssetRegistry")->GetValue();
        if ($caseAR ne $ARValue) {
			return "Cannot change Asset Registry because Test Cases are currently using this Iteration for the following Asset Registry: '" . $caseAR . "'";
        }
    }


program:
# Return one of
    #   $CQPerlExt::CQ_MANDATORY
    #   $CQPerlExt::CQ_OPTIONAL
     #   $CQPerlExt::CQ_READONLY
    # Example:
    #   if ($username eq "pat") {
    #      $result = $CQPerlExt::CQ_READONLY; 
    #   } else {
    #      $result = $CQPerlExt::CQ_OPTIONAL;
    #   }
    $result = $CQPerlExt::CQ_READONLY;
    my $testCaseValue = $entity->GetFieldValue("TestCase")->GetValue();
    if (($testCaseValue eq "") || ($testCaseValue eq NULL)) {
        return $CQPerlExt::CQ_MANDATORY;
    }


program:
# This hook will be run each time the field's value changes.
    # This hook runs before the new value is validated so be aware
    # the new value may not be valid.
    # Example:
    #   my $op_sys = $entity->GetFieldValue($fieldname)->GetValue();
    #   if ($op_sys eq "windows") {
    #      $entity->SetFieldValue("os_version", "NT 4.x");
    #      <etc.>
    #   }
    $entity->FireNamedHook("InheritScript","");


program:
# build the query object
 	$sessionObj = $entity->GetSession();
 	$queryDefObj = $sessionObj->BuildQuery("TMTestSuite");
  	
	# set the fields we are intested in
 	$queryDefObj->BuildField("id");
 	 	
	# get the ctc id
 	@ctc = $entity->GetFieldValue("id")->GetValue();


 
 	# build the filter
 	$operator = $queryDefObj->BuildFilterOperator($CQPerlExt::CQ_BOOL_OP_AND);
  	$operator->BuildFilter("ConfiguredTestCases", $CQPerlExt::CQ_COMP_OP_IN,\@ctc );

 
   	# execute the query
 	$resultSetObj = $sessionObj->BuildResultSet($queryDefObj);
 	$resultSetObj->Execute();

  	# loop and update any old records by changing the field value to reflect that they
 	# are not the latest

	my $records = "";
 	while ($resultSetObj->MoveNext == $CQPerlExt::CQ_SUCCESS) {
  		# get the ids of the records
 		$id = $resultSetObj->GetColumnValue(1);
 		
		$records = $records . $id . " ";
 	}
	
	if( $records ne "" ) {
		$entity->SetFieldRequirednessForCurrentAction($fieldname, $CQPerlExt::CQ_READONLY);
		# $result = "The configuration value can not be changed while this record belongs to the following Test Suite records : " . $records; 
	
	}
	else {
		$entity->SetFieldRequirednessForCurrentAction($fieldname, $CQPerlExt::CQ_MANDATORY);
	}


program:
my $script = $entity->GetFieldValue($fieldname)->GetValue();
	if( $script eq NULL || $script eq "" ) {
		$entity->SetFieldValue("ScriptOptions", "" );
		$entity->SetFieldValue("TestType","" );
	}


program:
my $case = $entity->GetFieldValue("TestCase")->GetValue();
    if (($case eq "") || ($case eq NULL)) {
	 	return $result;
	}


	my $plan = $session->GetEntity("TMTestCase", $case)->GetFieldValue("ParentPlan")->GetValue();


	my $assetRegistry = $session->GetEntity("TMTestPlan", $plan)->GetFieldValue("AssetRegistry")->GetValue();


    if (($assetRegistry eq "") || ($assetRegistry eq NULL)) {
        return $result;
     }


	 my $refFormIterations = $entity->GetFieldValue("Iterations")->GetValueAsList();

	 my $refAssetIterations = $session->GetEntity("TMAssetRegistry",$assetRegistry )->GetFieldValue("Iterations")->GetValueAsList();

	 my @assetIterations = @$refAssetIterations;
	 my @formIterations = @$refFormIterations;



	# now see if all of the iterations are part of the asset registryf
	foreach  $formIt (@formIterations ) {

		my $found = 0;
		foreach $assetIt (@assetIterations) {

			if($assetIt eq $formIt ){
				$found = 1;
				last;
			}
		}

		if( $found < 1 ){
			$result = "Some Iterations do not belong to the Asset Registry";
			last;
		}
		$found = 0;
	}


program:
REM Return a non-empty string explaining why the action
   REM cannot commit with the current values.
   REM Or, if it is valid, return an empty string value.
   REM Example: 
   REM    Dim value_info
   REM    Set value_info = GetFieldValue("some field")
   REM    If Len(value_info.GetValue()) < 10 Then
   REM        TMConfiguredTestCase_Validation = "Must be at least 10 chars long"
   REM    End If

REM Checks if associations still exist with current CQ record when user tries to delete it
REM if none, deletion completed
REM if some, deletion canceled

	Dim a_CurrentActionType					'Action type of the action that initiated the execution of this script

	a_CurrentActionType = GetActionType()
   'Check to see if the real action is a delete action.
	'If not exit.
	if a_CurrentActionType = AD_DELETE then
		'Don't allow user to delete the current record unless no requirements are
		'associated with it
		Dim ac_sCQReqListAttName				'Name of the global variable containing the name of the field of the CQ record that stores associations
		Dim a_vTableDBIDs							'List of DBIDs of Req proxies associated to the current CQ record
	
		ac_sCQReqListAttName= "Requirements_List"
' RATLC00015495 
'		a_vTableReqIds = GetFieldValue(ac_sCQReqListAttName).GetValueAsList		
        a_vTableDBIDs = GetFieldValue(ac_sCQReqListAttName).GetValueAsList
		if IsEmpty(a_vTableDBIDs) then
'			EnhancementRequest_Validation = vbNullString		
		TMConfiguredTestCase_Validation = vbNullString		
		else
'			EnhancementRequest_Validation = "Rational RequisitePro/ClearQuest Integration: You have to remove all associations with RequisitePro requirements before you can delete the current ClearQuest record."	    	
			TMConfiguredTestCase_Validation = "Rational RequisitePro/ClearQuest Integration: You have to remove all associations with RequisitePro requirements before you can delete the current ClearQuest record."
		end if
	end if	'a_CurrentActionType


program:
REM Check the requirement type for its type guid
   REM Check the type of the current record type
   REM pull up a requirement map for this record type
   REM see if the requirement type guid is the same as the guid 
   REM for the requirement that is being added.
	
	' Get all the requirement types that this artifact can be associated to
	Dim session, reqList, listItem, tempReq, recordType
	
	TMConfiguredTestCase_Validation = ""
	Set session = GetSession
	recordType = GetEntityDefName

	Dim queryDef, queryField, operator, filterNode, resultSet
	Dim ac_sTagField
	Dim ac_sNameField
	
	ac_sTagField = "Tag"
	ac_sNameField = "Name"

	Set queryDef = session.BuildQuery("RequirementMap")
	If Not queryDef is Nothing then
	' Building the query
		queryField = queryDef.BuildField("RPReqTypeGUID")
		Set operator = queryDef.BuildFilterOperator(AD_COMP_OP_EQ)
		operator.BuildFilter "CQEntityDefName",	AD_COMP_OP_EQ, recordType
		Set resultSet = session.BuildResultSet(queryDef)
		resultSet.Execute()

		Dim found, tempGUID, counter, status, GUIDs

		Set GUIDs = CreateObject("Scripting.dictionary")

		found = False
		counter = 0
		status = resultSet.MoveNext
	'	build the requirement types GUIDs array
		Do While status = AD_SUCCESS 
			tempGUID = resultSet.GetColumnValue(1)
			GUIDs.Add counter, tempGUID
			counter = counter + 1
		 	status = resultSet.MoveNext
		 Loop 

	'	Retrieve all the requirements that are associated to the current artifact
		Dim tempReqList
		tempReqList = GetFieldValue("Requirements_List").GetValue	

		If tempReqList <> "" then
		'	Break the string of line feed separated requirement ids in to an array
			Dim array ' array of requirements
			Dim u ' number of elements in the array
			Dim result
			result = ""
		'	Splitting it
		  	array = Split(Cstr(tempReqList),vbLF)
			u = UBound(array)
			Dim ReqId, requirement, reqTypeGUID
		'	Check if the requirement's type is in the list of allowed requirement GUIDs list
			For i = 0 To u
				found = False
				ReqId = array(i)
			'	Get the requirement
				Set requirement = session.GetEntity("Requirement", ReqId)
				If Not requirement Is Nothing Then
					Dim fieldDef 
				'	Get the requirement type
					reqTypeGUID = requirement.GetFieldValue("Type_GUID").GetValue
				'	Check to see if the GUID is matching with the existing list
					For j = 0 to GUIDs.count
						If GUIDs.Item(j) <> "" Then
							If GUIDs.Item(j) = reqTypeGUID Then
							'	Found it so dont need to loop anymore
								found = True
								Exit For
							End If
						Else
							'	Valid guid's are done so skip
							Exit For
						End If
					Next

				End If
			'	Create the erroneous list of requirements

				If Not found Then
					Dim sReq
					Dim sName
					
					sName = requirement.GetFieldValue(ac_sNameField).GetValue
					sReq = requirement.GetFieldValue(ac_sTagField).GetValue
					' Limiting the name length to about 30 characters for display
					if len(sName) = 0 then
						result = result & vbLF & sReq
					elseif len(sText) > 33 then
						result = result & vbLF & sReq & ": " & left(sName, 30) + "..."
					else
						result = result & vbLF & sReq & ": " & sName
					end if
				end if				
			Next
			'	Check to see if the erroneous list of requirements is empty or not
			If result <> "" Then
			'	if the list is not empty create the error message.
				TMConfiguredTestCase_Validation = "The following Requirements types dont match " & result
			End If
		End If

	End If


program:
my $testCaseValue = $entity->GetFieldValue("TestCase")->GetValue();
  	if (($testCaseValue ne "") && ($testCaseValue ne NULL)) {
        my $parentTestCase = $session->GetEntity("TMTestCase", $testCaseValue);
        my $defaultScriptValue = $parentTestCase->GetFieldValue("DefaultScript")->GetValue();
        if (($defaultScriptValue ne "") && ($defaultScriptValue ne NULL)) {
            $entity->SetFieldValue("Script", $defaultScriptValue);
        }
        my $defaultScriptValueType = $parentTestCase->GetFieldValue("DefaultScriptType")->GetValue();
        if (($defaultScriptValueType ne "") && ($defaultScriptValueType ne NULL)) {
            $entity->SetFieldValue("TestType", $defaultScriptValueType);
        }

        my $defaultScriptOptions = $parentTestCase->GetFieldValue("DefaultScriptOptions")->GetValue();
        if (($defaultScriptOptions ne "") && ($defaultScriptOptions ne NULL)) {
            $entity->SetFieldValue("ScriptOptions", $defaultScriptOptions);
        }


    }


program:
REM add your hook code here

REM Launch RequisitePro Association dialog box, with list of Req Proxy DBIDs of Requirements already associated to current CQ record
REM if return of call is OK
REM	Position state of state machine to "MODIFIED"
REM if return of call is Cancel


	Dim eRet_Empty
	Dim eRet_OK
	Dim eRet_Cancel
	Dim eRet_Error
	Dim ac_sCQReqListAttName				'Name of the global variable containing the name of the field of the CQ record that stores associations
	Dim ac_sCQIStateVar						'Name of the global variable containing the current state of the state machine
	Dim ac_sCQIListReqsVar					'Name of the global variable containing the list of Proxy Req DBIDs associated to the current CQ record
	Dim ac_sCQIdbidSeparator				'Character used to separate dbids in string list 
	Dim a_bWeb									'Web or not
	Dim a_bIsRunningIntegration			'Contains a boolean indicating if the integration is already in progress, to prevent reccurence
	Dim a_bProjectSet							'Contains a boolean indicating if a Rational Project has been selected for the current CQ record
	Dim a_oCQSession							'Current CQ session
	Dim a_oRequisiteProTool					'Reference to a ASCQIIntegration.RequisiteProTool instance
	Dim a_sListReqDBIDs						'List of Req Proxy DBIDs associated to the current CQ record
	Dim a_eRet									'Contains value returned by the call to integration
	Dim a_sError								'Error message sent back by integration in case of a failure
	Dim a_vTableDBIDs							'List of DBIDs of Req proxies associated to the current CQ record
	Dim a_lIndex
	Dim a_sFail									'Return value of the creation of the association in ClearQuest between current CQ record and the Req Proxy

	eRet_Empty = 0
	eRet_OK = 1
	eRet_Cancel = 2
	eRet_Error = 3	

	ac_sCQReqListAttName= "Requirements_List"	
	ac_sCQIStateVar = "CQIState"
	ac_sCQIListReqsVar = "CQIReqs"
	ac_sCQIdbidSeparator = ","
	
	a_bWeb = Check_Web()

	' RATLC01009865 - Display message for non-functional button in CQWeb
	if a_bWeb then
		' Need this Error handler otherwise it does not work from CQWeb.
		On Error resume next
	 	err.clear

		TMConfiguredTestCase_CQI_Select_Req = "This operation is not available in the Web client."
		return
	end if	


   'This script must no be launched through the web
	'We also test if the record is editable
	If (IsEditable AND NOT a_bWeb) Then

		if Check_RAProjectMaster then
			a_bIsRunningIntegration = CQI_IsRunningIntegration()
			if not a_bIsRunningIntegration then
				a_bProjectSet = Check_Project()
				if a_bProjectSet then
				 	Set a_oCQSession = GetSession
					if not a_oCQSession is nothing then
						set a_oRequisiteProTool = CQI_GetRequisiteProTool()	
						if a_oRequisiteProTool is nothing then
							msgbox "ClearQuest could not connect to the Integration Server." + vbcrlf + "Please contact your Administrator.", vbOKOnly + vbCritical, "Rational RequisitePro/ClearQuest Integration"
						else
							' RATLC01201983 - Do not use list of requirements when beginning to modify the record.
							' instead use the current list of requirements
							' a_sListReqDBIDs = a_oCQSession.NameValue(ac_sCQIListReqsVar)
							a_vTableDBIDs = getfieldValue(ac_sCQReqListAttName).GetValueAsList
							if not IsEmpty(a_vTableDBIDs) then
								CQI_GetListFromDBIDTable a_vTableDBIDs, ac_sCQIdbidSeparator, a_sListReqDBIDs
							end if   ' a_vTableDBIDs

							a_eRet = a_oRequisiteProTool.AssociateFromClearQuest(me, ac_sCQReqListAttName, a_sListReqDBIDs, a_sError)
							Select Case a_eRet
							   	Case eRet_OK
									a_oCQSession.NameValue(ac_sCQIStateVar)= "MODIFIED" 
									if a_sListReqDBIDs <> vbNullString then
										a_vTableDBIDs = empty
										if CQI_GetTableFromDBIDList(a_sListReqDBIDs, ac_sCQIdbidSeparator, a_vTableDBIDs) then
											if not IsEmpty(a_vTableDBIDs) then
												for a_lIndex = LBound(a_vTableDBIDs) to UBound(a_vTableDBIDs)
											        a_sFail = AddFieldValue(ac_sCQReqListAttName, cstr(a_vTableDBIDs(a_lIndex)))
													if a_sFail = vbNullString then
														call CQI_AddDBIDToList(cstr(a_vTableDBIDs(a_lIndex)), ac_sCQIdbidSeparator)
													end if	'a_sFail
												next
											end if
										end if
									end if
				
						      Case eRet_Cancel

								Case Else		
									msgbox a_sError ,vbOKOnly + vbCritical, "Rational RequisitePro/ClearQuest Integration"
				
							End Select
						end if	'a_oRequisiteProTool
					end if	'a_oCQSession
				else
					if GetEntityDefName = "EnhancementRequest" and GetActionType = AD_SUBMIT then
						msgbox "In order to associate a requirement, you must first submit the EnhancementRequest record.", vbOKOnly + vbInformation, "Rational RequisitePro/ClearQuest Integration"
					else 						
						MsgBox "A valid RAProject must be selected.", vbOKOnly + vbInformation, "Rational RequisitePro/ClearQuest Integration"
					end if
				end if	'a_bProjectSet
			else								  
				msgbox "Modification (or viewing) of Requirement properties cannot be done at this point, as the Clearquest information is currently displayed from RequisitePro. Please access the Requirement Properties dialog from RequisitePro.", vbOKOnly + vbInformation, "Rational RequisitePro/ClearQuest Integration" 
			end if	'a_bIsRunningIntegration

		else								  
			msgbox "This ClearQuest/RequisitePro integration operation is not supported. This ClearQuest record is associated with a Rational project that is not accessible from your local area network.", vbOKOnly + vbInformation, "Rational RequisitePro/ClearQuest Integration" 
		end if	'Check_RAProjectMaster
	end if	'a_bWeb

	set a_oRequisiteProTool = nothing
	set a_oCQSession = nothing


program:
REM add your hook code here

REM Launch RequisitePro Properties dialog box for the selected Requirement in the CQ list box, and pass its DBID 
REM if return of call is ePrp_OK
REM	Nothing is done
REM if return of call is ePrp_Removed
REM	then the requirement is removed fromlist of requirement associated with current CQ record

	On Error resume next	'handle ListSelection empty
	err.clear

	Dim a_bWeb									'Web or not
	Dim a_bIsRunningIntegration			'Contains a boolean indicating if the integration is already in progress, to prevent reccurence
	Dim a_oCQSession							'Current CQ session
	Dim a_lNumberSel							'Number of Requirements currently selected in the CQ List Box
	Dim a_sStrElm								'CQ Key of the Req Proxy selected in the CQ List Box (currently dbid)
	Dim a_sDBID									'DBID of the Req Proxy selected in the CQ List Box
	Dim a_bEmpty								'Boolean indicationg wether or not a Req Proxy is selected in the CQ List Box
	Dim a_sError								'Error message sent back by integration in case of a failure
	Dim a_sFail									'Return value of the deletion of the association in ClearQuest between current CQ record and the Req Proxy
 	dim a_oReq									' selected Requirement record
	Dim vRet									' Generic return value
	Dim ac_sCQReqListAttName
	
	ac_sCQReqListAttName= "Requirements_List"

	a_bWeb = Check_Web()

	' RATLC01009865 - Display message for non-functional button in CQWeb
	if a_bWeb then
		TMConfiguredTestCase_CQI_Properties_Req = "You cannot view a requirement from this record in the Web client. Open the requirement record and select View."
		return
	end if	

   'This script must not be launched through the web
	'We also test if the record is editable
	If (IsEditable AND NOT a_bWeb) Then
		a_bIsRunningIntegration = CQI_IsRunningIntegration()
		if not a_bIsRunningIntegration then
		 	Set a_oCQSession = GetSession
			if not a_oCQSession is nothing then
				if Check_Eclipse() then
					' Handle the selection differently for CQ Eclipse.
					' param = string of selected DBIDs separated by Line Feed.
					Dim sParam 
					Dim bGotOne

					sParam = cstr(param)
					bGotOne = false
					' There is an extra LF added at the end of every DBID 
					' even for one selection. The code below handles both the 
					' cases, with and without the last LF.
					if len(sParam) > 1 then
					    If InStrRev(sParam, vbLf) = Len(sParam) Then
					    	If InStrRev(Left(sParam, Len(sParam) - 1), vbLf) = 0 Then
					            ' There is an extra LF at the end of the string
					            a_sDBID = Left(sParam, Len(sParam) - 1)
					            bGotOne = True
					        End If
					    Else
					        If InStrRev(sParam, vbLf) = 0 Then
					            a_sDBID = sParam
					            bGotOne = True
					        End If
					    End If
					End If

					if bGotOne then
						set a_oReq = a_oCQSession.GetEntity("Requirement", a_sDBID)
						if not a_oReq is nothing then
							vRet = a_oReq.FireNamedHook("CQI_Properties_Req", "")
							set a_oReq = nothing
						end if
					else
						MsgBox "Please select one requirement in the list view to get the properties.", vbOKOnly + vbInformation, "Rational RequisitePro/ClearQuest Integration"
					end if
				else
					a_lNumberSel = 0
					For Each a_sStrElm In param.ListSelection
						a_sDBID = a_sStrElm
						a_lNumberSel = a_lNumberSel + 1
					Next
					a_bEmpty = IsNull(a_sDBID) or IsEmpty(a_sDBID)
					if a_bEmpty then
						'Nothing to do
						MsgBox "Please select one requirement in the list view to get the properties.", vbOKOnly + vbInformation, "Rational RequisitePro/ClearQuest Integration"
					else
		on error goto 0
						if a_lNumberSel = 1 then
	 						set a_oReq = a_oCQSession.GetEntity("Requirement", a_sDBID)
	 						if not a_oReq is nothing then
	 							vRet = a_oReq.FireNamedHook("CQI_Properties_Req", "")
	 						end if
	 				   	else
							MsgBox "Please select one requirement in the list view to get the properties.", vbOKOnly + vbInformation, "Rational RequisitePro/ClearQuest Integration"
						end if
					end if	'a_bEmpty
				end if ' Check_Eclipse()

				' RATLC01011263 - If the Requirement is deleted from RP. Prompt user to remove the association 
				if vRet = "DELETED" then
					vRet = Msgbox ("The requirement has been deleted in Rational RequisitePro." _
									+ vbcrlf+ "Do you want to remove the association?", _
									vbYesNo + vbQuestion, _
									"Rational RequisitePro/ClearQuest Integration")
					if vRet = vbYes then
						DeleteFieldValue ac_sCQReqListAttName, a_sDBID
					end if
				end if

			end if	'a_oCQSession
		else								  
			msgbox "Modification (or viewing) of Requirement properties cannot be done at this point, as the Clearquest information is currently displayed from RequisitePro. Please access the Requirement Properties dialog from RequisitePro.", vbOKOnly + vbInformation, "Rational RequisitePro/ClearQuest Integration" 
		end if	'a_bIsRunningIntegration
	end if	'a_bWeb

	set a_oReq = nothing
	set a_oCQSession = nothing


program:
REM add your hook code here

REM Refreshes the Requirement proxies of associated Requirements in the CQ list box
 	On Error resume next
 	err.clear

	Dim ac_sCQReqListAttName				'Name of the global variable containing the name of the field of the CQ record that stores associations
	Dim ac_sCQIdbidSeparator				'Character used to separate dbids in string list 
	Dim a_bWeb								'Web or not
	Dim a_bIsRunningIntegration				'Contains a boolean indicating if the integration is already in progress, to prevent reccurence
	Dim a_oCQSession						'Current CQ session
	Dim a_oRequisiteProTool					'Reference to a ASCQIIntegration.RequisiteProTool instance
	Dim a_sListReqDBIDs						'List of Req Proxy DBIDs associated to the current CQ record
	Dim a_vTableDBIDs						'List of DBIDs of Req proxies associated to the current CQ record
	Dim a_sError							'Error message sent back by integration in case of a failure
	Dim a_sDBIDtoRemove						'List of DBIDs of Req proxies associated to the current CQ record to remove because they don't exist anymore
	Dim a_sDBID								'DBIDs to remove
 	Dim a_oCurReq
	 dim ac_sRequirement
 	Dim ac_sReqRefreshAction
	ac_sRequirement = "Requirement" 
	ac_sReqRefreshAction = "Refresh"					  

	ac_sCQReqListAttName= "Requirements_List"	
	ac_sCQIdbidSeparator = ","

	a_bWeb = Check_Web()

	' RATLC01009865 - Display message for non-functional button in CQWeb
	if a_bWeb then
		TMConfiguredTestCase_CQI_Refresh_Req = "You cannot refresh requirements from this record in the Web client. Open the requirement record and select Refresh."
		return
	end if	

   'This script must no be launched through the web
	'We also test if the record is editable, it should be as we are in an initialization hook
	If (IsEditable AND NOT a_bWeb) Then
		if Check_RAProjectMaster then
			a_bIsRunningIntegration = CQI_IsRunningIntegration()
			if not a_bIsRunningIntegration then
			 	Set a_oCQSession = GetSession
				if not a_oCQSession is nothing then
					set a_oRequisiteProTool = CQI_GetNewReqProTool()
					if a_oRequisiteProTool is nothing then
						msgbox "ClearQuest could not connect to the Integration Server." + vbcrlf + "Please contact your Administrator.", vbOKOnly + vbCritical, "Rational RequisitePro/ClearQuest Integration"
					else
						a_sError = me.Validate
						if a_sError <> vbNullString then
							MsgBox a_sError, vbOKOnly + vbInformation, _
									"Rational RequisitePro/ClearQuest Integration"
							
							if not a_oRequisiteProTool.Unload(a_sError) then
								Msgbox a_sError, vbOKOnly + vbCritical, "Rational RequisitePro/ClearQuest Integration"
	 						end if
							
							exit function
						end if

						a_vTableDBIDs = getfieldValue(ac_sCQReqListAttName).GetValueAsList
						if not IsEmpty(a_vTableDBIDs) then
 							Dim sRAProjectName
							Dim sRPProjectPath
							Dim sUserName 
							Dim sPassWord
							Dim sRequirementGUID
							dim bGotLogonInfo

							sRAProjectName = me.GetFieldValue("RAProject").GetValue
							sRPProjectPath = CQI_GetRPProjectFromRA(sRAProjectName)
							bGotLogonInfo = CQI_RPlogon(sRPProjectPath, sUserName, sPassword)
							if not bGotLogonInfo then
								if not a_oRequisiteProTool.Unload(a_sError) then
									Msgbox a_sError, vbOKOnly + vbCritical, "Rational RequisitePro/ClearQuest Integration"
		 						end if
								set a_oCQSession = nothing
							 	set a_oCurReq = nothing
							 	set a_oRequisiteProTool = nothing
								exit function
							end if

							if (LBound(a_vTableDBIDs) <= UBound(a_vTableDBIDs)) Then
								For a_lIndex = LBound(a_vTableDBIDs) To UBound(a_vTableDBIDs)
									bRefreshed = a_oRequisiteProTool.RefreshReqFromPlaceholder (GetSession(), _
															cstr(a_vTableDBIDs(a_lIndex)), _
															sRPProjectPath, _
															sUserName, _
															sPassword, _
															a_sError)
									if len (a_sError) <> 0 then
									 	MsgBox "Could not Refresh Requirement - " + a_oCurReq.GetFieldValue("Tag").GetValue + ":" + a_oCurReq.GetFieldValue("Name").GetValue + _
													vbcrlf + "Error: " + vbcrlf + a_sError, _
													vbOKOnly + vbInformation, _
													"Rational RequisitePro/ClearQuest Integration"
										err.clear	
									end if
	
								Next
							end if	'Bound vTable()
 						end if	'a_vTableDBIDs

						if not a_oRequisiteProTool.Unload(a_sError) then
							Msgbox a_sError, vbOKOnly + vbCritical, "Rational RequisitePro/ClearQuest Integration"
 						end if
					end if	'a_oRequisiteProTool
				end if	'a_oCQSession
			end if	'a_bIsRunningIntegration
		else

			msgbox "This ClearQuest/RequisitePro integration operation is not supported. This ClearQuest record is associated with a Rational project that is not accessible from your local area network.", vbOKOnly + vbInformation, "Rational RequisitePro/ClearQuest Integration" 
		end if	'Check_RAProjectMaster

	end if	'a_bWeb

	set a_oCQSession = nothing
 	set a_oCurReq = nothing
 	set a_oRequisiteProTool = nothing


program:
# Do any setup for the action here.
	my $primaryActionType = $entity->GetActionType();
	if($primaryActionType ne $CQPerlExt::CQ_SUBMIT)
	{
		$entity->SetFieldRequirednessForCurrentAction("Build_System_ID",$CQPerlExt::CQ_READONLY);
		$entity->SetFieldRequirednessForCurrentAction("Start_DateTime",$CQPerlExt::CQ_READONLY);
		if($primaryActionType ne $CQPerlExt::CQ_MODIFY)
		{
			$entity->SetFieldRequirednessForCurrentAction("Build_System_URL",$CQPerlExt::CQ_READONLY);
		}
	}


program:
# Return one of
    #   $CQPerlExt::CQ_MANDATORY
    #   $CQPerlExt::CQ_OPTIONAL
    #   $CQPerlExt::CQ_READONLY
    # Example:
    #   if ($username eq "pat") {
    #      $result = $CQPerlExt::CQ_READONLY; 
    #   } else {
    #      $result = $CQPerlExt::CQ_OPTIONAL;
    #   }
    $result = $CQPerlExt::CQ_READONLY;
    my $editAllowed = $session->GetNameValue("CTCOrderEditing");
    if ($editAllowed eq "true") {
        $result = $CQPerlExt::CQ_OPTIONAL;
    }


program:
my $suiteConfig = $entity->GetFieldValue("Configuration")->GetValue();
  	if( $suiteConfig eq "" ||  $suiteConfig eq NULL) {
 		return $result;
 	}
   	# make sure the selected CTCs are from the same configuration
 	my $tCtcs = $entity->GetFieldValue("ConfiguredTestCases")->GetValueAsList();
 	my @ctcs = @$tCtcs;
  	my $validConf = 1;
 	foreach $ctcValue (@ctcs) {
  	 	my  $ctcConfiguration = $session->GetEntity("TMConfiguredTestCase",$ctcValue )->GetFieldValue("Configuration")->GetValue();
 	 	if( $ctcConfiguration ne $suiteConfig ) {
 			$validConf = 0;
 	 		last;
 		}
 	}
  	if( $validConf == 0 ) { 
		$result = "Some Configured Test Cases are not part of the selected Configuration";
 	}


program:
# Return a non-empty string explaining why the field's current
    # value is not valid. If it is valid, return an empty string.

     my $formAssetRegistry = $entity->GetFieldValue("AssetRegistry");
     my $formAssetRegistryValue = $formAssetRegistry->GetValue();
	 

     if (($formAssetRegistryValue eq "") || ($formAssetRegistryValue eq NULL)) {
         return $result;
     }


	 my $refFormIterations = $entity->GetFieldValue("Iterations")->GetValueAsList();

	 my $refAssetIterations = $session->GetEntity("TMAssetRegistry",$formAssetRegistryValue )->GetFieldValue("Iterations")->GetValueAsList();

	 my @assetIterations = @$refAssetIterations;
	 my @formIterations = @$refFormIterations;



	# can't have more form iterations than there are for the actual assetRegistry, 
	 if( $#assetIterations < $#formIterations) {

	 	$result = "Some Iterations do not belong to the Asset Registry";
	 }
	 else {

			# now see if all of the iterations are part of the asset registryf
			foreach  $formIt (@formIterations ) {

				my $found = 0;
				foreach $assetIt (@assetIterations) {

					if($assetIt eq $formIt ){
						$found = 1;
						last;
					}
				}

				if( $found < 1 ){
					$result = "Some Iterations do not belong to the Asset Registry";
					last;
				}
				$found = 0;
			}
	 }


program:
# Return one of
    #   $CQPerlExt::CQ_MANDATORY
    #   $CQPerlExt::CQ_OPTIONAL
    #   $CQPerlExt::CQ_READONLY
    # Example:
    #   if ($username eq "pat") {
    #      $result = $CQPerlExt::CQ_READONLY; 
    #   } else {
    #      $result = $CQPerlExt::CQ_OPTIONAL;
    #   }
      $result = $CQPerlExt::CQ_MANDATORY;
     my $assetRegistry = $entity->GetFieldValue("AssetRegistry")->GetValue();
     if (($assetRegistry eq "") || ($assetRegistry eq NULL)) {
         return $result;
     }
     my @CTCs = $entity->GetFieldValue("ConfiguredTestCases")->GetValueAsList();
     if ($CTCs > 0) {
 		$result = $CQPerlExt::CQ_READONLY;
     }


program:
# Return one of
    #   $CQPerlExt::CQ_MANDATORY
    #   $CQPerlExt::CQ_OPTIONAL
    #   $CQPerlExt::CQ_READONLY
    # Example:
    #   if ($username eq "pat") {
    #      $result = $CQPerlExt::CQ_READONLY; 
    #   } else {
    #      $result = $CQPerlExt::CQ_OPTIONAL;
    #   } 	
    $result = $CQPerlExt::CQ_READONLY;
    my $editAllowed = $session->GetNameValue("CTCOrderEditing");
    if ($editAllowed eq "true") {
        $result = $CQPerlExt::CQ_OPTIONAL;     }
       # $session->SetNameValue("CTCOrderEditing", "false");


program:
# Return a non-empty string explaining why the action cannot commit
    # with its current values. If it is valid, return an empty string.
    # Example:
    #    my $value_info = $entity->GetFieldValue("some field");
    #    if (length($value_info->GetValue()) < 10) {
    #        $result = "Must be at least 10 chars long";
    #    }


program:
# Return one of
    #   $CQPerlExt::CQ_MANDATORY
    #   $CQPerlExt::CQ_OPTIONAL
    #   $CQPerlExt::CQ_READONLY
    # Example:
    #   if ($username eq "pat") {
    #      $result = $CQPerlExt::CQ_READONLY; 
    #   } else {
    #      $result = $CQPerlExt::CQ_OPTIONAL;
    #   }
    $result = $CQPerlExt::CQ_OPTIONAL;


program:
my $childPlans = $entity->GetFieldValue("ChildPlans")->GetValueAsList();
    my $childTestCases = $entity->GetFieldValue("ChildTestCases")->GetValueAsList();
    my @plans = @$childPlans;
	my @tcs = @$childTestCases;
	if( ($#plans < 0 ) && ($#tcs < 0 ) ) {
	    $entity->FireNamedHook("InheritAssetRegistry","");
	}
    $entity->FireNamedHook("RecalculateRequiredness","");


program:
# Return a non-empty string explaining why the field's current
    # value is not valid. If it is valid, return an empty string.

    # changing the parent plan could result in a couple undesirable states:
    # 1) This plan could end up as a descendant of itself
    # 2) If this plan has either child plans or test cases, make sure assetregistry isn't changing
   
    my $refParentPlans = $entity->GetFieldValue("ParentPlan")->GetValueAsList();
    my @parentPlans = @$refParentPlans;
    if ( $parentPlans > 0 ){
        $result = "This Test Plan can only have one parent Plan\n";
        return $result;
    }
   
    my $parentPlanValue = $entity->GetFieldValue("ParentPlan")->GetValue();
    if (($parentPlanValue ne "") && ($parentPlanValue ne NULL)) {

        # First check - make sure no cyclic references:
        $result = "";
        my $id = $entity->GetFieldValue("id")->GetValue();
        my $curParent = $parentPlanValue;
        my $parentEntity;
        while (($curParent ne "") && ($curParent ne NULL)) {
            if ($id eq $curParent) {
                return "Invalid parent Test Plan - a plan cannot be a descendant of itself.";
            }
            $parentEntity = $session->GetEntity("TMTestPlan", $curParent);
            $curParent = $parentEntity->GetFieldValue("ParentPlan")->GetValue();
        }

        my $parentPlanEntity = $session->GetEntity("TMTestPlan", $parentPlanValue);
        my $parentPlanAssetRegistry = $parentPlanEntity->GetFieldValue("AssetRegistry")->GetValue();
        my @childPlans = $entity->GetFieldValue("ChildPlans")->GetValueAsList();
        my @childTestCases = $entity->GetFieldValue("ChildTestCases")->GetValueAsList();

        # Second check - make sure assetregistry isn't changing, if there are any child tcs or plans.
        my $assetregistry = $entity->GetFieldValue("AssetRegistry")->GetValue();
        if (($assetregistry ne "") && ($assetregistry ne NULL)) {

            if ($parentPlanAssetRegistry ne $assetregistry) {
                if (($#childTestCases > -1) || ($#childPlans > -1)) {
                    return "This Test Plan has children, and therefore can only be reparented to a Test Plan of the same Asset Registry";
                }
            }
        }
    }


program:
# Return one of
    #   $CQPerlExt::CQ_MANDATORY
    #   $CQPerlExt::CQ_OPTIONAL
    #   $CQPerlExt::CQ_READONLY
    # Example:
    #   if ($username eq "pat") {
    #      $result = $CQPerlExt::CQ_READONLY; 
    #   } else {
    #      $result = $CQPerlExt::CQ_OPTIONAL;
    #   }

    $result = $CQPerlExt::CQ_MANDATORY;

    my $editAllowed = $session->GetNameValue("TestPlanEditing");
    if ($editAllowed eq "true") {
        return $result;
	}

    # if child TCs or Plans exist, do not allow assetregistry to change
    my $childTestCases = $entity->GetFieldValue("ChildTestCases")->GetValueAsList();
    my $childTestPlans = $entity->GetFieldValue("ChildPlans")->GetValueAsList();

    my @tcs = @$childTestCases;
    $session->OutputDebugString("Number of tcs: " . $#tcs . "\n");
	my @plans = @$childTestPlans;
    $session->OutputDebugString("Number of plans: " . $#plans . "\n");

    if ($#tcs > -1 || $#plans > -1) {
        return $CQPerlExt::CQ_READONLY;
    }

	# regardless of child TCs, if there's no parent, require an AssetRegistry
    my $parentPlanValue = $entity->GetFieldValue("ParentPlan")->GetValue();
    if (($parentPlanValue eq NULL) || ($parentPlanValue eq "")) {
        return $CQPerlExt::CQ_MANDATORY;
    }


program:
# This hook will be run each time the field's value changes.
    # This hook runs before the new value is validated so be aware
    # the new value may not be valid.
    # Example:
    #   my $op_sys = $entity->GetFieldValue($fieldname)->GetValue();
    #   if ($op_sys eq "windows") {
    #      $entity->SetFieldValue("os_version", "NT 4.x");
    #      <etc.>
    #   }
	$entity->FireNamedHook("RecalculateRequiredness","");


program:
my $formAssetRegistry = $entity->GetFieldValue("AssetRegistry");
     my $formAssetRegistryValue = $formAssetRegistry->GetValue();
	 

     if (($formAssetRegistryValue eq "") || ($formAssetRegistryValue eq NULL)) {
         return $result;
     }


	 my $refFormIterations = $entity->GetFieldValue("Iterations")->GetValueAsList();

	 my $refAssetIterations = $session->GetEntity("TMAssetRegistry",$formAssetRegistryValue )->GetFieldValue("Iterations")->GetValueAsList();

	 my @assetIterations = @$refAssetIterations;
	 my @formIterations = @$refFormIterations;



	# can't have more form iterations than there are for the actual assetRegistry, 
	 if( $#assetIterations < $#formIterations) {

	 	$result = "Some Iterations do not belong to the Asset Registry";
	 }
	 else {

			# now see if all of the iterations are part of the asset registryf
			foreach  $formIt (@formIterations ) {

				my $found = 0;
				foreach $assetIt (@assetIterations) {

					if($assetIt eq $formIt ){
						$found = 1;
						last;
					}
				}

				if( $found < 1 ){
					$result = "Some Iterations do not belong to the Asset Registry";
					last;
				}
				$found = 0;
			}
	 }


program:
# Do any setup for the action here.

    $session->SetNameValue("OldAssetRegistry", $entity->GetFieldValue("AssetRegistry")->GetValue());
    $session->OutputDebugString("Old AssetRegistry: " . $entity->GetFieldValue("AssetRegistry")->GetValue() . "\n");


program:
REM Return a non-empty string explaining why the action
   REM cannot commit with the current values.
   REM Or, if it is valid, return an empty string value.
   REM Example: 
   REM    Dim value_info
   REM    Set value_info = GetFieldValue("some field")
   REM    If Len(value_info.GetValue()) < 10 Then
   REM        TMTestPlan_Validation = "Must be at least 10 chars long"
   REM    End If

REM Checks if associations still exist with current CQ record when user tries to delete it
REM if none, deletion completed
REM if some, deletion canceled

	Dim a_CurrentActionType					'Action type of the action that initiated the execution of this script

	a_CurrentActionType = GetActionType()
   'Check to see if the real action is a delete action.
	'If not exit.
	if a_CurrentActionType = AD_DELETE then
		'Don't allow user to delete the current record unless no requirements are
		'associated with it
		Dim ac_sCQReqListAttName				'Name of the global variable containing the name of the field of the CQ record that stores associations
		Dim a_vTableDBIDs							'List of DBIDs of Req proxies associated to the current CQ record
	
		ac_sCQReqListAttName= "Requirements_List"
' RATLC00015495 
'		a_vTableReqIds = GetFieldValue(ac_sCQReqListAttName).GetValueAsList		
        a_vTableDBIDs = GetFieldValue(ac_sCQReqListAttName).GetValueAsList
		if IsEmpty(a_vTableDBIDs) then
'			EnhancementRequest_Validation = vbNullString		
		TMTestPlan_Validation = vbNullString		
		else
'			EnhancementRequest_Validation = "Rational RequisitePro/ClearQuest Integration: You have to remove all associations with RequisitePro requirements before you can delete the current ClearQuest record."	    	
			TMTestPlan_Validation = "Rational RequisitePro/ClearQuest Integration: You have to remove all associations with RequisitePro requirements before you can delete the current ClearQuest record."
		end if
	end if	'a_CurrentActionType


program:
REM Check the requirement type for its type guid
   REM Check the type of the current record type
   REM pull up a requirement map for this record type
   REM see if the requirement type guid is the same as the guid 
   REM for the requirement that is being added.
	
	' Get all the requirement types that this artifact can be associated to
	Dim session, reqList, listItem, tempReq, recordType
	
	TMTestPlan_Validation = ""
	Set session = GetSession
	recordType = GetEntityDefName

	Dim queryDef, queryField, operator, filterNode, resultSet
	Dim ac_sTagField
	Dim ac_sNameField
	
	ac_sTagField = "Tag"
	ac_sNameField = "Name"

	Set queryDef = session.BuildQuery("RequirementMap")
	If Not queryDef is Nothing then
	' Building the query
		queryField = queryDef.BuildField("RPReqTypeGUID")
		Set operator = queryDef.BuildFilterOperator(AD_COMP_OP_EQ)
		operator.BuildFilter "CQEntityDefName",	AD_COMP_OP_EQ, recordType
		Set resultSet = session.BuildResultSet(queryDef)
		resultSet.Execute()

		Dim found, tempGUID, counter, status, GUIDs

		Set GUIDs = CreateObject("Scripting.dictionary")

		found = False
		counter = 0
		status = resultSet.MoveNext
	'	build the requirement types GUIDs array
		Do While status = AD_SUCCESS 
			tempGUID = resultSet.GetColumnValue(1)
			GUIDs.Add counter, tempGUID
			counter = counter + 1
		 	status = resultSet.MoveNext
		 Loop 

	'	Retrieve all the requirements that are associated to the current artifact
		Dim tempReqList
		tempReqList = GetFieldValue("Requirements_List").GetValue	

		If tempReqList <> "" then
		'	Break the string of line feed separated requirement ids in to an array
			Dim array ' array of requirements
			Dim u ' number of elements in the array
			Dim result
			result = ""
		'	Splitting it
		  	array = Split(Cstr(tempReqList),vbLF)
			u = UBound(array)
			Dim ReqId, requirement, reqTypeGUID
		'	Check if the requirement's type is in the list of allowed requirement GUIDs list
			For i = 0 To u
				found = False
				ReqId = array(i)
			'	Get the requirement
				Set requirement = session.GetEntity("Requirement", ReqId)
				If Not requirement Is Nothing Then
					Dim fieldDef 
				'	Get the requirement type
					reqTypeGUID = requirement.GetFieldValue("Type_GUID").GetValue
				'	Check to see if the GUID is matching with the existing list
					For j = 0 to GUIDs.count
						If GUIDs.Item(j) <> "" Then
							If GUIDs.Item(j) = reqTypeGUID Then
							'	Found it so dont need to loop anymore
								found = True
								Exit For
							End If
						Else
							'	Valid guid's are done so skip
							Exit For
						End If
					Next

				End If
			'	Create the erroneous list of requirements

				If Not found Then
					Dim sReq
					Dim sName
					
					sName = requirement.GetFieldValue(ac_sNameField).GetValue
					sReq = requirement.GetFieldValue(ac_sTagField).GetValue
					' Limiting the name length to about 30 characters for display
					if len(sName) = 0 then
						result = result & vbLF & sReq
					elseif len(sText) > 33 then
						result = result & vbLF & sReq & ": " & left(sName, 30) + "..."
					else
						result = result & vbLF & sReq & ": " & sName
					end if
				end if				
			Next
			'	Check to see if the erroneous list of requirements is empty or not
			If result <> "" Then
			'	if the list is not empty create the error message.
				TMTestPlan_Validation = "The following Requirements types dont match " & result
			End If
		End If

	End If


program:
if (ref ($param) eq "CQEventObject") {
        # add your CQEventObject parameter handling code here
    } elsif (ref (\$param) eq "SCALAR") {
        # add your scalar parameter handling code here

  		my $parentPlanValue = $entity->GetFieldValue("ParentPlan")->GetValue();
 		if (($parentPlanValue eq NULL) || ($parentPlanValue eq "")) {
 			return $result;
 		}

 		my $parentPlan = $session->GetEntity("TMTestPlan", $parentPlanValue);
 		$entity->SetFieldValue("AssetRegistry", $parentPlan->GetFieldValue("AssetRegistry")->GetValue()); 


    } else {
        # add your handling code for other type parameters here, for example:
        # die("Unknown parameter type");
    }


program:
my $parentPlanValue = $entity->GetFieldValue("ParentPlan")->GetValue();
    my $assetRegistryValue = $entity->GetFieldValue("AssetRegistry")->GetValue();
    my $childTestCases = $entity->GetFieldValue("ChildTestCases")->GetValueAsList();
    my @tcs = @$childTestCases;

	$entity->SetFieldRequirednessForCurrentAction("AssetRegistry", $CQPerlExt::CQ_MANDATORY);
    $entity->SetFieldRequirednessForCurrentAction("ParentPlan", $CQPerlExt::CQ_OPTIONAL);
    my $editAllowed = $session->GetNameValue("TestPlanEditing");
    if ($editAllowed eq "true") {
        return $result;
    } elsif (($assetRegistryValue ne "") && ($assetRegistryValue ne NULL)) {

        if (($#tcs > -1) || (($parentPlanValue ne "") && ($parentPlanValue ne NULL))) {
            $entity->SetFieldRequirednessForCurrentAction("AssetRegistry", $CQPerlExt::CQ_READONLY);
        }

    }


program:
if (ref ($param) eq "CQEventObject") {
        # add your CQEventObject parameter handling code here
    } elsif (ref (\$param) eq "SCALAR") {
        # add your scalar parameter handling code here
    } else {
  
  		
    }


program:
REM add your hook code here

REM Launch RequisitePro Association dialog box, with list of Req Proxy DBIDs of Requirements already associated to current CQ record
REM if return of call is OK
REM	Position state of state machine to "MODIFIED"
REM if return of call is Cancel


	Dim eRet_Empty
	Dim eRet_OK
	Dim eRet_Cancel
	Dim eRet_Error
	Dim ac_sCQReqListAttName				'Name of the global variable containing the name of the field of the CQ record that stores associations
	Dim ac_sCQIStateVar						'Name of the global variable containing the current state of the state machine
	Dim ac_sCQIListReqsVar					'Name of the global variable containing the list of Proxy Req DBIDs associated to the current CQ record
	Dim ac_sCQIdbidSeparator				'Character used to separate dbids in string list 
	Dim a_bWeb									'Web or not
	Dim a_bIsRunningIntegration			'Contains a boolean indicating if the integration is already in progress, to prevent reccurence
	Dim a_bProjectSet							'Contains a boolean indicating if a Rational Project has been selected for the current CQ record
	Dim a_oCQSession							'Current CQ session
	Dim a_oRequisiteProTool					'Reference to a ASCQIIntegration.RequisiteProTool instance
	Dim a_sListReqDBIDs						'List of Req Proxy DBIDs associated to the current CQ record
	Dim a_eRet									'Contains value returned by the call to integration
	Dim a_sError								'Error message sent back by integration in case of a failure
	Dim a_vTableDBIDs							'List of DBIDs of Req proxies associated to the current CQ record
	Dim a_lIndex
	Dim a_sFail									'Return value of the creation of the association in ClearQuest between current CQ record and the Req Proxy

	eRet_Empty = 0
	eRet_OK = 1
	eRet_Cancel = 2
	eRet_Error = 3	

	ac_sCQReqListAttName= "Requirements_List"	
	ac_sCQIStateVar = "CQIState"
	ac_sCQIListReqsVar = "CQIReqs"
	ac_sCQIdbidSeparator = ","
	
	a_bWeb = Check_Web()

	' RATLC01009865 - Display message for non-functional button in CQWeb
	if a_bWeb then
		' Need this Error handler otherwise it does not work from CQWeb.
		On Error resume next
	 	err.clear

		TMTestPlan_CQI_Select_Req = "This operation is not available in the Web client."
		return
	end if	


   'This script must no be launched through the web
	'We also test if the record is editable
	If (IsEditable AND NOT a_bWeb) Then

		if Check_RAProjectMaster then
			a_bIsRunningIntegration = CQI_IsRunningIntegration()
			if not a_bIsRunningIntegration then
				a_bProjectSet = Check_Project()
				if a_bProjectSet then
				 	Set a_oCQSession = GetSession
					if not a_oCQSession is nothing then
						set a_oRequisiteProTool = CQI_GetRequisiteProTool()	
						if a_oRequisiteProTool is nothing then
							msgbox "ClearQuest could not connect to the Integration Server." + vbcrlf + "Please contact your Administrator.", vbOKOnly + vbCritical, "Rational RequisitePro/ClearQuest Integration"
						else
							' RATLC01201983 - Do not use list of requirements when beginning to modify the record.
							' instead use the current list of requirements
							' a_sListReqDBIDs = a_oCQSession.NameValue(ac_sCQIListReqsVar)
							a_vTableDBIDs = getfieldValue(ac_sCQReqListAttName).GetValueAsList
							if not IsEmpty(a_vTableDBIDs) then
								CQI_GetListFromDBIDTable a_vTableDBIDs, ac_sCQIdbidSeparator, a_sListReqDBIDs
							end if   ' a_vTableDBIDs

							a_eRet = a_oRequisiteProTool.AssociateFromClearQuest(me, ac_sCQReqListAttName, a_sListReqDBIDs, a_sError)
							Select Case a_eRet
							   	Case eRet_OK
									a_oCQSession.NameValue(ac_sCQIStateVar)= "MODIFIED" 
									if a_sListReqDBIDs <> vbNullString then
										a_vTableDBIDs = empty
										if CQI_GetTableFromDBIDList(a_sListReqDBIDs, ac_sCQIdbidSeparator, a_vTableDBIDs) then
											if not IsEmpty(a_vTableDBIDs) then
												for a_lIndex = LBound(a_vTableDBIDs) to UBound(a_vTableDBIDs)
											        a_sFail = AddFieldValue(ac_sCQReqListAttName, cstr(a_vTableDBIDs(a_lIndex)))
													if a_sFail = vbNullString then
														call CQI_AddDBIDToList(cstr(a_vTableDBIDs(a_lIndex)), ac_sCQIdbidSeparator)
													end if	'a_sFail
												next
											end if
										end if
									end if
				
						      Case eRet_Cancel

								Case Else		
									msgbox a_sError ,vbOKOnly + vbCritical, "Rational RequisitePro/ClearQuest Integration"
				
							End Select
						end if	'a_oRequisiteProTool
					end if	'a_oCQSession
				else
					if GetEntityDefName = "EnhancementRequest" and GetActionType = AD_SUBMIT then
						msgbox "In order to associate a requirement, you must first submit the EnhancementRequest record.", vbOKOnly + vbInformation, "Rational RequisitePro/ClearQuest Integration"
					else 						
						MsgBox "A valid RAProject must be selected.", vbOKOnly + vbInformation, "Rational RequisitePro/ClearQuest Integration"
					end if
				end if	'a_bProjectSet
			else								  
				msgbox "Modification (or viewing) of Requirement properties cannot be done at this point, as the Clearquest information is currently displayed from RequisitePro. Please access the Requirement Properties dialog from RequisitePro.", vbOKOnly + vbInformation, "Rational RequisitePro/ClearQuest Integration" 
			end if	'a_bIsRunningIntegration

		else								  
			msgbox "This ClearQuest/RequisitePro integration operation is not supported. This ClearQuest record is associated with a Rational project that is not accessible from your local area network.", vbOKOnly + vbInformation, "Rational RequisitePro/ClearQuest Integration" 
		end if	'Check_RAProjectMaster
	end if	'a_bWeb

	set a_oRequisiteProTool = nothing
	set a_oCQSession = nothing


program:
REM add your hook code here

REM Launch RequisitePro Properties dialog box for the selected Requirement in the CQ list box, and pass its DBID 
REM if return of call is ePrp_OK
REM	Nothing is done
REM if return of call is ePrp_Removed
REM	then the requirement is removed fromlist of requirement associated with current CQ record

	On Error resume next	'handle ListSelection empty
	err.clear

	Dim a_bWeb									'Web or not
	Dim a_bIsRunningIntegration			'Contains a boolean indicating if the integration is already in progress, to prevent reccurence
	Dim a_oCQSession							'Current CQ session
	Dim a_lNumberSel							'Number of Requirements currently selected in the CQ List Box
	Dim a_sStrElm								'CQ Key of the Req Proxy selected in the CQ List Box (currently dbid)
	Dim a_sDBID									'DBID of the Req Proxy selected in the CQ List Box
	Dim a_bEmpty								'Boolean indicationg wether or not a Req Proxy is selected in the CQ List Box
	Dim a_sError								'Error message sent back by integration in case of a failure
	Dim a_sFail									'Return value of the deletion of the association in ClearQuest between current CQ record and the Req Proxy
 	dim a_oReq									' selected Requirement record
	Dim vRet									' Generic return value
	Dim ac_sCQReqListAttName
	
	ac_sCQReqListAttName= "Requirements_List"

	a_bWeb = Check_Web()

	' RATLC01009865 - Display message for non-functional button in CQWeb
	if a_bWeb then
		TMTestPlan_CQI_Properties_Req = "You cannot view a requirement from this record in the Web client. Open the requirement record and select View."
		return
	end if	

   'This script must not be launched through the web
	'We also test if the record is editable
	If (IsEditable AND NOT a_bWeb) Then
		a_bIsRunningIntegration = CQI_IsRunningIntegration()
		if not a_bIsRunningIntegration then
		 	Set a_oCQSession = GetSession
			if not a_oCQSession is nothing then
				if Check_Eclipse() then
					' Handle the selection differently for CQ Eclipse.
					' param = string of selected DBIDs separated by Line Feed.
					Dim sParam 
					Dim bGotOne

					sParam = cstr(param)
					bGotOne = false
					' There is an extra LF added at the end of every DBID 
					' even for one selection. The code below handles both the 
					' cases, with and without the last LF.
					if len(sParam) > 1 then
					    If InStrRev(sParam, vbLf) = Len(sParam) Then
					    	If InStrRev(Left(sParam, Len(sParam) - 1), vbLf) = 0 Then
					            ' There is an extra LF at the end of the string
					            a_sDBID = Left(sParam, Len(sParam) - 1)
					            bGotOne = True
					        End If
					    Else
					        If InStrRev(sParam, vbLf) = 0 Then
					            a_sDBID = sParam
					            bGotOne = True
					        End If
					    End If
					End If

					if bGotOne then
						set a_oReq = a_oCQSession.GetEntity("Requirement", a_sDBID)
						if not a_oReq is nothing then
							vRet = a_oReq.FireNamedHook("CQI_Properties_Req", "")
							set a_oReq = nothing
						end if
					else
						MsgBox "Please select one requirement in the list view to get the properties.", vbOKOnly + vbInformation, "Rational RequisitePro/ClearQuest Integration"
					end if
				else
					a_lNumberSel = 0
					For Each a_sStrElm In param.ListSelection
						a_sDBID = a_sStrElm
						a_lNumberSel = a_lNumberSel + 1
					Next
					a_bEmpty = IsNull(a_sDBID) or IsEmpty(a_sDBID)
					if a_bEmpty then
						'Nothing to do
						MsgBox "Please select one requirement in the list view to get the properties.", vbOKOnly + vbInformation, "Rational RequisitePro/ClearQuest Integration"
					else
		on error goto 0
						if a_lNumberSel = 1 then
	 						set a_oReq = a_oCQSession.GetEntity("Requirement", a_sDBID)
	 						if not a_oReq is nothing then
	 							vRet = a_oReq.FireNamedHook("CQI_Properties_Req", "")
	 						end if
	 				   	else
							MsgBox "Please select one requirement in the list view to get the properties.", vbOKOnly + vbInformation, "Rational RequisitePro/ClearQuest Integration"
						end if
					end if	'a_bEmpty
				end if ' Check_Eclipse()

				' RATLC01011263 - If the Requirement is deleted from RP. Prompt user to remove the association 
				if vRet = "DELETED" then
					vRet = Msgbox ("The requirement has been deleted in Rational RequisitePro." _
									+ vbcrlf+ "Do you want to remove the association?", _
									vbYesNo + vbQuestion, _
									"Rational RequisitePro/ClearQuest Integration")
					if vRet = vbYes then
						DeleteFieldValue ac_sCQReqListAttName, a_sDBID
					end if
				end if

			end if	'a_oCQSession
		else								  
			msgbox "Modification (or viewing) of Requirement properties cannot be done at this point, as the Clearquest information is currently displayed from RequisitePro. Please access the Requirement Properties dialog from RequisitePro.", vbOKOnly + vbInformation, "Rational RequisitePro/ClearQuest Integration" 
		end if	'a_bIsRunningIntegration
	end if	'a_bWeb

	set a_oReq = nothing
	set a_oCQSession = nothing


program:
REM add your hook code here

REM Refreshes the Requirement proxies of associated Requirements in the CQ list box
 	On Error resume next
 	err.clear

	Dim ac_sCQReqListAttName				'Name of the global variable containing the name of the field of the CQ record that stores associations
	Dim ac_sCQIdbidSeparator				'Character used to separate dbids in string list 
	Dim a_bWeb								'Web or not
	Dim a_bIsRunningIntegration				'Contains a boolean indicating if the integration is already in progress, to prevent reccurence
	Dim a_oCQSession						'Current CQ session
	Dim a_oRequisiteProTool					'Reference to a ASCQIIntegration.RequisiteProTool instance
	Dim a_sListReqDBIDs						'List of Req Proxy DBIDs associated to the current CQ record
	Dim a_vTableDBIDs						'List of DBIDs of Req proxies associated to the current CQ record
	Dim a_sError							'Error message sent back by integration in case of a failure
	Dim a_sDBIDtoRemove						'List of DBIDs of Req proxies associated to the current CQ record to remove because they don't exist anymore
	Dim a_sDBID								'DBIDs to remove
 	Dim a_oCurReq
	 dim ac_sRequirement
 	Dim ac_sReqRefreshAction
	ac_sRequirement = "Requirement" 
	ac_sReqRefreshAction = "Refresh"					  

	ac_sCQReqListAttName= "Requirements_List"	
	ac_sCQIdbidSeparator = ","

	a_bWeb = Check_Web()

	' RATLC01009865 - Display message for non-functional button in CQWeb
	if a_bWeb then
		TMTestPlan_CQI_Refresh_Req = "You cannot refresh requirements from this record in the Web client. Open the requirement record and select Refresh."
		return
	end if	

   'This script must no be launched through the web
	'We also test if the record is editable, it should be as we are in an initialization hook
	If (IsEditable AND NOT a_bWeb) Then
		if Check_RAProjectMaster then
			a_bIsRunningIntegration = CQI_IsRunningIntegration()
			if not a_bIsRunningIntegration then
			 	Set a_oCQSession = GetSession
				if not a_oCQSession is nothing then
					set a_oRequisiteProTool = CQI_GetNewReqProTool()
					if a_oRequisiteProTool is nothing then
						msgbox "ClearQuest could not connect to the Integration Server." + vbcrlf + "Please contact your Administrator.", vbOKOnly + vbCritical, "Rational RequisitePro/ClearQuest Integration"
					else
						a_sError = me.Validate
						if a_sError <> vbNullString then
							MsgBox a_sError, vbOKOnly + vbInformation, _
									"Rational RequisitePro/ClearQuest Integration"
							
							if not a_oRequisiteProTool.Unload(a_sError) then
								Msgbox a_sError, vbOKOnly + vbCritical, "Rational RequisitePro/ClearQuest Integration"
	 						end if
							
							exit function
						end if

						a_vTableDBIDs = getfieldValue(ac_sCQReqListAttName).GetValueAsList
						if not IsEmpty(a_vTableDBIDs) then
 							Dim sRAProjectName
							Dim sRPProjectPath
							Dim sUserName 
							Dim sPassWord
							Dim sRequirementGUID
							dim bGotLogonInfo

							sRAProjectName = me.GetFieldValue("RAProject").GetValue
							sRPProjectPath = CQI_GetRPProjectFromRA(sRAProjectName)
							bGotLogonInfo = CQI_RPlogon(sRPProjectPath, sUserName, sPassword)
							if not bGotLogonInfo then
								if not a_oRequisiteProTool.Unload(a_sError) then
									Msgbox a_sError, vbOKOnly + vbCritical, "Rational RequisitePro/ClearQuest Integration"
		 						end if
								set a_oCQSession = nothing
							 	set a_oCurReq = nothing
							 	set a_oRequisiteProTool = nothing
								exit function
							end if

							if (LBound(a_vTableDBIDs) <= UBound(a_vTableDBIDs)) Then
								For a_lIndex = LBound(a_vTableDBIDs) To UBound(a_vTableDBIDs)
									bRefreshed = a_oRequisiteProTool.RefreshReqFromPlaceholder (GetSession(), _
															cstr(a_vTableDBIDs(a_lIndex)), _
															sRPProjectPath, _
															sUserName, _
															sPassword, _
															a_sError)
									if len (a_sError) <> 0 then
									 	MsgBox "Could not Refresh Requirement - " + a_oCurReq.GetFieldValue("Tag").GetValue + ":" + a_oCurReq.GetFieldValue("Name").GetValue + _
													vbcrlf + "Error: " + vbcrlf + a_sError, _
													vbOKOnly + vbInformation, _
													"Rational RequisitePro/ClearQuest Integration"
										err.clear	
									end if
	
								Next
							end if	'Bound vTable()
 						end if	'a_vTableDBIDs

						if not a_oRequisiteProTool.Unload(a_sError) then
							Msgbox a_sError, vbOKOnly + vbCritical, "Rational RequisitePro/ClearQuest Integration"
 						end if
					end if	'a_oRequisiteProTool
				end if	'a_oCQSession
			end if	'a_bIsRunningIntegration
		else

			msgbox "This ClearQuest/RequisitePro integration operation is not supported. This ClearQuest record is associated with a Rational project that is not accessible from your local area network.", vbOKOnly + vbInformation, "Rational RequisitePro/ClearQuest Integration" 
		end if	'Check_RAProjectMaster

	end if	'a_bWeb

	set a_oCQSession = nothing
 	set a_oCurReq = nothing
 	set a_oRequisiteProTool = nothing


program:
# Set $result to 1 if the user has permission to perform
    # this action, otherwise set it to 0.
    $result = 0;
    my $createAllowed = $session->GetNameValue("TestTypeCreation");
    if ($createAllowed eq "true") {
        $result = 1;
        $session->SetNameValue("TestTypeCreation", "false");
    }


program:
my $ctcVal = $entity->GetFieldValue("ConfiguredTestCase")->GetValue();

		

    if (($ctcVal ne "") && ($ctcVal ne NULL)) {
		
#		$session->OutputDebugString(" Changed\n");
#    	$session->SetNameValue("AdapterTestLogCreation", "false");
		
        $entity->SetFieldRequirednessForCurrentAction("Iteration", $CQPerlExt::CQ_OPTIONAL);
		
        my $ctcEntity = $session->GetEntity("TMConfiguredTestCase", $ctcVal);
        my $scriptValue = $ctcEntity->GetFieldValue("Script")->GetValue();
        if (($scriptValue ne "") && ($scriptValue ne NULL)) {
            $entity->SetFieldValue("Script", $scriptValue);
        }
        my $testTypeValue = $ctcEntity->GetFieldValue("TestType")->GetValue();
        if (($testTypeValue ne "") && ($testTypeValue ne NULL)) {
            $entity->SetFieldValue("TestType", $testTypeValue);
        }

        my $scriptOptionsValue = $ctcEntity->GetFieldValue("ScriptOptions")->GetValue();
        if (($scriptOptionsValue ne "") && ($scriptOptionsValue ne NULL)) {
            $entity->SetFieldValue("ScriptOptions", $scriptOptionsValue);
        }
        my $configValue = $ctcEntity->GetFieldValue("Configuration")->GetValue();
        my $configEntity = $session->GetEntity("TMConfiguration", $configValue);
        my $configs = $configEntity->GetFieldValue("Variables")->GetValueAsList();
        my @configArray = @$configs;
        $entity->SetFieldValue("ConfigurationValues", "");
        foreach $cval (@configArray) {
            $entity->AddFieldValue("ConfigurationValues", $cval);
        }
    }
	else {
			$entity->SetFieldValue( "Iteration", "" );
	        $entity->SetFieldRequirednessForCurrentAction("Iteration", $CQPerlExt::CQ_READONLY);

	}


program:
# Return one of
    #   $CQPerlExt::CQ_MANDATORY
    #   $CQPerlExt::CQ_OPTIONAL
    #   $CQPerlExt::CQ_READONLY
    # Example:
    #   if ($username eq "pat") {
    #      $result = $CQPerlExt::CQ_READONLY; 
    #   } else {
    #      $result = $CQPerlExt::CQ_OPTIONAL;
    #   }
   $result = $CQPerlExt::CQ_READONLY;
    my $editAllowed = $session->GetNameValue("BuildEditing");
    if ($editAllowed eq "true") {
        $result = $CQPerlExt::CQ_OPTIONAL;
    }
# intentionally leaving it read only for backwards compatibility, remove line when 
# reving major version of schema.
   $result = $CQPerlExt::CQ_OPTIONAL;


program:
# Return one of
    #   $CQPerlExt::CQ_MANDATORY
    #   $CQPerlExt::CQ_OPTIONAL
    #   $CQPerlExt::CQ_READONLY
    # Example:
    #   if ($username eq "pat") {
    #      $result = $CQPerlExt::CQ_READONLY; 
    #   } else {
    #      $result = $CQPerlExt::CQ_OPTIONAL;
    #   }

#		$session->OutputDebugString(" perm1\n");
    # If the log is to be modified from the plugin adapters, allow any iteration
    $result = $CQPerlExt::CQ_OPTIONAL;
    if ($session->GetNameValue("AdapterTestLogCreation") eq "true") {
        return $result;
    }
		$session->OutputDebugString(" perm2\n");

    # if you're doing by hand, you need CTC before Iteration.
    my $ctcVal = $entity->GetFieldValue("ConfiguredTestCase")->GetValue();
    if (($ctcVal eq NULL) || ($ctcVal eq "")) {
        return $CQPerlExt::CQ_READONLY;
    }


program:
@choices = ();

	$ctcValue = $entity->GetFieldValue("ConfiguredTestCase")->GetValue();

	if( $ctcValue eq "" || $ctcValue eq NULL ) {
		return @choices;
	}
	$ctc = $session->GetEntity("TMConfiguredTestCase", $ctcValue);


	$tcValue = $ctc->GetFieldValue("TestCase")->GetValue();
 	$tc = $session->GetEntity("TMTestCase", $tcValue);
	$tpValue = $tc->GetFieldValue( "ParentPlan")->GetValue();
 	$tp = $session->GetEntity("TMTestPlan", $tpValue);

	@assReg = $tp->GetFieldValue("AssetRegistry")->GetValue();

	my $querydef = $session->BuildQuery("TMIteration");

	#
	# set fields to be displayed by the query
	#
	$querydef->BuildField("AssetRegistry");
	$querydef->BuildField("Name");


	#
	# set fields to be matched by the query -- the query filter(s)
	# i.e. set no required matching fields so as to return all TestPlan records
	#
	my $operator = $querydef->BuildFilterOperator($CQPerlExt::CQ_BOOL_OP_AND);
  	$operator->BuildFilter("AssetRegistry", $CQPerlExt::CQ_COMP_OP_EQ,\@assReg );


	#
	# execute the query and save the headline of each TestPlan found by the query
	#
	my $resultset = $session->BuildResultSet($querydef);
	$resultset->Execute;

	while ($resultset->MoveNext eq $CQPerlExt::CQ_SUCCESS) {
		$session->OutputDebugString("found TestPlan record: $resultset->GetColumnValue(1)\n");
		$str = $resultset->GetColumnValue(1). " " . $resultset->GetColumnValue(2);
		push(@choices, $str);
	}


program:
# Return one of
    #   $CQPerlExt::CQ_MANDATORY
    #   $CQPerlExt::CQ_OPTIONAL
    #   $CQPerlExt::CQ_READONLY
    # Example:
    #   if ($username eq "pat") {
    #      $result = $CQPerlExt::CQ_READONLY; 
    #   } else {
    #      $result = $CQPerlExt::CQ_OPTIONAL;
    #   }
    $result = $CQPerlExt::CQ_READONLY;
    my $editAllowed = $session->GetNameValue("TraceFilesEditing");
    if ($editAllowed eq "true") {
        $result = $CQPerlExt::CQ_OPTIONAL;
    }


program:
# This hook will be run each time the field's value changes.
    # This hook runs before the new value is validated so be aware
    # the new value may not be valid.
    # Example:
    #   my $op_sys = $entity->GetFieldValue($fieldname)->GetValue();
    #   if ($op_sys eq "windows") {
    #      $entity->SetFieldValue("os_version", "NT 4.x");
    #      <etc.>
    #   }
    my $buildVal = $entity->GetFieldValue("BuildRecord.Build_System_ID")->GetValue();
	$entity->SetFieldValue("Build",$buildVal)


program:
# Do any setup for the action here.

    $entity->SetFieldRequirednessForCurrentAction("ConfiguredTestCase", $CQPerlExt::CQ_MANDATORY);


program:
# build the query object

	# Add the new build value to the dynamic list so that other users
    # have it available.
	my $buildVal = $entity->GetFieldValue("Build")->GetValue();
	if (($buildVal ne "") && ($buildVal ne NULL) && ($session->HasUserPrivilege($CQPerlExt::CQ_DYNAMIC_LIST_ADMIN))) {
		eval {
			$session->AddListMember("Build", $buildVal);
		};
		if ($@) {
			$session->OutputDebugString("AddListMember threw: " . $@ . "\n");
		}
	}



	$sessionObj = $entity->GetSession();
 	$queryDefObj = $sessionObj->BuildQuery("TMTestLog");
  	# set the fields we are intested in
 	$queryDefObj->BuildField("dbid");
 	 	# get the ctc and the iteration for the filter
 	my @ctc = $entity->GetFieldValue("ConfiguredTestCase")->GetValue();
 	my @it;	
	my $itOperator = $CQPerlExt::CQ_COMP_OP_IS_NULL;	
	my $itVal = $entity->GetFieldValue("Iteration")->GetValue();	
	if( ($itVal ne NULL) && ($itVal ne "" ) ) {		
		@it = $entity->GetFieldValue("Iteration")->GetValue();		
		$itOperator = $CQPerlExt::CQ_COMP_OP_EQ;	
	} 	
 	@latest = "true";
 	# build the filter
 	$operator = $queryDefObj->BuildFilterOperator($CQPerlExt::CQ_BOOL_OP_AND);
  	$operator->BuildFilter("Iteration", $itOperator, \@it );
 	$operator->BuildFilter("ConfiguredTestCase", $CQPerlExt::CQ_COMP_OP_EQ, \@ctc );
 	$operator->BuildFilter("Latest", $CQPerlExt::CQ_COMP_OP_EQ,\@latest );
  	# execute the query
 	$resultSetObj = $sessionObj->BuildResultSet($queryDefObj);
 	$resultSetObj->Execute();
  	# loop and update any old records by changing the field value to reflect that they
 	# are not the latest
 	while ($resultSetObj->MoveNext == $CQPerlExt::CQ_SUCCESS) {  		# get the ids of the records
 		$dbid = $resultSetObj->GetColumnValue(1);
 		$newDbid = $entity->GetDbId();
  		if( $newDbid ne $dbid ){
  			# get the entity of the current value in the record set
 			$OldEntity = $session->GetEntity("TMTestLog", $dbid);
  			# set the new value
			eval {
 			$OldEntity->EditEntity("modify");
 			$OldEntity->SetFieldValue("Latest", "false");
  			# validate changes
 			$status = $OldEntity->Validate();
  			# commit changes
 			if ($status eq "") {
 				$OldEntity->Commit();
 			} else {
 				$OldEntity->Revert();
 			}
			};
			if ($@) {
			    $session->OutputDebugString("Modify()/Commit()/Revert() threw: " . $@ . " when trying to clear the latest bit from TMTestLogs.\n");
			};

 		}
 	}


program:
# Return a non-empty string explaining why the action cannot commit
    # with its current values. If it is valid, return an empty string.
    # Example:
    #    my $value_info = $entity->GetFieldValue("some field");
    #    if (length($value_info->GetValue()) < 10) {
    #        $result = "Must be at least 10 chars long";
    #    }
	$sessionObj = $entity->GetSession();
	my $recordType = $entity->GetEntityDefName();
	my $origIt = $entity->GetFieldOriginalValue("Iteration")->GetValue();
	my $iter = $entity->GetFieldValue("Iteration")->GetValue();
	# we only really need to change the latest if we were latest
	if ($origIt ne $iter)
	{
		my $filter = "ConfiguredTestCase";
		CQTM_SetLatestLogOrigIter($entity,$filter);
		CQTM_SetLatestLog($entity,$filter); 
	} # if iter has changed
	$result = "";


program:
# This hook is fired during the "commit" step of an entity update, so
    # it is the appropriate place to put activity which should be bundled
    # into the same transaction as the commit, such as subactions or an
    # update of external data storage.
if ($entity->GetFieldValue("Latest") eq "true")
{
	$sessionObj = $entity->GetSession();
	$queryDefObj = $sessionObj->BuildQuery("TMTestLog");
  	# set the fields we are intested in
 	$queryDefObj->BuildField("dbid");
	$queryDefObj->BuildField("StartTime");
	my $queryField = $queryDefObj->GetFieldByPosition(2);
	$queryField->SetSortOrder(1); 	
	$queryField->SetSortType($CQPerlExt::CQ_SORT_DESC);

 	# get the ctc and the iteration for the filter
 	my @ctc = $entity->GetFieldValue("ConfiguredTestCase")->GetValue();
 	my @it;	
	my $itOperator = $CQPerlExt::CQ_COMP_OP_IS_NULL;	
	my $itVal = $entity->GetFieldValue("Iteration")->GetValue();	
	if( ($itVal ne NULL) && ($itVal ne "" ) ) {		
		@it = $entity->GetFieldValue("Iteration")->GetValue();		
		$itOperator = $CQPerlExt::CQ_COMP_OP_EQ;	
	} 	
 	@latest = "true";  # we are looking for things not equal this
 	# build the filter
 	$operator = $queryDefObj->BuildFilterOperator($CQPerlExt::CQ_BOOL_OP_AND);
  	$operator->BuildFilter("Iteration", $itOperator, \@it );
 	$operator->BuildFilter("ConfiguredTestCase", $CQPerlExt::CQ_COMP_OP_EQ, \@ctc );
 	$operator->BuildFilter("Latest", $CQPerlExt::CQ_COMP_OP_NEQ,\@latest );
  	# execute the query
 	$resultSetObj = $sessionObj->BuildResultSet($queryDefObj);
 	$resultSetObj->Execute();

 	# Set the first object to the latest, since we're sorted by date already.
 	if($resultSetObj->MoveNext == $CQPerlExt::CQ_SUCCESS) {  		# get the ids of the records
 		$dbid = $resultSetObj->GetColumnValue(1);
 		$newDbid = $entity->GetDbId();
  		if( $newDbid ne $dbid ){
  			# get the entity of the current value in the record set
 			$OldEntity = $session->GetEntity("TMTestLog", $dbid);
  			# set the new value
			eval {
 			$OldEntity->EditEntity("modify");
 			$OldEntity->SetFieldValue("Latest", "true");
  			# validate changes
 			$status = $OldEntity->Validate();
  			# commit changes
 			if ($status eq "") {
 				$OldEntity->Commit();
 			} else {
 				$OldEntity->Revert();
 			}
			};
			if ($@) {
			    $session->OutputDebugString("Modify()/Commit()/Revert() threw: " . $@ . " when trying to set the latest bit from TMTestLogs.\n");
			};

 		}
 	}
} # if we're true


program:
# TODO -- put your perl script code here
sub CQTM_SetLatestLog
{
	# we get the filter type as the second param, "Suite" suite logs, and "ConfiguredTestCase" for test logs
	# though it could be anything. We get the record type based on the entity's record type name

	# sets the latest flag on the new (current) iteration 
	my ($entity,$filter) = @_;
	my $recordType = $entity->GetEntityDefName();
	$sessionObj = $entity->GetSession();
	my $queryDefObj = $sessionObj->BuildQuery($entity->GetEntityDefName());
  	# set the fields we are intested in
 	$queryDefObj->BuildField("dbid");
	$queryDefObj->BuildField("StartTime");
	my $queryField = $queryDefObj->GetFieldByPosition(2);
	$queryField->SetSortOrder(1); 	
	$queryField->SetSortType($CQPerlExt::CQ_SORT_DESC);

	my @latest = "true";
	my @ctc = $entity->GetFieldValue($filter)->GetValue();
	my @it;	
	my $itOperator = $CQPerlExt::CQ_COMP_OP_IS_NULL;	
	my $itVal = $entity->GetFieldValue("Iteration")->GetValue();	
	if( ($itVal ne NULL) && ($itVal ne "" ) ) 
	{		
		@it = $entity->GetFieldValue("Iteration")->GetValue();		
		$itOperator = $CQPerlExt::CQ_COMP_OP_EQ;	
	} 
 	# build the filter
	# We don't worry about finding ourselves in the query because we haven't been saved yet
 	$operator = $queryDefObj->BuildFilterOperator($CQPerlExt::CQ_BOOL_OP_AND);
  	$operator->BuildFilter("Iteration", $itOperator, \@it );
 	$operator->BuildFilter($filter, $CQPerlExt::CQ_COMP_OP_EQ, \@ctc );
 	$operator->BuildFilter("Latest", $CQPerlExt::CQ_COMP_OP_EQ,\@latest );
  	# execute the query
 	$resultSetObj = $sessionObj->BuildResultSet($queryDefObj);
 	$resultSetObj->Execute();
	my $amILatest = "true";
	my $myTime = $entity->GetFieldValue("StartTime")->GetValue();
 	while($resultSetObj->MoveNext == $CQPerlExt::CQ_SUCCESS) 
	{  	
		# get the ids of the records
	 	$dbid = $resultSetObj->GetColumnValue(1);
		$startTime = $resultSetObj->GetColumnValue(2);
	
  		if($myTime lt $startTime )
		{
			$amILatest = "false";
		}
		if ($amILatest eq "true")
		{
			# get the entity of the current value in the record set
			my $OldEntity = $sessionObj->GetEntity($recordType, $dbid);
			# set the new value
			eval 
			{
				$OldEntity->EditEntity("modify");
				$OldEntity->SetFieldValue("Latest", "false");
	 			# validate changes
				$status = $OldEntity->Validate();
	 			# commit changes
				if ($status eq "") {
					$OldEntity->Commit();
	
				} else {
					$OldEntity->Revert();
				}
			};
			if ($@) {
			    $session->OutputDebugString("Modify()/Commit()/Revert() threw: " . $@ . " when trying to set the latest bit from " . $recordType . ".\n");
			};
		} # if I'm latest

	}  # while resultset	
	$entity->SetFieldValue("Latest", $amILatest);
}


program:
# TODO -- put your perl script code here
sub CQTM_SetLatestLogOrigIter
{
	# we get the filter type as the second param, "Suite" suite logs, and "ConfiguredTestCase" for test logs
	# though it could be anything. We get the record type based on the entity's record type name
	# set the original iter's lastest

	my ($entity,$filter) = @_;
	my $recordType = $entity->GetEntityDefName();
	if ($entity->GetFieldValue("Latest")->GetValue() eq "true")
	{
		my $queryDefObj = $sessionObj->BuildQuery($recordType);
	  	# We want to see dbid and StartTime, sorted by the latest StartTime first
	 	$queryDefObj->BuildField("dbid");
		$queryDefObj->BuildField("StartTime");
		my $queryField = $queryDefObj->GetFieldByPosition(2);
		$queryField->SetSortOrder(1); 	
		$queryField->SetSortType($CQPerlExt::CQ_SORT_DESC);

	 	# get the ctc and the iteration for the filter, we're using the original iteration
	 	my @ctc = $entity->GetFieldValue($filter)->GetValue();
		my @it = $entity->GetFieldOriginalValue("Iteration")->GetValue();
		my $origIt = $entity->GetFieldOriginalValue("Iteration")->GetValue();
		my $itOperator = $CQPerlExt::CQ_COMP_OP_IS_NULL;

		if( ($origIt ne NULL) && ($origIt ne "" ) ) 
		{		
			$itOperator = $CQPerlExt::CQ_COMP_OP_EQ;	
		} 

	 	# We want things in the same CTC (or suite) and Iteration
		my $operator = $queryDefObj->BuildFilterOperator($CQPerlExt::CQ_BOOL_OP_AND);
	  	$operator->BuildFilter("Iteration", $itOperator, \@it );
	 	$operator->BuildFilter($filter, $CQPerlExt::CQ_COMP_OP_EQ, \@ctc );
	  	# execute the query
	 	my $resultSetObj = $sessionObj->BuildResultSet($queryDefObj);
	 	$resultSetObj->Execute();
		# we only need to touch the first record, since that's the latest because of our sort
	 	if($resultSetObj->MoveNext == $CQPerlExt::CQ_SUCCESS) 
		{  	
  			# get the entity of the current value in the record set
	 		my $dbid = $resultSetObj->GetColumnValue(1);
 			my $OldEntity = $sessionObj->GetEntity($recordType, $dbid);
			if ($dbid ne $entity->GetDbId() )
			{
	  			# Set the latest flag
				eval 
				{
		 			$OldEntity->EditEntity("modify");
		 			$OldEntity->SetFieldValue("Latest", "true");
		  			# validate changes
		 			$status = $OldEntity->Validate();
		  			# commit changes
		 			if ($status eq "") 
					{
		 				$OldEntity->Commit();
		 			} 
					else 
					{
		 				$OldEntity->Revert();
		 			}
				}; # eval
				if ($@) 
				{
				    $session->OutputDebugString("Modify()/Commit()/Revert() threw: " . $@ . " when trying to set the latest bit on original iteration from".$recordType.".\n");
				};
			} # if the result is not us
			else
			{		
				# only need first record, unless we got ourselves
				if($resultSetObj->MoveNext == $CQPerlExt::CQ_SUCCESS )
				{
		  			# Set the latest flag
					eval 
					{
						$dbid = $resultSetObj->GetColumnValue(1);
 						$OldEntity = $sessionObj->GetEntity($recordType, $dbid);
			 			$OldEntity->EditEntity("modify");
			 			$OldEntity->SetFieldValue("Latest", "true");
			  			# validate changes
			 			$status = $OldEntity->Validate();
			  			# commit changes
			 			if ($status eq "") 
						{
			 				$OldEntity->Commit();
			 			} 
						else 
						{
			 				$OldEntity->Revert();
			 			}
					}; # eval
					if ($@) 
					{
					    $session->OutputDebugString("Modify()/Commit()/Revert() threw: " . $@ . " when trying to set the latest bit on original iteration from ". $recordType. ".\n");
					};
				}; # inner if we got a result
			} # else we are ourselves, get another
 		}; # if we got a result
	}; # if we were latest


}


program:
sub getReferredDbId {
	($session, $fieldTypeName, $fieldValue) = @_;
    return $session->GetEntity($fieldTypeName, $fieldValue)->GetDbId() . "";
}

sub getReferredDbIds {
	($session, $fieldTypeName, $fieldValueList) = @_;
    
     $returnValue = "";
     foreach $fieldValue (@$fieldValueList) {
         $returnValue = $returnValue . 
		                getReferredDbId($session, $fieldTypeName, $fieldValue) .
						" ";
         
     }
	 $returnValue =~ s/\s+$//;   # eliminate the trailing space(s)
     return $returnValue;
}

sub addAttachmentsRecords {
    my ($attachfields) = @_;
	my ($changeRecord, $attachfield, $theAttachments, $anAttachment, 
	     $i, $j, $fieldValue, $xml);
	$field_value = "";
	# Work with the first attachment field 
	for ($i=0;$i<$attachfields->Count();$i++) {
		$attachfield = $attachfields->Item($i);
		$theAttachments = $attachfield->GetAttachments(); 
		if ($theAttachments->Count() > 0) {
			$field_value .= "<field name=\"Attachments\"";
			$field_value .= " type=\"" . $CQPerlExt::CQ_ATTACHMENT_LIST . "\" >";
			# For this attachment field, get the collection of all 
			# its attachments
			$field_value .= "Attachment";
			for ($j=0;$j<$theAttachments->Count();$j++) {
				$anAttachment = $theAttachments->Item($j);
				$field_value .= " \"" . $anAttachment->GetFileName() . "\"";
        	}
			$field_value .= "</field>"
         }
     }
	 return $field_value;
}

sub addSyncedRecord {
	my ($entityDbId, $entityRecordTypeName, $projectArea, $session) = @_;
	if (!lookupSyncTable($entityDbId, $entityRecordTypeName, $projectArea, $session)) {
		my ($syncRecord);
		$syncRecord = $session->BuildEntity("JazzConnectorSyncHistory");
		$syncRecord->SetFieldValue("recordDbid", $entityDbId);
		$syncRecord->SetFieldValue("entityRecordType", $entityRecordTypeName);
		$syncRecord->SetFieldValue("jazz_ProjectArea_id", $projectArea);
		$syncRecord->Validate();
#		$invalidFields = $syncRecord->GetInvalidFieldValues();
#		for ($i=0;$i<$invalidFields->Count();$i++) {
#			$field = $invalidFields->Item($i); 
#			$session->OutputDebugString($field->GetName() . " = " . $field->GetValue() . "\n");
#		}
		$syncRecord->Commit();
    }
}

%ignoreFields = ("history", true);

sub WriteChangeHistoryRecord {
	my ($fullStateIncluded, $projectArea) = @_;
	my ($session, 
	    $versionNumber, 
		$entityDbId, 
		$recordTypeName,
		$changedFields, 
		$i, 
		$changedField, 
		$changeRecord,
		$fieldType,
		$fieldTypeName,
		$fieldName,
		$displayName,
		$xml,
		$xmlForField);
	
	$session = $entity->GetSession();
	$versionNumber = $entity->GetFieldValue("version")->GetValue();
	$entityDbId = $entity->GetDbId() . "";
	$displayName = $entity->GetDisplayName();
	$recordTypeName = $entity->GetEntityDefName();
	$recordType = $session->GetEntityDef($recordTypeName);
#   if it never was synced before, send all
#   fields, even if it isn't a create.
	if ($fullStateIncluded == 0) {
		$changedFields = $entity->GetFieldsUpdatedThisAction();
    } else {
    	$changedFields = $entity->GetAllFieldValues();
    }
	$xml = "<fields>";
	$changeRecord = $session->BuildEntity("JazzConnectorChangeEvents");
	$changeRecord->SetFieldValue("ratl_mastership", determineConnectorMastership());
	$changeRecord->SetFieldValue("entity_dbid", $entityDbId);
	$changeRecord->SetFieldValue("version_number", $versionNumber);
	$changeRecord->SetFieldValue("entity_record_type", $recordTypeName);
	$changeRecord->SetFieldValue("entity_display_name", $displayName);
	$changeRecord->SetFieldValue("modifiedBy", $session->GetUserLoginName());
	$changeRecord->SetFieldValue("full_state_included", $fullStateIncluded . "");
	$changeRecord->SetFieldValue("jazz_ProjectArea_id", $projectArea);
	for ($i=0;$i<$changedFields->Count();$i++)
	{
	  $xmlForField = "";
	  $changedField = $changedFields->Item($i);
	  $fieldType = $changedField->GetType();
	  $fieldName = $changedField->GetName();
	  $fieldValue = "";
	  if (!$ignoreFields{$fieldName}) { 
	  	$xmlForField .= "<field name=\"" . $fieldName . "\"";
		$xmlForField .= " type=\"" . $fieldType . "\" >";
	  	if ($fieldType eq $CQPerlExt::CQ_REFERENCE) {
		    $fieldValue = $changedField->GetValue();
			if ($fieldValue ne "") {
		    	$fieldTypeName = $recordType->GetFieldReferenceEntityDef($fieldName)->GetName();
				$fieldValue = $fieldTypeName . " " . getReferredDbId($session, 
		                              	  					         $fieldTypeName,
									  	  					         $changedField->GetValue());
			}
	  	}
	  	elsif ($fieldType eq $CQPerlExt::CQ_REFERENCE_LIST) {
			$fieldTypeName = $recordType->GetFieldReferenceEntityDef($fieldName)->GetName();
			$fieldValue = getReferredDbIds($session, 
		                              	   $fieldTypeName,
									  	   $changedField->GetValueAsList());
			if ($fieldValue ne "") {
				$fieldValue = $fieldTypeName . " " . $fieldValue;
			}
		}
		elsif ($fieldType eq $CQPerlExt::CQ_ATTACHMENT_LIST) {
#			shouldn't be in this list....
			next;		    
		}
		elsif ($fieldType eq $CQPerlExt::CQ_MULTILINE_STRING ||
		       $fieldType eq $CQPerlExt::CQ_SHORT_STRING) {
$fieldValue = " " . $changedField->GetValue() . " ";
        }
		else {
	  		$fieldValue = $changedField->GetValue();
      	}
		$xmlForField .= $fieldValue . "</field>";
		$xml .= $xmlForField;
      }
    }
	
	if ($entity->IsDuplicate()) {
		$fieldValue = $recordTypeName . " ";
		$fieldValue = $fieldValue . $entity->GetOriginal()->GetDbId();
    } else {
		$fieldValue = "";
    }
	$xml .= "<field name=\"original\" type=\"" . $CQPerlExt::CQ_REFERENCE . "\" >" .
	                       $fieldValue . "</field>";
	$xml .= addAttachmentsRecords($entity->GetAttachmentFields());
    $xml .= "</fields>";
#    $session->OutputDebugString("$xml\n");
	$changeRecord->SetFieldValue("field_values", $xml);
	$changeRecord->Validate();
#	$invalidFields = $changeRecord->GetInvalidFieldValues();
#	for ($i=0;$i<$invalidFields->Count();$i++) {
#		$field = $invalidFields->Item($i); 
#		$session->OutputDebugString($field->GetName() . " = " . $field->GetValue() . "\n");
#	}
	$changeRecord->Commit();
	addSyncedRecord($entityDbId, $recordTypeName, $projectArea, $session);
}

sub Change_History_Delete {
	my ($projectArea) = @_;
	my ($changeRecord);
	$changeRecord = $session->BuildEntity("JazzConnectorChangeEvents");
	$changeRecord->SetFieldValue("entity_dbid", $entity->GetDbId() . "");
	$changeRecord->SetFieldValue("version_number", "-1");
	$changeRecord->SetFieldValue("entity_record_type", $entity->GetEntityDefName());
	$changeRecord->SetFieldValue("modifiedBy", $session->GetUserLoginName());
	$changeRecord->SetFieldValue("ratl_membership", determineConnectorMastership());
	$changeRecord->SetFieldValue("full_state_included", "0");
	$changeRecord->SetFieldValue("jazz_ProjectArea_id", $projectArea);
	$changeRecord->Validate();
	$changeRecord->Commit();
#   the sync record is deleted by the gateway after the proxy is deleted.
}

#sub findQueryName {
#	my ($session, $entity) = @_;
#	my ($resultSetObj,
#		$filterNode,
#		$query,
#		$recordTypeName,
#		$queryKeyString,
#		@queryKey);
#	$recordTypeName = $entity->GetEntityDefName();
#	$queryKeyString = "cq.query." . $recordTypeName;
#	@queryKey = ($queryKeyString );
#	if ($session->HasValue($queryKeyString)) {
#		return $session->GetNameValue($queryKeyString);
#	}
#	$query = $session->BuildQuery("JazzConnectorProperties");
#	$query->BuildField("value");
#	$filterNode = $query->BuildFilterOperator($CQPerlExt::CQ_BOOL_OP_AND);
#	$filterNode->BuildFilter("name", $CQPerlExt::CQ_COMP_OP_EQ, \@queryKey);
#	$resultSetObj = $session->BuildResultSet($query);
#	$resultSetObj->EnableRecordCount();
#	$resultSetObj->Execute();
#	if ($resultSetObj->GetRecordCount() == 0) {
#		return undef;
#   } else {
#		$resultSetObj->MoveNext();
#		$queryName = $resultSetObj->GetColumnValue(1);
#		if ($queryName ne "") {
#			$session->SetNameValue($queryKeyString, $queryName);
#        }
#		return $queryName;
#    }
#}

sub determineConnectorMastership {
	my ($session,
		$mastership,
		$record);
	$session = $entity->GetSession();
	$mastership = $session->GetNameValue("ConnectorMastership");
	if ($mastership eq "") {
		$query = $session->BuildQuery("JazzConnectorQueryInfo");
		$query->BuildField("ratl_mastership");
		$resultSetObj = $session->BuildResultSet($query);
		$resultSetObj->Execute();
		if ($resultSetObj->MoveNext() == $CQPerlExt::CQ_NO_DATA_FOUND) {
#           This means there are no queries, even the "ALL" query
			return;
		}
		$mastership = $resultSetObj->GetColumnValue(1);
		$session->SetNameValue("ConnectorMastership", $mastership);
	}
	return $mastership;

}

sub querySyncTable {
	my ($entityDbid,
		$recordTypeName,
		$session) = @_;
    my ($query,
	    $filterNode,
		$resultSetObj,
		@dbid,
		@recordType,
		%projectAreaIds);
	@dbid = ( $entityDbid );	
	@recordType = ( $recordTypeName );
	$query = $session->BuildQuery("JazzConnectorSyncHistory");
	$query->BuildField("jazz_ProjectArea_id");
	$filterNode = $query->BuildFilterOperator($CQPerlExt::CQ_BOOL_OP_AND);
	$filterNode->BuildFilter("recordDbid", $CQPerlExt::CQ_COMP_OP_EQ, \@dbid);
	$filterNode->BuildFilter("entityRecordType", $CQPerlExt::CQ_COMP_OP_EQ, \@recordType);
	$resultSetObj = $session->BuildResultSet($query);
	$resultSetObj->Execute();
	while ($resultSetObj->MoveNext() != $CQPerlExt::CQ_NO_DATA_FOUND) {
		$projectAreaIds{$resultSetObj->GetColumnValue(1)} = 1;
	}
	return %projectAreaIds;
}

sub lookupSyncTable {
	my ($entityDbid,
		$recordTypeName,
		$projectArea,
		$session) = @_;
    my ($query,
	    $filterNode,
		$resultSetObj,
		@dbid,
		@recordType,
		@projectAreaId);
	@dbid = ( $entityDbid );	
	@recordType = ( $recordTypeName );
	@projectAreaId = ( $projectArea );
	$query = $session->BuildQuery("JazzConnectorSyncHistory");
	$query->BuildField("jazz_ProjectArea_id");
	$filterNode = $query->BuildFilterOperator($CQPerlExt::CQ_BOOL_OP_AND);
	$filterNode->BuildFilter("recordDbid", $CQPerlExt::CQ_COMP_OP_EQ, \@dbid);
	$filterNode->BuildFilter("entityRecordType", $CQPerlExt::CQ_COMP_OP_EQ, \@recordType);
	$filterNode->BuildFilter("jazz_ProjectArea_id", $CQPerlExt::CQ_COMP_OP_EQ, \@projectAreaId);
	$resultSetObj = $session->BuildResultSet($query);
	$resultSetObj->Execute();
	if($resultSetObj->MoveNext() == $CQPerlExt::CQ_SUCCESS) {
		return 1;
	}
	return return 0;
}

sub queryQueryInfoTable {
	my ($recordTypeName,
		$session) = @_;
    my ($query,
	    $filterNode,
		$resultSetObj,
		@dbid,
		@recordType,
		%projectAreaQueryMap);
	@dbid = ( $entityDbid );	
	@recordType = ( $recordTypeName );
	$query = $session->BuildQuery("JazzConnectorQueryInfo");
	$query->BuildField("query_dbid");
	$query->BuildField("jazz_ProjectArea_id");
	$filterNode = $query->BuildFilterOperator($CQPerlExt::CQ_BOOL_OP_AND);
	$filterNode->BuildFilter("entityRecordType", $CQPerlExt::CQ_COMP_OP_EQ, \@recordType);
	$resultSetObj = $session->BuildResultSet($query);
	$resultSetObj->Execute();
	while ($resultSetObj->MoveNext() != $CQPerlExt::CQ_NO_DATA_FOUND) {
		$projectAreaQueryMap{$resultSetObj->GetColumnValue(1)} = $resultSetObj->GetColumnValue(2);
	}
	return %projectAreaQueryMap;
}

sub RunInteropFilter {
	my($actiontype) = @_;
	my ($interopFilterQueryName,
		$resultSetObj,
		$filterQuery,
		$session,
		$topNode,
		$recordCount,
		$currentWorkspace,
		@entityDbId,
		%previousProjectAreaIds,
		%currentProjectAreaIds,
		%projectAreaQueryMap,
		%projectAreaFullStateMap,
		$currentQueryMatches,
		$unspecifiedProjectAreaFound);
	$currentQueryMatches = 0;	
	$session = $entity->GetSession();
	$currentWorkspace = $session->GetWorkSpace();
	$recordTypeName = $entity->GetEntityDefName();
	%previousProjectAreaIds = querySyncTable($entity->GetDbId() . "", $recordTypeName, $session);
	if ($actiontype eq $CQPerlExt::CQ_DELETE) {
		foreach my $projectArea (keys %previousProjectAreaIds) {
			Change_History_Delete($projectArea); 
		}
	} else {
#       run all queries for the record type
		%projectAreaQueryMap = queryQueryInfoTable($recordTypeName, $session);
		$unspecifiedProjectAreaFound = 0;
    	foreach my $query_dbid (keys %projectAreaQueryMap) {
    		# how to handle the no query??
    		my $queryPassed = 0;
    		if ($query_dbid eq "") {
    			$queryPassed = 1;
    		} else {
				my $filterQuery = $currentWorkspace->GetQueryDefByDbId($query_dbid);
				$topNode = $filterQuery->CreateTopNode($CQPerlExt::CQ_BOOL_OP_AND);
				@entityDbId = ($entity->GetDbId() . "");
				$topNode->BuildFilter("dbid", $CQPerlExt::CQ_COMP_OP_EQ, \@entityDbId);
				$resultSetObj = $session->BuildResultSet($filterQuery);
				$resultSetObj->EnableRecordCount();
				$resultSetObj->Execute();
				$recordCount = $resultSetObj->GetRecordCount();
				$queryPassed = ($recordCount == 1);
			}
			if ($queryPassed == 1) {
				$currentProjectAreaIds{$projectAreaQueryMap{$query_dbid}} = 1;
				$currentQueryMatches++;
			}
		}
#       Determine whether or not to sync this record to each project area with
#       a matching query, "moving" a record if it no longer syncs with 
#       a project area it has previously.
		foreach my $projectAreaId (values %projectAreaQueryMap) {
			if ($previousProjectAreaIds{$projectAreaId} == 1 &&
			    $currentProjectAreaIds{$projectAreaId} == 1) {
#               the record was synced with the project area before, so
#               just do an update
				WriteChangeHistoryRecord(0, $projectAreaId);
			} 
			elsif ($previousProjectAreaIds{$projectAreaId} != 1 &&
			    	 $currentProjectAreaIds{$projectAreaId} == 1) {
#				the record is being created for the first time
			    WriteChangeHistoryRecord(1, $projectAreaId);
			}
			elsif ($previousProjectAreaIds{$projectAreaId} == 1 &&
			    	 $currentProjectAreaIds{$projectAreaId} != 1) {
#                  this case when it it moved, it is no longer in this project area
				if ($currentQueryMatches > 0) {
#                  but it is in some other one
					Change_History_Delete($projectAreaId);
				} else {
#                 didn't match any query - keep syncing to the last project area.
				    WriteChangeHistoryRecord(1, $projectAreaId);
				}
			}
		}
#		Note that the algorithm does not disconnect records from any Jazz items 
#       when the number of queries selected a record goes to zero. We feel that 
#       would be too aggressive; we don't want a mistake in a query to cause 
#       massive disconnection of all connected records, especially since there 
#       is no way to reconnect to a work item.
	}
}

sub JazzCQConnector {
    my($actionname, $actiontype) = @_;
    # $actionname as string scalar
    # $actiontype as long scalar
	RunInteropFilter($actiontype);
}


# m_statedeftype

description:
Identifies all states that are not associated to the Resolved state type.


description:
Identifies all states considered to be resolved.


# master_packages

description:
Fix for RATLC00506628 and RATLC00453464 and RATLC00751502


description:
This package contains the field and form tab for resolving a defect.


description:
This package contains the field and form tab for attachments.


description:
This package contains the History control to be added to the record form.


description:
This package contains the Project record type.


description:
Enlarge submit form of record type Customer


description:
Setup package for the DefectTracking schema


description:
This package contains the EnhancementRequest record type


description:
Removed following fields from PQC tab: Test Tool, Test Command, Stack ID, & Stack


description:
Setup package for DevelopmentStudio schema


description:
UCM policy scripts - required by UnifiedChangeManagement package


description:
Convenient activity record type to be used with ClearCase UCM


description:
The base schedule package for AM work activities.  This package is necessary for both AM and the CQ-MSP integration


description:
ClearCase Unified Change Management package


description:
Setup package for the UnifiedChangeManagement schema


# master_schemarevs

description:
Schema for ClearQuest Enabled UCM Projects in a Rational Team Concert Connectors Environment.


description:
Enabled schema for '1.06' version of package 'JazzInterop'


# master_schemas

description:
Schema for ClearQuest Enabled UCM Projects in a Rational Team Concert Connectors Environment.


