Automatic merge from PDK_3.0.h CompilerCompatibility
authorWilliam Roberts <williamr@symbian.org>
Sun, 14 Mar 2010 13:12:01 +0000
branchCompilerCompatibility
changeset 10 5851d9e42c5b
parent 8 bb577720afcd (current diff)
parent 7 ca4caa9ba686 (diff)
child 13 a01b4044eb85
Automatic merge from PDK_3.0.h
--- a/connectivitymodules/SeCon/services/csc/bld/sconcsc.mmp	Mon Mar 08 21:44:10 2010 +0000
+++ b/connectivitymodules/SeCon/services/csc/bld/sconcsc.mmp	Sun Mar 14 13:12:01 2010 +0000
@@ -67,7 +67,6 @@
 LIBRARY         hal.lib
 LIBRARY         platformenv.lib
 LIBRARY         charconv.lib
-LIBRARY	        customapi.lib
 LIBRARY	        centralrepository.lib
 LIBRARY         apgrfx.lib
 LIBRARY         apparc.lib
--- a/connectivitymodules/SeCon/services/csc/src/sconversioninfo.cpp	Mon Mar 08 21:44:10 2010 +0000
+++ b/connectivitymodules/SeCon/services/csc/src/sconversioninfo.cpp	Sun Mar 14 13:12:01 2010 +0000
@@ -1,5 +1,5 @@
 /*
-* Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
+* Copyright (c) 2008-2010 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"
@@ -23,8 +23,7 @@
 #include <etel3rdparty.h> // read imsi
 #include <etel.h>
 #include <etelmm.h>
-#include <e32event.h>
-#include <e32svr.h>
+#include <hal.h>
 
 #include "caputils.h"
 #include "debug.h"
@@ -200,13 +199,6 @@
         iProductCode = info.AllocL();
         }
     
-    // screen size
-    TPckgBuf<TScreenInfoV01> siBuf;
-    UserSvr::ScreenInfo(siBuf);
-    TScreenInfoV01& si=siBuf();
-    iScreenSize = si.iScreenSize;
-    
-    
     // read DesktopSync key value
     CRepository* repository(NULL);
     TRAP( iDesktopSyncError, repository = CRepository::NewL( KCRUidDSDCMOConfig ));
@@ -222,7 +214,9 @@
         LOGGER_WRITE_1("Could not create CRepository, err: %d", iDesktopSyncError );
         }
     
-    
+    // screen size
+    HAL::Get(HAL::EDisplayXPixels, iScreenSize.iWidth);
+    HAL::Get(HAL::EDisplayYPixels, iScreenSize.iHeight);
     
     iInfoFetched = ETrue;
     TRACE_FUNC_EXIT;   
--- a/connectivitymodules/SeCon/services/pcd/inc/sconpcdconsts.h	Mon Mar 08 21:44:10 2010 +0000
+++ b/connectivitymodules/SeCon/services/pcd/inc/sconpcdconsts.h	Sun Mar 14 13:12:01 2010 +0000
@@ -42,6 +42,7 @@
 // ConML Status code: No memory
 const TInt KSConCodeNoMemory( 420 );
 
+
 // ConML Status codes in installer errorcases
 const TInt KSConCodeInstErrUserCancel = KSConCodeCancelled; // User cancelled the operation
 const TInt KSConCodeInstErrFileCorrupted = 600; // File is corrupted
@@ -57,6 +58,9 @@
 const TInt KSConCodeInstErrAccessDenied = 608;  // Target location of package is not accessible
 const TInt KSConCodeInstUpgradeError = 609;  // The package is an invalid upgrade
 
+// ConML Status code: 1001...1050 System wide error code
+const TInt KSConCodeFirstSymbianErr( 1000 );
+
 struct SDeviceInfo
 	{
 	TSConMethodName method;
--- a/connectivitymodules/SeCon/services/pcd/inc/sconvideoparser.h	Mon Mar 08 21:44:10 2010 +0000
+++ b/connectivitymodules/SeCon/services/pcd/inc/sconvideoparser.h	Sun Mar 14 13:12:01 2010 +0000
@@ -1,5 +1,5 @@
 /*
-* Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
+* Copyright (c) 2008-2010 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"
@@ -141,9 +141,12 @@
 private: // data
     CVideoPlayerUtility* iVideoUtil;
     CTNEVideoClipInfo*   iVideoClip;
-
+    
     RWsSession          iWsSession;
     CWsScreenDevice*    iScreen;
+    RWindow*            iWindow;
+    RWindowGroup        iRootWindow;
+    
     TRequestStatus*     iCallerStatus;
     CActiveSchedulerWait iWait;
     CSconTimeOut*       iTimeOut;
--- a/connectivitymodules/SeCon/services/pcd/src/sconbrqueue.cpp	Mon Mar 08 21:44:10 2010 +0000
+++ b/connectivitymodules/SeCon/services/pcd/src/sconbrqueue.cpp	Sun Mar 14 13:12:01 2010 +0000
@@ -30,12 +30,10 @@
 //
 CSConBackupRestoreQueue* CSConBackupRestoreQueue::NewL( const TInt aMaxObjectSize, RFs& aFs )
 	{
-	TRACE_FUNC_ENTRY;
 	CSConBackupRestoreQueue* self = new (ELeave) CSConBackupRestoreQueue();
 	CleanupStack::PushL( self );
 	self->ConstructL( aMaxObjectSize, aFs );
 	CleanupStack::Pop( self );
-	TRACE_FUNC_EXIT;
     return self;
 	}
 	
@@ -56,11 +54,9 @@
 //
 void CSConBackupRestoreQueue::ConstructL( const TInt aMaxObjectSize, RFs& aFs )
 	{
-	TRACE_FUNC_ENTRY;
 	iBackupRestore = CSConBackupRestore::NewL( this, aMaxObjectSize, aFs );
 	CActiveScheduler::Add( iBackupRestore );
 	User::LeaveIfError( iTimer.CreateLocal() );
-	TRACE_FUNC_EXIT;
 	}
 	
 // -----------------------------------------------------------------------------
@@ -88,7 +84,6 @@
 //
 void CSConBackupRestoreQueue::StartQueue()	
 	{
-	TRACE_FUNC_ENTRY;
 	if( IsActive() )
 		{
 		Cancel();
@@ -96,7 +91,6 @@
 		
 	iTimer.After( iStatus, KSConTimerValue );
 	SetActive();
-	TRACE_FUNC_EXIT;
 	}
 	
 // -----------------------------------------------------------------------------
@@ -106,9 +100,7 @@
 //
 void CSConBackupRestoreQueue::StopQueue()	
 	{
-	TRACE_FUNC_ENTRY;
 	iTimer.Cancel();
-	TRACE_FUNC_EXIT;
 	}
 
 // -----------------------------------------------------------------------------
@@ -139,7 +131,6 @@
 		}
 
 	ret = iQueue.InsertInOrder( aNewTask, CSConTaskQueue::Compare );
-	LOGGER_WRITE_1( "CSConBackupRestoreQueue::AddNewTask() : returned %d", ret );
 	return ret;
 	}
 
@@ -189,7 +180,6 @@
 //
 void CSConBackupRestoreQueue::QueueAddress( CSConInstallerQueue*& aTaskQueue )
 	{
-	TRACE_FUNC;
 	iInstQueueAddress = aTaskQueue;
 	}
 
@@ -253,14 +243,11 @@
 //
 void CSConBackupRestoreQueue::RunL()
 	{
-	TRACE_FUNC_ENTRY;
-	LOGGER_WRITE_1( "There are still %d tasks in this queue", iQueue.Count() );
 	if( iQueue.Count() > 0 )
 		{
 		PollQueue();
 		StartQueue();
 		}
-	TRACE_FUNC_EXIT;
 	}
 
 // End of file
--- a/connectivitymodules/SeCon/services/pcd/src/sconpcdutility.cpp	Mon Mar 08 21:44:10 2010 +0000
+++ b/connectivitymodules/SeCon/services/pcd/src/sconpcdutility.cpp	Sun Mar 14 13:12:01 2010 +0000
@@ -21,7 +21,7 @@
 #include <swi/sisregistrysession.h>
 #include <swi/sisregistrypackage.h>
 #include <stringresourcereader.h>
-#include <WidgetRegistryClient.h>
+#include <widgetregistryclient.h>
 #include <javaregistryincludes.h>
 #include <appversion.h>
 #include <mmf/common/mmfcontrollerpluginresolver.h>
--- a/connectivitymodules/SeCon/services/pcd/src/sconqueue.cpp	Mon Mar 08 21:44:10 2010 +0000
+++ b/connectivitymodules/SeCon/services/pcd/src/sconqueue.cpp	Sun Mar 14 13:12:01 2010 +0000
@@ -265,7 +265,17 @@
             
             default :
                 iQueue[index]->SetCompleteValue( complete );
-                progress = KSConCodeConflict;
+                if ( aError < KErrNone && aError >= KErrCorruptSurrogateFound )
+                    {
+                    // aError is always negative
+                    //  -> returned errorcode is from KSConCodeFirstSymbianErr...n
+                    progress = KSConCodeFirstSymbianErr - aError;
+                    }
+                else
+                    {
+                    progress = KSConCodeConflict;
+                    }
+                
                 break;
             }
             
--- a/connectivitymodules/SeCon/services/pcd/src/sconvideoparser.cpp	Mon Mar 08 21:44:10 2010 +0000
+++ b/connectivitymodules/SeCon/services/pcd/src/sconvideoparser.cpp	Sun Mar 14 13:12:01 2010 +0000
@@ -1,5 +1,5 @@
 /*
-* Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
+* Copyright (c) 2008-2010 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"
@@ -57,6 +57,13 @@
         iVideoUtil->Close();
         }
     delete iVideoUtil;
+    
+    if ( iWindow )
+        {
+        iWindow->Close();
+        }
+    delete iWindow;
+    iRootWindow.Close();
     delete iScreen;
     iWsSession.Close();
     
@@ -90,26 +97,16 @@
     User::LeaveIfError( iWsSession.Connect() );
     
     iScreen = new(ELeave) CWsScreenDevice( iWsSession );
-    iScreen->Construct();
-    
-    RWindowGroup wg( iWsSession );
-    User::LeaveIfError( wg.Construct(reinterpret_cast<TUint32>(&wg), EFalse) );
-    CleanupClosePushL( wg );
+    User::LeaveIfError( iScreen->Construct() );
     
-    CWindowGc* gc;
-    User::LeaveIfError( iScreen->CreateContext(gc) );
-    CleanupStack::PushL(gc);
+    iRootWindow = RWindowGroup(iWsSession);
+    User::LeaveIfError( iRootWindow.Construct(reinterpret_cast<TUint32>(&iWsSession), EFalse) );
     
-    RWindow window( iWsSession );
-    User::LeaveIfError( window.Construct(wg, reinterpret_cast<TUint32>(&wg) + 1) );
-    CleanupClosePushL( window );
+    iWindow = new(ELeave) RWindow( iWsSession );
+    User::LeaveIfError( iWindow->Construct(iRootWindow, reinterpret_cast<TUint32>(&iRootWindow) + 1) );
     
     TRect temp(0,0,320,240); // dummy parameter
-    iVideoUtil = CVideoPlayerUtility::NewL(*this, EMdaPriorityNormal, EMdaPriorityPreferenceNone, iWsSession, *(iScreen), window, temp, temp);
-    
-    CleanupStack::PopAndDestroy( &window );
-    CleanupStack::PopAndDestroy( gc );
-    CleanupStack::PopAndDestroy( &wg );
+    iVideoUtil = CVideoPlayerUtility::NewL(*this, EMdaPriorityNormal, EMdaPriorityPreferenceNone, iWsSession, *iScreen, *iWindow, temp, temp);
     
     iTimeOut = CSconTimeOut::NewL( *this );
     
--- a/mtpdataproviders/mtpfileandfolderdp/inc/cmtpfiledp.h	Mon Mar 08 21:44:10 2010 +0000
+++ b/mtpdataproviders/mtpfileandfolderdp/inc/cmtpfiledp.h	Sun Mar 14 13:12:01 2010 +0000
@@ -27,6 +27,7 @@
 #include "mtpdebug.h"
 #include "rmtpfiledpsingletons.h"
 #include "rmtpdpsingletons.h"
+#include "rmtpframework.h"
 
 class CMTPFileDpExclusionMgr;
 class CMTPFSEnumerator;
@@ -117,6 +118,8 @@
     
     TInt								iActiveProcessor;
     TBool								iActiveProcessorRemoved;
+    
+	RMTPFramework               		iSingletons;
 
     };
     
--- a/mtpdataproviders/mtpfileandfolderdp/src/cmtpfiledp.cpp	Mon Mar 08 21:44:10 2010 +0000
+++ b/mtpdataproviders/mtpfileandfolderdp/src/cmtpfiledp.cpp	Sun Mar 14 13:12:01 2010 +0000
@@ -28,6 +28,7 @@
 #include "mtpfiledpconst.h"
 #include "mtpfiledppanic.h"
 #include "mtpfiledpprocessor.h"
+#include "cmtpdataprovidercontroller.h"
 
 // Class constants
 static const TInt KArrayGranularity = 3;
@@ -63,6 +64,7 @@
     iActiveProcessors.Close();
     iDpSingletons.Close();
 	iFileDPSingletons.Close();
+	iSingletons.Close();
     delete iFileEnumerator;
     delete iExclusionMgr;
     __FLOG(_L8("~CMTPFileDataProvider - Exit"));
@@ -135,12 +137,12 @@
     {
     __FLOG(_L8("StartObjectEnumerationL - Entry"));
 
-    iExclusionMgr->AppendFormatExclusionListL();
-    iDpSingletons.MTPUtility().FormatExtensionMapping();
     iPendingEnumerations.AppendL(aStorageId);
     if (iPendingEnumerations.Count() == 1)
         {
-        iFileEnumerator->StartL(iPendingEnumerations[KActiveEnumeration]);
+		CMTPDataProviderController& dpController(iSingletons.DpController());
+		TBool bOnlyScanRoot = ( (dpController.EnumerateState() == CMTPDataProviderController::EEnumeratingFrameworkObjects) && (dpController.NeedEnumeratingPhase2()) );
+		iFileEnumerator->StartL(iPendingEnumerations[KActiveEnumeration], bOnlyScanRoot);
         }
     __FLOG(_L8("StartObjectEnumerationL - Exit"));
     }
@@ -148,6 +150,8 @@
 void CMTPFileDataProvider::StartStorageEnumerationL()
     {
     __FLOG(_L8("StartStorageEnumerationL - Entry"));
+    iExclusionMgr->AppendFormatExclusionListL();
+    iDpSingletons.MTPUtility().FormatExtensionMapping();
     Framework().StorageEnumerationCompleteL();
     __FLOG(_L8("StartStorageEnumerationL - Exit"));
     }
@@ -220,7 +224,9 @@
     iPendingEnumerations.Remove(KActiveEnumeration);
     if (iPendingEnumerations.Count())
         {
-        iFileEnumerator->StartL(iPendingEnumerations[KActiveEnumeration]);
+		CMTPDataProviderController& dpController(iSingletons.DpController());
+		TBool bOnlyScanRoot = ( (dpController.EnumerateState() == CMTPDataProviderController::EEnumeratingFrameworkObjects) && (dpController.NeedEnumeratingPhase2()) );
+        iFileEnumerator->StartL(iPendingEnumerations[KActiveEnumeration], bOnlyScanRoot);
         }
     __FLOG(_L8("HandleEnumerationCompletedL - Exit"));
     }
@@ -246,6 +252,7 @@
     __FLOG(_L8("ConstructL - Entry"));
   	iDpSingletons.OpenL(Framework());
   	iFileDPSingletons.OpenL(Framework());
+  	iSingletons.OpenL();
   	
   	iExclusionMgr = CMTPFileDpExclusionMgr::NewL(Framework());
   	iDpSingletons.SetExclusionMgrL(*iExclusionMgr);
--- a/mtpdataproviders/mtpimagedp/src/cmtpimagedpdeleteobject.cpp	Mon Mar 08 21:44:10 2010 +0000
+++ b/mtpdataproviders/mtpimagedp/src/cmtpimagedpdeleteobject.cpp	Sun Mar 14 13:12:01 2010 +0000
@@ -261,6 +261,15 @@
     {
     __FLOG(_L8(">> CMTPImageDpDeleteObject::StartL"));
     
+    if(iCancelled)
+        {
+        __FLOG(_L8("Cancell the delete"));
+        CMTPRequestProcessor::SendResponseL(EMTPRespCodeTransactionCancelled);
+        iObjectsToDelete.Reset();
+        iCancelled = EFalse;
+        return;
+        }
+    
     TInt numObjectsToDelete = iObjectsToDelete.Count();
 
     if ( numObjectsToDelete > 0 )
--- a/mtpfws/mtpfw/daemon/server/src/cmtpshutdown.cpp	Mon Mar 08 21:44:10 2010 +0000
+++ b/mtpfws/mtpfw/daemon/server/src/cmtpshutdown.cpp	Sun Mar 14 13:12:01 2010 +0000
@@ -54,7 +54,7 @@
     
 void CMTPShutdown::RunL()
     {
-    if ( iSingletons.DpController().EnumerateState() != CMTPDataProviderController::EEnumerated )
+    if ( iSingletons.DpController().EnumerateState() != CMTPDataProviderController::EEnumeratedFulllyCompleted )
         {
         Start();
         }
--- a/mtpfws/mtpfw/dataproviders/devdp/inc/cmtpgetnumobjects.h	Mon Mar 08 21:44:10 2010 +0000
+++ b/mtpfws/mtpfw/dataproviders/devdp/inc/cmtpgetnumobjects.h	Sun Mar 14 13:12:01 2010 +0000
@@ -24,9 +24,11 @@
 
 #include "cmtprequestprocessor.h"
 #include "rmtpframework.h"
+#include "rmtpdevicedpsingletons.h"
 
 class MMTPObjectMgr;
 
+
 /** 
 Implements device data provider GetNumObjects request processor
 @internalComponent
@@ -55,6 +57,8 @@
 private:
 
 	RMTPFramework iSingletons;
+
+    RMTPDeviceDpSingletons              iDevDpSingletons;
 	};
 	
 #endif // CMTPGETNUMOBJECTS_H
--- a/mtpfws/mtpfw/dataproviders/devdp/inc/cmtpstoragewatcher.h	Mon Mar 08 21:44:10 2010 +0000
+++ b/mtpfws/mtpfw/dataproviders/devdp/inc/cmtpstoragewatcher.h	Sun Mar 14 13:12:01 2010 +0000
@@ -27,9 +27,11 @@
 #include "mtpdebug.h"
 #include "rmtpframework.h"
 #include "rmtpdpsingletons.h"
+#include "rmtpdevicedpsingletons.h"
 
 class MMTPDataProviderFramework;
 
+
 /** 
 Implements the MTP device data provider system storage watcher.
 @internalComponent
@@ -119,6 +121,8 @@
     */
     RMTPDpSingletons				iDpSingletons;
     
+    RMTPDeviceDpSingletons          iDevDpSingletons;
+    
 private: // Not owned.
 
     MMTPDataProviderFramework&      iFramework;
