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);
	}
TInt FConnection::GetIAPIDFromName(const StringBuffer& aIAPName)
{
    TInt ret = -1;
    RBuf iapName;
    iapName.Assign(stringBufferToNewBuf(aIAPName));

    CCommsDatabase* commDb = CCommsDatabase::NewL(EDatabaseTypeIAP);
    CleanupStack::PushL(commDb);
    CApSelect* select = CApSelect::NewLC(*commDb,KEApIspTypeAll,EApBearerTypeAll,KEApSortUidAscending);

    TBool ok = select->MoveToFirst();
    for (TUint32 i=0; ok &&(i<select->Count()); i++)
    {
        StringBuffer tmp = bufToStringBuffer(select->Name());
        //LOG.debug("Found IAP: %s (id = %d)", tmp.c_str(), select->Uid());
        if (select->Name() == iapName) {
            ret = select->Uid();
            //LOG.debug("Found IAP: %s (id = %d)", aIAPName.c_str(), ret);
            break;
        }
        else {
            ok = select->MoveNext();
        }
    }
    //LOG.debug("IAP Found");
    CleanupStack::PopAndDestroy(2);    //commdb and select

    return ret;
}
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); 
	}
//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 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());
	}
Exemple #6
0
TInt E32Main()
	{
	TInt cmdLineLen = User::CommandLineLength();
	if (cmdLineLen == 0)
		return PagingInfo::PrintAll();
	else
		{
		RBuf cmdLine;
		TInt r = cmdLine.Create(cmdLineLen);
		if (r != KErrNone)
			return r;
		User::CommandLine(cmdLine);

		if (cmdLine == _L("-r"))
			{
			RDebug::Printf("Resetting demand paging info");
			return PagingInfo::ResetAll();
			}
		else
			{
			RDebug::Printf("usage: dpinfo [-r]");
			return KErrArgument;
			}
		}
	}
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);
	}
//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()
	}
//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()
	}
/*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;
	}	
/**
  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();

    }
/**
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;
	}
Exemple #13
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;
	}
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"));
    }
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;
			}
		}
	}
//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);	
	}
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 );
    }
void CFeatRegListBoxData::DoInfoForDialogL(RBuf& aTitle, RBuf& inf, TDes* /*name*/)
	{
	SFeature& info = *reinterpret_cast<SFeature*>(iInfo);

	_LIT(KInfo, "Feature info");
	aTitle.Copy(KInfo);

	gPlugin->FormatValue(inf, MProductPlugin::EFeature, info.iFeature, 0);
	_LIT(KFeatureFmt, "\n0x%x\n\nFeature present: %i\n(Additional info: %i)");

	inf.AppendFormat(KFeatureFmt, info.iFeature, info.iErr, info.iInfo);
	}
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,
    }
//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 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 CQueueEntry::InternalizeL( RReadStream& aStream )
    {
    TInt size;
    RBuf text;
	CleanupClosePushL( text );
    RBuf8 text8;
	CleanupClosePushL( text8 );

    size =  aStream.ReadInt32L( );
    text.ReAllocL( size );
    aStream.ReadL( text, size ); 
    SetUrlL(text);

    size =  aStream.ReadInt32L( );
    if( size > text.Length() ) text.ReAllocL( size );
    aStream.ReadL( text, size ); 
    SetTitleL(text);

    size =  aStream.ReadInt32L( );
    if( size > text.Length() ) text.ReAllocL( size );
    aStream.ReadL( text, size ); 
    SetTagsL(text);

    size =  aStream.ReadInt32L( );
    if( size > text.Length() ) text.ReAllocL( size );
    aStream.ReadL( text, size ); 
    SetDescriptionL( text );

    size =  aStream.ReadInt32L( );
    if( size > text.Length() ) text.ReAllocL( size );
    aStream.ReadL( text, size ); 
    SetFilename( text );

	CleanupStack::PopAndDestroy( &text8 );
	CleanupStack::PopAndDestroy( &text );
    
    iType = (TEntryType) aStream.ReadInt32L( );

	iStatus = (TEntryStatus) aStream.ReadInt32L( );

	iCategory = (TMovieCategory) aStream.ReadInt32L( );

	iPublic = aStream.ReadInt32L( );
		
	iSize = aStream.ReadInt32L( );

	iUid = aStream.ReadInt32L( );
    }
void CWindowGroupListBoxData::DoFormatL(TObjectKernelInfo* aInfo, RBuf& name, RBuf& more, TInt& /*itemId*/)
	{
	SWgInfo& info = *reinterpret_cast<SWgInfo*>(aInfo);
	CApaWindowGroupName* wgName = info.iName;
	name.Copy(wgName->Caption());
	_LIT(KUnnamed, "<Untitled window group>");
	if (name.Length() == 0) name.Copy(KUnnamed);

	TThreadId tid;
	TInt res = info.iSession->GetWindowGroupClientThreadId(info.iHandle, tid);
	if (res == KErrNone)
		{
		res = tid;
		}
	more.Format(_L("Busy=%i System=%i Tid=%i"), wgName->IsBusy(), wgName->IsSystem(), res);
	}
void CMscFileSession::SetupLogicalUnitL( const RMessage2& aMessage )
    {
    TRACE_FUNC_ENTRY
    TInt protocol;
    TInt lun;
    RBuf fullImageFileName;
    TInt len = aMessage.GetDesLength( 0 );
    fullImageFileName.CreateL( len );
    fullImageFileName.CleanupClosePushL();
    aMessage.ReadL( 0, fullImageFileName );
    protocol = aMessage.Int1();
    lun = aMessage.Int2();
    
    iMscFileServer.Controller().SetupLogicalUnitL( fullImageFileName, protocol, lun );
    CleanupStack::PopAndDestroy( &fullImageFileName );
    TRACE_FUNC_EXIT
    }
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();
}
/** 
  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
	}