Evaluate Parameters

When working with extension plugins and parameters Visual Studio will sometimes pass the parameter name as a string into your function.
 
As an example when the parameter (i.e. {{ParameterName}}) is used as as a value in your plugin properties VSTS is not evaluating that parameter into value.
 
This will pretty mych always manifest itself by failed request and investigation of the cause will reviel string looking like {{ParameterName}} rather then the value you would expect.
 
Following function addresses that issue and evaluete all parameter names enclosed in duble curly brackets (i.e. "{{" "}}") into parameter value.
 
This function takes two parameters: text to evaluate and context parameter which can be obtained from e.WebTest.Context parameter of the PreRequest method.
/*********************************************************************************
  * Function signature: string EvaluateParameter(string textToEvaluate, WebTestContext context)
  * Description:
  *                  
  *
  * Parameters
  * textToEvaluate
  *
  *
  * Return Value
  *
  ********************************************************************************/
public string EvaluateParameter(string textToEvaluate, WebTestContext context)
{
    string result = textToEvaluate;
    
    //Iterate through all context parameters and attempt to replace the {{ParameterName}} //string with the parameter value
    foreach (var contextParameter in context.Keys)
        result = result.Replace("{{" + contextParameter + "}}", context[contextParameter].ToString());
 
    //return the evaluated expression
    return result;
}
 

Here is sample use of this function:

public override void PreRequest(object sender, PreRequestEventArgs e)
{
    //m_jsonCode could come from the user

    string evaluatedString = EvaluateParameter(m_jsonCode, e.WebTest.Context);

    //make use of the evaluated string
}

Comments