public void DenyUnrestricted() { // can we call everything without a SecurityException ? XmlSchemaException xe = new XmlSchemaException(String.Empty, null); Assert.AreEqual(0, xe.LineNumber, "LineNumber"); Assert.AreEqual(0, xe.LinePosition, "LinePosition"); Assert.IsNotNull(xe.Message, "Message"); Assert.IsNull(xe.SourceSchemaObject, "SourceSchemaObject"); Assert.IsNull(xe.SourceUri, "SourceUri"); }
private static void HandleBadSchemaFile(Exception ex, string dirPath) { if (ex is XmlSchemaException) { XmlSchemaException ex2 = (XmlSchemaException)ex; string text = (ex2.SourceUri != null) ? ex2.SourceUri : string.Empty; AirSyncDiagnostics.TraceError <string, string>(ExTraceGlobals.RequestsTracer, null, "Schema file with path '{0}' is corrupted. Exception '{1}'", text, ex2.ToString()); throw new AirSyncFatalException(EASServerStrings.SchemaFileCorrupted(text), "SchemaFileCorrupted", false, ex2); } AirSyncDiagnostics.TraceError <string, string>(ExTraceGlobals.RequestsTracer, null, "Unable to compile the XSD SchemaSet under the folder '{0}'. Exception '{1}' ", dirPath, (ex == null) ? string.Empty : ex.ToString()); throw new AirSyncFatalException(EASServerStrings.SchemaUnknownCompilationError(dirPath), "SchemaUnknownCompilationError", true, ex); }
public void validationHandler(object sender, ValidationEventArgs args) { XmlSchemaException xse = args.Exception; // TODO dunno how xse encode the filename throw new Exception(String.Format( "{0}:{1}:{2}:{3}", d_filename, xse.LineNumber, xse.LinePosition, args.Message)); // d_nrMessages +=1; // if (d_nrMessages == 3) // throw new Exception("Stopped at 3"); }
internal void ValidationCallback(object Sender, ValidationEventArgs e) { switch (e.Severity) { case XmlSeverityType.Error: this.exception = e.Exception; break; case XmlSeverityType.Warning: Log.Warning(e.Message, this.objectId); break; } }
private void Initialize(XmlSchemaException ex, string defaultSourcePath) { _hasLineInfo = true; _lineNumber = ex.LineNumber; _linePosition = ex.LinePosition; if (String.IsNullOrEmpty(ex.SourceUri)) { _source = (String.IsNullOrEmpty(ex.Source)) ? ((defaultSourcePath == null) ? "" : defaultSourcePath) : ex.Source; } else { _source = ex.SourceUri; } }
public static SbbInstructionSet LoadFromFile(string filename) { XmlReaderSettings settings = new XmlReaderSettings(); settings.Schemas.Add(GetInstructionSetSchema()); settings.ValidationType = ValidationType.Schema; settings.ValidationFlags = XmlSchemaValidationFlags.ProcessIdentityConstraints | XmlSchemaValidationFlags.ReportValidationWarnings; XmlSchemaException firstException = null; settings.ValidationEventHandler += delegate(object sender, ValidationEventArgs args) { if (args.Severity == XmlSeverityType.Warning) { logger.DebugFormat("Warning from Xml Validations: {0}", args.Message); } else { if (firstException == null) { firstException = args.Exception; } logger.Error(string.Format("Error from Xml Validation at Line {0} Pos {1}", args.Exception.LineNumber, args.Exception.LinePosition), args.Exception); } }; var res = new SbbInstructionSet(); using (var stream = System.IO.File.OpenRead(filename)) { using (XmlReader reader = XmlReader.Create(stream, settings)) { XmlSerializer ser = new XmlSerializer(res.GetType()); res = ser.Deserialize(reader) as SbbInstructionSet; } } if (firstException != null) { throw new ApplicationException(string.Format("Could not load instruction files due to XML validation error at Line {0} Position {1}: {2}", firstException.LineNumber, firstException.LinePosition, firstException.Message), firstException); } return(res); }
internal static void HandleSchemaValidationError(object sender, ValidationEventArgs args, Collection <MetadataConversionError> errors) { MetadataConversionError item = null; if ((args.Exception != null) && (args.Exception.SourceUri != null)) { XmlSchemaException exception = args.Exception; item = new MetadataConversionError(System.ServiceModel.SR.GetString("SchemaValidationError", new object[] { exception.SourceUri, exception.LineNumber, exception.LinePosition, exception.Message })); } else { item = new MetadataConversionError(System.ServiceModel.SR.GetString("GeneralSchemaValidationError", new object[] { args.Message })); } if (!errors.Contains(item)) { errors.Add(item); } }
static internal void HandleSchemaValidationError(object sender, ValidationEventArgs args, Collection <MetadataConversionError> errors) { MetadataConversionError warning = null; if (args.Exception != null && args.Exception.SourceUri != null) { XmlSchemaException ex = args.Exception; warning = new MetadataConversionError(string.Format(SRServiceModel.SchemaValidationError, ex.SourceUri, ex.LineNumber, ex.LinePosition, ex.Message)); } else { warning = new MetadataConversionError(string.Format(SRServiceModel.GeneralSchemaValidationError, args.Message)); } if (!errors.Contains(warning)) { errors.Add(warning); } }
/// <summary> /// Validation callback for a validating XML reader. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="args">Any data pertinent to the event.</param> private void HandleValidation(object sender, ValidationEventArgs args) { if (args.Severity == XmlSeverityType.Error) { XmlSchemaException ex = args.Exception; XmlReader xmlReader = (XmlReader)sender; if (!NamespaceParserRegistry.GetSchemas().Contains(xmlReader.NamespaceURI) #if NET_2_0 && ex is XmlSchemaValidationException #endif ) { // try wellknown parsers bool registered = NamespaceParserRegistry.RegisterWellknownNamespaceParserType(xmlReader.NamespaceURI); if (registered) { throw new RetryParseException(); } } #if !NET_2_0 // ignore validation errors for well-known 'xml' namespace. This seems to be a bug in net 1.0 + 1.1 if (ex.Message.IndexOf("http://www.w3.org/XML/1998/namespace:") > -1) { return; } #endif throw ex; } else { #region Instrumentation if (log.IsWarnEnabled) { log.Warn( "Ignored XML validation warning: " + args.Message, args.Exception); } #endregion } }
private void HandleValidation(object sender, ValidationEventArgs args) { XmlReader reader = (XmlReader)sender; // WORKAROUND: known bug in .NET framework 1.x // TODO: verify for 2.0 if (args.Message.IndexOf("http://www.w3.org/XML/1998/namespace:base") >= 0) { s_log.DebugFormat( "Ignoring the following schema validation error in {0}, because it is considered a known .NET framework bug: {1}", reader.BaseURI, args.Message); return; } IXmlLineInfo lineInfo = sender as IXmlLineInfo; XmlSchemaValidationErrorInfo errorInfo = new XmlSchemaValidationErrorInfo(args.Message, reader.BaseURI, lineInfo, args.Severity); _messages.Add(errorInfo); if (args.Severity == XmlSeverityType.Error) { s_log.Error(errorInfo); ++_errors; if (_failOnError) { throw args.Exception; } if (_errors == 0) { _firstError = errorInfo; _firstException = args.Exception; } } else { s_log.Warn(errorInfo); ++_warnings; } }
private static bool HandleXmlSchemaException(Exception exception, int tab = 0) { string s = new string(' ', tab); XmlSchemaException ex = exception as XmlSchemaException; if (null != ex) { Console.WriteLine($"{s}{Path.GetFileName(ex.SourceUri)}: {ex.Message}"); HandleXmlSchemaException(ex.InnerException, tab + 2); return(true); } XmlException ex2 = exception as XmlException; if (null != ex2) { Console.WriteLine($"{s}{Path.GetFileName(ex2.SourceUri)}: {ex2.Message}"); HandleXmlSchemaException(ex2.InnerException, tab + 2); return(true); } return(false); }
private MapFile ReadMapFile(XmlReader reader) { try { return(Wrap(GetMapFileSerializer().Deserialize(reader))); } catch (InvalidOperationException ex) { XmlException xmlException = ex.InnerException as XmlException; if (xmlException != null) { // the innerException contains detail error message throw xmlException; } XmlSchemaException schemaException = ex.InnerException as XmlSchemaException; if (schemaException != null) { if (schemaException.LineNumber > 0) { // append line/position to the message throw new XmlSchemaException(String.Format(CultureInfo.CurrentCulture, WCFModelStrings.ReferenceGroup_AppendLinePosition, schemaException.Message, schemaException.LineNumber, schemaException.LinePosition), schemaException, schemaException.LineNumber, schemaException.LinePosition); } else { throw schemaException; } } // It's something we can't handle, throw it. throw; } }
//Hook up validaton callback public void ValidationCallback(object sender, ValidationEventArgs args) { if (args.Severity == XmlSeverityType.Error) { _output.WriteLine("ERROR: "); bErrorCallback = true; XmlSchemaException se = args.Exception as XmlSchemaException; errorLineNumbers[errorCount] = se.LineNumber; errorCount++; _output.WriteLine("Exception Message:" + se.Message + "\n"); if (se.InnerException != null) { _output.WriteLine("InnerException Message:" + se.InnerException.Message + "\n"); } else { _output.WriteLine("Inner Exception is NULL\n"); } } }
internal static string WarningDetails(XmlSchemaException exception, string message) { XmlSchemaObject sourceSchemaObject = exception.SourceSchemaObject; if ((exception.LineNumber == 0) && (exception.LinePosition == 0)) { return(GetSchemaItem(sourceSchemaObject, null, message)); } string targetNamespace = null; if (sourceSchemaObject != null) { while (sourceSchemaObject.Parent != null) { sourceSchemaObject = sourceSchemaObject.Parent; } if (sourceSchemaObject is XmlSchema) { targetNamespace = ((XmlSchema)sourceSchemaObject).TargetNamespace; } } return(System.Web.Services.Res.GetString("SchemaSyntaxErrorDetails", new object[] { targetNamespace, message, exception.LineNumber, exception.LinePosition })); }
internal static Exception CreateValidationException(XmlSchemaException exception, string message) { XmlSchemaObject sourceSchemaObject = exception.SourceSchemaObject; if ((exception.LineNumber == 0) && (exception.LinePosition == 0)) { throw new InvalidOperationException(GetSchemaItem(sourceSchemaObject, null, message), exception); } string targetNamespace = null; if (sourceSchemaObject != null) { while (sourceSchemaObject.Parent != null) { sourceSchemaObject = sourceSchemaObject.Parent; } if (sourceSchemaObject is System.Xml.Schema.XmlSchema) { targetNamespace = ((System.Xml.Schema.XmlSchema)sourceSchemaObject).TargetNamespace; } } throw new InvalidOperationException(Res.GetString("XmlSchemaSyntaxErrorDetails", new object[] { targetNamespace, message, exception.LineNumber, exception.LinePosition }), exception); }
/// <summary> /// Handler method for validation errors. Throws an exception when an error is encountered /// </summary> /// <param name="sender">Sender of the validation event</param> /// <param name="args">Validation error arguments</param> private static void ValidationHandler(object sender, System.Xml.Schema.ValidationEventArgs args) { switch (args.Severity) { case System.Xml.Schema.XmlSeverityType.Error: XmlSchemaException xmlSchemaException = args.Exception as XmlSchemaException; if (xmlSchemaException != null) { throw new InvalidOperationException("'" + xmlSchemaException.Message + "' at line " + xmlSchemaException.LineNumber + " position " + xmlSchemaException.LinePosition); } else { throw new InvalidOperationException("'" + args.Message + "'"); } case System.Xml.Schema.XmlSeverityType.Warning: if (args.Message == "No DTD found.") // Unfortunately there does not seem to be a typed exception for not having a DTD, so need to test the message :-( { throw new InvalidOperationException("'" + args.Message + "'"); } // Else: Do nothing break; } }
public ValidationEventHandler CreateValidationHandler() { return(delegate(object sender, ValidationEventArgs e) { XmlSchemaException schemaError = e.Exception; int lineNumber = schemaError.LineNumber + _firstLineNumber - 1; int linePosition = schemaError.LinePosition + _indents[schemaError.LineNumber - 1]; string errorMessage = string.Format( "{0}({1},{2}): {3} WG{4:0000}: {5}", _file.FullName, lineNumber, linePosition, e.Severity.ToString().ToLower(), (int)InputError.InvalidSchema, schemaError.Message); Console.Error.WriteLine(errorMessage); if (e.Severity == XmlSeverityType.Error) { _hasFailed = true; } }); }
internal ValidationEventArgs( XmlSchemaException ex , XmlSeverityType severity ) : base() { this.ex = ex; this.severity = severity; }
internal ValidationEventArgs( XmlSchemaException ex ) : base() { this.ex = ex; severity = XmlSeverityType.Error; }
protected virtual void Read(XmlReader reader) { //Add the attributes that should only be used during read phase //These attributes are kept for compatibility with previous versions //They should never been used during write process var attrs = new ReadOnlyAttributes(); attrs.Build(); // Create an instance of the XmlSerializer specifying type and read-attributes. try { validationExceptions.Clear(); XmlSerializer serializer = new XmlSerializer(typeof(TestSuiteXml), attrs); // Use the Deserialize method to restore the object's state. TestSuite = (TestSuiteXml)serializer.Deserialize(reader); } catch (InvalidOperationException ex) { if (ex.InnerException is XmlException) { XmlSchemaException xmlSchemaException; if (ex.InnerException.Message.Contains("For security reasons DTD is prohibited")) { xmlSchemaException = new XmlSchemaException("DTD is prohibited. To activate it, set the flag allow-dtd-processing to true in the config file associated to this test-suite"); } else { var regex = new Regex(@"Line (\d+), position (\d+).$"); var match = regex.Match(ex.InnerException.Message); if (match.Success) { int line = 0; Int32.TryParse(match.Groups[1].Value, out line); int position = 0; Int32.TryParse(match.Groups[2].Value, out position); xmlSchemaException = new XmlSchemaException(ex.InnerException.Message, ex, line, position); } else { xmlSchemaException = new XmlSchemaException(ex.InnerException.Message); } } Console.WriteLine(xmlSchemaException.Message); validationExceptions.Add(xmlSchemaException); } else { ParseCascadingInvalidOperationException(ex.InnerException as InvalidOperationException); } } if (validationExceptions.Count > 0) { var message = "The test suite is not valid. Check with the XSD."; message += string.Format(" {0} error{1} {2} been found during the validation of the test-suite:\r\n" , validationExceptions.Count , validationExceptions.Count > 1 ? "s" : string.Empty , validationExceptions.Count > 1 ? "have" : "has"); foreach (var error in validationExceptions) { message += string.Format("\tAt line {0}: {1}\r\n", error.LineNumber, error.Message); } throw new ArgumentException(message); } }
/// <summary> /// Create an instance of an xsdValidation Info /// </summary> /// <param name="message"></param> /// <param name="exception"></param> public XsdValidationInfo(string message, XmlSchemaException exception) { Message = message; Exception = exception; }
internal ValidationEventArgs(XmlSchemaException ex, XmlSeverityType severity) : base() { this.ex = ex; this.severity = severity; }
internal ValidationEventArgs(XmlSchemaException ex) : base() { this.ex = ex; severity = XmlSeverityType.Error; }
private string FormatPosition(XmlSchemaException xmlSchemaException) { return(string.Format(" @ line:{0} column:{1}", xmlSchemaException.LineNumber, xmlSchemaException.LinePosition)); }
/// <summary> /// Координаты ошибки /// </summary> private string FormatLineInfo(XmlSchemaException xmlSchemaException) { return(string.Format(" Строка:{0} Позиция:{1}", xmlSchemaException.LineNumber, xmlSchemaException.LinePosition)); }
internal static CompilerError XmlSchemaValidationError(XmlSchemaException ex, LexicalInfo location) { return(Instantiate("MCE0018", new LexicalInfo(location.FileName, location.Line, location.Column, 0), ex.Message)); }
public async Task <ValidationFinishedEventArgs> ValidateXmlStreamAgainstSchemaAsync(Stream stream, XmlSchemaSet schemaSet, bool reportErrorListAtTheEndOfValidation, CancellationToken cancellationToken) { var stopWatch = new Stopwatch(); stopWatch.Start(); try { xmlValidationUtils.ValidateXmlSchemaSet(schemaSet); } catch (Exception e) { stopWatch.Stop(); return(new ValidationFinishedEventArgs { ElapsedTime = stopWatch.Elapsed, ErrorCount = 1, Errors = new List <ValidationErrorEventArgs> { new ValidationErrorEventArgs(new XmlSchemaException("The XML Schema Set is not valid. See inner exception for more details.", e)) } }); } if (!streamValidator.StreamIsValid(stream)) { stopWatch.Stop(); return(new ValidationFinishedEventArgs { ElapsedTime = stopWatch.Elapsed, ErrorCount = 1, Errors = new List <ValidationErrorEventArgs> { new ValidationErrorEventArgs(new Exception("The XML Stream is not valid. It is either closed or could not be seeked.")) } }); } stream.Seek(0, SeekOrigin.Begin); var errorList = new List <ValidationErrorEventArgs>(); var errorCount = 0; var readerSettings = xmlReaderSettingsFactory.CreateXmlSettings(); readerSettings.Async = true; readerSettings.ValidationEventHandler += (s, e) => { errorCount++; OnErrorOccurred(s, new ValidationErrorEventArgs(e), cancellationToken); }; if (reportErrorListAtTheEndOfValidation) { readerSettings.ValidationEventHandler += (s, e) => { errorList.Add(new ValidationErrorEventArgs(e)); }; } if (!schemaSet.IsCompiled) { try { schemaSet.Compile(); } catch (Exception e) { errorCount++; errorList.Add(new ValidationErrorEventArgs(e)); return(new ValidationFinishedEventArgs { ElapsedTime = stopWatch.Elapsed, ErrorCount = errorCount, Errors = errorList }); } } readerSettings.Schemas = schemaSet; try { using (var reader = XmlReader.Create(stream, readerSettings)) { while (await reader.ReadAsync()) { // Do nothing. Just read and let the reader validate things. } } } catch (Exception e) { errorCount++; var exc = new XmlSchemaException(e.Message, e); if (reportErrorListAtTheEndOfValidation) { errorList.Add(new ValidationErrorEventArgs(exc)); } OnErrorOccurred(this, new ValidationErrorEventArgs(exc, XmlSeverityType.Error), cancellationToken); } finally { stopWatch.Stop(); } var result = new ValidationFinishedEventArgs { ElapsedTime = stopWatch.Elapsed, ErrorCount = errorCount, Errors = errorList }; OnFinishedValidating(this, result, cancellationToken); return(result); }
/// <summary> /// Extracts the message of the specified <see cref="Exception"/>, prepending the error /// location if it is an <see cref="XmlException"/> or <see cref="XmlSchemaException"/>. /// </summary> /// <param name="exception"> /// The <see cref="Exception"/> object whose error message to extract.</param> /// <returns> /// A <see cref="String"/> containing the error location (if available) and <see /// cref="Exception.Message"/> of the specified <paramref name="exception"/>, or an empty /// string if <paramref name="exception"/> is a null reference.</returns> /// <remarks><para> /// <b>GetXmlMessage</b> provides a convenient way to extract the additional error /// information provided by <see cref="XmlException"/> and <see cref="XmlSchemaException"/>, /// namely the error location returned by the <see cref="XmlException.LineNumber"/> and <see /// cref="XmlException.LinePosition"/> properties. /// </para><para> /// If the specified <paramref name="exception"/> is of either type and specifies a /// <b>LineNumber</b> greater than zero, <b>GetXmlMessage</b> prepends a localized error /// location statement to the <see cref="Exception.Message"/> specified by <paramref /// name="exception"/>. Otherwise, only the <b>Message</b> is returned.</para></remarks> public static string GetXmlMessage(Exception exception) { if (exception == null) { return(""); } // XML exceptions provide error location int lineNumber = -1, linePosition = -1; string intro = ""; XmlException xe = exception as XmlException; if (xe != null) { intro = Strings.XmlError; lineNumber = xe.LineNumber; linePosition = xe.LinePosition; } else { XmlSchemaException xse = exception as XmlSchemaException; if (xse != null) { intro = Strings.XmlSchemaError; lineNumber = xse.LineNumber; linePosition = xse.LinePosition; } } // create location statement if (lineNumber > 0) { // specify error type (XML or XML Schema) StringBuilder sb = new StringBuilder(intro); // append error line if available sb.AppendFormat(Strings.FormatAtLine, lineNumber); // append error column if available if (linePosition > 0) { sb.AppendFormat(Strings.FormatAtColumn, linePosition); } // conclude error type line sb.Append('.'); // append message if available if (!String.IsNullOrEmpty(exception.Message)) { sb.Append(Environment.NewLine); sb.Append(Environment.NewLine); sb.Append(exception.Message); } // return message with location return(sb.ToString()); } // just return message return(exception.Message); }
public XmlValidator(string ObjectID) { this.objectId = ObjectID; this.exception = null; }
private static XsdValidationException ToXsdValidationException(XmlSchemaException exception) { return(new XsdValidationException(exception.Message, exception.SourceUri, exception.LineNumber, exception.LinePosition)); }
public UblDocumentValidationError(XmlSchemaException exception, string message, XmlSeverityType severity) { Severity = severity; Message = message; Exception = exception; }
public ValidationError(XmlSchemaException exception) { Initialize(exception.LineNumber, exception.LinePosition, exception.Message, exception, XmlValidationStatus.Critical); }