Export (0) Print
Expand All
CLR Generics Versus C++ Templates
Copy Constructors, Assignment Operators, and More
Counting MDI Children, Browsing for Folders
Dialog Templates, RegexTest
Disabling Print Screen, Calling Derived Destructors, and More
Enum Declarations, Template Function Specialization
Form Validation with Regular Expressions in MFC
Generic Programming Under .NET
Generic Programming: Template Specialization
Hello, C++/CLI
Installing a Hook, Strings in Managed C++, and More
Layered Windows, Blending Images
Making Static Links Keyboard-Capable, Launching URLs from Your App
Persisting View State Update, Using Managed Extensions in a DLL
Power Your App with the Programming Model and Compiler Optimizations of Visual C++
Reflecting on Generic Types
Unreferenced Parameters, Adding Task Bar Commands, and More
Wrappers: Use Our ManWrap Library to Get the Best of .NET in Native C++ Code -- MSDN Magazine, April 2005
Expand Minimize

SOAP in the Middle Tier

 

Eric Jarvi
Microsoft Corporation

October 2001

Summary: This article describes a technique to add SOAP functionality to the middle tier and expose it to the presentation layer through SRF tags. This technique allows you to shield Web designers from the programming required to integrate Web services into their Web applications. (8 printed pages)

Download Srfsoap.exe.


Note   For this article, you should be familiar with C++, the ATL Server libraries, IIS, Microsoft® SQL Server™, and SOAP.

Contents

Introduction
Creating the News Feed Web Service
Accessing the Web Service with SRF Tags
A World of New Opportunities

Introduction

The n-tiered architecture approach to Web development has proven itself in enterprise environments. Naturally, the more data and functionality available through the middle tier, the richer the presentation layer can be. As more and more Web services become available, beefing up a middle tier can become simply a matter of linking in to Web services with SOAP.

Why Use ATL Server?

Active Template Library (ATL) Server SRF files provide a clean separation between a developer and a Web designer. This allows a developer simply to ship a dynamic link library (DLL) to the Web designer, along with a document describing the special tags to use. The Web designer can begin to use it immediately.

You may find this technique useful if any of the following apply to you:

  • Consumers of your Web service are Web designers with few programming skills.
  • Your consumers want to include your content and/or functionality in a way that lets them brand it as their own.
  • Your consumers have a presentation layer that consists of several different markup languages such as WML, HTML, XHTML, or customized XML. As long as the presentation layer text-based, you can easily modify the SRF pages to generate the output in the correct format.
  • You want the performance of an ISAPI DLL, or you need to control the way end-users access your Web service through SOAP.

A News Feed Example

In this article, I'll demonstrate an example of this technique with a "news feed" Web service. The process involves three distinct roles:

  • (Developer) Creating the news feed Web service.
  • (Developer) Creating an ATL Server combo DLL capable of rendering SRF files and accessing the news feed Web service. The replacement tags that are implemented in this step should be documented for the Web designer.
  • (Web Designer) Writing SRF pages by using HTML mixed with the replacement tags defined in the ATL Server combo DLL.

In this article, we will walk through the process starting with the creation of the news feed Web service. If you are new to ATL Server, you may want to get up to speed by first reading the introductory MSDN Magazine article ATL Server and Visual Studio .NET: Developing High-Performance Web Applications Gets Easier.

Creating the News Feed Web Service

This Web service will work in conjunction with SQL Server to store and retrieve news items.

Preparing the Database

First, we must create a database for storing the news items. I used the following steps:

  1. Install SQL Server 2000 Developer Edition—making sure you have applied SP1 for database components (for the security updates)—from http://www.microsoft.com/sql/downloads/2000/sp1.asp.
  2. Open the SQL Enterprise Manager.
  3. Under Databases, create a new database named "NewsCenter."
  4. Under Security, add a new login for the local IUSR_machinename account. Specify Windows Authentication, and set the default database to NewsCenter. Under Database Access tab, permit access to the NewsCenter database and permit the db_datawriter and db_datareader roles.
  5. Create a table called Articles using the SQL script NewsCenterDatabase.sql, which can be found in the NewsCenter project folder of the code accompanying this article.
  6. You should seed the database with at least five starter news items.
  7. Your database is now ready to go.

Building the Web Service

We are now ready to write a simple Web service layer on top of the database. Assuming the database and Web server are both on your local machine, you should be able to open NewsCenter.sln and rebuild the solution. This will build and deploy the NewsCenter Web service to IIS on your local machine.

