<a id="agent-knowledge"></a>
<a id="id1"></a>
# Agent Knowledge

These are the Medidata Rave and Veeva Vault EDC facts TrialGrid gives its agents, exactly as the agents are sent them. They are maintained by TrialGrid Ltd and change only with a release.

Each agent's **Agent Knowledge** page, under the URL's **Agent Knowledge** link, lists the entries that agent is given beside your organization's conventions for it: the object instructions on the Object Definitions it works from. An agent follows a convention over its own defaults, but never over one of these facts. The **Knowledge used** panel under an agent result links to the entries that result was given.

<a id="clinical-query-language"></a>
## Clinical Query Language

<a id="field-references"></a>
<a id="knowledge-rave-cql-field-references"></a>
### Field references

`rave.cql.field-references` · Medidata Rave · Used by: Bulk Edit Check Creator, Edit Check Agent, Test Case Agent

- Field references: `*.FORM.FIELD` (any folder), `FOLDER.FORM.FIELD` (specific folder)

<a id="standard-coded-and-user-values"></a>
<a id="knowledge-rave-cql-data-formats"></a>
### Standard, coded and user values

`rave.cql.data-formats` · Medidata Rave · Used by: Bulk Edit Check Creator, Edit Check Agent, Test Case Agent

- Data formats: a bare `*.FORM.FIELD` compares the field's STANDARD value. `.CodedValue` compares a field with a DataDictionaryName by its coded value; a coded field's standard value is not its dictionary label. `.UserValue` compares the text exactly as the user entered it. That is the only way to reach an unknown-date sentinel, which lives in the entered text and not in the standard value.
- Value types: a text value is quoted, a numeric value is not

<a id="literals-and-partial-dates"></a>
<a id="knowledge-rave-cql-literals"></a>
### Literals and partial dates

`rave.cql.literals` · Medidata Rave · Used by: Bulk Edit Check Creator, Edit Check Agent, Test Case Agent

- Literals: Strings `'value'`, Numbers `5`, Dates `d'13 MAR 1967'`, partial dates `d'UN MAY 2024'` A date literal's positions are `d'DAY MON YEAR'`. Partial-date sentinels are POSITION-SPECIFIC: `UN` for day, `UNK` for month, `UNKN` for year. `UNK` is never valid in the year position. Only fields whose format includes the unknown marker (e.g. `dd-MMM-yyyy-`) accept partial-date literals; a `dd-MMM-yyyy` field does not.

<a id="testing-for-an-unknown-date-sentinel"></a>
<a id="knowledge-rave-cql-sentinel-tests"></a>
### Testing for an unknown-date sentinel

`rave.cql.sentinel-tests` · Medidata Rave · Used by: Bulk Edit Check Creator, Edit Check Agent, Specification Review, Test Case Agent

TESTING FOR A SENTINEL: an unknown date component is not a gap in the date. The study stores a SENTINEL in that position, and the sentinel is part of the entered text. That is true of Rave's own `UN` / `UNK` / `UNKN` and equally of a study's own convention such as a year of 0000: a date whose year is unknown literally contains '0000'. `FIELD.UserValue Contains 'X'` finds a sentinel in the entered text, but `Contains` is a plain SUBSTRING test and the sentinels NEST — `UN` is inside `UNK` is inside `UNKN`. So `Contains 'UN'` also fires on an unknown month or year, and `Contains 'UNK'` also fires on an unknown year. Only the longest sentinel a study uses can be tested this way safely. Studies differ in the sentinels they use.

<a id="operators-and-functions"></a>
<a id="knowledge-rave-cql-operators"></a>
### Operators and functions

`rave.cql.operators` · Medidata Rave · Used by: Bulk Edit Check Creator, Edit Check Agent, Specification Review, Test Case Agent

- Comparisons: `==`, `!=`, `>`, `>=`, `<`, `<=`
- Logical: `AND`, `OR`, `NOT`
- Arithmetic: `+`, `-`, `*`, `/`; `&` joins two text values
- String ops: `Contains`, `StartsWith`
- Functions: `age(ref1, ref2)`, `dayspan(ref1, ref2)`, `timespan(ref1, ref2)`, `length(ref)` `age` is the age in years between two dates, `dayspan` the number of days between two dates, and `timespan` the number of MINUTES between two date-times, which is how a time window such as "within 5 hours +/- 15 minutes" is checked.
- Date arithmetic: `ref AddDay N`, `ref AddMonth N`, `ref AddYear N`, `ref AddHour N`, `ref AddMin N`, `ref AddSec N`
- Aggregate: `all(ref1, ref2, ...).Method`, `any(ref1, ref2, ...) == value`
- Custom functions: `cf('function_name')` or `ref.cf('function_name')`

<a id="logical-record-position"></a>
<a id="knowledge-rave-cql-record-position"></a>
### Logical record position

`rave.cql.record-position` · Medidata Rave · Used by: Bulk Edit Check Creator, Edit Check Agent, Specification Review, Test Case Agent

- Logical record position: a field reference wrapped in a position function reads the value from one chosen record among a subject's records, for example to compare a value with its value on the previous record: `Max(*.FORM.FIELD in SCOPE)`, `Min(*.FORM.FIELD in SCOPE)` — the largest or smallest value `First(*.FORM.FIELD in SCOPE order by ORDER)`, and likewise `Last`, `Next` and `Previous` — the value on the first, last, next or previous record in that order SCOPE is `Form`, `Folder` or `Subject`; ORDER is `RecordDate` or `CRFLocation`. `Max` and `Min` take no order by; `First`, `Last`, `Next` and `Previous` require one. e.g. `*.VS.WEIGHT != Previous(*.VS.WEIGHT in Subject order by RecordDate)`

<a id="field-methods"></a>
<a id="knowledge-rave-cql-field-methods"></a>
### Field methods

`rave.cql.field-methods` · Medidata Rave · Used by: Bulk Edit Check Creator, Edit Check Agent, Specification Review, Test Case Agent

FIELD METHODS - these are the ONLY valid methods on a field reference:

- `.IsEmpty` - field has no value
- `.IsNotEmpty` - field has a value
- `.IsPresent` - field is present
- `.IsActive` - field is active
- `.IsNonConformant` - field is non-conformant
- `.InLocalLabRange` - value is in local lab range

NO OTHER METHODS EXIST: there is no .Day, .Month, .IsPartial, .Year, etc. There is no way to extract date components (day, month, year) from a date field in CQL.

<a id="no-form-status-test-in-cql"></a>
<a id="knowledge-rave-cql-form-status"></a>
### No form-status test in CQL

`rave.cql.form-status` · Medidata Rave · Used by: Bulk Edit Check Creator, Edit Check Agent, Specification Review, Test Case Agent

Field methods test a single DATA POINT, not FORM-level status: there is no way to test whether a form was submitted / entered / created in CQL. A field's `.IsPresent` / `.IsEmpty` cannot tell "the form is not submitted" from "the field is blank" (a field can be blank on a submitted form), so a form-status condition needs a custom function.

<a id="a-partial-date-literal-compares-the-whole-date"></a>
<a id="knowledge-rave-cql-partial-date-literal"></a>
### A partial-date literal compares the whole date

`rave.cql.partial-date-literal` · Medidata Rave · Used by: Bulk Edit Check Creator, Edit Check Agent, Specification Review, Test Case Agent

A partial-date literal (e.g. `*.FORM.DATE == d'UN MAY 2024'`) compares the ENTIRE date value against ONE fixed partial-date shape — it CANNOT test a single component on its own. A requirement like "the month is unknown but the day is entered", or comparing the month/day of two dates, is per-component logic a check cannot express — it needs a custom function.

<a id="empty-fields-in-comparisons"></a>
<a id="knowledge-rave-cql-empty-fields"></a>
### Empty fields in comparisons

`rave.cql.empty-fields` · Medidata Rave · Used by: Bulk Edit Check Creator, Edit Check Agent, Test Case Agent

