Revision: 201009 RCL_3
authorDremov Kirill (Nokia-D-MSW/Tampere) <kirill.dremov@nokia.com>
Mon, 15 Mar 2010 12:42:24 +0200
branchRCL_3
changeset 7 3cebc1a84278
parent 6 646a02f170b9
child 8 50de4d668bb6
Revision: 201009 Kit: 201010
clfwrapper/ClientSrc/CCLFDefaultOperation.cpp
clfwrapper/ClientSrc/CCLFEngineImpl.cpp
clfwrapper/ClientSrc/CCLFItemListModelImpl.cpp
clfwrapper/ClientSrc/CCLFSortingStyleImpl.cpp
contextengine/plugins/calendarplugin/group/calendarcontextplugin.mmp
harvester/blacklistclient/src/blacklistclient.cpp
harvester/blacklistserver/src/blacklistserver.cpp
harvester/client/src/harvestereventobserverao.cpp
harvester/client/src/harvesterrequestqueue.cpp
harvester/common/bwincw/harvestercommonwinscw.def
harvester/common/eabi/harvestercommonarm.def
harvester/common/inc/harvestercommon.h
harvester/common/inc/harvesterpluginfactory.h
harvester/common/src/harvestercenreputil.cpp
harvester/common/src/harvesterplugin.cpp
harvester/common/src/harvesterpluginfactory.cpp
harvester/common/src/listener.cpp
harvester/common/src/propertywatcher.cpp
harvester/composerplugins/imagecomposer/src/composerimageplugin.cpp
harvester/composerplugins/imagecomposer/src/imagecomposerao.cpp
harvester/harvesterplugins/AudioPlugin/inc/harvesteraudioplugin.h
harvester/harvesterplugins/AudioPlugin/src/harvesteraudioplugin.cpp
harvester/harvesterplugins/ImagePlugin/src/harvesterimageplugin.cpp
harvester/harvesterplugins/MessagePlugin/src/harvestermessageplugin.cpp
harvester/harvesterplugins/OMADRMPlugin/src/harvesteromadrmplugin.cpp
harvester/harvesterplugins/RTPPlugin/src/harvesterrtpplugin.cpp
harvester/harvesterplugins/VideoPlugin/src/harvestervideoplugin.cpp
harvester/harvesterplugins/WMVPlugin/src/harvesterwmvplugin.cpp
harvester/monitorplugins/fileplugin/src/fileeventhandlerao.cpp
harvester/monitorplugins/inc/fsutil.inl
harvester/monitorplugins/mdsoomplugin/inc/mdsoomplugin.h
harvester/monitorplugins/mdsoomplugin/src/mdsoomplugin.cpp
harvester/monitorplugins/mmcplugin/inc/mmcmonitorao.h
harvester/monitorplugins/mmcplugin/inc/mmcscannerao.h
harvester/monitorplugins/mmcplugin/src/mmcmonitorao.cpp
harvester/monitorplugins/mmcplugin/src/mmcmonitorplugin.cpp
harvester/monitorplugins/mmcplugin/src/mmcmounttaskao.cpp
harvester/monitorplugins/mmcplugin/src/mmcscannerao.cpp
harvester/server/group/harvesterserver.mmp
harvester/server/inc/harvesterao.h
harvester/server/inc/harvesterdiskspaceobserver.h
harvester/server/inc/restorewatcher.h
harvester/server/src/harvesterao.cpp
harvester/server/src/harvesterdiskspaceobserver.cpp
harvester/server/src/harvesteroomao.cpp
harvester/server/src/harvesterqueue.cpp
harvester/server/src/harvesterserver.cpp
harvester/server/src/harvesterserversession.cpp
harvester/server/src/mdeobjecthandler.cpp
harvester/server/src/restorewatcher.cpp
inc/mdscommoninternal.h
locationmanager/client/src/rlocationobjectmanipulator.cpp
locationmanager/client/src/rtracklog.cpp
locationmanager/locationtrail/inc/clocationrecord.h
locationmanager/locationtrail/src/cgpxconverterao.cpp
locationmanager/locationtrail/src/clocationrecord.cpp
locationmanager/locationtrail/src/cpositioninfo.cpp
locationmanager/locationtrail/src/locationremappingao.cpp
locationmanager/server/inc/clocationmanagerserver.h
locationmanager/server/src/clocationmanagerserver.cpp
mds_plat/metadata_engine_api/inc/mdeobjectdef.h
mds_plat/metadata_engine_api/inc/mdesession.h
metadataengine/client/group/mdeclient.mmp
metadataengine/client/inc/mdenotifierao.h
metadataengine/client/inc/mdesessionimpl.h
metadataengine/client/src/mdeharvestersession.cpp
metadataengine/client/src/mdelogiccondition.cpp
metadataengine/client/src/mdenotifierao.cpp
metadataengine/client/src/mdeobjectcondition.cpp
metadataengine/client/src/mdeobjectdef.cpp
metadataengine/client/src/mdequery.cpp
metadataengine/client/src/mdequerycriteriaserialization.cpp
metadataengine/client/src/mdesessionimpl.cpp
metadataengine/common/src/mdcserializationbuffer.cpp
metadataengine/server/group/mdsserver.mmp
metadataengine/server/inc/mdsmanipulationengine.h
metadataengine/server/inc/mdsnamespacedef.h
metadataengine/server/inc/mdsnotifier.h
metadataengine/server/inc/mdsnotifycomparator.h
metadataengine/server/inc/mdssqlobjectmanipulate.h
metadataengine/server/src/mdsfindsqlclause.cpp
metadataengine/server/src/mdsgetimeiao.cpp
metadataengine/server/src/mdsmanipulationengine.cpp
metadataengine/server/src/mdsnamespacedef.cpp
metadataengine/server/src/mdsnotifier.cpp
metadataengine/server/src/mdsnotifycomparator.cpp
metadataengine/server/src/mdsschema.cpp
metadataengine/server/src/mdsserver.cpp
metadataengine/server/src/mdsserversession.cpp
metadataengine/server/src/mdssqlfindoperation.cpp
metadataengine/server/src/mdssqlobjectmanipulate.cpp
sis/mds/mds_stub.sis
sis/mds/package.pkg
sis/mds/package_separate.pkg
sis/mds/stub.pkg
watchdog/src/watchdog.cpp
--- a/clfwrapper/ClientSrc/CCLFDefaultOperation.cpp	Fri Mar 12 15:44:28 2010 +0200
+++ b/clfwrapper/ClientSrc/CCLFDefaultOperation.cpp	Mon Mar 15 12:42:24 2010 +0200
@@ -102,8 +102,7 @@
 void AppendItemsToArrayL( const TArray<MCLFItem*>& aSourceArray,
                           RPointerArray<MCLFItem>& aDestArray )
     {
-    const TInt count( aSourceArray.Count() );
-    for( TInt i = 0 ; i < count ; ++i )
+    for( TInt i = aSourceArray.Count() - 1; i >=0; i--)
         {
         aDestArray.AppendL( aSourceArray[ i ] );
         }
--- a/clfwrapper/ClientSrc/CCLFEngineImpl.cpp	Fri Mar 12 15:44:28 2010 +0200
+++ b/clfwrapper/ClientSrc/CCLFEngineImpl.cpp	Mon Mar 15 12:42:24 2010 +0200
@@ -308,8 +308,7 @@
 
     if ( aError )
         {
-        const TInt count( iChangedItemObserverArray.Count() );
-        for( TInt i = 0 ; i < count ; ++i )
+        for( TInt i = iChangedItemObserverArray.Count() - 1; i >=0; i--)
             {
             iChangedItemObserverArray[i]->HandleError( aError );
             }
@@ -326,8 +325,7 @@
         // notify changed item observers
         if ( iChangedItemModel.iChangedItemIdArray.Count() > 0 )
             {
-            const TInt count( iChangedItemObserverArray.Count() );
-            for( TInt i = 0 ; i < count ; ++i )
+            for( TInt i = iChangedItemObserverArray.Count() - 1; i >=0; i--)
                 {
                 iChangedItemObserverArray[i]->HandleItemChangeL(
                             iChangedItemModel.iChangedItemIdArray.Array() );
--- a/clfwrapper/ClientSrc/CCLFItemListModelImpl.cpp	Fri Mar 12 15:44:28 2010 +0200
+++ b/clfwrapper/ClientSrc/CCLFItemListModelImpl.cpp	Mon Mar 15 12:42:24 2010 +0200
@@ -284,7 +284,7 @@
             }
         CDesCArray* array = new (ELeave) CDesCArrayFlat( mimeTypeCount );
         CleanupStack::PushL( array );
-        for( TInt i = 0 ; i < mimeTypeCount ; ++i )
+        for( TInt i = mimeTypeCount - 1; i >=0; i--)
             {
             array->AppendL( aMimeTypes.MdcaPoint( i ) );
             }
@@ -335,7 +335,7 @@
         CArrayFix<TInt>* array =
                         new ( ELeave ) CArrayFixFlat<TInt>( count );
         CleanupStack::PushL( array );
-        for( TInt i = 0 ; i < count ; ++i )
+        for(TInt i = count - 1; i >=0; i--)
             {
             array->AppendL( aMediaTypes[i] );
             }
@@ -363,7 +363,7 @@
         CArrayFix<TInt>* array =
                 new ( ELeave ) CArrayFixFlat<TInt>( numMediaTypes );
         CleanupStack::PushL( array );
-        for( TInt i = 0 ; i < numMediaTypes ; ++i )
+        for( TInt i = numMediaTypes - 1; i >=0; i--)
             {
             array->AppendL( aResource.ReadInt32() );
             }
@@ -443,8 +443,7 @@
 void CCLFItemListModelImpl::CopyArrayL( const TArray<MCLFItem*>& aSource,
                                         RPointerArray<MCLFItem>& aDest )
     {
-    const TInt count( aSource.Count() );
-    for( TInt i = 0 ; i < count ; ++i )
+    for( TInt i = aSource.Count() - 1; i >=0; i--)
         {
         aDest.AppendL( aSource[i] );
         }
@@ -532,7 +531,7 @@
         const TInt count( iItemArray.Count() );
         RArray<TCLFItemId> idArray( count == 0 ? 1 : count );
         CleanupClosePushL( idArray );
-        for( TInt i = 0 ; i < count ; ++i )
+        for( TInt i = count - 1; i >=0; i--)
             {
             idArray.AppendL( iItemArray[i]->ItemId() );
             }
--- a/clfwrapper/ClientSrc/CCLFSortingStyleImpl.cpp	Fri Mar 12 15:44:28 2010 +0200
+++ b/clfwrapper/ClientSrc/CCLFSortingStyleImpl.cpp	Mon Mar 15 12:42:24 2010 +0200
@@ -127,8 +127,7 @@
 //
 void CCLFSortingStyleImpl::GetFieldsL( RArray<TCLFFieldId>& aArray ) const
     {
-    const TInt count( iFieldIDArray.Count() );
-    for( TInt i = 0 ; i < count ; ++i )
+    for( TInt i = iFieldIDArray.Count() - 1; i >=0; i--)
         {
         aArray.AppendL( iFieldIDArray[i] );
         }
--- a/contextengine/plugins/calendarplugin/group/calendarcontextplugin.mmp	Fri Mar 12 15:44:28 2010 +0200
+++ b/contextengine/plugins/calendarplugin/group/calendarcontextplugin.mmp	Mon Mar 15 12:42:24 2010 +0200
@@ -61,5 +61,5 @@
 
 PAGED
 BYTEPAIRCOMPRESSTARGET
-OPTION ARMCC -O3 -OTime
+OPTION ARMCC -O2 -OTime
 
--- a/harvester/blacklistclient/src/blacklistclient.cpp	Fri Mar 12 15:44:28 2010 +0200
+++ b/harvester/blacklistclient/src/blacklistclient.cpp	Mon Mar 15 12:42:24 2010 +0200
@@ -37,14 +37,14 @@
 //
 EXPORT_C RBlacklistClient::~RBlacklistClient()
     {
-    WRITELOG( "CBlacklistServer::~RBlacklistClient - begin" );
+    WRITELOG( "RBlacklistClient::~RBlacklistClient - begin" );
     
     RSessionBase::Close(); 
     iBlacklistMemoryTable.ResetAndDestroy();
     iBlacklistMemoryTable.Close();
 	iBlacklistChunk.Close();
 
-    WRITELOG( "CBlacklistServer::~RBlacklistClient - end" );
+    WRITELOG( "RBlacklistClient::~RBlacklistClient - end" );
     }
 
 // ---------------------------------------------------------------------------
@@ -53,7 +53,7 @@
 //
 EXPORT_C TInt RBlacklistClient::Connect()
     {
-    WRITELOG( "CBlacklistServer::Connect - begin" );
+    WRITELOG( "RBlacklistClient::Connect - begin" );
 
     TInt retryCount = 2;
     TInt error = KErrNone;
@@ -81,7 +81,7 @@
         --retryCount;
         }
     
-    WRITELOG( "CBlacklistServer::Connect - end" );
+    WRITELOG( "RBlacklistClient::Connect - end" );
 
     return error;
     }
@@ -92,7 +92,7 @@
 //
 TVersion RBlacklistClient::Version() const
     {
-    WRITELOG( "CBlacklistServer::Version - begin" );
+    WRITELOG( "RBlacklistClient::Version - begin" );
 
     return TVersion( KBlacklistServerMajorVersion, KBlacklistServerMinorVersion,
     	KBlacklistServerBuildVersion );
@@ -105,7 +105,7 @@
 //
 TInt RBlacklistClient::StartServer()
     {
-    WRITELOG( "CBlacklistServer::CustomSecurityCheckL - begin" );
+    WRITELOG( "RBlacklistClient::CustomSecurityCheckL - begin" );
 
     const TUidType serverUid = ( KNullUid, KNullUid, KUidKBlacklistServer );
 
@@ -132,7 +132,7 @@
     error = server.ExitType() == EExitPanic ? KErrGeneral : status.Int();
     server.Close();
 
-    WRITELOG( "CBlacklistServer::Version - end" );
+    WRITELOG( "RBlacklistClient::Version - end" );
 
     return error;
     }
@@ -143,7 +143,7 @@
 //
 void RBlacklistClient::RemoveFromDBL( const TDesC& aUri, TUint32 aMediaId ) const
     {
-    WRITELOG( "CBlacklistServer::RemoveFromDBL - begin" );
+    WRITELOG( "RBlacklistClient::RemoveFromDBL - begin" );
 
     TPckgBuf<TUint32> mediaIdPckg( aMediaId );
     
@@ -154,7 +154,7 @@
     const TInt err = SendReceive( EBlacklistRemoveFromDB, ipcArgs );
     User::LeaveIfError( err );
 
-    WRITELOG( "CBlacklistServer::RemoveFromDBL - end" );
+    WRITELOG( "RBlacklistClient::RemoveFromDBL - end" );
     }
 
 // ---------------------------------------------------------------------------
@@ -163,7 +163,7 @@
 //
 void RBlacklistClient::DoLoadBlacklistL( TInt& aHandle ) const
     {
-    WRITELOG( "CBlacklistServer::DoLoadBlacklistL - begin" );
+    WRITELOG( "RBlacklistClient::DoLoadBlacklistL - begin" );
 
     TPckgBuf<TInt> handleBuf;
     TIpcArgs ipcArgs;
@@ -172,7 +172,7 @@
     User::LeaveIfError( err );
     aHandle = handleBuf();
 
-    WRITELOG( "CBlacklistServer::DoLoadBlacklistL - end" );
+    WRITELOG( "RBlacklistClient::DoLoadBlacklistL - end" );
     } 
 
 // ---------------------------------------------------------------------------
@@ -181,7 +181,7 @@
 //
 EXPORT_C void RBlacklistClient::LoadBlacklistL()
     {
-    WRITELOG( "CBlacklistServer::LoadBlacklistL - begin" );
+    WRITELOG( "RBlacklistClient::LoadBlacklistL - begin" );
 
     if ( !iSessionOk )
         {
@@ -221,7 +221,7 @@
 	TUint32 mediaId ( 0 );
     HBufC* uri = NULL;
     
-    for( TInt i( 0 ); i < listCount; i++ )
+    for( TInt i = listCount - 1; i >=0; i-- )
         {
         // get modified and media id
 	    buffer->ReceiveL( modified );
@@ -238,7 +238,7 @@
 	CleanupStack::PopAndDestroy( buffer );
 	CleanupStack::PopAndDestroy( name );
 
-    WRITELOG( "CBlacklistServer::LoadBlacklistL - end" );
+    WRITELOG( "RBlacklistClient::LoadBlacklistL - end" );
     }
 
 // ---------------------------------------------------------------------------
@@ -248,7 +248,7 @@
 void RBlacklistClient::AddToMemoryTableL( const TInt64& aModified,
         const TDesC& aUri, const TUint32 aMediaId )
     {
-    WRITELOG( "CBlacklistServer::AddToMemoryTableL - begin" );
+    WRITELOG( "RBlacklistClient::AddToMemoryTableL - begin" );
 
     CBlacklistItem* item = CBlacklistItem::NewL( aModified, aUri, aMediaId );
     
@@ -259,7 +259,7 @@
         }
 
 
-    WRITELOG( "CBlacklistServer::AddToMemoryTableL - end" );
+    WRITELOG( "RBlacklistClient::AddToMemoryTableL - end" );
     }
 
 // ---------------------------------------------------------------------------
@@ -268,7 +268,7 @@
 //
 void RBlacklistClient::RemoveFromMemoryTableL( const TDesC& aUri, const TUint32 aMediaId )
     {
-    WRITELOG( "CBlacklistServer::RemoveFromMemoryTableL - begin" );
+    WRITELOG( "RBlacklistClient::RemoveFromMemoryTableL - begin" );
 
     const TInt index = GetListIndex( aUri, aMediaId );
     if ( index >= 0 )
@@ -278,7 +278,7 @@
         iBlacklistMemoryTable.Remove( index );
         }
 
-    WRITELOG( "CBlacklistServer::RemoveFromMemoryTableL - end" );
+    WRITELOG( "RBlacklistClient::RemoveFromMemoryTableL - end" );
     }
  
 
@@ -288,7 +288,7 @@
 //
 EXPORT_C TBool RBlacklistClient::IsBlacklistedL( const TDesC& aUri, TUint32 aMediaId, TTime aLastModifiedTime )
     {
-    WRITELOG( "CBlacklistServer::IsBlacklistedL - begin" );
+    WRITELOG( "RBlacklistClient::IsBlacklistedL - begin" );
 
     const TInt index = GetListIndex( aUri, aMediaId );
     if ( index >= 0 )
@@ -300,7 +300,7 @@
             {
             if ( modified == aLastModifiedTime.Int64() )
                 {
-                WRITELOG( "CBlacklistServer::IsBlacklistedL - file is blacklisted, modification time is different" );
+                WRITELOG( "RBlacklistClient::IsBlacklistedL - file is blacklisted, modification time is different" );
                 return ETrue;
                 }
             else
@@ -315,13 +315,13 @@
             }
         else
             {
-            WRITELOG( "CBlacklistServer::IsBlacklistedL - file is blacklisted, no modification time found" );
+            WRITELOG( "RBlacklistClient::IsBlacklistedL - file is blacklisted, no modification time found" );
             return ETrue;
             }
         
         }
    
-    WRITELOG( "CBlacklistServer::IsBlacklistedL - end" );
+    WRITELOG( "RBlacklistClient::IsBlacklistedL - end" );
     return EFalse;
     }
 
@@ -331,7 +331,7 @@
 //
 TInt RBlacklistClient::GetListIndex( const TDesC& aUri, TUint32 aMediaId )
     {
-    WRITELOG( "CBlacklistServer::GetListIndex - begin" );
+    WRITELOG( "RBlacklistClient::GetListIndex - begin" );
 
     for ( TInt i( 0 ); i < iBlacklistMemoryTable.Count(); ++i )
         {
@@ -341,7 +341,7 @@
             }
         }
 
-    WRITELOG( "CBlacklistServer::GetListIndex - end" );
+    WRITELOG( "RBlacklistClient::GetListIndex - end" );
 
     return KErrNotFound;
     }
@@ -353,7 +353,7 @@
 //
 EXPORT_C void RBlacklistClient::AddL( const TDesC& aUri, TUint32 aMediaId, TTime aLastModifiedTime ) const
     {
-    WRITELOG( "CBlacklistServer::AddL - begin" );
+    WRITELOG( "RBlacklistClient::AddL - begin" );
 
     TPckgC<TUint32> mediaIdPckg( aMediaId );
     TPckgC<TTime> lastModifiedTimePckg( aLastModifiedTime );
@@ -366,7 +366,7 @@
     const TInt err = SendReceive( EBlacklistAdd, ipcArgs );
     User::LeaveIfError( err );
 
-    WRITELOG( "CBlacklistServer::AddL - end" );
+    WRITELOG( "RBlacklistClient::AddL - end" );
     }
 
 
@@ -376,7 +376,7 @@
 //
 EXPORT_C void RBlacklistClient::RemoveL( const TDesC& aUri, TUint32 aMediaId ) const
     {
-    WRITELOG( "CBlacklistServer::RemoveL - begin" );
+    WRITELOG( "RBlacklistClient::RemoveL - begin" );
 
     TPckgBuf<TUint32> mediaIdPckg( aMediaId );
     
@@ -387,7 +387,7 @@
     const TInt err = SendReceive( EBlacklistRemove, ipcArgs );
     User::LeaveIfError( err );
 
-    WRITELOG( "CBlacklistServer::RemoveL - end" );
+    WRITELOG( "RBlacklistClient::RemoveL - end" );
     }
 
 // ---------------------------------------------------------------------------
@@ -396,7 +396,7 @@
 //
 EXPORT_C void RBlacklistClient::CloseDBL()
     {
-    WRITELOG( "CBlacklistServer::CloseDBL - begin" );
+    WRITELOG( "RBlacklistClient::CloseDBL - begin" );
 
     if ( !iSessionOk )
         {
@@ -407,7 +407,7 @@
         Send( EBlacklistCloseDB );
         }
 
-    WRITELOG( "CBlacklistServer::CloseDBL - end" );
+    WRITELOG( "RBlacklistClient::CloseDBL - end" );
     }
 
 
--- a/harvester/blacklistserver/src/blacklistserver.cpp	Fri Mar 12 15:44:28 2010 +0200
+++ b/harvester/blacklistserver/src/blacklistserver.cpp	Mon Mar 15 12:42:24 2010 +0200
@@ -184,21 +184,16 @@
  
     iBlacklistMemoryTable.ResetAndDestroy();
     iBlacklistMemoryTable.Close();
-   	
-   	
-    const TInt KRowCountRemovedItems = iBufferedRemoveItems.Count();
 
-    for( TInt i = 0; i < KRowCountRemovedItems; i++ )
+    for( TInt i = iBufferedRemoveItems.Count() - 1; i >=0; i-- )
     	{
     	iBufferedRemoveItems[i]->Close();
     	}
 
     iBufferedRemoveItems.ResetAndDestroy();
     iBufferedRemoveItems.Close();  	
-   	
-    const TInt KRowCountAddedItems = iBufferedAddedItems.Count();
 
-    for( TInt i = 0; i < KRowCountAddedItems; i++ )
+    for( TInt i = iBufferedAddedItems.Count() - 1; i >=0; i-- )
     	{
     	iBufferedAddedItems[i]->Close();
     	}
--- a/harvester/client/src/harvestereventobserverao.cpp	Fri Mar 12 15:44:28 2010 +0200
+++ b/harvester/client/src/harvestereventobserverao.cpp	Mon Mar 15 12:42:24 2010 +0200
@@ -179,7 +179,7 @@
 
 	// Find smallest unused observer ID 
 	const TUint count = iObservers.Count();
-	for( TUint i = 0; i < count; i++ )
+	for( TInt i = count - 1; i >=0; i-- )
 		{
 		// Return first free observer ID 
 		if( iObservers[i]->iObserverInfo.iObserverId != i )
--- a/harvester/client/src/harvesterrequestqueue.cpp	Fri Mar 12 15:44:28 2010 +0200
+++ b/harvester/client/src/harvesterrequestqueue.cpp	Mon Mar 15 12:42:24 2010 +0200
@@ -224,8 +224,7 @@
 
     iShutdown = ETrue;
     
-    const TInt count( iRequests.Count() );
-    for( TInt i = 0; i < count; i++ )
+    for( TInt i = iRequests.Count() - 1; i >=0; i-- )
         {
         CHarvesterRequestActive* request = iRequests[i];
         if( request )
--- a/harvester/common/bwincw/harvestercommonwinscw.def	Fri Mar 12 15:44:28 2010 +0200
+++ b/harvester/common/bwincw/harvestercommonwinscw.def	Mon Mar 15 12:42:24 2010 +0200
@@ -65,4 +65,5 @@
 	?UnregisterEventObserver@CHarvesterEventManager@@QAEHABVRMessage2@@@Z @ 64 NONAME ; int CHarvesterEventManager::UnregisterEventObserver(class RMessage2 const &)
 	?HandleObjectPropertyL@CMdeObjectWrapper@@SAXAAVCMdEObject@@AAVCMdEPropertyDef@@PAXH@Z @ 65 NONAME ; void CMdeObjectWrapper::HandleObjectPropertyL(class CMdEObject &, class CMdEPropertyDef &, void *, int)
 	?SendHarvestingStatusEventL@CHarvesterPluginFactory@@QAEXH@Z @ 66 NONAME ; void CHarvesterPluginFactory::SendHarvestingStatusEventL(int)
+	?PauseHarvester@CHarvesterPluginFactory@@QAEXH@Z @ 67 NONAME ; void CHarvesterPluginFactory::PauseHarvester(int)
 
--- a/harvester/common/eabi/harvestercommonarm.def	Fri Mar 12 15:44:28 2010 +0200
+++ b/harvester/common/eabi/harvestercommonarm.def	Mon Mar 15 12:42:24 2010 +0200
@@ -85,4 +85,5 @@
 	_ZN18CHarvesterExifUtilD0Ev @ 84 NONAME
 	_ZN18CHarvesterExifUtilD1Ev @ 85 NONAME
 	_ZN18CHarvesterExifUtilD2Ev @ 86 NONAME
+	_ZN23CHarvesterPluginFactory14PauseHarvesterEi @ 87 NONAME
 
--- a/harvester/common/inc/harvestercommon.h	Fri Mar 12 15:44:28 2010 +0200
+++ b/harvester/common/inc/harvestercommon.h	Mon Mar 15 12:42:24 2010 +0200
@@ -86,8 +86,8 @@
 
 enum TMdsOomStatus
 	{
-	TMdsOomFreeRam,
-	TMdsOomMemoryGood
+	EMdsOomFreeRam,
+	EMdsOomMemoryGood
 	};
 
 const TInt KHarvesterGetRootDirFlags = EDirsFirst;
--- a/harvester/common/inc/harvesterpluginfactory.h	Fri Mar 12 15:44:28 2010 +0200
+++ b/harvester/common/inc/harvesterpluginfactory.h	Mon Mar 15 12:42:24 2010 +0200
@@ -43,6 +43,7 @@
 		IMPORT_C TBool IsContainerFileL( const TDesC& aURI );
 		
 		IMPORT_C void SendHarvestingStatusEventL( TBool aStarted );
+		IMPORT_C void PauseHarvester( TBool aPaused );
 
 	private:
 		CHarvesterPluginFactory();
--- a/harvester/common/src/harvestercenreputil.cpp	Fri Mar 12 15:44:28 2010 +0200
+++ b/harvester/common/src/harvestercenreputil.cpp	Mon Mar 15 12:42:24 2010 +0200
@@ -97,8 +97,7 @@
 	TInt ret = repo->FindL( KIgnorePathPartialKey, KSearchMask, ignoredKeys );
 	
 	TBuf<KMaxFileName> path;
-	const TInt count = ignoredKeys.Count();
-	for( TInt i=0;i<count;i++ )
+	for( TInt i = ignoredKeys.Count() - 1; i >=0; i-- )
 		{
 		const TInt error( repo->Get( ignoredKeys[i], path ) );
 		if( error != KErrNone )
@@ -191,7 +190,7 @@
 	TBuf<KMaxFileName> path;
 	const TInt count = scanPathKeys.Count();
 	aPaths.ReserveL( count );
-	for( TInt i = 0; i < count; i++ )
+	for( TInt i = count - 1; i >=0; i-- )
 		{
 	    const TInt error( repo->Get( scanPathKeys[i], path ) );
 	    if( error != KErrNone )
@@ -215,8 +214,7 @@
 	repo->FindL( aPartialKey, KSearchMask, scanPathKeys );
 
 	TBuf<KMaxFileName> path;
-	const TInt count = scanPathKeys.Count();
-	for( TInt i = 0; i < count; i++ )
+	for( TInt i = scanPathKeys.Count() - 1; i >=0; i-- )
 		{
 	    const TInt error( repo->Get( scanPathKeys[i], path ) );
 	    if( error != KErrNone )
--- a/harvester/common/src/harvesterplugin.cpp	Fri Mar 12 15:44:28 2010 +0200
+++ b/harvester/common/src/harvesterplugin.cpp	Mon Mar 15 12:42:24 2010 +0200
@@ -167,7 +167,7 @@
             	else if( iFastModeEnabled )
             	    {
                     iFastModeEnabled = EFalse;
-                    SetPriority( KHarvesterPriorityHarvestingPlugin + 1 );
+                    SetPriority( KHarvesterPriorityHarvestingPlugin );
             	    }
             	
 				if( iBlacklist )
@@ -220,7 +220,6 @@
 //
 EXPORT_C void CHarvesterPlugin::DoCancel()
     {
-    
     }
 
 // ---------------------------------------------------------------------------
--- a/harvester/common/src/harvesterpluginfactory.cpp	Fri Mar 12 15:44:28 2010 +0200
+++ b/harvester/common/src/harvesterpluginfactory.cpp	Mon Mar 15 12:42:24 2010 +0200
@@ -111,7 +111,7 @@
 				return;
 				}
 			}
-		for( TInt i = 0; i < sCount; i++ )
+		for( TInt i = sCount - 1; i >=0; i-- )
 			{
 			CHarvesterPluginInfo* info = supportedPlugins[i];
 			if ( !(info->iPlugin) )
@@ -148,8 +148,7 @@
         RPointerArray<CHarvesterPluginInfo> supportedPlugins;
         TRAP_IGNORE( GetSupportedPluginsL( supportedPlugins, extPtr ) );
         
-        const TInt sCount = supportedPlugins.Count();
-        for( TInt i = 0; i < sCount; i++ )
+        for( TInt i = supportedPlugins.Count() - 1; i >=0; i-- )
             {
             CHarvesterPluginInfo* info = supportedPlugins[i];
             if ( !(info->iPlugin) )
@@ -164,11 +163,11 @@
                 info->iPlugin->SetHarvesterPluginFactory( *this );  
                 info->iPlugin->SetBlacklist( *iBlacklist );
                 }
-                info->iPlugin->GetMimeType( aUri, aMimeType );
-                if( aMimeType.Length() > 0 )
-                    {
-                    break;
-                    }
+            info->iPlugin->GetMimeType( aUri, aMimeType );
+            if( aMimeType.Length() > 0 )
+                {
+                break;
+                }
             }
         supportedPlugins.Close();
         }
@@ -210,7 +209,7 @@
 		   	hpi->iQueue.Insert( aHD, 0 );
 		   	if( !hpi->iPlugin->IsActive() )
 		   	    {
-	            hpi->iPlugin->SetPriority( KHarvesterPriorityHarvestingPlugin + 2 );
+	            hpi->iPlugin->SetPriority( KHarvesterPriorityHarvestingPlugin + 1 );
 		   	    }
 		    }
 	    else
@@ -244,12 +243,14 @@
 	WRITELOG( "CHarvesterPluginFactory::SetBlacklist()" );
 	iBlacklist = &aBlacklist;
 	
-	TInt count = iHarvesterPluginInfoArray.Count();
-	for ( TInt i = 0; i < count; i++ )
+	const TInt count = iHarvesterPluginInfoArray.Count();
+	for ( TInt i = count; --i >= 0; )
 		{
-		iHarvesterPluginInfoArray[i]->iPlugin->SetBlacklist( *iBlacklist );
-		}
-	
+	    if( iHarvesterPluginInfoArray[i]->iPlugin )
+	        {
+	        iHarvesterPluginInfoArray[i]->iPlugin->SetBlacklist( *iBlacklist );
+	        }
+		}	
 	}
 
 // ---------------------------------------------------------------------------
@@ -324,10 +325,11 @@
     
     pluginInfo->iPluginUid = aPluginUid;
     
-    // Load plugin
+#ifdef MDS_HARVESTERPLUGINS_ON_BOOT
     pluginInfo->iPlugin = CHarvesterPlugin::NewL( pluginInfo->iPluginUid );
     pluginInfo->iPlugin->SetQueue( pluginInfo->iQueue );
-    pluginInfo->iPlugin->SetHarvesterPluginFactory( *this );  
+    pluginInfo->iPlugin->SetHarvesterPluginFactory( *this );
+#endif
     
     iHarvesterPluginInfoArray.AppendL( pluginInfo );
     CleanupStack::Pop( pluginInfo );
@@ -394,8 +396,7 @@
 		RPointerArray<CHarvesterPluginInfo> supportedPlugins;
 		CleanupClosePushL( supportedPlugins );
 		GetSupportedPluginsL( supportedPlugins, extPtr );
-		const TInt sCount = supportedPlugins.Count();
-		for( TInt i = 0; i < sCount; i++ )
+		for( TInt i = supportedPlugins.Count() - 1; i >=0; i-- )
 			{
 			CHarvesterPluginInfo* info = supportedPlugins[i];
 			if( info->iObjectTypes.Count() >  1 )
@@ -458,3 +459,19 @@
         }
     }
 
+EXPORT_C void CHarvesterPluginFactory::PauseHarvester( TBool aPaused )
+    {
+    const TInt count = iHarvesterPluginInfoArray.Count();
+    for ( TInt i = count; --i >= 0; )
+        {
+        if( iHarvesterPluginInfoArray[i]->iPlugin && aPaused )
+            {
+            iHarvesterPluginInfoArray[i]->iPlugin->Cancel();
+            }
+        else if( iHarvesterPluginInfoArray[i]->iPlugin )
+            {
+            iHarvesterPluginInfoArray[i]->iPlugin->StartHarvest();
+            }
+        }
+    }
+
--- a/harvester/common/src/listener.cpp	Fri Mar 12 15:44:28 2010 +0200
+++ b/harvester/common/src/listener.cpp	Mon Mar 15 12:42:24 2010 +0200
@@ -48,7 +48,7 @@
 CListener* CListener::NewLC( const TUid aPropertyCategory,
 		const TUint aKey )
     {
-    WRITELOG( "CHarvesterAO::NewLC() - begin" );
+    WRITELOG( "CListener::NewLC() - begin" );
     
     CListener* self = new ( ELeave ) CListener( aPropertyCategory, aKey );
     CleanupStack::PushL( self );
--- a/harvester/common/src/propertywatcher.cpp	Fri Mar 12 15:44:28 2010 +0200
+++ b/harvester/common/src/propertywatcher.cpp	Mon Mar 15 12:42:24 2010 +0200
@@ -189,6 +189,7 @@
 	WRITELOG( "CPropertyWatcher::~CPropertyWatcher() - begin" ); 
 	
 	iListenersArray.ResetAndDestroy(); // Clean array and objects.
+    iListenersArray.Close(); 
 	
 	WRITELOG( "CPropertyWatcher::~CPropertyWatcher() - end" ); 
 	}
--- a/harvester/composerplugins/imagecomposer/src/composerimageplugin.cpp	Fri Mar 12 15:44:28 2010 +0200
+++ b/harvester/composerplugins/imagecomposer/src/composerimageplugin.cpp	Mon Mar 15 12:42:24 2010 +0200
@@ -197,7 +197,9 @@
     CMdEObjectDef& imageObjDef = defaultNamespace.GetObjectDefL( MdeConstants::Image::KImageObject );
     CMdEObjectDef& locationObjDef = defaultNamespace.GetObjectDefL( MdeConstants::Location::KLocationObject );
 	CMdEObject* object = iSession->GetObjectL( aObjectId, imageObjDef );
+	CleanupStack::PushL( object );
 	CMdEObject* location = iSession->GetObjectL( locationId, locationObjDef );
+	CleanupStack::PushL( location );
 	
 	if( object && location )
 		{
@@ -208,7 +210,7 @@
 			iMdEHarvesterSession->ResetPendingL( objectId );
 			}
 		}
