Link to home
Start Free TrialLog in
Avatar of mathieu_cupryk
mathieu_cuprykFlag for Canada

asked on

Need to test the following code in Visual C# 2005.


Below is a piece of code that i need to run in Visual C# 2005.

How do I go about testing this. Do I go Visual C# console application. What are the steps? I appreciate any help.

using System;
using System.Collections;
using System.Data;
using System.IO;
using System.Xml;
using System.Xml.Schema;
using System.Text;

public class XMLValidator
{
    // Validation Error Count
    static int ErrorsCount = 0;

     // Validation Error Message
    static string ErrorMessage = "";

    public static void ValidationHandler(object sender,
                                         ValidationEventArgs args)
    {
        ErrorMessage = ErrorMessage + args.Message + "\r\n";
        ErrorsCount ++;
    }

    public void Validate(string strXMLDoc)
    {
        try
        {
            // Declare local objects
            XmlTextReader         tr   = null;
            XmlSchemaCollection   xsc  = null;
            XmlValidatingReader   vr   = null;

            // Text reader object
            tr  = new XmlTextReader(urlpath);
            xsc = new XmlSchemaCollection();
            xsc.Add(null, tr);

            // XML validator object

            vr = new XmlValidatingReader( strXMLDoc,
                         XmlNodeType.Document, null);

            vr.Schemas.Add(xsc);

            // Add validation event handler

            vr.ValidationType = ValidationType.Schema;
            vr.ValidationEventHandler +=
                     new ValidationEventHandler(ValidationHandler);

            // Validate XML data

            while(vr.Read());

            vr.Close();

            // Raise exception, if XML validation fails
            if (ErrorsCount > 0)
            {
                throw new Exception(ErrorMessage);
            }

            // XML Validation succeeded
            Console.WriteLine("XML validation succeeded.\r\n");
        }
        catch(Exception error)
        {
            // XML Validation failed
            Console.WriteLine("XML validation failed." + "\r\n" +
            "Error Message: " + error.Message);
        }
    }
Avatar of Arthur_Wood
Arthur_Wood
Flag of United States of America image

What version of Visual Studio are you using?  

Are you familiar with the concept of Unit Testing?

Do you have NUnit loaded on your system?  (check out http://www.nunit.org/)

AW

Avatar of mathieu_cupryk

ASKER

I am using 2005 visual studio.

I just want to setup an application.
Avatar of paulb1989
paulb1989

File -> New -> Project
Create a new Console Application from the Windows category
Go to the Solution Explorer, right click on your project and click Add -> New Item
Make a new code file, lets say called XmlValidator.cs
Enter the code you posted into that file (Theres a } missing from the end of the code you posted, make sure its there and visual studio isn't showing errors)
Go back to the Program.cs file that visual studio generated for you
Change your Main method to something like this:

    static void Main(string[] args)
    {
      if (args.Length == 1)
      {
        XMLValidator xmlval = new XMLValidator();
        xmlval.Validate(args[0]);
      }
    }

However, the code you posted does have an error at the following line because urlpath isn't defined

    tr = new XmlTextReader(urlpath);

I compiled by adding the following before the above line, but I'm not sure if its right or not, I just guessed from the how urlpath is used

      string urlpath = Path.GetTempFileName();
      File.WriteAllText(urlpath, strXMLDoc);

If that is correct, you'd probably want to use File.Delete to delete the file after you're finished with it and not clutter up the temp folder.
Ok Paul very good so far, however.

I get the following compilation errors:



Warning      1      'System.Xml.Schema.XmlSchemaCollection' is obsolete: 'Use System.Xml.Schema.XmlSchemaSet for schema compilation and validation. http://go.microsoft.com/fwlink/?linkid=14202'      C:\Documents and Settings\matt\My Documents\Visual Studio 2005\Projects\XmlValidator\XmlValidator\XmlValidator.cs      30      13      XmlValidator
Warning      2      'System.Xml.XmlValidatingReader' is obsolete: 'Use XmlReader created by XmlReader.Create() method using appropriate XmlReaderSettings instead. http://go.microsoft.com/fwlink/?linkid=14202'      C:\Documents and Settings\matt\My Documents\Visual Studio 2005\Projects\XmlValidator\XmlValidator\XmlValidator.cs      31      13      XmlValidator
Warning      3      'System.Xml.Schema.XmlSchemaCollection' is obsolete: 'Use System.Xml.Schema.XmlSchemaSet for schema compilation and validation. http://go.microsoft.com/fwlink/?linkid=14202'      C:\Documents and Settings\matt\My Documents\Visual Studio 2005\Projects\XmlValidator\XmlValidator\XmlValidator.cs      39      23      XmlValidator
Warning      4      'System.Xml.XmlValidatingReader' is obsolete: 'Use XmlReader created by XmlReader.Create() method using appropriate XmlReaderSettings instead. http://go.microsoft.com/fwlink/?linkid=14202'      C:\Documents and Settings\matt\My Documents\Visual Studio 2005\Projects\XmlValidator\XmlValidator\XmlValidator.cs      44      22      XmlValidator

In my project.cs i have:

using System;
using System.Collections.Generic;
using System.Text;

namespace XmlValidator
{
    class Program
    {
        static void Main(string[] args)
        {
            if (args.Length == 1)
            {
                XMLValidator xmlval = new XMLValidator();
                xmlval.Validate(args[0]);
            }

        }
    }
}
and

in the XmlValidator.cs I have:

using System;
using System.Collections;
using System.Data;
using System.IO;
using System.Xml;
using System.Xml.Schema;
using System.Text;

public class XMLValidator
{
    // Validation Error Count
    static int ErrorsCount = 0;

    // Validation Error Message
    static string ErrorMessage = "";

    public static void ValidationHandler(object sender,
                                         ValidationEventArgs args)
    {
        ErrorMessage = ErrorMessage + args.Message + "\r\n";
        ErrorsCount++;
    }

    public void Validate(string strXMLDoc)
    {
        try
        {
            // Declare local objects
            XmlTextReader tr = null;
            XmlSchemaCollection xsc = null;
            XmlValidatingReader vr = null;

            string urlpath = Path.GetTempFileName();
            File.WriteAllText(urlpath, strXMLDoc);


            // Text reader object
            tr = new XmlTextReader(urlpath);
            xsc = new XmlSchemaCollection();
            xsc.Add(null, tr);

            // XML validator object

            vr = new XmlValidatingReader(strXMLDoc,
                         XmlNodeType.Document, null);

            vr.Schemas.Add(xsc);

            // Add validation event handler

            vr.ValidationType = ValidationType.Schema;
            vr.ValidationEventHandler +=
                     new ValidationEventHandler(ValidationHandler);

            // Validate XML data

            while (vr.Read()) ;

            vr.Close();

            // Raise exception, if XML validation fails
            if (ErrorsCount > 0)
            {
                throw new Exception(ErrorMessage);
            }

            // XML Validation succeeded
            Console.WriteLine("XML validation succeeded.\r\n");
        }
        catch (Exception error)
        {
            // XML Validation failed
            Console.WriteLine("XML validation failed." + "\r\n" +
            "Error Message: " + error.Message);
        }
    }
}

What should I do?

ASKER CERTIFIED SOLUTION
Avatar of paulb1989
paulb1989

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Ok.
I will fix these right away. Can you check the syntax for me.
The VB.NET code

Please don't make a class using common names like 'XML'

I made minor changes, have a try:

Public Class CXML
    Private errorsCount As Int32 = 0
    Private errorMsg As StringBuilder

    Public Sub ValidationHandler(ByVal sender As Object, ByVal args As ValidationEventArgs)
        With errorMsg
            .Append(args.Message)
            .Append(vbCrLf)
        End With
        errorsCount += 1
    End Sub

    Public Function validateXml(ByVal strXMLData As String, ByVal xsdFile As String) As Boolean
        Dim tr As XmlTextReader = Nothing
        Dim mySchema As XmlTextReader = Nothing

        Dim xss As System.Xml.Schema.XmlSchemaSet = Nothing
        Dim xrs As XmlReaderSettings = Nothing
        Dim xr As XmlReader

        'create your fragment reader
        tr = New XmlTextReader(strXMLData, Xml.XmlNodeType.Document, Nothing)
        'create your schema
        mySchema = New XmlTextReader(xsdFile)

        xss = New System.Xml.Schema.XmlSchemaSet

        xss.Add(Nothing, mySchema)

        'add the schema to your reader settings
        xrs = New XmlReaderSettings
        xrs.Schemas.Add(xss)

        'add the validation type
        xrs.ValidationType = ValidationType.Schema
        AddHandler xrs.ValidationEventHandler, AddressOf ValidationHandler

        errorMsg = New StringBuilder
        errorMsg.Remove(0, errorMsg.Length)

        'create your reader with the validation
        xr = XmlReader.Create(tr, xrs)

        'read
        While xr.Read

        End While

        xr.Close()

        If errorsCount > 0 Then
            Return False
        Else
            Return True
        End If
    End Function
End Class

I will convert this to C#
https://www.experts-exchange.com/questions/21779576/Validate-xml-with-an-XSD-file.html?qid=21779576
Paul does this look ok.

public void Validate(string strXMLDoc, string strXSDFile)
    {
        try
        {
            // Declare local objects
            XmlTextReader tr = null;
            XmlTextReader mySchema = null;
            XmlSchemaSet xss = null;
            XmlReaderSettings xrs = null;
            XmlReader xr = null;

            // Create your fragment reader
            tr = new XmlTextReader (strXMLDoc,XmlNodeType.Document, null);
           
            // Create your schema
            mySchema = new XmlTextReader (strXSDFile);

            xss = new System.Xml.Schema.XmlSchemaSet();
            xss.Add(null, mySchema);

            // Add the schema to your reader settings
            xrs = new XmlReaderSettings();
            xrs.Schemas.Add(xss);
                           
            // Add validation event handler

            xrs.ValidationType = ValidationType.Schema;
            xrs.ValidationEventHandler +=
                     new ValidationEventHandler(ValidationHandler);


            // Create your reader with the validation
            xr = XmlReader.Create(tr, xrs);

            // Validate XML data
            while (xr.Read()) ;
              xr.Close();

            // Raise exception, if XML validation fails
            if (ErrorsCount > 0)
            {
                throw new Exception(ErrorMessage);
            }

            // XML Validation succeeded
            Console.WriteLine("XML validation succeeded.\r\n");
        }
        catch (Exception error)
        {
            // XML Validation failed
            Console.WriteLine("XML validation failed." + "\r\n" +
            "Error Message: " + error.Message);
        }
    }