Read Trx File From C#

Introduction

A Trx file is nothing but a Visual Studio unit test result file extension. This file is in XML format. The result of a unit test is kept in the TestResult folder in the base directory. You can open these files in Visual Studio to see the results.

Objective

To understand the parsing of a trx file using C#.

How to Parse TRX File?

Microsoft Visual Studio provides a schema to read a trx file. The schema is available in the Visual Studio installation folder. It is named vstst.xsd and can be found under your Visual Studio installation directory. You can easily run the xsd.exe tool on this schema and generate the C# classes to parse the trx files.

Use the command line to generate a C# class from schema.

Run following command in a command prompt to generate the C# class file.

C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin\x64\xsd.exe" "C:\Program Files (x86)\Microsoft Visual Studio 9.0\Xml\Schemas\vstst.xsd" /c

Figure 1.jpg

Source Code

I used an ASP.Net GridView to display the result. Create a ASP.Net web-based application and include the vstst.cs file (that you got after running the xsd command).

In the following code snippet I am accessing the base directory and iterating through all the files that have a trx extension. While iterationg I am using "TestRunType" that is defined in the vstst.cs file. Here I am creating a datatable at run time and retrieving all the important information from UnitTestResultType. This datatable is then used as a source for GridView. You can refer to the attached document to see the full code.

using System;
using System.Data;
using System.IO;
using System.Xml.Serialization;

public class YourClass
{
    public DataTable GetTestResultData()
    {
        string fileName;
        DataTable testResultTable = null;

        try
        {
            // Construct DirectoryInfo for the folder path passed in as an argument
            string baseDirectory = AppDomain.CurrentDomain.BaseDirectory;
            DirectoryInfo di = new DirectoryInfo(baseDirectory);
            ResultTable resultTable = new ResultTable();
            testResultTable = resultTable.CreateTestResultTable();

            // For each .trx file in the given folder process it
            foreach (FileInfo file in di.GetFiles("*.trx"))
            {
                fileName = file.Name;

                // Deserialize TestRunType object from the trx file
                StreamReader fileStreamReader = new StreamReader(file.FullName);
                XmlSerializer xmlSer = new XmlSerializer(typeof(TestRunType));
                TestRunType testRunType = (TestRunType)xmlSer.Deserialize(fileStreamReader);

                // Navigate to UnitTestResultType object and update the sheet with test result information
                foreach (object itob1 in testRunType.Items)
                {
                    ResultsType resultsType = itob1 as ResultsType;

                    if (resultsType != null)
                    {
                        foreach (object itob2 in resultsType.Items)
                        {
                            UnitTestResultType unitTestResultType = itob2 as UnitTestResultType;

                            if (unitTestResultType != null)
                            {
                                DataRow row = testResultTable.NewRow();
                                row[Constant.PROCESSEDFILENAME] = fileName;
                                row[Constant.TESTID] = unitTestResultType.testId;
                                row[Constant.TESTNAME] = unitTestResultType.testName;
                                row[Constant.TESTOUTCOME] = unitTestResultType.outcome;
                                row[Constant.ERRORMESSAGE] = ((System.Xml.XmlNode[])(((OutputType)(((TestResultType)(unitTestResultType)).Items[0])).ErrorInfo.Message))[0].Value;
                                testResultTable.Rows.Add(row);
                            }
                        }
                    }
                }
            }
        }
        catch (Exception)
        {
            // Handle exceptions here
        }

        return testResultTable;
    }
}

Design Source Code

I used a GridView and bound all the columns to the display. You can refer to the attached document to see the full code.

public class YourClass
{
    public void YourMethod()
    {
        // Assuming this is where you want to put the GridView creation logic
        
        GridView grdTestResult = new GridView
        {
            ID = "grdTestResult",
            runat = "server",
            CssClass = "text",
            AutoGenerateColumns = false,
            CellPadding = 5,
            GridLines = "Both",
            SelectedIndex = 0
        };

        // Adding BoundFields to the GridView
        grdTestResult.Columns.Add(new BoundField
        {
            DataField = "ProcessedFileName",
            HeaderText = "Processed File Name"
        });

        grdTestResult.Columns.Add(new BoundField
        {
            DataField = "TestID",
            HeaderText = "Test Run ID"
        });

        grdTestResult.Columns.Add(new BoundField
        {
            DataField = "TestName",
            HeaderText = "Test Name"
        });

        grdTestResult.Columns.Add(new BoundField
        {
            DataField = "TestOutcome",
            HeaderText = "Test Outcome"
        });

        // Rest of your logic goes here...

        // Assuming you want to add the GridView to a parent control
        // parentControl.Controls.Add(grdTestResult);
    }
}

Note. If you have generated a fresh C# class file from the schema then don't forget to comment the Items property of these two classes.

  1. GenericTestType
  2. CodedWebTestElementType

Conclusion

With the schema provided by Microsoft it's easy to parse a trx file.


Similar Articles