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); 
	}
 /*
  * Save Form data, function to be executed when save option is selected. 
  * Creates the second form which allows for selecting the category.
  */
 TBool CYPagesForm1::SaveFormDataL()
{  
    CAknPopupFieldText* popupFieldText = static_cast <CAknPopupFieldText*> (ControlOrNull(EYPagesPopup));
 	if (popupFieldText) {		
		TInt categoryIndex = popupFieldText->CurrentValueIndex();
		TBuf <30> KMyTextFile;
		KMyTextFile.Format(_L("D:\\YPages\\%d%d.txt"), iColor, categoryIndex);
		
		RFs fileServer;
 	    User :: LeaveIfError (fileServer.Connect());
 	    RFile file;
 	    User::LeaveIfError(file.Open(fileServer, KMyTextFile, EFileRead|EFileStreamText));
 	    CleanupClosePushL(file);
 	    
 	    TFileText fileText;
 	    fileText.Set(file);
 	    
 	    TBuf<100> buffer;
 	    buffer = _L("");

 	    RBuf rBuf;
 	    rBuf.Create(buffer);
 	    rBuf.CleanupClosePushL();
 	    
 	  
 	    TInt err = KErrNone;
 	    while(err != KErrEof) {
 			err = fileText.Read(buffer);
 	    
 			if ((err != KErrNone) && (err != KErrEof)) {
 				User :: Leave(err);
 			}
 			if (KErrNone == err) {
 				rBuf.ReAllocL(rBuf.Length() + buffer.Length()+2);
 				rBuf.Append(buffer);
 				rBuf.Append(_L("\n"));
 			}
 	    }
 	    CAknMessageQueryDialog* dlg = CAknMessageQueryDialog::NewL(rBuf);
 	    dlg->PrepareLC(R_ABOUT_HEADING_PANE);
   	    dlg->SetHeaderTextL(_L(""));  
   	    dlg->RunLD();
 	    		     
 	    CleanupStack::PopAndDestroy(&rBuf);
 	    CleanupStack::PopAndDestroy(&file);
 	    
 	    fileServer.Close();

 	
 	}

        

 	return ETrue;
 }
// ----------------------------------------------------------
// 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,
    }
Esempio n. 5
0
void CVideoEntry::GenerateThumbnailFileL( const TDesC& aCacheDirectory )
	{
	delete iThumbnailFile;

	RBuf path;
	CleanupClosePushL( path );
	path.Create( aCacheDirectory.Length() + iVideoId->Length() + KCacheFileExtension().Length() );
	path.Copy( aCacheDirectory );
	path.Append( *iVideoId );
	path.Append( KCacheFileExtension() );
	iThumbnailFile = path.AllocL();
	CleanupStack::PopAndDestroy( &path );
	}
Esempio n. 6
0
void CPluginUtils::AddUrlParamL( RBuf& aBuf, const TDesC& aParam, const TDesC& aValue, TBool aLast)
	{
	aBuf.ReAllocL( aBuf.Length() + 1 + aParam.Length() + aValue.Length() );
	aBuf.Append( aParam );
	aBuf.Append( _L("=") );
	aBuf.Append( aValue );

	if( !aLast )
		{
		aBuf.ReAllocL( aBuf.Length() + 1 );
		aBuf.Append( _L("&") );
		}
	}
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);
	}
Esempio n. 8
0
void CPluginUtils::AddUrlParamL( RBuf& aBuf, const TDesC& aParam, TInt aValue, TBool aLast )
	{
	TBuf<12> t;
	t.Format( _L("%d"), aValue );
	aBuf.ReAllocL( aBuf.Length() + 1 + aParam.Length() + t.Length() );
	aBuf.Append( aParam );
	aBuf.Append( _L("=") );
	aBuf.Append( t );

	if( !aLast )
		{
		aBuf.ReAllocL( aBuf.Length() + 1 );
		aBuf.Append( _L("&") );
		}
	}
Esempio n. 9
0
// -----------------------------------------------------------------------------
// 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 );
    }
Esempio n. 10
0
void CWindowGroupListBoxData::DoInfoForDialogL(RBuf& aTitle, RBuf& inf, TDes* name)
	{
	SWgInfo& info = *reinterpret_cast<SWgInfo*>(iInfo);
	_LIT(KInfo, "Window group info");
	aTitle.Copy(KInfo);
	CApaWindowGroupName* wg = info.iName;
	*name = wg->WindowGroupName();
	PrettyName(EListWindowGroups, *name);

	inf.Append(*name);
	TThreadId tid;
	TInt res = info.iSession->GetWindowGroupClientThreadId(info.iHandle, tid);
	inf.AppendFormat(_L("\n\nOwner thread: %i"), res == KErrNone ? (TInt)tid : res);
	RThread thread;
	if (res == KErrNone)
		{
		res = thread.Open(tid);
		}
	if (res == KErrNone)
		{
		*name = thread.FullName();
		PrettyName(EListThread, *name);
		inf.AppendFormat(_L(" (%S)"), name);
		}
	inf.AppendFormat(_L("\nBusy=%i System=%i Hidden=%i"), wg->IsBusy(), wg->IsSystem(), wg->Hidden());
	}
