Azure API Management – Liquid Template – Escape XML Characters

Requirement:

Create an API that allows creation of customer in backend ERP.

API should be accessible publicly and secured.

Landscape:

  1. ERP is SAP and is located on a on-premise network.
  2. BizTalk is used as middleware to connect to SAP and is also located on-premise. BizTalk doesn’t have a public endpoint available.
  3. Azure API Management is deployed in Azure cloud without direct connection to on-premise network.

Solution:

  1. BizTalk to leverage WCF-BasicHttpRelay to Azure Service Bus to be able to have public endpoint.

2. Azure API management to convert the JSON Request to XML message using Liquid Template.

3. Azure API management to send the request to Azure Service Bus.

4. BizTalk receives the request in XML and send the request to SAP.

Problem:

If the JSON request contains XML reserved characters: & < > ‘ the request is failing in Azure API management.

Solution:

Add the following to the policy:

<!–Replace Reserved XML characters from Request Body–>

BizTalk Map – Eliminate duplicate records using functoid

Recently there’s a requirement to eliminate the duplicate records in the output using BizTalk map.

Brilliant solution can be found here:

I’ve added step by step on how to do it.

Overall solution it looks like this:

Duplicate

You’ll need 2 script functiods and Equal logical functoid

  1. Top functoid will contain the declaration of variable with following code:

System.Collections.Specialized.StringCollection uniqueIds = new System.Collections.Specialized.StringCollection() ;

2.  Another functoid will take in the ID of source messsage wherein the uniqueness will be checked. In this case, CustomerId as input. The following code is as follows:

public bool IsUniqueId(string id)
{
if (uniqueIds.Contains(id))
return false;
uniqueIds.Add(id);
return true;
}

3.  Equal logical functoid will take the output of the second script functoid and output should be map to the target record

 

This is my input message:

http://BizTalk_Server_Project1.Order”>;

1
Customer 1


1
Deplicate Customer


2
Customer 2

And this is the output:

http://BizTalk_Server_Project1.Order”>;

1

Customer 1

-

2

Customer 2

 

Viola!!, without using xslt you can achieve same results.

BizTalk – BTDF Compilation Error – ICE01

Current setup:

  • BizTalk Server 2016
  • Azure DevOps On-premise Build Agent

Error Message:

Error executing ICE action ‘ICE01’. The most common cause of this kind of ICE failure is an incorrectly registered scripting engine. See http://wix.sourceforge.net/faq.html#Error217 for details and how to solve this problem. The following string format was not expected by the external UI message logger: “The Windows Installer Service could not be accessed. This can occur if the Windows Installer is not correctly installed. Contact your support personnel for assistance

Solution:

Change the Log On As of VSTS Agent to Local System Account

  1. Run services.msc
  2. Look for the VSTS Agent Service
  3. On Tab change the Log On from Network Service to Local System account

Agent-LocalSystem

BizTalk – SAP Adapter – RFC_INVALID_HANDLE

All receive location green and by the moment you’ve send your first IDoc this warning occurs:

The adapter “WCF-Custom” raised an error message. Details “Microsoft.Adapters.SAP.RFCException: Details: ErrorCode=RFC_INVALID_HANDLE. AdapterErrorMessage=An exception has occurred on the listener while executing RfcWaitForRequest..”.

To solve this error you’ll need to install the BizTalk SAP Adapter Schema.

Steps:

  1. Create a BizTalk application or use the default BizTalk Application
  2. Right Click Add Resource.
  3. Browse to: \bin\Microsoft.Adapters.SAP.BiztalkPropertySchema.dll
  4. In the options check all.

BizTalkSchemas

BizTalk – File Adapter – File transport does not have read/write priveleges

Recently, I have to investigate error related to BizTalk – File Adapter. The error that was thrown was:

The Messaging Engine failed to add a receive location “{Receive Location Name}” with URL “{RecieveLocationPath}\*.*” to the adapter “FILE”. Reason: “File transport does not have read/write privileges for receive location “{RecieveLocationPath}\”. “.

I think the error was obvious, and these are the steps I’ve performed to investigate:

  1. Checked if path exists (duh!).
  2.  Checked the Share Folder settings and Security Settings (looks ok!)
  3.  Double checked which account is accessing the folder in BizTalk Admin Console. Since there was no account specified in the Authentication Tab, then I assume that this is using the default account of the Host Instance.