-	CleanupStack::PopAndDestroy( &objectId );
+	CleanupStack::PopAndDestroy( 3, &objectId );
 	}
 
 void CComposerImagePlugin::HandlePendingObjects( const RArray<TItemId>& aObjectIdArray )
--- a/harvester/composerplugins/imagecomposer/src/imagecomposerao.cpp	Fri Mar 12 15:44:28 2010 +0200
+++ b/harvester/composerplugins/imagecomposer/src/imagecomposerao.cpp	Mon Mar 15 12:42:24 2010 +0200
@@ -88,7 +88,7 @@
 // ---------------------------------------------------------------------------
 //
 CImageComposerAO::CImageComposerAO() : // first-phase C++ constructor
-		CActive( KHarvesterPriorityComposerPlugin + 1 ) // To match image harvester plugin
+		CActive( KHarvesterPriorityComposerPlugin )
     {
     WRITELOG( "CImageComposerAO::CImageComposerAO()" );
     }
@@ -871,6 +871,7 @@
         if ( !cellIdProperty && !countryCodeProperty && !networkCodeProperty
             && !locationAreaCodeProperty && !speedProperty && !directionProperty && !qualityProperty )
             {
+            // Ignore return value - if operation does not succeed, there is no much that can be done here
             iSession->RemoveObjectL( aLocationObject->Id(), iDefaultNamespace );
             }
         }
--- a/harvester/harvesterplugins/AudioPlugin/inc/harvesteraudioplugin.h	Fri Mar 12 15:44:28 2010 +0200
+++ b/harvester/harvesterplugins/AudioPlugin/inc/harvesteraudioplugin.h	Mon Mar 15 12:42:24 2010 +0200
@@ -44,6 +44,7 @@
 		CMdEPropertyDef* iSizePropertyDef;
 		CMdEPropertyDef* iItemTypePropertyDef;
 		CMdEPropertyDef* iTitlePropertyDef;
+		CMdEPropertyDef* iTimeOffsetPropertyDef;
 
 		// Media property definitions	
 		CMdEPropertyDef* iRatingPropertyDef;
--- a/harvester/harvesterplugins/AudioPlugin/src/harvesteraudioplugin.cpp	Fri Mar 12 15:44:28 2010 +0200
+++ b/harvester/harvesterplugins/AudioPlugin/src/harvesteraudioplugin.cpp	Mon Mar 15 12:42:24 2010 +0200
@@ -42,13 +42,14 @@
 	{
 	CMdENamespaceDef& nsDef = aObjectDef.NamespaceDef();
 
-	// Image property definitions
+	// Common property definitions
 	CMdEObjectDef& objectDef = nsDef.GetObjectDefL( MdeConstants::Object::KBaseObject );
 	iCreationDatePropertyDef = &objectDef.GetPropertyDefL( MdeConstants::Object::KCreationDateProperty );
 	iLastModifiedDatePropertyDef = &objectDef.GetPropertyDefL( MdeConstants::Object::KLastModifiedDateProperty );
 	iSizePropertyDef = &objectDef.GetPropertyDefL( MdeConstants::Object::KSizeProperty );
 	iItemTypePropertyDef = &objectDef.GetPropertyDefL( MdeConstants::Object::KItemTypeProperty );
 	iTitlePropertyDef = &objectDef.GetPropertyDefL( MdeConstants::Object::KTitleProperty );
+    iTimeOffsetPropertyDef = &objectDef.GetPropertyDefL( MdeConstants::Object::KTimeOffsetProperty );
 
 	// Media property definitions
 	CMdEObjectDef& mediaDef = nsDef.GetObjectDefL( MdeConstants::MediaObject::KMediaObject );
@@ -136,7 +137,7 @@
         TRAP_IGNORE( iTNM = CThumbnailManager::NewL( *this ) );
         }
     
-    SetPriority( KHarvesterPriorityHarvestingPlugin - 1);
+    SetPriority( KHarvesterPriorityHarvestingPlugin - 2 );
 	}
 
 // ---------------------------------------------------------------------------
@@ -266,9 +267,9 @@
         User::Leave( err ); // metadata cannot be gathered!
         }
     
-	TTime now;
-	now.HomeTime();
-    
+    TTimeIntervalSeconds timeOffsetSeconds = User::UTCOffset();
+    TTime localModifiedDate = entry.iModified + timeOffsetSeconds;
+	
 	if( !iPropDefs )
 		{
 		CMdEObjectDef& objectDef = mdeObject.Def();
@@ -276,7 +277,7 @@
 		}
 	
 	CMdeObjectWrapper::HandleObjectPropertyL(
-                 mdeObject, *iPropDefs->iCreationDatePropertyDef, &now, aIsAdd );
+                 mdeObject, *iPropDefs->iCreationDatePropertyDef, &localModifiedDate, aIsAdd );
 
 	CMdeObjectWrapper::HandleObjectPropertyL(
              mdeObject, *iPropDefs->iLastModifiedDatePropertyDef, &entry.iModified, aIsAdd );
@@ -361,7 +362,12 @@
 	    CMdEObjectDef& audioObjectDef = mdeObject.Def();
 		iPropDefs = CHarvesterAudioPluginPropertyDefs::NewL( audioObjectDef );
 		}
-    
+ 
+    // Time offset
+    TTimeIntervalSeconds timeOffsetSeconds = User::UTCOffset();
+    TInt16 timeOffsetMinutes = timeOffsetSeconds.Int() / 60;
+    CMdeObjectWrapper::HandleObjectPropertyL(mdeObject, *iPropDefs->iTimeOffsetPropertyDef, &timeOffsetMinutes, aIsAdd );
+	
     if ( song.Length() > 0
         && song.Length() < iPropDefs->iTitlePropertyDef->MaxTextLengthL() )
         {    
--- a/harvester/harvesterplugins/ImagePlugin/src/harvesterimageplugin.cpp	Fri Mar 12 15:44:28 2010 +0200
+++ b/harvester/harvesterplugins/ImagePlugin/src/harvesterimageplugin.cpp	Mon Mar 15 12:42:24 2010 +0200
@@ -25,7 +25,6 @@
 #include "mdsutils.h"
 #include "harvesterexifutil.h"
 #include "harvesterimageplugin.h"
-#include "harvestercommon.h"
 #include "mdeobjectwrapper.h"
 
 using namespace MdeConstants;
@@ -257,7 +256,6 @@
     User::LeaveIfError( iMimeTypeMappings.InsertInOrder( TMimeTypeMapping<TImageMetadataHandling>(
             KExtOtb(), KOtbMime(), EOtherHandling ), cmp ) );
     
-    SetPriority( KHarvesterPriorityHarvestingPlugin + 1 );
 	}
 
 void CHarvesterImagePlugin::HarvestL( CHarvesterData* aHD )
@@ -452,15 +450,59 @@
         TPtr8 imageDataPtr = aFileData.iImageData->Des();
         TRAP( err, iDecoder->OpenL(imageDataPtr, aFileData.iMime8,
                 CImageDecoder::TOptions( CImageDecoder::EPreferFastDecode | CImageDecoder::EOptionIgnoreExifMetaData ) ) );
-        WRITELOG( "CHarvesterImagePlugin::GatherData() - Image decoder has opened the file." );
 
         if ( err != KErrNone )
             {
             WRITELOG1( "CHarvesterImagePlugin::GatherData() - ERROR: Decoder could not open image data! Code %d", err );
+#ifdef _DEBUG
+            if( err == KErrInUse || err == KErrLocked )
+                {
+                TPtrC fileName( uri.Mid(2) );
+                WRITELOG1( "CHarvesterImagePlugin :: Checking open file handles to %S", &fileName );
+
+                CFileList* fileList = 0;
+                TOpenFileScan fileScan( iFs );
+
+                fileScan.NextL( fileList );   
+  
+                while ( fileList )   
+                    {
+                    const TInt count( fileList->Count() );
+                    for (TInt i = 0; i < count; i++ )   
+                        {   
+                        if ( (*fileList)[i].iName == uri.Mid(2) )
+                            {
+                            TFullName processName;
+                            TFindThread find(_L("*"));
+                            while( find.Next( processName ) == KErrNone )
+                                {
+                                RThread thread;
+                                TInt err = thread.Open( processName );
+     
+                                if ( err == KErrNone )
+                                    {
+                                    if ( thread.Id().Id() ==  fileScan.ThreadId() )
+                                        {
+                                        processName = thread.Name();
+                                        thread.Close();
+                                        WRITELOG1( "CHarvesterImagePlugin:: %S has a file handle open", &processName );
+                                        break;
+                                        }
+                                    thread.Close();
+                                    }
+                                }
+                            }
+                        }
+                    fileScan.NextL( fileList );   
+                    } 
+                }
+#endif
             iDecoder->Reset();
             return KErrCompletion; // metadata item still can be created, thus KErrCompletion
             }
 
+        WRITELOG( "CHarvesterImagePlugin::GatherData() - Image decoder has opened the file." );
+        
         if ( !iDecoder->ValidDecoder() )
         	{
         	// read all remaining data from file
--- a/harvester/harvesterplugins/MessagePlugin/src/harvestermessageplugin.cpp	Fri Mar 12 15:44:28 2010 +0200
+++ b/harvester/harvesterplugins/MessagePlugin/src/harvestermessageplugin.cpp	Mon Mar 15 12:42:24 2010 +0200
@@ -30,6 +30,7 @@
 #include <mdetextproperty.h>
 
 #include "harvestermessageplugin.h"
+#include "harvestercommon.h"
 #include "harvesterlog.h"
 #include "mdsutils.h"
 #include "mdeobjectdef.h"
@@ -283,9 +284,9 @@
 void CHarvesterMessagePlugin::SetPropertiesL( CHarvesterData& aHD )
 	{	    
 	WRITELOG( "CHarvesterMessagePlugin::SetPropertiesL enter" );
-	CMdEObject& aMetadataObject = aHD.MdeObject();
+	CMdEObject& metadataObject = aHD.MdeObject();
 	
-	CMdEObjectDef& messageObjectDef = aMetadataObject.Def();
+	CMdEObjectDef& messageObjectDef = metadataObject.Def();
 	
 	CMdEPropertyDef& creationTimeDef = messageObjectDef.GetPropertyDefL( 									  
 		MdeConstants::Object::KCreationDateProperty ) ;
@@ -318,19 +319,19 @@
 	
 	if ( EHarvesterAdd == aHD.EventType() )
 		{
-		aMetadataObject.AddTimePropertyL( creationTimeDef, now );			
-		aMetadataObject.AddTimePropertyL( lastModTimeDef, iDate );										
-		aMetadataObject.AddBoolPropertyL( receivedDef, iIncoming );
+	    metadataObject.AddTimePropertyL( creationTimeDef, now );			
+	    metadataObject.AddTimePropertyL( lastModTimeDef, iDate );										
+	    metadataObject.AddBoolPropertyL( receivedDef, iIncoming );
 		if (iFromOrTo && iFromOrTo->Length())
 			{
-			aMetadataObject.AddTextPropertyL( textDef, *iFromOrTo );
+		    metadataObject.AddTextPropertyL( textDef, *iFromOrTo );
 			}
-		aMetadataObject.AddTextPropertyL( ItemtypeDef, iItemType );									
-		aMetadataObject.AddUint32PropertyL( sizeDef, iSize );
-		aMetadataObject.AddInt16PropertyL( offSetDef, timeOffset.Int() / 60 );
+		metadataObject.AddTextPropertyL( ItemtypeDef, iItemType );									
+		metadataObject.AddUint32PropertyL( sizeDef, iSize );
+		metadataObject.AddInt16PropertyL( offSetDef, timeOffset.Int() / 60 );
 		
 		CMdEProperty* prop = NULL;	
-		TInt index = aMetadataObject.Property( titleDef, prop );
+		TInt index = metadataObject.Property( titleDef, prop );
 		
 		if (iSubject.Length())
 			{
@@ -340,7 +341,7 @@
 				}
 			else
 				{
-				aMetadataObject.AddTextPropertyL( titleDef, iSubject );
+			    metadataObject.AddTextPropertyL( titleDef, iSubject );
 				}
 			}
 		else
@@ -353,7 +354,7 @@
 					}
 				else
 					{
-					aMetadataObject.AddTextPropertyL( titleDef, *iFromOrTo );
+				    metadataObject.AddTextPropertyL( titleDef, *iFromOrTo );
 					}
 				}
 			}
@@ -361,7 +362,7 @@
 	else
 		{	
 		CMdEProperty* prop = NULL;	
-		TInt index = aMetadataObject.Property( textDef, prop );
+		TInt index = metadataObject.Property( textDef, prop );
 		if (iFromOrTo && iFromOrTo->Length())
 			{
 			if (prop)
@@ -370,18 +371,18 @@
 				}
 			else
 				{
-				aMetadataObject.AddTextPropertyL( textDef, *iFromOrTo );
+			    metadataObject.AddTextPropertyL( textDef, *iFromOrTo );
 				}
 			}
 		else if (index >= 0)
 			{
-			aMetadataObject.RemoveProperty(index);
+		    metadataObject.RemoveProperty(index);
 			}
 		
-		aMetadataObject.Property( sizeDef, prop );
+		metadataObject.Property( sizeDef, prop );
 		static_cast<CMdEUint32Property *>(prop)->SetValueL( iSize );
 		
-		aMetadataObject.Property( lastModTimeDef, prop );
+		metadataObject.Property( lastModTimeDef, prop );
 		static_cast <CMdETimeProperty *>(prop)->SetValueL( iDate );										
 		}
 
--- a/harvester/harvesterplugins/OMADRMPlugin/src/harvesteromadrmplugin.cpp	Fri Mar 12 15:44:28 2010 +0200
+++ b/harvester/harvesterplugins/OMADRMPlugin/src/harvesteromadrmplugin.cpp	Mon Mar 15 12:42:24 2010 +0200
@@ -21,6 +21,7 @@
 #include "mdsutils.h"
 #include "harvesteromadrmplugin.h"
 #include "harvesterlog.h"
+#include "harvestercommon.h"
 #include "mdeobjectwrapper.h"
 #include <harvesterdata.h>
 
@@ -109,6 +110,7 @@
 void CHarvesterOMADRMPlugin::ConstructL()
 	{
 	WRITELOG( "CHarvesterOMADRMPlugin::ConstructL()" );
+    SetPriority( KHarvesterPriorityHarvestingPlugin - 1 );
 	}
 
 void CHarvesterOMADRMPlugin::HarvestL( CHarvesterData* aHD )
--- a/harvester/harvesterplugins/RTPPlugin/src/harvesterrtpplugin.cpp	Fri Mar 12 15:44:28 2010 +0200
+++ b/harvester/harvesterplugins/RTPPlugin/src/harvesterrtpplugin.cpp	Mon Mar 15 12:42:24 2010 +0200
@@ -23,6 +23,7 @@
 #include "harvesterlog.h"
 #include "mdeobject.h"
 #include "mdsutils.h"
+#include "harvestercommon.h"
 #include "mdeobjectwrapper.h"
 #include "harvesterrtpmetadatareader.h"
 #include <mdenamespacedef.h>
@@ -86,6 +87,7 @@
 void CHarvesterRtpPlugin::ConstructL()
     {
     WRITELOG( "CHarvesterRtpPlugin::ConstructL()" );
+    SetPriority( KHarvesterPriorityHarvestingPlugin - 1 );
     }
 
 // ---------------------------------------------------------------------------
--- a/harvester/harvesterplugins/VideoPlugin/src/harvestervideoplugin.cpp	Fri Mar 12 15:44:28 2010 +0200
+++ b/harvester/harvesterplugins/VideoPlugin/src/harvestervideoplugin.cpp	Mon Mar 15 12:42:24 2010 +0200
@@ -25,7 +25,6 @@
 #include "harvestervideoplugin.h"
 #include "harvesterlog.h"
 #include "harvesterblacklist.h"
-#include "harvestercommon.h"
 #include "mdeobjectwrapper.h"
 
 #include <mdenamespacedef.h>
@@ -267,7 +266,6 @@
                     KMimeTypeWmv(), KMimeTypeWmv() ) ), 
             cmp ) );
     
-    SetPriority( KHarvesterPriorityHarvestingPlugin + 1 );
     }
 
 
@@ -306,6 +304,47 @@
         WRITELOG1( "CHarvesterVideoPlugin::GetObjectType - File open error: %d", error );
         if( error == KErrInUse )
             {
+#ifdef _DEBUG
+            TPtrC fileName( aUri.Mid(2) );
+            WRITELOG1( "CHarvesterVideoPlugin :: Checking open file handles to %S", &fileName );
+
+            CFileList* fileList = 0;
+            TOpenFileScan fileScan( iFs );
+
+            TRAP_IGNORE( fileScan.NextL( fileList ) );   
+  
+            while ( fileList )   
+                {
+                const TInt count( fileList->Count() ); 
+                for (TInt i = 0; i < count; i++ )   
+                    {   
+                    if ( (*fileList)[i].iName == aUri.Mid(2) )
+                        {
+                        TFullName processName;
+                        TFindThread find(_L("*"));
+                        while( find.Next( processName ) == KErrNone )
+                            {
+                            RThread thread;
+                            TInt err = thread.Open( processName );
+     
+                            if ( err == KErrNone )
+                                {
+                                if ( thread.Id().Id() ==  fileScan.ThreadId() )
+                                    {
+                                    processName = thread.Name();
+                                    thread.Close();
+                                    WRITELOG1( "CHarvesterVideoPlugin:: %S has a file handle open", &processName );
+                                    break;
+                                    }
+                                thread.Close();
+                                }
+                            }
+                        }
+                    }
+                fileList = NULL;
+                TRAP_IGNORE( fileScan.NextL( fileList ) );   
+                } 
+#endif
             aObjectType.Copy( KInUse() );
             }
         return;
@@ -401,6 +440,46 @@
          error == KErrLocked )
         {
         WRITELOG( "CHarvesterVideoPlugin - File is open!" );
+#ifdef _DEBUG
+            TPtrC fileName( uri.Mid(2) );
+            WRITELOG1( "CHarvesterVideoPlugin :: Checking open file handles to %S", &fileName );
+
+            CFileList* fileList = 0;
+            TOpenFileScan fileScan( iFs );
+
+            fileScan.NextL( fileList );   
+  
+            while ( fileList )   
+                {
+                const TInt count( fileList->Count() ); 
+                for (TInt i = 0; i < count; i++ )   
+                    {   
+                    if ( (*fileList)[i].iName == uri.Mid(2) )
+                        {
+                        TFullName processName;
+                        TFindThread find(_L("*"));
+                        while( find.Next( processName ) == KErrNone )
+                            {
+                            RThread thread;
+                            TInt err = thread.Open( processName );
+     
+                            if ( err == KErrNone )
+                                {
+                                if ( thread.Id().Id() ==  fileScan.ThreadId() )
+                                    {
+                                    processName = thread.Name();
+                                    thread.Close();
+                                    WRITELOG1( "CHarvesterVideoPlugin:: %S has a file handle open", &processName );
+                                    break;
+                                    }
+                                thread.Close();
+                                }
+                            }
+                        }
+                    }
+                fileScan.NextL( fileList );   
+                } 
+#endif
         CleanupStack::PopAndDestroy( &file );
         User::Leave( KErrInUse );
         }
@@ -420,16 +499,6 @@
         {
         CMdEProperty* prop = NULL;
         CMdEObjectDef& objectDef = aMetadataObject.Def();
-        CMdEPropertyDef& sizeDef = objectDef.GetPropertyDefL( MdeConstants::Object::KSizeProperty );
-        aMetadataObject.Property( sizeDef, prop );
-        if( prop )
-            {
-            aVHD.iFileSize  = prop->Uint32ValueL();
-            }
-        else
-            {
-            dataExtracted = EFalse;
-            }
         CMdEPropertyDef& modifiedDef = objectDef.GetPropertyDefL( MdeConstants::Object::KLastModifiedDateProperty );
         aMetadataObject.Property( modifiedDef, prop );
         if( prop )
@@ -456,9 +525,9 @@
         
         aVHD.iModified = entry.iModified;
         aVHD.iFileSize = (TUint)entry.iSize;
+        
+        WRITELOG1( "CHarvesterVideoPlugin - File size: %d", aVHD.iFileSize );
         }
-    
-    WRITELOG1( "CHarvesterVideoPlugin - File size: %d", aVHD.iFileSize );
 
     // now the minimum information has been harvested
     // from now on the harvested data should always be stored
--- a/harvester/harvesterplugins/WMVPlugin/src/harvesterwmvplugin.cpp	Fri Mar 12 15:44:28 2010 +0200
+++ b/harvester/harvesterplugins/WMVPlugin/src/harvesterwmvplugin.cpp	Mon Mar 15 12:42:24 2010 +0200
@@ -21,6 +21,7 @@
 #include "mdsutils.h"
 #include "harvesterdata.h"
 #include "harvesterlog.h"
+#include "harvestercommon.h"
 #include "harvesterwmvplugin.h"
 #include <mdenamespacedef.h>
 #include <mdeobjectdef.h>
@@ -77,6 +78,7 @@
 CHarvesterWMVPlugin::~CHarvesterWMVPlugin()
     {
     WRITELOG( "CHarvesterWMVPlugin::~CHarvesterWMVPlugin()" );
+    delete iPropDefs;
     }
 
 // ---------------------------------------------------------------------------
@@ -154,6 +156,7 @@
 void CHarvesterWMVPlugin::ConstructL()
     {
     WRITELOG( "CHarvesterWMVPlugin::ConstructL()" );
+    SetPriority( KHarvesterPriorityHarvestingPlugin - 1 );
     }
 
 // ---------------------------------------------------------------------------
--- a/harvester/monitorplugins/fileplugin/src/fileeventhandlerao.cpp	Fri Mar 12 15:44:28 2010 +0200
+++ b/harvester/monitorplugins/fileplugin/src/fileeventhandlerao.cpp	Mon Mar 15 12:42:24 2010 +0200
@@ -110,6 +110,9 @@
     delete iEventArray;
     
     iQueue.ResetAndDestroy();
+    iQueue.Close();
+	
+    iUriArray.ResetAndDestroy();
     iUriArray.Close();
     }
 
