private void bTestOutputCreation_Click(object sender, RoutedEventArgs e) { CreateSampleDocument(); XsdValidator validator = new XsdValidator { }; if (!validator.ValidateDocument(schemaVersion1, tbOldDoc.Text)) { throw new Exception("Old document invalid"); } Transform(); validator = new XsdValidator { }; if (!validator.ValidateDocument(schemaVersion2, tbNewDoc.Text)) { throw new Exception("New document invalid"); } SaveRef(null); MessageBox.Show("Created OK", "Created OK", MessageBoxButton.OK, MessageBoxImage.Information); }
public virtual void BeforeExecution() { if (!string.IsNullOrEmpty(RequestContractInUri) && !string.IsNullOrEmpty(Context.RequestBody)) { XsdValidator.ValidateXml(Context.RequestBody, new[] { RequestContractInUri }, this.GetType()); } }
public virtual void AfterExecution() { if (!string.IsNullOrEmpty(ResponseContractOutUri) && !string.IsNullOrEmpty(Context.ResponseBody)) { XsdValidator.ValidateXml(Context.ResponseBody, new[] { ResponseContractOutUri }, this.GetType()); } }
/// <summary> /// The deserialize EDUGAME questions. /// </summary> /// <param name="format"> /// The format. /// </param> /// <param name="filePath"> /// The file path. /// </param> /// <param name="schemaPath"> /// The schema path. /// </param> /// <returns> /// The <see cref="EdugameQuestions"/>. /// </returns> /// <exception cref="FileNotFoundException"> /// File not found /// </exception> /// <exception cref="SerializationException"> /// Serialized exception /// </exception> /// <exception cref="ArgumentException"> /// Argument exception /// </exception> private EdugameQuestions DeserializeEdugameQuestions(FormatsEnum format, string filePath, string schemaPath) { if (!System.IO.File.Exists(filePath) || !System.IO.File.Exists(schemaPath)) { throw new FileNotFoundException(); } string rawData = System.IO.File.ReadAllText(filePath); string data = format == FormatsEnum.WebEx ? HttpUtility.HtmlDecode(rawData) : rawData; string validationError; if (!XsdValidator.ValidateXmlAgainsXsd(data, schemaPath, out validationError)) { throw new SerializationException(validationError); } EdugameQuestions questions = this.ImportFromString(data, format); if (string.IsNullOrEmpty(data) || questions == null || questions.Questions == null || questions.Questions.Count == 0) { throw new ArgumentException(); } return(questions); }
public void ValidateSokeresultatUtvidet() { var xsdValidator = new XsdValidator(Directory.GetCurrentDirectory()); List <string> validationErrors = new List <string>(); string sokeresultat = File.ReadAllText(Directory.GetCurrentDirectory() + "/TestData/Responses/sokeresultatUtvidet.xml"); xsdValidator.ValidateArkivmeldingSokeresultatUtvidet(sokeresultat, validationErrors); foreach (var validationError in validationErrors) { Console.Out.WriteLine(validationError); } Assert.True(validationErrors.Count == 0); }
private void bValidateNew_Click(object sender, RoutedEventArgs e) { XsdValidator validator = new XsdValidator(); bool valid = validator.ValidateDocument(schemaVersion2, tbNewDoc.Text); if (valid) { ExolutioMessageBox.Show("Validation", "Valid", "The new version is valid."); } else { ExolutioErrorMsgBox.Show("ERROR - The new version is not valid!", validator.ErrorMessage); } }
public void ShouldValidateXsdSchemaSuccessfully() { // Arrange string xmlContent = XmlTestData.GetValidXmlContent(); string xsdContent = XmlTestData.GetXsdMarkup(); IXsdValidator xsdValidator = new XsdValidator(); // Act var validationResult = xsdValidator.Validate(xmlContent, xsdContent); // Assert validationResult.IsValid.Should().BeTrue(); }
// Constructor public MainPage() { this.InitializeComponent(); XmlSerializerHelperDemo demo = new XmlSerializerHelperDemo(); demo.Start(); string inputString = "This is a test string"; XsdValidator x = new XsdValidator(); //var result = x.Validate("", ""); var serialized = XmlSerializerHelper.Current.SerializeToXml(inputString); var deserialized = XmlSerializerHelper.Current.DeserializeFromXml <string>(serialized); }
protected static void ValidateXmlAndThrowIfInvalid(string xml) { var xsdValidator = new XsdValidator(); xsdValidator.Validate(xml); string validationWarnings; xsdValidator.Validate(xml, out validationWarnings); if (!string.IsNullOrEmpty(validationWarnings)) { throw new InvalidXmlException(validationWarnings); } }
public void ShouldFailToValidateXsdSchema() { // Arrange string xmlContent = XmlTestData.GetInvalidXmlContent(); string xsdContent = XmlTestData.GetXsdMarkup(); IXsdValidator xsdValidator = new XsdValidator(); // Act var validationResult = xsdValidator.Validate(xmlContent, xsdContent); // Assert validationResult.IsValid.Should().BeFalse(); validationResult.Errors.Should().HaveCount(1); validationResult.Errors.ElementAt(0).Message.Should().Be("The element 'Root' has invalid child element 'Child3'. List of possible elements expected: 'Child2'."); }
static void Main(string[] args) { IXsdValidator xsdValidator = new XsdValidator(); var xsdContent = XmlTestData.GetXsdMarkup(); { Console.WriteLine("// Demo: Validate a valid XML file against an XSD schema"); string validXmlContent = XmlTestData.GetValidXmlContent(); var validationResult = xsdValidator.Validate(validXmlContent, xsdContent); Console.WriteLine($"validationResult.IsValid: {validationResult.IsValid}"); Console.WriteLine($"validationResult.Errors ({validationResult.Errors.Count()}):\n{FormatValidationErrors(validationResult)}"); Console.WriteLine(); } { Console.WriteLine("// Demo: Validate an invalid XML file against an XSD schema"); string invalidXmlContent = XmlTestData.GetInvalidXmlContent(); var validationResult = xsdValidator.Validate(invalidXmlContent, xsdContent); Console.WriteLine($"validationResult.IsValid: {validationResult.IsValid}"); Console.WriteLine($"validationResult.Errors ({validationResult.Errors.Count()}):\n{FormatValidationErrors(validationResult)}"); Console.WriteLine(); } Console.WriteLine("// Demo: Serialize/deserialize string to XML"); const string inputString = "This is a test string"; Console.WriteLine($"inputString:\n{inputString}"); Console.WriteLine(); var serialized = XmlSerializerHelper.Current.SerializeToXml(inputString); Console.WriteLine($"SerializeToXml:\n{serialized}"); Console.WriteLine(); var deserialized = XmlSerializerHelper.Current.DeserializeFromXml <string>(serialized); Console.WriteLine($"DeserializeFromXml:\n{deserialized}"); Console.WriteLine(); Console.ReadKey(); }
private static int Main(string[] args) { Directory.SetCurrentDirectory(AppDomain.CurrentDomain.BaseDirectory); var showHelp = false; var dryRun = false; var listSchemas = false; var filePath = default(string); var xsdPath = "Resources/Schemas"; var verbose = false; var p = new OptionSet { { "Help" }, { "h|help", "Display this message", x => showHelp = true }, { "d|dry-run", "Test how parameters are parsed", x => dryRun = true }, { "l|list-schemas", "List supported XSD-schemas", x => listSchemas = true }, { "Validation" }, { "f|file=", "(Required) Path to file", x => filePath = x }, { "x|xsd-path=", "(Optional) Path to XSD-schemas", x => xsdPath = x }, { "v|verbose", "(Optional) (Resource intensive) Detailed output", x => verbose = true } }; var list = p.Parse(args); if (list.Count > 0) { Console.WriteLine($"Unknown arguments: {string.Join(", ", list)}\n"); p.WriteOptionDescriptions(Console.Out); Console.WriteLine(); return(1); } if (showHelp) { p.WriteOptionDescriptions(Console.Out); Console.WriteLine(); return(0); } if (dryRun) { Console.WriteLine("Parsed parameters:"); Console.WriteLine($"- file: {Path.GetFullPath(filePath)}"); Console.WriteLine($"- xsd-path: {Path.GetFullPath(xsdPath)}"); Console.WriteLine($"- verbose: {verbose}"); Console.WriteLine(); return(0); } var schemas = SchemaLoader.LoadDirectory(xsdPath); if (listSchemas) { var namespaces = schemas.Schemas() .OfType <XmlSchema>() .Select(s => s.TargetNamespace) .OrderBy(ns => ns); var sb = new StringBuilder(); sb.AppendLine("Supported xsd-schemas:"); foreach (var ns in namespaces) { sb .Append(" - ") .Append(ns) .AppendLine(); } Console.WriteLine(); Console.WriteLine(sb); return(0); } if (filePath == default) { Console.WriteLine("ERROR: A file must be specified"); return(1); } // todo more error handling // todo better output if (verbose) { bool hasError; try { var xDoc = XDocument.Load(filePath); hasError = XsdValidator.Validate(xDoc, schemas, Console.Out); } catch (Exception ex) { Console.WriteLine(ex.Message); hasError = true; } return(hasError ? 1 : 0); } try { XsdValidator.ValidateFile(filePath, schemas, true); } catch (AggregateException aex) { var sb = new StringBuilder(); sb.AppendLine("Error in xml:"); foreach (var iex in aex.InnerExceptions) { sb.Append(" - ") .AppendLine(iex.Message); } Console.WriteLine(sb); return(1); } catch (Exception ex) { Console.WriteLine($"Error in xml {ex.Message}"); return(1); } return(0); }
public static void Main() { var catalogueXml = "../../XMLs/catalogue.xml"; // Task 2. Write program that extracts all different artists which are found in the catalog.xml. Console.WriteLine(CustomDomParser.GetAlbumsCount(catalogueXml)); // Task 3. Implement the previous using XPath. Console.WriteLine(XPath.GetAlbumsCount(catalogueXml)); // Task 4. Using the DOM parser write a program to delete from catalog.xml all albums having price > 20. var strippedCatalogueDom = CustomDomParser.DeleteAlbumsHigherThanSpecifiedPrice(catalogueXml, 20); // Task 5. Write a program, which using XmlReader extracts all song titles from catalog.xml. Console.WriteLine(StaxParser.ExtractSongTitles(catalogueXml)); // Task 6. Rewrite the same using XDocument and LINQ query. Console.WriteLine(LinqToXml.ExtractSongTitles(catalogueXml)); // Task 7. In a text file we are given the name, address and phone number of given person(each at a single line). var personDataTxt = "../../XMLs/person-id-info.txt"; var personXml = "../../XMLs/person-id.xml"; LinqToXml.CreateXmlDocFromTxt(personDataTxt, personXml); // Task 8. Write a program, which (using XmlReader and XmlWriter) reads the file catalog.xml and creates // the file album.xml, in which stores in appropriate way the names of all albums and their authors. var albumXml = "../../XMLs/albums.xml"; StaxParser.ExtractAlbums(catalogueXml, albumXml); // Task 9. Write a program to traverse given directory and write to a XML file its contents together with all subdirectories and files. // Set to traverse the Desktop. Try it out with any directory. var targetDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop); var outputUrlXmlWriter = "../../XMLs/directory-xml-writer.xml"; DirectoryIterator.TraverseXmlWriter(targetDirectory, outputUrlXmlWriter); // Task 10. Rewrite the last exercises using XDocument, XElement and XAttribute. // Set to traverse the Desktop. Try it out with any directory. var outputUrlXDoc = "../../XMLs/directory-xdoc.xml"; DirectoryIterator.TraverseXDoc(targetDirectory, outputUrlXDoc); // Task 11. Write a program, which extract from the file catalog.xml the prices for all albums, published 5 years ago or earlier. Console.WriteLine(XPath.ExtractPricesByYear(catalogueXml, 15)); // Task 12. Rewrite the previous using LINQ query. Console.WriteLine(LinqToXml.ExtractPricesByYear(catalogueXml, 15)); // Task 14. Write a C# program to apply the XSLT stylesheet transformation on the file catalog.xml using the class XslTransform. var catalogueXslt = "../../XMLs/catalogue-template.xslt"; var catalogueHtml = "../../XMLs/catalogue.html"; XsltConvertor.GenerateHtmlPageForCatalogueXml(catalogueXml, catalogueXslt, catalogueHtml); // Task 16. Using Visual Studio generate an XSD schema for the file catalog.xml. var catalogueXsd = "../../XMLs/catalogue.xsd"; Console.WriteLine(XsdValidator.ValidateXml(catalogueXml, catalogueXsd)); Console.WriteLine(XsdValidator.ValidateXml(personXml, catalogueXsd)); }
/// <summary> /// The validate against schema. /// </summary> /// <param name="xml"> /// The xml. /// </param> /// <returns> /// The <see cref="bool"/>. /// </returns> private bool ValidateAgainstVCFProfileSchema(string xml) { var xsdFileName = HttpContext.Current.Server.MapPath(Content.xsd.vcfProfile_xsd); return(XsdValidator.ValidateXmlAgainsXsd(xml, xsdFileName, out this.validationError)); }
public IEnumerable <ValidationError> ValidateFile(string filePath) { var rtn = new List <ValidationError>(); var file = new FileInfo(filePath); // Check that the file exists first, there's no point in continuing if it doesn't exist if (!file.Exists) { rtn.Add(new ValidationError { Description = "The file does not exist", ErrorSeverity = ErrorSeverity.Error }); return(rtn); } IEnumerable <FileInfo> configFiles = new FileInfo[0]; try { if (file.Directory != null) { configFiles = file.Directory.GetFiles("Folder.config", SearchOption.TopDirectoryOnly); } } catch (UnauthorizedAccessException) { // We may not have been allowed to read the directory, in which // case we will get an UnauthorizedAccessException thrown. } catch (IOException) { // We may not have been allowed to read the directory, in which // case we will get an UnauthorizedAccessException thrown. } var currentFolderConfig = configFiles.Any() ? Serializer.Deserialize <FolderConfig>(File.ReadAllText(configFiles.First().FullName)) : null; if (currentFolderConfig == null || !currentFolderConfig.Schemas.Any()) { return(rtn); } var validator = new XsdValidator(); foreach (var schema in currentFolderConfig.Schemas) { if (Path.IsPathRooted(schema)) { validator.AddSchema(schema); } else { if (file.Directory != null) { validator.AddSchema(Path.Combine(file.Directory.FullName, schema)); } } } validator.IsValid(filePath); rtn.AddRange(validator.Errors.Select(e => new ValidationError { Description = e, ErrorSeverity = ErrorSeverity.Error })); rtn.AddRange(validator.Warnings.Select(e => new ValidationError { Description = e, ErrorSeverity = ErrorSeverity.Warning })); return(rtn); }