RabbitMQ Server: Error: Host name in Upper-case

This is a small thing, but very annoying.

I didn’t find it in Internet, so decided to blog it here.

My environment: Windows Server 2008 R2 x64; RabbitMQ 2.7.1.

I installed the RabbitMQ Server and tried to interact with it using the rabbitmqctl.bat script. This script requires to use the host name:

>rabbitmqctl –n rabbit@Win2K8R2 status

I was getting the error again and again:

“Error: unable to connect to node rabbit@Win2K8R2: nodedown”

RabbitServer.Status

 

I used the exact string provided me by script (see above in red) -

- nodes and their ports on Win2K8R2:…

and the error text was -

Status of node rabbit@Win2K8R2

When I changed the host name to upper-case, error was gone.

          >rabbitmqctl –n rabbit@WIN2K8R2 status

Conclusion:

   Use only upper-case letters in the host name in rabbitmqctl.bat script!

BizTalk and RabbitMQ

The same article in the TechNet.

If you are working with queues in BizTalk Server, the most possible it is the MSMQ (in my experience).

MSMQ is an old man of the Microsoft technology stack. It was created when there were no good standards for messaging. Now MSMQ is wrapped partly in the .NET System.Messaging namespace. It is just a small facelift. MSMQ is still a proprietary technology without well-defined messaging protocol. It means, you cannot use the MSMQ messaging protocol without MSMQ itself.

Now we see vortex of new messaging standards and technologies. One on the top is the AMQP standard and one of the bold implementation of AMQP is the RabbitMQ.

It is one more protocol, one more messaging system which, for sure, can be integrated with BizTalk Server.

Here I will implement the standard queue messaging: sending and receiving messages from BizTalk down through the RabbitMQ queue. I am using the WCF-Custom LOB Adapter (provided from BizTalk side) and the WCF RabbitMQ Binding (provided from RabbitMQ side) to link two systems.

Installation and preparation

Assuming the BizTalk Server and the Visual Studio 2010 are also installed.

