Friday, January 2, 2009

Read XML files to List of XML Strings Dynamically

I needed to dynamically get XML files into a list of strings for load testing a web service. To improve performance this list needed to be static, but I wanted it to also be random. So here is what I came up with:

A class to load and contain the list of xml string from xml files:

public class TestXMLFiles
{
private static List _xmlStrings;
public static List XmlStrings
{
get
{
if (_xmlStrings == null)
{
try
{
// get files
string[] _files = System.IO.Directory.GetFiles("../../../WebService_LoadTest/TestXMLFiles", "*.xml");
// create list for strings
_xmlStrings = new List(_files.Length);

System.IO.StreamReader _stream;
// cycle through files
foreach (string _file in _files)
{
// open stream to file
_stream = System.IO.File.OpenText(_file);
using (_stream) // this will dispose of stream when done
{
// read from steam to list
XmlStrings.Add(_stream.ReadToEnd());
}
}
}
catch (Exception e)
{
throw e;
}

}
return _xmlStrings;
}
}
}



Now to call it from the webTest inside of the GetRequestEnuberator().

To get the string for FormPostParameters, I create a string like this:
String _xml = TestXMLFiles.XmlStrings[getRandomXML()];


And here is the random method:
private int getRandomXML()
{
Random rand = new Random();
return rand.Next(0, TestXMLFiles.XmlStrings.Count);
}


This will allow you to just drop xml files into the directory "TestXMLFiles" and they will be randomly put into your load test. I think it's cool. ;)

No comments: