Skip to main content

By clicking Submit, you agree to the developerWorks terms of use.

The first time you sign into developerWorks, a profile is created for you. Select information in your developerWorks profile is displayed to the public, but you may edit the information at any time. Your first name, last name (unless you choose to hide them), and display name will accompany the content that you post.

All information submitted is secure.

  • Close [x]

The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerworks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

By clicking Submit, you agree to the developerWorks terms of use.

All information submitted is secure.

  • Close [x]

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

Ben Thompson (bthomps@uk.ibm.com), Consulting IT Specialist, IBM
Author photo
Ben Thompson is a Consulting IT Specialist working on the WebSphere Message Broker development team at the IBM Hursley Software Lab in the UK. He is currently working on the design and implementation of .NET support in Message Broker. In the past, he has worked for IBM Software Services for WebSphere designing and implementing WebSphere solutions for IBM customers worldwide. You can contact Ben at bthomps@uk.ibm.com.
(An IBM developerWorks Contributing Author)
Matthew Golby-Kirk (mgk@uk.ibm.com), Software Developer, IBM
Matthew Golby-Kirk photo
Matthew Golby-Kirk is a software developer working on the WebSphere Message Broker development team at the IBM Hursley Software Lab in the UK. He works on the design and implementation of the HTTP and Web services support, along with the ESQL language run time in WebSphere Message Broker. You can contact Matthew at mgk@uk.ibm.com.

Summary:  This series of four tutorials demonstrates the new support for Microsoft .NET in WebSphere Message Broker V8. Part 2 describes integration with Microsoft Word. Readers should be familiar with either Microsoft .NET or WebSphere Message Broker but need not be familiar with both.

View more content in this series

Date:  18 Jan 2012
Level:  Intermediate

Comments:  

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
  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

    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
  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
  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
  6. The Solution Explorer should now show that the assembly references have been added successfully:

    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

    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

    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);
              run.Append(text);
              paragraph. Append(run);
              body.Append(paragraph);
         }
    

    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"
                   }
              ));
              tableRow.Append(tableCell);
         }
    

    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 = 
              WordprocessingDocument.Create(srcFile,WordprocessingDocumentType.Document);
         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");
         table.Append(HeaderRow);
    

  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 = 
              inputMessage.RootElement["XMLNSC"]["SaleEnvelope"]["SaleList"]["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"]);
              table.Append(NewRow);
         }
    body.Append(table);
    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.");
    DocPart.Document.Append(body);
    DocPart.Document.Save();
    wpDoc.Close();
    

  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 = "http://www.acmeorders.com/Order";
         string soapNs = "http://schemas.xmlsoap.org/soap/envelope/";
         NBElement ctx = soap.CreateLastChild("Context").CreateLastChild("Namespace");
         ctx.CreateLastChild(SOAP.DoubleNamespaceDeclaration, 
              "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

    Opening the Output window in Microsoft Visual Studio

    If the Output window is not visible, and you are using Microsoft Visual Studio Professional Edition, then you can open it by selecting Debug => Windows => Output. If the Output window is not visible, and you are using Microsoft Visual Studio Express Edition, open it by selecting View => Output.

  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

    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\
    MSWordDotNetProject\bin\Debug\MSWordDotNetProject.dll
    

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.

4 of 9 | Previous | Next

Comments



Help: Update or add to My dW interests

What's this?

This little timesaver lets you update your My developerWorks profile with just one click! The general subject of this content (AIX and UNIX, Information Management, Lotus, Rational, Tivoli, WebSphere, Java, Linux, Open source, SOA and Web services, Web development, or XML) will be added to the interests section of your profile, if it's not there already. You only need to be logged in to My developerWorks.

And what's the point of adding your interests to your profile? That's how you find other users with the same interests as yours, and see what they're reading and contributing to the community. Your interests also help us recommend relevant developerWorks content to you.

View your My developerWorks profile

Return from help

Help: Remove from My dW interests

What's this?

Removing this interest does not alter your profile, but rather removes this piece of content from a list of all content for which you've indicated interest. In a future enhancement to My developerWorks, you'll be able to see a record of that content.

View your My developerWorks profile

Return from help

static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=WebSphere
ArticleID=785520
TutorialTitle=Using Microsoft .NET in WebSphere Message Broker V8: Part 2: Integrating with Microsoft Word
publish-date=01182012
author1-email=bthomps@uk.ibm.com
author1-email-cc=
author2-email=mgk@uk.ibm.com
author2-email-cc=

Tags

Help
Use the search field to find all types of content in My developerWorks with that tag.

Use the slider bar to see more or fewer tags.

Popular tags shows the top tags for this particular content zone (for example, Java technology, Linux, WebSphere).

My tags shows your tags for this particular content zone (for example, Java technology, Linux, WebSphere).

Use the search field to find all types of content in My developerWorks with that tag. Popular tags shows the top tags for this particular content zone (for example, Java technology, Linux, WebSphere). My tags shows your tags for this particular content zone (for example, Java technology, Linux, WebSphere).