TInt CSenBaseIdentityManager::WriteConfigurationToL( const TDesC& aFile )
    {
    // First, collect everything into MEMORY
    CBufFlat *pBuf = CBufFlat::NewL(KFLATBUF_SIZE);
    CleanupStack::PushL(pBuf);

    RBufWriteStream bufWs(*pBuf);
    CleanupClosePushL(bufWs);

    bufWs.WriteL(KUsersStart);

    if(iIdentity)
        {
        iIdentity->WriteAsXMLToL(bufWs);
        }

    bufWs.WriteL(KUsersEnd);

    TPtrC8 p8 = pBuf->Ptr(0);

    CleanupStack::PopAndDestroy(1); // bufWs

    // Everything in MEMORY ok, prepare to write into file
    RFs fss;
    User::LeaveIfError(fss.Connect());
    CleanupClosePushL(fss);

    RFileWriteStream fileOutStream;
    CleanupClosePushL(fileOutStream);


    if(!SysUtil::FFSSpaceBelowCriticalLevelL(&fss, p8.Length()) )
        {
        // note, this will zero-length the file(!)
        // it is better to require that 2xfilesize is available and not to
        // dangerously zero the old file and find out
        // that there is no space left..

        //Data caging 2 implementation
#if defined( EKA2 ) || defined( RD_SECURE_PRIV_DATA )
        TBuf<KMaxPath> file;
        fss.CreatePrivatePath(EDriveC);
        fss.PrivatePath(file);
        file.Append(aFile);
        fileOutStream.Replace(fss, file, EFileWrite);
#else
        fileOutStream.Replace(fss, aFile, EFileWrite);
#endif
        // finally write the UTF-8 into the file. 
        fileOutStream.WriteL(p8);
        }

    CleanupStack::PopAndDestroy(3); // fileOutStream, fss, pBuf

    return KErrNone;
    }
/**
exports all contacts items in db to vcard file, if aDelete, cleans database afterwards
*/
void CPerformanceFunctionalityBase::ExportVcardL(const TBool aDelete, const TDesC &aVCard)
	{
	iIterate->Reset();
	CContactIdArray *ids = CContactIdArray::NewLC();
	TInt i = 0;
	for(; i < iContacts; ++i)
		{
		ids->AddL( iIterate->NextL() );
		}

	RFileWriteStream rfws;
	CleanupClosePushL(rfws);
	User::LeaveIfError( rfws.Replace( iParent->Fs(),aVCard , EFileWrite | EFileShareAny ) );

	iContactsDatabase->ExportSelectedContactsL(	TUid::Uid(KUidVCardConvDefaultImpl), *ids, rfws,
										CContactDatabase::EIncludeX | CContactDatabase::ETTFormat );

	CleanupStack::PopAndDestroy(&rfws);
	if( aDelete )
		{
		CLEAR( iContactsDatabase );
		iContactsDatabase = CContactDatabase::ReplaceL();
		}
	CleanupStack::PopAndDestroy(ids);
	}
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-STORE-CT-1127
@SYMTestCaseDesc	    Stream encryption test.
                        Tests the functionality of REncryptStream and RDecryptStream classes
@SYMTestPriority 	    High
@SYMTestActions  	    Tests for writing an encrypted string to a stream,reading back the data,decrypt and
                        check with the original data.
@SYMTestExpectedResults Test must not fail
@SYMREQ                 REQ0000
*/
LOCAL_C void testSimpleStreamEncryptionL()
    {
	test.Next(_L(" @SYMTestCaseID:SYSLIB-STORE-CT-1127 "));
   	CPBEncryptElement* elementKey = CPBEncryptElement::NewL(KTestPassword);
	CleanupStack::PushL(elementKey);
	TParsePtrC parse(KFileLocationSpec);
	
	RFileWriteStream writeStream;
    writeStream.PushL();
    User::LeaveIfError(writeStream.Replace(TheFs, parse.NameAndExt(), EFileWrite));

	REncryptStream encryptStream;
	encryptStream.OpenLC(writeStream, *elementKey);

    encryptStream << KTestDes;
    encryptStream.CommitL();
    writeStream.CommitL();
    CleanupStack::PopAndDestroy(2); // encryptStream, writeStream

    RFileReadStream readStream;
    readStream.PushL();
    User::LeaveIfError(readStream.Open(TheFs, parse.NameAndExt(), EFileWrite));

    RDecryptStream decryptStream;
	decryptStream.OpenLC(readStream, *elementKey);

    decryptStream >> TheBuf;

    test(KTestDes == TheBuf);

    CleanupStack::PopAndDestroy(3, elementKey); // decryptStream, readStream
    }
