BizTalk EDI: Creating batching configuration in code

For outbound EDI batching, we have to create Batch Configuration in Party Configuration and set Filter Criteria about what messages should constitute one batch. But what if Filter Criteria is dynamic or we have too many batches to configure

here is code snippet to create batch configuration through API

 var builder = new SqlConnectionStringBuilder("DATA SOURCE="BTSSQLServer;Initial Catalog=BizTalkMgmtDb;
Integrated Security=SSPI;");
            using (var tmpCtx = TpmContext.Create(builder))
                var agreement = (from p in tmpCtx.Agreements where p.Name == AgreementName select p).FirstOrDefault();
                if (agreement == null)//create agreement if does not exist.
                    string Sender = ConfigurationManager.AppSettings["Sender"] ?? "SenderPartyName";
                    string Receiver = ConfigurationManager.AppSettings["Receiver"] ?? "ReceiverPartyName";
                    var OneWayAgreement = agreement.GetOnewayAgreement(Sender, Receiver); 
                    var firstBatch = OneWayAgreement.GetBatches()[0]; // first batch config is used as template
                    var newBatch = OneWayAgreement.CreateBatch(BatchName);
                    FilterPredicate predicate = firstBatch.GetFilterPredicate();
                    predicate.Groups[0].Statements[0].Value = "FilterRHS";
// this SQL insert is required to Activate the batch config
                    using (var cmd = new SqlCommand(@" INSERT INTO [dbo].[PAM_Control]
                                                                       ,[SenderPartyName], ReceiverPartyName, AgreementName)
                                                                    SELECT 0 as EDIMessageType
                                                                  ,'EdiBatchActivate' as 'ActionType'
                                                                  ,GetDate() as 'ActionDateTime'
                                                                  ,0 as 'UsedOnce' 
                                                                  ," + newBatch.Id + @" as [BatchId]
                                                                  ,'" + BatchName + @"' as [BatchName], '"+ Sender +@"', '"+
 Receiver +@"', '" + AgreementName + "'", new SqlConnection(builder.ConnectionString)))
Posted in BizTalk, C#. Tags: , . Leave a Comment »

BizTalk EDI: AK2 missing from 997 ACK


We can correlate a 997 with corresponding EDI request message by looking at AK2 segment (AK2:02 = ST02 in request), but by default BizTalk generates AK2 only for failed transactions, thus makes it difficult to correlate 997 with corresponding request in Async setup. To bring AK2 in 997, enable from Parties configuration


Posted in BizTalk. 1 Comment »

BizTalk: ‘Unspecified error’ when starting Host Instance


I was stuck with this error when starting BizTalk host instances after database connectivity was lost and resumed,


event log:

A failure occurred when executing a Windows service request.
Service request: Start
BizTalk host name: BizTalkServerApplication
Windows service name: BTSSvc$BizTalkServerApplication
Additional error information:
Error code: 0x80131604
Error source: mscorlib
Error description: Exception has been thrown by the target of an invocation.


one of possible reasons (among other is a reported issue in BizTalk – and MS provides CU for it) is a new section in BizTalk config file that is not declared in machine.config. In my case, I added a new config section to define appSettings configuration keys  – but I forgot to update machine.config first



Notes from E-Myth Revisited


The E-Myth Revisited: Why Most Small Businesses Don’t Work and What to Do About It

If your business depends on you, you don’t own a business – you have a job. (and you’re working for a lunatic)
The purpose of going into business is to get free of a job so you can create jobs for other people.

A business that "gets small again" is a business reduced to the level of its owner’s personal resistance to change – its owner’s comfort zone. (works and waits for something positive to happen)

Your business is not your life.

Your business is something apart from you, with its own rules and its own purposes. An organism that will live or die according to how well it performs its sole function : find and keep customers.
The primary purpose of your business is to serve your life (not vice-versa)