--- a/mtpfws/mtpfw/dataproviders/devdp/inc/mtpdevdppanic.h	Mon Mar 08 21:44:10 2010 +0000
+++ b/mtpfws/mtpfw/dataproviders/devdp/inc/mtpdevdppanic.h	Sun Mar 14 13:12:01 2010 +0000
@@ -35,6 +35,7 @@
     EMTPDevDpInvalidRequest             = 7,
     EMTPDevDpUnknownDeviceProperty      = 8,
     EMTPDevDpUnknownServiceID           = 9,
+    EMTPDevDpObjectNull					= 10,
 
     };
 
--- a/mtpfws/mtpfw/dataproviders/devdp/inc/rmtpdevicedpsingletons.h	Mon Mar 08 21:44:10 2010 +0000
+++ b/mtpfws/mtpfw/dataproviders/devdp/inc/rmtpdevicedpsingletons.h	Sun Mar 14 13:12:01 2010 +0000
@@ -45,6 +45,8 @@
     CMTPDeviceDataStore& DeviceDataStore();
     CMTPDeviceDpConfigMgr& ConfigMgr();
     
+    RArray<TUint>& PendingStorages();
+    
 private:
     
     /**
@@ -79,6 +81,11 @@
         The device dp config manager.
         */
         CMTPDeviceDpConfigMgr*	iConfigMgr;
+        
+        /*
+         * The pending storageids which is not enumerated.
+         */
+        RArray<TUint>         iPendingStorages;
     };
     
 private: // Owned
--- a/mtpfws/mtpfw/dataproviders/devdp/src/cmtpgetnumobjects.cpp	Mon Mar 08 21:44:10 2010 +0000
+++ b/mtpfws/mtpfw/dataproviders/devdp/src/cmtpgetnumobjects.cpp	Sun Mar 14 13:12:01 2010 +0000
@@ -18,6 +18,7 @@
 #include <mtp/mmtpobjectmgr.h>
 #include <mtp/mmtpdataprovider.h>
 #include <mtp/cmtpdataproviderplugin.h>
+#include <mtp/cmtpobjectmetadata.h>
 
 #include "cmtpdataprovidercontroller.h"
 #include "cmtpdataprovider.h"
@@ -26,6 +27,7 @@
 #include "mtpdevicedpconst.h"
 #include "mtpdevdppanic.h"
 
+
 /**
 Verification data for GetNumObjects request
 */
@@ -57,6 +59,7 @@
 */	
 CMTPGetNumObjects::~CMTPGetNumObjects()
 	{	
+	iDevDpSingletons.Close();
     iSingletons.Close();
 	}
 /**
@@ -74,19 +77,51 @@
 void CMTPGetNumObjects::ConstructL()
     {
     iSingletons.OpenL();
+    iDevDpSingletons.OpenL(iFramework);
     }
 
 TMTPResponseCode CMTPGetNumObjects::CheckRequestL()
 	{
 	TMTPResponseCode responseCode = CMTPRequestProcessor::CheckRequestL();
-	if(responseCode == EMTPRespCodeOK)
+	if(responseCode != EMTPRespCodeOK)
+		{
+		return responseCode;	
+		}
+	
+	TUint32 formatCode = Request().Uint32(TMTPTypeRequest::ERequestParameter2); 
+	if(formatCode != 0 && !IsSupportedFormatL(formatCode))
+		{
+		return EMTPRespCodeInvalidObjectFormatCode;
+		}
+	
+	if(iSingletons.DpController().EnumerateState() != CMTPDataProviderController::EEnumeratedFulllyCompleted)
 		{
-		TUint32 formatCode = Request().Uint32(TMTPTypeRequest::ERequestParameter2);
-		if(formatCode != 0 && !IsSupportedFormatL(formatCode))
+		TUint storageID = Request().Uint32(TMTPTypeRequest::ERequestParameter1);
+		TUint handle = Request().Uint32(TMTPTypeRequest::ERequestParameter3);
+		if(iDevDpSingletons.PendingStorages().FindInOrder(storageID) != KErrNotFound)
+			{
+			responseCode = EMTPRespCodeDeviceBusy;
+			}
+		else if( (handle != KMTPHandleNone) && (handle != KMTPHandleAll)  )
 			{
-			responseCode = EMTPRespCodeInvalidObjectFormatCode;
+			CMTPObjectMetaData* meta = iRequestChecker->GetObjectInfo(handle);
+			__ASSERT_DEBUG(meta, Panic(EMTPDevDpObjectNull));
+			
+			if( meta->Uint(CMTPObjectMetaData::EFormatCode) == EMTPFormatCodeAssociation )
+				{
+				responseCode = EMTPRespCodeDeviceBusy;
+				}
+			}
+		else if(EMTPFormatCodeUndefined == formatCode)
+			{
+			responseCode = EMTPRespCodeDeviceBusy;
 			}
 		}
+	else if(iDevDpSingletons.PendingStorages().Count() > 0)
+		{
+		iDevDpSingletons.PendingStorages().Close();
+		}
+	
 	return responseCode;	
 	}
 	
--- a/mtpfws/mtpfw/dataproviders/devdp/src/cmtpopensession.cpp	Mon Mar 08 21:44:10 2010 +0000
+++ b/mtpfws/mtpfw/dataproviders/devdp/src/cmtpopensession.cpp	Sun Mar 14 13:12:01 2010 +0000
@@ -83,7 +83,7 @@
 void CMTPOpenSession::ServiceL()    
     {
     iSingletons.DpController().WaitForEnumerationComplete();
-    if(iSingletons.DpController().EnumerateState() != CMTPDataProviderController::EEnumerated)
+    if(iSingletons.DpController().EnumerateState() < CMTPDataProviderController::EEnumeratingPhaseOneDone)
     	{
     	SendResponseL(EMTPRespCodeDeviceBusy);
     	}
--- a/mtpfws/mtpfw/dataproviders/devdp/src/cmtpstoragewatcher.cpp	Mon Mar 08 21:44:10 2010 +0000
+++ b/mtpfws/mtpfw/dataproviders/devdp/src/cmtpstoragewatcher.cpp	Sun Mar 14 13:12:01 2010 +0000
@@ -24,7 +24,6 @@
 #include "cmtpstoragemgr.h"
 #include "cmtpobjectmgr.h"
 #include "cmtpstoragewatcher.h"
-#include "rmtpdevicedpsingletons.h"
 #include "cmtpdevicedpconfigmgr.h"
 
 
@@ -61,6 +60,7 @@
     iDpSingletons.Close();
     iDrivesExcluded.Close();
     iFrameworkSingletons.Close();
+    iDevDpSingletons.Close();
     __FLOG(_L8("~CMTPStorageWatcher - Exit"));
     __FLOG_CLOSE;
     }
@@ -278,13 +278,10 @@
     iFrameworkSingletons.OpenL();
     iFrameworkSingletons.FrameworkConfig().GetValueL(CMTPFrameworkConfig::ELogicalStorageIdsAllocationEnable, iAllocateLogicalStorages);
     
-    RMTPDeviceDpSingletons devSingletons;
-    devSingletons.OpenL(iFramework);
-    CleanupClosePushL(devSingletons);
-    
     iDpSingletons.OpenL(iFramework);
-    iFolderExclusionList = devSingletons.ConfigMgr().GetArrayValueL(CMTPDeviceDpConfigMgr::EFolderExclusionList); 
-    CleanupStack::PopAndDestroy(&devSingletons);
+    iDevDpSingletons.OpenL(iFramework);
+    iFolderExclusionList = iDevDpSingletons.ConfigMgr().GetArrayValueL(CMTPDeviceDpConfigMgr::EFolderExclusionList); 
+
     __FLOG(_L8("ConstructL - Exit"));
     }
     
@@ -475,6 +472,11 @@
         {
         TMTPNotificationParamsStorageChange params = {physical};
         iFrameworkSingletons.DpController().NotifyDataProvidersL(EMTPStorageAdded, static_cast<TAny*>(&params));
+        
+        if(iFrameworkSingletons.DpController().EnumerateState() == CMTPDataProviderController::EEnumeratingSubDirFiles)
+			{
+			iDevDpSingletons.PendingStorages().InsertInOrder(logical);
+			}
         }
 
     // Notify any connected Initiator(s).
@@ -515,6 +517,12 @@
     TMTPNotificationParamsStorageChange params = {physical};
     iFrameworkSingletons.DpController().NotifyDataProvidersL(EMTPStorageRemoved, static_cast<TAny*>(&params));
 
+    TInt index = iDevDpSingletons.PendingStorages().FindInOrder( logical);
+	if(KErrNotFound != index)
+		{
+		iDevDpSingletons.PendingStorages().Remove(index);
+		}
+        	
     // Notify any connected Initiator(s).
     if (iAllocateLogicalStorages)
         {
--- a/mtpfws/mtpfw/dataproviders/devdp/src/rmtpdevicedpsingletons.cpp	Mon Mar 08 21:44:10 2010 +0000
+++ b/mtpfws/mtpfw/dataproviders/devdp/src/rmtpdevicedpsingletons.cpp	Sun Mar 14 13:12:01 2010 +0000
@@ -141,6 +141,7 @@
     __FLOG(_L8("CSingletons::~CSingletons - Entry"));
     delete iConfigMgr;
     delete iDeviceDataStore;
+    iPendingStorages.Close();
     __FLOG(_L8("CSingletons::~CSingletons - Exit"));
     __FLOG_CLOSE;
     }
@@ -154,3 +155,11 @@
     __FLOG(_L8("CSingletons::ConstructL - Exit"));
     }
 
+RArray<TUint>& RMTPDeviceDpSingletons::PendingStorages()
+	{
+    __FLOG(_L8("PendingStorages - Entry"));
+    __ASSERT_DEBUG(iSingletons, User::Invariant());
+    __FLOG(_L8("PendingStorages - Exit"));
+    return iSingletons->iPendingStorages;
+	}
+
--- a/mtpfws/mtpfw/dataproviders/dputility/inc/cmtpfsenumerator.h	Mon Mar 08 21:44:10 2010 +0000
+++ b/mtpfws/mtpfw/dataproviders/dputility/inc/cmtpfsenumerator.h	Sun Mar 14 13:12:01 2010 +0000
@@ -46,7 +46,7 @@
     IMPORT_C static CMTPFSEnumerator* NewL(MMTPDataProviderFramework& aFramework, CMTPFSExclusionMgr& aExclusionMgr, MMTPEnumerationCallback& aCallback, TInt aProcessLimit);
     IMPORT_C ~CMTPFSEnumerator();
 
-	IMPORT_C void StartL(TUint32 aStorageId);	
+	IMPORT_C void StartL(TUint32 aStorageId, TBool aOnlyRoot = EFalse);	
 	
 private:
 	//from CActive
@@ -64,10 +64,11 @@
 	void ScanNextStorageL();
 	void ScanNextSubdirL();
 	void ProcessEntriesL();
-	void AddEntryL(const TDesC& aPath, TUint32 &aHandle, TMTPFormatCode format, TUint32 aDPId, const TEntry& aEntry);
-	void AddFileEntryForOtherDpL(const TDesC& aPath, TUint32 &aHandle, TMTPFormatCode format, TUint32 aDPId, const TEntry& aEntry);
+	void AddEntryL(const TDesC& aPath, TUint32 &aHandle, TMTPFormatCode format, TUint32 aDPId, const TEntry& aEntry, TUint32 aStorageId, TUint32 aParentHandle);
+	void AddFileEntryForOtherDpL(const TDesC& aPath, TUint32 &aHandle, TMTPFormatCode format, TUint32 aDPId, const TEntry& aEntry, TUint32 aStorageId, TUint32 aParentHandle);
 	void NotifyObjectAddToDP(const TUint32 aHandle,const TUint DpId);
 	
+	
 private: 
 	// Owned
 	MMTPDataProviderFramework&  iFramework;
@@ -88,6 +89,10 @@
 	TUint						iDpID;
 	RMTPFramework               iSingletons;
 	TBool                       iSkipCurrentStorage;
+	
+	TBool						iIsFileEnumerator;
+	TBool						iOnlyScanRoot;
+	TInt						iNumOfFoldersAndFiles;
 	/**
     FLOGGER debug trace member variable.
     */
--- a/mtpfws/mtpfw/dataproviders/dputility/inc/cmtpknowledgehandler.h	Mon Mar 08 21:44:10 2010 +0000
+++ b/mtpfws/mtpfw/dataproviders/dputility/inc/cmtpknowledgehandler.h	Sun Mar 14 13:12:01 2010 +0000
@@ -31,6 +31,93 @@
 class CMTPTypeFile;
 class CRepository;
 
+NONSHARABLE_CLASS(CKnowledgeObject) : public CBase
+	{
+public:
+	static CKnowledgeObject* NewL(CRepository& aRepository);
+	~CKnowledgeObject();
+	
+	/**
+	Get the value from the central repository
+	@leave One of the system wide error codes, if repository get value fail
+	*/
+	void LoadL();
+	/**
+	Set the cached value to the central repository
+	@leave One of the system wide error codes, if repository set value fail
+	*/
+	void CommitL();
+	/** 
+	Clear the cached knowledge object property values 
+	*/
+	void Clear();
+	/**
+	Update cached DateModified to current Device time
+	*/
+	void RefreshDateModifed();
+	/**
+	Check if the cached object property values are aligned with repository
+	*/
+	TBool IsDirty() {return iDirty;};
+	
+	//Get method for all prop
+	TUint64 Size(){return iKnowledgeObjectSize;};
+	TDesC& DateModified(){return iDateModified;};
+	TDesC& Name(){return iName;};
+	const TMTPTypeUint128& LastAuthorProxyID() {return iLastAuthorProxyID;};
+	
+	//Set method for all prop
+	void SetSize(TUint64 aSize);
+	void SetDateModified(const TDesC& aDateModified);
+	void SetName(const TDesC& aName);
+	void SetLastAuthorProxyID(TUint64 aHigh, TUint64 aLow);
+	
+private:
+	//key of central repository
+	enum TMTPKnowledgeStoreKeyNum
+		{
+		ESize 				= 0x10001, 
+		EDateModified 		= 0x10002,
+		EName 				= 0x10003,
+		ELastAuthorProxyID 	= 0x10004
+		};
+
+	// Bit flag of the property
+	enum TMTPKnowledgeBitFlag
+		{
+		EBitFlagNone 				= 0x00,
+		EBitFlagSize 				= 0x01, 
+		EBitFlagDateModified 		= 0x02,
+		EBitFlagName 				= 0x04,
+		EBitFlagLastAuthorProxyID 	= 0x08,
+		EBitFlagAll 				= 0x0F
+		};
+
+private:
+	CKnowledgeObject(CRepository& aRepository);
+	
+	void ConstructL();
+	
+	TMTPResponseCode SetColumnType128Value(TMTPKnowledgeStoreKeyNum aColumnNum, TMTPTypeUint128& aNewData);
+	
+	CRepository&     	iRepository;
+
+	// The bit wise value of TMTPKnowledgeBitFlag 
+	// to state which property is not aligned with repository
+	TUint				iDirty;
+	
+	TUint64          	iKnowledgeObjectSize; 
+	RBuf             	iDateModified;
+	RBuf             	iName;
+	TMTPTypeUint128  	iLastAuthorProxyID;
+	
+	/**
+	FLOGGER debug trace member variable.
+	*/
+	__FLOG_DECLARATION_MEMBER_MUTABLE;
+	
+	};
+
 /** 
 Controls access to the knowledge object.
 @internalComponent
@@ -68,58 +155,24 @@
 	void RollBack();
 	void ReleaseObjectBuffer();	
 
-	enum TCacheStatus
-		{
-		EOK,
-		EDirty,
-		EDeleted
-		};
-	//key of central repository
-	enum TMTPKnowledgeStoreKeyNum
-		{
-		ESize = 0x10001, 
-		EDateModified = 0x10002,
-		EName = 0x10003,
-		ELastAuthorProxyID = 0x10004
-		};
 	
-	TMTPResponseCode SetColumnType128Value(TMTPKnowledgeStoreKeyNum aColumnNum, TMTPTypeUint128& aNewData);
-
 private:
 	CMTPKnowledgeHandler(MMTPDataProviderFramework& aFramework,TUint16 aFormatCode, CRepository& aReposotry, const TDesC& aKwgSuid);
 	void ConstructL();
 	
 	/**
-	Get the value from the central repository
-	@leave One of the system wide error codes, if repository get value fail
-	*/
-	void LoadKnowledgeObjPropertiesL();
-	/**
-	Cleanup Item operation for drop all knowledge properties
-	*/
-	static void DropCacheWrapper(TAny* aObject);
-	void DropKnowledgeObjPropertiesCache();
-	/**
 	Helper for GetObjectInfo request handling
 	*/
 	void BuildObjectInfoL(CMTPTypeObjectInfo& aObjectInfo) const;
-	/**
-	Delete knowledge object properties and content
-	@leave One of the system wide error codes, if repository set value fail
-	*/
-	void DeleteAllObjectPropertiesL();
 	
 private:
 	MMTPDataProviderFramework&  iFramework;
 	CRepository&                iRepository;
 	TUint32                     iStorageID;
 	TUint16                     iKnowledgeFormatCode;
-	TUint64                     iKnowledgeObjectSize; 
-	HBufC*                      iDateModified;
-	HBufC*                      iName;
-	TMTPTypeUint128             iLastAuthorProxyID;
-	TCacheStatus                iCacheStatus;
-	TCacheStatus                iCacheStatusFlag;
+	
+	CKnowledgeObject*			iCachedKnowledgeObject;
+	
 	TFileName                   iKnowObjFileName;
 	TFileName                   iKnowObjSwpFileName;
 	// Knowledge object content file
--- a/mtpfws/mtpfw/dataproviders/dputility/inc/cmtprequestprocessor.h	Mon Mar 08 21:44:10 2010 +0000
+++ b/mtpfws/mtpfw/dataproviders/dputility/inc/cmtprequestprocessor.h	Sun Mar 14 13:12:01 2010 +0000
@@ -182,7 +182,7 @@
 	const TMTPTypeRequest*		    iRequest;			//the pending requst object
 	MMTPConnection&				    iConnection;		//the connection from which the request comes
 	TMTPTypeResponse			    iResponse;			//the response object to send to the initiator
-	TBool						    iCancelled;			//indicates whether the data phase (send/receive) has been cancelled
+	TBool						    iCancelled;			//indicates whether this request has been cancelled
 	CMTPRequestChecker*		    	iRequestChecker;	//a utility class providing generic request verification service
 	TInt					    	iElementCount;		//number of verification elements used for request checker
 	const TMTPRequestElementInfo*	iElements;	 		//pointer to an array of verification elements
--- a/mtpfws/mtpfw/dataproviders/dputility/inc/mtpsvcdpconst.h	Mon Mar 08 21:44:10 2010 +0000
+++ b/mtpfws/mtpfw/dataproviders/dputility/inc/mtpsvcdpconst.h	Sun Mar 14 13:12:01 2010 +0000
@@ -230,6 +230,7 @@
 const TUint32 KMTPServicePropertyAll = 0x00000000;
 
 const TUint32 KMTPUnInitialized32 = 0xFFFFFFFF;
+const TUint64 KMTPUnInitialized64 = ~0; //MAKE_TINT64(KMTPUnInitialized32, KMTPUnInitialized32);
 const TUint32 KMaxSUIDLength = 50;
 const TUint64 KObjectSizeNotAvaiable = ~0;
 const TUint32 KLongStringMaxLength = 0x1000;
