Using Microsoft .NET in WebSphere Message Broker V8

Part 2: Integrating with Microsoft Word


Content series:

This content is part # of # in the series: Using Microsoft .NET in WebSphere Message Broker V8

Stay tuned for additional content in this series.

This content is part of the series:Using Microsoft .NET in WebSphere Message Broker V8

Stay tuned for additional content in this series.

Before you start

IBM® WebSphere® Message Broker V8 (hereafter called Message Broker) provides the capability to integrate with existing Microsoft® .NET® Framework (hereafter called .NET) applications. You can do this integration by wiring the new Message Broker .NETCompute node into a message flow, or by calling a .NET application from an ESQL Compute node. This series of tutorials shows you how to use the .NETCompute node integration technique.

WebSphere Message Broker and Microsoft .NET

WebSphere Message Broker and Microsoft .NET

About this tutorial series

This series of four tutorials shows you how to write and build C# code in Microsoft Visual Studio 2010 (either Express Edition or Professional Edition) using an embedded template provided by WebSphere Message Broker Toolkit. The four tutorials explore the following topics:

  1. Using the .NETCompute node sample
  2. Using the .NETCompute node to integrate with Microsoft Word
  3. Using the .NETCompute node to integrate with Microsoft Excel
  4. Using the .NETCompute node for exception handling

About this tutorial

This .NETCompute node sample filters, modifies, and transforms messages using code written in C#. You can use the .NETCompute node on Microsoft Windows® brokers to construct output messages and interact with the Microsoft .NET framework (.NET) or Component Object Model (COM) applications.

WebSphere Message Broker enables you to host and run .NET code inside an execution group. The new .NETCompute node routes or transforms messages by using any Common Language Runtime (CLR) compliant .NET programming language, such as C#, Visual Basic (VB), F#, or C++/Common Language Infrastructure (CLI). This tutorial describes the new .NET API provided by WebSphere Message Broker, which enables .NET developers to interact with Message Broker's logical tree.

Prerequisites and system requirements

This tutorial is written for WebSphere Message Broker programmers who want to learn about the new .NETCompute node, and for .NET programmers who want to learn about using WebSphere Message Broker. If you have a general familiarity with C# or with Message Broker, then you should find the tutorial relatively easy to complete.

To build and execute the example in this tutorial, you will need:

  • A Windows installation that includes Microsoft .NET Framework V4
  • WebSphere Message Broker (Toolkit and Runtime) V8
  • Microsoft Visual Studio 2010 (Express Edition or Professional Edition) to write and build the required C# code

The C# code in this tutorial takes data from the Message Broker logical tree and uses it to create a Microsoft Word document. The code uses the Open XML Format SDK (Version 2), which is an API for the .NET Framework that enables developers in both client and server environments to interact with Microsoft Word. Before starting the tutorial:

  1. Download Microsoft Open XML SDK V2.
  2. Launch OpenXMLSDKv2.msi, click Next on the splash panel, and accept the license agreement.
  3. Choose an install location or accept the default: C:\Program Files\Open XML SDK\V2.0\.
  4. Confirm the settings, wait for the installation to complete, and then click Close.

If you do not have a full copy of Microsoft Word, you can download and install the Microsoft Word Viewer and the Microsoft Office Compatibility Pack:

  1. Download Microsoft Word Viewer.
  2. Launch wordview_en-us.exe, accept the licence terms, click Continue, accept additional licence terms, and then click Next.
  3. Choose an install location or accept the default: C:\Program Files\Microsoft Office\.
  4. Wait for the installation to complete and then click OK twice to exit the installer.
  5. Download Microsoft Office Compatibility Pack.
  6. Launch FileFormatConverter.exe, accept the licence terms, and click Continue.
  7. Wait for the installation to complete and then click OK.

This tutorial provides a simple Web service definition using a WSDL file that you can drag and drop onto a Message Broker flow in order to create a Message Broker Web service facade. This flow can be called by a Web service client using SOAP over HTTP. The request message sent to the flow represents a sales order for various items from a store.

Having received the data, the message flow uses C# code within a .NETCompute node to create a short Microsoft Word document that contains the detail of the sales order in a table. The Word document is written to a directory on the file system and then the message flow sends an acknowledgement message back to the Web service client.


