//Query the aItem from Table DscItem	
void CDscDatabase::QueryItemL(RDbView& aView, const CDscItem& aItem) const
	{
	RBuf sqlCmd;
	CleanupClosePushL(sqlCmd);
	
	if (aItem.ItemId())
		{
		sqlCmd.CreateL(KSqlSelectDscItemOnIdLength);
		sqlCmd.Format(	KSqlSelectDscItemOnId, &KDscIdCol, &KItemIdCol, &KFileNameCol, 
						&KArgListCol,&KStartMethodCol, &KTimeoutCol, &KNoOfRetriesCol, 
						&KMonitorCol, &KStartupTypeCol, &KViewlessCol, &KStartInBackgroundCol, 
						&KItemTable, &KDscIdCol, aItem.DscId(), &KItemIdCol, aItem.ItemId());
		}
	else 
		{
		const TPtrC filename = aItem.FileName();
		const TPtrC argList = aItem.Args();	//whitespace already trimmed
		
		LeaveIfFileParamsNotValidL(aItem);
			
		const TInt length = KSqlSelectDscItemOnNameLength + filename.Length() + argList.Length();
		sqlCmd.CreateL(length);
		sqlCmd.Format(KSqlSelectDscItemOnName, &KDscIdCol, &KItemIdCol, &KFileNameCol,&KArgListCol, &KStartMethodCol, 
					 &KTimeoutCol, &KNoOfRetriesCol, &KMonitorCol, &KStartupTypeCol, &KViewlessCol, &KStartInBackgroundCol, 
					 &KItemTable, &KDscIdCol, aItem.DscId(), &KFileNameCol, &filename, &KArgListCol, &argList);
		}

	DebugPrint(sqlCmd);
	
	User::LeaveIfError(aView.Prepare(iDatabase, sqlCmd));
	User::LeaveIfError(aView.EvaluateAll());  //no error for non existing item
	CleanupStack::PopAndDestroy(&sqlCmd);	
	}
void GetEnumValuesL(TLex& aLex, RBuf& aValues, RBuf& aDescriptions)
	{
	aValues.CreateL(0x100);
	aDescriptions.CreateL(0x100);

	while (!aLex.Eos())
		{
		TLexMark mark;
		aLex.Mark(mark);
		TPtrC command(NextCommand(aLex));
		if (command == KCmndEnumValue)
			{
			TPtrC value(NextWord(aLex));
			TPtrC description(TextToNextCommand(aLex));
			if (value.Length() == 0)
				{
				User::Leave(KErrArgument);
				}
			AppendL(aValues, value, EFalse);
			if (description.Length() > 0)
				{
				AppendL(aDescriptions, description, ETrue);
				}
			}
		else
			{
			aLex.UnGetToMark(mark);
			break;
			}
		}
	}
void TestFileLengthExceedMax()
	{
	test.Next(_L("Test accesing a long file with filename length >250 characters"));
	__UHEAP_MARK;

	// logging for failure
	gTCType = ESymbianFATSpecific;
	RBuf failedOnBuf;
	failedOnBuf.CreateL(gLogFailureData.iFuncName);
	gTCId = 0;
	RBuf tcUniquePath;
	tcUniquePath.CreateL(KNone());

	QuickFormat();
	CreateTestDirectory(_L("\\F32-TST\\T_FATCHARSETCONV\\"));

	TInt r = TheFs.SessionPath(gSessionPath);
	testAndLog(r==KErrNone);
	
	TBuf<350> longName;

	_LIT(KTestDir1,	"\\TEST\\TESTLONGFILENAMELENGTH\\TESTMORETHAN260CHARACTERS\\") ;
	_LIT(KTestDir2,  "\x65B0\x6587\x4EF6\x4EF6(ABCDEFGH)\\(\x65B0\x6587\x4EF6\x4EF6)PQRST\\");
	_LIT(KTestDir3,  "MULTILEVEL-FOLDER1\\MULTILEVEL-FOLDER2\\MULTILEVEL-FOLDER3\\");
	_LIT(KTestDir4,  "\x65B0\x65B0\x65B0\x65B0(x6587)\\(\x6587\x6587\x6587\x6587)PQRST\\");
	_LIT(KTestDir5,  "\x4EF6\x4EF6\x4EF6\x4EF6(x4EF6)\\(\x6587\x6587\x6587\x6587)XYZ\\");	
	_LIT(KTestDir6,  "TESTINGINPROGRESS(TESTLENGTH)>256\\");	
	_LIT(KTestLongFileLength,  "\x4EF6\x4EF6\x4EF6\x4EF6(x4EF6).TXT");
	
	longName = gSessionPath;
	longName += KTestDir1;
	longName += KTestDir2;
	longName += KTestDir3;
	longName += KTestDir4;
	longName += KTestDir5;
	longName += KTestDir6;
	
	test.Printf(_L("longName length is  %d "), longName.Length());
	r=TheFs.MkDirAll(longName);
	
	longName += KTestLongFileLength;
	test.Printf(_L("longName count is  %d "), longName.Length());

	testAndLog(longName.Length()>256);
	
	r=TheFile.Create(TheFs,longName ,EFileWrite);
	testAndLog(r==KErrBadName);
	// TheFile.Close();
		
	r=TheFile.Open(TheFs,longName ,EFileWrite);
	testAndLog(r==KErrBadName);
	// TheFile.Close();
	
	TheFs.Delete(longName);	
	failedOnBuf.Close();
	tcUniquePath.Close();
	__UHEAP_MARKEND;		
	}
