How to integrate BizTalk Server 2010 / 2013 with Service Bus for Windows Server

This solution shows how to integrate a BizTalk Server 2010/2013 application with Service Bus for Windows Server using the WCF-Custom adapter to exchange messages with external systems in a reliable, flexible, and scalable manner.

C# (5.3 MB)
 
 
 
 
 
4.7 Star
(6)
1,705 times
Add to favorites
6/20/2014
E-mail Twitter del.icio.us Digg Facebook

Solution explorer

C#
#region Copyright
//=======================================================================================
//Microsoft Windows Server AppFabric Customer Advisory Team (CAT)  
//
// This sample is supplemental to the technical guidance published on the community
// blog at http://blogs.msdn.com/paolos. 
// 
// Author: Paolo Salvatori
//=======================================================================================
// Copyright � 2011 Microsoft Corporation. All rights reserved.
// 
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER 
// EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF 
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. YOU BEAR THE RISK OF USING IT.
//=======================================================================================
#endregion

#region Using Directives
using System;
using System.IO;
using System.Xml;
using System.Collections.Generic;
using Microsoft.XLANGs.BaseTypes;
using Microsoft.BizTalk.Streaming;
using Microsoft.WindowsAzure.CAT.Samples.ServiceBusForWindowsServer.PropertySchemas;
#endregion

namespace Microsoft.WindowsAzure.CAT.Samples.ServiceBusForWindowsServer.BusinessLogic
{
    /// <summary>
    /// This class contains helper methods used by the orchestrations.
    /// </summary>
    [Serializable]
    public class RequestManager
    {
        #region Private Constants
        //***************************
        // Private Constants
        //***************************
        private const string CalculatorResponseNamespace = "http://windowsazure.cat.microsoft.com/samples/servicebusforwindowsserver";
        private const string OperationUnknownErrorMessageFormat = "The operation failed because the operator {0} is unknown.";
        private const string OperationFormat = "[RequestManager]{0} {1} {2} = {3}";
        private const string Ok = "Ok";
        private const string None = "None";
        private const string OperationsFailed = "Some operations failed";
        #endregion

        #region Private Fields
        //***************************
        // Private Fields
        //***************************
        private LogHelper logHelper = new LogHelper();
        #endregion

        #region Public Methods
        //***************************
        // Public Methods
        //***************************

        /// <summary>
        /// This function is used by the StaticSendPortOrchestration to determine 
        /// whether to return the response message via queue or a topic.
        /// </summary>
        /// <param name="message">The request message.</param>
        /// <returns>true if the replyTo url contains the word queue, false otherwise.</returns>
        public bool ReturnResponseViaQueue(XLANGMessage message)
        {
            var toQueue = true;
            string uri = null;
            try
            {
                if (message != null)
                {
                    uri = message.GetPropertyValue(typeof (ReplyTo)) as string;
                    toQueue = !string.IsNullOrEmpty(uri) && uri.ToLower().Contains("queue");
                }
            }
            catch (Exception ex)
            {
                logHelper.WriteLine(string.Format("[RequestManager] {0}", ex.Message));
            }
            finally
            {
                logHelper.WriteLine(string.Format(toQueue ? 
                                                  "[RequestManager] Send response message to [{0}] queue." :
                                                  "[RequestManager] Send response message to [{0}] topic.", 
                                                  uri ?? "NULL"));
                if (message != null)
                {
                    message.Dispose();
                }
            }
            return toQueue;
        }

