A few months ago I came upon the need to validate some XML in an orchestration against one of the schemas in the project. So, I turned to the wisdom of the net and came accross the desired information in the Arch hacker's BizTalk Blog:
http://thearchhacker.blogspot.com/2004/09/cool-xsd-validation-function-for.html
The code he wrote was functional and elegant. I especailly like the way he referenced the schema in its assembly using the schema strong name. Nice. But alas, I was upgrading this project to BizTalk 2006 (and this .Net Framework 2.0) and was notified that:
warning CS0618: 'System.Xml.XmlValidatingReader' is obsolete: 'Use XmlReader created by XmlReader.Create() method using appropriate XmlReaderSettings instead. http://go.microsoft.com/fwlink/?linkid=14202
So in an attempt to rid myself of the annoying compiler warnings, I set out in search of an updated version to no avail. It was time to crack the Framework docs and do it myself. So here it is:
public static bool ValidateDocument( XmlDocument businessDocument, string schemaStrongName, ref string xmlValidationException )
{
// Constants
const int PARTS_IN_SCHEMA_STRONG_NAME = 2;
const int PART_CLASS_NAME = 0;
const int PART_QUALIFIED_ASSEMBLY_NAME = 1;
// Parse schema strong name
string[] assemblyNameParts = schemaStrongName.Split( new char[] { ',' }, PARTS_IN_SCHEMA_STRONG_NAME );
string className = assemblyNameParts[PART_CLASS_NAME].Trim();
string fullyQualifiedAssemblyName = assemblyNameParts[PART_QUALIFIED_ASSEMBLY_NAME].Trim();
// Load assembly
Assembly schemaAssembly = Assembly.Load( fullyQualifiedAssemblyName );
// Create instance of the BTS schema in order to get to the actual schemas
Type schemaType = schemaAssembly.GetType( className );
Microsoft.XLANGs.BaseTypes.SchemaBase btsSchemaCollection =
( Microsoft.XLANGs.BaseTypes.SchemaBase ) Activator.CreateInstance( schemaType );
// Set up XML reader and validate document
XmlReaderSettings ReaderSettings = new XmlReaderSettings();
ReaderSettings.ValidationType = ValidationType.Schema;
ReaderSettings.Schemas.Add(btsSchemaCollection.Schema);
XmlReader reader = XmlReader.Create(new StringReader(businessDocument.OuterXml), ReaderSettings);
try
{
while( reader.Read() ) {}
}
catch(XmlSchemaException xse)
{
xmlValidationException = string.Format("XML Validation Error: {0}", xse.Message);
return false;
}
catch(Exception ex)
{
xmlValidationException = string.Format("Unexpected Error: {0}", ex.Message);
return false;
}
// success
xmlValidationException = String.Empty;
return true;
}
And it is called from an expression shape as was previously documented in the Arch hacker's blog:
ValidateDocument( myBtsMessage, myBtsMessage( BTS.SchemaStrongName ) );