//Update aItem. 
void CDscDatabase::UpdateItemL(const CDscItem& aItem)
	{
	//Leave if DB is opened for enumeration
	if (iIsEnumOpened)
		{
		User::Leave(KErrLocked);
		}

	if(aItem.ItemId() == 0)
		{
		LeaveIfFileParamsNotValidL(aItem);
		}

	DatabaseBeginLC();

	//Leave if aItem does not exist
	if (!ItemExistsL( aItem))
		{
		User::Leave(KErrNotFound);	
		}
	
	RBuf sqlCmd;
	CleanupClosePushL(sqlCmd);

	if (aItem.ItemId())
		{
		sqlCmd.CreateL(KSqlUpdateUsingIdLength);
		sqlCmd.Format(KSqlUpdateUsingId, &KItemTable, &KStartMethodCol, aItem.StartMethod(), &KTimeoutCol, aItem.Timeout(),
				&KNoOfRetriesCol, aItem.NoOfRetries(), &KMonitorCol, aItem.Monitored(), &KStartupTypeCol, aItem.StartupType(),
				&KViewlessCol, aItem.Viewless(), &KStartInBackgroundCol, aItem.StartInBackground(),
				&KDscIdCol, aItem.DscId(), &KItemIdCol, aItem.ItemId());
		}
	else 
		{
		const TPtrC filename = aItem.FileName();
		const TPtrC argList = aItem.Args();	//whitespace already trimmed
		
		const TInt length = KSqlUpdateUsingNameLength + filename.Length() + argList.Length();
		sqlCmd.CreateL(length);		
		sqlCmd.Format(KSqlUpdateUsingName, &KItemTable, &KStartMethodCol, aItem.StartMethod(), &KTimeoutCol, aItem.Timeout(),
						&KNoOfRetriesCol, aItem.NoOfRetries(), &KMonitorCol, aItem.Monitored(), &KStartupTypeCol, aItem.StartupType(),
						&KViewlessCol, aItem.Viewless(), &KStartInBackgroundCol, aItem.StartInBackground(),
						&KDscIdCol, aItem.DscId(), &KFileNameCol, &filename, &KArgListCol, &argList);
		}

	DebugPrint(sqlCmd);
		
	User::LeaveIfError(iDatabase.Execute(sqlCmd));	
	CleanupStack::PopAndDestroy(&sqlCmd);
	DatabaseCommitL(); //CommitL + CleanupStack::Pop()
	}
void CDscDatabase::GetDscDescriptionL(const TUid &aDscId, TDes& aDescription) const
	{	
	RDbView view;
	CleanupClosePushL(view);

	RBuf sqlCmd;
	CleanupClosePushL(sqlCmd);
	sqlCmd.CreateL(KSqlSelectDscDescriptionLength);
	
	sqlCmd.Format(KSqlSelectDscDescription, &KDescriptionCol, &KDscTable, &KDscIdCol, aDscId);
	DebugPrint(sqlCmd);
	User::LeaveIfError(view.Prepare(iDatabase, sqlCmd));
	User::LeaveIfError(view.EvaluateAll());  
	CleanupStack::PopAndDestroy(&sqlCmd);
	
	if(view.IsEmptyL())
		{
		User::Leave(KErrNotFound);
		}
	
 	view.FirstL();
	view.GetL();
	
	//Check the length of aDescription
	TPtrC description(view.ColDes(1));
	if (description.Length() > aDescription.MaxLength())
		{
		User::Leave(KErrOverflow);
		}
	
	aDescription.Zero();	
	aDescription=description;
	
	CleanupStack::PopAndDestroy(&view);
	}
//Delete the DSC with aDscId, all items related to aDscId are deleted too.  
void CDscDatabase::DeleteDscL(const TUid& aDscId)
	{
	//If the DSC is opened for enumeration, leave with KErrLocked
	if (iIsEnumOpened)
		{
		User::Leave(KErrLocked);
		}
	
	//Start a new transaction		
	DatabaseBeginLC();
	
	if (!DscExistsL(aDscId))
		{
		// aDscId doesn't exist, leave with KErrNotFound
		User::Leave(KErrNotFound);
		}
		
	RBuf sqlCmd;
	CleanupClosePushL(sqlCmd);
	sqlCmd.CreateL(KSqlDeleteUsingIdLength);
	
	//Delete all items related with aDscId first
	sqlCmd.Format(KSqlDeleteUsingId, &KItemTable, &KDscIdCol, aDscId);
	DebugPrint(sqlCmd);
	User::LeaveIfError(iDatabase.Execute(sqlCmd));

	//Then delete the row in Table DSC
	sqlCmd.Format(KSqlDeleteUsingId, &KDscTable, &KDscIdCol, aDscId);	
	DebugPrint(sqlCmd);
	User::LeaveIfError(iDatabase.Execute(sqlCmd));
	
	CleanupStack::PopAndDestroy(&sqlCmd);
	
	DatabaseCommitL(); //CommitL + CleanupStack::Pop()
	}
//Add a DSC with aDscId to DSC DB. if the aDscId exists, leave with KErrAlreadyExists
void CDscDatabase::CreateDscL(const TUid& aDscId, const TDesC& aDescription)
	{
	//The maximum length of aDescription is KDbMaxStrLen
	if(aDescription.Length() > KDbMaxStrLen)
		{
		User::Leave(KErrArgument);
		}
	
	//If the DSC is opened for enumeration, leave with KErrLocked
	if (iIsEnumOpened)
		{
		User::Leave(KErrLocked);
		}
		
	//Start a new transaction		
	DatabaseBeginLC();

	//Insert aDscId in Table DSC. If aDscId exists, will leave with KErrAlreadyExists	
	RBuf sqlCmd;
	CleanupClosePushL(sqlCmd);
	sqlCmd.CreateL(KSqlInsertDscLength + aDescription.Length());
	
	sqlCmd.Format(KSqlInsertDsc, &KDscTable, &KDscIdCol, &KDescriptionCol, aDscId, &aDescription);
	DebugPrint(sqlCmd);
	User::LeaveIfError(iDatabase.Execute(sqlCmd));
	
	CleanupStack::PopAndDestroy(&sqlCmd);
	
	DatabaseCommitL(); //CommitL + CleanupStack::Pop()
	}