Esempio n. 11
0
HBufC* CPluginUtils::ConvertUtfToUnicodeL( const TDesC8& aUtf7 )
	{

	RBuf output;
	CleanupClosePushL( output );
	
	TBuf16<20> outputBuffer;
	TPtrC8 remainderOfUtf7( aUtf7 );

	for(;;)
		{
		const TInt returnValue = CnvUtfConverter::ConvertToUnicodeFromUtf8(outputBuffer, remainderOfUtf7);
		if (returnValue==CnvUtfConverter::EErrorIllFormedInput)
			return NULL;
		else if (returnValue<0)
			return NULL;
        
		output.ReAllocL( output.Length() + outputBuffer.Length() );
		output.Append( outputBuffer );

        if (returnValue == 0)
            break;

        remainderOfUtf7.Set(remainderOfUtf7.Right(returnValue));
		}

	HBufC* ret = output.AllocL();
	
	CleanupStack::PopAndDestroy( &output );
	return ret;
	}
Esempio n. 12
0
/**
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 );
}
void CTestRControlChannel::SavePreviousLogFileL()
	{
	_LIT(KInfoLogFile, "Saving Previous logs If any.... \n");
	INFO_PRINTF1(KInfoLogFile);
	RFs fileserv;
	TInt error = fileserv.Connect();
	if(!error)
		{
		_LIT(KlogFile, "C:\\logs\\log.txt");
		_LIT(KPrefixLog, "C:\\logs\\");
		_LIT(KSuffix, "_UDEB");
		_LIT(KExtn, ".txt");
		
		CFileMan* fMan = NULL;
		TRAP_IGNORE(fMan = CFileMan::NewL(fileserv));
		if(fMan != NULL)
			{
			CleanupStack::PushL(fMan);
			RBuf newFileName;
			const TInt KTwenty = 20;
			newFileName.Create(ConfigSection().Length() + KTwenty );
			newFileName.Copy(KPrefixLog);
			//Script file name
			iScriptName.Copy(ConfigSection());
			newFileName.Append(iScriptName);
			newFileName.Append(KSuffix);
			newFileName.Append(KExtn);
			
			TInt error = fMan->Rename(KlogFile, newFileName);
			if (error != KErrNone)
				{
				_LIT(KErrInfo, "Unable to Save Previous logs...May be NO Previous logs exist \n");
				ERR_PRINTF1(KErrInfo);
				}
			else
				{
				_LIT(KSavingInfo, "Saved Previous logs with File Name: %S \n");
				INFO_PRINTF2(KSavingInfo, &newFileName);
				}
			CleanupStack::PopAndDestroy(fMan);
			newFileName.Close();
			}
		}
	fileserv.Close();
	_LIT(KInfoLogFile1, "Saving Previous logs End.... \n");
	INFO_PRINTF1(KInfoLogFile1);
	}
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
	}
Esempio n. 15
0
void CPluginUtils::AddMultipartParamL( RBuf& aBuf, const TDesC& aParam, const TDesC& aValue )
	{
	aBuf.ReAllocL( aBuf.Length() + KBoundary().Length() + aParam.Length() + aValue.Length() + 2 + 2 + 2 + 2 + 2 + 1 + KDisposition().Length() );
	aBuf.Append( _L("--") );
	aBuf.Append( KBoundary() );
	aBuf.Append( KCrLf );
	aBuf.Append( KDisposition() );
	aBuf.Append( aParam );
	aBuf.Append( _L("\"") );
	aBuf.Append( KCrLf );
	aBuf.Append( KCrLf );
	aBuf.Append( aValue );
	aBuf.Append( KCrLf );
	}
Esempio n. 16
0
EXPORT_C void SoftwareTypeRegInfoUtils::SerializeUniqueSwTypeNamesL(const RPointerArray<Usif::CSoftwareTypeRegInfo>& aSwTypeRegInfoArray, RBuf& aSerializedNames)
	{
	const TInt numNames = aSwTypeRegInfoArray.Count();
	
	TInt bufLen = 0;
	for (TInt i=0; i<numNames; ++i)
		{
		const Usif::CSoftwareTypeRegInfo& info = *aSwTypeRegInfoArray[i];
		bufLen += info.UniqueSoftwareTypeName().Length() + sizeof(TChar);
		}
	
	aSerializedNames.ReAllocL(aSerializedNames.Length()+bufLen);
	
	for (TInt i=0; i<numNames; ++i)
		{
		const Usif::CSoftwareTypeRegInfo& info = *aSwTypeRegInfoArray[i];
		aSerializedNames.Append(info.UniqueSoftwareTypeName());
		aSerializedNames.Append(static_cast<TChar>(KUniqueNameSeparator));
		}
	}
// ---------------------------------------------------------------------------
//
// ---------------------------------------------------------------------------
//
void CaSqlQueryCreator::CreateIdListL( const TInt aIdEntryCount,
        RBuf& aEntryIdList, const TDesC& aColName )
    {
    DEBUG(("_CA_:CASqlQueryCreator::CreateIdListL"));
    //    Create an list of ids seperated by commas
    if( aIdEntryCount > 0 )
        {
        aEntryIdList.CreateL( aIdEntryCount * ( aColName.Length()
                + KMaxIntNumLength ) - 1 );
        for( TInt i = 0; i < aIdEntryCount; i++ )
            {
            aEntryIdList.Append( aColName );
            aEntryIdList.AppendNum( i );
            if( i != aIdEntryCount - 1 )
                {
                aEntryIdList.Append( KComma );
                }
            }
        }
    }
// ---------------------------------------------------------------------------
//
// ---------------------------------------------------------------------------
//
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 );
    }
Esempio n. 19
0
void CPluginUtils::AddMultipartParamL( RBuf& aBuf, const TDesC& aParam, TInt aValue )
	{
	TBuf<12> t;
	t.Format( _L("%d"), aValue );

	aBuf.ReAllocL( aBuf.Length() + KBoundary().Length() + aParam.Length() + t.Length() + 2 + 2 + 2 + 2 + 2 + 1 + KDisposition().Length() );
	aBuf.Append( _L("--") );
	aBuf.Append( KBoundary() );
	aBuf.Append( KCrLf );
	aBuf.Append( KDisposition() );
	aBuf.Append( aParam );
	aBuf.Append( _L("\"") );
	aBuf.Append( KCrLf );
	aBuf.Append( KCrLf );
	aBuf.Append( t );
	aBuf.Append( KCrLf );
	}
void AppendL(RBuf& aBuf, const TDesC& aDes, TBool aQuote)
	{
	const TInt requiredSpace = aDes.Length() + ((aBuf.Length() == 0) ? 0 : KEnumSeparator().Length()) + (aQuote ? 2 : 0);
	if ((aBuf.Length() + requiredSpace) > aBuf.MaxLength())
		{
		aBuf.ReAllocL(Max(aBuf.Length() * 2, aBuf.Length() + requiredSpace));
		}
	if (aBuf.Length() > 0)
		{
		aBuf.Append(KEnumSeparator);
		}
	if (aQuote)
		{
		aBuf.Append(KEnumQuote);
		}
	aBuf.Append(aDes);
	if (aQuote)
		{
		aBuf.Append(KEnumQuote);
		}
	}
Esempio n. 21
0
/** 
  Terminates the timer
  @param aComment Name of API.
*/
EXPORT_C void TTimerLogger::EndTimer(const TDesC& aComment)
	{
    #if defined (__LOG_PERFORMANCE) && !defined (_DEBUG)
	iEndTime.UniversalTime();
	TTimeIntervalMicroSeconds iTimeDifference = iEndTime.MicroSecondsFrom(iStartTime);	
	_LIT(KTimeDiff, ",%d microseconds\n");
	RBuf myBuf;
	TInt err = myBuf.Create (aComment.Length()+64);
	__ASSERT_ALWAYS(KErrNone == err, User::Invariant() );
	myBuf.Append (aComment );
	myBuf.AppendFormat(KTimeDiff, iTimeDifference.Int64());
    LogIt(myBuf);
	myBuf.Close();	
	iStartTime = 0;
	iEndTime = 0;
	#endif
	}
