Added notification messages for conflicts and multifile operations on Pithos.Core...
[pithos-ms-client] / trunk / Pithos.Core / Agents / NetworkAgent.cs
index aa087af..6ce712a 100644 (file)
@@ -1,4 +1,42 @@
-using System;
+// -----------------------------------------------------------------------
+// <copyright file="NetworkAgent.cs" company="GRNET">
+// Copyright 2011 GRNET S.A. All rights reserved.
+// 
+// Redistribution and use in source and binary forms, with or
+// without modification, are permitted provided that the following
+// conditions are met:
+// 
+//   1. Redistributions of source code must retain the above
+//      copyright notice, this list of conditions and the following
+//      disclaimer.
+// 
+//   2. Redistributions in binary form must reproduce the above
+//      copyright notice, this list of conditions and the following
+//      disclaimer in the documentation and/or other materials
+//      provided with the distribution.
+// 
+// THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
+// OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
+// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
+// USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
+// AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
+// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+// POSSIBILITY OF SUCH DAMAGE.
+// 
+// The views and conclusions contained in the software and
+// documentation are those of the authors and should not be
+// interpreted as representing official policies, either expressed
+// or implied, of GRNET S.A.
+// </copyright>
+// -----------------------------------------------------------------------
+
+using System;
+using System.Collections.Concurrent;
 using System.Collections.Generic;
 using System.ComponentModel.Composition;
 using System.Diagnostics;
@@ -6,66 +44,75 @@ using System.Diagnostics.Contracts;
 using System.IO;
 using System.Linq;
 using System.Net;
-using System.Text;
 using System.Threading;
 using System.Threading.Tasks;