--- a/mtpfws/mtpfw/dataproviders/dputility/src/cmtpfsenumerator.cpp	Mon Mar 08 21:44:10 2010 +0000
+++ b/mtpfws/mtpfw/dataproviders/dputility/src/cmtpfsenumerator.cpp	Sun Mar 14 13:12:01 2010 +0000
@@ -27,10 +27,18 @@
 #include "mmtpenumerationcallback.h"
 #include "cmtpdataprovidercontroller.h"
 #include "cmtpdataprovider.h"
+#include "mtpframeworkconst.h"
+
 
 // Class constants.
 __FLOG_STMT(_LIT8(KComponent,"FSEnumerator");)
 
+const TUint KMTPMaxFullFileName = 259;
+/*
+ * 
+ */
+#define KMAX_FILECOUNT_ENUMERATINGPHASE1 5000
+
 /**
  * the files should not be owned by any dp. 
  */
@@ -86,9 +94,13 @@
 Kick off the enumeration on the specified storage
 @param aStorageId storage to be enumerated
 */
-EXPORT_C void CMTPFSEnumerator::StartL(TUint32 aStorageId)
+EXPORT_C void CMTPFSEnumerator::StartL(TUint32 aStorageId, TBool aOnlyRoot)
 	{
 	__ASSERT_DEBUG(!IsActive(), User::Invariant());
+	iNumOfFoldersAndFiles = 0;
+	iOnlyScanRoot = aOnlyRoot;
+	__FLOG_VA((_L8("iOnlyScanRoot == %d "), iOnlyScanRoot));
+	
 	MMTPStorageMgr& storageMgr(iFramework.StorageMgr());
 	if (aStorageId == KMTPStorageAll)
 	    {
@@ -157,6 +169,11 @@
 		}
 	else
 		{
+		if((!iIsFileEnumerator) &&(iNumOfFoldersAndFiles > KMAX_FILECOUNT_ENUMERATINGPHASE1))
+			{
+			iSingletons.DpController().SetNeedEnumeratingPhase2(ETrue);
+			}
+		
 		iCallback.NotifyEnumerationCompleteL(iStorageId, KErrNone);
 		
 		TMTPTypeEvent event;
@@ -248,7 +265,12 @@
 		{
 		// We are done
 		iStorages.Reset();
+		if((!iIsFileEnumerator) &&(iNumOfFoldersAndFiles > KMAX_FILECOUNT_ENUMERATINGPHASE1))
+			{
+			iSingletons.DpController().SetNeedEnumeratingPhase2(ETrue);
+			}
 		iCallback.NotifyEnumerationCompleteL(iStorageId, KErrNone);
+		
 		}
 	__FLOG_VA(_L8("ScanNextStorageL - exit"));
 	}
@@ -283,7 +305,7 @@
 	__FLOG_VA(_L8("ScanNextL - entry"));
 	TInt count = iDirStack.Count();
 	
-	if (count == 0)
+	if ((count == 0) || iOnlyScanRoot )
 		{
 		// No more directories on the stack, try the next storage
 		ScanNextStorageL();
@@ -372,6 +394,7 @@
 	__FLOG_VA((_L8("RunError - entry with error %d"), aError));
 	 if(!iFramework.StorageMgr().ValidStorageId(iStorages[0]))
 		 {
+		 __FLOG_VA((_L8("Invalid StorageID = %d"),iStorages[0] ));
 		 if (iStorages.Count()>1)
 			 {
 			 //Not necessary to process any entry on the storage, since the storage removed.
@@ -411,6 +434,7 @@
 	iDpSingletons.OpenL(iFramework);
 	iObject = CMTPObjectMetaData::NewL();	
 	iDpID = iFramework.DataProviderId();
+	iIsFileEnumerator = (KMTPFileDPID == iDpID);
 	}
 
 /**
@@ -419,8 +443,6 @@
 
 void CMTPFSEnumerator::ProcessEntriesL()
 	{
-	const TUint KMTPMaxFullFileName = 259;
-
 	TBuf<KMTPMaxFullFileName> path = iPath.DriveAndPath();
 	
 	// Start looping through entries at where we left off
@@ -429,7 +451,11 @@
 	count = Min(count, iProcessLimit);
 	iFirstUnprocessed += count;		
 	
-		
+	if(!iIsFileEnumerator)
+		{
+		iNumOfFoldersAndFiles +=count;
+		}	
+	
 	for (TInt i = (iFirstUnprocessed - count); i < iFirstUnprocessed; ++i)
 		{
 		const TEntry& entry = iEntries[i];
@@ -475,14 +501,14 @@
 				path.Append('\\');
 				++len;
 				format = EMTPFormatCodeAssociation;
-				AddEntryL(path, handle, format, iDpID, entry);
+				AddEntryL(path, handle, format, iDpID, entry, iStorages[0], iParentHandle);
 				iDirStack.AppendL(entry);
 				}
 			}
 		else if ( iExclusionMgr.IsFileAcceptedL(path,iStorages[0]) )
 			{
 			format = EMTPFormatCodeUndefined;
-			AddEntryL(path, handle, format, iDpID, entry);
+			AddEntryL(path, handle, format, iDpID, entry, iStorages[0], iParentHandle);
 			}
 		else if ( parse.ExtPresent() )
 		    {
@@ -492,7 +518,7 @@
                 if (KMTPHandleNone == iFramework.ObjectMgr().HandleL(path))
                     {
                     format = EMTPFormatCodeUndefined;
-                    AddEntryL(path, handle, format, iDpID, entry);		   
+                    AddEntryL(path, handle, format, iDpID, entry, iStorages[0], iParentHandle);		   
                     }
                 break;
                 
@@ -501,7 +527,7 @@
                     {
                     format = iDpSingletons.MTPUtility().GetFormatByExtension(parse.Ext().Mid(1));  
                     TUint32 DpId = iDpSingletons.MTPUtility().GetDpId(parse.Ext().Mid(1), KNullDesC);
-                    AddFileEntryForOtherDpL(path, handle, format, DpId, entry);
+                    AddFileEntryForOtherDpL(path, handle, format, DpId, entry, iStorages[0], iParentHandle);
                     }
                 break;
                 
@@ -509,7 +535,7 @@
                 {
                 format = iDpSingletons.MTPUtility().GetFormatByExtension(parse.Ext().Mid(1));  
                 TUint32 DpId = iDpSingletons.MTPUtility().GetDpId(parse.Ext().Mid(1), KNullDesC);
-                AddFileEntryForOtherDpL(path, handle, format, DpId, entry);
+                AddFileEntryForOtherDpL(path, handle, format, DpId, entry, iStorages[0], iParentHandle);
                 }
                 break;
                 
@@ -531,7 +557,7 @@
 @param aPath    The full path name of the entry
 @return MTP object handle, or KMTPHandleNone if entry was not accepted
 */    
-void CMTPFSEnumerator::AddEntryL(const TDesC& aPath, TUint32 &aHandle, TMTPFormatCode format, TUint32 aDPId, const TEntry& aEntry)
+void CMTPFSEnumerator::AddEntryL(const TDesC& aPath, TUint32 &aHandle, TMTPFormatCode format, TUint32 aDPId, const TEntry& aEntry, TUint32 aStorageId, TUint32 aParentHandle)
 	{
 #ifdef __FLOG_ACTIVE    
 	TBuf8<KMaxFileName> tmp;
@@ -561,10 +587,10 @@
         
         iObject->SetUint(CMTPObjectMetaData::EDataProviderId, aDPId);
         iObject->SetUint(CMTPObjectMetaData::EFormatCode, format);
-        iObject->SetUint(CMTPObjectMetaData::EStorageId, iStorages[0]);
+        iObject->SetUint(CMTPObjectMetaData::EStorageId, aStorageId);
         iObject->SetDesCL(CMTPObjectMetaData::ESuid, aPath);
         iObject->SetUint(CMTPObjectMetaData::EFormatSubCode, assoc);
-        iObject->SetUint(CMTPObjectMetaData::EParentHandle, iParentHandle);
+        iObject->SetUint(CMTPObjectMetaData::EParentHandle, aParentHandle);
         iObject->SetUint(CMTPObjectMetaData::ENonConsumable, EMTPConsumable);
         iObject->SetDesCL(CMTPObjectMetaData::EName, name);
         iFramework.ObjectMgr().InsertObjectL(*iObject);
@@ -572,7 +598,7 @@
 	__FLOG_VA(_L8("AddEntryL - exit"));	
 	}
 
-void CMTPFSEnumerator::AddFileEntryForOtherDpL(const TDesC& aPath, TUint32 &aHandle, TMTPFormatCode format, TUint32 aDPId, const TEntry& /*aEntry*/)
+void CMTPFSEnumerator::AddFileEntryForOtherDpL(const TDesC& aPath, TUint32 &aHandle, TMTPFormatCode format, TUint32 aDPId, const TEntry& /*aEntry*/, TUint32 aStorageId, TUint32 aParentHandle)
     {
 #ifdef __FLOG_ACTIVE    
     TBuf8<KMaxFileName> tmp;
@@ -589,10 +615,10 @@
     
     iObject->SetUint(CMTPObjectMetaData::EDataProviderId, aDPId);
     iObject->SetUint(CMTPObjectMetaData::EFormatCode, format);
-    iObject->SetUint(CMTPObjectMetaData::EStorageId, iStorages[0]);
+    iObject->SetUint(CMTPObjectMetaData::EStorageId, aStorageId);
     iObject->SetDesCL(CMTPObjectMetaData::ESuid, aPath);
     iObject->SetUint(CMTPObjectMetaData::EFormatSubCode, assoc);
-    iObject->SetUint(CMTPObjectMetaData::EParentHandle, iParentHandle);
+    iObject->SetUint(CMTPObjectMetaData::EParentHandle, aParentHandle);
     iObject->SetUint(CMTPObjectMetaData::ENonConsumable, EMTPConsumable);
     iObject->SetDesCL(CMTPObjectMetaData::EName, name);
     iFramework.ObjectMgr().InsertObjectL(*iObject);
@@ -604,3 +630,4 @@
     iSingletons.DpController().NotifyDataProvidersL(DpId,EMTPObjectAdded,(TAny*)&aHandle);
     }
 
+
--- a/mtpfws/mtpfw/dataproviders/dputility/src/cmtpknowledgehandler.cpp	Mon Mar 08 21:44:10 2010 +0000
+++ b/mtpfws/mtpfw/dataproviders/dputility/src/cmtpknowledgehandler.cpp	Sun Mar 14 13:12:01 2010 +0000
@@ -39,6 +39,183 @@
 _LIT(KMTPKnowledgeObjFileName, "mtp_knowledgeobj.dat");
 _LIT(KMTPKnowledgeObjSwpFileName, "mtp_knowledgeobj.swp");
 
+
+CKnowledgeObject* CKnowledgeObject::NewL(CRepository& aRepository)
+	{
+	CKnowledgeObject *self = new (ELeave) CKnowledgeObject(aRepository);
+	CleanupStack::PushL(self);
+	self->ConstructL();
+	CleanupStack::Pop(self);
+	return self;
+	}
+
+CKnowledgeObject::CKnowledgeObject(CRepository& aRepository) : iRepository(aRepository)
+	{
+	
+	}
+CKnowledgeObject::~CKnowledgeObject()
+	{
+	__FLOG(_L8("~CKnowledgeObject - Entry")); 
+	iDateModified.Close();
+	iName.Close();
+	__FLOG(_L8("~CKnowledgeObject - Exit")); 
+	__FLOG_CLOSE;
+	}
+void CKnowledgeObject::ConstructL()
+	{
+	__FLOG_OPEN(KMTPSubsystem, KComponent);
+	__FLOG(_L8("CKnowledgeObject Construct - Entry"));
+	iKnowledgeObjectSize = KObjectSizeNotAvaiable;
+	iDateModified.CreateL(KDateTimeMaxLength);
+	iName.CreateL(KNameMaxLength);
+	iLastAuthorProxyID.Set(KMTPUnInitialized64, KMTPUnInitialized64);
+	iDirty = EBitFlagAll;
+	__FLOG(_L8("CKnowledgeObject Construct - Exit"));
+	}
+
+void CKnowledgeObject::LoadL()
+	{
+	__FLOG(_L8("CKnowledgeObject LoadL - Entry"));
+	// Load ObjectSize
+	TInt objSize;
+	User::LeaveIfError(iRepository.Get(ESize, objSize));
+	iKnowledgeObjectSize = objSize;
+
+	// Load DateModify
+	iDateModified.Zero();
+	User::LeaveIfError(iRepository.Get(EDateModified, iDateModified));
+	
+	// Load Name
+	iName.Zero();
+	User::LeaveIfError(iRepository.Get(EName, iName));
+
+	// Load LastAuthorProxyID:
+	TPtr8 writeBuf(NULL, 0); //walkaroud for the TMTPTypeUint128
+	iLastAuthorProxyID.FirstWriteChunk(writeBuf);
+	User::LeaveIfError(iRepository.Get(ELastAuthorProxyID, writeBuf));
+	iDirty = EBitFlagNone;
+	__FLOG(_L8("CKnowledgeObject LoadL - Exit"));
+	return;
+	}
+
+
+void CKnowledgeObject::Clear()
+	{
+	__FLOG(_L8("CKnowledgeObject Clear - Entry"));
+	iKnowledgeObjectSize = KObjectSizeNotAvaiable;
+	iDateModified.Zero();
+	iName.Zero();
+	iLastAuthorProxyID.Set(KMTPUnInitialized64, KMTPUnInitialized64);
+	iDirty = EBitFlagAll;
+	__FLOG(_L8("CKnowledgeObject Clear - Exit"));
+	}
+
+void CKnowledgeObject::SetSize(TUint64 aSize)
+	{
+	iKnowledgeObjectSize = aSize;
+	iDirty |= EBitFlagSize;
+	}
+
+void CKnowledgeObject::SetDateModified(const TDesC& /*aDateModified*/)
+	{
+	/**
+	 * DateModifed will be auto updated when commit. If PC set this prop, it will be ignored.
+	 * If someday PC want to force the DateModifed be saved, the following code piece should 
+	 * be opened, and add check in commit when save DateModified.
+	 *iDateModified.Copy(aDateModified);
+	 *iDirty |= EBitFlagDateModified;
+	**/
+	}
+
+void CKnowledgeObject::SetName(const TDesC& aName)
+	{
+	iName.Copy(aName);
+	iDirty |= EBitFlagName;
+	}
+
+void CKnowledgeObject::SetLastAuthorProxyID(TUint64 aHigh, TUint64 aLow) 
+	{
+	iLastAuthorProxyID.Set(aHigh, aLow);
+	iDirty |= EBitFlagLastAuthorProxyID;
+	}
+
+void CKnowledgeObject::CommitL()
+	{
+	__FLOG(_L8("CKnowledgeObject CommitL - Entry"));
+	if (EBitFlagSize == (iDirty & EBitFlagSize))
+		{
+		// TUint64 -> TInt, some capability is lost, 
+		// anyway, it's enough for knowledge object.   
+		User::LeaveIfError(iRepository.Set(ESize, (TInt)iKnowledgeObjectSize));
+		}
+
+	if (EBitFlagName == (iDirty & EBitFlagName))
+		{
+		User::LeaveIfError(iRepository.Set(EName, iName));
+		}
+	
+	if (EBitFlagLastAuthorProxyID == (iDirty & EBitFlagLastAuthorProxyID))
+		{
+		if (EMTPRespCodeOK != SetColumnType128Value(ELastAuthorProxyID, iLastAuthorProxyID))
+			{
+			User::Leave(KErrGeneral);
+			}
+		}
+	
+	// update DateModified to be the time of Commit
+	RefreshDateModifed();
+	User::LeaveIfError(iRepository.Set(EDateModified, iDateModified));
+
+	iDirty = EBitFlagNone;
+	__FLOG(_L8("CKnowledgeObject KnowledgeObject CommitL - Exit"));
+	return;
+	}
+
+TMTPResponseCode CKnowledgeObject::SetColumnType128Value(TMTPKnowledgeStoreKeyNum aColumnNum, TMTPTypeUint128& aNewData)
+	{
+	__FLOG(_L8("CKnowledgeObject SetColumnType128ValueL - Entry"));
+	TInt ret;
+	TMTPResponseCode responseCode = EMTPRespCodeOK;
+	TBuf8<KMTPTypeINT128Size>  data;
+	data.FillZ(data.MaxLength());
+	TUint64 upperValue = aNewData.UpperValue();
+	TUint64 lowerValue = aNewData.LowerValue();
+	
+	/**
+	Least significant 64-bit buffer offset.
+	*/
+	const TInt           KMTPTypeUint128OffsetLS = 0;
+	/**
+	Most significant 64-bit buffer offset.
+	*/
+	const TInt           KMTPTypeUint128OffsetMS = 8;
+	
+	memcpy(&data[KMTPTypeUint128OffsetMS], &upperValue, sizeof(upperValue));
+	memcpy(&data[KMTPTypeUint128OffsetLS], &lowerValue, sizeof(lowerValue));
+	
+	ret = iRepository.Set(aColumnNum, data);
+	if (KErrNone != ret)
+		{
+		responseCode = EMTPRespCodeGeneralError;
+		}
+	__FLOG_VA((_L8("CKnowledgeObject SetColumnType128ValueL - Exit with responseCode = 0x%04X"), responseCode));
+	return responseCode;
+	}
+
+
+void CKnowledgeObject::RefreshDateModifed()
+	{
+	__FLOG(_L8("CKnowledgeObject RefreshDateModifed - Entry"));
+	//get current time
+	TTime now;	
+	now.UniversalTime();
+	_LIT(KFormat,"%F%Y%M%DT%H%T%SZ");
+	iDateModified.Zero();
+	now.FormatL(iDateModified, KFormat);
+	__FLOG(_L8("CKnowledgeObject RefreshDateModifed - Exit"));
+	return;
+	}
+
 EXPORT_C CMTPKnowledgeHandler* CMTPKnowledgeHandler::NewL(MMTPDataProviderFramework& aFramework, TUint16 aFormatCode, 
 												CRepository& aReposotry, const TDesC& aKwgSuid)
 	{
@@ -52,18 +229,16 @@
 EXPORT_C CMTPKnowledgeHandler::~CMTPKnowledgeHandler()
 	{
 	__FLOG(_L8("~CMTPKnowledgeHandler - Entry")); 
-	delete iDateModified;
-	delete iName;
 	delete iKnowledgeObj;
 	delete iKnowledgeSwpBuffer;
+	delete iCachedKnowledgeObject;
 	__FLOG(_L8("~CMTPKnowledgeHandler - Exit"));
 	__FLOG_CLOSE;
 	}
 
 CMTPKnowledgeHandler::CMTPKnowledgeHandler(MMTPDataProviderFramework& aFramework, TUint16 aFormatCode, 
 										CRepository& aReposotry, const TDesC& aKwgSuid) :
-	iFramework(aFramework), iRepository(aReposotry), iKnowledgeFormatCode(aFormatCode),
-	iKnowledgeObjectSize(KObjectSizeNotAvaiable), iCacheStatus(EOK), iSuid(aKwgSuid)
+	iFramework(aFramework), iRepository(aReposotry), iKnowledgeFormatCode(aFormatCode), iSuid(aKwgSuid)
 	{
 	}
 
@@ -93,7 +268,9 @@
 		User::LeaveIfError(iFramework.Fs().Delete(iKnowObjSwpFileName));
 		}
 
-	LoadKnowledgeObjPropertiesL();
+	// create and load knowledge object properties
+	iCachedKnowledgeObject = CKnowledgeObject::NewL(iRepository);
+	iCachedKnowledgeObject->LoadL();
 	__FLOG(_L8("ConstructL - Exit"));
 	}
 
@@ -105,26 +282,11 @@
 void CMTPKnowledgeHandler::CommitL()
 	{
 	__FLOG(_L8("CommitL - Entry"));
-
 	User::LeaveIfError(iRepository.StartTransaction(CRepository::EReadWriteTransaction));
 	iRepository.CleanupCancelTransactionPushL();
-	if(iKnowledgeObjectSize != KObjectSizeNotAvaiable)
-		{
-		User::LeaveIfError(iRepository.Set(ESize, (TInt)iKnowledgeObjectSize));
-		}
-	if(iDateModified)
-		{
-		User::LeaveIfError(iRepository.Set(EDateModified, *iDateModified));
-		}
-	if(iName)
-		{
-		User::LeaveIfError(iRepository.Set(EName, *iName));
-		}
 	
-	if (EMTPRespCodeOK != SetColumnType128Value(ELastAuthorProxyID, iLastAuthorProxyID))
-		{
-		User::Leave(KErrGeneral);
-		}
+	iCachedKnowledgeObject->CommitL();
+	
 	// Close all knowledge file and reset pointer.
 	if (iKnowledgeObj)
 		{
@@ -144,10 +306,11 @@
 		User::LeaveIfError(iFramework.Fs().Replace(iKnowObjSwpFileName, iKnowObjFileName));
 		}
 	// If swp file isn't exsited, that means 0 sized object received, need do nothing.
-	
+
 	TUint32 keyInfo;
 	User::LeaveIfError(iRepository.CommitTransaction(keyInfo));
 	CleanupStack::Pop(&iRepository);
+
 	__FLOG(_L8("CommitL - Exit"));
 	}
 
@@ -160,80 +323,21 @@
 void CMTPKnowledgeHandler::RollBack()
 	{
 	__FLOG(_L8("Rollback - Entry"));
-	TRAP_IGNORE(LoadKnowledgeObjPropertiesL());
+	iCachedKnowledgeObject->Clear();
+	TRAP_IGNORE(iCachedKnowledgeObject->LoadL());
 	__FLOG(_L8("Rollback - Exit"));
 	}
 
 EXPORT_C void CMTPKnowledgeHandler::GetObjectSuidL(TDes& aSuid) const
 	{
 	__FLOG(_L8("GetObjectSuidL - Entry"));
-	if(iKnowledgeObjectSize != KObjectSizeNotAvaiable)
+	if(iCachedKnowledgeObject->Size() != KObjectSizeNotAvaiable)
 		{
 		aSuid.Append(iSuid);
 		}
 	__FLOG(_L8("GetObjectSuidL - Exit"));
 	}
 
-void CMTPKnowledgeHandler::LoadKnowledgeObjPropertiesL()
-	{
-	__FLOG(_L8("LoadKnowledgeObjPropertiesL - Entry"));
-	iCacheStatus = EOK;
-	iCacheStatusFlag = EDirty;
-	TCleanupItem cacheDroper(DropCacheWrapper, this);
-	CleanupStack::PushL(cacheDroper);
-	TInt objSize;
-	User::LeaveIfError(iRepository.Get(ESize, objSize));
-	iKnowledgeObjectSize = objSize;
-
-	// Load DateModify
-	delete iDateModified;
-	iDateModified = NULL;
-	iDateModified = HBufC::NewL(KDateTimeMaxLength);
-	TPtr ptrDate(iDateModified->Des());
-	User::LeaveIfError(iRepository.Get(EDateModified, ptrDate));
-	
-	// Load Name
-	delete iName;
-	iName = NULL;
-	iName = HBufC::NewL(KNameMaxLength);
-	TPtr ptrName(iName->Des());
-	User::LeaveIfError(iRepository.Get(EName, ptrName));
-
-	// Load LastAuthorProxyID:
-	TPtr8 writeBuf(NULL, 0); //walkaroud for the TMTPTypeUint128
-	iLastAuthorProxyID.FirstWriteChunk(writeBuf);
-	User::LeaveIfError(iRepository.Get(ELastAuthorProxyID, writeBuf));
-	CleanupStack::Pop(this);
-	// Doesn't load object content to cache beacause it can grow up to 100KB
-	__FLOG(_L8("LoadKnowledgeObjPropertiesL - Exit"));
-	}
-
-void CMTPKnowledgeHandler::DropCacheWrapper(TAny* aObject)
-	{
-	reinterpret_cast<CMTPKnowledgeHandler*>(aObject)->DropKnowledgeObjPropertiesCache();
-	}
-
-void CMTPKnowledgeHandler::DropKnowledgeObjPropertiesCache()
-	{
-	__FLOG(_L8("DropKnowledgeObjPropertiesCache - Entry"));
-	iCacheStatus = iCacheStatusFlag;
-	iKnowledgeObjectSize = KObjectSizeNotAvaiable;
-	
-	// Load DateModify
-	delete iDateModified;
-	iDateModified = NULL;
-	
-	// Load Name
-	delete iName;
-	iName = NULL;
-	
-	// Reset LastAuthorProxyID
-	TMTPTypeUint128 tmp(MAKE_TINT64(KMTPUnInitialized32, KMTPUnInitialized32), 
-						MAKE_TINT64(KMTPUnInitialized32, KMTPUnInitialized32));
-	iLastAuthorProxyID.Set(tmp.UpperValue(), tmp.LowerValue());
-	__FLOG(_L8("DropKnowledgeObjPropertiesCache - Exit"));
-	}
-
 TMTPResponseCode CMTPKnowledgeHandler::SendObjectInfoL(const CMTPTypeObjectInfo& aObjectInfo, TUint32& aParentHandle, TDes& aSuid)
 	{
 	__FLOG(_L("SendObjectInfoL - Entry"));
@@ -245,21 +349,22 @@
 	else
 		{
 		//if there's a read error reread
-		if(EDirty == iCacheStatus)
+		if(iCachedKnowledgeObject->IsDirty())
 			{
-			LoadKnowledgeObjPropertiesL();
+			__FLOG(_L8("Warning: The cached knowledge is dirty"));
+			iCachedKnowledgeObject->Clear();
+			iCachedKnowledgeObject->LoadL();
 			}
 		//already has a knowledge object
-		if(iKnowledgeObjectSize != KObjectSizeNotAvaiable)
+		if(iCachedKnowledgeObject->Size() != KObjectSizeNotAvaiable)
 			{
 			responseCode = EMTPRespCodeAccessDenied;
 			}
 		else
 			{
-			iKnowledgeObjectSize = aObjectInfo.Uint32L(CMTPTypeObjectInfo::EObjectCompressedSize);
-			delete iDateModified;
-			iDateModified = NULL;
-			iDateModified = aObjectInfo.StringCharsL(CMTPTypeObjectInfo::EDateModified).AllocL();
+			iCachedKnowledgeObject->Clear();
+			iCachedKnowledgeObject->SetSize(aObjectInfo.Uint32L(CMTPTypeObjectInfo::EObjectCompressedSize));
+			// DateModified will be updated when commit.
 			aSuid = iSuid;
 			}
 		}
@@ -280,18 +385,21 @@
 		{
 		//if there's a read error reread
 		aParentHandle = KMTPHandleNoParent;
-		if(EDirty == iCacheStatus)
+		if(iCachedKnowledgeObject->IsDirty())
 			{
-			LoadKnowledgeObjPropertiesL();
+			__FLOG(_L8("Warning: The cached knowledge is dirty"));
+			iCachedKnowledgeObject->Clear();
+			iCachedKnowledgeObject->LoadL();
 			}
 		//already has a knowledge object
-		if(iKnowledgeObjectSize != KObjectSizeNotAvaiable)
+		if(iCachedKnowledgeObject->Size() != KObjectSizeNotAvaiable)
 			{
 			responseCode = EMTPRespCodeAccessDenied;
 			}
 		else
 			{
-			iKnowledgeObjectSize = aObjectSize;
+			iCachedKnowledgeObject->Clear();
+			iCachedKnowledgeObject->SetSize(aObjectSize);
 			aSuid = iSuid;
 			}
 		}
@@ -307,6 +415,12 @@
 	CMTPTypeObjectPropListElement* propertyElement = NULL;
 	TUint32 aHandle = aObjectMetaData.Uint(CMTPObjectMetaData::EHandle);
 	
+	if(iCachedKnowledgeObject->IsDirty())
+		{
+		__FLOG(_L8("Warning: The cached knowledge is dirty"));
+		iCachedKnowledgeObject->LoadL();
+		}
+	
 	switch (aPropertyCode)
 		{
 		case EMTPGenObjPropCodeParentID:
@@ -319,9 +433,9 @@
 		case EMTPGenObjPropCodeName:
 			{
 			propertyElement = &(aPropList.ReservePropElemL(aHandle, aPropertyCode));
-			if (iName && iName->Length() > 0)
+			if (iCachedKnowledgeObject->Name().Length() > 0)
 				{
-				propertyElement->SetStringL(CMTPTypeObjectPropListElement::EValue, *iName);			
+				propertyElement->SetStringL(CMTPTypeObjectPropListElement::EValue, iCachedKnowledgeObject->Name());
 				}
 			else
 				{
@@ -349,10 +463,10 @@
 
 		case EMTPGenObjPropCodeObjectSize:
 			{
-			if (iKnowledgeObjectSize != ~0)
+			if (iCachedKnowledgeObject->Size() != KObjectSizeNotAvaiable)
 				{
 				propertyElement = &(aPropList.ReservePropElemL(aHandle, aPropertyCode));
-				propertyElement->SetUint64L(CMTPTypeObjectPropListElement::EValue,iKnowledgeObjectSize);
+				propertyElement->SetUint64L(CMTPTypeObjectPropListElement::EValue, iCachedKnowledgeObject->Size());
 				}
 			break;
 			}
@@ -380,34 +494,24 @@
 
 		case EMTPGenObjPropCodeDateModified:
 			{
-			propertyElement = &(aPropList.ReservePropElemL(aHandle, aPropertyCode));
-			if(iDateModified && iDateModified->Length() > 0)
-				{
-				propertyElement->SetStringL(CMTPTypeObjectPropListElement::EValue, *iDateModified);	
-				}
-			else
+			if(iCachedKnowledgeObject->DateModified().Length() == 0)
 				{
-				TTime now;	
-				now.UniversalTime();
-				const TInt KMaxTimeStringSize = 50;
-				TBuf<KMaxTimeStringSize> dateTimeBuf;
-				_LIT(KFormat,"%F%Y%M%DT%H%T%S");
-				now.FormatL(dateTimeBuf, KFormat);
-				propertyElement->SetStringL(CMTPTypeObjectPropListElement::EValue, dateTimeBuf);	
+				iCachedKnowledgeObject->RefreshDateModifed();
 				}
+			propertyElement = &(aPropList.ReservePropElemL(aHandle, aPropertyCode));
+			propertyElement->SetStringL(CMTPTypeObjectPropListElement::EValue, iCachedKnowledgeObject->DateModified());
 			break;
 			}
 			
 		case EMTPSvcObjPropCodeLastAuthorProxyID:
 			{
-			const TMTPTypeUint128 unInitValue(MAKE_TUINT64(KMTPUnInitialized32, KMTPUnInitialized32), 
-										MAKE_TUINT64(KMTPUnInitialized32, KMTPUnInitialized32));
-			if(!unInitValue.Equal(iLastAuthorProxyID))
+			if ((iCachedKnowledgeObject->LastAuthorProxyID().UpperValue() != KMTPUnInitialized64)
+				 && (iCachedKnowledgeObject->LastAuthorProxyID().LowerValue() !=KMTPUnInitialized64))
 				{
 				propertyElement = &(aPropList.ReservePropElemL(aHandle, aPropertyCode));
 				propertyElement->SetUint128L(CMTPTypeObjectPropListElement::EValue,
-											iLastAuthorProxyID.UpperValue(),
-											iLastAuthorProxyID.LowerValue());
+						iCachedKnowledgeObject->LastAuthorProxyID().UpperValue(),
+						iCachedKnowledgeObject->LastAuthorProxyID().LowerValue());
 				}
 			break;	
 			}
@@ -437,43 +541,27 @@
 		switch (propertyCode)
 			{
 			case EMTPGenObjPropCodeObjectSize:
-				if(aOperationCode == EMTPOpCodeSetObjectPropList)
-					{
-					ret = iRepository.Set(ESize, (TInt)aElement.Uint64L(CMTPTypeObjectPropListElement::EValue));
-					}
-				iKnowledgeObjectSize = aElement.Uint64L(CMTPTypeObjectPropListElement::EValue);
+				{
+				iCachedKnowledgeObject->SetSize(aElement.Uint64L(CMTPTypeObjectPropListElement::EValue));
 				break;
-				
+				}
 			case EMTPGenObjPropCodeDateModified:
-				if(aOperationCode == EMTPOpCodeSetObjectPropList)
-					{
-					ret = iRepository.Set(EDateModified, aElement.StringL(CMTPTypeObjectPropListElement::EValue));
-					}
-				delete iDateModified;
-				iDateModified = NULL;
-				iDateModified = aElement.StringL(CMTPTypeObjectPropListElement::EValue).AllocL();
+				{
+				// DateModified will be updated when Commit
+				iCachedKnowledgeObject->SetDateModified(aElement.StringL(CMTPTypeObjectPropListElement::EValue));
 				break;
-				
+				}
 			case EMTPGenObjPropCodeName:
-				if(aOperationCode == EMTPOpCodeSetObjectPropList)
-					{
-					ret = iRepository.Set(EName, aElement.StringL(CMTPTypeObjectPropListElement::EValue));
-					}
-				delete iName;
-				iName = NULL;
-				iName = aElement.StringL(CMTPTypeObjectPropListElement::EValue).AllocL();
+				{
+				iCachedKnowledgeObject->SetName(aElement.StringL(CMTPTypeObjectPropListElement::EValue));
 				break;
-				
+				}
 			case EMTPSvcObjPropCodeLastAuthorProxyID:
 				{
 				TUint64 high_value = 0;
 				TUint64 low_value  = 0;
 				aElement.Uint128L(CMTPTypeObjectPropListElement::EValue, high_value, low_value);
-				if(aOperationCode == EMTPOpCodeSetObjectPropList)
-					{
-					responseCode = SetColumnType128Value(ELastAuthorProxyID, iLastAuthorProxyID);
-					}
-				iLastAuthorProxyID.Set(high_value, low_value);
+				iCachedKnowledgeObject->SetLastAuthorProxyID(high_value, low_value);
 				break;
 				}
 				
@@ -494,16 +582,31 @@
 TMTPResponseCode CMTPKnowledgeHandler::DeleteObjectL(const CMTPObjectMetaData& /*aObjectMetaData*/)
 	{
 	__FLOG(_L8("DeleteObjectL - Entry"));
-	iCacheStatusFlag = EDirty;
-	TCleanupItem cacheDroper(DropCacheWrapper, this);
-	CleanupStack::PushL(cacheDroper);
+
+	User::LeaveIfError(iRepository.StartTransaction(CRepository::EReadWriteTransaction));
+	iRepository.CleanupCancelTransactionPushL();
+
 	// Delete obejct properties in transaction, if leave, mgr will rollback all properties.
-	DeleteAllObjectPropertiesL();
-	CleanupStack::Pop(this);
-	// Drop all cached properties.
-	iCacheStatusFlag = EDeleted;
-	CMTPKnowledgeHandler::DropCacheWrapper(this);
-	LoadKnowledgeObjPropertiesL();
+	iCachedKnowledgeObject->Clear();
+	iCachedKnowledgeObject->CommitL();
+	
+	// Reset knowledgeobject pointer and close the file.
+	if (iKnowledgeObj)
+		{
+		delete iKnowledgeObj;
+		iKnowledgeObj = NULL;
+		}
+	
+	// Keep file delete is atomic.
+	if (BaflUtils::FileExists(iFramework.Fs(), iKnowObjFileName))
+		{
+		User::LeaveIfError(iFramework.Fs().Delete(iKnowObjFileName));
+		}
+
+	TUint32 keyInfo;
+	User::LeaveIfError(iRepository.CommitTransaction(keyInfo));
+	CleanupStack::Pop(&iRepository);
+
 	__FLOG(_L8("DeleteObjectL - Exit"));
 	return EMTPRespCodeOK;
 	}
@@ -538,19 +641,12 @@
 	switch (aPropertyCode)
 		{
 		case EMTPGenObjPropCodeDateModified:
-			delete iDateModified;
-			iDateModified = NULL;
-			if (KErrNone != iRepository.Set(EDateModified, KEmptyContent16))
-				{
-				responseCode = EMTPRespCodeGeneralError;
-				}
+			// DateModified will be updated when Commit
+			iCachedKnowledgeObject->SetDateModified(KEmptyContent16);
 			break;
 		case EMTPSvcObjPropCodeLastAuthorProxyID:
 			{
-			TMTPTypeUint128 tmp(MAKE_TINT64(KMTPUnInitialized32, KMTPUnInitialized32), 
-								MAKE_TINT64(KMTPUnInitialized32, KMTPUnInitialized32));
-			iLastAuthorProxyID.Set(tmp.UpperValue(), tmp.LowerValue());
-			responseCode = SetColumnType128Value(ELastAuthorProxyID, iLastAuthorProxyID);
+			iCachedKnowledgeObject->SetLastAuthorProxyID(KMTPUnInitialized64, KMTPUnInitialized64);
 			break;
 			}
 			
@@ -594,7 +690,7 @@
 	aObjectInfo.SetUint16L(CMTPTypeObjectInfo::EObjectFormat, iKnowledgeFormatCode);
 	// Not use
 	aObjectInfo.SetUint16L(CMTPTypeObjectInfo::EProtectionStatus, 0x0000);
-	aObjectInfo.SetUint32L(CMTPTypeObjectInfo::EObjectCompressedSize, iKnowledgeObjectSize);
+	aObjectInfo.SetUint32L(CMTPTypeObjectInfo::EObjectCompressedSize, iCachedKnowledgeObject->Size());
 	aObjectInfo.SetUint16L(CMTPTypeObjectInfo::EThumbFormat, 0);
 	aObjectInfo.SetUint32L(CMTPTypeObjectInfo::EThumbCompressedSize, 0);
 	aObjectInfo.SetUint32L(CMTPTypeObjectInfo::EThumbPixWidth, 0);
@@ -615,7 +711,7 @@
 TMTPResponseCode CMTPKnowledgeHandler::GetObjectInfoL(const CMTPObjectMetaData& /*aObjectMetaData*/, CMTPTypeObjectInfo& aObjectInfo)
 	{
 	__FLOG(_L8("GetObjectInfoL - Entry"));
-	if(iKnowledgeObjectSize != KObjectSizeNotAvaiable)
+	if(iCachedKnowledgeObject->Size() != KObjectSizeNotAvaiable)
 		{
 		BuildObjectInfoL(aObjectInfo);
 		}
@@ -624,42 +720,6 @@
 	}
 
 
-void CMTPKnowledgeHandler::DeleteAllObjectPropertiesL()
-	{
-	__FLOG(_L8("DeleteAllObjectPropertiesL - Entry"));
-	User::LeaveIfError(iRepository.StartTransaction(CRepository::EReadWriteTransaction));
-	iRepository.CleanupCancelTransactionPushL();
-	User::LeaveIfError(iRepository.Set(EDateModified, KEmptyContent16));
-	User::LeaveIfError(iRepository.Set(EName, KEmptyContent16));
-	User::LeaveIfError(iRepository.Set(ESize, static_cast<TInt>(KObjectSizeNotAvaiable)));
-	
-	TMTPTypeUint128 tmp(MAKE_TINT64(KMTPUnInitialized32, KMTPUnInitialized32), 
-						MAKE_TINT64(KMTPUnInitialized32, KMTPUnInitialized32));
-	if (EMTPRespCodeOK != SetColumnType128Value(ELastAuthorProxyID, tmp))
-		{
-		User::Leave(KErrGeneral);
-		}
-	// Reset knowledgeobject pointer and close the file.
-	if (iKnowledgeObj)
-		{
-		delete iKnowledgeObj;
-		iKnowledgeObj = NULL;
-		}
-	
-	// Keep file delete is atomic.
-	if (BaflUtils::FileExists(iFramework.Fs(), iKnowObjFileName))
-		{
-		User::LeaveIfError(iFramework.Fs().Delete(iKnowObjFileName));
-		}
-	
-	TUint32 keyInfo;
-	User::LeaveIfError(iRepository.CommitTransaction(keyInfo));
-	CleanupStack::Pop(&iRepository);
-	
-	__FLOG(_L8("DeleteAllObjectPropertiesL - Exit"));
-	return;
-	}
-
 void CMTPKnowledgeHandler::ReleaseObjectBuffer()
 	{
 	__FLOG(_L8("ReleaseObjectBuffer - Entry"));
@@ -678,42 +738,11 @@
 		{
 		return EMTPRespCodeGeneralError;
 		}
-	aObjectSize = iKnowledgeObjectSize;
+	aObjectSize = iCachedKnowledgeObject->Size();
 	__FLOG(_L8("GetObjectSizeL - Exit"));
 	return EMTPRespCodeOK;
 	}
 
-TMTPResponseCode CMTPKnowledgeHandler::SetColumnType128Value(TMTPKnowledgeStoreKeyNum aColumnNum, TMTPTypeUint128& aNewData)
-	{
-	__FLOG(_L8("SetColumnType128ValueL - Entry"));
-	TInt ret;
-	TMTPResponseCode responseCode = EMTPRespCodeOK;
-	TBuf8<KMTPTypeINT128Size>  data;
-	data.FillZ(data.MaxLength());
-	TUint64 upperValue = aNewData.UpperValue();
-	TUint64 lowerValue = aNewData.LowerValue();
-	
-	/**
-	Least significant 64-bit buffer offset.
-	*/
-	const TInt           KMTPTypeUint128OffsetLS = 0;
-	/**
-	Most significant 64-bit buffer offset.
-	*/
-	const TInt           KMTPTypeUint128OffsetMS = 8;
-	
-	memcpy(&data[KMTPTypeUint128OffsetMS], &upperValue, sizeof(upperValue));
-	memcpy(&data[KMTPTypeUint128OffsetLS], &lowerValue, sizeof(lowerValue));
-	
-	ret = iRepository.Set(aColumnNum, data);
-	if (KErrNone != ret)
-		{
-		responseCode = EMTPRespCodeGeneralError;
-		}
-	__FLOG_VA((_L8("SetColumnType128ValueL - Exit with responseCode = 0x%04X"), responseCode));
-	return responseCode;
-	}
-
 TMTPResponseCode CMTPKnowledgeHandler::GetAllObjectPropCodeByGroupL(TUint32 aGroupId, RArray<TUint32>& aPropCodes)
 	{
 	__FLOG(_L8("GetAllObjectPropCodeByGroupL - Entry"));
@@ -749,3 +778,5 @@
 	__FLOG(_L8("GetAllObjectPropCodeByGroupL - Exit"));
 	return responseCode;
 	}
+
+
--- a/mtpfws/mtpfw/dataproviders/proxydp/inc/cmtpdeleteobject.h	Mon Mar 08 21:44:10 2010 +0000
+++ b/mtpfws/mtpfw/dataproviders/proxydp/inc/cmtpdeleteobject.h	Sun Mar 14 13:12:01 2010 +0000
@@ -45,7 +45,8 @@
 private: // From CMTPRequestProcessor
 
     void ServiceL();    
-
+	TMTPResponseCode CheckRequestL();
+	
 private: // From MMTPTransactionProxy
 
     void ProxyReceiveDataL(MMTPType& aData, const TMTPTypeRequest& aRequest, MMTPConnection& aConnection, TRequestStatus& aStatus);
--- a/mtpfws/mtpfw/dataproviders/proxydp/inc/cmtpobjectbrowser.h	Mon Mar 08 21:44:10 2010 +0000
+++ b/mtpfws/mtpfw/dataproviders/proxydp/inc/cmtpobjectbrowser.h	Sun Mar 14 13:12:01 2010 +0000
@@ -58,6 +58,15 @@
     void GetRootObjectHandlesL( TUint32 aCurDepth, TUint32 aFormatCode, TUint32 aDepth, const TBrowseCallback& aBrowseCallback ) const;
     void GetObjectHandlesTreeL( TUint32 aCurDepth, TUint32 aFormatCode, TUint32 aDepth, TUint32 aParentHandle, const TBrowseCallback& aBrowseCallback ) const;
     
+    /**
+     * This function retrives all the object handles with the format code of aFormatCode.
+     * 
+     * If aFormatCode == KMTPFormatsAll, only Legacy dp's object handles are returned. Object
+     * Handles of service dp's will not be returned.
+     * 
+     */
+    void GetAllObjectHandlesL( TUint32 aFormatCode,const TBrowseCallback& aBrowseCallback ) const;
+    
 private:
     __FLOG_DECLARATION_MEMBER_MUTABLE;
     
--- a/mtpfws/mtpfw/dataproviders/proxydp/src/cmtpdeleteobject.cpp	Mon Mar 08 21:44:10 2010 +0000
+++ b/mtpfws/mtpfw/dataproviders/proxydp/src/cmtpdeleteobject.cpp	Sun Mar 14 13:12:01 2010 +0000
@@ -86,6 +86,19 @@
     __FLOG( _L8("-ConstructL") );
     }
     
+TMTPResponseCode CMTPDeleteObject::CheckRequestL()
+	{
+    __FLOG(_L8("CheckRequestL - Entry"));
+    TMTPResponseCode responseCode = CMTPRequestProcessor::CheckRequestL();   
+    if ((EMTPRespCodeOK == responseCode) && (iSingletons.DpController().EnumerateState() == CMTPDataProviderController::EEnumeratingSubDirFiles))
+        {
+		responseCode = EMTPRespCodeDeviceBusy;
+        }
+    
+	__FLOG_VA((_L8("CheckRequestL - Exit with responseCode = 0x%04X"), responseCode));
+    return responseCode;
+	}
+
 /**
 DeleteObject request handler
 */ 
@@ -158,11 +171,21 @@
     
     if ( iStatus == KErrNone )
         {
-        NextObjectHandleL();
-        if ( iOwnerDp != KInvalidDpId )
+        //First check if the operation has been cancelled or not
+        if(iCancelled)
             {
-            CMTPDataProvider& dp = iSingletons.DpController().DataProviderL( iOwnerDp );
-            dp.ExecuteProxyRequestL( iCurrentRequest, Connection(), *this );
+            __FLOG(_L8("Initiator cancell delete, send response with cancelled code "));
+            SendResponseL(EMTPRespCodeTransactionCancelled);
+            iCancelled = EFalse;
+            }
+        else
+            {
+            NextObjectHandleL();
+            if ( iOwnerDp != KInvalidDpId )
+                {
+                CMTPDataProvider& dp = iSingletons.DpController().DataProviderL( iOwnerDp );
+                dp.ExecuteProxyRequestL( iCurrentRequest, Connection(), *this );
+                }
             }
         }
     else
@@ -209,6 +232,7 @@
     iHandles.Reset();
     iCurrentHandle = 0;
     iDeletedObjectsNumber = 0;
+    
     MMTPType::CopyL( Request(), iCurrentRequest );
     
     CMTPObjectBrowser::TBrowseCallback callback = { CMTPDeleteObject::OnBrowseObjectL, this };
--- a/mtpfws/mtpfw/dataproviders/proxydp/src/cmtpgetobjectproplist.cpp	Mon Mar 08 21:44:10 2010 +0000
+++ b/mtpfws/mtpfw/dataproviders/proxydp/src/cmtpgetobjectproplist.cpp	Sun Mar 14 13:12:01 2010 +0000
@@ -248,18 +248,7 @@
     
     if ( 0 == iHandles.Count() )
         {
-        if ( handle==KMTPHandleNone && depth==0 )
-            {
-            SendDataL( *iObjectPropList );
-            }
-        else if ( fmtCode != KMTPFormatsAll )
-            {
-            SendResponseL(EMTPRespCodeSpecificationByFormatUnsupported);
-            }
-        else if ( handle != KMTPHandleAll )
-            {
-            SendResponseL(EMTPRespCodeInvalidObjectHandle);
-            }
+          SendDataL( *iObjectPropList );
         }
     else
         {
--- a/mtpfws/mtpfw/dataproviders/proxydp/src/cmtpobjectbrowser.cpp	Mon Mar 08 21:44:10 2010 +0000
+++ b/mtpfws/mtpfw/dataproviders/proxydp/src/cmtpobjectbrowser.cpp	Sun Mar 14 13:12:01 2010 +0000
@@ -55,7 +55,16 @@
     switch ( aHandle )
         {
         case KMTPHandleAll:
-            GetObjectHandlesL( 0, KMTPStorageAll, aFormatCode, KMaxTUint, KMTPHandleNoParent, aBrowseCallback );
+           //for the format code of serveice dp's, need to check the format
+           if( (aFormatCode >= EMTPFormatCodeVendorExtStart)&&(aFormatCode <= EMTPFormatCodeVendorExtEnd) )
+               {
+               GetAllObjectHandlesL( aFormatCode,aBrowseCallback );
+               }
+           else
+               {
+               GetAllObjectHandlesL( KMTPFormatsAll,aBrowseCallback );
+               }
+           
             break;
         case KMTPHandleNone:
             GetRootObjectHandlesL( 0, aFormatCode, aDepth, aBrowseCallback );
@@ -88,7 +97,16 @@
     
     RMTPObjectMgrQueryContext   context;
     RArray< TUint >             handles;
-    TMTPObjectMgrQueryParams    params( aStorageId, aFormatCode, aParentHandle );
+    TMTPObjectMgrQueryParams    params( aStorageId, KMTPFormatsAll, aParentHandle );
+    // if parenthandle = 0, depth >0 and != ffffffff, for service dp, 
+    // 1. there is no tree structure
+    // 2. KMTPFormatsAll may make the low lever api filter the handls of service dp.
+    if( (aFormatCode >= EMTPFormatCodeVendorExtStart)&&(aFormatCode <= EMTPFormatCodeVendorExtEnd) )
+        {
+        params.iFormatCode = aFormatCode ;
+        }
+     
+      
     CleanupClosePushL( context );
     CleanupClosePushL( handles );
     
@@ -107,7 +125,13 @@
             {
             for ( TUint i = 0; i < handleCount; i++ )
                 {
-                aBrowseCallback.iCallback( aBrowseCallback.iContext, handles[i], aCurDepth );
+                //before insert the handle to th result list , check it's format.
+                iDpFw.ObjectMgr().ObjectL( handles[i], *iObjMetaCache );
+                if ( (KMTPFormatsAll == aFormatCode) || ( aFormatCode == iObjMetaCache->Uint( CMTPObjectMetaData::EFormatCode )) )
+                   {
+                   aBrowseCallback.iCallback( aBrowseCallback.iContext, handles[i], aCurDepth );
+                   }
+           
                 }
             }
         }
@@ -123,16 +147,18 @@
     {
     __FLOG_VA( ( _L8("+GetFolderObjectHandlesL( %d, 0x%08X, %d, 0x%08X )"), aCurDepth, aFormatCode, aDepth, aParentHandle ) );
     
-    if ( 0 == aDepth )
-        {
-        aBrowseCallback.iCallback( aBrowseCallback.iContext, aParentHandle, aCurDepth );
-        }
-    else
+    if (  aDepth > 0)
         {
         GetObjectHandlesL( aCurDepth + 1, KMTPStorageAll, aFormatCode, aDepth - 1, aParentHandle, aBrowseCallback );
-        aBrowseCallback.iCallback( aBrowseCallback.iContext, aParentHandle, aCurDepth );
         }
     
+    //before insert the handle to th result list , check it's format.
+    iDpFw.ObjectMgr().ObjectL( aParentHandle, *iObjMetaCache );
+    if ( (KMTPFormatsAll == aFormatCode) || ( aFormatCode == iObjMetaCache->Uint( CMTPObjectMetaData::EFormatCode )) )
+       {
+       aBrowseCallback.iCallback( aBrowseCallback.iContext, aParentHandle, aCurDepth );
+       }
+            
     __FLOG( _L8("-GetFolderObjectHandlesL") );
     }
 
@@ -140,19 +166,21 @@
     {
     __FLOG_VA( ( _L8("+GetRootObjectHandlesL( %d, 0x%08X, %d )"), aCurDepth, aFormatCode, aDepth ) );
     
-    switch ( aDepth )
-        {
-        case KMaxTUint:
-            GetObjectHandlesL( aCurDepth, KMTPStorageAll, aFormatCode, aDepth, KMTPHandleNoParent, aBrowseCallback );
-            break;
-        case 0:
-            // do nothing
-            break;
-        default:
-            GetObjectHandlesL( aCurDepth, KMTPStorageAll, aFormatCode, aDepth, KMTPHandleNoParent, aBrowseCallback );
-            break;
+    if( aDepth > 0)
+        {        
+            if (KMaxTUint == aDepth)
+                {
+                GetAllObjectHandlesL( aFormatCode,aBrowseCallback );
+                }
+            else
+                {
+                // attention: aDepth should be reduced by 1 here
+                GetObjectHandlesL( aCurDepth, KMTPStorageAll, aFormatCode, aDepth-1, KMTPHandleNoParent, aBrowseCallback );
+                }
         }
     
+    // if aDepth == 0, no handles should be returned.
+    
     __FLOG( _L8("-GetRootObjectHandlesL") );
     }
 
@@ -169,9 +197,13 @@
         {
         GetFolderObjectHandlesL( aCurDepth, aFormatCode, aDepth, aParentHandle, aBrowseCallback );
         }
+    else if ( (KMTPFormatsAll == aFormatCode) || ( aFormatCode == iObjMetaCache->Uint( CMTPObjectMetaData::EFormatCode )) )
+        {
+        aBrowseCallback.iCallback( aBrowseCallback.iContext, aParentHandle, aCurDepth );
+        }
     else
         {
-        aBrowseCallback.iCallback( aBrowseCallback.iContext, aParentHandle, aCurDepth );
+          // format doesn't match, do nothing
         }
 #ifdef __FLOG_ACTIVE
     __FLOG_1( _L8("recursion_depth: %d"), aCurDepth );
@@ -181,4 +213,45 @@
     __FLOG( _L8("-GetObjectHandlesTreeL") );
     }
 
+/**
+ * This function retrives all the object handles with the format code of aFormatCode.
+ * 
+ * If aFormatCode == KMTPFormatsAll, only Legacy dp's object handles are returned. Object
+ * Handles of service dp's will not be returned.
+ * 
+ */
 
+void CMTPObjectBrowser::GetAllObjectHandlesL(TUint32 aFormatCode,const TBrowseCallback& aBrowseCallback ) const
+    {
+    __FLOG( _L8("CMTPObjectBrowser::GetAllObjectHandles-----entry") );
+
+    RMTPObjectMgrQueryContext   context;
+    RArray< TUint >             handles;
+    TMTPObjectMgrQueryParams    params( KMTPStorageAll, aFormatCode, KMTPHandleNone );
+    
+   
+    CleanupClosePushL( context );
+    CleanupClosePushL( handles );
+      
+    do
+        {
+        iDpFw.ObjectMgr().GetObjectHandlesL( params, context, handles );
+        TUint handleCount = handles.Count();
+        
+        for ( TUint i = 0; i < handleCount; i++ )
+          {
+            /* the argument aCurDepth of the callback is set to 0, since the call back never use this argument. 
+             * If aCurDepth is used later, this arugment shoud be changed to the valid value.
+             */
+            aBrowseCallback.iCallback( aBrowseCallback.iContext, handles[i], 0 );
+          }
+        
+        }
+    while ( !context.QueryComplete() );
+      
+    CleanupStack::PopAndDestroy( &handles );
+    CleanupStack::PopAndDestroy( &context );
+    
+    __FLOG( _L8("CMTPObjectBrowser::GetAllObjectHandles------exit") );
+    }
+
--- a/mtpfws/mtpfw/datatypes/interface/cmtptypefile.h	Mon Mar 08 21:44:10 2010 +0000
+++ b/mtpfws/mtpfw/datatypes/interface/cmtptypefile.h	Sun Mar 14 13:12:01 2010 +0000
@@ -33,6 +33,43 @@
 */
 class CMTPTypeFile : public CActive, public MMTPType
     {
+
+class CFileWriter : public CActive
+    {
+public:
+    
+    static CFileWriter* NewL(RFile&  aFile, RBuf8& aWriteBuf);
+    /*
+     * Get the buffer for transport to receive data.
+     */
+    void GetWriteBuf(TPtr8& aChunk);
+    /*
+     * Get the file write result.
+     */
+    TInt GetResult() const;
+    /*
+     * Issue a async request to write aLength Data
+     * 
+     */
+    void Write(TInt aLength);
+    /*
+     * Wait until the async write complete.
+     */
+    void WaitForWriteComplete();
+    void RunL();
+    ~CFileWriter();
+    
+private:
+    void DoCancel();
+    CFileWriter(RFile&  aFile, RBuf8& aBuf);
+    void ConstructL();
+    
+private:
+    TInt    iWriteResult;
+    RFile&  iFile;
+    RBuf8&  iBuf;
+    };
+
 public:
 
     IMPORT_C static CMTPTypeFile* NewL(RFs& aFs, const TDesC& aFileName, TFileMode aFileMode);
@@ -167,6 +204,14 @@
 	TInt64          iOffSet;
     
     mutable TInt64          iByteSent;
+    /*
+     * Use the writer to controll buffer1 write.
+     */
+    CFileWriter    *iFileWriter1;
+    /*
+     * Use the writer to controll buffer2 write.
+     */
+    CFileWriter    *iFileWriter2;
 
     };
     
--- a/mtpfws/mtpfw/datatypes/src/cmtptypefile.cpp	Mon Mar 08 21:44:10 2010 +0000
+++ b/mtpfws/mtpfw/datatypes/src/cmtptypefile.cpp	Sun Mar 14 13:12:01 2010 +0000
@@ -32,6 +32,80 @@
 
 const TUint KUSBHeaderLen = 12;
 
+
+
+CMTPTypeFile::CFileWriter* CMTPTypeFile::CFileWriter::NewL(RFile&  aFile, RBuf8& aWriteBuf)
+    {
+    CFileWriter *self = new(ELeave)CFileWriter(aFile, aWriteBuf);
+    CleanupStack::PushL(self);
+    self->ConstructL();
+    CleanupStack::Pop(self);
+    return self;
+    }
+
+void CMTPTypeFile::CFileWriter::GetWriteBuf(TPtr8& aChunk)
+    {
+    WaitForWriteComplete();
+    aChunk.Set(&iBuf[0], 0, iBuf.MaxLength());
+    }
+    
+TInt CMTPTypeFile::CFileWriter::GetResult() const
+    {
+    return iWriteResult;
+    }
+    
+void CMTPTypeFile::CFileWriter::Write(TInt aLength)
+    {
+    iFile.Write(iBuf, aLength, iStatus);
+    SetActive();
+    }
+    
+void CMTPTypeFile::CFileWriter::WaitForWriteComplete()
+    {
+    /*
+     * We didn't want to cancel the file write here.
+     * But we need to wait until the file write complete.
+     * The Cancel() function of CActive will do the wait until the file write complete.
+     * If the Write already complete and the RunL() invoked there's nothing happened in the Cancel().
+     */
+    Cancel(); 
+    //Have to save the result.
+    iWriteResult = iStatus.Int();
+    }
+
+void CMTPTypeFile::CFileWriter::RunL()
+    {
+    //Have to save the result.
+    iWriteResult = iStatus.Int();
+    }
+    
+    
+CMTPTypeFile::CFileWriter::~CFileWriter()
+    {
+    WaitForWriteComplete(); //make sure all async request complete
+    if(iWriteResult != KErrNone)
+        {
+        iFile.SetSize(0);
+        }
+    }
+
+
+void CMTPTypeFile::CFileWriter::DoCancel()
+    {
+    //We didn't really want to cancel the file write, so we do nothing here
+    }
+
+
+CMTPTypeFile::CFileWriter::CFileWriter(RFile&  aFile, RBuf8& aBuf):CActive(EPriorityStandard), iWriteResult(KErrNone), iFile(aFile), iBuf(aBuf) 
+    {
+    }
+    
+
+void CMTPTypeFile::CFileWriter::ConstructL()
+    {
+    CActiveScheduler::Add(this);
+    }
+
 /**
  MTP file object data type factory method. 
  @param aFs The handle of an active file server session.
@@ -88,13 +162,9 @@
  */
 EXPORT_C CMTPTypeFile::~CMTPTypeFile()
     {
-    if(iCurrentCommitChunk.Length() != 0)
-        {
-        ToggleRdWrBuffer();
-        }
-
+    delete iFileWriter1;
+    delete iFileWriter2;
     iFile.Close();
-
     iBuffer1.Close();
     iBuffer2.Close();
     Cancel();
@@ -133,6 +203,8 @@
         User::LeaveIfError(iFile.SetSize(aSize));
         iCurrentFileSetSize = aSize;
         }
+    iFileWriter1 = CFileWriter::NewL(iFile, iBuffer1);
+    iFileWriter2 = CFileWriter::NewL(iFile, iBuffer2);
     }
 
 /**
@@ -311,19 +383,14 @@
     TInt err(iFile.Seek(ESeekStart, pos));
     if (err == KErrNone)
         {
-        //Because USB HS's transmission rate is several time faster than the rate of writting data into File System.
-        //If the first packet is a full chunk size packet, then the writting of that data will not start until the full-chunk
-        //sized packet is received. Here we intentionly reduce the first packet size to 1/4 of the full chunk size, therefore,
-        //the start of writting data into File system will start only after 1/4 of the full chunk size data is received.
-        //This can make the writting of data to FS start earlier.
-        aChunk.Set(&iBuffer1[0], 0, iBuffer1.MaxLength());
+        iFileWriter1->GetWriteBuf(aChunk);
         iWriteSequenceState = EInProgress;
 
         //this chunk is going to be used by Transport to write data into it, and when it is full, transport
-        //will call back CommitChunkL(), at that time, the EFalse means it already contains data in it.
+        //will call back CommitChunkL(), at that time, the ETrue means it already contains data in it.
         //it is ready for reading data from it. 
         //This is a initial value for it to trigger the double-buffering mechanism.
-        iBuffer1AvailForWrite = EFalse;
+        iBuffer1AvailForWrite = ETrue;
         }
 
     return err;
@@ -342,11 +409,11 @@
         {//toggle between buffer 1 and buffer 2 here.
         if(iBuffer1AvailForWrite)
             {
-            aChunk.Set(&iBuffer1[0], 0, iBuffer1.MaxLength());
+            iFileWriter1->GetWriteBuf(aChunk);
             }
         else
             {
-            aChunk.Set(&iBuffer2[0], 0, iBuffer2.MaxLength());
+            iFileWriter2->GetWriteBuf(aChunk);
             }
         }
 
@@ -402,51 +469,43 @@
 
 EXPORT_C MMTPType* CMTPTypeFile::CommitChunkL(TPtr8& aChunk)
     {
-	if(iFileRdWrError)
-		{
-		return NULL;
-		}
-	if(0 == aChunk.Length())
-		{
-		ToggleRdWrBuffer();
-		return NULL;
-		}
+    if(iFileRdWrError)
+        {
+        return NULL;
+        }
     iCurrentCommitChunk.Set(aChunk);
-
     if(iRemainingDataSize> iCurrentCommitChunk.Length())
-        {//This is NOT the last chunk, we issue an active object to commit it to File system.
-        iRemainingDataSize -= iCurrentCommitChunk.Length();
-		/*
-		if (!IsActive())
-			{
-			//Since the writting data into file sever will take a long time, will issue a dedicated Active Object to do that.
-			SetActive();
-			TRequestStatus* thisAO = &iStatus;
-			User::RequestComplete(thisAO, KErrNone);
-			}
-		else
-			{
-			//This is a very extreme cases, it only occurs when the following assumption is met
-			//1. USB received buffer1 and already call this CommitChunkL(), therefore, the ActiveObject has completed itself, and USB then use another buffer to
-			//receive the data.
-			//2. Somehow, this active object is not scheduled to be running even after the USB already fill out the other buffer.
-			//3. USB's active object is scheduled to be running prior to the last File active object(this should not happen if ActiveScheduler follow the priority scheduler).
-			//4. USB call this function again to commit the other data buffer.
-			//5. Then it find the previous active is not scheduled to run.
-			//in single-core platform, the code rely on the CActiveScheduler to guarantee the first active call which has higher priority to be running firstly before
-			//the 2nd USB active. but for multi-core platform, this should be re-evaluated .
-			iFileRdWrError = ETrue;//if it really discard the incoming recevied file.			
-			//__FLOG(_L8("\nThe program should not arrive here !!!!!\n"));
-			}
-			*/
+        {
+        iRemainingDataSize -= iCurrentCommitChunk.Length();    
         }
     else
-        {//This is the last chunk, we synchronous commit it 
+        {
         iRemainingDataSize = 0;
-        ToggleRdWrBuffer();
-			return NULL;
+        }
+    //wait until previous write complete
+    if(iBuffer1AvailForWrite)
+        {
+        iFileWriter2->WaitForWriteComplete();
+        iFileRdWrError = (iFileWriter2->GetResult() != KErrNone); 
+        }
+    else
+        {
+        iFileWriter1->WaitForWriteComplete();
+        iFileRdWrError = (iFileWriter1->GetResult() != KErrNone);
         }
-	return this;
+    ToggleRdWrBuffer();
+    if(iRemainingDataSize <= 0) //last chunk need wait the write complete
+        {
+        iFileWriter1->WaitForWriteComplete();
+        iFileWriter2->WaitForWriteComplete();
+        if(iFileWriter1->GetResult() != KErrNone || iFileWriter2->GetResult() != KErrNone)
+            {
+            iFile.SetSize(0);
+            iFileRdWrError = ETrue;
+            }
+        }
+    
+    return NULL;
     }
 
 //for partial
@@ -590,17 +649,20 @@
                 }
             else
                 {
-                err = iFile.Write(iCurrentCommitChunk);
-                if (err != KErrNone)
-                    {// file Write failed,	this means we cannot successfully received this file but however, we cannot disrupt a current DIOR phase according to MTP spec.
-                    // We should continue to receive the data and discard this data, only after the data  phase is finished can we send back an error response
-                    //to Initiator. Therefore, we pretend to continue to write this data into file, and let final processor to check the file size and then give back a 
-                    //corresponding error code to MTP initiator.
-                    iFileRdWrError = ETrue;
-                    iFile.SetSize(0);
+                if(iBuffer1AvailForWrite)
+                    {
+                    iFileWriter1->Write(iCurrentCommitChunk.Length());
+                    }
+                else
+                    {
+                    iFileWriter2->Write(iCurrentCommitChunk.Length());
                     }
                 }
             }
+        else
+            {
+            iFile.SetSize(0);
+            }
         iCurrentCommitChunk.Zero();
         }
     else
--- a/mtpfws/mtpfw/inc/cmtpconnection.h	Mon Mar 08 21:44:10 2010 +0000
+++ b/mtpfws/mtpfw/inc/cmtpconnection.h	Sun Mar 14 13:12:01 2010 +0000
@@ -90,7 +90,7 @@
     IMPORT_C void SessionClosedL(TUint32 aSessionMTPId);
     IMPORT_C void SessionOpenedL(TUint32 aSessionMTPId);
     IMPORT_C TInt GetDataReceiveResult() const;
-    void ConnectionSuspended();
+    TBool ConnectionSuspended();
     void ConnectionResumedL(MMTPTransportConnection& aTransportConnection);
     void TransactionCompleteL(const TMTPTypeRequest& aRequest);
     
@@ -116,7 +116,7 @@
     void SendDataCompleteL(TInt aErr, const MMTPType& aData, const TMTPTypeRequest& aRequest);
     void SendEventCompleteL(TInt aErr, const TMTPTypeEvent& aEvent);
     void SendResponseCompleteL(TInt aErr, const TMTPTypeResponse& aResponse, const TMTPTypeRequest& aRequest);
-	void Unbind(MMTPTransportConnection& aConnection);
+    void Unbind(MMTPTransportConnection& aConnection);
 
 private:
 
@@ -132,6 +132,7 @@
     TUint ActiveSessions() const;
     void CloseAllSessions();
     void CloseSession(TUint aIdx);
+    void CompleteCloseConnection();
     CMTPSession& SessionL(const TMTPTypeFlatBase& aDataset, TInt aSessionIdElementNo) const;
     
     static TInt SessionOrder(const TUint32* aL, const CMTPSession& aR);
--- a/mtpfws/mtpfw/inc/cmtpconnectionmgr.h	Mon Mar 08 21:44:10 2010 +0000
+++ b/mtpfws/mtpfw/inc/cmtpconnectionmgr.h	Sun Mar 14 13:12:01 2010 +0000
@@ -54,6 +54,7 @@
     IMPORT_C CMTPConnection& ConnectionL(TUint aConnectionId) const;
     TUint ConnectionCount() const;
     CMTPConnection& operator[](TInt aIndex) const;
+	void ConnectionCloseComplete(const TUint& aConnUid);
     IMPORT_C void StartTransportL(TUid aTransport);
     IMPORT_C void StartTransportL(TUid aTransport, const TAny* aParameter);  
     IMPORT_C void QueueTransportL( TUid aTransport, const TAny* aParameter );
@@ -63,13 +64,11 @@
     IMPORT_C void StopTransports();
     IMPORT_C TInt TransportCount() const;
     IMPORT_C TUid TransportUid();
-	
-	    
+                  
 private: // From MMTPConnectionMgr
 
-    void ConnectionClosed(MMTPTransportConnection& aTransportConnection);
+    TBool ConnectionClosed(MMTPTransportConnection& aTransportConnection);
     void ConnectionOpenedL(MMTPTransportConnection& aTransportConnection);
-    TBool DeleteConnection(TUint aConnectionId);
     TUid ClientSId();
     
 private:
@@ -92,6 +91,7 @@
     TUid                            iTransportUid;
     TUint							iTransportCount;
     TUid 							iSecureId;
+    TBool                           iIsTransportStopping;
     
     /**
      * Array storing the UIDs of the suspended transport plugins
--- a/mtpfws/mtpfw/inc/cmtpdataprovidercontroller.h	Mon Mar 08 21:44:10 2010 +0000
+++ b/mtpfws/mtpfw/inc/cmtpdataprovidercontroller.h	Sun Mar 14 13:12:01 2010 +0000
@@ -62,7 +62,9 @@
         EEnumeratingDataProviderStorages    = 3,
         EEnumeratingFrameworkObjects        = 4,
         EEnumeratingDataProviderObjects     = 5,
-        EEnumerated                         = 6,
+        EEnumeratingPhaseOneDone            = 6,
+        EEnumeratingSubDirFiles				= 7, //Only File DP care the status.
+        EEnumeratedFulllyCompleted			= 8,
         };
         
 public:
@@ -90,6 +92,9 @@
 
     IMPORT_C void WaitForEnumerationComplete();
     TBool FreeEnumerationWaiter();
+    
+    IMPORT_C void SetNeedEnumeratingPhase2(TBool aNeed);
+    IMPORT_C TBool NeedEnumeratingPhase2() const;
 private: // From CActive
 
     void DoCancel();
@@ -115,7 +120,7 @@
     static void ImplementationsCleanup(TAny* aData);
     static TInt ImplementationsLinearOrderUid(const TUid* aUid, const CImplementationInformation& aObject);
     static TInt ImplementationsLinearOrderUid(const CImplementationInformation& aL, const CImplementationInformation& aR);
-        
+    
 private: // Owned
     /**
     FLOGGER debug trace member variable.
@@ -208,11 +213,12 @@
     opensession waiter
     */
     CActiveSchedulerWait *iOpenSessionWaiter;
-    
-    /**
-    Flag for Create DBSnapshot
-    */
-    TUint8 iFlagDb;
+
+    /*
+     The number of folders and files that will be enumerated.
+     */
+    TBool		iNeedEnumeratingPhase2;
+    TUint32 	iNeedEnumeratingPhase2StorageId;
 
     };
 
--- a/mtpfws/mtpfw/src/cmtpconnection.cpp	Mon Mar 08 21:44:10 2010 +0000
+++ b/mtpfws/mtpfw/src/cmtpconnection.cpp	Sun Mar 14 13:12:01 2010 +0000
@@ -108,14 +108,6 @@
     }
 
 /**
-Unbinds the Transport Connection
-*/    
-void CMTPConnection::Unbind(MMTPTransportConnection& /*aConnection*/)
-	{
-	iTransportConnection = NULL;
-	}
-
-/**
 Initiates MTP transaction data phase processing for initiator-to-responder
 data flows. This method should only be invoked when the MTP transaction phase 
 state is ERequestPhase. This is an asynchronous method.
@@ -351,45 +343,43 @@
  * Signals the connection is suspended, the connection state is set to EStateShutdown which 
  * means that all the current transaction will not be able to send/receive any data via the
  * connection
+ * @return ETrue - there is an active transaction currently, and Connection will suspend when it finishes
+ * EFalse - No active transaction, connection suspends immediately.
  */
-void CMTPConnection::ConnectionSuspended()
+TBool CMTPConnection::ConnectionSuspended()
     {
     __FLOG(_L8("ConnectionSuspended - Entry"));
     
+    TBool ret = EFalse;
     TUint currentState = State();
-    if (currentState!=EStateShutdown && currentState!=EStateErrorShutdown)
+    if (currentState != EStateShutdown)
         {
-        SetState(EStateShutdown);
-        
-        if (iTransportConnection != NULL)
-            {
-            iTransportConnection->Unbind(*this);
-            iTransportConnection = NULL;
-            }
-        PublishConnState(EDisconnectedFromHost);   
-    
-        if (ActiveSessions() == 0)
+        if (ActiveSessions() == 0 || currentState == EStateErrorShutdown)
             {
-            CloseAllSessions();
-            iSessions.Reset();
-            iSingletons.Close();
+            CompleteCloseConnection();
+            ret = ETrue;
             }
-        else 
-            {
-            //some session may be in data or response phase, complete them and set transaction phase to ECompletingPhase.
-            const TUint count(iSessions.Count());
-            for (TUint i(0); (i < count); i++)
-                {
-                if (iSessions[i]->TransactionPhase() & (EDataIToRPhase|EDataRToIPhase|EResponsePhase))
-                    {
-                    iSessions[i]->SetTransactionPhase(ECompletingPhase);
-                    iSessions[i]->CompletePendingRequest(KErrCancel);
-                    }
-                }
-            }
+        
+        SetState(EStateShutdown);
+        PublishConnState(EDisconnectedFromHost);   
         }
     
     __FLOG(_L8("ConnectionSuspended - Exit"));
+    return ret;
+    }
+
+void CMTPConnection::CompleteCloseConnection()
+    {
+    __FLOG(_L8("CompleteCloseConnection - Entry"));
+    
+    CloseAllSessions();
+    iSessions.Reset();
+    
+    //notify ConnectionMgr and corresponding transports of completion of connection close
+    iSingletons.ConnectionMgr().ConnectionCloseComplete(iConnectionId);    
+    iSingletons.Close();
+
+    __FLOG(_L8("CompleteCloseConnection - Exit"));
     }
 
 /*
@@ -439,24 +429,18 @@
     if (ValidFrameworkRequest(&session, KValidPhases, NULL))
         {
         session.SetTransactionPhase(EIdlePhase);
-        if (State() == EStateShutdown)
-            {
-            if (ActiveSessions() == 0)
-                {        
-                CloseAllSessions();
-                iSessions.Reset();
-                iSingletons.Close();
-                
-                // Move the log here because ShutdownComplete will delete this object.
-                __FLOG(_L8("TransactionCompleteL - Exit"));
-                }
+        
+        if (State() == EStateShutdown && ActiveSessions() == 0)
+            {     
+            CompleteCloseConnection();
             }
-        else
+        
+        if (iTransportConnection != NULL)
             {
             iTransportConnection->TransactionCompleteL(aRequest);
-            __FLOG(_L8("TransactionCompleteL - Exit"));
             }
         }
+    __FLOG(_L8("TransactionCompleteL - Exit"));
     }
     
 TUint CMTPConnection::ConnectionId() const
@@ -700,6 +684,11 @@
     __FLOG(_L8("SendResponseCompleteL - Exit"));
     }
 
+void CMTPConnection::Unbind(MMTPTransportConnection& /*aConnection*/)
+    {
+    iTransportConnection = NULL;
+    }
+
    
 TMTPTransactionPhase CMTPConnection::TransactionPhaseL(TUint32 aMTPId) const
     {
--- a/mtpfws/mtpfw/src/cmtpconnectionmgr.cpp	Mon Mar 08 21:44:10 2010 +0000
+++ b/mtpfws/mtpfw/src/cmtpconnectionmgr.cpp	Sun Mar 14 13:12:01 2010 +0000
@@ -93,6 +93,15 @@
     return iTransportUid;
     }
 
+void CMTPConnectionMgr::ConnectionCloseComplete(const TUint& /*aConnUid*/)
+    {
+    if (iIsTransportStopping)
+        {
+        iIsTransportStopping = EFalse;
+        ResumeSuspendedTransport();
+        }
+    }
+
 EXPORT_C void CMTPConnectionMgr::StartTransportL(TUid aTransport)
     {
     StartTransportL( aTransport, NULL );
@@ -187,14 +196,14 @@
             {
             TRAP_IGNORE( SuspendTransportL( aTransport ) );
             }
+        iIsTransportStopping = ETrue;
         iTransport->Stop(*this);
         delete iTransport;
         iTransport = NULL;
         iTransportUid = KNullUid;
         iTransportCount--;
-
-
         }
+    
     if ( aByBearer )
         {
         UnsuspendTransport( aTransport );
@@ -227,7 +236,7 @@
 	return iTransportCount;
     }
 
-void CMTPConnectionMgr::ConnectionClosed(MMTPTransportConnection& aTransportConnection)
+TBool CMTPConnectionMgr::ConnectionClosed(MMTPTransportConnection& aTransportConnection)
     {
     __FLOG(_L8("ConnectionClosed - Entry"));
     
@@ -236,11 +245,9 @@
     __ASSERT_DEBUG((idx != KErrNotFound), User::Invariant());
     
     CMTPConnection* connection(iConnections[idx]);
-    connection->ConnectionSuspended();
-    
-    ResumeSuspendedTransport();
     
     __FLOG(_L8("ConnectionClosed - Exit"));
+    return connection->ConnectionSuspended();
     }
     
 void CMTPConnectionMgr::ConnectionOpenedL(MMTPTransportConnection& aTransportConnection)
@@ -267,26 +274,6 @@
     __FLOG(_L8("ConnectionOpenedL - Exit"));
     }
 