// ---------------------------------------------------------------------------
//
// ---------------------------------------------------------------------------
//
void CaSqlQueryCreator::ModifyQueryForSortOrderLastMostUsedL(
        const CCaInnerQuery::TSortAttribute aSortType, RBuf& aQuery )
    {
    DEBUG(("_CA_:CASqlQueryCreator::ModifyQueryForSortOrderLastMostUsedL"));

    RBuf descPart;
    descPart.CleanupClosePushL();
    if( aSortType == CCaInnerQuery::MostUsedDesc || 
         aSortType == CCaInnerQuery::LastUsedDesc )
        {
        descPart.CreateL( KDesc );
        }
    else
        {
        descPart.CreateL( KNullDesC );
        }

    RBuf usageDataQuery;
    usageDataQuery.CleanupClosePushL();
    if( aSortType == CCaInnerQuery::MostUsed || 
         aSortType == CCaInnerQuery::MostUsedDesc )
        {
        usageDataQuery.CreateL( KSQLGetMostUsed );
        }
    else
        {
        usageDataQuery.CreateL( KSQLGetLastUsed );
        }

    RBuf newQuery;
    newQuery.CleanupClosePushL();
    newQuery.CreateL( KSQLGetListByLaunchDataPart1().Length() +
            KSQLGetListByLaunchDataPart1().Length() +
            KSQLGetListByLaunchDataPart3().Length() +
            usageDataQuery.Length() +
            descPart.Length() +
            aQuery.Length() );
    newQuery.Append( KSQLGetListByLaunchDataPart1 );
    newQuery.Append( aQuery );
    newQuery.Append( KSQLGetListByLaunchDataPart2 );
    newQuery.Append( usageDataQuery );
    newQuery.Append( KSQLGetListByLaunchDataPart3 );
    newQuery.Append( descPart );
    aQuery.Close();
    aQuery.CreateL( newQuery );

    CleanupStack::PopAndDestroy( &newQuery );
    CleanupStack::PopAndDestroy( &usageDataQuery );
    CleanupStack::PopAndDestroy( &descPart );
    }
// ---------------------------------------------------------------------------
//
// ---------------------------------------------------------------------------
//
void CaSqlQueryCreator::CreateUpdateIconQueryL(
        const CCaInnerEntry* aEntry, CCaSqlQuery* aQuery )
    {
    DEBUG(("_CA_:CASqlQueryCreator::CreateUpdateIconQueryL"));
    RBuf query;
    query.CleanupClosePushL();
    query.CreateL( KSQLUpdateIcon().Length() );
    query.Append( KSQLUpdateIcon );
    if( aEntry->Icon()->FileName().Compare( KNullDesC ) )
        {
        query.ReAllocL( query.Length() + KSQLUpdateIconFileName().Length()
                + KComma().Length() );
        query.Append( KSQLUpdateIconFileName );
        query.Append( KComma );
        }
    if( aEntry->Icon()->SkinId().Compare( KNullDesC ) )
        {
        query.ReAllocL( query.Length() + KSQLUpdateIconSkinId().Length()
                + KComma().Length() );
        query.Append( KSQLUpdateIconSkinId );
        query.Append( KComma );
        }
     if( aEntry->Icon()->ApplicationId().Compare(KNullDesC) )
        {
        query.ReAllocL( query.Length() + KSQLUpdateIconAppId().Length()
                + KComma().Length() );
        query.Append( KSQLUpdateIconAppId );
        }
    if( !query.Right( KComma().Length() ).Compare( KComma ) )
        {
        query.Delete( query.Length() - KComma().Length(), KComma().Length() );
        }
    // add WHERE expr
    query.ReAllocL( query.Length() + KSQLUpdateIconWhere().Length() );
    query.Append( KSQLUpdateIconWhere );

    aQuery->SetQueryL( query );
    aQuery->SetTableType( CCaSqlQuery::EIconTable );

    CleanupStack::PopAndDestroy( &query );
    }