BTS-FileAdapter-AuthenticationTab

4. Re(enable) the Receive Location (immediately shutdown)

5. Restart the Host Instance, repeat step 4. (doesn’t work)

6. Re-enter the password of Host Instance Service (using services.msc) and restart and repeat 4 (no use!).

6. Reboot the Server (still doesn’t work).

Hmm, weird huh?

What i did next is to go to Shared Folder Management (in the server where the folder is hosted). This can be access using Run-> mmc -> Add/Remove Snap-In -> Share Folder.

From the menu, go to Open Files.

MMC-ShareFolder

What i see is: there are 2 different service accounts of BizTalk connecting to the same share folder server. Hmm.. So i changed one of the Receive Location to use the same account as the other one and repeat Step 4.  After this step, the receive locations are now green again!.

It looks like BizTalk can’t connect to a Share Folder Server using 2 different accounts.

 

 

 

 

 

Key to successful BizTalk Deployment

It’s been a while since my last blog, but IMHO this is one of important blog that I’ve ever made that can be useful pointer for every aspiring developer / companies that will/already implement application integration. Below contains a list / summary of best practices I’ve acquired in my more or less 10 years working with BizTalk, SSIS, WCF and .NET integration (primarily Microsoft Technology) but this I think is also applicable to other technology.

Design / Development:

#1 K.I.S.S (Keep it simple, stupid). Don’t get me wrong, I like complex integrations, from  multiple message correlations, requirement to aggregate certain line items with certain condition in the message to having a direct binding with delivery notification set to transmitted (multiple send port / send port groups, this will result in some zombie messages). Anyone from novice to expert BizTalk Developer can build a solution, it can be done & solve  in different ways but the key here is providing a simple and effective solution for a complex integration.

#2 Isolation with maximum reusability. Isolation for me means that the application can be deployed without having too much dependency to other BizTalk artifacts that are shared. During the design it’s always a struggle on how to seperate artifacts, on which solution / projects it should be placed to avoid having to uninstall all referencing application before you can refresh the dependency (GACing works in some situation but not for all, you’ll be surprise how BizTalk deal with it internally). Once identifying or isolating a certain integration flow whenever there’s a new requirement, we should always check whether it fits on already existing solution (extend) without having to build a new integration flow. in this case we will have maximum reuse of existing solution.

#3 Consistency. Every solution that will be build should look as if it’s build / coded by one person. Having a naming convention on BizTalk artifacts, namespace, solutions, project & folder structures should be define first. Based on experience providing a proper name is always a challenge since if you define it incorrectly, it will be a costly mistake later on.

#4 Nuget – all common code / components / libraries should be referenced from a local nuget repository. Having a local nuget repository not only simplifies referencing dependencies but also saves you once you start using TFS Build Server (autorestore feature). This means that shared assemblies is not required to be checked in together with the source codes.

#5 .NET over XLST in complex mapping  Whenever there’s a requirement for complex mapping like grouping, aggregation, unique numbering over a certain combinations or constructing a hashtable in the mapping, I always go for .NET component. Using .NET component it is easier to maintain and tested (unit testing + mockup) vs doing everything in XSLT (in which can be forgotten in time).

Build / Deployment:

#1 Release Pipeline – It’s important to define strategy on how you would build and be able to do ‘Build once’ and deploy to multiple environments. In our case, part of our strategy is to minimize branching and always build from MAIN. In TFS, we’ve implemented a Gated Checkin which means that every checkin will trigger a release pipeline. During the checkin, a build will be triggerred (MSBuild and BTDF build), it will run all unit test and copies the binaries to drop folder (only If all steps are successful). From this point the Ops can just enter a command (application name) and environment and then the automated deployment will take over..

#2 Configuration over Code for normal deployment most of time you would see that a solution contains a powershell script for deployment, this is not bad but i think this only works on sample codes or tutorials but a problem in Enterprise deployment. For this you need a good deployment framework (compilation of scripts) to do the deployment and during the deployment preparation just replace the values in the templates like servernames, shared folders and etc.  I’ve posted some blogs earlier how to do this:

Centralize Powershell Repository:

https://randypaulo.wordpress.com/2012/02/27/powershell-centralize-powershell-script-modules-repository/

ESB Toolkit overrides BizTalk config (BTSNTSvc.exe.config)

I’ve setup a BizTalk Server 2013 environment with ESB Toolkit 2.2 and since I use Enterprise Library for logging I also updated the BTSNTSvc64.exe.config file, but when I tried to run a sample application it throws an error:

Activation error occured while trying to get instance of type LogWriter, key “”:Microsoft.Practices.ServiceLocation.ActivationException: Activation error occured while trying to get instance of type LogWriter, key “” —> Microsoft.Practices.Unity.ResolutionFailedException: Resolution of the dependency failed, type = “Microsoft.Practices.EnterpriseLibrary.Logging.LogWriter”, name = “(none)”.

Exception occurred while: while resolving.

Exception is: InvalidOperationException – The type LogWriter cannot be constructed. You must configure the container to supply this value.

Apparently, ESBToolkit is overriding the BizTalk configuration.

Solution:

Move the configuration to \esb.config file.

BizTalk: How to fix regional settings problem (decimal number formatting)

The regional settings of the operating system wherein your BizTalk Server is hosted, affects how the numbers/date are formatted. This in some cases, becomes a problem when trying to insert data in SQL Server using WCF-SQL.

For instance if the server is setup to use Dutch regional settings, the decimal number is separated by (,) comma. When you try to insert a data for instance 10.001, it becomes 10001. To fix the problem, you need to change the regional settings of the service account wherein the host instance is running.

Basically there are two things you can do.

One is to logon the account -> Go to regional settings -> Change the number formatting.

Now, if it’s impossible to login the account, you can fix it by changing the registry settings, for this you need the SID of the user account.

Updating Regional settings of an account using registry:

1. Open Regedit.

2. To get the SID, navigate to HKLM\SOFTWARE\Microsoft\Windows NT\ProfileList

Browse to every folder below and using the value in ProfileImagePath, you can determine the correct user account.

Then use the SId of the folder.

3. Once you have the GUID, browse to: HKEY_USERS\\Control Panel\International

Change the string values, for Decimal, change the sDecimal value.

 

BizTalk Archiving – SQL and File Documentation

I moved the documentation from: http://biztalkarchiving.codeplex.com/documentation, since it’s unreadable on the site.
 

BizTalk Archiving SQL and File Documentation

 

Installation

  1. Run MSI installer
  2. Install it on \BizTalk Server 2010\PipelineComponents.
  3. Go to \BizTalk Server 2010\PipelineComponents\BizTalkMsgArchiveScripts folder, execute RegisterSource.cmd (As administrator), this will register the source so that the pipeline can log to the event log.

Usage – Design Time – VS2010

  1. Open VS2010 -> Create new BizTalk Project -> Add Receive Pipeline
  2. Right Click ToolBox -> Choose Items
  3. Go to BizTalk Pipeline Components -> Check BizTalk Message Archiving Component
  4. New Pipepline Added to the toolbox.
  5. Drag & Drop the BizTalk Message Archiving Component to Decode Stage.
  6. Configure Properties (see Configuration)

Note: You can also configure the Properties using BizTalk Administration Console.

Setup – SQL Archiving

Since the archiving will use an SQL Database, you’ll need to create the database and table.

  1. Go to \BizTalk Server 2010\PipelineComponents\BizTalkMsgArchiveScripts folder.
  2. Execute the CreateDatabase.sql on the target database server. This will create the database named: BizTalkArchiveDb, table named: Messages and stored procedure named: InsMessages

Configuration

  1. Deploy the pipeline that uses the BizTalk Message Archiving Component (See Usage – Design Time – VS2010)
  2. Using BizTalk Administration Console, create a new Receive Location and use the pipeline on previous number, on the pipeline click the Elipsis .. to display properties.