+using System.Threading.Tasks.Dataflow;
+using Castle.ActiveRecord;
 using Pithos.Interfaces;
 using Pithos.Network;
 using log4net;
 
 namespace Pithos.Core.Agents
 {
+    //TODO: Ensure all network operations use exact casing. Pithos is case sensitive
     [Export]
     public class NetworkAgent
     {
         private Agent<CloudAction> _agent;
 
-        [Import]
+        //A separate agent is used to execute delete actions immediatelly;
+        private ActionBlock<CloudDeleteAction> _deleteAgent;
+        readonly ConcurrentDictionary<string,DateTime> _deletedFiles=new ConcurrentDictionary<string, DateTime>();
+
+
+        private readonly ManualResetEventSlim _pauseAgent = new ManualResetEventSlim(true);
+
+        [System.ComponentModel.Composition.Import]
         public IStatusKeeper StatusKeeper { get; set; }
         
         public IStatusNotification StatusNotification { get; set; }
-/*
-        [Import]
-        public FileAgent FileAgent {get;set;}
-*/
-
-       /* public int BlockSize { get; set; }
-        public string BlockHash { get; set; }*/
 
         private static readonly ILog Log = LogManager.GetLogger("NetworkAgent");
 
-        private List<AccountInfo> _accounts=new List<AccountInfo>();
+        private readonly ConcurrentBag<AccountInfo> _accounts = new ConcurrentBag<AccountInfo>();
 
-        public void Start(/*int blockSize, string blockHash*/)
-        {
-/*
-            if (blockSize<0)
-                throw new ArgumentOutOfRangeException("blockSize");
-            if (String.IsNullOrWhiteSpace(blockHash))
-                throw new ArgumentOutOfRangeException("blockHash");
-            Contract.EndContractBlock();
-*/
-
-/*
-            BlockSize = blockSize;
-            BlockHash = blockHash;
-*/
+        [System.ComponentModel.Composition.Import]
+        public IPithosSettings Settings { get; set; }
 
+        private bool _firstPoll = true;
+        private TaskCompletionSource<bool> _tcs;
 
+        public void Start()
+        {
+            _firstPoll = true;
             _agent = Agent<CloudAction>.Start(inbox =>
             {
                 Action loop = null;
                 loop = () =>
                 {
+                    _pauseAgent.Wait();
                     var message = inbox.Receive();
                     var process=message.Then(Process,inbox.CancellationToken);
                     inbox.LoopAsync(process, loop);
                 };
                 loop();
             });
+
+            _deleteAgent = new ActionBlock<CloudDeleteAction>(message =>ProcessDelete(message),new ExecutionDataflowBlockOptions{MaxDegreeOfParallelism=4});
+            /*
+                Action loop = null;
+                loop = () =>
+                            {
+                                var message = inbox.Receive();
+                                var process = message.Then(ProcessDelete,inbox.CancellationToken);
+                                inbox.LoopAsync(process, loop);
+                            };
+                loop();
+*/
+
         }
 
-        private Task<object> Process(CloudAction action)
+        private async Task Process(CloudAction action)
         {
             if (action == null)
                 throw new ArgumentNullException("action");
@@ -77,62 +124,76 @@ namespace Pithos.Core.Agents
 
             using (log4net.ThreadContext.Stacks["NETWORK"].Push("PROCESS"))
             {                
-                Log.InfoFormat("[ACTION] Start Processing {0}:{1}->{2}", action.Action, action.LocalFile,
-                               action.CloudFile.Name);
+                Log.InfoFormat("[ACTION] Start Processing {0}", action);
 
-                var localFile = action.LocalFile;
-                var cloudFile = action.CloudFile;                
-                var downloadPath = (cloudFile == null)
-                                       ? String.Empty
-                                       : Path.Combine(accountInfo.AccountPath, cloudFile.RelativeUrlToFilePath(accountInfo.UserName));
+                var cloudFile = action.CloudFile;
+                var downloadPath = action.GetDownloadPath();
 
                 try
                 {
-                    var account = action.CloudFile.Account ?? accountInfo.UserName;
-                    var container = action.CloudFile.Container ?? FolderConstants.PithosContainer;
 
-                    switch (action.Action)
+                    if (action.Action == CloudActionType.DeleteCloud)
                     {
-                        case CloudActionType.UploadUnconditional:
-                            UploadCloudFile(accountInfo,account, container, localFile, action.LocalHash.Value, action.TopHash.Value);
-                            break;
-                        case CloudActionType.DownloadUnconditional:
-
-                            DownloadCloudFile(accountInfo, account, container, cloudFile,
-                                              downloadPath);
-                            break;
-                        case CloudActionType.DeleteCloud:
-                            DeleteCloudFile(accountInfo, account, container, cloudFile.Name);
-                            break;
-                        case CloudActionType.RenameCloud:
-                            var moveAction = (CloudMoveAction)action;
-                            RenameCloudFile(accountInfo, account, container, moveAction.OldFileName, moveAction.NewPath,
-                                            moveAction.NewFileName);
-                            break;
-                        case CloudActionType.MustSynch:
-
-                            if (!File.Exists(downloadPath))
-                            {                                
-                                DownloadCloudFile(accountInfo, account, container, cloudFile, downloadPath);
-                            }
-                            else
-                            {
-                                SyncFiles(accountInfo, action);
-                            }
-                            break;
+                        //Redirect deletes to the delete agent 
+                        _deleteAgent.Post((CloudDeleteAction)action);                        
+                    }
+                    if (IsDeletedFile(action))
+                    {
+                        //Clear the status of already deleted files to avoid reprocessing
+                        if (action.LocalFile != null)
+                            this.StatusKeeper.ClearFileStatus(action.LocalFile.FullName);
+                    }
+                    else
+                    {
+                        switch (action.Action)
+                        {
+                            case CloudActionType.UploadUnconditional:
+                                //Abort if the file was deleted before we reached this point
+                                await UploadCloudFile(action);
+                                break;
+                            case CloudActionType.DownloadUnconditional:
+                                await DownloadCloudFile(accountInfo, cloudFile, downloadPath);
+                                break;
+                            case CloudActionType.RenameCloud:
+                                var moveAction = (CloudMoveAction) action;
+                                RenameCloudFile(accountInfo, moveAction);
+                                break;
+                            case CloudActionType.MustSynch:
+                                if (!File.Exists(downloadPath) && !Directory.Exists(downloadPath))
+                                {
+                                    await DownloadCloudFile(accountInfo, cloudFile, downloadPath);
+                                }
+                                else
+                                {
+                                    await SyncFiles(accountInfo, action);
+                                }
+                                break;
+                        }
                     }
                     Log.InfoFormat("[ACTION] End Processing {0}:{1}->{2}", action.Action, action.LocalFile,
                                            action.CloudFile.Name);
                 }
+                catch (WebException exc)
+                {
+                    Log.ErrorFormat("[WEB ERROR] {0} : {1} -> {2} due to exception\r\n{3}", action.Action, action.LocalFile, action.CloudFile, exc);
+                }
                 catch (OperationCanceledException)
                 {
                     throw;
                 }
-                catch (FileNotFoundException exc)
+                catch (DirectoryNotFoundException)
+                {
+                    Log.ErrorFormat("{0} : {1} -> {2}  failed because the directory was not found.\n Rescheduling a delete",
+                        action.Action, action.LocalFile, action.CloudFile);
+                    //Post a delete action for the missing file
+                    Post(new CloudDeleteAction(action));                    
+                }
+                catch (FileNotFoundException)
                 {
                     Log.ErrorFormat("{0} : {1} -> {2}  failed because the file was not found.\n Rescheduling a delete",
-                        action.Action, action.LocalFile, action.CloudFile, exc);
-                    Post(new CloudDeleteAction(accountInfo,action.CloudFile,action.FileState));
+                        action.Action, action.LocalFile, action.CloudFile);
+                    //Post a delete action for the missing file
+                    Post(new CloudDeleteAction(action));
                 }
                 catch (Exception exc)
                 {
@@ -140,12 +201,102 @@ namespace Pithos.Core.Agents
                                      action.Action, action.LocalFile, action.CloudFile, exc);
 
                     _agent.Post(action);
+                }                
+            }
+        }
+
+        /// <summary>
+        /// Processes cloud delete actions
+        /// </summary>
+        /// <param name="action">The delete action to execute</param>
+        /// <returns></returns>
+        /// <remarks>
+        /// When a file/folder is deleted locally, we must delete it ASAP from the server and block any download
+        /// operations that may be in progress.
+        /// <para>
+        /// A separate agent is used to process deletes because the main agent may be busy with a long operation.
+        /// </para>
+        /// </remarks>
+        private async Task ProcessDelete(CloudDeleteAction action)
+        {
+            if (action == null)
+                throw new ArgumentNullException("action");
+            if (action.AccountInfo==null)
+                throw new ArgumentException("The action.AccountInfo is empty","action");
+            Contract.EndContractBlock();
+
+            var accountInfo = action.AccountInfo;
+
+            using (log4net.ThreadContext.Stacks["NETWORK"].Push("PROCESS"))
+            {                
+                Log.InfoFormat("[ACTION] Start Processing {0}", action);
+
+                var cloudFile = action.CloudFile;
+
+                try
+                {
+                    //Acquire a lock on the deleted file to prevent uploading/downloading operations from the normal
+                    //agent
+                    using (var gate = NetworkGate.Acquire(action.LocalFile.FullName, NetworkOperation.Deleting))
+                    {
+
+                        //Add the file URL to the deleted files list
+                        var key = GetFileKey(action.CloudFile);
+                        _deletedFiles[key] = DateTime.Now;
+
+                        _pauseAgent.Reset();
+                        // and then delete the file from the server
+                        DeleteCloudFile(accountInfo, cloudFile);
+
+                        Log.InfoFormat("[ACTION] End Delete {0}:{1}->{2}", action.Action, action.LocalFile,
+                                       action.CloudFile.Name);
+                    }
+                }
+                catch (WebException exc)
+                {
+                    Log.ErrorFormat("[WEB ERROR] {0} : {1} -> {2} due to exception\r\n{3}", action.Action, action.LocalFile, action.CloudFile, exc);
+                }
+                catch (OperationCanceledException)
+                {
+                    throw;
+                }
+                catch (DirectoryNotFoundException)
+                {
+                    Log.ErrorFormat("{0} : {1} -> {2}  failed because the directory was not found.\n Rescheduling a delete",
+                        action.Action, action.LocalFile, action.CloudFile);
+                    //Repost a delete action for the missing file
+                    _deleteAgent.Post(action);
+                }
+                catch (FileNotFoundException)
+                {
+                    Log.ErrorFormat("{0} : {1} -> {2}  failed because the file was not found.\n Rescheduling a delete",
+                        action.Action, action.LocalFile, action.CloudFile);
+                    //Post a delete action for the missing file
+                    _deleteAgent.Post(action);
+                }
+                catch (Exception exc)
+                {
+                    Log.ErrorFormat("[REQUEUE] {0} : {1} -> {2} due to exception\r\n{3}",
+                                     action.Action, action.LocalFile, action.CloudFile, exc);
+
+                    _deleteAgent.Post(action);
+                }
+                finally
+                {
+                    if (_deleteAgent.InputCount == 0)
+                        _pauseAgent.Set();
+
                 }
-                return CompletedTask<object>.Default;
             }
         }
 
-        private void SyncFiles(AccountInfo accountInfo,CloudAction action)
+        private static string GetFileKey(ObjectInfo info)
+        {
+            var key = String.Format("{0}/{1}/{2}", info.Account, info.Container,info.Name);
+            return key;
+        }
+
+        private async Task SyncFiles(AccountInfo accountInfo,CloudAction action)
         {
             if (accountInfo == null)
                 throw new ArgumentNullException("accountInfo");
@@ -161,13 +312,8 @@ namespace Pithos.Core.Agents
 
             var localFile = action.LocalFile;
             var cloudFile = action.CloudFile;
-            var downloadPath=action.LocalFile.FullName.ToLower();
-
-            var account = cloudFile.Account;
-            //Use "pithos" by default if no container is specified
-            var container = cloudFile.Container ?? FolderConstants.PithosContainer;
+            var downloadPath=action.LocalFile.GetProperCapitalization();
 
-            var cloudUri = new Uri(cloudFile.Name, UriKind.Relative);
             var cloudHash = cloudFile.Hash.ToLower();
             var localHash = action.LocalHash.Value.ToLower();
             var topHash = action.TopHash.Value.ToLower();
@@ -189,8 +335,7 @@ namespace Pithos.Core.Agents
             if (lastUpTime <= lastLocalTime)
             {
                 //It probably means it was changed while the app was down                        
-                UploadCloudFile(accountInfo,account, container, localFile, action.LocalHash.Value,
-                                action.TopHash.Value);
+                UploadCloudFile(action);
             }
             else
             {
@@ -201,7 +346,7 @@ namespace Pithos.Core.Agents
                 {
                     case FileStatus.Unchanged:                        
                         //If the local file's status is Unchanged, we can go on and download the newer cloud file
-                        DownloadCloudFile(accountInfo,account, container,cloudFile,downloadPath);
+                        await DownloadCloudFile(accountInfo,cloudFile,downloadPath);
                         break;
                     case FileStatus.Modified:
                         //If the local file is Modified, we may have a conflict. In this case we should mark the file as Conflict
@@ -236,36 +381,6 @@ namespace Pithos.Core.Agents
             StatusNotification.NotifyChange(message, TraceLevel.Warning);
         }
 
-/*
-        private Task<object> Process(CloudMoveAction action)
-        {
-            if (action == null)
-                throw new ArgumentNullException("action");
-            Contract.EndContractBlock();
-
-            Log.InfoFormat("[ACTION] Start Processing {0}:{1}->{2}", action.Action, action.LocalFile, action.CloudFile.Name);
-
-            try
-            {
-                RenameCloudFile(action.OldFileName, action.NewPath, action.NewFileName);
-                Log.InfoFormat("[ACTION] End Processing {0}:{1}->{2}", action.Action, action.LocalFile, action.CloudFile.Name);
-            }
-            catch (OperationCanceledException)
-            {
-                throw;
-            }
-            catch (Exception exc)
-            {
-                Log.ErrorFormat("[REQUEUE] {0} : {1} -> {2} due to exception\r\n{3}",
-                                action.Action, action.OldFileName, action.NewFileName, exc);
-
-                _agent.Post(action);
-            }
-            return CompletedTask<object>.Default;
-        }
-*/
-
-
         public void Post(CloudAction cloudAction)
         {
             if (cloudAction == null)
@@ -273,25 +388,38 @@ namespace Pithos.Core.Agents
             if (cloudAction.AccountInfo==null)
                 throw new ArgumentException("The CloudAction.AccountInfo is empty","cloudAction");
             Contract.EndContractBlock();
-            
+
+            _pauseAgent.Wait();
+
             //If the action targets a local file, add a treehash calculation
-            if (cloudAction.LocalFile != null)
+            if (!(cloudAction is CloudDeleteAction) && cloudAction.LocalFile as FileInfo != null)
             {
                 var accountInfo = cloudAction.AccountInfo;
-                if (cloudAction.LocalFile.Length>accountInfo.BlockSize)
-                    cloudAction.TopHash = new Lazy<string>(() => Signature.CalculateTreeHashAsync(cloudAction.LocalFile,
-                                    accountInfo.BlockSize, accountInfo.BlockHash).Result
-                                     .TopHash.ToHashString());
+                var localFile = (FileInfo) cloudAction.LocalFile;
+                if (localFile.Length > accountInfo.BlockSize)
+                    cloudAction.TopHash =
+                        new Lazy<string>(() => Signature.CalculateTreeHashAsync(localFile,
+                                                                                accountInfo.BlockSize,
+                                                                                accountInfo.BlockHash).Result
+                                                    .TopHash.ToHashString());
                 else
                 {
-                    cloudAction.TopHash=new Lazy<string>(()=> cloudAction.LocalHash.Value);
+                    cloudAction.TopHash = new Lazy<string>(() => cloudAction.LocalHash.Value);
                 }
-
             }
-            _agent.Post(cloudAction);
+            else
+            {
+                //The hash for a directory is the empty string
+                cloudAction.TopHash = new Lazy<string>(() => String.Empty);
+            }
+            
+            if (cloudAction is CloudDeleteAction)
+                _deleteAgent.Post((CloudDeleteAction)cloudAction);
+            else
+                _agent.Post(cloudAction);
         }
 
-        class ObjectInfoByNameComparer:IEqualityComparer<ObjectInfo>
+       /* class ObjectInfoByNameComparer:IEqualityComparer<ObjectInfo>
         {
             public bool Equals(ObjectInfo x, ObjectInfo y)
             {
@@ -302,43 +430,61 @@ namespace Pithos.Core.Agents
             {
                 return obj.Name.ToLower().GetHashCode();
             }
-        }
+        }*/
 
-        
+        public void SynchNow()
+        {             
+            if (_tcs!=null)
+                _tcs.SetResult(true);
+            else
+            {
+                //TODO: This may be OK for testing purposes, but we have no guarantee that it will
+                //work properly in production
+                PollRemoteFiles(repeat:false);
+            }
+        }
 
         //Remote files are polled periodically. Any changes are processed
-        public Task ProcessRemoteFiles(DateTime? since=null)
+        public async Task PollRemoteFiles(DateTime? since = null,bool repeat=true)
         {
-            return Task<Task>.Factory.StartNewDelayed(10000, () =>
+
+            _tcs = new TaskCompletionSource<bool>();
+            var wait = TaskEx.Delay(TimeSpan.FromSeconds(Settings.PollingInterval), _agent.CancellationToken);
+            var signaledTask=await TaskEx.WhenAny(_tcs.Task,wait);
+            //If polling is signalled by SynchNow, ignore the since tag
+            if (signaledTask is Task<bool>)
+                since = null;
+
+            using (log4net.ThreadContext.Stacks["Retrieve Remote"].Push("All accounts"))
             {
-                using (log4net.ThreadContext.Stacks["Retrieve Remote"].Push("All accounts"))
+
+                try
                 {
                     //Next time we will check for all changes since the current check minus 1 second
                     //This is done to ensure there are no discrepancies due to clock differences
                     DateTime nextSince = DateTime.Now.AddSeconds(-1);
-                    
-                    var tasks=from accountInfo in _accounts
-                              select ProcessAccountFiles(accountInfo, since);
-                    var process=Task.Factory.Iterate(tasks);
 
-                    return process.ContinueWith(t =>
-                    {
-                        if (t.IsFaulted)
-                        {
-                            Log.Error("Error while processing accounts");
-                            t.Exception.Handle(exc=>
-                                                   {
-                                                       Log.Error("Details:", exc);
-                                                       return true;
-                                                   });                            
-                        }
-                        ProcessRemoteFiles(nextSince);
-                    });
+                    var tasks = from accountInfo in _accounts
+                                select ProcessAccountFiles(accountInfo, since);
+
+                    await TaskEx.WhenAll(tasks.ToList());
+
+                    _firstPoll = false;
+                    if (repeat)
+                        PollRemoteFiles(nextSince);
+                }
+                catch (Exception ex)
+                {
+                    Log.ErrorFormat("Error while processing accounts\r\n{0}",ex);
+                    //In case of failure retry with the same parameter
+                    PollRemoteFiles(since);
                 }
-            });            
+                
+
+            }
         }
 
-        public Task ProcessAccountFiles(AccountInfo accountInfo,DateTime? since=null)
+        public async Task ProcessAccountFiles(AccountInfo accountInfo,DateTime? since=null)
         {   
             if (accountInfo==null)
                 throw new ArgumentNullException("accountInfo");
@@ -351,54 +497,95 @@ namespace Pithos.Core.Agents
                 Log.Info("Scheduled");
                 var client=new CloudFilesClient(accountInfo);
 
-                //Get the list of server objects changed since the last check
-                var listObjects = Task<IList<ObjectInfo>>.Factory.StartNew(() =>
-                                client.ListObjects(accountInfo.UserName, FolderConstants.PithosContainer, since));
-                //Get the list of deleted objects since the last check
-                var listTrash = Task<IList<ObjectInfo>>.Factory.StartNew(() =>
-                                client.ListObjects(accountInfo.UserName, FolderConstants.TrashContainer, since));
-
-                var listShared = Task<IList<ObjectInfo>>.Factory.StartNew(() =>
-                                client.ListSharedObjects());
+                var containers = client.ListContainers(accountInfo.UserName);
+                
+                CreateContainerFolders(accountInfo, containers);
 
-                var listAll = Task.Factory.TrackedSequence(
-                    () => listObjects,
-                    () => listTrash,
-                    () => listShared);
+                try
+                {
+                    _pauseAgent.Wait();
+                    //Get the poll time now. We may miss some deletions but it's better to keep a file that was deleted
+                    //than delete a file that was created while we were executing the poll
+                    var pollTime = DateTime.Now;
+                    
+                    //Get the list of server objects changed since the last check
+                    //The name of the container is passed as state in order to create a dictionary of tasks in a subsequent step
+                    var listObjects = from container in containers
+                                      select  Task<IList<ObjectInfo>>.Factory.StartNew(_ =>
+                                            client.ListObjects(accountInfo.UserName,container.Name, since),container.Name);
 
 
+                    var listTasks = await Task.Factory.WhenAll(listObjects.ToArray());
 
-                var enqueueFiles = listAll.ContinueWith(task =>
-                {
-                    if (task.IsFaulted)
-                    {
-                        //ListObjects failed at this point, need to reschedule
-                        Log.ErrorFormat("[FAIL] ListObjects for{0} in ProcessRemoteFiles with {0}", accountInfo.UserName,task.Exception);
-                        return;
-                    }
                     using (log4net.ThreadContext.Stacks["SCHEDULE"].Push("Process Results"))
                     {
-                        var remoteObjects = ((Task<IList<ObjectInfo>>) task.Result[0]).Result;
-                        var trashObjects = ((Task<IList<ObjectInfo>>) task.Result[1]).Result;
-                        var sharedObjects = ((Task<IList<ObjectInfo>>) task.Result[2]).Result;
+                        var dict = listTasks.ToDictionary(t => t.AsyncState);
+
+                        //Get all non-trash objects. Remember, the container name is stored in AsyncState
+                        var remoteObjects = from objectList in listTasks
+                                            where (string) objectList.AsyncState != "trash"
+                                            from obj in objectList.Result
+                                            select obj;
+
+                        //TODO: Change the way deleted objects are detected.
+                        //The list operation returns all existing objects so we could detect deleted remote objects
+                        //by detecting objects that exist only locally. There are several cases where this is NOT the case:
+                        //1.    The first time the application runs, as there may be files that were added while 
+                        //      the application was down.
+                        //2.    An object that is currently being uploaded will not appear in the remote list
+                        //      until the upload finishes.
+                        //      SOLUTION 1: Check the upload/download queue for the file
+                        //      SOLUTION 2: Check the SQLite states for the file's entry. If it is being uploaded, 
+                        //          or its last modification was after the current poll, don't delete it. This way we don't
+                        //          delete objects whose upload finished too late to be included in the list.
+                        //We need to detect and protect against such situations
+                        //TODO: Does FileState have a LastModification field?
+                        //TODO: How do we update the LastModification field? Do we need to add SQLite triggers?
+                        //      Do we need to use a proper SQLite schema?
+                        //      We can create a trigger with 
+                        // CREATE TRIGGER IF NOT EXISTS update_last_modified UPDATE ON FileState FOR EACH ROW
+                        //  BEGIN
+                        //      UPDATE FileState SET LastModification=datetime('now')  WHERE Id=old.Id;
+                        //  END;
+                        //
+                        //NOTE: Some files may have been deleted remotely while the application was down. 
+                        //  We DO have to delete those files. Checking the trash makes it easy to detect them,
+                        //  Otherwise, we can't be really sure whether we need to upload or delete 
+                        //  the local-only files.
+                        //  SOLUTION 1: Ask the user when such a local-only file is detected during the first poll.
+                        //  SOLUTION 2: Mark conflict and ask the user as in #1
+
+                        var trashObjects = dict["trash"].Result;
+                        //var sharedObjects = ((Task<IList<ObjectInfo>>) task.Result[2]).Result;
 
                         //Items with the same name, hash may be both in the container and the trash
                         //Don't delete items that exist in the container
                         var realTrash = from trash in trashObjects
-                                        where !remoteObjects.Any(info => info.Hash == trash.Hash)
+                                        where
+                                            !remoteObjects.Any(
+                                                info => info.Name == trash.Name && info.Hash == trash.Hash)
                                         select trash;
-                        ProcessDeletedFiles(accountInfo,realTrash);                        
+                        ProcessTrashedFiles(accountInfo, realTrash);
 
 
-                        var remote = from info in remoteObjects.Union(sharedObjects)
+                        var cleanRemotes = (from info in remoteObjects
+                                     //.Union(sharedObjects)
                                      let name = info.Name
                                      where !name.EndsWith(".ignore", StringComparison.InvariantCultureIgnoreCase) &&
-                                           !name.StartsWith("fragments/", StringComparison.InvariantCultureIgnoreCase)
-                                     select info;
+                                           !name.StartsWith(FolderConstants.CacheFolder + "/",
+                                                            StringComparison.InvariantCultureIgnoreCase)
+                                     select info).ToList();
+
+
+
+                        ProcessDeletedFiles(accountInfo, cleanRemotes, pollTime);
 
                         //Create a list of actions from the remote files
-                        var allActions = ObjectsToActions(accountInfo,remote);
-                       
+                        var allActions = ObjectsToActions(accountInfo, cleanRemotes);
+
+                        
+                        //var relativePath = objectInfo.RelativeUrlToFilePath(accountInfo.UserName);
+
                         //And remove those that are already being processed by the agent
                         var distinctActions = allActions
                             .Except(_agent.GetEnumerable(), new PithosMonitor.LocalFileComparer())
@@ -410,28 +597,86 @@ namespace Pithos.Core.Agents
                             Post(message);
                         }
 
-                        //Report the number of new files
-                        var remoteCount = distinctActions.Count(action=>
-                            action.Action==CloudActionType.DownloadUnconditional);
-                        if ( remoteCount > 0)
-                            StatusNotification.NotifyChange(String.Format("Processing {0} new files", remoteCount));
-
-                        Log.Info("[LISTENER] End Processing");                        
+                        Log.Info("[LISTENER] End Processing");
                     }
-                });
+                }
+                catch (Exception ex)
+                {
+                    Log.ErrorFormat("[FAIL] ListObjects for{0} in ProcessRemoteFiles with {1}", accountInfo.UserName, ex);
+                    return;
+                }
 
-                var log = enqueueFiles.ContinueWith(t =>
-                {                    
-                    if (t.IsFaulted)
-                    {
-                        Log.Error("[LISTENER] Exception", t.Exception);
-                    }
-                    else
-                    {
-                        Log.Info("[LISTENER] Finished");
-                    }
-                });
-                return log;
+                Log.Info("[LISTENER] Finished");
+
+            }
+        }
+
+        /// <summary>
+        /// Deletes local files that are not found in the list of cloud files
+        /// </summary>
+        /// <param name="accountInfo"></param>
+        /// <param name="cloudFiles"></param>
+        /// <param name="pollTime"></param>
+        private void ProcessDeletedFiles(AccountInfo accountInfo, IEnumerable<ObjectInfo> cloudFiles, DateTime pollTime)
+        {
+            if (accountInfo == null)
+                throw new ArgumentNullException("accountInfo");
+            if (String.IsNullOrWhiteSpace(accountInfo.AccountPath))
+                throw new ArgumentException("The AccountInfo.AccountPath is empty", "accountInfo");
+            if (cloudFiles == null)
+                throw new ArgumentNullException("cloudFiles");
+            Contract.EndContractBlock();
+
+            //Check the Modified date to ensure that were just created and haven't been uploaded yet
+            //NOTE: The NHibernate LINQ provider doesn't support custom functions so we need to break the query 
+            //in two steps
+            //NOTE: DON'T return files that are already in conflict. The first poll would mark them as 
+            //"In Conflict" but subsequent polls would delete them
+            var deleteCandidates = (from state in FileState.Queryable
+                                   where 
+                                        state.Modified <= pollTime 
+                                        && state.FilePath.StartsWith(accountInfo.AccountPath)
+                                        && state.FileStatus != FileStatus.Conflict
+                                   select state).ToList();
+
+            var filesToDelete = (from deleteCandidate in deleteCandidates 
+                         let localFile = FileInfoExtensions.FromPath(deleteCandidate.FilePath) 
+                         let relativeFilePath = localFile.AsRelativeTo(accountInfo.AccountPath) 
+                         where !cloudFiles.Any(r => Path.Combine(r.Container, r.Name) == relativeFilePath) 
+                         select localFile).ToList();
+
+            //On the first run
+            if (_firstPoll)
+            {
+                //Set the status of missing files to Conflict
+                foreach (var item in filesToDelete)
+                {
+                    StatusKeeper.SetFileState(item.FullName, FileStatus.Conflict, FileOverlayStatus.Deleted);
+                }
+                StatusNotification.NotifyConflicts(filesToDelete, String.Format("{0} local files are missing from Pithos, possibly because they were deleted",filesToDelete.Count));
+            }
+            else
+            {
+                foreach (var item in filesToDelete)
+                {
+                    item.Delete();
+                    StatusKeeper.ClearFileStatus(item.FullName);
+                }
+                StatusNotification.NotifyForFiles(filesToDelete, String.Format("{0} files were deleted",filesToDelete.Count),TraceLevel.Info);
+            }
+
+        }
+
+        private static void CreateContainerFolders(AccountInfo accountInfo, IEnumerable<ContainerInfo> containers)
+        {
+            var containerPaths = from container in containers
+                                 let containerPath = Path.Combine(accountInfo.AccountPath, container.Name)
+                                 where container.Name != FolderConstants.TrashContainer && !Directory.Exists(containerPath)
+                                 select containerPath;
+
+            foreach (var path in containerPaths)
+            {
+                Directory.CreateDirectory(path);
             }
         }
 