void IntegrityDeleteFileL(const TDesC& aPath, CIntegrityTreeLeaf* aLeaf, RFs& aFs, 
							   RLoader& aLoader, CFileMan& aFileMan)
	{
    _LIT(KSysBin, "\\sys\\bin");
	RBuf name;
	name.CreateL(aPath, KMaxFileName);
	CleanupClosePushL(name);
	name.Append(aLeaf->Name());

	TEntry entry;
	TInt err = aFs.Entry(name, entry);
	if (err == KErrNone)
		{
		aFs.SetAtt(name, 0, KEntryAttReadOnly);
		if(entry.IsDir())
			{
			// Make sure to append slash before calling RmDir - otherwise it deletes the parent directory			
			if (name[name.Length()-1] != KPathDelimiter) 
	  			{
  				name.Append(KPathDelimiter);
  				}
			User::LeaveIfError(aFileMan.RmDir(name));
			}
		else
			{			
            if ( aLeaf->Type() == EBackupFile ) // Implies a commit operation is in progress
                {
                
                 if ( IsBinary(entry) )
                     {
                     // Forming the file name so the renamed file can be under sys/bin
					 // for special delete mechanism using RLoader::Delete
                     RBuf tmpName;
                     TParsePtrC fileName(name);
                     tmpName.CreateL(name.Length() + KSysBin.iTypeLength);
                     CleanupClosePushL(tmpName);

                     tmpName.Append(fileName.Drive());
                     tmpName.Append(KSysBin);
                     tmpName.Append(fileName.Path());
                     tmpName.Append(fileName.NameAndExt());

					 DEBUG_PRINTF3(_L("Integrity Services - Renaming %S to %S"), &name, &tmpName);
                     aFileMan.Rename(name,tmpName,CFileMan::EOverWrite);
                     User::LeaveIfError(aLoader.Delete(tmpName)); // Using RLoader delete for paged binaries
					 DEBUG_PRINTF2(_L("Integrity Services - Deleted renamed file %S"), &tmpName);

					 // prune the directory tree if possible
                     RemoveDirectoryTreeL(aFs, tmpName);
                     CleanupStack::PopAndDestroy(&tmpName);
                     }
                 else
                     {
                     User::LeaveIfError(aFileMan.Delete(name));
                     }
                }
            else
                {
				// Need to use RLoader Delete which can be used during deletion of Added files during Rollback
                User::LeaveIfError(aLoader.Delete(name));
                }
			}
			
		// prune the directory tree if possible
		RemoveDirectoryTreeL(aFs, name);
		}
	else if(err != KErrNotFound && err != KErrPathNotFound)
		{
		DEBUG_PRINTF3(_L("Integrity Services - error %d removing %S"), err, &name);
		User::Leave(err);
		}
	else
	    {

		DEBUG_PRINTF3(_L("Integrity Services - error %d removing %S"), err, &name);

	    // Check for any renamed files to move it to sys/bin for special delete mechanism
	    RBuf tmpName;
	    TParsePtrC fileName(name);
	    tmpName.CreateL(name.Length() + KSysBin.iTypeLength);
	    CleanupClosePushL(tmpName);

	    tmpName.Append(fileName.Drive());
	    tmpName.Append(KSysBin);
	    tmpName.Append(fileName.Path());
	    tmpName.Append(fileName.NameAndExt());
		DEBUG_PRINTF2(_L("Integrity Services - Removing  %S renamed binary files if any"), &tmpName);

	    aLoader.Delete(tmpName);
		// prune the directory tree if possible
	    RemoveDirectoryTreeL(aFs, tmpName);
	    CleanupStack::PopAndDestroy(&tmpName);
	    }

	CleanupStack::PopAndDestroy(&name);
	}
// ---------------------------------------------------------------------------
//
// ---------------------------------------------------------------------------
//
void CaSqlQueryCreator::ModifyQueryForSortOrderL(
        const CCaInnerQuery::TSortAttribute aSortType, RBuf& aQuery,
        TBool aSortByGroup )
    {
    DEBUG(("_CA_:CASqlQueryCreator::ModifyQueryForSortOrderL"));
    switch ( aSortType )
        {
        case CCaInnerQuery::Name:
            {
            aQuery.ReAllocL( aQuery.Length()
                    + KSQLSortOrderNameAsc().Length() );
            aQuery.Append( KSQLSortOrderNameAsc );
            break;
            }
        case CCaInnerQuery::NameDesc:
            {
            aQuery.ReAllocL( aQuery.Length()
                    + KSQLSortOrderNameDesc().Length() );
            aQuery.Append( KSQLSortOrderNameDesc );
            break;
            }
        case CCaInnerQuery::CreatedTimestamp:
            {
            aQuery.ReAllocL( aQuery.Length()
                    + KSQLSortOrderCreatedTimestampAsc().Length() );
            aQuery.Append( KSQLSortOrderCreatedTimestampAsc );
            break;
            }
        case CCaInnerQuery::CreatedTimestampDesc:
            {
            aQuery.ReAllocL( aQuery.Length()
                    + KSQLSortOrderCreatedTimestampDesc().Length() );
            aQuery.Append( KSQLSortOrderCreatedTimestampDesc );
            break;
            }
        case CCaInnerQuery::MostUsed:
        case CCaInnerQuery::MostUsedDesc:
        case CCaInnerQuery::LastUsed:
        case CCaInnerQuery::LastUsedDesc:
            {
            ModifyQueryForSortOrderLastMostUsedL( aSortType, aQuery );
            break;
            }
        case CCaInnerQuery::DefaultDesc:
            {
            if( aSortByGroup )
                {
                aQuery.ReAllocL( aQuery.Length()
                        + KSQLSortOrderDefaultDesc().Length() );
                aQuery.Append( KSQLSortOrderDefaultDesc );
                }
            else
                {
                aQuery.ReAllocL( aQuery.Length()
                        + KSQLSortOrderIdDesc().Length() );
                aQuery.Append( KSQLSortOrderIdDesc );
                }
            break;
            }
        case CCaInnerQuery::Default:
        default:
            {
            if( aSortByGroup )
                {
                aQuery.ReAllocL( aQuery.Length()
                        + KSQLSortOrderDefault().Length() );
                aQuery.Append( KSQLSortOrderDefault );
                }
            else
                {
                aQuery.ReAllocL( aQuery.Length()
                        + KSQLSortOrderIdAsc().Length() );
                aQuery.Append( KSQLSortOrderIdAsc );
                }
            break;
            }
        }
    }