void CDscDatabase::CreateTablesL()
	{
	RBuf sqlCmd;
	CleanupClosePushL(sqlCmd);
	sqlCmd.CreateL(KMaxDdlLength);	
		
	//Start a new transaction		
	DatabaseBeginLC();

	//Create Table DSC
	sqlCmd.Format(KSqlCreateDscTable, &KDscTable, &KDscIdCol, &KDescriptionCol, KDbUndefinedLength);
	DebugPrint(sqlCmd);
	User::LeaveIfError(iDatabase.Execute(sqlCmd));

	//Create unique index for Table DSC
	sqlCmd.Format(KSqlCreateDscIndex, &KIdIndex, &KDscTable, &KDscIdCol);
	DebugPrint(sqlCmd);
 	User::LeaveIfError(iDatabase.Execute(sqlCmd));
 	
	//Create Table DscItem	
	sqlCmd.Format(KSqlCreateItemTable, &KItemTable, &KDscIdCol, &KItemIdCol, &KFileNameCol, KDbUndefinedLength, &KArgListCol,
				KDbUndefinedLength, &KStartMethodCol, &KTimeoutCol, &KNoOfRetriesCol, &KMonitorCol, &KStartupTypeCol,
				&KViewlessCol, &KStartInBackgroundCol);
	DebugPrint(sqlCmd);
	User::LeaveIfError(iDatabase.Execute(sqlCmd));
	
	//Create unique index for Table DscItem
	sqlCmd.Format(KSqlCreateItemIndex, &KIndex, &KItemTable, &KDscIdCol, &KItemIdCol);
	DebugPrint(sqlCmd);
	User::LeaveIfError(iDatabase.Execute(sqlCmd));
	
	DatabaseCommitL(); //CommitL + CleanupStack::Pop()
	
 	CleanupStack::PopAndDestroy(&sqlCmd);
	}
/**
  Launch a process
  @param aExeName the executable used to create the process
  @param aCommandLine the commandline parameters passed to the new process file name of the executable used to create the process
  @return KErrNone on success, or one of the other system wide error codes
  */
TInt CRunModeAgent::LaunchProcessL( RProcess& aProcess, const TDesC& aExeName, const TDesC& aCommandLine )
    {
    LOG_ENTRY(); 
    
    RBuf launcherOptions;
    launcherOptions.CleanupClosePushL();
    const TInt additionalWords = 1; 
    launcherOptions.CreateL( aCommandLine.Length() + additionalWords );
    launcherOptions.Format( aCommandLine, iParams.iTestTargetPriority);
   
    LOG_DES(_L("launcherOptions %S"), &launcherOptions);
    
    TInt err = aProcess.Create( aExeName, launcherOptions );   
    CleanupStack::PopAndDestroy();
    
    // check that there was no error raised
    if (err != KErrNone)
        return err;
    
    // rendezvous with process
    TRequestStatus status = KRequestPending;
    aProcess.Rendezvous(status);

    // start the test target
    aProcess.Resume();
    User::WaitForRequest(status);
  
    if(KErrNone != status.Int())
        {
        aProcess.Kill(KErrNone);
        }
     LOG_EXIT(); 
     return status.Int();

    }
/**
A helper function of MoveObjectL.
@param aNewFolderName the new file folder name after the folder is moved.
*/
void CMTPMoveObject::MoveFolderL()
{
    OstTraceFunctionEntry0( CMTPMOVEOBJECT_MOVEFOLDERL_ENTRY );

    RBuf oldFolderName;
    oldFolderName.CreateL(KMaxFileName);
    oldFolderName.CleanupClosePushL();
    oldFolderName = iObjectInfo->DesC(CMTPObjectMetaData::ESuid);
    iPathToMove = oldFolderName.AllocL();

    if (iObjectInfo->Uint(CMTPObjectMetaData::EDataProviderId) == iFramework.DataProviderId())
    {
        GetPreviousPropertiesL(oldFolderName);
        // Remove backslash.
        oldFolderName.SetLength(oldFolderName.Length() - 1);
        SetPreviousPropertiesL(*iNewRootFolder);
        _LIT(KBackSlash, "\\");
        oldFolderName.Append(KBackSlash);

        iObjectInfo->SetDesCL(CMTPObjectMetaData::ESuid, *iNewRootFolder);
        iObjectInfo->SetUint(CMTPObjectMetaData::EParentHandle, iNewParentHandle);
        iObjectInfo->SetUint(CMTPObjectMetaData::EStorageId, iStorageId);
        iFramework.ObjectMgr().ModifyObjectL(*iObjectInfo);
    }

    CleanupStack::PopAndDestroy(); // oldFolderName.

    OstTraceFunctionExit0( CMTPMOVEOBJECT_MOVEFOLDERL_EXIT );
}
CUninstallMachine::TState* CUninstallMachine::TRegistrationState::CompleteL()
/**
	Obtains the log file handle and its name from the SWI Observer.
	Adds the log file to the transaction
 */
	{
	DEBUG_PRINTF(_L8("Uninstall Machine - Registration State complete"));
	RBuf logFileName;
	logFileName.CreateL(KMaxFileName);
	logFileName.CleanupClosePushL();
	
	//Get created a log file and obtains its full name.
	iUninstallMachine.Observer().GetFileHandleL(logFileName);

	//Add the log file to the transaction
#ifdef SYMBIAN_UNIVERSAL_INSTALL_FRAMEWORK
	iUninstallMachine.TransactionSession().RegisterNewL(logFileName);
#else
	iUninstallMachine.IntegrityServicesL().AddL(logFileName);
#endif

	CleanupStack::PopAndDestroy(&logFileName);
	// Get Controllers.
	return static_cast<TState*>(&iUninstallMachine.iConfirmationState);
	}
