I'm using the hl7-dotnetcore package to create new HL7 messages. After creating them I want to serialize some of them to strings and some of them to bytes. I created an empty .NET Core console project with the following snippet
internal class Program
{
private static void Main(string[] args)
{
Message mdmMessage = new Message();
mdmMessage.AddSegmentMSH(
"sendingApplication",
"sendingFacility",
"receivingApplication",
"receivingFacility",
string.Empty,
"MDM^T02",
$"Id{DateTime.Now.Ticks}",
"P",
"2.6");
HL7Encoding hl7Encoding = new HL7Encoding();
//################################
// Add a field e.g. TXA.1
Segment txaSegment = new Segment("TXA", hl7Encoding);
txaSegment.AddNewField("1", 1);
mdmMessage.AddNewSegment(txaSegment);
//################################
// Add a component field e.g. PID.5.1
Segment pidSegment = new Segment("PID", hl7Encoding);
Field patientNameField = new Field(hl7Encoding);
Component pidFamilyNameComponent = new Component("Doe", hl7Encoding);
patientNameField.AddNewComponent(pidFamilyNameComponent, 1);
pidSegment.AddNewField(patientNameField, 5);
mdmMessage.AddNewSegment(pidSegment);
try
{
string messageString = mdmMessage.SerializeMessage(true); // This will throw an exception
}
catch (Exception exception)
{
Console.WriteLine($"Serialization failed:{Environment.NewLine}{exception.Message}");
}
try
{
byte[] messageBytes = mdmMessage.GetMLLP(true); // This will throw an exception
}
catch (Exception exception)
{
Console.WriteLine($"Conversion failed:{Environment.NewLine}{exception.Message}");
}
Console.ReadLine();
}
}
Unfortunately I get two exceptions with
"Failed to validate the message with error - No Message Found"
Does someone know what I'm missing here?
Both Message.SerializeMessage
and Message.GetMLLP
accept boolean argument validateMessage
which behaves in a bit weird way: if true then original message, that is message you passed to the constructor of Message
or set via HL7Message
property, is being validated. Since you do not have original message but building a new one (without using mentioned property or constructor) - there is nothing to validate, and empty message is treated as invalid, so you see the error. So just pass false
to avoid this unnecessary in your case validation:
string messageString = mdmMessage.SerializeMessage(false);
byte[] messageBytes = mdmMessage.GetMLLP(false);