Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

This guide Scripts Module (How-to Guide) walks you through configuring the Scripts module for custom automation and business logic. You'll create reusable classes, automated tasks, simple expressions, and integrate external libraries using C#, VB.NET, or Python.

Prerequisites:

  • Basic programming knowledge (C#, VB.NET, or Python)
  • Understanding of event-driven programming
  • Tags configured for script interaction

In this page:

Table of Contents
maxLevel2
minLevel2
indent10px
excludeSteps
stylenone


Configuration Workflow

  1. Create ScriptClasses - Build reusable function libraries
  2. Create ScriptTasks - Implement automated processes
  3. Add ScriptExpressions - Simple one-line actions
  4. Add ReferencesScriptReferences - Include external DLL libraries
  5. Test and Debug - Verify script execution

Step 1: Create ScriptClasses

ScriptClasses are libraries of reusable methods available throughout your solution.

Creating a Class

  1. Navigate to Scripts → Classes
  2. Click Plus icon
  3. Configure:
    • Name: Class identifier
    • Code: Language (C#, VB.NET, Python)
    • Domain: Server or Client execution
    • ClassContent: Methods (standard) or Namespace (advanced)
  4. Click OK
  5. Double-click to open Code Editor

Built-in Classes

ClassPurposeDomain
ServerMainMethods for all server tasksServer
ClientMainMethods for all client displaysClient

Example Class

Method

Code

<ac:structured-macro ac:name="warning"> ac:rich-text-body Important: ScriptClasses with Methods type contain only method definitions - NO class declaration wrapper </ac:rich-text-body> </ac:structured-macro>

csharp

public class ServerMain
{
    // CORRECT - Methods directly, no class wrapper
public double CalculateEfficiency(double input, double output)
    {
        if (input == 0) return 0;
        return (output / input) * 100;
    }
    
    public void LogEvent(string message)
    {
        @Alarm.AuditTrail.AddCustomMessage(message);
}

public string GetStatus(double value, double limit)
{
     }return value > limit ? "High" : "Normal";
}

Step 2: Create ScriptTasks

ScriptTasks execute code based on triggers or schedules.

Creating a Task

  1. Go to Scripts → Tasks
  2. Click Plus icon
  3. Configure:
    • Name: Task identifier
    • Code: Language selection
    • Domain: Server (default) or Client
    • Trigger: Execution condition
    • Period: Time interval (if periodic)
    • InitialState: Enabled or Disabled
  4. Click OK
  5. Double-click to edit code

Built-in Tasks

TaskTriggerPurpose
Server Startup
ServerStartupSolution startsInitialize server resources
Server Shutdown
ServerShutdownSolution stopsCleanup operations
Client Startup
ClientStartupClient connectsSetup client environment
Client Shutdown
ClientShutdownClient disconnectsClient cleanup

Trigger Options

Trigger TypeExampleUse Case
Tag Change
Tag
@Tag.TemperatureReact to value changes
Period60000 (ms)Run every minute
Condition
Tag
@Tag.Level > 100Monitor thresholds
Interval00:00:30Periodic executionSchedule
Daily at 06:00Scheduled reports
StartupBuilt-in
Initialization
One-time initialization

Example Task Code

<ac:structured-macro ac:name="warning"> ac:rich-text-body Important: ScriptTasks contain only the method body - NO function declarations or wrappers </ac:rich-text-body> </ac:structured-macro>

csharp

// CORRECT - Code directly, no method wrapper
// Task: MonitorProduction
// Trigger: Tag@Tag.ProductionRun (on change)

public void RunTask()
{
    if (@Tag.ProductionRun == 1)
    {
        @Tag.StartTime = DateTime.Now;
        @Tag.BatchNumber = @Tag.BatchNumber + 1;
        
        // Call class method
        @Script.Class.ServerMain.LogEvent("Production Started");
    }
    else
    {
        @Tag.EndTime = DateTime.Now;
        TimeSpan duration = @Tag.EndTime - @Tag.StartTime;
        @Tag.BatchDuration = duration.TotalMinutes;
    }
}

Step 3: Add ScriptExpressions

Expressions are single-line VB.NET statements for simple operations.

Creating an Expression

  1. Navigate to Scripts → Expressions
  2. Add new row with:
PropertyDescriptionExample
ObjectTarget tag to receive resultTag.Result
Expression
Calculation
VB.NET calculation/actionTag.Input1 + Tag.Input2
ExecutionWhen to runOnChange
DomainServer or ClientServer
TriggerOptional trigger tagTag.Calculate


Info
titleExpressions Syntax

Expressions use VB.NET / C# syntax and don't require @ symbol for tags, as there is no local .NET. variables declared in the same context.


Expression Methods

IIF Method (all parameters evaluated):

vbnet

Tag.Status = IIF(Tag.Value > 100, "High", "Normal")
' Both "High" and "Normal" are evaluated

TIF Method (conditional evaluation - recommended):

vbnet

Tag.Result = TIF(Tag.Mode == 1, @ScriptScript.Class.ServerMain.Method1(), @ScriptScript.Class.ServerMain.Method2())
' Only executes Method1() OR Method2(), not both

Common Expression Examples

csharpvbnet

//' Mathematical
Tag.Average = (Tag.Value1 + Tag.Value2) / 2

//' Conditional
Tag.Alarm = Tag.Temperature > Tag.Setpoint

//' Method call
@ScriptTag.Efficiency = Script.Class.ServerMain.CalculateEfficiency(Tag.Input, Tag.Output)

//' String manipulation
Tag.FullName = Tag.FirstName + " " + Tag.LastName

' Using TIF for conditional execution
Tag.Status = TIF(Tag.Running, "Active", "Stopped")

Step 4: Add External References

Adding DLL References


  1. Warning


    Go to Scripts → References

  2. Click Plus icon
  3. Browse and select DLL file
  4. Configure:
    • Name: Reference identifier
    • Domain: Server or Client
  5. Click OK

DLL Location Best Practices

LocationMacroUse For
ThirdParty folder_ThirdParty_Server-side DLLs
WpfControls folder_WpfControls_Client-side controls
Solution folder_SolutionPath_Solution-specific DLLs

Adding Namespaces

  1. Open Code Editor
  2. Click Namespace Declarations button
  3. Add using/import statementsrequired namespaces in dialog:

csharp

using System.Data;
using MyCustomLibrary;
System.Linq
MyCustomLibrary

Warning

Never add using/import statements directly in code - always use Namespace Declarations dialog



Step 5: Test and Debug

Enable Debugging

  1. Go to Runtime → Build and Publish
  2. Enable Debug Information
  3. Save solution

Using the Debugger

  1. Start runtime (F5)
  2. Go to Runtime → Startup
  3. Click Connect
  4. Open script in Code Editor
  5. Click Attach .NET Debugger
  6. Set breakpoints by clicking line numbers
  7. Use step controls when stopped

Monitoring Execution

Check script performance:

csharp

// InAccess in expressions or displays
@Script.Task.MyTask.ExecutionCount    // Number of executions
@Script.Task.MyTask.LastCPUTime       // Last execution time
@Script.Task.MyTask.State             // Running or Idle

Code Editor Features

IntelliSense

  • Type @ to see all namespaces
  • Type . after objects for property listproperties
  • Automatic method completion
  • Parameter hints

Productivity Tools

Tool
Shortcut
ActionPurpose
Format DocumentToolbar buttonAuto-format code
Comment
Ctrl+K,C
OutToolbar buttonComment selection
Uncomment
Ctrl+K,U
Toolbar buttonUncomment selection
Compile
F6
Save or toolbarCheck for errors

Toolkit Methods

Common operations via TK namespace:

csharp

// Type conversion
double value = TK.ConvertTo<double>("123.45");

// Tag to DataTable
DataTable dt = TK.CopyTagToDataTableTagsToDataTable(@Tag"Tag.MyTemplate*");

// Dynamic property access
object val = TK.GetPropertyValueGetObjectValue(@Tag"Tag.MyTag, "Value");

Common Issues

Script Not Executing

  • Check trigger configuration
  • Verify InitialState is Enabled
  • Review BuildStatus for errors
  • Confirm domain (Server/Client) matches deployment

Compilation Errors

  • Check BuildErrors column
  • Verify references resolved
  • BuildStatus column (red X indicates errors)
  • Double-click to see error details
  • Verify Review namespace declarations
  • Ensure language syntax correctcorrect code structure (no wrappers)

DLL Not Found

  • Use macros instead of absolute paths
  • Place in correct folder (ThirdParty/WpfControls)
  • Restart script module Designer after DLL updateupdates
  • Check Resolved status in References

Performance

Issues

Issue

  • Monitor LastCPUTime property
  • Avoid infinite loops
  • Use async operations for long tasks
  • Optimize database queries
Best Practices
  • appropriate trigger type
  • Consider execution frequency

Best Practices

(tick) Code Structure - Remember: no class/method wrappers in Tasks and Classes

(tick) Use descriptive names - Clear task and class identification

(tick) Handle exceptions -

Try-catch blocks for error handling

Platform provides automatic protection, but validate inputs

(tick) Reuse code- Create methods in

classes

ScriptClasses

- Document purpose and parameters

(tick)

Comment complex logic

Use @ symbol correctly - Required in Tasks/Classes, not in Expressions

(tick) Test incrementally - Verify BuildStatus after each

script separately

change

(tick) Monitor performance - Check execution

times

metrics regularly

(tick)

Avoid circular references - Classes shouldn't reference each other

Use TIF over IIF - Avoid unnecessary method execution in expressions


Script Examples

Data Calculation Task

csharp

// Runs every 1 minute
public void CalculateKPIs()
{
    Task body only - no method wrapper
// Trigger: Period = 60000 (1 minute)

double production = @Tag.ProductionCount;
    double runtime = @Tag.RuntimeHours;
    
    if (runtime > 0)
    {
        @Tag.ProductionRate = production / runtime;
        @Tag.Efficiency = @Script.Class.ServerMain.
            CalculateEfficiency(@Tag.PlannedProduction, production);
    }
}

Alarm Response Expression

vbnet

//' Object: Tag.AlarmActiveAlarmMessage
//' Expression:
TIF(Tag.Critical == 1, @Script.Class.ServerMain.SendAlert(), 0"CRITICAL: System Alert", "Normal Operation")

Client Display Initialization

csharp

// ClientClientStartup StartupTask Task
public- voidbody InitializeClient()
{
    only
@Display.MainPage.UserLabel = @Client.UserName;
    @Display.MainPage.LoginTime = DateTime.Now;
}@Script.Class.ClientMain.LoadUserPreferences();

Next Steps

  • [Display Code Behind →] Scripts in displays
  • [Python Integration →] Configure Python scripts
  • [API Integration →] External system connections



In this section...

Page Tree
root@parent
spaces93DRAF