Errors and COM Output Parameters
The code snippet below (from the AutomateXMLSpy example) shows how to handle errors and COM output parameters. The method XMLSpy.ActiveDocument.IsValid(ref strErrorText, ref nErrorNumber, ref errorData) uses output parameters that are used, in the code snippet below, to generate an error-message text.
The AutomateXMLSpy example (see the file Form1.cs) is located in the C# subfolder of the API Examples folder:
Windows 7, Windows 8, Windows 10, Windows 11 | C:\Users\<username>\Documents\ |
You can compile and run the project from within Visual Studio 2012/2013/2015/2017/2019/2022.
Code snippet
// Handler for button "Validate"
private void validate_Click(object sender, EventArgs e)
{
// COM errors are returned to C# as exceptions. We use a try/catch block to handle them.
try
{
// Method 'IsValid' is one of the few functions that uses output parameters
// Use 'object' type for these parameters
object strErrorText = "";
object nErrorNumber = 0;
object errorData = null;
if (!XMLSpy.ActiveDocument.IsValid(ref strErrorText, ref nErrorNumber, ref errorData))
{
// The COM call succeeded but the document is not valid
// A detailed description of the problem is returned in strErrorText, nErrorNumber and errorData
listBoxMessages.Items.Add("Document " + XMLSpy.ActiveDocument.Name + " is not valid.");
listBoxMessages.Items.Add("\tErrorText : " + strErrorText);
listBoxMessages.Items.Add("\tErrorNumber: " + nErrorNumber);
listBoxMessages.Items.Add("\tElement : " + (errorData != null ? ((XMLSpyLib.XMLData)errorData).TextValue : "null"));
}
else
{
// The COM call succeeded and the document is valid
listBoxMessages.Items.Add("Document " + XMLSpy.ActiveDocument.Name + " is valid.");
}
}
catch (Exception ex)
{
// The COM call was not successful
// Probably no application instance has been started or no document is open.
listBoxMessages.Items.Add("Error validating active document: " + ex.Message);
}
}