Tutorial: Creating and Accessing WCF COBOL Services

Shows how to create and access WCF services in COBOL.

Overview and Demonstration Applications

The tutorial is based on the BookWrapper demonstrations supplied with this COBOL development system. The BookWrapper is an intermediary program which maps .NET data types onto COBOL data types. It then calls the existing COBOL program, book.cbl, to perform the business logic.

In this tutorial you expose the functionality of the BookWrapper program as a WCF service and use a console application as a client to communicate with it.

A more sophisticated version of the demonstration shown here is supplied with the product samples. To check the code, start Visual COBOL Samples Browser, select Show managed only from the drop-down list at the top and open the WCF Book Service and Client demonstration in the WCF category.

Prerequisites

To complete this tutorial, you need:

  • An advanced edition of Visual Studio such as Professional, Enterprise or Community Edition.
  • The WCF Tools feature installed in Enterprise Developer. If this feature is missing, see To install missing features from the IDE for installation instructions.
  • To build the BookWrapper and LegacyBook projects that are part of the WinBook sample. To do this:
    1. Start the Visual COBOL Samples Browser. If you need instructions, see To start the Samples Browser.
    2. Click Windows Forms in the left pane and then Win Book.
    3. Click Open sample in Visual Studio.
    4. In Solution Explorer, right-click WinBook solution and choose Build Solution.

      The build creates two binaries, BookWrapper.dll and LegacyBook.dll, in the bin\Debug subfolder of the WinBook solution.

Outline

In order to create and configure a WCF service and then use a client to access it, you need to:

  1. Create the WCF service.
  2. Define a service contract.
  3. Implement the service.
  4. Host and test the service.
  5. Create and configure a COBOL client application.
  6. Run the client and access the service.

Create a WCF Service Project

To start you need to create a solution to hold your WCF service and the client application:

  1. Start Enterprise Developer with administrative rights. This is to prevent issues for users without administrator privileges for the namespace the WCF service uses. If you need instructions, see To start Enterprise Developer as an administrator.
  2. In Visual Studio, click File > New > Project.
  3. In the New Project dialog box, expand Installed > COBOL.
  4. Click the Web category.
  5. Select WCF Service Library (.NET Framework).
  6. Complete the remaining fields as follows:
    Name WCFBook
    Location Full path to any local directory; for example, c:\VSTutorials
    Solution Name WCFBook
    Framework Choose the appropriate .NET Framework version from the drop-down list.
  7. If the location you specified doesn't exist, check Create directory for solution.
  8. Click OK.

Add the BookWrapper and the LegacyBook Demonstrations to the Solution

You need to add the program that includes the functionality to expose as a service to your solution. To do this:

  1. In Solution Explorer, right-click your solution and select Add > Existing Project.
  2. Navigate to the Forms\BookWrapper subfolder in the Enterprise Developer samples.
  3. Select BookWrapper.cblproj and click Open.
  4. In a similar way, add the LegacyBook demonstration which is installed in the Forms\LegacyBook subfolder to your solution.

Add the BookWrapper and the LegacyBook projects as references in the WCFBook Project

To enable your service to access the functionality in the BookWrapper and the LegacyBook projects, you must add them as project references to the WCFBook project:

  1. In Solution Explorer, right-click the References folder in your WCFBook project.
  2. Select Add Reference.
  3. Expand Projects in the left-hand pane and click Solution.
  4. Check the BookWrapper and the LegacyBook projects and click OK.

