Custom actions created with script extensions can generate code that implement conditional logic, that is, contains if…then or if…then…else statements. To generate a conditional statement, follow these steps:
-
Create an
IfSyntaxobject using theSyntax.CreateIfmethod. -
Create a
ConditionSyntaxobject corresponding to the condition you want to test and assign it to theConditionproperty of theIfSyntaxobject. (See Generating Comparison and Logical Expressions.) -
Create syntax elements corresponding to the statements of the
thenandelsebranches and assign them to theTrueSyntaxandFalseSyntaxproperties of theIfSyntaxobject, respectively.If you want a particular branch contain multiple statements, you should create a
CollectionSyntaxobject that will serve as the block container and add the desired statements to this collection. (See Generating Statement Collections.)
After you have configured the IfSyntax object, you can pass it to the Syntax.GenerateSource method to get the actual script code of the conditional statement.
The example below demonstrates how you can generate conditional statements. It generates the code that posts an error message to the test log if the Success variable value is False:
JScript
function ShowIfThenStatement()
{
var oVarName = Syntax.CreateInvoke();
oVarName.InvokeName = "Success";
oVarName.IsProperty = true;
var oCondition = Syntax.CreateCondition();
oCondition.OperatorType = oCondition.otNot;
oCondition.Right = oVarName;
var oMethodCall = Syntax.CreateInvoke();
oMethodCall.ClassValue = "Log";
oMethodCall.InvokeName = "Error";
oMethodCall.IsProperty = false;
oMethodCall.AddParameter("Checkpoint failed.");
var oIf = Syntax.CreateIf();
oIf.Condition = oCondition;
oIf.TrueSyntax = oMethodCall;
var strCode = Syntax.GenerateSource(oIf);
aqDlg.ShowMessage(strCode);
}
VBScript
Sub ShowIfThenStatement
Dim oVarName, oCondition, oMethodCall, oIf, strCode
Set oVarName = Syntax.CreateInvoke
oVarName.InvokeName = "Success"
oVarName.IsProperty = True
Set oCondition = Syntax.CreateCondition
oCondition.OperatorType = oCondition.otNot
oCondition.Right = oVarName
Set oMethodCall = Syntax.CreateInvoke
oMethodCall.ClassValue = "Log"
oMethodCall.InvokeName = "Error"
oMethodCall.IsProperty = False
oMethodCall.AddParameter "Checkpoint failed."
Set oIf = Syntax.CreateIf
oIf.Condition = oCondition
oIf.TrueSyntax = oMethodCall
strCode = Syntax.GenerateSource(oIf)
aqDlg.ShowMessage strCode
End Sub
The generated code is as follows:
JavaScript, JScript
if(!Success)
Log.Error("Checkpoint failed.");
Python
if not Success:
Log.Error("Checkpoint failed.")
VBScript
If (Not Success) Then
Call Log.Error("Checkpoint failed.")
End If
DelphiScript
if not Success then
Log.Error('Checkpoint failed.');
C++Script, C#Script
if(!Success)
Log["Error"]("Checkpoint failed.");
See Also
Generating Script Code
Generating Comparison and Logical Expressions
IfSyntax Object
Syntax.CreateIf Method
