I'm still hoping ideas on the second question, but I can answer the first part of the question. Perhaps I should split that into a separate question.
[EDIT: figured out 2nd question as well. See below.]
I was somehow masking an obscure error: System.InvalidOperationException: Cannot change conformance checking to Document. Make sure the ConformanceLevel in XmlReaderSettings is set to Auto for wrapping scenarios.
Resolving that leads to the working code below. It also has some other changes, but the keys is settings.ConformanceLevel = ConformanceLevel.Auto.
<SqlFunction()> _
Public Shared Function ResetSchema(ByVal targetNameSpace As SqlString, ByVal schemaUri As SqlString) As Boolean
Dim result As Boolean
Try
schemaSet = New XmlSchemaSet
schemaSet.Add(targetNameSpace, schemaUri)
schemaSet.Compile()
settings = New XmlReaderSettings
settings.Schemas = schemaSet
settings.ValidationType = ValidationType.Schema
settings.ConformanceLevel = ConformanceLevel.Auto
settings.ValidationFlags = settings.ValidationFlags Or XmlSchemaValidationFlags.ReportValidationWarnings
AddHandler settings.ValidationEventHandler, AddressOf ValidationCallBack
result = True
Catch
'result = False
End Try
ResetSchema = result
End Function
Public Shared Function ValidateWithXsd(ByVal xml As SqlXml) As SqlBoolean
Try
isValid = True
Dim reader As XmlReader = xml.CreateReader
Dim validatingReader As XmlReader = XmlReader.Create(reader, settings)
While validatingReader.Read
End While
Catch ex As Exception
Throw ex
Finally
ValidateWithXsd = isValid
End Try
End Function
Private Shared Sub ValidationCallBack(ByVal sender As Object, ByVal args As ValidationEventArgs)
isValid = False
End Sub
As for the second question, I moved the actual validation to a 2nd friend class. I still keep the schema cached, but can do set based operation with the function.
I won't post the changes to the primary class as they are pretty trivial, but the new class:
Friend Class SchemaValidator
Private isValid As Boolean
Friend Function Validate(ByVal baseReader As XmlReader, ByVal settings As XmlReaderSettings) As Boolean
Try
isValid = True
AddHandler settings.ValidationEventHandler, AddressOf ValidationEventHandler
Dim validatingReader As XmlReader = XmlReader.Create(baseReader, settings)
While validatingReader.Read
End While
Catch ex As Exception
Throw ex
Finally
RemoveHandler settings.ValidationEventHandler, AddressOf ValidationEventHandler
Validate = isValid
End Try
End Function
Private Sub ValidationEventHandler(ByVal sender As Object, ByVal args As ValidationEventArgs)
isValid = False
End Sub
End Class