Sending Soap with Attachments (SwA) using BizTalk – Part 2

This is a continuation to my previous article.

Create a WCF service which can send the SOAP message with attachment.

1. Create a standard wcf service ( I guess this shouldnt be an issue )

2. Below is a very rough idea of what should go inside the service implementation

string endpoint = “”
ResponseObject resp = null;
using(var cf = new ChannelFactory<IService>(endpoint)
var channel = cf.CreateChannel();
using(var scope = new OperationContextScope(IContextChannel)channel))
OperationContext.Current.OutgoingMessageProperties[SWAEncoderConstants.AttachmentProperty] = attachment.ToSimpleXmlUTF8();
resp = channel.method(request).response;

I will write a detailed post with a sample implementation later.


2013 in review

The stats helper monkeys prepared a 2013 annual report for this blog.

Here’s an excerpt:

A New York City subway train holds 1,200 people. This blog was viewed about 7,700 times in 2013. If it were a NYC subway train, it would take about 6 trips to carry that many people.

Click here to see the complete report.

An error occurred while receiving the HTTP response to http://…….svc. This could be due to the service endpoint binding not using the HTTP protocol. This could also be due to an HTTP request context being aborted by the server (possibly due to the service shutting down). See server logs for more details

My solution is to have a wcf service which can accept a pdf/text file streamed as byte array in one of the elements.

I had a BizTalk orchestration exposed as a wcf service. The schema has a content element which is set as xs:base64binary. So the wcf service expects the service consumer to convert the text/pdf document into a byte array and send it to my service. When you expose services which expects one of the element content as byte array, the memory size of the message significanly increases.

You will get the below error when a client sends a bigger file, say 12 mb pdf file.

An error occurred while receiving the HTTP response to http://…&#8230;.svc.
This could be due to the service endpoint binding not using the HTTP protocol. This could also be due to an HTTP
request context being aborted by the server (possibly due to the service shutting down). See server logs for more

To troubleshoot this, add wcf tracing in web.config

  1. In the web.config add the below under <configuration> section

    <source name=”System.ServiceModel” 
    switchValue=”Information, ActivityTracing”
    <add name=”traceListener” 
    initializeData= “c:\log\Traces.svclog” />

    Make sure to create the “Log” folder under “C” Drive or feel free to configure a different location to save the logs.

  2. Use the WCF Trace viewer tool to view the Traces.

a. Open the tool from the path C:\Program files(x86)\Microsoft SDKs\Windows\v7.0A\Bin
b. Open the trace file.
c. You would be able to locate the exception details in the Description pane on the right side.
d. You would see the System.ServiceModel.CommunicationException thrown and the exception message would be “Maximum request length exceeded”

This conforms that the issue we have is related to the request length.

Two things must be done to resolve the issue.

  1. In the BizTalk receive location, set the Maximum receive message size property to 2,147,483,647. This can be found in Adapter properties > Binding section.

  2. In the web.config, add the below line under <system.web> section

<httpRuntime maxRequestLength=”2147483647″ />

Please bear in mind that setting the Maximum value for request length might solve the problem, but this can easily be expolited in case of a DOS attack.

Schematron validation using XSLT using BizTalk – Part 3

This post is a continuation to the Schematron validation using XSLT in BizTalk blog series

The source code for this blog post has been uploaded in the below location
Now that you know about the basic schematron XSLT implementation, we will now see how we can achieve this in BizTalk.

High Level steps for BizTalk implementation

1. Create the schematron-output schema which we discussed in the last section
2. Create a custom pipeline component( Any Category type, so that we can have the component in any of the pipeline stage, except disassembling stage)
a. Implement Custom UI functionality so that we can have the Schematron rules as property. We are also going to add a property to hold the physical path to the conformance1-5.xsl. So it is important that the conformance1-5.xsl and the skeleton1-5.xsl is placed in appropriate directories.
b. If we have any schematron errors, then we will promote the message type with the schematron output message type.
3. Apply an inbound map in the receive port if transformation is required(Optional Step)

Detailed Steps for BizTalk implementation
1. I will skip the creation of schematron-output schema .
2. Custom Pipeline component

The pipeline component has three parts
a. The component itself
b. Custom UI form
c. Custom UI Type Editor class

The custom UI is a windows form which can accept the XSLT and store it in a XML serialized format. This is pretty useful, as we can load the XSLT stylesheet from the pipeline component property itself.

The code for Custom UI and Type Editor Class are self-explanatory and I will proceed with the actual transformation logic.

public IBaseMessage Execute(IPipelineContext pc, IBaseMessage inMsg)
if (Enabled)
ReadOnlySeekableStream seekableStm = new ReadOnlySeekableStream(inMsg.BodyPart.Data);