@@ -452,13 +697,20 @@ namespace Pithos.Core.Agents
                 
                 if (fileAgent.Exists(relativePath))
                 {
-                    var localFile = fileAgent.GetFileInfo(relativePath);
-                    var state = FileState.FindByFilePath(localFile.FullName);
-                    //Common files should be checked on a per-case basis to detect differences, which is newer
+                    //If a directory object already exists, we don't need to perform any other action                    
+                    var localFile = fileAgent.GetFileSystemInfo(relativePath);
+                    if (objectInfo.Content_Type == @"application/directory" && localFile is DirectoryInfo)
+                        continue;
+                    using (new SessionScope(FlushAction.Never))
+                    {
+                        var state =  StatusKeeper.GetStateByFilePath(localFile.FullName);
+                        //FileState.FindByFilePath(localFile.FullName);
+                        //Common files should be checked on a per-case basis to detect differences, which is newer
 
-                    yield return new CloudAction(accountInfo,CloudActionType.MustSynch,
-                                                   localFile, objectInfo, state, accountInfo.BlockSize,
-                                                   accountInfo.BlockHash);
+                        yield return new CloudAction(accountInfo, CloudActionType.MustSynch,
+                                                     localFile, objectInfo, state, accountInfo.BlockSize,
+                                                     accountInfo.BlockHash);
+                    }
                 }
                 else
                 {
@@ -480,179 +732,182 @@ namespace Pithos.Core.Agents
             return AgentLocator<FileAgent>.Get(accountInfo.AccountPath);
         }
 