@@ -837,7 +840,7 @@
 void CFileEventHandlerAO::AddToQueueL( TMdsFSPStatus& aEvent )
 	{
 	CMdsFSPQueueItem* item = CMdsFSPQueueItem::NewL(aEvent);
-	iQueue.Append(item);
+	iQueue.AppendL(item);
 	if( iNextRequest == ERequestIdle && !iCacheEvents )
 		{
 		SetNextRequest( ERequestProcessing );
--- a/harvester/monitorplugins/inc/fsutil.inl	Fri Mar 12 15:44:28 2010 +0200
+++ b/harvester/monitorplugins/inc/fsutil.inl	Mon Mar 15 12:42:24 2010 +0200
@@ -52,8 +52,7 @@
 	sess->GetPresentMediasL( presentMedias );
 
     TUint32 mediaid = 0;
-    TInt count = presentMedias.Count();
-    for( TInt i=0;i<count;i++ )
+    for( TInt i = presentMedias.Count() - 1; i >=0; i-- )
     	{
     	TMdEMediaInfo info = presentMedias[i];
     	if( info.iDrive == aDrive )
--- a/harvester/monitorplugins/mdsoomplugin/inc/mdsoomplugin.h	Fri Mar 12 15:44:28 2010 +0200
+++ b/harvester/monitorplugins/mdsoomplugin/inc/mdsoomplugin.h	Mon Mar 15 12:42:24 2010 +0200
@@ -32,7 +32,7 @@
 *  CMdSOomPlugin
 * 
 */
-class CMdSOomPlugin : public COomMonitorPlugin
+class CMdSOomPlugin : public COomMonitorPluginV2
 	{
 public:
 	// Constructors and destructor
@@ -45,14 +45,14 @@
 	
 
 	/**
-	 * From COomMonitorPlugin
+	 * From COomMonitorPlugin v2
 	 * FreeRam is called when the system RAM level becomes
 	 * low. This plugin is requested to help free some RAM.
 	 */
-	void FreeRam();
+	void FreeRam( TInt aBytesToFree );
 
 	/**
-	 * From COomMonitorPlugin
+	 * From COomMonitorPlugin v2
 	 * MemoryGood is called when the system RAM level becomes
 	 * good after being low.The plugin may take this opportunity
 	 * to start using RAM again.
--- a/harvester/monitorplugins/mdsoomplugin/src/mdsoomplugin.cpp	Fri Mar 12 15:44:28 2010 +0200
+++ b/harvester/monitorplugins/mdsoomplugin/src/mdsoomplugin.cpp	Mon Mar 15 12:42:24 2010 +0200
@@ -49,11 +49,11 @@
 	}
 
 
-void CMdSOomPlugin::FreeRam()
+void CMdSOomPlugin::FreeRam( TInt /*aBytesToFree*/ )
 	{
 	WRITELOG("CMdSOomPlugin::FreeRam() - start");
 	
-	iOomMsgQueue.Send( TMdsOomFreeRam );
+	iOomMsgQueue.Send( EMdsOomFreeRam );
 	
 	WRITELOG("CMdSOomPlugin::FreeRam() - end");
 	}
@@ -62,7 +62,7 @@
 	{
 	WRITELOG("CMdSOomPlugin::MemoryGood - start");
 	
-	iOomMsgQueue.Send( TMdsOomMemoryGood );	
+	iOomMsgQueue.Send( EMdsOomMemoryGood );	
 	
 	WRITELOG("CMdSOomPlugin::MemoryGood - end ");
 	}
--- a/harvester/monitorplugins/mmcplugin/inc/mmcmonitorao.h	Fri Mar 12 15:44:28 2010 +0200
+++ b/harvester/monitorplugins/mmcplugin/inc/mmcmonitorao.h	Mon Mar 15 12:42:24 2010 +0200
@@ -75,20 +75,6 @@
         TBool StopMonitoring();
         
         /**
-        * Resumes paused monitoring.
-        *
-        * @return ETrue if success, EFalse if not
-        */
-        TBool Resume();
-        
-        /**
-        * Pauses monitoring.
-        *
-        * @return ETrue if success, EFalse if not
-        */
-        TBool Pause();
-        
-        /**
         * Inherited from CActive. This method will be called on file server notifying.
         */
         void RunL();
--- a/harvester/monitorplugins/mmcplugin/inc/mmcscannerao.h	Fri Mar 12 15:44:28 2010 +0200
+++ b/harvester/monitorplugins/mmcplugin/inc/mmcscannerao.h	Mon Mar 15 12:42:24 2010 +0200
@@ -28,7 +28,7 @@
 // FORWARD DECLARATION
 class MMonitorPluginObserver;
 
-class CMmcScannerAO : public CTimer 
+class CMmcScannerAO : public CActive 
 	{
 public:
 	// Cancel and destroy
@@ -37,7 +37,7 @@
 	// Two-phased constructor.
 	static CMmcScannerAO* NewL( TUint32 aMediaId, CMdEHarvesterSession* aMdEClient,
 			MMonitorPluginObserver* aObserver, CHarvesterPluginFactory* aHarvesterPluginFactory,
-			const TInt aPriority, TBool aAlreadyWaited );
+			const TInt aPriority );
 
 public:
 
@@ -48,7 +48,7 @@
 			const TInt aPriority );
 
 	// Second-phase constructor
-	void ConstructL( TBool aAlreadyWaited );
+	void ConstructL();
 
 private:
 	enum TCMmcScannerAOState
@@ -75,6 +75,11 @@
 	
 	void SetState( TCMmcScannerAOState aState );		
 
+    /**
+    * From CActive
+    */
+    void DoCancel();
+	
 private:
 	TInt iState; // State of the active object
 	
@@ -101,6 +106,8 @@
 	RPointerArray<CHarvesterData> iHdArray;
 	
     CHarvesterEventManager* iHEM;
+    
+    RTimer iTimer;
 	};
 
 #endif // CMMCSCANNERAO_H
--- a/harvester/monitorplugins/mmcplugin/src/mmcmonitorao.cpp	Fri Mar 12 15:44:28 2010 +0200
+++ b/harvester/monitorplugins/mmcplugin/src/mmcmonitorao.cpp	Mon Mar 15 12:42:24 2010 +0200
@@ -44,7 +44,7 @@
 	
 	User::LeaveIfError( iFs.Connect() );
 	CActiveScheduler::Add( this );
-	for( TInt i=0; i<KMaxDrives; i++ )
+	for( TInt i = KMaxDrives - 1; i >=0; i-- )
 	    {
 	    iMediaIdList[i] = 0;
 	    }
@@ -112,27 +112,6 @@
 	return ETrue;
 	}
 
-TBool CMMCMonitorAO::Resume()
-	{
-	WRITELOG( "CMMCMonitorAO::Resume" ); // DEBUG INFO
-
-	iPreviousDriveList.Zero();
-	iPreviousDriveList.Copy( iDriveList );
-
-	BuildDriveList();
-	CompareDriveLists();
-	StartNotify();
-	
-	return ETrue;
-	}
-
-TBool CMMCMonitorAO::Pause()
-	{
-	WRITELOG( "CMMCMonitorAO::Pause" ); // DEBUG INFO
-	
-	return StopMonitoring();
-	}
-
 void CMMCMonitorAO::RunL()
 	{
 #ifdef _DEBUG
--- a/harvester/monitorplugins/mmcplugin/src/mmcmonitorplugin.cpp	Fri Mar 12 15:44:28 2010 +0200
+++ b/harvester/monitorplugins/mmcplugin/src/mmcmonitorplugin.cpp	Mon Mar 15 12:42:24 2010 +0200
@@ -112,7 +112,6 @@
     
 	TUint32 hdMediaId( 0 );
     hdMediaId = iMountTask->GetInternalDriveMediaId();
-    TBool alreadyWaited( EFalse );
     
     const TInt count( medias.Count() );
     for ( TInt i = 0; i < count; i++ )
@@ -130,8 +129,7 @@
     	        iMmcScanner = NULL;
     	        }
     		TRAP_IGNORE( iMmcScanner = CMmcScannerAO::NewL( medias[i].iMediaId, iMdEClient, iObserver,
-    		    				aHarvesterPluginFactory, CActive::EPriorityHigh, alreadyWaited ) );
-    		alreadyWaited = ETrue;
+    		    				aHarvesterPluginFactory, CActive::EPriorityUserInput ) );
     		}
     	}
  
@@ -157,7 +155,7 @@
 			medias.Append( hdInfo );
 			
 			TRAP_IGNORE( iHddScanner = CMmcScannerAO::NewL( hdMediaId, iMdEClient, iObserver,
-			    				aHarvesterPluginFactory, KHarvesterCustomImportantPriority, alreadyWaited ));
+			    				aHarvesterPluginFactory, KHarvesterCustomImportantPriority ));
 			}
 		}
 
@@ -251,10 +249,6 @@
             {
             WRITELOG( "CMMCMonitorPlugin::MountEvent with parameter EMounted" );
             mountData->iMountType = TMountData::EMount;
-            if( !iMountTask->IsActive() )
-                {
-                iMountTask->SetPriority( KHarvesterPriorityMonitorPlugin );
-                }
             iMountTask->StartMount( *mountData );
             }
         break;
@@ -269,10 +263,6 @@
             	{
 	            WRITELOG( "CMMCMonitorPlugin::MountEvent with parameter EDismounted" );
 	            mountData->iMountType = TMountData::EUnmount;
-	            if( !iMountTask->IsActive() )
-	                {
-	                iMountTask->SetPriority( KHarvesterPriorityMonitorPlugin );
-	                }
 	            iMountTask->StartUnmount( *mountData );
             	}
             }
@@ -282,18 +272,16 @@
             {
             WRITELOG( "CMMCMonitorPlugin::MountEvent with parameter EFormatted" );
             mountData->iMountType = TMountData::EFormat;
-            if( !iMountTask->IsActive() )
-                {
-                iMountTask->SetPriority( KHarvesterPriorityMonitorPlugin );
-                }
             iMountTask->StartUnmount( *mountData );
             }
         break;
         
         default:
             {
+#ifdef _DEBUG
             _LIT( KLogPanic, "unknown state" );
             User::Panic( KLogPanic, KErrArgument );
+#endif
             }
         break;
         }
--- a/harvester/monitorplugins/mmcplugin/src/mmcmounttaskao.cpp	Fri Mar 12 15:44:28 2010 +0200
+++ b/harvester/monitorplugins/mmcplugin/src/mmcmounttaskao.cpp	Mon Mar 15 12:42:24 2010 +0200
@@ -72,8 +72,11 @@
 	iFs.Close();
 	
 	iMountDataQueue.ResetAndDestroy();
+	iMountDataQueue.Close();
 	iEntryArray.ResetAndDestroy();
+	iEntryArray.Close();
 	iHarvestEntryArray.ResetAndDestroy();
+	iHarvestEntryArray.Close();
 	
 	delete iMdeSession;
   
@@ -126,7 +129,6 @@
 			{
 			Cancel();
 			Deinitialize();
-			iNextRequest = ERequestIdle;
 			}
 		}
 		
@@ -188,7 +190,6 @@
 				}
 			else
 				{
-			    SetPriority( KHarvesterCustomImportantPriority );
 				SetNextRequest( ERequestIdle );
 				iMountDataQueue.Compress();
 				}
@@ -349,7 +350,6 @@
 			WRITELOG( "CMMCMountTaskAO::RunL - ERequestCleanup" );
 			TBool present = (iMountData->iMountType == TMountData::EMount);
 			iMdeSession->SetMediaL( iMountData->iMediaID, iMountData->iDrivePath[0], present );
-			SetPriority( KHarvesterCustomImportantPriority );
 			Deinitialize();
 			SetNextRequest( ERequestStartTask );
 			}
--- a/harvester/monitorplugins/mmcplugin/src/mmcscannerao.cpp	Fri Mar 12 15:44:28 2010 +0200
+++ b/harvester/monitorplugins/mmcplugin/src/mmcscannerao.cpp	Mon Mar 15 12:42:24 2010 +0200
@@ -31,7 +31,7 @@
 CMmcScannerAO::CMmcScannerAO( TUint32 aMediaId, 
 		CMdEHarvesterSession* aMdEClient, MMonitorPluginObserver* aObserver, 
 		CHarvesterPluginFactory* aHarvesterPluginFactory, const TInt aPriority ) : 
-		CTimer( aPriority ), iState( EUninitialized ), iMmcFileList( NULL )   
+		CActive( aPriority ), iState( EUninitialized ), iMmcFileList( NULL )   
 	{
 	iMediaId = aMediaId;
 	iMdEClient = aMdEClient;
@@ -41,45 +41,39 @@
 
 CMmcScannerAO* CMmcScannerAO::NewL( TUint32 aMediaId, CMdEHarvesterSession* aMdEClient,
 		MMonitorPluginObserver* aObserver, CHarvesterPluginFactory* aHarvesterPluginFactory, 
-		const TInt aPriority, TBool aAlreadyWaited )
+		const TInt aPriority )
 	{
 	CMmcScannerAO* self = new ( ELeave ) CMmcScannerAO( aMediaId, aMdEClient, aObserver, 
 			aHarvesterPluginFactory, aPriority );
 	
 	CleanupStack::PushL( self );
-	self->ConstructL( aAlreadyWaited );
+	self->ConstructL( );
 	CleanupStack::Pop( self );
 	return self;
 	}
 
-void CMmcScannerAO::ConstructL( TBool aAlreadyWaited )
+void CMmcScannerAO::ConstructL()
 	{
-	CTimer::ConstructL();
-	CActiveScheduler::Add( this ); // Add to scheduler
+    CActiveScheduler::Add( this ); // Add to scheduler
+	iTimer.CreateLocal();
 	iState = EUninitialized;
 	User::LeaveIfError( iFs.Connect() );
 	iMmcFileList = CMmcFileList::NewL();
 	
-	if( !aAlreadyWaited )
-	    {
-        TInt tmpDelay( KDefaultDelay );
-        TTimeIntervalMicroSeconds32 delay( tmpDelay * KMillion ); 
-        CRepository* repo = CRepository::NewLC( KRepositoryUid );
-        const TInt err = repo->Get( KScanDelayKey, tmpDelay );
-        if ( err == KErrNone )
-            {
-            delay = tmpDelay * KMillion;
-            }
-        CleanupStack::PopAndDestroy( repo );
-        After( delay );
-	    }
-	else
-	    {
-	    TTimeIntervalMicroSeconds32 delay( 5 ); 
-	    After( delay );
-	    }
+    TInt tmpDelay( KDefaultDelay );
+    TTimeIntervalMicroSeconds32 delay( tmpDelay * KMillion ); 
+    CRepository* repo = CRepository::NewLC( KRepositoryUid );
+    const TInt err = repo->Get( KScanDelayKey, tmpDelay );
+    if ( err == KErrNone )
+        {
+        delay = tmpDelay * KMillion;
+        }
+    CleanupStack::PopAndDestroy( repo );
 	
     iHEM = CHarvesterEventManager::GetInstanceL();
+    
+    iTimer.After( iStatus, delay );
+    SetActive();
 	}
 
 CMmcScannerAO::~CMmcScannerAO()
@@ -207,10 +201,16 @@
 		case( EDone ):
 			{
 			iFs.Close();
+			iTimer.Close();
 		    iHdArray.Reset();
 		    iHdArray.Compress();
 			iEntryArray.Compress();
 			iHarvestEntryArray.Compress();
+		    if (iHEM)
+		        {
+		        iHEM->ReleaseInstance();
+		        iHEM = NULL;
+		        }
 			break;
 			}
 		
@@ -282,3 +282,10 @@
 		SetActive();
 		}
 	}
+
+void CMmcScannerAO::DoCancel()
+    {
+    iTimer.Cancel();
+    iTimer.Close();
+    }
+
--- a/harvester/server/group/harvesterserver.mmp	Fri Mar 12 15:44:28 2010 +0200
+++ b/harvester/server/group/harvesterserver.mmp	Mon Mar 15 12:42:24 2010 +0200
@@ -57,6 +57,7 @@
 SOURCE      harvesteroomao.cpp
 SOURCE      pauseobserverao.cpp
 SOURCE    harvestershutdownobserver.cpp
+SOURCE    harvesterdiskspaceobserver.cpp
 
 MW_LAYER_SYSTEMINCLUDE
 
--- a/harvester/server/inc/harvesterao.h	Fri Mar 12 15:44:28 2010 +0200
+++ b/harvester/server/inc/harvesterao.h	Mon Mar 15 12:42:24 2010 +0200
@@ -35,6 +35,7 @@
 #include "harvesteroomao.h"
 #include "backupsubscriber.h"
 #include "harvestermediaidutil.h"
+#include "harvesterdiskspaceobserver.h"
 
 
 // forward declarations
@@ -99,7 +100,8 @@
                      public MMdESessionObserver,
                      public MBackupRestoreObserver,
                      public MUnmountObserver,
-                     public MHarvesterOomObserver
+                     public MHarvesterOomObserver,
+                     public MMdSHarvesterDiskSpaceObserver
 	{
     public:
     
@@ -279,6 +281,9 @@
          * Backup&Restore has finished backup or restore.
          */
         void BackupRestoreReady();
+
+        // From MMdSHarvesterDiskSpaceObserver
+        void HandleDiskSpaceNotificationL( TDiskSpaceDirection aCrossDirection );
         
         /** */  	
         void HandleUnmount( TUint32 aMediaId );
@@ -546,6 +551,21 @@
         
         // Own.
         CDesCArray* iCameraExtensionArray;
+
+        /**
+        * Notifier for situations where free disk space runs out. Own
+        */
+        CMdSHarvesterDiskspaceObserverAO* iDiskFullNotifier;
+        
+        TBool iRamFull;
+        
+        TBool iDiskFull;
+        
+        TBool iManualPauseEnabled;
+        
+        TBool iFastHarvestNeeded;
+        
+        TBool iHarvestingPlaceholders;
 	};
 	
 #endif //__CHARVESTERAO_H__
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/server/inc/harvesterdiskspaceobserver.h	Mon Mar 15 12:42:24 2010 +0200
@@ -0,0 +1,152 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Low disk space observer for harvester server
+*
+*/
+
+
+#ifndef MDSHARVESTERDISKSPACEOBSERVERAO_H
+#define MDSHARVESTERDISKSPACEOBSERVERAO_H
+
+// INCLUDE FILES
+#include <e32base.h>
+#include <f32file.h>
+
+/**
+* MMdSHarvesterDiskSpaceObserver
+* Observer interface for a disk space notifier.
+*/
+class MMdSHarvesterDiskSpaceObserver
+    {
+    public :
+        enum TDiskSpaceDirection
+            {
+            /** Disk space is larger than threshold level */
+            EMore,
+
+            /** Disk space is smaller than threshold level */
+            ELess
+            };
+
+        /**
+         * Called to notify the observer that disk space has crossed the specified threshold value.
+         *
+         * @param aCrossDirection threshold cross direction
+         */
+        virtual void HandleDiskSpaceNotificationL(TDiskSpaceDirection aDiskSpaceDirection) = 0;
+    };
+
+/**
+* CMSDiskSpaceNotifierAO.
+* A disk space notifier class
+*/
+class CMdSHarvesterDiskspaceObserverAO : public CActive
+    {
+    public:
+        enum TDiskSpaceNotifierState
+            {
+            ENormal,
+            EIterate
+            };
+
+    public : // Constructors and destructors
+        /**
+         * Constructs a disk space notifier implementation.
+         *
+         * @param aThreshold minimum free disk space threshold level in bytes
+         * @param aFilename filename which defines monitored drive's number
+         * @return  metadata server implementation
+         */
+        static CMdSHarvesterDiskspaceObserverAO* NewL(
+            MMdSHarvesterDiskSpaceObserver& aObserver, 
+            TInt64 aThreshold, const TDesC& aFilename);
+
+        /**
+         * Constructs a disk space notifier implementation and leaves it
+         * in the cleanup stack.
+         *
+         * @param aThreshold minimum free disk space threshold level in bytes
+         * @param aFilename filename which defines monitored drive's number
+         * @return  metadata server implementation
+         */
+        static CMdSHarvesterDiskspaceObserverAO* NewLC(        
+            MMdSHarvesterDiskSpaceObserver& aObserver, 
+            TInt64 aThreshold, const TDesC& aFilename);
+
+        /**
+        * Destructor.
+        */
+        virtual ~CMdSHarvesterDiskspaceObserverAO();
+
+    protected: // Functions from base classes
+        /**
+         * From CActive
+         * Callback function.
+         * Invoked to handle responses from the server.
+         */
+        void RunL();
+
+        /**
+         * From CActive
+         * Handles errors that occur during notifying the observer.
+         */
+        TInt RunError(TInt aError);
+
+        /**
+         * From CActive
+         * Cancels any outstanding operation.
+         */
+        void DoCancel();
+
+    private: // Constructors and destructors
+
+        /**
+         * constructor
+         */
+        CMdSHarvesterDiskspaceObserverAO(
+            MMdSHarvesterDiskSpaceObserver& aObserver,
+            TInt64 aThreshold, TDriveNumber aDrive);
+
+        /**
+         * 2nd phase constructor
+         * @param aThreshold minimum free disk space threshold level in bytes
+         * @param aDrive monitored drive's number
+         */
+        void ConstructL();
+
+    private: // New methods
+
+        void StartNotifier();
+
+        static TDriveNumber GetDriveNumberL( const TDesC& aFilename );
+
+    private: // Data
+
+        MMdSHarvesterDiskSpaceObserver& iObserver;
+        
+        RFs iFileServerSession;
+        
+        const TInt64 iThreshold;
+        
+        const TDriveNumber iDrive;
+        
+        TDiskSpaceNotifierState iState;
+        
+        TInt iIterationCount;
+    };
+
+#endif // MDSHARVESTERDISKSPACEOBSERVERAO_H
+
+// End of File
+
--- a/harvester/server/inc/restorewatcher.h	Fri Mar 12 15:44:28 2010 +0200
+++ b/harvester/server/inc/restorewatcher.h	Mon Mar 15 12:42:24 2010 +0200
@@ -139,6 +139,9 @@
 	
 	/*iFileName - File used for restore flag.*/
 	TFileName iFileName;
+	
+	/*iFs - File server session, own.*/
+	RFs iFs;
 	};
 
 #endif  // RESTOREWATCHER_H
--- a/harvester/server/src/harvesterao.cpp	Fri Mar 12 15:44:28 2010 +0200
+++ b/harvester/server/src/harvesterao.cpp	Mon Mar 15 12:42:24 2010 +0200
@@ -125,7 +125,7 @@
 // CHarvesterAO
 // ---------------------------------------------------------------------------
 //
-CHarvesterAO::CHarvesterAO() : CActive( KHarvesterCustomImportantPriority )
+CHarvesterAO::CHarvesterAO() : CActive( KHarvesterPriorityHarvestingPlugin )
     {
     WRITELOG( "CHarvesterAO::CHarvesterAO() - begin" );
     
@@ -134,6 +134,12 @@
     
     iContextEngineInitialized = EFalse;
     iMdeSessionInitialized = EFalse;
+    
+    iRamFull = EFalse;
+    iDiskFull = EFalse;
+    iManualPauseEnabled = EFalse;
+    iFastHarvestNeeded = EFalse;
+    iHarvestingPlaceholders = EFalse;
     }
      
 // ---------------------------------------------------------------------------
@@ -164,6 +170,7 @@
     StopComposers();
     DeleteComposers();
 
+    delete iDiskFullNotifier;
 	delete iBackupSubscriber;
     
     if (iBlacklist)
@@ -186,9 +193,6 @@
             }
         }
     iHarvestFileMessages.Close();
-    
-    iMonitorPluginArray.ResetAndDestroy();
-    iMonitorPluginArray.Close();
   	
     iPHArray.ResetAndDestroy();
     iPHArray.Close();
@@ -231,10 +235,6 @@
 
     // Setting up MdE Session
 	iMdESession = CMdESession::NewL( *this );
-	
-    RProcess process;
- 	process.SetPriority( EPriorityBackground );
- 	process.Close();
  	
     // Setting up context Engine (initialization is ready when ContextInitializationStatus -callback is called)
     iCtxEngine = CContextEngine::GetInstanceL( this ); // Create the context engine
@@ -330,6 +330,8 @@
     WRITELOG( "CHarvesterAO::DeleteMonitorPlugins()" );
     
     iMonitorPluginArray.ResetAndDestroy();
+    iMonitorPluginArray.Close();
+    WRITELOG( "CHarvesterAO::DeleteMonitorPlugins() - end" );
     }
 
 // ---------------------------------------------------------------------------
@@ -405,7 +407,14 @@
 //
 void CHarvesterAO::HandleUnmount( TUint32 aMediaId )
 	{
-	WRITELOG1( "CHarvesterAO::HandleUnmount(%d)", aMediaId );
+    WRITELOG1( "CHarvesterAO::HandleUnmount(%d)", aMediaId );    
+    
+    if( !iServerPaused )
+        {
+        // Stop harvesting for unmount
+        PauseMonitoring();
+        PauseHarvester();
+        }
 	
     TUint32 mediaId( 0 );
     TUint removed( 0 );
@@ -421,7 +430,7 @@
         {
         for( TInt i=arrayCount-1; i>= 0; i--)
             {
-            hd = iPHArray[i];
+            hd = iReadyPHArray[i];
             err = iMediaIdUtil->GetMediaId( hd->Uri(), mediaId );
             
             if( err == KErrNone && mediaId == aMediaId )
@@ -434,6 +443,10 @@
                 arrayCount--;
                 }
             }
+        if( iReadyPHArray.Count() == 0 )
+            {
+            iReadyPHArray.Compress();
+            }
         WRITELOG1( "CHarvesterAO::HandleUnmount() DecreaseItemCountL iReadyPHArray %d", removed);
         TRAP_IGNORE( iHarvesterEventManager->DecreaseItemCountL( EHEObserverTypePlaceholder, removed) );
         }
@@ -461,6 +474,10 @@
                 arrayCount--;
                 }
             }
+        if( iPHArray.Count() == 0 )
+            {
+            iPHArray.Compress();
+            }
         WRITELOG1( "CHarvesterAO::HandleUnmount() DecreaseItemCountL iPHArray %d", removed);
         TRAP_IGNORE( iHarvesterEventManager->DecreaseItemCountL( EHEObserverTypePlaceholder, removed) );
         }
@@ -488,6 +505,10 @@
                 arrayCount--;
                 }
             }
+        if( iContainerPHArray.Count() == 0 )
+            {
+            iContainerPHArray.Compress();
+            }
         WRITELOG1( "CHarvesterAO::HandleUnmount() DecreaseItemCountL iContainerPHArray %d", removed);
         TRAP_IGNORE( iHarvesterEventManager->DecreaseItemCountL( EHEObserverTypePlaceholder, removed) );
         }
@@ -513,8 +534,6 @@
 	const TInt hpiArrayCount( hpiArray.Count() );
 	if( hpiArrayCount > 0 )
 		{
-		RArray<TItemId> placeholders;
-		
 		TUint32 mediaId( 0 );
 		TInt err( KErrNone );
 		
@@ -528,24 +547,22 @@
 				
 				err = iMediaIdUtil->GetMediaId( mdeobj.Uri(), mediaId );
 	
-				if( mdeobj.Placeholder() && ( aMediaId == mediaId || err != KErrNone ))
+				if( aMediaId == mediaId || err != KErrNone )
 					{
+                    hpi->iQueue.Remove(j);
 					removed++;
-					                    
-					TItemId id = mdeobj.Id();
-					placeholders.Append( id );
+
 					TRAP_IGNORE( iMdESession->CancelObjectL( mdeobj ) );
 					
 					delete hd;
 					hd = NULL;
-					hpi->iQueue.Remove(j);
-					
-					if( hpi->iQueue.Count() == 0 )
-						{
-						hpi->iQueue.Compress();
-						}
 					}
 				}
+			
+            if( hpi->iQueue.Count() == 0 )
+                {
+                hpi->iQueue.Compress();
+                }
 			}
 		
 		if( removed )
@@ -554,12 +571,15 @@
             TRAP_IGNORE( iHarvesterEventManager->DecreaseItemCountL( EHEObserverTypePlaceholder, removed ) );
             TRAP_IGNORE( iHarvesterEventManager->DecreaseItemCountL( EHEObserverTypeMMC, removed ) );
 		    }
-		
-		RArray<TItemId> results;
-		TRAP_IGNORE( iMdESession->RemoveObjectsL( placeholders, results, NULL ) );
-		results.Close();
-		placeholders.Close();
 		}
+	
+	// resume harvesting from last state
+    if( !iRamFull && !iDiskFull )
+        {
+        // resume monitoring
+        ResumeMonitoring();
+        TRAP_IGNORE( ResumeHarvesterL() );    
+        }
 	}
 
 // ---------------------------------------------------------------------------
@@ -622,6 +642,7 @@
     WRITELOG( "CHarvesterAO::DeleteComposers()" );
     
     iComposerPluginArray.ResetAndDestroy();
+    iComposerPluginArray.Close();
 
     WRITELOG( "CHarvesterAO::DeleteComposers() - end" );
     }
@@ -659,14 +680,58 @@
     
     if ( hd->ObjectType() == EPlaceholder )
     	{
+        iHarvestingPlaceholders = ETrue;
+        if( !iFastHarvestNeeded )
+            {
+            SetPriority( KHarvesterCustomImportantPriority );
+            }
     	while( hd != NULL &&
 				iPHArray.Count() < KPlaceholderQueueSize &&
 				hd->ObjectType() == EPlaceholder )
     		{
         	iPHArray.Append( hd );
+        	if( hd->Origin() == MdeConstants::Object::ECamera || 
+        	    hd->ObjectType() == EFastHarvest  )
+        	    {
+        	    if( !iFastHarvestNeeded )
+        	        {
+                    iFastHarvestNeeded = ETrue;
+                    // Fast harvest event must be handled even if MMC handling would be ongoing
+                    SetPriority( KHarvesterPriorityMonitorPlugin );
+        	        }
+        	    break;
+        	    }
+        	else if( iFastHarvestNeeded )
+        	    {
+        	    iFastHarvestNeeded = EFalse;
+        	    SetPriority( KHarvesterCustomImportantPriority );
+        	    }
         	hd = iQueue->GetNextItem();
     		}
     	
+    	if( iFastHarvestNeeded && iPHArray.Count() > 0 )
+    	    {
+            TRAPD( err, HandlePlaceholdersL( ETrue ) );
+
+            // make sure that when HandlePlaceholdersL leaves, iPHArray is cleared
+            if ( err != KErrNone )
+                {
+                iPHArray.ResetAndDestroy();
+                User::Leave( err );
+                }
+            
+            TInt count( iReadyPHArray.Count() );
+            for( TInt i = 0; i < count; i++ )
+                {
+                CheckFileExtensionAndHarvestL( iReadyPHArray[i] );
+                iReadyPHArray.Remove( i );
+                // correct the index so harvesting order remains ok
+                i--;
+                count--;
+                }
+            return;
+    	    }
+    	
 		if( hd )
     		{
 	    	if( hd->ObjectType() == EPlaceholder )
@@ -693,6 +758,11 @@
     	}
     else
     	{
+        if( iHarvestingPlaceholders && !iFastHarvestNeeded )
+            {
+            SetPriority( KHarvesterPriorityHarvestingPlugin );
+            }
+        iHarvestingPlaceholders = EFalse;
         CheckFileExtensionAndHarvestL( hd );
     	}
     }
@@ -1216,19 +1286,20 @@
                 WRITELOG( "CHarvesterAO::HandleSessionOpened() - ObjectHandler creation failed" );
                 }
         
+        // Setting up monitor plugins
+        TRAP( errorTrap, LoadMonitorPluginsL() );
+        if ( errorTrap != KErrNone )
+            {
+            WRITELOG( "CHarvesterAO::HandleSessionOpened() - error loading monitor plugins" );
+            }
+
+        // To check if the default namespace structure is in order
         TRAP( errorTrap, PreallocateNamespaceL( aSession.GetDefaultNamespaceDefL() ) );
         if ( errorTrap != KErrNone )
             {
             WRITELOG( "CHarvesterAO::HandleSessionOpened() - error loading default schema" );
             }
         
-        // Setting up monitor plugins
-        TRAP( errorTrap, LoadMonitorPluginsL() );
-        if ( errorTrap != KErrNone )
-            {
-            WRITELOG( "CHarvesterAO::HandleSessionOpened() - error loading monitor plugins" );
-            }
-            
         TRAP( errorTrap, StartComposersL() );
         if ( errorTrap != KErrNone )
             {
@@ -1250,6 +1321,12 @@
 
             // Starting monitor plugins
         StartMonitoring();
+
+        TRAP( errorTrap, iDiskFullNotifier = CMdSHarvesterDiskspaceObserverAO::NewL( *this, KDiskFullThreshold, KMdsSqlDbDefaultName ) );
+        if ( errorTrap != KErrNone )
+            {
+            WRITELOG( "CHarvesterAO::HandleSessionOpened() - couldn't start diskspace observer" );
+            }
         
         TRAP( errorTrap, iOnDemandAO = COnDemandAO::NewL( *iMdESession, *iQueue, 
         		*iHarvesterPluginFactory, &iReadyPHArray ) );
@@ -1374,8 +1451,16 @@
     {
     WRITELOG( "CHarvesterAO::PauseHarvester()" );
 
+    Cancel();
+    
+    iHarvesterPluginFactory->PauseHarvester( ETrue );
     iServerPaused = ETrue;
     
+    if( !iRamFull && !iDiskFull )
+        {
+        iManualPauseEnabled = ETrue;
+        }
+    
     // Everything is paused
     WRITELOG( "CHarvesterAO::PauseHarvester() - Moving paused state paused" );
     
@@ -1390,7 +1475,9 @@
     {
     WRITELOG( "CHarvesterAO::ResumeHarvesterL()" );
     
+    iHarvesterPluginFactory->PauseHarvester( EFalse );
     iServerPaused = EFalse;
+    iManualPauseEnabled = EFalse;
     
     SetNextRequest( ERequestHarvest );
     }
@@ -1430,17 +1517,31 @@
                 {
                 ReadItemFromQueueL();
 				SetNextRequest( ERequestHarvest );
+				break;
                 }
 
-            // no more items to harvest
+            // no more items to handle from main queue
             else
                 {
-                // if container files to harvest, handle those
+                // All registered fast harvested items or placeholders handled at this point     
+                // if container files to harvest, handle those next
                 if( iContainerPHArray.Count() > 0 )
                 	{
+                    iFastHarvestNeeded = EFalse;
+                    iHarvestingPlaceholders = EFalse;
+                    SetPriority( KHarvesterPriorityHarvestingPlugin );
                 	SetNextRequest( ERequestContainerPlaceholder );
                 	break;
                 	}
+                else if( iHarvestingPlaceholders || iFastHarvestNeeded )
+                    {
+                    // reset to default priority       
+                    iFastHarvestNeeded = EFalse;
+                    iHarvestingPlaceholders = EFalse;
+                    SetPriority( KHarvesterPriorityHarvestingPlugin );
+                    SetNextRequest( ERequestHarvest );
+                    break;
+                    }
                 
                 const TInt arrayCount( iReadyPHArray.Count() );
 				if( arrayCount > 0 )
@@ -1494,6 +1595,7 @@
 	    	// make sure that when HandlePlaceholdersL leaves, iPHArray is cleared
 	    	if ( err != KErrNone )
 	    		{
+	    	    iContainerPHArray.ResetAndDestroy();
 	    		iPHArray.ResetAndDestroy();
 	    		User::Leave( err );
 	    		}
@@ -1650,6 +1752,43 @@
     }
 
 // ---------------------------------------------------------------------------
+// From MMdSHarvesterDiskSpaceObserver.
+// Called when change is disk space status occures
+// ---------------------------------------------------------------------------
+//
+void CHarvesterAO::HandleDiskSpaceNotificationL( TDiskSpaceDirection aDiskSpaceDirection )
+    {
+    WRITELOG("CHarvesterAO::HandleDiskSpaceNotificationL()");
+    if( MMdSHarvesterDiskSpaceObserver::EMore == aDiskSpaceDirection )
+        {
+        WRITELOG("CHarvesterAO::HandleDiskSpaceNotificationL() - disk full");
+        iDiskFull = EFalse;
+        }
+    else
+        {
+        WRITELOG("CHarvesterAO::HandleDiskSpaceNotificationL() - disk space available");
+        iDiskFull = ETrue;
+        if( iServerPaused )
+            {
+            return;
+            }
+        }
+    
+    if( iDiskFull )
+        {
+        // cache monitored events
+        PauseMonitoring();   
+        PauseHarvester();    
+        }
+    else if( !iRamFull && !iManualPauseEnabled && iServerPaused )
+        {
+        // resume monitoring
+        ResumeMonitoring();
+        TRAP_IGNORE( ResumeHarvesterL() );    
+        }
+    }
+
+// ---------------------------------------------------------------------------
 // HarvestFile
 // ---------------------------------------------------------------------------
 //
@@ -2352,9 +2491,7 @@
 
 TBool CHarvesterAO::IsDescInArray(const TPtrC& aSearch, const RPointerArray<HBufC>& aArray)
 	{
-	const TInt count = aArray.Count();
-	
-	for( TInt i = 0; i < count; i++ )
+	for( TInt i = aArray.Count() - 1; i >=0; i-- )
 		{
 		const TDesC& ignorePath = aArray[i]->Des();
 		
@@ -2584,17 +2721,14 @@
 
 void CHarvesterAO::PreallocateNamespaceL( CMdENamespaceDef& aNamespaceDef )
 	{
-	const TInt objectDefCount = aNamespaceDef.ObjectDefCount();
-
-	for( TInt i = 0; i < objectDefCount; i++ )
+	for( TInt i = aNamespaceDef.ObjectDefCount() - 1; i >=0; i-- )
 		{
 		CMdEObjectDef& objectDef = aNamespaceDef.ObjectDefL( i );
 
-		const TInt propertyDefCount = objectDef.PropertyDefCount();
-
-		for( TInt j = 0; j < propertyDefCount; j++ )
+		for( TInt j = objectDef.PropertyDefCount() - 1; j >=0; j-- )
 			{
-			CMdEPropertyDef& propertyDef = objectDef.PropertyDefL( j );
+		    // No need for a local copy of the returned pointer
+			objectDef.PropertyDefL( j );
 			}
 		}
 	}
@@ -2639,20 +2773,35 @@
 
 void CHarvesterAO::MemoryLow()
 	{
-	WRITELOG("CHarvesterAO::MemoryLow()");
+    WRITELOG("CHarvesterAO::MemoryLow()");
+    iRamFull = ETrue;
+    
+    if( iServerPaused )
+        {
+        return;
+        }
+
 	// cache monitored events
 	PauseMonitoring();
+	PauseHarvester();
 	
-	PauseHarvester();
+	iPHArray.Compress();
+	iReadyPHArray.Compress();
+	iContainerPHArray.Compress();
 	}
 
 void CHarvesterAO::MemoryGood()
 	{
-	WRITELOG("CHarvesterAO::MemoryGood()");
-	// resume monitoring
-	ResumeMonitoring();
-	
-	TRAP_IGNORE( ResumeHarvesterL() );
+    WRITELOG("CHarvesterAO::MemoryGood()");    
+    iRamFull = EFalse;
+    
+    if( !iDiskFull && !iManualPauseEnabled && iServerPaused )
+        {
+        // resume monitoring
+        ResumeMonitoring();
+    
+        TRAP_IGNORE( ResumeHarvesterL() );    
+        }
 	}
 
 TBool CHarvesterAO::CheckForCameraItem( CHarvesterData* aHd, TDes& aObjectDef )
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/harvester/server/src/harvesterdiskspaceobserver.cpp	Mon Mar 15 12:42:24 2010 +0200
@@ -0,0 +1,189 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Low disk space observer for harvester server
+*
+*/
+
+#include "harvesterdiskspaceobserver.h"
+#include "harvestercommon.h"
+
+CMdSHarvesterDiskspaceObserverAO* CMdSHarvesterDiskspaceObserverAO::NewL(
+    MMdSHarvesterDiskSpaceObserver& aObserver, TInt64 aThreshold, const TDesC& aFilename)
+    {
+    CMdSHarvesterDiskspaceObserverAO* self = 
+        CMdSHarvesterDiskspaceObserverAO::NewLC( aObserver, aThreshold, aFilename );
+    CleanupStack::Pop( self );
+    return self;
+    }
+
+CMdSHarvesterDiskspaceObserverAO* CMdSHarvesterDiskspaceObserverAO::NewLC(
+    MMdSHarvesterDiskSpaceObserver& aObserver, TInt64 aThreshold, const TDesC& aFilename)
+    {
+    TDriveNumber driveNumber = GetDriveNumberL( aFilename );
+
+    CMdSHarvesterDiskspaceObserverAO* self = 
+        new ( ELeave ) CMdSHarvesterDiskspaceObserverAO( aObserver, aThreshold, driveNumber );
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    return self;
+    }
+
+CMdSHarvesterDiskspaceObserverAO::~CMdSHarvesterDiskspaceObserverAO()
+    {
+    Cancel();
+
+    iFileServerSession.Close();
+    }
+
+void CMdSHarvesterDiskspaceObserverAO::RunL()
+    {   
+    TVolumeInfo volumeInfo;
+
+    if ( iState == CMdSHarvesterDiskspaceObserverAO::ENormal )
+        {
+        TInt status = iStatus.Int();
+        
+        switch( status )
+            {
+            case KErrNone:
+                {
+                const TInt error = iFileServerSession.Volume( volumeInfo, iDrive );
+                if( error != KErrNone )
+                    {
+                    // Continue harvester if some error in accessing volume occures so that harvester does not remain paused forever 
+                    iObserver.HandleDiskSpaceNotificationL( MMdSHarvesterDiskSpaceObserver::EMore );
+                    StartNotifier();
+                    break;
+                    }
+                
+                // Check if free space is less than threshold level
+                if( volumeInfo.iFree < iThreshold )
+                    {
+                    iObserver.HandleDiskSpaceNotificationL( MMdSHarvesterDiskSpaceObserver::ELess );
+                    iState = EIterate;
+                    iIterationCount = 0;
+                    SetActive();
+                    TRequestStatus* status = &iStatus;
+                    User::RequestComplete( status, KErrNone );
+                    return;
+                    }
+                else
+                    {
+                    iObserver.HandleDiskSpaceNotificationL( MMdSHarvesterDiskSpaceObserver::EMore );
+                    }
+                StartNotifier();
+                break;
+                }
+
+            default:
+                StartNotifier();
+                break;
+            }
+        }
+    else if ( iState == CMdSHarvesterDiskspaceObserverAO::EIterate )
+        {
+        const TInt KMaxIterations = 5;
+        TInt error = iFileServerSession.Volume( volumeInfo, iDrive );
+        if( error != KErrNone )
+            {
+            // Continue harvester if some error in accessing volume occures so that harvester does not remain paused forever 
+            iObserver.HandleDiskSpaceNotificationL( MMdSHarvesterDiskSpaceObserver::EMore );
+            iState = ENormal;
+            iIterationCount = 0;
+            StartNotifier();
+            return;
+            }
+
+        if ( volumeInfo.iFree < iThreshold )
+            {
+            ++iIterationCount;
+            if ( iIterationCount < KMaxIterations )
+                {
+                SetActive();
+                TRequestStatus* status = &iStatus;
+                User::RequestComplete( status, KErrNone );
+                return;
+                }
+            }
+        else
+            {
+            iObserver.HandleDiskSpaceNotificationL( MMdSHarvesterDiskSpaceObserver::EMore );
+            }
+        iState = ENormal;
+        iIterationCount = 0;
+        StartNotifier();            
+        }
+    else
+        {
+        User::Leave( KErrGeneral );
+        }
+    }
+
+TInt CMdSHarvesterDiskspaceObserverAO::RunError(TInt /*aError*/)
+    {
+    StartNotifier();     
+    
+    return KErrNone;
+    }
+
+void CMdSHarvesterDiskspaceObserverAO::DoCancel()
+    {
+    if( IsActive() )
+        {   
+        iFileServerSession.NotifyDiskSpaceCancel();
+        }
+    }
+
+CMdSHarvesterDiskspaceObserverAO::CMdSHarvesterDiskspaceObserverAO(
+    MMdSHarvesterDiskSpaceObserver& aObserver, TInt64 aThreshold, TDriveNumber aDrive)
+    : CActive( KHarvesterPriorityMonitorPlugin), 
+    iObserver( aObserver ), iThreshold( aThreshold ), iDrive( aDrive ), iState( CMdSHarvesterDiskspaceObserverAO::ENormal )
+    {
+    CActiveScheduler::Add( this );
+    }
+
+void CMdSHarvesterDiskspaceObserverAO::ConstructL()
+    {   
+    TInt KMessageSlotCount = 2; // slots for NotifyDiskSpace and NotifyDiskSpaceCancel
+
+    User::LeaveIfError( iFileServerSession.Connect( KMessageSlotCount ) );
+
+    StartNotifier();
+    }
+
+void CMdSHarvesterDiskspaceObserverAO::StartNotifier()
+    {   
+    iFileServerSession.NotifyDiskSpace( iThreshold, iDrive, iStatus );
+    
+    SetActive();
+    }
+
+TDriveNumber CMdSHarvesterDiskspaceObserverAO::GetDriveNumberL( const TDesC& aFilename )
+    {
+    TLex driveParser( aFilename );
+    
+    TChar driveChar = driveParser.Get();
+
+    if( 0 == driveChar || TChar( ':' ) != driveParser.Peek() )
+        {
+        User::Leave( KErrArgument );
+        }
+        
+    TInt driveNumber;
+    
+    RFs::CharToDrive( driveChar, driveNumber );
+    
+    return (TDriveNumber)driveNumber;
+    }
+
--- a/harvester/server/src/harvesteroomao.cpp	Fri Mar 12 15:44:28 2010 +0200
+++ b/harvester/server/src/harvesteroomao.cpp	Mon Mar 15 12:42:24 2010 +0200
@@ -77,7 +77,7 @@
 	TInt oomStatus( 0 );
 	const TInt err = iOomMsgQueue.Receive( oomStatus );
 	
-	if( oomStatus == TMdsOomFreeRam )
+	if( oomStatus == EMdsOomFreeRam )
 		{
 		iObserver->MemoryLow();
 		}
--- a/harvester/server/src/harvesterqueue.cpp	Fri Mar 12 15:44:28 2010 +0200
+++ b/harvester/server/src/harvesterqueue.cpp	Mon Mar 15 12:42:24 2010 +0200
@@ -20,6 +20,7 @@
 #include "harvesterlog.h"
 #include "harvesterblacklist.h"
 #include "mdsutils.h"
+#include "harvestercommon.h"
 
 // ---------------------------------------------------------------------------
 // NewL
@@ -157,6 +158,10 @@
     if ( aItem->ObjectType() == EFastHarvest || aItem->Origin() == MdeConstants::Object::ECamera )
     	{
     	err = iItemQueue.Insert( aItem, 0 );
+    	if( !iHarvesterAO->IsActive() )
+    	    {
+            iHarvesterAO->SetPriority( KHarvesterPriorityMonitorPlugin );
+    	    }
     	}
     else
     	{
@@ -188,7 +193,7 @@
     TUint32 mediaId( 0 );
     CHarvesterData* hd = NULL;
     
-    for(TInt i = iItemQueue.Count() - 1; i >=0; i--)
+    for( TInt i = iItemQueue.Count() - 1; i >=0; i-- )
         {
         hd = iItemQueue[i];
         err = iMediaIdUtil->GetMediaId( hd->Uri(), mediaId );
@@ -212,7 +217,10 @@
             WRITELOG1( "CHarvesterQueue::RemoveItems( ) GetMediaId err == %d", err);
             }
         }
-    iItemQueue.Compress();
+    if( removedCount > 0 )
+        {
+        iItemQueue.Compress();
+        }
 #ifdef _DEBUG
     WRITELOG2( "CHarvesterQueue::RemoveItems() iItemQueue.Count() = %d, removedCount = %d", iItemQueue.Count(), removedCount);
 #endif
--- a/harvester/server/src/harvesterserver.cpp	Fri Mar 12 15:44:28 2010 +0200
+++ b/harvester/server/src/harvesterserver.cpp	Mon Mar 15 12:42:24 2010 +0200
@@ -157,7 +157,7 @@
     WRITELOG( "CHarvesterServer::NewLC() - begin" );
     
 	CHarvesterServer* self = new (ELeave) CHarvesterServer(
-			CActive::EPriorityStandard, KHarvesterServerPolicy, 
+			CActive::EPriorityUserInput, KHarvesterServerPolicy, 
 			ESharableSessions );
 	CleanupStack::PushL( self );
 	self->ConstructL();
@@ -196,8 +196,12 @@
 	WRITELOG( "CHarvesterServer::ConstructL() - begin" );
 	StartL( KHarvesterServerName );
 	iHarvesterAO = CHarvesterAO::NewL();
-	iHarvesterAO->SetHarvesterStatusObserver( this );
 	
+    RProcess process;
+    process.SetPriority( EPriorityBackground );
+    process.Close();
+	
+	iHarvesterAO->SetHarvesterStatusObserver( this );	
 	iPauseObserverAO = CPauseObserverAO::NewL( *this );
 	
     // create shutdown observer
--- a/harvester/server/src/harvesterserversession.cpp	Fri Mar 12 15:44:28 2010 +0200
+++ b/harvester/server/src/harvesterserversession.cpp	Mon Mar 15 12:42:24 2010 +0200
@@ -55,7 +55,6 @@
 void CHarvesterServerSession::ConstructL()
 	{
     WRITELOG( "CHarvesterServerSession::ConstructL()" );
-
 	}
 
 // ---------------------------------------------------------------------------
--- a/harvester/server/src/mdeobjecthandler.cpp	Fri Mar 12 15:44:28 2010 +0200
+++ b/harvester/server/src/mdeobjecthandler.cpp	Mon Mar 15 12:42:24 2010 +0200
@@ -127,7 +127,7 @@
                		iMdeSession->NewRelationLC(
                 		albumRelationDef, albumId, objectId, 0 );
                 relationEventArray.Append( STATIC_CAST( CMdEInstanceItem*, relation ) );
-                CleanupStack::Pop();
+                CleanupStack::Pop(); //relation
                 }
             }
         }
@@ -141,7 +141,7 @@
             CMdEEvent* event = iMdeSession->NewEventLC( 
             		*eventDef, objectId, time );
             relationEventArray.Append( STATIC_CAST( CMdEInstanceItem*, event ) );
-            CleanupStack::Pop();
+            CleanupStack::Pop(); // event
             }
         }
 
@@ -186,6 +186,49 @@
                 error = tempFile.Open( iFs, aHD.Uri(), EFileRead | EFileShareReadersOnly );
                 if( error != KErrNone )
                     {
+#ifdef _DEBUG
+                    if( error == KErrInUse || error || KErrLocked )
+                        {
+                        TPtrC fileName( aHD.Uri().Mid(2) );
+                        WRITELOG1( "CMdeObjectHandler :: Checking open file handles to %S", &fileName );
+
+                        CFileList* fileList = 0;
+                        TOpenFileScan fileScan( iFs );
+
+                        fileScan.NextL( fileList );   
+          
+                        while ( fileList )   
+                            {
+                            const TInt count( fileList->Count() ); 
+                            for (TInt i = 0; i < count; i++ )   
+                                {   
+                                if ( (*fileList)[i].iName == aHD.Uri().Mid(2) )
+                                    {
+                                    TFullName processName;
+                                    TFindThread find(_L("*"));
+                                    while( find.Next( processName ) == KErrNone )
+                                        {
+                                        RThread thread;
+                                        TInt err = thread.Open( processName );
+             
+                                        if ( err == KErrNone )
+                                            {
+                                            if ( thread.Id().Id() ==  fileScan.ThreadId() )
+                                                {
+                                                processName = thread.Name();
+                                                thread.Close();
+                                                WRITELOG1( "CMdeObjectHandler:: %S has a file handle open", &processName );
+                                                break;
+                                                }
+                                            thread.Close();
+                                            }
+                                        }
+                                    }
+                                }
+                            fileScan.NextL( fileList );   
+                            } 
+                        }
+#endif
                     WRITELOG( "CMdeObjectHandler::GetMetadataObjectL() - file handle is open! Returning." );
                     return NULL;
                     }
--- a/harvester/server/src/restorewatcher.cpp	Fri Mar 12 15:44:28 2010 +0200
+++ b/harvester/server/src/restorewatcher.cpp	Mon Mar 15 12:42:24 2010 +0200
@@ -66,7 +66,6 @@
 //
 CRestoreWatcher::~CRestoreWatcher()
 	{
-	
 	if( iPropertyWatcher )
 		{
 		iPropertyWatcher->StopListeningKeyChanges( 
@@ -80,6 +79,8 @@
 		
 		iPropertyWatcher->Delete(); // Release connection to TLS object.
 		}
+	
+	iFs.Close();
 	}
 
 // -----------------------------------------------------------------------------
@@ -91,6 +92,8 @@
 	{
 	WRITELOG("CRestoreWatcher::ConstructL()");
 
+    User::LeaveIfError( iFs.Connect() );
+	
 	CreateFileNameL();
 	CheckRestoreL();
     WRITELOG1("CRestoreWatcher::ConstructL() - iRestoreDone: %d", iRestoreDone );
@@ -136,17 +139,12 @@
 	TInt drive ( 0 );
 	User::LeaveIfError( 
 			DriveInfo::GetDefaultDrive( DriveInfo::EDefaultSystem, drive ) );
-
-    RFs fsSession;
-    User::LeaveIfError( fsSession.Connect() );
   
     TChar driveLetter;
-    fsSession.DriveToChar( drive, driveLetter );
+    iFs.DriveToChar( drive, driveLetter );
 	
     iFileName.Append( driveLetter );
     iFileName.Append( KRestoreFile );  // result-> C:\\private\\200009F5\\restoredone
- 
-    fsSession.Close();
 	}
 
 
@@ -274,22 +272,17 @@
 //
 void CRestoreWatcher::SetRestoreFlagL( TBool aRestoreDone )
 	{	
-	RFs fs;
-	User::LeaveIfError( fs.Connect() );
-	
 	iRestoreDone = aRestoreDone;
 	if( aRestoreDone )
 		{	
 		RFile64 file;
-		file.Replace( fs, iFileName, EFileWrite );
+		file.Replace( iFs, iFileName, EFileWrite );
 		file.Close();
 		}
 	else
 		{
-		fs.Delete( iFileName );
+		iFs.Delete( iFileName );
 		}
-	
-	fs.Close();
 	}
 
 // -----------------------------------------------------------------------------
@@ -299,13 +292,10 @@
 //
 void CRestoreWatcher::CheckRestoreL()
 	{
-	RFs fs;
 	RFile64 file;
-	User::LeaveIfError( fs.Connect() );
 	TInt fileError( KErrNotFound );
-	fileError = file.Open( fs, iFileName, EFileRead );
+	fileError = file.Open( iFs, iFileName, EFileRead );
 	file.Close();
-	fs.Close();
     
 	WRITELOG1("CRestoreWatcher::StartMonitoring - fileError: %d", fileError);
 	
--- a/inc/mdscommoninternal.h	Fri Mar 12 15:44:28 2010 +0200
+++ b/inc/mdscommoninternal.h	Mon Mar 15 12:42:24 2010 +0200
@@ -58,8 +58,9 @@
 const TUint KMdSServMinorVersionNumber=5;
 const TUint KMdSServBuildVersionNumber=0;
 
+const TUint32 KNokiaVendorId = 52487775;
 
-const TUint32 KNokiaVendorId = 52487775;
+const TInt64 KDiskFullThreshold = 1024*50; // 50 kB
 
 // P&S stuff
 static _LIT_SECURITY_POLICY_PASS(KAllowAllPolicy);
@@ -268,6 +269,10 @@
 	
 	ESchemaModify             = 0x01000000,
 	
+	EObjectNotifyAddWithUri        = 0x10000000,
+    EObjectNotifyModifyWithUri     = 0x20000000,
+    EObjectNotifyRemoveWithUri     = 0x40000000,	
+	
 	// 0x80000000 is not allowed (signed number is negative)
 	};
 
--- a/locationmanager/client/src/rlocationobjectmanipulator.cpp	Fri Mar 12 15:44:28 2010 +0200
+++ b/locationmanager/client/src/rlocationobjectmanipulator.cpp	Mon Mar 15 12:42:24 2010 +0200
@@ -132,7 +132,7 @@
     TInt urisRequiredSize = CMdCSerializationBuffer::KRequiredSizeForTInt32;
 
     // and URIs
-    for( TInt i = 0; i < uriCount; i++ )
+    for( TInt i = uriCount - 1; i >=0; i-- )
     	{
     	urisRequiredSize += CMdCSerializationBuffer::RequiredSize( *aTargetURIs[i] );
     	}
@@ -150,7 +150,7 @@
         return;
         }
 
-    for( TInt i = 0; i < uriCount; i++ )
+    for( TInt i = uriCount - 1; i >=0; i-- )
 		{
 		TRAPD( err, uriBuffer->InsertL( *aTargetURIs[i] ) );
 		
--- a/locationmanager/client/src/rtracklog.cpp	Fri Mar 12 15:44:28 2010 +0200
+++ b/locationmanager/client/src/rtracklog.cpp	Mon Mar 15 12:42:24 2010 +0200
@@ -52,7 +52,7 @@
     LOG( "RTrackLog::StopTrackLog()" );
     if ( iHandle )
         {
-        SendReceive( ELocManStopTrackLog);
+        Send( ELocManStopTrackLog );
         }   
     }
 
--- a/locationmanager/locationtrail/inc/clocationrecord.h	Fri Mar 12 15:44:28 2010 +0200
+++ b/locationmanager/locationtrail/inc/clocationrecord.h	Mon Mar 15 12:42:24 2010 +0200
@@ -61,6 +61,18 @@
                                   const TInt aError ) __SOFTFP = 0;
     
     virtual void GPSSignalQualityChanged( const TPositionSatelliteInfo& aSatelliteInfo ) __SOFTFP = 0;