Typical owner of a small business prefers highly skilled people because he believes they make his job easier – he can simply leave the work to them.
Unfortunately then the business grows to depend on the whims and moods of its people.
If they’re in the mood, the job gets done. If they’re not, it doesn’t.
In this kind of business, "How do I motivate my people?" comes up : "How do I keep them in the mood?"
It is literally impossible to create a consistent result in a business that depends on extraordinary people.
When you intentionally build your business around the skills of ordinary people, you will be forced to ask the difficult questions about how to produce a result without the extraordinary ones.
You will be forced to find a system that leverages your ordinary people to the point where they can produce extraordinary results over and over again.

Most small businesses are started by people who are skilled at something and who enjoy doing that thing. When these people strike out on their own, they tend to continue doing the work they are skilled at, and ignore the overarching aspects of business. Without clear goals and quantification benchmarks, they soon find themselves overworked, understaffed, and eventually broke.

Every business owner needs to simultaneously be an entrepreneur, a manager and a technician. The technician is the worker-bee, the manager makes sure operations and finances run smoothly. The entrepreneur formulates the goals, and steers the business in the direction needed to reach those goals. Of these three personalities, the entrepreneur is key- -without it, the technician will work to death or bankruptcy. As the business grows, the business owner will need to draw away from the technician work and manager work and delegate this work to others.


BizTalk ESB: Exception Handling in Orchestration

here is how to use Exception Handling framework from Orchestration

This post is about couple of errors that consumed lots of time to figure out when testing an implementation that uses ESB Exception Handling framework.

in windows event log (BizTalk ESB Toolkit 2.1):

Object reference not set to an instance of an object.

Source: Microsoft.Practices.ESB.ExceptionHandling.PipelineComponents.ProcessFault

Method: Microsoft.BizTalk.Message.Interop.IBaseMessage Execute(Microsoft.BizTalk.Component.Interop.IPipelineContext, Microsoft.BizTalk.Message.Interop.IBaseMessage)

Error Source: Microsoft.Practices.ESB.ExceptionHandling.PipelineComponents

Error TargetSite: Void WriteHeaderFailedMessageRouting(System.Xml.XmlTextWriter, Microsoft.BizTalk.Message.Interop.IBaseMessage, System.Object ByRef) 

Error StackTrace:    at Microsoft.Practices.ESB.ExceptionHandling.PipelineComponents.ProcessFault.WriteHeaderFailedMessageRouting(XmlTextWriter writer, IBaseMessage pInMsg, Object& portName)
   at Microsoft.Practices.ESB.ExceptionHandling.PipelineComponents.ProcessFault.WriteHeader(XmlTextWriter writer, XmlTextReader reader, FaultSource faultSource, IBaseMessage pInMsg, Object& portName)
   at Microsoft.Practices.ESB.ExceptionHandling.PipelineComponents.ProcessFault.Execute(IPipelineContext pContext, IBaseMessage pInMsg)


// Add the message to the Fault Message
Microsoft.Practices.ESB.ExceptionHandling.ExceptionMgmt.AddMessage(MsgFaultMultipart, MsgInboundMessage);

this line is required in Orchestration code for ProcessFault pipeline component to work.


in windows event log:

xlang/s engine event log entry: Uncaught exception (see the ‘inner exception’ below) has suspended an instance of service (a42d0855-ec7c-3dc7-5e9f-442c84746e85)’.

The service instance will remain suspended until administratively resumed or terminated.

If resumed the instance will continue from its last persisted state and may re-throw the same unexpected exception.

InstanceId: 003a57d2-42b3-4a20-8cfa-a03b810df217

Shape name: Send_1

ShapeId: ad8c422b-4b45-41c5-bd0b-5ce958491e1e

Exception thrown from: segment 5, progress 8

Inner exception: Exception occurred when persisting state to the database.

Exception type: PersistenceException

Source: Microsoft.XLANGs.BizTalk.Engine

Target Site: Void Commit()