// ---------------------------------------------------------------------------
//
// ---------------------------------------------------------------------------
//
void CaSqlQueryCreator::CreateGetEntriesQueryByQueryL(
        const CCaInnerQuery* aQuery, CCaSqlQuery* aSqlQuery )
    {
    DEBUG(("_CA_:CASqlQueryCreator::CreateGetEntriesQueryByQueryL"));
    RBuf whereStatement;
    whereStatement.CleanupClosePushL();

    TUint flagsOn = aQuery->GetFlagsOn();
    if( flagsOn != 0 )
        {
        whereStatement.ReAllocL( KAnd().Length() + whereStatement.Length()
                + KSQLGetEntryFlagsOn().Length() );
        whereStatement.Append( KAnd );
        whereStatement.Append( KSQLGetEntryFlagsOn );
        }

    TUint flagsOff = aQuery->GetFlagsOff();
    if( flagsOff != 0 )
        {
        whereStatement.ReAllocL( KAnd().Length() + whereStatement.Length()
                + KSQLGetEntryFlagsOff().Length() );
        whereStatement.Append( KAnd );
        whereStatement.Append( KSQLGetEntryFlagsOff );
        }

    TInt role = aQuery->GetRole();
    if( role != 0 )
        {
        whereStatement.ReAllocL( KAnd().Length() + whereStatement.Length()
                + KSQLGetEntryRole().Length() );
        whereStatement.Append( KAnd );
        whereStatement.Append( KSQLGetEntryRole );
        }

    TUint uid = aQuery->GetUid();
    if( uid != 0 )
        {
        whereStatement.ReAllocL( KAnd().Length() + whereStatement.Length()
                + KSQLGetEntryUid().Length() );
        whereStatement.Append( KAnd );
        whereStatement.Append( KSQLGetEntryUid );
        }

    const CDesC16ArrayFlat* typeNames = aQuery->GetEntryTypeNames();

    if( typeNames && typeNames->MdcaCount() > 0 )
        {
        RBuf typeNameWhereStatement;
        typeNameWhereStatement.CleanupClosePushL();
        for( TInt i = 0; i < typeNames->MdcaCount(); i++ )
            {
            typeNameWhereStatement.ReAllocL(
                    typeNameWhereStatement.Length()
                    + typeNames->MdcaPoint( i ).Length()
                    + KSingleQuotes().Length() * 2 + KComma().Length() );
            typeNameWhereStatement.Append( KSingleQuotes );
            typeNameWhereStatement.Append( typeNames->MdcaPoint( i ) );
            typeNameWhereStatement.Append( KSingleQuotes );
            if( i != typeNames->MdcaCount() - 1 )
                {
                typeNameWhereStatement.Append( KComma );
                }
            }
        whereStatement.ReAllocL( KAnd().Length()
                + KSQLGetEntryTypeNames().Length()
                + typeNameWhereStatement.Length()
                + whereStatement.Length() );
        whereStatement.Append( KAnd );
        whereStatement.AppendFormat( KSQLGetEntryTypeNames,
                &typeNameWhereStatement );
        CleanupStack::PopAndDestroy( &typeNameWhereStatement );
        }
    
    if( aQuery->GetAttributes().Count() )
        {
        RBuf whereAttributes;
        whereAttributes.CleanupClosePushL();
        whereAttributes.CreateL( KEmpty );
        
        for( TInt j=1; j <= aQuery->GetAttributes().Count(); j++ )
            {
            // at1.AT_NAME = 'Attribute_Name_1' AND at1.AT_VALUE = 'Attribute_VALUE_1'
            TPtrC atrName( aQuery->GetAttributes().operator [](j-1)->Name() );
            TPtrC atrValue( aQuery->GetAttributes().operator [](j-1)->Value() );

            whereAttributes.ReAllocL( whereAttributes.Length() + 2 * KAnd().Length() + 
                    4 * KSingleQuotes().Length() +
                    2 * KMaxIntNumLength + 
                    2 * KAt().Length() + 2 * KDot().Length() + 2 * KEqual().Length() +
                    KColumnAttrName().Length() + KColumnAttrValue().Length() +
                    atrName.Length() + atrValue.Length() );
            
            whereAttributes.Append( KAnd );
            
            whereAttributes.Append( KAt );
            whereAttributes.AppendNum( j );
            whereAttributes.Append( KDot );
            whereAttributes.Append( KColumnAttrName );
            whereAttributes.Append( KEqual );
            whereAttributes.Append( KSingleQuotes );
            whereAttributes.Append( atrName );
            whereAttributes.Append( KSingleQuotes );
            
            whereAttributes.Append( KAnd );
            
            whereAttributes.Append( KAt );
            whereAttributes.AppendNum( j );
            whereAttributes.Append( KDot );
            whereAttributes.Append( KColumnAttrValue );
            whereAttributes.Append( KEqual );
            whereAttributes.Append( KSingleQuotes );
            whereAttributes.Append( atrValue );
            whereAttributes.Append( KSingleQuotes );
            
            }
        
        whereStatement.ReAllocL( whereStatement.Length() + whereAttributes.Length() );
        whereStatement.Append( whereAttributes );
        
        CleanupStack::PopAndDestroy( &whereAttributes );
        }

    RBuf leftJoins;
    leftJoins.CleanupClosePushL();
    leftJoins.CreateL( KEmpty );
    if( aQuery->GetAttributes().Count() )
        {
        for( TInt j=1; j <= aQuery->GetAttributes().Count(); j++ )
            {
            // LEFT JOIN CA_ATTRIBUTE as at1 ON ENTRY_ID = at1.AT_ENTRY_ID
            leftJoins.ReAllocL( leftJoins.Length() + 
                    KLeftJoinCaAttrubute1().Length() + KMaxIntNumLength +
                    KLeftJoinCaAttrubute2().Length() + KMaxIntNumLength +
                    KLeftJoinCaAttrubute3().Length()
                    );
            
            leftJoins.Append( KLeftJoinCaAttrubute1 );
            leftJoins.AppendNum( j );
            leftJoins.Append( KLeftJoinCaAttrubute2 );
            leftJoins.AppendNum( j );
            leftJoins.Append( KLeftJoinCaAttrubute3 );
            }
        }
    
    
    whereStatement.ReAllocL( whereStatement.Length() + 
            KGroupBy().Length() + KColumnEntryId().Length() );
    whereStatement.Append( KGroupBy );
    whereStatement.Append( KColumnEntryId );

    TInt groupId = aQuery->GetParentId();
    RBuf query;
    query.CleanupClosePushL();
    if( groupId > 0 )
        {
        RBuf getListByParentId2withWhere;
        getListByParentId2withWhere.CleanupClosePushL();
        getListByParentId2withWhere.CreateL( KSQLGetListByParentId2().Length() + whereStatement.Length() );
        getListByParentId2withWhere.AppendFormat( KSQLGetListByParentId2, &whereStatement );
        
        query.ReAllocL( KSQLGetListByParentId1().Length() +  leftJoins.Length() +
                getListByParentId2withWhere.Length() );
        query.Append( KSQLGetListByParentId1 );
        query.Append( leftJoins );
        query.Append( getListByParentId2withWhere );
        CleanupStack::PopAndDestroy( &getListByParentId2withWhere );
        }
    else if ( aQuery->GetChildId() > 0 )
        {
        RBuf getListByCildIdwithWhere;
        getListByCildIdwithWhere.CleanupClosePushL();
        getListByCildIdwithWhere.CreateL( KSQLGetListByChildId().Length() + whereStatement.Length() );
        getListByCildIdwithWhere.AppendFormat( KSQLGetListByChildId, &whereStatement );
        
        query.ReAllocL( KSQLGetListByParentId1().Length() +  leftJoins.Length() +
                getListByCildIdwithWhere.Length() );
        query.Append( KSQLGetListByParentId1 );
        query.Append( leftJoins );
        query.Append( getListByCildIdwithWhere );
        CleanupStack::PopAndDestroy( &getListByCildIdwithWhere );
        }
    else
        {
        query.CreateL( KSQLGetList1().Length() );
        query.Append( KSQLGetList1 );
        query.ReAllocL( query.Length() + leftJoins.Length() + KSQLGetList2().Length() );
        query.Append( leftJoins );
        query.Append( KSQLGetList2 );
        if( whereStatement.Length() >= KAnd().Length() )
            {
            TPtrC ptrWhereStatement( whereStatement.Right(
                    whereStatement.Length() - KAnd().Length() ) );
            query.ReAllocL( query.Length() +  KWhere().Length()
                    + ptrWhereStatement.Length() );

            query.Append( KWhere );
            query.Append( ptrWhereStatement );
            }
        }

    CCaInnerQuery::TSortAttribute sort = aQuery->GetSort();
    ModifyQueryForSortOrderL( sort, query, groupId > 0 );

    if( aQuery->GetCount() > 0 )
        {
        query.ReAllocL( query.Length() + KLimit().Length()
                + KMaxIntNumLength );
        query.Append( KLimit );
        TInt limitCount = aQuery->GetCount();
        query.AppendNum( limitCount );
        }

    aSqlQuery->SetQueryL( query );
    CleanupStack::PopAndDestroy( &query );
    CleanupStack::PopAndDestroy( &leftJoins );
    CleanupStack::PopAndDestroy( &whereStatement );
    }