VirtualStream vs = null;

XmlTextReader stylesheet = new XmlTextReader(new StringReader(this.SchematronXSLT));

XmlTextReader conformanceStylesheet = new XmlTextReader(this.ConformanceXSLTPath);

// Load transform
BTSXslTransform trans = new BTSXslTransform();

XmlTextReader inputReader = new XmlTextReader(seekableStm);

//Create memory stream to hold transformed data.
vs = new VirtualStream(VirtualStream.MemoryFlag.AutoOverFlowToDisk);

//Preform transform
trans.ScalableTransform(stylesheet, null, vs, new XmlUrlResolver(), false);

vs.Seek(0, SeekOrigin.Begin);

XmlTextReader validatingXSLReader = new XmlTextReader(vs);
BTSXslTransform ValidatingTrans = new BTSXslTransform();

VirtualStream vs1 = new VirtualStream(VirtualStream.MemoryFlag.AutoOverFlowToDisk);

ValidatingTrans.ScalableTransform(inputReader, null, vs1, new XmlUrlResolver(), false);
vs1.Seek(0, SeekOrigin.Begin);
XmlDocument outputDoc = new XmlDocument();
if (outputDoc.SelectNodes(“//failed-assert”).Count > 0)
vs1.Seek(0, SeekOrigin.Begin);
inMsg.BodyPart.Data = vs1;
inMsg.Context.Promote(“MessageType”, “;, “;);
inMsg.BodyPart.Data.Position = 0;
seekableStm.Seek(0, SeekOrigin.Begin);
inMsg.BodyPart.Data = seekableStm;

catch (Exception ex)
System.Diagnostics.EventLog.WriteEntry(this.Name, ex.Message);

return inMsg;


Key things from the above code is I have used BTSXslTransform class to do the transformation and used VirtualStream to hold the transformed data. One nice feature about VirtualStream is that it is initialized with VirtualStream.MemoryFlag.AutoOverFlowToDisk i.e. when the internal memory is not sufficient to hold the transformed data, it will be stored to the disk. This is greatly useful in case of large messages.

Other than that, the code is quite simple to follow.


So far, we have seen the development of the schematron XSLT infrastructure and how to use it with BizTalk. This part of the tutorial is only a beginner and we will see more complex schematron in the upcoming posts.

Schematron validation using XSLT in BizTalk – Part 2

This post is a continuation to the Schematron validation using XSLT in BizTalk blog series

The source code for this blog post has been uploaded in the below location

So, How to do schematron validation using XSLT in BizTalk?

High level steps
1. Define the schematron rules in the .sch file
2. Use XSLT processor(MSXSL) and pass the Rules.sch file and the Conformance1-5.xsl file
3. STEP 2 would produce a Validating XSLT file, let’s call Valdating.xsl.
4. Use XSLT processor and pass the XML document and Validating.xsl. This would produce the final schematron results.

Pros of using this approach
1. There is no dependency with any third party library
2. The schematron skeleton XSLT template that we use is ISO standard, open source and is used widely in various companies.
3. Complete use of XSLT functions like document(), key() etc.

Cons of using this approach
1. Compared to the XPATH implementation it is slower, as there is an additional step of preparing the validating XSLT.
2. The initial setup is a bit complex, but when you have setup the Pipeline components and required schemas and Schematron Skeleton XSLTs, then it is easier.

Detailed Implementation
We have seen the high level steps and now it’s time to get down deep into the implementation details.
Before going into the implementation, let’s take a scenario, so that we can use that for our implementation
A manufacturing company has adopted an e-Commerce solution by integrating its services with its client. Its clients can send purchase order by placing the files in a FILE folder. The Manufacturing Company is responsible for validating the structure of the message before processing the Purchase Order.
We need to have a consistent approach for validating the semantics of the schema and report any errors. We will go step in step in implementing this solution.

1. Define the PurchaseOrder schema

Below is the high level structure of the schema.


Please also check the schema file from the below link.

Okay, we have defined the schema. The next step would be writing schematron rules.

2. Define schematron rules

To start with, we will define quite simple schematron rules.

Schematron schema has a predefined structure. Below is the skeleton structure of the schematron.

<?xml version=”1.0″ encoding=”UTF-8″?>

<sch:schema xmlns:sch=”; xmlns:xs=”; queryBinding=”xslt2″

We will add the namespace to it.

<sch:ns uri=” ” prefix=”nms” />

And we will add a very simple rule

<sch:pattern name=”Check Existence”>

<sch:rule context=”nms:PurchaseOrder”>

<sch:assert test=”nms:Id”>PurchaseOrder Id is missing or cannot be empty</sch:assert>


Let’s put it together.

<?xml version=”1.0″ encoding=”UTF-8″?>

<sch:schema xmlns:sch=”; xmlns:xs=”; queryBinding=”xslt2″ >

<sch:ns uri=” ” prefix=”nms” />

<sch:pattern name=”Check Existence”>

<sch:rule context=”nms:PurchaseOrder”>

<sch:assert test=”nms:Id”>PurchaseOrder Id is missing</sch:assert>



That’s it; we have got a very simple schematron schema.

3. Define schema to populate error information
When we run the XSLT processor with conformance1-5.xslt, we will get a schematron-output message with all the error information. We will use the same structure to define a schema, so that we can apply an inbound map to transform this into a more meaningful message or transform this to a client response message.


4. Download Schematron Skeleton XSLTs

The conformance1-5.xsl and the skeleton1-5.xsl has been provided by Academia Sinica Computing Center, Taiwan

As already said, the above XSLTs are open source and can be downloaded from

5. Download MSXSL 3.0 for testing purpose
Download the command line utility MSXSL 3.0 for testing purpose. In the actual development we will use the BTSXslTransform class to apply the XSLTs.

6. Generate Validating XSLT using XSLT processor and Skeleton XSLTs

Execute the below to generate the validating XSLT

msxsl -o PO-Validating.xsl PurchaseOrder.sch conformance1-5.xsl

Below is the auto generated Validating XSLT

<?xml version=”1.0″ encoding=”UTF-16″ standalone=”yes”?>

<xsl:stylesheet version=”1.0″ nms:dummy-for-xmlns=”” xmlns:xsl=”; xmlns:sch=”; xmlns:nms=” “>

<xsl:output method=”xml” omit-xml-declaration=”no” standalone=”yes” indent=”yes” />

<xsl:template match=”*|@*” mode=”schematron-get-full-path”>

<xsl:apply-templates select=”parent::*” mode=”schematron-get-full-path” />


<xsl:if test=”count(. | ../@*) = count(../@*)”>@</xsl:if>

<xsl:value-of select=”name()” />


<xsl:value-of select=”1+count(preceding-sibling::*[name()=name(current())])” />



<xsl:template match=”/”>

<schematron-output title=”” schemaVersion=”” phase=”#ALL”>

<ns uri=” ” prefix=”nms” />

<active-pattern name=”Check Existence”>

<xsl:apply-templates />


<xsl:apply-templates select=”/” mode=”M1″ />



<xsl:template match=”nms:PurchaseOrder” priority=”4000″ mode=”M1″>

<fired-rule id=”” context=”nms:PurchaseOrder” role=”” />


<xsl:when test=”nms:Id” />


<failed-assert id=”” test=”nms:Id” role=””>

<xsl:attribute name=”location”>

<xsl:apply-templates select=”.” mode=”schematron-get-full-path” />


<text>PurchaseOrder Id is missing</text>




<xsl:apply-templates mode=”M1″ />


<xsl:template match=”text()” priority=”-1″ mode=”M1″ />

<xsl:template match=”text()” priority=”-1″ />


Below is a sample PurchaseOrder instance

<?xml version=”1.0″ encoding=”UTF-8″?>

<!–Sample XML file generated by XMLSpy v2011 (–>

<nms:PurchaseOrder xsi:schemaLocation=” PurchaseOrder.xsd” xmlns:nms=”; xmlns:xsi=””&gt;












































If you inspect the xml message, you can see that the ID field is missing. We will now run the XSLT processor against this xml instance and the Validating XSLT

​Below is the command

msxsl -o PO-Result.xml PO-Test.xml PO-Validating.xsl

And below is the contents of PO-Result.xml

<?xml version=”1.0″ encoding=”UTF-8″ standalone=”yes”?>

<schematron-output title=”” schemaVersion=”” phase=”#ALL” xmlns:sch=”; xmlns:nms=”″&gt;

<ns uri=” ” prefix=”nms” />

<active-pattern name=”Check Existence”/>

<fired-rule id=”” context=”nms:PurchaseOrder” role=”” />

<failed-assert id=”” test=”nms:Id” role=”” location=”/nms:PurchaseOrder[1]”>

<text>PurchaseOrder Id is missing</text>



What we have done and achieved so far

1. Defined a schematron rules
2. Defined a Schematron Output schema
3. Executed the XSLT processor and got the results.

If you want to have schematron functionality for another flow, all you have to do is create the step 1, i.e. define schematron rules and that’s it, the rest all are the same.