Added check for startup option
[pithos-ms-client] / trunk / Pithos.Core / Agents / NetworkAgent.cs
1 // -----------------------------------------------------------------------
2 // <copyright file="NetworkAgent.cs" company="GRNET">
3 // Copyright 2011 GRNET S.A. All rights reserved.
4 // 
5 // Redistribution and use in source and binary forms, with or
6 // without modification, are permitted provided that the following
7 // conditions are met:
8 // 
9 //   1. Redistributions of source code must retain the above
10 //      copyright notice, this list of conditions and the following
11 //      disclaimer.
12 // 
13 //   2. Redistributions in binary form must reproduce the above
14 //      copyright notice, this list of conditions and the following
15 //      disclaimer in the documentation and/or other materials
16 //      provided with the distribution.
17 // 
18 // THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
19 // OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
20 // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
21 // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
22 // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
25 // USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
26 // AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27 // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
28 // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29 // POSSIBILITY OF SUCH DAMAGE.
30 // 
31 // The views and conclusions contained in the software and
32 // documentation are those of the authors and should not be
33 // interpreted as representing official policies, either expressed
34 // or implied, of GRNET S.A.
35 // </copyright>
36 // -----------------------------------------------------------------------
37
38 using System;
39 using System.Collections.Concurrent;
40 using System.Collections.Generic;
41 using System.ComponentModel.Composition;
42 using System.Diagnostics;
43 using System.Diagnostics.Contracts;
44 using System.IO;
45 using System.Linq;
46 using System.Net;
47 using System.Threading;
48 using System.Threading.Tasks;
49 using System.Threading.Tasks.Dataflow;
50 using Castle.ActiveRecord;
51 using Pithos.Interfaces;
52 using Pithos.Network;
53 using log4net;
54
55 namespace Pithos.Core.Agents
56 {
57     //TODO: Ensure all network operations use exact casing. Pithos is case sensitive
58     [Export]
59     public class NetworkAgent
60     {
61         private Agent<CloudAction> _agent;
62
63         //A separate agent is used to execute delete actions immediatelly;
64         private ActionBlock<CloudDeleteAction> _deleteAgent;
65         readonly ConcurrentDictionary<string,DateTime> _deletedFiles=new ConcurrentDictionary<string, DateTime>();
66
67
68         private readonly ManualResetEventSlim _pauseAgent = new ManualResetEventSlim(true);
69
70         [System.ComponentModel.Composition.Import]
71         public IStatusKeeper StatusKeeper { get; set; }
72         
73         public IStatusNotification StatusNotification { get; set; }
74
75         private static readonly ILog Log = LogManager.GetLogger("NetworkAgent");
76
77         private readonly ConcurrentBag<AccountInfo> _accounts = new ConcurrentBag<AccountInfo>();
78
79         [System.ComponentModel.Composition.Import]
80         public IPithosSettings Settings { get; set; }
81
82         private bool _firstPoll = true;
83         private TaskCompletionSource<bool> _tcs;
84
85         public void Start()
86         {
87             _firstPoll = true;
88             _agent = Agent<CloudAction>.Start(inbox =>
89             {
90                 Action loop = null;
91                 loop = () =>
92                 {
93                     _pauseAgent.Wait();
94                     var message = inbox.Receive();
95                     var process=message.Then(Process,inbox.CancellationToken);
96                     inbox.LoopAsync(process, loop);
97                 };
98                 loop();
99             });
100
101             _deleteAgent = new ActionBlock<CloudDeleteAction>(message =>ProcessDelete(message),new ExecutionDataflowBlockOptions{MaxDegreeOfParallelism=4});
102             /*
103                 Action loop = null;
104                 loop = () =>
105                             {
106                                 var message = inbox.Receive();
107                                 var process = message.Then(ProcessDelete,inbox.CancellationToken);
108                                 inbox.LoopAsync(process, loop);
109                             };
110                 loop();
111 */
112
113         }
114
115         private async Task Process(CloudAction action)
116         {
117             if (action == null)
118                 throw new ArgumentNullException("action");
119             if (action.AccountInfo==null)
120                 throw new ArgumentException("The action.AccountInfo is empty","action");
121             Contract.EndContractBlock();
122
123             var accountInfo = action.AccountInfo;
124
125             using (log4net.ThreadContext.Stacks["NETWORK"].Push("PROCESS"))
126             {                
127                 Log.InfoFormat("[ACTION] Start Processing {0}", action);
128
129                 var cloudFile = action.CloudFile;
130                 var downloadPath = action.GetDownloadPath();
131
132                 try
133                 {
134
135                     if (action.Action == CloudActionType.DeleteCloud)
136                     {
137                         //Redirect deletes to the delete agent 
138                         _deleteAgent.Post((CloudDeleteAction)action);                        
139                     }
140                     if (IsDeletedFile(action))
141                     {
142                         //Clear the status of already deleted files to avoid reprocessing
143                         if (action.LocalFile != null)
144                             this.StatusKeeper.ClearFileStatus(action.LocalFile.FullName);
145                     }
146                     else
147                     {
148                         switch (action.Action)
149                         {
150                             case CloudActionType.UploadUnconditional:
151                                 //Abort if the file was deleted before we reached this point
152                                 await UploadCloudFile(action);
153                                 break;
154                             case CloudActionType.DownloadUnconditional:
155                                 await DownloadCloudFile(accountInfo, cloudFile, downloadPath);
156                                 break;
157                             case CloudActionType.RenameCloud:
158                                 var moveAction = (CloudMoveAction) action;
159                                 RenameCloudFile(accountInfo, moveAction);
160                                 break;
161                             case CloudActionType.MustSynch:
162                                 if (!File.Exists(downloadPath) && !Directory.Exists(downloadPath))
163                                 {
164                                     await DownloadCloudFile(accountInfo, cloudFile, downloadPath);
165                                 }
166                                 else
167                                 {
168                                     await SyncFiles(accountInfo, action);
169                                 }
170                                 break;
171                         }
172                     }
173                     Log.InfoFormat("[ACTION] End Processing {0}:{1}->{2}", action.Action, action.LocalFile,
174                                            action.CloudFile.Name);
175                 }
176                 catch (WebException exc)
177                 {
178                     Log.ErrorFormat("[WEB ERROR] {0} : {1} -> {2} due to exception\r\n{3}", action.Action, action.LocalFile, action.CloudFile, exc);
179                 }
180                 catch (OperationCanceledException)
181                 {
182                     throw;
183                 }
184                 catch (DirectoryNotFoundException)
185                 {
186                     Log.ErrorFormat("{0} : {1} -> {2}  failed because the directory was not found.\n Rescheduling a delete",
187                         action.Action, action.LocalFile, action.CloudFile);
188                     //Post a delete action for the missing file
189                     Post(new CloudDeleteAction(action));                    
190                 }
191                 catch (FileNotFoundException)
192                 {
193                     Log.ErrorFormat("{0} : {1} -> {2}  failed because the file was not found.\n Rescheduling a delete",
194                         action.Action, action.LocalFile, action.CloudFile);
195                     //Post a delete action for the missing file
196                     Post(new CloudDeleteAction(action));
197                 }
198                 catch (Exception exc)
199                 {
200                     Log.ErrorFormat("[REQUEUE] {0} : {1} -> {2} due to exception\r\n{3}",
201                                      action.Action, action.LocalFile, action.CloudFile, exc);
202
203                     _agent.Post(action);
204                 }                
205             }
206         }
207
208         /// <summary>
209         /// Processes cloud delete actions
210         /// </summary>
211         /// <param name="action">The delete action to execute</param>
212         /// <returns></returns>
213         /// <remarks>
214         /// When a file/folder is deleted locally, we must delete it ASAP from the server and block any download
215         /// operations that may be in progress.
216         /// <para>
217         /// A separate agent is used to process deletes because the main agent may be busy with a long operation.
218         /// </para>
219         /// </remarks>
220         private async Task ProcessDelete(CloudDeleteAction action)
221         {
222             if (action == null)
223                 throw new ArgumentNullException("action");
224             if (action.AccountInfo==null)
225                 throw new ArgumentException("The action.AccountInfo is empty","action");
226             Contract.EndContractBlock();
227
228             var accountInfo = action.AccountInfo;
229
230             using (log4net.ThreadContext.Stacks["NETWORK"].Push("PROCESS"))
231             {                
232                 Log.InfoFormat("[ACTION] Start Processing {0}", action);
233
234                 var cloudFile = action.CloudFile;
235
236                 try
237                 {
238                     //Acquire a lock on the deleted file to prevent uploading/downloading operations from the normal
239                     //agent
240                     using (var gate = NetworkGate.Acquire(action.LocalFile.FullName, NetworkOperation.Deleting))
241                     {
242
243                         //Add the file URL to the deleted files list
244                         var key = GetFileKey(action.CloudFile);
245                         _deletedFiles[key] = DateTime.Now;
246
247                         _pauseAgent.Reset();
248                         // and then delete the file from the server
249                         DeleteCloudFile(accountInfo, cloudFile);
250
251                         Log.InfoFormat("[ACTION] End Delete {0}:{1}->{2}", action.Action, action.LocalFile,
252                                        action.CloudFile.Name);
253                     }
254                 }
255                 catch (WebException exc)
256                 {
257                     Log.ErrorFormat("[WEB ERROR] {0} : {1} -> {2} due to exception\r\n{3}", action.Action, action.LocalFile, action.CloudFile, exc);
258                 }
259                 catch (OperationCanceledException)
260                 {
261                     throw;
262                 }
263                 catch (DirectoryNotFoundException)
264                 {
265                     Log.ErrorFormat("{0} : {1} -> {2}  failed because the directory was not found.\n Rescheduling a delete",
266                         action.Action, action.LocalFile, action.CloudFile);
267                     //Repost a delete action for the missing file
268                     _deleteAgent.Post(action);
269                 }
270                 catch (FileNotFoundException)
271                 {
272                     Log.ErrorFormat("{0} : {1} -> {2}  failed because the file was not found.\n Rescheduling a delete",
273                         action.Action, action.LocalFile, action.CloudFile);
274                     //Post a delete action for the missing file
275                     _deleteAgent.Post(action);
276                 }
277                 catch (Exception exc)
278                 {
279                     Log.ErrorFormat("[REQUEUE] {0} : {1} -> {2} due to exception\r\n{3}",
280                                      action.Action, action.LocalFile, action.CloudFile, exc);
281
282                     _deleteAgent.Post(action);
283                 }
284                 finally
285                 {
286                     if (_deleteAgent.InputCount == 0)
287                         _pauseAgent.Set();
288
289                 }
290             }
291         }
292
293         private static string GetFileKey(ObjectInfo info)
294         {
295             var key = String.Format("{0}/{1}/{2}", info.Account, info.Container,info.Name);
296             return key;
297         }
298
299         private async Task SyncFiles(AccountInfo accountInfo,CloudAction action)
300         {
301             if (accountInfo == null)
302                 throw new ArgumentNullException("accountInfo");
303             if (action==null)
304                 throw new ArgumentNullException("action");
305             if (action.LocalFile==null)
306                 throw new ArgumentException("The action's local file is not specified","action");
307             if (!Path.IsPathRooted(action.LocalFile.FullName))
308                 throw new ArgumentException("The action's local file path must be absolute","action");
309             if (action.CloudFile== null)
310                 throw new ArgumentException("The action's cloud file is not specified", "action");
311             Contract.EndContractBlock();
312
313             var localFile = action.LocalFile;
314             var cloudFile = action.CloudFile;
315             var downloadPath=action.LocalFile.GetProperCapitalization();
316
317             var cloudHash = cloudFile.Hash.ToLower();
318             var localHash = action.LocalHash.Value.ToLower();
319             var topHash = action.TopHash.Value.ToLower();
320
321             //Not enough to compare only the local hashes, also have to compare the tophashes
322             
323             //If any of the hashes match, we are done
324             if ((cloudHash == localHash || cloudHash == topHash))
325             {
326                 Log.InfoFormat("Skipping {0}, hashes match",downloadPath);
327                 return;
328             }
329
330             //The hashes DON'T match. We need to sync
331             var lastLocalTime = localFile.LastWriteTime;
332             var lastUpTime = cloudFile.Last_Modified;
333             
334             //If the local file is newer upload it
335             if (lastUpTime <= lastLocalTime)
336             {
337                 //It probably means it was changed while the app was down                        
338                 UploadCloudFile(action);
339             }
340             else
341             {
342                 //It the cloud file has a later date, it was modified by another user or computer.
343                 //We need to check the local file's status                
344                 var status = StatusKeeper.GetFileStatus(downloadPath);
345                 switch (status)
346                 {
347                     case FileStatus.Unchanged:                        
348                         //If the local file's status is Unchanged, we can go on and download the newer cloud file
349                         await DownloadCloudFile(accountInfo,cloudFile,downloadPath);
350                         break;
351                     case FileStatus.Modified:
352                         //If the local file is Modified, we may have a conflict. In this case we should mark the file as Conflict
353                         //We can't ensure that a file modified online since the last time will appear as Modified, unless we 
354                         //index all files before we start listening.                       
355                     case FileStatus.Created:
356                         //If the local file is Created, it means that the local and cloud files aren't related,
357                         // yet they have the same name.
358
359                         //In both cases we must mark the file as in conflict
360                         ReportConflict(downloadPath);
361                         break;
362                     default:
363                         //Other cases should never occur. Mark them as Conflict as well but log a warning
364                         ReportConflict(downloadPath);
365                         Log.WarnFormat("Unexcepted status {0} for file {1}->{2}", status,
366                                        downloadPath, action.CloudFile.Name);
367                         break;
368                 }
369             }
370         }
371
372         private void ReportConflict(string downloadPath)
373         {
374             if (String.IsNullOrWhiteSpace(downloadPath))
375                 throw new ArgumentNullException("downloadPath");
376             Contract.EndContractBlock();
377
378             StatusKeeper.SetFileOverlayStatus(downloadPath, FileOverlayStatus.Conflict);
379             var message = String.Format("Conflict detected for file {0}", downloadPath);
380             Log.Warn(message);
381             StatusNotification.NotifyChange(message, TraceLevel.Warning);
382         }
383
384         public void Post(CloudAction cloudAction)
385         {
386             if (cloudAction == null)
387                 throw new ArgumentNullException("cloudAction");
388             if (cloudAction.AccountInfo==null)
389                 throw new ArgumentException("The CloudAction.AccountInfo is empty","cloudAction");
390             Contract.EndContractBlock();
391
392             _pauseAgent.Wait();
393
394             //If the action targets a local file, add a treehash calculation
395             if (!(cloudAction is CloudDeleteAction) && cloudAction.LocalFile as FileInfo != null)
396             {
397                 var accountInfo = cloudAction.AccountInfo;
398                 var localFile = (FileInfo) cloudAction.LocalFile;
399                 if (localFile.Length > accountInfo.BlockSize)
400                     cloudAction.TopHash =
401                         new Lazy<string>(() => Signature.CalculateTreeHashAsync(localFile,
402                                                                                 accountInfo.BlockSize,
403                                                                                 accountInfo.BlockHash).Result
404                                                     .TopHash.ToHashString());
405                 else
406                 {
407                     cloudAction.TopHash = new Lazy<string>(() => cloudAction.LocalHash.Value);
408                 }
409             }
410             else
411             {
412                 //The hash for a directory is the empty string
413                 cloudAction.TopHash = new Lazy<string>(() => String.Empty);
414             }
415             
416             if (cloudAction is CloudDeleteAction)
417                 _deleteAgent.Post((CloudDeleteAction)cloudAction);
418             else
419                 _agent.Post(cloudAction);
420         }
421
422        /* class ObjectInfoByNameComparer:IEqualityComparer<ObjectInfo>
423         {
424             public bool Equals(ObjectInfo x, ObjectInfo y)
425             {
426                 return x.Name.Equals(y.Name,StringComparison.InvariantCultureIgnoreCase);
427             }
428
429             public int GetHashCode(ObjectInfo obj)
430             {
431                 return obj.Name.ToLower().GetHashCode();
432             }
433         }*/
434
435         public void SynchNow()
436         {             
437             if (_tcs!=null)
438                 _tcs.SetResult(true);
439             else
440             {
441                 //TODO: This may be OK for testing purposes, but we have no guarantee that it will
442                 //work properly in production
443                 PollRemoteFiles(repeat:false);
444             }
445         }
446
447         //Remote files are polled periodically. Any changes are processed
448         public async Task PollRemoteFiles(DateTime? since = null,bool repeat=true)
449         {
450
451             _tcs = new TaskCompletionSource<bool>();
452             var wait = TaskEx.Delay(TimeSpan.FromSeconds(Settings.PollingInterval), _agent.CancellationToken);
453             var signaledTask=await TaskEx.WhenAny(_tcs.Task,wait);
454             //If polling is signalled by SynchNow, ignore the since tag
455             if (signaledTask is Task<bool>)
456                 since = null;
457
458             using (log4net.ThreadContext.Stacks["Retrieve Remote"].Push("All accounts"))
459             {
460
461                 try
462                 {
463                     //Next time we will check for all changes since the current check minus 1 second
464                     //This is done to ensure there are no discrepancies due to clock differences
465                     DateTime nextSince = DateTime.Now.AddSeconds(-1);
466
467                     var tasks = from accountInfo in _accounts
468                                 select ProcessAccountFiles(accountInfo, since);
469
470                     await TaskEx.WhenAll(tasks.ToList());
471
472                     _firstPoll = false;
473                     if (repeat)
474                         PollRemoteFiles(nextSince);
475                 }
476                 catch (Exception ex)
477                 {
478                     Log.ErrorFormat("Error while processing accounts\r\n{0}",ex);
479                     //In case of failure retry with the same parameter
480                     PollRemoteFiles(since);
481                 }
482                 
483
484             }
485         }
486
487         public async Task ProcessAccountFiles(AccountInfo accountInfo,DateTime? since=null)
488         {   
489             if (accountInfo==null)
490                 throw new ArgumentNullException("accountInfo");
491             if (String.IsNullOrWhiteSpace(accountInfo.AccountPath))
492                 throw new ArgumentException("The AccountInfo.AccountPath is empty","accountInfo");
493             Contract.EndContractBlock();
494
495             using (log4net.ThreadContext.Stacks["Retrieve Remote"].Push(accountInfo.UserName))
496             {
497                 Log.Info("Scheduled");
498                 var client=new CloudFilesClient(accountInfo);
499
500                 var containers = client.ListContainers(accountInfo.UserName);
501                 
502                 CreateContainerFolders(accountInfo, containers);
503
504                 try
505                 {
506                     _pauseAgent.Wait();
507                     //Get the poll time now. We may miss some deletions but it's better to keep a file that was deleted
508                     //than delete a file that was created while we were executing the poll
509                     var pollTime = DateTime.Now;
510                     
511                     //Get the list of server objects changed since the last check
512                     //The name of the container is passed as state in order to create a dictionary of tasks in a subsequent step
513                     var listObjects = from container in containers
514                                       select  Task<IList<ObjectInfo>>.Factory.StartNew(_ =>
515                                             client.ListObjects(accountInfo.UserName,container.Name, since),container.Name);
516
517
518                     var listTasks = await Task.Factory.WhenAll(listObjects.ToArray());
519
520                     using (log4net.ThreadContext.Stacks["SCHEDULE"].Push("Process Results"))
521                     {
522                         var dict = listTasks.ToDictionary(t => t.AsyncState);
523
524                         //Get all non-trash objects. Remember, the container name is stored in AsyncState
525                         var remoteObjects = from objectList in listTasks
526                                             where (string) objectList.AsyncState != "trash"
527                                             from obj in objectList.Result
528                                             select obj;
529
530                         //TODO: Change the way deleted objects are detected.
531                         //The list operation returns all existing objects so we could detect deleted remote objects
532                         //by detecting objects that exist only locally. There are several cases where this is NOT the case:
533                         //1.    The first time the application runs, as there may be files that were added while 
534                         //      the application was down.
535                         //2.    An object that is currently being uploaded will not appear in the remote list
536                         //      until the upload finishes.
537                         //      SOLUTION 1: Check the upload/download queue for the file
538                         //      SOLUTION 2: Check the SQLite states for the file's entry. If it is being uploaded, 
539                         //          or its last modification was after the current poll, don't delete it. This way we don't
540                         //          delete objects whose upload finished too late to be included in the list.
541                         //We need to detect and protect against such situations
542                         //TODO: Does FileState have a LastModification field?
543                         //TODO: How do we update the LastModification field? Do we need to add SQLite triggers?
544                         //      Do we need to use a proper SQLite schema?
545                         //      We can create a trigger with 
546                         // CREATE TRIGGER IF NOT EXISTS update_last_modified UPDATE ON FileState FOR EACH ROW
547                         //  BEGIN
548                         //      UPDATE FileState SET LastModification=datetime('now')  WHERE Id=old.Id;
549                         //  END;
550                         //
551                         //NOTE: Some files may have been deleted remotely while the application was down. 
552                         //  We DO have to delete those files. Checking the trash makes it easy to detect them,
553                         //  Otherwise, we can't be really sure whether we need to upload or delete 
554                         //  the local-only files.
555                         //  SOLUTION 1: Ask the user when such a local-only file is detected during the first poll.
556                         //  SOLUTION 2: Mark conflict and ask the user as in #1
557
558                         var trashObjects = dict["trash"].Result;
559                         //var sharedObjects = ((Task<IList<ObjectInfo>>) task.Result[2]).Result;
560
561                         //Items with the same name, hash may be both in the container and the trash
562                         //Don't delete items that exist in the container
563                         var realTrash = from trash in trashObjects
564                                         where
565                                             !remoteObjects.Any(
566                                                 info => info.Name == trash.Name && info.Hash == trash.Hash)
567                                         select trash;
568                         ProcessTrashedFiles(accountInfo, realTrash);
569
570
571                         var cleanRemotes = (from info in remoteObjects
572                                      //.Union(sharedObjects)
573                                      let name = info.Name
574                                      where !name.EndsWith(".ignore", StringComparison.InvariantCultureIgnoreCase) &&
575                                            !name.StartsWith(FolderConstants.CacheFolder + "/",
576                                                             StringComparison.InvariantCultureIgnoreCase)
577                                      select info).ToList();
578
579
580
581                         ProcessDeletedFiles(accountInfo, cleanRemotes, pollTime);
582
583                         //Create a list of actions from the remote files
584                         var allActions = ObjectsToActions(accountInfo, cleanRemotes);
585
586                         
587                         //var relativePath = objectInfo.RelativeUrlToFilePath(accountInfo.UserName);
588
589                         //And remove those that are already being processed by the agent
590                         var distinctActions = allActions
591                             .Except(_agent.GetEnumerable(), new PithosMonitor.LocalFileComparer())
592                             .ToList();
593
594                         //Queue all the actions
595                         foreach (var message in distinctActions)
596                         {
597                             Post(message);
598                         }
599
600                         Log.Info("[LISTENER] End Processing");
601                     }
602                 }
603                 catch (Exception ex)
604                 {
605                     Log.ErrorFormat("[FAIL] ListObjects for{0} in ProcessRemoteFiles with {1}", accountInfo.UserName, ex);
606                     return;
607                 }
608
609                 Log.Info("[LISTENER] Finished");
610
611             }
612         }
613
614         /// <summary>
615         /// Deletes local files that are not found in the list of cloud files
616         /// </summary>
617         /// <param name="accountInfo"></param>
618         /// <param name="cloudFiles"></param>
619         /// <param name="pollTime"></param>
620         private void ProcessDeletedFiles(AccountInfo accountInfo, IEnumerable<ObjectInfo> cloudFiles, DateTime pollTime)
621         {
622             if (accountInfo == null)
623                 throw new ArgumentNullException("accountInfo");
624             if (String.IsNullOrWhiteSpace(accountInfo.AccountPath))
625                 throw new ArgumentException("The AccountInfo.AccountPath is empty", "accountInfo");
626             if (cloudFiles == null)
627                 throw new ArgumentNullException("cloudFiles");
628             Contract.EndContractBlock();
629
630             if (_firstPoll) return;
631
632             var deleteCandidates = from state in FileState.Queryable
633                                    let stateUrl = FileInfoExtensions.FromPath(state.FilePath)
634                                        .AsRelativeUrlTo(accountInfo.AccountPath)
635                                    where state.Modified <= pollTime &&
636                                          !cloudFiles.Any(r => r.Name == stateUrl)
637                                    select state;
638
639             foreach (var deleteCandidate in deleteCandidates)
640             {
641                 File.Delete(deleteCandidate.FilePath);
642                 StatusKeeper.ClearFileStatus(deleteCandidate.FilePath);
643             }
644         }
645
646         private static void CreateContainerFolders(AccountInfo accountInfo, IEnumerable<ContainerInfo> containers)
647         {
648             var containerPaths = from container in containers
649                                  let containerPath = Path.Combine(accountInfo.AccountPath, container.Name)
650                                  where container.Name != FolderConstants.TrashContainer && !Directory.Exists(containerPath)
651                                  select containerPath;
652
653             foreach (var path in containerPaths)
654             {
655                 Directory.CreateDirectory(path);
656             }
657         }
658
659         //Creates an appropriate action for each server file
660         private IEnumerable<CloudAction> ObjectsToActions(AccountInfo accountInfo,IEnumerable<ObjectInfo> remote)
661         {
662             if (remote==null)
663                 throw new ArgumentNullException();
664             Contract.EndContractBlock();
665             var fileAgent = GetFileAgent(accountInfo);
666
667             //In order to avoid multiple iterations over the files, we iterate only once
668             //over the remote files
669             foreach (var objectInfo in remote)
670             {
671                 var relativePath = objectInfo.RelativeUrlToFilePath(accountInfo.UserName);
672                 //and remove any matching objects from the list, adding them to the commonObjects list
673                 
674                 if (fileAgent.Exists(relativePath))
675                 {
676                     //If a directory object already exists, we don't need to perform any other action                    
677                     var localFile = fileAgent.GetFileSystemInfo(relativePath);
678                     if (objectInfo.Content_Type == @"application/directory" && localFile is DirectoryInfo)
679                         continue;
680                     using (new SessionScope(FlushAction.Never))
681                     {
682                         var state =  StatusKeeper.GetStateByFilePath(localFile.FullName);
683                         //FileState.FindByFilePath(localFile.FullName);
684                         //Common files should be checked on a per-case basis to detect differences, which is newer
685
686                         yield return new CloudAction(accountInfo, CloudActionType.MustSynch,
687                                                      localFile, objectInfo, state, accountInfo.BlockSize,
688                                                      accountInfo.BlockHash);
689                     }
690                 }
691                 else
692                 {
693                     //If there is no match we add them to the localFiles list
694                     //but only if the file is not marked for deletion
695                     var targetFile = Path.Combine(accountInfo.AccountPath, relativePath);
696                     var fileStatus = StatusKeeper.GetFileStatus(targetFile);
697                     if (fileStatus != FileStatus.Deleted)
698                     {
699                         //Remote files should be downloaded
700                         yield return new CloudDownloadAction(accountInfo,objectInfo);
701                     }
702                 }
703             }            
704         }
705
706         private static FileAgent GetFileAgent(AccountInfo accountInfo)
707         {
708             return AgentLocator<FileAgent>.Get(accountInfo.AccountPath);
709         }
710
711         private void ProcessTrashedFiles(AccountInfo accountInfo,IEnumerable<ObjectInfo> trashObjects)
712         {
713             var fileAgent = GetFileAgent(accountInfo);
714             foreach (var trashObject in trashObjects)
715             {
716                 var barePath = trashObject.RelativeUrlToFilePath(accountInfo.UserName);
717                 //HACK: Assume only the "pithos" container is used. Must find out what happens when
718                 //deleting a file from a different container
719                 var relativePath = Path.Combine("pithos", barePath);
720                 fileAgent.Delete(relativePath);                                
721             }
722         }
723
724
725         private void RenameCloudFile(AccountInfo accountInfo,CloudMoveAction action)
726         {
727             if (accountInfo==null)
728                 throw new ArgumentNullException("accountInfo");
729             if (action==null)
730                 throw new ArgumentNullException("action");
731             if (action.CloudFile==null)
732                 throw new ArgumentException("CloudFile","action");
733             if (action.LocalFile==null)
734                 throw new ArgumentException("LocalFile","action");
735             if (action.OldLocalFile==null)
736                 throw new ArgumentException("OldLocalFile","action");
737             if (action.OldCloudFile==null)
738                 throw new ArgumentException("OldCloudFile","action");
739             Contract.EndContractBlock();
740             
741             
742             var newFilePath = action.LocalFile.FullName;
743             
744             //How do we handle concurrent renames and deletes/uploads/downloads?
745             //* A conflicting upload means that a file was renamed before it had a chance to finish uploading
746             //  This should never happen as the network agent executes only one action at a time
747             //* A conflicting download means that the file was modified on the cloud. While we can go on and complete
748             //  the rename, there may be a problem if the file is downloaded in blocks, as subsequent block requests for the 
749             //  same name will fail.
750             //  This should never happen as the network agent executes only one action at a time.
751             //* A conflicting delete can happen if the rename was followed by a delete action that didn't have the chance
752             //  to remove the rename from the queue.
753             //  We can probably ignore this case. It will result in an error which should be ignored            
754
755             
756             //The local file is already renamed
757             StatusKeeper.SetFileOverlayStatus(newFilePath, FileOverlayStatus.Modified);
758
759
760             var account = action.CloudFile.Account ?? accountInfo.UserName;
761             var container = action.CloudFile.Container;
762             
763             var client = new CloudFilesClient(accountInfo);
764             //TODO: What code is returned when the source file doesn't exist?
765             client.MoveObject(account, container, action.OldCloudFile.Name, container, action.CloudFile.Name);
766
767             StatusKeeper.SetFileStatus(newFilePath, FileStatus.Unchanged);
768             StatusKeeper.SetFileOverlayStatus(newFilePath, FileOverlayStatus.Normal);
769             NativeMethods.RaiseChangeNotification(newFilePath);
770         }
771
772         private void DeleteCloudFile(AccountInfo accountInfo, ObjectInfo cloudFile)
773         {
774             if (accountInfo == null)
775                 throw new ArgumentNullException("accountInfo");
776             if (cloudFile==null)
777                 throw new ArgumentNullException("cloudFile");
778
779             if (String.IsNullOrWhiteSpace(cloudFile.Container))
780                 throw new ArgumentException("Invalid container", "cloudFile");
781             Contract.EndContractBlock();
782             
783             var fileAgent = GetFileAgent(accountInfo);
784
785             using ( log4net.ThreadContext.Stacks["DeleteCloudFile"].Push("Delete"))
786             {
787                 var fileName= cloudFile.RelativeUrlToFilePath(accountInfo.UserName);
788                 var info = fileAgent.GetFileSystemInfo(fileName);                
789                 var fullPath = info.FullName.ToLower();
790
791                 StatusKeeper.SetFileOverlayStatus(fullPath, FileOverlayStatus.Modified);
792
793                 var account = cloudFile.Account ?? accountInfo.UserName;
794                 var container = cloudFile.Container ;//?? FolderConstants.PithosContainer;
795
796                 var client = new CloudFilesClient(accountInfo);
797                 client.DeleteObject(account, container, cloudFile.Name);
798
799                 StatusKeeper.ClearFileStatus(fullPath);
800             }
801         }
802
803         //Download a file.
804         private async Task DownloadCloudFile(AccountInfo accountInfo, ObjectInfo cloudFile , string filePath)
805         {
806             if (accountInfo == null)
807                 throw new ArgumentNullException("accountInfo");
808             if (cloudFile == null)
809                 throw new ArgumentNullException("cloudFile");
810             if (String.IsNullOrWhiteSpace(cloudFile.Account))
811                 throw new ArgumentNullException("cloudFile");
812             if (String.IsNullOrWhiteSpace(cloudFile.Container))
813                 throw new ArgumentNullException("cloudFile");
814             if (String.IsNullOrWhiteSpace(filePath))
815                 throw new ArgumentNullException("filePath");
816             if (!Path.IsPathRooted(filePath))
817                 throw new ArgumentException("The filePath must be rooted", "filePath");
818             Contract.EndContractBlock();
819
820             var localPath = Interfaces.FileInfoExtensions.GetProperFilePathCapitalization(filePath);
821             var relativeUrl = new Uri(cloudFile.Name, UriKind.Relative);
822
823             var url = relativeUrl.ToString();
824             if (cloudFile.Name.EndsWith(".ignore", StringComparison.InvariantCultureIgnoreCase))
825                 return;
826
827
828             //Are we already downloading or uploading the file? 
829             using (var gate=NetworkGate.Acquire(localPath, NetworkOperation.Downloading))
830             {
831                 if (gate.Failed)
832                     return;
833                 //The file's hashmap will be stored in the same location with the extension .hashmap
834                 //var hashPath = Path.Combine(FileAgent.CachePath, relativePath + ".hashmap");
835                 
836                 var client = new CloudFilesClient(accountInfo);
837                 var account = cloudFile.Account;
838                 var container = cloudFile.Container;
839
840                 if (cloudFile.Content_Type == @"application/directory")
841                 {
842                     if (!Directory.Exists(localPath))
843                         Directory.CreateDirectory(localPath);
844                 }
845                 else
846                 {
847                     //Retrieve the hashmap from the server
848                     var serverHash = await client.GetHashMap(account, container, url);
849                     //If it's a small file
850                     if (serverHash.Hashes.Count == 1)
851                         //Download it in one go
852                         await
853                             DownloadEntireFileAsync(accountInfo, client, cloudFile, relativeUrl, localPath, serverHash);
854                         //Otherwise download it block by block
855                     else
856                         await DownloadWithBlocks(accountInfo, client, cloudFile, relativeUrl, localPath, serverHash);
857
858                     if (cloudFile.AllowedTo == "read")
859                     {
860                         var attributes = File.GetAttributes(localPath);
861                         File.SetAttributes(localPath, attributes | FileAttributes.ReadOnly);                        
862                     }
863                 }
864
865                 //Now we can store the object's metadata without worrying about ghost status entries
866                 StatusKeeper.StoreInfo(localPath, cloudFile);
867                 
868             }
869         }
870
871         //Download a small file with a single GET operation
872         private async Task DownloadEntireFileAsync(AccountInfo accountInfo, CloudFilesClient client, ObjectInfo cloudFile, Uri relativeUrl, string filePath,TreeHash serverHash)
873         {
874             if (client == null)
875                 throw new ArgumentNullException("client");
876             if (cloudFile==null)
877                 throw new ArgumentNullException("cloudFile");
878             if (relativeUrl == null)
879                 throw new ArgumentNullException("relativeUrl");
880             if (String.IsNullOrWhiteSpace(filePath))
881                 throw new ArgumentNullException("filePath");
882             if (!Path.IsPathRooted(filePath))
883                 throw new ArgumentException("The localPath must be rooted", "filePath");
884             Contract.EndContractBlock();
885
886             var localPath = Pithos.Interfaces.FileInfoExtensions.GetProperFilePathCapitalization(filePath);
887             //If the file already exists
888             if (File.Exists(localPath))
889             {
890                 //First check with MD5 as this is a small file
891                 var localMD5 = Signature.CalculateMD5(localPath);
892                 var cloudHash=serverHash.TopHash.ToHashString();
893                 if (localMD5==cloudHash)
894                     return;
895                 //Then check with a treehash
896                 var localTreeHash = Signature.CalculateTreeHash(localPath, serverHash.BlockSize, serverHash.BlockHash);
897                 var localHash = localTreeHash.TopHash.ToHashString();
898                 if (localHash==cloudHash)
899                     return;
900             }
901
902             var fileAgent = GetFileAgent(accountInfo);
903             //Calculate the relative file path for the new file
904             var relativePath = relativeUrl.RelativeUriToFilePath();
905             //The file will be stored in a temporary location while downloading with an extension .download
906             var tempPath = Path.Combine(fileAgent.CachePath, relativePath + ".download");
907             //Make sure the target folder exists. DownloadFileTask will not create the folder
908             var tempFolder = Path.GetDirectoryName(tempPath);
909             if (!Directory.Exists(tempFolder))
910                 Directory.CreateDirectory(tempFolder);
911
912             //Download the object to the temporary location
913             await client.GetObject(cloudFile.Account, cloudFile.Container, relativeUrl.ToString(), tempPath);
914
915             //Create the local folder if it doesn't exist (necessary for shared objects)
916             var localFolder = Path.GetDirectoryName(localPath);
917             if (!Directory.Exists(localFolder))
918                 Directory.CreateDirectory(localFolder);            
919             //And move it to its actual location once downloading is finished
920             if (File.Exists(localPath))
921                 File.Replace(tempPath,localPath,null,true);
922             else
923                 File.Move(tempPath,localPath);
924             //Notify listeners that a local file has changed
925             StatusNotification.NotifyChangedFile(localPath);
926
927                        
928         }
929
930         //Download a file asynchronously using blocks
931         public async Task DownloadWithBlocks(AccountInfo accountInfo, CloudFilesClient client, ObjectInfo cloudFile, Uri relativeUrl, string filePath, TreeHash serverHash)
932         {
933             if (client == null)
934                 throw new ArgumentNullException("client");
935             if (cloudFile == null)
936                 throw new ArgumentNullException("cloudFile");
937             if (relativeUrl == null)
938                 throw new ArgumentNullException("relativeUrl");
939             if (String.IsNullOrWhiteSpace(filePath))
940                 throw new ArgumentNullException("filePath");
941             if (!Path.IsPathRooted(filePath))
942                 throw new ArgumentException("The filePath must be rooted", "filePath");
943             if (serverHash == null)
944                 throw new ArgumentNullException("serverHash");
945             Contract.EndContractBlock();
946             
947            var fileAgent = GetFileAgent(accountInfo);
948             var localPath = Interfaces.FileInfoExtensions.GetProperFilePathCapitalization(filePath);
949             
950             //Calculate the relative file path for the new file
951             var relativePath = relativeUrl.RelativeUriToFilePath();
952             var blockUpdater = new BlockUpdater(fileAgent.CachePath, localPath, relativePath, serverHash);
953
954             
955                         
956             //Calculate the file's treehash
957             var treeHash = await Signature.CalculateTreeHashAsync(localPath, serverHash.BlockSize, serverHash.BlockHash);
958                 
959             //And compare it with the server's hash
960             var upHashes = serverHash.GetHashesAsStrings();
961             var localHashes = treeHash.HashDictionary;
962             for (int i = 0; i < upHashes.Length; i++)
963             {
964                 //For every non-matching hash
965                 var upHash = upHashes[i];
966                 if (!localHashes.ContainsKey(upHash))
967                 {
968                     if (blockUpdater.UseOrphan(i, upHash))
969                     {
970                         Log.InfoFormat("[BLOCK GET] ORPHAN FOUND for {0} of {1} for {2}", i, upHashes.Length, localPath);
971                         continue;
972                     }
973                     Log.InfoFormat("[BLOCK GET] START {0} of {1} for {2}", i, upHashes.Length, localPath);
974                     var start = i*serverHash.BlockSize;
975                     //To download the last block just pass a null for the end of the range
976                     long? end = null;
977                     if (i < upHashes.Length - 1 )
978                         end= ((i + 1)*serverHash.BlockSize) ;
979                             
980                     //Download the missing block
981                     var block = await client.GetBlock(cloudFile.Account, cloudFile.Container, relativeUrl, start, end);
982
983                     //and store it
984                     blockUpdater.StoreBlock(i, block);
985
986
987                     Log.InfoFormat("[BLOCK GET] FINISH {0} of {1} for {2}", i, upHashes.Length, localPath);
988                 }
989             }
990
991             //Want to avoid notifications if no changes were made
992             var hasChanges = blockUpdater.HasBlocks;
993             blockUpdater.Commit();
994             
995             if (hasChanges)
996                 //Notify listeners that a local file has changed
997                 StatusNotification.NotifyChangedFile(localPath);
998
999             Log.InfoFormat("[BLOCK GET] COMPLETE {0}", localPath);            
1000         }
1001
1002
1003         private async Task UploadCloudFile(CloudAction action)
1004         {
1005             if (action == null)
1006                 throw new ArgumentNullException("action");           
1007             Contract.EndContractBlock();
1008
1009             try
1010             {
1011                 var accountInfo = action.AccountInfo;
1012
1013                 var fileInfo = action.LocalFile;
1014
1015                 if (fileInfo.Extension.Equals("ignore", StringComparison.InvariantCultureIgnoreCase))
1016                     return;
1017                 
1018                 var relativePath = fileInfo.AsRelativeTo(accountInfo.AccountPath);
1019                 if (relativePath.StartsWith(FolderConstants.OthersFolder))
1020                 {
1021                     var parts = relativePath.Split('\\');
1022                     var accountName = parts[1];
1023                     var oldName = accountInfo.UserName;
1024                     var absoluteUri = accountInfo.StorageUri.AbsoluteUri;
1025                     var nameIndex = absoluteUri.IndexOf(oldName);
1026                     var root = absoluteUri.Substring(0, nameIndex);
1027
1028                     accountInfo = new AccountInfo
1029                     {
1030                         UserName = accountName,
1031                         AccountPath = Path.Combine(accountInfo.AccountPath, parts[0], parts[1]),
1032                         StorageUri = new Uri(root + accountName),
1033                         BlockHash = accountInfo.BlockHash,
1034                         BlockSize = accountInfo.BlockSize,
1035                         Token = accountInfo.Token
1036                     };
1037                 }
1038
1039
1040                 var fullFileName = fileInfo.GetProperCapitalization();
1041                 using (var gate = NetworkGate.Acquire(fullFileName, NetworkOperation.Uploading))
1042                 {
1043                     //Abort if the file is already being uploaded or downloaded
1044                     if (gate.Failed)
1045                         return;
1046
1047                     var cloudFile = action.CloudFile;
1048                     var account = cloudFile.Account ?? accountInfo.UserName;
1049
1050                     var client = new CloudFilesClient(accountInfo);                    
1051                     //Even if GetObjectInfo times out, we can proceed with the upload            
1052                     var info = client.GetObjectInfo(account, cloudFile.Container, cloudFile.Name);
1053
1054                     //If this is a read-only file, do not upload changes
1055                     if (info.AllowedTo == "read")
1056                         return;
1057                     
1058                     //TODO: Check how a directory hash is calculated -> All dirs seem to have the same hash
1059                     if (fileInfo is DirectoryInfo)
1060                     {
1061                         //If the directory doesn't exist the Hash property will be empty
1062                         if (String.IsNullOrWhiteSpace(info.Hash))
1063                             //Go on and create the directory
1064                             await client.PutObject(account, cloudFile.Container, cloudFile.Name, fullFileName, String.Empty, "application/directory");
1065                     }
1066                     else
1067                     {
1068
1069                         var cloudHash = info.Hash.ToLower();
1070
1071                         var hash = action.LocalHash.Value;
1072                         var topHash = action.TopHash.Value;
1073
1074                         //If the file hashes match, abort the upload
1075                         if (hash == cloudHash || topHash == cloudHash)
1076                         {
1077                             //but store any metadata changes 
1078                             StatusKeeper.StoreInfo(fullFileName, info);
1079                             Log.InfoFormat("Skip upload of {0}, hashes match", fullFileName);
1080                             return;
1081                         }
1082
1083
1084                         //Mark the file as modified while we upload it
1085                         StatusKeeper.SetFileOverlayStatus(fullFileName, FileOverlayStatus.Modified);
1086                         //And then upload it
1087
1088                         //Upload even small files using the Hashmap. The server may already contain
1089                         //the relevant block
1090
1091                         //First, calculate the tree hash
1092                         var treeHash = await Signature.CalculateTreeHashAsync(fullFileName, accountInfo.BlockSize,
1093                                                                               accountInfo.BlockHash);
1094
1095                         await UploadWithHashMap(accountInfo, cloudFile, fileInfo as FileInfo, cloudFile.Name, treeHash);
1096                     }
1097                     //If everything succeeds, change the file and overlay status to normal
1098                     StatusKeeper.SetFileState(fullFileName, FileStatus.Unchanged, FileOverlayStatus.Normal);
1099                 }
1100                 //Notify the Shell to update the overlays
1101                 NativeMethods.RaiseChangeNotification(fullFileName);
1102                 StatusNotification.NotifyChangedFile(fullFileName);
1103             }
1104             catch (AggregateException ex)
1105             {
1106                 var exc = ex.InnerException as WebException;
1107                 if (exc == null)
1108                     throw ex.InnerException;
1109                 if (HandleUploadWebException(action, exc)) 
1110                     return;
1111                 throw;
1112             }
1113             catch (WebException ex)
1114             {
1115                 if (HandleUploadWebException(action, ex))
1116                     return;
1117                 throw;
1118             }
1119             catch (Exception ex)
1120             {
1121                 Log.Error("Unexpected error while uploading file", ex);
1122                 throw;
1123             }
1124
1125         }
1126
1127         private bool IsDeletedFile(CloudAction action)
1128         {            
1129             var key = GetFileKey(action.CloudFile);
1130             DateTime entryDate;
1131             if (_deletedFiles.TryGetValue(key, out entryDate))
1132             {
1133                 //If the delete entry was created after this action, abort the action
1134                 if (entryDate > action.Created)
1135                     return true;
1136                 //Otherwise, remove the stale entry 
1137                 _deletedFiles.TryRemove(key, out entryDate);
1138             }
1139             return false;
1140         }
1141
1142         private bool HandleUploadWebException(CloudAction action, WebException exc)
1143         {
1144             var response = exc.Response as HttpWebResponse;
1145             if (response == null)
1146                 throw exc;
1147             if (response.StatusCode == HttpStatusCode.Unauthorized)
1148             {
1149                 Log.Error("Not allowed to upload file", exc);
1150                 var message = String.Format("Not allowed to uplad file {0}", action.LocalFile.FullName);
1151                 StatusKeeper.SetFileState(action.LocalFile.FullName, FileStatus.Unchanged, FileOverlayStatus.Normal);
1152                 StatusNotification.NotifyChange(message, TraceLevel.Warning);
1153                 return true;
1154             }
1155             return false;
1156         }
1157
1158         public async Task UploadWithHashMap(AccountInfo accountInfo,ObjectInfo cloudFile,FileInfo fileInfo,string url,TreeHash treeHash)
1159         {
1160             if (accountInfo == null)
1161                 throw new ArgumentNullException("accountInfo");
1162             if (cloudFile==null)
1163                 throw new ArgumentNullException("cloudFile");
1164             if (fileInfo == null)
1165                 throw new ArgumentNullException("fileInfo");
1166             if (String.IsNullOrWhiteSpace(url))
1167                 throw new ArgumentNullException(url);
1168             if (treeHash==null)
1169                 throw new ArgumentNullException("treeHash");
1170             if (String.IsNullOrWhiteSpace(cloudFile.Container) )
1171                 throw new ArgumentException("Invalid container","cloudFile");
1172             Contract.EndContractBlock();
1173
1174             var fullFileName = fileInfo.GetProperCapitalization();
1175
1176             var account = cloudFile.Account ?? accountInfo.UserName;
1177             var container = cloudFile.Container ;
1178
1179             var client = new CloudFilesClient(accountInfo);
1180             //Send the hashmap to the server            
1181             var missingHashes =  await client.PutHashMap(account, container, url, treeHash);
1182             //If the server returns no missing hashes, we are done
1183             while (missingHashes.Count > 0)
1184             {
1185
1186                 var buffer = new byte[accountInfo.BlockSize];
1187                 foreach (var missingHash in missingHashes)
1188                 {
1189                     //Find the proper block
1190                     var blockIndex = treeHash.HashDictionary[missingHash];
1191                     var offset = blockIndex*accountInfo.BlockSize;
1192
1193                     var read = fileInfo.Read(buffer, offset, accountInfo.BlockSize);
1194
1195                     try
1196                     {
1197                         //And upload the block                
1198                         await client.PostBlock(account, container, buffer, 0, read);
1199                         Log.InfoFormat("[BLOCK] Block {0} of {1} uploaded", blockIndex, fullFileName);
1200                     }
1201                     catch (Exception exc)
1202                     {
1203                         Log.ErrorFormat("[ERROR] uploading block {0} of {1}\n{2}", blockIndex, fullFileName, exc);
1204                     }
1205
1206                 }
1207
1208                 //Repeat until there are no more missing hashes                
1209                 missingHashes = await client.PutHashMap(account, container, url, treeHash);
1210             }
1211         }
1212
1213
1214         public void AddAccount(AccountInfo accountInfo)
1215         {            
1216             if (!_accounts.Contains(accountInfo))
1217                 _accounts.Add(accountInfo);
1218         }
1219     }
1220
1221    
1222
1223
1224 }