-TBool CMTPConnectionMgr::DeleteConnection(TUint aConnectionId)
-    {
-    __FLOG(_L8("DeleteConnection - Entry"));
-    
-    TBool ret = EFalse;    
-    TInt idx = ConnectionFind(aConnectionId);
-    
-    if (idx != KErrNotFound)
-        {
-        CMTPConnection* connection(iConnections[idx]);
-        iConnections.Remove(idx);
-        delete connection;
-        ret = ETrue;
-        }
-    
-    __FLOG(_L8("DeleteConnection - Entry"));
-    
-    return ret;
-    }
-
 EXPORT_C TUid CMTPConnectionMgr::ClientSId()
 	{
 	return iSecureId;
@@ -297,7 +284,8 @@
 CMTPConnectionMgr::CMTPConnectionMgr() :
     iConnectionOrder(ConnectionOrderCompare),
     iShutdownConnectionIdx(KErrNotFound),
-	iTransportUid(KNullUid)
+	iTransportUid(KNullUid),
+	iIsTransportStopping(EFalse)
     {
     __FLOG_OPEN(KMTPSubsystem, KComponent);    
     }
--- a/mtpfws/mtpfw/src/cmtpdataprovider.cpp	Mon Mar 08 21:44:10 2010 +0000
+++ b/mtpfws/mtpfw/src/cmtpdataprovider.cpp	Sun Mar 14 13:12:01 2010 +0000
@@ -558,7 +558,7 @@
             }
         }
     