+    
+    /**
+     * Callback method to notify observer that during waiting for positioning stop timeout remap is done.
+     */
+    virtual void RemapedCompleted() = 0;
+    
+    /**
+     * Returns if in ETrialStopping state server waits for positioning stop timeout
+     * @returns <code>ETrue</code> if server is waiting for positioning stop timeout
+     *          <code>EFalse</code>, otherwise.
+     */
+    virtual TBool WaitForPositioningStopTimeout() = 0;
     };
 
 /**
--- a/locationmanager/locationtrail/src/cgpxconverterao.cpp	Fri Mar 12 15:44:28 2010 +0200
+++ b/locationmanager/locationtrail/src/cgpxconverterao.cpp	Mon Mar 15 12:42:24 2010 +0200
@@ -275,8 +275,7 @@
 				distance = iBoundaries->distance;
 				}
 			
-			TInt count = iObservers.Count();
-			for( TInt i = 0; i < count; i++ )
+			for( TInt i = iObservers.Count() - 1; i >=0; i-- )
 				{
 				iObservers[i]->GpxFileCreated( iGpxPath, iTagId, distance, iStartTime, iEndTime );
 				}
--- a/locationmanager/locationtrail/src/clocationrecord.cpp	Fri Mar 12 15:44:28 2010 +0200
+++ b/locationmanager/locationtrail/src/clocationrecord.cpp	Mon Mar 15 12:42:24 2010 +0200
@@ -403,6 +403,13 @@
                 		)
                 		}
                		iRemapper->StartRemappingObjects( iNewItem.iLocationData );
+
+                    if( iObserver->WaitForPositioningStopTimeout() && !RemappingNeeded() )                                
+               		    {                                                
+                        iObserver->RemapedCompleted();
+                        return;
+               		    }
+               		
                 	}
                 if ( iState != RLocationTrail::ETrailStopping )
                 	{
@@ -1094,12 +1101,16 @@
     CMdEProperty* property = NULL;
     
     object = iMdeSession->GetObjectL( aObjectId );
+    CleanupStack::PushL( object );
     object->Property( timeDef, property, 0 );
     if ( !property )
         {
         User::Leave( KErrNotFound );
         }
-    return property->TimeValueL();
+    
+    const TTime timeValue( property->TimeValueL() );
+    CleanupStack::PopAndDestroy( object );
+    return timeValue;
     }
 
 EXPORT_C TBool CLocationRecord::RemappingNeeded()
--- a/locationmanager/locationtrail/src/cpositioninfo.cpp	Fri Mar 12 15:44:28 2010 +0200
+++ b/locationmanager/locationtrail/src/cpositioninfo.cpp	Mon Mar 15 12:42:24 2010 +0200
@@ -45,6 +45,7 @@
     : CActive( CActive::EPriorityStandard ),
     iFirstInterval( ETrue )
     {
+    LOG( "CPositionInfo::CPositionInfo()");
     CActiveScheduler::Add( this );
     iTrail = aTrail;
     iTrailCaptureSetting = RLocationTrail::ECaptureAll;
@@ -101,6 +102,15 @@
     iFirstInterval = ETrue;
     iPositionInfo = TPositionSatelliteInfo();
     
+    // Set update interval.
+     iUpdateOptions.SetUpdateInterval( TTimeIntervalMicroSeconds(KFirstInterval) );
+     // Set time out level. 
+     iUpdateOptions.SetUpdateTimeOut( TTimeIntervalMicroSeconds( KFirstTimeOut) );
+     // Positions which have time stamp below KMaxAge can be reused
+     iUpdateOptions.SetMaxUpdateAge( TTimeIntervalMicroSeconds(KMaxAge) );
+     // Disables location framework to send partial position data
+     iUpdateOptions.SetAcceptPartialUpdates( EFalse );
+    
     if ( aCaptureSetting == RLocationTrail::ECaptureAll ) 
     	{
 	    User::LeaveIfError( iPosServer.Connect() );
@@ -149,11 +159,8 @@
 //
 void CPositionInfo::Stop()
     {
-    Cancel();
-    
-    iFirstInterval = ETrue;
-    iUpdateOptions.SetUpdateInterval( TTimeIntervalMicroSeconds( KFirstInterval ) );
-    
+    Cancel();    
+
     iPositioner.Close();
     iPosServer.Close();
     }    
@@ -165,11 +172,19 @@
 void CPositionInfo::RunL()
     { 
     iTrail->Position( iPositionInfo, iStatus.Int() );
-    if ( iFirstInterval && iTrailCaptureSetting == RLocationTrail::ECaptureAll )
+ 
+    if ( iFirstInterval && IsActive() )
     	{
-    	iUpdateOptions.SetUpdateInterval( TTimeIntervalMicroSeconds( iUpdateInterval ) );
-    	iUpdateOptions.SetUpdateTimeOut( TTimeIntervalMicroSeconds( KUpdateTimeOut ) );
-    	User::LeaveIfError( iPositioner.SetUpdateOptions( iUpdateOptions ) );
+    	Cancel();
+    	LOG("CPositionInfo::RunL() - First Time");
+    	iUpdateOptions.SetUpdateInterval( TTimeIntervalMicroSeconds (iUpdateInterval) );  
+    	iUpdateOptions.SetUpdateTimeOut( TTimeIntervalMicroSeconds(KUpdateTimeOut ) );
+        if ( iTrailCaptureSetting == RLocationTrail::ECaptureAll ) 
+        	{
+        	User::LeaveIfError( iPositioner.SetUpdateOptions( iUpdateOptions ) );        	
+        	iPositioner.NotifyPositionUpdate( iPositionInfo, iStatus );
+        	}
+    	SetActive();
     	iFirstInterval = EFalse;
     	}
     }    
@@ -180,7 +195,8 @@
 // 
 void CPositionInfo::DoCancel()
     {
-    if ( !IsActive() )    
+    LOG( "CPositionInfo::DoCancel()" );
+    if ( IsActive() )    
         {
         iPositioner.CancelRequest( EPositionerNotifyPositionUpdate );
         }
--- a/locationmanager/locationtrail/src/locationremappingao.cpp	Fri Mar 12 15:44:28 2010 +0200
+++ b/locationmanager/locationtrail/src/locationremappingao.cpp	Mon Mar 15 12:42:24 2010 +0200
@@ -149,8 +149,7 @@
 	// clear all "old" location id's from remap items
 	if( removeLocations.Count() < 0 )
 		{
-		index = iRemapItems.Count();
-		for( TInt i = 0; i < index; i++ )
+		for( TInt i = iRemapItems.Count() - 1; i >=0; i-- )
 			{
 			TInt err = removeLocations.Find( iRemapItems[i].iLocationId );
 			if ( err != KErrNotFound )
--- a/locationmanager/server/inc/clocationmanagerserver.h	Fri Mar 12 15:44:28 2010 +0200
+++ b/locationmanager/server/inc/clocationmanagerserver.h	Mon Mar 15 12:42:24 2010 +0200
@@ -310,6 +310,18 @@
      */
     void GPSSignalQualityChanged( const TPositionSatelliteInfo& aSatelliteInfo ) __SOFTFP;
     
+    /**
+     * Callback method to notify observer that during waiting for positioning stop timeout remap is done.
+     */
+    void RemapedCompleted();
+    
+    /**
+     * Returns if in ETrialStopping state server waits for positioning stop timeout
+     * @returns <code>ETrue</code> if server is waiting for positioning stop timeout
+     *          <code>EFalse</code>, otherwise.
+     */
+    TBool WaitForPositioningStopTimeout();
+    
 public: // from MMdeObjectObserver
 	/**
 	 * Called to notify the observer that new objects has been
@@ -466,7 +478,12 @@
     TInt iLocManStopRemapDelay;
     
     RLocationTrail::TTrailCaptureSetting iCaptureSetting;
-    TBool iRemoveLocation;    
+    TBool iRemoveLocation;   
+    
+    /**
+     * A flag for state of waiting for position stop timeout.
+     */
+    TBool iWaitForPositioningStopTimeout;
     };
 
 
--- a/locationmanager/server/src/clocationmanagerserver.cpp	Fri Mar 12 15:44:28 2010 +0200
+++ b/locationmanager/server/src/clocationmanagerserver.cpp	Mon Mar 15 12:42:24 2010 +0200
@@ -100,7 +100,8 @@
                      iLocManStopDelay( 0 ),
                      iLocManStopRemapDelay( 0 ),
                      iCaptureSetting( RLocationTrail::EOff ),
-                     iRemoveLocation( EFalse )
+                     iRemoveLocation( EFalse ),
+                     iWaitForPositioningStopTimeout ( EFalse )
     {
     }
 
@@ -307,6 +308,8 @@
 void CLocationManagerServer::StartGPSPositioningL( RLocationTrail::TTrailCaptureSetting aCaptureSetting )
     {
     LOG( "CLocationManagerServer::StartGPSPositioningL" );
+    iWaitForPositioningStopTimeout = EFalse;
+    
     if ( aCaptureSetting == RLocationTrail::EOff )
     	{
     	return;
@@ -338,6 +341,7 @@
     {
     LOG( "CLocationManagerServer::StopGPSPositioningL()" );
     iCaptureSetting = RLocationTrail::EOff;
+    iWaitForPositioningStopTimeout = EFalse;
     
     RLocationTrail::TTrailState state;
     GetLocationTrailState( state );
@@ -345,7 +349,7 @@
     
     if( state != RLocationTrail::ETrailStopped && state != RLocationTrail::ETrailStopping )
         {
-        TRAPD( error, iTimer = CPeriodic::NewL( CActive::EPriorityHigh ) );
+        TRAPD( error, iTimer = CPeriodic::NewL( CActive::EPriorityUserInput ) );
         
         if ( error != KErrNone )
             {
@@ -369,8 +373,9 @@
 //
 void CLocationManagerServer::StopRecording()
 	{
-    LOG( "CLocationManagerServer::StopRecording()" );
-	iLocationRecord->Stop();
+    LOG( "CLocationManagerServer::StopRecording()" );    
+    iWaitForPositioningStopTimeout = EFalse;
+    iLocationRecord->Stop();		
 	delete iTimer;
 	iTimer = NULL;
 	}
@@ -402,6 +407,7 @@
     if ( self->iLocationRecord->RemappingNeeded() )
         {     
         self->iTimer->Start( self->iLocManStopRemapDelay * 1000000, 0, TCallBack( PositioningStopTimeout, self ) );
+        self->iWaitForPositioningStopTimeout = ETrue;
         }
     else
         {        
@@ -773,8 +779,7 @@
     if( iTargetObjectIds.Count() <= 0 )
     	{
     	TInt err = 0;
-	    const TInt count = aTargets.Count();
-	    for( TInt i = 0 ; i < count ; i++ )
+	    for( TInt i = aTargets.Count() - 1; i >=0; i-- )
 	    	{
 	    	TRAP( err, iMdeSession->CheckObjectL( obj, aTargets[i], &namespaceDef ) );
 	    	if ( err == KErrNone )
@@ -881,8 +886,7 @@
     CMdERelationDef& containsRelDef = aQuery.NamespaceDef().GetRelationDefL( 
     		Relations::KContainsLocation );
     
-    const TInt count = iTargetObjectIds.Count();
-    for( TInt i=0;i<count;i++ )
+    for( TInt i = iTargetObjectIds.Count() - 1; i >=0; i-- )
     	{
         CMdERelation* relationObject = iMdeSession->NewRelationLC( containsRelDef, iTargetObjectIds[i],
         		rightId, 0 );
@@ -891,6 +895,7 @@
         
         CleanupStack::PopAndDestroy( relationObject );
     	}
+    
     CleanupStack::PopAndDestroy( sourceLocation );
     
     for ( TInt i = iCopyReqs.Count() - 1; i >= 0; --i  )
@@ -967,9 +972,9 @@
 		    targetUris.ReserveL( uriCount );
 
 		    // deserialize URIs
-		    for( TInt i = 0; i < uriCount; i++ )
+		    for( TInt i = uriCount- 1; i >=0; i-- )
 		    	{
-		    	targetUris.Append( uriBuffer->ReceivePtr16L() );
+		    	targetUris.AppendL( uriBuffer->ReceivePtr16L() );
 		    	}
 		    
 	        LOG1("CLocationManagerSession::CopyLocationDataByUriL ID count:%d", targetUris.Count());
@@ -1271,4 +1276,17 @@
 	{
 	iTrackLog->AddGpxObserver( aObserver );
 	}
+
+void CLocationManagerServer::RemapedCompleted()
+    {
+    LOG( "CLocationManagerServer::RemapedCompleted()" );
+    StopRecording();
+    }
+
+TBool CLocationManagerServer::WaitForPositioningStopTimeout()
+    {
+    LOG( "CLocationManagerServer::WaitForPositioningStopTimeout()" );
+    return iWaitForPositioningStopTimeout;
+    }
+
 // End of file 
--- a/mds_plat/metadata_engine_api/inc/mdeobjectdef.h	Fri Mar 12 15:44:28 2010 +0200
+++ b/mds_plat/metadata_engine_api/inc/mdeobjectdef.h	Mon Mar 15 12:42:24 2010 +0200
@@ -96,7 +96,7 @@
 	 */
 	virtual ~CMdEObjectDef();
 
-	TDefId Id() const;	
+	IMPORT_C TDefId Id() const;	
 	
 	/**
 	 * Returns the property definition with the specified id
--- a/mds_plat/metadata_engine_api/inc/mdesession.h	Fri Mar 12 15:44:28 2010 +0200
+++ b/mds_plat/metadata_engine_api/inc/mdesession.h	Mon Mar 15 12:42:24 2010 +0200
@@ -222,6 +222,27 @@
 						TObserverNotificationType aType,
 						const RArray<TItemId>& aObjectIdArray) = 0;
     };
+
+class MMdEObjectObserverWithUri
+    {
+public:
+
+    /**
+     * Called to notify the observer that new objects has been
+     * added/modified/removed in the metadata engine database.
+     * 
+     * @param aSession session
+     * @param aType defines if object was added/modified/remove
+     * @param aObjectIdArray IDs of added object
+     * @param aUriArray Uris of added object
+     * @see CMdESession::AddObjectObserverL
+     * @see CMdELogicCondition
+     */
+    virtual void HandleUriObjectNotification(CMdESession& aSession, 
+                        TObserverNotificationType aType,
+                        const RArray<TItemId>& aObjectIdArray,
+                        const RPointerArray<HBufC>& aObjectUriArray) = 0;
+    };
     
 /**
  * Observer interface for modifications of the objects in the metadata engine 
@@ -1712,6 +1733,45 @@
 	virtual void SetObjectToPresentByGuidL( 
 			const TInt64& aGuidHigh, const TInt64& aGuidLow ) = 0;
 	
+    /**
+      * Adds a new object observer to the session. No duplicate observers are 
+      * allowed.
+      *
+      * The following restrictions are placed on the condition nodes:
+      * - Only CMdEObjectCondition and CMdEPropertyCondition nodes can be
+      *   used. CMdERangePropertyConditions are not allowed.
+      * - No nested logic conditions are allowed.
+      * 
+      * Be adviced, this version with the URI in the callback is much less
+      * efficient than using version without the URI
+      *
+      * @param aObserver   Observer.
+      * @param aCondition  Condition that the objects, about which the observer
+      *                    wants to receive notifications, must fulfill or NULL,
+      *                    to receive notifications of all objects.
+      *                    Ownership of the condition is transferred to the
+      *                    session.
+      * @param aNotificationType what event type (add, modify, remove) should
+      *                          be notified to client
+      * @param aNamespaceDef specified namespace (if namespace is NULL, the 
+      *                      default namespace is used)
+      * @param aUriRequired determines if uri is required in the callback
+      * 
+      * @leave KErrAlreadyExists if the same observer has already been added
+      */
+     virtual void AddObjectObserverWithUriL( MMdEObjectObserverWithUri& aObserver,
+             CMdELogicCondition* aCondition = NULL, 
+             TUint32 aNotificationType = ENotifyAdd | ENotifyModify | ENotifyRemove,
+             CMdENamespaceDef* aNamespaceDef = NULL ) = 0;
+
+     /**
+      * Removes the specified object observer from the session.
+      *
+      * @param aObserver  observer
+      */
+     virtual void RemoveObjectObserverWithUriL( MMdEObjectObserverWithUri& aObserver, 
+                             CMdENamespaceDef* aNamespaceDef = NULL ) = 0;
+     
 protected:
 
 	/* Constructors. */
--- a/metadataengine/client/group/mdeclient.mmp	Fri Mar 12 15:44:28 2010 +0200
+++ b/metadataengine/client/group/mdeclient.mmp	Mon Mar 15 12:42:24 2010 +0200
@@ -85,5 +85,3 @@
 
 DEBUGLIBRARY    flogger.lib
 
-OPTION ARMCC -O2 -OTime
-
--- a/metadataengine/client/inc/mdenotifierao.h	Fri Mar 12 15:44:28 2010 +0200
+++ b/metadataengine/client/inc/mdenotifierao.h	Mon Mar 15 12:42:24 2010 +0200
@@ -131,6 +131,7 @@
         void DoNotifyObserver();
 		
 		void DecodeIdBufferL();
+		void DecodeDataBufferL();
 		void DecodeRelationItemBufferL();
 
     private: // Data
@@ -156,6 +157,8 @@
         CMdCSerializationBuffer* iDataBuffer;
 
 		RArray<TItemId> iIdArray;
+		
+		RPointerArray<HBufC> iUriArray;
 
 		RArray<TMdERelation> iRelationItemArray;
     };
--- a/metadataengine/client/inc/mdesessionimpl.h	Fri Mar 12 15:44:28 2010 +0200
+++ b/metadataengine/client/inc/mdesessionimpl.h	Mon Mar 15 12:42:24 2010 +0200
@@ -517,6 +517,15 @@
 		 */
 		void NotifyError(TInt aError);
 
+        /* From MdESession. */
+        void AddObjectObserverWithUriL( MMdEObjectObserverWithUri& aObserver,
+                                CMdELogicCondition* aCondition,
+                                TUint32 aNotificationType,
+                                CMdENamespaceDef* aNamespaceDef );
+        
+        /* From MdESession. */
+        void RemoveObjectObserverWithUriL( MMdEObjectObserverWithUri& aObserver, 
+                                CMdENamespaceDef* aNamespaceDef );
     protected:
 
         /*
--- a/metadataengine/client/src/mdeharvestersession.cpp	Fri Mar 12 15:44:28 2010 +0200
+++ b/metadataengine/client/src/mdeharvestersession.cpp	Mon Mar 15 12:42:24 2010 +0200
@@ -139,7 +139,7 @@
 	TInt urisSize = CMdCSerializationBuffer::KRequiredSizeForTUint32;
 
 	WRITELOG( "CMdEHarvesterSession::SetFilesToPresentL -- Loop urisSize" );
-	for( TInt i = 0; i < fileCount; i++ )
+	for( TInt i = fileCount - 1; i >=0; i-- )
 		{
 		urisSize += CMdCSerializationBuffer::RequiredSize( aUris[i] );
 		}
@@ -298,9 +298,7 @@
 EXPORT_C void CMdEHarvesterSession::AutoLockL( 
 		RPointerArray<CMdEObject>& aObjects )
 	{
-	const TInt objectCount = aObjects.Count();
-	
-	for( TInt i = 0; i < objectCount; i++ )
+	for( TInt i = aObjects.Count() - 1; i >=0; i-- )
 		{
 		aObjects[i]->AutoLockL();
 		}
--- a/metadataengine/client/src/mdelogiccondition.cpp	Fri Mar 12 15:44:28 2010 +0200
+++ b/metadataengine/client/src/mdelogiccondition.cpp	Mon Mar 15 12:42:24 2010 +0200
@@ -111,10 +111,8 @@
     // Base class locking.
     CMdECondition::SetLocked(aLocked);    
     
-    const TInt count = iChildren.Count();
-    
     // Lock children as well.
-    for(TInt i = 0; i < count; ++i)
+    for( TInt i = iChildren.Count()- 1; i >=0; i-- )
         {
         iChildren[i]->SetLocked(aLocked);
         }
@@ -122,10 +120,8 @@
 
 TUint32 CMdELogicCondition::InternalQueryOptimizationFlags(TUint32& aFlags)
 	{
-	const TInt count = iChildren.Count();
-	
 	// get flag from childrens
-	for( TInt i = 0 ; i < count; i++)
+	for( TInt i = iChildren.Count() - 1; i >=0; i-- )
 		{
 		iOptimizationFlags |= iChildren[i]->InternalQueryOptimizationFlags(aFlags);
 		}
@@ -144,7 +140,7 @@
 	bufferSize += count * CMdCSerializationBuffer::KRequiredSizeForTUint32;
 
 	// Required size for childrens
-	for( TInt i = 0 ; i < count; i++)
+	for( TInt i = count - 1; i >=0; i-- )
 		{
 		bufferSize += iChildren[i]->RequiredBufferSize();
 		}
@@ -338,8 +334,8 @@
     {
     AssertNotLocked();
 
-    CMdETextPropertyCondition* condition 
-        = CMdETextPropertyCondition::NewLC(aPropertyDef, aCompareMethod, aText);
+    CMdETextPropertyCondition* condition = CMdETextPropertyCondition::NewLC( aPropertyDef, 
+                                                                                                                      aCompareMethod, aText );
     AddL(condition);
     CleanupStack::Pop(condition);
     return *condition;
--- a/metadataengine/client/src/mdenotifierao.cpp	Fri Mar 12 15:44:28 2010 +0200
+++ b/metadataengine/client/src/mdenotifierao.cpp	Mon Mar 15 12:42:24 2010 +0200
@@ -165,8 +165,7 @@
 	        iSession.DoListen( Id(), &iResultSize, iStatus );  // continue listening for events
 	        SetActive();
 	        }
-	    else if ( status & ( /*ERelationItemNotifyAdd | ERelationItemNotifyModify
-	                         |*/ ERelationItemNotifyRemove ) ) // a relation was removed
+	    else if ( status & ( ERelationItemNotifyRemove ) ) // a relation was removed
 	    	{
 	    	if( !iDataBuffer )
 	    		{
@@ -198,6 +197,33 @@
 	        iSession.DoListen( Id(), &iResultSize, iStatus ); // continue listening for events
 	        SetActive();
 	    	}
+	    else if ( status & ( EObjectNotifyAddWithUri | EObjectNotifyModifyWithUri
+	                           | EObjectNotifyRemoveWithUri ) )
+	        {
+	        if( !iDataBuffer )
+	            {
+	            iDataBuffer = CMdCSerializationBuffer::NewL( iResultSize() );
+	            }
+	        else if( iDataBuffer->Buffer().MaxSize() < iResultSize() )
+	            {
+	            delete iDataBuffer;
+	            iDataBuffer = NULL;
+	            iDataBuffer = CMdCSerializationBuffer::NewL( iResultSize() );
+	            }
+	        
+	        if( iResultSize() )
+	            {
+	            iSession.DoGetDataL( *iDataBuffer, Id() ); // reads data to the buffer
+	            DecodeDataBufferL(); // decodes ids and uri from the data buffer 
+	            
+	            delete iDataBuffer;
+	            iDataBuffer = NULL;
+	            
+	            DoNotifyObserver(); // notifies the observer about the event
+	            }
+	        iSession.DoListen( Id(), &iResultSize, iStatus );  // continue listening for events
+	        SetActive();
+	        }
     	}
     else
         {
@@ -327,7 +353,32 @@
             obs->HandleSchemaModified();
         	break;
         	}
-
+        	
+        case EObjectNotifyAddWithUri:
+            {
+            MMdEObjectObserverWithUri* obs = static_cast<MMdEObjectObserverWithUri*>( iObserver );
+            obs->HandleUriObjectNotification( iSessionImpl, ENotifyAdd, iIdArray, iUriArray );
+            iUriArray.ResetAndDestroy();
+            iUriArray.Compress();
+            break;
+            }
+        case EObjectNotifyModifyWithUri:
+            {
+            MMdEObjectObserverWithUri* obs = static_cast<MMdEObjectObserverWithUri*>( iObserver );
+            obs->HandleUriObjectNotification( iSessionImpl, ENotifyModify, iIdArray, iUriArray );
+            iUriArray.ResetAndDestroy();
+            iUriArray.Compress();
+            break;
+            }
+        case EObjectNotifyRemoveWithUri:
+            {
+            MMdEObjectObserverWithUri* obs = static_cast<MMdEObjectObserverWithUri*>( iObserver );
+            obs->HandleUriObjectNotification( iSessionImpl, ENotifyRemove, iIdArray, iUriArray );
+            iUriArray.ResetAndDestroy();
+            iUriArray.Compress();
+            break;
+            }    	
+        	
         default:
         	// no observer to call - this should be skipped on server side!
         	break;
@@ -356,6 +407,42 @@
 		}
 	}
 
+void CMdENotifierAO::DecodeDataBufferL()
+    {    
+    iIdArray.Reset();
+    iUriArray.ResetAndDestroy();
+    
+    iDataBuffer->PositionL( KNoOffset );
+    
+    const TMdCItemIds& itemIds = TMdCItemIds::GetFromBufferL( *iDataBuffer );
+    __ASSERT_DEBUG( iNamespaceDefId == itemIds.iNamespaceDefId, User::Panic( _L("Incorrect namespaceDef from returned items!"), KErrCorrupt ) );
+    
+    // Get IDs
+    iDataBuffer->PositionL( itemIds.iObjectIds.iPtr.iOffset );
+	iIdArray.ReserveL( itemIds.iObjectIds.iPtr.iCount );
+    for( TUint32 i = 0; i < itemIds.iObjectIds.iPtr.iCount; ++i )
+        {
+        TItemId id;
+        iDataBuffer->ReceiveL( id );
+        iIdArray.AppendL( id );
+        }
+    
+    // Get uri count
+    TUint32 uriCount ( 0 );
+    iDataBuffer->ReceiveL( uriCount );
+    
+    HBufC* uri = NULL;
+    
+    for( TInt i( 0 ); i < uriCount; i++ )
+        {        
+        //Get uri
+        uri = iDataBuffer->ReceiveDes16L();
+        CleanupStack::PushL( uri );
+        iUriArray.AppendL( uri );
+        CleanupStack::Pop( uri );
+        }
+    }
+
 void CMdENotifierAO::DecodeRelationItemBufferL()
 	{
     iRelationItemArray.Reset();
@@ -376,3 +463,4 @@
     		}
     	}
 	}
+
--- a/metadataengine/client/src/mdeobjectcondition.cpp	Fri Mar 12 15:44:28 2010 +0200
+++ b/metadataengine/client/src/mdeobjectcondition.cpp	Mon Mar 15 12:42:24 2010 +0200
@@ -128,7 +128,7 @@
 	    
 		for( TInt i = 0; i < objectIdCount; i++ )
 			{
-			iObjectIds->Append( (*aObjectIds)[i] );
+			iObjectIds->AppendL( (*aObjectIds)[i] );
 			}
 		}
 	else if ( aRange )
--- a/metadataengine/client/src/mdeobjectdef.cpp	Fri Mar 12 15:44:28 2010 +0200
+++ b/metadataengine/client/src/mdeobjectdef.cpp	Mon Mar 15 12:42:24 2010 +0200
@@ -174,7 +174,7 @@
             break;
             }
         