Define the WCF Service Contract and Create the Service

  1. In Solution Explorer to rename the following files in the WCFBook project:
    • Service1.cbl to BookService.cbl
    • IService1.cbl to IBookService.cbl

    In order to rename the files:

    1. Right-click the file in Solution Explorer and click Rename.

      This starts the Suggested rename dialog box offering to rename any references to the file either in the current project or the entire solution.

    2. Click No to only rename the file name.
  2. Paste the code below in the IBookService.cbl file, overwriting the existing content. This defines the service and data contracts.
    • The methods that are marked with the System.ServiceModel.OperationContract() attribute define the operations from the BookWrapper program that are exposed through the service endpoints.
    • The WCFBookWrapper.Book class that is marked with the DataContract attribute exposes the data from the BookWrapper program.
           interface-id WCFBook.IBookService
                         attribute System.ServiceModel.ServiceContract().
             
           method-id GetData public
               attribute System.ServiceModel.OperationContract().
           procedure division using by value the-value as binary-long
                              returning return-value as string.
           end method.
    
           method-id GetDataUsingDataContract public
               attribute System.ServiceModel.OperationContract().
           procedure division using by value stockNumber as string
                              returning return-value as type WCFBookWrapper.Book.
           
           end method.
           
           method-id Read public attribute System.ServiceModel.OperationContract().
           procedure division using by value stockNumber as string returning theBook as type WCFBookWrapper.Book.
           end method.      
    
           end interface.
    
           class-id WCFBookWrapper.Book attribute DataContract().
           
           working-storage section.
           01 BookTitle string property as "Title" attribute DataMember().
    	   01 BookType string property as "Type" attribute DataMember().
    	   01 BookAuthor string property as "Author" attribute DataMember().
           01 BookStockno string property as "StockNumber" attribute DataMember().
           01 BookRetail decimal property as "RetailPrice" attribute DataMember().
           01 BookOnhand binary-long property as "NumberOnHand" attribute DataMember().
           01 BookSold binary-long property as "NumberSold" attribute DataMember().
           01 StockValue float-short property as "StockValue" attribute DataMember().
           
           method-id New.
           working-storage section.
           01 newBook type WCFBookWrapper.Book.
           procedure division using by value stdbook as type BookWrapper.Book.
               set BookTitle to stdbook::Title
               set BookType to stdbook::Type
               set BookAuthor to stdbook::Author
               set BookStockno to stdbook::StockNumber
               set BookRetail to stdbook::RetailPrice
               set BookOnhand to stdbook::NumberOnHand
               set BookSold to stdbook::NumberSold
               set StockValue to stdbook::StockValue
               goback.
           end method.
           
           end class.
  3. Paste the code below into the BookService.cbl file. This is the actual WCF service.
           class-id WCFBook.BookService 
                     implements type WCFBook.IBookService. 
                      
           working-storage section. 
     
           method-id GetData public. 
           procedure division using by value the-value as binary-long 
                              returning return-value as string. 
               set return-value to string::Format("You entered {0}" the-value) 
               goback. 
           end method. 
     
           method-id GetDataUsingDataContract public. 
           working-storage section. 
           01 book type BookWrapper.Book. 
           01 bookException type BookWrapper.BookException. 
           procedure division using by value stockNumber as string returning theBook as type WCFBookWrapper.Book.                
     
               try                          
                   set book to type BookWrapper.Book::Read(stockNumber) 
                   set theBook to new WCFBookWrapper.Book(book) 
               catch bookException 
                   raise new System.ServiceModel.FaultException(bookException::Message) 
               end-try 
               goback. 
           end method. 
            
           method-id Read public. 
           working-storage section. 
           01 book type BookWrapper.Book. 
           01 bookException type BookWrapper.BookException. 
           procedure division using by value stockNumber as string returning theBook as type WCFBookWrapper.Book.
     
               try 
                   set book to type BookWrapper.Book::Read(stockNumber) 
                   set theBook to new WCFBookWrapper.Book(book) 
               catch bookException 
                   raise new System.ServiceModel.FaultException(bookException::Message) 
               end-try 
               goback. 
           end method.       
     
           end class. 

Provide Access to the Legacy Code

Additionally, you need to configure your WCF service to call the BookWrapper code as follows:

  1. Right-click the App.config file in your WCF service project and select Open.
  2. Add the code below immediately after the opening <configuration> tag:
      <configSections>
        <!--The following code declares a section group for application configuration -->
        <sectionGroup name="MicroFocus.COBOL.Application">
          <section name="Switches" type="System.Configuration.NameValueSectionHandler" />
          <section name="Environment" type="System.Configuration.NameValueSectionHandler" />
        </sectionGroup>
        <!--The following code declares a section group for run-time configuration -->
        <sectionGroup name="MicroFocus.COBOL.Runtime">
          <section name="Tunables" type="System.Configuration.NameValueSectionHandler" />
          <section name="Switches" type="System.Configuration.NameValueSectionHandler" />
        </sectionGroup>
      </configSections>
      <MicroFocus.COBOL.Application>
        <Switches />
        <Environment>
          <add key="dd_bookfile" value="%Public%\Documents\Micro Focus\Enterprise Developer\Samples\BookData\bookfile.dat" />
        </Environment>
      </MicroFocus.COBOL.Application>
     
  3. Scroll down the file in the editor.

    Notice that there are a number of references to the default Service1 which were not renamed when you renamed the files. You need to rename these manually.

  4. Press CTRL+H and replace the string Service1 with BookService in the entire file.
  5. Save and close the App.config file.
  6. Build the WCFBook project.

Configure the service endpoints

Next, you need to configure the service endpoint details as follows:

  1. Right-click the App.config file in your WCF service project select Edit WCF Configuration.
  2. In the Microsoft Service Configuration Editor, expand WCFBook.BookService.
  3. Click Host.
    Note: The default base address of the service is localhost - Visual Studio hosts the service on your machine.
  4. Expand Endpoints and click on the first item in that group.

    This displays the general details of the endpoint - the address of the service, its binding and the service contract you want to expose - all known as the ABC of the endpoint. You need to configure the endpoint to use the IBookService contract you defined earlier.

  5. On the General tab, click on the row for Contract and then click .
  6. Navigate to the \bin\Debug subfolder in the WCFBook project directory.
  7. Double-click the WCFBook.dll file.
  8. Select the WCFBook.IBookService contract and click Open.
  9. Click the second item under Endpoints.

    This is the default endpoint that exposes metadata details about your service through the IMetaData Exchange contract. We are not going to change this contract.

  10. Click File > Save in the Configuration Editor and close the window.

