Search code examples
c#datetimeload-testingweb-performance

Webtest - Using Dates as Context Parameters


I've created a webtest and have a CSV data source that contains a column with a list of short dates (MM/dd/yyyy)

I need to manipulate the parameter due to part of the web page I'm testing has a form parameter that needs it to be formatted as yyyyMMdd

When the date that is captured from the data source (ex: 02/12/2016), I noticed in the Context tab of my test run that the format to "2/12/2016 12:00:00 AM"

I've created a Request plug-in and added the following code:

public override void PreRequest(object sender, PreRequestEventArgs e)
{
   base.PreRequest(sender e)

   string CSVDate = e.WebTest.Context["<datasource date column>"].ToString();
   DateTime dt = DateTime.ParseExact(CSVDate, "MM/dd/yyyy HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture);
   e.WebTest.Context.Add("NewDate", dt.ToString("yyyyMMdd"));

}

This generates a String was not recognized as a valid DateTime error. I tried changing the format to MM/dd/yyyy, but I encountered the same error.

Does anyone know how the correct DateTime format I should be using?


Solution

  • The date-time as shown in the context is 2/12/2016 12:00:00 AM. This has only one digit for the month whereas the format specifier has MM which wants two digits. The date-time also contains the letters AM that are not matched by the format.

    Modifying the format to be M/dd/yyyy HH:mm:ss matches the date-time 2/12/2016 12:00:00, but does not match the AM part. In theory the tt format specifier should match this, but it did not work for me.

    Rather than using ParseExact you can use Parse and it works out the correct format. Using the following worked on the date-time string provided:

    DateTime dt1 = DateTime.Parse(CSVDate, new System.Globalization.CultureInfo("en-US"));
    

    The CultureInfo is needed because the input date has the month and the days the wrong way around.

    However, the real problem is in the way CSV files are handled by the web test. It appears to read them using the same logic as Microsoft Excel uses when reading CSVs. Namely, if it looks like a date then convert it to a date. So any string matching dd/dd/dddd (where d is a digit) might be connverted to a date. (E.g. 15/15/2017 will not be converted because 15 is not a month number.) I recommend rewriting the CSV to format the input date differently, use something that Excel would not treat as a date. One option is to have the date in three columns of the CSV, so have explicit day,monthandyearcolumns. Another option is to add non-date characters to the string and format it correctly, eg asz20160212and then remove thezwithin the web test. Generally, I would advise to avoid the conversion of string toDateTime` then another conversion to a different string.