-        TInt compare( aId - iPropertyDefs[mid]->Id() );
+        const TInt compare( aId - iPropertyDefs[mid]->Id() );
         if( compare == 0 )
             {
             return iPropertyDefs[mid];
--- a/metadataengine/client/src/mdequery.cpp	Fri Mar 12 15:44:28 2010 +0200
+++ b/metadataengine/client/src/mdequery.cpp	Mon Mar 15 12:42:24 2010 +0200
@@ -47,10 +47,8 @@
     // This will destroy the entire conditions tree.
    	delete iConditions;
 
-   	const TInt count = iResults.Count();
-   	
     // Destroy all result items this query instance owns.
-    for(TInt i = 0; i < count; ++i)
+   	for( TInt i = iResults.Count() - 1; i >=0; i-- )
         {
         if(iResults[i].iOwned)
             {
@@ -149,11 +147,9 @@
         User::Leave(KErrNotReady);
         }
     
-    const TInt count = iResults.Count();
-    
 	// clear old results
 	// Destroy all result items this query instance owns.
-    for(TInt i = 0; i < count; ++i)
+    for( TInt i = iResults.Count() - 1; i >=0; i-- )
         {
         if(iResults[i].iOwned)
             {
--- a/metadataengine/client/src/mdequerycriteriaserialization.cpp	Fri Mar 12 15:44:28 2010 +0200
+++ b/metadataengine/client/src/mdequerycriteriaserialization.cpp	Mon Mar 15 12:42:24 2010 +0200
@@ -170,7 +170,7 @@
 			CMdCSerializationBuffer::KRequiredSizeForTUint32;
 
 	// Required size for order rules
-	for( TInt i = 0; i < orderRuleCount; i++ )
+	for( TInt i = orderRuleCount - 1; i >=0; i-- )
 		{
 		criteriaBufferSize += aOrderRules[i].RequiredBufferSize();
 		}
--- a/metadataengine/client/src/mdesessionimpl.cpp	Fri Mar 12 15:44:28 2010 +0200
+++ b/metadataengine/client/src/mdesessionimpl.cpp	Mon Mar 15 12:42:24 2010 +0200
@@ -2678,8 +2678,7 @@
 TInt CMdESessionImpl::FindNotifier( TUint32 aNotifyType, TAny* aObserver, 
 									CMdENamespaceDef& aNamespaceDef )
     {
-    const TInt notifiersCount = iNotifiers.Count();
-    for( TInt i = 0; i < notifiersCount; ++i )
+    for( TInt i = iNotifiers.Count() - 1; i >=0; i-- )
         {
         if ( iNotifiers[i]->Match( aNotifyType, aObserver, aNamespaceDef ) )
         	{
@@ -2944,3 +2943,93 @@
     	return &GetDefaultNamespaceDefL();
     	}
 	}
+	
+void CMdESessionImpl::AddObjectObserverWithUriL( MMdEObjectObserverWithUri& aObserver,
+                                          CMdELogicCondition* aCondition, 
+                                          TUint32 aNotificationType,
+                                          CMdENamespaceDef* aNamespaceDef )
+    {
+    CleanupStack::PushL( aCondition );
+    
+    // if condition is given, check that it is correct type
+    if( aCondition && ( EConditionTypeLogic != aCondition->Type() ) )
+        {
+        User::Leave( KErrArgument );
+        }
+
+    // if namespace is not given get default namespace definition
+    CMdENamespaceDef* namespaceDef = NULL;
+    if ( !aNamespaceDef )
+        {
+        namespaceDef = &GetDefaultNamespaceDefL();
+        }
+    else
+        {
+        namespaceDef = aNamespaceDef;
+        }
+
+    TUint32 type = 0;
+    if ( aNotificationType & ENotifyAdd )
+        {
+        type |= EObjectNotifyAddWithUri;
+        }
+    if ( aNotificationType & ENotifyModify )
+        {
+        type |= EObjectNotifyModifyWithUri;
+        }
+    if ( aNotificationType & ENotifyRemove )
+        {
+        type |= EObjectNotifyRemoveWithUri;
+        }
+        
+    TInt err = FindNotifier( type, &aObserver, *namespaceDef );
+    
+    if ( err != KErrNotFound )
+        {
+        if ( err >= 0 )
+            {
+            err = KErrAlreadyExists;
+            }
+        User::LeaveIfError( err );
+        }
+
+    CMdENotifierAO* notifier = CMdENotifierAO::NewLC( *this, iSession );
+    notifier->RegisterL( type, &aObserver, aCondition, *namespaceDef );
+
+    CleanupStack::Pop( notifier );
+    iNotifiers.Append( notifier );
+    
+    CleanupStack::PopAndDestroy( aCondition );
+    }
+
+void CMdESessionImpl::RemoveObjectObserverWithUriL( 
+        MMdEObjectObserverWithUri& aObserver, CMdENamespaceDef* aNamespaceDef )
+    {
+    // if namespace is not given get default namespace definition
+    CMdENamespaceDef* namespaceDef = NULL;
+    if ( !aNamespaceDef )
+        {
+        namespaceDef = &GetDefaultNamespaceDefL();
+        }
+    else
+        {
+        namespaceDef = aNamespaceDef;
+        }
+
+    const TInt index = FindNotifier( 
+            EObjectNotifyAddWithUri | EObjectNotifyModifyWithUri | EObjectNotifyRemoveWithUri,
+            &aObserver, *namespaceDef );
+    if ( index != KErrNotFound )
+        {
+        iNotifiers[index]->Cancel();
+        delete iNotifiers[index];
+        iNotifiers[index] = NULL;
+        iNotifiers.Remove( index );
+        iNotifiers.Compress();
+        }
+    else
+        {
+        User::Leave( KErrNotFound );
+        }
+    }
+
--- a/metadataengine/common/src/mdcserializationbuffer.cpp	Fri Mar 12 15:44:28 2010 +0200
+++ b/metadataengine/common/src/mdcserializationbuffer.cpp	Mon Mar 15 12:42:24 2010 +0200
@@ -992,7 +992,7 @@
 #ifdef _DEBUG
     // for testing initilize to 0x99
     TUint8* ptr = (TUint8*)(iBuffer.Ptr());
-    for(TInt32 i = 0; i < aSize; i++)
+    for( TInt32 i = aSize - 1; i >=0; i-- )
     	{
     	ptr[i] = 0x99;
     	}
--- a/metadataengine/server/group/mdsserver.mmp	Fri Mar 12 15:44:28 2010 +0200
+++ b/metadataengine/server/group/mdsserver.mmp	Mon Mar 15 12:42:24 2010 +0200
@@ -99,3 +99,5 @@
 
 OPTION ARMCC -O3 -OTime
 
+EPOCPROCESSPRIORITY background
+
--- a/metadataengine/server/inc/mdsmanipulationengine.h	Fri Mar 12 15:44:28 2010 +0200
+++ b/metadataengine/server/inc/mdsmanipulationengine.h	Mon Mar 15 12:42:24 2010 +0200
@@ -292,6 +292,14 @@
 		TInt GetPendingL( TDefId aObjectDefId, TInt aBufferSize, 
 				RArray<TItemId>& aObjectIds );
 		
+	      /**
+	         * Fetches object uris based on id array
+	         * @param aObjectIds list of object ids.
+	         * @param aObjectUris array for object uris.
+	         */
+		void GetObjectUrisByIdsL( const RArray<TItemId>& aObjectIds, 
+		                                         RPointerArray<HBufC>& aUriArray );
+		
 	protected:
 		TBool StartGarbageCollectionL();
 
--- a/metadataengine/server/inc/mdsnamespacedef.h	Fri Mar 12 15:44:28 2010 +0200
+++ b/metadataengine/server/inc/mdsnamespacedef.h	Mon Mar 15 12:42:24 2010 +0200
@@ -213,6 +213,10 @@
 	void MergeRelationsL( CMdsNamespaceDef* aNamespace, const TBool& aDryRun );
 	void MergeEventsL( CMdsNamespaceDef* aNamespace, const TBool& aDryRun );
 
+    static TInt CompareObjectDefId(const CMdsObjectDef& aFirst, const CMdsObjectDef& aSecond);
+    static TInt CompareEventDefId(const CMdsEventDef& aFirst, const CMdsEventDef& aSecond);
+    static TInt CompareRelationDefId(const CMdsRelationDef& aFirst, const CMdsRelationDef& aSecond);
+	
 private:
 enum TNamespaceDefFlags
 	{
--- a/metadataengine/server/inc/mdsnotifier.h	Fri Mar 12 15:44:28 2010 +0200
+++ b/metadataengine/server/inc/mdsnotifier.h	Mon Mar 15 12:42:24 2010 +0200
@@ -27,6 +27,7 @@
 class CMdSNotifyComparator;
 class CMdSSchema;
 class CMdCSerializationBuffer;
+class CMdSManipulationEngine;
 
 /**
 * A class that contains notification profiles for clients.
@@ -140,10 +141,12 @@
                 * Triggers the notifier causing the observer to be
                 * notifier with the given code.
                 * @param aCompleteCode either added/removed/modified
-                * @param aItem the target of the event
+                * @param aIdArray ids of matching results
+                * @param aUriArray uris of matching results 
                 */
                 void TriggerL( TUint32 aCompleteCode,
-                    const RArray<TItemId>& aIdArray );
+                    const RArray<TItemId>& aIdArray,
+                    RPointerArray<HBufC>& aUriArray );
 
                 /**
                  * Triggers the notifier causing the observer to be
@@ -166,7 +169,9 @@
 				 *	The entry has currently no message active, 
 				 *	wait until one is available.
 				 */
-                void CacheL(TUint32 aCompleteCode, const RArray<TItemId>& aIdArray );
+                void CacheL(TUint32 aCompleteCode, 
+                                    const RArray<TItemId>& aIdArray,
+                                    const RPointerArray<HBufC>& aUriArray);
 
                 /**
 				 *	The entry has currently no message active, 
@@ -195,6 +200,15 @@
 				 */
 				CMdCSerializationBuffer* CopyToBufferL(
 						const RArray<TItemId>& aIdArray);
+				
+                /**
+                 * Copy all URIs from the array in to the buffer
+                 * 
+                 * @param aUriArray URI array
+                 * @return new buffer
+                 */
+                CMdCSerializationBuffer* CopyToBufferL(const RArray<TItemId>& aIdArray,
+                                                                              const RPointerArray<HBufC>& aUriArray);
 
 				/**
 				 * Copy matched relation IDs to a buffer
@@ -290,8 +304,10 @@
        /**
         * notifiers that items has been modified
         * @param aObjectIds object IDs
+        * @param aMEngine pointer to manipulator class for utility functions
         */
-        void NotifyModifiedL(const RArray<TItemId>& aObjectIds);
+        void NotifyModifiedL( const RArray<TItemId>& aObjectIds,
+                                           CMdSManipulationEngine* aMEngine );
 
 	   /**
         * notifiers that objects has been set to present or not present state
@@ -320,15 +336,21 @@
 		 * Can be only used for default namespace.
 		 * 
 		 * @param aItemIdArray modified item IDs
+		 * @param aMEngine pointer to manipulator class for utility functions
 		 */
-		void NotifyRemovedL(const RArray<TItemId>& aItemIdArray);
+		void NotifyRemovedL( const RArray<TItemId>& aItemIdArray,
+		                                    CMdSManipulationEngine* aMEngine );
 		
 		/**
         * notifiers that items has been removed
         * @param aSerializedItemIds serialized item IDs
         * @param aItemIsConfidential are items confidential
+        * @param aRemovedItemUriArray uri array if uris are present
+        * @param aMEngine pointer to manipulator class for utility functions
         */
-        void NotifyRemovedL(CMdCSerializationBuffer& aSerializedItemIds, TBool aItemIsConfidential );
+        void NotifyRemovedL(CMdCSerializationBuffer& aSerializedItemIds, TBool aItemIsConfidential,
+                                           RPointerArray<HBufC>& aRemovedItemUriArray,
+                                           CMdSManipulationEngine* aMEngine );
 
 		void NotifySchemaAddedL();
 		
--- a/metadataengine/server/inc/mdsnotifycomparator.h	Fri Mar 12 15:44:28 2010 +0200
+++ b/metadataengine/server/inc/mdsnotifycomparator.h	Mon Mar 15 12:42:24 2010 +0200
@@ -60,6 +60,11 @@
         * @param aSerializedItems the items to compare
         * @param aSerializedItemIds the item IDs (successful and failed IDs)
         * @param aMatchingItemIdArray matching object IDs
+        * @param aAllItemsIdArray array to store the ids if all matched
+        * @param aMatchingItemUriArray matching object URIs
+        * @param aAllItemsUriArray array to store the uris if all matched
+        * @param aAllMatched to determine if there is no specific conditions to match
+        * @param aAllUrisFetched to determine if all uris have been previously fetched
         * 
         * @return If true at least some item matches.
         */
@@ -67,8 +72,14 @@
         		CMdCSerializationBuffer& aSerializedCondition,
         		CMdCSerializationBuffer& aSerializedItems,
 		    	CMdCSerializationBuffer& aSerializedItemIds,
-		    	RArray<TItemId>& aMatchingItemIdArray, 
-		    	TBool aAllowConfidential);
+		    	RArray<TItemId>& aMatchingItemIdArray,
+		    	RArray<TItemId>& aAllItemsIdArray,
+		    	RPointerArray<HBufC>& aMatchingItemUriArray, 
+		    	RPointerArray<HBufC>& aAllItemsUriArray,
+		    	TBool aAllowConfidential,
+		    	TBool uriNotify,
+		    	TBool& aAllMatched,
+		    	TBool& aAllUrisFetched);
 
 		/**
         * Matches object against the given condition. This variant matches only
--- a/metadataengine/server/inc/mdssqlobjectmanipulate.h	Fri Mar 12 15:44:28 2010 +0200
+++ b/metadataengine/server/inc/mdssqlobjectmanipulate.h	Mon Mar 15 12:42:24 2010 +0200
@@ -215,25 +215,32 @@
 		 * @param aBuffer id's to remove
 		 * @param aCount id's count
 		 * @param aIdArray result id's
-		 * @param aUserLevel not used - delete
-		 * @param aLockList list of locked objects
+         * @param aRelationIds result relation id's
+         * @param aEventIds result event id's
+         * @param aUrisRequired determines if uris are to be fetched
+         * @param aRemovedItemUriArray result uris
 		 */
 		void RemoveObjectsByIdL( CMdCSerializationBuffer& aBuffer, TInt aCount,
 				RArray<TItemId>& aIdArray, RArray<TItemId>& aRelationIds, 
-				RArray<TItemId>& aEventIds );
+				RArray<TItemId>& aEventIds,
+				TBool aUrisRequired, 
+				RPointerArray<HBufC>& aRemovedItemUriArray);
 
 		/**
 		 * Remove object using it's URI's
 		 *
 		 * @param aBuffer URI's to remove
 		 * @param aCount URI's count
-		 * @param aIdArray result id's
-		 * @param aUserLevel not used - delete
-		 * @param aLockList list of locked objects
-		 */
+		 * @param aIdArray result object id's
+         * @param aRelationIds result relation id's
+         * @param aEventIds result event id's
+         * @param aRemovedItemUriArray result uris
+         */
 		void RemoveObjectsByUriL( CMdCSerializationBuffer& aBuffer, TInt aCount,
 				RArray<TItemId>& aIdArray, RArray<TItemId>& aRelationIds, 
-				RArray<TItemId>& aEventIds );
+				RArray<TItemId>& aEventIds,
+				TBool aUrisRequired,
+				RPointerArray<HBufC>& aRemovedItemUriArray );
 
 		/**
 		 * search for object uri
@@ -244,6 +251,15 @@
 		 */
 		TItemId SearchObjectByUriL( const TDesC16& aUri, TUint32& aFlags );
 
+        /**
+         * search for object uri
+         *
+         * @param aId object id to search uri for
+         * @param aFlags return found object flags
+         * @return reference to object uri
+         */
+		HBufC*& SearchObjectUriByIdL( const TItemId aId, TUint32& aFlags );
+		
 		/**
 		 * update freetext (add and remove)
 		 */
@@ -529,7 +545,6 @@
         
         /**
          * common usage buffers (initial size = 1024)
-         * NOT THREAD SAFE!
          */
         RArray<TLockBuffer> iBuffers;
 
@@ -550,11 +565,13 @@
 
 	    CMdSObjectLockList& iLockList;
 	    
+	    // Last handled uri.
+	    HBufC* iUri;
+	
 	    TBuf<256> iLastAddedObjName;
 	    
 	private:
 		class RClauseBuffer
-					// NOT THREAD SAFE !!!!!
 			{
 			public:
 				RClauseBuffer(CMdSSqlObjectManipulate& aSOM, TInt aSize = 1024);
--- a/metadataengine/server/src/mdsfindsqlclause.cpp	Fri Mar 12 15:44:28 2010 +0200
+++ b/metadataengine/server/src/mdsfindsqlclause.cpp	Mon Mar 15 12:42:24 2010 +0200
@@ -266,7 +266,7 @@
 			{
 			TDefId objectDefId;
 			iSerializedBuffer->ReceiveL( objectDefId );			
-			iSourceObjectDefs->Append( objectDefId );
+			iSourceObjectDefs->AppendL( objectDefId );
 			}
 		}
 	else
--- a/metadataengine/server/src/mdsgetimeiao.cpp	Fri Mar 12 15:44:28 2010 +0200
+++ b/metadataengine/server/src/mdsgetimeiao.cpp	Mon Mar 15 12:42:24 2010 +0200
@@ -24,7 +24,7 @@
 CMdsGetImeiAO* CMdsGetImeiAO::NewL()
 	{
 	CMdsGetImeiAO *self = CMdsGetImeiAO::NewLC();
-	CleanupStack::Pop();
+	CleanupStack::Pop(); //self
 	return self;
 	}
 
--- a/metadataengine/server/src/mdsmanipulationengine.cpp	Fri Mar 12 15:44:28 2010 +0200
+++ b/metadataengine/server/src/mdsmanipulationengine.cpp	Mon Mar 15 12:42:24 2010 +0200
@@ -32,6 +32,9 @@
 #include "mdeinternalerror.h"
 #include "mdeerror.h"
 
+// for CleanupResetAndDestroyPushL
+#include <mmf/common/mmfcontrollerpluginresolver.h>
+
 __USES_LOGGER
 
 // ---------------------------------------------------------------------------
@@ -326,8 +329,12 @@
 	CleanupClosePushL( removedRelations );
 	RArray<TItemId> removedEvents;
 	CleanupClosePushL( removedEvents );
+	RPointerArray<HBufC> removedItemUriArray;
+	CleanupResetAndDestroyPushL( removedItemUriArray );
 
     CMdSSqLiteConnection& connection = MMdSDbConnectionPool::GetDefaultDBL();
+    
+    const TBool uriNotify = iNotifier.CheckForNotifier(EObjectNotifyRemoveWithUri);
 
     // Remove objects by id or URI.
     if (itemIds.iObjectIds.iPtr.iCount + itemIds.iObjectUris.iPtr.iCount > 0)
@@ -340,13 +347,19 @@
 			{
 			aBuffer.PositionL( itemIds.iObjectUris.iPtr.iOffset );
 			iManipulate->RemoveObjectsByUriL( aBuffer, itemIds.iObjectUris.iPtr.iCount,
-					idArray, removedRelations, removedEvents );
+					idArray, removedRelations, removedEvents, uriNotify, removedItemUriArray );
 			}
 		else
 			{
+		    // pause garbage collector so it does not remove the objects
+			// before uris are read
+		    if( iGarbageCollector && uriNotify )
+		        {
+		        iGarbageCollector->Pause();
+		        }
 			aBuffer.PositionL( itemIds.iObjectIds.iPtr.iOffset );
 			iManipulate->RemoveObjectsByIdL( aBuffer, itemIds.iObjectIds.iPtr.iCount,
-					idArray, removedRelations, removedEvents );
+					idArray, removedRelations, removedEvents, uriNotify, removedItemUriArray );
 			}
 
 	    transaction.CommitL();
@@ -445,13 +458,15 @@
 	aResultBuffer.PositionL( KNoOffset );
 	resultIds.SerializeL( aResultBuffer );
 
-	// notify about items removed
-	const TBool notify = iNotifier.CheckForNotifier(EObjectNotifyRemove|EEventNotifyRemove|ERelationNotifyRemove);
-	if (notify)
-		{
-		iNotifier.NotifyRemovedL( aResultBuffer, EFalse );
-		}
-
+	TBool notify = iNotifier.CheckForNotifier(EObjectNotifyRemove|EEventNotifyRemove|ERelationNotifyRemove);
+	
+	// notify about items removed 
+	if( uriNotify || notify )
+	    {
+	    iNotifier.NotifyRemovedL( aResultBuffer, EFalse, removedItemUriArray, this );
+		notify = ETrue;
+	    }
+	
 	// notify about additional items removed
 	const TInt KRemovedItemsCount = removedRelations.Count() + removedEvents.Count();
     if ( notify && KRemovedItemsCount > 0 )
@@ -505,7 +520,14 @@
 
 		buffer->PositionL( KNoOffset );
 		additResultIds.SerializeL( *buffer );
-		iNotifier.NotifyRemovedL( *buffer, EFalse );
+		const TBool notifyEnabled = iNotifier.CheckForNotifier(EEventNotifyRemove|ERelationNotifyRemove);
+		if (notifyEnabled)
+		    {
+	        RPointerArray<HBufC> nullArray; // For when uris are not available or needed
+	        CleanupResetAndDestroyPushL( nullArray );
+		    iNotifier.NotifyRemovedL( *buffer, EFalse, nullArray, this );
+		    CleanupStack::PopAndDestroy( &nullArray );
+		    }
 		CleanupStack::PopAndDestroy( buffer );
     	}
 
@@ -532,8 +554,8 @@
 		iGarbageCollector->Start( KGarbageCollectionDelay );
 		}
 
-	// removedEvents, removedRelations, idArray
-    CleanupStack::PopAndDestroy( 3, &idArray );
+	// removedItemUriArray, removedEvents, removedRelations, idArray
+    CleanupStack::PopAndDestroy( 4, &idArray );
     }
 
 void CMdSManipulationEngine::UpdateL( CMdCSerializationBuffer& aBuffer, 
@@ -611,6 +633,14 @@
 		resultIds.iRelationIds.iPtr.iOffset = aResultBuffer.Position();
 		resultIds.iRelationIds.iPtr.iCount = items.iRelations.iPtr.iCount;
 
+        RMdSTransaction transaction( connection );
+        CleanupClosePushL(transaction);
+        const TInt beginError( transaction.Error() );
+        if( beginError != KErrNone )
+            {
+            CleanupStack::PopAndDestroy( &transaction );
+            }
+		
 		for ( TInt i = 0; i < items.iRelations.iPtr.iCount; ++i )
 			{
 			aBuffer.PositionL( items.iRelations.iPtr.iOffset + i * sizeof(TMdCRelation) );
@@ -630,6 +660,11 @@
 					}
 				}
 			}
+        if( beginError == KErrNone )
+            {
+            transaction.CommitL();
+            CleanupStack::PopAndDestroy( &transaction );
+            }
 		}
 	else
 		{
@@ -879,7 +914,7 @@
 		
 		if( objectIds.Count() > 0 )
 			{
-			iNotifier.NotifyRemovedL( objectIds );
+			iNotifier.NotifyRemovedL( objectIds, this );
 			}
 		
 		CleanupStack::PopAndDestroy( &objectIds );
@@ -963,7 +998,7 @@
 
 	iManipulate->ChangePathL( aOldPath, aNewPath, objectIds );
 
-	iNotifier.NotifyModifiedL( objectIds );
+	iNotifier.NotifyModifiedL( objectIds, this );
 	
 	CleanupStack::PopAndDestroy( &objectIds );
 	
@@ -1059,3 +1094,17 @@
 	{
 	return iManipulate->GetPendingL( aObjectDefId, aBufferSize, aObjectIds );
 	}
+
+void CMdSManipulationEngine::GetObjectUrisByIdsL( const RArray<TItemId>& aObjectIds, 
+                                                                                   RPointerArray<HBufC>& aUriArray )
+    {
+    const TInt count( aObjectIds.Count() );
+    for( TInt i( 0 ); i < count; i++ )
+        {
+        TUint32 flags;
+        HBufC* uri = iManipulate->SearchObjectUriByIdL( aObjectIds[i], flags );
+        aUriArray.AppendL( uri );
+        uri = NULL;
+        }
+    }
+
--- a/metadataengine/server/src/mdsnamespacedef.cpp	Fri Mar 12 15:44:28 2010 +0200
+++ b/metadataengine/server/src/mdsnamespacedef.cpp	Mon Mar 15 12:42:24 2010 +0200
@@ -101,7 +101,6 @@
 	CMdsObjectDef* parent = GetObjectDef( aParentName );
 	if ( !parent )
 		{
-		/* testing */
 		// found namespace in default schema
 		if ( aDefaultSchema )
 			{
@@ -118,7 +117,7 @@
 			}
 		}
 	CMdsObjectDef* object = CMdsObjectDef::NewLC( aObjectName, parent );
-	iObjectDefs.AppendL( object );
+	User::LeaveIfError( iObjectDefs.InsertInOrderAllowRepeats(object, TLinearOrder<CMdsObjectDef>(CMdsNamespaceDef::CompareObjectDefId) ) );
 	CleanupStack::Pop( object );
 	return object;
 	}
@@ -135,8 +134,8 @@
 		}
 	CMdsObjectDef* object = CMdsObjectDef::NewLC( aName, parent );
 	object->SetFlags( (CMdsObjectDef::TObjectDefFlags)aFlags );
-	iObjectDefs.AppendL( object );
 	object->SetId(aId);
+	User::LeaveIfError( iObjectDefs.InsertInOrderAllowRepeats(object, TLinearOrder<CMdsObjectDef>(CMdsNamespaceDef::CompareObjectDefId) ) );
 	object->SetStoredInDB();
 	CleanupStack::Pop( object );
 	}
@@ -170,7 +169,7 @@
 		User::Leave( KErrAlreadyExists );
 		}
 	CMdsRelationDef* relation = CMdsRelationDef::NewLC( aRelationName );
-	iRelationDefs.AppendL( relation );
+	User::LeaveIfError( iRelationDefs.InsertInOrderAllowRepeats(relation, TLinearOrder<CMdsRelationDef>(CMdsNamespaceDef::CompareRelationDefId) ) );
 	CleanupStack::Pop( relation );
 	}
 
@@ -179,7 +178,7 @@
 	{
 	CMdsRelationDef* relation = CMdsRelationDef::NewLC( aRelationName );
 	relation->SetId(aId);
-	iRelationDefs.AppendL( relation );
+	User::LeaveIfError( iRelationDefs.InsertInOrderAllowRepeats(relation, TLinearOrder<CMdsRelationDef>(CMdsNamespaceDef::CompareRelationDefId) ) );
 	relation->SetStoredInDB();
 	CleanupStack::Pop( relation );
 	}
@@ -206,7 +205,7 @@
 		User::Leave( KErrAlreadyExists );
 		}
 	CMdsEventDef* event = CMdsEventDef::NewLC( aEventName, aPriority );
-	iEventDefs.AppendL( event );
+	User::LeaveIfError( iEventDefs.InsertInOrderAllowRepeats(event, TLinearOrder<CMdsEventDef>(CMdsNamespaceDef::CompareEventDefId) ) );
 	CleanupStack::Pop( event );
 	}
 
@@ -214,7 +213,7 @@
 	{
 	CMdsEventDef* event = CMdsEventDef::NewLC( aEventName, aPriority );
 	event->SetId(aId);
-	iEventDefs.AppendL( event );
+	User::LeaveIfError( iEventDefs.InsertInOrderAllowRepeats(event, TLinearOrder<CMdsEventDef>(CMdsNamespaceDef::CompareEventDefId) ) );
 	event->SetStoredInDB();
 	CleanupStack::Pop( event );
 	}
@@ -239,44 +238,80 @@
 		{
 		return iBaseObject;
 		}
-	
-	const TInt count = iObjectDefs.Count();
-	
-	for ( TInt i = 0; i < count; ++i )
-		{
-		if( iObjectDefs[i]->GetId() == aId )
-			{
-			return iObjectDefs[i];
-			}
-		}
+
+    TInt low( 0 );
+    TInt high( iObjectDefs.Count() );
+    
+    while( low < high )
+        {
+        TInt mid( (low+high)>>1 );
+        
+        const TInt compare( aId - iObjectDefs[mid]->GetId() );
+        if( compare == 0 )
+            {
+            return iObjectDefs[mid];
+            }
+        else if( compare > 0 )
+            {
+            low = mid + 1;
+            }
+        else
+            {
+            high = mid;
+            }
+        }   
 	return NULL;
 	}
 
 const CMdsEventDef* CMdsNamespaceDef::GetEventByIdL( TDefId aId ) const
 	{
-	const TInt count = iEventDefs.Count();
-	
-	for ( TInt i = 0; i < count; ++i )
-		{
-		if( iEventDefs[i]->GetId() == aId )
-			{
-			return iEventDefs[i];
-			}
-		}
+    TInt low( 0 );
+    TInt high( iEventDefs.Count() );
+    
+    while( low < high )
+        {
+        TInt mid( (low+high)>>1 );
+        
+        const TInt compare( aId - iEventDefs[mid]->GetId() );
+        if( compare == 0 )
+            {
+            return iEventDefs[mid];
+            }
+        else if( compare > 0 )
+            {
+            low = mid + 1;
+            }
+        else
+            {
+            high = mid;
+            }
+        }
 	return NULL;
 	}
 
 const CMdsRelationDef* CMdsNamespaceDef::GetRelationByIdL( TDefId aId ) const
 	{
-	const TInt count = iRelationDefs.Count();
-	
-	for ( TInt i = 0; i < count; ++i )
-		{
-		if( iRelationDefs[i]->GetId() == aId )
-			{
-			return iRelationDefs[i];
-			}
-		}
+    TInt low( 0 );
+    TInt high( iRelationDefs.Count() );
+    
+    while( low < high )
+        {
+        TInt mid( (low+high)>>1 );
+        
+        const TInt compare( aId - iRelationDefs[mid]->GetId() );
+        if( compare == 0 )
+            {
+            return iRelationDefs[mid];
+            }
+        else if( compare > 0 )
+            {
+            low = mid + 1;
+            }
+        else
+            {
+            high = mid;
+            }
+        }
 	return NULL;
 	}
 
@@ -312,6 +347,7 @@
 		{
 		iObjectDefs[i]->StoreToDBL( GetId() );
 		}
+	iObjectDefs.Sort( TLinearOrder<CMdsObjectDef>(CMdsNamespaceDef::CompareObjectDefId) );
 	
 	const TInt eventDefCount = iEventDefs.Count();
 	
@@ -320,6 +356,7 @@
 		{
 		iEventDefs[i]->StoreToDBL( GetId() );
 		}
+	iEventDefs.Sort( TLinearOrder<CMdsEventDef>(CMdsNamespaceDef::CompareEventDefId) );
 	
 	const TInt relationDefCount = iRelationDefs.Count();
 	
@@ -328,6 +365,7 @@
 		{
 		iRelationDefs[i]->StoreToDBL( GetId() );
 		}
+	iRelationDefs.Sort( TLinearOrder<CMdsRelationDef>(CMdsNamespaceDef::CompareRelationDefId) );
 
 	CleanupStack::PopAndDestroy( &rowData );
 	}
@@ -346,7 +384,8 @@
 			}
 		else if ( !aDryRun )
 			{
-			iObjectDefs.AppendL( aNamespace->iObjectDefs[i] );
+		    User::LeaveIfError( iObjectDefs.InsertInOrderAllowRepeats(aNamespace->iObjectDefs[i], 
+		                                  TLinearOrder<CMdsObjectDef>(CMdsNamespaceDef::CompareObjectDefId) ) );
 			aNamespace->iObjectDefs[i]->SetAllNotStoredInDB();
 			aNamespace->iObjectDefs[i] = NULL;
 			}
@@ -369,7 +408,8 @@
 			}
 		else if ( !aDryRun )
 			{
-			iRelationDefs.AppendL( aNamespace->iRelationDefs[i] );
+		    User::LeaveIfError( iRelationDefs.InsertInOrderAllowRepeats(aNamespace->iRelationDefs[i], 
+		                                        TLinearOrder<CMdsRelationDef>(CMdsNamespaceDef::CompareRelationDefId) ) );
 			aNamespace->iRelationDefs[i]->SetAllNotStoredInDB();
 			aNamespace->iRelationDefs[i] = NULL;
 			}
@@ -392,7 +432,7 @@
 			}
 		else if ( !aDryRun )
 			{
-			iEventDefs.AppendL( aNamespace->iEventDefs[i] );
+		    User::LeaveIfError( iEventDefs.InsertInOrderAllowRepeats(aNamespace->iEventDefs[i], TLinearOrder<CMdsEventDef>(CMdsNamespaceDef::CompareEventDefId) ) );
 			aNamespace->iEventDefs[i]->SetAllNotStoredInDB();
 			aNamespace->iEventDefs[i] = NULL;
 			}
@@ -480,6 +520,7 @@
 		{
 		iObjectDefs[i]->ImportFromDBL();
 		}
+	iObjectDefs.Sort( TLinearOrder<CMdsObjectDef>(CMdsNamespaceDef::CompareObjectDefId) );
 
 	// everything is ok, so set the flags
 	SetStoredInDB();
@@ -612,6 +653,21 @@
 	return NULL;
 	}
 
+TInt CMdsNamespaceDef::CompareObjectDefId(const CMdsObjectDef& aFirst, const CMdsObjectDef& aSecond)
+    {
+    return aFirst.GetId() - aSecond.GetId();
+    }
+
+TInt CMdsNamespaceDef::CompareEventDefId(const CMdsEventDef& aFirst, const CMdsEventDef& aSecond)
+    {
+    return aFirst.GetId() - aSecond.GetId();
+    }
+
+TInt CMdsNamespaceDef::CompareRelationDefId(const CMdsRelationDef& aFirst, const CMdsRelationDef& aSecond)
+    {
+    return aFirst.GetId() - aSecond.GetId();
+    }
+
 /**
  * Initialize static variables
  */
--- a/metadataengine/server/src/mdsnotifier.cpp	Fri Mar 12 15:44:28 2010 +0200
+++ b/metadataengine/server/src/mdsnotifier.cpp	Mon Mar 15 12:42:24 2010 +0200
@@ -22,8 +22,12 @@
 #include "mdsnotifycomparator.h"
 #include "mdslogger.h"
 #include "mdcserializationbuffer.h"
+#include "mdsmanipulationengine.h"
 #include "mdccommon.pan"
 
+// for CleanupResetAndDestroyPushL
+#include <mmf/common/mmfcontrollerpluginresolver.h>
+
 __USES_LOGGER
 
 // ------------------------------------------------