Property Name Description Use In Sample Values Notes
CompressionPassword Password that will be used in zip file File & SQL Archiving P@ssw0rd
DbConnProvider Connection Provider SQL Archiving System.Data.SqlClient
DbConnStr Database connection string SQL Archiving Data Source=localhost;Initial Catalog=BizTalkArchiveDb;Integrated Security=SSPI; Using integrated security you need to grant the identity of the host wherein the receive/send port is binded permission to BizTalkArchiveDb with ff roles: dbdatareaderdatawriter, db and execute permission on the stored procedure InsMessages
DbFileExtensions File extension to be used SQL Archiving .xml
DbPropList This is a set of delimited values of name & namespace of message context properties that will be passed to the stored procedure to be used for custom logging. SQL Archiving ReceivedFileName;http://schemas.microsoft.com/BizTalk/2003/file-properties|ReceivedPortName;http://schemas.microsoft.com/BizTalk/2003/system-properties Format is Property Name;Namespace and for multiple values the delimiter is ‘|’ pipe symbol.
DbSPName Stored procedure name SQL Archiving Built-In: InsMessages The stored procedure can be customized as long as it has the same signature with the default one. For instance, there can be additional logic to parse the Message Properties and insert it into the new custom table
FileArchiveBackFolder Folder / Shared Location / Network location wherein the files will be archived File Archiving \\RPaulo2011\Test\Archive If it’s a shared folder the pipeline will try to use first the identity of the host, if it failed it will use the credentials supplied (see FileArchive UserName, Password, Domain)
FileArchiveFileName Name of the archive file File Archiving %SourceFileName%_%datetime% Supported macros are: – %SourceFileName%, %MessageID%,%datetime%, %time%
FileArchiveIsOverwriteFiles Overwrite Flag File Archiving True
FileArchiveUserDomain Domain name of user credentials File Archiving PAULOR This values will be used if the identity of the host instance doesn’t have permission on the backup folder.
FileArchiveUserName User name File Archiving BizTalkUser This values will be used if the identity of the host instance doesn’t have permission on the backup folder.
FileArchiveUserPwd Password File Archiving P@ssword This values will be used if the identity of the host instance doesn’t have permission on the backup folder.
IsArchiveToDb Archive to database flag SQL Archiving True True = Archive to database, False = Disabled
IsArchiveToFile Archive to file flag File Archiving True True = Archive to file, False = Disabled
IsCompressFile compress file flag SQL & File Archiving True True = Compress the file, False = No compression, It uses DotNetZip

Usage – Downloading Archive Files using ASP.NET

https://randypaulo.wordpress.com/2011/06/21/storing-files-to-database-and-downloading-using-asp-net/

Sending IDOCs to SAP using SSIS – MSSQL Integration Services

Normally receiving and sending IDOCs can be easily done by using BizTalk Adapter for mySAP Business in BizTalk Server which is included in Microsoft BizTalk Adapter Pack 2.0. But what if I want to send an IDOC using SSIS and BizTalk is installed on a different server? Below are the steps on how you can do that.

Note: Since SSIS 2008 only supports <= .NET 3.5 all custom assemblies that will be called within it should be using this framework.

Prerequisites:

1. WCF LOB SDK Adapter (WCF-LOB-Adapter-SDK-2010-x86.exe) – Get it here. or in BizTalk DVD Installer under BizTalk Server\ASDK_X86

2. Microsoft BizTalk Adapter Pack 2.0 x86 – Get Evaluation version here. or in BizTalk DVD Installer under BizTalk Server\AdapterPack_x86

3. SAP Libraries x86 – this needs to be installed on C:\Windows\SysWOW64 folder. See section for SAP Adapter in this Microsoft Adapter Pack 2.0 install guide.

IDOC Library:

Next step is to create an IDOC WCF Client that you can call inside SSIS.

1. Open Visual Studio -> Create a new Project Library.

2. Right click the Project -> Click Add Adapter Service Reference.

3. Set the binding to sapBinding and set the configure a URI to:

sap://CLIENT={SAP Client ID};LANG=EN;@A/{Application Server Host}/{System Number}?ListenerGwServ={Gateway Service}&ListenerGwHost={Gateway Host}&ListenerProgramId={Program Id}&RfcSdkTrace=False&AbapDebug=False.  See this help for the configuration

4. Click Configure and set the credentials, then click Connect. Since we are sending IDOCS the contract type should be set to Client (Outbound operations).

5. In the Category, browse for the specific type of IDOC and version, when generating the schema you might encounter an error : “Error returned by RfcCallReceiveEx while calling RFC: IDOCTYPE_READ_COMPLETE..”, It means that you’re selecting an incorrect version of the IDOC, you should ask your SAP resource to identify the Release Number.

