Skip to content

Utility Functions

Helper functions for logging, dynamic property access, validation, and other utilities.


Logging

$Log

Outputs message to StandardOutput.

Signature:

$Log(message)
$Log(formatString, arg1, arg2, ...)

Parameters:

  • message (string): Message to log
  • formatString (string): .NET format string with placeholders
  • args (any): Values for placeholders

Returns: null

Examples:

$Log("Hello World");

value = 42;
$Log("Value: " + value.ToString());

// With format string
$Log("Customer {0} has premium {1}", name, premium);
$Log("Date: {0}, Amount: {1}", date, amount);

// Debugging
$Log("Processing item " + i.ToString() + " of " + total.ToString());

// Multiple values
$Log("Values: {0}, {1}, {2}", a, b, c);

Notes:

  • Output captured in EverSharpRunner.StandardOutput
  • Useful for debugging and tracing
  • No console output in production usage

Dynamic Property Access

$GetValue

Gets object property value by name.

Signature:

$GetValue(object, propertyName);
$GetValue(object, "nested.property.path");

Parameters:

  • object (Instance): Object to query
  • propertyName (string): Property name or path

Returns: (any) Property value, or null if not found

Examples:

customer = {
  "firstName": "John",
  "lastName": "Doe",
  "age": 35
};

// Get property
firstName = $GetValue(customer, "firstName"); // "John"
age = $GetValue(customer, "age"); // 35

// Nested property access
policy = {
  "customer": {
    "contact": {
      "email": "john@example.com"
    }
  }
};

email = $GetValue(policy, "customer.contact.email");
// "john@example.com"

// Dynamic property name
fieldName = "premium";
value = $GetValue(policy, fieldName);

// Returns null if not found
missing = $GetValue(customer, "notExists"); // null

$HasProperty

Checks whether an object contains a property key.

Signature:

$HasProperty(object, propertyName);
object.HasProperty(propertyName);

Parameters:

  • object (Instance/any): Object to query when using the global function, or any target value when called as instance method .HasProperty(...)
  • propertyName (string): Property name to check

Returns: (boolean) true if the property exists on an object (even when its value is null); false if property does not exist or if the target is null, string, or any non-object value.

Examples:

customer = {
  "name": "Alice",
  "age": 30,
  "email": null
};

hasName = $HasProperty(customer, "name"); // true
hasAge = customer.HasProperty("age"); // true
hasEmail = customer.HasProperty("email"); // true
hasPhone = $HasProperty(customer, "phone"); // false

Notes:

  • Checks key existence, not value content
  • Returns false if target object is null, string, or non-Instance value
  • Use this instead of $GetValue(...) != null when null is a valid stored value

$SetValue

Sets object property value by name.

Signature: $SetValue(object, propertyName, value)

Parameters:

  • object (Instance): Object to modify
  • propertyName (string): Property name
  • value (any): Value to set

Returns: null

Examples:

customer = { "name": "Alice" };

$SetValue(customer, "age", 30);
age = customer.age; // 30

$SetValue(customer, "isActive", true);

// Dynamic property name
propertyName = "premium";
$SetValue(policy, propertyName, 1200);

// Update existing
$SetValue(customer, "age", 31);

Notes:

  • Creates property if it doesn't exist
  • Updates value if property exists
  • Modifies object in-place

.AddProperty(name, value)

Adds property to object (instance method).

Signature: object.AddProperty(propertyName, value)

Parameters:

  • propertyName (string): Property name
  • value (any): Property value

Returns: (Instance) A new object with the added or updated property

Examples:

customer = { "name": "Alice" };

customer = customer.AddProperty("age", 30);
customer = customer.AddProperty("email", "alice@example.com");

age = customer.age; // 30

Notes:

  • Similar to $SetValue but instance method
  • Returns a new object instead of mutating the existing one
  • Can update existing properties

.IsNullOrEmpty()

Checks whether a string, array, or object/dictionary is null or empty.

Signature: value.IsNullOrEmpty()

Parameters: None

Returns: (boolean) true if null, empty string "", empty array [], or empty object {}; false otherwise.

Examples:

"".IsNullOrEmpty(); // true
"hello".IsNullOrEmpty(); // false

([]).IsNullOrEmpty(); // true
([1, 2, 3]).IsNullOrEmpty(); // false

({}).IsNullOrEmpty(); // true
({ "a": 1 }).IsNullOrEmpty(); // false

nullVal = null;
nullVal.IsNullOrEmpty(); // true

Validation

$IsInRange

Checks if value is within range (inclusive).

