Get a Word Count (number of occurences) for a specific word in a VSTS WebTest

How to get the total word count for a specific word in your VSTS WebTest.

1. Create an Extension Method (has to be static) that allows your Count to appear off of any string as if it were a method of the class.
2. Use Extension method in any project, by just adding your static class.
3. Usage is elegant and works with any string. 

    e.Response.BodyString.CountTotalOccurences("msdn",StringComparison.InvariantCultureIgnoreCase)

1. Add a class to your project, and your source code like following:

using System;

namespace TestExperimentMar09

{

    public static class StaticExtensionsClass

    {

        /// <summary>

        /// CountTotalOccurences of a string within the current string

        /// </summary>

        /// <param name="searchPattern">enter t</param>

        /// <param name="comparisonType">provide the StringComparison (i.e. case sensitive search)</param>

        /// <returns></returns>

        public static int CountTotalOccurences(this string sourceText, string searchPattern,StringComparison comparisonType)

        {

            int countTotal = 0;

            int i = 0;

            while ((i = sourceText.IndexOf(searchPattern, i,comparisonType)) != -1)

            {

                i += searchPattern.Length;

                countTotal++;

            }

            return countTotal;

        }

    }

}

 

**** Here is a sample of how this would be used in your WebTest, in this case its set to fire on the PostReqest event, so you may need to tweak which event you hook this up for.

       void WebTest2Coded_PostRequest(object sender, PostRequestEventArgs e)

        {

            //do we have something to work with

            if ( (e.ResponseExists) && (! e.Response.IsBodyEmpty) )

            {

                //created an extension method in a static class that was added to the project

                //all this does is give you the count of the occurences of the string you pass in

                e.WebTest.Context.Add("SearchCount", e.Response.BodyString.CountTotalOccurences("msdn",StringComparison.InvariantCultureIgnoreCase));

            }

        }