-		else if (iSingletons.DpController().EnumerateState() != CMTPDataProviderController::EEnumerated)
+		else if (iSingletons.DpController().EnumerateState() < CMTPDataProviderController::EEnumeratingPhaseOneDone)
     	{
         __FLOG(_L8("DP Enumeration is not complete"));
 
--- a/mtpfws/mtpfw/src/cmtpdataprovidercontroller.cpp	Mon Mar 08 21:44:10 2010 +0000
+++ b/mtpfws/mtpfw/src/cmtpdataprovidercontroller.cpp	Sun Mar 14 13:12:01 2010 +0000
@@ -236,7 +236,7 @@
         iEnumeratingStorages.AppendL(params->iStorageId);
         
         // Only schedule the operation start if there is not one currently underway.
-        if (iEnumerationState == EEnumerated)
+        if (iEnumerationState == EEnumeratedFulllyCompleted) 
             {
             iNextDpId           = iDpIdDeviceDp;
             iEnumerationState   = EEnumeratingFrameworkObjects;
@@ -385,7 +385,7 @@
 */ 
 EXPORT_C void CMTPDataProviderController::WaitForEnumerationComplete()
 {
-	if(EnumerateState() != CMTPDataProviderController::EEnumerated)
+	if(EnumerateState() < CMTPDataProviderController::EEnumeratingPhaseOneDone)
 		{
 		iOpenSessionWaiter->Start();
 		}
@@ -406,6 +406,7 @@
 void CMTPDataProviderController::EnumerationStateChangedL(const CMTPDataProvider& aDp)
     {
     __FLOG(_L8("EnumerationStateChangedL - Entry"));
+    __FLOG_VA((_L8("Entry iEnumerationState: 0x%x iNextDpId: %d"), iEnumerationState, iNextDpId));
     switch (iEnumerationState)
         {        
     case EEnumeratingFrameworkStorages:
@@ -463,27 +464,42 @@
             break;
             
         case KMTPImplementationUidFileDp:
-            iSingletons.ObjectMgr().RemoveNonPersistentObjectsL(aDp.DataProviderId());
-            // No other data providers
-            iNextDpId = 0;
-            iEnumeratingStorages.Remove(0);
-            if (iEnumeratingStorages.Count() == 0)
-                {
-                // No queued enumerations.
-                iSingletons.ObjectMgr().ObjectStore().CleanDBSnapshotL();
-                iEnumerationState   = EEnumerated;
-                Cancel();
-                if(iOpenSessionWaiter->IsStarted())
-                    {
-                    iOpenSessionWaiter->AsyncStop();
-                    }
-                }
-            else
-                {
-                // Queued enumerations.
-                iNextDpId           = iDpIdDeviceDp;
-                Schedule();
-                }
+			// No other data providers
+			if(NeedEnumeratingPhase2())
+				{
+				iEnumerationState = EEnumeratingSubDirFiles;
+				if(iOpenSessionWaiter->IsStarted())
+					{
+					iOpenSessionWaiter->AsyncStop();
+					}
+				//Schedule FildDP to enumerate the files in sub-dir
+				iNextDpId           = iDpIdFileDp;
+				Schedule();
+				}
+			else
+				{
+				iNextDpId = 0;
+				iEnumeratingStorages.Remove(0);
+				if (iEnumeratingStorages.Count() == 0)
+					{
+					iSingletons.ObjectMgr().RemoveNonPersistentObjectsL(aDp.DataProviderId());
+					iEnumerationState   = EEnumeratedFulllyCompleted;
+					iSingletons.ObjectMgr().ObjectStore().CleanDBSnapshotL();
+						
+					Cancel();
+					if(iOpenSessionWaiter->IsStarted())
+						{
+						iOpenSessionWaiter->AsyncStop();
+						}
+					}
+				else
+					{
+					// Queued enumerations.
+					iNextDpId           = iDpIdDeviceDp;
+					Schedule();
+					}
+				}
+        		
             }
         break;
         
@@ -496,9 +512,23 @@
         if ((iEnumeratingDps.Count() == 0) && iDpIdArrayIndex >= iDataProviderIds.Count())
             {
             // Enumeration complete.
-            iNextDpId = 0;
             iNextDpId           = iDpIdFileDp;
             iEnumerationState   = EEnumeratingFrameworkObjects;
+            			
+			if ( ( iEnumeratingStorages.Count() > 1 ) &&(KErrNotFound != iEnumeratingStorages.Find(KMTPStorageAll)) )
+				{
+				const TUint storageid = iEnumeratingStorages[0];
+				iEnumeratingStorages.Remove(0);
+				if(KMTPStorageAll == storageid)
+					{
+					iEnumeratingStorages.Append(KMTPStorageAll);
+					}
+				
+				if(iEnumeratingStorages[0] != KMTPStorageAll)
+					{
+					iNextDpId = iDpIdDeviceDp;
+					}
+				}
             }
         else
             {
@@ -511,13 +541,39 @@
         Schedule();        
         break;
         
+    case EEnumeratingSubDirFiles:
+    	{
+    	if(aDp.ImplementationUid().iUid == KMTPImplementationUidFileDp)
+    		{
+			iSingletons.ObjectMgr().RemoveNonPersistentObjectsL(aDp.DataProviderId());
+			iNextDpId = 0;
+			iEnumeratingStorages.Remove(0);
+			if(iEnumeratingStorages.Count() == 0)
+				{
+				iSingletons.DpController().SetNeedEnumeratingPhase2(EFalse);
+				iEnumerationState   = EEnumeratedFulllyCompleted;
+				iSingletons.ObjectMgr().ObjectStore().CleanDBSnapshotL();
+				}
+			else //removable card plug in
+				{
+				iNextDpId           = iDpIdDeviceDp;
+				iEnumerationState   = EEnumeratingFrameworkObjects;
+				Schedule();
+				}
+    		}
+    	}
+    	break;
+    	
+    case EEnumeratedFulllyCompleted:
     case EUnenumerated:
     case EEnumerationStarting:
-    case EEnumerated:
+    case EEnumeratingPhaseOneDone:
     default:
         __DEBUG_ONLY(User::Invariant());
         break;
         }
+    
+    __FLOG_VA((_L8("Exit iEnumerationState: 0x%x, iNextDpId: %d, UID=0x%x"), iEnumerationState, iNextDpId, aDp.ImplementationUid().iUid));
     __FLOG(_L8("EnumerationStateChangedL - Exit"));
     }
 
@@ -556,8 +612,6 @@
             iNextDpId           = iDpIdDeviceDp;
             iEnumerationState   = EEnumeratingFrameworkObjects;
 	
-            
-        
             Schedule();
             }
         break;
@@ -573,7 +627,7 @@
             iEnumeratingStorages.Remove(0);
             if (iEnumeratingStorages.Count() == 0)
                 {
-                iEnumerationState = EEnumerated;
+                iEnumerationState = EEnumeratedFulllyCompleted;
                 }
             else
                 {
@@ -591,21 +645,22 @@
                     {
                     iSingletons.ObjectMgr().ObjectStore().EstablishDBSnapshotL(storageId);
                     }
-                else
+                else 
                     {
-                    const CMTPStorageMetaData& storage(iSingletons.StorageMgr().StorageL(storageId));
-                    if(storage.Uint(CMTPStorageMetaData::EStorageSystemType) == CMTPStorageMetaData::ESystemTypeDefaultFileSystem)
-                        {
-                        const RArray<TUint>& logicalIds(storage.UintArray(CMTPStorageMetaData::EStorageLogicalIds));
-                        const TUint KCountLogicalIds(logicalIds.Count());
-                        for (TUint i(0); (i < KCountLogicalIds); i++)
-                            {
-                            __FLOG_VA((_L8("Establish snapshot for storage: 0x%x"), storageId));
-                            iSingletons.ObjectMgr().ObjectStore().EstablishDBSnapshotL(storageId);
-                            }
-                        }
+					const CMTPStorageMetaData& storage(iSingletons.StorageMgr().StorageL(storageId));
+                	if(storage.Uint(CMTPStorageMetaData::EStorageSystemType) == CMTPStorageMetaData::ESystemTypeDefaultFileSystem)
+                		{
+						const RArray<TUint>& logicalIds(storage.UintArray(CMTPStorageMetaData::EStorageLogicalIds));
+						const TUint KCountLogicalIds(logicalIds.Count());
+						for (TUint i(0); (i < KCountLogicalIds); i++)
+							{
+							__FLOG_VA((_L8("Establish snapshot for storage: 0x%x"), logicalIds[i]));
+							iSingletons.ObjectMgr().ObjectStore().EstablishDBSnapshotL(logicalIds[i]);
+							}	
+                		}
                     }
                 }
+            	
             EnumerateDataProviderObjectsL(iNextDpId);          
             }
         	}