//Open a view of items with aDscID for enumeration, need to 
//call EnumClose() to close the view after enumeration.	
void CDscDatabase::EnumOpenLC(const TUid& aDscId)
	{
	//If the DSC is opened for enumeration, leave with KErrLocked
	if (iIsEnumOpened)
		{
		User::Leave(KErrLocked);
		}
		
	//Start a new transaction to add read-lock on DSC	
	EnumBeginLC();
		
	//Leave with KErrNotFound if aDscId doesn't exist
	if (!DscExistsL(aDscId))
		{
		User::Leave(KErrNotFound);
		}

	iIsEnumOpened = ETrue;

	//Open a view contains all items in aDscId
	RBuf sqlCmd;
	CleanupClosePushL(sqlCmd);
	sqlCmd.CreateL(KSqlSelectAllItemsInDscLength);
	
	sqlCmd.Format(KSqlSelectAllItemsInDsc, &KDscIdCol, &KItemIdCol, &KFileNameCol, &KArgListCol,
				&KStartMethodCol, &KTimeoutCol, &KNoOfRetriesCol, &KMonitorCol, &KStartupTypeCol,
				&KViewlessCol, &KStartInBackgroundCol, &KItemTable, &KDscIdCol, aDscId, &KItemIdCol);
	DebugPrint(sqlCmd);
	User::LeaveIfError(iView.Prepare(iDatabase, sqlCmd));
	User::LeaveIfError(iView.EvaluateAll());  //no error for non existing item
	CleanupStack::PopAndDestroy(&sqlCmd);
	}
void CCmdCustomCommand::WriteHandleToFileL(TInt aHandle)
	{
	const TChar sysDrive = RFs::GetSystemDriveChar();
	RBuf filename;
	filename.CreateL(KNeverUnloadLibHandleFile().Length() + 1);
	filename.Append(sysDrive);
	filename.Append(KNeverUnloadLibHandleFile());
	filename.CleanupClosePushL();
	RFs fs;
	User::LeaveIfError(fs.Connect());
	CleanupClosePushL(fs);

	fs.MkDirAll(filename); // ignore any error
	RFile file;
	CleanupClosePushL(file);
	TInt err=KErrNone;
	TInt pos = 0;
	if(KErrNotFound == (err = file.Open(fs, filename, EFileShareExclusive|EFileStream|EFileWrite)))
		{
		User::LeaveIfError(file.Replace(fs, filename, EFileShareExclusive|EFileStream|EFileWrite));
		}
	else
		{
		User::LeaveIfError(err);
		file.Seek(ESeekEnd, pos);
		}
	RFileWriteStream targetStream;
	targetStream.Attach(file, pos); // file gets closed by this call, but that's okay, we don't need it any more (targetStream has its own copy of this RFile object that it owns)
	CleanupClosePushL(targetStream);
	targetStream.WriteInt32L(aHandle);
	targetStream.CommitL();
	CleanupStack::PopAndDestroy(4); 
	}
// ---------------------------------------------------------------------------
//
// ---------------------------------------------------------------------------
//
void CaSqlQueryCreator::CreateFindIconQueryL( CCaInnerEntry* aEntry,
        CCaSqlQuery* aQuery)
    {
    RBuf iconQuery;
    iconQuery.CleanupClosePushL();
    iconQuery.CreateL( KSQLGetIconIdWhere );

    if( aEntry->Icon()->FileName().Compare( KNullDesC ) )
        {
        iconQuery.ReAllocL( iconQuery.Length() + KSQLUpdateIconFileName().Length()
                + KAnd().Length() );
        iconQuery.Append( KSQLUpdateIconFileName );
        iconQuery.Append( KAnd );
        }
    else
        { 
        iconQuery.ReAllocL( iconQuery.Length() + KSQLEmptyIconFileName().Length()
                + KAnd().Length() );
        iconQuery.Append( KSQLEmptyIconFileName );
        iconQuery.Append( KAnd );
        }

    if( aEntry->Icon()->SkinId().Compare( KNullDesC ) )
        {
        iconQuery.ReAllocL( iconQuery.Length() + KSQLUpdateIconSkinId().Length()
                + KAnd().Length() );
        iconQuery.Append( KSQLUpdateIconSkinId );
        iconQuery.Append( KAnd );
        }
    else
        {
        iconQuery.ReAllocL( iconQuery.Length() + KSQLEmptyIconSkinId().Length()
                + KAnd().Length() );
        iconQuery.Append( KSQLEmptyIconSkinId );
        iconQuery.Append( KAnd );
        }

    if( aEntry->Icon()->ApplicationId().Compare( KNullDesC ) )
        {
        iconQuery.ReAllocL( iconQuery.Length() + KSQLUpdateIconAppId().Length()
                + KAnd().Length() );
        iconQuery.Append( KSQLUpdateIconAppId );
        iconQuery.Append( KAnd );
        }
    else
        {
        iconQuery.ReAllocL( iconQuery.Length() + KSQLEmptyIconAppId().Length()
                + KAnd().Length() );
        iconQuery.Append( KSQLEmptyIconAppId );
        iconQuery.Append( KAnd );
        }

    if (!iconQuery.Right(KAnd().Length()).Compare(KAnd))
        {    
        iconQuery.Delete( iconQuery.Length() - KAnd().Length(), KAnd().Length() );
        }
    
    aQuery->SetQueryL( iconQuery );
    CleanupStack::PopAndDestroy( &iconQuery );
    }