@@ -125,21 +129,34 @@
 //
 void CMdSNotifier::TEntry::TriggerL(
 	TUint32 aCompleteCode,
-    const RArray<TItemId>& aIdArray )
+    const RArray<TItemId>& aIdArray,
+    RPointerArray<HBufC>& aUriArray )
     {
     const TInt remoteSizeMsgSlot = iRemoteSizeMsgSlot;
     iRemoteSizeMsgSlot = KErrNotFound;
 
     __ASSERT_DEBUG( !iDataBuffer, MMdCCommon::Panic( KErrCorrupt ) );
 
-    if(aIdArray.Count())
+    if( iMessage.IsNull() )
+        {
+        return;
+        }
+    
+    if( aIdArray.Count() )
 		{
-		iDataBuffer = CopyToBufferL( aIdArray );
+		if( iType & ( EObjectNotifyAddWithUri | EObjectNotifyModifyWithUri | EObjectNotifyRemoveWithUri  ) )
+		    {
+		    iDataBuffer = CopyToBufferL( aIdArray, aUriArray );
+		    }
+		else
+		    {
+		    iDataBuffer = CopyToBufferL( aIdArray );
+		    }
 	    iSession.SizeToRemoteL( iMessage, remoteSizeMsgSlot, iDataBuffer->Size());
 		}
 	else
 		{
-	    iSession.SizeToRemoteL( iMessage, remoteSizeMsgSlot, 0);
+	    iSession.SizeToRemoteL( iMessage, remoteSizeMsgSlot, 0 );
 		}
 
     __LOG2( ELogServer, "<- Notify trigger %d (%d)", iId, aCompleteCode );
@@ -161,6 +178,11 @@
 
     __ASSERT_DEBUG( !iDataBuffer, MMdCCommon::Panic( KErrCorrupt ) );
 
+    if( iMessage.IsNull() )
+        {
+        return;
+        }
+    
     if(aRelationIdArray.Count())
 		{
 		iDataBuffer = CopyItemsToBufferL( aBuffer, aRelationIdArray );
@@ -180,7 +202,12 @@
 // ------------------------------------------------
 //
 void CMdSNotifier::TEntry::TriggerSchema()
-    {
+    {    
+    if( iMessage.IsNull() )
+        {
+        return;
+        }
+    
     iRemoteSizeMsgSlot = KErrNotFound;
     iMessage.Complete( ESchemaModify );
     }
@@ -233,6 +260,59 @@
 	}
 
 // ------------------------------------------------
+// CopyToBufferL copies ids and uris to buffer
+// ------------------------------------------------
+//
+CMdCSerializationBuffer* CMdSNotifier::TEntry::CopyToBufferL(const RArray<TItemId>& aIdArray,
+                                                                                                  const RPointerArray<HBufC>& aUriArray)
+    {
+    const TUint32 count = aIdArray.Count();
+    const TUint32 uriCount = aUriArray.Count();
+
+    TInt urisSize = CMdCSerializationBuffer::KRequiredSizeForTUint32;
+
+    for( TInt i = uriCount - 1; i >=0; i-- )
+        {
+        urisSize += CMdCSerializationBuffer::RequiredSize( *aUriArray[i] );
+        }
+    
+    TInt idsSize( sizeof( TMdCItemIds ) + count * CMdCSerializationBuffer::KRequiredSizeForTItemId );
+    
+    CMdCSerializationBuffer* buffer = CMdCSerializationBuffer::NewLC(
+            urisSize + idsSize );
+    
+    TMdCItemIds itemIds;
+    itemIds.iNamespaceDefId = NamespaceDefId();
+    itemIds.iObjectIds.iPtr.iCount = count;
+    itemIds.iObjectIds.iPtr.iOffset = sizeof(TMdCItemIds);
+    itemIds.SerializeL( *buffer );
+
+    // Insert IDs
+    for( TInt i = 0; i < count; ++i )
+        {
+        buffer->InsertL( aIdArray[i] );
+        }
+    
+    // Insert uri count
+    buffer->InsertL( uriCount );
+    
+    // Insert uris
+    for( TInt i = 0; i < uriCount; ++i )
+        {
+        // add uri
+        const TDesC& uri =  *aUriArray[i];
+        HBufC* lcUri = HBufC::NewLC( uri.Length() );
+        lcUri->Des().Append( uri );
+        buffer->InsertL( *lcUri );
+        CleanupStack::PopAndDestroy( lcUri ); 
+        lcUri = NULL;
+        }
+
+    CleanupStack::Pop( buffer );
+    return buffer;  
+    }
+
+// ------------------------------------------------
 // CopyItemsToBufferL copies relation items to buffer
 // ------------------------------------------------
 //
@@ -282,14 +362,25 @@
 // CacheL caches the notification
 // ------------------------------------------------
 //
-void CMdSNotifier::TEntry::CacheL(TUint32 aCompleteCode, const RArray<TItemId>& aIdArray )
+void CMdSNotifier::TEntry::CacheL(TUint32 aCompleteCode, 
+                                                         const RArray<TItemId>& aIdArray, 
+                                                         const RPointerArray<HBufC>& aUriArray)
     {
     if ( aIdArray.Count() <= 0 )
     	{
     	return;
     	}
 
-    CMdCSerializationBuffer* data = CopyToBufferL( aIdArray );
+    CMdCSerializationBuffer* data( NULL );
+    
+    if( iType & ( EObjectNotifyAddWithUri | EObjectNotifyModifyWithUri | EObjectNotifyRemoveWithUri  ) )
+        {
+        data = CopyToBufferL( aIdArray, aUriArray );
+        }
+    else
+        {
+        data = CopyToBufferL( aIdArray );
+        }
     iSession.CacheNotificationL( iId, aCompleteCode, data );
     }
 
@@ -327,6 +418,11 @@
 
     __ASSERT_DEBUG( !iDataBuffer, MMdCCommon::Panic( KErrCorrupt ) );
 
+    if( iMessage.IsNull() )
+        {
+        return;
+        }
+    
     if( aData )
     	{
     	iSession.SizeToRemoteL( iMessage, remoteSizeMsgSlot, aData->Size());
@@ -470,49 +566,85 @@
 void CMdSNotifier::NotifyAddedL(CMdCSerializationBuffer& aSerializedItems, 
 							    CMdCSerializationBuffer& aSerializedItemIds)
     {
-    const TInt count = iEntries.Count();
+    const TBool uriNotify = CheckForNotifier(EObjectNotifyAddWithUri);
+    TBool allMatched( EFalse );
+    TBool allItemsFetched( EFalse );
     
-    for( TInt i = 0; i < count; ++i )
+    RArray<TItemId> allItemsIdArray;
+    CleanupClosePushL( allItemsIdArray );
+    RPointerArray<HBufC> allItemsUriArray;
+    CleanupResetAndDestroyPushL( allItemsUriArray );
+    
+    for( TInt i = iEntries.Count() - 1; i >=0; i-- )
         {
         TEntry& e = iEntries[i];
 
-        if ( ! (e.iType & ( EObjectNotifyAdd | ERelationNotifyAdd | EEventNotifyAdd ) ) )
+        if ( ! (e.iType & ( EObjectNotifyAdd | ERelationNotifyAdd | EEventNotifyAdd | EObjectNotifyAddWithUri ) ) )
         	{
         	continue;
         	}
         
         RArray<TItemId> matchingItemIdArray;
+        RPointerArray<HBufC> matchingItemUriArray;
    		CleanupClosePushL( matchingItemIdArray );
+   		CleanupResetAndDestroyPushL( matchingItemUriArray );
 
 		aSerializedItems.PositionL( KNoOffset );
 		aSerializedItemIds.PositionL( KNoOffset );
 
 		const TBool someMatches = iComparator->MatchL( e.NamespaceDefId(), e.iType, e.Condition(), 
-												 aSerializedItems, aSerializedItemIds, 
-												 matchingItemIdArray,
-												 e.AllowConfidential() );
+										    		 aSerializedItems, aSerializedItemIds, 
+											    	 matchingItemIdArray,
+											    	 allItemsIdArray,
+												     matchingItemUriArray,
+												     allItemsUriArray,
+						     						 e.AllowConfidential(),
+							     					 uriNotify,
+								    				 allMatched,
+								    				 allItemsFetched );
 
         if( someMatches ) // check if there is some matches
             {
             if( e.IsPending() )
             	{
+            	TInt err( KErrNone );
             	// match found. trigger notifier entry !
-	            TRAPD( err, e.TriggerL( EObjectNotifyAdd | ERelationNotifyAdd | EEventNotifyAdd,
-	            		matchingItemIdArray ) );
-	            if( err != KErrNone )
-	            	{
-	            	e.TriggerError( err );
-	            	}
+            	if( allMatched )
+            	    {
+                    TRAP( err, e.TriggerL( EObjectNotifyAdd | ERelationNotifyAdd | EEventNotifyAdd | EObjectNotifyAddWithUri,
+                            allItemsIdArray, allItemsUriArray ) );  
+            	    }
+            	else
+            	    {
+                    TRAP( err, e.TriggerL( EObjectNotifyAdd | ERelationNotifyAdd | EEventNotifyAdd | EObjectNotifyAddWithUri,
+                            matchingItemIdArray, matchingItemUriArray ) );  
+            	    }
+                if( err != KErrNone )
+                    {
+                    e.TriggerError( err );
+                    }
             	}
             else
             	{
-            	TRAP_IGNORE( e.CacheL( EObjectNotifyAdd | ERelationNotifyAdd | EEventNotifyAdd,
-            			matchingItemIdArray ) );
+                if( allMatched )
+                    {
+                    TRAP_IGNORE( e.CacheL( EObjectNotifyAdd | ERelationNotifyAdd | EEventNotifyAdd | EObjectNotifyAddWithUri,
+                             allItemsIdArray, allItemsUriArray ) );    
+                    }
+                else
+                    {
+                    TRAP_IGNORE( e.CacheL( EObjectNotifyAdd | ERelationNotifyAdd | EEventNotifyAdd | EObjectNotifyAddWithUri,
+                             matchingItemIdArray, matchingItemUriArray ) );    
+                    }
             	}
+            // Copy of each uri is made to each client, which will own the returned uri
+            // Thus URI ownership is transferred and original array can be destroyed
+            matchingItemUriArray.ResetAndDestroy();
             }
 
-   		CleanupStack::PopAndDestroy( &matchingItemIdArray );
+   		CleanupStack::PopAndDestroy( 2, &matchingItemIdArray );
         }
+    CleanupStack::PopAndDestroy( 2, &allItemsIdArray ); // allItemsIdArray, allItemsUriArray
     }
 
 // ------------------------------------------------
@@ -520,7 +652,9 @@
 // ------------------------------------------------
 //
 void CMdSNotifier::NotifyRemovedL(CMdCSerializationBuffer& aSerializedItemIds, 
-								  TBool aItemIsConfidential)
+								  TBool aItemIsConfidential,
+								  RPointerArray<HBufC>& aRemovedItemUriArray,
+								  CMdSManipulationEngine* aMEngine )
     {
 	aSerializedItemIds.PositionL( KNoOffset );
 
@@ -587,8 +721,7 @@
 			|| eventCount != 0 
 			|| relationCount != 0 )
 		{
-		const TInt entriesCount = iEntries.Count();
-	    for( TInt i=0; i < entriesCount; ++i )
+		for( TInt i = iEntries.Count() - 1; i >=0; i-- )
 	        {
 	        TEntry& e = iEntries[i];
 	        
@@ -603,6 +736,9 @@
 	        	continue;	
 	        	}
 
+	        RPointerArray<HBufC> uriArray;
+	        CleanupResetAndDestroyPushL( uriArray );
+	        
 	        if( e.iType & EObjectNotifyRemove && objectCount > 0 )
 	            {
 	            // collect matching object IDs
@@ -624,12 +760,12 @@
 		            		{
 		            		// all matches so send whole object ID array
 		            		TRAP( err, e.TriggerL( EObjectNotifyRemove, 
-		            				objectIdArray ) );
+		            				objectIdArray, uriArray ) );
 		            		}
 		            	else
 		            		{
 		            		TRAP( err, e.TriggerL( EObjectNotifyRemove, 
-		            				matchingObjectIdArray ) );
+		            				matchingObjectIdArray, uriArray ) );
 		            		}
 	
 		            	if( err != KErrNone )
@@ -643,18 +779,72 @@
 		            		{
 		            		// all matches so send whole object ID array
 	            			TRAP_IGNORE( e.CacheL( EObjectNotifyRemove, 
-	            					objectIdArray ) );
+	            					objectIdArray, uriArray ) );
 		            		}
 		            	else
 		            		{
 		            		TRAP_IGNORE( e.CacheL( EObjectNotifyRemove, 
-		            				matchingObjectIdArray ) );
+		            				matchingObjectIdArray, uriArray ) );
 		            		}
 	            		}
 	            	}
 	
 				CleanupStack::PopAndDestroy( &matchingObjectIdArray );
 				}
+	        else if( e.iType & EObjectNotifyRemoveWithUri && objectCount > 0 )
+                {
+                // collect matching object IDs
+                RArray<TItemId> matchingObjectIdArray;
+                CleanupClosePushL( matchingObjectIdArray );
+    
+                const TBool allMatches = iComparator->MatchObjectIdsL( e.Condition(),
+                        objectIdArray, matchingObjectIdArray );
+    
+                // check is there any matches
+                if( allMatches || matchingObjectIdArray.Count() > 0 )
+                    {
+                    if(e.IsPending())
+                        {
+                        // Match found. Trigger notifier entry.
+                        TInt err( KErrNone );
+                        
+                        if( allMatches )
+                            {
+                            // all matches so send whole object ID array
+                            TRAP( err, e.TriggerL( EObjectNotifyRemoveWithUri, 
+                                    objectIdArray, aRemovedItemUriArray ) );
+                            }
+                        else
+                            {
+                            aMEngine->GetObjectUrisByIdsL( objectIdArray, uriArray );
+                            TRAP( err, e.TriggerL( EObjectNotifyRemoveWithUri, 
+                                    matchingObjectIdArray, uriArray ) );
+                            }
+    
+                        if( err != KErrNone )
+                            {
+                            e.TriggerError( err );
+                            }
+                        }
+                    else
+                        {
+                        if( allMatches )
+                            {
+                            // all matches so send whole object ID array
+                            TRAP_IGNORE( e.CacheL( EObjectNotifyRemoveWithUri, 
+                                    objectIdArray, aRemovedItemUriArray ) );
+                            }
+                        else
+                            {
+                            aMEngine->GetObjectUrisByIdsL( objectIdArray, uriArray );
+                            TRAP_IGNORE( e.CacheL( EObjectNotifyRemoveWithUri, 
+                                    matchingObjectIdArray, uriArray ) );
+                            }
+                        }
+                    }
+    
+                CleanupStack::PopAndDestroy( &matchingObjectIdArray );
+                }
 	        else if( ( e.iType & EEventNotifyRemove ) 
 	        		&& eventCount > 0 )
             	{
@@ -664,7 +854,7 @@
 	        		{
 	            	// Match found. Trigger notifier entry.
 	            	TRAPD( err, e.TriggerL( EEventNotifyRemove, 
-	            			eventIdArray ) );
+	            			eventIdArray, uriArray ) );
 	            	if( err != KErrNone )
 		            	{
 		            	e.TriggerError( err );
@@ -673,7 +863,7 @@
 	        	else
 	        		{
 	        		TRAP_IGNORE( e.CacheL( EEventNotifyRemove, 
-	        				eventIdArray ) );
+	        				eventIdArray, uriArray ) );
 	        		}
             	}
 	        else if( ( e.iType & ERelationNotifyRemove ) 
@@ -685,7 +875,7 @@
 	        		{
 	            	// Match found. Trigger notifier entry.
 	            	TRAPD( err, e.TriggerL( ERelationNotifyRemove, 
-	            			relationIdArray ) );
+	            			relationIdArray, uriArray ) );
 	            	if( err != KErrNone )
 		            	{
 		            	e.TriggerError( err );
@@ -694,9 +884,10 @@
 	        	else
 	        		{
 	        		TRAP_IGNORE( e.CacheL( ERelationNotifyRemove, 
-	        				relationIdArray ) );
+	        				relationIdArray, uriArray ) );
 	        		}
             	}
+	        CleanupStack::PopAndDestroy( &uriArray );
 	        }
 		}
 	CleanupStack::PopAndDestroy( 3, &objectIdArray ); // relationIdArray, eventIdArray, objectIdArray
@@ -709,74 +900,115 @@
 void CMdSNotifier::NotifyModifiedL(CMdCSerializationBuffer& aSerializedItems, 
 							       CMdCSerializationBuffer& aSerializedItemIds)
     {
-    const TInt count = iEntries.Count();
+    const TBool uriNotify = CheckForNotifier(EObjectNotifyModifyWithUri);
+    TBool allMatched( EFalse );
+    TBool allItemsFetched( EFalse );
+
+    RArray<TItemId> allItemsIdArray;
+    CleanupClosePushL( allItemsIdArray );
+    RPointerArray<HBufC> allItemsUriArray;
+    CleanupResetAndDestroyPushL( allItemsUriArray );
     
-    for( TInt i = 0; i < count; ++i )
+    for( TInt i = iEntries.Count() - 1; i >=0; i-- )
         {
         TEntry& e = iEntries[i];
 
-        if ( ! (e.iType & ( EObjectNotifyModify | ERelationNotifyModify ) ) )
+        if ( ! (e.iType & ( EObjectNotifyModify | ERelationNotifyModify | EObjectNotifyModifyWithUri ) ) )
         	{
         	continue;
         	}
   
         RArray<TItemId> matchingObjectIdArray;
+        RPointerArray<HBufC> matchingItemUriArray;
 		CleanupClosePushL( matchingObjectIdArray );
+		CleanupResetAndDestroyPushL( matchingItemUriArray );
 
 		aSerializedItems.PositionL( KNoOffset );
 		aSerializedItemIds.PositionL( KNoOffset );
 
-		const TBool someMatches = iComparator->MatchL( e.NamespaceDefId(), 
-				e.iType, e.Condition(), aSerializedItems, aSerializedItemIds, 
-				matchingObjectIdArray, e.AllowConfidential() );
+		const TBool someMatches = iComparator->MatchL( e.NamespaceDefId(), e.iType, e.Condition(), 
+                                          aSerializedItems, aSerializedItemIds, 
+                                          matchingObjectIdArray,
+                                          allItemsIdArray,
+                                          matchingItemUriArray,
+                                          allItemsUriArray,
+                                          e.AllowConfidential(),
+                                          uriNotify,
+                                          allMatched,
+                                          allItemsFetched );
 
         if( someMatches ) // check if there is some matches
             {
             if( e.IsPending() )
             	{
-            	// match found. trigger notifier entry !
-	            TRAPD( err, e.TriggerL( EObjectNotifyModify | ERelationNotifyModify,
-	            		matchingObjectIdArray ) );
-	            if( err != KErrNone )
-	            	{
-	            	e.TriggerError( err );
-	            	}
+            	TInt err( KErrNone );
+                // match found. trigger notifier entry !
+                if( allMatched )
+                    {
+                    TRAP( err, e.TriggerL( EObjectNotifyModify | ERelationNotifyModify | EObjectNotifyModifyWithUri,
+                            allItemsIdArray, allItemsUriArray ) );  
+                    }
+                else
+                    {
+                    TRAP( err, e.TriggerL( EObjectNotifyModify | ERelationNotifyModify | EObjectNotifyModifyWithUri,
+                            matchingObjectIdArray, matchingItemUriArray ) );  
+                    }
+                if( err != KErrNone )
+                    {
+                    e.TriggerError( err );
+                    }         
             	}
             else
             	{
-            	TRAP_IGNORE( e.CacheL( EObjectNotifyModify | ERelationNotifyModify,
-            			matchingObjectIdArray ) );
-            	}
+                if( allMatched )
+                    {
+                    TRAP_IGNORE( e.CacheL( EObjectNotifyModify | ERelationNotifyModify | EObjectNotifyModifyWithUri,
+                             allItemsIdArray, allItemsUriArray ) );    
+                    }
+                else
+                    {
+                    TRAP_IGNORE( e.CacheL( EObjectNotifyModify | ERelationNotifyModify | EObjectNotifyModifyWithUri,
+                            matchingObjectIdArray, matchingItemUriArray ) );    
+                    }
+                }
+            // Copy of each uri is made to each client, which will own the returned uri
+            // Thus URI ownership is transferred and original array can be destroyed
+            matchingItemUriArray.ResetAndDestroy();
             }
-
-		CleanupStack::PopAndDestroy( &matchingObjectIdArray );
+		CleanupStack::PopAndDestroy( 2, &matchingObjectIdArray );
         }
+    CleanupStack::PopAndDestroy( 2, &allItemsIdArray ); // allItemsIdArray, allItemsUriArray
     }
 
 // ------------------------------------------------
 // NotifyModified
 // ------------------------------------------------
 //
-void CMdSNotifier::NotifyModifiedL(const RArray<TItemId>& aObjectIds)
+void CMdSNotifier::NotifyModifiedL(const RArray<TItemId>& aObjectIds,
+                                                         CMdSManipulationEngine* aMEngine)
 	{
 	if (aObjectIds.Count() == 0)
     	{
     	return;
     	}
 
-    const TInt count = iEntries.Count();
+    TBool allUrisFetched( EFalse );
+    RPointerArray<HBufC> allUrisArray;
+    CleanupResetAndDestroyPushL( allUrisArray );
 
-    for( TInt i = 0; i < count; ++i )
+    for( TInt i = iEntries.Count() - 1; i >=0; i-- )
         {
         TEntry& e = iEntries[i];
 
-        if( e.iType & EObjectNotifyModify )
+        if( e.iType & (EObjectNotifyModify | EObjectNotifyModifyWithUri) )
             {
             // collect matching object IDs
             RArray<TItemId> matchingObjectIdArray;
 			CleanupClosePushL( matchingObjectIdArray );
+		    RPointerArray<HBufC> uriArray;
+		    CleanupResetAndDestroyPushL( uriArray );
 
-                const TBool allMatches = iComparator->MatchObjectIdsL( e.Condition(),
+            const TBool allMatches = iComparator->MatchObjectIdsL( e.Condition(), 
             		aObjectIds, matchingObjectIdArray );
 
 			// check is there any matches
@@ -790,15 +1022,36 @@
 	            	if( allMatches )
 	            		{
 	            		// all matches so send whole object ID array
-	            		TRAP( err, e.TriggerL( EObjectNotifyModify, 
-	            				aObjectIds ) );
+	            		if( e.iType & EObjectNotifyModifyWithUri )
+	            		    {
+	            		    if( !allUrisFetched )
+	            		        {
+	            		        aMEngine->GetObjectUrisByIdsL( aObjectIds, allUrisArray );
+	            		        allUrisFetched = ETrue;
+	            		        }
+	                        TRAP( err, e.TriggerL( EObjectNotifyModifyWithUri, 
+	                                 aObjectIds, allUrisArray ) );
+	            		    }
+	            		else
+	            		    {
+                            TRAP( err, e.TriggerL( EObjectNotifyModify, 
+                                     aObjectIds, uriArray ) );
+	            		    }
 	            		}
 	            	else
 	            		{
-	            		TRAP( err, e.TriggerL( EObjectNotifyModify, 
-	            				matchingObjectIdArray ) );
+                        if( e.iType & EObjectNotifyModifyWithUri )
+                            {
+                            aMEngine->GetObjectUrisByIdsL( matchingObjectIdArray, uriArray );
+                            TRAP( err, e.TriggerL( EObjectNotifyModifyWithUri, 
+                                    matchingObjectIdArray, uriArray ) );
+                            }
+                        else
+                            {
+                            TRAP( err, e.TriggerL( EObjectNotifyModify, 
+                                    matchingObjectIdArray, uriArray ) );
+                            }
 	            		}
-
 	            	if( err != KErrNone )
 		            	{
 		            	e.TriggerError( err );
@@ -808,39 +1061,72 @@
             		{
 					if( allMatches )
 	            		{
-	            		// all matches so send whole object ID array
-            			TRAP_IGNORE( e.CacheL( EObjectNotifyModify, 
-            					aObjectIds ) );
+                        // all matches so send whole object ID array
+                        if( e.iType & EObjectNotifyModifyWithUri )
+                            {
+                            if( !allUrisFetched )
+                                {
+                                aMEngine->GetObjectUrisByIdsL( aObjectIds, allUrisArray );
+                                allUrisFetched = ETrue;
+                                }
+                            TRAP_IGNORE( e.CacheL( EObjectNotifyModifyWithUri, 
+                                     aObjectIds, allUrisArray ) );
+                            }
+                        else
+                            {
+                            TRAP_IGNORE( e.CacheL( EObjectNotifyModify, 
+                                     aObjectIds, uriArray ) );
+                            }
 	            		}
 	            	else
 	            		{
-	            		TRAP_IGNORE( e.CacheL( EObjectNotifyModify, 
-	            				matchingObjectIdArray ) );
+                        if( e.iType & EObjectNotifyModifyWithUri )
+                            {
+                            aMEngine->GetObjectUrisByIdsL( matchingObjectIdArray, uriArray );
+                            TRAP_IGNORE( e.CacheL( EObjectNotifyModifyWithUri, 
+                                    matchingObjectIdArray, uriArray ) );
+                            }
+                        else
+                            {
+                            TRAP_IGNORE( e.CacheL( EObjectNotifyModify, 
+                                    matchingObjectIdArray, uriArray ) );
+                            }
 	            		}
             		}
             	}
-
-			CleanupStack::PopAndDestroy( &matchingObjectIdArray );
+			CleanupStack::PopAndDestroy( 2, &matchingObjectIdArray ); // matchingObjectIdArray, uriArray
             }
         }
+    CleanupStack::PopAndDestroy( &allUrisArray );
 	}
 
 // ------------------------------------------------
 // NotifyRemoved
 // ------------------------------------------------
 //
-void CMdSNotifier::NotifyRemovedL(const RArray<TItemId>& aItemIdArray)
+void CMdSNotifier::NotifyRemovedL(const RArray<TItemId>& aItemIdArray,
+                                                          CMdSManipulationEngine* aMEngine)
 	{
-    const TInt entriesCount( iEntries.Count() );
-    for( TInt i=0; i<entriesCount; ++i )
+    if (aItemIdArray.Count() == 0)
+        {
+        return;
+        }
+    
+    RPointerArray<HBufC> uriArray;
+    CleanupResetAndDestroyPushL( uriArray );
+    TBool urisFetched( EFalse );
+	
+    for( TInt i = iEntries.Count()- 1; i >=0; i-- )
         {
         TEntry& e = iEntries[i];
 
         if( e.iType & EObjectNotifyRemove )
         	{
+        	RPointerArray<HBufC> nullArray; // For when uris are not needed
+        	CleanupResetAndDestroyPushL( nullArray );
             if( e.IsPending() )
             	{
-	            TRAPD( err, e.TriggerL( EObjectNotifyRemove, aItemIdArray ) );
+	            TRAPD( err, e.TriggerL( EObjectNotifyRemove, aItemIdArray, nullArray ) );
 	            if( err != KErrNone )
 	            	{
 	            	e.TriggerError( err );
@@ -848,10 +1134,32 @@
             	}
             else
             	{
-            	TRAP_IGNORE( e.CacheL( EObjectNotifyRemove, aItemIdArray ) );
+            	TRAP_IGNORE( e.CacheL( EObjectNotifyRemove, aItemIdArray, nullArray ) );
             	}
+            CleanupStack::PopAndDestroy( &nullArray );
         	}
+        else if( e.iType & EObjectNotifyRemoveWithUri )
+            {
+            if( !urisFetched && aMEngine )
+                {
+                aMEngine->GetObjectUrisByIdsL( aItemIdArray, uriArray );
+                urisFetched = ETrue;
+                }
+            if( e.IsPending() )
+                {
+                TRAPD( err, e.TriggerL( EObjectNotifyRemoveWithUri, aItemIdArray, uriArray ) );
+                if( err != KErrNone )
+                    {
+                    e.TriggerError( err );
+                    }
+                }
+            else
+                {
+                TRAP_IGNORE( e.CacheL( EObjectNotifyRemoveWithUri, aItemIdArray, uriArray ) );
+                }
+            }
         }
+    CleanupStack::PopAndDestroy( &uriArray );
 	}
 
 // ------------------------------------------------
@@ -865,9 +1173,7 @@
     	return;
     	}
 
-    const TInt count = iEntries.Count();
-    
-    for( TInt i = 0; i < count; ++i )
+    for( TInt i = iEntries.Count() - 1; i >=0; i-- )
         {
         TEntry& e = iEntries[i];
 
@@ -878,10 +1184,11 @@
             const TMdSObserverNotificationType objectState = 
             	aPresent ? EObjectNotifyPresent : EObjectNotifyNotPresent;
 
+            RPointerArray<HBufC> nullArray; // For when uris are not needed
             if( e.IsPending() )
             	{
             	// match found. trigger notifier entry !
-	            TRAPD( err, e.TriggerL( objectState, aObjectIds ) );
+	            TRAPD( err, e.TriggerL( objectState, aObjectIds, nullArray ) );
 	            if( err != KErrNone )
 	            	{
 	            	e.TriggerError( err );
@@ -889,8 +1196,9 @@
             	}
             else
             	{
-            	TRAP_IGNORE( e.CacheL( objectState, aObjectIds ) );
+            	TRAP_IGNORE( e.CacheL( objectState, aObjectIds, nullArray ) );
             	}
+            nullArray.Close();
             }
         }
     }
@@ -906,9 +1214,7 @@
     	return;
     	}
 
-    const TInt count = iEntries.Count();
-    
-    for( TInt i = 0; i < count; ++i )
+    for( TInt i = iEntries.Count() - 1; i >=0; i-- )
         {
         TEntry& e = iEntries[i];
 
@@ -919,10 +1225,11 @@
             const TMdSObserverNotificationType relationState = 
             	aPresent ? ERelationNotifyPresent : ERelationNotifyNotPresent;
 
+            RPointerArray<HBufC> nullArray; // For when uris are not needed
             if( e.IsPending() )
             	{
             	// match found. trigger notifier entry !
-	            TRAPD( err, e.TriggerL( relationState, aRelationIds ) );
+	            TRAPD( err, e.TriggerL( relationState, aRelationIds, nullArray ) );
 	            if( err != KErrNone )
 	            	{
 	            	e.TriggerError( err );
@@ -930,8 +1237,9 @@
             	}
             else
             	{
-            	TRAP_IGNORE( e.CacheL( relationState, aRelationIds ) );
+            	TRAP_IGNORE( e.CacheL( relationState, aRelationIds, nullArray ) );
             	}
+            nullArray.Close();
             }
         }
     }
