Web Services

Snoops

   

 
Migrating to .NET: A Pragmatic Path to Visual Basic .NET, Visual C++ .NET, and ASP.NET
By Dhananjay  Katre, Prashant  Halari, Narayana  Rao  Surapaneni, Manu  Gupta, Meghana  Deshpande

Table of Contents
Chapter 8.   New Features in Visual C++ .NET


A Web service is a piece of code that is Internet friendly and uses standardized XML for messaging. For Web services, SOAP is accepted as the industry standard for XML messaging. Web services allow access to software components through standard Web protocols such as HTTP and SMTP. Web services combine the best of both Distributed Component Architecture and the World Wide Web, extending distributed computing to broader ranges of client applications. Let's look at the Web services provided by Visual C++ .NET.

ATL Server

In the classical approach, a Web application comprises of ASP pages. Whenever an HTTP client requests the ASP page, the IIS loads the ASP.dll in the memory and passes the requested ASP page to the ASP.dll. The output generated by the ASP.dll is then rendered back to the HTTP client. Although we can do the session management with the objects like session and response, this approach lacks in performance as compared to C++ because of scripting language.

The other approach is to have the Internet Server API (ISAPI) DLL serve the HTTP client requests. These DLLs are loaded into memory by the IIS to serve page requests. Because the ISAPI DLL does not have intrinsic session management capabilities, the developer has to do some workaround to achieve this.

The ATL Server project in Visual C++ .NET addresses the drawbacks of the two preceding approaches. The architecture of the ATL Server application is given in Figure 8-1. The ATL Server application is based upon the new file format called Server Response File (SRF). The SRF is a text file containing the HTML and the special tags, which are replaced by the Web application while serving the HTML contents to the HTTP client. The sample SRF file has the following format:

Figure 8-1. ATL Server architecture.

graphics/08fig01.gif

 graphics/icon01.gif {{handler <atlserversample.dll}}  <HTML>  <BODY>  {{Test}}  </BODY>  </HTML> 

The double braces ({{}}) are the placeholders that will be replaced by the contents at the runtime by the Web application DLL. The HTTP client requests the Web server for a given file, such as http://myserver/test.srf . The IIS loads the ISAPI DLL associated with the Web application DLL specified in the handler tag of the requested SRF file. The ISAPI DLL checks whether the required application is loaded in the cache or not. If the application DLL doesn't exist in the cache, it loads it. The ISAPI DLL maintains a thread pool to serve the request. The given request is queued until it gets a free thread. Once it does so, the request is passed to the Web application DLL that contains the request handler classes derived from the CRequestHandlerT . These classes contain the code for the tag replacement. The CRequestHandlerT class contains the member variables to access the form variables , cookies, requeststream, and so on.

Let's have a look at the a sample Web application:

 graphics/icon01.gif //atlserversample.dll  [request_handler ("default")]  class CsampleHandler  {  public:  [tag_name ("Test")]  DWORD CodeForTest (IWriteStream* pIWStm)  {      // Code for the replacement of SRF Tag  } 

The ATL Server project provides the framework for this functionality, which reduces the learning curve associated with the ATL. The ATL Server Framework provides various ATL classes, such as CStencil , CrequestHandlerT , and ChtmlTagReplacer , to help the programmer build high-performance Web applications that have features such as session management, cookie management, and so on. The ATL Server also provides classes to wrap a crypto-API to perform secure processing, Web proxies, and remote management facility.

ATL Server Web Services

The ATL Server architecture is extended to handle the XML-based Web services request in an efficient manner. By using SOAP/ XML, the ATL Server Web services can be easily be published and can be located by the .Disco (Discovery) files. The architecture of ATL Server Web services is shown in Figure 8-2.

Figure 8-2. Soap architecture.

graphics/08fig02.gif