Installing RabbitMQ Service

  1. Go to the RabbitMQ site and download the last versions of server and client for Windows. For me it was rabbitmq-server-2.7.1.exe and rabbitmq-dotnet-client-2.7.1-dotnet-3.0.zip. Client includes the WCF binding which I will use lately. There are several good manuals: rabbitmq-dotnet-client-2.7.1-user-guide.pdf and rabbitmq-dotnet-client-2.7.1-wcf-service-model.pdf. I was quite impressed by quality distributives and documentation.
  2. Start rabbitmq--server-x.x.x.exe. It will request to install Erlang. Agree, go to the Erlang site [http://www.erlang.org/] and download it. For me it was Erlang.otp_win32_R15B.exe
  3. Start Erlang…exe. Installation went smoothly.
  4. Start rabbitmq--server-x.x.x.exe again. Installation went smoothly.

RabbitMQ service is installed. You can see it in the Services window.

Creating RabbitMQ Client Base Assemblies

 Now it is time to install the client for .NET and WCF binding extension. Use this manual.

  1.  Downloaded the .msi. Installed it. Hmm… no Rabbit.Client.dll (When I started with Examples, they all need this file. It is a main client dll).

  2. Downloaded the *-dotnet-3.0.zip. Nope, it was wrong.
  3. We need the last rabbitmq-dotnet-client-2.7.1.zip file. Extract everything from this zip.
  4. Made a copy of the Local.props.example file to Local.props file in the same root folder.
  5. Start Visual Studio with RabbitMQDotNetClient.sln and successfully build it. The ..\rabbitmq-dotnet-client-2.7.1\projects\wcf\RabbitMQ.ServiceModel\obj\Debug\RabbitMQ.ServiceModel.dll was created. This dll together with the RabbitMQ.Client.dll are the assemblies used by the RabbitMQ clients.

Set up the RabbitMQ binding extension

Here I really lost a lot of time. It is easy for the C# clients; the RabbitMQ.ServiceModel.Test gives all the information. But we have to use this binding from the WCF-Custom LOB adapter. To do so we have to add the assemblies to GAC, change machine.config, etc. See the WCF LOP Adapter documentation.

  1. Sign the RabbitMQ.ServiceModel and RabbitMQ.Client projects and GAC-ed them.
  2. Insert  an <add> node into the config section of machine.config:

<extensions>
      <bindingExtensions>
        …
        <add  name="RabbitMQBinding" 
          type="RabbitMQ.ServiceModel.RabbitMQBindingSection, RabbitMQ.ServiceModel, Version=0.0.0.0, Culture=neutral,   PublicKeyToken=1751e286f1ab778d"/>
      </bindingExtensions>
    </extensions>

Note:

  • When the binding extension assembly is placed in GAC, we cannot use the above section in the app.config file! This <add> element should be placed only into the machine.config file. Otherwise it cannot be seen in the binding extension list of the WCF LOB Adapter.
  • Use >Gacutil.exe /l RabbitMQ.ServiceModel
    to get the real parameters for your assembly.
I have several machine.config files in folders:
    • C:\Windows\Microsoft.NET\Framework\v2.0.50727\CONFIG
    • C:\Windows\Microsoft.NET\Framework\v4.0.30319\Config
    • C:\Windows\Microsoft.NET\Framework64\v2.0.50727\CONFIG
    • C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Config

Which one to use? My VM is 64bit. BizTalk Host of the port is 32bit. BizTalk is the 2010 version. In my case the right file was the C:\Windows\Microsoft.NET\Framework\v4.0.30319\Config\machine.config.



Finally the RabbitMQ binding installed and we can see it in the Binding Type list for WCF-Custom adapter.

Testing

Creating the BizTalk test

I have created two pairs of port for testing.

File RP -> WCF-Custom (RabbitMQ) SP ->

 [RabbitMQ Server]

 -> WCF-Custom (RabbitMQ RP) -> File RP

 

I’ve changed only two parameters: “hostname” and “oneWay” and let others be default:

 

URL-s for the Send and Receive RabbitMQ Ports set up as “soap.amqp://192.168.11.128/Mytest” for both of them.

Let’s test it.

Small text file was dropped into In folder, consumed by Receive Port, went through the RabbitMQ queue, and appeared in Out folder. Success.

Note:

  • Now the RabbitMQ binding is set up to process only well-formed Xml documents.
  • “localhost” as “hostname” works fine.

Using the RabbitMQ Binding Element

The RabbitMQ binding is limited to the Text messaging encoding. If we need to change it or add more binding extensions, we have to use the customBinding type and use the rabbitMQBindingElement together with another element (including another encoding). How to do this?

1. Add the <add> node to the machine.config:

<bindingElementExtensions>
                           …
        <add name="rabbitMQBindingElement" type="RabbitMQ.ServiceModel.RabbitMQTransportElement, RabbitMQ.ServiceModel,   Version=0.0.0.0, Culture=neutral, PublicKeyToken=1751e286f1ab778d"/>
</bindingElementExtensions>

 2. Change the Receive Location transport parameters. It was the RabbitMQBinding. Change it to the customBinding. The Transport Binding Element has to be changed to the rabbitMQBindingElement. I changed only one parameter: hostname as “localhost”.

 

 3. Test it as previously.

Conclusion

Using RabbitMQ as one more transport for BizTalk and/or WCF applications is possible and straightforward. The learning curve is short. There are not too many issues with setting up the RabbitMQ Service and Client parts. Actually there wasn’t any RabbitMQ part which was exposed to the BizTalk directly. RabbitMQ works only with WCF-Custom adapter and only this adapter communicates with RabbitMQ Service.
Now the RabbitMQ implements limited client functionality for the WCF. RabbitMQ implements the AMQP v.0.9 protocol, not the last version 1.0.

Next steps

Next steps are to test this solution with different messaging patterns and try to figure out how to use RabbitMQ advantages (if there are some) over the MSMQ. Potentially the advantages are the simplest implementation of the Request/Response and Duplex patterns, better scalability, better performance, better manageability and support.

 

BizTalk and 0MQ (ZeroMQ)

It is stupid to compare those two beasts.

BizTalk Server is a pricey, huge development and run-time system, it includes tons of the tools, supports tons of protocols and systems. It works for very specialized middle ware integration stack. It integrates big and complex systems as SAP, CRM, Oracle and intermediates many protocols and standards as SOAP, EDI, SWIFT, FTP, tons of them.

It is a messaging system.

ZeroMQ is a low-level, wire-level protocol, the same level as TCP. It has ultra-simple API. It is implemented as a library for dozens languages as C#, Java, Python, PHP, C++, COBOL, Ada, Haskel, F#, Erlang, etc. It works in the most OS: Windows, Linux, QNX... It is free and works under open-source license.

It is a messaging system.

 

BizTalk implements many messaging exchange patterns: Request-Response, Pub-Sub, Queue, Message Broker, Router, Convoy.

0MQ implements the same: Request-Response, Pub-Sub, Pub-Sub with Topics, Queue, Message Broker, Router...

BizTalk development stack is compounded of several editors. BizTalk run-time stack includes several services on top of SQL Server, several tools, and tons of dll-s and SQL code.

0MQ is just a library, a dll. Library per language, per OS. No dedicated services.

...
Why I feel so comfortable with this 0MQ?
Why I think it is a serious choice to do messaging in my real-life messaging?
Do I want to abandon the comfort of a big track to ride almost bare-bone wheels?

I am not the only one who comparing 0MQ with big brokers. There is interesting article comparing RabittMQ (AMQP) and 0MQ.

BizTalk: Ordered Delivery

 

It is one more description of the Ordered Delivery (OD) in BizTalk.

The main article about it is in MSDN.

Here I am discussing the BizTalk Ordered Delivery “implementation details”.

OD Considerations

  • Ordered Delivery (sequential) mode is opposite of the “Parallel Delivery” mode. Parallel Delivery is the most productive mode; the Ordered Delivery is less productive mode.
  • Transports such MSMQ and protocols, supporting the WS-ReliableMessaging, are the protocols supporting OD. Other protocols as FTP, File, SQL, SMTP etc. do not have notion of the “order”.
  • BizTalk application usually is a part of the whole message workflow.
  • There are two approaches in the OD implementation:
    • All steps of the message workflow independently support OD.
    • A Destination System implements the re-sequencing and manages lost and duplicate messages.
  • Order is relative. Sequences can be ordered regards one or several parameters. For example, OD for the Company or for the Company + Department.

OD and the BizTalk Architecture

  • MessageBox is an implementation of the Message Queue. OD is an intrinsic feature of the MessageBox.
  • The BizTalk Server works in the Parallel Delivery mode by default.
  • There are three parts in the BizTalk message exchange outside of the MessageBox in relation to OD: Receive Locations; Orchestrations; Send ports.
    • Receive Locations support OD on the Transport level (say, MSMQ and some WCF adapters).
    • OD in Orchestrations is implemented by the sequential convoy pattern.
    • Send ports support OD for all static adapters.
  • The BizTalk Pipelines (part of Receive and Send Ports) always process messages in order using streams.

OD and Ports

To force Send Ports work in order we set up a flag the “Ordered Delivery” in Send Ports, then the BizTalk MessageBox takes care of implementing OD.

To force Receive Locations work in order we set up flag the “Ordered Delivery” option in the Receive Location Transports, whenever is possible. Then the BizTalk Transport Adapter takes care of implementing OD.

Ordered Delivery Send Port instance works as a singleton service. Since start it stays in Running state. It will not recycle if we restart its Host Instance. We could manually terminate it, if we want.

 

OD and Orchestrations

MessageBox implements the convoy message exchange pattern [See Using Correlations in Orchestrations]. See the detail convoy description in the BizTalk Server 2004 Convoy Deep Dive article.
It is not just a design pattern that developer should follow. There are special mechanisms inside MessageBox responsible for implementing OD.

OD and Orchestration: Sample

 

Imagine four Orchestrations which implement four approaches to the sequencing.



The first is the ProcessNoOrder Orchestration. It processes all messages without any order. One ProcessNoOrder Orchestration instance will be created for each inbound message.

The ProcessInOrder Orchestration processes all messages in one sequence. Only one ProcessInOrder Orchestration instance will be created.

The ProcessInOrderByCompany Orchestration processes messages in sequences correlated by the Company value (A, B, C, D, etc.). The separate queue is created for each new value of the Company. Messages inside queues are processed in order. Queues for different Companies are independent. A separate ProcessInOrderByCompany Orchestration instance will be created for each new Company value.

The ProcessInOrderByProduct Orchestration works exactly as the ProcessInOrderByCompany Orchestration but correlated by the Product value (xx, yy, etc.).

Discussions

Performance

By default all Orchestration and Messaging Service instances works in the Parallel Delivery mode with maximum performance.

If we check up the Ordered Delivery option in Send Port, BizTalk will initiate the Send Port instance as a singleton service. It is always a single instance. We don’t have the flexibility of the Orchestration where we could tune up “the proportion of the sequencing” and could control the recycling of the service instance.

Send Port OD could be in two states, on and off:

  • OD is off: a service instance per message, one message per queue, maximum performance.
  • OD is on: one infinite service instance, all messages in one queue, minimum performance.

Orchestration OD could be in two states also, on and off:

  • OD is off: a service instance per one activating message, one activating message per queue, maximum performance.
  • OD is on: one or several service instances, one per new correlation set value; all correlated messages per queue; performance is from min to max, depends ot the correlation set..

Carefully designing the correlation sets we could tune up the performance of the Orchestration. For example, if we only care of the document order for each separate Company, we include the Company to the Correlation set. If we had thousand documents related to hundreds companies, the performance will be near maximum. If there are only two companies, the performance will be near minimum, and we should consider improving the correlation with one more parameter.

Orchestrations and Zombies

Zombies are big problem of Convoy Orchestrations. See BizTalk: Instance Subscription and Convoys: Details article with description of this problem. This problem could be mitigated but could not be completely removed. We are waiting a new version of the BizTalk Server where this issue will be targeted.

BizTalk Server version Next, Ordered Delivery and Zombies

It is possible the BizTalk Server version Next will implement the automatic Ordered Delivery for Orchestrations, with pattern similar to the Ordered Delivery in Send Ports.

Three new Orchestration parameters are shown up there: Ordered Delivery, Stop on Exception, and Recycle Interval (in seconds).

 



Ordered Delivery parameter works in the same way as the Ordered Delivery parameter of the Send Port. Now we don’t have to build the Convoy Orchestration manually. No more Loop inside Orchestration.

If the Ordered Delivery parameter set up to True, the Orchestration is working as a Singleton. The first Receive shape receives all correlated messages in sequence. Correlation set is created implicitly regards of the Activation Subscription expression.

There are several limitations for this kind of Orchestration. The most important is: only one Receive shape is permitted here.

There are two big advantages of this new feature:

  • Simplified Orchestration design for the Ordered Delivery.
  • No more Zombies. The Orchestration instance is recycled in controllable way, when no messages, matched the Orchestration Subscription, are placed in the MessageBox.

Conclusion

We discussed the Ordered Delivery implemented in the BizTalk Server and ways to improve it.

 

BizTalk: Advanced Questions

This article is a Part 6 of the Interview Questions series.

It is time for fun!

These questions are for an Advanced level of the BizTalk Developers. I hope you don’t have a single chance to answer these questions, if you don’t have a real life experience in BizTalk Server projects.

I would appreciate, if you write the answers in comments to this article. Thanks!
I will mark the questions which got a right/good answer.

If you have more advanced questions, please, comment them down and I will add them to this list under your name.

I will constantly add more questions into the end of list. Be in tune.

Advanced level

  • The error in BizTalk usually creates a suspended message. But routing error creates two messages. Why so? How we could utilize this feature?
  • Send ports have an “Ordered delivery” option. How it works for a File adapter, if the File protocol does not have a notion of file order?
  • Send ports have an “Ordered delivery” option but Receive ports do not have it. Why so?
  • You set up an “Ordered delivery” option in Send Port. What is special about Service Instance of this Port?
  • How to force an Orchestration do the ordered delivery? Is there a special “Ordered delivery” option in Orchestration? If it is not, why?
  • Send ports have the “Priority” options, but Receive ports and Receive Locations do not have them. Why so?
  • How does the Priority feature of the Send Port work?
  • Why the Priority option can be set up only for the Send Port?
  • Send ports have the “Retry” options, but Receive ports and Receive Locations do not have them. Why so?
  • How does the Retry feature of the Send Port work? In what scenarios this feature is helpful, in
  • Send ports have a “Backup Transport” but Receive ports do not have it. Why so?
  • Send ports have a “Filter” but Receive ports do not have it. Why so?
  • Send ports have the “Maps” and “Transport”; Receive ports have “Maps” but “Transport” is associated with Receive Locations. Why so?
  • What is the difference between “Send Port Group – Send Port” relation and “Receive Port – Receive Location” relation?
  • Receive Location have the Schedule parameters for date and time but Send Ports have the Schedule parameters only time. Why so?
  • Can we create two Send Ports with the same URL? Can we create two Receive Locations with the same URL? Why so
  • Filter expression for the Send Port is defined at run-time, but Filter expression for the Orchestrations is defined only at design-time. Why so?
  • We created a custom pipeline component. Do we have to place it into the “<BizTalkFolder>\Pipeline Component” or install it to GAC or both?
  • How does an Orchestration make sure the message was sent successfully by one-way Send port? How does it changed for a two-way Send port?
  • What is it the “CodeList Database” property of the Schema? How to use it?
  • What is the “Property Schema Base” property of the Property schema element? It has the values: MessageDataProperyBase, MessageContextPropertyBase, and PartContextPropertyBase. What is the difference between using MessageDataProperyBase and MessageContextPropertyBase?
  • We bind the Orchestration with Send Port. What does it do regards of the subscription?
  • We bind the Orchestration with Receive Port. What does it do regards of the subscription?
  • How do Filters of the Send Ports and Send Port Groups work together? Say, a Send Port belongs to a Send Port Group. If this Send Port and this Send Port Group have the same Filter expression, does it create two subscriptions and, as a result, two messages are sent to the Send?
  • Why do we need a special Property schema for Promoted properties? What is the purpose of this schema? Distinguished properties do not use this kind of schema. Why so?
  • Properties of some BizTalk artifacts have the Tracking option. Right-click menu of some BizTalk artifacts have the “Tracking…” command. Why there is such a difference between artifacts? Why Maps do not have any Tracking options? Why Schemas have only Tracking property? Why Send Port Groups do not have any Tracking options? Why Receive Locations do not have any Tracking options? Why BizTalk Applications do not have any Tracking options?
  • When the BizTalk Assembly is deployed, is it stored in the BizTalk database or it is just referenced in the BizTalk database?
  • Why BizTalk Assembly must be installed into GAC? Why deploying it to BizTalk database is not enough? 
  • Can you describe at least three scenarios where smart Orchestration Engine finds the errors in the messages patterns at design time (while build the BizTalk project)?
  • Host has an "Authentication Trusted" option. What does it mean? What implication it has to the message processing? How do we have to use it / don't use?
  • Could you create an XLANGMessage in the C#/VB code? Please, provide code.
  • You can use an XmlDocument class as a Message type for receive untyped Xml messages in Orchestration. What .NET classes we have to use for receive untyped text or binary messages in Orchestration. Why so?
  • Is the Publish-Subscribe BizTalk Engine API well defined? Where? If not, why so?
  • Does BizTalk use the strategy “First  received, first processed” or “First received, last processed” of “First received, first processed, first sent” of something else? Why so?
    Describe scenarios, when this strategy works better, and scenarios, when this strategy works badly.
  • Are Orchestration Instances processed in order? Why so? Describe scenarios.
  • Is it possible to force Hydration / Dehydration of the Orchestration instances, Messaging instances? How to do this? Why do this?
  • In what scenarios you will use the Compensations in Orchestrations? Why so?
  • Atomic scopes in Orchestrations have a Retry feature. How it works? Describe scenarios when it is used.
  • What serializer does BizTalk use, XmlSerializer or DataContractSerializer? What implication it has for the real life scenarios?
  • What transform engine is BizTalk using, XslTransform or XslCompiledTransform? What implication it has for the real life scenarios?
  • BizTalk Business Rule Engine uses a Rete engine inside. In what scenarios this Rete engine is the more efficient / less efficient?
  • Let’s classify the applications as Front-end, Middle-level and Back-end. Where are the best places to use BizTalk? Please, provide scenarios. What are the most important features we have to take in account?
  • What BizTalk features are the differentiators, when you compare BizTalk Server with other alternatives? What are those alternatives?
  • What is the Heartbeat in BizTalk? Why it is implemented? Can we change the heartbeat interval? How does this interval influence processes in MessageBox? 
  • What is the difference, if any, between ESB and Broker conceptions?

BizTalk: Samples: Error Handling, Email Notification

One problem with email notifications is it usually sends too many emails. Errors frequently happen in series. For example, a temporarily issue with network can result in hundreds repetitive emails. In result an email notification designed as a “VIP” notification is downgraded to the “annoying” status.

This email flooding could be mitigated with this solution.

A Sample demonstrates using the emails for sending notification in case of failed messages.

It compounds several similar errors in one email notification.

 

Recently I've uploaded this sample 

BizTalk: Samples: ErrorHandling: Notification emails

to MSDN Gallery.

It has all solution artifacts and can be used in real-life projects.

 

BizTalk: Sample: Error Handling

Recently I uploaded a "BizTalk: Sample: Error Handling" in MSDN Gallery

This sample shows the BizTalk features:

  • Routing Failed Messages in ports
  • Catching Failed Messages with Send Port
  • Catching Failed Messages with Orchestration
  • Handling Exceptions inside Orchestration
  • Handling SOAP Fault messages inside Orchestration

BizTalk Orchestration Naming Conventions

 This is a second part of the BizTalk Naming Convention.

Special Orchestration Objects 

<Message> =: 
      msg_ + <ShortMessageType>

<Variable> =: 
      var_ + <Name>

<CorrelationSet> =: 
      cor_ + <Name>

<OrchestrationParameter> =: 
      par_ + < Name>

<RoleLink> =: 
      roleLink_ + <Name>

Note: These objects are special BizTalk objects. They are used in different language context and sometime they use different language syntax. Prefixes help to differentiate the objects in the XLang expressions.

<Port> =: 
      <prefix> + <Name>

where

Send

Receive

Send-Receive
(Solicit-Response)

Receive-Send
(Request- Response)

prefix

S_+

R_+

SR_+

RS_+

Notes:

  • The Port objects are the only objects which can be seen outside orchestration. We see them while bind orchestration with Ports, not the orchestration Ports but Ports created in the BizTalk Administration Console. Sometimes the orchestration Ports are named as Logical Ports and the Ports as the Physical Ports. Here are some considerations about this ambiguity with Port names.
  • Send-receive prefixes help while Orchestration is binding with Ports. Ports with different Communication pattern are using different prefixes.

Example: S_ OrderAck.

 

Orchestration Object Types

<ArtifactType> =:
      <ArtifactName> + “_type

Note: We can see orchestration types in the Orchestration View window in Types. They are: Port, Multi-part Message, Correlation and Role Link Types. We can use one suffix the “_type” for all different types because different types are seen only in the different lists and never mixed. For instance, we can never see the port types together with message types.

Controversial:Suffixes for types work better than prefixes, because types are mostly used in the drop-down lists not in the XLang expressions.

Orchestration Workflow Shapes

Problems with orchestration shapes:

  •         Shapes are too small to display long names (only 12-18 characters are visible).
  •         We have to hover a mouse over a shape or click shape to see Properties window and to "understand" this shape, to understand which message is processed.

Useful features:

  •          Shapes have names, but names are not the “variable names”, not identifiers. They are descriptions (excluding the Port shapes names, which have not Name parameter but Identifier and Description parameters). Shape names are used only for description not as XLang variable identifiers. Shape names can be long and can include any symbols as spaces, dots, etc.
  •          Icons of shapes give us the useful information. Do not repeat the “icon information” by words. For example, we can a name a Construction shape as “Construct OrderAck” or as “OrderAck”. Last variant give us more clear and short definition because we have the Construction icon + name.
  •          Shape names are used mainly in Orchestration Editor (excluding the Port shapes names). We don’t need the “well-sorted” names, so we don’t need to use prefixes, because the main purpose of the prefixes is creating well-sorted lists.
  •          Group shape is a scalable shape. Nesting other shapes to a Group shape can make a long description visible. Group shape will display as much text as you want. Group shapes add a lot of documentation value to the orchestration.

Rules for shapes

  •          Whenever it is possible use the short MessageType as a shape name.
  •          Do not repeat a type of shape icon by word.
  •          Feel free to use spaces and any other symbols inside the shape names.
  •          Feel free to repeat the shape names.

Note: Purpose of the orchestration and the most of the shapes is in processing the messages. We can unambiguously describe the messages by the message type. A message type gives us the main information about a message. That is why in the most cases using the message type as the shape name gives us the main information about message flow, about the whole orchestration processing.
Example: Send shape with name "OrderAck" means “send OrderAck message”.

Controversial:

  • Orchestration Naming Convetion works not to make easier the administration and troubleshooting but mostly to make orchestration more readable. Most orchestration names are not visible outside the Orchestration Editor. So, do not force the orchestration naming convention to hard! If your developers use differen conventions, it is fine; of course, if they understand each other. Forcing convention can do more harm than help. It can force team to spend more effort for a little.
  • When exception is thrown from a shape, the error description includes a name of the shape. It is a rare case when names are exposed outside of the Orchestration Editor. When we use MessageType as a name of shapes, many shapes can get the same name. So, if we want to differentiate shape names for debugging purpose, we could use numbers or single letters in the end of names.
    Example: “OrderAck 2”

 

BizTalk: Sample: PGP Encryption/Decryption Pipeline Components

A sample demonstrates the PGP Encryption/Decryption in pipelines.

You can download code here.
		
A sample is based on a sample by Brian Jones See original code here
		

The main additions to original code:

·         Single pipeline component was separated to two Encrypt and Decrypt pipeline components. It simplifies the pipeline configurations.

·         Configuration parameters are stored in SSO, which, I hope, improves security.

·         File names for temporary files are regenerated randomly each time. That eliminates errors in case when temporary file names are based on the inbound file names and pipelines are working simultaneously in several ports.

To build pipeline components you have to download a BouncyCastle.Crypto.dll assembly from http://www.bouncycastle.org/csharp .

The solution includes two pairs of the PGP keys. You can generate yours pairs using, for example, PortablePGP utility http://primianotucci.com

Configuration includes a config file for a SSO Config Store utility created by Richard Seroter.

The test pipeline project includes four pipelines:

·         Send and Receive pipelines for Encryption

·         Send and Receive pipelines for Decryption.

To test these pipelines I’ve created four receive ports and four send ports. They create four test workflows:

·         Encryption on a Receive port:
RP::GLD.Samples.Pipelines.Encrypt.Encode  ( PgpEncryptReceive pipeline )
 
è SP:: GLD.Samples.Pipelines.Encrypt.PassThru

·         Encryption on a Send port:
RP::GLD.Samples.Pipelines.Encrypt.PassThru  
 
è SP:: GLD.Samples.Pipelines.Encrypt.Encode ( PgpEncryptSend pipeline )

·         Decryption on a Receive port:
RP:: GLD.Samples.Pipelines.Decrypt.Decode ( PgpDecryptReceive pipeline )
 
è SP:: GLD.Samples.Pipelines.Decrypt.PassThru

·         Decryption on a Send port:
RP:: GLD.Samples.Pipelines.Decrypt.PassThru
 
è SP:: GLD.Samples.Pipelines.Decrypt.Decrypt ( PgpDecryptSend pipeline )

To test pipelines:

·         Use test text files in a Tests\TestData folder

·         To test encryption:

1.        Copy test files to a Tests\Encrypt\In folder

2.        Encrypted files are created in a Test\Encrypt\Out folder.

·         To test decryption:

3.        Copy test encrypted files from a Test\Encrypt\Out folder to a Tests\Decrypt\In folder

4.        Decrypted files are created in a Test\Decrypt\Out folder.

 

BizTalk and WCF adapters: Operation and SOAP Action

One area here is not so well documented.

When we are filling in the Transport properties for WCF adapter, we see the SOAP Action header section.

What is it? Where we could take the values for Operations and Actions?

If we use the Consume WCF Service wizard, this section is filled up automatically. But sometimes we have to fill it in manually.

NP

Open a WSDL for the Web-service and search for a binding section. If you add the “?wsdl” to the Web-service URL, usually the Web-service WSDL is opened.

That’s how operations and actions in the WCF parameters and WSDL are mapping:

Hope it helps.

WCF: Questions for studying and interview: Routing Service

This article is a Part 5 of the Interview Questions series.

WCF, Routing Service

Q&A

• What are the features of the Routing Service (RS): Protocol bridging; Message transformation; Content-based routing; Application pools; Dynamic configuration; SOAP processing; Service hosting; Error handling; Backup endpoints?
• Which routing scenarios can RS implement: Service aggregation; Interface recomposition; Service versioning; Service chain; Priority routing?
• Is it possible to modify the routing configuration at run time?
• What is the RS doing if there is no match for a message routing?
• Can we route to the mix of the one-way and two-way destination endpoints using a single service endpoint?
• Do we have to create the implementation of the RS as a .NET class or an .svc file with “Service="System.ServiceModel.Routing.RoutingService, …” plus a configuration file is enough?
• What is it a SOAP processing? How it works?
• Can it convert messages between Soap 1.1/Soap 1.2/Soap 2.0 and/or WS-Addressing August 2004/WS-Addressing 1.0?
• What is it a Backup endpoint?
• What is the maximum number of the Backup endpoints?
• What is it a Protocol bridging?
• What is it a Content-based routing?
• How the Priority routing is working?
• How we can host the RS?
• Are there limits on using streaming for the RS? Where we have to buffer the messages?
• How we can expose mex endpoints of the original services through the RS?
• Can we use the RS as a load balancer?
 

WCF: Questions for studying and interview: Discovery

Q&A: WCF, Discovery
·         When the WS-Discovery standard gets approval first time?
·         Is the WS-Discovery using the XML format for messages? 
·         Is the WS-Discovery using the SOAP format for messages? 
·         What are the versions of the WS_Discovery protocol?
·         What version is the default version?
·         What is a difference between the Add-hoc and Managed modes? What are the Pro and Cons?
·         Describe the message exchange sequences of the Discovery protocol.
·         What are the message exchange sequences in the Add-hoc and Managed modes?
·         Can the Add-hoc and Managed modes be switched dynamically?
·         What messages are multicast and what are unicast?
·         What is the Discovery Proxy service?
·         It there a default Discovery Proxy service?
·         What is the difference between the Probe and Resolve requests?
·         What are the response messages for the Probe and Resolve requests?
·         What are the response messages for the Probe and Resolve requests if there is no match?
·         Who sends the announcement message, service or client?
·         What announcement messages are used?
·         Is announcement using a Special endpoint?
·         Is announcement optional or mandatory?
·         How to make a Web-hosted service discoverable? What two options do we have? How AppFabric or Discovery Proxy service is used to help with it?
·         What is a FindCriteria class? What are the Search criteria?
·         How long a client is waiting the results from the discovery request?
·         What happens if a discovery request didn’t get you any service endpoint?
·         Can we use different versions together on a single service host?
·         What endpoints are used for the Discovery?
·         What is a difference between the DiscoveryEndpoint and the DynamicEndpoint? Do we have to use a DynamicEndpoint with a DiscoveryClient?
·         What Discovery endpoints are the system endpoints?
·         How to make a custom endpoint discoverable?
·         Why the UPD protocol is used for discovery? What pros and cons?
·         How to use the Discovery Client Channel? What are alternatives?
·         What are the pros and cons using the Discovery Client Channel?
·         How to create a DiscoveryEndpoint on demand?
·         Can you compare the WS-Discovery and the UDDI?

 

Microsoft 2011 MVP Global Summit: Pictures

Photos from Summit

Mighty Canada

Mighty Canada

Oh, Canada!

Oh, Canada!

Microsoft is hearing you, guys.

Microsoft is hearing you, guys.

New Zealand is here.

New Zealand is here.

Portugal and Brazil are here...

Portugal and Brazil are here

France is here...

France is here...

Netherlands is here...

Netherlands is here...

all BizTalkiens

all BizTalkiens

and the whole world is here...

[See more MVP-s]

Vsem privet!

 

BizTalk: Using context for routing

Imagine the project where most of the routing happens between orchestrations. I.e. routing is mostly between the MessageBox and orchestration with direct endpoints.
Imagine also the most of the messages are with the same Message type.
Usually in this case messages got the special node only for the routing. For example, the field can be the “Originator” or “Recipient” or “From” or “To”.
What wrong is with this approach, it creates the dependency between the message and the message processing. Message “knows” something about Originator or Recipient.
So what we can do with it? How can we “colorize” the same message to route it to the different places without changing the message itself?
One of the decisions is to use the message context.
BizTalk uses the promoted properties for routing.  There are two kinds of the properties: the content properties and the context properties. The content property extracts its value from inside the message, it is a value of the element or attribute. [See MSDN] The context property gets its value from the message environment. It can be the port name that receive this message, it can be the message Id, created by the BizTalk. Context properties look like the headers in the SOAP message. Actually they are not the headers but behave like headers. The context properties are the good match for our case.
First, we don’t have to change the message itself to set or change the routing property. The context is stored outside the message body.
Second, we don’t have to create the property schema to use the context properties. [See MSDN: How to create Property schema] BizTalk has the predefined schema set for the context properties. [See MSDN: Message Context Properties] Use one of them and that's it.
The main purpose of the context properties is working on behalf of the BizTalk internals. But we can read, create and change them. Just do not interfere with BizTalk internals on this way.

 

BizTalk: Sample: Context routing and Throttling with orchestration

The sample demonstrates using orchestration for throttling and using context routing.
Usually throttling is implemented on the host level (in BizTalk 2010 we can also use the host instance level throttling). This sample demonstrates the throttling with orchestration convoy, that slows down a message flow from some customers. Sample implements sort of quality service agreement layer for different kind of customers.
The sample demonstrates the context routing between orchestrations. It has several advantages over the content routing. For example, we don’t have to create the property schema and promote properties on the schemas; we don’t have to change the message content to change routing.
Use case:
 The BizTalk application has a main processing orchestration that process all input messages. The application usually works as an OLTP application. Input messages came in random order without peaks, typical scenario for the on-line users.
But sometimes the big data batch payloads come. These batches overload processing orchestrations. All processes, activated by on-line users after the payload, come to the same queue and are processed only after the payload. Result is on-line users can see significant delay in processing. It can be minutes or hours, depending of the batch size.
Requirements:
On-line user’s processing should work without delays. Big batches cannot disturb on-line users. There should be higher priority for the on-line users and the lower priority for the batches.
Design:
Decision is to divide the message flow in two branches, one for on-line users and second for batches. Branch with batches provides messages to the processing line with low priority, and the on-line user’s branch – with high priority.
All messages are provided by one hi-speed receive port.
BTS.ReceivePortName context property is used for routing. The Router orchestration separates messages sent from on-line users and from the batch messages.
But the Router does not use the BizTalk provided value of this property, the Router set up this value by itself. Router uses the content of the messages to decide if it is from on-line users or from batches.
The message context property the BTS.ReceivePortName is changed respectively, its value works as a recipient address, as the “To” address for the next recipient orchestrations. Ideally we should use two receive ports or two receive locations and BizTalk set up the context property for us. If we use the same context for both messages (the same port and location), we need to use orchestration to modify the context property using content of the messages or something else.
Those next orchestrations are the BatchBottleneck and the MainProcess orchestrations.
Messages with context equal “ToBatch” are filtered up by the BatchBottleneck orchestration. It is a unified convoy orchestration and it throttles the message flow, delaying the message delivery to the MainProcess orchestration.
The BatchBottleneck orchestration changes the message context to the “ToProcess” and sends messages one after another with small delay in between. Delay can be configured in the BizTalk config file as:

                <appSettings>
                                <add key="GLD_Tests_TwoWayRouting_BatchBottleneck_DelayMillisec" value="100"/>
                </appSettings>
 
Of course, messages with context equal “ToProcess” are filtered up by the MainProcess orchestration.
 

NOTES:
  • Filters with string values: In Orchestrations (the first Receive shape in orchestration) use string values WITH quotes; in Send Ports use string values WITHOUT quotes.
  • Filters on the Send Ports are dynamic; we can change them in run-time. Filters on the Orchestrations are static; we can change them only in design-time.
  • To check the existence of the promoted property inside orchestration use the Expression shape with construction like this:
          if (BTS.ReceivePortName exists myMessage) { …; }
    It is not possible in the Message Assignment shape because using the “if” statement inside Message Assignment is prohibited.
  • Several predefined context properties can behave in specific way. Say MessageTracking.OriginatingMessage or XMLNORM.DocumentSpecName, they are required some internal rules should be applied to the format or usage of this properties. MessageTracking.* parameters require you have to use tracking and you can get unexpected run-time errors in some cases. My recommendation is - use very limited set of the predefined context properties.
  • To “attach” the new promoted property to the message, we have to use correlation. The correlation type should include this property. [Here is a good explanation by Saravana ]
  • Say we have two correlation types, each with one parameter inside. If we want to correlate to both parameters simultaneously, we cannot use both correlation types, we have to create the correlation type with both parameters and use this type. Otherwise only one correlation type would be chosen for correlation, that means only parameter would be used for correlation.

 

BizTalk: Suspend shape and Convoy

This is a Part 2.

I am discussing the Suspend shape together with Convoys and going to show that using them together is undesirable.
In previous article we investigated the Instance Subscriptions and how they could create situation with dangerous zones in processing. 

Let' start with Suspend shape. [See the BizTalk Help]
"You can use the Suspend shape to make an orchestration instance stop running until an administrator explicitly intervenes, perhaps to reflect an error condition that requires attention beyond the scope of the orchestration. All of the state information for the orchestration instance is saved, and will be reinstated when the administrator resumes the orchestration instance.
When an orchestration instance is suspended, an error is raised. You can specify a message string to accompany the error to help the administrator diagnose the situation."
 
On the Suspend shape the orchestration is stopped in the Suspended (Resumable) state. Next we have two choices, one is to resume and the second is to terminate the orchestration.
Is the orchestration is stopped or unenlisted? You don't find a note about it anywhere. The fact is the Orchestration is stopped and still enlisted. It is very important.
So again, the suspended orchestration can be resumed or terminated. The moment when the operator or the operation script resumes or terminates can be far away. It is also important.
Let's go back to the case from previous article. Make sure you notice the convoy and the dangerous zone after the last Receive shape.
 
 
Now we have a Suspend shape inside the orchestration.
The first orchestration instance is suspended. Next messages start new orchestration instance and have been consumed by this orchestration, right? Wrong!
The orchestration is stopped on the Suspend shape but still enlisted. Now the dangerous zone, the "zombie zone" is expanded to the interval between the last receive and the moment of termination or end of the orchestration. The new orchestration instance for this convoy will not start till this moment. How fast operator finds out this suspended orchestration? Maybe hours or days. All this time orchestration is still enlisted and gathering the convoy messages. We can resume the orchestration but we cannot resume these messages together with orchestration.
Seems the name Suspended of the orchestration is misleading. The orchestration can be in the Started (and Enlisted)/Stopped (and Enlisted)/Unenlisted state. The Suspend shape switches orchestration exactly to the Stopped state. The Stop name would describe the shape clearly and unambiguously and the Stopped state would describe the orchestration.

Imagine we can change the BizTalk.
  • The Orchestration editor can search these situations and returns the compile error. In similar case the Orchestration Editor forces us to use only ordered delivery port with convoys.
  • The run-time core can force the orchestration with convoy be suspended in Unresumable state, that means the run-time unenlists the orchestration instance subscriptions.
  • The Suspend shape name should be changed. The "Suspend" name is misleading. The "Stop" name is clear and unambiguous. The same for the orchestration state, it should be “Stopped” not “Suspended (Resumable)”.
 

Conclusion:
  •  It is not recommended using a Suspend shape together with the convoy orchestrations.

BizTalk: Instance Subscription and Convoys: Details

 
This is Part 1.
 
Convoys are frequently used in the in the orchestrations in BizTalk Server. Sometimes we have got contra intuitive behavior in the convoys, when messages and orchestrations get suspended in unpredictable manner. This issue is well-known, the suspended messages get name the "zombie". The name is unofficial, but issue is still there. Here I would describe in details, what, when and why this zombie situations are happen.

 An orchestration can be enlisted with many subscriptions. In other word it can have several Receive shapes. Usually the first Receive uses the Activation subscription but other Receives create the Instance subscriptions. [See “Publish and Subscribe Architecture” in MSDN]
Here is a sample process.
This orchestration has two receives. It is a typical Sequential Convoy. [See "BizTalk Server 2004 Convoy Deep Dive" in MSDN by Stephen W. Thomas].
Let's experiment started.
 
There are three possible scenarios depended of the message sequences.
First scenario: everything is OK
Activation subscription for the Sample message is created when the orchestration the SampleProcess is enlisted.
The Instance subscription is created only when the SampleProcess orchestration instance starts and this subscription is removed when the orchestration instance ends.
So far so good, the Message_2 is delivered exactly in this time interval and consumed.
Second scenario: no consumers
Three Sample_2 messages are delivered. The first one is delivered before the SampleProcess starts and before the instance subscription is created. Second message is delivered in the correct time interval. The third one is delivered after the SampleProcess orchestration ended and the instance subscription was removed.
Note:
·         It is not the first Sample_2 consumed. It was first in the queue but it was not waiting, it was suspended when it had been delivered to the Message Box and didn’t have any subscribers at this moment.
The first and the last Sample_2 messages are Suspended (Nonresumable) in the Message Box. For each of them two (!) service instances have created. One service instance has the ServiceClass of Messaging, and its Error Description is:
 
The second service instance has the ServiceClass of RoutingFailureReport, and its Error Description is:
 
 
Third scenario: something goes wrong
Two Sample_2 messages are delivered. Both are delivered in the same interval, while the SampleProcess orchestration is working and the instance subscription has created.
First Sample_2 is consumed. The second Sample_2 has the subscription, but the subscriber, the SampleProcess orchestration, will not consume it. After the SampleProcess orchestration is ended (And only after! I will discuss this in the next article.), it is suspended (Nonresumable). Now only one service instance is suspended. This service instance has the ServiceClass of Orchestration, and its Error Description is:
In the Message tab the Sample_2 message is in the Suspended (Resumable) status.
Notes:
  •  The orchestration consumes the extra message(s) and gets suspended together with these extra messages. These messages are not consumed in term of “processed by orchestration”. But they are consumed in term of the “delivered to the subscriber”. The receive shape in the orchestration does not receive these extra messages. But these messages are routed to the orchestration. The Error information looks ambiguous.
  • The time zone between the last receive shape and the end of the orchestration is a "dangerous zone". The message delivery pattern should be scrutinized to avoid it.
 
 
Unified Sequential convoy
 Now one more scenario.
It is a unified sequential convoy. The activation subscription is for the same message type as it for the instance subscription. The Sample_2 message now is the Sample message. For simplicity the SampleProcess orchestration consumes only two Sample messages. Usually the orchestration consumes a lot of messages inside a loop in this scenario, but now there are only two of them.
First message starts the orchestration, the second message goes inside this orchestration. Then the next pair of messages follows, and so on.
But if the input messages follow in shorter intervals we have got the problem.
We lose messages in unpredictable manner.

Conclusion:

  • Maybe the better behavior would be if the orchestration removes the instance subscription after the message is consumed, not in the end on the orchestration. This behavior looks like a bug. But right now it is a “feature” of the BizTalk subscription mechanism.
  • The time zone between the last receive shape and the end of the orchestration is a "dangerous zone". The message delivery pattern should be scrutilized to avoid this zone as much as possible.
 

 Note [2011-2-9]:
  • I saw several times the explanation of the zombies, where the zombie can be created in the time zone between the moment an orchestration is scheduled to dispose and the moment the orchestration is disposed. I.e. the average dangerous time zone is about half of the MessageBox heartbeat interval (by default it is 1 sec), that means 0.5 sec. It is not correct. The dangerous zone is between the last receive (for the message with the instance subscription) and end of orchestration, and this zone could be much bigger than a heartbeat.

See more about zombies in BizTalk from the BizTalk Core Engine Blog

 

SQL Server Management Studio: Dynamic Folders

One of the problem with SQL Server Management Studio is it shows the objects in one list. For example, see the list of stored procedures for the BizTalkMsgBoxDb database, one of the BizTalk database.
It is a huge list. Smart developers are trying to make this list useful and searchable and use suffixes and prefixes to group the objects together.
See prefixes “adm_” and “bts_”. Following this practice we have got the nested compound prefixes. See the subgroups after the “bts_” prefix.
It is completely and absolutely awful view. We have to scroll down and up this list to find out the right object.
The same lists are for others SQL objects.
But it can be much better with small change.
Let’s create the virtual dynamic folders.
Now the list is short, easy searchable and easy observable. Moreover, the long awful names are folded to something readable. Yes, now the names are readable.
All we can do to this beauty is to set up the parameters for these virtual dynamic folders.
Right-click the “Stored Procedures” folder and choose Properties / Dynamic Folders…
There are only few parameters to set up:
·         Objects to fold, more than X (auto by default)
·         Characters to fold, more than X (auto by default
·         Show full name (unchecked by default)
Folders are smart enough to fold with good taste and intellect. But sometimes it helps to fold objects with unusual name conventions.

 

BizTalk and SQL: Alternatives to the SQL receive adapter. Using Msmq to receive SQL data

If we have to get data from the SQL database, the standard way is to use a receive port with SQL adapter.
SQL receive adapter is a solicit-response adapter. It periodically polls the SQL database with queries. That’s only way it can work. Sometimes it is undesirable. With new WCF-SQL adapter we can use the lightweight approach but still with the same principle, the WCF-SQL adapter periodically solicits the database with queries to check for the new records.
Imagine the situation when the new records can appear in very broad time limits, some - in a second interval, others - in the several minutes interval. Our requirement is to process the new records ASAP. That means the polling interval should be near the shortest interval between the new records, a second interval. As a result the most of the poll queries would return nothing and would load the database without good reason. If the database is working under heavy payload, it is very undesirable.
Do we have other choices? Sure. We can change the polling to the “eventing”.
The good news is the SQL server could issue the event in case of new records with triggers. Got a new record –the trigger event is fired. No new records – no the trigger events – no excessive load to the database.
The bad news is the SQL Server doesn’t have intrinsic methods to send the event data outside. For example, we would rather use the adapters that do listen for the data and do not solicit. There are several such adapters-listeners as File, Ftp, SOAP, WCF, and Msmq. But the SQL Server doesn’t have methods to create and save files, to consume the Web-services, to create and send messages in the queue, does it?
Can we use the File, FTP, Msmq, WCF adapters to get data from SQL code?
Yes, we can. The SQL Server 2005 and 2008 have the possibility to use .NET code inside SQL code. See the SQL Integration.
How it works for the Msmq, for example:
·         New record is created, trigger is fired
·         Trigger calls the CLR stored procedure and passes the message parameters to it
·         The CLR stored procedure creates message and sends it to the outgoing queue in the SQL Server computer.
·         Msmq service transfers message to the queue in the BizTalk Server computer.
·         WCF-NetMsmq adapter receives the message from this queue.
For the File adapter the idea is the same, the CLR stored procedure creates and stores the file with message, and then the File adapter picks up this file.
Using WCF-NetMsmq adapter to get data from SQL
I am describing the full set of the deployment and development steps for the case with the WCF-NetMsmq adapter.
Development:
1.       Create the .NET code: project, class and method to create and send the message to the MSMQ queue.
2.       Create the SQL code in triggers to call the .NET code.
Installation and Deployment:
1.       SQL Server:
a.       Register the CLR assembly with .NET (CLR) code
b.      Install the MSMQ Services
2.       BizTalk Server:
a.       Install the MSMQ Services
b.      Create the MSMQ queue
c.       Create the WCF-NetMsmq receive port.
The detailed description is below.
Code
.NET code
using System.Xml;
using System.Xml.Linq;
using System.Xml.Serialization;
 
//namespace MyCompany.MySolution.MyProject – doesn’t work. The assembly name is MyCompany.MySolution.MyProject
// I gave up with the compound namespace. Seems the CLR Integration cannot work with it L. Maybe I’m wrong.
    public class Event
    {
        static public XElement CreateMsg(int par1, int par2, int par3)
        {
            XNamespace ns = "http://schemas.microsoft.com/Sql/2008/05/TypedPolling/my_storedProc";
            XElement xdoc =
                new XElement(ns + "TypedPolling",
                    new XElement(ns + "TypedPollingResultSet0",
                        new XElement(ns + "TypedPollingResultSet0",
                            new XElement(ns + "par1", par1),
                            new XElement(ns + "par2", par2),
                            new XElement(ns + "par3", par3),
                        )
                    )
                );
            return xdoc;
        }
    }
 
////////////////////////////////////////////////////////////////////////
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.Transactions;
using System.Data;
using System.Data.Sql;
using System.Data.SqlTypes;
 
public class MsmqHelper
{
    [Microsoft.SqlServer.Server.SqlProcedure]
    // msmqAddress as "net.msmq://localhost/private/myapp.myqueue";
    public static void SendMsg(string msmqAddress, string action, int par1, int par2, int par3)
    {
        using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Suppress))
        {
            NetMsmqBinding binding = new NetMsmqBinding(NetMsmqSecurityMode.None);
            binding.ExactlyOnce = true;
            EndpointAddress address = new EndpointAddress(msmqAddress);
 
            using (ChannelFactory<IOutputChannel> factory = new ChannelFactory<IOutputChannel>(binding, address))
            {
                IOutputChannel channel = factory.CreateChannel();
                try
                {
                    XElement xe = Event.CreateMsg(par1, par2, par3);
                    XmlReader xr = xe.CreateReader();
                    Message msg = Message.CreateMessage(MessageVersion.Default, action, xr);
                    channel.Send(msg);
                    //SqlContext.Pipe.Send(…); // to test
                }
                catch (Exception ex)
                {
                }
            }
            scope.Complete();
        }
    }
 
SQL code in triggers
 
-- sp_SendMsg was registered as a name of the MsmqHelper.SendMsg()
EXEC
sp_SendMsg'net.msmq://biztalk_server_name/private/myapp.myqueue', 'Create', @par1, @par2, @par3
 
Installation and Deployment
On the SQL Server
Registering the CLR assembly
1.       Prerequisites: .NET 3.5 SP1 Framework. It could be the issue for the production SQL Server!
2.       For more information, please, see the link http://nielsb.wordpress.com/sqlclrwcf/
3.       Copy files:
>copy “\Windows\Microsoft.net\Framework\v3.0\Windows Communication Foundation\Microsoft.Transactions.Bridge.dll” “\Program Files\Reference Assemblies\Microsoft\Framework\v3.0 \Microsoft.Transactions.Bridge.dll”
If your machine is a 64-bit, run two commands:
>copy “\Windows\Microsoft.net\Framework\v3.0\Windows Communication Foundation\Microsoft.Transactions.Bridge.dll” “\Program Files (x86)\Reference Assemblies\Microsoft\Framework\v3.0 \Microsoft.Transactions.Bridge.dll”
>copy “\Windows\Microsoft.net\Framework64\v3.0\Windows Communication Foundation\Microsoft.Transactions.Bridge.dll” “\Program Files\Reference Assemblies\Microsoft\Framework\v3.0 \Microsoft.Transactions.Bridge.dll”
4.       Execute the SQL code to register the .NET assemblies:
-- For x64 OS:
CREATE ASSEMBLY SMdiagnostics AUTHORIZATION dbo FROM 'C:\Windows\Microsoft.NET\Framework\v3.0\Windows Communication Foundation\SMdiagnostics.dll' WITH permission_set = unsafe
CREATE ASSEMBLY [System.Web] AUTHORIZATION dbo FROM 'C:\Windows\Microsoft.NET\Framework64\v2.0.50727\System.Web.dll' WITH permission_set = unsafe
CREATE ASSEMBLY [System.Messaging] AUTHORIZATION dbo FROM 'C:\Windows\Microsoft.NET\Framework\v2.0.50727\System.Messaging.dll' WITH permission_set = unsafe
CREATE ASSEMBLY [System.ServiceModel] AUTHORIZATION dbo FROM 'C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\v3.0\System.ServiceModel.dll' WITH permission_set = unsafe
CREATE ASSEMBLY [System.Xml.Linq] AUTHORIZATION dbo FROM 'C:\Program Files\Reference Assemblies\Microsoft\Framework\v3.5\System.Xml.Linq.dll' WITH permission_set = unsafe
 
-- For x32 OS:
--CREATE ASSEMBLY SMdiagnostics AUTHORIZATION dbo FROM 'C:\Windows\Microsoft.NET\Framework\v3.0\Windows Communication Foundation\SMdiagnostics.dll' WITH permission_set = unsafe
--CREATE ASSEMBLY [System.Web] AUTHORIZATION dbo FROM 'C:\Windows\Microsoft.NET\Framework\v2.0.50727\System.Web.dll' WITH permission_set = unsafe
--CREATE ASSEMBLY [System.Messaging] AUTHORIZATION dbo FROM 'C:\Windows\Microsoft.NET\Framework\v2.0.50727\System.Messaging.dll' WITH permission_set = unsafe
--CREATE ASSEMBLY [System.ServiceModel] AUTHORIZATION dbo FROM 'C:\Program Files\Reference Assemblies\Microsoft\Framework\v3.0\System.ServiceModel.dll' WITH permission_set = unsafe
5.       Register the assembly with the external stored procedure:
CREATE ASSEMBLY [HelperClass] AUTHORIZATION dbo FROM ’<FilePath>MyCompany.MySolution.MyProject.dll' WITH permission_set = unsafe
where the <FilePath> - the path of the file on this machine!
6. Create the external stored procedure
CREATE PROCEDURE sp_SendMsg
(
       @msmqAddress nvarchar(100),
       @Action NVARCHAR(50),
       @par1 int,
       @par2 int,
       @par3 int
)
AS EXTERNAL NAME HelperClear.MsmqHelper.SendMsg
 
Installing the MSMQ Services
1.       Check if the MSMQ service is NOT installed.
To check:
 Start / Administrative Tools / Computer Management,
on the left pane open the “Services and Applications”,
search to the “Message Queuing”. If you cannot see it, follow next steps.
2.       Start / Control Panel / Programs and Features
3.       Click “Turn Windows Features on or off”
4.       Click Features, click “Add Features”
5.       Scroll down the feature list; open the “Message Queuing” / “Message Queuing Services”; and check the “Message Queuing Server” option 
6.       Click Next; Click Install; wait to the successful finish of the installation
Creating the MSMQ queue
We don’t need to create the queue on the “sender” side.
On the BizTalk Server
Installing the MSMQ Services
The same is as for the SQL Server.
Creating the MSMQ queue
1.       Start / Administrative Tools / Computer Management,
on the left pane open the “Services and Applications”,
open the “Message Queuing”, and open the “Private Queues”.
2.       Right-click the “Private Queues”; choose New; choose “Private Queue”.
3.       Type the Queue name as ’myapp.myqueue'; check the “Transactional” option.
Creating the WCF-NetMsmq receive port
I will not go through this step in all details. It is straightforward.
URI for this receive location should be 'net.msmq://localhost/private/myapp.myqueue'.
Notes
·         The biggest problem is usually on the step the “Registering the CLR assembly”. It is hard to predict where are the assemblies from the assembly list, what version should be used, x86 or x64. It is pity of such “rude” integration of the SQL with .NET.
·         In couple cases the new WCF-NetMsmq port was not able to work with the queue. Try to replace the WCF- NetMsmq port with the WCF-Custom port with netMsmqBinding. It was working fine for me.
·         To test how messages go through the queue you can turn on the Journal /Enabled option for the queue. I used the QueueExplorer utility to look to the messages in Journal. The Computer Management can also show the messages but it shows only small part of the message body and in the weird format. The QueueExplorer can do the better job; it shows the whole body and Xml messages are in good color format.

BizTalk: History of one integration project

"In the beginning God made heaven and earth. Then he started to integrate." At the very start was the requirement: integrate two working systems. [fairy tale of the system integrators]
Small digging up: It was one system. It was good but IT guys want to change it to the new one, much better, chipper, more flexible, and more progressive in technologies, more suitable for the future, for the faster world and hungry competitors.
One thing. One small, little thing. We cannot turn off the old system (call it A, because it was the first), turn on the new one (call it B, because it is second but not the last one). The A has a hundreds users all across a country, they must study B. A still has a lot of nice custom features, home-made features that cannot disappear. These features have to be moved to the B and it is a long process, months and months of redevelopment.
So, the decision was simple. Let’s move slowly not jump, let’s both systems working side-by-side several months. In this time we could teach the users and move all custom A’s special functionality to B.
That automatically means both systems should work side-by-side all these months and use the same data. Data in A and B must be in sync. That’s how the integration projects get birth.
Moreover, the specific of the user tasks requires the both systems must be in sync in real-time. Nightly synchronization is not working, absolutely.  
First draft
The first draft seems absolutely cool. Both systems keep data in SQL databases. When data changes, the Create, Update, Delete operations performed on the data, and the sync process could be started. The obvious decision is to use triggers on tables. When we are talking about data, we are talking about several entities. For example, Orders and Items [in Orders].
The decision was to use the BizTalk Server to synchronize systems. Why it was chosen is another story.
Second draft

 

Let’s take an example how it works in more details.
1.       User creates a new entity in the A system. This fires an insert trigger on the entity table. Trigger has to pass the message “Entity created”. This message includes all attributes of the new entity, but I focused on the Id of this entity in the A system. Notation for this message is id.A. System A sends id.A to the BizTalk Server.
2.       BizTalk transforms id.A to the format of the system B. This is easiest part and I will not focus on this kind of transformations in the following text. The message on the picture is still id.A but it is in slightly different format, that’s why it is changing color. BizTalk sends id.A to the system B.
3.       The system B creates the entity on its side. But it uses different id-s for entities, these id-s are id.B. System B saves id.A+id.B. System B sends the message id.A+id.B back to the BizTalk.
4.       BizTalk sends the message id.A+id.B to the system A.
5.       System A saves id.A+id.B.
Why both id-s should be saved on both systems? It was one of the next requirements. Users of both systems have to know the systems are in sync or not in sync. Users working with the entity on the system A can see the id.B and use it to switch to the system B and work there with the copy of the same entity. The decision was to store the pairs of entity id-s on both sides. If there is only one id, the entities are not in sync yet (for the Create operation).
Third draft
Next problem was the reliability of the synchronization. The synchronizing process can be interrupted on each step, when message goes through the wires. It can be communication problem, timeout, temporary shutdown one of the systems, the second system cannot be synchronized by some internal reason. There were several potential problems that prevented from enclosing the whole synchronization process in one transaction.
Decision was to restart the whole sync process if it was not finished (in case of the error). For this purpose was created an additional service. Let’s call it the Resync service.
We still keep the id pairs in both systems, but only for the fast access not for the synchronization process. For the synchronizing these id-s now are kept in one main place, in the Resync service database.
The Resync service keeps record as:
·       Id.A
·       Id.B
·       Entity.Type
·       Operation (Create, Update, Delete)
·       IsSyncStarted (true/false)
·       IsSyncFinished (true/false0
The example now looks like:
1.       System A creates id.A. id.A is saved on the A. Id.A is sent to the BizTalk.
2.       BizTalk sends id.A to the Resync and to the B. id.A is saved on the Resync.
3.       System B creates id.B. id.A+id.B are saved on the B. id.A+id.B are sent to the BizTalk.
4.       BizTalk sends id.A+id.B to the Resync and to the A. id.A+id.B are saved on the Resync.
5.       id.A+id.B are saved on the B.
Resync changes the IsSyncStarted and IsSyncFinished flags accordingly.
The Resync service implements three main methods:
·       Save (id.A, Entity.Type, Operation)
·       Save (id.A, id.B, Entity.Type, Operation)
·       Resync ()
Two Save() are used to save id-s to the service storage. See in the above example, in 2 and 4 steps.
What about the Resync()? It is the method that finishes the interrupted synchronization processes. If Save() is started by the trigger event, the Resync() is working as an independent process. It periodically scans the Resync storage to find out “unfinished” records. Then it restarts the synchronization processes. It tries to synchronize them several times then gives up.
 

 

One more thing, both systems A and B must tolerate duplicates of one synchronizing process. Say on the step 3 the system B was not able to send id.A+id.B back. The Resync service must restart the synchronization process that will send the id.A to B second time. In this case system B must just send back again also created id.A+id.B pair without errors. That means “tolerate duplicates”.
Fourth draft
Next draft was created only because of the aesthetics. As it always happens, aesthetics gave significant performance gain to the whole system.
First was the stupid question. Why do we need this additional service with special database? Can we just master the BizTalk to do something like this Resync() does?
So the Resync orchestration is doing the same thing as the Resync service.
It is started by the Id.A and finished by the id.A+id.B message. The first works as a Start message, the second works as a Finish message.
 

 

Here is a diagram the whole process without errors. It is pretty straightforward.
The Resync orchestration is waiting for the Finish message specific period of time then resubmits the Id.A message. It resubmits the Id.A message specific number of times then gives up and gets suspended. It can be resubmitted then it starts the whole process again:
waiting [, resubmitting [, get suspended]], finishing.
Tuning up
The Resync orchestration resubmits the id.A message with special “Resubmitted” flag. The subscription filter on the Resync orchestration includes predicate as (Resubmit_Flag != “Resubmitted”). That means only the first Sync orchestration starts the Resync orchestration. Other Sync orchestrations instantiated by the resubmitting can finish this Resync orchestration but cannot start another instance of the Resync.

 

Here is a diagram where system B was inaccessible for some period of time. The Resync orchestration resubmitted the id.A two times. Then system B got the response the id.A+id.B and this finished the Resync service execution.
What is interesting about this, there were submitted several identical id.A messages and only one id.A+id.B message. Because of this, the system B and the Resync must tolerate the duplicate messages. We also told about this requirement for the system B. Now the same requirement is for the Resunc.
Let’s assume the system B was very slow in the first response and the Resync service had time to resubmit two id.A messages. System B responded not, as it was in previous case, with one id.A+id.B but with two id.A+id.B messages.
First of them finished the Resync execution for the id.A. What about the second id.A+id.B? Where it goes? So, we have to add one more internal requirement. The whole solution must tolerate many identical id.A+id.B messages. It is easy task with the BizTalk. I added the “SinkExtraMessages” subscriber (orchestration with one receive shape), that just get these messages and do nothing.
Real design
Real architecture is much more complex and interesting.
In reality each system can submit several id.A almost simultaneously and completely unordered.
There are not only the “Create entity” operation but the Update and Delete operations. And these operations relate each other. Say the Update operation after Delete means not the same as Update after Create.
In reality there are entities related each other. Say the Order and Order Items. Change on one of it could start the series of the operations on another. Moreover, the system internals are the “black boxes” and we cannot predict the exact content and order of the operation series.
It worth to say, I had to spend a time to manage the zombie message problems. The zombies are still here, but this is not a problem now. And this is another story.
What is interesting in the last design? One orchestration works to help another to be more reliable. Why two orchestration design is more reliable, isn’t it something strange? The Synch orchestration takes all the message exchange between systems, here is the area where most of the errors could happen. The Resync orchestration sends and receives messages only within the BizTalk server.
Is there another design? Sure. All Resync functionality could be implemented inside the Sync orchestration. Hey guys, some other ideas?