// ---------------------------------------------------------------------------
//
// ---------------------------------------------------------------------------
//
void CaSqlQueryCreator::CreateAddQueryL( CCaInnerEntry* aEntry,
        RPointerArray<CCaSqlQuery>& aSqlQuery, RSqlDatabase& aSqlDb )
    {
    DEBUG(("_CA_:CASqlQueryCreator::CreateAddQueryL"));
    CCaSqlQuery* queryIcon = CCaSqlQuery::NewLC( aSqlDb );
    
    TIconType iconType = CaSqlQueryCreator::CheckIconType( aEntry );
    
    if( iconType == EProperIcon )
        {
        CreateAddIconQueryL( aEntry, queryIcon, aSqlDb );
        //add new icon to DB
        aSqlQuery.AppendL( queryIcon );
        CleanupStack::Pop( queryIcon );
        }
    else
        {
        // icon added to DB by another entry or not added
        CleanupStack::PopAndDestroy( queryIcon );
        queryIcon = NULL;
        }

    if( aEntry->GetId() != -1 )
        {
        // check if entry is new and has to be added to DB or just updated
        CCaSqlQuery* query = CCaSqlQuery::NewLC( aSqlDb );
        if( aEntry->GetId() > 0 )
            {
            //Update query is faster than replace query
            CreateUpdateQueryEntryL( aEntry, query );
            }
        else
            {
            // check if entry's Uid was set
            if( aEntry->GetUid() == 0 )
                {
                if( ( aEntry->GetIconId() == 0 ) && ( queryIcon == NULL ) )
                    {
                    query->SetQueryL( 
                            KSQLInsertToEntryUniqueUidWithoutIcon );
                    }
                else
                    {
                    query->SetQueryL( KSQLInsertToEntryUniqueUid );
                    }
                }
            else
                {
                if( ( aEntry->GetIconId() == 0 ) && ( queryIcon == NULL ) )
                    {
                    query->SetQueryL( KSQLInsertToEntryWithoutIcon );
                    }
                else
                    {
                    query->SetQueryL( KSQLInsertToEntry );
                    }
                }
            }
        query->SetTableType( CCaSqlQuery::EEntryTable );
        aSqlQuery.AppendL( query );
        CleanupStack::Pop( query );
        }
    // remove all entry's attributs from DB
    CCaSqlQuery* query = CCaSqlQuery::NewLC( aSqlDb );
    query->SetQueryL( KSQLDeleteAttribute );
    aSqlQuery.Append( query );
    query->SetTableType( CCaSqlQuery::EAttributeTable );
    CleanupStack::Pop( query );

    if( aEntry->GetAttributes().Count() > 0 )
        {
        CCaSqlQuery* query = CCaSqlQuery::NewLC( aSqlDb );
        query->SetQueryL( KSQLInsertToAttribute );
        aSqlQuery.AppendL( query );
        query->SetTableType( CCaSqlQuery::EAttributeTable );
        CleanupStack::Pop( query );
        }
    
    if( iconType == ENullIconToRemove )
        {
        RBuf queryRemoveIcon;
        queryRemoveIcon.CleanupClosePushL();
        queryRemoveIcon.CreateL( KSQLDeleteIconWhereIconId().Length() );
        queryRemoveIcon.Append( KSQLDeleteIconWhereIconId );
        queryRemoveIcon.ReAllocL( KSQLDeleteIconWhereIconId().Length() + KMaxIntNumLength );
        queryRemoveIcon.AppendNum( aEntry->GetIconId() );
        
        CCaSqlQuery* query = CCaSqlQuery::NewLC( aSqlDb );
        query->SetQueryL( queryRemoveIcon );
        aSqlQuery.AppendL( query );
        query->SetTableType( CCaSqlQuery::EIconTable );
        
        CleanupStack::Pop( query );
        CleanupStack::PopAndDestroy( &queryRemoveIcon );
        }
    }
// ---------------------------------------------------------------------------
//
// ---------------------------------------------------------------------------
//
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::CreateUpdateQueryEntryL(
        const CCaInnerEntry* aEntry, CCaSqlQuery* aQuery )
    {
    DEBUG( ("_CA_:CASqlQueryCreator::CreateUpdateQueryEntryL") );
    RBuf query;
    query.CleanupClosePushL();
    query.CreateL( KSQLUpdateEntry().Length() );
    query.Append( KSQLUpdateEntry );
    // text
    if( aEntry->GetText().Length() != 0 )
        {
        query.ReAllocL( query.Length() + KSQLUpdateEntryText().Length()
                + KComma().Length() );
        query.Append( KSQLUpdateEntryText );
        query.Append( KComma );
        }
    // description
    query.ReAllocL( query.Length() + KSQLUpdateEntryDescription().Length()
            + KComma().Length() );
    query.Append( KSQLUpdateEntryDescription );
    query.Append( KComma );
    // role
    query.ReAllocL( query.Length() + KSQLUpdateEntryRole().Length()
            + KComma().Length() );
    query.Append( KSQLUpdateEntryRole );
    query.Append( KComma );
    // type_name
    if( aEntry->GetEntryTypeName().Length() != 0 )
        {
        query.ReAllocL( query.Length() + KSQLUpdateEntryTypeName().Length()
                + KComma().Length() );
        query.Append( KSQLUpdateEntryTypeName );
        query.Append( KComma );
        }
    // id_icon
    TIconType iconType = CaSqlQueryCreator::CheckIconType( aEntry );
    if( iconType == ENullIconToRemove || iconType == ENullIcon )
        {
        query.ReAllocL( query.Length( ) + 
                KSQLUpdateEntryIdIconNull().Length() + KComma().Length() );
        query.Append( KSQLUpdateEntryIdIconNull );
        }
    else
        { 
        query.ReAllocL( query.Length( ) + KSQLUpdateEntryIdIcon().Length()
                + KComma().Length() );
        query.Append( KSQLUpdateEntryIdIcon );
        }
    query.Append( KComma );
    // check if entry's Uid was set
    if( aEntry->GetUid() )
        {
        query.ReAllocL( query.Length() + KSQLUpdateEntryUid().Length()
                + KComma().Length() );
        query.Append( KSQLUpdateEntryUid );
        query.Append( KComma );
        }
    else
        {
        query.ReAllocL( query.Length() + KSQLUpdateEntryUidNULL().Length()
                + KComma().Length() );
        query.Append( KSQLUpdateEntryUidNULL );
        query.Append( KComma );
        }
    //flags
    query.ReAllocL( query.Length() + KSQLUpdateEntryFlags().Length()
            + KComma().Length() );
    query.Append( KSQLUpdateEntryFlags );

    query.ReAllocL( query.Length() + KSQLUpdateWhere().Length() );
    query.Append( KSQLUpdateWhere );

    aQuery->SetQueryL( query );
    CleanupStack::PopAndDestroy( &query );
    }