Creating the message flow

Download the zip file at the bottom of the article and extract the contents into the directory C:\student\DOTNET\lab_msword.

  1. Assuming that the WebSphere Message Broker Toolkit has not yet been started, from the Start menu, choose Start => Programs => IBM WebSphere Message Broker Toolkit => IBM WebSphere Message Broker Toolkit 8.0 => WebSphere Message Broker Toolkit 8.0. You will be asked for the location of a workspace -- the rest of this tutorial assumes that you are using C:\student\DOTNET\lab_msword\workspace.
  2. Close the Welcome screen and from your empty workspace, launch the Quick Start wizard: Click Start from WSDL and/or XSD, as shown below with the red box. If you have chosen to use your own existing workspace, you can also launch the Quick Start menu by clicking on the New link at the top of the Broker Development view on the left side of the window:

    Quick Start menu
    Quick Start menu
  3. The Quick Start wizard requires an application name for the application in which the message flow and Web service definition will be located. Specify the name App_DotNet_MSWord and click Next:

    Quick Start wizard
    Quick Start wizard
  4. On the next panel, select Use external resources and navigate to the artifacts provided in the download file. If you have followed the instructions so far, you will find them in the directory C:\student\DOTNET\lab_msword. Select the Order.wsdl file, which contains the Web service definition, and then click Next:

    Quick Start wizard
    Quick Start wizard
  5. On the final Binding Selection panel, accept the default settings, which will import the OrderSoapHttpBinding (the WSDL file contains only one binding!). Click Finish:

    Binding selection
    Binding selection
  6. When the wizard completes, you will see that a new application that contains the imported WSDL file and the XML schema file that it references. In the next step, you will use the WSDL file to generate the message flow contents, as described by the pop-up box that the Message Broker Toolkit displays on completing the wizard:

    Drag and drop results
    Drag and drop results
  7. The message flow file MyFlow.msgflow should already be open in the WebSphere Message Broker Toolkit. Drag the WSDL file Order.wsdl and drop it on to the message flow canvas. The Configure New Web Service Usage wizard opens. The WSDL file is used to describe an interface to the flow and expose it as a Web service. Leave all of the default settings and click Finish:

    Configure nNew Web service usage
    Configure nNew Web service usage
  8. The Broker Toolkit generates a message flow that has been populated with a SOAP Input node, a SOAP Reply node, and a subflow named Order. The subflow extracts the body of the SOAP message and places it in the XMLNSC message domain, before returning to the main flow. In its current state, the message flow leaves a gap between the subflow and the SOAP Reply node. It is in this gap that you place a transformation that generates the Microsoft Word document, and also produces a reply message of the correct format, which is passed to the SOAP Reply node to send back to the Web service client:

    MyFlow.msgflow at creation time
    MyFlow.msgflow at creation time
  9. Place a .NETCompute node from the Transformation drawer of the flow palette into the message flow between the Order subflow node and the SOAPReply node. Wire the node terminals as shown below:

    MyFlow.msgflow with .NETCompute node added
    MyFlow.msgflow with .NETCompute node added
  10. Right-click the .NETCompute node and select Open Microsoft Visual Studio to launch Microsoft Visual Studio, which you will use to develop the C# code that the .NETCompute node will use to integrate with the logical message tree and create the Microsoft Word document:

    Open Microsoft Visual Studio menu option
    Open Microsoft Visual Studio menu option

You will return to the message flow once you have written and built the C# code in Microsoft Visual Studio.

Writing the C# code in Microsoft Visual Studio