Select the Send and click Add. Click OK. This will generate a WCF client that you can call inside SSIS.

6. Sign the Assembly, compile and deploy to GAC then copy to C:\windows\Microsoft.NET\Framework\v2.0.50727.

It’s necessary to copy to this folder so you can add a reference to it in SSIS.

SSIS:

1. Add a data flow.

2. Set OLE DB Source / File / etc.

3. Add a Script Task, set the script task to Script Destination. Double click the script task and change the target framework to .NET 3.5 by going to project properties.

Add reference to the IDOC Library.

Create the IDOC object and pass it to the IDOC WCF Client.

References:

Using Scripting Destination in SSIS

Sample on how to call WCF client in SSIS
To call IDOC WCF Client:

I’ve modified the code and copied it from http://technet.microsoft.com/en-us/library/cc185231(BTS.10).aspx


using System;
using System.Collections.Generic;
using System.Text;

// Add WCF, WCF LOB Adapter SDK, and SAP adapter namepaces
using System.ServiceModel;     //Change the Project to target .NET 3.5 and reference System.ServiceModel
using Microsoft.Adapters.SAP; //This assembly is under the Microsoft Adapter Pack 2.0 install folder
using Microsoft.ServiceModel.Channels; //This assembly is under WCF LOB SDK Install folder

// Include this namespace for WCF LOB Adapter SDK and SAP exceptions
using Microsoft.ServiceModel.Channels.Common;

namespace SapTypeIDOCClient
{
    class Program
    {
        static void Main(string[] args)
        {
            // variable for the IDOC client
            IdocClient idocClient = null;

            Console.WriteLine("IDOC XML client sample started");
            try
            {

                //Construct IDOC Object here. MATMAS01, PHRMAS01, SUBMAS
                var idocObj = new {IDOC OBJECT}

                //Assign Properties and segments of IDOCS here.
                //idocObj.

                // Variable for the GUID
                System.Nullable adapterTxGuid;
                // string to hold the Idoc data
                string idocData;
                // string to hold the SAP transaction ID (TID)
                string sapTxId;

                // The client can be configured from app.config, but it is
                // explicitly configured here for demonstration.
                // set AutoConfirmSentIdocs property to true
                SAPBinding binding = new SAPBinding();
                binding.AutoConfirmSentIdocs = true;

                // Set endpoint address
                EndpointAddress endpointAddress = new EndpointAddress("{SAP Connection String see settings above");

                // Create client and set credentials
                idocClient = new {IDOC WCF Client}(binding, endpointAddress);
                idocClient.ClientCredentials.UserName.UserName = "YourUserName";
                idocClient.ClientCredentials.UserName.Password = "YourPassword";

                // Open the client and send the Idoc
                idocClient.Open();

                //Get a new GUID to pass to SendIdoc. You can also assign a null.
                //value to have the adapter generate a GUID.
                adapterTxGuid = Guid.NewGuid().ToString();

                //We are using the Send Method, it accepts a strongly typed iDOC (XML), SendIdoc sends FlatFile IDOC
                idocClient.Send(idocData, ref adapterTxGuid);

                // The AutoConfirmSentIdocs binding property is set to true, so there is no need to
                // confirm the IDOC. If this property is not set to true, you must call the
                // RfcConfirmTransID method of a TrfcClient with adapterTxGuid to
                // confirm the transaction on the SAP system.

                // Get SAP tx id from GUID
                sapTxId = SAPAdapterUtilities.ConvertGuidToTid((Guid) adapterTxGuid);

                Console.WriteLine("IDOC sent");
                Console.WriteLine("The SAP Transaction Id is : " + sapTxId);

            catch (Exception ex)
            {
                Console.WriteLine("Exception is: " + ex.Message);
                if (ex.InnerException != null)
                {
                    Console.WriteLine("Inner Exception is: " + ex.InnerException.Message);
                }
            }
            finally
            {
                // Close the IDOC client
                if (idocClient != null)
                {
                    if (idocClient.State == CommunicationState.Opened)
                        idocClient.Close();
                    else
                        idocClient.Abort();
                }
            }

        }
    }
}