Modified loggers to use their enclosing class
[pithos-ms-client] / trunk / Pithos.Core / Agents / StatusAgent.cs
1 #region
2 /* -----------------------------------------------------------------------
3  * <copyright file="StatusAgent.cs" company="GRNet">
4  * 
5  * Copyright 2011-2012 GRNET S.A. All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or
8  * without modification, are permitted provided that the following
9  * conditions are met:
10  *
11  *   1. Redistributions of source code must retain the above
12  *      copyright notice, this list of conditions and the following
13  *      disclaimer.
14  *
15  *   2. Redistributions in binary form must reproduce the above
16  *      copyright notice, this list of conditions and the following
17  *      disclaimer in the documentation and/or other materials
18  *      provided with the distribution.
19  *
20  *
21  * THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
22  * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
23  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
24  * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
25  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
26  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
27  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
28  * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
29  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
31  * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
32  * POSSIBILITY OF SUCH DAMAGE.
33  *
34  * The views and conclusions contained in the software and
35  * documentation are those of the authors and should not be
36  * interpreted as representing official policies, either expressed
37  * or implied, of GRNET S.A.
38  * </copyright>
39  * -----------------------------------------------------------------------
40  */
41 #endregion
42 using System;
43 using System.Collections.Generic;
44 using System.ComponentModel.Composition;
45 using System.Data.SQLite;
46 using System.Diagnostics;
47 using System.Diagnostics.Contracts;
48 using System.IO;
49 using System.Linq;
50 using System.Reflection;
51 using System.Text;
52 using System.Threading;
53 using System.Threading.Tasks;
54 using Castle.ActiveRecord;
55 using Castle.ActiveRecord.Framework.Config;
56 using Pithos.Interfaces;
57 using Pithos.Network;
58 using log4net;
59
60 namespace Pithos.Core.Agents
61 {
62     [Export(typeof(IStatusChecker)),Export(typeof(IStatusKeeper))]
63     public class StatusAgent:IStatusChecker,IStatusKeeper
64     {
65         private static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
66
67         [System.ComponentModel.Composition.Import]
68         public IPithosSettings Settings { get; set; }
69
70         private Agent<Action> _persistenceAgent;
71
72
73
74         public StatusAgent()
75         {            
76             var appDataPath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
77             
78
79
80             _pithosDataPath = Path.Combine(appDataPath , "GRNET");
81             if (!Directory.Exists(_pithosDataPath))
82                 Directory.CreateDirectory(_pithosDataPath);
83
84             var dbPath = Path.Combine(_pithosDataPath, "pithos.db");
85
86             MigrateOldDb(dbPath, appDataPath);
87
88             var source = GetConfiguration(_pithosDataPath);
89             ActiveRecordStarter.Initialize(source,typeof(FileState),typeof(FileTag));
90             ActiveRecordStarter.UpdateSchema();
91
92
93             if (!File.Exists(dbPath))
94                 ActiveRecordStarter.CreateSchema();
95
96             CreateTrigger();
97             
98         }
99
100
101         private static void MigrateOldDb(string dbPath, string appDataPath)
102         {
103             Contract.Requires(!String.IsNullOrWhiteSpace(dbPath));
104             Contract.Requires(!String.IsNullOrWhiteSpace(appDataPath));
105
106             var oldDbPath = Path.Combine(appDataPath, "Pithos", "pithos.db");
107             var oldDbInfo = new FileInfo(oldDbPath);
108             if (oldDbInfo.Exists && !File.Exists(dbPath))
109             {
110                 var oldDirectory = oldDbInfo.Directory;
111                 oldDbInfo.MoveTo(dbPath);                
112                 oldDirectory.Delete(true);
113             }
114         }
115
116         private void CreateTrigger()
117         {
118             using (var connection = GetConnection())
119             using (var triggerCommand = connection.CreateCommand())
120             {
121                 var cmdText = new StringBuilder()
122                     .AppendLine("CREATE TRIGGER IF NOT EXISTS update_last_modified UPDATE ON FileState FOR EACH ROW")
123                     .AppendLine("BEGIN")
124                     .AppendLine("UPDATE FileState SET Modified=datetime('now')  WHERE Id=old.Id;")
125                     .AppendLine("END;")
126                     .AppendLine("CREATE TRIGGER IF NOT EXISTS insert_last_modified INSERT ON FileState FOR EACH ROW")
127                     .AppendLine("BEGIN")
128                     .AppendLine("UPDATE FileState SET Modified=datetime('now')  WHERE Id=new.Id;")
129                     .AppendLine("END;")
130                     .ToString();
131                 triggerCommand.CommandText = cmdText;                
132                 triggerCommand.ExecuteNonQuery();
133             }
134         }
135
136
137         private static InPlaceConfigurationSource GetConfiguration(string pithosDbPath)
138         {
139             if (String.IsNullOrWhiteSpace(pithosDbPath))
140                 throw new ArgumentNullException("pithosDbPath");
141             if (!Path.IsPathRooted(pithosDbPath))
142                 throw new ArgumentException("path must be a rooted path", "pithosDbPath");
143             Contract.EndContractBlock();
144
145             var properties = new Dictionary<string, string>
146                                  {
147                                      {"connection.driver_class", "NHibernate.Driver.SQLite20Driver"},
148                                      {"dialect", "NHibernate.Dialect.SQLiteDialect"},
149                                      {"connection.provider", "NHibernate.Connection.DriverConnectionProvider"},
150                                      {
151                                          "proxyfactory.factory_class",
152                                          "NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle"
153                                          },
154                                  };
155
156             var connectionString = String.Format(@"Data Source={0}\pithos.db;Version=3;Enlist=N", pithosDbPath);
157             properties.Add("connection.connection_string", connectionString);
158
159             var source = new InPlaceConfigurationSource();                        
160             source.Add(typeof (ActiveRecordBase), properties);
161             source.SetDebugFlag(false);            
162             return source;
163         }
164
165         public void StartProcessing(CancellationToken token)
166         {
167             _persistenceAgent = Agent<Action>.Start(queue =>
168             {
169                 Action loop = null;
170                 loop = () =>
171                 {
172                     var job = queue.Receive();
173                     job.ContinueWith(t =>
174                     {
175                         var action = job.Result;
176                         try
177                         {
178                             action();
179                         }
180                         catch (SQLiteException ex)
181                         {
182                             Log.ErrorFormat("[ERROR] SQL \n{0}", ex);
183                         }
184                         catch (Exception ex)
185                         {
186                             Log.ErrorFormat("[ERROR] STATE \n{0}", ex);
187                         }
188 // ReSharper disable AccessToModifiedClosure
189                         queue.DoAsync(loop);
190 // ReSharper restore AccessToModifiedClosure
191                     });
192                 };
193                 loop();
194             });
195             
196         }
197
198        
199
200         public void Stop()
201         {
202             _persistenceAgent.Stop();            
203         }
204        
205
206         public void ProcessExistingFiles(IEnumerable<FileInfo> existingFiles)
207         {
208             if(existingFiles  ==null)
209                 throw new ArgumentNullException("existingFiles");
210             Contract.EndContractBlock();
211             
212             //Find new or matching files with a left join to the stored states
213             var fileStates = FileState.Queryable;
214             var currentFiles=from file in existingFiles
215                       join state in fileStates on file.FullName.ToLower() equals state.FilePath.ToLower() into gs
216                       from substate in gs.DefaultIfEmpty()
217                                select new {File = file, State = substate};
218
219             //To get the deleted files we must get the states that have no corresponding
220             //files. 
221             //We can't use the File.Exists method inside a query, so we get all file paths from the states
222             var statePaths = (from state in fileStates
223                              select new {state.Id, state.FilePath}).ToList();
224             //and check each one
225             var missingStates= (from path in statePaths
226                                 where !File.Exists(path.FilePath) && !Directory.Exists(path.FilePath)
227                                select path.Id).ToList();
228             //Finally, retrieve the states that correspond to the deleted files            
229             var deletedFiles = from state in fileStates 
230                         where missingStates.Contains(state.Id)
231                         select new { File = default(FileInfo), State = state };
232
233             var pairs = currentFiles.Union(deletedFiles);
234
235             foreach(var pair in pairs)
236             {
237                 var fileState = pair.State;
238                 var file = pair.File;
239                 if (fileState == null)
240                 {
241                     //This is a new file
242                     var fullPath = pair.File.FullName;
243                     var createState = FileState.CreateForAsync(fullPath, BlockSize, BlockHash);
244                     createState.ContinueWith(state => _persistenceAgent.Post(state.Result.Create));
245                 }                
246                 else if (file == null)
247                 {
248                     //This file was deleted while we were down. We should mark it as deleted
249                     //We have to go through UpdateStatus here because the state object we are using
250                     //was created by a different ORM session.
251                     _persistenceAgent.Post(()=> UpdateStatusDirect(fileState.Id, FileStatus.Deleted));                    
252                 }
253                 else
254                 {
255                     //This file has a matching state. Need to check for possible changes
256                     var hashString = file.CalculateHash(BlockSize,BlockHash);
257                     //If the hashes don't match the file was changed
258                     if (fileState.Checksum != hashString)
259                     {
260                         _persistenceAgent.Post(() => UpdateStatusDirect(fileState.Id, FileStatus.Modified));
261                     }                    
262                 }
263             };            
264          
265         }
266
267         private int UpdateStatusDirect(Guid id, FileStatus status)
268         {
269             using (log4net.ThreadContext.Stacks["StatusAgent"].Push("UpdateStatusDirect"))
270             {
271
272                 try
273                 {
274                     
275                     using (var connection = GetConnection())
276                     using (
277                         var command = new SQLiteCommand("update FileState set FileStatus= :fileStatus where Id = :id  ",
278                                                         connection))
279                     {                                                
280                         command.Parameters.AddWithValue("fileStatus", status);
281
282                         command.Parameters.AddWithValue("id", id);
283                         
284                         var affected = command.ExecuteNonQuery();
285                         
286                         return affected;
287                     }
288
289                 }
290                 catch (Exception exc)
291                 {
292                     Log.Error(exc.ToString());
293                     throw;
294                 }
295             }
296         }
297         
298         private int UpdateStatusDirect(string path, FileStatus status)
299         {
300             using (log4net.ThreadContext.Stacks["StatusAgent"].Push("UpdateStatusDirect"))
301             {
302
303                 try
304                 {
305
306                     
307                     using (var connection = GetConnection())
308                     using (
309                         var command =
310                             new SQLiteCommand("update FileState set FileStatus= :fileStatus where FilePath = :path COLLATE NOCASE",
311                                               connection))
312                     {
313
314
315                         command.Parameters.AddWithValue("fileStatus", status);
316
317                         command.Parameters.AddWithValue("path", path);
318                         
319                         var affected = command.ExecuteNonQuery();
320                         return affected;
321                     }
322                 }
323                 catch (Exception exc)
324                 {
325                     Log.Error(exc.ToString());
326                     throw;
327                 }
328             }
329         }
330
331         private int UpdateStatusDirect(string absolutePath, FileStatus fileStatus, FileOverlayStatus overlayStatus)
332         {
333             using (log4net.ThreadContext.Stacks["StatusAgent"].Push("UpdateStatusDirect"))
334             {
335
336                 try
337                 {
338
339                     
340                     using (var connection = GetConnection())
341                     using (
342                         var command =
343                             new SQLiteCommand(
344                                 "update FileState set OverlayStatus= :overlayStatus, FileStatus= :fileStatus where FilePath = :path COLLATE NOCASE ",
345                                 connection))
346                     {
347
348                         command.Parameters.AddWithValue("path", absolutePath);
349                         command.Parameters.AddWithValue("fileStatus", fileStatus);
350                         command.Parameters.AddWithValue("overlayStatus", overlayStatus);
351                         
352                         var affected = command.ExecuteNonQuery();
353                         return affected;
354                     }
355                 }
356                 catch (Exception exc)
357                 {
358                     Log.Error(exc.ToString());
359                     throw;
360                 }
361             }
362         }
363         
364
365
366         public string BlockHash { get; set; }
367
368         public int BlockSize { get; set; }
369         public void ChangeRoots(string oldPath, string newPath)
370         {
371             if (String.IsNullOrWhiteSpace(oldPath))
372                 throw new ArgumentNullException("oldPath");
373             if (!Path.IsPathRooted(oldPath))
374                 throw new ArgumentException("oldPath must be an absolute path", "oldPath");
375             if (string.IsNullOrWhiteSpace(newPath))
376                 throw new ArgumentNullException("newPath");
377             if (!Path.IsPathRooted(newPath))
378                 throw new ArgumentException("newPath must be an absolute path", "newPath");
379             Contract.EndContractBlock();
380
381             FileState.ChangeRootPath(oldPath,newPath);
382
383         }
384
385         private PithosStatus _pithosStatus=PithosStatus.InSynch;       
386
387         public void SetPithosStatus(PithosStatus status)
388         {
389             _pithosStatus = status;
390         }
391
392         public PithosStatus GetPithosStatus()
393         {
394             return _pithosStatus;
395         }
396
397
398         private readonly string _pithosDataPath;
399
400
401         public FileState GetStateByFilePath(string path)
402         {
403             if (String.IsNullOrWhiteSpace(path))
404                 throw new ArgumentNullException("path");
405             if (!Path.IsPathRooted(path))
406                 throw new ArgumentException("The path must be rooted", "path");
407             Contract.EndContractBlock();
408
409             try
410             {
411                 
412                 using (var connection = GetConnection())
413                 using (var command = new SQLiteCommand("select Id, FilePath, OverlayStatus,FileStatus ,Checksum   ,Version    ,VersionTimeStamp,IsShared   ,SharedBy   ,ShareWrite  from FileState where FilePath=:path COLLATE NOCASE", connection))
414                 {
415                     
416                     command.Parameters.AddWithValue("path", path);
417                     
418                     using (var reader = command.ExecuteReader())
419                     {
420                         if (reader.Read())
421                         {
422                             //var values = new object[reader.FieldCount];
423                             //reader.GetValues(values);
424                             var state = new FileState
425                                             {
426                                                 Id = reader.GetGuid(0),
427                                                 FilePath = reader.IsDBNull(1)?"":reader.GetString(1),
428                                                 OverlayStatus =reader.IsDBNull(2)?FileOverlayStatus.Unversioned: (FileOverlayStatus) reader.GetInt64(2),
429                                                 FileStatus = reader.IsDBNull(3)?FileStatus.Missing:(FileStatus) reader.GetInt64(3),
430                                                 Checksum = reader.IsDBNull(4)?"":reader.GetString(4),
431                                                 Version = reader.IsDBNull(5)?default(long):reader.GetInt64(5),
432                                                 VersionTimeStamp = reader.IsDBNull(6)?default(DateTime):reader.GetDateTime(6),
433                                                 IsShared = !reader.IsDBNull(7) && reader.GetBoolean(7),
434                                                 SharedBy = reader.IsDBNull(8)?"":reader.GetString(8),
435                                                 ShareWrite = !reader.IsDBNull(9) && reader.GetBoolean(9)
436                                             };
437 /*
438                             var state = new FileState
439                                             {
440                                                 Id = (Guid) values[0],
441                                                 FilePath = (string) values[1],
442                                                 OverlayStatus = (FileOverlayStatus) (long)values[2],
443                                                 FileStatus = (FileStatus) (long)values[3],
444                                                 Checksum = (string) values[4],
445                                                 Version = (long?) values[5],
446                                                 VersionTimeStamp = (DateTime?) values[6],
447                                                 IsShared = (long)values[7] == 1,
448                                                 SharedBy = (string) values[8],
449                                                 ShareWrite = (long)values[9] == 1
450                                             };
451 */
452                             return state;
453                         }
454                         else
455                         {
456                             return null;
457                         }
458
459                     }                    
460                 }
461             }
462             catch (Exception exc)
463             {
464                 Log.ErrorFormat(exc.ToString());
465                 throw;
466             }            
467         }
468
469         public FileOverlayStatus GetFileOverlayStatus(string path)
470         {
471             if (String.IsNullOrWhiteSpace(path))
472                 throw new ArgumentNullException("path");
473             if (!Path.IsPathRooted(path))
474                 throw new ArgumentException("The path must be rooted", "path");
475             Contract.EndContractBlock();
476
477             try
478             {
479                 
480                 using (var connection = GetConnection())
481                 using (var command = new SQLiteCommand("select OverlayStatus from FileState where FilePath=:path  COLLATE NOCASE", connection))
482                 {
483                     
484                     command.Parameters.AddWithValue("path", path);
485                     
486                     var s = command.ExecuteScalar();
487                     return (FileOverlayStatus) Convert.ToInt32(s);
488                 }
489             }
490             catch (Exception exc)
491             {
492                 Log.ErrorFormat(exc.ToString());
493                 return FileOverlayStatus.Unversioned;
494             }
495         }
496
497         private string GetConnectionString()
498         {
499             var connectionString = String.Format(@"Data Source={0}\pithos.db;Version=3;Enlist=N;Pooling=True", _pithosDataPath);
500             return connectionString;
501         }
502
503         private SQLiteConnection GetConnection()
504         {
505             var connectionString = GetConnectionString();
506             var connection = new SQLiteConnection(connectionString);
507             connection.Open();
508             using(var cmd =connection.CreateCommand())
509             {
510                 cmd.CommandText = "PRAGMA journal_mode=WAL";
511                 cmd.ExecuteNonQuery();
512             }
513             return connection;
514         }
515
516         public void SetFileOverlayStatus(string path, FileOverlayStatus overlayStatus)
517         {
518             if (String.IsNullOrWhiteSpace(path))
519                 throw new ArgumentNullException("path");
520             if (!Path.IsPathRooted(path))
521                 throw new ArgumentException("The path must be rooted","path");
522             Contract.EndContractBlock();
523
524             _persistenceAgent.Post(() => FileState.StoreOverlayStatus(path,overlayStatus));
525         }
526
527        /* public void RenameFileOverlayStatus(string oldPath, string newPath)
528         {
529             if (String.IsNullOrWhiteSpace(oldPath))
530                 throw new ArgumentNullException("oldPath");
531             if (!Path.IsPathRooted(oldPath))
532                 throw new ArgumentException("The oldPath must be rooted", "oldPath");
533             if (String.IsNullOrWhiteSpace(newPath))
534                 throw new ArgumentNullException("newPath");
535             if (!Path.IsPathRooted(newPath))
536                 throw new ArgumentException("The newPath must be rooted", "newPath");
537             Contract.EndContractBlock();
538
539             _persistenceAgent.Post(() =>FileState.RenameState(oldPath, newPath));
540         }*/
541
542         public void SetFileState(string path, FileStatus fileStatus, FileOverlayStatus overlayStatus)
543         {
544             if (String.IsNullOrWhiteSpace(path))
545                 throw new ArgumentNullException("path");
546             if (!Path.IsPathRooted(path))
547                 throw new ArgumentException("The path must be rooted", "path");
548             Contract.EndContractBlock();
549
550             Debug.Assert(!path.Contains(FolderConstants.CacheFolder));
551             Debug.Assert(!path.EndsWith(".ignore"));
552
553             _persistenceAgent.Post(() => UpdateStatusDirect(path, fileStatus, overlayStatus));
554         }
555
556 /*
557         public void StoreInfo(string path,ObjectInfo objectInfo)
558         {
559             if (String.IsNullOrWhiteSpace(path))
560                 throw new ArgumentNullException("path");
561             if (!Path.IsPathRooted(path))
562                 throw new ArgumentException("The path must be rooted", "path");            
563             if (objectInfo == null)
564                 throw new ArgumentNullException("objectInfo", "objectInfo can't be empty");
565             Contract.EndContractBlock();
566
567             _persistenceAgent.Post(() =>
568             {
569                 var filePath = path.ToLower();
570                 //Load the existing files state and set its properties in one session            
571                 using (new SessionScope())
572                 {
573                     //Forgetting to use a sessionscope results in two sessions being created, one by 
574                     //FirstOrDefault and one by Save()
575                     var state =FileState.FindByFilePath(filePath);
576                     
577                     //Create a new empty state object if this is a new file
578                     state = state ?? new FileState();
579
580                     state.FilePath = filePath;
581                     state.Checksum = objectInfo.Hash;
582                     state.Version = objectInfo.Version;
583                     state.VersionTimeStamp = objectInfo.VersionTimestamp;
584
585                     state.FileStatus = FileStatus.Unchanged;
586                     state.OverlayStatus = FileOverlayStatus.Normal;
587                     
588                   
589                     //Do the save
590                     state.Save();
591                 }
592             });
593
594         }
595 */
596         
597         public void StoreInfo(string path, ObjectInfo objectInfo)
598         {
599             if (String.IsNullOrWhiteSpace(path))
600                 throw new ArgumentNullException("path");
601             if (!Path.IsPathRooted(path))
602                 throw new ArgumentException("The path must be rooted", "path");
603             if (objectInfo == null)
604                 throw new ArgumentNullException("objectInfo", "objectInfo can't be empty");
605             Contract.EndContractBlock();
606
607             _persistenceAgent.Post(() => StoreInfoDirect(path, objectInfo));
608
609         }
610
611         private void StoreInfoDirect(string path, ObjectInfo objectInfo)
612         {
613             try
614             {
615                 
616                 using (var connection = GetConnection())
617                 using (var command = new SQLiteCommand(connection))
618                 {
619                     if (StateExists(path, connection))
620                         command.CommandText =
621                             "update FileState set FileStatus= :fileStatus where FilePath = :path  COLLATE NOCASE ";
622                     else
623                     {
624                         command.CommandText =
625                             "INSERT INTO FileState (Id,FilePath,Checksum,Version,VersionTimeStamp,FileStatus,OverlayStatus) VALUES (:id,:path,:checksum,:version,:versionTimeStamp,:fileStatus,:overlayStatus)";
626                         command.Parameters.AddWithValue("id", Guid.NewGuid());
627                     }
628
629                     command.Parameters.AddWithValue("path", path);
630                     command.Parameters.AddWithValue("checksum", objectInfo.Hash);
631                     command.Parameters.AddWithValue("version", objectInfo.Version);
632                     command.Parameters.AddWithValue("versionTimeStamp",
633                                                     objectInfo.VersionTimestamp);
634                     command.Parameters.AddWithValue("fileStatus", FileStatus.Unchanged);
635                     command.Parameters.AddWithValue("overlayStatus",
636                                                     FileOverlayStatus.Normal);
637
638                     var affected = command.ExecuteNonQuery();
639                     return;
640                 }
641             }
642             catch (Exception exc)
643             {
644                 Log.Error(exc.ToString());
645                 throw;
646             }
647         }
648
649         private bool StateExists(string filePath,SQLiteConnection connection)
650         {
651             using (var command = new SQLiteCommand("Select count(*) from FileState where FilePath=:path  COLLATE NOCASE", connection))
652             {
653                 command.Parameters.AddWithValue("path", filePath);
654                 var result = command.ExecuteScalar();
655                 return ((long)result >= 1);
656             }
657
658         }
659
660         public void SetFileStatus(string path, FileStatus status)
661         {
662             if (String.IsNullOrWhiteSpace(path))
663                 throw new ArgumentNullException("path");
664             if (!Path.IsPathRooted(path))
665                 throw new ArgumentException("The path must be rooted", "path");
666             Contract.EndContractBlock();
667             
668             _persistenceAgent.Post(() => UpdateStatusDirect(path, status));
669         }
670
671         public FileStatus GetFileStatus(string path)
672         {
673             if (String.IsNullOrWhiteSpace(path))
674                 throw new ArgumentNullException("path");
675             if (!Path.IsPathRooted(path))
676                 throw new ArgumentException("The path must be rooted", "path");
677             Contract.EndContractBlock();
678
679             
680             using (var connection = GetConnection())
681             {
682                 var command = new SQLiteCommand("select FileStatus from FileState where FilePath=:path  COLLATE NOCASE", connection);
683                 command.Parameters.AddWithValue("path", path);
684                 
685                 var statusValue = command.ExecuteScalar();
686                 if (statusValue==null)
687                     return FileStatus.Missing;
688                 return (FileStatus)Convert.ToInt32(statusValue);
689             }
690         }
691
692         /// <summary>
693         /// Deletes the status of the specified file
694         /// </summary>
695         /// <param name="path"></param>
696         public void ClearFileStatus(string path)
697         {
698             if (String.IsNullOrWhiteSpace(path))
699                 throw new ArgumentNullException("path");
700             if (!Path.IsPathRooted(path))
701                 throw new ArgumentException("The path must be rooted", "path");
702             Contract.EndContractBlock();
703
704             _persistenceAgent.Post(() => DeleteDirect(path));   
705         }
706
707         /// <summary>
708         /// Deletes the status of the specified folder and all its contents
709         /// </summary>
710         /// <param name="path"></param>
711         public void ClearFolderStatus(string path)
712         {
713             if (String.IsNullOrWhiteSpace(path))
714                 throw new ArgumentNullException("path");
715             if (!Path.IsPathRooted(path))
716                 throw new ArgumentException("The path must be rooted", "path");
717             Contract.EndContractBlock();
718
719             _persistenceAgent.Post(() => DeleteFolderDirect(path));   
720         }
721
722         public IEnumerable<FileState> GetChildren(FileState fileState)
723         {
724             if (fileState == null)
725                 throw new ArgumentNullException("fileState");
726             Contract.EndContractBlock();
727
728             var children = from state in FileState.Queryable
729                            where state.FilePath.StartsWith(fileState.FilePath + "\\")
730                            select state;
731             return children;
732         }
733
734         private int DeleteDirect(string filePath)
735         {
736             using (log4net.ThreadContext.Stacks["StatusAgent"].Push("DeleteDirect"))
737             {
738
739                 try
740                 {
741
742                     
743                     using (var connection = GetConnection())
744                     {
745                         var command = new SQLiteCommand("delete from FileState where FilePath = :path  COLLATE NOCASE",
746                                                         connection);
747
748                         command.Parameters.AddWithValue("path", filePath);
749                         
750                         var affected = command.ExecuteNonQuery();
751                         return affected;
752                     }
753                 }
754                 catch (Exception exc)
755                 {
756                     Log.Error(exc.ToString());
757                     throw;
758                 }
759             }
760         }
761
762         private int DeleteFolderDirect(string filePath)
763         {
764             using (log4net.ThreadContext.Stacks["StatusAgent"].Push("DeleteDirect"))
765             {
766
767                 try
768                 {
769
770                     
771                     using (var connection = GetConnection())
772                     {
773                         var command = new SQLiteCommand("delete from FileState where FilePath = :path or FilePath like :path + '/%'  COLLATE NOCASE",
774                                                         connection);
775
776                         command.Parameters.AddWithValue("path", filePath);
777                         
778                         var affected = command.ExecuteNonQuery();
779                         return affected;
780                     }
781                 }
782                 catch (Exception exc)
783                 {
784                     Log.Error(exc.ToString());
785                     throw;
786                 }
787             }
788         }
789
790         public void UpdateFileChecksum(string path, string checksum)
791         {
792             if (String.IsNullOrWhiteSpace(path))
793                 throw new ArgumentNullException("path");
794             if (!Path.IsPathRooted(path))
795                 throw new ArgumentException("The path must be rooted", "path");            
796             Contract.EndContractBlock();
797
798             _persistenceAgent.Post(() => FileState.UpdateChecksum(path, checksum));
799         }
800
801     }
802
803    
804 }