public static ServiceResult ApplyDataEncoding(ServiceMessageContext context, QualifiedName dataEncoding, ref object value)
{
// check if nothing to do.
if (QualifiedName.IsNull(dataEncoding) || value == null)
{
return ServiceResult.Good;
}
// check for supported encoding type.
if (dataEncoding.NamespaceIndex != 0)
{
return StatusCodes.BadDataEncodingUnsupported;
}
bool useXml = dataEncoding.Name == DefaultXml;
if (!useXml && dataEncoding.Name != DefaultBinary)
{
return StatusCodes.BadDataEncodingUnsupported;
}
try
{
// check for array of encodeables.
IList<IEncodeable> encodeables = value as IList<IEncodeable>;
if (encodeables == null)
{
// check for array of extension objects.
IList<ExtensionObject> extensions = value as IList<ExtensionObject>;
if (extensions != null)
{
// convert extension objects to encodeables.
encodeables = new IEncodeable[extensions.Count];
for (int ii = 0; ii < encodeables.Count; ii++)
{
if (ExtensionObject.IsNull(extensions[ii]))
{
encodeables[ii] = null;
continue;
}
IEncodeable element = extensions[ii].Body as IEncodeable;
if (element == null)
{
return StatusCodes.BadTypeMismatch;
}
encodeables[ii] = element;
}
}
}
// apply data encoding to the array.
if (encodeables != null)
{
ExtensionObject[] extensions = new ExtensionObject[encodeables.Count];
for (int ii = 0; ii < extensions.Length; ii++)
{
extensions[ii] = Encode(context, encodeables[ii], useXml);
}
value = extensions;
return ServiceResult.Good;
}
// check for scalar value.
IEncodeable encodeable = value as IEncodeable;
if (encodeable == null)
{
ExtensionObject extension = value as ExtensionObject;
if (extension == null)
{
return StatusCodes.BadDataEncodingUnsupported;
}
encodeable = extension.Body as IEncodeable;
}
if (encodeable == null)
{
return StatusCodes.BadDataEncodingUnsupported;
}
// do conversion.
value = Encode(context, encodeable, useXml);
return ServiceResult.Good;
}
catch (Exception e)
{
return ServiceResult.Create(e, StatusCodes.BadTypeMismatch, "Could not convert value to requested format.");
}
}