An EMPTY field still takes part in a comparison: in a range or relational comparison (`<`, `>`, `<=`, `>=`) a blank field can read as below or above a bound, and an empty field is trivially `!= X`.

<a id="checkbox-fields-in-checks"></a>
<a id="knowledge-rave-cql-checkbox-fields"></a>
### Checkbox fields in checks

`rave.cql.checkbox-fields` · Medidata Rave · Used by: Bulk Edit Check Creator, Edit Check Agent, Test Case Agent

A checkbox always holds a value, so `.IsEmpty` / `.IsNotEmpty` exclude nothing on a checkbox field. A checkbox holds no other value than checked or unchecked — never 'Y', 'N', 'ON', 'OFF' or 'checked', whatever wording the specification uses.

<a id="when-a-custom-function-is-required"></a>
<a id="knowledge-rave-cql-custom-function-required"></a>
### When a Custom Function is required

`rave.cql.custom-function-required` · Medidata Rave · Used by: Bulk Edit Check Creator, Edit Check Agent, Specification Review, Test Case Agent

A custom function IS needed for: regex/pattern matching; extracting or comparing individual date components — e.g. 'the day is entered but the month is not', or comparing the month/day of two dates; testing whether a FORM (not a field) has been submitted / entered / created / is present, or its status (signed, frozen, locked); averaging/summing/counting across multiple records; complex iteration; external data lookups; extracting or replacing a substring; or conditional value computation. (Testing whether a value CONTAINS a substring is not in that list — `Contains` is a first-class CQL operator and needs no custom function.)

<a id="edit-check-actions"></a>
## Edit check actions

<a id="edit-check-action-options"></a>
<a id="knowledge-rave-ec-action-options"></a>
### Edit check action options

`rave.ec.action-options` · Medidata Rave · Used by: Bulk Edit Check Creator, Edit Check Agent, Test Case Agent

- action_options: Action-specific values:

  OpenQuery -> "MarkingGroup,RequiresResponse,RequiresManualClose"\
  AddForm -> the form OID to add\
  AddMatrix / MrgMatrix -> the matrix OID (e.g. "C9")\
  SetDataPointVisible -> "Visible" or "Hidden"\
  CustomFunction -> the custom function's name

<a id="a-check-s-actions-all-fire-together"></a>
<a id="knowledge-rave-ec-actions-fire-together"></a>
### A check's actions all fire together

`rave.ec.actions-fire-together` · Medidata Rave · Used by: Bulk Edit Check Creator, Edit Check Agent, Test Case Agent

A check's CONDITION is CQL and all of its actions fire when that condition is met. A check can carry ANY NUMBER of actions, and they may be of the same type: adding four forms is four AddForm actions on one check, each with ONE form OID in its action_options, and opening a query while adding a form is two actions on one check.

<a id="checks-that-call-a-custom-function"></a>
<a id="knowledge-rave-ec-custom-function-action"></a>
### Checks that call a Custom Function

`rave.ec.custom-function-action` · Medidata Rave · Used by: Bulk Edit Check Creator, Edit Check Agent, Test Case Agent

A CustomFunction action runs the named custom function, with the function's name in action_options and no action_string. The function performs its own query or other behavior when it runs, so the check that calls it needs no OpenQuery or other action of its own.

<a id="field-values-and-formats"></a>
## Field values and formats

<a id="checkbox-values"></a>
<a id="knowledge-rave-field-values-checkbox"></a>
### Checkbox values

`rave.field-values.checkbox` · Medidata Rave · Used by: Bulk Edit Check Creator, Custom Function Agent, Custom Function Reviewer, Edit Check Agent, Field Visibility Advisor, Test Case Agent

For CheckBox fields, use "1" for checked and "0" for unchecked (not "Yes"/"No")

<a id="what-a-field-s-dataformat-says"></a>
<a id="knowledge-rave-field-values-data-formats"></a>
### What a field's DataFormat says

`rave.field-values.data-formats` · Medidata Rave · Used by: Bulk Edit Check Creator, Edit Check Agent, Field Visibility Advisor, Test Case Agent

A field's DataFormat says what kind of value it holds: a format starting with $ is text (e.g. $200), a format like 10.5, 5.2 or 3 is numeric, and a format like dd MMM yyyy is a date.

<a id="custom-functions-either-api"></a>
## Custom Functions (either API)

<a id="date-handling-in-custom-functions"></a>
<a id="knowledge-rave-cf-date-handling"></a>
### Date handling in Custom Functions

`rave.cf.date-handling` · Medidata Rave · Used by: Custom Function Agent

Date handling:

- Parse with DateTime.TryParse(dp.Data, out DateTime dt) (inline out variable)
- Prefer nullable DateTime? over DateTime.MinValue sentinels for missing dates
- Check for null before comparing nullable dates

<a id="field-values-in-custom-functions"></a>
<a id="knowledge-rave-cf-field-values"></a>
### Field values in Custom Functions

`rave.cf.field-values` · Medidata Rave · Used by: Custom Function Agent, Custom Function Reviewer

Field values:

- DataPoint.Data is always a string
- Use exact equality (==) for field value comparisons, NOT .Contains() .Contains() can cause false matches (e.g. "15-FATAL".Contains("5-FATAL") is true) Example: dp.Data == "5-FATAL" (correct), dp.Data.Contains("5-FATAL") (wrong)

<a id="custom-functions-v1-api"></a>
## Custom Functions (V1 API)

<a id="custom-function-return-semantics"></a>
<a id="knowledge-rave-cf-v1-return-semantics"></a>
### Custom Function return semantics

`rave.cf.v1.return-semantics` · Medidata Rave · Used by: Custom Function Agent

Return semantics:

- Custom functions ALWAYS return null
- Query actions are performed via CustomFunction.PerformQueryAction()
- Do NOT use "return true" or "return false" — these are not valid for Rave CFs

<a id="rave-object-model"></a>
<a id="knowledge-rave-cf-v1-object-model"></a>
### Rave object model

`rave.cf.v1.object-model` · Medidata Rave · Used by: Custom Function Agent

Object model:

- Subject → DataPages (one per form instance)
- DataPage → Records (index 0 = standard/non-log record; index 1+ = log/repeating records)
- Record → DataPoints (one per field)
- DataPoint.Data → the field value as string (null or empty = no data)

<a id="custom-function-core-apis"></a>
<a id="knowledge-rave-cf-v1-core-apis"></a>
### Custom Function core APIs

`rave.cf.v1.core-apis` · Medidata Rave · Used by: Custom Function Agent, Custom Function Reviewer

Key APIs:

SAME-FORM field access (fields on the same form as the trigger):

- dpInput.Record.DataPoints.FindByFieldOID(fieldOID) → DataPoint on same record
- dpInput.Record.DataPage → DataPage of the triggering field
- dpInput.Record.DataPage.Records → all records on the same form

CROSS-FORM field access (fields on a DIFFERENT form):

- CustomFunction.FetchAllDataPointsForOIDPath(fieldOID, formOID, folderOID, subject)

  - → returns DataPoints collection from another form
  - → for a log field it returns EVERY instance, one per log line, not only the first
  - → folderOID: use a string like "COMMON" if a folder applies, or null if not
  - → subject: dpInput.Record.Subject
  - → Example: CustomFunction.FetchAllDataPointsForOIDPath("DTHDAT", "DD", null, subj)
  - → Check result: if (dps != null && dps.Count > 0 && dps[0] != null && dps[0].Active)

CURRENT FOLDER / FORM (the folder/visit and form the triggering field is in):

- dpInput.Record.DataPage.Instance.Folder.OID → folder OID of the triggering field
- dpInput.Record.DataPage.Form.OID → form OID of the triggering field

  - → Use these to include/exclude the current visit/form, e.g. exclude certain folders:

    ```
    string currentFolder = dpInput.Record.DataPage.Instance.Folder.OID;
    if (currentFolder != "UNS" && currentFolder != "EOT") { ... }
    ```

OTHER:

- dpInput.Record.Subject → Subject (for cross-form lookups)
- Record.DataPoints.FindByFieldOID(fieldOID) → DataPoint or null
- Record.Active → true if record is active
- DataPoint.ChangeCount → number of times the field has been changed
- CustomFunction.PerformQueryAction(queryText, 1, false, false, dp, openQuery, afp.CheckID, afp.CheckHash) → open/close query on a DataPoint
- subject.CRFVersionID → CRF version ID (needed for Form.FetchByOID)

NON-EXISTENT APIs — do NOT use these (they will cause compilation errors):

- Subject.DataPages → DOES NOT EXIST
- Subject.FindDataPage() → DOES NOT EXIST
- subj.DataPages.FindByFormOID() → DOES NOT EXIST (use Instance.DataPages.FindByFormOID)
- Record[fieldOID] indexer → DOES NOT EXIST (use FindByFieldOID)
- Record.IsInactive → DOES NOT EXIST (use Record.Active)
- OpenQuery() → DOES NOT EXIST (use PerformQueryAction)
- dp.Data = "value" (direct assign) → DO NOT USE (use DataPoint.Enter() instead)
- Record.ChangeCount → DOES NOT EXIST (use DataPoint.ChangeCount instead)
- DataPage.FolderOID → DOES NOT EXIST (use DataPage.Instance.Folder.OID)
- Record.FolderOID → DOES NOT EXIST (use Record.DataPage.Instance.Folder.OID)
- DataPage.FormOID → DOES NOT EXIST (use DataPage.Form.OID)

<a id="derivation-apis"></a>
<a id="knowledge-rave-cf-v1-derivation-apis"></a>
### Derivation APIs

`rave.cf.v1.derivation-apis` · Medidata Rave · Used by: Custom Function Agent, Custom Function Reviewer

Writing data (derivation CFs):

- DataPoint.Enter(value, "", 0) → write a value to a field

  - → value: string value to enter (use null or "" to clear)
  - → Do NOT assign dp.Data directly — use Enter() to trigger audit trail and cascading
  - → Example: dpTarget.Enter(dpInput.Data, "", 0);
  - → Example (clear): dpTarget.Enter(null, "", 0);
- DataPoint.SetNonConformant(bool) → mark/clear non-conformant status

  - → true = value is non-conformant (not in valid list), false = clear
  - → Used for dynamic search list validation

<a id="add-form-apis"></a>
<a id="knowledge-rave-cf-v1-add-form-apis"></a>
### Add Form APIs

`rave.cf.v1.add-form-apis` · Medidata Rave · Used by: Custom Function Agent

Adding/removing forms in a visit (AddForm CFs):

- dpInput.Record.Instance → Instance of the triggering record's visit

- dpInput.Record.DataPage.Instance → same as above, via DataPage

- Instance.DataPages.FindByFormOID(formOID) → find DataPage by form OID (or null)

- Instance.SubjectMatrixID → ID needed for AddCRF

- Form.FetchByOID(formOID, subject.CRFVersionID) → fetch a Form definition

- instance.AddCRF(form, instance.SubjectMatrixID) → add a form to an existing folder instance

- DataPage.Active → get/set whether a form is active

- DataPage.IsBitSet(Status.IsTouched) → true if the form has been touched by a user

- DataPoint.ChangeCount → number of times a field has been changed

- Pattern for adding a form:

  ```
  Instance inst = dpInput.Record.DataPage.Instance;
  DataPage pg = inst.DataPages.FindByFormOID("FORMOID");
  if (pg == null)
  {
    Form frm = Form.FetchByOID("FORMOID", subj.CRFVersionID);
    if (frm != null) { inst.AddCRF(frm, inst.SubjectMatrixID); }
  }
  else { pg.Active = true; }
  ```

- Pattern for deactivating an untouched form:

  ```
  if (pg != null && !pg.IsBitSet(Status.IsTouched)) { pg.Active = false; }
  ```

<a id="folder-and-matrix-apis"></a>
<a id="knowledge-rave-cf-v1-folder-matrix-apis"></a>
### Folder and matrix APIs

`rave.cf.v1.folder-matrix-apis` · Medidata Rave · Used by: Custom Function Agent, Custom Function Reviewer

Folder/matrix management (creating/merging visit folders):

- subject.Instances → all folder instances for the subject

- subject.Instances.FindByFolderOID(folderOID) → find Instance by folder OID (or null)

- subject.Instances[i].Folder.OID → folder OID of instance i

- subject.Instances[i].InstanceRepeatNumber → repeat number of the instance

- subject.Instances[i].Active → true if instance is active

- dpInput.Record.Instance.InstanceRepeatNumber → repeat number of current instance

- Matrix.FetchByOID(matrixOID, subject.CRFVersionID) → fetch a Matrix definition

- subject.AddMatrix(matrix) → add a new folder instance for the subject

- subject.MergeMatrix(matrix) → merge a matrix (creates folder if not present)

- subject.UnMergeMatrix(matrix) → un-merge a matrix (removes the merged folder)

- Example: create a new folder:

  ```
  Matrix mtx = Matrix.FetchByOID("CM", subject.CRFVersionID);
  if (mtx != null) { subject.MergeMatrix(mtx); }
  ```

- Example: conditionally merge or un-merge a matrix:

  ```
  Matrix mtx = Matrix.FetchByOID("INJSR", subject.CRFVersionID);
  if (mtx != null)
  {
    if (toMerge) { subject.MergeMatrix(mtx); }
    else { subject.UnMergeMatrix(mtx); }
  }
  ```

<a id="log-forms-in-custom-functions"></a>
<a id="knowledge-rave-cf-v1-log-forms"></a>
### Log forms in Custom Functions

`rave.cf.v1.log-forms` · Medidata Rave · Used by: Custom Function Agent

Log vs non-log forms:

- Non-log form: one record per subject visit → use DataPage.MasterRecord or Records[0]
- Log form: multiple records per subject visit → iterate DataPage.Records
- When iterating log records, skip inactive: if (!r.Active) continue;
- Index 0 is the standard record; log lines start at index 1

IMPORTANT — log fields vs non-log fields on a log form:

- A log form contains BOTH log fields (repeating, one value per log line) and non-log/standard fields (single value, exists only on record 0).

- The triggering field (dpInput) is ALREADY resolved — use dpInput.Data directly. Do NOT re-fetch the triggering field from each log record.

- When comparing a non-log field against a log field across log lines, the correct pattern is: read the non-log field ONCE (from dpInput or record 0), then iterate log records to read only the log field from each record.

- Example: AEENDAT (non-log, trigger) vs AESTDAT (log field, per record):

  ```
  string endDateStr = dpInput.Data;  // non-log: read once from trigger
  foreach (Record r in dpInput.Record.DataPage.Records)
  {
    if (!r.Active) { continue; }
    DataPoint dpStart = r.DataPoints.FindByFieldOID("AESTDAT");  // log field
    // compare endDateStr against dpStart.Data
  }
  ```

<a id="null-checking-in-custom-functions"></a>
<a id="knowledge-rave-cf-v1-null-checking"></a>
### Null checking in Custom Functions

`rave.cf.v1.null-checking` · Medidata Rave · Used by: Custom Function Agent

Null-checking pattern:

```
Records rds = dpInput.Record.DataPage.Records;
foreach (Record r in rds)
{
  if (!r.Active) { continue; }
  DataPoint dp = r.DataPoints.FindByFieldOID(fieldOID);
  if (dp != null && !string.IsNullOrEmpty(dp.Data))
  {
    // use dp.Data
  }
}
```

<a id="custom-function-source-format"></a>
<a id="knowledge-rave-cf-v1-source-format"></a>
### Custom Function source format

`rave.cf.v1.source-format` · Medidata Rave · Used by: Custom Function Agent

Source code format:

- Rave custom function source is the FUNCTION BODY only
- NEVER wrap code in a method signature like "public bool Eval(object arg) { ... }"
- NEVER include line numbers in the output
- The code starts with the ActionFunctionParams boilerplate
- Use ONLY the APIs listed in this reference — do not invent properties or methods
- Record has Active (bool) — there is NO "IsInactive" property
- Use Record.DataPoints.FindByFieldOID(oid) — do NOT use Record[oid] indexer syntax
- Use exact equality (==) for field value comparisons, NEVER .Contains()
- C# 7+ features are supported and preferred when they produce cleaner code:

  - Local functions: define helper methods inside the function body instead of as separate methods after the main body
  - Nullable value types: use DateTime? instead of DateTime.MinValue sentinels
  - Inline out variables: DateTime.TryParse(str, out DateTime dt)
  - Pattern matching: if (obj is DateTime dt)
- MAXIMUM SOURCE LENGTH: 8000 characters (line breaks count as 2 chars). Rave validation will reject source code exceeding this limit. Keep code concise — use local functions, avoid verbose comments, and minimize redundant null checks to stay within the limit.

<a id="custom-function-boilerplate"></a>
<a id="knowledge-rave-cf-v1-boilerplate"></a>
### Custom Function boilerplate

`rave.cf.v1.boilerplate` · Medidata Rave · Used by: Custom Function Agent

Standard CF boilerplate — every custom function starts with:

```
ActionFunctionParams afp = (ActionFunctionParams) ThisObject;
DataPoint dpInput = afp.ActionDataPoint;
// ... function logic here ...
return null;
```

Do NOT wrap logic in try/catch unless the prompt explicitly requests error handling.

<a id="cross-form-pattern"></a>
<a id="knowledge-rave-cf-v1-cross-form-pattern"></a>
### Cross-form pattern

`rave.cf.v1.cross-form-pattern` · Medidata Rave · Used by: Custom Function Agent

Cross-form lookup pattern:

```
Subject subj = dpInput.Record.Subject;
DataPoints dps = CustomFunction.FetchAllDataPointsForOIDPath(
  "FIELDOID", "FORMOID", folderOID, subj);
if (dps != null && dps.Count > 0 && dps[0] != null
    && dps[0].Active && !string.IsNullOrEmpty(dps[0].Data))
{
  string value = dps[0].Data;
  // use value
}
NOTE: folderOID is a string like "COMMON" or null if no folder applies.
```

<a id="query-pattern"></a>
<a id="knowledge-rave-cf-v1-query-pattern"></a>
### Query pattern

`rave.cf.v1.query-pattern` · Medidata Rave · Used by: Custom Function Agent

Query action pattern — decide with a bool, then make ONE call on the path that evaluates the rule:

```
bool openQry = false;
// ... set openQry based on logic ...
CustomFunction.PerformQueryAction(queryText, 1, false, false, dpInput, openQry, afp.CheckID, afp.CheckHash);
Do NOT call it twice on the same path — once with true and then once with false — which leaves the outcome depending on call order. Compute the bool and pass it.
A guard clause that exits early is different and is expected: it calls PerformQueryAction with false and returns, so a query opened by an earlier evaluation is closed rather than left standing. See the custom code example.
The sixth argument is the only one that decides anything. false closes the query, true opens it.
```

<a id="custom-function-worked-example"></a>
<a id="knowledge-rave-cf-v1-worked-example"></a>
### Custom Function worked example

`rave.cf.v1.worked-example` · Medidata Rave · Used by: Custom Function Agent

COMPLETE CUSTOM CODE EXAMPLE — cross-form lookup with log-form iteration:

This example checks if a value selected on the current form matches any record on a log form. If DSAENO on the DS form contains a value, find the matching AE record by AESPID on the AE form and check that AEACN == "DRUG WITHDRAWN".

```
ActionFunctionParams afp = (ActionFunctionParams) ThisObject;
DataPoint dpInput = afp.ActionDataPoint;

// Get the triggering field value (same-form)
string dsaeno = dpInput.Data;
if (string.IsNullOrEmpty(dsaeno))
{
  CustomFunction.PerformQueryAction("query text", 1, false, false,
    dpInput, false, afp.CheckID, afp.CheckHash);
  return null;
}

// Cross-form lookup: get AESPID from the AE log form
Subject subj = dpInput.Record.Subject;
DataPoints dpsSpid = CustomFunction.FetchAllDataPointsForOIDPath(
  "AESPID", "AE", null, subj);

bool openQry = true;  // default: open query (no match found)

if (dpsSpid != null && dpsSpid.Count > 0)
{
  for (int i = 0; i < dpsSpid.Count; i++)
  {
    DataPoint dpSpid = dpsSpid[i];
    if (dpSpid == null || !dpSpid.Active) { continue; }
    if (string.IsNullOrEmpty(dpSpid.Data)) { continue; }

    if (dpSpid.Data == dsaeno)
    {
      // Found matching record — now check another field on SAME record
      DataPoint dpAcn = dpSpid.Record.DataPoints.FindByFieldOID("AEACN");
      if (dpAcn != null && dpAcn.Data == "DRUG WITHDRAWN")
      {
        openQry = false;  // match found, no query needed
      }
      break;
    }
  }
}

CustomFunction.PerformQueryAction("query text", 1, false, false,
  dpInput, openQry, afp.CheckID, afp.CheckHash);
return null;
```

KEY PATTERNS demonstrated:

- Cross-form field access: CustomFunction.FetchAllDataPointsForOIDPath()
- Iterate returned DataPoints by index (NOT foreach on Records)
- Access another field on the SAME record: dpSpid.Record.DataPoints.FindByFieldOID()
- Single PerformQueryAction call with bool variable
- Always return null

<a id="dynamic-search-lists"></a>
<a id="knowledge-rave-cf-v1-dynamic-search-lists"></a>
### Dynamic Search Lists

`rave.cf.v1.dynamic-search-lists` · Medidata Rave · Used by: Custom Function Agent

Dynamic Search List CFs:

- Use DynamicSearchParams instead of ActionFunctionParams:

  ```
  Medidata.Core.Objects.DynamicSearchParams DSP = (Medidata.Core.Objects.DynamicSearchParams)ThisObject;
  DataPoint dpAction = DSP.DataPoint;
  Subject subject = dpAction.Record.Subject;
  ```

- Return a KeyValueCollection (NOT null):

  ```
  Medidata.Utilities.KeyValueCollection KVC = new Medidata.Utilities.KeyValueCollection();
  Medidata.Utilities.KeyValue KV = new Medidata.Utilities.KeyValue(display, value);
  KVC.Add(KV);
  return KVC;
  ```

- Collect values into ArrayList, sort, then build KVC

- Skip standard record (RecordPosition == 0) and inactive records

- DataPoint.ChangeCount — number of times the field has been changed (NOT Record.ChangeCount)

- Number.IsValidInteger(str) — check if string is a valid integer

<a id="rave-platform-facts"></a>
<a id="knowledge-rave-cf-v1-platform-facts"></a>
### Rave platform facts

`rave.cf.v1.platform-facts` · Medidata Rave · Used by: Custom Function Agent, Custom Function Reviewer

RAVE PLATFORM FACTS:

Null safety:

- Once a Rave object is non-null (User, Role, Subject, DataPoint, Record, Form, Folder, Site, Study, etc.), ALL its properties are non-null, transitively (if subj is non-null, subj.Interaction.TrueUser is non-null).
- EXCEPTION: DataPage.Instance CAN be null (e.g. for non-folder-level data) — null-check it.
- Find/Fetch/Get calls (FindByFieldOID, FindByFormOID, Form.FetchByOID, …) can return null.
- FindByFormOID returns both active AND inactive forms (it does not return null for an inactive form).

Field values:

- null and empty string are equivalent for a field value — both mean "no data entered". "Unknown" is a distinct user-entered value like "UNK"/"UN", not empty.
- DataPoint.StandardValue() returns the value in the field's DataFormat-typed form; casting it is safe when field metadata confirms the type.
- DataPoint.ChangeCount: 0 = untouched (never saved), 1 = first entry, 2+ = later edits. ChangeCount > 0 means "field has data" (includes the first entry).
- DateTime.MinValue is a standard sentinel for a missing/invalid date.