// ---------------------------------------------------------------------------
//
// ---------------------------------------------------------------------------
//
void CaSqlQueryCreator::CreateGetParentsIdsQueryL(
        const RArray<TInt>& aEntryIdArray, CCaSqlQuery* aSqlQuery,
        const RArray<TInt>& aParentIdArray )
    {
    DEBUG(("_CA_:CASqlQueryCreator::CreateGetParentsIdsQueryL"));
    RBuf entryIdList;
    entryIdList.CleanupClosePushL();
    CreateIdListL( aEntryIdArray.Count(), entryIdList, KSQLGEEntryId );
    RBuf parentIdList;
    parentIdList.CleanupClosePushL();
    CreateIdListL( aParentIdArray.Count(), parentIdList, KSQLGEIdGroup );

    RBuf query;
    query.CleanupClosePushL();
    query.CreateL( KSQLGetParentIds().Length() + entryIdList.Length() );
    query.AppendFormat( KSQLGetParentIds, &entryIdList );
    if( aParentIdArray.Count() > 0 )
        {
        query.ReAllocL( query.Length() + parentIdList.Length()
                + KSQLNotINIds().Length() );
        query.AppendFormat( KSQLNotINIds, &parentIdList );
        }

    aSqlQuery->SetQueryL( query );

    CleanupStack::PopAndDestroy( &query );
    CleanupStack::PopAndDestroy( &parentIdList );
    CleanupStack::PopAndDestroy( &entryIdList );
    }
/*static*/TBool CStsServer::CheckIfFileModificationAllowedL(const RMessage2& aMsg)
	{
	RBuf filePath;
	filePath.CreateL(KMaxFileName);
	filePath.CleanupClosePushL();
	aMsg.ReadL(KFilePathIPCSlot, filePath, 0);

	// Retrieve the required capabilities for write access to this path
	TCapabilitySet requiredCapabilities = SecCommonUtils::FileModificationRequiredCapabilitiesL(filePath, aMsg.SecureId());
	
	TBool result = EFalse;
	TBool allFilesRequired = requiredCapabilities.HasCapability(ECapabilityAllFiles);
	TBool tcbRequired = requiredCapabilities.HasCapability(ECapabilityTCB);
	
	// Test whether the client has at least one of the required capabilities
	if (allFilesRequired)
		result = aMsg.HasCapability(ECapabilityAllFiles);
	if (!result && tcbRequired)
		result = aMsg.HasCapability(ECapabilityTCB);
	if (!allFilesRequired && !tcbRequired)
		result = ETrue;
	
	CleanupStack::PopAndDestroy(&filePath);
	return result;
	}	
void CNcdNodeActivate::SetContentFileL( MNcdInstalledFile& aFile, 
    CNcdNodeInstallProxy& aInstall,
    MNcdDeviceService& aService )
    {
    DLTRACEIN((""));
    RBuf fileName;
    fileName.CreateL( KMaxFileName );
    CleanupClosePushL( fileName );

    // Get the file handle to the file that will be activated.    
    RFile file = aFile.OpenFileL();
    CleanupClosePushL( file );

    // Get the filename from the handle. 
    // The name will be used for the activation
    file.FullName( fileName );
    CleanupStack::PopAndDestroy( &file );                

    if ( aInstall.IsPurpose( ENcdItemPurposeRingtone ) )
        {                
        aService.SetAsRingingToneL( fileName );
        }
    else if( aInstall.IsPurpose( ENcdItemPurposeWallpaper ) )
        {                   
        aService.SetAsWallpaperL( fileName );        
        }
    else
        {
        User::Leave( KErrNotSupported );
        }
    CleanupStack::PopAndDestroy ( &fileName );        
    DLTRACEOUT(("All is well"));
    }
/**
Test framework to check for panic scenarios
It requires to create a separate thread so we can check the panic category and code.
*/
TInt StartSwpInvalidListInThreadL(CSsmValidSwpListTest* aSsmValidSwpListTest)
	{
	RThread thread;
	// Give each thread a unique name to avoid KErrAlreadyExists error on thread creation
	_LIT(KThreadNamePrefix, "SsmTestThread");

	RBuf threadName;
	CleanupClosePushL(threadName);
	threadName.CreateL(KThreadNamePrefix().Length() + 6); // 6 digit thread number
	threadName = KThreadNamePrefix;
	threadName.AppendNumFixedWidth(aSsmValidSwpListTest->Function(), EDecimal, 6);
	const TInt KMinHeapSize = 0xc800; // 50k - NOTE just an arbitrary value, please feel free to change it
	const TInt KMaxHeapSize = 0x19000; // 100k - NOTE just an arbitrary value, please feel free to change it
	User::LeaveIfError(thread.Create(threadName, ThreadStartSwpInvalidListFn, KDefaultStackSize, KMinHeapSize, KMaxHeapSize, aSsmValidSwpListTest));
	CleanupStack::PopAndDestroy(&threadName);
	TRequestStatus status;
	thread.Logon(status);
	TBool jit =	User::JustInTime();
	User::SetJustInTime(EFalse);
	thread.Resume();
	User::WaitForRequest(status);
	
	// always expecting a state transition engine panic
	TExitCategoryName category = thread.ExitCategory();
	if (category.Compare(KPanicSysStateMgr) != 0)
		{
		User::Leave(KTestInvalidPanicCategory);
		}
	const TInt exitReason = thread.ExitReason();
	thread.Close();
	User::SetJustInTime(jit);

	// return the exit reason for the caller to verify the expected panic value
	return exitReason;
	}