-        private void ProcessDeletedFiles(AccountInfo accountInfo,IEnumerable<ObjectInfo> trashObjects)
+        private void ProcessTrashedFiles(AccountInfo accountInfo,IEnumerable<ObjectInfo> trashObjects)
         {
             var fileAgent = GetFileAgent(accountInfo);
             foreach (var trashObject in trashObjects)
             {
-                var relativePath = trashObject.RelativeUrlToFilePath(accountInfo.UserName);
-                //and remove any matching objects from the list, adding them to the commonObjects list
+                var barePath = trashObject.RelativeUrlToFilePath(accountInfo.UserName);
+                //HACK: Assume only the "pithos" container is used. Must find out what happens when
+                //deleting a file from a different container
+                var relativePath = Path.Combine("pithos", barePath);
                 fileAgent.Delete(relativePath);                                
             }
         }
 
 
-        private void RenameCloudFile(AccountInfo accountInfo,string account, string container,string oldFileName, string newPath, string newFileName)
+        private void RenameCloudFile(AccountInfo accountInfo,CloudMoveAction action)
         {
             if (accountInfo==null)
                 throw new ArgumentNullException("accountInfo");
-            if (String.IsNullOrWhiteSpace(account))
-                throw new ArgumentNullException("account");
-            if (String.IsNullOrWhiteSpace(container))
-                throw new ArgumentNullException("container");
-            if (String.IsNullOrWhiteSpace(oldFileName))
-                throw new ArgumentNullException("oldFileName");
-            if (String.IsNullOrWhiteSpace(oldFileName))
-                throw new ArgumentNullException("newPath");
-            if (String.IsNullOrWhiteSpace(oldFileName))
-                throw new ArgumentNullException("newFileName");
+            if (action==null)
+                throw new ArgumentNullException("action");
+            if (action.CloudFile==null)
+                throw new ArgumentException("CloudFile","action");
+            if (action.LocalFile==null)
+                throw new ArgumentException("LocalFile","action");
+            if (action.OldLocalFile==null)
+                throw new ArgumentException("OldLocalFile","action");
+            if (action.OldCloudFile==null)
+                throw new ArgumentException("OldCloudFile","action");
             Contract.EndContractBlock();
+            
+            
+            var newFilePath = action.LocalFile.FullName;
+            
+            //How do we handle concurrent renames and deletes/uploads/downloads?
+            //* A conflicting upload means that a file was renamed before it had a chance to finish uploading
+            //  This should never happen as the network agent executes only one action at a time
+            //* A conflicting download means that the file was modified on the cloud. While we can go on and complete
+            //  the rename, there may be a problem if the file is downloaded in blocks, as subsequent block requests for the 
+            //  same name will fail.
+            //  This should never happen as the network agent executes only one action at a time.
+            //* A conflicting delete can happen if the rename was followed by a delete action that didn't have the chance
+            //  to remove the rename from the queue.
+            //  We can probably ignore this case. It will result in an error which should be ignored            
+
+            
             //The local file is already renamed
-            this.StatusKeeper.SetFileOverlayStatus(newPath, FileOverlayStatus.Modified);
+            StatusKeeper.SetFileOverlayStatus(newFilePath, FileOverlayStatus.Modified);
 
+
+            var account = action.CloudFile.Account ?? accountInfo.UserName;
+            var container = action.CloudFile.Container;
+            
             var client = new CloudFilesClient(accountInfo);
-            client.MoveObject(account, container, oldFileName, container, newFileName);
+            //TODO: What code is returned when the source file doesn't exist?
+            client.MoveObject(account, container, action.OldCloudFile.Name, container, action.CloudFile.Name);
 
-            this.StatusKeeper.SetFileStatus(newPath, FileStatus.Unchanged);
-            this.StatusKeeper.SetFileOverlayStatus(newPath, FileOverlayStatus.Normal);
-            NativeMethods.RaiseChangeNotification(newPath);
+            StatusKeeper.SetFileStatus(newFilePath, FileStatus.Unchanged);
+            StatusKeeper.SetFileOverlayStatus(newFilePath, FileOverlayStatus.Normal);
+            NativeMethods.RaiseChangeNotification(newFilePath);
         }
 