        /// <summary>
        /// Processes a request message and returns the response message in a stream.
        /// </summary>
        /// <param name="message">The request message.</param>
        /// <returns>The stream containing the payload of the response message.</returns>
        public Stream ProcessRequestReturnStream(XLANGMessage message)
        {
            VirtualStream stream = null;
            var responseList = new List<Response>();
            var status = Ok;
            var ok = true;
            var i = 0;

            try
            {
                logHelper.WriteLine("[RequestManager] Request message received.");
                const int bufferSize = 1048576; 
                const int thresholdSize = 1048576;
                using (var virtualStream = new VirtualStream(bufferSize, thresholdSize))
                {
                    using (var partStream = (Stream)message[0].RetrieveAs(typeof(Stream)))
                    {
                        using (var readOnlySeekableStream = new ReadOnlySeekableStream(partStream, virtualStream, bufferSize))
                        {
                            using (var reader = XmlReader.Create(readOnlySeekableStream))
                            {
                                while (reader.Read() && ok)
                                {
                                    if (reader.LocalName == "Operator" &&
                                        reader.NodeType == XmlNodeType.Element)
                                    {
                                        var succeeded = true;
                                        var error = None;
                                        double value = 0;
                                        var op = reader.ReadElementContentAsString();
                                        reader.MoveToContent();
                                        var operand1 = reader.ReadElementContentAsDouble();
                                        reader.MoveToContent();
                                        var operand2 = reader.ReadElementContentAsDouble();
                                        i++;
                                        switch (op)
                                        {
                                            case "+":
                                                value = operand1 + operand2;
                                                break;
                                            case "-":
                                                value = operand1 - operand2;
                                                break;
                                            case "*":
                                            case "x":
                                                value = operand1 * operand2;
                                                break;
                                            case "/":
                                            case "\\":
                                            case ":":
                                                value = operand1 / operand2;
                                                break;
                                            default:
                                                error = string.Format(OperationUnknownErrorMessageFormat, op);
                                                status = OperationsFailed;
                                                ok = false;
                                                succeeded = false;
                                                break;
                                        }
                                        logHelper.WriteLine(succeeded
                                                                ? string.Format(OperationFormat, 
                                                                                operand1, 
                                                                                op, 
                                                                                operand2,
                                                                                value)
                                                                : error);
                                        responseList.Add(new Response(error, value));
                                    }
                                }
                            }
                        }
                    }
                }
                if (ok)
                {
                    stream = new VirtualStream();
                    using (var writer = XmlWriter.Create(stream))
                    {
                        writer.WriteStartDocument();
                        writer.WriteStartElement("CalculatorResponse", CalculatorResponseNamespace);
                        writer.WriteStartElement("Status", CalculatorResponseNamespace);
                        writer.WriteString(status);
                        writer.WriteEndElement();
                        writer.WriteStartElement("Results", CalculatorResponseNamespace);
                        for (i = 0; i < responseList.Count; i++)
                        {
                            writer.WriteStartElement("Result", CalculatorResponseNamespace);
                            writer.WriteStartElement("Value", CalculatorResponseNamespace);
                            writer.WriteString(responseList[i].Value.ToString());
                            writer.WriteEndElement();
                            writer.WriteStartElement("Error", CalculatorResponseNamespace);
                            writer.WriteString(responseList[i].Error);
                            writer.WriteEndElement();
                            writer.WriteEndElement();
                        }
                        writer.WriteEndElement();
                        writer.WriteEndElement();
                    }
                    stream.Seek(0, SeekOrigin.Begin);
                    logHelper.WriteLine("[RequestManager] Response message successfully processed.");
                }
            }
            catch (Exception ex)
            {
                logHelper.WriteLine(string.Format("[RequestManager] {0}", ex.Message));
                stream = new VirtualStream();
                using (var writer = XmlWriter.Create(stream))
                {
                    writer.WriteStartDocument();
                    writer.WriteStartElement("CalculatorResponse", CalculatorResponseNamespace);
                    writer.WriteStartElement("Status", CalculatorResponseNamespace);
                    writer.WriteString(ex.Message);
                    writer.WriteEndElement();
                    writer.WriteEndElement();
                }
                stream.Seek(0, SeekOrigin.Begin);
            }
            finally
            {
                message.Dispose();
            }
            return stream;
        }
        #endregion
    }
}