Sunday, August 24, 2008

Reusability In COM-II (Aggregation)

One way to reuse a component within another component is using containment. Another way to do so is using aggregation. In containment the outer component makes use of the inner component, but does not directly expose the inner component to its clients. The outer component can choose to use the inner component to implement some of its functionality. If the outer component decides to implement one or more of the interfaces of the inner component it must provide a wrapper for every method in the exposed interfaces. The method wrappers can simply call the inner component’s methods directly, or they can perform additional tasks such as validating parameters, recording usage, or otherwise extending the inner component’s interface.

Sometimes, it’s more convenient to expose the interfaces of the inner object directly, without writing a collection of wrappers. This is aggregation. A client creates the outer object, and when it asks QueryInterface( ) for an interface supported by the inner object, it gets passed a pointer to the inner object’s interface. When we use containment or aggregation the client does not know that there are actually two separate components acting in unison. We may as well have more than two objects. The outer component can aggregate several different components. Similarly, the inner component can aggregate another component into itself.

Aggregation has one distinct advantage over containment: it requires much less knowledge of the inner component on the part of the person implementing the outer component. Also, bypassing the wrapper layer makes the component that bit more efficient. The disadvantages of aggregation are that the inner (aggregated) object must be specially written so that it can be aggregated, and that the inner object can only be implemented in a DLL that is loaded directly into the same apartment as the outer object. There is no cross-apartment, cross-process or cross-machine aggregation.

Let us now understand aggregation with the help of some concrete example. Suppose we have a component that knows how to swap mouse buttons and set the time interval between two clicks of the mouse button. We can develop another component which uses this existing component and additionally also manage mouse trails. The existing component becomes the inner component. Given below is the procedure for building these components and a client that accesses the functionality of both the components.

Creating The Inner Component

The process of creating components in ATL consists of three steps:

(a) Creating Module:

To create a module the Developer Studio provides an ATL COM AppWizard. Carry out the following steps:

  • Select ‘New’ from the ‘File’ menu.

  • Select ‘ATL COM AppWizard’ as the project. Type ‘Inner’ as the project name and click ‘OK’ to continue.

  • Select type of module as ‘Dynamic Link Library’, click ‘Finish’.

(b) Adding Component To The Module

To add component to the module we can use ‘ATL Object Wizard’. Carry out the following steps for adding a component using this wizard:

  • Select ‘Insert | New ATL Object’ menu item. This would display the ‘ATL Object Wizard’

  • Select ‘Simple Object’ from the various object categories and click on ‘Next’.

  • A ‘ATL Object Wizard Properties’ dialog is displayed.

  • Enter the ‘Short Name’ as ‘Mouse’. As soon as you do this all other edit controls would be filled automatically. Click on OK.

(c) Adding Methods To The Component

The component that has been added does not contain any functionality. To provide functionality we should add two methods named SwapButton( ) and SetDoubleclicktime( ) as indicated below.

  • Switch to class view tab. Select the interface ‘IMouse’ and click the right mouse button. From the menu that pops up, select ‘Add Method’.

  • In the ‘Add Method to Interface’ dialog specify the method name as ‘SwapButton’ and leave the parameters edit control empty.

  • Click on ‘OK’.

  • Adding the SwapButton( ) method creates a function definition in ‘Mouse.cpp’ as shown below:

STDMETHODIMP CMouse::SwapButton( )
{

// TODO: Add your implementation code here

return S_OK ;

}

  • Add the following code to the SwapButton( ) method by double clicking on this method from the Class view tab:

mousestatus = !mousestatus ;

SystemParametersInfo ( SPI_SETMOUSEBUTTONSWAP, mousestatus,NULL,NULL ) ;

  • From the class view tab add a private variable mousestatus of type BOOL to the CMouse class. Initialize this variable to FALSE in the constructor of CMouse class.

  • On similar lines add another method called SetDoubleclicktime( ). Its code is given below:

STDMETHODIMP CMouse::SetDoubleclicktime ( long time )

{

AFX_MANAGE_STATE(AfxGetStaticModuleState( ) )

// TODO: Add your implementation code here

SystemParametersInfo ( SPI_SETDOUBLECLICKTIME, time, NULL, NULL ) ;

return S_OK ;

}

Creating The Outer Component

The procedure for creating the outer component is same as that for creating the inner component. First create a module called ‘Outer’. Insert a component called ‘MouseTrails’ in it and then add a method called SetMouseTrails( ) to it.

This methods is shown below:

STDMETHODIMP CMouseTrails::SetMouseTrails ( int trails )

{

AFX_MANAGE_STATE ( AfxGetStaticModuleState( ) )

// TODO: Add your implementation code here

SystemParametersInfo ( SPI_SETMOUSETRAILS, trails, NULL, NULL ) ;

return S_OK ;

}

  • Include the file ‘inner.h’ in ‘mousetrail.h’ as shown below:

# include "..\inner\inner.h"

  • Add a private member variable called m_agg in the outer class from the class view tab:

CComPtr m_agg ;

This variable would be used to hold the IUnknown pointer that we are going to get back from the aggregate when we create it.

  • Add the following macro to the file ‘MouseTrails.h’

DECLARE_GET_CONTROLLING_UNKNOWN( )

  • Add the following function to the ‘MouseTrails.h’ file.

HRESULT FinalConstruct( )

{

HRESULT hr ;

CLSID clsid ;

CoInitialize ( NULL ) ;

hr = CLSIDFromProgID ( OLESTR ( "inner.Mouse" ), &clsid )

if ( FAILED ( hr ) )

::MessageBox ( 0, "", "CLSIDFromProgID failed", 0 ) ;

hr = CoCreateInstance ( clsid, GetControllingUnknown( ), CLSCTX_INPROC, IID_IUnknown, ( void ** ) &m_agg ) ;

if ( FAILED ( hr ) )

::MessageBox ( 0, "", "CoCreate failed",0) ;

return S_OK ;

}

This function creates an instance of the inner object when the outer object first gets initialized. Here we are using CoCreateInstance( ) to create the instance of the CMouse coclass. The second parameter to CoCreateInstance( ) is the outer unknown of CMouseTrails object. We do not know that the current instance of the CMouse coclass is the controlling object, or whether it too has been aggregated. Hence we are using GetControllingUnknown( ) which will either return the controlling outer IUnknown if it is aggregated, or its own IUnknown if it is not. The fourth parameter is the interface we are asking for, which must be IUnknown when we are creating an object as part of an aggregate.

  • Add the following function to the ‘MouseTrails.h’ file.

HRESULT FinalRelease( )
{
inner->Release( ) ;
}

  • Add a COM_INTERFACE_ENTRY_AGGREGATE( ) macro for the IMouse interface to the com map.

COM_INTERFACE_ENTRY_AGGREGATE( IID_IMouse, m_agg.p )

This macro takes an interface identifier for the interface that we are exposing and an IUnknown * for the inner object that implements the interface. The macro itself hides the details that handle the implementation of QueryInterface( ).

  • Update the file outer.idl file as shown below:

library OUTERLib
{
importlib("stdole32.tlb");
importlib("stdole2.tlb");
importlib("..\inner\inner.tlb");
[
uuid(CB45BCB0-8A4A-11BD-A251-E0EAC39E8615),
helpstring("MouseTrails Class")
]
coclass MouseTrails
{
[default] interface IMouseTrails;
interface IMouse ;
};
};

Creating A Client

The steps to create a COM Client using MFC are as under:

  • Create a dialog-based project using AppWizard (EXE).

  • Add two edit boxes and three buttons to the dialog as shown in Figure 1.

Figure 1.

  • Add two variables m_trails and m_dctime of type integer for the two edit controls in the dialog box.

  • Import the Type Libraries into the client. This is done by adding the following statements to the file ‘StdAfx.h’.

# import "..\Outer\Outer.tlb"
using namespace OUTERLib ;
# import "..\Inner\Inner.tlb"
using namespace INNERLib ;

  • Add the regulation code in the OnInitDialog( ) function as shown below:

BOOL CContClientDlg::OnInitDialog( )
{

// AppWizard generated code
// TODO: Add extra initialization here
CLSID c ;
HRESULT h ;
CoInitialize ( NULL ) ;
h = CLSIDFromProgID ( OLESTR ( "Outer.MouseTrails" ),
&c ) ;
if ( FAILED ( h ) )
MessageBox ( "CLSIDFromProgID Failed" ) ;
h = CoCreateInstance ( c, NULL, CLSCTX_ALL, __uuidof ( IMouseTrails ), ( void ** ) &outer ) ;

if ( FAILED ( h ) )
MessageBox ( " Not able to create instance of an object ") ;

hr = outer -> QueryInterface ( __uuidof ( IMouse ), (void **) &inner );
if ( FAILED ( hr ) )

MessageBox ( "Unable to query the inner interface" ) ;

inner -> SwapButtons = FALSE ;

return TRUE; // return TRUE unless you set the focus to a control

}

  • From the class view tab add private variables outer, inner of types IMouseTrails * and IMouse * respectively to the CClientDlg class.

  • Use the COM Object. Now that we have obtained the interface pointer, the client application can call the methods of the COM server object as shown below:

void CClientDlg::OnSwap( )
{
// TODO: Add your control notification handler code he
inner -> SwapButton( ) ;
}

void CClientDlg::OnMouseTrails( )
{
// TODO: Add your control notification handler code here
UpdateData ( TRUE ) ;
inner -> SetMouseTrails ( m_trails ) ;
}

void CClientDlg::OnDoubleClick( )
{
// TODO: Add your control notification handler code here
UpdateData ( TRUE ) ;
outer -> Setdoubleclicktime ( m_dctime ) ;
}

  • Uninitialize the COM library by the function CoUninitialize( ) at the end of InitInstance( ) function as shown below:

BOOL CContClientApp::InitInstance( )
{
// wizard generate code
CoUninitialize( ) ;
return FALSE;
}