-        private void DeleteCloudFile(AccountInfo accountInfo, string account, string container, string fileName)
+        private void DeleteCloudFile(AccountInfo accountInfo, ObjectInfo cloudFile)
         {
             if (accountInfo == null)
                 throw new ArgumentNullException("accountInfo");
-            if (String.IsNullOrWhiteSpace(account))
-                throw new ArgumentNullException("account");
-            if (String.IsNullOrWhiteSpace(container))
-                throw new ArgumentNullException("container");
-            if (String.IsNullOrWhiteSpace(container))
-                throw new ArgumentNullException("container");
-
-            if (String.IsNullOrWhiteSpace(fileName))
-                throw new ArgumentNullException("fileName");
-            if (Path.IsPathRooted(fileName))
-                throw new ArgumentException("The fileName should not be rooted","fileName");
+            if (cloudFile==null)
+                throw new ArgumentNullException("cloudFile");
+
+            if (String.IsNullOrWhiteSpace(cloudFile.Container))
+                throw new ArgumentException("Invalid container", "cloudFile");
             Contract.EndContractBlock();
             
             var fileAgent = GetFileAgent(accountInfo);
 
             using ( log4net.ThreadContext.Stacks["DeleteCloudFile"].Push("Delete"))
             {
-                var info = fileAgent.GetFileInfo(fileName);
+                var fileName= cloudFile.RelativeUrlToFilePath(accountInfo.UserName);
+                var info = fileAgent.GetFileSystemInfo(fileName);                
                 var fullPath = info.FullName.ToLower();
-                this.StatusKeeper.SetFileOverlayStatus(fullPath, FileOverlayStatus.Modified);
+
+                StatusKeeper.SetFileOverlayStatus(fullPath, FileOverlayStatus.Modified);
+
+                var account = cloudFile.Account ?? accountInfo.UserName;
+                var container = cloudFile.Container ;//?? FolderConstants.PithosContainer;
 
                 var client = new CloudFilesClient(accountInfo);
-                client.DeleteObject(account, container, fileName);
+                client.DeleteObject(account, container, cloudFile.Name);
 
-                this.StatusKeeper.ClearFileStatus(fullPath);
+                StatusKeeper.ClearFileStatus(fullPath);
             }
         }
 
         //Download a file.
