XPathExtractionRule.cs 4.58 KB
//*************************************************************************************************
// XPathExtractionRule.cs
// Owner: Mahipal Kante
//
// This web test plugin extracts data from a Web Service response using XPath expression.
// The Web Service response can be plain XML or 'application/soap+msbin1'
// (binary - used by Silverlight application with WCF RIA) or JSON
//
// Copyright(c) Microsoft Corporation, 2010
//*************************************************************************************************
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using Microsoft.VisualStudio.TestTools.WebTesting;
using System.Xml.XPath;
using System.Xml;
using System.IO;

namespace WebTest.WebService.Plugin.Runtime
{
    [DisplayName("XPathExtractionRule")]
    [Description("Extracts a value using XPath expression")]
    public class XPathExtractionRule : ExtractionRule
    {
        // The name of the desired input field
        private string xPathValue;
        [DisplayName("XPathToSearch")]
        [Description("Extracts a value using XPath expression")]
        public string XPathToSearch
        {
            get { return xPathValue; }
            set { xPathValue = value; }
        }

        // To set a default value use:[DefaultValue(<value>)]
        private int indexValue;
        [Description("Indicates which occurrence of the string to extract. This is zero-based index.")]
        public int Index
        {
            get { return indexValue; }
            set { indexValue = value; }
        }

        private bool randomMatch;
        [DisplayName("ExtractRandomMatch")]
        [Description("If true, all matches are found and one of the matches is randomly returned.")]
        public bool ExtractRandomMatch
        {
            get { return randomMatch; }
            set { randomMatch = value; }
        }

        [DisplayName("Pass if not found")]
        [Description("If set to true, this rule will pass the request even if no match is found.")]
        [DefaultValue(false)]
        public bool passIfNotFound { get; set; }

        /// <summary>
        /// The Extract method.  The parameter e contains the Web test context.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public override void Extract(object sender, ExtractionEventArgs e)
        {
            try
            {
                ContentHandler contentHandler = ContentHandlerFactory.GetHandler(e.Response.ContentType);
                if (contentHandler != null) {
                    if (contentHandler.IsBinary)
                    {
                        contentHandler.MessageBytes = e.Response.BodyBytes;
                    }
                    else
                    {
                        contentHandler.MessageString = e.Response.BodyString;
                    }

                    XPathNodeIterator iterator = contentHandler.EvaluateXPath(XPathToSearch);

                    List<string> values = new List<string>();

                    int i = 0;
                    while (iterator.MoveNext())
                    {
                        XPathNavigator nav2 = iterator.Current.Clone();

                        string value;
                        if (nav2.NodeType.Equals(XPathNodeType.Element))
                        {
                            value = nav2.InnerXml;
                        }
                        else
                        {
                            value = nav2.Value;
                        }

                        values.Add(value);
                        if (!ExtractRandomMatch && (i == Index))
                        {
                            // add the extracted value to the Web test context
                            e.WebTest.Context.Add(this.ContextParameterName, value);
                            e.Success = true;
                            return;
                        }
                        i++;
                    }

                    if (ExtractRandomMatch && (values.Count > 0))
                    {
                        Random random = new Random();
                        e.WebTest.Context.Add(this.ContextParameterName, values[random.Next(values.Count)]);
                        e.Success = true;
                        return;
                    }
                }
            }
            catch (Exception ex)
            {
                e.Message = ex.Message;
            }

            e.Success = passIfNotFound;
            e.Message += " (XPath not found)";
            return;
        }
    }
}