@@ -943,9 +1251,7 @@
 //
 void CMdSNotifier::NotifySchemaAddedL()
     {
-    const TInt count = iEntries.Count();
-    
-    for( TInt i = 0; i < count; ++i )
+    for( TInt i = iEntries.Count() - 1; i >=0; i-- )
         {
         TEntry& e = iEntries[i];
 
@@ -973,9 +1279,7 @@
 //
 TBool CMdSNotifier::CheckForNotifier( TUint32 aNotifyTypes )
     {
-    const TInt count = iEntries.Count();
-    
-    for( TInt i = 0; i < count; ++i )
+    for( TInt i = iEntries.Count() - 1; i >=0; i-- )
         {
         if ( iEntries[i].iType & aNotifyTypes )
         	{
@@ -994,8 +1298,7 @@
 
 	if( items.iRelations.iPtr.iCount )
 		{
-		const TInt entriesCount = iEntries.Count();
-	    for( TInt i = 0; i < entriesCount; ++i )
+		for( TInt i = iEntries.Count() - 1; i >=0; i-- )
 	        {
 	        TEntry& e = iEntries[i];
 	        
--- a/metadataengine/server/src/mdsnotifycomparator.cpp	Fri Mar 12 15:44:28 2010 +0200
+++ b/metadataengine/server/src/mdsnotifycomparator.cpp	Mon Mar 15 12:42:24 2010 +0200
@@ -62,7 +62,13 @@
     CMdCSerializationBuffer& aSerializedItems,
     CMdCSerializationBuffer& aSerializedItemIds,
     RArray<TItemId>& aMatchingItemIdArray,
-    TBool aAllowConfidential)
+    RArray<TItemId>& aAllItemsIdArray,
+    RPointerArray<HBufC>& aMatchingItemUriArray,
+    RPointerArray<HBufC>& aAllItemsUriArray,
+    TBool aAllowConfidential,
+    TBool uriNotify,
+    TBool& aAllMatched,
+    TBool& aAllItemsFetched )
     {
     const TMdCItems& items = TMdCItems::GetFromBufferL( aSerializedItems );
 
@@ -74,14 +80,17 @@
     	return EFalse;
     	}
 
+    aAllMatched = EFalse;
+    
     if( ( items.iObjects.iPtr.iCount > 0 ) && 
     	( itemIds.iObjectIds.iPtr.iCount > 0 ) && 
-    	( aType & ( EObjectNotifyAdd | EObjectNotifyModify ) ) )
+    	( aType & ( EObjectNotifyAdd | EObjectNotifyModify | EObjectNotifyAddWithUri | EObjectNotifyModifyWithUri ) ) )
     	{
     	// object ID count and object item count should match
 		__ASSERT_DEBUG( items.iObjects.iPtr.iCount == itemIds.iObjectIds.iPtr.iCount, MMdCCommon::Panic( KErrCorrupt ) );
 
     	aSerializedItemIds.PositionL( itemIds.iObjectIds.iPtr.iOffset );
+    	TBool allItemsFetched( aAllItemsFetched );
     	for( TUint32 i = 0; i < itemIds.iObjectIds.iPtr.iCount; i++ )
     		{
     		TItemId objectId;
@@ -140,13 +149,48 @@
 
 	    	    if ( succeed )    
 	                {
+	                if( uriNotify )
+	                    {
+	                    // set correct position to item buffer
+	                    aSerializedItems.PositionL( items.iObjects.iPtr.iOffset + 
+	                               i * sizeof(TMdCObject) );
+	                    
+	                   const TMdCObject& object = TMdCObject::GetFromBufferL( aSerializedItems );
+
+	                    aSerializedItems.PositionL( object.iUri.iPtr.iOffset );
+	                    HBufC* uriBuf = aSerializedItems.ReceiveDes16L();
+	                    aMatchingItemUriArray.AppendL( uriBuf );
+	                    }
 	                aMatchingItemIdArray.AppendL( objectId );
 	                }
     			}
     		else
     			{
-    			aMatchingItemIdArray.AppendL( objectId );
-    			}
+                aAllMatched = ETrue;		
+                if( uriNotify && (!aAllItemsFetched || !allItemsFetched) )
+                    {
+                    // set correct position to item buffer
+                    aSerializedItems.PositionL( items.iObjects.iPtr.iOffset + 
+                               i * sizeof(TMdCObject) );
+                    
+                   const TMdCObject& object = TMdCObject::GetFromBufferL( aSerializedItems );
+
+                    aSerializedItems.PositionL( object.iUri.iPtr.iOffset );
+                    HBufC* uriBuf = aSerializedItems.ReceiveDes16L();
+                    aAllItemsUriArray.AppendL( uriBuf );
+                    aAllItemsIdArray.AppendL( objectId );
+                    allItemsFetched = ETrue;
+                    }
+                else if( !aAllItemsFetched || !allItemsFetched )
+                    {
+                    aAllItemsIdArray.AppendL( objectId );
+                    allItemsFetched = ETrue;
+                    }
+                }
+    		}
+    	if( allItemsFetched )
+    	    {
+    	    aAllItemsFetched = ETrue;
     		}
     	}
     else if( ( items.iEvents.iPtr.iCount > 0 ) && 
@@ -215,7 +259,7 @@
     		}
     	}
 
-    if( aMatchingItemIdArray.Count() > 0 )
+    if( aMatchingItemIdArray.Count() > 0 || ( aAllItemsIdArray.Count() > 0 && aAllMatched ))
     	{
     	return ETrue;
     	}
--- a/metadataengine/server/src/mdsschema.cpp	Fri Mar 12 15:44:28 2010 +0200
+++ b/metadataengine/server/src/mdsschema.cpp	Mon Mar 15 12:42:24 2010 +0200
@@ -203,7 +203,7 @@
 
 void CMdsSchema::CreateObjectTablesL()
 	{
-	_LIT( KBaseObjectDefinition,  "CREATE TABLE IF NOT EXISTS %S%u(ObjectId INTEGER PRIMARY KEY AUTOINCREMENT,ObjectDefId INTEGER NOT NULL,Flags INTEGER,MediaId LARGEINT,UsageCount LARGEINT DEFAULT 0,GuidHigh LARGEINT,GuidLow LARGEINT,URI TEXT NOT NULL COLLATE NOCASE,Origin INTEGER,Size LARGEINT,TimeOffset INTEGER,CreationDate LARGEINT,LastModifiedDate LARGEINT,ItemType TEXT,Title TEXT,UNIQUE(GuidHigh,GuidLow),UNIQUE(MediaId,URI));" );	
+	_LIT( KBaseObjectDefinition,  "CREATE TABLE IF NOT EXISTS %S%u(ObjectId INTEGER PRIMARY KEY AUTOINCREMENT,ObjectDefId INTEGER NOT NULL,Flags INTEGER,MediaId LARGEINT,UsageCount LARGEINT DEFAULT 0,GuidHigh LARGEINT,GuidLow LARGEINT,URI TEXT NOT NULL COLLATE NOCASE,Origin INTEGER,Size LARGEINT,TimeOffset INTEGER,CreationDate LARGEINT,LastModifiedDate LARGEINT,ItemType TEXT,Title TEXT,UNIQUE(GuidHigh,GuidLow),UNIQUE(URI,MediaId));" );	
 	_LIT( KCreateRelationsTable,  "CREATE TABLE IF NOT EXISTS Relations%u(RelationId INTEGER PRIMARY KEY AUTOINCREMENT,Flags INTEGER,RelationDefId INTEGER NOT NULL,LeftObjectId INTEGER NOT NULL,RightObjectId INTEGER NOT NULL,Parameter INTEGER,GuidHigh LARGEINT,GuidLow LARGEINT,LastModifiedDate LARGEINT);" );
 	_LIT( KCreateEventsTable,     "CREATE TABLE IF NOT EXISTS Event%u(EventId INTEGER PRIMARY KEY AUTOINCREMENT,ObjectId INTEGER NOT NULL, EventDefId INTEGER NOT NULL, Timestamp INTEGER NOT NULL, Source TEXT, Participant TEXT);" );
 	_LIT( KCreateTxtSrchTable,    "CREATE TABLE IF NOT EXISTS TextSearch%u(WordId INTEGER NOT NULL,ObjectId INTEGER NOT NULL,Position INTEGER);" );
@@ -233,6 +233,9 @@
 	
 	// ObjectTypeDefinition index
 	_LIT( KMdsIndexObjectDefId, "CREATE INDEX ObjectDefIndex%u ON Object%u(ObjectDefId);" );
+	
+    // MediaId index
+    _LIT( KMdsIndexMediaId, "CREATE INDEX MediaIdIndex%u ON Object%u(MediaId);" );
 
 	// create tables
 	CMdsClauseBuffer* clause = CMdsClauseBuffer::NewLC( 1024 );
@@ -339,6 +342,11 @@
             clauseTrigger->BufferL().Format( KMdsIndexObjectDefId, namespaceDefId, namespaceDefId );
             connection.ExecuteL( clauseTrigger->ConstBufferL(), emptyRowData );
             
+            // add mediaidindex[number]
+            clauseTrigger->ReserveSpaceL( KMdsIndexMediaId().Size() + ( KMaxUintValueLength * 2 ) );  
+            clauseTrigger->BufferL().Format( KMdsIndexMediaId, namespaceDefId, namespaceDefId );
+            connection.ExecuteL( clauseTrigger->ConstBufferL(), emptyRowData );
+            
 			namespaceDef->SetTableStoredInDB();
 			}
 
--- a/metadataengine/server/src/mdsserver.cpp	Fri Mar 12 15:44:28 2010 +0200
+++ b/metadataengine/server/src/mdsserver.cpp	Mon Mar 15 12:42:24 2010 +0200
@@ -35,7 +35,6 @@
 __DEFINE_LOGGER
 
 const TInt64 KDiskSpaceGarbageCollectorThreshold = 1024*1024; // 1 MB
-const TInt64 KDiskFullThreshold = 1024*50; // 50 kB
 
 _LIT( KSchema, "schema.mde" );
 _LIT( KDefaultImportProfile, "defaultimportfile.mde" );
@@ -156,6 +155,36 @@
     NULL //mdsElements
     };
 
+// ======================= LOCAL FUNCTIONS ================================
+
+void CheckAndInitializeFileL( RFs& aFs, TBuf<KMaxFileName>& aFile, const TDesC16& aFilePath,
+                                            RFileReadStream& aTempFile, CFileMan* aFileMan )
+    {
+    __LOG1( ELogAlways, "CheckAndInitializeFileL() - handling file %S", &aFilePath );
+    const TInt err = aTempFile.Open( aFs, aFile, EFileRead | EFileShareAny );
+    __LOG1( ELogAlways, "CheckAndInitializeFileL() - open file error %d", err );
+    aTempFile.Close();
+    if ( err != KErrNone )
+        {
+        if ( err == KErrNotFound )
+            {
+            // Path found but not schema.mde, copy schema.m
+            const TInt error = aFileMan->Copy( aFilePath, aFile, CFileMan::EOverWrite );
+            __LOG1( ELogAlways, "CheckAndInitializeFileL() - copy file error %d", error );
+            }
+        else if ( err == KErrPathNotFound)
+            {
+            // Create private dir
+            User::LeaveIfError( aFs.CreatePrivatePath( EDriveC ) );
+            
+            // Copy schema.mde
+            const TInt error = aFileMan->Copy( aFilePath, aFile, CFileMan::EOverWrite );
+            __LOG1( ELogAlways, "CheckAndInitializeFileL() - copy file error %d", error );
+            }    
+        }    
+    }
+
+// ======================= MEMBER FUNCTIONS ===============================
 
 CPolicyServer::TCustomResult CMdSServer::CustomSecurityCheckL(
         const RMessage2& aMsg, TInt& /*aAction*/, TSecurityInfo& /*aMissing*/ )
@@ -325,6 +354,10 @@
     __INIT_LOGGER;
     StartL( KMdSServerName );
     __LOGLB( ELogAlways, "Server start" );
+
+    RProcess process;
+    process.SetPriority( EPriorityBackground );
+    process.Close();
     
     CheckInitSriptL();
     
@@ -871,73 +904,13 @@
     backupRegistration.Append( KBackupRegistration );
     
     CFileMan* fileMan = CFileMan::NewL( fs );
-    CleanupStack::PushL( fileMan);
+    CleanupStack::PushL( fileMan );
+    
+    CheckAndInitializeFileL( fs, schema, KSchemaPath(), tmpFile, fileMan );
     
-    TInt err = tmpFile.Open( fs, schema, EFileRead | EFileShareAny );
-    __LOG1( ELogAlways, "open schema.mde %d", err );
-    tmpFile.Close();
-    if ( err != KErrNone )
-        {
-        if ( err == KErrNotFound )
-            {
-            // Path found but not schema.mde, copy schema.m
-            const TInt error = fileMan->Copy( KSchemaPath, schema, CFileMan::EOverWrite );
-            __LOG1( ELogAlways, "copy schema.mde %d", error );
-            }
-        else if ( err == KErrPathNotFound)
-            {
-            // Create private dir
-            User::LeaveIfError( fs.CreatePrivatePath( EDriveC ) );
-            
-            // Copy schema.mde
-            const TInt error = fileMan->Copy( KSchemaPath, schema, CFileMan::EOverWrite );
-            __LOG1( ELogAlways, "copy schema.mde %d", error );
-            }    
-        }
-
-    err = tmpFile.Open( fs, defaultImportProfile, EFileRead | EFileShareAny );
-    __LOG1( ELogAlways, "open defaultimportprofile.mde %d", err );
-    tmpFile.Close();
-    if ( err != KErrNone )
-        {
-        if ( err == KErrNotFound )
-            {
-            // Path found but not schema.mde, copy schema.m
-            const TInt error1 = fileMan->Copy( KDefaultImportProfilePath, defaultImportProfile, CFileMan::EOverWrite );
-            __LOG1( ELogAlways, "copy defaultimportprofile.mde %d", error1 );
-            }
-        else if ( err == KErrPathNotFound)
-            {
-            // Create private dir
-            User::LeaveIfError( fs.CreatePrivatePath( EDriveC ) );
-             
-            // Copy schema.mde
-            const TInt error1 = fileMan->Copy( KDefaultImportProfilePath, defaultImportProfile, CFileMan::EOverWrite );
-            __LOG1( ELogAlways, "copy defaultimportprofile.mde %d", error1 );
-            }    
-        }    
+    CheckAndInitializeFileL( fs, defaultImportProfile, KDefaultImportProfilePath(), tmpFile, fileMan );    
     
-    err = tmpFile.Open( fs, backupRegistration, EFileRead | EFileShareAny );
-    __LOG1( ELogAlways, "open backup_registration.xml %d", err );
-    tmpFile.Close();
-    if ( err != KErrNone )
-        {
-        if ( err == KErrNotFound )
-            {
-            // Path found but not schema.mde, copy schema.m
-            const TInt error2 = fileMan->Copy( KBackupRegistrationPath, backupRegistration, CFileMan::EOverWrite );
-            __LOG1( ELogAlways, "copy backup_registration.xml %d", error2 );
-            }
-        else if ( err == KErrPathNotFound)
-            {
-            // Create private dir
-            User::LeaveIfError( fs.CreatePrivatePath( EDriveC ) );
-            
-            // Copy schema.mde
-            const TInt error2 = fileMan->Copy( KBackupRegistrationPath, backupRegistration, CFileMan::EOverWrite );
-            __LOG1( ELogAlways, "copy backup_registration.xml %d", error2 );
-            }    
-        }   
+    CheckAndInitializeFileL( fs, backupRegistration, KBackupRegistrationPath(), tmpFile, fileMan );
 
     CleanupStack::PopAndDestroy( 2 ); //fileman, fs
     }
--- a/metadataengine/server/src/mdsserversession.cpp	Fri Mar 12 15:44:28 2010 +0200
+++ b/metadataengine/server/src/mdsserversession.cpp	Mon Mar 15 12:42:24 2010 +0200
@@ -638,12 +638,10 @@
     CMdSFindEngine* findEngine = NULL;
 
     const TUint32 queryId = (TUint32)aMsg.Int0();
-
-    const TInt count = iFindEngines.Count();
-
+    
     TInt feIndex = 0;
 
-    for( TInt i = 0; i < count; i++ )
+    for( TInt i = iFindEngines.Count() - 1; i >=0; i-- )
     	{
     	if( queryId == iFindEngines[i]->QueryId() )
     		{
@@ -684,9 +682,7 @@
     
     const TUint32 queryId = (TUint32)aMsg.Int0();
 
-    const TInt count = iFindEngines.Count();
-    
-    for( TInt i = 0; i < count; i++ )
+    for( TInt i = iFindEngines.Count() - 1; i >=0; i-- )
     	{
     	CMdSFindEngine* findEngine = iFindEngines[i];
 
@@ -1195,10 +1191,8 @@
 void CMdSServerSession::ShutdownL( const RMessage2& /*aMsg*/ )
     {
     __LOGLB( ELogServer, "-> Shutdown session" );
-    
-    const TInt count = iFindEngines.Count();
-    
-    for( TInt i = 0; i < count; i++ )
+
+    for( TInt i = iFindEngines.Count() - 1; i >=0; i-- )
         {
         CMdSFindEngine* fe = iFindEngines[i];
         
--- a/metadataengine/server/src/mdssqlfindoperation.cpp	Fri Mar 12 15:44:28 2010 +0200
+++ b/metadataengine/server/src/mdssqlfindoperation.cpp	Mon Mar 15 12:42:24 2010 +0200
@@ -1405,9 +1405,7 @@
     {
 	if( EQueryResultModeId != iResultMode )
 		{    
-	    const TInt KRowCount = iResultRows.Count();
-
-	    for( TInt i = 0; i < KRowCount; i++ )
+	    for( TInt i = iResultRows.Count() - 1; i >=0; i-- )
 	    	{
 	    	iResultRows[i]->Close();
 	    	}
--- a/metadataengine/server/src/mdssqlobjectmanipulate.cpp	Fri Mar 12 15:44:28 2010 +0200
+++ b/metadataengine/server/src/mdssqlobjectmanipulate.cpp	Mon Mar 15 12:42:24 2010 +0200
@@ -39,11 +39,12 @@
 #include "mdsgetimeiao.h"
 
 #include <e32math.h>
+#include <mdeobject.h>
 
 /** logging instance */
 __USES_LOGGER
 
-const TInt KMaxBuffers = 3;
+const TInt KMaxBuffers = 5;
 
 _LIT( KMemoryCard, "MC" );
 
@@ -181,6 +182,7 @@
 	iBuffers.Close();
 
 	delete iGenerator;
+	delete iUri;
     }
 
 CMdSSqlObjectManipulate::CMdSSqlObjectManipulate( const CMdsSchema& aSchema, 
@@ -657,21 +659,27 @@
 void CMdSSqlObjectManipulate::SetRelationsToNotPresentL(
 		TUint32 aMediaId, RArray<TItemId>& aRelationIds)
 	{
-	_LIT( KSearchPresentRelations, "SELECT DISTINCT A.RelationId FROM Relations%u AS A LEFT JOIN object%u AS B On A.LeftObjectId = B.ObjectId OR A.RightObjectId = B.ObjectId WHERE NOT A.Flags&%u AND NOT A.Flags&%u AND B.MediaId=%u" );
+	_LIT( KSearchPresentRelations, "SELECT A.RelationId FROM Relations%u AS A, Object%u AS B WHERE A.LeftObjectId = B.ObjectId AND B.MediaId=%u AND NOT A.Flags&%u AND NOT A.Flags&%u UNION SELECT A.RelationId FROM Relations%u AS A, Object%u AS B WHERE A.RightObjectId = B.ObjectId AND B.MediaId=%u AND NOT A.Flags&%u AND NOT A.Flags&%u" );
 	_LIT( KSetRelationsToPresent, "UPDATE Relations%u SET Flags=Flags|? WHERE NOT Flags&? AND RelationId IN (%S);" );
 
 	// RelationIDs query sql statement
 	RClauseBuffer commonClauseOne(*this, 
 			KSearchPresentRelations.iTypeLength + 
-			KMaxUintValueLength  );
+			2*KMaxUintValueLength  );
     CleanupClosePushL( commonClauseOne );
 	CMdsClauseBuffer& clauseBufferOne = commonClauseOne.BufferL();
 	clauseBufferOne.BufferL().Format( KSearchPresentRelations, 
                 KDefaultNamespaceDefId,
                 KDefaultNamespaceDefId,
+                aMediaId,
                 EMdERelationFlagDeleted,
                 EMdERelationFlagNotPresent,
-                aMediaId );
+                KDefaultNamespaceDefId,
+                KDefaultNamespaceDefId,
+                aMediaId,
+                EMdERelationFlagDeleted,
+                EMdERelationFlagNotPresent
+                );
 	
     CMdSSqLiteConnection& connection = MMdSDbConnectionPool::GetDefaultDBL();
     	
@@ -1415,8 +1423,6 @@
 	if(objName != iLastAddedObjName)
 	    {
         iLastAddedObjName = objName;
-        aMdsBaseObjStatement.Close();
-        aMdsBaseObjStatement = RMdsStatement();
 	    aMdsObjStatement.Close();
         aMdsObjStatement = RMdsStatement();
         }
@@ -2130,7 +2136,8 @@
 
 void CMdSSqlObjectManipulate::RemoveObjectsByIdL( 
 		CMdCSerializationBuffer& aBuffer, TInt aCount, RArray<TItemId>& aIdArray, 
-		RArray<TItemId>& aRelationIds, RArray<TItemId>& aEventIds )
+		RArray<TItemId>& aRelationIds, RArray<TItemId>& aEventIds,
+		TBool aUrisRequired, RPointerArray<HBufC>& aRemovedItemUriArray )
 	{
 	if ( !iNamespaceDef )
 		{
@@ -2156,15 +2163,28 @@
 			objectIds.AppendL( objectId );
 			}
 		}
-
-	CollectRemovedItemsL( objectIds, aIdArray, aRelationIds, aEventIds );
-
+    
+    CollectRemovedItemsL( objectIds, aIdArray, aRelationIds, aEventIds );
+
+    if( aUrisRequired )
+         {
+         const TInt count( aIdArray.Count() );
+         for( TInt i( 0 ); i < count; i++ )
+             {
+             TUint32 flags;
+             SearchObjectUriByIdL( aIdArray[i], flags );
+             aRemovedItemUriArray.AppendL( iUri );
+             iUri = NULL;
+             }
+         }
+    
     CleanupStack::PopAndDestroy( &objectIds );
 	}
 
 void CMdSSqlObjectManipulate::RemoveObjectsByUriL( 
 		CMdCSerializationBuffer& aBuffer, TInt aCount, RArray<TItemId>& aIdArray,
-        RArray<TItemId>& aRelationIds, RArray<TItemId>& aEventIds )
+        RArray<TItemId>& aRelationIds, RArray<TItemId>& aEventIds, 
+        TBool aUrisRequired, RPointerArray<HBufC>& aRemovedItemUriArray )
 	{
 	if ( !iNamespaceDef )
 		{
@@ -2190,6 +2210,13 @@
 				}
 			
 			objectIds.AppendL( objectId );
+			
+			if( aUrisRequired )
+			    {
+			    // Only objects have uris, so if the are removed by uri, it can be assumed
+			    // that only objects are removed.
+			    aRemovedItemUriArray.AppendL( uri.AllocL() );
+			    }
 			}
 		}
 
@@ -2248,6 +2275,57 @@
 	return objectId;
 	}
 
+HBufC*& CMdSSqlObjectManipulate::SearchObjectUriByIdL( const TItemId aId, 
+        TUint32& aFlags )
+    {
+    _LIT( KMdsSearchObjectUribyId, "SELECT URI,Flags FROM Object%u WHERE NOT Flags&? AND ObjectId=? LIMIT 1;" );
+
+    if ( !iNamespaceDef )
+        {
+        User::Leave( KErrMdEUnknownNamespaceDef );
+        }
+
+    RClauseBuffer commonClauseOne(*this, KMdsSearchObjectUribyId.iTypeLength + KMaxUintValueLength );
+    CleanupClosePushL( commonClauseOne );
+    CMdsClauseBuffer& searchUriClause = commonClauseOne.BufferL();
+
+    searchUriClause.BufferL().Format( KMdsSearchObjectUribyId, iNamespaceDef->GetId() );
+
+    CMdSSqLiteConnection& connection = MMdSDbConnectionPool::GetDefaultDBL();
+
+    TPtrC16 uri;
+    aFlags = 0;
+
+    RRowData varSearch;
+    CleanupClosePushL( varSearch );
+    varSearch.AppendL( TColumn( EMdEObjectFlagNotPresent ) );
+    varSearch.AppendL( TColumn( aId ) );
+
+    RMdsStatement getQuery;
+    CleanupClosePushL( getQuery );
+
+    __LOGQUERY_16( _L("Search object URI by ID:"), 
+            searchUriClause.ConstBufferL(), varSearch);
+    TRAPD( err, connection.ExecuteQueryL( 
+            searchUriClause.ConstBufferL(), getQuery, varSearch ) );
+
+    varSearch.Free();
+    varSearch.Reset();
+    varSearch.AppendL( TColumn( uri ) );
+    varSearch.AppendL( TColumn( aFlags ) );
+    if ( err == KErrNone && connection.NextRowL( getQuery, varSearch ) )
+        {
+        varSearch.Column(0).Get( uri );
+        varSearch.Column(1).Get( aFlags );
+        iUri = uri.AllocL();
+        }
+
+    CleanupStack::PopAndDestroy( 2, &varSearch ); // getQuery, varSearch
+    CleanupStack::PopAndDestroy( &commonClauseOne );
+    
+    return iUri;
+    }
+
 TItemId CMdSSqlObjectManipulate::UpdateObjectL( 
 		CMdSSqLiteConnection& aConnection, CMdCSerializationBuffer& aBuffer )
 	{
@@ -2455,10 +2533,8 @@
 		objectRow.AppendL( TColumn( object.iId ) );
 		}
 
-	TInt queryResult = 0, err;
-    RMdSTransaction transaction( aConnection );
-    CleanupClosePushL( transaction );
-    User::LeaveIfError( transaction.Error() );
+	TInt queryResult( 0 );
+	TInt err( KErrNone );
 
 	if ( KUpdateModObject || KBaseObjectPropertyMod )
 		{
@@ -2509,9 +2585,6 @@
 			}
 		}
 
-    transaction.CommitL();
-    CleanupStack::PopAndDestroy( &transaction );
-
     CleanupStack::PopAndDestroy( uriBuf );
     CleanupStack::PopAndDestroy( &commonClauseTwo );
 	CleanupStack::PopAndDestroy( &commonClauseOne );
Binary file sis/mds/mds_stub.sis has changed
--- a/sis/mds/package.pkg	Fri Mar 12 15:44:28 2010 +0200
+++ b/sis/mds/package.pkg	Mon Mar 15 12:42:24 2010 +0200
@@ -17,7 +17,7 @@
 &EN
 
 ;packet-header (name, uid, major, minor, build, type)
-#{"Metadata System Upgrade"},(0x200009F5), 9, 20, 6, TYPE=SA, RU
+#{"Metadata System Upgrade"},(0x200009F5), 9, 20, 8, TYPE=SA, RU
 
 ; Localised vendor name
 %{"Nokia"}
--- a/sis/mds/package_separate.pkg	Fri Mar 12 15:44:28 2010 +0200
+++ b/sis/mds/package_separate.pkg	Mon Mar 15 12:42:24 2010 +0200
@@ -17,7 +17,7 @@
 &EN
 
 ;packet-header (name, uid, major, minor, build, type)
-#{"Metadata System Upgrade"},(0x200009F5), 9, 20, 6, TYPE=SA, RU
+#{"Metadata System Upgrade"},(0x200009F5), 9, 20, 8, TYPE=SA, RU
 
 ; Localised vendor name
 %{"Nokia"}
--- a/sis/mds/stub.pkg	Fri Mar 12 15:44:28 2010 +0200
+++ b/sis/mds/stub.pkg	Mon Mar 15 12:42:24 2010 +0200
@@ -17,7 +17,7 @@
 &EN
 
 ; Header
-#{"Metadata System"}, (0x200009F5), 9, 20, 6, TYPE=SA
+#{"Metadata System"}, (0x200009F5), 9, 20, 8, TYPE=SA
 
 ; Localised Vendor name
 %{"Nokia"}
--- a/watchdog/src/watchdog.cpp	Fri Mar 12 15:44:28 2010 +0200
+++ b/watchdog/src/watchdog.cpp	Mon Mar 15 12:42:24 2010 +0200
@@ -89,20 +89,35 @@
     PRINT(_L("CWatchdog::ConstructL() - create observer"));
     iShutdownObserver = CWDShutdownObserver::NewL( *this );        
     iSelfShutdownObserver = CWDSelfShutdownObserver::NewL( *this ); 
-    
-    RProcess process;
-    process.SetPriority( EPriorityBackground );
-    process.Close();
     }
 
 void CWatchdog::Start()
-    {
-    
+    {  
     PRINT(_L("CWatchdog::Start()"));
 
-    // Create the server process
+    // Double check that harvester server is not already running
+    TFullName name;
     TInt res( KErrNone );
+        
+    // find Harvester Server
+    TFindProcess findProcess( KHarvesterServerProcess );
+    if ( findProcess.Next(name) == KErrNone )
+        {                
+        PRINT(_L("CWatchdog::Start() - server already running, start listening"));
+        
+        iProcess.Close();
+        res = iProcess.Open(name);
+        if ( res != KErrNone )
+            {
+            PRINT(_L("CWatchdog::Start() - error in starting listening "));
+            return;
+            }
+        iState = EWaitingRendezvous;   
+        SetActive();
+        return;
+        }        
     
+    // Create the server process
     // KNullDesC param causes server's E32Main() to be run
     res = iProcess.Create( KHarvesterServerExe, KNullDesC );
     if ( res != KErrNone )
@@ -189,8 +204,7 @@
               }
             
           default:
-              break;
-              
+              break; 
           
     	}