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#

Then select a scope for the rule. For details, see Rule scope.

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 sv.Request
To access response data hpsv.response sv.Response
To access Service Call Activity data hpsv.serviceCallActivities[ ] sv.Activities

Note:

  • JavaScript: The serviceCallActivities 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 as shown in the screen shot above. To access the getClaim Service Call Activity, use hpsv.serviceCallActivities[0]; for enterClaim use hpsv.serviceCallActivities[1]; for listClaim use hpsv.serviceCallActivities[2].

    • You can access request and response data in a similar way as for the virtual service itself: hpsv.serviceCallActivities[i].request and hpsv.serviceCallActivities[i].response (where i is the SCA index).

    • Additionally you can check whether the Service Call Activity is enabled or if it was executed: hpsv.serviceCallActivities[i].enabled and hpsv.serviceCallActivities[i].executed (where i is the SCA index).

  • C#: In C# rules, you can access Service Call Activities under the name they have in the Data Model. In the screen shot above, use sv.Activities.getClaim, sv.Activities.enterClaim, or sv.Activities.listClaim.

    • You can access request and response data in a similar way as for the virtual service itself: sv.Activities.getClaim.Request, sv.Activities.getClaim.Response

    • Additionally you can check whether the Service Call Acticity is enabled or if it was executed: sv.Activities.getClaim.Enabled, sv.Activities.getClaim.Executed

For stateful behavior, define a context for the script:

Context JavaScript property C# property Description
Server hpsv.context.server sv.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 sv.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 sv.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 sv.Contexts.Session The data is visible only to requests coming from the same user session. Data is deleted when the user session ends.
Call hpsv.context.call sv.Contexts.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.

  • For the Server context type, you can use the AddPersistent method to store a value in a persistent manner that is not cleared even after the server restart. For details see HpsvPersistentContext.AddPersistent Method.

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 'sv' with 'hpsv' and 'Contexts' with 'context'.)

To search for existing keys:

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

To remove all keys:

foreach(string key in listOfExistingKeys) {
      sv.Contexts.Server.Remove(key);    
}

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 sv.Environment.MachineName The NetBIOS name of the computer.
UserDomainName hpsv.environment.userDomainName sv.Environment.UserDomainName The domain to which the current user belongs.
UserName hpsv.environment.userName sv.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 sv.ServiceInfo.Id
Virtual service name hpsv.serviceInfo.name sv.ServiceInfo.Name
Virtualization project identifier hpsv.serviceInfo.projectId sv.ServiceInfo.ProjectId
Virtualization project name hpsv.serviceInfo.projectName sv.ServiceInfo.ProjectName
An array of related endpoints hpsv.serviceInfo.endpoints sv.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 = sv.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" />

    </logger>

    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.

    Note:  

    • 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\Micro Focus\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\Micro Focus\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 sv.Logger.Error
    Warning hpsv.logger.warn sv.Logger.Warn
    Information hpsv.logger.info sv.Logger.Info
    Debug hpsv.logger.debug sv.Logger.Debug
  3. Notice of intended deprecation: Access to the dataLogger is planned to be deprecated in a future version of SV.

    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.

    sv.dataLogger.log("<custom logfile name>.log", sv.request.<request operation name>.<element1 name>.<element2 name>, sv.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:

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

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

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

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