The following images were taken with Microsoft Visual Studio Professional Edition, you can also do this tutorial using Microsoft Visual Studio Express Edition.

  1. Once the Microsoft Visual Studio has launched, it displays the Start page shown below. Select New project, as highlighted in the red box:

    Microsoft Visual Studio New Project
    Microsoft Visual Studio New Project
  2. The New Project wizard offers you the three types of Project templates. Select the one named Project to create a Message Broker message, specify the properties at the bottom of the window as follows, and then click OK:

    Name = MSWordDotNetProject
    Location = C:\student\DOTNET\lab_msword\visual studio 2010\Projects
    Solution Name = MSWordDotNetProject

    New Project dialog
    New Project dialog

    If the WebSphere Message Broker Toolkit is installed after Microsoft Visual Studio, then the Message Broker project templates will be automatically installed ready for you to use. However, if the Broker Toolkit is installed first, then you will need to manually install the templates by executing the file IBM.Broker.DotNet.vsix and stepping through the wizard. If you have used the default installation location, you will find this file at
    C:\Program Files (x86)\IBM\WMBT800\wmbt.

  3. Once the project is created, expand the Solution Explorer view. You should see that the CreateNode.cs file has been created to contain the C# class. Also notice that a reference to IBM.Broker.Plugin has been added. This assembly contains the API provided by Message Broker to transform messages in a .NETCompute node. You will also be interacting with two additional .NET Framework assemblies -- one provided by the Open XML SDK 2.0 API, and one that is included in the Windows .NET framework. Right-click the References level of the hierarchy in Solution Explorer and select Add Reference:

    Solution Explorer
    Solution Explorer
  4. In the Add Reference dialog, switch to the .NET tab and locate the component DocumentFormat.OpenXml. If you cannot find the entry, first make sure that you have sorted the components alphabetically. If the entry is definitely not in the list, then return to the System requirements section above and follow the instructions to download and install the Open XML SDK 2.0 API. Once you locate the DocumentFormat.OpenXml component, click OK:

    Add reference to DocumentFormat.OpenXml
    Add reference to DocumentFormat.OpenXml
  5. Repeat the last two steps in order to add a second reference to the project. This time, locate the reference named WindowsBase on the .NET tab, as shown below, and click OK:

    Add reference to WindowsBase
    Add reference to WindowsBase
  6. The Solution Explorer should now show that the assembly references have been added successfully:

    Solution Explorer references
    Solution Explorer references
  7. The template class file CreateNode.cs should be open and ready for you to edit. At the top of the file, add some using directives so that you can use the classes and methods contained in the assembly references that were just added without having to fully qualify them in the C# code. This technique enables you to write more concise and more readable code. The image below shows where to insert the statements, and the listing that follows provides the statements that should be added:

    Inserting using statements
    Inserting using statements
    Listing 1. Using directives to be placed at the top of CreateNode.cs
    using DocumentFormat.OpenXml;
    using DocumentFormat.OpenXml.Packaging;
    using DocumentFormat.OpenXml.Wordprocessing;
    using SOAP = IBM.Broker.Plugin.NBParsers.SOAP;
  8. Create two new methods within the CreateNode class, named AddParagraph and AddCellToTable. The methods will be called from the Evaluate method (the entry point for the C# code that is executed by the .NETCompute node). Insert these two methods into the hierarchy of the CreateNode.cs class file as siblings of the CopyMessageHeaders method, as highlighted by the red arrow below:

    Location of methods in CreateNode.cs
    Location of methods in CreateNode.cs

    C# code is provided for the methods in the two code listings below. The AddParagraph method's signature receives a Body object and a text string. The purpose of the method is to create and then append a new paragraph at the end of the document body. The string passed to the method provides the content for the paragraph:

    Listing 2. Sample code for the AddParagraph method
    private static void AddParagraph(Body body, String wording)
              Paragraph paragraph = new Paragraph();
              Run run = new Run();
              Text text = new Text(wording);
              paragraph. Append(run);

    The AddCellToTable method's signature receives a TableRow object and a text string. The purpose of the method is to create and then append a new cell to the end of the table row in the document. The string passed to the method provides the content for the cell:

    Listing 3. Sample code for the AddCellToTable method
    private static void AddCellToTable(TableRow tableRow, String wording)
              var tableCell = new TableCell();
              tableCell.Append(new Paragraph(new Run(new Text(wording))));
              tableCell.Append(new TableCellProperties(new TableCellWidth()
                        Type = TableWidthUnitValues.Dxa,
                        Width = "2400"

    Next, populate the UserCode region of the Evaluate method. The code for this section has been broken up into four separate listings below, so that we can explain the purpose of each section as we go along.

  9. The purpose of the first section of code within the Evaluate method is to create a WordprocessingDocument object that represents the content and structure of the Microsoft Word document file that will be produced. A static path is defined for the output file at C:\student\DOTNET\lab_msword\Test.docx. The document that will be produced is a letter of correspondence. It begins with a few lines of text, and then each paragraph is appended to the body of the output document by calling the logic in the AddParagraph method you created earlier:
    Listing 4. First section of sample code for the UserCode region of the Evaluate method
    #region UserCode
         // Add user code in this region to create a new output message
         string filename = "Test.docx";
         string path = @"C:\student\DOTNET\lab_msword\";
         string srcFile = System.IO.Path.Combine(path, filename);
         WordprocessingDocument wpDoc = 
         MainDocumentPart DocPart = wpDoc.AddMainDocumentPart();
         DocPart.Document = new Document();
         Body body = new Body();
         AddParagraph(body, "Dear Sir,");
         AddParagraph(body, "");
         string text = "Thank you very much for your recent correspondence. ";
         text = text + "Your invoice is displayed in the table below:";
         AddParagraph(body, text);
         AddParagraph(body, "");
  10. The second section of sample code that is added to the Evaluate method sets up a table in the document. A Table object is created along with a TableRow object. Seven invocations of the AddCellToTable method are made, each of which adds an extra cell with some static text to the TableRow. This row is appended as the first row in the table. The purpose of this header row is to hold the title names for each data column. The next section of code populates data values into further rows of the table.
    Listing 5. Second section of sample code for the UserCode region of the Evaluate method
         Table table = new Table();
         var HeaderRow = new TableRow();
         AddCellToTable(HeaderRow, "Code(1)");
         AddCellToTable(HeaderRow, "Code(2)");
         AddCellToTable(HeaderRow, "Code(3)");
         AddCellToTable(HeaderRow, "Description");
         AddCellToTable(HeaderRow, "Category");
         AddCellToTable(HeaderRow, "Price");
         AddCellToTable(HeaderRow, "Quantity");
  11. The next section of the C# code navigates to the Invoice section of the inbound message and uses the Itemlist variable to hold the set of child elements, which are named Item. Each iteration of the loop adds an extra row to the table, which contains values from the input message for the properties of each Item, such as Code, Description, and Price. Once the loop is complete, the table is appended to the body of the document, and then some additional invocations of the AddParagraph method finish off the letter. Finally for this section of code, the body object is appended to the document, which is then saved and closed:
    Listing 6. Third section of sample code for the UserCode region of the Evaluate method
    NBElement Invoice = 
         var Itemlist = Invoice.Children("Item");
         foreach (NBElement element in Itemlist)
              var NewRow = new TableRow();
              AddCellToTable(NewRow, (string)element["Code", 0]);
              AddCellToTable(NewRow, (string)element["Code", 1]);
              AddCellToTable(NewRow, (string)element["Code", 2]);
              AddCellToTable(NewRow, (string)element["Description"]);
              AddCellToTable(NewRow, (string)element["Category"]);
              AddCellToTable(NewRow, ((decimal)element["Price"]).ToString());
              AddCellToTable(NewRow, (string)element["Quantity"]);
    AddParagraph(body, "");
    AddParagraph(body, "Yours faithfully,");
    AddParagraph(body, "");
    AddParagraph(body, "The WebSphere Message Broker");
    AddParagraph(body, "IBM UK Ltd, Hursley Park, Winchester SO21 2JN, UK.");
  12. The purpose of the final section of C# in the UserCode region is to construct the logical tree for the reply message that the message flow will end up returning to the Web service client. The output logical tree is constructed under the XMLNSC domain. The root element of the XMLNSC tree is named SaleAcknowledge, and this element becomes the root element of the message's SOAP body when it is written to the wire. The CreateDoubleNamespaceDeclaration method is a useful helper method provided by the WebSphere Message Broker .NET API that creates a namespace prefix / pair mapping in the tree, so that you can create messages that use your choice of prefix when serialising the output. The CreateFirstChild message is used to create the ResponseMessage element, which simply contains the string Message received! to indicate to the Web service client that the invocation of the broker flow has been successfully completed:
    Listing 7. Fourth section of sample code for the UserCode region of the Evaluate method
         NBElement soap = outputRoot.CreateLastChildUsingNewParser(SOAP.ParserName);
         string ns = "";
         string soapNs = "";
         NBElement ctx = soap.CreateLastChild("Context").CreateLastChild("Namespace");
              "xmlns", "soapenv", soapNs);
         NBElement soapBody = soap.CreateLastChild("Body");
         NBElement saleAck = soapBody.CreateLastChild(ns, "SaleAcknowledge");
         saleAck.CreateLastChild(SOAP.DoubleNamespaceDeclaration, "xmlns", "order", ns);
         saleAck.CreateLastChild(null, "ResponseMessage", "Message received!");
    #endregion UserCode
  13. With the development work now complete, you will build an assembly file that you will reference from the .NETCompute node. From the Solution Explorer, right click on Solution and select Build Solution:

    Build the solution
    Build the solution
  14. The Output window shows you where the built assembly file has been saved on your file system. Depending on how you have Microsoft Visual Studio configured, the Build Output window may not be immediately visible. If it is not, follow the instructions in the sidebar to open the Output window.

    Build output
    Build output

    If you have used the default naming suggested throughout this tutorial, the assembly file will be saved at:

    C:\student\DOTNET\lab_msword\visual studio 2010\Projects\MSWordDotNetProject\

The next section of the tutorial shows you how to unite your message flow development and the C# assembly you have built, and deploy to Message Broker.

Preparation and deployment to Message Broker

Having built an assembly file from the C# code, you can drag and drop the assembly file from a Windows Explorer window directly onto a .NETCompute node in a message flow in order to associate the node with the code. This technique results in a hard-coded absolute location for the assembly. This approach saves time when developing, testing, and hot-swapping the .NET code that the Broker is executing. For production situations, a more typical approach is to define a Message Broker Configurable Service that specifies to a .NETCompute node where to locate the assembly file. If a Configurable Service is used, it will override a hard-coded absolute location for the assembly. Here is the drag and drop technique for the configuration of the current scenario:

  1. To prepare for the drag and drop, return to the WebSphere Message Broker Toolkit, where the message flow MyFlow.msgflow that you created earlier should still be open. Open a Windows Explorer window in front of the Toolkit and navigate to the location where you built the assembly file in the previous section. If you have followed the default naming so far, the location will be:
    C:\student\DOTNET\lab_msword\visual studio 2010\Projects\MSWordDotNetProject\

    Drag and drop the assembly on top of the .NETCompute node in the flow, as shown by the red arrow:

    Drag and drop assembly to configure the .NETCompute node
    Drag and drop assembly to configure the .NETCompute node
  2. Inspect the properties of the .NETCompute node and you should see that the Assembly name property has now been configured, as shown below. Save the message flow by pressing Ctrl-S:

    Assembly name property of the .NETCompute node
    Assembly name property of the .NETCompute node
  3. In order to deploy the application (which contains the message flow and Web service definition) you have created, simply drag and drop it onto a runtime execution group, such as the default configuration shown below. The red arrow shows the drag and drop movement:

    Application deployment via drag and drop
    Application deployment via drag and drop

The next section of the tutorial shows you how to test the scenario.

Testing the Scenario

This final section of the tutorial shows you how to test the entire scenario directly from the Message Broker Toolkit using its built-in Test Client.

  1. The test data for the message flow has been saved into a message flow test client file with the file extension .mbtest. This test data file is included in the download file for this article. From the Message Broker Toolkit, select File => Import. In the resulting wizard, expand the General section, highlight File system import as shown below, and then click Next:

    Import wizard
    Import wizard
  2. On the next panel of the wizard, navigate to the location in your file system where you extracted the download file. The image below assumes a location of C:\student\DOTNET\lab_msword. Select the test client file named App_DotNet_MSWord.mbtest. Using the Browse button, specify the folder App_DotNet_MSWord as the import destination, and then click Finish:

    Import wizard -- File system panel
    Import wizard -- File system panel
  3. Locate the imported file, App_DotNet_MSWord.mbtest in the application App_DotNet_MSWord, and double-click on it to open:

    Open test client file App_DotNet_MSWord.mbtest
    Open test client file App_DotNet_MSWord.mbtest
  4. This tutorial assumes that you have already set up a runtime broker using the default configuration, which provides a message broker named MB8BROKER. For more information on the default configuration, see Creating the Default Configuration in the Message Broker information center. If you are using a different runtime configuration, you can edit the test client file by switching to the Configuration tab, marked with the red box below:

    Configuration tab of App_DotNet_MSWord.mbtest
    Configuration tab of App_DotNet_MSWord.mbtest
  5. The sample test input message provided in the test client file is shown in the listing below:
    Listing 8. Sample test message input data
    <soapenv:Envelope xmlns:soapenv=""
           <Description>The Times Newspaper</Description>
           <Category>Books and Media</Category>

    To test the message flow, click the Send Message button as marked by the red box below:

    Send message button of App_DotNet_MSWord.mbtest
    Send message button of App_DotNet_MSWord.mbtest
  6. Once the test has run, you should see the output acknowledgement message displayed:

    Test result
    Test result

    Here is a listing of the output message:
    Listing 9. SaleEnvelope message sample output data
    <?xml version="1.0" encoding="utf-8"?>
    <soapenv:Envelope xmlns:soapenv="">
      <order:SaleAcknowledge xmlns:order="">
       <ResponseMessage>Message received!</ResponseMessage>
  7. Finally, use a Windows Explorer window to navigate to the output location of the Word document on the file system at C:\student\DOTNET\lab_msword\Test.docx. Open the Word document and you should see the contents of the invoice displayed in the table:

    Test result
    Test result

This is the end of the task steps for Part 2 of this tutorial series. You can continue on to the download links, resource links, and author information by clicking Next below, or you can go on to Part 3 of the tutorial series.

Downloadable resources

Related topics

  • WebSphere Message Broker resources
  • WebSphere resources
    • developerWorks WebSphere developer resources
      Technical information and resources for developers who use WebSphere products. developerWorks WebSphere provides product downloads, how-to information, support resources, and a free technical library of more than 2000 technical articles, tutorials, best practices, IBM Redbooks, and online product manuals.
    • developerWorks WebSphere application integration developer resources
      How-to articles, downloads, tutorials, education, product info, and other resources to help you build WebSphere application integration and business integration solutions.
    • Most popular WebSphere trial downloads
      No-charge trial downloads for key WebSphere products.
    • WebSphere forums
      Product-specific forums where you can get answers to your technical questions and share your expertise with other WebSphere users.
    • WebSphere on-demand demos
      Download and watch these self-running demos, and learn how WebSphere products and technologies can help your company respond to the rapidly changing and increasingly complex business environment.
    • developerWorks WebSphere weekly newsletter
      The developerWorks newsletter gives you the latest articles and information only on those topics that interest you. In addition to WebSphere, you can select from Java, Linux, Open source, Rational, SOA, Web services, and other topics. Subscribe now and design your custom mailing.
    • WebSphere-related books from IBM Press
      Convenient online ordering through Barnes & Noble.
    • WebSphere-related events
      Conferences, trade shows, Webcasts, and other events around the world of interest to WebSphere developers.
  • developerWorks resources
    • Trial downloads for IBM software products
      No-charge trial downloads for selected IBM® DB2®, Lotus®, Rational®, Tivoli®, and WebSphere® products.
    • developerWorks blogs
      Join a conversation with developerWorks users and authors, and IBM editors and developers.
    • developerWorks cloud computing resources
      Access the IBM or Amazon EC2 cloud, test an IBM cloud computing product in a sandbox, see demos of cloud computing products and services, read cloud articles, and access other cloud resources.
    • developerWorks tech briefings
      Free technical sessions by IBM experts to accelerate your learning curve and help you succeed in your most challenging software projects. Sessions range from one-hour virtual briefings to half-day and full-day live sessions in cities worldwide.
    • developerWorks podcasts
      Listen to interesting and offbeat interviews and discussions with software innovators.
    • developerWorks on Twitter
      Check out recent Twitter messages and URLs.
    • IBM Education Assistant
      A collection of multimedia educational modules that will help you better understand IBM software products and use them more effectively to meet your business requirements.


Sign in or register to add and subscribe to comments.

ArticleTitle=Using Microsoft .NET in WebSphere Message Broker V8: Part 2: Integrating with Microsoft Word