Avatar of mathieu_cupryk
mathieu_cupryk
Flag 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);
        }
    }
C#

Avatar of undefined
Last Comment
mathieu_cupryk

8/22/2022 - Mon
Arthur_Wood

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

mathieu_cupryk

ASKER
I am using 2005 visual studio.

I just want to setup an application.
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.
Experts Exchange is like having an extremely knowledgeable team sitting and waiting for your call. Couldn't do my job half as well as I do without it!
James Murphy
mathieu_cupryk

ASKER
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
paulb1989

Log in or sign up to see answer
Become an EE member today7-DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform
Sign up - Free for 7 days
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
Not exactly the question you had in mind?
Sign up for an EE membership and get your own personalized solution. With an EE membership, you can ask unlimited troubleshooting, research, or opinion questions.
ask a question
mathieu_cupryk

ASKER
Ok.
I will fix these right away. Can you check the syntax for me.
mathieu_cupryk

ASKER
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/Programming/Programming_Languages/Dot_Net/VB_DOT_NET/Q_21779576.html?qid=21779576
Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.
mathieu_cupryk

ASKER
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);
        }
    }