Start and Test the Service

Visual Studio provides a built-in WCF Service Host application and a WCF Test Client application to help you test your service without your own client application. This is enabled by default on the WCF Options tab in the project's properties.

  1. In Solution Explorer, right-click the WCFBook project and select Set as StartUp Project.
  2. Click Debug > Start Without Debugging.

    Visual Studio hosts your service in the WCF Service Host and loads it in the WCF Test Client application. The test client displays the endpoint for your service and the operations that are exposed.

  3. Double-click the GetDataUsingDataContract() operation.

    This displays the operation details and enables you to test the operation with various parameters.

  4. In the Request pane, change the value for stockNumber from null to 1111 and press Enter.
  5. Click Invoke.

    This displays the details about record 1111 in the BookWrapper application in the Response pane.

  6. Test the Read operation with other stock numbers. The valid numbers are 1111, 2222 and 3333.
  7. Close the WCF Test Client application.

Create a WCF Client Application

In the real world, you use various client applications to access services through their available endpoints. As part of this tutorial, you will create a simple managed console application that accesses the BookWrapper application through the WCF service contract and reads the records that it contains:

  1. In Visual Studio, click File > New > Project.
  2. In the New Project dialog box, expand Installed > COBOL.
  3. Click the Windows Desktop category.
  4. Select Console Applcation (.NET Framework).
  5. Specify a name such as WCFClient and click OK.

Add the WCF Service as a Service Reference to the Client

Visual Studio provides an easy way to use a WCF service in a client application. The Add Service Reference functionality adds the service to the client project and generates a proxy for the client to use.

  1. Right-click the project for the client and choose Add > Service Reference.
  2. Click Discover in the Add Service Reference dialog to locate the WCF service.
  3. In the Namespace field, rename the namespace for the service to WCFBook.
  4. Click OK.

Edit the Client Application

You need to program your WCF client so that it uses the exposed operations of the WCF service reference. In this tutorial, the client uses the Read operation to access the information in the BookWrapper application and displays the record for a specified stock number.

  1. Edit Program1.cbl in the project for the client application.
  2. Replace the code in the COBOL program with the following:
           program-id. Program1 as "WCFClient.Program1".
    
           data division.
           working-storage section.
           01 stock-no              string.
           01 bookClient            type WCFBook.BookServiceClient.
           01 myBook                type WCFBook.Book.
           
           procedure division.
    
           invoke type System.Console::WriteLine("Enter a stock number and press Enter.")
    
           set stock-no to type System.Console::ReadLine() 
           set bookClient to new WCFBook.BookServiceClient
           set myBook to bookClient::Read(stock-no)
           
           invoke type System.Console::WriteLine(myBook::Title)
           invoke type System.Console::WriteLine(myBook::Type)
           invoke type System.Console::WriteLine(myBook::Author)
           invoke type System.Console::WriteLine(myBook::StockNumber)
           invoke type System.Console::WriteLine(myBook::RetailPrice)
           invoke type System.Console::WriteLine(myBook::NumberOnHand)
           invoke type System.Console::WriteLine(myBook::NumberSold)
           invoke type System.Console::WriteLine(myBook::StockValue)
           
           invoke type System.Console::WriteLine("Press Enter to exit.")
           invoke type System.Console::ReadLine()
           
           
                      goback.
               
           end program Program1.
  3. Click File > Save.
  4. Build the project for the client.

Configure the Client Endpoints

You need to configure the client so that it uses the WCF service endpoint and the service contract:

  1. Right-click the app.config file in the WCFClient project.
  2. Click Edit WCF Configuration.
  3. In the Configuration pane, expand Client and then Endpoints.
  4. Click WCHttpBinding_IBookService.
  5. In the Client Endpoint pane and on the General tab, click on the row for the Contract.
  6. Navigate to the \bin\Debug subfolder in the directory of the WCFBook project.
  7. Double-click WCFBook.dll.
  8. Select the WCFBook.IBookService contract and click Open.
  9. In the Microsoft Service Configuration Editor window, click File > Save.
  10. Close the configuration editor.
  11. Build the project.

Use the Client to Access the Service

  1. Set the WCFClient project as the StartUp project for the entire solution.
  2. Click Debug > Start Debugging.

    This hosts the service in the WCF Service Host and starts the client.

  3. In the console, enter a valid stock number and press Enter.

    The record for that stock number is displayed.