The following is a stack trace that identifies the location where the exception occured

   at Microsoft.BizTalk.XLANGs.BTXEngine.BTXXlangStore.Commit()

   at Microsoft.XLANGs.Core.Service.Persist(Boolean dehydrate, Context ctx, Boolean idleRequired, Boolean finalPersist, Boolean bypassCommit, Boolean terminate)

   at Microsoft.XLANGs.Core.ServiceContext.PendingCommit(Boolean ignore, XMessage msg)

   at Microsoft.XLANGs.Core.ExceptionHandlingContext.PendingCommit(Boolean ignoreCommit, XMessage msg)

   at Microsoft.XLANGs.Core.ExceptionHandlingContext.PendingCommit(Boolean ignoreCommit, XMessage msg)

   at Microsoft.BizTalk.XLANGs.BTXEngine.BTXPortBase.SendMessage(Int32 iOperation, XLANGMessage msg, Correlation[] initCorrelations, Correlation[] followCorrelations, Context cxt, Segment seg, ActivityFlags flags)

   at XX.segment5(StopConditions stopOn)

   at Microsoft.XLANGs.Core.SegmentScheduler.RunASegment(Segment s, StopConditions stopCond, Exception& exp)

Additional error information:

        A batch item failed persistence Item-ID 5f10694f-5a1f-4b05-ab88-6c9edbd1140d OperationType MAIO_CommitBatch Status -1061151998 ErrorInfo The published message could not be routed because no subscribers were found. .

Exception type: PersistenceItemException

Additional error information:

        Failed to publish (send) a message in the batch. This is usually because there is no one expecting to receive this message.  The error was The published message could not be routed because no subscribers were found.  with status -1061151998.

Exception type: PublishMessageException



1. Add Microsoft.Practices.ESB in your Application’s References

2. configure a SQL send port with ProcessFault pipeline component to insert exception in ExceptionDB.

(Alternatively, we can use All.Exceptions send port that was created with ESB Core installation)

17-Sep-12 12-24-36 PM

BizTalk ESB Toolkit 2.1: Index (zero based) must be greater than or equal to …

After installation and configuration of ESB Toolkit 2.1, ESB Portal gives this error.  I tried to debug ESB.Portal solution but unfortunately Microsoft does not provide source code for BizTalk Operations Service and we are left with trying different options.

The reason in this case was that BizTalk Operations Service Application Pool user should be member of BizTalk Administrator group (or some other BizTalk group who has permissions to retrieve list of installed BizTalk applications.



BizTalk: Log HL7 Parsing Errors

HL7 Disassembler writes parsing errors in windows event log and there is no documented way to get those error through code to log in custom database or some other data store.

Here is what HL7 pipeline writes into event log:


we can get these error in code by writing a wrapper disassembler component on top of HL7 OOTB Disassembler

Omitting details about how to write a custom pipeline component, we just need to override Disassemble and GetNext methods

  public HL7DASM()
            HL7Dasm = new HL72fDasm();
      public new void Disassemble(IPipelineContext pContext, IBaseMessage pInMsg)
            HL7Dasm.Disassemble(pContext, pInMsg);

If HL7 party is configured to return ACKs, GetNext() method will execute multiple times.

public new IBaseMessage GetNext(IPipelineContext pContext)
            IBaseMessage msg = HL7Dasm.GetNext(pContext);

            if (msg != null && !msg.BodyPart.Data.CanSeek)  //if parsing fails, stream is not seekable

                 FieldInfo ParserErrorField = HL7Dasm.GetType().GetField("mBodyErrors", BindingFlags.NonPublic | BindingFlags.Instance); 
var ParserError = (System.Collections.ArrayList)ParserErrorField.GetValue(HL7Dasm);
StringBuilder errorList = new StringBuilder();

                foreach (HL7Error error in ParserError)
    // now errorList string contains all parsing errors details in same format as in windows event log
            return msg;