Exemple #5
0
//存档
void TPlayerInfo::WriterPlayerInfo()
{
    RFs oFs;
    if (oFs.Connect())
    {
        return;
    };
    RFileWriteStream oWriteStream;
    if (oWriteStream.Replace(oFs, *iFileName, EFileWrite))
    {
        oFs.Close();
        return;
    };
    oWriteStream.PushL();
    TInt32 playerCount = AWARD_PLAYER_COUNT;
    oWriteStream << playerCount;
    for (TInt i = 0; i < playerCount; i++)
    {
        if (i < AWARD_PLAYER_COUNT)
        {
            //iPlayerArray[i].ExternalizeL(oWriteStream);
            iPlayerList[i]->ExternalizeL(oWriteStream);
        }
    }
    oWriteStream.CommitL();
    oWriteStream.Pop();
    oWriteStream.Release();
    oFs.Close();
}
/**
@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();
}
/**
 ssmtestapprvafterretry.exe is eventually invoked successfully. SsmStartSafe is configured to
 make 1 + retries attempts to start the recalcitrant app. The app is configured to start
 after retries attempts
*/
void CSsTestStepAppStart::DoTestAppStartWithRetriesL()
{
    INFO_PRINTF1( _L("\nStart recalcitrant app with 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 );

    if( KErrNone != fs.Connect()
            || KErrNone != writeStream.Replace(fs, KDontRvCountFile, EFileWrite) )
    {
        User::Leave( KErrCouldNotConnect );
    }
    const TInt KSsTestDontRvCount = 4;
    writeStream.WriteInt8L( KSsTestDontRvCount );
    writeStream.CommitL();

    CleanupStack::PopAndDestroy( 2, &fs );
    //


    const TInt KRetries = KSsTestDontRvCount + 1;
    CSsmStartupProperties* startupProperties_0 = CSsmStartupProperties::NewL();
    CleanupStack::PushL( startupProperties_0 );

    startupProperties_0->SetFileParamsL( KTestAppRvAfterRetry, KNullDesC );
    startupProperties_0->SetCommandTypeL( ESsmCmdStartApp );
    startupProperties_0->SetExecutionBehaviour( ESsmWaitForSignal );
    startupProperties_0->SetRetries( KRetries );
    // For each retry KTestAppRvAfterRetry takes 2secs
    startupProperties_0->SetTimeout( KSsTestAppStartTimeout*1.5 );

    RProcess process;
    TInt id_0 = 0;

    CStartAcknowledge* ack_0 = new(ELeave) CStartAcknowledge( this );
    CleanupStack::PushL( ack_0 );

    CSsmStartSafe* ss  = CSsmStartSafe::NewLC();
    ss->Start(*startupProperties_0, process, ack_0->iStatus, id_0);


    CAsPauseStopper* pauseStopper = new(ELeave) CAsPauseStopper( KSsAsStopperNominalTimeout * 10 );
    CleanupStack::PushL( pauseStopper );
    CActiveScheduler::Start();
    process.Close();

    TEST( ack_0->iStatus == KErrNone );

    CleanupStack::PopAndDestroy( 4, startupProperties_0 );

    TEST( 1 == FindAndKill(KTestAppRvAfterRetry) );
}
void CRequestManager::SaveConfigInfoL()
	{
	FLOG(_L("[IMAGEPRINTUI]<<< CEventManager;SaveConfigInfoL "));
	RFileWriteStream stream;
  	CleanupClosePushL(stream);
	if((stream.Replace(CCoeEnv::Static()->FsSession(),iCongFileName->Des() ,EFileWrite)) == KErrNone)
		{
		ExternalizeL(stream);
		}
	CleanupStack::PopAndDestroy(&stream);
	}
Exemple #9
0
void CAccessCountTests::ExportVcardL(const CContactIdArray &aConids)
	{	
	RFileWriteStream rfws;
	CleanupClosePushL(rfws);
	User::LeaveIfError( rfws.Replace( iParent->Fs(), KVcardFile, EFileWrite | EFileShareAny ) );
	
	iContactsDatabase->ExportSelectedContactsL(	TUid::Uid(KUidVCardConvDefaultImpl), aConids, rfws,
										CContactDatabase::EIncludeX | CContactDatabase::ETTFormat );
	
	CleanupStack::PopAndDestroy(&rfws);		
	}	
// ----------------------------------------------------------------------------
// 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();
    }
// -----------------------------------------------------------------------------
// CDRMHelperServer::StoreL().
// This function store internal list into data file
// -----------------------------------------------------------------------------
//
void CDRMHelperServer::StoreL()
    {

#ifdef _DRM_TESTING
    WriteL(_L8("StoreL"));
#endif

    RFileWriteStream file;
    User::LeaveIfError(file.Replace( iFs , DataFileL(iFs).FullName() , EFileWrite ));
    file.PushL();
    ExternalizeL(file);
    file.CommitL();
    CleanupStack::PopAndDestroy(&file);//file
    }
void ExportEntriesL(RPointerArray<CCalEntry>& aCalEntries, const TDesC& aFileName)
    {
    TEntry dirEntry;
    
    // Create a directory if not present
    if (calTestLibrary->FileSession().Entry(KWriteDataDir(), dirEntry) != KErrNone)
        {
    	calTestLibrary->FileSession().MkDir(KWriteDataDir());
        }
	RFileWriteStream fileWriteStream;
	CleanupClosePushL(fileWriteStream);
	User::LeaveIfError(fileWriteStream.Replace(calTestLibrary->FileSession(), aFileName, EFileWrite));
	calTestLibrary->DataExchangeL().ExportL(KUidVCalendar, fileWriteStream, aCalEntries);
	
	CleanupStack::PopAndDestroy(&fileWriteStream);
    }
/**
 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 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 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
	                                                                     
    	
}
//////////////////////////////////////////////////////////////////////////////////
//	Test fix for INC023303: CX509Certificate externalize - internalize don't work 
//////////////////////////////////////////////////////////////////////////////////
void CSyntaxTest::TestInternalizeExternalizeL(CX509Certificate* aCert)
	{
	RFileWriteStream newwriter;
	newwriter.PushL();
	User::LeaveIfError(newwriter.Replace(iFs,_L("x509stream"),EFileStream));
	
	aCert->ExternalizeL(newwriter);
	newwriter.CommitL();
	CleanupStack::PopAndDestroy(1);//newwriter
	
	RFileReadStream newreader;
	newreader.PushL();
	newreader.Open(iFs,_L("x509stream"),EFileStream);
	CX509Certificate* readCert=CX509Certificate::NewLC(newreader); //Use the stream to create new cert

	if (!readCert->IsEqualL(*aCert))
		User::Leave(KErrGeneral);

//	iFs.Delete(_L("x509stream"));
	CleanupStack::PopAndDestroy(2);	//	readCert, newreader
	}
/**
  Write the results to the result file, to be later extracted by
  testexecute test case.
  These contain the results of the individual tests. The order in
  which these results are written in MUST match the order in which
  they are read and tested in CSysStartApparcTestStep::GetApparcResultsL()
  and the expected result tested in CSysStartApparcTestStep::Testxxx must
  match that in the test specification\n

  The format is:
  StartApp1LRes1 count=value1
  StartApp1LRes2 count=value2

  '=' is used as the deliminator.
*/
void CSysStartApparcTestCase::WriteResultFileL()
	{
	RFs	fs;
 	User::LeaveIfError(fs.Connect());
 	CleanupClosePushL(fs);

	RFileWriteStream writer;
	User::LeaveIfError(writer.Replace(fs, KSsaacResultFile, EFileWrite));
	CleanupClosePushL(writer);

	// write data to file
	writer << _L("StartApp1LRes1 count=");
	writer.WriteInt16L(iStartApp1LRes1);
	writer << _L("\n");
	writer << _L("StartApp1LRes2 count=");
	writer.WriteInt16L(iStartApp1LRes2);
	writer << _L("\n");

	writer.CommitL();
	CleanupStack::PopAndDestroy(2, &fs);
	}
/**
@SYMTestCaseID          PDS-STORE-CT-4042
@SYMTestCaseDesc	    Tests for attaching write stream and read stream to an encrypted stream.
@SYMTestPriority 	    High
@SYMTestActions  	    Encrypt data and write to a store.Read the encrypted data for decrypting and compare the result.
@SYMTestExpectedResults Test must not fail
@SYMDEF                 DEF135804
*/
LOCAL_C void testEncryptionDataAttachL()
	{
	test.Next(_L(" @SYMTestCaseID:PDS-STORE-CT-4042 "));
	CPBEncryptElement* elementKey = CPBEncryptElement::NewLC(KTestPassword);
	TParsePtrC parse(KFileLocationSpec);
	
	RFileWriteStream writeStream;
	writeStream.PushL();
	User::LeaveIfError(writeStream.Replace(TheFs, parse.NameAndExt(), EFileWrite));
	
	REncryptStream encryptStream;
	TRAPD(ret, encryptStream.AttachL(writeStream, *elementKey));
	test(ret == KErrNone);
	encryptStream.PushL();
	
	encryptStream << KTestDes;
	encryptStream.CommitL();
	writeStream.CommitL();
	
	CleanupStack::PopAndDestroy(2); // encryptStream, writeStream
	
	const CPBEncryptionData& encryptData = elementKey->EncryptionData();
	
	CPBEncryptElement* newElementKey = CPBEncryptElement::NewLC(encryptData, KTestPassword);
	
	RFileReadStream readStream;
	readStream.PushL();
	User::LeaveIfError(readStream.Open(TheFs, parse.NameAndExt(), EFileWrite));
	
	
	RDecryptStream decryptStream;
	decryptStream.AttachL(readStream, *newElementKey);
	decryptStream.PushL();
	
	decryptStream >> TheBuf;
	
	test(KTestDes == TheBuf);
	
	CleanupStack::PopAndDestroy(4, elementKey);
	}
void CHttpCacheManager::GenerateEmptyIndexFileL(const TDesC& aIndexFile, RFs& aRfs )
    {
    // Going to remove non-web client cache files in OrphanedFilesL call,
    // Signal to these clients by emptying (or creating) an 'empty' index file
    // do this before we start cleaning up files, to lessen the chances that any
    // of the files are in use when we're trying to delete them.
    
    // 'adopt' code from httpcachelookuptable for dealing with indexes.
    // save entries to index.dat
    RFileWriteStream writeStream;

    TInt ret = KErrNone;
    TInt tryCount = 0;
    for (tryCount = 0; tryCount < 5; tryCount++) 
        {
        ret = writeStream.Replace( aRfs, aIndexFile, EFileWrite );
        if (ret == KErrInUse)
            {
            // When the cache is full, it takes 65 - 85 miliseconds to write the index.
            // So wait 50 miliseconds and try again
            User::After(50000);
            }
        else
            {
            break;
            }
        }
    if( ret == KErrNone )
        {
        CleanupClosePushL( writeStream );
        writeStream.WriteInt32L( KCacheVersionNumber );
        writeStream.WriteInt32L( 0 ); // no entries in the index.
        writeStream.CommitL();
        CleanupStack::PopAndDestroy(); // writeStream
        }
    }
// ---------------------------------------------------------------------------
// 
// ---------------------------------------------------------------------------
//    
void CNcdProviderUtils::WriteDatabaseVersionsL(
    const TDesC& aRootPath,
    TUint32 aGeneralVersion,
    TUint32 aPurchaseHistoryVersion )
    {
    DLTRACEIN(("Writing versions, general: %d, purchase history: %d",
        aGeneralVersion, aPurchaseHistoryVersion ));

    RBuf path;
    
    AppendPathsLC( 
        path, 
        aRootPath, 
        NcdProviderDefines::KNcdDatabaseVersionFile );
        
    RFileWriteStream stream;
    CleanupClosePushL( stream );
    User::LeaveIfError( stream.Replace( FileSession(),
        path, EFileWrite ) );
    stream.WriteUint32L( aGeneralVersion );
    stream.WriteUint32L( aPurchaseHistoryVersion );
    CleanupStack::PopAndDestroy( 2, &path );
    DLTRACEOUT(("Versions successfully written"));
    }
TBool CDiscussion::WriteDiscussionToFileL() {
	TPtr pId(iDiscussionId->Des());
	
	if(iDiscussionInMemory && pId.Length() > 0) {
		RFs aSession = CCoeEnv::Static()->FsSession();	
		TFileName aFilePath = GetFileName(aSession);

		RFileWriteStream aFile;
		TBuf8<128> aBuf;
		
#ifdef _DEBUG
		if(iDiscussionReadObserver) {
			aBuf.Format(_L8("DISC  Start: Save discussion %d to file"), iItemId);
			iDiscussionReadObserver->DiscussionDebug(aBuf);
		}
#endif
	
		if(aFile.Replace(aSession, aFilePath, EFileStreamText|EFileWrite) == KErrNone) {
			CleanupClosePushL(aFile);

			CXmppAtomEntryParser* aAtomEntryParser = CXmppAtomEntryParser::NewLC();
			
			aFile.WriteL(_L8("<?xml version='1.0' encoding='UTF-8'?>\r\n"));		
			aBuf.Format(_L8("\t<discussion notify='%d'>\r\n"), iNotify);
			aFile.WriteL(aBuf);

			for(TInt i = 0; i < iEntries.Count(); i++) {
				CThreadedEntry* aThread = iEntries[i];			
				CAtomEntryData* aEntry = aThread->GetEntry();	
				
				aFile.WriteL(_L8("\t\t"));						
				aFile.WriteL(aAtomEntryParser->AtomEntryToXmlL(aEntry, KNullDesC8, true));
				aFile.WriteL(_L8("\r\n"));						
				
				if(aThread->CommentCount() > 0) {
					aFile.WriteL(_L8("\t\t<comments>\r\n"));	
					
					for(TInt x = 0; x < aThread->CommentCount(); x++) {
						CAtomEntryData* aComment = aThread->GetCommentByIndex(x);
						
						aFile.WriteL(_L8("\t\t\t"));						
						aFile.WriteL(aAtomEntryParser->AtomEntryToXmlL(aComment, aEntry->GetId(), true));
						aFile.WriteL(_L8("\r\n"));						
					}
					
					aFile.WriteL(_L8("\t\t</comments>\r\n"));	
				}
			}

			aFile.WriteL(_L8("\t</discussion>\r\n</?xml?>"));

			CleanupStack::PopAndDestroy(); // CXmppAtomEntryParser
			CleanupStack::PopAndDestroy(&aFile);
			
#ifdef _DEBUG
			if(iDiscussionReadObserver) {
				aBuf.Format(_L8("DISC  End: Save discussion %d to file"), iItemId);
				iDiscussionReadObserver->DiscussionDebug(aBuf);
			}
#endif
		
			return true;
		}
#ifdef _DEBUG
		else {
			if(iDiscussionReadObserver) {
				aBuf.Format(_L8("DISC  Fail: Save discussion %d to file"), iItemId);
				iDiscussionReadObserver->DiscussionDebug(aBuf);
			}
		}
#endif		
	}
	
	return false;
}
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();
	}