@@ -624,11 +679,19 @@
             iEnumeratingDps.InsertInOrderL(currentDp);
             EnumerateDataProviderObjectsL(currentDp);
             }
+        
+        __FLOG_VA((_L8("iDpIdArrayIndex = %d, KLoadedDps = %d"), iDpIdArrayIndex, KLoadedDps));
         }
         break;
         
+    case EEnumeratingSubDirFiles:
+    	{
+    	EnumerateDataProviderObjectsL(iNextDpId); 
+    	}
+    	break;
+    case EEnumeratedFulllyCompleted:
     case EUnenumerated:
-    case EEnumerated:
+    case EEnumeratingPhaseOneDone:
     default:
         __DEBUG_ONLY(User::Invariant());
         break;
@@ -666,7 +729,7 @@
         break;
         
     case EUnenumerated:
-    case EEnumerated:
+    case EEnumeratingPhaseOneDone:
     default:
         User::Invariant();
         break;
@@ -709,7 +772,7 @@
 	iMode = (TMTPOperationalMode)tMTPMode;
 	CreateRegistrySessionAndEntryL();
     
-	iFlagDb = 0;
+	SetNeedEnumeratingPhase2(EFalse);
 	
     iOpenSessionWaiter = new(ELeave) CActiveSchedulerWait();
     __FLOG(_L8("ConstructL - Exit"));