/**
GetObjectHandles request handler
*/	
void CMTPGetObjectHandles::ServiceL()
	{
    OstTraceFunctionEntry0( CMTPGETOBJECTHANDLES_SERVICEL_ENTRY );
    
    if(iSingletons.DpController().EnumerateState() != CMTPDataProviderController::EEnumeratedFulllyCompleted)
        {
        TUint storageId = Request().Uint32(TMTPTypeRequest::ERequestParameter1);
        TUint handle = Request().Uint32(TMTPTypeRequest::ERequestParameter3);
        TUint enumerateState = iSingletons.DpController().StorageEnumerateState(storageId);
        if ( (enumerateState < CMTPDataProviderController::EEnumeratingPhaseOneDone)
            || (enumerateState != CMTPDataProviderController::EEnumeratedFulllyCompleted && handle != KMTPHandleAll))
            {
            if (iTimeoutCount++ >= KMTPGetObjectHandlesTimeOut)
                {
                OstTrace0( TRACE_NORMAL, CMTPGETOBJECTHANDLES_SERVICEL, 
                        "Wait for enumeration time out, return busy." );
                SendResponseL(EMTPRespCodeDeviceBusy);
                iTimeoutCount = 0;
                OstTraceFunctionExit0( CMTPGETOBJECTHANDLES_SERVICEL_EXIT );
                return;
                }
            else
                {
                OstTrace0( TRACE_NORMAL, DUP1_CMTPGETOBJECTHANDLES_SERVICEL, 
                        "Enumeration not completed, suspend request." );
                RegisterPendingRequest(20);
                OstTraceFunctionExit0( DUP1_CMTPGETOBJECTHANDLES_SERVICEL_EXIT );
                return; 
                }
            }
        }
    
    iTimeoutCount = 0;
    
	delete iHandles;
	iHandles = NULL;
	iHandles = CMTPTypeArray::NewL(EMTPTypeAUINT32);

	OstTraceExt2( TRACE_NORMAL, DUP2_CMTPGETOBJECTHANDLES_SERVICEL, 
	        "IsConnectMac = %d; ERequestParameter2 = %d", iDevDpSingletons.DeviceDataStore().IsConnectMac(), Request().Uint32(TMTPTypeRequest::ERequestParameter2));	
    if(iDevDpSingletons.DeviceDataStore().IsConnectMac()
       &&(KMTPFormatsAll == Request().Uint32(TMTPTypeRequest::ERequestParameter2)))
        {
        OstTrace0( TRACE_NORMAL, DUP3_CMTPGETOBJECTHANDLES_SERVICEL, "ConnectMac and Fetch all." );
        HandleObjectHandlesUnderMacL(*iHandles);
        }
    else
        {
    	RMTPObjectMgrQueryContext   context;
    	RArray<TUint>               handles;
    	CleanupClosePushL(context);
    	CleanupClosePushL(handles);        
    	TMTPObjectMgrQueryParams    params(Request().Uint32(TMTPTypeRequest::ERequestParameter1), Request().Uint32(TMTPTypeRequest::ERequestParameter2), Request().Uint32(TMTPTypeRequest::ERequestParameter3));	
    	do
    	    {
        	iFramework.ObjectMgr().GetObjectHandlesL(params, context, handles);
			
        	TUint32 storageId = Request().Uint32(TMTPTypeRequest::ERequestParameter1);
        	TUint32 parentHandle = Request().Uint32(TMTPTypeRequest::ERequestParameter3);
        	if ( storageId != KMTPStorageAll && parentHandle == KMTPHandleNoParent )
	            {
	            const CMTPStorageMetaData& storage(iFramework.StorageMgr().StorageL(storageId));
	            HBufC* StorageSuid = storage.DesC(CMTPStorageMetaData::EStorageSuid).AllocL();
            
	            RBuf suid;
	            suid.CleanupClosePushL();
	            suid.CreateL(KMaxFileName);
	            suid = *StorageSuid;
	            _LIT(WMPInfoXml,"WMPInfo.xml");
	            suid.Append(WMPInfoXml); 
	            TUint32 handle = iFramework.ObjectMgr().HandleL(suid);
	            if ( handle != KMTPHandleNone )
	                {
	                TInt index = handles.Find(handle);
	                if ( index != KErrNotFound )
	                    {
	                    handles.Remove(index);
	                    handles.InsertL(handle,0);
	                    }
	                }   
	            delete StorageSuid;
	            StorageSuid = NULL;
	            CleanupStack::PopAndDestroy();
            	}
        	iHandles->AppendL(handles);
    	    }
    	while (!context.QueryComplete()); 
    	CleanupStack::PopAndDestroy(&handles);
    	CleanupStack::PopAndDestroy(&context);        
        }        
    						
	SendDataL(*iHandles);
	OstTraceFunctionExit0( DUP2_CMTPGETOBJECTHANDLES_SERVICEL_EXIT );
	}