TBool CSupLoginServiceProvider::WriteDataToFileL()
{
	__LOGSTR_TOFILE("CSupLoginServiceProvider::WriteDataToFileL() begins");

	// If current operation should be cancelled
	if (iCancelStatus)
		return EFalse;

	// Return value
	TBool retValue = EFalse;

	// If credentials data is not empty
	if (iMemberID && iUsername && iPassword)
	{
		retValue = ETrue;

		RFs fsSession;
		RFileWriteStream writeStream; // Write file stream

		// Install write file session
		User::LeaveIfError(fsSession.Connect());
		CleanupClosePushL(fsSession);

		// Open file stream
		// if already exists - replace with newer version
		TInt err = writeStream.Replace(fsSession, iSettingsFile, EFileStream | EFileWrite | EFileShareExclusive);
		CleanupClosePushL(writeStream);

		// Return EFalse if failed to open stream
		if (err != KErrNone)
		{
			retValue = EFalse;

			__LOGSTR_TOFILE("CSupLoginServiceProvider::WriteDataToFileL() failed to open file");
		}

		if (retValue)
		{
			__LOGSTR_TOFILE("CSupLoginServiceProvider::WriteDataToFileL() succeed to open the file");

			// Write data
			// iMemberID
			writeStream.WriteInt32L(iMemberID->Des().MaxLength());
			writeStream << *iMemberID;
			// iUsername
			writeStream.WriteInt32L(iUsername->Des().MaxLength());
			writeStream << *iUsername;
			// iPassword
			writeStream.WriteInt32L(iPassword->Des().MaxLength());
			writeStream << *iPassword;

			// Just to ensure that any buffered data is written to the stream
			writeStream.CommitL();
		}	

		// Free resource handlers
		CleanupStack::PopAndDestroy(&writeStream);
		CleanupStack::PopAndDestroy(&fsSession);		
	}	

	__LOGSTR_TOFILE("CSupLoginServiceProvider::WriteDataToFileL() ends");

	return retValue;
}
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);
	}