@@ -1148,3 +1211,18 @@
 	iSisSession.Close();
 	}
 
+EXPORT_C void CMTPDataProviderController::SetNeedEnumeratingPhase2(TBool aNeed)
+	{
+	__FLOG(_L8("SetNeedEnumeratingPhase2 - Entry"));
+	__FLOG_VA((_L8("Need = %d"), aNeed)); 
+	
+	iNeedEnumeratingPhase2 = aNeed;
+	
+	__FLOG(_L8("SetNeedEnumeratingPhase2 - Exit"));
+	}
+
+EXPORT_C TBool CMTPDataProviderController::NeedEnumeratingPhase2() const
+	{
+	return iNeedEnumeratingPhase2;
+	}
+
--- a/mtpfws/mtpfw/src/cmtpobjectstore.cpp	Mon Mar 08 21:44:10 2010 +0000
+++ b/mtpfws/mtpfw/src/cmtpobjectstore.cpp	Sun Mar 14 13:12:01 2010 +0000
@@ -385,6 +385,7 @@
 	TBool needToInsert = EFalse;
 	TBool needUpdateOwner = EFalse;
 	TUint dpId(aObject.Uint(CMTPObjectMetaData::EDataProviderId));
+
 	TFileName suid;
 	suid.CopyLC(aObject.DesC(CMTPObjectMetaData::ESuid));
 	TUint32 suidHash = DefaultHash::Des16(suid);
@@ -392,7 +393,7 @@
 	TUint32 handle = KMTPHandleNone, handleInDB = KMTPHandleAll;
 	TInt64 id = 0;
 	// Check if the dp is enumerating
-	if (iSingletons.DpController().EnumerateState() != CMTPDataProviderController::EEnumerated && iCacheExist)
+	if (iSingletons.DpController().EnumerateState() != CMTPDataProviderController::EEnumeratedFulllyCompleted && iCacheExist)
 		{
 		//it is in the object enumeration phase. 
 		// if it's see if we have an object with the same SUID
@@ -438,7 +439,8 @@
 				}
 			else
 				{
-				User::Leave(KErrAlreadyExists);
+				//while enumerating, we ignore the repeatedly INSERT operations.
+				//User::Leave(KErrAlreadyExists);
 				}
 			}
 		}