Record and instance indices (independent concepts — one is not a substitute for another):

- Record.RecordPosition → which log LINE (row) within a form instance: 1-based, stable, gap-free. Index 0 is the master/standard record; log lines are 1 … Count-1.
- DataPage.PageRepeatNumber → which form INSTANCE within a folder (0-based).
- Instance.InstanceRepeatNumber → which FOLDER instance when folders repeat.
- MasterRecord is the standard record at index 0 (== Records[0]); non-repeating fields live on it. Instance.Instances holds sibling instances of the same folder type; after AddMatrix() the newly created instance is Instance.Instances[Count-1].
- IsLog (repeating vs non-repeating) is unrelated to folders — passing null for the folder in FetchAllDataPointsForOIDPath is normal regardless of log status.

Field visibility:

- dpt.IsVisible = true / false directly on the DataPoint shows/hides a field. This is the ONLY visibility API in a custom function. "SetDataPointVisible" is an edit-check ACTION name, NOT a custom-function API — never call it in CF code.
- You MUST set IsVisible to change visibility; clearing a field with Enter(null, "", 0) alone does NOT hide it. The "Enter Empty When Not Visible" pattern clears each field as it is hidden.
- A hidden field cannot hold data. Setting a field's visibility from another field's value is the intended design pattern — it is NOT a circular dependency.

<a id="custom-functions-v2-api"></a>
## Custom Functions (V2 API)

<a id="custom-function-return-semantics-v2-api"></a>
<a id="knowledge-rave-cf-v2-return-semantics"></a>
### Custom Function return semantics (V2 API)

`rave.cf.v2.return-semantics` · Medidata Rave · Used by: Custom Function Agent

Return semantics:

- Custom functions ALWAYS return null
- Query actions are performed via Rave.Marking.PerformQueryAction()
- Do NOT use "return true" or "return false" — these are not valid for Rave CFs

<a id="rave-object-model-v2-api"></a>
<a id="knowledge-rave-cf-v2-object-model"></a>
### Rave object model (V2 API)

`rave.cf.v2.object-model` · Medidata Rave · Used by: Custom Function Agent

Object model (V2 API — every Rave object is used through its interface):

- ISubject → Instances (folders) → DataPages (one per form instance)
- IDataPage → AllRecords (index 0 = standard/non-log record; index 1+ = log/repeating records)
- IRecord → AllDataPoints (one per field)
- IDataPoint.Data → the field value as string (null or empty = no data)
- Collections are IReadOnlyList<T>: index them and read .Count. To build your own list use List<T>.

<a id="custom-function-core-apis-v2-api"></a>
<a id="knowledge-rave-cf-v2-core-apis"></a>
### Custom Function core APIs (V2 API)

`rave.cf.v2.core-apis` · Medidata Rave · Used by: Custom Function Agent, Custom Function Reviewer

Key APIs (V2):

SAME-FORM field access (fields on the same form as the trigger):

- dpInput.Record.AllDataPoints.FindByFieldOid(fieldOID) → IDataPoint on same record
- dpInput.Record.DataPage → IDataPage of the triggering field
- dpInput.Record.DataPage.AllRecords → all records on the same form

CROSS-FORM field access (fields on a DIFFERENT form):

- subject.GetDataPointsByOidPath(fieldOID, formOID, folderOID)

  - → returns IReadOnlyList<IDataPoint> from another form, INACTIVE data points included
  - → for a log field it returns EVERY instance, one per log line, not only the first
  - → folderOID: use a string like "COMMON" if a folder applies, or null if not
  - → subject: dpInput.Record.Subject
  - → Example: subj.GetDataPointsByOidPath("DTHDAT", "DD", null)
  - → Check result: if (dps != null && dps.Count > 0 && dps[0] != null && dps[0].Active)

CURRENT FOLDER / FORM (the folder/visit and form the triggering field is in):

- dpInput.Record.DataPage.Instance.Folder.OID → folder OID of the triggering field
- dpInput.Record.DataPage.Form.OID → form OID of the triggering field

OTHER:

- dpInput.Record.Subject → ISubject (for cross-form lookups)
- IRecord.Active → true if record is active
- IDataPoint.ChangeCount → number of times the field has been changed
- Rave.Marking.PerformQueryAction(dp, queryText, 1, false, false, openQuery, afp.CheckRef, afp.CheckHash) → open/close query on a data point. The data point is the FIRST argument.
- subject.CrfVersionRef → CRF version reference (needed by Rave.Architect)

A DATA POINT'S QUERIES AND VALUES:

- dp.Queries → IReadOnlyList<IQuery>, the data point's queries
- dp.HasOpenQueries() → bool
- query.QueryText → string
- query.QueryStatus → a QueryStatusEnum: compare with QueryStatusEnum.Open
- query.Close() → close that query
- dp.UserValue, dp.CodedValue → typed object, NOT string: assign to object, then use .ToString() after a null check. "string s = dp.UserValue;" does not compile.
- There is no dp.FetchQueries() and no query.Status.

IDs ARE REFERENCES in V2 (CheckRef, CrfVersionRef, SubjectMatrixRef, ...):

- Pass a reference on, or compare two with == / !=, or with default(CheckRef).
- A reference is NOT a number: do not compare it with 0, do arithmetic on it, or put it in text.

V1 NAMES THAT ARE WRONG IN V2 — do NOT use these in V2 code:

- ActionFunctionParams afp = (ActionFunctionParams) ThisObject

  - → IActionFunctionParams afp = Rave.Context.ActionFunctionParams;

- afp.ActionDataPoint → Rave.Context.ActionDataPoint

- DataPoint / Record / DataPage / Instance / Subject / Form / Matrix as types

  - → IDataPoint / IRecord / IDataPage / IInstance / ISubject / IForm / IMatrix

- DataPoints / Records as types → IReadOnlyList<IDataPoint> / IReadOnlyList<IRecord>

- Record.DataPoints, DataPage.Records → Record.AllDataPoints, DataPage.AllRecords

- FindByFieldOID / FindByFormOID / FindByFolderOID → FindByFieldOid / FindByFormOid / FindByFolderOid

- CustomFunction.FetchAllDataPointsForOIDPath(field, form, folder, subject)

  - → subject.GetDataPointsByOidPath(field, form, folder)

- CustomFunction.PerformQueryAction(text, 1, false, false, dp, open, afp.CheckID, afp.CheckHash)

  - → Rave.Marking.PerformQueryAction(dp, text, 1, false, false, open, afp.CheckRef, afp.CheckHash)

- afp.CheckID, subject.CRFVersionID, x.SubjectMatrixID → afp.CheckRef, subject.CrfVersionRef, x.SubjectMatrixRef

- x.FooID == 0 / > 0 (no object) → x.FooRef == default(FooRef) / != default(FooRef) (a Ref is a struct:

  never compare one with null, and initialize one with default(FooRef))

- dp.StandardValue() (a method) → dp.StandardValue (a property)

- dp.IsVisible → dp.IsVisibleRaw

- x.Active = true / x.Active = false → x.Activate(null) / x.InActivate(null) (reading x.Active is fine; a protocol deviation keeps `deviation.Active = flag`, and has no Activate)

- dp.Verify(true) → dp.Verify(true, false, false) (all three arguments are required)

- dp.Freeze(true) / dp.Freeze(false) → dp.Freeze() / dp.UnFreeze()

- dp.Lock(true) / dp.Lock(false) → dp.Lock() / dp.Unlock()

- dp.FreezeDisplayStatus == FreezeDisplayStatusEnum.Frozen → dp.IsFrozenRaw