// -----------------------------------------------------------------------------
// CMoveObject::MoveObjectL
// Move object operation
// -----------------------------------------------------------------------------
//
void CMoveObject::MoveObjectL()
    {
    PRINT( _L( "MM MTP => CMoveObject::MoveObjectL" ) );
    TMTPResponseCode responseCode = EMTPRespCodeOK;

    GetParametersL();

    RBuf newObjectName;
    newObjectName.CreateL( KMaxFileName );
    newObjectName.CleanupClosePushL(); // + newObjectName
    newObjectName = *iDest;

    TPtrC suid( iObjectInfo->DesC( CMTPObjectMetaData::ESuid ) );
    TParsePtrC fileNameParser( suid );
    if ( ( newObjectName.Length() + fileNameParser.NameAndExt().Length() )
        <= newObjectName.MaxLength() )
        {
        newObjectName.Append( fileNameParser.NameAndExt() );
        responseCode = CanMoveObjectL( suid, newObjectName );

        if ( responseCode == EMTPRespCodeOK )
            MoveFileL( newObjectName );
        }
    else
        // Destination is not appropriate for the full path name shouldn't be longer than 255
        responseCode = EMTPRespCodeInvalidDataset;

    SendResponseL( responseCode );

    CleanupStack::PopAndDestroy( &newObjectName ); // - newObjectName

    PRINT1( _L( "MM MTP <= CMoveObject::MoveObjectL responseCode = 0x%x" ), responseCode );
    }
void TestLeadingE5Handling()
	{
	test.Next(_L("Test Leading \'E5\' byte handling"));
	__UHEAP_MARK;
	
	// logging for failure
	gTCType = ESymbianFATSpecific;
	RBuf failedOnBuf;
	failedOnBuf.CreateL(gLogFailureData.iFuncName);
	gTCId = 0;
	RBuf tcUniquePath;
	tcUniquePath.CreateL(KNone());

	QuickFormat();
	CreateTestDirectory(_L("\\F32-TST\\T_FATCHARSETCONV\\"));

	// Enables codepage dll implementation of LocaleUtils functions for this test only
	TInt r = TheFs.ControlIo(CurrentDrive(), KControlIoEnableFatUtilityFunctions);
	testAndLog(r==KErrNone);
	
	r = UserSvr::ChangeLocale(KTestLocale);
	testAndLog(r==KErrNone);

	r=TheFs.SessionPath(gSessionPath);
	testAndLog(r==KErrNone);

	_LIT(KTestFilePathAndName,		"\\F32-TST\\T_FATCHARSETCONV\\\x88F9.TXT");
	_LIT(KTestFileShortName, 		"\x88F9.TXT");
	
	MakeFile(KTestFilePathAndName);
	TFileName sn;
	r = TheFs.GetShortName(KTestFilePathAndName, sn);
	testAndLog(r==KErrNone);
	r = sn.Compare(KTestFileShortName);
	testAndLog(r==KErrNone);
	
	r=TheFs.Delete(KTestFilePathAndName);
	testAndLog(r==KErrNone);

	// Disables codepage dll implementation of LocaleUtils functions for other base tests
	r = TheFs.ControlIo(CurrentDrive(), KControlIoDisableFatUtilityFunctions);
	testAndLog(r==KErrNone);
	failedOnBuf.Close();
	tcUniquePath.Close();
	__UHEAP_MARKEND;
	}
void IntegrityRestoreFileL(const TDesC& aPath, CIntegrityTreeLeaf* aLeaf, RFs& aFs, 
								RLoader& /*aLoader*/, CFileMan& /*aFileMan*/)
	{
	RBuf name;
	name.CreateL(aPath, KMaxFileName);
	CleanupClosePushL(name);
	name.Append(aLeaf->Name());

	// find the peer file, and check it's a backup.
	CIntegrityTreeLeaf* peer = aLeaf->Peer();
	if (peer->Type() != EBackupFile)
		{
		User::Leave(KErrCorrupt);
		}
	
	TParsePtrC parse(peer->Journal());
	RBuf backup;
	backup.CreateL(parse.DriveAndPath(), KMaxFileName);
	CleanupClosePushL(backup);
	backup.Append(parse.Name());
	backup.Append(KPathDelimiter);
	backup.Append(peer->Name());

	TInt err = aFs.MkDirAll(name);
	if(err != KErrNone && err != KErrAlreadyExists)
		{
		User::Leave(err);
		}
			
	err = aFs.Rename(backup, name);
	if (err != KErrNone)
		{
		VerifyDeletionErrorL(err);
		// we may have already moved it back during a previous recovery
		// attempt, check for its presence in the original location
		TEntry restoredEntry;
		User::LeaveIfError(aFs.Entry(name, restoredEntry));
		}
	else
		{
		// prune the backup directory tree if possible.
		RemoveDirectoryTreeL(aFs, backup);
		}
	CleanupStack::PopAndDestroy(2, &name);	// backup
	}