Signature: $IsInRange(min, max, value)

Parameters:

  • min (decimal): Minimum value (inclusive)
  • max (decimal): Maximum value (inclusive)
  • value (decimal): Value to check

Returns: (boolean) True if value >= min AND value <= max

Examples:

inRange = $IsInRange(1, 10, 5); // true
inRange = $IsInRange(1, 10, 10); // true (inclusive)
inRange = $IsInRange(1, 10, 11); // false

// Age validation
ageValid = $IsInRange(18, 100, customerAge);

// Percentage validation
percentValid = $IsInRange(0, 100, percentage);

// In conditions
if ($IsInRange(100000, 500000, coverage)) {
  // Standard coverage tier
}

// Filter
eligible = customers.Filter((c) => $IsInRange(25, 65, c.age));

$IsNumber

Checks whether a value is numeric or can be parsed as a number.

Signature: $IsNumber(value)

Parameters:

  • value (any): Value to evaluate

Returns: (boolean) true when the value is a numeric type or a numeric string

Examples:

$IsNumber(42); // true
$IsNumber("42.5"); // true
$IsNumber("  -12  "); // true
$IsNumber("hello"); // false
$IsNumber(null); // false

Notes:

  • String values are parsed using invariant culture
  • Useful before calling .ToNumber()

HTTP Requests

$Fetch

Makes HTTP requests to external APIs and services.

Signature: $Fetch(url, options?)

Parameters:

  • url (string): URL to fetch
  • options (object, optional): Request configuration
  • method (string): HTTP method - "GET", "POST", "PUT", or "DELETE" (default: "GET")
  • body (string): Request body for POST/PUT requests (use with $Stringify())

Returns: Response object with the following properties:

  • StatusCode (number): HTTP status code (e.g., 200, 404, 500)
  • Ok (boolean): true if request was successful (status 200-299)
  • Body (object|array): Parsed JSON response body (only present on success)
  • Error (string): Error message (only present on failure)

Examples:

// Simple GET request
response = $Fetch("https://api.example.com/data");
if (response.Ok) {
  data = response.Body;
  $Log("Received data:", data);
} else {
  $Log("Error:", response.Error);
}

// Access response properties
status = response.StatusCode; // 200
isSuccess = response.Ok; // true

// GET with response handling
todos = $Fetch("https://api.example.com/todos");
firstItem = todos.Body[0];
itemId = firstItem.id;

// POST request with body
newItem = {
  "title": "New Todo",
  "completed": false,
  "userId": 1
};

response = $Fetch("https://api.example.com/todos", {
  "method": "POST",
  "body": $Stringify(newItem)
});

if (response.Ok) {
  created = response.Body;
  $Log("Created item with ID:", created.id);
}

// PUT request to update
updatedItem = {
  "title": "Updated Todo",
  "completed": true,
  "userId": 1
};

response = $Fetch("https://api.example.com/todos/1", {
  "method": "PUT",
  "body": $Stringify(updatedItem)
});

// DELETE request
response = $Fetch("https://api.example.com/todos/1", {
  "method": "DELETE"
});

if (response.Ok) {
  $Log("Item deleted successfully");
}

// Error handling
response = $Fetch("https://api.example.com/unknown");
if (!response.Ok) {
  $Log("Status:", response.StatusCode); // 404
  $Log("Error:", response.Error); // "Not Found - {}"
}

Notes:

  • Availability depends on environment setup
  • May be restricted in production environments
  • Synchronous call (blocks execution until response received)
  • Response body is automatically parsed from JSON
  • Does not currently support custom headers or authentication
  • For authenticated APIs, consider C# integration or custom extension functions

Data Conversion Helpers

$Stringify

Converts value to JSON string (if available).

Signature: $Stringify(value)

Parameters:

  • value (any): Value to convert

Returns: (string) JSON representation

Examples:

object = {
  "name": "Alice",
  "age": 30,
  "isActive": true
};

json = $Stringify(object);
// '{"name":"Alice","age":30,"isActive":true}'

array = [1, 2, 3, 4, 5];
jsonArray = $Stringify(array);
// '[1,2,3,4,5]'

Common Patterns

Pattern 1: Dynamic Field Access

function getField(object, fieldName, defaultValue) {
  value = $GetValue(object, fieldName);

  if (value == null) {
    return defaultValue;
  }

  return value;
}

age = getField(customer, "age", 0);

Pattern 2: Conditional Logging

DEBUG = true;

function logDebug(message) {
  if (DEBUG) {
    $Log("[DEBUG] " + message);
  }
}

logDebug("Processing item");