The core architecture of the ATL Server Web services is similar to the ATL Server. The main difference is that we have extended the HTTP request handler classes to support the SOAP interface. The Web application DLL will have the following request handler class:

 graphics/icon01.gif //atlwebservice.dll  __interface IATLWebService  {     [id(1) HRESULT GetResult([in]long lCustID,[out,retval] char  * pcCustomerName)]  }  [request_handler (name="default", sdl="SampleATLWebSer- vice"),soap_handler(name="ATLWebService",namespace="urn:ATL- WebService",protocol="soap"]  class CATLWebService  public: IATLWebService  {      HTTP_CODE InitializeHandler(AtlServerRequest *pRequest- Info, IServiceProvider *pProvider)  {  if (HTTP_SUCCESS != CSoapHandler <CATLWebService> ::  InitializeHandler(pRequestInfo, pProvider))            return HTTP_FAIL;  return HTTP_SUCCESS;  }  [soap_method]  HRESULT GetResult(long lCustID, char * pcCustomerName)  {      // Custom Code      return S_OK;  } 

Here the IATLWebService is the interface exposed by the Web service. The HTTP client can call any exposed method of this interface. In the preceding code snippet, the soap_handler will result in the following method calls: DispatchSoapCall , ParseSoapHeaders , and __AtlGetSDL . These methods take care of handling the SOAP messages, calling of the internally mapped methods , and wrapping the return value of the method to the SOAP response.

The CSoapHandler<> class in atlsoap.h handles all SOAP requests through HTTP. This class serves as the base class whenever the soap_handler attribute is specified. Besides this class, the ATL library provides the various other classes for the SOAP such as CSDLGenerator , CSoapHandler , CSoapMSXMLINETClient , CSoapRootHandler , CSoapSocketClientT , and CSoapWiniNETClient .

Managed C++ Web Services

The Managed C++ Web services project template provides the plumbing work required for building a Web service.

ENTRY POINT FOR THE WEB SERVICE

An asmx file provides the required entry point. To the Web service clients , this asmx file is the entry point to a Web service. You need to put this in a virtual directory, in the Web server, that has the execute scripts permission turned on. The Managed C++ Web service Framework performs this task for you.

If you open an asmx file, you will find the following line: <%@WebService Class = <namespace>.Class1 %> . This indicates to the Web server that the <namespace>.Class1 is a Web service.

HELPER CLASSES FOR A WEB SERVICE

This section is more about .NET-specific feature than those in Visual C++ .NET; .NET Framework provides different namespaces that help you implement Web services. The different Web service related namespaces and their brief description follow:

  1. System.Web. Contains classes and interfaces that enable browser/ server communication. This namespace contains classes for managing HTTP output to the client (HttpResponse) and reading HTTP requests (HttpRequest). Additional classes provide facilities for server-side utilities and processes, cookie manipulation, file transfer, exception information, and output cache control.

  2. System.Web.UI. Contains classes for creating Web Form pages, including the Page class and other standard classes used to create Web user interfaces.

  3. System.Web.UI.HtmlControls. Contains classes for HTML-specific controls that can be added to Web Forms to create Web user interfaces.

  4. System.Web.UI.WebControls. Contains classes for creating ASP.NET Web server controls. When added to a Web Form, these controls render browser-specific HTML and script to create a device-independent Web user interface.

  5. System.Web.Services. Contains classes that enable you to build and use XML Web services, which are programmable entities residing on a Web server and exposed via standard Internet protocols.

MAKING A SERVICE AVAILABLE TO THE REMOTE CLIENT

Derive the class that you want to expose as a Web service from the WebService class so that it inherits the basic Web services functionality. When you create a Web service through the Managed C++ Web service, a project template implements this behavior.

By specifying the WebServiceAttribute attribute to the exposed class, we can specify a different name for a Web service than that of the namespace and the class. Beside this, we can specify the other properties such as EnableSession and TransactionOption . The transaction management with a Web service is explained in the next chapter. Specifying the WebMethod attribute to the public method makes this method available to the remote client.

After creating a Web service, you can provide the supporting files to help in the discovery of a service. The project template does this by creating the vsdisco file. This dynamic discovery file enables all Web services underneath a specific URL on your Web site to be listed automatically. The clients to the Web services need to know how to communicate through HTTP and understand the Web Services Description Language (WSDL) to communicate with the service. We can also develop Web services in any language and on any platform as long as we adhere to the specification of WSDL.

SHARED MFC CLASSES

MFC and ATL are the pillars of the Visual C++ programming. Because they provide common functionality wrapped in the various classes, the developer can focus on business needs rather than the technical aspects of the implementation. The ATL library is lightweight in terms of load time and memory footprint as compared to the MFC library. To use even a single helper class such as CString from the MFC library, we have to include the MFC library during the compile time. This makes the whole application bulky. To overcome this, Visual C++ .NET has introduced the concept of shared MFC classes. In MFC 7.0 some frequently used classes that are not derived from CObject are made shared classes. This means we can use these shared MFC classes in our ATL application without MFC dependency. Now the developer can have the ease of using MFC classes without having any MFC overhead, which will help to keep the application light. A few of the shared classes are CString , CPoint , CRect , CSize , and CImage .

One of the most frequently used MFC classes is Cstring , which has been completely rewritten based on the template class CStringT<> . This helps support different types of character types ( char, whar_t, TCHAR , etc.). Because CString is now a template-based class, a specialization for each character type can be created. Further, a new shared class is added that allows users to define the amount of storage. CFixedStringT<> is also a template class and is very efficient because it reduces a lot of heap-based allocations . The newly added CImage class is also a shared class and provides much needed multiple-image format support.

GDI+

GDI+ replaces GDI, the graphic device interface associated with the previous MFC version. GDI+ is a set of conventional C APIs that are encapsulated and exposed in the managed classes. You can use GDI+ to draw two-dimensional graphics, high-clarity images, and formatted text.

GDI+ expands on the features of GDI by providing a host of new capabilities. Some of the new features provided by GDI+ are gradient brushes (linear gradient and path gradient), cardinal splines, independent path objects, transformations (translation, rotation, scaling, etc.), the matrix object, scalable regions , and alpha blending (pixel-level blending). One of most important new features is multiple-image format support. Now GDI+ supports BMP, JIF, JPEG, EXIF, PNG, TIFF, ICON, EMF, and WMF image formats. Using the shared MFC class CImage, GDI+ can load and save the images of these types.

GDI+ uses a different programming model than GDI does. In GDI+ we don't have to use handle or device context. Instead a graphics object is used. The graphics class provides the functions required to perform the required task. Actually, the graphics object is a .NET encapsulation of the device context.

ATL CONTAINER CLASSES

ATL 7.0 is now equipped new container classes. The reason for having ATL container classes is to incorporate even those types that are not completely compatible with the primitive datatypes (e.g., Smart pointers). The existing container classes of MFC and STL do not support these types. ATL collection classes are divided into three categories:

  • Small collection classes. This category includes CSimpleArray and CSimpleMap classes. These classes are used by ATL internally, and you should not use these classes directly.

  • General-purpose collection classes. This category includes CAtlArray , CAtlList , CAtlMap , CRBMap , and CRBMultiMap classes. These classes can be used to contain special types such as smart pointers with the help of trait classes. Trait classes define the behavior of the elements (copying, transferring, comparing, hashing, etc.). A number of trait classes are defined for the commonly used trait type. The following example will show how to use the trait classes with ATL classes:

     CAtlArray < CString, CStringElementTraits<CString>>; 
  • Specialized collection classes. Specialized classes are provided for memory pointers and interface pointers. They include CAutoPtrArray , CAutoPtrList , CComUnkArray , CHeapPtrList , CInterfaceArray , and CInterfaceList classes.

TYPE-SAFE MESSAGE MAPS

In Visual C++ 7.0 message maps are made more type safe. This is done by having a strict type checking of the return type and parameters of the handler function. Whenever we are migrating some code from an older version to Visual C++ 7.0 message maps, if not implemented correctly, we are most likely to break the code. For example, suppose we have a handler for ON_MESSAGE event, afx_msg LRESULT OnMyMessage(WPARAM f_wParam, LPARAM f_lParam ), which is implemented as

 graphics/icon01.gif LRESULT CMyClass::OnMyMessage(WPARAM f_wParam, LPARAM  f_lParam)  {      // Implementation details  } 

The previous versions of compilers do not check for the return type or function parameter. So you could write statements like

 afx_msg void OnMyMessage();  afx_msg LRESULT OnMyMessage(WPARAM f_wParam); 

This code will compile, but the application will crash at runtime.

Visual C++ 7.0 enforces stricter type checking, so if you compile the preceding code, the compiler will throw error C2440. This will saves a lot of testing and debugging efforts.

THREAD POOLS

Thread pools are instrumental in creating more efficient multithreaded applications. They are extremely useful in high-performance server applications where you want maximum concurrency and minimum context switching overhead. This is a pool of worker threads that can be used to post work items, process asynchronous I/O, wait on behalf of other threads, and process timers. In a multithreaded application a thread spends a chunk of its lifetime in sleep state waiting for an event. The thread pool provides the worker thread that takes care of this factor. The default number of threads created is 25. This number can be customized. Generally, the optimal number of concurrent threads is a multiple of the number of processors on your server. Each thread created in the thread pool has a default stack size , runs at the default priority, and is in the multithreaded apartment. A thread pool can be created using the ThreadPool class provided by the .NET Framework. There can be only one thread pool object for a given application. The ATL 7.0 also provides the CThreadPool class, based on the Windows NT I/O completion port.

PERFORMANCE COUNTERS

Performance counters are the mechanism through which Windows collects the performance data. Performance counters play an important role in monitoring the performance of the running application by providing the runtime operating information. Windows has a fixed number of performance counters, with each counter addressed to some specific area of system functionality. In .NET you can connect to the performance counters using the Performance-Counter component or define your own custom performance counters. To facilitate this, a new set of classes, macros, and attributes are added in ATL Server. These are present in Atlperf.h. The ATL provides you the three classes to make your life easy: CPerfMon , CperfObject , and Cperflock .

To monitor the performance of your application, you will have to define three entities in your application as depicted in Figure 8-3. In the figure, the performance object manager is on the top in the hierarchy, which exposes your application's performance object and performance counters. This object will usually be unique to your application. Derive your monitor class from CperfMon class. Visual C++. NET gives you a performance monitor object manager wizard, which inserts the performance monitor object in the project. It can also add a sample performance monitor for you. This wizard is invoked when you try to add a new class to your project and select class type ATL Performance Monitor Object Manager. But you can invoke this wizard for ATL DLLs only.

Figure 8-3. Performance Counters.

graphics/08fig03.gif

Now we are ready to add and implement the performance counters. You can use the ATL Performance Monitor Control Wizard. Through this wizard you can specify the detail level (novice, advanced, expert, or wizard), variable type (ULONG, ULONGLONG), counter type, and so on. Whenever you are dealing with the unattributed code, you have to specify a counter map, and each map should be added to this map.

Now that we have implemented the performance counters, you can directly access them using the performance objects as its data members .

SECURITY CLASSES

ATL 7.0 has now a set of security classes. These classes are wrapper classes for common Win32 security classes and objects. The different classes introduced under this category provide wrappers for access tokens and ACL (access-control list), DACL (discretionary access-control list), SACL (system access-control list), SECURITY_ATTRIBUTES , SECURITY_DESCRIPTOR , SID (security identifier), TOKEN_GROUPS, and TOKEN_PRIVILEGES structures.


Snoops

   
Top


Migrating to. NET. A Pragmatic Path to Visual Basic. NET, Visual C++. NET, and ASP. NET
Migrating to. NET. A Pragmatic Path to Visual Basic. NET, Visual C++. NET, and ASP. NET
ISBN: 131009621
EAN: N/A
Year: 2001
Pages: 149

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net