The following steps were used to create the NewsCenter Web Service project:

  • Open Visual Studio® .NET and select File | New Project | C++ Project | ATL Server Web Service Project.
  • Name the project "NewsCenter" and click OK.
  • Accept the default configuration, and click Finish.
  • Create the struct ArticleStruct that will be passed through the SOAP methods.
  • Replace the HelloWorld method in the generated file in the attributed interface definition and the attributed request handler class with the following two methods: AddArticle and GetTopArticles.
  • Right-click on the project name and select Add Class | OLEDB Consumer class. Connect to the database and select the table you created. By selecting integrated auth with the IUSR account, you can avoid storing the connection string password in plaintext in the generated source code.
  • Write the code inside of AddArticle that takes the input of the SOAP method and then adds it to the database using the OLEDB Consumer class created earlier.
  • Write the code inside of GetTopArticles that will use the OLEDB Consumer class to query the database and fill up an array with the top five news items to send back through the SOAP method. You can also modify the SQL command in the .h file generated by the OLE DB Consumer class wizard so that the newest items are returned first, in this case: ORDER BY submissionDate DESC.
  • Build the solution. This will deploy the relevant files to IIS.
  • Open http://localhost/NewsCenter/NewsCenter.htm and make sure the WSDL is being returned properly.

You should now have a Web service layer capable of adding and retrieving items from the database.

Accessing the Web Service with SRF Tags

Begin With the End in Mind

Let's take a look at what the end-result will be for users of your DLL. The following is an example of the .SRF file that a Web designer might write to include a list of news articles in their Web page:

{{handler NewsReader.dll/NewsReader}}
<html>
<head><title>News</title></head>
<body>
<h1>The Latest News</h1>
{{GetLatestNewsItems}}
<table>
{{while NewsItemPresent}}
     <tr><td>
        <a href="{{NewsPrint(content)}}">{{NewsPrint(title)}}</a>
     </td></tr>
     {{NextNewsItem}}
{{endwhile}}
</table>
</body>
</html>

When IIS receives a request for this file, it calls into NewsReader.dll whenever one of the special replacement tags is reached. The resultant HTML generated from the above SRF file might look something like this:

<html>
<head><title>News</title></head>
<body>
<h1>The Latest News</h1>
<table>
     <tr><td><a href="http://link1">First news story</a></td></tr>
     <tr><td><a href="http://link2">Second news story</a></td></tr>
     <tr><td><a href="http://link3">Third news story</a></td></tr>
     <tr><td><a href="http://link4">Fourth news story</a></td></tr>
     <tr><td><a href="http://link5">Fifth news story</a></td></tr>
</table>
</body>
</html>

Creating the NewsReader DLL

First, it's important to explain a little ATL Server terminology. In ATL Server, two DLLs are normally involved—the "ISAPI DLL" and the "Application DLL." You rarely need to change anything in the ISAPI DLL; it has standard functionality for reading .SRF files and knowing which application DLL to use based on the {{handler}} tag used inside of the SRF file. Since multiple application DLLs can share the same ISAPI DLL, this often comes in handy.

There is an alternative, however, in which the ATL Server Project Wizard calls a "Combo DLL." This DLL combines ISAPI functionality with your custom application DLL functionality. I've chosen to use a combo DLL in this example. Our final goal is to make it as simple as possible for a Web designer to access a Web service by using SRF tags. With a combo DLL, the Web designer only has to keep track of one DLL.

The code accompanying this article contains the NewsReader project, which includes the code to access the Web service as well as a demonstration .SRF page.

The following steps were used to create the NewsReader Combo DLL project:

  • Open Visual Studio .NET and select File | New Project | ATL Server Project.
  • Name the project NewsReader, select OK, select Combo DLL and click Finish.
  • Document the tags that you want to make available. Based on the above example, we need to add the following tags: {{GetLatestNewsItems}}, {{NewsItemsPresent}}, {{NewsPrint(content|title)}}, and {{NextNewsItem}}.
  • Remove the HelloWorld tag and add your custom replacement tag methods to the project—for example, the GetLatestNewsItems tag.
  • Right-click on the Project and select Add Web Reference.
  • In the dialog that is presented, type in the URL to retrieve the WSDL, probably http://localhost/NewsCenter/NewsCenter.dll?Handler=GenNewsCenterWSDL. After this, you should see the XML of the WSDL displayed in the left-hand corner of the screen. When it is displayed, click OK.
  • A new .h file is added to the project containing a SOAP client proxy class. This class contains methods that you can use within your code as if it were the actual remote method itself. When you call this method, it performs the SOAP processing for you behind the scenes, marshalling data and filling the appropriate data structures.
  • Add this generated .h file to stdafx.h, add the namespace defined in this file (you can find this by opening the .h file and looking for the namespace)—and then add an instance of the Web service proxy class where needed.
  • Add code inside of the GetLatestNewsItems method to open the proxy class and call the remote method on the Web service. For the purposes of this demonstration, this will only occur once per page load and will fill in an array that is maintained only for the duration of the page view. This also initializes an internal counter. Note that by doing this you can decrease the risk of Web designers inadvertently performing a denial of service (DoS) attack on your Web service, since your server is only contacted once per page view. Of course, this represents only one way of doing it. You have control of what happens behind the SRF tags, so it's wise to make sure that users can't use the SRF tags in a way that might cause performance degradation.
  • Add code inside of NextItem to move the index forward to the next item in the array of structs.
  • Add code inside of NewsPrint to take the parameter, and print either the "contents" URL or the "title" text that is in the struct. Sending the string out through the default m_HttpResponse stream accomplishes this.
  • Build the project. This will also deploy the relevant files to the IIS server at the location: http://localhost/NewsReader/NewsReader.srf.
  • You may want to create some test .srf pages to test the replacement tag methods you created. Note that debugging .SRF pages can often be tricky. If you get HTTP 500 errors, it is helpful to set a breakpoint at each tag method in the replacement handler and debug the application until you hit the breakpoint. If you don't hit a breakpoint, you may have misspelled a tag or included a tag that doesn't exist in the handler. In this case, another strategy is to minimize the number of tags you are calling from the SRF page and start adding tags until you see the HTTP 500 error again.

