public void SimpleElementPattern1()
        {
            SetupReaderFromUrl(TestResourceHelper.GetFullPathOfResource("Test/XmlFiles/SimpleElementPattern1.xml"),
                               TestResourceHelper.GetFullPathOfResource("Test/XmlFiles/SimpleElementPattern1.rng"));

            while (!reader.EOF)
            {
                reader.Read();
            }
        }
Example #2
0
        public void SimpleElementPattern1()
        {
            SetupReaderFromUrl("Test/XmlFiles/SimpleElementPattern1.xml",
                               "Test/XmlFiles/SimpleElementPattern1.rng");

            while (!reader.EOF)
            {
                reader.Read();
            }
        }
Example #3
0
        public static void Main(string[] args)
        {
            try {
                if (args.Length != 1)
                {
                    Console.Error.WriteLine("valdoc: wrong nr of arguments");
                    Console.Error.WriteLine("valdoc: usage: valdoc <xml file>");
                    Environment.Exit(1);
                }

                Stream schemaStream = new MemoryStream(Encoding.UTF8.GetBytes(RelaxNgSchema.SCHEMA));
                xmlFile = args[0];

                XmlReader schema   = new XmlTextReader(schemaStream);
                XmlReader document = new XmlTextReader(xmlFile);

                XmlDocument doc = new XmlDocument();
                XmlReader   rvr = new RelaxngValidatingReader(document, schema);

                while (rvr.Read())
                {
                    ;
                }
                Console.WriteLine("valdoc: document {0} is VALID.", new FileInfo(xmlFile).Name);
            } catch (RngException ex) {
                Console.Error.WriteLine("valdoc: document {0} is NOT VALID.", xmlFile);
                Console.Error.WriteLine("valdoc: {0}", ex.Message);
                Environment.Exit(1);
            } catch (Exception ex) {
                Console.Error.WriteLine("valdoc: internal error");
                Console.Error.WriteLine("valdoc: {0}", ex.Message);
                Environment.Exit(1);
            }
        }
        public bool Verify(string content, out TestResult result)
        {
            if (content == null)
            {
                throw new ArgumentNullException("content");
            }

            using (StringReader sr = new StringReader(content))
            {
                XmlTextReader xtrXml = new XmlTextReader(sr);

                using (RelaxngValidatingReader vr = new RelaxngValidatingReader(xtrXml, this.rngPattern))
                {
                    try
                    {
                        while (vr.Read())
                        {
                            // Ignore
                        }

                        result = new TestResult();
                        return(true);
                    }
                    catch (RelaxngException rngex)
                    {
                        result = new TestResult()
                        {
                            LineNumberInError = vr.LineNumber, ErrorDetail = rngex.Message
                        };
                    }

                    return(false);
                }
            }
        }
        private bool _validatePattern()
        {
            if (!_validateGrammarFormat() || !_validateGrammarRules())
            {
                return(false);
            }

            try
            {
                RelaxngValidatingReader reader = new RelaxngValidatingReader(_instanceReader, _grammarReader);
                while (reader.Read())
                {
                    ;
                }
                PatternMatchError = null;
                return(true);
            }
            catch (Exception e)
            {
                if (e is RelaxngException || e is XmlException)
                {
                    PatternMatchError = e.Message;
                    return(false);
                }
                else
                {
                    throw;
                }
            }
        }
Example #6
0
 /// <summary>
 /// Get the first validation error for the given XML document, converting an error in
 /// xmlns (namespace) attribute to a version problem, since that's where the version
 /// number is set.  Returns null if there are no errors.
 /// </summary>
 /// <param name="documentReader"></param>
 /// <returns>string describing first validation error, or null if there are none</returns>
 static public string GetAnyValidationErrors(XmlTextReader documentReader)
 {
     using (Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("SIL.OxesIO.oxes.rng"))
         using (XmlTextReader rngReader = new XmlTextReader(stream))
             using (RelaxngValidatingReader reader = new RelaxngValidatingReader(documentReader, rngReader))
             {
                 //RelaxngValidatingReader reader = new RelaxngValidatingReader(documentReader,
                 //    new XmlTextReader(Assembly.GetExecutingAssembly().GetManifestResourceStream("SIL.OxesIO.oxes.rng")));
                 reader.ReportDetails = true;
                 string lastGuy = "oxes";
                 try
                 {
                     while (!reader.EOF)
                     {
                         //Debug.WriteLine(reader.Value);
                         reader.Read();
                         lastGuy = reader.Name;
                     }
                 }
                 catch (Exception e)
                 {
                     string xmlns = null;
                     if (reader.Name == "oxes")
                     {
                         xmlns = reader.GetAttribute("xmlns");
                     }
                     else if (reader.Name == "xmlns" && (lastGuy == "oxes" || lastGuy == ""))
                     {
                         xmlns = reader.Value;
                     }
                     if (String.IsNullOrEmpty(xmlns))
                     {
                         return(String.Format(OxesIOStrings.ksErrorNear, e.Message, lastGuy, reader.Name, reader.Value));
                     }
                     else
                     {
                         string sVersion;
                         int    idx = xmlns.IndexOf("version_");
                         if (idx >= 0)
                         {
                             sVersion = xmlns.Substring(idx + 8);
                         }
                         else
                         {
                             sVersion = xmlns;
                         }
                         return(String.Format(OxesIOStrings.ksWrongVersion, sVersion, OxesVersion));
                     }
                 }
                 return(null);
             }
 }
Example #7
0
        public void Bug463267()
        {
            var         datatypeLibrary = SetupMyDataProvider();
            XmlDocument xml             = new XmlDocument();

            xml.LoadXml("<root> <v2>1</v2> <v1>mytype</v1> </root>");
            XmlDocument schemaXml = ReadDoc("Test/XmlFiles/463267.rng");
            XmlReader   reader    = new RelaxngValidatingReader(new XmlNodeReader(xml), new XmlNodeReader(schemaXml), datatypeLibrary);

            while (reader.Read())
            {
                ;
            }
        }
        public void CustomTypeProvider()
        {
            var         datatypeLibrary = SetupMyDataProvider();
            XmlDocument xml             = new XmlDocument();

            xml.LoadXml("<root> <v1>mytype</v1> <v2>1</v2> </root>");
            XmlDocument schemaXml = ReadDoc(TestResourceHelper.GetFullPathOfResource("Test/XmlFiles/463264.rng"));
            XmlReader   reader    = new RelaxngValidatingReader(new XmlNodeReader(xml), new XmlNodeReader(schemaXml), datatypeLibrary);

            while (reader.Read())
            {
                ;
            }
        }
Example #9
0
        public void SimpleDefaultNamespace()
        {
            var g = RncParser.ParseRnc(new StringReader("element e { empty }"));
            var x = XmlReader.Create(new StringReader("<e/>"));
            var r = new RelaxngValidatingReader(x, g);

            try {
                while (!r.EOF)
                {
                    r.Read();
                }
            } finally {
                r.Close();
            }
        }
Example #10
0
        public void InheritDefaultNamespace()
        {
            RelaxngPattern          g   = Compile("Test/XmlFiles/include-default-namespace.rnc");
            XmlReader               xtr = new XmlTextReader("Test/XmlFiles/include-default-namespace.xml");
            RelaxngValidatingReader r   = new RelaxngValidatingReader(xtr, g);

            try {
                while (!r.EOF)
                {
                    r.Read();
                }
            } finally {
                r.Close();
            }
        }
Example #11
0
        public override TestResult Run()
        {
            RelaxngValidatingReader v = new RelaxngValidatingReader(
                new XmlTextReader(new StringReader(Validator.Text)),
                Validator.RelaxSchema);

            try {
                while (v.Read())
                {
                }
            } catch (RelaxngException e) {
                return(new TestResult(Severity.Error, e.Message));
            }

            return(new TestResult(Severity.Success));
        }
Example #12
0
        public void RelaxNGBasicDataTests_Basic()
        {
            DataStoreUtility.DataStoreSetup();

            string filePath = Path.Combine(DataStore.Instance.AD.CurrentDataFolder.Path, Constants.StorageXMLFileName);

            XmlReader instance = new XmlTextReader(filePath);

            XmlReader grammar = new XmlTextReader(rngStream);

            RelaxngValidatingReader reader =
                new RelaxngValidatingReader(instance, grammar);

            while (reader.Read())
            {
                // TODO parse based on NodeType
            }
        }
Example #13
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="xmlReader"></param>
 public void Validate(XmlReader xmlReader)
 {
     using (var reader = new RelaxngValidatingReader(xmlReader, relaxPattern))
     {
         try
         {
             while (!reader.EOF)
             {
                 reader.Read();
             }
         }
         catch (RelaxngException ex)
         {
             RaiseValidationError(ex, OpdsValidationErrorLevel.OpdsInvalid);
         }
         catch (XmlException ex)
         {
             RaiseValidationError(ex, OpdsValidationErrorLevel.XmlInvalid);
         }
     }
 }
Example #14
0
        static public string GetFirstValidationError(string rngFile, string document)
        {
            RelaxngValidatingReader reader = new RelaxngValidatingReader(
                new XmlTextReader(document), new XmlTextReader(rngFile));

            reader.ReportDetails = true;
            string lastGuy = "";

            try
            {
                while (!reader.EOF)
                {
                    reader.Read();
                    lastGuy = reader.Name;
                }
            }
            catch (Exception e)
            {
                return(String.Format("{0}\r\nError near: {1} {2} '{3}'",
                                     e.Message, lastGuy, reader.Name, reader.Value));
            }
            return(null);
        }
Example #15
0
        // --- Methods ---
        public ScriptManifestValidationResult Validate(string path)
        {
            try {
                XmlTextReader           xmlReader = new XmlTextReader(path);
                RelaxngValidatingReader validator;

                using (Stream resourceStream
                           = Plug.New("resource://mindtouch.deki.script.check/MindTouch.Deki.Script.ExtensionManifest.rnc").Get().ToStream()) {
                    using (TextReader source = new StreamReader(resourceStream)) {
                        RncParser      parser  = new RncParser(new NameTable());
                        RelaxngPattern pattern = parser.Parse(source);
                        validator = new RelaxngValidatingReader(xmlReader, pattern);
                    }
                }
                while (validator.Read())
                {
                    // do nothing, errors will be reported through exceptions
                }
            } catch (Exception e) {
                return(new ScriptManifestValidationResult(true, e.Message));
            }

            return(new ScriptManifestValidationResult());
        }
Example #16
0
    static void RunTest()
    {
        foreach (DirectoryInfo di in new DirectoryInfo(@"relax-ng").GetDirectories())
        {
            XmlTextReader xtr = null;
            FileInfo      fi  = new FileInfo(di.FullName + "/i.rng");
            // Invalid grammar case:
            if (fi.Exists)
            {
                xtr = new XmlTextReader(fi.FullName);
                try {
                    RelaxngPattern.Read(xtr).Compile();
                    Console.WriteLine("Expected error: " + di.Name);
                } catch (RelaxngException ex) {
                } catch (XmlException ex) {
                } catch (ArgumentNullException ex) {
                } catch (UriFormatException ex) {
                } catch (Exception ex) {
                    Console.WriteLine("Unexpected error type : " + di.Name + " : " + ex.Message);
                } finally {
                    xtr.Close();
                }
                continue;
            }

            // Valid grammar case:
            xtr = new XmlTextReader(di.FullName + "/c.rng");
            RelaxngPattern p = null;
            try {
                p = RelaxngPattern.Read(xtr);
                p.Compile();
            } catch (Exception ex) {
                Console.WriteLine("Invalidated grammar: " + di.Name + " : " + ex.Message);
                continue;
            } finally {
                xtr.Close();
            }


            // Instance validation
            foreach (FileInfo inst in di.GetFiles("*.xml"))
            {
                try {
                    RelaxngValidatingReader vr = new RelaxngValidatingReader(new XmlTextReader(inst.FullName), p);
                    if (skip_error)
                    {
                        vr.InvalidNodeFound += RelaxngValidatingReader.IgnoreError;
                    }
                    while (!vr.EOF)
                    {
                        vr.Read();
                    }
                    if (inst.Name.IndexOf("i.") >= 0 && !skip_error)
                    {
                        Console.WriteLine("Incorrectly validated instance: " + di.Name + "/" + inst.Name);
                    }
                } catch (RelaxngException ex) {
                    string path = di.Name + "/" + inst.Name;
                    if (skip_error)
                    {
                        Console.WriteLine("Failed to skip error : " + path + ex.Message);
                    }
                    if (inst.Name.IndexOf("i.") >= 0)
                    {
                        continue;
                    }
                    Console.WriteLine("Invalidated instance: " + path + " : " + ex.Message);
                }
            }
        }
    }
Example #17
0
 ///<summary>
 /// Validate the LIFT file contained in the XmlTextReader.  Progress reporting is
 /// supported.
 ///</summary>
 static private string GetSchemaValidationErrors(string path, IValidationProgress progress)
 {
     using (XmlTextReader documentReader = new XmlTextReader(path))
     {
         progress.Status = "Checking for Schema errors...";
         var resourceStream = typeof(LiftMultiText).Assembly.GetManifestResourceStream("Palaso.Lift.Validation.lift.rng");
         if (resourceStream == null)
         {
             throw new Exception();
         }
         RelaxngValidatingReader reader = new RelaxngValidatingReader(
             documentReader, new XmlTextReader(resourceStream));
         reader.ReportDetails = true;
         string lastGuy = "lift";
         int    line    = 0;
         int    step    = 0;
         if (progress != null)
         {
             try
             {
                 if (documentReader.BaseURI != null)
                 {
                     string sFilePath = documentReader.BaseURI.Replace("file://", "");
                     if (sFilePath.StartsWith("/"))
                     {
                         // On Microsoft Windows, the BaseURI may be "file:///C:/foo/bar.lift"
                         if (sFilePath.Length > 3 &&
                             Char.IsLetter(sFilePath[1]) && sFilePath[2] == ':' && sFilePath[3] == '/')
                         {
                             sFilePath = sFilePath.Substring(1);
                         }
                     }
                     System.IO.FileInfo fi = new System.IO.FileInfo(sFilePath);
                     // Unfortunately, XmlTextReader gives access to only line numbers,
                     // not actual file positions while reading.  A check of 8 Flex
                     // generated LIFT files showed a range of 43.9 - 52.1 chars per
                     // line.  The biatah sample distributed with WeSay has an average
                     // of only 23.1 chars per line.  We'll compromise by guessing 33.
                     // The alternative is to read the entire file to get the actual
                     // line count.
                     int maxline = (int)(fi.Length / 33);
                     if (maxline < 8)
                     {
                         progress.MaxRange = 8;
                     }
                     else if (maxline < 100)
                     {
                         progress.MaxRange = maxline;
                     }
                     else
                     {
                         progress.MaxRange = 100;
                     }
                     step = (maxline + 99) / 100;
                 }
                 if (step <= 0)
                 {
                     step = 1;
                 }
             }
             catch
             {
                 step = 100;
             }
         }
         try
         {
             while (!reader.EOF)
             {
                 // Debug.WriteLine(reader.v
                 reader.Read();
                 lastGuy = reader.Name;
                 if (progress != null && reader.LineNumber != line)
                 {
                     line = reader.LineNumber;
                     if (line % step == 0)
                     {
                         progress.Step(1);
                     }
                 }
             }
         }
         catch (Exception e)
         {
             if (reader.Name == "version" && (lastGuy == "lift" || lastGuy == ""))
             {
                 return(String.Format(
                            "This file claims to be version {0} of LIFT, but this version of the program uses version {1}",
                            reader.Value, LiftVersion));
             }
             string m = string.Format("{0}\r\nError near: {1} {2} '{3}'", e.Message, lastGuy, reader.Name, reader.Value);
             return(m);
         }
         return(null);
     }
 }
Example #18
0
        public static string RelaxNGValidate(string xml, string rngFile)
        {
            string r = "\r\n";

            // Files must exist.
            if (!File.Exists(rngFile))
            {
                return("Schema file not found.");
            }

            // Grammar.
            RelaxngPattern p = null;

            if (Path.GetExtension(rngFile).ToUpper() == ".RNG")
            {
                XmlTextReader xtrRng = new XmlTextReader(rngFile);
                try
                {
                    p = RelaxngPattern.Read(xtrRng);
                    p.Compile();
                }
                catch (Exception ex1)
                {
                    return("Schema file has invalid grammar:" + r
                           + rngFile + r + ex1.Message);
                }
                finally
                {
                    xtrRng.Close();
                }
            }
            else
            if (Path.GetExtension(rngFile).ToUpper() == ".RNC")
            {
                var trRnc = new StreamReader(rngFile);
                try
                {
                    p = RncParser.ParseRnc(trRnc);
                    p.Compile();
                }
                catch (Exception ex1)
                {
                    return("Schema file has invalid grammar:" + r
                           + rngFile + r + ex1.Message);
                }
                finally
                {
                    trRnc.Close();
                }
            }
            else
            {
                return("Unknown schema file extension: " + Path.GetExtension(rngFile));
            }

            byte[]       byteArray = Encoding.Default.GetBytes(xml);
            MemoryStream stream    = new MemoryStream(byteArray);

            // Validate instance.
            XmlTextReader           xtrXml = new XmlTextReader(stream);
            RelaxngValidatingReader vr     = new RelaxngValidatingReader(xtrXml, p);

            try
            {
                while (!vr.EOF)
                {
                    vr.Read();
                }
                // XML file is valid.
                return("");
            }
            catch (RelaxngException ex2)
            {
                // XML file not valid.
                return(ex2.Message);
            }
            catch (Exception ex3)
            {
                // XML file not well-formed.
                return(ex3.Message);
            }
            finally
            {
                vr.Close();
                xtrXml.Close();
            }
        }