@@ -686,7 +688,7 @@
 	{
 	if (LocateByHandleL(aHandle.Value()))
 		{
-		if (iSingletons.DpController().EnumerateState() != CMTPDataProviderController::EEnumerated &&
+		if (iSingletons.DpController().EnumerateState() != CMTPDataProviderController::EEnumeratedFulllyCompleted &&
 			IsMediaFormat(iBatched.ColUint16(EObjectStoreFormatCode)))
 			{
 			iMtpDeltaDataMgr->UpdateDeltaDataTableL(iBatched.ColInt64(EObjectStorePOUID), CMtpDeltaDataMgr::EDeleted);
@@ -702,7 +704,7 @@
 	{
 	if(LocateBySuidL(aSuid))
 		{
-		if (iSingletons.DpController().EnumerateState() != CMTPDataProviderController::EEnumerated &&
+		if (iSingletons.DpController().EnumerateState() != CMTPDataProviderController::EEnumeratedFulllyCompleted &&
 			IsMediaFormat(iBatched_SuidHashID.ColUint16(EObjectStoreFormatCode)))
 			{
 			iMtpDeltaDataMgr->UpdateDeltaDataTableL(iBatched_SuidHashID.ColInt64(EObjectStorePOUID), CMtpDeltaDataMgr::EDeleted);
--- a/mtpfws/mtpfw/transports/transportapi/inc/mmtpconnectionmgr.h	Mon Mar 08 21:44:10 2010 +0000
+++ b/mtpfws/mtpfw/transports/transportapi/inc/mmtpconnectionmgr.h	Sun Mar 14 13:12:01 2010 +0000
@@ -39,8 +39,13 @@
     Signals that an MTP transport layer connection has become unavailable.
     @param aTransportConnection Interface handle of the MTP transport layer 
     connection instance.
+    @return ETrue means MTP framework successfully cleanup ts env and can accept
+    another ConnectionOpendedL call. EFalse means there is a transaction alive currently,
+    ConnectionOpenedL must not be called until MMTPTransportConnection::TransactionCompleteL is called.
+    @see MMTPConnectionMgr::ConnectionOpenedL()
+    @see MMTPTransportConnection::TransactionCompleteL()
     */
-    virtual void ConnectionClosed(MMTPTransportConnection& aTransportConnection) = 0;
+    virtual TBool ConnectionClosed(MMTPTransportConnection& aTransportConnection) = 0;
     
     /**
     Signals that an MTP transport layer connection has become available.
@@ -56,4 +61,4 @@
     virtual TUid ClientSId()=0;
             
     };
-#endif // MMTPCONNECTIONMGR_H
\ No newline at end of file
+#endif // MMTPCONNECTIONMGR_H
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mtpfws/mtpintegrationtest/integration/mtpmodeselector/inc/CMAppGroupView.H	Sun Mar 14 13:12:01 2010 +0000
@@ -0,0 +1,48 @@
+// Copyright (c) 1997-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:
+//
+
+/**
+ @file
+ @internalComponent 
+ @test
+*/
+#if !defined(__CMAPPGroupVIEW_H__)
+#define __CMAPPGroupVIEW_H__
+
+#include "CMLSTVW.H"
+
+
+class CContactsManAppGroupView : public CContactsManListView
+	{
+public:
+	static CContactsManAppGroupView* NewL(CCoeControl& aContainer,CContactsAppModel& aModel);
+	TInt CurrentItemIndex();
+	TInt NumberOfItems();
+private:
+	CContactsManAppGroupView(CContactsAppModel& aModel,TContactsListViewPrefs* aPreferences);
+	void NewGroupL();
+// from CContactsManViewBase
+	virtual void HandleModelChangeL(TBool aCountChanged);
+	virtual TBool HandleCommandL(TInt aCommand);		
+	virtual TUid ViewUid() const;
+//from 	MCoeView
+	virtual void ViewActivatedL(const TVwsViewId& aPrevViewId, TUid aCustomMessageId, const TDesC8& aCustomMessage);
+	virtual void ViewDeactivated();
+// from CCoeControl
+	virtual TKeyResponse OfferKeyEventL(const TKeyEvent& aKeyEvent,TEventCode aType);
+	void ConstructL(CCoeControl& aContainer);
+	};
+
+#endif // __CMAPPGroupVIEW_H__
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mtpfws/mtpintegrationtest/integration/mtpmodeselector/inc/CtransportInitiator.h	Sun Mar 14 13:12:01 2010 +0000
@@ -0,0 +1,53 @@
+// This material, including documentation and any related computer
+// programs, is protected by copyright controlled by Nokia. All
+// rights are reserved. Copying, including reproducing, storing
+// adapting or translating, any or all of this material requires the
+// prior written consent of Nokia. This material also contains
+// confidential information which may not be disclosed to others
+// without the prior written consent of Nokia.
+
+
+
+/**
+ @file CtransportInitiator.h
+*/
+ #ifndef __CTRANSPORTINITIATOR_H__
+ #define __CTRANSPORTINITIATOR_H__
+ #include <e32base.h>
+ #include <f32file.h>
+ #include <bautils.h> 
+ #include <mtp/mtpdataproviderapitypes.h>
+ 
+ 
+ _LIT(KCMTPTest, "c:\\mtptest\\");
+_LIT(KZMTPTest, "z:\\mtptest\\");
+/**
+ class CtransportInitiator
+ Descibes creation of subset drives 
+ Running and stopping the transport as wished by the user
+*/ 
+ class CtransportInitiator: public CBase
+	 {
+	 public :
+	      static CtransportInitiator* NewL();
+	      ~CtransportInitiator();
+	      
+	 private:
+	     void ConstructL();	 
+	     CtransportInitiator();
+	 
+	 public :
+	     void SetModeL(TMTPOperationalMode aMode);
+	     void RunMtpL();
+	     TInt DeleteMTPTestStorages();
+	     TInt CreateMTPTestStoragesL();    	
+	 };
+	 
+#endif	 
+
+	 
+ 
+ 
+ 
+ 
+ 
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mtpfws/mtpintegrationtest/integration/mtpmodeselector/inc/MtpModeSelector.h	Sun Mar 14 13:12:01 2010 +0000
@@ -0,0 +1,122 @@
+// This material, including documentation and any related computer
+// programs, is protected by copyright controlled by Nokia. All
+// rights are reserved. Copying, including reproducing, storing
+// adapting or translating, any or all of this material requires the
+// prior written consent of Nokia. This material also contains
+// confidential information which may not be disclosed to others
+// without the prior written consent of Nokia.
+
+
+
+/**
+ @file
+ @internalComponent
+ @test
+*/
+#ifndef __MTPMODESELECTOR_H__
+#define __MTPMODESELECTOR_H__
+
+#include <eikdialg.h>
+#include <eikchlst.h>
+#include "CtransportInitiator.h"
+
+
+class CMtpModeSelectorDlg : public CEikDialog
+	{
+public:	
+	static CMtpModeSelectorDlg* NewL();
+	CMtpModeSelectorDlg();
+   
+private:
+    void ConstructL();
+	~CMtpModeSelectorDlg();
+	// from CEikDialog
+	TBool OkToExitL(TInt aButtonId);
+	void PreLayoutDynInitL();
+public :
+    CtransportInitiator* iTransportInitiator;	
+	
+	};
+	
+
+	
+/**
+ *	CModeSelectorAppView for creating a window and to draw the text
+ *	
+ */  
+class CModeSelectorAppView : public CCoeControl
+    {
+public:
+	// creates a CModeSelectorAppView object
+	static CModeSelectorAppView* NewL(const TRect& aRect);
+	~CModeSelectorAppView();
+private:
+	CModeSelectorAppView();
+	void ConstructL(const TRect& aRect);
+	//Draws the text on the screen	           
+	void Draw(const TRect& /*aRect*/) const;
+
+private:
+	//contains the text needs to be drawn
+	HBufC*  iExampleText;
+    };
+    
+    
+/**
+ *	CModeSelectorAppUi handles the system events and menu events
+ *	
+ */  
+class CModeSelectorAppUi : public CEikAppUi
+    {
+public:
+    void ConstructL();
+	~CModeSelectorAppUi();
+
+private:
+    // Inherirted from class CEikAppUi for handling menu events
+	void HandleCommandL(TInt aCommand);
+	
+	// From CCoeAppUi to handle system events
+	void HandleSystemEventL(const TWsEvent& aEvent);
+
+private:
+	CCoeControl* iAppView;
+	};
+
+
+/**
+ *	CExampleDocument for creating the application UI
+ *	
+ */  
+class CModeSelectorDocument : public CEikDocument
+	{
+public:
+	// creates a CExampleDocument object
+	static CModeSelectorDocument* NewL(CEikApplication& aApp);
+	CModeSelectorDocument(CEikApplication& aApp);
+	void ConstructL();
+private: 
+	// Inherited from CEikDocument for creating the AppUI
+	CEikAppUi* CreateAppUiL();
+	};
+	
+	
+	
+/**
+ *	CExampleApplication creates a new instance of the document 
+ *   associated with this application
+ *	
+ */  
+class CModeSelectorApplication : public CEikApplication
+	{
+private: 
+	// Inherited from class CApaApplication to create a new instance of the document
+	CApaDocument* CreateDocumentL();
+	//gets teh Application's UID
+	TUid AppDllUid() const;
+	};	 
+	
+#endif	   
+	
+
+	
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mtpfws/mtpintegrationtest/integration/mtpmodeselector/inc/mtpstarter.h	Sun Mar 14 13:12:01 2010 +0000
@@ -0,0 +1,18 @@
+// This material, including documentation and any related computer
+// programs, is protected by copyright controlled by Nokia. All
+// rights are reserved. Copying, including reproducing, storing
+// adapting or translating, any or all of this material requires the
+// prior written consent of Nokia. This material also contains
+// confidential information which may not be disclosed to others
+// without the prior written consent of Nokia.
+
+
+
+#ifndef __MTPSTARTER_H__
+#define __MTPSTARTER_H__
+
+
+TInt StartMTP();
+TInt StopMTP();
+
+#endif // MTPSTARTER_H
--- a/mtptransports/mtpptpiptransport/ptpipplugin/src/cptpipconnection.cpp	Mon Mar 08 21:44:10 2010 +0000
+++ b/mtptransports/mtpptpiptransport/ptpipplugin/src/cptpipconnection.cpp	Sun Mar 14 13:12:01 2010 +0000
@@ -68,6 +68,11 @@
 	delete iPTPIPCommandContainer;
 	delete iPTPIPDataContainer;
 	delete iPTPIPEventContainer;
+
+        if (iProtocolLayer != NULL)
+           {
+           iProtocolLayer->Unbind(*this);
+           }
 	
 	iNullBuffer.Close();
 
--- a/mtptransports/mtpusbtransport/usbsic_imp/inc/cmtpusbconnection.h	Mon Mar 08 21:44:10 2010 +0000
+++ b/mtptransports/mtpusbtransport/usbsic_imp/inc/cmtpusbconnection.h	Sun Mar 14 13:12:01 2010 +0000
@@ -150,7 +150,7 @@
     
     void ResumeConnectionL();
     void StartConnectionL();
-    void StopConnection();
+    TBool StopConnection();
     void SuspendConnectionL();
     
     void StartUsbL();
@@ -418,6 +418,12 @@
 	TBool 												iIsCancelReceived;
 	
     /**
+    A flag to reflect if a Host initiated cancel transaction
+    is triggered.
+    */
+    TBool                                               iIsResetRequestSignaled;
+	
+    /**
     FLOGGER debug trace member variable.
     */
     __FLOG_DECLARATION_MEMBER_MUTABLE;
--- a/mtptransports/mtpusbtransport/usbsic_imp/src/cmtpusbconnection.cpp	Mon Mar 08 21:44:10 2010 +0000
+++ b/mtptransports/mtpusbtransport/usbsic_imp/src/cmtpusbconnection.cpp	Sun Mar 14 13:12:01 2010 +0000
@@ -78,7 +78,7 @@
 CMTPUsbConnection::~CMTPUsbConnection()
     {
     __FLOG(_L8("~CMTPUsbConnection - Entry"));
-
+    
     // Terminate all endpoint data transfer activity.
     StopConnection();
         
@@ -91,11 +91,13 @@
     StopUsb();
     
     iNullBuffer.Close();
-    if (iProtocolLayer)
-	    {    	
-	    iProtocolLayer->Unbind(*this);
-	    }
 
+    if (iProtocolLayer != NULL)
+        {
+        BoundProtocolLayer().Unbind(*this);
+        }
+    iProtocolLayer = NULL;
+    
     __FLOG(_L8("~CMTPUsbConnection - Exit"));
     __FLOG_CLOSE;
     }
@@ -331,21 +333,27 @@
     __FLOG(_L8("TransactionCompleteL - Entry"));
    
    	__FLOG_VA((_L8("DeviceState: 0x%x TransactionState: 0x%x"), iDeviceStatusCode, iBulkTransactionState));
-    
-    if (iBulkTransactionState != ERequestPhase)
-    	{
-	    // Update the transaction state.
-    	SetBulkTransactionState(EIdlePhase);
-    	
-   		// Update the device status
-   		SetDeviceStatus(EMTPUsbDeviceStatusOK); 
-   		
-   		// Clear the cancel flag.
-   		iIsCancelReceived = EFalse; 
-   		
-   		// Initiate the next request phase bulk data receive sequence.
-   		InitiateBulkRequestSequenceL();
-    	}
+   	
+   	if (iBulkTransactionState != ERequestPhase)
+   	    {
+        // Update the transaction state.
+        SetBulkTransactionState(EIdlePhase);    
+        // Update the device status
+        SetDeviceStatus(EMTPUsbDeviceStatusOK);     
+        // Clear the cancel flag.
+        iIsCancelReceived = EFalse; 
+        
+        if (ConnectionOpen())
+            {
+            // Initiate the next request phase bulk data receive sequence.
+            InitiateBulkRequestSequenceL();   		    
+            }
+        else if (iIsResetRequestSignaled)
+            {
+            iIsResetRequestSignaled = EFalse;
+            StartConnectionL();
+            }
+   	    }
     
     __FLOG(_L8("TransactionCompleteL - Exit"));
     } 
@@ -587,8 +595,7 @@
         {
         TUint16 containerType(iUsbBulkContainer->Uint16L(CMTPUsbContainer::EContainerType));
 
-#ifdef _DEBUG        
-      
+#ifdef _DEBUG              
         TUint16 transactionID(iUsbBulkContainer->Uint32L(CMTPUsbContainer::ETransactionID));
         RDebug::Print(_L("Time Stamp is :%d"), User::TickCount());
         RDebug::Print(_L("the container Type is 0x%x, the transaction ID is 0x%x\n"), containerType,transactionID);
@@ -906,6 +913,8 @@
 CMTPUsbConnection::CMTPUsbConnection(MMTPConnectionMgr& aConnectionMgr) :
     CActive(EPriorityStandard),
     iEndpointInfo(KEndpointMetaData, EMTPUsbEpNumEndpoints),
+    iIsCancelReceived(EFalse),
+    iIsResetRequestSignaled(EFalse),
     iConnectionMgr(&aConnectionMgr)
     {
     CActiveScheduler::Add(this);
@@ -1233,7 +1242,7 @@
 void CMTPUsbConnection::ProcessControlRequestDeviceResetL(const TMTPUsbControlRequestSetup& /*aRequest*/)
     {
     __FLOG(_L8("ProcessControlRequestDeviceResetL - Entry"));
-                
+    
     // Clear stalled endpoints and re-open connection
     BulkEndpointsStallClearL();
     StartConnectionL();
@@ -1243,9 +1252,18 @@
     sequence and initiate the next control request sequence. 
     */
     static_cast<CMTPUsbEpControl*>(iEndpoints[EMTPUsbEpControl])->SendControlRequestStatus();
-    StopConnection();
+    TBool connIsStopped = StopConnection();
     InitiateControlRequestSequenceL();
-    StartConnectionL();
+    
+    if (connIsStopped)
+        {
+        StartConnectionL();
+        }
+    else
+        {
+        iIsResetRequestSignaled = ETrue;
+        }
+
     __FLOG(_L8("ProcessControlRequestDeviceResetL - Exit"));
     }
     
@@ -1261,8 +1279,7 @@
     
     TUint offset = 0;
     for(TUint i(EMTPUsbEpControl); i<EMTPUsbEpNumEndpoints; ++i)
-    	{
-        
+    	{        
         if ( IsEpStalled(i) )
             {
             TInt epSize(0);
@@ -1277,16 +1294,11 @@
             //but in practice, it's requested by host with a 32-bit value, so we plus offset with 4 to reflect this.
             TUint32 epAddress = epDesc[KEpAddressOffsetInEpDesc];
             iUsbControlRequestDeviceStatus.SetUint32((offset + TMTPUsbControlRequestDeviceStatus::EParameter1), epAddress);            
-            CleanupStack::PopAndDestroy(); // calls epDesc.Close()
-            
+            CleanupStack::PopAndDestroy(); // calls epDesc.Close()            
             ++offset;
             }
         }
-   
 
-  
-   
-    
     // if the current status is OK and a cancel event has been received but the device has not respond 
     // transaction_cancelled yet, return transaction_cancelled firstly.
     TUint16 originalStatus = iDeviceStatusCode;
@@ -1296,10 +1308,7 @@
     	  // clear the transaction cancelled flag
         isResponseTransactionCancelledNeeded = false;
     	}
-    
-    
 
-    
     // Set the Code and wLength fields and send the dataset.
     iUsbControlRequestDeviceStatus.SetUint16(TMTPUsbControlRequestDeviceStatus::ECode, iDeviceStatusCode);
     iUsbControlRequestDeviceStatus.SetUint16(TMTPUsbControlRequestDeviceStatus::EwLength, iUsbControlRequestDeviceStatus.Size());
@@ -1511,7 +1520,6 @@
     __FLOG(_L8("BulkEndpointsStallL - Entry"));
     EndpointStallL(EMTPUsbEpBulkIn);
     EndpointStallL(EMTPUsbEpBulkOut);
-    SetDeviceStatus(EMTPUsbDeviceStatusTransactionCancelled);
     __FLOG(_L8("BulkEndpointsStallL - Exit"));
     }
 
@@ -1523,7 +1531,6 @@
     __FLOG(_L8("BulkEndpointsStallClearL - Entry"));
     EndpointStallClearL(EMTPUsbEpBulkIn);
     EndpointStallClearL(EMTPUsbEpBulkOut);
-    SetDeviceStatus(EMTPUsbDeviceStatusOK);
     __FLOG(_L8("BulkEndpointsStallClearL - Exit"));  
     }
 
@@ -1582,14 +1589,9 @@
     CMTPUsbEpBase& ep(*iEndpoints[aId]);
     ep.Stall();
     
-    // Stop the connection.
-    StopConnection();
+    // Update the connection state.
+    SetConnectionState(EStalled);
     
-    // Update the connection state.
-    if (!(ConnectionState() & EStalled))
-        {
-        SetConnectionState(EStalled);
-        }
     __FLOG(_L8("EndpointStallL - Exit"));
     }
     
@@ -1617,7 +1619,7 @@
         else if (!IsEpStalled( aId ) )
             {
             // All data endpoint stall conditions are clear.
-          	SetConnectionState(EIdlePhase);
+          	SetConnectionState(EIdle);
             }
         }
     __FLOG(_L8("EndpointStallClearL - Exit"));
@@ -1651,8 +1653,9 @@
     if (ConnectionClosed())
         {
         __FLOG(_L8("Notifying protocol layer connection opened"));
-        iConnectionMgr->ConnectionOpenedL(*this);  
+        iConnectionMgr->ConnectionOpenedL(*this);
         SetConnectionState(EOpen);
+        SetDeviceStatus(EMTPUsbDeviceStatusOK);
         InitiateBulkRequestSequenceL();
         }
     __FLOG(_L8("StartConnectionL - Exit"));
@@ -1661,10 +1664,11 @@
 /**
 Halts USB MTP device class processing.
 */ 
-void CMTPUsbConnection::StopConnection()
+TBool CMTPUsbConnection::StopConnection()
     {
     __FLOG(_L8("StopConnection - Entry"));
     
+    TBool ret = ETrue;
     // Stop all data transfer activity.
     DataEndpointsStop();    
     
@@ -1672,13 +1676,16 @@
     if (ConnectionOpen())
         {
         __FLOG(_L8("Notifying protocol layer connection closed"));
-        iConnectionMgr->ConnectionClosed(*this);
+        ret = iConnectionMgr->ConnectionClosed(*this);
         SetBulkTransactionState(EUndefined);
         SetConnectionState(EIdle);
         SetSuspendState(ENotSuspended);
+        SetDeviceStatus(EMTPUsbDeviceStatusBusy);
         }
     
     __FLOG(_L8("StopConnection - Exit"));
+    
+    return ret;
     }
        
 /**
@@ -1706,7 +1713,7 @@
 */
 void CMTPUsbConnection::StartUsbL()
     {
-    __FLOG(_L8("StartUsbL - Exit"));
+    __FLOG(_L8("StartUsbL - Entry"));
     
     // Open the USB device interface.
     User::LeaveIfError(iLdd.Open(KDefaultUsbClientController));
--- a/obex/obexprotocol/obex/public/obexbase.h	Mon Mar 08 21:44:10 2010 +0000
+++ b/obex/obexprotocol/obex/public/obexbase.h	Sun Mar 14 13:12:01 2010 +0000
@@ -164,10 +164,17 @@
 	IMPORT_C TBool IsConnected() const;
 	IMPORT_C TBool IsStrictPeer() const;
 	IMPORT_C const TObexConnectInfo& LocalInfo() const;
-	IMPORT_C TInt SetLocalWho(const TDesC8& aInfo); 
-    IMPORT_C const TObexConnectInfo& RemoteInfo() const;
-   	IMPORT_C void SuppressAuthenticationHeaderElements(TObexSuppressedAuthElements aSuppressedObexAuthElements);
+	IMPORT_C TInt SetLocalWho(const TDesC8& aInfo);
+	IMPORT_C const TObexConnectInfo& RemoteInfo() const;
+	IMPORT_C void SuppressAuthenticationHeaderElements(TObexSuppressedAuthElements aSuppressedObexAuthElements);
 	
+public: // Implementation of MObexNotify Interface (No longer used)
+	virtual void Process(CObexPacket& aPacket);
+	virtual void Error(TInt aError);
+	virtual void TransportUp();
+	virtual void TransportDown(TBool aForceTransportDeletion);
+	
+public:
 	virtual void UserPasswordL( const TDesC& aPassword) = 0; 
 	IMPORT_C void RemoteAddr(TSockAddr& anAddr); 
 
@@ -181,12 +188,6 @@
 	void NotifyTransportUp();
 	void NotifyTransportDown(TBool);
 	
-public: // Implementation of MObexNotify Interface (No longer used)
-	virtual void Process(CObexPacket& aPacket);
-	virtual void Error(TInt aError) ;
-	virtual void TransportUp();
-	virtual void TransportDown(TBool aForceTransportDeletion);
-	
 protected:
 	CObex();
 	virtual void ConstructL(TObexTransportInfo& aObexTransportInfo);