Pattern 3: Range Validation

function validateAge(age) {
  if (!$IsInRange(18, 100, age)) {
    return {
      "valid": false,
      "error": "Age must be between 18 and 100"
    };
  }

  return { "valid": true };
}

Pattern 4: Object Builder

function buildCustomer(data) {
  customer = {};

  $SetValue(customer, "firstName", data.firstName);
  $SetValue(customer, "lastName", data.lastName);
  $SetValue(customer, "age", data.age);
  $SetValue(customer, "createdDate", $Today());

  return customer;
}

Pattern 5: Trace Execution

function processOrder(order) {
  $Log("=== Processing Order {0} ===", order.id);

  $Log("Validating order...");
  isValid = validateOrder(order);
  $Log("Validation result: {0}", isValid);

  if (isValid) {
    $Log("Calculating total...");
    total = calculateTotal(order);
    $Log("Total: {0}", total);
  }

  $Log("=== Complete ===");

  return total;
}

Pattern 6: Config-Driven Logic

config = {
  "minAge": 18,
  "maxAge": 100,
  "minCoverage": 50000,
  "maxCoverage": 1000000
};

function validatePolicy(policy) {
  minAge = $GetValue(config, "minAge");
  maxAge = $GetValue(config, "maxAge");

  if (!$IsInRange(minAge, maxAge, policy.customer.age)) {
    return false;
  }

  minCoverage = $GetValue(config, "minCoverage");
  maxCoverage = $GetValue(config, "maxCoverage");

  if (!$IsInRange(minCoverage, maxCoverage, policy.coverage)) {
    return false;
  }

  return true;
}

Best Practices

1. Check Property Existence

// Good: checks whether the key exists, even if the stored value is null
if (object.HasProperty("property")) {
  value = $GetValue(object, "property");
}

// Also valid
if ($HasProperty(object, "property")) {
  value = $GetValue(object, "property");
}

// Different meaning: checks whether the value is non-null
value = $GetValue(object, "property");
if (value != null) {
  // Use value only when a non-null value is required
}

2. Use Descriptive Log Messages

// Good
$Log("Processing customer {0} - Age: {1}, Premium: {2}", customer.id, customer.age, customer.premium);

// Less helpful
$Log("Processing");

3. Validate Ranges Explicitly

// Good
if ($IsInRange(min, max, value)) {
  // Process
}

// More verbose
if (value >= min && value <= max) {
  // Process
}

4. Use $SetValue for Dynamic Properties

// Good - Dynamic
properties = ["name", "age", "email"];
properties.ForEach((prop) => {
  $SetValue(object, prop, getValue(prop));
});

// Less flexible - Static
object = object.AddProperty("name", nameValue);
object = object.AddProperty("age", ageValue);
object = object.AddProperty("email", emailValue);

Advanced Examples

Example 1: Dynamic Object Mapper

function mapObject(source, mappings) {
  target = {};

  mappings.ForEach((mapping) => {
    sourceField = mapping.source;
    targetField = mapping.target;

    value = $GetValue(source, sourceField);
    $SetValue(target, targetField, value);
  });

  return target;
}

mappings = [
  { "source": "firstName", "target": "first_name" },
  { "source": "lastName", "target": "last_name" },
  { "source": "age", "target": "customer_age" }
];

customer = { "firstName": "John", "lastName": "Doe", "age": 35 };
mapped = mapObject(customer, mappings);

Example 2: Validation Framework

function validate(object, rules) {
  errors = [];

  rules.ForEach((rule) => {
    fieldName = rule.field;
    value = $GetValue(object, fieldName);

    if (rule.required && value == null) {
      errors.Push(fieldName + " is required");
    }

    if (rule.min != null && rule.max != null) {
      if (!$IsInRange(rule.min, rule.max, value)) {
        errors.Push(fieldName + " must be between " + rule.min.ToString() + " and " + rule.max.ToString());
      }
    }
  });

  return errors;
}

rules = [
  { "field": "age", "required": true, "min": 18, "max": 100 },
  { "field": "coverage", "required": true, "min": 50000, "max": 1000000 }
];

errors = validate(policy, rules);

Example 3: Execution Tracer

function trace(name, fn) {
  $Log(">>> Entering: {0}", name);
  startTime = $Now();

  result = fn();

  endTime = $Now();
  duration = $DifferenceInSeconds(endTime, startTime);
  $Log("<<< Exiting: {0} (Duration: {1}s)", name, duration);

  return result;
}

result = trace("calculatePremium", () => {
  return calculatePremium(coverage, age, risk);
});

Next Steps