Issue 7 Q3 2009 Table of Contents 07, 2017 · WMI and Dynamics AX Integration with BizTalk. ......

79
Page 1 Issue 7 Q3 2009 Table of Contents Preface .......................................................................................................................................................... 3 B2B 2.0 Azure a durable competitive advantage for Microsoft Take 2 ..................................................... 4 EDI - continues to dominate B2B! ........................................................................................................... 4 B2B Adoption blockers are in fact opportunities for Microsoft............................................................. 5 State of the „technology‟.......................................................................................................................... 5 B2B 2.0 with Azure the durable competitive advantage for Microsoft ............................................. 6 Unit Testing Schemas and Maps in BizTalk Server 2009 A Different Approach! ...................................... 8 Summary ................................................................................................................................................... 8 Testing schema ......................................................................................................................................... 8 Why is it Failing? ................................................................................................................................. 10 How can it be Resolved? ..................................................................................................................... 10 Now let’s look at Map Files ..................................................................................................................... 12 Why is it Failing? ................................................................................................................................. 13 How can it be Resolved? ..................................................................................................................... 13 Conclusion ............................................................................................................................................... 15 Advantages with the above approaches ............................................................................................. 15 Disadvantages with the above approaches ........................................................................................ 15 Book Review for "SOA Patterns with BizTalk Server 2009" By Richard Seroter ......................................... 16 How to Throw Typed Fault Exceptions from Orchestrations Published as WCF Services .......................... 18 Typed Faults ............................................................................................................................................ 18 Untyped Faults ........................................................................................................................................ 19

Transcript of Issue 7 Q3 2009 Table of Contents 07, 2017 · WMI and Dynamics AX Integration with BizTalk. ......

Page 1

Issue 7 Q3 2009

Table of Contents Preface .......................................................................................................................................................... 3

B2B 2.0 Azure – a durable competitive advantage for Microsoft Take 2 ..................................................... 4

EDI - continues to dominate B2B! ........................................................................................................... 4

B2B Adoption blockers are in fact opportunities for Microsoft ............................................................. 5

State of the „technology‟ .......................................................................................................................... 5

B2B 2.0 with Azure – the durable competitive advantage for Microsoft ............................................. 6

Unit Testing Schemas and Maps in BizTalk Server 2009 – A Different Approach! ...................................... 8

Summary ................................................................................................................................................... 8

Testing schema ......................................................................................................................................... 8

Why is it Failing? ................................................................................................................................. 10

How can it be Resolved? ..................................................................................................................... 10

Now let’s look at Map Files ..................................................................................................................... 12

Why is it Failing? ................................................................................................................................. 13

How can it be Resolved? ..................................................................................................................... 13

Conclusion ............................................................................................................................................... 15

Advantages with the above approaches ............................................................................................. 15

Disadvantages with the above approaches ........................................................................................ 15

Book Review for "SOA Patterns with BizTalk Server 2009" By Richard Seroter ......................................... 16

How to Throw Typed Fault Exceptions from Orchestrations Published as WCF Services .......................... 18

Typed Faults ............................................................................................................................................ 18

Untyped Faults ........................................................................................................................................ 19

Page 2

BizTalk Orchestrations and Typed Faults ................................................................................................ 19

The Solution ............................................................................................................................................ 22

Proof of Concept in Action ...................................................................................................................... 35

Show me the code! ................................................................................................................................. 35

BizTalk Resources ........................................................................................................................................ 37

BizTalk 24x7............................................................................................................................................. 37

BizTalk Gurus ........................................................................................................................................... 37

BizTalk Server Customer Advisory Team ................................................................................................ 37

Recently Released Documentation ......................................................................................................... 37

BizTalk Server 2009 Install Documentation - June 2009 Update ........................................................ 37

BizTalk Server 2009 Operations Guide - July 2009 ............................................................................. 37

Microsoft Dynamics AX integration using Microsoft BizTalk Server ........................................................... 39

Introduction ............................................................................................................................................ 39

Configuring Microsoft Dynamics AX Adapter for BizTalk ........................................................................ 41

Terminology ........................................................................................................................................ 41

Configuring Microsoft Dynamics AX – Application Integration Framework (AIF) .............................. 42

Send Data from BizTalk to Dynamics AX ............................................................................................. 54

Receive Data from Dynamics AX in BizTalk ......................................................................................... 56

Error Handling and Messages ............................................................................................................. 59

Appendix A Configuring Message Properties for sending data to Microsoft Dynamics AX ................... 73

Appendix B Related Documents/References .......................................................................................... 74

Manage BizTalk Services Thru WMI – Using C# .......................................................................................... 75

Summary ................................................................................................................................................. 75

Creating a WMI Managed Class for BizTalk ............................................................................................ 75

Terminate Suspended Instances ............................................................................................................. 76

Resume Suspended Instances ................................................................................................................. 78

Advantages of WMI with C# approach ................................................................................................... 79

Conclusion ............................................................................................................................................... 79

Page 3

Preface

This issue has articles about Azure, BizTalk WCF Adapters, Book review, Unit Testing, Management with

WMI and Dynamics AX Integration with BizTalk.

BizTalk 2009 was released in May 2009. It was followed by ESB Toolkit 2.0. ESB Toolkit is now available

to download from http://www.microsoft.com/biztalk/en/us/esb-guidance.aspx. It is built on top of

BizTalk 2009 and is a fully supported product. BizTalk Adapter Pack 2.0 was also released. In addition to

enhancements to the existing adapters it contains new adapters for SQL Server and Oracle EBS.

I want to thank Virtual TS Andy Morrison(Digineer) for helping with this issue. I also want to thank all the

contributors for submitting their articles. If you have any suggestions for improvements or want to write

in a future issue don't hesitate to contact me.

Rajinder Singh

[email protected]

Page 4

B2B 2.0 Azure – a durable competitive advantage for Microsoft Take 2 By Suren Machiraju, Principal Program Manager, Customer Experience Team, Microsoft

Business-to-business (B2B) describes commerce transactions between businesses, such as

between a manufacturer and a wholesaler, or between a hospital and an insurance

company. Such transactions are expected to be generated and consumed by Line-of-

Business applications with a high degree of automation and integration. Although the level

of automation and processing of the B2B commerce has matured in industry segments

dominated by mega- corporations such as financials (banking industry) and shipping (sea

cargo and locomotive freight); and there are great many opportunities for establishing B2B

commerce in supply chain and the Health Care industry verticals.

EDI - continues to dominate B2B!

The National Institute of Standards and Technology defines Electronic Data Interchange

(EDI) as "the computer-to-computer interchange of strictly formatted messages that

represent documents. The current volume of worldwide EDI transactions is more than 20

million per day and accounts for a significant amount of worldwide commercial activity. In

fact, some studies determined that more than one-third of the US GDP is directly supported

by EDI transactions. The EDI market is estimated to be worth $3-$7 trillion. Some estimate

that global EDI transactions are increasing between 5% and 10% per year.

EDI transaction volume is expected to continue to grow in view of the adoption of

automation strategies around the world to reduce cost of doing business; and politically

driven investment initiatives e.g., in Health Care IT initiatives in American Recovery and

Reinvestment Act of 2009.

For the sake of completeness it‟s worth mentioning here that there are other encoding

standards (Financial–SWIFT; internet commerce/B2C-xCBL or cXML; Manufacturing-

RosettaNet); however these do not match the popularity or prevalence of EDI. However there

is no technical reason to exclude building out vertical/domain specific protocol handlers in

line with the solution advocated here for EDI.

Page 5

B2B Adoption blockers are in fact opportunities for Microsoft

Many surveys conducted have consistently indicated that key adoption blockers to

implementing B2B/EDI solutions are related to investments; availability; and reliability of the

computer applications. More than 2/3rd of typical survey respondents have cited initial

investment of the computer system to be the prime adoption blocker. This is quite easy to

comprehend given the complexity of setting up computer systems to conduct B2B

transactions. These adoption blockers play easily into the strength of the Microsoft,

especially around the hosted offering with Azure. Additionally BPD has the core abilities to

design and implement on a topical solution B2B2.0!

Results of a (typical and publicly available data) survey conducted in an emerging market

are presented below.

Factor Mean* Std Deviation

Initial Investment 4.16 0.97

Customer and supplier requirements 3.72 1.10

Software reliability 3.68 1.10

Software capability 3.66 1.08

Software availability 3.66 0.88

Hardware availability 3.59 0.74

Hardware reliability 3.56 0.90

Management Support 3.55 1.15

Availability of EDI applications 3.54 1.14

Internet skills/resources 3.54 0.85

Availability of EDI standards 3.45 1.26

Availability of maturity in EDI applications 3.25 1.08

Strategic objectives 3.13 1.13

End user acceptance 3.10 1.15

Organizational resistance 2.82 1.12

*measured using a 5-point scale

State of the „technology‟

EDI encoded documents are presented as delimited flat files and although the Standards

(SDOs) and Industry Advisory organizations do not recommend transmission protocols, FTP

(EDI over dedicated networks) and HTTP along with SMIME encryption and signature (EDI-

INT or EDI over Internet) are the prevalent protocols with the latter gaining ground by the

day.

Page 6

While EDI documents over FTP are a prevalent protocol among the VAN (Value Added

Networks) providers; EDI-INT is gaining market share over VAN solutions due to low

operational costs and availability. Further dominant industry leaders (e.g., Walmart) force

suppliers to use EDI-INT over VAN further eroding the latter‟s market share. However VANs

have some advantages over EDI-INT, mostly the requirement of only one physical

connection, allowing multiple trading partners to be accessed via a single VAN connection

reliably and securely. VAN revenues are expected to continue to decrease as EDI-INT

increases. As this shift continues, VANs are focusing on the “Value Added” part of their

offerings, by offering more sophisticated mailbox features and reporting for the trading

partners they service.

There is a breed of ISV/Vendors that have sized on the opportunity to use the ubiquity of the

internet for EDI-INT transmissions while providing the single point connectivity that VAN

solutions offer. Such vendors are categorized as EDI Service Bureaus.

The attractiveness of an EDI Service Bureaus is that they have out-of-box connectivity to

100s of „Partners‟. Partners are generally the mega corporations that everyone wants to

transact with. The more comprehensive the list the grater attraction it is to its customer

community. Customers are the „smaller‟ partners that are forced into EDI solutions by their

larger „partners‟.

B2B 2.0 with Azure – the durable competitive advantage for Microsoft

