void Cdmatest::SaveMappingsL()
    {
	TInt c( iMappingTable.Count() );
	if ( c > 0 )
	{
    	RFs fs;
    	User::LeaveIfError( fs.Connect() );
    	CleanupClosePushL( fs );
    	RFileWriteStream buf;
    	User::LeaveIfError( buf.Replace( fs, KMappingTableFile, EFileWrite ) );
    	CleanupClosePushL( buf );
		
		TInt i( 0 ) ;
		do 
			{
			buf.WriteUint32L( iMappingTable[i].iURI.Length() );
			buf.WriteL( iMappingTable[i].iURI );
			buf.WriteUint32L( iMappingTable[i].iLuid.Length() );
			buf.WriteL( iMappingTable[i].iLuid );
			}
		while ( ++i < c )	;
		buf.CommitL();
		buf.Close();
	
		CleanupStack::PopAndDestroy(); // buf
		CleanupStack::PopAndDestroy(); // fs
		}
    }
/**
@SYMTestCaseID			SYSLIB-SQL-CT-1635
@SYMTestCaseDesc		RSqlSecurityPolicy test.
						Tests RSqlSecurityPolicy API.
@SYMTestPriority		High
@SYMTestActions			RSqlSecurityPolicy test.
@SYMTestExpectedResults Test must not fail
@SYMREQ					REQ5792
                        REQ5793
*/
void SqlSecurityPolicyTest()
{
    RSqlSecurityPolicy securityPolicy;
    TInt err = securityPolicy.Create(KDefaultPolicy);
    TEST2(err, KErrNone);

    //Empty RSqlSecurityPolicy object tests
    //Database policies
    TSecurityPolicy policy = securityPolicy.DbPolicy(RSqlSecurityPolicy::ESchemaPolicy);
    TEST(policy == KDefaultPolicy);
    policy = securityPolicy.DbPolicy(RSqlSecurityPolicy::EReadPolicy);
    TEST(policy == KDefaultPolicy);
    policy = securityPolicy.DbPolicy(RSqlSecurityPolicy::EWritePolicy);
    TEST(policy == KDefaultPolicy);
    //Table policies
    policy = securityPolicy.Policy(RSqlSecurityPolicy::ETable, _L("A-Tbl"), RSqlSecurityPolicy::EReadPolicy);
    TEST(policy == KDefaultPolicy);
    policy = securityPolicy.Policy(RSqlSecurityPolicy::ETable, _L("B-Tbl"), RSqlSecurityPolicy::EWritePolicy);
    TEST(policy == KDefaultPolicy);
    //
    securityPolicy.Close();

    //Tests with initialized RSqlSecurityPolicy object
    CreateTestSecurityPolicy(securityPolicy);
    //Check the created and initialized object
    CheckTestSecurityPolicy(securityPolicy);

    //Externalize, then internalize and check the security policy object
    RFileWriteStream out;
    err = out.Replace(TheFs, KTestFile, EFileRead | EFileWrite);
    TEST2(err, KErrNone);
    TRAP(err, securityPolicy.ExternalizeL(out));
    TEST2(err, KErrNone);
    TRAP(err, out.CommitL());
    out.Close();
    TEST2(err, KErrNone);

    securityPolicy.Close();
    err = securityPolicy.Create(KDefaultPolicy);
    TEST2(err, KErrNone);
    RFileReadStream in;
    err = in.Open(TheFs, KTestFile, EFileRead);
    TEST2(err, KErrNone);
    TRAP(err, securityPolicy.InternalizeL(in));
    in.Close();
    TEST2(err, KErrNone);
    CheckTestSecurityPolicy(securityPolicy);

    //Change some security policies and check that the RqlSecurityPolicy content was properly updated
    err = securityPolicy.SetPolicy(RSqlSecurityPolicy::ETable, KTableName11, RSqlSecurityPolicy::EReadPolicy, KPolicy3);
    TEST2(err, KErrNone);
    policy = securityPolicy.Policy(RSqlSecurityPolicy::ETable, KTableName1, RSqlSecurityPolicy::EReadPolicy);
    TEST(policy == KPolicy3);
    policy = securityPolicy.Policy(RSqlSecurityPolicy::ETable, KTableName11, RSqlSecurityPolicy::EWritePolicy);
    TEST(policy == KPolicy2);
    //
    securityPolicy.Close();
}
// ----------------------------------------------------------------------------
// CAudioStreamEngine::SaveAudioFileL()
//
// saves the audio data in the buffer into a file
// ----------------------------------------------------------------------------
void CAudioStreamEngine::SaveAudioFileL()
    {
    if (!iBufferOK)
    {
        // In case the encoding was changed between recording and trying to save the file
        ShowMessage(_L("CAudioStreamEngine::SaveAudioFileL() Recorded buffer does not match current encoding."), ETrue);   
        ShowMessage(_L("CAudioStreamEngine::SaveAudioFileL() Please re-record and try again."), EFalse); 
        return;
    }
    RFileWriteStream audiofile;

    // Check for free space for saving the sample
    TVolumeInfo volinfo;
    TInt err=iFs.Volume(volinfo,EDriveC);
    if ( volinfo.iFree<(iFrameCount*iFrameSize))
        {
        // Not enough free space on drive for saving, report and exit
        ShowMessage(_L("CAudioStreamEngine::SaveAudioFileL() Cannot save file:\nnot enough space!"), ETrue); 
        return;
        }

    TFileName fileName;
    fileName.Copy(iAudioFilePath);
    fileName.Append(iAudioFile);
    err = audiofile.Replace(iFs, fileName, EFileWrite|EFileStream);
    if (err==KErrNone) 
        {
        if (iUseAMR)
            {
                // Write the six-byte AMR header, so that the file can be used by other
                // applications as well.
                for (int i = 0; i < KAMRHeaderLength; i++)
                    audiofile.WriteUint8L(KAMRNBHeader[i]);
            }
            
        // File opened ok, proceed writing.
        // Write audio data directly from iStreamBuffer
        for (TUint idx=iStreamStart; idx<=iStreamEnd; idx++)//iFrameCount; idx++)
            {
            audiofile.WriteL(GetFrame(idx));
            }
        ShowMessage(_L("CAudioStreamEngine::SaveAudioFileL() Saving complete!"), ETrue); 
        }   
    else 
        {
        // failed to open file
        ShowMessage(_L("CAudioStreamEngine::SaveAudioFileL() Error saving audio sample!"), ETrue); 
        }
    audiofile.Close();
    }
/**
 Overload of the CCoeAppUi virtual method.
 The method in the base class merely returns ETrue. Overloads would normally just return EFalse.
 In this case however, we do some jiggery-pokery in order to invoke the StartSafe retry mechanism.
 ie we return EFalse on each of several invocations but don't do the Rendezvous, then 
 eventually ETrue, so the Framework Rendezvous for us. our final invocation therefore being successful.
 
 The count file is written from the test-step, and 
 if successful, deleted here.
 
 The code is nearly all parenthesised within a TRAP harness in order to preserve the integrity 
 of this function, which is called by the framework.

*/
TBool CTestAppUi::FrameworkCallsRendezvous() const
	{
	
	TBool frameworkRendezvous = EFalse;

	TRAPD( err,
		{			
		RFs fs;
		RFileReadStream readStream;
		RFileWriteStream writeStream;
						
		CleanupClosePushL( fs );
		CleanupClosePushL( readStream );
		CleanupClosePushL( writeStream );
		
			
		if( KErrNone != fs.Connect()
		 || KErrNone != readStream.Open(fs, KDontRvCountFile, EFileRead) )
			{
			User::Leave( KErrCouldNotConnect );	
			}
		

		TInt failCount = readStream.ReadInt8L();
		readStream.Close();	
		

		if( 0 == failCount )
			{
			fs.Delete( KDontRvCountFile );
			
			// We've decided to be good this time. Let the framework do it for us.
			frameworkRendezvous = ETrue;
			}
		else
			{
			// StartSafe will timeout while waiting for a Rendezvous()
			User::LeaveIfError( writeStream.Open(fs, KDontRvCountFile, EFileWrite) );
	
			writeStream.WriteInt8L( --failCount );
			writeStream.CommitL();
			writeStream.Close();
			}
			
		CleanupStack::PopAndDestroy( 3, &fs );
		} );
/**
 Start a test application synchronously using Wait-for-Signal with timeout
 more than the time required for the application to start and which starts after the no. of retries given.
*/
void CSsTestStepAppTimeout::DoTestWaitForSignalWithMoreTimeOutAndWithRetriesL()
	{	
	INFO_PRINTF1(_L("Performing Wait-for-Signal test with timeout and retries"));

	// Write the retry number to a file to be read, updated 
	// and eventually deleted by the test-app.
	RFs fs;	
	CleanupClosePushL( fs );
	
	RFileWriteStream writeStream;
	CleanupClosePushL( writeStream );

	User::LeaveIfError(fs.Connect());
	User::LeaveIfError(writeStream.Replace(fs, KFileForFAndF, EFileWrite));

	const TInt KSsTestRequiredDelay = 0;
	const TInt KSsTestFailCount = 1;
	const TInt KSsTestRetryCount = 0;
	writeStream.WriteInt8L(KSsTestRetryCount);
	writeStream.WriteInt8L(KSsTestFailCount);
	writeStream.WriteInt8L(KSsTestRequiredDelay);
	writeStream.CommitL();
	writeStream.Close();
	
	const TInt KRetries = KSsTestFailCount + 1;
	TInt completionCode = DoTestAndStopperL(KRetries, KWaitTimeForTestAppForFAndF * 3, KTestAppForFAndF);
	TEST(completionCode == 0);
	
	INFO_PRINTF2( _L("Anticipated completion code 0. Supplied completion code %d"),completionCode);
	RFileReadStream readStream;
	CleanupClosePushL(readStream);

	User::LeaveIfError(readStream.Open(fs, KFileForFAndF, EFileRead));
	TInt retryCount = readStream.ReadInt8L();
	readStream.Close();	
	fs.Delete(KFileForFAndF);

	CleanupStack::PopAndDestroy(3, &fs);

	TEST(1 == FindAndKill(KTestAppForFAndF));
	TEST(retryCount == 1);

	INFO_PRINTF3( _L("ssmtestappsucessfulafterretry.exe is started after %d retries. anticipated retries value %d"),retryCount, 1);
	}
void VersitExportContactL(const TDesC& aExportFileName)
{
    RFileWriteStream writeStream;
    User::LeaveIfError(writeStream.Replace(fsSession, aExportFileName, EFileWrite));
    CleanupClosePushL(writeStream);
    
    CContactIdArray* idArray = CContactIdArray::NewLC();
    TInt count = CntTest->Db()->CountL();
	test(count == 1);
    TContactItemId contactId = CntTest->Db()->GetCurrentItem();
    
    idArray->InsertL(0, contactId);
    
    CntTest->Db()->ExportSelectedContactsL(TUid::Uid(KUidVCardConvDefaultImpl), *idArray, writeStream,0);
    writeStream.Close();
    
	CleanupStack::PopAndDestroy(2); //idArray, writeStream
	                                                                     
    	
}
void TTcSettings::Store()
	{
	// Connect to file server
	RFs fs;
	if( fs.Connect() )
		{
		return;
		}

	// Open the settings file for writing, replace any existing data
	RFileWriteStream out;
	if( !out.Replace( fs, KTcSettingsFile, EFileWrite ) )
		{
		// Write actual data, ignore errors
		TRAP_IGNORE( doStoreL( out ) )
		}

	out.Close();
	fs.Close();
	}
void CTestImpExvCardSuiteStepBase::ExportItemL(TBuf<80> aPath, TBool aAddBDay)
	{
	OpenDBL();
	
	TContactItemId itemId;
	RFs fsSession;
	RFileWriteStream fileStream;

	CContactIdArray* idArray = NULL;
	CContactCard* contactAdded = NULL;
	TTime now;
	
	User::LeaveIfError(fsSession.Connect());
	CleanupClosePushL(fsSession);
	
	idArray = CContactIdArray::NewL();

	CleanupStack::PushL(idArray);   // idArray

	fsSession.MkDirAll(aPath);
	User::LeaveIfError(fileStream.Replace(fsSession, aPath, EFileWrite));

	contactAdded = CContactCard::NewL();

	CleanupStack::PushL(contactAdded);   // contactAdded
	
	contactAdded->IncAccessCount();
	
	// ADD BDAY
	if (aAddBDay)
		{
		CContactItemFieldSet& fieldSet=contactAdded->CardFields();
		const TInt pos=fieldSet.Find(KUidContactFieldBirthday);
	
		if (pos!=KErrNotFound)
			{
			fieldSet[pos].DateTimeStorage()->SetTime(iBDayLocal);
			}
		else
			{
			CContactItemField* field=CContactItemField::NewLC(KStorageTypeDateTime,KUidContactFieldBirthday);
   			field->SetMapping(KUidContactFieldVCardMapBDAY);
			field->DateTimeStorage()->SetTime(iBDayLocal);
			contactAdded->AddFieldL(*field);
	
			CleanupStack::Pop(); // field
			}
		}
	
	SetNameL(*contactAdded, KUidContactFieldGivenName, _L("toby"), ETrue);
	SetNameL(*contactAdded, KUidContactFieldPhoneNumber, _L("6041233214"), ETrue);

	User::After(3000000);

	// There is no need to call SetLastModifed because
	// That function will be call by ExportSelectedContactsL below
	now.UniversalTime();
	iRecordedTime = now;
	
	INFO_PRINTF1(_L("Adding contact to Database....."));
	itemId = iDb->AddNewContactL(*contactAdded);
	INFO_PRINTF1(_L("Contact Added to Database"));
	CleanupStack::PopAndDestroy(contactAdded);  // contactAdded
	contactAdded = NULL;

	idArray->InsertL(0, itemId);

	INFO_PRINTF1(_L("Exporting Contact....."));
	iDb->ExportSelectedContactsL(TUid::Uid(KUidVCardConvDefaultImpl), *idArray, fileStream, CContactVCardConverter::EDefault, ETrue);
	INFO_PRINTF1(_L("Exported Contact"));
	fileStream.CommitL();
	fileStream.Close();
	
	CleanupStack::PopAndDestroy(idArray);  // idArray
	fsSession.Close();
	CleanupStack::PopAndDestroy();  // fsSession
	CloseDB();
	}
// ---------------------------------------------------------------------------
// CLbtCleanupHandler::WriteCleanupDataToFileL
// ---------------------------------------------------------------------------
//
void CLbtCleanupHandler::WriteCleanupDataToFileL()
	{
	FUNC_ENTER("CLbtCleanupHandler::WriteCleanupDataToFileL");	
	
	RFs fs;
	User::LeaveIfError( fs.Connect() );
	
	CleanupClosePushL( fs );
    
    // Obtain the file path
    TFileName file;
    
    // Gets the path in which the file can be created
    fs.SessionPath(file);

    // Create the file Directory ie the private directory of the process
    fs.MkDirAll(file);
    
    // Append the name of the file
    file.Append(KLbtAppCleanupFileName);
    
    // Open write stream to write to the file
    RFileWriteStream writeStream;
    
    // Open the file to replace the contents. If the file is not preset
    // this method will create the file
    TInt error = writeStream.Replace( fs, file, EFileWrite );    
    if( error != KErrNone )
    	{
    	ERROR("Opening of cleanup file failed with : %d", error);
    	writeStream.Close();
    	CleanupStack::PopAndDestroy(); //fs
    	User::Leave(error);
    	}
    CleanupClosePushL( writeStream );
    
    // First write the number of cleanup items
    writeStream.WriteInt16L( iCleanupItems.Count() );

	for(TInt i=0;i<iCleanupItems.Count();++i)
		{
		RArray<TLbtTriggerId>& triggers = iCleanupItems[i]->GetTriggers();
		
		// Write the trigger ids into the file
		writeStream.WriteInt16L( triggers.Count() );
		for(TInt j=0;j<triggers.Count();++j)
			{
			writeStream.WriteUint32L( triggers[j] );
			}
		
		// Write the time into the file
		const TDateTime dateTime = iCleanupItems[i]->GetTime().DateTime();
		
		// Write the year
		writeStream.WriteInt32L( dateTime.Year() );
		
		// Write the month
		writeStream.WriteInt32L( dateTime.Month() );
		
		// Write the day
		writeStream.WriteInt32L( dateTime.Day() );
		}
    
    CleanupStack::PopAndDestroy(2); //fs and writeSteam    
	}
void CTestContactsPBAPExport::ExportContactsL()
	{
	TInt err = KErrNone;
	// Retrieve the file name to which contact item is to be exported
   	RFs fsSession;
	RFileWriteStream writeStream;

	// connect to file system
	User::LeaveIfError(fsSession.Connect());
	CleanupClosePushL(fsSession);

	GetInputFromIni();

   	// Makes one or more directories.
   	fsSession.MkDirAll(iExportTo);

	// Replaces a single file with another
	User::LeaveIfError(writeStream.Replace(fsSession, iExportTo, EFileWrite));

	INFO_PRINTF1(_L("Exporting Contact....."));

	// Existing database
   	TPtrC databaseFile(_L("C:contactDb.cdb"));

	CContactDatabase* dBase = NULL;
	CContactIdArray* idArray = NULL;

	// Open the existing database
	dBase = CContactDatabase::OpenL(databaseFile);
	CleanupStack::PushL(dBase);

	// Create Utility class object, to export the contact from database
	CTestStep* self = static_cast<CTestStep*>(this);
	iExportObj = new(ELeave) CContactsPBAPExportUtilityClass(self);

	SetFilterL();

	CCntFilter* exportFilter = CCntFilter::NewL();
	CleanupStack::PushL(exportFilter);

	// Get all the contacts from the database to export
	exportFilter->SetContactFilterTypeCard(ETrue);
	dBase->FilterDatabaseL(*exportFilter);
	idArray = exportFilter->iIds;
	CleanupStack::PushL(idArray);

	if(iDamageDb)
		{
		#ifdef _DEBUG
		#ifndef __SYMBIAN_CNTMODEL_USE_SQLITE__
		TRAPD(err1,dBase->DamageDatabaseL(0x666));
		if(err1 == KErrNone)
			{
			TRAPD(err,iExportObj->ExportvCardL(dBase, iStandard, idArray, writeStream, iContactFilter));
			INFO_PRINTF2(_L("Err:%d"),err);
			if(err == KErrNotReady)
				{
				SetTestStepResult(EPass);
				}
			else
				{
				SetTestStepResult(EFail);
				}
			if(dBase->IsDamaged())
				{
				dBase->RecoverL();
				}
			}
		else
			{
			INFO_PRINTF2(_L("Could not damage database Err:"),err1);
			}
		#else
			SetTestStepResult(EPass);
		#endif
		#endif
		}
    else
	    {
	    if(iInvalidFileSystem)
		    {
		    #ifdef _DEBUG
		    fsSession.SetErrorCondition(KErrNotReady);
		    TRAPD(err,iExportObj->ExportvCardL(dBase, iStandard, idArray, writeStream, iContactFilter));
			if(err == KErrNotReady)
				{
				SetTestStepResult(EPass);
				}
			else
				{
				SetTestStepResult(EFail);
				}
			fsSession.SetErrorCondition(KErrNone);
			#endif
			}
	    else
			{
			if(!iSetOOM)
				{
				if(idArray->Count() > 0)
					{
					for(TInt i=0; i<idArray->Count() ; i++)
						{
						TInt dCount = dBase->CountL();
						if(i>=dCount)
							{
							break;
							}

						// temporary array used to export one contact at a time
						CContactIdArray* tempIdArray = CContactIdArray::NewL();
						CleanupStack::PushL(tempIdArray);
						tempIdArray->AddL((*idArray)[i]);
						TRAPD(err,iExportObj->ExportvCardL(dBase, iStandard, tempIdArray, writeStream, iContactFilter));

						if(err != KErrNone )
							{
							if(err != KErrNotFound)
								{
								SetTestStepError(err);
								}
							}

						CleanupStack::PopAndDestroy(tempIdArray);
						}
					}
				else
					{
					if(idArray->Count()==0)
						{
						TRAPD(err,iExportObj->ExportvCardL(dBase, iStandard, idArray, writeStream, iContactFilter));
						if(err != KErrNone)
							{
							SetTestStepError(err);
							}
						}
					}

				}
			else
				{
				TInt tryCount = 1;
				for ( ;; )
					{
					__UHEAP_SETFAIL(RHeap::EDeterministic, tryCount);
					TRAP(err, iExportObj->ExportvCardL(dBase, iStandard, idArray, writeStream, iContactFilter));

					if ( err == KErrNone )
						{
						__UHEAP_RESET;
						INFO_PRINTF1(_L("OOM testing of CContactDatabase::ExportSelectedContactsL Api is done"));
						break;
						}
					if ( err != KErrNoMemory )
						{
						INFO_PRINTF2(_L("The unexpected error code is:%d"),err);
						SetTestStepResult(EFail);
						break;
						}
					__UHEAP_SETFAIL(RHeap::ENone, 0);
					tryCount++;
					}
				}
			}
	    }

	CleanupStack::Pop(idArray);
	CleanupStack::PopAndDestroy(exportFilter);

	INFO_PRINTF1(_L("Exported Contact"));
	writeStream.CommitL();
	writeStream.Close();

	INFO_PRINTF2(_L("Total number of contacts in database %d "), dBase->CountL());

	// Cleanup
	CleanupStack::PopAndDestroy(dBase);
    CleanupStack::PopAndDestroy(&fsSession);
	}