-        private void DownloadCloudFile(AccountInfo accountInfo, string account, string container,ObjectInfo cloudFile , string localPath)
+        private async Task DownloadCloudFile(AccountInfo accountInfo, ObjectInfo cloudFile , string filePath)
         {
             if (accountInfo == null)
                 throw new ArgumentNullException("accountInfo");
-            if (String.IsNullOrWhiteSpace(account))
-                throw new ArgumentNullException("account");
-            if (String.IsNullOrWhiteSpace(container))
-                throw new ArgumentNullException("container");
             if (cloudFile == null)
                 throw new ArgumentNullException("cloudFile");
-            if (String.IsNullOrWhiteSpace(localPath))
-                throw new ArgumentNullException("localPath");
-            if (!Path.IsPathRooted(localPath))
-                throw new ArgumentException("The localPath must be rooted", "localPath");
-            Contract.EndContractBlock();
-            
-            Debug.Assert(cloudFile.Account==account);
-            Debug.Assert(cloudFile.Container == container);
-
-            var download=Task.Factory.Iterate(DownloadIterator(accountInfo,account,container, cloudFile, localPath));
-            download.Wait();
-        }
-
-        private IEnumerable<Task> DownloadIterator(AccountInfo accountInfo, string account, string container, ObjectInfo cloudFile, string localPath)
-        {
-            if (accountInfo == null)
-                throw new ArgumentNullException("accountInfo");
-            if (String.IsNullOrWhiteSpace(account))
-                throw new ArgumentNullException("account");
-            if (String.IsNullOrWhiteSpace(container))
-                throw new ArgumentNullException("container");
-            if (cloudFile==null)
+            if (String.IsNullOrWhiteSpace(cloudFile.Account))
+                throw new ArgumentNullException("cloudFile");
+            if (String.IsNullOrWhiteSpace(cloudFile.Container))
                 throw new ArgumentNullException("cloudFile");
-            if (String.IsNullOrWhiteSpace(localPath))
-                throw new ArgumentNullException("localPath");
-            if (!Path.IsPathRooted(localPath))
-                throw new ArgumentException("The localPath must be rooted", "localPath");
+            if (String.IsNullOrWhiteSpace(filePath))
+                throw new ArgumentNullException("filePath");
+            if (!Path.IsPathRooted(filePath))
+                throw new ArgumentException("The filePath must be rooted", "filePath");
             Contract.EndContractBlock();
 
-            Uri relativeUrl = new Uri(cloudFile.Name, UriKind.Relative);
+            var localPath = Interfaces.FileInfoExtensions.GetProperFilePathCapitalization(filePath);
+            var relativeUrl = new Uri(cloudFile.Name, UriKind.Relative);
 
             var url = relativeUrl.ToString();
             if (cloudFile.Name.EndsWith(".ignore", StringComparison.InvariantCultureIgnoreCase))
-                yield break;
+                return;
+
 
             //Are we already downloading or uploading the file? 
             using (var gate=NetworkGate.Acquire(localPath, NetworkOperation.Downloading))
             {
                 if (gate.Failed)
-                    yield break;
+                    return;
                 //The file's hashmap will be stored in the same location with the extension .hashmap
-                //var hashPath = Path.Combine(FileAgent.FragmentsPath, relativePath + ".hashmap");
+                //var hashPath = Path.Combine(FileAgent.CachePath, relativePath + ".hashmap");
                 
                 var client = new CloudFilesClient(accountInfo);
-                //Retrieve the hashmap from the server
-                var getHashMap = client.GetHashMap(account, container, url);
-                yield return getHashMap;
-                
-                var serverHash=getHashMap.Result;
-                //If it's a small file
-                var downloadTask=(serverHash.Hashes.Count == 1 )
-                    //Download it in one go
-                    ? DownloadEntireFile(accountInfo,client, account, container, relativeUrl, localPath,serverHash) 
-                    //Otherwise download it block by block
-                    : DownloadWithBlocks(accountInfo,client, account, container, relativeUrl, localPath, serverHash);
+                var account = cloudFile.Account;
+                var container = cloudFile.Container;
 
-                yield return downloadTask;
-
-                if (cloudFile.AllowedTo == "read")
+                if (cloudFile.Content_Type == @"application/directory")
                 {
-                    var attributes=File.GetAttributes(localPath);
-                    File.SetAttributes(localPath,attributes|FileAttributes.ReadOnly);
+                    if (!Directory.Exists(localPath))
+                        Directory.CreateDirectory(localPath);
                 }
-                //Retrieve the object's metadata
-                var info=client.GetObjectInfo(account, container, url);
-                Debug.Assert(cloudFile==info);
-                //And store it
-                StatusKeeper.StoreInfo(localPath, info);
-                
-                //Notify listeners that a local file has changed
-                StatusNotification.NotifyChangedFile(localPath);
+                else
+                {
+                    //Retrieve the hashmap from the server
+                    var serverHash = await client.GetHashMap(account, container, url);
+                    //If it's a small file
+                    if (serverHash.Hashes.Count == 1)
+                        //Download it in one go
+                        await
+                            DownloadEntireFileAsync(accountInfo, client, cloudFile, relativeUrl, localPath, serverHash);
+                        //Otherwise download it block by block
+                    else
+                        await DownloadWithBlocks(accountInfo, client, cloudFile, relativeUrl, localPath, serverHash);
 
+                    if (cloudFile.AllowedTo == "read")
+                    {
+                        var attributes = File.GetAttributes(localPath);
+                        File.SetAttributes(localPath, attributes | FileAttributes.ReadOnly);                        
+                    }
+                }
+
+                //Now we can store the object's metadata without worrying about ghost status entries
+                StatusKeeper.StoreInfo(localPath, cloudFile);
+                
             }
         }
 
         //Download a small file with a single GET operation
-        private Task DownloadEntireFile(AccountInfo accountInfo, CloudFilesClient client, string account, string container, Uri relativeUrl, string localPath,TreeHash serverHash)
+        private async Task DownloadEntireFileAsync(AccountInfo accountInfo, CloudFilesClient client, ObjectInfo cloudFile, Uri relativeUrl, string filePath,TreeHash serverHash)
         {
             if (client == null)
                 throw new ArgumentNullException("client");
-            if (String.IsNullOrWhiteSpace(account))
-                throw new ArgumentNullException("account");
-            if (String.IsNullOrWhiteSpace(container))
-                throw new ArgumentNullException("container");
+            if (cloudFile==null)
+                throw new ArgumentNullException("cloudFile");
             if (relativeUrl == null)
                 throw new ArgumentNullException("relativeUrl");
-            if (String.IsNullOrWhiteSpace(localPath))
-                throw new ArgumentNullException("localPath");
-            if (!Path.IsPathRooted(localPath))
-                throw new ArgumentException("The localPath must be rooted", "localPath");
+            if (String.IsNullOrWhiteSpace(filePath))
+                throw new ArgumentNullException("filePath");
+            if (!Path.IsPathRooted(filePath))
+                throw new ArgumentException("The localPath must be rooted", "filePath");
             Contract.EndContractBlock();
 
+            var localPath = Pithos.Interfaces.FileInfoExtensions.GetProperFilePathCapitalization(filePath);
             //If the file already exists
             if (File.Exists(localPath))
             {
@@ -660,93 +915,70 @@ namespace Pithos.Core.Agents
                 var localMD5 = Signature.CalculateMD5(localPath);
                 var cloudHash=serverHash.TopHash.ToHashString();
                 if (localMD5==cloudHash)
-                    return CompletedTask.Default;
+                    return;
                 //Then check with a treehash
                 var localTreeHash = Signature.CalculateTreeHash(localPath, serverHash.BlockSize, serverHash.BlockHash);
                 var localHash = localTreeHash.TopHash.ToHashString();
                 if (localHash==cloudHash)
-                    return CompletedTask.Default;
+                    return;
             }
 
             var fileAgent = GetFileAgent(accountInfo);
             //Calculate the relative file path for the new file
             var relativePath = relativeUrl.RelativeUriToFilePath();
             //The file will be stored in a temporary location while downloading with an extension .download
-            var tempPath = Path.Combine(fileAgent.FragmentsPath, relativePath + ".download");
+            var tempPath = Path.Combine(fileAgent.CachePath, relativePath + ".download");
             //Make sure the target folder exists. DownloadFileTask will not create the folder
             var tempFolder = Path.GetDirectoryName(tempPath);
             if (!Directory.Exists(tempFolder))
                 Directory.CreateDirectory(tempFolder);
 
             //Download the object to the temporary location
-            var getObject = client.GetObject(account, container, relativeUrl.ToString(), tempPath).ContinueWith(t =>
-            {
-                t.PropagateExceptions();
-                //Create the local folder if it doesn't exist (necessary for shared objects)
-                var localFolder = Path.GetDirectoryName(localPath);
-                if (!Directory.Exists(localFolder))
-                    Directory.CreateDirectory(localFolder);
-                //And move it to its actual location once downloading is finished
-                if (File.Exists(localPath))
-                    File.Replace(tempPath,localPath,null,true);
-                else
-                    File.Move(tempPath,localPath);
-            });
-            return getObject;
+            await client.GetObject(cloudFile.Account, cloudFile.Container, relativeUrl.ToString(), tempPath);
+
+            //Create the local folder if it doesn't exist (necessary for shared objects)
+            var localFolder = Path.GetDirectoryName(localPath);
+            if (!Directory.Exists(localFolder))
+                Directory.CreateDirectory(localFolder);            
+            //And move it to its actual location once downloading is finished
+            if (File.Exists(localPath))
+                File.Replace(tempPath,localPath,null,true);
+            else
+                File.Move(tempPath,localPath);
+            //Notify listeners that a local file has changed
+            StatusNotification.NotifyChangedFile(localPath);
+
+                       
         }
 
         //Download a file asynchronously using blocks