CIntegrityTreeLeaf* CIntegrityTreeNode::AddNodeL(const TDesC& aFileName, TIntegrityServicesEvent aType, const TDesC& aOwningJournal)
{
    RBuf filename;
    filename.CreateL(aFileName, aFileName.Length());
    CleanupClosePushL(filename);
    CIntegrityTreeLeaf* leaf = DoAddNodeL(filename, aType, aOwningJournal);
    CleanupStack::PopAndDestroy(&filename);
    return leaf;
}
TInt CIntegrityTreeNode::FindNode(const TDesC& aFileName, TIntegrityServicesEvent aType)
{
    RBuf filename;
    TInt found = 0;
    TRAPD(err,
          filename.CreateL(aFileName, aFileName.Length());
          CleanupClosePushL(filename);
          found = DoFindNode(filename, aType);
          CleanupStack::PopAndDestroy(&filename);
         );
//Add aItem to DSC at aPos
void CDscDatabase::AddItemL(CDscItem& aItem, TDscPosition aPos)
	{
	//Leave if DB is opened for enumeration
	if (iIsEnumOpened)
		{
		User::Leave(KErrLocked);
		}
	
	//verify data integrity,
	LeaveIfFileParamsNotValidL(aItem);
	if(aItem.ItemId() != 0)
		{
		User::Leave(KErrArgument);
		}

	//Start transaction
	DatabaseBeginLC();

	//Leave if aDscId doesn't exist
	if (!DscExistsL(aItem.DscId()))
		{
		User::Leave(KErrNotFound);
		}

	//Leave if aItem exists
	if (ItemExistsL(aItem))
		{
		User::Leave(KErrAlreadyExists);
		}

	const TPtrC filename = aItem.FileName();
	const TPtrC argList = aItem.Args();	//whitespace already trimmed
	const TInt itemId = GetNextItemIdL(aPos, aItem.DscId());
	
	RBuf sqlCmd;
	CleanupClosePushL(sqlCmd);
	sqlCmd.CreateL(KSqlInsertDscItemLength + filename.Length() + argList.Length());
	
	//insert the item
	sqlCmd.Format(KSqlInsertDscItem, &KItemTable, &KDscIdCol, &KItemIdCol, &KFileNameCol, &KArgListCol,
				&KStartMethodCol, &KTimeoutCol, &KNoOfRetriesCol, &KMonitorCol, &KStartupTypeCol,
				&KViewlessCol, &KStartInBackgroundCol, aItem.DscId(), itemId, &filename, &argList, aItem.StartMethod(),
				aItem.Timeout(), aItem.NoOfRetries(), aItem.Monitored(),
				aItem.StartupType(), aItem.Viewless(), aItem.StartInBackground());

	DebugPrint(sqlCmd);
	
	User::LeaveIfError(iDatabase.Execute(sqlCmd));
	CleanupStack::PopAndDestroy(&sqlCmd);
	DatabaseCommitL(); //CommitL + CleanupStack::Pop()
	
	//Now aItem is persistent, set the ItemId so it can be read by the client
	aItem.SetItemId(itemId);
	}
// ---------------------------------------------------------------------------
//
// ---------------------------------------------------------------------------
//
void CaSqlQueryCreator::CreateLocalizationTableQueryL( CCaSqlQuery* aSqlQuery,
        const TDesC& aStatement)
    {
    DEBUG(("_CA_:CASqlQueryCreator::CreateLocalizationTableQueryL"));
    RBuf query;
    query.CleanupClosePushL();
    query.CreateL( aStatement.Length() );
    query.Append( aStatement );
    aSqlQuery->SetQueryL( query );
    CleanupStack::PopAndDestroy( &query );
    }
// ----------------------------------------------------------
// CBTEnterpriseItSecurityInfoNotifier::ShowNoteAndCompleteL
// Shows the notifier in backround 
// ----------------------------------------------------------
//
void CBTEnterpriseItSecurityInfoNotifier::ShowNoteAndCompleteL()
	{
	FLOG(_L("[BTNOTIF]\t CBTEnterpriseItSecurityInfoNotifier::ShowNoteAndComplete()"));
	
	//get full path to the DCMO resource file
	TParse* parser = new (ELeave) TParse;
	parser->Set(KDcmoResourceFileName(), &KDC_RESOURCE_FILES_DIR, NULL);
	CleanupStack::PushL(parser);
	TFileName* fileName = new (ELeave) TFileName;
	*fileName = parser->FullName();
	CleanupStack::PopAndDestroy(parser);
	CleanupStack::PushL(fileName);
	
	//create the resource reader object that we need to use several times
	CTulStringResourceReader* reader = CTulStringResourceReader::NewL(*fileName);
	CleanupStack::PushL(reader);
	
	//get pointer to the message part of the notifier
	TPtrC resourceString;
	resourceString.Set(reader->ReadResourceString(R_DM_RUN_TIME_VAR_DISABLE));

	//create descriptor with a max length to fit the localised "disabled" text + new line + "Bluetooth"
	RBuf content;
	content.CreateL(resourceString.Length() + KNewLine().Length() + KDefaultBluetoothStringLength);
	CleanupClosePushL(content);
	
	//add resource string and new line character to the content descriptor
	content.Append(resourceString);	
	content.Append(KNewLine());
	
	//get pointer to the Bluetooth name part of the notifier (can't assume this is actually "Bluetooth" in all languages)
	resourceString.Set(reader->ReadResourceString(R_DM_RUN_TIME_VAR_BLUETOOTH));
	
	//check that the resource string will fit into the content descriptor
	TInt requiredLength = content.Length() + resourceString.Length();
	if (requiredLength > content.MaxLength())
		{
		//allocate more space in the content descriptor
		content.ReAllocL(requiredLength);
		}
	
	//add resource string to the content descriptor
	content.Append(resourceString);	
	
	//display the notifier and complete
	iNotifUiUtil->ShowInfoNoteL(content, ECmdBTnotifUnavailable);
	CompleteMessage(KErrNone);
	
	//pop and destroy the content descriptor, resource reader and file name
	CleanupStack::PopAndDestroy(3, fileName);
	
	FLOG(_L("[BTNOTIF]\t CBTEnterpriseItSecurityInfoNotifier::ShowNoteAndComplete() complete"));
	}
LOCAL_C void mainL()
	{
	CCommandLineArguments* cmdLine = CCommandLineArguments::NewLC();
	CConsoleBase* console = Console::NewL(_L("Siftestintegrationlockfile"),TSize(KConsFullScreen,KConsFullScreen));
	CleanupStack::PushL(console);
	TInt argTotal(cmdLine->Count());
	if (argTotal < 2  || argTotal > 3)
		{
		console->Printf(_L("Incorrect arguments specified: expected 1, received %d"), argTotal - 1);
		User::Leave(KErrArgument);
		}
		
	TPtrC filename(cmdLine->Arg(1));
	_LIT(KDoLockFileParam, " lockfile");
	if (argTotal == 2)
		{
		RBuf params;
		params.CreateL(filename.Length() + KDoLockFileParam().Length());
		params.CleanupClosePushL();
		params.Append(cmdLine->Arg(1));
		params.Append(KDoLockFileParam());
		// Since this executable is used by TEF, we wish to lock the file after the launched process has exited, so we spawn this process again with a different set of parameters
		RProcess newInstance;
		User::LeaveIfError(newInstance.Create(_L("Siftestintegrationlockfile"), params));
		CleanupClosePushL(newInstance);
		newInstance.Resume();
		TRequestStatus status;		
		newInstance.Rendezvous(status);
		User::WaitForRequest(status);
		User::LeaveIfError(status.Int());
		CleanupStack::PopAndDestroy(2, &params); // newInstance
		}
	else
		{
		// This is the execution for locking the file, invoked using the branch above
		console->Printf(_L("Locking file %S for read"), &filename);	
		RFs fs;
		User::LeaveIfError(fs.Connect());
		CleanupClosePushL(fs);
	
		RFile file;
		User::LeaveIfError(file.Open(fs, filename, EFileShareReadersOnly|EFileRead));
		CleanupClosePushL(file);
		// Signal the invoker only here, so that the file will definitely get locked before TEF proceeds to the next step
		RProcess::Rendezvous(KErrNone);		
		
		User::After(10*1000*1000); // Wait for 10 seconds
	
		CleanupStack::PopAndDestroy(2 , &fs); // file
		}
	CleanupStack::PopAndDestroy(2, cmdLine); // console,
    }
void CTestRControlChannel::ExtractServiceDescriptionL (const TDesC& aConfigSection, CUPnPServiceRegisterParamSet& aServiceRegisterParamSet)
	{
	RFs fs;
	RFile file;
	RBuf8 buf;

	User::LeaveIfError(fs.Connect());
	CleanupClosePushL(fs);

	TPtrC descriptionPath;
	_LIT(KDescriptionPath, "Description_Path");
	GetStringFromConfig(aConfigSection, KDescriptionPath, descriptionPath);

	TInt err = file.Open(fs, descriptionPath, EFileShareReadersOnly);
	
	// For Hardware system path is c:, so descriptionPath value present in '.ini' is referring 'c:'
	if ( err == KErrPathNotFound )
		{				
		RBuf fileName;
		TDriveName aSystemDrive;
		TDriveUnit driveunit(RFs::GetSystemDrive());
		aSystemDrive.Zero();
		aSystemDrive=driveunit.Name();				
		fileName.CreateL ( descriptionPath.Length () );
		fileName.Zero();
		fileName.Append(aSystemDrive);
		fileName.Append ( descriptionPath.Mid ( aSystemDrive.Length () ) );				
		
		err = file.Open(fs, fileName, EFileShareReadersOnly);
		}
	if (err != KErrNone)
		{
		User::LeaveIfError(err);
		}

	CleanupClosePushL(file);
	TInt fileSize = 0;
	file.Size(fileSize);

	buf.Create(fileSize);

	err = file.Read(buf, fileSize);
	aServiceRegisterParamSet.SetServiceDescriptionL ( buf );

	CleanupStack::PopAndDestroy(2 );
	buf.Close();
	_LIT(KInfoLogFile, "CRControlChannelObserver::ExtractServiceDescriptionL End.... \n");
	INFO_PRINTF1(KInfoLogFile);
	}
/**
Initialize the counter with the numeric equivalent of the descriptor contents
This function is here to demonstrate reading from the client address space.
Note that in this example, the client and the server are part of the same process,
*/
void CCountServSession::SetFromStringL(const RMessage2& aMessage)
	{
	
	  // length of passed descriptor (1st parameter passed from client)
	TInt deslen = aMessage.GetDesLength(0);
	
	  // Passed data will be saved in this descriptor.
    RBuf buffer;
      
      // Max length set to the value of "deslen", but current length is zero
    buffer.CreateL(deslen);
      
      // Do the right cleanup if anything subsequently goes wrong
    buffer.CleanupClosePushL();
    
      // Copy the client's descriptor data into our buffer.
    aMessage.ReadL(0,buffer,0);
    
      // Now do a validation to make sure that the string only has digits
    if (buffer.Length() == 0)
        {
    	User::Leave(ENonNumericString);
        }
    
    TLex16 lexer;
    
    lexer.Assign(buffer);
    while (!lexer.Eos())
        {
        TChar thechar;
        
        thechar = lexer.Peek();
        if (!thechar.IsDigit())
            {
        	User::Leave(ENonNumericString);
            }
        lexer.Inc();
        }
       
      // Convert to a simple TInt value. 
    lexer.Assign(buffer);           
    if (lexer.Val(iCount))
        {
    	User::Leave(ENonNumericString);
        }
    	
	  // Clean up the memory acquired by the RBuf variable "buffer"
	CleanupStack::PopAndDestroy();
	}
void PopulateDatabaseL()
{
	test.Start(_L("Populate database"));
	RUpsSession session;
	User::LeaveIfError(session.Connect());
	CleanupClosePushL(session);

	RThread thd;
	RUpsSubsession clientSubsession;
	TInt r = clientSubsession.Initialise(session, thd);
	test(r == KErrNone);
	CleanupClosePushL(clientSubsession);

	RBuf destination;
	destination.CreateL(100);
	CleanupClosePushL(destination);

	for(TInt i=0 ; i<100; ++i)
		{
		TServiceId serviceId = {42};
		if( i & 1) serviceId.iUid = 43;
		destination.Zero();
		destination.AppendFormat(_L("destination %x"), i);
		
		TUpsDecision dec = EUpsDecNo;
		TRequestStatus rs;
		clientSubsession.Authorise(EFalse, serviceId, destination, _L8("Opaque data"), dec, rs);
		User::WaitForRequest(rs);
		test(rs == KErrNone);
		if(serviceId.iUid == 42)
			{
			test(dec == EUpsDecYes);
			}
		else
			{
			test(dec == EUpsDecNo);
			}

		}

	CleanupStack::PopAndDestroy(&destination);
	CleanupStack::PopAndDestroy(&clientSubsession);
	CleanupStack::PopAndDestroy(&session);

	test.End();
}