// ---------------------------------------------------------------------------
// 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 CAiwPrintingProvider::DoHandleCmdL(TInt aMenuCmdId,
                            const CAiwGenericParamList& aInParamList,
                            CAiwGenericParamList& aOutParamList,
                            TUint /*aCmdOptions*/,
                            const MAiwNotifyCallback* aCallback)
    {
    if ( aMenuCmdId == KAiwCmdPrint || aMenuCmdId == KAiwCmdPrintPreview  )
        {
        FLOG(_L("[CAiwPrintingProvider]<<<  DoHandleCmdL"));
        
        CAiwGenericParamList* checkedParams = CAiwGenericParamList::NewL();
        
        iConsumerInParamList = &aInParamList;
        iConsumerOutParamList = &aOutParamList;
        iConsumerCallback = aCallback;
        
        TInt index( 0 );
	    const TAiwGenericParam* param = aInParamList.FindFirst(index,
	            EGenericParamFile,
	            EVariantTypeDesC);
	    while ( index != KErrNotFound )
			{
	        TFileName filename( param->Value().AsDes() );
 	        TInt err = KErrNone;
	        TBool result = EFalse;
	        TRAP( err, result = IsPrintingSupportedL( filename ) );
	        if ( err == KErrNone && result )
	        	{
	            FLOG(_L("[CAiwPrintingProvider] DoHandleCmdL; supported file"));
	        	checkedParams->AppendL(*param);
	        	}
	        else
	        	{
	        	FLOG(_L("[CAiwPrintingProvider] DoHandleCmdL; not supported"));
	        	++iNumberOfUnSuppFiles;
	        	iUnsupportedFiles = ETrue;
	        	}	
	        param = aInParamList.FindNext(index,
	            EGenericParamFile,
	            EVariantTypeDesC);
	        }
   
                
		FTRACE(FPrint(_L("[CAiwPrintingProvider] UnSuppFiles is %d"), iNumberOfUnSuppFiles )); 

		RFileWriteStream stream;
	  	CleanupClosePushL(stream);
		if((stream.Replace(iEikEnv.FsSession(), *iUnsuppFileName ,EFileWrite)) == KErrNone)
			{
			stream.WriteInt16L(iNumberOfUnSuppFiles);
			stream.CommitL();
			}
		CleanupStack::PopAndDestroy(&stream); 
		
        FLOG(_L("[IMAGEPRINTUI]<<< CAiwPrintingProvider;Save iUnsupportedFiles  is done"));
	
        
        RFileWriteStream writeStream;
        User::LeaveIfError( writeStream.Replace(iEikEnv.FsSession(),
        										*iPrintFileName , EFileWrite) );
        writeStream.PushL();
        checkedParams->ExternalizeL(writeStream);
        writeStream.CommitL();
        CleanupStack::PopAndDestroy( &writeStream );
        
        iNumberOfUnSuppFiles = 0;
        delete checkedParams;
        checkedParams = NULL;
        
        LaunchImagePrintApplicationL();
        FLOG(_L("[CAiwPrintingProvider]>>> DoHandleCmdL "));
        }
    }