- Audits.Load(dp) → dp.FetchAudits() (V2's audits have no ID: to order them by when they were made, use .OrderByDescending(a => a.AuditTime), never a Ref)

- Number.IsValidInteger(text) → Rave.DataFormat.IsValidInteger(text)

- new KeyValueCollection() → Rave.Edc.CreateKeyValueCollection()

- new KeyValue(key, value) → cannot be created; add with collection.Add(key, value)

- CustomFunction.PerformCustomFunction(name, subject.CRFVersionID, arg)

  - → Rave.PerformCustomFunction(name, subject.CrfVersionRef, arg)

- a user's Active → Enabled; Rave.Configuration.FetchUserByLogin(login) finds a user

Do NOT mix V1 and V2 names in one function.

<a id="derivation-apis-v2-api"></a>
<a id="knowledge-rave-cf-v2-derivation-apis"></a>
### Derivation APIs (V2 API)

`rave.cf.v2.derivation-apis` · Medidata Rave · Used by: Custom Function Agent, Custom Function Reviewer

Writing data (derivation CFs, V2):

- IDataPoint.Enter(value, "", 0) → write a value to a field

  - → value: string value to enter (use null or "" to clear)
  - → Do NOT assign dp.Data directly — use Enter() to trigger audit trail and cascading
  - → Example: dpTarget.Enter(dpInput.Data, "", 0);
  - → Example (clear): dpTarget.Enter(null, "", 0);
- IDataPoint.SetNonConformant(bool) → mark/clear non-conformant status

  - → true = value is non-conformant (not in valid list), false = clear
  - → Used for dynamic search list validation

<a id="add-form-apis-v2-api"></a>
<a id="knowledge-rave-cf-v2-add-form-apis"></a>
### Add Form APIs (V2 API)

`rave.cf.v2.add-form-apis` · Medidata Rave · Used by: Custom Function Agent

Adding/removing forms in a visit (AddForm CFs, V2):

- dpInput.Record.DataPage.Instance → IInstance of the triggering record's visit

- instance.DataPages.FindByFormOid(formOID) → find IDataPage by form OID (or null)

- Rave.Architect.FetchFormByOid(formOID, subject.CrfVersionRef) → fetch an IForm definition

- instance.AddDataPage(form) → add a form to an existing folder instance

- page.Active → read whether a form is active

- page.Activate(null) / page.InActivate(null) → make a form active / inactive

- page.IsStatusSet(Status.IsTouched) → read a form's IsTouched status

- Pattern for adding a form:

  ```
  IInstance inst = dpInput.Record.DataPage.Instance;
  IDataPage pg = inst.DataPages.FindByFormOid("FORMOID");
  if (pg == null)
  {
    IForm frm = Rave.Architect.FetchFormByOid("FORMOID", subj.CrfVersionRef);
    if (frm != null) { inst.AddDataPage(frm); }
  }
  else { pg.Activate(null); }
  ```

- Pattern for deactivating an untouched form:

  ```
  if (pg != null && !pg.IsStatusSet(Status.IsTouched)) { pg.InActivate(null); }
  ```

<a id="folder-and-matrix-apis-v2-api"></a>
<a id="knowledge-rave-cf-v2-folder-matrix-apis"></a>
### Folder and matrix APIs (V2 API)

`rave.cf.v2.folder-matrix-apis` · Medidata Rave · Used by: Custom Function Agent, Custom Function Reviewer

Folder/matrix management (creating/merging visit folders, V2):

- subject.Instances → all folder instances for the subject

- subject.Instances.FindByFolderOid(folderOID) → find IInstance by folder OID (or null)

- subject.Instances[i].Folder.OID → folder OID of instance i

- subject.Instances[i].InstanceRepeatNumber → repeat number of the instance

- subject.Instances[i].Active → true if instance is active

- Rave.Architect.FetchMatrixByOid(matrixOID, subject.CrfVersionRef) → fetch an IMatrix definition

- subject.AddMatrix(matrix) → add a new folder instance for the subject

- subject.MergeMatrix(matrix) → merge a matrix (creates folder if not present)

- subject.UnMergeMatrix(matrix) → un-merge a matrix (removes the merged folder)

- Example: conditionally merge or un-merge a matrix:

  ```
  IMatrix mtx = Rave.Architect.FetchMatrixByOid("INJSR", subject.CrfVersionRef);
  if (mtx != null)
  {
    if (toMerge) { subject.MergeMatrix(mtx); }
    else { subject.UnMergeMatrix(mtx); }
  }
  ```

<a id="log-forms-in-custom-functions-v2-api"></a>
<a id="knowledge-rave-cf-v2-log-forms"></a>
### Log forms in Custom Functions (V2 API)

`rave.cf.v2.log-forms` · Medidata Rave · Used by: Custom Function Agent

Log vs non-log forms (V2):

- Non-log form: one record per subject visit → use DataPage.MasterRecord or AllRecords[0]
- Log form: multiple records per subject visit → iterate DataPage.AllRecords
- When iterating log records, skip inactive: if (!r.Active) continue;
- Index 0 is the standard record; log lines start at index 1

IMPORTANT — log fields vs non-log fields on a log form:

- A log form contains BOTH log fields (repeating, one value per log line) and non-log/standard fields (single value, exists only on record 0).

- The triggering field (dpInput) is ALREADY resolved — use dpInput.Data directly. Do NOT re-fetch the triggering field from each log record.

- Example: AEENDAT (non-log, trigger) vs AESTDAT (log field, per record):

  ```
  string endDateStr = dpInput.Data;  // non-log: read once from trigger
  foreach (IRecord r in dpInput.Record.DataPage.AllRecords)
  {
    if (!r.Active) { continue; }
    IDataPoint dpStart = r.AllDataPoints.FindByFieldOid("AESTDAT");  // log field
    // compare endDateStr against dpStart.Data
  }
  ```

<a id="null-checking-in-custom-functions-v2-api"></a>
<a id="knowledge-rave-cf-v2-null-checking"></a>
### Null checking in Custom Functions (V2 API)

`rave.cf.v2.null-checking` · Medidata Rave · Used by: Custom Function Agent

Null-checking pattern (V2):

```
IReadOnlyList<IRecord> rds = dpInput.Record.DataPage.AllRecords;
foreach (IRecord r in rds)
{
  if (!r.Active) { continue; }
  IDataPoint dp = r.AllDataPoints.FindByFieldOid(fieldOID);
  if (dp != null && !string.IsNullOrEmpty(dp.Data))
  {
    // use dp.Data
  }
}
```

<a id="custom-function-source-format-v2-api"></a>
<a id="knowledge-rave-cf-v2-source-format"></a>
### Custom Function source format (V2 API)

`rave.cf.v2.source-format` · Medidata Rave · Used by: Custom Function Agent

Source code format:

- Rave custom function source is the FUNCTION BODY only
- NEVER wrap code in a method signature like "public bool Eval(object arg) { ... }"
- NEVER include line numbers in the output
- The code starts with the V2 boilerplate below
- Write the V2 API ONLY. Use ONLY the APIs listed in this reference — do not invent properties or methods, and do not fall back to a V1 name because it is familiar
- Use Record.AllDataPoints.FindByFieldOid(oid) — do NOT use Record[oid] indexer syntax
- Use exact equality (==) for field value comparisons, NEVER .Contains()
- C# 7+ features are supported and preferred when they produce cleaner code:

  - Local functions: define helper methods inside the function body instead of as separate methods after the main body
  - Nullable value types: use DateTime? instead of DateTime.MinValue sentinels
  - Inline out variables: DateTime.TryParse(str, out DateTime dt)
- MAXIMUM SOURCE LENGTH: 8000 characters (line breaks count as 2 chars). Rave validation will reject source code exceeding this limit. V2 names are longer than V1's, so keep code concise.

<a id="custom-function-boilerplate-v2-api"></a>
<a id="knowledge-rave-cf-v2-boilerplate"></a>
### Custom Function boilerplate (V2 API)

`rave.cf.v2.boilerplate` · Medidata Rave · Used by: Custom Function Agent

Standard CF boilerplate (V2) — every custom function starts with:

```
IActionFunctionParams afp = Rave.Context.ActionFunctionParams;
IDataPoint dpInput = Rave.Context.ActionDataPoint;
// ... function logic here ...
return null;
```

Do NOT cast ThisObject to get these: that is V1, and does not compile in V2. Do NOT wrap logic in try/catch unless the prompt explicitly requests error handling.

<a id="cross-form-pattern-v2-api"></a>
<a id="knowledge-rave-cf-v2-cross-form-pattern"></a>
### Cross-form pattern (V2 API)

`rave.cf.v2.cross-form-pattern` · Medidata Rave · Used by: Custom Function Agent

Cross-form lookup pattern (V2):

```
ISubject subj = dpInput.Record.Subject;
IReadOnlyList<IDataPoint> dps = subj.GetDataPointsByOidPath("FIELDOID", "FORMOID", folderOID);
if (dps != null && dps.Count > 0 && dps[0] != null
    && dps[0].Active && !string.IsNullOrEmpty(dps[0].Data))
{
  string value = dps[0].Data;
  // use value
}
NOTE: folderOID is a string like "COMMON" or null if no folder applies.
```

<a id="query-pattern-v2-api"></a>
<a id="knowledge-rave-cf-v2-query-pattern"></a>
### Query pattern (V2 API)

`rave.cf.v2.query-pattern` · Medidata Rave · Used by: Custom Function Agent

Query action pattern (V2) — decide with a bool, then make ONE call on the path that evaluates the rule:

```
bool openQry = false;
// ... set openQry based on logic ...
Rave.Marking.PerformQueryAction(dpInput, queryText, 1, false, false, openQry, afp.CheckRef, afp.CheckHash);
The data point comes FIRST. Putting it fifth, as V1 does, is wrong in V2.
Do NOT call it twice on the same path — once with true and then once with false — which leaves the outcome depending on call order. Compute the bool and pass it.
A guard clause that exits early is different and is expected: it calls PerformQueryAction with false and returns, so a query opened by an earlier evaluation is closed rather than left standing. See the custom code example.
The sixth argument is the only one that decides anything. false closes the query, true opens it.
```

<a id="custom-function-worked-example-v2-api"></a>
<a id="knowledge-rave-cf-v2-worked-example"></a>
### Custom Function worked example (V2 API)

`rave.cf.v2.worked-example` · Medidata Rave · Used by: Custom Function Agent

COMPLETE CUSTOM CODE EXAMPLE (V2) — cross-form lookup with log-form iteration:

This example checks if a value selected on the current form matches any record on a log form. If DSAENO on the DS form contains a value, find the matching AE record by AESPID on the AE form and check that AEACN == "DRUG WITHDRAWN".

```
IActionFunctionParams afp = Rave.Context.ActionFunctionParams;
IDataPoint dpInput = Rave.Context.ActionDataPoint;

// Get the triggering field value (same-form)
string dsaeno = dpInput.Data;
if (string.IsNullOrEmpty(dsaeno))
{
  Rave.Marking.PerformQueryAction(dpInput, "query text", 1, false, false, false, afp.CheckRef, afp.CheckHash);
  return null;
}

// Cross-form lookup: get AESPID from the AE log form
ISubject subj = dpInput.Record.Subject;
IReadOnlyList<IDataPoint> dpsSpid = subj.GetDataPointsByOidPath("AESPID", "AE", null);

bool openQry = true;  // default: open query (no match found)

if (dpsSpid != null && dpsSpid.Count > 0)
{
  for (int i = 0; i < dpsSpid.Count; i++)
  {
    IDataPoint dpSpid = dpsSpid[i];
    if (dpSpid == null || !dpSpid.Active) { continue; }
    if (string.IsNullOrEmpty(dpSpid.Data)) { continue; }

    if (dpSpid.Data == dsaeno)
    {
      // Found matching record — now check another field on SAME record
      IDataPoint dpAcn = dpSpid.Record.AllDataPoints.FindByFieldOid("AEACN");
      if (dpAcn != null && dpAcn.Data == "DRUG WITHDRAWN")
      {
        openQry = false;  // match found, no query needed
      }
      break;
    }
  }
}

Rave.Marking.PerformQueryAction(dpInput, "query text", 1, false, false, openQry, afp.CheckRef, afp.CheckHash);
return null;
```

KEY PATTERNS demonstrated:

- Cross-form field access: subject.GetDataPointsByOidPath()
- Iterate the returned list by index, skipping inactive data points
- Access another field on the SAME record: dpSpid.Record.AllDataPoints.FindByFieldOid()
- Single PerformQueryAction call with bool variable, data point first
- Always return null

<a id="dynamic-search-lists-v2-api"></a>
<a id="knowledge-rave-cf-v2-dynamic-search-lists"></a>
### Dynamic Search Lists (V2 API)

`rave.cf.v2.dynamic-search-lists` · Medidata Rave · Used by: Custom Function Agent

Dynamic Search List CFs (V2):

- Start from the data point the list is for:

  ```
  IDataPoint dpAction = Rave.Context.ActionDataPoint;
  ISubject subject = dpAction.Record.Subject;
  ```

- Return a key value collection (NOT null):

  ```
  Medidata.Utilities.Interfaces.IKeyValueCollection KVC = Rave.Edc.CreateKeyValueCollection();
  KVC.Add(display, value);
  return KVC;
  ```

- A key value pair cannot be created on its own in V2: there is no "new KeyValue(...)"

- Collect values into ArrayList, sort, then build KVC

- Skip standard record (RecordPosition == 0) and inactive records

- Rave.DataFormat.IsValidInteger(str) — check if string is a valid integer

<a id="rave-platform-facts-v2-api"></a>
<a id="knowledge-rave-cf-v2-platform-facts"></a>
### Rave platform facts (V2 API)

`rave.cf.v2.platform-facts` · Medidata Rave · Used by: Custom Function Agent, Custom Function Reviewer

RAVE PLATFORM FACTS (V2 API):

Null safety:

- Once a Rave object is non-null (IInternalUser, ISubject, IDataPoint, IRecord, IForm, IFolder, etc.), ALL its properties are non-null, transitively.
- EXCEPTION: DataPage.Instance CAN be null (e.g. for non-folder-level data) — null-check it.
- Find/Fetch/Get calls (FindByFieldOid, FindByFormOid, Rave.Architect.FetchFormByOid, …) can return null.
- FindByFormOid returns both active AND inactive forms (it does not return null for an inactive form).

Field values:

- null and empty string are equivalent for a field value — both mean "no data entered". "Unknown" is a distinct user-entered value like "UNK"/"UN", not empty.
- IDataPoint.StandardValue (a property in V2) returns the value in the field's DataFormat-typed form; casting it is safe when field metadata confirms the type.
- IDataPoint.ChangeCount: 0 = untouched (never saved), 1 = first entry, 2+ = later edits. ChangeCount > 0 means "field has data" (includes the first entry).
- DateTime.MinValue is a standard sentinel for a missing/invalid date.

Record and instance indices (independent concepts — one is not a substitute for another):

- Record.RecordPosition → which log LINE (row) within a form instance: 1-based, stable, gap-free. Index 0 is the master/standard record; log lines are 1 … Count-1.
- DataPage.PageRepeatNumber → which form INSTANCE within a folder (0-based).
- Instance.InstanceRepeatNumber → which FOLDER instance when folders repeat.
- MasterRecord is the standard record at index 0 (== AllRecords[0]); non-repeating fields live on it.
- IsLog (repeating vs non-repeating) is unrelated to folders — passing null for the folder in GetDataPointsByOidPath is normal regardless of log status.
- GetDataPointsByOidPath returns inactive data points as well as active ones — check .Active.

Field visibility:

- dpt.IsVisibleRaw is a data point's visibility property. "SetDataPointVisible" is an edit-check ACTION name, NOT a custom-function API — never call it in CF code.
- Clearing a field with Enter(null, "", 0) alone does NOT hide it.
- A hidden field cannot hold data. Setting a field's visibility from another field's value is the intended design pattern — it is NOT a circular dependency.

Frozen and locked:

- dp.IsFrozenRaw says whether a data point is frozen, and stays true if it is then locked. dp.LockStatus reads Locked for a locked data point whether or not it was frozen first, so it does not answer "is this frozen".

<a id="reviewing-custom-functions"></a>
## Reviewing Custom Functions

<a id="custom-function-review-guidance"></a>
<a id="knowledge-rave-cf-review-guidance"></a>
### Custom Function review guidance

`rave.cf.review.guidance` · Medidata Rave · Used by: Custom Function Reviewer

REVIEW GUIDANCE (validate every finding against these before reporting):

Null checks:

- A missing null check is only a finding when the Find/Fetch result is used with NO null check at all. Redundant-but-harmless null checks, and null checks guarding against configuration errors, are correct defensive coding — not findings.

Repeat numbers / record access:

- Do not suggest replacing RecordPosition, PageRepeatNumber, or InstanceRepeatNumber with one another. Do not flag MasterRecord access, or Instance.Instances[Count-1] after AddMatrix(), as incorrect.

Log record iteration:

- for(i=1; i<rds.Count; i++) iterates all log records — correct, not an off-by-one error; do not suggest i<=rds.Count (that would be out of bounds). i<=Count-1 and i<Count are identical. for(i=0; i<rds.Count; i++) with a skip on RecordPosition==0 is also correct.
- Skipping RecordPosition==0 (the master record) for log-only operations is intentional and correct. Comparing a non-repeating field value against each log record is a standard pattern.

Same-record vs cross-record:

- "CROSS" in a check/function name means cross-field (multiple fields on the same record), not cross-record. Only flag cross-record concerns when the header comment explicitly describes cross-record logic.

Form / folder lookups:

- FindByFormOID returns both active AND inactive forms — do not claim it only returns active forms. Accessing a folder's Instances (e.g. Instance.Instances) is a standard pattern; do not claim it accesses the wrong folder's instances.

Edit check configuration:

- The wiring (trigger field, ActionDataPoint, actions, query target) is configured by the user and is always correct. Do not suggest changes to it, and do not flag circular dependencies between trigger and action fields. Only review the code logic within the function.
- Which field receives the query (the PerformQueryAction target) is the user's intentional design choice — do not claim the query is on the "wrong field".

Compilation:

- Assume the code compiles unless there is strong evidence otherwise. Be cautious about claiming type mismatches or compilation errors — variable names differing by one character (e.g. dps vs dp) are usually intentional and refer to different types.

Code style:

- Case-insensitive string comparison on numeric values is harmless. Variable/parameter naming is never a finding. If code produces correct results, style choices are not findings.
- The guillemet characters « » in source code represent < and > respectively — display substitutions, not bugs. Treat « as < and » as > when reading code.

<a id="reviewing-v2-code"></a>
<a id="knowledge-rave-cf-review-v2"></a>
### Reviewing V2 code

`rave.cf.review.v2` · Medidata Rave · Used by: Custom Function Reviewer

REVIEWING V2 CODE:

- This function is written with the V2 API. The V2 names listed above are correct: do NOT report them as misspellings of V1 names, and do NOT report Rave.Context, Rave.Marking, Rave.Architect, Rave.Edc, Rave.Configuration or an interface type (IDataPoint, …) as unknown.
- Rave.Marking.PerformQueryAction takes the data point FIRST. A call written in V1's order (text first, data point fifth) is a real finding.
- A reference (CheckRef, CrfVersionRef, SubjectMatrixRef) compared with a number or put into text is a real finding.

<a id="reviewing-code-that-mixes-v1-and-v2"></a>
<a id="knowledge-rave-cf-review-mixed"></a>
### Reviewing code that mixes V1 and V2

`rave.cf.review.mixed` · Medidata Rave · Used by: Custom Function Reviewer

THIS FUNCTION USES BOTH THE V1 AND THE V2 API. Both references are given: judge each line against the API it is written in. Mixing the two is reported separately, so do NOT report it as a finding.

<a id="clinical-form-patterns"></a>
## Clinical form patterns

<a id="which-fields-on-a-clinical-form-are-conditional"></a>
<a id="knowledge-clinical-conditional-field-patterns"></a>
### Which fields on a clinical form are conditional

`clinical.conditional-field-patterns` · Any · Used by: Field Visibility Advisor, Progressive Display Advisor

IMPORTANT - Common clinical form patterns:

When a form starts with a leading field like "Was X performed?" or "Were Y completed?" with Yes/No options, ALL subsequent fields typically depend on that leading field being "Yes". Examples:

- "Were Vital Signs measured?" (Yes/No) → Date, Time, BP, Heart Rate, etc. all depend on Yes
- "Was ECG performed?" (Yes/No) → ECG Date, PR interval, QRS, etc. all depend on Yes
- "Was lab collected?" (Yes/No) → Collection date, time, results all depend on Yes
- "Was questionnaire completed?" (Yes/No) → ALL questionnaire questions depend on Yes (e.g., "Have you had fevers?", "Have you had joint pain?" - these are the questionnaire content)

These fields should be marked as conditional even if their pretext doesn't say "If Yes".

IMPORTANT - Sex/Gender-dependent fields (MUST identify these):

Look for a SEX or GENDER field with options like "Male, Female" (or "M, F" or similar). Questions about pregnancy, childbearing potential, or menstrual status ONLY apply to females (biologically only females can become pregnant or have childbearing potential). These fields MUST be marked as conditional on the SEX/GENDER field = Female (or the female option). Examples - ALL of these depend on SEX=Female (use the actual female option text as trigger_user_value):

- "Is the participant of childbearing potential?" → depends on SEX=Female
- "Childbearing potential" → depends on SEX=Female
- "Pregnant?" or "Currently pregnant?" → depends on SEX=Female
- "Date of last menstrual period" → depends on SEX=Female
- "Currently breastfeeding?" → depends on SEX=Female
- "Pregnancy test result" → depends on SEX=Female

These MUST be marked as conditional even though their pretext doesn't say "If Female".

Fields that should NOT be marked as conditional:

- Fields with "If known", "If applicable", "If available" (these are always shown)
- Fields that are always visible regardless of other field values
- The leading field itself (e.g., "Was X performed?")
- Classification questions (see below)

IMPORTANT - Classification questions vs leading fields:

On forms that collect events (AE - Adverse Events, CM - Concomitant Medications, MH - Medical History), questions that classify or categorize the record are NOT leading fields for STANDARD form fields. Example: On an AE form, "Does the subject have [specific condition]?" (e.g., CABG, COVID, etc.) classifies what TYPE of AE was reported. Standard AE fields like start date, end date, severity, outcome, etc. apply to ALL adverse events and should NOT depend on this classification.

However, classification questions CAN still be leading fields for their own specific follow-up fields. For example, if "Does the subject have CABG?" is followed by "CABG procedure date" or "CABG details", those specific CABG fields SHOULD be conditional on the CABG question = Yes.

The key distinction:

- Standard form fields (dates, severity, outcomes, etc.) are NOT conditional on classification questions
- Specific follow-up fields that only make sense for one classification ARE conditional
- Other independent leading field patterns on the form still apply normally

<a id="veeva-vault-edc"></a>
## Veeva Vault EDC

<a id="events-forms-and-items"></a>
<a id="knowledge-veeva-design-objects"></a>
### Events, forms and items

`veeva.design-objects` · Veeva Vault EDC · Used by: Specification Review

Event names describe study visits ("Screening", "Cycle 1"). Form names label CRFs ("Demographics", "Adverse Events"). Item names are the fields on a form ("AGE", "AESEV").

<a id="how-a-data-point-is-addressed"></a>
<a id="knowledge-veeva-datapoint-address"></a>
### How a data point is addressed

`veeva.datapoint-address` · Veeva Vault EDC · Used by: Veeva Test Case Agent

A Veeva Vault EDC data point is addressed by five segments: event group, event, form, item group and item. All five are required.
