Create a Scripted Rule

You can write a customized script inside a rule in the data model.

Create a new scripted rule

In the Data Model Editor, click New Rule > Scripted Rule and select an option:

  • JavaScript
  • C#

Back to top

Edit a script

Select one of the following:

What do you want to do? Available for: Instructions:
Edit script in the data model C#/JavaScript rules Expand the rule to configure the script.
Edit script in a separate tab C#/JavaScript rules

Select Script > Edit in New Tab.

The scripted rule content remains locked until you save your changes and close the tab.

Edit script in an external editor C#/JavaScript rules

Opens the rule as a .cs or .js file in your default editor.

  1. Select Script > Edit in External Editor.
  2. When you finish making changes, save them in the external editor.
  3. In Service Virtualization, reload the modified script when prompted.
  4. Save the data model.
Edit script in a Visual Studio project C# rule only

Opens the rule as a .csproj Visual Studio project in your default editor.

All IntelliSense and code completion features are available.

  1. Select Script > Edit in Visual Studio project.
  2. When you finish making changes, save them in the external editor.
  3. In Service Virtualization, reload the modified script when prompted.
  4. Save the data model.

Back to top

Script guidelines

Write the script content according to the following guidelines:

Note: The rules contain commented out configuration assistance and sample scripts.

  • JavaScript: Use any JavaScript expression from ECMAScript 5 strict mode along with Service Virtualization exposed objects.

  • C#: You can code any algorithmic implementation designed to process messages that are received by Service Virtualization.

    To include code in the script that will act on external elements, such as files in the file system, windows configuration, printers, network, database checks, or other programs, you must specify these rules in the Service Virtualization security policy file. For details on configuring the security policy file, see Configure C# Security.

  • You can insert the path to a Service Virtualization object, instead of entering it manually. Select a scripted rule, and from the Data Model Editor Script menu, select Insert Path. Select a data element to add to the script.

In addition, the following Service Virtualization objects are available:

For manipulating messages:

Description JavaScript property C# property
To access request data hpsv.request hpsv.Request
To access response data hpsv.response hpsv.Response
To access Service Call Activity data hpsv.serviceCallActivities[ ] hpsv.Activities[ ]

Note: The Service Call Activity property represents an array, where each index corresponds to one service call activity. The service call activities are indexed starting from 0, according to the order in the data model, from left to right.

For example:

For a C# rule, you can also use the following syntax: hpsv.Activities.<Activity>

Where <Activity> has the form Activity{UniqueId}_{ActivityName}. <Activity> does not change when you add/remove other activities (unlike the activity index when using the hpsv.Activities[] indexer).

Example: hpsv.Activities.Activity4_getClaim

For stateful behavior, define a context for the script:

Context JavaScript property C# property Description
Server hpsv.context.server hpsv.Contexts.Server The data is visible to all services on the server that are simulating. Data is deleted when the server restarts.
Service hpsv.context.service hpsv.Contexts.Service The data is visible only to the service for all simulated messages. Data is deleted when the service simulation ends.
Operation hpsv.context.operation hpsv.Contexts.Operation The data is visible only to requests of the current operation. Data is deleted when the service simulation ends.
Session hpsv.context.session hpsv.Contexts.Session The data is visible only to requests coming from the same user session. Data is deleted when the user session ends.
Call The data is visible only to one service call (= simulated request). Data is deleted when the simulation of that request ends.

Note: If you want to add complex objects such as DTOs into the Context object, you must first make the complex object serializable so that it can be stored inside the Context object.

To search the content of contexts:

It can be helpful to search the contexts of your script, to check for possible memory leaks, for example.

To take advantage of this functionality, use the property 'Keys' from any context.

Example: These examples are for a C# rule. (For a JavaScript rule, replace 'Contexts' with 'context'.)

To search for existing keys:

string[] listOfExistingKeys = hpsv.Contexts.Server.Keys;

To remove all keys:

foreach(string key in listOfExistingKeys) {

For information on the current environment:

You may want to enable the script to identify the environment in which the virtual service is running, so the script can execute differently in different environments based on that information.

To take advantage of this functionality, use the property 'Environment' from the root HpsvObject in your scripts, together with the following fields:

Field JavaScript property C# property Description
MachineName hpsv.environment.machineName hpsv.Environment.MachineName The NetBIOS name of the computer.
UserDomainName hpsv.environment.userDomainName hpsv.Environment.UserDomainName The domain to which the current user belongs.
UserName hpsv.environment.userName hpsv.Environment.UserName The user who started the Service Virtualization Server or the Designer (embedded server).

For information on the current service:

Description JavaScript property C# property
Virtual service identifier hpsv.ServiceInfo.Id
Virtual service name hpsv.ServiceInfo.Name
Virtualization project identifier hpsv.serviceInfo.projectId hpsv.ServiceInfo.ProjectId
Virtualization project name hpsv.serviceInfo.projectName hpsv.ServiceInfo.ProjectName
An array of related endpoints hpsv.serviceInfo.endpoints hpsv.ServiceInfo.Endpoints

Additional endpoint properties:

The endpoints property represents a collection of endpoints. You need to provide an integer (indexed from 0) to access one of the items within the collection. For example:

var myAgentId = hpsv.serviceInfo.endpoints[0].virtualOutputAgentId;

Description JavaScript property C# property
Virtual address URL address Address
Real address URL realAddress RealAddress
ID of real input agent realInputAgentId RealInputAgentId
ID of real output agent realOutputAgentId RealOutputAgentId
ID of virtual input agent virtualInputAgentId VirtualInputAgentId
ID of virtual output agent virtualOutputAgentId VirtualOutputAgentId

Tip: If you encounter any problems while using a scripting rule, delete the rule using the script and restart simulation.

Back to top

Configure logging for scripted rules

Configure logging using one or more of the following methods:

Log messages to the Service Virtualization log file

  1. Prerequisite: Enable logging

    To enable your scripts to write to the log file, add the following entry to the log4net section of the configuration file for the Designer or Service Virtualization Server.

    <logger name="JavascriptLogger"> OR <logger name="CsharpRuleFileLogger">

    <level value="XXX" />


    where XXX is one of the following log levels: DEBUG, INFO, WARNING, ERROR.

    By default, only log level WARNING is set.

    For more information, consult the log4net documentation.


    • Service Virtualization Server configuration file: HP.SV.StandaloneServer.exe.config, located on the Service Virtualization Server machine in the server installation folder. By default, C:\Program Files\HPE\HPE Service Virtualization Server\Server\bin.

    • Designer configuration file: VirtualServiceDesigner.exe.config, located on the Designer machine in the installation folder. By default, C:\Program Files\HPE\HPE Service Virtualization Designer\Designer\bin\.
    • For details on log file locations, see Virtual Service Editor.
  2. Configure a logging level in the script.

    Log level JavaScript C#
    Error hpsv.logger.error hpsv.Logger.Error
    Warning hpsv.logger.warn hpsv.Logger.Warn
    Information hpsv.Logger.Info
    Debug hpsv.logger.debug hpsv.Logger.Debug
  3. To log request and response data for a specific data element, add the following line to the script. Assign a name for the custom log file, and enter actual names for the request and response operations, and data elements.

    hpsv.dataLogger.log("<custom logfile name>.log", hpsv.request.<request operation name>.<element1 name>.<element2 name>, hpsv.response.<response operation name>.<element1 name>.<element2 name>)

Send messages to the Designer Problem List

To add messages to the Designer Problem List instead of logging to a file, add one of the following lines to your script:

hpsv.MessageLogger.Error("error: " + log);

hpsv.MessageLogger.Warn("warn: " + log);

hpsv.MessageLogger.Info("info: " + log);

hpsv.MessageLogger.Debug("debug: " + log);

You can then view logged messages in the Problem List.

By default, only errors and warnings are displayed in the Problem List. You can set the filter to display messages from other log levels as well. For details, see Problem List.

Back to top

Set options for the scripted rule

The following options are available for the scripted rule:

  • Skip the first simulation pass. To modify or complete data filled in by another rule, the scripted rule must be have a higher priority than the rule you want to override. However, during the first simulation pass, all the response data for the script has not yet been filled in by the other rules. In this case, you may want to skip the scripted rule during the first simulation pass.
  • Execute the rule only once. As an example, you may be using the script to add an item into an array, such as assigning an ID to a user. Each time the script is run, the rule will modify the response, causing the simulation process to continue repeatedly. In this case, use this option to properly execute the simulation.

By default, both of these options are enabled. (For more details on how simulation is performed, see The Simulation Process.)

To change this default setting and reduce CPU time during simulation, configure the rule's properties by right-clicking the scripted rule and select Properties.

Back to top

See also: