void CMFPreviewHandlerBase::ReadActiveProfileL()
    {
    iActiveProfileRead = EFalse;
    
    MProfileEngine* profileEngine = CreateProfileEngineL();
    CleanupReleasePushL( *profileEngine );
    
    MProfile* activeProfile  = profileEngine->ActiveProfileL();
    CleanupReleasePushL( *activeProfile );
        
    const MProfileTones& profileTones = activeProfile->ProfileTones();
     
    const TProfileToneSettings& toneSettings = profileTones.ToneSettings();
    iActiveProfileVibra = toneSettings.iVibratingAlert;
    iActiveProfileRingingVolume = toneSettings.iRingingVolume;
    iActiveProfileRingingType = toneSettings.iRingingType;
          
    const MProfileExtraSettings& extra = activeProfile->ProfileExtraSettings();
    const MProfile3DToneSettings& threeD = extra.Profile3DToneSettings();
    
    iActiveProfile3DEffect = threeD.Effect();
    iActiveProfile3DEcho = threeD.Echo();
   
    CleanupStack::PopAndDestroy( activeProfile ); 
    CleanupStack::PopAndDestroy( profileEngine );
    
    iActiveProfileRead = ETrue;
    }
// -----------------------------------------------------------------------------
// CMediaMtpDataProvider::LocateRequestProcessorL
// Find or create a request processor that can process the request
// -----------------------------------------------------------------------------
//
TInt CMediaMtpDataProvider::LocateRequestProcessorL( const TMTPTypeRequest& aRequest,
    MMTPConnection& aConnection )
    {
    TInt index = KErrNotFound;
    TInt count = iActiveProcessors.Count();
    for ( TInt i = 0; i < count; i++ )
        {
        if ( iActiveProcessors[i]->Match( aRequest, aConnection ) )
            {
            index = i;
            break;
            }
        }
    if ( index == KErrNotFound )
        {
        MMmRequestProcessor* processor =
            MediaMtpDataProviderProcessor::CreateL( Framework(),
                aRequest,
                aConnection,
                *this );

        CleanupReleasePushL( *processor );
        iActiveProcessors.AppendL( processor );
        CleanupStack::Pop( processor );
        index = count;
        }

    return index;
    }
MNcdSearchOperation* CNcdNodeSearch::SearchL( MNcdLoadNodeOperationObserver& aObserver,
                                              MNcdSearchFilter& aSearchFilter )
    {
    DLTRACEIN((""));
    
    if ( aSearchFilter.Keywords().MdcaCount() < 1 )
        {
        DLERROR(("Error, no keywords in search!"));
        DASSERT( 0 );
        User::Leave( KErrArgument );
        }
    // make sure that search root is created
    CNcdSearchRootNodeProxy* searchRoot = &iNode.NodeManager().SearchRootNodeL();    
    CNcdLoadNodeOperationProxy* operation = iOperationManager.CreateLoadNodeOperationL( iNode,
        EFalse, // don't load children
        0, // pagesize, meaningless in this case
        0, // pagestart, meaningless in this case
        0, // depth, meaningless in this case
        ELoadStructure, // meaningless in this case
        &aSearchFilter );
    CleanupReleasePushL( *operation );
    // Search root is added as an observer here to make it
    // update once the op is complete. 
    operation->AddObserverL( searchRoot );
    operation->AddObserverL( &iNode );
    operation->AddObserverL( &aObserver );
    CleanupStack::Pop( operation );
    return operation;
    }
void CNcdQuery::InternalizeL( RReadStream& aReadStream )
    {
    delete iId;
    iId = NULL;
    iId = HBufC::NewL( aReadStream, KMaxTInt );
    iIsOptional = aReadStream.ReadInt32L();
    iSemantics = static_cast<MNcdQuery::TSemantics>(
        aReadStream.ReadInt32L());
    delete iTitle;
    iTitle = NULL;
    iTitle = CNcdString::NewL( aReadStream );
    delete iBody;
    iBody = NULL;
    iBody = CNcdString::NewL( aReadStream );
    iResponse = static_cast<TResponse>( aReadStream.ReadInt32L() );
    iIsSecureConnection = aReadStream.ReadInt32L();
    TInt itemCount( aReadStream.ReadInt32L() );
    iItems.ResetAndRelease();
    for ( TInt i = 0 ; i < itemCount ; i++ )
        {
        TNcdInterfaceId interfaceId = static_cast<TNcdInterfaceId>(aReadStream.ReadInt32L());
        CNcdQueryItem* item = NULL;
        switch ( interfaceId )
            {
            case ENcdQueryTextItemUid:
                {
                item = CNcdQueryTextItem::NewL( aReadStream, *this );
                break;
                }
            case ENcdQueryNumericItemUid:
                {
                item = CNcdQueryNumericItem::NewL( aReadStream, *this );
                break;
                }
            case ENcdQueryPinCodeItemUid:
                {
                item = CNcdQueryPinCodeItem::NewL( aReadStream, *this );
                break;
                }
            case ENcdQuerySelectionItemUid:
                {
                item = CNcdQuerySelectionItem::NewL( aReadStream, *this );
                break;
                }
            default:
                {
                User::Leave( KErrCorrupt );
                break;
                }
            }

        // Object's refcount must be at least 1 for Release() to work correctly
        item->AddRef();
        CleanupReleasePushL( *item );
        iItems.AppendL( item );        
        CleanupStack::Pop( item );
        }
    }
/*static*/ CCheckedCertStore* CCheckedCertStore::NewCheckedWritableCertStoreL(MCTTokenInterface* aTokenIF, RProperty& aProperty)
    {
    assert(aTokenIF);
	MCTWritableCertStore& tokenInterface = static_cast<MCTWritableCertStore&>(*aTokenIF);
	CCheckedCertStore* me = new (ELeave) CCheckedCertStore(tokenInterface, aProperty);
    CleanupReleasePushL(*me);
    me->ConstructL();
    CleanupStack::Pop();
	return (me);
    }
MNcdLoadNodeOperation* CNcdSearchNodeFolderProxy::LoadChildrenL( TInt aIndex, 
                                                           TInt aSize,
                                                           TNcdChildLoadMode aMode,
                                                           MNcdLoadNodeOperationObserver& aObserver )
    {
    DLTRACEIN((("this: %X"), this));
    DASSERT( iSearchFilter );
    
    if( aSize < 1 || aIndex < 0 || ( aMode == ELoadMetadata && aIndex + aSize > ChildCount() ))
        {
        // Nothing to be done 
        DLERROR(( "Argument error. ChildCount: %d Given index: %d, size: %d",
                  ChildCount(), aIndex, aSize ));
        DASSERT( EFalse );
        User::Leave( KErrArgument );
        }

    DLTRACE(( _L("Node: %S, %S"), &Namespace(), &Id() ));

    #ifdef CATALOGS_BUILD_CONFIG_DEBUG    
    const MDesCArray& keywords = iSearchFilter->Keywords();
    DLINFO(("Search filter: "));
    for ( TInt i = 0; i < keywords.MdcaCount(); i++ ) 
        {
        DLINFO((_L("%S"), &keywords.MdcaPoint( i ) ));
        }
    #endif
        
    CNcdLoadNodeOperationProxy* operation = 
        OperationManager().CreateLoadNodeOperationL( *this,
            ETrue, // load children
            aSize, 
            aIndex,
            1,
            aMode,
            iSearchFilter );

    if( operation == NULL )
        {
        DLTRACEOUT(("NULL"));     
        return NULL;
        }

    CleanupReleasePushL( *operation );
    operation->AddObserverL( this );
    operation->AddObserverL( &aObserver );
    CleanupStack::Pop( operation );
    
    DLTRACEOUT((""));

    return operation;
    }
// The caller must free the returned buffer. The buffer is guaranteed
// to have a zero terminator.
HBufC8* CSensor_profile::GetCurrentProfileNameL()
{
  MProfile* profile = iProfileEngine->ActiveProfileL();
  CleanupReleasePushL(*profile);

  const MProfileName& profileName = profile->ProfileName();
  const TDesC& name16 = profileName.Name();

  HBufC8* name8 = ConvToUtf8ZL(name16);

  CleanupStack::PopAndDestroy(); // profile

  return name8;
}
RCatalogsArray<MNcdOperation> CNcdNodeProxy::OperationsL() const
    {
    DLTRACEIN(("this: %x, iMetadata: %x", this, iMetadata ));
    RCatalogsArray<MNcdOperation> operations;
    CleanupClosePushL( operations );

    if ( iMetadata ) 
        {
        // Get the original array and insert its content to catalogs array.
        // Also, increase the reference counter for the items.
        const RPointerArray<MNcdOperation>& origArray = iOperationManager.Operations();
        MNcdOperation* oper( NULL );
        MNcdNode* node( NULL );
        
        CNcdNodeMetadataProxy* metadata( NULL );
        DLTRACE(("Getting metaidentifier"));
        const CNcdNodeIdentifier& metadataId( iMetadata->Identifier() );
        
        DLTRACE(("Origarray.count: %d", origArray.Count() ));
        for ( TInt i = 0; i < origArray.Count(); ++i )
            {            
            oper = origArray[ i ];
            DLTRACE(("oper: %x", oper));
            // Notice that node ref count is increased. So, release it when done.
            node = oper->Node();
            if ( node ) 
                {
                CleanupReleasePushL( *node );
    
                // Compare metadatas
                metadata = static_cast<CNcdNodeProxy*>( node )->Metadata();
                DLTRACE(("Metadata: %x", metadata));
                if ( metadata && metadata->Identifier().Equals( metadataId ) )
                    {
                    DLTRACE(("Appending to ops array"));
                    operations.AppendL( oper );
                    oper->AddRef();
                    }
    
                CleanupStack::PopAndDestroy( node );
                }
            }
        }

    CleanupStack::Pop( &operations );
    
    DLTRACEOUT(( "" ));
    return operations;
    }
MNcdLoadNodeOperation* CNcdSearchNodeFolderProxy::LoadL( MNcdLoadNodeOperationObserver& aObserver )
    {
    CNcdLoadNodeOperationProxy* operation = OperationManager().CreateLoadNodeOperationL( *this,
        EFalse, // don't load children
        0, // pagesize, meaningless in this case
        0, // pagestart, meaningless in this case
        0, // depth, meaningless in this case
        ELoadStructure, // meaningless in this case
        iSearchFilter );
    CleanupReleasePushL( *operation );
    
    operation->AddObserverL( this );
    operation->AddObserverL( &aObserver );
    CleanupStack::Pop( operation );
    return operation;
    }
void CBcaController::StartLoadL(const CBCAProvision* aBCAProvisionConfig,MUpperControl* aControl, 
		MUpperDataReceiver* aData)
/**
 *  This method loads the C32BCA library and uses Ioctl to set the Bca iIapId.
 *  
 * @param aBCAProvisionConfig pointer to CBCAProvision for extracting the pond
 * @param aControl pointer to BasebandChannelAdaptation2::MUpperControl passed to the MBca2 to pass control information up the stack
 * * @param aData pointer to BasebandChannelAdaptation2::MUpperDataReceiver passed to the MBca2 to push packets up the stack
 * @return none 
 */
	{
	OstTraceDef0(OST_TRACE_CATEGORY_DEBUG, TRACE_INTERNALS, CBCACONTROLLER_STARTLOADL_1, "CBcaControl::StartLoad");

	iBCAProvisionConfig = aBCAProvisionConfig;
	iUpperControl = aControl;
	iUpperDataReceiver = aData;
	// Loads Bca Dll and creates a Bca instance;
	User::LeaveIfError(iBcaDll.iObj.Load(iBCAProvisionConfig->GetBCAName()));
	
	TNewBca2FactoryL newBca2FactoryProcL = (TNewBca2FactoryL)iBcaDll.iObj.Lookup(1);
	if (NULL == newBca2FactoryProcL)
		{
		OstTraceDef1(OST_TRACE_CATEGORY_DEBUG, TRACE_INTERNALS, CBCACONTROLLER_STARTLOADL_2, "Library entry point found error %d", KErrBadLibraryEntryPoint);
		User::Leave(KErrBadLibraryEntryPoint);	
		}
	
	MBca2Factory* bcaFactory = (*newBca2FactoryProcL)();

	if(!bcaFactory)
		{
		OstTraceDef1(OST_TRACE_CATEGORY_DEBUG, TRACE_INTERNALS, CBCACONTROLLER_STARTLOADL_3, "BcaFactory creation error %d", KErrCompletion);
		User::Leave(KErrCompletion);	
		}
	CleanupReleasePushL(*bcaFactory);
	
	iMBca = bcaFactory->NewBcaL();
	CleanupStack::PopAndDestroy(bcaFactory);
	
	TPckg<TUint32> aOpt(iBCAProvisionConfig->GetIAPid());
	iMBca->Control(iStatus,KBcaOptLevelGeneric,KBCASetIapId,aOpt);
	
	iState = EIdling;
	SetActive();
	}
void T_MProfile::CreateTestL()
    {
    MProfile* profile = NULL;
    profile = iProfileEngine->ActiveProfileL();
    EUNIT_ASSERT( profile );
    profile->Release();
    profile = NULL;

    profile = iProfileEngine->ActiveProfileL();
    EUNIT_ASSERT( profile );
    CleanupReleasePushL( *profile );
    CleanupStack::PopAndDestroy();
    profile = NULL;

    profile = iProfileEngine->ActiveProfileLC();
    EUNIT_ASSERT( profile );
    CleanupStack::PopAndDestroy();
    profile = NULL;
    }
// ---------------------------------------------------------------------------
// NewLC
// ---------------------------------------------------------------------------
//
CNcdFileDownloadOperationProxy* CNcdFileDownloadOperationProxy::NewLC( 
    MCatalogsClientServer& aSession,
    TInt aHandle,
    MNcdOperationProxyRemoveHandler* aRemoveHandler,
    CNcdNodeProxy* aNode,
    CNcdNodeManagerProxy* aNodeManager,
    const TDesC& aTargetFilename,
    MNcdFileDownloadOperationObserver* aObserver,
    TNcdDownloadDataType aDataType )
    {
    CNcdFileDownloadOperationProxy* self =
        new( ELeave ) CNcdFileDownloadOperationProxy( aDataType );    
    
    self->AddRef();
    CleanupReleasePushL( *self );        
    self->ConstructL( aSession, aHandle, aRemoveHandler,
        aNode, aNodeManager, aObserver, aTargetFilename );
    return self;
    }
RCatalogsArray<MNcdOperation> CNcdRootNodeProxy::OperationsL() const
    {
    DLTRACEIN((""));
    RCatalogsArray<MNcdOperation> operations;
    CleanupClosePushL( operations );

    // Operations will be get differently for root node, because root
    // node does not have metadata.
    
    // Get the original array and insert its content to catalogs array.
    // Also, increase the reference counter for the items.
    const RPointerArray<MNcdOperation>& origArray = OperationManager().Operations();
    const MNcdNode* thisNode( this );
    MNcdOperation* oper( NULL );
    MNcdNode* node( NULL );

    for ( TInt i = 0; i < origArray.Count(); ++i )
        {
        oper = origArray[ i ];

        // Notice that node ref count is increased. So, release it when done.
        node = oper->Node();
        CleanupReleasePushL( *node );

        if( node == thisNode )
            {
            operations.AppendL( oper );
            oper->AddRef();
            }

        CleanupStack::PopAndDestroy( node );
        }

    CleanupStack::Pop( &operations );
    
    DLTRACEOUT(( "" ));
    return operations;
    }
// create a custom interface Mux implementation
MMMFDevSoundCustomInterfaceMuxPlugin* CMMFDevSoundCIMuxUtility::CreateCustomInterfaceMuxL(TUid aInterfaceId)
	{
	// The Uid of the plugin will be used as string for matching the best suitable plug in.
	TInt uidAsInteger = aInterfaceId.iUid;
	TBuf8<KMuxTempBufferSize> tempBuffer;
	tempBuffer.Num(uidAsInteger, EHex);
	TUid interfaceUid = {KUidDevSoundCustomInterfaceMux};
	
	TUid destructorKey;
	MMMFDevSoundCustomInterfaceMuxPlugin* self = 
		static_cast<MMMFDevSoundCustomInterfaceMuxPlugin*>
		(MmPluginUtils::CreateImplementationL(interfaceUid, destructorKey, tempBuffer, KRomOnlyResolverUid));

	// pass the destructor key so class can destroy itself
	self->PassDestructorKey(destructorKey);
	CleanupReleasePushL(*self);

	// attempt to construct the plugin
	self->CompleteConstructL(this);
	CleanupStack::Pop(); // self
		
	return self;
	}
/**
Find or create a request processor that can process the request
@param aRequest    The request to be processed
@param aConnection The connection from which the request comes
@return the index of the found/created request processor
*/
TInt CMTPDeviceDataProvider::LocateRequestProcessorL(const TMTPTypeRequest& aRequest, MMTPConnection& aConnection)
    {
    OstTraceFunctionEntry0( CMTPDEVICEDATAPROVIDER_LOCATEREQUESTPROCESSORL_TMTPTYPEREQUEST_ENTRY );
    TInt index = KErrNotFound;
    TInt count = iActiveProcessors.Count();
    for(TInt i = 0; i < count; i++)
        {
        if(iActiveProcessors[i]->Match(aRequest, aConnection))
            {
            index = i;
            break;
            }
        }
    if(index == KErrNotFound)
        {
        MMTPRequestProcessor* processor = MTPDeviceDpProcessor::CreateL(Framework(), aRequest, aConnection);
        __ASSERT_DEBUG(processor, Panic(EMTPDevDpNoMatchingProcessor));
        CleanupReleasePushL(*processor);
        iActiveProcessors.AppendL(processor);
        TUint16 operationCode(aRequest.Uint16(TMTPTypeRequest::ERequestOperationCode));

       if (operationCode >= EMTPOpCodeGetDevicePropDesc && operationCode <=EMTPOpCodeResetDevicePropValue)
		{
		TUint propCode = aRequest.Uint32(TMTPTypeRequest::ERequestParameter1);
		TInt foundplugin = FindExtnPlugin (propCode);
		if(foundplugin!= KErrNotFound)
			{
			iDevDpSingletons.DeviceDataStore().SetExtnDevicePropDp(iExtnPluginMapArray[foundplugin]->ExtPlugin());
			}
		}
	        CleanupStack::Pop();
	        index = count;
        }
    OstTraceFunctionExit0( CMTPDEVICEDATAPROVIDER_LOCATEREQUESTPROCESSORL_TMTPTYPEREQUEST_EXIT );
    return index;
    }
Exemple #16
0
/** Puts a cleanup item for this object onto the cleanup stack.

This allows allocated resources to be cleaned up if a subsequent leave occurs. */
EXPORT_C void MStreamBuf::PushL()
	{
	CleanupReleasePushL(*this);
	}
void CCLayerTestSsmSimStatusObserver::doTestSimChangedAndOwnedL()
	{
	INFO_PRINTF1(_L("Entering test for change and owned parts of SSM SIM status observer/cmd"));
	__UHEAP_MARK;
	
	// Delete any existing defines, ignore return value
	TInt err1 = RProperty::Delete(CSsmUiSpecific::StartupPSUid(), KPSSimChanged);
	TInt err2 = RProperty::Delete(CSsmUiSpecific::StartupPSUid(), KPSSimOwned);
	INFO_PRINTF3(_L("Value of err1 & err2 = %d & %d"), err1, err2);
	TInt err = KErrNone;
	
	INFO_PRINTF1(_L("Constructing SSM SIM publish cmd"));	
	CCustomCmdPublishSimOwnedAndChanged* simCustomCmd = CCustomCmdPublishSimOwnedAndChanged::NewL();
	CleanupReleasePushL(*simCustomCmd);	
	simCustomCmd->Initialize(NULL);
	CleanupClosePushL(*simCustomCmd);
	
	INFO_PRINTF1(_L("Executing SSM SIM publish cmd without defining SIM properties"));
	TBuf8<1> emptyBuf;
	simCustomCmd->Execute(emptyBuf, iRequestStatus);
	TEST(iRequestStatus == KRequestPending);

	INFO_PRINTF1(_L("Adding callBack"));
	TCallBack stop(CallBackL, this);
    iAsyncStopScheduler->Set(stop);
    
    iAsyncStopScheduler->CallBack();
	INFO_PRINTF1(_L("Testing running active scheduler for publish startup mode without property defined"));
	iActiveScheduler->Start();
	User::WaitForRequest(iRequestStatus);
	
	TEST(iRequestStatus == KErrNotFound);
	
	INFO_PRINTF1(_L("Checking execute cancel does nothing"));
	simCustomCmd->ExecuteCancel();
	
	INFO_PRINTF1(_L("Cleaning up SSM SIM publish cmd"));
	
	// Close simCustomCmd
	CleanupStack::PopAndDestroy(simCustomCmd);
	// Release simCustomCmd
	CleanupStack::PopAndDestroy(simCustomCmd);
	simCustomCmd = NULL;
		
	INFO_PRINTF1(_L("Constructing SSM SIM publish cmd"));	
	simCustomCmd = CCustomCmdPublishSimOwnedAndChanged::NewL();
	CleanupReleasePushL(*simCustomCmd);
	simCustomCmd->Initialize(NULL);
	CleanupClosePushL(*simCustomCmd);
	
	INFO_PRINTF1(_L("Initializing SSM SIM status observer without defining SIM changed property"));
	err = RProperty::Define(CSsmUiSpecific::StartupPSUid(), KPSSimOwned, RProperty::EInt);
	INFO_PRINTF2(_L("Define returns err = %d") ,err);
	TEST(err == KErrNone);
	simCustomCmd->Execute(emptyBuf, iRequestStatus);
	
	INFO_PRINTF1(_L("Adding callback"));
	iAsyncStopScheduler->CallBack();
	INFO_PRINTF1(_L("Testing running active scheduler for publish startup mode without defining SIM changed property"));
	iActiveScheduler->Start();
	User::WaitForRequest(iRequestStatus);
	TEST(iRequestStatus == KErrNotFound);
	
	INFO_PRINTF1(_L("Cleaning up SSM SIM publish cmd"));
	
	// Close simCustomCmd
	CleanupStack::PopAndDestroy(simCustomCmd);
	// Release simCustomCmd
	CleanupStack::PopAndDestroy(simCustomCmd);
	simCustomCmd = NULL;

	INFO_PRINTF1(_L("Constructing SSM SIM publish cmd"));	
	simCustomCmd = CCustomCmdPublishSimOwnedAndChanged::NewL();
	CleanupReleasePushL(*simCustomCmd);
	simCustomCmd->Initialize(NULL);
	CleanupClosePushL(*simCustomCmd);
	
	INFO_PRINTF1(_L("Initializing SSM SIM status observer with defined SIM properties, both false"));
	AdaptationCliWrapper::SetSimOwned(EFalse);
	AdaptationCliWrapper::SetSimChanged(EFalse);
	err = RProperty::Define(CSsmUiSpecific::StartupPSUid(), KPSSimChanged, RProperty::EInt);
	TEST(err == KErrNone);
	simCustomCmd->Execute(emptyBuf, iRequestStatus);
	
	INFO_PRINTF1(_L("callback"));
    iAsyncStopScheduler->CallBack();
	INFO_PRINTF1(_L("Testing running active scheduler for publish startup mode with defined SIM properties, both false"));
	iActiveScheduler->Start();	
	User::WaitForRequest(iRequestStatus);
	
	
	TEST(iRequestStatus == KErrPermissionDenied);
	TInt simChangedValue = 0;
	TInt simOwnedValue = 0;
	err = RProperty::Get(CSsmUiSpecific::StartupPSUid(), KPSSimChanged, simChangedValue);
	TEST(err == KErrNone);
	TEST(simChangedValue == ESimChanged);
	err = RProperty::Get(CSsmUiSpecific::StartupPSUid(), KPSSimOwned, simOwnedValue);
	TEST(err == KErrNone);
	TEST(simOwnedValue == ESimNotOwned);
	
	INFO_PRINTF1(_L("Cleaning up SSM SIM publish cmd"));
	// Close simCustomCmd
	CleanupStack::PopAndDestroy(simCustomCmd);
	// Release simCustomCmd
	CleanupStack::PopAndDestroy(simCustomCmd);
	simCustomCmd = NULL;

	INFO_PRINTF1(_L("Constructing SSM SIM publish cmd"));	
	simCustomCmd = CCustomCmdPublishSimOwnedAndChanged::NewL();
	CleanupReleasePushL(*simCustomCmd);
	simCustomCmd->Initialize(NULL);
	CleanupClosePushL(*simCustomCmd);
	
	INFO_PRINTF1(_L("Initializing SSM SIM status observer with get owned failure"));
	AdaptationCliWrapper::SetSimOwned(ETrue);
	AdaptationCliWrapper::SetSimOwnedReturnValue(KErrNotSupported);
	simCustomCmd->Execute(emptyBuf, iRequestStatus);
	
	INFO_PRINTF1(_L("callback"));
    iAsyncStopScheduler->CallBack();
	INFO_PRINTF1(_L("Testing running active scheduler for publish startup mode with get owned failure"));
	iActiveScheduler->Start();	
	User::WaitForRequest(iRequestStatus);
	
	TEST(iRequestStatus == KErrPermissionDenied);
	err = RProperty::Get(CSsmUiSpecific::StartupPSUid(), KPSSimChanged, simChangedValue);
	TEST(err == KErrNone);
	TEST(simChangedValue == ESimChanged);
	err = RProperty::Get(CSsmUiSpecific::StartupPSUid(), KPSSimOwned, simOwnedValue);
	TEST(err == KErrNone);
	TEST(simOwnedValue == ESimNotOwned);
	AdaptationCliWrapper::SetSimOwnedReturnValue(KErrNone);
	AdaptationCliWrapper::SetSimOwned(EFalse);
	
	INFO_PRINTF1(_L("Cleaning up SSM SIM publish cmd"));
	// Close simCustomCmd
	CleanupStack::PopAndDestroy(simCustomCmd);
	// Release simCustomCmd
	CleanupStack::PopAndDestroy(simCustomCmd);
	simCustomCmd = NULL;

	INFO_PRINTF1(_L("Constructing SSM SIM publish cmd"));	
	simCustomCmd = CCustomCmdPublishSimOwnedAndChanged::NewL();
	CleanupReleasePushL(*simCustomCmd);
	simCustomCmd->Initialize(NULL);
	CleanupClosePushL(*simCustomCmd);
	
	INFO_PRINTF1(_L("Initializing SSM SIM status observer with get changed failure"));
	AdaptationCliWrapper::SetSimChangedReturnValue(KErrNotSupported);
	simCustomCmd->Execute(emptyBuf, iRequestStatus);
	
	INFO_PRINTF1(_L("callback"));
    iAsyncStopScheduler->CallBack();
	INFO_PRINTF1(_L("Testing running active scheduler for publish startup mode SIM status observer with get changed failure"));
	iActiveScheduler->Start();	
	User::WaitForRequest(iRequestStatus);
	
	TEST(iRequestStatus == KErrPermissionDenied);
	err = RProperty::Get(CSsmUiSpecific::StartupPSUid(), KPSSimChanged, simChangedValue);
	TEST(err == KErrNone);
	TEST(simChangedValue == ESimChanged);
	err = RProperty::Get(CSsmUiSpecific::StartupPSUid(), KPSSimOwned, simOwnedValue);
	TEST(err == KErrNone);
	TEST(simOwnedValue == ESimNotOwned);
	AdaptationCliWrapper::SetSimChangedReturnValue(KErrNone);
	
	INFO_PRINTF1(_L("Cleaning up SSM SIM publish cmd"));
	// Close simCustomCmd
	CleanupStack::PopAndDestroy(simCustomCmd);
	// Release simCustomCmd
	CleanupStack::PopAndDestroy(simCustomCmd);
	simCustomCmd = NULL;

	INFO_PRINTF1(_L("Constructing SSM SIM publish cmd"));	
	simCustomCmd = CCustomCmdPublishSimOwnedAndChanged::NewL();
	CleanupReleasePushL(*simCustomCmd);
	simCustomCmd->Initialize(NULL);
	CleanupClosePushL(*simCustomCmd);
	
	INFO_PRINTF1(_L("Initializing SSM SIM status observer with defined SIM properties, both true"));
	AdaptationCliWrapper::SetSimOwned(ETrue);
	AdaptationCliWrapper::SetSimChanged(ETrue);
	simCustomCmd->Execute(emptyBuf, iRequestStatus);
	
	INFO_PRINTF1(_L("callback"));
	iAsyncStopScheduler->CallBack();
	INFO_PRINTF1(_L("Testing running active scheduler for publish startup mode with defined SIM properties, both true"));
	iActiveScheduler->Start();	
	User::WaitForRequest(iRequestStatus);	
		
	TEST(iRequestStatus == KErrPermissionDenied);
	err = RProperty::Get(CSsmUiSpecific::StartupPSUid(), KPSSimChanged, simChangedValue);
	TEST(err == KErrNone);
	TEST(simChangedValue == ESimChanged);
	err = RProperty::Get(CSsmUiSpecific::StartupPSUid(), KPSSimOwned, simOwnedValue);
	TEST(err == KErrNone);
	TEST(simOwnedValue == ESimOwned);
	
	INFO_PRINTF1(_L("Cleaning up SSM SIM publish cmd"));
	// Close simCustomCmd
	CleanupStack::PopAndDestroy(simCustomCmd);
	// Release simCustomCmd
	CleanupStack::PopAndDestroy(simCustomCmd);
	simCustomCmd = NULL;
		
	__UHEAP_MARKEND;
	INFO_PRINTF1(_L("Leaving test for change and owned parts of SSM SIM status observer/cmd"));
	}
void CNcdQuery::InternalizeL( const MNcdConfigurationProtocolQuery& aQuery )
    {
    delete iId;
    iId = NULL;
    iId = aQuery.Id().AllocL();
    iIsOptional = aQuery.Optional();
    iSemantics = aQuery.Semantics();
    delete iTitle;
    iTitle = NULL;
    iTitle = CNcdString::NewL( aQuery.Title().Key(), aQuery.Title().Data() );
    delete iBody;
    iBody = NULL;
    iBody = CNcdString::NewL( aQuery.BodyText().Key(), aQuery.BodyText().Data() );
        
    iItems.ResetAndRelease();    
    for ( TInt i = 0 ; i < aQuery.QueryElementCount() ; i++ )
        {
        const MNcdConfigurationProtocolQueryElement& queryElement =
            aQuery.QueryElementL( i );
        CNcdQueryItem* item = NULL;
        switch ( queryElement.Type() )
            {
            case MNcdConfigurationProtocolQueryElement::EFreeText:
            case MNcdConfigurationProtocolQueryElement::EFile:
            case MNcdConfigurationProtocolQueryElement::EGpsLocation:
            case MNcdConfigurationProtocolQueryElement::EConfiguration:
                {
                item = CNcdQueryTextItem::NewL( queryElement, *this );                
                break;
                }
            case MNcdConfigurationProtocolQueryElement::ENumeric:
                {
                if ( queryElement.Semantics() ==
                    MNcdQueryItem::ESemanticsPinCode )
                    {
                    item = CNcdQueryPinCodeItem::NewL( queryElement, *this );
                    }
                else
                    {
                    item = CNcdQueryNumericItem::NewL( queryElement, *this );
                    }
                break;
                }            
            case MNcdConfigurationProtocolQueryElement::ESingleSelect:
            case MNcdConfigurationProtocolQueryElement::EMultiSelect:
                {
                item = CNcdQuerySelectionItem::NewL( queryElement, *this );                
                break;
                }
            default:
                {
                User::Leave( KErrCorrupt );
                break;
                }
            }
        
        // Object's refcount must be at least 1 for Release() to work correctly
        item->AddRef();
        CleanupReleasePushL( *item );		
        iItems.AppendL( item );
        CleanupStack::Pop( item );        
        }
    }
// -----------------------------------------------------------------------------
// void CWimAuthenticationObject::DoMakeObjectsL()
// Protected objects are validated here
// -----------------------------------------------------------------------------
//
void CWimAuthenticationObject::DoMakeObjectsL()
    {
    _WIMTRACE ( _L( "CWimAuthenticationObject::DoMakeObjectsL()" ) );
    if ( iStatus.Int() == KErrNone ) // Not cancelled
        {
        TInt count = iKeyInfos.Count();
        TInt i = 0;
        for ( ; i < count; i++ )
            {
            // Make a copy of key info
            HBufC* wlabel = HBufC::NewLC( ( iKeyInfos )[i]->Label().Length() );
            wlabel->Des().Copy( ( iKeyInfos )[i]->Label() );
            // Make a copy of protector if there is
            MCTAuthenticationObject* protector = NULL;
            if ( iKeyInfos[i]->Protector() )
                {
                TUint thishandle = iKeyInfos[i]->Protector()->
                                                    Handle().iObjectId;
                
                //All the key list here is protected by this Authobj
                if( this->Handle().iObjectId == thishandle )
	                {
	                protector = MakeAuthObjectL();
	                }
                                                    
                else
                    {
                	return;
                    }
                
                
                if ( protector )
                    {
                    CleanupStack::PushL( protector );
                    }
                }
#ifdef __SECURITY_PLATSEC_ARCH__
            CCTKeyInfo* copy =
                CCTKeyInfo::NewL( ( iKeyInfos ) [i]->ID(),
                                  ( iKeyInfos ) [i]->Usage(),
                                  ( iKeyInfos ) [i]->Size(),
                                    protector,
                                    wlabel,
                                  ( iKeyInfos ) [i]->Token(),
                                  ( iKeyInfos ) [i]->Handle().iObjectId,
                                  ( iKeyInfos ) [i]->UsePolicy(),
                                  ( iKeyInfos ) [i]->ManagementPolicy(),
                                  ( iKeyInfos ) [i]->Algorithm(),
                                  ( iKeyInfos ) [i]->AccessType(),
                                  ( iKeyInfos ) [i]->Native(),
                                  ( iKeyInfos ) [i]->StartDate(),
                                  ( iKeyInfos ) [i]->EndDate() );
#else
            CCTKeyInfo* copy =
                CCTKeyInfo::NewL( ( iKeyInfos ) [i]->ID(),
                                  ( iKeyInfos ) [i]->Usage(),
                                  ( iKeyInfos ) [i]->Size(),
                                    protector,
                                    wlabel,
                                  ( iKeyInfos ) [i]->Token(),
                                  ( iKeyInfos ) [i]->Handle().iObjectId,
                                  ( iKeyInfos ) [i]->Owner(),
                                  ( iKeyInfos ) [i]->Users(),
                                  ( iKeyInfos ) [i]->Algorithm(),
                                  ( iKeyInfos ) [i]->AccessType(),
                                  ( iKeyInfos ) [i]->Native(),
                                  ( iKeyInfos ) [i]->StartDate(),
                                  ( iKeyInfos ) [i]->EndDate() );
#endif
            // Call Release() for copy, if leave occurs
            CleanupReleasePushL( *copy );
            // Take MCTokenObject part of it and append it to client
            MCTTokenObject* obj = copy;
            User::LeaveIfError( iObjects->Append ( obj ) );
            CleanupStack::Pop( copy );
            if ( protector )
                {
                CleanupStack::Pop( protector );
                }
            CleanupStack::Pop( wlabel );
            }
        count = iCertStoreEntries.Count();
        for ( i = 0; i < count; i++ )
            {
            // Make a copy of certificate info

            CCTCertInfo* copy = CCTCertInfo::NewLC( *iCertStoreEntries [i] );
            MCTTokenObject* obj = copy;
            User::LeaveIfError( iObjects->Append ( obj ) );
            CleanupStack::Pop( copy );
            }
        }
    FreeUnifiedKeyStore();
    FreeUnifiedCertStore();
    iPhase = EIdle;
    User::RequestComplete( iOriginalRequestStatus, iStatus.Int() );
    }
/**
Creates a new surface for video rendering and registers it with the windows server for all displays.

@param aSize Surface size in pixels
@param aNumBuffers The minimum number of buffers required. The renderer can create a surface with more buffers.
@param aFormat Surface data format
@param aSurface Output: Surface ID for the new surface

@leave KErrNoMemory Out of memory
@leave KErrNotSupported The requested parameters are not supported
@leave KErrInUse Too many video surfaces are already in use
*/
EXPORT_C void CVideoRenderer::CreateSurfaceL(const TSize& aSize, TInt aNumBuffers, const TUncompressedVideoFormat& aFormat, TSurfaceId& aSurface)
	{
	if (iBufferManager != NULL)
		{
		User::Leave(KErrInUse);
		}
	else if (aNumBuffers <= 0)
		{
		User::Leave(KErrNotSupported);
		}
	
	RSurfaceManager::TSurfaceCreationAttributesBuf attribBuf;
	RSurfaceManager::TSurfaceCreationAttributes& attrib = attribBuf();
	attrib.iSize = aSize;
	attrib.iBuffers = aNumBuffers;
	attrib.iPixelFormat = VideoRendererUtil::ConvertUncompressedVideoFormatToUidPixelFormatL(aFormat);
	attrib.iStride = aSize.iWidth * VideoRendererUtil::BytesPerPixelL(attrib.iPixelFormat);
	attrib.iOffsetToFirstBuffer = 0;
	attrib.iAlignment = 4;
	attrib.iContiguous = ETrue;
	attrib.iMappable = ETrue;

	User::LeaveIfError(iSurfaceManager.CreateSurface(attribBuf, iSurfaceId));
	
	// Push surfaceId to cleanup stack in case buffer manager constructor leave.
	// SurfaceId needs to be pushed because the renderer state is inconsistent 
	// if buffer manager creation leave
	CleanupReleasePushL(*this);
	
	RChunk chunk;
	User::LeaveIfError(iSurfaceManager.MapSurface(iSurfaceId, chunk));
	CleanupClosePushL(chunk);
	
	RSurfaceManager::TInfoBuf infoBuf;
	User::LeaveIfError(iSurfaceManager.SurfaceInfo(iSurfaceId, infoBuf));

	// Register must take place after 'this' pushed onto cleanupstack just in case 
	// function leaves after registration
	RegisterSurfaceL();
	
	// prepare the renderer relay
	RSurfaceManager::TSurfaceInfoV01 info = infoBuf();
	if (iTimed)
		{
		TRequestStatus updateRequest = KRequestPending;
		TRequestStatus logonRequest = KRequestPending;

		// While a function call is in progress this thread is suspended
		// and the undertaker will not catch panics, listen for these here
		iRendererThread.Logon(logonRequest);

		// Send request to renderer thread
		iRendererRelay->PrepareL(iSurfaceId, info.iBuffers, &updateRequest);
		User::WaitForRequest(logonRequest, updateRequest);

		if(logonRequest != KRequestPending)
			{
			// renderer thread got panic from surface update session, so panic client
			TInt reason = iRendererThread.ExitReason();
			TExitCategoryName category = iRendererThread.ExitCategory();
			User::Panic(category,reason);
			}

		// Thread is still alive and well
		iRendererThread.LogonCancel(logonRequest);
		User::WaitForRequest(logonRequest); // Consume the signal
		
		// leave if memory allocation failed in renderer thread
		User::LeaveIfError(updateRequest.Int());

		__ASSERT_DEBUG(updateRequest != KRequestPending, User::Panic(_L("CVR::UpdateBuffer"), KErrCorrupt));
		}
	else
		{
		iRendererRelay->PrepareL(iSurfaceId, info.iBuffers, NULL);
		}
	
	// find the buffer offsets
	RArray<TInt> offsets;
	CleanupClosePushL(offsets);
	
	TInt offsetInChunk = 0;
	for (TInt i = 0; i < info.iBuffers; ++i)
		{
		User::LeaveIfError(iSurfaceManager.GetBufferOffset(iSurfaceId, i, offsetInChunk));
		offsets.AppendL(offsetInChunk);
		}
	
	// finally, create buffer manager
	iBufferManager = CRendererBufferManager::NewL(info, offsets, chunk, iTimed);

	CleanupStack::PopAndDestroy(&offsets);
	CleanupStack::Pop(&chunk);
	CleanupStack::Pop(this); // surfaceId
	
	aSurface = iSurfaceId;
	iRendererRelay->SetBufferManager(iBufferManager);
	
	for (TInt i = 0; i < info.iBuffers; ++i)
		{
		// notify observer once for each buffer created
		iObserver.MvroVideoBufferAvailable();
		}
	}
void MT_MProEngProfile::ReleaseTestL()
    {
    MProEngProfile* profile = iEngine->ProfileL( iProfileId );
    CleanupReleasePushL( *profile );
    CleanupStack::PopAndDestroy(); // profile
    }
void MT_MProEngProfile::CommitChangeTestL()
    {
    RDebug::Print( _L( "Digia:CommitchangeTest: begin" ) );
    //////////////////////////////////////////
    // change  settings and commit changes
    //////////////////////////////////////////
    MProEngProfileName& pn1 = iProfile->ProfileName();
    MProEngTones& pt1 = iProfile->ProfileTones();
    MProEngToneSettings& pts1 = iProfile->ToneSettings();
    if( ( iProfileId != EProfileOffLineId ) &&
        ( iProfileId != EProfileGeneralId ) )
        {
        User::LeaveIfError( pn1.SetNameL( KProEngMTTestName ) );
        }
    //TInt error( iProfile->SetAlertForL( iContactGroups.Array() ) );
    TInt error( KErrNone );
    EUNIT_ASSERT( error == KErrNone );
    User::LeaveIfError( pt1.SetMessageAlertToneL( KProEngMTTestTone ) );
    if( iProfileId != EProfileOffLineId )
        {
        User::LeaveIfError( pt1.SetRingingTone1L( KProEngMTTestTone ) );
        User::LeaveIfError( pt1.SetRingingTone2L( KProEngMTTestTone ) );
        User::LeaveIfError( pt1.SetEmailAlertToneL( KProEngMTTestTone ) );
        User::LeaveIfError( pt1.SetVideoCallRingingToneL( KProEngMTTestTone ) );
        User::LeaveIfError( pts1.SetRingingType( KProEngMTTestRingingType ) );
        User::LeaveIfError( pts1.SetTextToSpeech( !pts1.TextToSpeech() ) );
        }
    User::LeaveIfError( pts1.SetKeypadVolume( KProEngMTTestKeypadVolume ) );
    User::LeaveIfError( pts1.SetRingingVolume( KProEngMTTestRingingVolume ) );
    User::LeaveIfError( pts1.SetVibratingAlert( !pts1.VibratingAlert() ) );
    User::LeaveIfError( pts1.SetWarningAndGameTones( !pts1.WarningAndGameTones() ) );
    RDebug::Print( _L( "Digia:CommitchangeTest: before CommitChangeL" ) );
    iProfile->CommitChangeL();
    RDebug::Print( _L( "Digia:CommitchangeTest: after CommitChangeL" ) );

    // read settings
    MProEngProfile* profile = NULL;
    profile = iEngine->ProfileL( iProfileId );
    EUNIT_ASSERT( profile );
    CleanupReleasePushL( *profile );

    MProEngProfileName& pn2 = profile->ProfileName();
    MProEngTones& pt2 = profile->ProfileTones();
    MProEngToneSettings& pts2 = profile->ToneSettings();
    //const TArray<TContactItemId>& array = profile->AlertForL();
    

    EUNIT_ASSERT( pn1.Name().Compare( pn2.Name() ) == 0 );
    EUNIT_ASSERT( pt1.RingingTone1().Compare( pt2.RingingTone1() ) == 0 );
    EUNIT_ASSERT( pt1.RingingTone2().Compare( pt2.RingingTone2() ) == 0 );
    EUNIT_ASSERT( pt1.MessageAlertTone().Compare( pt2.MessageAlertTone() ) == 0 );
    EUNIT_ASSERT( pt1.EmailAlertTone().Compare( pt2.EmailAlertTone() ) == 0 );
    EUNIT_ASSERT( pts1.RingingType() == pts2.RingingType() );
    EUNIT_ASSERT( pts1.KeypadVolume() == pts2.KeypadVolume() );
    EUNIT_ASSERT( pts1.RingingVolume() == pts2.RingingVolume() );
    EUNIT_ASSERT( pts1.VibratingAlert() == pts2.VibratingAlert() );
    EUNIT_ASSERT( pts1.WarningAndGameTones() == pts2.WarningAndGameTones() );
    EUNIT_ASSERT( pts1.TextToSpeech() == pts2.TextToSpeech() );
    //EUNIT_ASSERT( T_ProfileTestTools::CompareArrays( array, iContactGroups.Array() ) );

    CleanupStack::PopAndDestroy();  //profile->Release
    RDebug::Print( _L( "Digia:CommitchangeTest: end" ) );
    }
void CUnifiedCertStore::RunL()
	{
	if ((iState != EInitializeGetReadableInterface) &&
		(iState != EInitializeGetReadableInterfaceFinished) &&
		(iState != EInitializeGetToken)) // We don't want to leave if we're in this state
										 // since we want to enumerate all tokens, see below
		{
		User::LeaveIfError(iStatus.Int());
		}

	switch (iState)
		{
		case EInitializeGetTokenList:
			// We need to try to get a list of Tokens for each of the Token Types
			iWorkingVars->iIndex++;
			TInt end;
			if (!iCurrentlyDoingReadOnly)
				{
				end = iWorkingVars->iWritableTokenTypes.Count();
				}
			else
				{
				end = iWorkingVars->iReadOnlyTokenTypes.Count();
				}
			if (iWorkingVars->iIndex < end)
				{
				assert(!iTokenType);
				TInt createRes = KErrNone;
				if (iCurrentlyDoingReadOnly)
					{
					TRAP(createRes, iTokenType = MCTTokenType::NewL(*iWorkingVars->iReadOnlyTokenTypes[iWorkingVars->iIndex], iFs));
					}
				else
					{
					TRAP(createRes, iTokenType = MCTTokenType::NewL(*iWorkingVars->iWritableTokenTypes[iWorkingVars->iIndex], iFs));
					}

				if (KErrNoMemory==createRes)
					{
					// Leave if there's no memory, so OOM tests work
					User::Leave(createRes);
					}
				else if (KErrNone!=createRes)
					{
					//	ECOM couldn't load that token type, don't give up, try the next...
					TRequestStatus* stat = &iStatus;
					User::RequestComplete(stat, KErrNone);
					}
				else
					{
					assert(iTokens.Count() == 0);
					iTokenType->List(iTokens, iStatus);
					iIndexTokens = -1;
					iState = EInitializeGetToken;
					}				   
				}
			else if (!iCurrentlyDoingReadOnly)
				{
				iCurrentlyDoingReadOnly = ETrue;
				iWorkingVars->iIndex = -1;
				TRequestStatus* status = &iStatus;
				User::RequestComplete(status, KErrNone);
				}
			else
				{
				iState = EInitializeFinished;
				TRequestStatus* status = &iStatus;
				User::RequestComplete(status, KErrNone);
				}
			SetActive();
			break;

		case EInitializeGetToken:
			if (iStatus.Int() == KErrHardwareNotAvailable) 
				{
				// If the hardware corresponding to this
				// TokenType has been removed then just skip it
				// but DO NOT leave!
				++iIndexTokens;
				iState = EInitializeGetToken;
				TRequestStatus* status = &iStatus;
				User::RequestComplete(status,KErrNone);
				}
            else 
				{
				User::LeaveIfError(iStatus.Int());

				// iIndexTokens is initialized at EInitializeGetTokenList
				++iIndexTokens;

				//	We need to try to get a certstore interface (readable or
				//	writable) for each of the Tokens in iTokens		
				if (iIndexTokens < iTokens.Count())
					{
                    assert(!iToken);
					iTokenType->OpenToken(*iTokens[iIndexTokens], iToken, iStatus);
					if ((iOpenedForWrite) && !iCurrentlyDoingReadOnly)
						{
						iState = EInitializeGetWritableInterface;
						}
					else
						{
						iState = EInitializeGetReadableInterface;
						}
					}
				else
					{
					// We don't need the iTokenType anymore
					iTokenType->Release();
					iTokenType = 0;
					// We don't need the list of Tokens anymore
					iTokens.Close();
					iState = EInitializeGetTokenList;
					TRequestStatus* status = &iStatus;
					User::RequestComplete(status, KErrNone);
					}
				}
			SetActive();
			break;

		case EInitializeGetWritableInterface:
			{
			User::LeaveIfError(iStatus.Int());
			// First we try to get a writable interface to the store, if
			// that doesn't work we will try to get a readable interface
            assert(iToken);
            assert(!iTokenInterface);
			TUid uid = { KInterfaceWritableCertStore };
			iToken->GetInterface(uid, iTokenInterface, iStatus);
			iState = EInitializeGetReadableInterface;
			SetActive();
			}
			break;

		case EInitializeGetReadableInterface:
			// We check if we managed to get a writable interface
			if (iStatus == KErrNoMemory)
				{
				User::Leave(KErrNoMemory);
				}
            
			if (!iCurrentlyDoingReadOnly && iOpenedForWrite && (iStatus == KErrNone))
				{
				assert(iTokenInterface);

				//	Drop the interface into a "writable checking" object
				CCheckedCertStore* interf = 
					CCheckedCertStore::NewCheckedWritableCertStoreL(iTokenInterface, iPSCertstoreChangeProperty);

                CleanupReleasePushL(*interf);
				iTokenInterface = 0;
				
				User::LeaveIfError(iWritableCertStores.Append(interf));
				CleanupStack::Pop();
				
				User::LeaveIfError(iCertStores.Append(interf));	
				
				// We don't need the Token anymore
				iToken->Release();
				iToken = 0;
				iState = EInitializeGetToken;
				TRequestStatus* status = &iStatus;
				User::RequestComplete(status, KErrNone);
				}
			else 
				{
				// We do the check only if we were not trying to get a Writeable Interface
				// before, if we trying to get a writeable interface before, we know that we
				// have a valid iToken.
				if ((iCurrentlyDoingReadOnly || !iOpenedForWrite) && (iStatus != KErrNone))
					{
					User::Leave(iStatus.Int());
					}
				else
					{
					assert(iToken);
                    assert(!iTokenInterface);
					TUid uid = { KInterfaceCertStore };
					iToken->GetInterface(uid, iTokenInterface, iStatus);
					iState = EInitializeGetReadableInterfaceFinished;
					}
				}
			SetActive();
			break;

		case EInitializeGetReadableInterfaceFinished:
			{
			if (iStatus == KErrNoMemory)
				{
				User::Leave(KErrNoMemory);
				}
            
			if (iStatus == KErrNone)
				{
				assert(iTokenInterface);

				//	Drop the interface into a "read only checking" object
                CCheckedCertStore* interf = 
						CCheckedCertStore::NewCheckedCertStoreL(iTokenInterface, iPSCertstoreChangeProperty);
				
				CleanupReleasePushL(*interf);
				iTokenInterface = 0;

				User::LeaveIfError(iReadOnlyCertStores.Append(interf));
				CleanupStack::Pop(interf);
                
				User::LeaveIfError(iCertStores.Append(interf));
				}			
				
			// We don't need the Token anymore
			iToken->Release();
			iToken = 0;
			
			iStatus = KErrNone;
			iState = EInitializeGetToken;
			TRequestStatus* status = &iStatus;
			User::RequestComplete(status, iStatus.Int());
			SetActive();
            }
			break;

		case EInitializeFinished:
            assert(!iTokenType);
            assert(!iToken);
            assert(!iTokenInterface);
			iIsInitialized = ETrue;
			Complete(iStatus.Int());
			break;

		case EList:
			// iIndex has been initialized in List
			iIndex++;
			iCurrentCertStore = NULL;
			if (iIndex < iCertStores.Count())
				{
				iCurrentCertStore = iCertStores[iIndex];
				iCurrentCertStore->List(*iWorkingVars->iCertInfos, *iWorkingVars->iFilter, iStatus);
				iWorkingVars->iCertIndex = 0;
				SetActive();
				}
			else if (iWorkingVars->iIssuerNames.Count() > 0)
				{
				// We have an issuer name. We now remove all certs
				// that don't match that issuer.

				// If this is the first time in here, we need to parse
				// and hash all the issuer names.
				if (iWorkingVars->iParsedIssuerNames.Count() == 0)
					{
					CSHA1* sha1 = CSHA1::NewL();
					CleanupStack::PushL(sha1);
					TInt count = iWorkingVars->iIssuerNames.Count();
					for (TInt i = 0; i < count; i++)
						{
						CX500DistinguishedName* dn = 
							CX500DistinguishedName::NewLC(*iWorkingVars->
														  iIssuerNames[i]);
						User::LeaveIfError(
							iWorkingVars->iParsedIssuerNames.Append(dn));
						CleanupStack::Pop(dn);
						TPtrC8 hash=sha1->Hash(*iWorkingVars->iIssuerNames[i]);
						User::LeaveIfError(
							iWorkingVars->iHashedIssuerNames.Append(
								hash.AllocLC()));
						CleanupStack::Pop();
						}
					CleanupStack::PopAndDestroy();
					}

				while (iWorkingVars->iCertIndex <
					   iWorkingVars->iCertInfos->Count())
					{
					CCTCertInfo* info = 
						(*iWorkingVars->iCertInfos)[iWorkingVars->iCertIndex];
					TCompareResults res = CompareCertInfoDN(info);
					if (res == EYes)
						{
						// It matches. leave it for the next one.
						iWorkingVars->iCertIndex++;
						}
					else if (res == ENo)
						{
						// It doesn't match. Remove it and try the next one.
						info->Release();
						iWorkingVars->iCertInfos->
							Remove(iWorkingVars->iCertIndex);
						}
					else // res == EMaybe
						{
						// Need to load the cert and properly compare the DNs.
						iCurrentCertStore = GetCertStore(info->Handle());
						assert(iCurrentCertStore);
						
						iWorkingVars->iCertDesC=HBufC8::NewMaxL(info->Size());
						iWorkingVars->iCertType = info->CertificateFormat();
						iState = ERetrieveForList;
						iWorkingVars->iCertDes.Set(iWorkingVars->iCertDesC->Des());
						iCurrentCertStore->Retrieve(*info, iWorkingVars->iCertDes, iStatus);
						SetActive();
						return;
						}
					}
				Complete(KErrNone);
				}
			else
				{
				Complete(KErrNone);
				}
			break;

	case ERetrieve:
		{
		switch (iWorkingVars->iCertType)
			{
            case EX509Certificate:
                {
                TPtr8 theCert(iWorkingVars->iCertDesC->Des());
                *(iWorkingVars->iReturnedCert) = CX509Certificate::NewL(theCert);
                }
                break;
            case EWTLSCertificate:
                {
                TPtr8 theCert(iWorkingVars->iCertDesC->Des());
                *(iWorkingVars->iReturnedCert) = CWTLSCertificate::NewL(theCert);			
                }
                break;
            default:
                assert(EFalse);
                break;
			}
		Complete(KErrNone);
		}
		break;

	case ERetrieveForList:
		{
		TPtr8 theCert(iWorkingVars->iCertDesC->Des());
		CX509Certificate* cert=CX509Certificate::NewLC(theCert);
		if (MatchL(cert->IssuerName()))
			{
			// It matches. leave it for the next one.
			iWorkingVars->iCertIndex++;
			}
		else
			{
			// It doesn't match. Remove it and try the next one.
			(*iWorkingVars->iCertInfos)[iWorkingVars->iCertIndex]->Release();
			iWorkingVars->iCertInfos->Remove(iWorkingVars->iCertIndex);
			}
		CleanupStack::PopAndDestroy(cert);
		delete iWorkingVars->iCertDesC;
		iWorkingVars->iCertDesC = 0;
		iState = EList;
		SetActive();
		TRequestStatus* status = & iStatus;
		User::RequestComplete(status, KErrNone);
		break;
		}
		
 	case ERemove:
 	case ESetApplicability:
 	case ESetTrust:
	case EGetCert:
	case EApplications:
	case EIsApplicable:
	case ETrusted:
	case ERetrieveData:
		Complete(KErrNone);
		break;

	default:
        User::Panic(KUCSPanic, 1);
		break;
		}
	}