Friday, August 1, 2014

Modify BizTalk Message using C# or External DLL in Orchestration

In many situations, the Mapper available with BizTalk Server or XPath functions might not be sufficient to construct the Required Message in BizTalk Server.

In these scenarios, we can use an external library and construct the message there using C# code.

Scenario:

You have a schema in your BizTalk Project. You receive a message in a receive folder and pass this message to an External Library, update the message and send it back to BizTalk. Save the updated message to a new location.

Solution:

There are two possible ways of doing this:

Option 1: Create an equivalent class file for the Schema and pass the message as class object to the External DLL

Option 2: Pass the message contents as an XML Document to the External DLL and modify the message using XMLDocument, XLinq or any other technique.

Option 1:

1. Create a new BizTalk Project and add a Sample schema Schema1 as shown below.


2. Use the XSD.EXE utility to convert the schema created above into a serializable class. For this, Go to Visual Studio Command Prompt and give the following Command at the directory where Schema is located.

XSD Schema1.xsd /c /o:c:\

Note: Refer this MSDN article for more details on xsd.exe

3. Create a Class Library Project and add the above class file to the Project. Now we have an equivalent class file for the schema.

4. Create a Static method in the Class that updates the Received Object and sends it back using C #as shown below.


5. Build it and add a reference of this class library to the BizTalk Project.

6. Add an orchestration to the BizTalk Project and create two messages of the Type Schema1

7. Add a Receive Shape and Message Constructor shape and a send shape and complete the orchestration as shown below.


8. Add the below code in the Message assignment shape.

Message_2 = ClassLib.Root.GetClassReference(Message_1);

9. This will call the GetClassReference and the Message Message_1 will be automatically serialized into the class Object. Within the method, schema elements and attributes can be accessed just like class properties.

10. To Test this project, deploy both BizTalk project and Class Library to GAC and put an input file, you will see that the values are updated.

Option 2:

The same can also be achieved by passing the Message Contents as an XML object as given below.

Variable_1 = Message_1;
Variable_1.LoadXml(ClassLib.Root.GetClassReferenceUsingXML(Variable_1.OuterXml));
Message_3 = Variable_1;

Note: Variable_1 is of tpye XMLDocument.

Now you should have a method in the External Library that modifies the message using XML Operations. A sample is given below.


While testing schemas with more than 50 Elements, it has been found out that using XMLDocument to modify the Contents (Option 2) was very much faster than using Class Objects (Option 1).
Post a Comment