Having established the business case for B2B and EDI messaging and armed with data that

the TCO for computer systems are the adoption blocker; it‟s fair to surmise that there is a

durable business model for Microsoft to provide a B2B platform to Service Bureaus thereby

providing a competitive opportunity vis-à-vis traditional VAN players in the B2B space.

Now let‟s examine the possibility of delivering a solution to customer inline with the

Microsoft Business Online Group‟s business model.

Hosted Platform: Windows Azure with .NET Services and SQL Data Services provides

the ideal platform for developing and hosting a secure cloud scale B2B Server

platform. The Server Platform would provide a range of essential (WCF) Services for

EDI Parsing; Mapping framework; Batching; Enveloping; Ack Reconciliation; Partner

Onboarding and Trading Partner Management Dashboard among other such

essential services accessed via a browser based client. Identity Services would be

Page 7

deployed for security and SQL Data Services would act as the interim store and by

choice the non repudiation-able receipt store.

On-premise client application(s): Although document management (e.g.,

upload/download of Excel documents) could be achieved via a browser client;

additionally an on-premise „black box‟ solution is proposed. The client would

comprise of a Silver Light client and use .NET components (WCF, WF, XSLT) and .EDI

libraries to process, establish connectivity, authenticate and upload the documents

to the Server. WCF streaming functionality with binary encoding and compression

would provide the superior performance for uploading the XML based content; while

Silver Light client would provide the rich client experience. Integration options

(adapters?) would be available for a set of back end applications (e.g., Dynamics

ERP). For customers desiring BPM and advanced connectivity options, the well

established BizTalk Server could be a preferred option with out-of-box connectivity to

back end systems while being able to offer comprehensive EDI functionality.

Importantly the client and dashboard will be customizable by the Service Bureau to

address the domain needs.

Monetization strategies will be in line with Business Online Service Group‟s licensing models

– usage or subscription based.

Page 8

Unit Testing Schemas and Maps in BizTalk Server 2009 – A Different

Approach! By Sooraj Payyoormana, Senior Development Lead, Microsoft

This article assumes you are familiar with BizTalk Server Schemas, Maps and Visual Studio 2008 Unit

testing scripts.

Audience: BizTalk Developers

Technologies: BizTalk Server 2009, VS.NET 2008

Skill level: Beginner to Expert

The source code used in this article can be downloaded from the following location:

http://cid-

61b5fd0cc0cf5b2e.skydrive.live.com/self.aspx/Source%20Code/BTSUnitTests/BTSUnitTests.zip

Summary There was an article on “Unit Testing in BizTalk Server 2009” by Rajinder Singh in BizTalk Hotrod

magazine1. I followed this article and the MSDN article on “Using the Unit Testing Features with

Schemas and Maps”2 to write unit test scripts for schema and map files.

In this article, I am trying to explain the approaches I took to resolve the following issues which I faced

during my unit test script development.

Not able to do the unit testing on the schema which was referring other schemas that are part

of different BizTalk assembly.

Unit Test scripts are not working on the map file which uses multi-part message as input.

Testing schema I needed to create automated unit test scripts for the “SalesOrder” and “PurchaseOrder” schemas.

The following unit testing script was written to validate the “SalesOrder” schema using valid and invalid

XML instances. Here I had written the unit test scripts based on the Unit Testing feature of BizTalk

Server 2009.

[TestMethod]

public void TestSOSchemaWithBuiltInMethod()