-        public Task DownloadWithBlocks(AccountInfo accountInfo, CloudFilesClient client, string account, string container, Uri relativeUrl, string localPath, TreeHash serverHash)
+        public async Task DownloadWithBlocks(AccountInfo accountInfo, CloudFilesClient client, ObjectInfo cloudFile, Uri relativeUrl, string filePath, TreeHash serverHash)
         {
             if (client == null)
                 throw new ArgumentNullException("client");
-            if (String.IsNullOrWhiteSpace(account))
-                throw new ArgumentNullException("account");
-            if (String.IsNullOrWhiteSpace(container))
-                throw new ArgumentNullException("container");
+            if (cloudFile == null)
+                throw new ArgumentNullException("cloudFile");
             if (relativeUrl == null)
                 throw new ArgumentNullException("relativeUrl");
-            if (String.IsNullOrWhiteSpace(localPath))
-                throw new ArgumentNullException("localPath");
-            if (!Path.IsPathRooted(localPath))
-                throw new ArgumentException("The localPath must be rooted", "localPath");
+            if (String.IsNullOrWhiteSpace(filePath))
+                throw new ArgumentNullException("filePath");
+            if (!Path.IsPathRooted(filePath))
+                throw new ArgumentException("The filePath must be rooted", "filePath");
             if (serverHash == null)
                 throw new ArgumentNullException("serverHash");
             Contract.EndContractBlock();
             
-            return Task.Factory.Iterate(BlockDownloadIterator(accountInfo,client,account,container, relativeUrl, localPath, serverHash));
-        }
-
-        private IEnumerable<Task> BlockDownloadIterator(AccountInfo accountInfo,CloudFilesClient client, string account, string container, Uri relativeUrl, string localPath, TreeHash serverHash)
-        {
-            if (client == null)
-                throw new ArgumentNullException("client");
-            if (String.IsNullOrWhiteSpace(account))
-                throw new ArgumentNullException("account");
-            if (String.IsNullOrWhiteSpace(container))
-                throw new ArgumentNullException("container");
-            if (relativeUrl == null)
-                throw new ArgumentNullException("relativeUrl");
-            if (String.IsNullOrWhiteSpace(localPath))
-                throw new ArgumentNullException("localPath");
-            if (!Path.IsPathRooted(localPath))
-                throw new ArgumentException("The localPath must be rooted", "localPath");
-            if(serverHash==null)
-                throw new ArgumentNullException("serverHash");
-            Contract.EndContractBlock();
-            
-            var fileAgent = GetFileAgent(accountInfo);
+           var fileAgent = GetFileAgent(accountInfo);
+            var localPath = Interfaces.FileInfoExtensions.GetProperFilePathCapitalization(filePath);
             
             //Calculate the relative file path for the new file
             var relativePath = relativeUrl.RelativeUriToFilePath();
-            var blockUpdater = new BlockUpdater(fileAgent.FragmentsPath, localPath, relativePath, serverHash);
+            var blockUpdater = new BlockUpdater(fileAgent.CachePath, localPath, relativePath, serverHash);
 
             
                         
             //Calculate the file's treehash
-            var calcHash = Signature.CalculateTreeHashAsync(localPath, serverHash.BlockSize,serverHash.BlockHash);
-            yield return calcHash;                        
-            var treeHash = calcHash.Result;
+            var treeHash = await Signature.CalculateTreeHashAsync(localPath, serverHash.BlockSize, serverHash.BlockHash);
                 
             //And compare it with the server's hash
             var upHashes = serverHash.GetHashesAsStrings();
@@ -770,141 +1002,207 @@ namespace Pithos.Core.Agents
                         end= ((i + 1)*serverHash.BlockSize) ;
                             
                     //Download the missing block
-                    var getBlock = client.GetBlock(account, container, relativeUrl, start, end);
-                    yield return getBlock;
-                    var block = getBlock.Result;
+                    var block = await client.GetBlock(cloudFile.Account, cloudFile.Container, relativeUrl, start, end);
 
                     //and store it
-                    yield return blockUpdater.StoreBlock(i, block);
+                    blockUpdater.StoreBlock(i, block);
 
 
                     Log.InfoFormat("[BLOCK GET] FINISH {0} of {1} for {2}", i, upHashes.Length, localPath);
                 }
             }
 
+            //Want to avoid notifications if no changes were made
+            var hasChanges = blockUpdater.HasBlocks;
             blockUpdater.Commit();
+            
+            if (hasChanges)
+                //Notify listeners that a local file has changed
+                StatusNotification.NotifyChangedFile(localPath);
+
             Log.InfoFormat("[BLOCK GET] COMPLETE {0}", localPath);            
         }
 
 
