# 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:
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.


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:
The person responsible for carrying out the activity.


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.


# actiondef

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


# scriptdef

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:
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
   groups_AccessControl = FALSE


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


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 ***

    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:
'  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:
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:
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:
# 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:
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:
on error resume next
  	RSEM_FieldsChoices choices


program:
on error resume next
	RSEM_FieldsChoices 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 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 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:
'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:
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:
on error resume next
	RSEM_ActionsChoices choices


program:
on error resume next
	RSEM_ActionTypesChoices choices


program:
on error resume next
	RSEM_StatesChoices choices


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:
# 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:
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:
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:
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_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:
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:
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_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:
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:
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:
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:
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:
' 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:
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:
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_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:
'---
  ' 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:
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:
' 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:
' 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

   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:
# 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:
# 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:
' ***** 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:
' ***** 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:
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);
}


# statedeftype

description:
Identifies all states considered to be resolved.


description:
Identifies all states that are not associated to the Resolved state type.


# property

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_AMStateTypes_1


name:
Applied Package Form Tab Names_UnifiedChangeManagement_9

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


name:
Applied Package Form Tab Names_JazzInterop_7


# 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