{

TestableSchemaBase salesOrderSchema = new SalesOrder.Schemas.SalesOrder();

Assert.IsTrue(salesOrderSchema.ValidateInstance(VALID_SO_INSTANCE,

Microsoft.BizTalk.TestTools.Schema.OutputInstanceType.XML), "Test failed for the Valid

Instance scenario.");

Assert.IsFalse(salesOrderSchema.ValidateInstance(INVALID_SO_INSTANCE,

Microsoft.BizTalk.TestTools.Schema.OutputInstanceType.XML), "Test failed for the

InValid Instance scenario.");

1 Issue 5 Q1 2009. See http://biztalkhotrod.com/Documents/BizTalk%20HotRod%20Magazine%20Q1%202009.pdf

2 http://msdn.microsoft.com/en-us/library/dd224279.aspx

Page 9

}

Let us see the Test Result after executing the above test method.

The test passed without any errors.

Now, let us write the unit test script for “PurchaseOrder” schema.

The “PurchaseOrder” schema was created by importing two schemas named “DocHeader” schema and

“OrderComponents” schema from different BizTalk assemblies.

We will follow the above mentioned code to write the unit test script for “PurchaseOrder” schema.

[TestMethod]

public void TestPOSchemaWithBuiltInMethod()

{

TestableSchemaBase purchaseOrderSchema = new

PurchaseOrder.Schemas.PurchaseOrder();

Assert.IsTrue(purchaseOrderSchema.ValidateInstance(VALID_PO_INSTANCE,

Microsoft.BizTalk.TestTools.Schema.OutputInstanceType.XML), "Test failed for the valid

Instance scenario.");

Assert.IsFalse(purchaseOrderSchema.ValidateInstance(INVALID_PO_INSTANCE,

Microsoft.BizTalk.TestTools.Schema.OutputInstanceType.XML), "Test failed for the

invalid Instance scenario.");

}

Let us execute the test script and see the result.

Page 10

The test failed! Are there any issues with the input instance XML files? Any issue with the schema(s)? Is

the instance XML file path is valid?

I manually verified whether the XML instance file path was wrong, whether the instances where

valid/invalid for their scenario (against the schema) and whether there were issues with the schemas.

There were no issues.

Why is it Failing?

The ValidateInstance method of TestableSchemaBase class returns a Boolean value.

Unfortunately, ValidateInstance method does not return any error information and it doesn’t

throw any exceptions. In the above code it returns false always, due to this, the first test method with

Assert.IsTrue is failing. One of the reasons could be that the ValidateInstance method is not

able to resolve the schemas specified in the import section which are referenced from other BizTalk

assemblies. The Assert.IsFalse in the above code block will execute successfully as the

ValidateInstance method returns false always.

How can it be Resolved?

The XmlReaderSettings and XmlReader3 classes can be used to validate the schema. I wrote a

helper class to do the XML validation using these classes. In the validation implementation code, the

method takes the object of the schema class and the XML instance file path.

public static ValidationResult ValidateSchema(TestableSchemaBase schemaObject, string

xmlInstancePath)

Now, create the XmlReaderSettings object using the schemaObject argument and set its

ValidationType property and ValidationEventHandler event handler.

XmlReaderSettings settings = new XmlReaderSettings();

XmlSchemaSet schemaSet = new XmlSchemaSet();

schemaSet.Add(schemaObject.Schema);

settings.Schema = schemaSet;

settings.ValidationType = ValidationType.Schema;

settings.ValidationEventHandler += new

ValidationEventHandler(SchemaReaderSettingsValidationEventHandler);

Next, create the XmlReader object using the XmlReaderSettings object created above, and with

the XML instance specified in the xmlInstancePath argument.

using (XmlReader reader = XmlReader.Create(xmlInstancePath, settings))

{

XmlValidatingReader xmlValidator = new

XmlValidatingReader(xmlInstanceReader);

3 The XmlReader class can enforce validation using a document type definition (DTD) or XML Schema definition

language (XSD) schema. Settings on the XmlReaderSettings object used by the Create method determine what type of data validation, if any, the XmlReader object supports – from MSDN.

Page 11

Read and validate the schema.

while (reader.Read())

{

if (!_IsValid)

break;

}

The code for the validation event handler:

void SchemaReaderSettingsValidationEventHandler(object sender, ValidationEventArgs

arguments)

{

if (arguments.Severity == XmlSeverityType.Error)

{

_IsValid = false;

validationMessage = arguments.Message;

Trace.WriteLine(arguments.Message);

}

}

The ValidationResult class code snippet:

/// <summary>

/// Class for returning the validation results.

/// </summary>

public class ValidationResult

{

/// <summary>

/// Return true if the schema is valid else false.

/// </summary>

public bool IsValid { get; set; }

/// <summary>

/// Returns the error message if the schema validation is failed.

/// </summary>

public string ValidationMessage { get; set; }

}

That’s it. You are now ready to call the ValidateSchema method from the unit test script:

Finally this is the customized unit test script for testing “PurchaseOrder” schema:

[TestMethod]

public void TestPOSchemaWithCustomMethod()

{

TestableSchemaBase purchaseOrderSchema = new

PurchaseOrder.Schemas.PurchaseOrder();

ValidationResult result1 =

XmlValidationHelper.ValidateSchema(purchaseOrderSchema, VALID_PO_INSTANCE);

Assert.IsTrue(result1.IsValid, "Test failed for the Valid Instance

scenario. Exception: {0}", result1.ValidationMessage);

ValidationResult result2 =

XmlValidationHelper.ValidateSchema(purchaseOrderSchema, INVALID_PO_INSTANCE);

Assert.IsFalse(result2.IsValid, "Test failed for the InValid Instance

scenario. Exception: {0}", result.ValidationMessage);

}

Page 12

In the above code block, we are creating the object of the “PurchaseOrder” schema and passes as the

first argument to the ValidateSchema method of the XmlValidationHelper class. The

ValidationResult class is used to capture the error message while validating the schema. The

IsValid property returns the Boolean value, which indicates the validation is successful or not and the

ValidationMessage returns the error message.

Now we will execute this test script and see the test result.

Yes, this time the test passed without any errors.

Now let’s look at Map Files The “PurchaseOrder” schema instance should be transformed as a “SalesOrder” schema instance. The

map file which is created for the transformation takes a multi-part message as the input and creates the

instance of the “SalesOrder” schema instance as output. One part of the multi-part message input is the

instance of the “PurchaseOrder” schema and the other is the instance of the “Store” schema, which is

created using a .NET assembly from the Orchestration. I have created an instance file for this multi-part

message type using the “Test Map” menu option of Visual Studio context menu.

The following unit test script is written for testing the map file, using the TestMap method of

TestableMapBase class.

[TestMethod]

public void TestSOMapping()

{

TestableMapBase target = new TransformSOMessage();

InputInstanceType inputType = InputInstanceType.Xml;

OutputInstanceType outputType = OutputInstanceType.XML;

target.TestMap(INPUT_FILE, inputType, OUTPUT_FILE, outputType);

Assert.IsTrue(File.Exists(OUTPUT_FILE), "Failed to generate output

file..");

ValidationResult vr = XmlValidationHelper.ValidateOutput(OUTPUT_FILE,

EXPECTED_FILE);

Assert.IsTrue(vr.IsValid, "Mapping test failed. Exception {0}",

vr.ValidationMessage);

}

We will execute the above test script and see the result.

Page 13

The test is failed!

Why is it Failing?

The generated output file and the expected results are not matching. The TestMap method generates

output with whitespace. Another reason could be that the unit test feature of BizTalk Server 2009

doesn’t support multi-part message types for testing map files.

How can it be Resolved?

By using the XslCompiledTransform 4class we can transform the schema instance with the help of

XSLT specified in the map file. BizTalk Server does the transformation based on the XSLT 1.0 syntax.

I wrote a c# function using the XslCompiledTransform class. Here is the code:

public static ValidationResult TestMapper(string inputPath, TransformBase mapperClass,

string outPutPath,

string expectedResultPath)

{

string xsltContent = mapperClass.XmlContent;

ValidationResult vr = new ValidationResult { IsValid = true,

ValidationMessage = string.Empty };

using (XmlTextReader xmlReader = new XmlTextReader(new

StringReader(xsltContent)))

{

XPathDocument inputDocument = new XPathDocument(inputPath);

XslCompiledTransform myXslTrans = new XslCompiledTransform();

myXslTrans.Load(xmlReader);

XmlWriterSettings settings = new XmlWriterSettings();

settings.OmitXmlDeclaration = true;

using (XmlWriter xmlWriter = XmlWriter.Create(outPutPath, settings))

{

myXslTrans.Transform(inputDocument, mapperClass.TransformArgs,

xmlWriter);

}

}

if (File.Exists(outPutPath))

{

4 The XslCompiledTransform class is an XSLT processor that supports the XSLT 1.0 syntax. It is a new

implementation and includes performance gains when compared to the obsolete XslTransform class. The structure of the XslCompiledTransform class is very similar to the XslTransform class. The Load method loads and compiles the style sheet, while the Transform method executes the XSLT transform. – From MSDN.

Page 14

vr = XmlValidationHelper.ValidateOutput(outPutPath,

expectedResultPath);

}

else

{

vr.IsValid = false;

vr.ValidationMessage = "Mapping failed..Output file is not generated";

}

return vr;

}

string xsltContent = mapperClass.XmlContent;

The above code returns the XSLT defined in the map class. Using that XSLT, we will be able to generate a

XML file which is the expected output from the map.

settings.OmitXmlDeclaration = true;

The OmitXmlDeclaration property is used to create the XML without having the XML declaration and allow us to do the comparison between the generated output file with the expected result. XmlValidationHelper.ValidateOutput method is used here to compare both the XML file and it reports the errors during the comparison. This code is available in the above mentioned for download. Finally the unit test script will look like this: [TestMethod]

public void TestSOMappingUsingCustomMethod()

{

TransformSOMessage salesOrderMap = new TransformSOMessage();

ValidationResult vr = XmlMapperHelper.TestMapper(INPUT_FILE,

salesOrderMap, OUTPUT_FILE, EXPECTED_FILE);

Assert.IsTrue(vr.IsValid, "Mapping test failed. Exception {0}",

vr.ValidationMessage);

}

Let us execute the test script and see the result.

Wow! The test passed without any errors.

Page 15

Conclusion The ValidateInstance method of the TestableSchemaBase class does not return any error

information, it always returns either true or false. Due to this we are not able to find the exact error with

the schema unit tests. My article is trying to address this issue and helps to find the exact error while

validating the schema.

Even though you will be able to find out the errors while testing the map files using the TestMap

method of the TestableMapBase class, we are not be able to compare the output file with the

expected result. Also, the Unit Testing feature of BizTalk Server 2009 doesn’t support unit testing of map

file which uses the multi-part type messages.

My article is trying to address these issues of map file unit testing and reports the issues.

Advantages with the above approaches

Generic and reusable code to do the unit test scripts on map and schema files

Better validation and error reporting

Write unit test scripts to test and validate map, when the input for the map file is a multi-part

message

Write unit test scripts to test schema, when there are one or more external referenced schemas

imported in the schema

Disadvantages with the above approaches

Developer should write the custom classes and methods for validating the Schemas and map

files for the first time. Later this can be reused in other unit test projects.

The developer should know more on XML, XSD and its related classes and methods in .NET.

Whereas with the BizTalk unit test script methods, the developer need not know these

classes/methods.

Happy Unit Testing!

Page 16

Book Review for "SOA Patterns with BizTalk Server 2009" By Richard

Seroter

I was recently asked to review this book. Like the title implies this book is shows you how to use BizTalk

to implement Service Oriented Architecture. It is written for developers and architects. It is not meant to

be a BizTalk tutorial. SOA cannot be implemented by any one tool. However anyone trying to implement

Service Oriented applications on Microsoft Platform should learn more about Windows Communication

Foundation and BizTalk Server.

Chapter 1 gives a brief overview of BizTalk Architecture and also describes artifacts needed to develop

BizTalk based solutions.

Chapter 2 gives you primer of Windows Communication Foundation. You will need to rely on other

sources to learn more about WCF.

Chapter 3 describes BizTalk WCF Adapters. It also shows how to use WCF adapters from Orchestrations

and Messaging only scenarios. It shows how to publish Orchestrations as WCF service and how to

consume a WCF Service from an Orchestration. This chapter did a great job in explaining how to use

BizTalk WCF adapters.

Chapter 4 starts by explaining core principles of SOA. It expands on this principles and shows how

BizTalk can be used to design SOA solutions. It also identifies various message exchange patterns and

service types.

Chapter 5 does an excellent job in documenting the best practices for building schemas that will work

well with the type of service you have chosen. It talks about building canonical schemas and benefits,

limitations of schema reuse. It also shows the impact of data type and node definition on the client

code. There is also a section on using generic schemas and tips for building contract first endpoints. This

chapter is must read for anyone who is designing schemas in a SOA based solution.

Chapter 6 explains benefits of asynchronous communication and how one can implement them with

WCF. It also shows how to implement such a solution with BizTalk. There is also a section on queue

based communication.

Chapter 7 you will learn about Orchestrations. It explains Direct binding and dynamic service ports. It

also shows how to implement various message exchange patterns in an Orchestration. There is a

section that shows how to chain Orchestrations together with the help of Business Rules Engine. The

chapters finishes with a section on role of Transactions and Complex Event Processing

Chapter 8 is must read for anyone who is grappling with versioning schemas, services and

Orchestrations. Versioning schemas and other BizTalk artifacts has always been tricky. This chapter is

one of the best reference you will find out this topic.

Page 17

Chapter 9 describes WCF SQL Server Adapter that was recently released as a part of BizTalk Adapter

Pack 2.0. It shows the differences between the old SQL adapter and the new adapter. It also shows you

various ways in which you can use this new adapter.

Chapter 10 UDDI V3 is now a part of BizTalk 2009. This chapter explains UDDI and shows you how to use

the UDDI Service that is a part of BizTalk 2009. There is not much documentation out there for UDDI and

this chapter will be a great resource for anyone interested in using UDDI.

Chapter 11 Gives you an overview of ESB Guidance 2.0. It describes various components of the ESB

Toolkit. It also shows how to implement various scenarios with ESB Toolkit. This chapter did a great job

in covering ESB Toolkit.

Chapter 12 This chapter briefly talks about Dublin, .Net Services and Oslo.

I found this book to be very easy to read. Richard has a knack for explaining concepts clearly with the

help of examples. There are not many books available that do such a good job of showing how to use

BizTalk to implement SOA. Anyone implementing SOA solutions on Microsoft platform will benefit from

this book.

Rajinder Singh

Technical Solutions Professional

Microsoft

Page 18

How to Throw Typed Fault Exceptions from Orchestrations Published as

WCF Services

By Paolo Salvatori, Principal Program Manager, Customer Experience Team, Microsoft Italy

In general, a WCF Web Service can return two types of SOAP faults: typed and untyped SOAP faults. BizTalk development tools allow you to publish an Orchestration was a WCF Service. Out of the box BizTalk Orchestrations published as WCF Services can throw untyped faults. This article will show you how to throw Typed Faults from Orchestrations published as a WCF Service.

Typed Faults

In order to throw a typed fault, a service operation must be decorated with a System.ServiceModel.FaultContractAttribute that specifies a fault data contract defined earlier. The following code snippet shows a WCF web service called HelloWorld which implements the IHelloWorld service or contract interface. This interface exposes a single synchronous operation called SayHello that is decorated with the FaultContractAttribute. The attribute declares that the SayHello method can throw a typed fault exception defined by the CustomError data contract class. The implementation of the SayHello method in the HelloWorld class checks if the incoming request is null and in this case it throws an error of type FaultException<CustomError>.

namespace Microsoft.BizTalk.CAT.Samples.PublishTypedFaults.Services

{

[Serializable]

[DataContract(Name = "HelloWorldRequest", Namespace =

"http://microsoft.biztalk.cat/10/helloworld")]

public class HelloWorldRequest

{

...

}

[Serializable]

[DataContract(Name = "HelloWorldResponse", Namespace =

"http://microsoft.biztalk.cat/10/helloworld")]

public class HelloWorldResponse

{

...

}

[Serializable]

[DataContract(Name = "CustomError", Namespace =

"http://microsoft.biztalk.cat/10/customerror")]

public class CustomError

{

...

}

[ServiceContract(Name = "HelloWorld", Namespace =

Page 19

"http://microsoft.biztalk.cat/10/helloworld")]

public interface IHelloWorld

{

[OperationContract(Action = "SayHello", ReplyAction = "SayHello",

ProtectionLevel = ProtectionLevel.None)]

[FaultContract(typeof(CustomError), Action = "CustomErrorFault")]

HelloWorldResponse SayHello(HelloWorldRequest request);

}

[ServiceBehavior(Name = "HelloWorld", Namespace =

"http://microsoft.biztalk.cat/10/helloworld")]

public class HelloWorld : IHelloWorld

{

[OperationBehavior]

public HelloWorldResponse SayHello(HelloWorldRequest request)

{

if (request == null || string.IsNullOrEmpty(request.Name))

{

throw CreateFault(NameCannotBeNullOrEmpty);

}

return new HelloWorldResponse(string.Format(SayHelloFormat,

request.Name));

}

private FaultException<CustomError> CreateFault(string message)

{

...

return fault;

}

}

}

Untyped Faults

Untyped SOAP faults are those that do not require a service operation to be decorated with a FaultContractAttribute that specify a custom data contract class.

BizTalk Orchestrations and Typed Faults

BizTalk Server 2006 R2 and BizTalk Server 2009 allow handling typed fault contracts when consuming WCF services from within orchestrations. The steps necessary to implement this technique are clearly described in the article “How to Handle Typed Fault Contracts in Orchestrations” on MSDN. Instead, WCF adapters actually do not support processing typed fault contract exceptions within orchestrations published as WCF services. However, untyped SOAP faults can always be returned by orchestrations or pipelines. For more information on this topic review the article “How to Throw Fault Exceptions from Orchestrations Published as WCF Services” on MSDN.

This constraint arises from how the Receive Handler of WCF Adapters is actually implemented. The WCF Receive Adapter instantiates a singleton instance of the BizTalkServiceInstance class for each WCF Receive Location. This class can be found in the Microsoft.BizTalk.Adapter.Wcf.Runtime.dll assembly. In particular, as you can see in the picture below, the BizTalkServiceInstance class is decorated with the attribute

Page 20

ServiceBehavior(InstanceContextMode=InstanceContextMode.Single, ConcurrencyMode=ConcurrencyMode.Multiple).

Therefore, all the incoming requests towards a given WCF Receive Location are managed by the same singleton object. When you enable a WCF Receive Location, the Adapter initializes and opens a dedicated instance of a ServiceHost-derived class (WebServiceHost), which dynamically builds the WCF runtime components within the in-process or isolated host process. This includes the channel stack, dispatcher, and generic service instance. Almost all of the WCF adapters can be hosted within the BizTalk service process itself – the only exception is WCF-CustomIsolated, which must be used in a BizTalk isolated host by design. Even the HTTP adapters can be hosted in-process now. The WCF Adapters build the generic service contracts shown in the table below. Each service contract implemented by the BizTalkServiceInstance covers a different scenario.

[ServiceContract(Namespace = "http://www.microsoft.com/biztalk/2006/r2/wcf-adapter")]

public interface IOneWayAsync

{

// Methods

[OperationContract(AsyncPattern = true, IsOneWay = true, Action = "*")]

IAsyncResult BeginOneWayMethod(Message message, AsyncCallback callback, object state);

[OperationContract(IsOneWay = true, Action = "BizTalkSubmit")]

Page 21

void BizTalkSubmit(Message message);

void EndOneWayMethod(IAsyncResult result);

}

[ServiceContract(Namespace = "http://www.microsoft.com/biztalk/2006/r2/wcf-adapter")]

public interface IOneWayAsyncTxn

{

// Methods

[OperationContract(AsyncPattern = true, IsOneWay = true, Action = "*")]

IAsyncResult BeginOneWayMethod(Message message, AsyncCallback callback, object state);

[OperationContract(IsOneWay = true, Action = "BizTalkSubmit")]

void BizTalkSubmit(Message message);

void EndOneWayMethod(IAsyncResult result);

}

[ServiceContract(Namespace = "http://www.microsoft.com/biztalk/2006/r2/wcf-adapter")]

public interface ITwoWayAsync

{

// Methods

[OperationContract(AsyncPattern = true, IsOneWay = false, Action = "*", ReplyAction =

"*")]

IAsyncResult BeginTwoWayMethod(Message message, AsyncCallback callback, object state);

[OperationContract(IsOneWay = false, Action = "BizTalkSubmit")]

Message BizTalkSubmit(Message message);

Message EndTwoWayMethod(IAsyncResult result);

}

[ServiceContract(Namespace = "http://www.microsoft.com/biztalk/2006/r2/wcf-adapter")]

public interface ITwoWayAsyncVoid

{

// Methods

[OperationContract(AsyncPattern = true, IsOneWay = false, Action = "*", ReplyAction =

"*")]

IAsyncResult BeginTwoWayMethod(Message message, AsyncCallback callback, object state);

[OperationContract(IsOneWay = false, Action = "BizTalkSubmit")]

void BizTalkSubmit(Message message);

void EndTwoWayMethod(IAsyncResult result);

}

[ServiceContract(Namespace = "http://www.microsoft.com/biztalk/2006/r2/wcf-adapter")]

public interface ITwoWayAsyncVoidTxn

{

// Methods

[TransactionFlow(TransactionFlowOption.Mandatory), OperationContract(AsyncPattern =

true, IsOneWay = false, Action = "*", ReplyAction = "*")]

IAsyncResult BeginTwoWayMethod(Message message, AsyncCallback callback, object state);

[TransactionFlow(TransactionFlowOption.Mandatory), OperationContract(IsOneWay = false,

Action = "BizTalkSubmit")]

void BizTalkSubmit(Message message);

void EndTwoWayMethod(IAsyncResult result);

}

As you can easily see in the code above, all the service contracts implemented by the BizTalkServiceInstance Class are generic and asynchronous. In fact, one-way service operations are decorated with [OperationContract(AsyncPattern = true, IsOneWay = true, Action = "*")] attribute, while request-response methods are decorated with the [OperationContract(AsyncPattern = true, IsOneWay = false, Action = "*", ReplyAction = "*")] attribute. Besides, they receive a generic inbound message of type System.ServiceModel.Channels.Message and eventually return a message of the same type.

Page 22

As a consequence, these methods can accept any request message and eventually process any reply message. However, since these operations are generic and untyped, they are not decorated by any FaultContractAttribute. As a consequence, WCF Receive Locations cannot return typed fault exceptions. Since every WCF Receive Location is implemented as an instance of the BizTalkServiceInstance and this class cannot be customized or inherited to expose typed service contracts, BizTalk Server does not natively support throwing typed fault exceptions within orchestrations published as WCF services or more in general throwing typed fault exceptions within a WCF Receive Location.

At this point a question arises: is there any workaround to throw typed fault exceptions within orchestrations published as WCF services? The answer, fortunately, is yes.

The Solution

The WCF-Custom and WCF-CustomIsolated Adapters provided by BizTalk Server 2006 R2 and BizTalk Server 2009 allow to define a custom WCF binding configuration to meet your precise communication needs. These adapters can be used to define custom WCF configurations for Send Ports or Receive Locations and extend their standard functionality using custom components as endpoint and service behaviors, message inspectors, custom bindings, binding elements, channels, etc. Therefore, I decided to create the following custom components:

Microsoft.BizTalk.CAT.Samples.PublishTypedFaults.WsdlExportExtensions assembly: flattens and extends the WSDL generated by the BizTalk WCF Service Publishing Wizard to enable WCF Receive locations to expose typed soap faults.

Microsoft.BizTalk.CAT.Samples.PublishTypedFaults.MessageInspector assembly: intercepts a reply message and when this latter is a fault, it creates and returns a typed fault message.

The following picture depicts the architecture of the proof of concept I implemented to test these components:

1. A WCF-CustomIsolated Request-Response Receive Location receives a new xml document from a client application.

2. The XML disassembler component within the XMLTransmit pipeline promotes the MsgType context property. The Message Agent submits the incoming message to the MessageBox (BizTalkMsgBoxDb).

Page 23

3. The inbound request starts a new instance of the HelloWorld orchestration type. 4. The orchestration checks the incoming HelloWorldRequest message, and if the Name

element is null or empty, it creates and return a new fault message of type CustomError. Otherwise, the orchestration returns a reply message of type HelloWorldResponse.

5. The HelloWorld orchestration publishes the reply message to the MessageBox (BizTalkMsgBoxDb).

6. The response message is retrieved by the WCF-CustomIsolated Request-Response Receive Location.

7. The reply message is processed by the CustomErrorMessageInspector component. If the response is a fault message, it creates a new typed fault message using the configuration data set on the Receive Location.

8. The reply message is returned to the client application.

The following picture shows the XML Schema which defines the CustomError typed fault.

The following figure shows the configuration of the WCF-CustomIsolated Request-Response Receive Location.

Page 25

The Receive Location exposes an endpoint that uses the WsHttpBinding and make use of the serviceThrottling service behavior (see System.ServiceModel.Description.ServiceThrottlingBehavior for more information) and 2 custom endpoint behaviors:

customError wsdlExport

These components must be configured in the machine.config as follows:

<?xml version="1.0" encoding="UTF-8"?>

<configuration>

...

<system.serviceModel>

...

<extensions>

<behaviorExtensions>

...

<add name="customError"

type="Microsoft.BizTalk.CAT.Samples.PublishTypedFaults.MessageInspector.CustomErrorBehaviorExte

nsionElement,

Microsoft.BizTalk.CAT.Samples.PublishTypedFaults.MessageInspector, Version=1.0.0.0,

Culture=neutral,

PublicKeyToken=d7f63d8d08d8f3a2" />

Page 26

<add name="wsdlExport"

type="Microsoft.BizTalk.CAT.Samples.PublishTypedFaults.WsdlExportExtensions.WsdlExportBehaviorE

xtensionElement,

Microsoft.BizTalk.CAT.Samples.PublishTypedFaults.WsdlExportExtensions, Version=1.0.0.0,

Culture=neutral,

PublicKeyToken=d7f63d8d08d8f3a2" />

</behaviorExtensions>

</extensions>

</system.serviceModel>

</configuration>

The “Include exception detail in faults” option must be set on the Messages tab to enable the WCF Receive Location to return the error detail in fault messages. Below you can see the code of the CustomErrorMessageInspector component. The constructor retrieves configuration data from the Receive Port configuration, while the IDispatchMessageInspector::BeforeSendReply method intercepts the reply message and if this latter is a fault, it generates a typed fault exception using the configuration data.

namespace Microsoft.BizTalk.CAT.Samples.PublishTypedFaults.MessageInspector

{

/// <summary>

/// This class can be customized to create a message inspector.

/// </summary>

public class CustomErrorMessageInspector : IDispatchMessageInspector,

IClientMessageInspector

{

#region Private Constants

...

#endregion

#region Private Fields

...

#endregion

#region Public Constructors

public CustomErrorMessageInspector(bool enabled,

bool traceEnabled,

int maxBufferSize,

string typedFaults)

{

this.enabled = enabled;

this.traceEnabled = traceEnabled;

this.maxBufferSize = maxBufferSize;

this.typedFaults = typedFaults;

try

{

if (!string.IsNullOrEmpty(typedFaults))

{

TypedFaults faultData = SerializationHelper.XmlDeserialize(typedFaults,

typeof(TypedFaults)) as TypedFaults;

if (faultData != null &&

faultData.FaultList != null &&

faultData.FaultList.Count > 0)

{

for (int i = 0; i < faultData.FaultList.Count; i++)

{

if (!string.IsNullOrEmpty(faultData.FaultList[i].Action) &&

Page 27

!string.IsNullOrEmpty(faultData.FaultList[i].Name))

{

faults.Add(string.Format(MessageTypeFormat,

faultData.FaultList[i].Namespace,

faultData.FaultList[i].Name ??

string.Empty),

new

CustomErrorFaultInfo(faultData.FaultList[i].Action,

faultData.FaultList[i].Reason));

}

}

}

}

}

catch (Exception ex)

{

EventLog.WriteEntry(Source, ex.Message, EventLogEntryType.Error);

}

}

#endregion

#region IDispatchMessageInspector Members

public object AfterReceiveRequest(ref Message request, IClientChannel channel,

InstanceContext instanceContext)

{

return request.Headers.Action;

}

public void BeforeSendReply(ref Message reply, object correlationState)

{

try

{

if (enabled &&

reply.IsFault &&

string.Compare(((string)correlationState), TransferGetNamespace, true) !=

0)

{

string action = correlationState as string;

MessageFault fault = MessageFault.CreateFault(reply, maxBufferSize);

string detail = fault.Reason.ToString();

CustomErrorMessageFault faultMessage = new CustomErrorMessageFault(faults,

new

FaultCode(FaultCodeName), detail, traceEnabled);

Message message = Message.CreateMessage(reply.Version, faultMessage, null);

message.Headers.CopyHeadersFrom(reply.Headers);

message.Properties.CopyProperties(reply.Properties);

if (string.IsNullOrEmpty(faultMessage.Action))

{

message.Headers.Action = action;

}

else

{

message.Headers.Action = faultMessage.Action;

}

reply = message;

}

}

catch (Exception ex)

{

EventLog.WriteEntry(Source, ex.Message, EventLogEntryType.Error);

throw ex;

Page 28

}

return;

}

#endregion

#region IClientMessageInspector Members

public void AfterReceiveReply(ref Message reply, object correlationState)

{

return;

}

public object BeforeSendRequest(ref Message request, IClientChannel channel)

{

return null;

}

#endregion

}

}

The following table contains the XML snippet used as configuration data for the CustomErrorMessageInspector component. As you can see, it allows defining multiple typed faults in a declarative way. At runtime it will use this data to recognize a fault reply message and accordingly set the Action and Reason properties of the fault message returned.

<TypedFaults xmlns="http://microsoft.biztalk.cat/10/typedfaults">

<TypedFault>

<Action>SayHello</Action>

<Name>CustomError</Name>

<Namespace>http://microsoft.biztalk.cat/10/customerror</Namespace>

<Reason>Custom Error</Reason>

</TypedFault>

</TypedFaults>

If you set the TraceEnabled property to true, at runtime the CustomErrorMessageInspector component will produce a trace that you can intercept and review with a tool such as Debug as shown in the picture below.

Page 29

The WCF-Receive Location can be created using the BizTalk WCF Service Publishing Wizard. In particular, this allows to create a WCF Receive Location to expose the HelloWorld orchestration as a WCF service. Moreover, setting the Enable metadata endpoint option it’s possible to enable the WCF Receive Location to expose a Metadata Endpoint.

This allows a developer to use Visual Studio or a tool such as svcutil to generate a proxy class to invoke the WCF Receive Location. Now, let’s say that you want to create a WCF client application to invoke the WCF Receive Location. Within Visual Studio you can create a new Windows Application, right-click the project inside the Solution Explorer and then select “Add Service Reference”. If the WCF Receive Location exposes a Metadata Endpoint, this operation will create a proxy class to invoke the corresponding WCF web service. However, if you review the code and in particular the contract interface, you’ll realize that the SayHello method is not decorated with a FaultContractAttribute. This is due to the fact, that since BizTalk Server does not support throwing typed fault exceptions, the native wsdl returned by the Metadata Endpoint exposed by the WCF Receive location does not contain any soap fault message. In order to sort out this problem, you can adopt one of the following techniques:

Create and expose a custom wsdl that contains the definition of your typed soap faults. Create a custom endpoint behavior to dynamically modify the wsdl produced by BizTalk.

The first technique is quite straightforward:

You manually define a custom wsdl using a text or xml editor. You publish the resulting wsdl file to IIS (e.g. http://localhost/samples/service.wsdl) You configure your WCF-Custom or WCF-CustomIsolated Receive Location to expose

metadata and in particular the newly created wsdl file.

Page 30

In order to accomplish the finale step, you can proceed as follows:

Start the BizTalk Server Administration Console. Open your WCF-Custom/WCF-CustomIsolated Receive Location. Click the Configure button in the Transport section. Click the Behavior tab. Right-click the Service Behavior node and choose to Add Extension. In the Select Behavior Extension window, choose the serviceMetadata component. Set the value of the httpGetEnabled property of the serviceMetadata behavior to True

(see the picture below). Set the value of the externalMetadataLocation property of the serviceMetadata behavior

to the url of your hand-built wsdl (see the picture below).

The second technique consists in creating a custom component called WsdlExtensions to modify at run-time the wsdl returned by the Metadata Endpoint exposed by a WCF-

Page 31

Custom/WCF-CustomIsolated Receive location. This component is implemented as an a custom endpoint behavior and it can be used along with any WCF-Custom or WCF-CustomIsolated Receive Location, as shown in the picture below.

The WsdlExtensions property exposed by the component accepts an XML snippet that allows to specify how the wsdl has to be customized at runtime.

<WsdlExtensions xmlns="http://microsoft.biztalk.cat/10/wsdlextensions">

<Prefix>bts</Prefix>

<XmlSchemas>

<XmlSchema>

<Name>CustomError</Name>

<Namespace>http://microsoft.biztalk.cat/10/customerror</Namespace>

</XmlSchema>

</XmlSchemas>

<Messages>

Page 32

<Message>

<Name>HelloWorld_SayHello_CustomErrorFault_FaultMessage</Name>

<Namespace>http://microsoft.biztalk.cat/10/customerror</Namespace>

<Parts>

<Part>

<Name>detail</Name>

<Element>CustomError</Element>

</Part>

</Parts>

</Message>

</Messages>

<PortTypes>

<PortType>

<Name>HelloWorld</Name>

<Operations>

<Operation>

<Name>SayHello</Name>

<Faults>

<Fault>

<Name>CustomErrorFault</Name>

<Message>HelloWorld_SayHello_CustomErrorFault_FaultMessage</Message>

</Fault> </Faults> </Operation> </Operations>

</PortType> </PortTypes></WsdlExtensions>

As shown in the picture above, the components allows to define the following information:

The prefix for the namespace of new messages created inside the wsdl. One or multiple Xml Schemas each defining a different typed fault. These schemas must

be deployed to BizTalk. At runtime, the component is able to retrieve the content of each schema from the BizTalkMgmtDb that subsequently is inserted in the outbound wsdl.

One or multiple fault messages, each containing one or multiple parts. One or multiple operation-fault associations. At runtime the component search through

the original wsdl structure and creates faults accordingly.

At runtime the WsdlExtensions component validates the XML configuration specified on the port and if the TraceEnabled property is set to true, it produces a trace with a tool such as Debug as shown in the picture below.

Formatted: Font: (Default) Times NewRoman, 12 pt, Font color: Blue

Page 33

The following picture shows the wsdl produced by the WsdlExtensions component at runtime. In particular, the parts added by the component are highlighted by a red frame.

Page 35

Note: Flattening the wsdl to include the XML schemas used to define messages allows to make the wsdl document compatible with non-Microsoft development environments. In fact, Visual Studio supports import and include directives in a wsdl, but some non-Microsoft development environments are not able to consume the wsdl exposed by a WCF web service.

Note: the XML Schemas defining the structure of the XML configuration data consumed at runtime respectively by the CustomErrorMessageInspector and by the WsdlExportEndpointBehavior can be found inside the BehaviorSchemas project. The corresponding assembly doesn’t need to be deployed to BizTalk Server.

Proof of Concept in Action

In order to test the WCF custom components, I created a WinForms application. In particular, when I leave the Name textbox blank and press the Call button, the HelloWorld orchestration returns a fault message. The client application intercepts the error with a catch (FaultException<HelloWorldBizTalk.CustomError> ex) block and opens a MessageBox to show the detail of the exception.

Show me the code!

At this point, you are probably saying “ok, cool, where’s the code”?

Well, I packaged the code in 2 different flavors:

- BizTalk Server 2009

- BizTalk Server 2006 R2

Page 36

Obviously, everything there are many ways to implement the same functionalities, so I’d be glad if you could leave a message on my blog(http://blogs.msdn.com/paolos/) and let me know how you used/customized/improved my code. Enjoy! ;-)

Page 37

BizTalk Resources We will use this section to document other BizTalk resources.

BizTalk 24x7 This site has a lot of great information about Books, Technical articles, Vides, blogs, Tools related to

BizTalk.

http://www.biztalk247.com/

BizTalk Gurus This is another BizTalk community site. You can sign up for their newsletter too.

http://www.biztalkgurus.com/

BizTalk Server Customer Advisory Team This team consists folks with deep knowledge about BizTalk. They have produced excellent

documentation about BizTalk operations, performance optimization etc.

http://msdn.microsoft.com/en-us/biztalk/dd876758.aspx

Recently Released Documentation

BizTalk Server 2009 Install Documentation - June 2009 Update

http://msdn.microsoft.com/en-us/biztalk/dd876758.aspx

BizTalk Server 2009 Operations Guide - July 2009

This document is a collaboration of Technical folks with real-world experience. Anyone working with BizTalk will find invaluable information in this guide.

Download it here

http://www.microsoft.com/downloads/details.aspx?displaylang=en&FamilyID=46a77327-affb-4ca2-9451-67912babbb03

Read it online

Page 38

http://msdn.microsoft.com/en-us/library/ee308947(BTS.10).aspx

Page 39

Microsoft Dynamics AX integration using Microsoft BizTalk Server By Ashish Mehndi, Consultant, Global Services, Microsoft

Introduction

Microsoft Dynamics AX is a global, adaptable business management solution that enables

organizations to make business decisions with greater confidence. By automating and streamlining

financial, customer relationship and supply chain processes, Microsoft Dynamics AX brings together

people, processes and technologies, increasing the productivity and effectiveness of the business

and helping to drive business success.

In today’s business environment all enterprises make extensive use of computer systems and

applications in order to establish and maintain a competitive advantage. In order for these

applications and systems to provide the desired advantage it is essential to ensure that the

resources are available to all users and business processes that may benefit from the use. To ensure

the same, these applications should be fully integrated to seamlessly flow the information across

and pool the available resources to maximize the benefits. And here fits Microsoft BizTalk Server as

a Business process management Server that enables companies to integrate, automate and

manage Business processes.

Enabling businesses to expose processes and data in real-time, BizTalk Server helps organizations to

optimize business processes, decreasing costs and eliminating inefficiencies. By providing simple

yet powerful tools to gain a real-time understanding of business processes, BizTalk enables

organizations to grow their business.

This article focuses on how to integrate Microsoft Dynamics AX using Microsoft BizTalk Server. But

before we dwell into the details of integration it is important to understand the features provided

by Dynamics AX and BizTalk Server to integrate seamlessly and making sure that they have been

installed appropriately.

Microsoft Dynamics AX provides Application Integration Framework (AIF):

Application Integration Framework (AIF) provides an extensible framework that supports multiple

asynchronous transports, as well as synchronous transport using Web services, to reliably exchange

Page 40

documents in XML format with trading partners or other systems. An exchange starts with a

document, that is, a document class defined using Microsoft Dynamics AX business logic. The

document is serialized into XML and header information is added to create a message, which may

then be transferred into or out of your Microsoft Dynamics AX system (called the local endpoint

within AIF). The other entity taking part in the exchanges is called the endpoint.

Microsoft Dynamics AX Adapter provided by Microsoft BizTalk Server:

BizTalk adapters extend the functionality of BizTalk Server, enabling it to connect to other servers,

applications and Web services. Specifically, they remove the need to develop infrastructure

components such as network protocol support and translation, data conversion, data

transformation, in the development of business process automation solutions. BizTalk Server

adapters are "no-code" connectivity solutions, and are provided in-box with BizTalk Server.

The Microsoft Dynamics AX Adapter for BizTalk can be installed on the BizTalk machine using the

Dynamics AX setup. After running the Dynamics AX setup on the BizTalk machine the following

steps needs to be followed:

1. On the Select installation type page, click Custom installation, and then click Next. 2. On the Select Computer Role page, under Application integration gateway, select BizTalk

adapter, and then click Next. 3. On the Installing page, you can monitor installation progress as Setup proceeds. 4. On the Completing Microsoft Dynamics AX Setup page, you can review the summary of roles

installed on the computer. 5. To exit the Microsoft Dynamics AX Setup wizard, click Finish.

Customers use these adapters to connect these applications and automate processes that may

span applications or organizational boundaries.

Page 41

The Microsoft Dynamics AX Adapter for BizTalk Server supports both Inbound and outbound

message processing.

Inbound message processing: An external system sends a message through a BizTalk Server

adapter. The AIF gateway receives service polls for messages and then brings them into the

gateway queue. The AIF inbound processing service takes the messages from the gateway queue.

Next, the business logic in the AIF document service processes the message and interacts with the

internal Microsoft Dynamics AX database.

Outbound message processing: The AIF outbound processing service processes send requests using

the document services and places the outbound messages in the gateway queue. The AIF gateway

send service then reads the messages from the gateway queue and sends them out using a

transport adapter. These transports adapters include Microsoft Message Queuing (MSMQ), the file

system, or other BizTalk Server adapter. The external system then receives the message from the

appropriate transport.

This article details on configuration operations related to the integration of Dynamics AX using

BizTalk Server and covers both inbound as well as outbound message exchange. Further it also

covers the basic guidance on where to look for errors in case of unexpected situations.

Configuring Microsoft Dynamics AX Adapter for BizTalk

Terminology This section explains the concepts used in the AIF.

Term Description

adapter A software component that enables message exchange using a specific transport. In AIF, an adapter means a transport adapter.

channel A named entity used to specify where and how to send and receive messages. A channel specifies an adapter with its associated configuration information and transport address.

endpoint A company or entity that participates in a business-to-business (B2B) or application-to-application (A2A) data exchange. An endpoint can be an in-house independent system, in the case of A2A.

endpoint action policy Determines which actions are valid for a particular endpoint. An action is bound to an endpoint using an endpoint action policy.

Page 42

gateway queue Provides temporary storage for documents while they wait for processing. Inbound messages are placed in a gateway queue by an inbound transport adapter. Outbound messages wait in a gateway queue until an outbound transport adapter picks it up for sending.

message An individual unit of data transported between endpoint locations. A message consists of a document plus a header containing information about the transfer.

document class An X++ class (prefixed with Axd) with methods that perform actions on documents.

pipeline processor The pipeline processor enables transformations of the inbound/outbound XML before/after the Microsoft Dynamics AX document class acts on the document. Components are provided in the base Microsoft Dynamics AX system for data value substitution and XSLT document transformations.

Web services A unit of application logic that provides data and services to other applications that clients invoke by using the Simple Object Access Protocol (SOAP) over the Hypertext Transfer Protocol (HTTP). Web services can perform functions ranging from simple requests to complicated business processes.

Configuring Microsoft Dynamics AX – Application Integration Framework (AIF) In order to integrate BizTalk with Microsoft Dynamics AX we need to configure the Application Integration Framework which acts as a bridge between the two. The following steps lists down the steps to set up the Application Integration Framework which exposes data to BizTalk Microsoft Dynamics AX adapter.

1. Start the Microsoft Dynamics AX client, and browse to the Basic Module (as shown below):

Page 43

2. Create the Local Endpoint or make sure that the Local Endpoint is configured:

A local endpoint is the origination for sent messages and the destination for received

messages. There may be more than one local endpoint, depending on how many companies

are configured for your Microsoft Dynamics AX installation.

a. Click Basic Setup Application Integration Framework Local endpoints. b. Press CTRL+N to create a new local endpoint record. c. Select a company from the Company field. d. Enter a name for the endpoint in the Local endpoint field. e. The name for the local endpoint should be representative of the Microsoft Dynamics

AX company name that participates in the exchange. f. Press CTRL+S to save the data.

Page 44

3. Configure an adapter

The following adapters are available after installing Microsoft Dynamics AX:

a. AifFileSystemAdapter

b. AifMSMQAdapter

c. AifWebServiceAdapter

d. AifBizTalkAdapter

Channels define the transport method that enables messages to move in and out of the framework to reach the endpoint. We need to configure adapter to use the channels in order to enable messages reach the endpoint. To configure an adapter for use in a channel, you activate it and specify its direction (inbound, outbound, or both) on the Transport adapters form. Ensure that Transport Adapter is configured for AifBizTalkAdapter.

Page 45

a. Click Basic Setup Application Integration Framework Transport Adapters. b. Press CTRL+N to create a new transport adapter record. c. Select the AifBizTalkAdapter from the list of Adapter classes available.

d. Enter a Name and make it active by selecting the “Active” checkbox (that is shown in the above figure as “A”), so that it is available for use.

e. The default value for AifBizTalkAdapter is “Receive and Respond” and this cannot be changed (as AifBizTalkAdapter is used for both sending and receiving data between BizTalk and Microsoft Dynamics AX).

Page 46

4. Creating and configuring channels

Channels define the transport method that enables messages to move in and out of the framework to reach the endpoint. Before configuring a channel, a transport adapter must be available.

Channels may support inbound transfers only, outbound only, or both. Configuration settings are different depending on the direction for the transfer in the channel as well as for different adapters. Inbound channels may use a response channel that handles verification or error responses to inbound transfers.

a. Click Basic Setup Application Integration Framework Channels.

b. Press CTRL+N to create a new channel.

c. Select an adapter in the Adapter field.

You must first have activated an adapter on the Transport adapters form before it appears in the list of available adapters.

d. Enter the unique identification information for the new channel, including an identifier in the Channel ID field and a friendly name in the Name field.

a. Provide the channel ID as “BizTalkChannel”

b. Provide the friendly Name as “BizTalkChannel”

e. To activate the channel and allow it to participate in document exchanges, click Active (or “A” as shown in the figure).

f. Configure the address for the adapter.

a. Provide the address as “BizTalkChannel”

Page 47

g. Select from the available directions for the transfers to be performed in this channel. The list of available directions depends on the adapter.

a. Provide the direction as “Both”

h. If the direction is set to Inbound / Both, you can select a response channel.

Inbound channels can use an outbound channel called a "response channel" to transfer or "respond back" to the source endpoint with verification results or error responses to inbound transfers.

i. On the General tab, set the Maximum batch size to the maximum number of messages to be processed at one time from the queues. You can select Unlimited if you do not want to limit this number.

j. Press CTRL + S to save the created / configured channel.

k. Now select the Channel created and press “Configure”, and enter the BizTalk Server

groups that you want AX to connect to:

Page 48

l. Enter the names of the computers running BizTalk Server that belong to the specified BizTalk group. Press CTRL+N to add each server to the list.

m. Press CTRL+S to save the channel.

5. Configure an action:

An action refers to the document and the operation to be performed on it, such as Send or Receive.

a. Click Basic Setup Application Integration Framework Action.

Page 49

b. To register all actions for document classes that exist, click Scan and register.

c. After all items are scanned and registered, select “Enabled” (in above figure the checkboxes with Column named as “E…”) to enable the actions you need for your

exchange.

Enable the action corresponding to the Interface, for example: “createListVendTable” for Interface 32.

6. Creating and configuring endpoints

Using Application Integration Framework (AIF), you enable document exchanges between endpoints and the local endpoint. A local endpoint is the origination for sent messages and the destination for received messages. That is, the local endpoint refers to your Microsoft Dynamics AX installation.

An endpoint is the destination for an outbound document and the source of an incoming document. That is, an endpoint represents your trading partner in a document exchange.

Before you can configure an endpoint, the following must already exist and be configured:

a. A local endpoint.

b. A named action for the exchange, consisting of a document and a description of the operation to be performed on it.

c. Microsoft Dynamics AX users to be associated with the endpoint.

d. An outbound channel must be already be defined if needed.

Steps to configure / create endpoint:

a. Click Basic Setup Application Integration Framework Endpoints.

b. Press CTRL+N to create a new endpoint, or select an existing endpoint from the list to be modified.

Page 50

c. Enter a unique Endpoint ID and user friendly name.

i. Enter Endpoint ID as “Inbound Vendors”. (an example)

ii. Enter friendly name as “Inbound Vendors”. (an example)

d. Go to “Constraints” tab and select “No Constraints” checkbox (as shown in figure below

e. Go back to the “Overview” tab, and select / provide the “Local endpoint ID”

from the list of local endpoint configured. (for example “AMC” as shown in figure below)

f. Now click on the “General” tab and select the “Outbound channel ID” from the list of Channels already configured (for example “BizTalkChannel” as shown below)

Page 51

e. Configure Action Policies:

To enable exchange of documents for endpoints, select which actions an endpoint may perform. This process is called configuring endpoint action policies.

a. To Configure the Action Policies for the End Point and associate action and endpoint, click on the “Action Policies”

i. Press CTRL + N to create a new Endpoint Action policy and select from the List of Actions displayed

Page 52

ii. Set the Status as “Enabled” and Logging Mode as “Log All”

f. Configure Action Data Policies:

A document is made up of many data fields. When you set up a document exchange, you decide, on a field-by-field basis, which data fields are transferred. This is known as the data policy. You configure the data policy on the Data Policies form.

a. To Configure the Action Data Policies for each of the Action Policies configured above.

Page 53

i. Select the Action Id in the window shown in figure above and click on Data Policies.

ii. Enable the fields as per the schema / requirements of the Interface

iii. Mark the fields as required which are not Optional as part of the Interface requirements / schemas.

g. Configure an endpoint user

You must enter information for at least one endpoint user or trusted intermediary who is authorized to initiate transactions for the endpoint on the Users tab.

Follow the steps mentioned below:

a. Click the Users tab.

b. Under Endpoint users, in the User type field, select either User or User group.

c. In the Application user or group field, select a valid Microsoft Dynamics AX user or user group name

For our purpose on the Users Tab follow the steps below:

i. On the “Users” tab, press (CTRL + N) for associating the new User /

Groups

ii. Select “User Group” under User type and “Admin” from the list under

Application user or group

Page 54

In order for the Application Integration Framework (AIF) to begin sending and receiving

documents with adapters, four services must be running as batch jobs within Microsoft

Dynamics AX:

a. AIFOutboundProcessingService b. AIFInboundProcessingService c. GatewaySendService d. GatewayReceiveService

Until these batch jobs are started, no documents can be processed in adapter-based exchanges.

Inbound documents do not enter your Microsoft Dynamics AX system and outbound documents

accumulate in the AIF outbound processing queue.

Refer the link below for more details.

http://msdn.microsoft.com/en-us/library/aa570105(AX.10).aspx

Send Data from BizTalk to Dynamics AX Interface 32 sends data to Microsoft Dynamics AX.

The following configuration needs to be performed in BizTalk Send Port which would send the data from the BizTalk Server to the Microsoft Dynamics AX using the Application Integration Framework (AIF):

Page 55

1. Create a New Send Port or use an existing Send Port (in case Orchestration is used).

2. Select the Transport Type as “Microsoft Dynamics AX”, and provide the details like Send

Handler, Send pipeline and Receive pipeline as per the requirements of the Interface.

3. Press “Configure” and set the following properties:

a. Set “Authentication Type” = “Host User”

b. Set “Gateway User” as BizTalk user under which the BizTalk Host Instance is

executing.

c. Set “AOS Server” to the name of “Dynamics AX Server”

d. Set “AOS Port” to the port number on which of Dynamics AX Server is running – the default is 2712.

Page 56

4. Please refer “Appendix A – Configuring Message Properties for sending data to Microsoft Dynamics AX”.

Receive Data from Dynamics AX in BizTalk

Microsoft Dynamics AX adapter pulls the data available in the Dynamics AX Queue and publishes

it into the Message Box. In one BizTalk Group there can be only one Receive Location that points

to a combination of AOS Server Name and AOS Port Number. You can create multiple receive

locations that points to different AOS Server and Port combination. BizTalk Server receive

location can receive different messages from the same AOS Server & Port combination and can

route the same do different BizTalk artifacts based upon the filters.

The following configuration needs to be performed in BizTalk Receive Port / Receive Location

which would receive the data from Microsoft Dynamics AX using the Application Integration

Framework (AIF) and publish the same into BizTalk Message Box:

1. A Static One Way port needs to be created under Receive Port in BizTalk Application

Page 57

2. The following provides the configuration for Receive Location –

a. Select the Transport Type as “Microsoft Dynamics AX”, also choose the Receive

handler and Receive pipeline as per the business requirement.

Page 58

b. Press “Configure” and set the following properties:

i. Set “Authentication Type” = “Host User”

ii. Set “Gateway User” as BizTalk user under which the BizTalk Host Instance

is executing.

iii. Set “AOS Server” to the name of “Dynamics AX Server”

iv. Set “AOS Port” to the port number on which of Dynamics AX Server is running – the default is 2712.

Page 59

Error Handling and Messages

Categories of Exceptions related to BizTalk / Dynamics AX Interfaces

1. When error Event Source: “Microsoft Dynamics AX adapter”

a. Refer the Microsoft Dynamics AX Server Event Log for more details

b. Refer the Microsoft Dynamics AX Exceptions

2. When error Event Source: “Microsoft BizTalk Server” / “Company.EAI.BizTalk”

a. This category of error is related to some error in Transformation, Orchestration or Transport.

b. Refer the BizTalk Administration Console for more details.

Microsoft BizTalk Server

(Event Source: “Microsoft BizTalk Server”)

This section provides the information on the exceptions that gets logged by BizTalk in case of erroneous conditions for Microsoft Dynamics AX interfaces.

Page 60

All the Exceptions that occur in Microsoft BizTalk Server are logged in Event Log of the BizTalk Server machine. These exceptions are logged on the Machine based upon the Host Instance configuration.

Apart from the Error / Detailed exception the Message / Orchestration (in case orchestration is used for processing and routing the message) also gets “SUSPENDED” as either Resume-able

or Non-Resume able state based upon the category and nature of the Exception.

The following sections detail the steps to be followed in case the error Event Source is “Microsoft BizTalk Server”.

1.1.1.1 Error Handling for data being sent to Microsoft Dynamics AX from BizTalk Server

1. Error occurs in the Interface which sends data to Microsoft Dynamics AX.

a. Case I: If the error occurs while transforming the data received from the Source

Systems into Canonical Message.

i. In this case the message would get suspended.

ii. The suspended messages can be retrieved using Microsoft BizTalk Server Administration Console.

iii. If the message needs to be replayed without any correction and is resume-able, then right-click click on the Suspended Message and click on “Resume Instance”.

Page 61

iv. If the message needs to be corrected, then the data needs to be altered in Source System and reposted to BizTalk.

b. Case 2: If the error occurs after the data has been transformed into the standardized or canonical format Canonical

i. The Interface would output / dump the Canonical Message to a configured location as per the Send Error Port.

ii. After correcting the issue in the Canonical Message the file can be replayed using the configured Error Replay folder.

Page 62

iii. Drop the Canonical Message at above configured location. Microsoft BizTalk Server would route the corrected canonical to the right Interface and perform the required transformations.

1.1.1.2 Error Handling for data being received from Microsoft Dynamics AX into BizTalk Server

2. Error occurs in the Interface which receives data from Microsoft Dynamics AX.

a. Case I: If the error occurs while transforming the data received from the Microsoft

Dynamics AX.

i. In this case the message would get suspended.

ii. The suspended messages can be retrieved using Microsoft BizTalk Server Administration Console.

Page 63

iii. If the message needs to be replayed without any correction and is resume-able, then right-click click on the Suspended Message, and click “Resume Instance”.

iv. If the message needs to be corrected, then the data needs to be altered in Microsoft Dynamics AX and reposted (refer Section 2.4.3.4 Repost Messages)

b. Case 2: If the error occurs after the data received from the Microsoft Dynamics AX

has been transformed into the Canonical (for Interface with Orchestration).

i. The Interface would output / dump the Canonical Message to a configured location as per the Send Error Port.

Page 64

ii. After correcting the issue in the Canonical Message the file can be replayed using the configured Error Replay folder.

Page 65

iii. Drop the Canonical File at above configured location. Microsoft BizTalk Server would route the corrected canonical to the right Interface and perform the required transformations.

c. Case 3: If the error occurs after the data received from the Microsoft Dynamics AX

has been transformed into the Canonical (for Interface without Orchestration).

i. In this case the message would get suspended.

ii. The suspended messages can be retrieved using Microsoft BizTalk Server Administration Console.

Page 66

iii. If the message needs to be replayed without any correction and is resume-able, then right-click click on the Suspended Message, and click on “Resume Instance”.

iv. If the message needs to be corrected then double click on any Suspended Message

Page 67

v. Go to “Messages” tab.

vi. Double Click on the Message.

Page 68

vii. Click on Body and copy the Message and store it on the Hard disk.

viii. Correct the message and rename the file as per the Interface (refer the Design Document for the corresponding Interface for the same)

ix. Drop the file at above configured location which is being monitored by BizTalk Server for existence of any new inputs (e.g. “C:\ErrorReplay” folder).

Microsoft BizTalk Server would route the corrected canonical to the right Interface and perform the required transformations.

Microsoft Dynamics AX (Event Source: “Microsoft Dynamics AX adapter”)

1.1.1.3 Queue Manager

The Queue Manager is internal queue maintained in Microsoft Dynamics AX. This Queue is the bridge between Dynamics AX and external systems.

All the messages sent from other systems or needs to be sent to external systems from Microsoft Dynamics AX goes through the Queue. The Queue Manager UI lets you monitor the messages sent to / from Dynamics AX.

The erroneous messages are not moved out of the Queue Manager and can be tracked using the User Interface as shown below:

Steps to monitor data under Queue Manager:

Page 69

1. Under Basic module, click on “Periodic” “Application Integration Framework” “Queue Manager”

1.1.1.4 Document History

The Document History maintains the history of all the messages sent to / from the Microsoft Dynamics AX. It’s a kind of Log of messages.

Steps to view data under Document History:

1. Under Basic module, click on “Periodic” “Application Integration Framework” “Document History”

Page 70

1.1.1.5 Exceptions

The exception view provides the details of Exceptions that occurred while processing messages received by Microsoft Dynamics AX. This view only provides the details of exceptions raised by Microsoft Dynamics AX.

1. Under Basic module, click on “Periodic” “Application Integration Framework” “Exceptions”

2. To view the details of the Exception, right click and select Record Info, then select Show All Fields. This would display the details of the Exception as below:

Page 71

1.1.1.6 Repost Messages

Microsoft Dynamics AX would be sending data to Microsoft BizTalk Server using Application Integration Framework (AIF). In case the any exception occurs while transmitting the data through AIF, the exception gets logged in the exception list as mentioned above.

Microsoft Dynamics AX would be configured to auto send the new / updated data to BizTalk Server. This would be done by configuring and executing Batch in Dynamics AX.

In case of errors, the administrators can repost the data using the Microsoft Dynamics AX UI. The batch still needs to run which actually post the data into the Dynamics AX Queue from where the BizTalk Adapter would pick the data and send the same to the Message Box.

The steps below detail the how to post an Invoice data manually, this posting of Invoices can be done in case there has been an exception in the batch process which posting invoices:

1. Click on the “Accounts Payable” module in Microsoft Dynamics AX

Page 72

2. Click on “Purchase Orders”

3. Click on “Posting” “Invoice” and press “OK”.

Page 73

Appendix A Configuring Message Properties for sending data to Microsoft

Dynamics AX

To send data to Microsoft Dynamics AX from BizTalk there are properties that needs to be set on the message, before Microsoft Dynamics AX adapter can push the same.

The following properties need to be set on the message:

i. Set the Dynamics Action on the Message as per the Action configured in Microsoft Dynamics AX: _message (Dynamics.Action)

ii. Set the Dynamics Destination Endpoint on the Message as per the Destination Endpoint configured in Microsoft Dynamics AX: _message (Dynamics.DestinationEndpoint)

iii. // Set the Dynamics Source Endpoint on the Message as per the Destination Endpoint configured in Microsoft Dynamics AX _message (Dynamics.SourceEndpoint)

iv. // Set the Dynamics Source Endpoint User on the Message as per the Destination Endpoint configured in Microsoft Dynamics AX _message (Dynamics.SourceEndpointUser)

Here is the sample for the setting the properties for VendTable:

// Set the Dynamics Action for VendTable

msg_VendTableRequest(Dynamics.Action)="createListVendTable"; // this

too can be made configurable and taken from SSO

// Set the Dynamics Destination Endpoint from the SSO Config

msg_VendTableRequest(Dynamics.DestinationEndpoint) =

SSOConfigHelper.Read("Company.BizTalk.OracleFinancials.VendorData",

"Dynamics.DestinationEndpoint");

// Set the Dynamics Source Endpoint from the SSO Config

msg_VendTableRequest(Dynamics.SourceEndpoint) =

SSOConfigHelper.Read("Company.BizTalk.OracleFinancials.VendorData",

"Dynamics.SourceEndpoint");

Page 74

// Set the Dynamics Source Endpoint User from the SSO Config

msg_VendTableRequest(Dynamics.SourceEndpointUser) =

SSOConfigHelper.Read("Company.BizTalk.OracleFinancials.VendorData",

"Dynamics.SourceEndpointUser");

Appendix B Related Documents/References

Document Document Location

Microsoft Dynamics AX

AIF Configuration White

Paper

http://www.microsoft.com/DOWNLOADS/details.aspx?FamilyID=e5764

bdf-c88d-47f2-a1df-55f368ca9f8d&displaylang=en

Microsoft Dynamics AX

AIF BizTalk Adapter

Configuration White

Paper

http://www.microsoft.com/downloads/details.aspx?FamilyID=fb4a979e

-cce1-4542-8188-4e8592031da2&displaylang=en

Page 75

Manage BizTalk Services Thru WMI – Using C# By Alok Verma, Software Development Engineer, Microsoft

This article assumes you are familiar with BizTalk Server, WMI and C#.

Audience: BizTalk Developers

Technologies: BizTalk Server 2006/2009, VS.NET 2005/2008, WMI

Skill level: Intermediate to Expert

The source code used in this article can be downloaded from this location

http://cid-e210012d5d7e02e1.skydrive.live.com/browse.aspx/Public/BizTalk%20Code

Summary There are situations when maintaining the BizTalk server MessageBox database becomes

challenging. Specifically, when your BizTalk application processes high volume transactions and

sporadically encounters many unsuccessful instances which end up putting many services and messages

into suspended queue.

The BizTalk Administration console is a handy tool for cleaning up small volumes of suspended service

instances; however, for large numbers of suspended service instances a different tool would be

beneficial.

WMI (Windows Management instrumentation) unleashes the capabilities of automating the

administrative tasks for a BizTalk application. To meet this requirement I was looking for a customizable

solution. Out of several options I chose to write a C# program using strongly typed WMI class.

The example I am discussing here talks about a managed solution for following requirements

- Terminate all suspended messages from queue.

- Terminate suspended messages older than 5 days.

- Resume messages which are suspended during last 24 hour.

Creating a WMI Managed Class for BizTalk To create the WMI Managed class follow these steps...

1- Select Management Classes from Visual Studio Server explorer as shown in Fig-1

Page 76

Fig-1

2- Expand the node to select “MSBTS_ServiceInstance” and generate managed class, Fig-2

Fig-2

This will create strongly typed BizTalk WMI class in file named as

“ROOT.MicrosoftBizTalkServer.MSBTS_ServiceInstance.cs”

Terminate Suspended Instances Here we have two requirements, the first is to terminate all suspended services from the

suspended message queue. Following is the sample code

public static void TerminateAllSuspendedMsgs()

{

try

{

//Retrieve the suspended (resumable and non-resumable) instance

collection and terminate each one in loop.

ROOT.MICROSOFTBIZTALKSERVER.ServiceInstance.ServiceInstanceCollection

colServiceIns;

string condition = " (ServiceClass5= 1 OR ServiceClass= 4 OR

ServiceClass = 64) AND (ServiceStatus6=4 OR ServiceStatus=32)";

colServiceIns =

ROOT.MICROSOFTBIZTALKSERVER.ServiceInstance.GetInstances(condition);

5See http://msdn.microsoft.com/en-us/library/ms949479.aspx

6 See http://msdn.microsoft.com/en-us/library/aa510147.aspx

Page 77

foreach(ROOT.MICROSOFTBIZTALKSERVER.ServiceInstance serviceIns in

colServiceIns)

{

serviceIns.Terminate();

}

}

catch (Exception ex)

{

Console.WriteLine("Error: " + ex.Message);

}

}

In the second scenario, we are terminating only those suspended services which are older than 5 days. To achieve this we will use the “SuspendTime” Property of “ServiceInstance” class.

public static void TerminateOldSuspendedMsgs()

{

try

{

double expiryDayIncrement = 5.0;

ROOT.MICROSOFTBIZTALKSERVER.ServiceInstance.ServiceInstanceCollection

colServiceIns; ;

string condition = " (ServiceClass = 1 OR ServiceClass = 4 OR

ServiceClass = 64) AND (ServiceStatus=4 OR ServiceStatus=32)";

colServiceIns =

ROOT.MICROSOFTBIZTALKSERVER.ServiceInstance.GetInstances(condition);

foreach (ROOT.MICROSOFTBIZTALKSERVER.ServiceInstance serviceIns in

colServiceIns)

{

DateTime dtSuspend = DateTime.MinValue;

dtSuspend = serviceIns.SuspendTime;

if (DateTime.Now.CompareTo(dtSuspend.AddDays(expiryDayIncrement))

< 0)

{

serviceIns.Terminate();

}

}

}

catch (Exception ex)

{

Console.WriteLine("Error: " + ex.Message);

}

}

In the above example, I am considering 5 days and this value can be customized using

ConfigurationManager class. The following code set the expiry day value by reading the configuration

file.

//Replace this code in the TerminateOldSuspendedMsgs() to get the expiry daya value

from config setting.

double expiryDayIncrement = 0.0;

expiryDayIncrement = Convert.ToDouble(ReadDataFromConfig("AddExpiryDay"));

private static string ReadDataFromConfig(string section)

{

Page 78

try

{

string value = ConfigurationManager.AppSettings[section];

return (value == null) ? null : value;

}

catch (ConfigurationException ex)

{

Console.WriteLine("Error while reading config data from App.config for

Section: " + section + " Error Message: " + ex.Message);

return null;

}

}

Here is “App.Config” setting,

<configuration>

<appSettings>

<!--AddExpiryDay value specify the number of day when added to a

suspended message time

will be treated as dead message afterwards, range 0-365 -->

<add key ="AddExpiryDay" value="5" />

</appSettings>

</configuration>

Resume Suspended Instances In this scenario we will resume service instances which are suspended in the last 24 hours. For service

instances older than 24 hours you can perform the clean up by calling the “TerminateAllSuspendedMsgs

()” as explained in above sample code.

public static void ResumeCurSuspendedMsgs()

{

try

{

double hourRange = 24.0;

ROOT.MICROSOFTBIZTALKSERVER.ServiceInstance.ServiceInstanceCollection

colServiceIns; ;

string condition = " (ServiceClass = 1 OR ServiceClass = 4 OR

ServiceClass = 64) AND (ServiceStatus=4)";

colServiceIns =

ROOT.MICROSOFTBIZTALKSERVER.ServiceInstance.GetInstances(condition);

foreach (ROOT.MICROSOFTBIZTALKSERVER.ServiceInstance serviceIns in

colServiceIns)

{

DateTime dtSuspend = DateTime.MinValue;

dtSuspend = serviceIns.SuspendTime;

if (DateTime.Now.CompareTo(dtSuspend.AddHours(hourRange))>= 0)

{

serviceIns.Resume();

}

}

}

catch (Exception ex)

{

Console.WriteLine("Error: " + ex.Message);

}

}

Page 79

Advantages of WMI with C# approach

Secured and reliable unlike VBScript code which is not acceptable in some production

environments

Better validation and exception handling

Scalable and Reusable code

Code can be invoked from task scheduler to execute at certain interval or can be run as

Windows service.

Conclusion WMI supports a uniform application programming interface (API) that gives applications and

scripts access to the WMI provider on a local computer or a remote computer. In above samples we just

tried to explore a small feature of the WMI capabilities for BizTalk administration tasks and there is lot

more to be explored in WMI world.

Happy Coding!