-        private void UploadCloudFile(AccountInfo accountInfo, string account, string container, FileInfo fileInfo, string hash, string topHash)
-        {
-            if (accountInfo == null)
-                throw new ArgumentNullException("accountInfo");
-            if (String.IsNullOrWhiteSpace(account))
-                throw new ArgumentNullException("account");
-            if (String.IsNullOrWhiteSpace(container))
-                throw new ArgumentNullException("container");
-            if (fileInfo == null)
-                throw new ArgumentNullException("fileInfo");
-            if (String.IsNullOrWhiteSpace(hash))
-                throw new ArgumentNullException("hash");
-            if (topHash == null)
-                throw new ArgumentNullException("topHash");
-            Contract.EndContractBlock();
-
-            var upload = Task.Factory.Iterate(UploadIterator(accountInfo,account,container,fileInfo, hash.ToLower(), topHash.ToLower()));
-            upload.Wait();
-        }
-
-        private IEnumerable<Task> UploadIterator(AccountInfo accountInfo, string account, string container, FileInfo fileInfo, string hash, string topHash)
+        private async Task UploadCloudFile(CloudAction action)
         {
-            if (accountInfo == null)
-                throw new ArgumentNullException("accountInfo");
-            if (String.IsNullOrWhiteSpace(account))
-                throw new ArgumentNullException("account");
-            if (String.IsNullOrWhiteSpace(container))
-                throw new ArgumentNullException("container");
-            if (fileInfo == null)
-                throw new ArgumentNullException("fileInfo");
-            if (String.IsNullOrWhiteSpace(hash))
-                throw new ArgumentNullException("hash");
-            if (topHash == null)
-                throw new ArgumentNullException("topHash");
+            if (action == null)
+                throw new ArgumentNullException("action");           
             Contract.EndContractBlock();
 
-            if (fileInfo.Extension.Equals("ignore", StringComparison.InvariantCultureIgnoreCase))
-                yield break;
-            
-            var url = fileInfo.AsRelativeUrlTo(accountInfo.AccountPath);
-
-            var fullFileName = fileInfo.FullName;
-            using(var gate=NetworkGate.Acquire(fullFileName,NetworkOperation.Uploading))
+            try
             {
-                //Abort if the file is already being uploaded or downloaded
-                if (gate.Failed)
-                    yield break;
+                var accountInfo = action.AccountInfo;
 
-                var client = new CloudFilesClient(accountInfo);
-                //Even if GetObjectInfo times out, we can proceed with the upload            
-                var info = client.GetObjectInfo(account, container, url);
-                var cloudHash = info.Hash.ToLower();
+                var fileInfo = action.LocalFile;
 
-                //If the file hashes match, abort the upload
-                if (hash == cloudHash  || topHash ==cloudHash)
+                if (fileInfo.Extension.Equals("ignore", StringComparison.InvariantCultureIgnoreCase))
+                    return;
+                
+                var relativePath = fileInfo.AsRelativeTo(accountInfo.AccountPath);
+                if (relativePath.StartsWith(FolderConstants.OthersFolder))
                 {
-                    //but store any metadata changes 
-                    this.StatusKeeper.StoreInfo(fullFileName, info);
-                    Log.InfoFormat("Skip upload of {0}, hashes match", fullFileName);
-                    yield break;
+                    var parts = relativePath.Split('\\');
+                    var accountName = parts[1];
+                    var oldName = accountInfo.UserName;
+                    var absoluteUri = accountInfo.StorageUri.AbsoluteUri;
+                    var nameIndex = absoluteUri.IndexOf(oldName);
+                    var root = absoluteUri.Substring(0, nameIndex);
+
+                    accountInfo = new AccountInfo
+                    {
+                        UserName = accountName,
+                        AccountPath = Path.Combine(accountInfo.AccountPath, parts[0], parts[1]),
+                        StorageUri = new Uri(root + accountName),
+                        BlockHash = accountInfo.BlockHash,
+                        BlockSize = accountInfo.BlockSize,
+                        Token = accountInfo.Token
+                    };
                 }
 
-                if (info.AllowedTo=="read")
-                    yield break;
 
-                //Mark the file as modified while we upload it
-                StatusKeeper.SetFileOverlayStatus(fullFileName, FileOverlayStatus.Modified);
-                //And then upload it
-
-                //If the file is larger than the block size, try a hashmap PUT
-                if (fileInfo.Length > accountInfo.BlockSize )
+                var fullFileName = fileInfo.GetProperCapitalization();
+                using (var gate = NetworkGate.Acquire(fullFileName, NetworkOperation.Uploading))
                 {
-                    //To upload using a hashmap
-                    //First, calculate the tree hash
-                    var treeHash = Signature.CalculateTreeHashAsync(fileInfo.FullName, accountInfo.BlockSize,
-                        accountInfo.BlockHash);
-                    yield return treeHash;
+                    //Abort if the file is already being uploaded or downloaded
+                    if (gate.Failed)
+                        return;
+
+                    var cloudFile = action.CloudFile;
+                    var account = cloudFile.Account ?? accountInfo.UserName;
+
+                    var client = new CloudFilesClient(accountInfo);                    
+                    //Even if GetObjectInfo times out, we can proceed with the upload            
+                    var info = client.GetObjectInfo(account, cloudFile.Container, cloudFile.Name);
+
+                    //If this is a read-only file, do not upload changes
+                    if (info.AllowedTo == "read")
+                        return;
                     
-                    yield return Task.Factory.Iterate(UploadWithHashMap(accountInfo,account,container,fileInfo,url,treeHash));
-                                        
-                }
-                else
-                {
-                    //Otherwise do a regular PUT
-                    yield return client.PutObject(account, container, url, fullFileName, hash);                    
+                    //TODO: Check how a directory hash is calculated -> All dirs seem to have the same hash
+                    if (fileInfo is DirectoryInfo)
+                    {
+                        //If the directory doesn't exist the Hash property will be empty
+                        if (String.IsNullOrWhiteSpace(info.Hash))
+                            //Go on and create the directory
+                            await client.PutObject(account, cloudFile.Container, cloudFile.Name, fullFileName, String.Empty, "application/directory");
+                    }
+                    else
+                    {
+
+                        var cloudHash = info.Hash.ToLower();
+
+                        var hash = action.LocalHash.Value;
+                        var topHash = action.TopHash.Value;
+
+                        //If the file hashes match, abort the upload
+                        if (hash == cloudHash || topHash == cloudHash)
+                        {
+                            //but store any metadata changes 
+                            StatusKeeper.StoreInfo(fullFileName, info);
+                            Log.InfoFormat("Skip upload of {0}, hashes match", fullFileName);
+                            return;
+                        }
+
+
+                        //Mark the file as modified while we upload it
+                        StatusKeeper.SetFileOverlayStatus(fullFileName, FileOverlayStatus.Modified);
+                        //And then upload it
+
+                        //Upload even small files using the Hashmap. The server may already contain
+                        //the relevant block
+
+                        //First, calculate the tree hash
+                        var treeHash = await Signature.CalculateTreeHashAsync(fullFileName, accountInfo.BlockSize,
+                                                                              accountInfo.BlockHash);
+
+                        await UploadWithHashMap(accountInfo, cloudFile, fileInfo as FileInfo, cloudFile.Name, treeHash);
+                    }
+                    //If everything succeeds, change the file and overlay status to normal
+                    StatusKeeper.SetFileState(fullFileName, FileStatus.Unchanged, FileOverlayStatus.Normal);
                 }
-                //If everything succeeds, change the file and overlay status to normal
-                this.StatusKeeper.SetFileState(fullFileName, FileStatus.Unchanged, FileOverlayStatus.Normal);
+                //Notify the Shell to update the overlays
+                NativeMethods.RaiseChangeNotification(fullFileName);
+                StatusNotification.NotifyChangedFile(fullFileName);
+            }
+            catch (AggregateException ex)
+            {
+                var exc = ex.InnerException as WebException;
+                if (exc == null)
+                    throw ex.InnerException;
+                if (HandleUploadWebException(action, exc)) 
+                    return;
+                throw;
+            }
+            catch (WebException ex)
+            {
+                if (HandleUploadWebException(action, ex))
+                    return;
+                throw;
+            }
+            catch (Exception ex)
+            {
+                Log.Error("Unexpected error while uploading file", ex);
+                throw;
+            }
+
+        }
+
+        private bool IsDeletedFile(CloudAction action)
+        {            
+            var key = GetFileKey(action.CloudFile);
+            DateTime entryDate;
+            if (_deletedFiles.TryGetValue(key, out entryDate))
+            {
+                //If the delete entry was created after this action, abort the action
+                if (entryDate > action.Created)
+                    return true;
+                //Otherwise, remove the stale entry 
+                _deletedFiles.TryRemove(key, out entryDate);
+            }
+            return false;
+        }
+
+        private bool HandleUploadWebException(CloudAction action, WebException exc)
+        {
+            var response = exc.Response as HttpWebResponse;
+            if (response == null)
+                throw exc;
+            if (response.StatusCode == HttpStatusCode.Unauthorized)
+            {
+                Log.Error("Not allowed to upload file", exc);
+                var message = String.Format("Not allowed to uplad file {0}", action.LocalFile.FullName);
+                StatusKeeper.SetFileState(action.LocalFile.FullName, FileStatus.Unchanged, FileOverlayStatus.Normal);
+                StatusNotification.NotifyChange(message, TraceLevel.Warning);
+                return true;
             }
-            //Notify the Shell to update the overlays
-            NativeMethods.RaiseChangeNotification(fullFileName);
-            StatusNotification.NotifyChangedFile(fullFileName);
+            return false;
         }
 
-        public IEnumerable<Task> UploadWithHashMap(AccountInfo accountInfo,string account,string container,FileInfo fileInfo,string url,Task<TreeHash> treeHash)
+        public async Task UploadWithHashMap(AccountInfo accountInfo,ObjectInfo cloudFile,FileInfo fileInfo,string url,TreeHash treeHash)
         {
             if (accountInfo == null)
                 throw new ArgumentNullException("accountInfo");
-            if (String.IsNullOrWhiteSpace(account))
-                throw new ArgumentNullException("account");
-            if (String.IsNullOrWhiteSpace(container))
-                throw new ArgumentNullException("container");
+            if (cloudFile==null)
+                throw new ArgumentNullException("cloudFile");
             if (fileInfo == null)
                 throw new ArgumentNullException("fileInfo");
             if (String.IsNullOrWhiteSpace(url))
                 throw new ArgumentNullException(url);
             if (treeHash==null)
                 throw new ArgumentNullException("treeHash");
+            if (String.IsNullOrWhiteSpace(cloudFile.Container) )
+                throw new ArgumentException("Invalid container","cloudFile");
             Contract.EndContractBlock();
 
-            var fullFileName = fileInfo.FullName;
+            var fullFileName = fileInfo.GetProperCapitalization();
+
+            var account = cloudFile.Account ?? accountInfo.UserName;
+            var container = cloudFile.Container ;
 
             var client = new CloudFilesClient(accountInfo);
             //Send the hashmap to the server            
-            var hashPut = client.PutHashMap(account, container, url, treeHash.Result);
-            yield return hashPut;
-
-            var missingHashes = hashPut.Result;
+            var missingHashes =  await client.PutHashMap(account, container, url, treeHash);
             //If the server returns no missing hashes, we are done
             while (missingHashes.Count > 0)
             {
@@ -913,26 +1211,26 @@ namespace Pithos.Core.Agents
                 foreach (var missingHash in missingHashes)
                 {
                     //Find the proper block
-                    var blockIndex = treeHash.Result.HashDictionary[missingHash];
+                    var blockIndex = treeHash.HashDictionary[missingHash];
                     var offset = blockIndex*accountInfo.BlockSize;
 
                     var read = fileInfo.Read(buffer, offset, accountInfo.BlockSize);
 
-                    //And upload the block                
-                    var postBlock = client.PostBlock(account, container, buffer, 0, read);
+                    try
+                    {
+                        //And upload the block                
+                        await client.PostBlock(account, container, buffer, 0, read);
+                        Log.InfoFormat("[BLOCK] Block {0} of {1} uploaded", blockIndex, fullFileName);
+                    }
+                    catch (Exception exc)
+                    {
+                        Log.ErrorFormat("[ERROR] uploading block {0} of {1}\n{2}", blockIndex, fullFileName, exc);
+                    }
 
-                    //We have to handle possible exceptions in a continuation because
-                    //*yield return* can't appear inside a try block
-                    yield return postBlock.ContinueWith(t => 
-                        t.ReportExceptions(
-                            exc => Log.ErrorFormat("[ERROR] uploading block {0} of {1}\n{2}", blockIndex, fullFileName, exc),
-                            ()=>Log.InfoFormat("[BLOCK] Block {0} of {1} uploaded", blockIndex,fullFileName)));
                 }
 
-                //Repeat until there are no more missing hashes
-                hashPut = client.PutHashMap(account, container, url, treeHash.Result);
-                yield return hashPut;
-                missingHashes = hashPut.Result;
+                //Repeat until there are no more missing hashes                
+                missingHashes = await client.PutHashMap(account, container, url, treeHash);
             }
         }