At this point, you should have a working .SRF page that calls your DLL, which calls the Web Service, and returns the appropriate data. You are successfully using SOAP in the middle tier for content delivery.

For your customers to use the news reader inside of their application, they need only to do the following:

  • Install that DLL on their Web server.
  • Associate the .SRF file extension in IIS Administrative console with the combo DLL.
  • Start writing SRF pages (you can provide your tests as a template).

Creating the NewsWriter DLL

So far, we have seen simple content delivery that uses SRF pages to output fresh data to the user. The circle is complete, however, when you can also accept input.

To accomplish this, we will create a new combo DLL. This NewsWriter DLL will be similar to the NewsReader DLL, but includes additional functionality for accepting user input. It will also have built-in SOAP client support for accessing the NewsCenter Web service.

This will be a standard SRF page that posts back to itself. If the input is not valid, it will continue to prompt the user for information until it is valid. Since this input needs to be safe for everyone consuming the news feed, it is essential to check the input for validity and protect against threats such as cross-site scripting. Once the input is confirmed to be valid, this DLL will use the built-in SOAP client to add the input into the database of news items.

You will notice additional JScript code inside of the SRF demonstrated below. This adds client-side validation of the input variables to the page. This saves a round-trip to the server when the user has scripting capability turned on in their browser settings. If the user has scripting turned off, or if a hacker tries to sends raw data, the server will perform the validation as well. If using script code is too confusing for your Web designers, you may want to hide all of it behind a replacement tag to make it easier for them to use, or just keep all validation on the server.

Here is an example of what a SRF page for accepting input might look like:

{{handler NewsWriter.dll/Writer}}
<html>
<body>
{{if ValidInput}}
<h1>Thank You</h1>
<p>Thank you for submitting your news article.</p>
{{else}}
<script language="JScript">
function validate(submission)
{
   var error_message = "";
   for (i=0; i<submission.elements.length; i++)
   {
      {{RegexTests}}
   }
   if (error_message=="")
   {
      return true;
   }
   else
   {
      alert("Please correct the following items:\n\n" + error_message);
      return false;
   }
} //validate
</script>

<h1>Add Article</h1>
<p>Please enter the article information here:</p>
{{ShowErrors}}
<form action="NewsWriter.srf"
      onSubmit="return validate(this)"
      method="post">
<table border="0" cellpadding="0" cellspacing="0">
      <tr><td>Title </td><td>{{Input(NewsTitle)}}</td></tr>
      <tr><td>URL </td><td>{{Input(NewsURL)}}</td></tr>
      <tr><td colspan="2"><input type="submit" value="Submit"></td></tr>
      </table>
</form>
{{endif}} 
</body>
</html>

To install the NewsWriter project, open the NewsWriter.sln file accompanying this article, and rebuild the solution. This will also deploy the appropriate files to IIS. The steps for creating the NewsWriter combo DLL are similar to those used earlier.

The following steps were used to create the NewsWriter project:

  • Open Visual Studio .NET and select File | New Project | ATL Server Project.
  • Name the project NewsWriter, select OK, select Combo DLL, and click Finish.
  • Document the tags that you want to make available through SRF.
  • Remove the HelloWorld tag and add your custom replacement tag methods.
  • Add code to ValidateAndExchange, which validates the input against the regular expressions you define for allowable URL and text patterns. Also, add the ValidInput and RegexTests replacement tag methods used from the SRF page.
  • Right-click on the Project, and then select Add Web Reference.
  • Similar to the NewsReader project, type in the URL to retrieve the WSDL of the NewsCenter service. After this, you should see the XML of the WSDL displayed in the left hand corner of the screen. When it is displayed, click OK.
  • The SOAP client proxy class is generated, as it was in the NewsReader project.
  • Add the generated .h file to stdafx.h, and add the namespace to your request handler code.
  • Add code that will call AddItem and send the input to the Web service once it has been validated.
  • Build the project. This will also deploy the relevant files to the IIS server at the location: http://localhost/NewsWriter/NewsWriter.srf.

You should now be able to use the NewsWriter SRF layer successfully to add new items to the NewsCenter Web service. You should be able to use the NewsReader SRF page from earlier to view the items you just added.

A World of New Opportunities

Once you can process input and output through the SRF layer, any middle tier business logic that can be put behind a SOAP Web service is potentially available.

This presents a world of new opportunities. Using this technique, you can write a SRF layer on top of any of your SOAP Web services, or you can write a SRF layer that aggregates multiple Web services. The remote Web services don't even have to be your own, as long as they are talking SOAP.

Show:
© 2014 Microsoft