Extracted upload/download functionality from NetworkAgent to Uploader.cs and Download...
authorpkanavos <pkanavos@gmail.com>
Tue, 3 Apr 2012 20:37:42 +0000 (23:37 +0300)
committerpkanavos <pkanavos@gmail.com>
Tue, 3 Apr 2012 20:38:16 +0000 (23:38 +0300)
Taskbar menu fixes
Empty file fixes

19 files changed:
trunk/Pithos.Client.WPF/Properties/AssemblyInfo.cs
trunk/Pithos.Client.WPF/Shell/ShellView.xaml
trunk/Pithos.Client.WPF/Shell/ShellViewModel.cs
trunk/Pithos.Core.Test/NetworkAgentTest.cs
trunk/Pithos.Core/Agents/Agent.cs
trunk/Pithos.Core/Agents/BlockExtensions.cs
trunk/Pithos.Core/Agents/CloudTransferAction.cs
trunk/Pithos.Core/Agents/CollectionExtensions.cs
trunk/Pithos.Core/Agents/Downloader.cs [new file with mode: 0644]
trunk/Pithos.Core/Agents/FileSystemWatcherAdapter.cs
trunk/Pithos.Core/Agents/NetworkAgent.cs
trunk/Pithos.Core/Agents/StatusAgent.cs
trunk/Pithos.Core/Agents/Uploader.cs [new file with mode: 0644]
trunk/Pithos.Core/FileState.cs
trunk/Pithos.Core/Pithos.Core.csproj
trunk/Pithos.Installer/rnotes.0.7.20403.html [new file with mode: 0644]
trunk/Pithos.Installer/versioninfo.xml
trunk/Pithos.Network/CloudFilesClient.cs
trunk/Pithos.Network/TreeHash.cs

index 5b1b657..663d11a 100644 (file)
@@ -56,7 +56,7 @@ using System.Windows;
 [assembly: AssemblyCopyright("Copyright © GRNet 2011-2012")]
 [assembly: AssemblyTrademark("")]
 [assembly: AssemblyCulture("")]
-[assembly: AssemblyInformationalVersion("2012-03-28")]
+[assembly: AssemblyInformationalVersion("2012-04-03")]
 
 // Setting ComVisible to false makes the types in this assembly not visible 
 // to COM components.  If you need to access a type in this assembly from 
@@ -93,5 +93,5 @@ using System.Windows;
 // You can specify all the values or you can default the Build and Revision Numbers 
 // by using the '*' as shown below:
 // [assembly: AssemblyVersion("1.0.*")]
-[assembly: AssemblyVersion("0.7.20401.0")]
-[assembly: AssemblyFileVersionAttribute("0.7.20401.0")]
+[assembly: AssemblyVersion("0.7.20403.0")]
+[assembly: AssemblyFileVersionAttribute("0.7.20403.0")]
index dcb8d66..8395cbe 100644 (file)
             <tb:TaskbarIcon.ContextMenu>
                 <ContextMenu x:Name="TaskbarMenu" >
                     <MenuItem Header="{Binding OpenFolderCaption}" IsEnabled="{Binding HasAccounts}" x:Name="OpenPithosFolder" ItemsSource="{Binding Accounts}" >                        
-                        <MenuItem.ItemTemplate>
+                        <MenuItem.ItemTemplate>                            
                             <DataTemplate>
-                                <StackPanel>
-                                <TextBlock x:Name="AccountLink"  Text="{Binding Path=UserName}" cal:Message.Attach="[Event MouseLeftButtonUp]=[Action OpenPithosFolder($dataContext)]" 
-                                           cal:Action.TargetWithoutContext="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=MenuItem, AncestorLevel=2}, Path=DataContext}" />
+                                <StackPanel 
+                                        cal:Message.Attach="[Event MouseLeftButtonUp]=[Action OpenPithosFolder($dataContext)]" 
+                                        cal:Action.TargetWithoutContext="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=MenuItem, AncestorLevel=2}, Path=DataContext}" >
+                                    <TextBlock x:Name="AccountLink"  Text="{Binding Path=UserName}" />
                                     <TextBlock Text="{Binding Path=StorageUri}" FontStyle="Italic" FontSize="10" />
                                 </StackPanel>
                             </DataTemplate>
                     <MenuItem Header="Go to Account Site" x:Name="GoToSiteMenu" ItemsSource="{Binding Accounts}" Visibility="{Binding Path=HasAccounts, Converter={StaticResource BooleanToVisible}}" >
                         <MenuItem.ItemTemplate>
                             <DataTemplate>
-                                <StackPanel>
-                                    <TextBlock x:Name="AccountLink" Text="{Binding Path=UserName}" cal:Message.Attach="[Event MouseLeftButtonUp]=[Action GoToSite($dataContext)]" 
-                                               cal:Action.TargetWithoutContext="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=MenuItem, AncestorLevel=2}, Path=DataContext}" />
+                                <StackPanel 
+                                        cal:Message.Attach="[Event MouseLeftButtonUp]=[Action GoToSite($dataContext)]" 
+                                        cal:Action.TargetWithoutContext="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=MenuItem, AncestorLevel=2}, Path=DataContext}" >
+                                    <TextBlock x:Name="AccountLink" Text="{Binding Path=UserName}" />
                                     <TextBlock Text="{Binding Path=StorageUri}" FontStyle="Italic" FontSize="10" />
                                 </StackPanel>
                             </DataTemplate>
index 69fae86..c99d650 100644 (file)
@@ -375,7 +375,6 @@ namespace Pithos.Client.WPF {
 
         public string VersionMessage { get; set; }
 
-           private string _tooltipMessage;
            public string TooltipMessage
            {
                get
@@ -647,17 +646,30 @@ namespace Pithos.Client.WPF {
                        StatusIcon = String.Format(@"../Images/{0}.ico", iconKey);
                }
 
-               public void ExitPithos()
-               {
-                       foreach (var pair in Monitors)
-                       {
-                               var monitor = pair.Value;
-                               monitor.Stop();
-                       }
+        public void ExitPithos()
+        {
+            try
+            {
 
-                       ((Window)GetView()).Close();
-               }
-               #endregion
+                foreach (var monitor in Monitors.Select(pair => pair.Value))
+                {
+                    monitor.Stop();
+                }
+
+                var view = GetView() as Window;
+                if (view != null)
+                    view.Close();
+                else
+                    Application.Current.Shutdown();
+            }
+            catch (Exception exc)
+            {
+                Log.Info("Exception while exiting", exc);
+                Application.Current.Shutdown();
+            }
+        }
+
+           #endregion
 
 
                private readonly Dictionary<PithosStatus, StatusInfo> _iconNames = new List<StatusInfo>
index fb8838c..d84fdcb 100644 (file)
@@ -55,7 +55,8 @@ namespace Pithos.Core.Test
             var cloudFile = new ObjectInfo {Account = account, Container = "pithos"};
             var fileInfo = new FileInfo(filePath);
 
-            agent.UploadWithHashMap(accountInfo,cloudFile,fileInfo,fileName,treeHash);
+            var uploader = new Uploader();
+            uploader.UploadWithHashMap(accountInfo,cloudFile,fileInfo,fileName,treeHash);
             
             var newHash = await client.GetHashMap(null, FolderConstants.PithosContainer, fileName);
 
@@ -91,7 +92,8 @@ namespace Pithos.Core.Test
             var cloudFile = new ObjectInfo {Account = account, Container = FolderConstants.PithosContainer};
 
             var newHash = client.GetHashMap(null, FolderConstants.PithosContainer, fileName).Result;
-            agent.DownloadWithBlocks(accountInfo, client, cloudFile, new Uri(fileName, UriKind.Relative), filePath, newHash)
+            var downloader = new Downloader();
+            downloader.DownloadWithBlocks(accountInfo, client, cloudFile, new Uri(fileName, UriKind.Relative), filePath, newHash)
                 .Wait();
 
             Assert.IsTrue(File.Exists(filePath));
index e749f33..215380d 100644 (file)
@@ -145,7 +145,10 @@ namespace Pithos.Core
         /// <param name="action">The action to execute</param>
         public void DoAsync(Action action)
         {
-            Contract.Requires(action!=null);
+            if(action==null)
+                throw new ArgumentNullException("action");
+            Contract.EndContractBlock();
+
             Task.Factory.StartNew(action, CancellationToken);
         }
 
@@ -191,8 +194,11 @@ namespace Pithos.Core
 
         public Task LoopAsync(Task process, Action loop,Action<Exception> onError=null)
         {
-            Contract.Requires(process!=null);
-            Contract.Requires(loop!=null);
+            if(process==null)
+                throw new ArgumentNullException("process");
+            if(loop==null)
+                throw new ArgumentNullException("loop");
+            Contract.EndContractBlock();
 
             return process.ContinueWith(t =>
             {   
index 3b5eea3..95b76d9 100644 (file)
@@ -103,8 +103,11 @@ namespace Pithos.Core.Agents
        /// <returns>A hash value for the entire file. An empty string if the file does not exist.</returns>
        public static string ComputeShortHash(this FileInfo info, HashAlgorithm hasher)
        {
-           Contract.Requires(info != null);
-           Contract.Requires(hasher!= null);           
+           if(info == null)
+               throw new ArgumentNullException("info");
+           if(hasher== null)
+               throw new ArgumentNullException("hasher");
+           Contract.EndContractBlock();
 
            if (!info.Exists)
                return String.Empty;
@@ -122,7 +125,9 @@ namespace Pithos.Core.Agents
 
         public static string ComputeShortHash(this FileInfo info)
        {
-           Contract.Requires(info != null);           
+           if(info == null)
+               throw new ArgumentNullException("info");
+            Contract.EndContractBlock();
 
            using (var hasher=HashAlgorithm.Create("sha1"))
            {               
index cb180d6..7ae68f4 100644 (file)
@@ -129,9 +129,12 @@ namespace Pithos.Core.Agents
 
         protected static ObjectInfo CreateObjectInfoFor(AccountInfo accountInfo, FileSystemInfo fileInfo)
         {
-            Contract.Requires(accountInfo!=null);
-            Contract.Requires(fileInfo!=null);
+            if(accountInfo==null)
+                throw new ArgumentNullException("accountInfo");
+            if(fileInfo==null)
+                throw new ArgumentNullException("fileInfo");
             Contract.Ensures(Contract.Result<ObjectInfo>()!=null);
+            Contract.EndContractBlock();
 
             var capitalizedFileInfo = fileInfo.WithProperCapitalization();
             var fullLocalName = capitalizedFileInfo.FullName;
index 781631c..b4e92c5 100644 (file)
 using System.Collections.Concurrent;\r
 using System.Diagnostics.Contracts;\r
 using Pithos.Interfaces;\r
+using System;\r
+using System.Collections.Generic;\r
+using System.Linq;\r
 \r
 namespace Pithos.Core.Agents\r
 {\r
-    using System;\r
-    using System.Collections.Generic;\r
-    using System.Linq;\r
-    using System.Text;\r
 \r
     /// <summary>\r
     /// Extension methods for collections\r
@@ -73,6 +72,7 @@ namespace Pithos.Core.Agents
         /// <summary>\r
         /// Remove the first message in a queue that matches the predicate\r
         /// </summary>\r
+        /// <param name="queue">The queue</param>\r
         /// <param name="predicate">The condition to match</param>\r
         /// <remarks>Removes the first message that matches the predicate by dequeing all \r
         /// messages and re-enqueing all except the first matching message</remarks>\r
@@ -146,8 +146,11 @@ namespace Pithos.Core.Agents
         /// <returns></returns>\r
         public static bool IsAtOrBelow(this Uri target,Uri root)\r
         {\r
-            Contract.Requires(root != null);\r
-            Contract.Requires(target != null);\r
+            if(root == null)\r
+                throw new ArgumentNullException("root");\r
+            if(target == null)\r
+                throw new ArgumentNullException("target");\r
+            Contract.EndContractBlock();\r
 \r
             var targetSegments = target.Segments;\r
             var rootSegments = root.Segments;\r
@@ -178,8 +181,11 @@ namespace Pithos.Core.Agents
         /// <returns></returns>\r
         public static bool IsAtOrDirectlyBelow(this Uri target,Uri root)\r
         {\r
-            Contract.Requires(root!=null);\r
-            Contract.Requires(target!=null);\r
+            if (root==null)\r
+                throw new ArgumentNullException("root");\r
+            if (target==null)\r
+                throw new ArgumentNullException("target");\r
+            Contract.EndContractBlock();\r
 \r
             return\r
                 //If the target is directly below the root, it will have exactly \r
@@ -197,8 +203,11 @@ namespace Pithos.Core.Agents
         /// <returns></returns>\r
         public static bool IsAtOrBelow(this string targetPath, string rootPath)\r
         {\r
-            Contract.Requires(!String.IsNullOrWhiteSpace(targetPath));\r
-            Contract.Requires(!String.IsNullOrWhiteSpace(rootPath));\r
+            if(String.IsNullOrWhiteSpace(targetPath))\r
+                throw new ArgumentNullException("targetPath");\r
+            if(String.IsNullOrWhiteSpace(rootPath))\r
+                throw new ArgumentNullException("rootPath");\r
+            Contract.EndContractBlock();\r
 \r
             var targetSegments = targetPath.Split('\\');\r
             var rootSegments = rootPath.Split('\\');\r
@@ -214,8 +223,12 @@ namespace Pithos.Core.Agents
         /// <returns></returns>\r
         public static bool IsAtOrDirectlyBelow(this string targetPath, string rootPath)\r
         {\r
-            Contract.Requires(!String.IsNullOrWhiteSpace(targetPath));\r
-            Contract.Requires(!String.IsNullOrWhiteSpace(rootPath));\r
+            if (String.IsNullOrWhiteSpace(targetPath))\r
+                throw new ArgumentNullException("targetPath");\r
+            if (String.IsNullOrWhiteSpace(rootPath))\r
+                throw new ArgumentNullException("rootPath");\r
+            Contract.EndContractBlock();\r
+\r
 \r
             var targetSegments = targetPath.Split('\\');\r
             var rootSegments = rootPath.Split('\\');\r
@@ -233,7 +246,7 @@ namespace Pithos.Core.Agents
         /// The target is not modified if it doesn't start with the prefix string\r
         /// </summary>\r
         /// <param name="target"></param>\r
-        /// <param name="remove"></param>\r
+        /// <param name="prefix"></param>\r
         /// <returns></returns>\r
         public static string After(this string target,string prefix)\r
         {            \r
diff --git a/trunk/Pithos.Core/Agents/Downloader.cs b/trunk/Pithos.Core/Agents/Downloader.cs
new file mode 100644 (file)
index 0000000..68b33c6
--- /dev/null
@@ -0,0 +1,298 @@
+using System;
+using System.ComponentModel.Composition;
+using System.Diagnostics.Contracts;
+using System.IO;
+using System.Reflection;
+using System.Threading.Tasks;
+using Pithos.Interfaces;
+using Pithos.Network;
+using log4net;
+
+namespace Pithos.Core.Agents
+{
+    [Export(typeof(Downloader))]
+    public class Downloader
+    {
+        private static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
+
+        [Import]
+        private IStatusKeeper StatusKeeper { get; set; }
+
+        
+        public IStatusNotification StatusNotification { get; set; }
+
+        //Download a file.
+        public async Task DownloadCloudFile(AccountInfo accountInfo, ObjectInfo cloudFile, string filePath)
+        {
+            if (accountInfo == null)
+                throw new ArgumentNullException("accountInfo");
+            if (cloudFile == null)
+                throw new ArgumentNullException("cloudFile");
+            if (String.IsNullOrWhiteSpace(cloudFile.Account))
+                throw new ArgumentNullException("cloudFile");
+            if (String.IsNullOrWhiteSpace(cloudFile.Container))
+                throw new ArgumentNullException("cloudFile");
+            if (String.IsNullOrWhiteSpace(filePath))
+                throw new ArgumentNullException("filePath");
+            if (!Path.IsPathRooted(filePath))
+                throw new ArgumentException("The filePath must be rooted", "filePath");
+            Contract.EndContractBlock();
+
+            using (ThreadContext.Stacks["Operation"].Push("DownloadCloudFile"))
+            {
+
+                var localPath = FileInfoExtensions.GetProperFilePathCapitalization(filePath);
+                var relativeUrl = new Uri(cloudFile.Name, UriKind.Relative);
+
+                var url = relativeUrl.ToString();
+                if (cloudFile.Name.EndsWith(".ignore", StringComparison.InvariantCultureIgnoreCase))
+                    return;
+
+
+                //Are we already downloading or uploading the file? 
+                using (var gate = NetworkGate.Acquire(localPath, NetworkOperation.Downloading))
+                {
+                    if (gate.Failed)
+                        return;
+
+                    var client = new CloudFilesClient(accountInfo);
+                    var account = cloudFile.Account;
+                    var container = cloudFile.Container;
+
+                    if (cloudFile.IsDirectory)
+                    {
+                        if (!Directory.Exists(localPath))
+                            try
+                            {
+                                Directory.CreateDirectory(localPath);
+                                if (Log.IsDebugEnabled)
+                                    Log.DebugFormat("Created Directory [{0}]", localPath);
+                            }
+                            catch (IOException)
+                            {
+                                var localInfo = new FileInfo(localPath);
+                                if (localInfo.Exists && localInfo.Length == 0)
+                                {
+                                    Log.WarnFormat("Malformed directory object detected for [{0}]", localPath);
+                                    localInfo.Delete();
+                                    Directory.CreateDirectory(localPath);
+                                    if (Log.IsDebugEnabled)
+                                        Log.DebugFormat("Created Directory [{0}]", localPath);
+                                }
+                            }
+                    }
+                    else
+                    {
+                        var isChanged = IsObjectChanged(cloudFile, localPath);
+                        if (isChanged)
+                        {
+                            //Retrieve the hashmap from the server
+                            var serverHash = await client.GetHashMap(account, container, url);
+                            //If it's a small file
+                            if (serverHash.Hashes.Count == 1)
+                                //Download it in one go
+                                await
+                                    DownloadEntireFileAsync(accountInfo, client, cloudFile, relativeUrl, localPath);
+                            //Otherwise download it block by block
+                            else
+                                await
+                                    DownloadWithBlocks(accountInfo, client, cloudFile, relativeUrl, localPath,
+                                                       serverHash);
+
+                            if (cloudFile.AllowedTo == "read")
+                            {
+                                var attributes = File.GetAttributes(localPath);
+                                File.SetAttributes(localPath, attributes | FileAttributes.ReadOnly);
+                            }
+                        }
+                    }
+
+                    //Now we can store the object's metadata without worrying about ghost status entries
+                    StatusKeeper.StoreInfo(localPath, cloudFile);
+
+                }
+            }
+        }
+
+        //Download a file asynchronously using blocks
+        public async Task DownloadWithBlocks(AccountInfo accountInfo, CloudFilesClient client, ObjectInfo cloudFile, Uri relativeUrl, string filePath, TreeHash serverHash)
+        {
+            if (client == null)
+                throw new ArgumentNullException("client");
+            if (cloudFile == null)
+                throw new ArgumentNullException("cloudFile");
+            if (relativeUrl == null)
+                throw new ArgumentNullException("relativeUrl");
+            if (String.IsNullOrWhiteSpace(filePath))
+                throw new ArgumentNullException("filePath");
+            if (!Path.IsPathRooted(filePath))
+                throw new ArgumentException("The filePath must be rooted", "filePath");
+            if (serverHash == null)
+                throw new ArgumentNullException("serverHash");
+            if (cloudFile.IsDirectory)
+                throw new ArgumentException("cloudFile is a directory, not a file", "cloudFile");
+            Contract.EndContractBlock();
+
+            var fileAgent = GetFileAgent(accountInfo);
+            var localPath = FileInfoExtensions.GetProperFilePathCapitalization(filePath);
+
+            //Calculate the relative file path for the new file
+            var relativePath = relativeUrl.RelativeUriToFilePath();
+            var blockUpdater = new BlockUpdater(fileAgent.CachePath, localPath, relativePath, serverHash);
+
+
+            StatusNotification.SetPithosStatus(PithosStatus.LocalSyncing, String.Format("Calculating hashmap for {0} before download", Path.GetFileName(localPath)));
+            //Calculate the file's treehash
+            var treeHash = await Signature.CalculateTreeHashAsync(localPath, serverHash.BlockSize, serverHash.BlockHash, 2);
+
+            //And compare it with the server's hash
+            var upHashes = serverHash.GetHashesAsStrings();
+            var localHashes = treeHash.HashDictionary;
+            ReportDownloadProgress(Path.GetFileName(localPath), 0, upHashes.Length, cloudFile.Bytes);
+            for (int i = 0; i < upHashes.Length; i++)
+            {
+                //For every non-matching hash
+                var upHash = upHashes[i];
+                if (!localHashes.ContainsKey(upHash))
+                {
+                    StatusNotification.Notify(new CloudNotification { Data = cloudFile });
+
+                    if (blockUpdater.UseOrphan(i, upHash))
+                    {
+                        Log.InfoFormat("[BLOCK GET] ORPHAN FOUND for {0} of {1} for {2}", i, upHashes.Length, localPath);
+                        continue;
+                    }
+                    Log.InfoFormat("[BLOCK GET] START {0} of {1} for {2}", i, upHashes.Length, localPath);
+                    var start = i * serverHash.BlockSize;
+                    //To download the last block just pass a null for the end of the range
+                    long? end = null;
+                    if (i < upHashes.Length - 1)
+                        end = ((i + 1) * serverHash.BlockSize);
+
+                    //Download the missing block
+                    var block = await client.GetBlock(cloudFile.Account, cloudFile.Container, relativeUrl, start, end);
+
+                    //and store it
+                    blockUpdater.StoreBlock(i, block);
+
+
+                    Log.InfoFormat("[BLOCK GET] FINISH {0} of {1} for {2}", i, upHashes.Length, localPath);
+                }
+                ReportDownloadProgress(Path.GetFileName(localPath), i, upHashes.Length, cloudFile.Bytes);
+            }
+
+            //Want to avoid notifications if no changes were made
+            var hasChanges = blockUpdater.HasBlocks;
+            blockUpdater.Commit();
+
+            if (hasChanges)
+                //Notify listeners that a local file has changed
+                StatusNotification.NotifyChangedFile(localPath);
+
+            Log.InfoFormat("[BLOCK GET] COMPLETE {0}", localPath);
+        }
+
+        //Download a small file with a single GET operation
+        private async Task DownloadEntireFileAsync(AccountInfo accountInfo, CloudFilesClient client, ObjectInfo cloudFile, Uri relativeUrl, string filePath)
+        {
+            if (client == null)
+                throw new ArgumentNullException("client");
+            if (cloudFile == null)
+                throw new ArgumentNullException("cloudFile");
+            if (relativeUrl == null)
+                throw new ArgumentNullException("relativeUrl");
+            if (String.IsNullOrWhiteSpace(filePath))
+                throw new ArgumentNullException("filePath");
+            if (!Path.IsPathRooted(filePath))
+                throw new ArgumentException("The localPath must be rooted", "filePath");
+            if (cloudFile.IsDirectory)
+                throw new ArgumentException("cloudFile is a directory, not a file", "cloudFile");
+            Contract.EndContractBlock();
+
+            var localPath = FileInfoExtensions.GetProperFilePathCapitalization(filePath);
+            StatusNotification.SetPithosStatus(PithosStatus.LocalSyncing, String.Format("Downloading {0}", Path.GetFileName(localPath)));
+            StatusNotification.Notify(new CloudNotification { Data = cloudFile });
+
+            var fileAgent = GetFileAgent(accountInfo);
+            //Calculate the relative file path for the new file
+            var relativePath = relativeUrl.RelativeUriToFilePath();
+            //The file will be stored in a temporary location while downloading with an extension .download
+            var tempPath = Path.Combine(fileAgent.CachePath, relativePath + ".download");
+            //Make sure the target folder exists. DownloadFileTask will not create the folder
+            var tempFolder = Path.GetDirectoryName(tempPath);
+            if (!Directory.Exists(tempFolder))
+                Directory.CreateDirectory(tempFolder);
+
+            //Download the object to the temporary location
+            await client.GetObject(cloudFile.Account, cloudFile.Container, relativeUrl.ToString(), tempPath);
+
+            //Create the local folder if it doesn't exist (necessary for shared objects)
+            var localFolder = Path.GetDirectoryName(localPath);
+            if (!Directory.Exists(localFolder))
+                try
+                {
+                    Directory.CreateDirectory(localFolder);
+                }
+                catch (IOException)
+                {
+                    //A file may already exist that has the same name as the new folder.
+                    //This may be an artifact of the way Pithos handles directories
+                    var fileInfo = new FileInfo(localFolder);
+                    if (fileInfo.Exists && fileInfo.Length == 0)
+                    {
+                        Log.WarnFormat("Malformed directory object detected for [{0}]", localFolder);
+                        fileInfo.Delete();
+                        Directory.CreateDirectory(localFolder);
+                    }
+                    else
+                        throw;
+                }
+            //And move it to its actual location once downloading is finished
+            if (File.Exists(localPath))
+                File.Replace(tempPath, localPath, null, true);
+            else
+                File.Move(tempPath, localPath);
+            //Notify listeners that a local file has changed
+            StatusNotification.NotifyChangedFile(localPath);
+
+
+        }
+
+
+        private void ReportDownloadProgress(string fileName, int block, int totalBlocks, long fileSize)
+        {
+            StatusNotification.Notify(totalBlocks == 0
+                                          ? new ProgressNotification(fileName, "Downloading", 1, 1, fileSize)
+                                          : new ProgressNotification(fileName, "Downloading", block, totalBlocks, fileSize));
+        }
+
+        private bool IsObjectChanged(ObjectInfo cloudFile, string localPath)
+        {
+            //If the target is a directory, there are no changes to download
+            if (Directory.Exists(localPath))
+                return false;
+            //If the file doesn't exist, we have a chagne
+            if (!File.Exists(localPath))
+                return true;
+            //If there is no stored state, we have a change
+            var localState = StatusKeeper.GetStateByFilePath(localPath);
+            if (localState == null)
+                return true;
+
+            var info = new FileInfo(localPath);
+            var shortHash = info.ComputeShortHash();
+            //If the file is different from the stored state, we have a change
+            if (localState.ShortHash != shortHash)
+                return true;
+            //If the top hashes differ, we have a change
+            return (localState.Checksum != cloudFile.Hash);
+        }
+
+        private static FileAgent GetFileAgent(AccountInfo accountInfo)
+        {
+            return AgentLocator<FileAgent>.Get(accountInfo.AccountPath);
+        }
+
+
+    }
+}
index 5c25207..3373096 100644 (file)
@@ -258,8 +258,11 @@ namespace Pithos.Core.Agents
 \r
         private void RaiseCreatedForChildren(object sender, FileSystemEventArgs e)\r
         {\r
-            Contract.Requires(sender!=null);\r
-            Contract.Requires(e!=null);\r
+            if(sender==null)\r
+                throw new ArgumentNullException("sender");\r
+            if (e==null)\r
+                throw new ArgumentNullException("e");\r
+            Contract.EndContractBlock();\r
 \r
             if (e.ChangeType != WatcherChangeTypes.Created)\r
                 return;\r
@@ -275,7 +278,7 @@ namespace Pithos.Core.Agents
                     Created(sender,new FileSystemEventArgs(WatcherChangeTypes.Created,path,info.Name));\r
                 }\r
             }\r
-            catch (IOException exc)\r
+            catch (IOException)\r
             {\r
                 TaskEx.Delay(1000)\r
                     .ContinueWith(_=>RaiseCreatedForChildren(sender,e));\r
index 8418b05..4551602 100644 (file)
@@ -65,7 +65,7 @@ namespace Pithos.Core.Agents
         private Agent<CloudAction> _agent;
 
         [System.ComponentModel.Composition.Import]
-        private DeleteAgent _deleteAgent { get; set; }
+        private DeleteAgent DeleteAgent { get; set; }
 
         [System.ComponentModel.Composition.Import]
         public IStatusKeeper StatusKeeper { get; set; }
@@ -77,7 +77,9 @@ namespace Pithos.Core.Agents
             set
             {
                 _statusNotification = value;
-                _deleteAgent.StatusNotification = value;
+                DeleteAgent.StatusNotification = value;
+                Uploader.StatusNotification = value;
+                Downloader.StatusNotification = value;
             }
         }
 
@@ -85,6 +87,12 @@ namespace Pithos.Core.Agents
         [System.ComponentModel.Composition.Import]
         public IPithosSettings Settings { get; set; }
 
+        [System.ComponentModel.Composition.Import]
+        public Uploader Uploader { get; set; }
+
+        [System.ComponentModel.Composition.Import]
+        public Downloader Downloader { get; set; }
+
         //The Proceed signals the poll agent that it can proceed with polling. 
         //Essentially it stops the poll agent to give priority to the network agent
         //Initially the event is signalled because we don't need to pause
@@ -109,7 +117,7 @@ namespace Pithos.Core.Agents
                 Action loop = null;
                 loop = () =>
                 {
-                    _deleteAgent.ProceedEvent.Wait();
+                    DeleteAgent.ProceedEvent.Wait();
                     var message = inbox.Receive();
                     var process=message.Then(Process,inbox.CancellationToken);
                     inbox.LoopAsync(process, loop);
@@ -130,7 +138,7 @@ namespace Pithos.Core.Agents
 
 
 
-            using (log4net.ThreadContext.Stacks["Operation"].Push(action.ToString()))
+            using (ThreadContext.Stacks["Operation"].Push(action.ToString()))
             {                
 
                 var cloudFile = action.CloudFile;
@@ -140,15 +148,15 @@ namespace Pithos.Core.Agents
                 {
                     StatusNotification.SetPithosStatus(PithosStatus.LocalSyncing,"Processing");
                     _proceedEvent.Reset();
-                    //UpdateStatus(PithosStatus.Syncing);
+                    
                     var accountInfo = action.AccountInfo;
 
                     if (action.Action == CloudActionType.DeleteCloud)
                     {                        
                         //Redirect deletes to the delete agent 
-                        _deleteAgent.Post((CloudDeleteAction)action);
+                        DeleteAgent.Post((CloudDeleteAction)action);
                     }
-                    if (_deleteAgent.IsDeletedFile(action))
+                    if (DeleteAgent.IsDeletedFile(action))
                     {
                         //Clear the status of already deleted files to avoid reprocessing
                         if (action.LocalFile != null)
@@ -160,10 +168,10 @@ namespace Pithos.Core.Agents
                         {
                             case CloudActionType.UploadUnconditional:
                                 //Abort if the file was deleted before we reached this point
-                                await UploadCloudFile(action);
+                                await Uploader.UploadCloudFile(action);
                                 break;
                             case CloudActionType.DownloadUnconditional:
-                                await DownloadCloudFile(accountInfo, cloudFile, downloadPath);
+                                await Downloader.DownloadCloudFile(accountInfo, cloudFile, downloadPath);
                                 break;
                             case CloudActionType.RenameCloud:
                                 var moveAction = (CloudMoveAction)action;
@@ -175,7 +183,7 @@ namespace Pithos.Core.Agents
                             case CloudActionType.MustSynch:
                                 if (!File.Exists(downloadPath) && !Directory.Exists(downloadPath))
                                 {
-                                    await DownloadCloudFile(accountInfo, cloudFile, downloadPath);
+                                    await Downloader.DownloadCloudFile(accountInfo, cloudFile, downloadPath);
                                 }
                                 else
                                 {
@@ -187,10 +195,21 @@ namespace Pithos.Core.Agents
                     Log.InfoFormat("End Processing {0}:{1}->{2}", action.Action, action.LocalFile,
                                            action.CloudFile.Name);
                 }
+/*
                 catch (WebException exc)
-                {
+                {                    
                     Log.ErrorFormat("[WEB ERROR] {0} : {1} -> {2} due to exception\r\n{3}", action.Action, action.LocalFile, action.CloudFile, exc);
+                    
+                    
+                    //Actions that resulted in server errors should be retried                    
+                    var response = exc.Response as HttpWebResponse;
+                    if (response != null && response.StatusCode >= HttpStatusCode.InternalServerError)
+                    {
+                        _agent.Post(action);
+                        Log.WarnFormat("[REQUEUE] {0} : {1} -> {2}", action.Action, action.LocalFile, action.CloudFile);
+                    }
                 }
+*/
                 catch (OperationCanceledException)
                 {
                     throw;
@@ -274,8 +293,8 @@ namespace Pithos.Core.Agents
                 FileInfoExtensions.GetProperFilePathCapitalization(previousFile.FullName):
                 FileInfoExtensions.GetProperDirectoryCapitalization(previousFile.FullName);                
             
-            using (var gateOld = NetworkGate.Acquire(previousFullPath, NetworkOperation.Renaming))
-            using (var gateNew = NetworkGate.Acquire(newPath,NetworkOperation.Renaming))
+            using (NetworkGate.Acquire(previousFullPath, NetworkOperation.Renaming))
+            using (NetworkGate.Acquire(newPath,NetworkOperation.Renaming)) 
             using (new SessionScope(FlushAction.Auto))
             {
                 if (isFile)
@@ -307,7 +326,7 @@ namespace Pithos.Core.Agents
             using (ThreadContext.Stacks["Operation"].Push("SyncFiles"))
             {
 
-                var localFile = action.LocalFile;
+                //var localFile = action.LocalFile;
                 var cloudFile = action.CloudFile;
                 var downloadPath = action.LocalFile.GetProperCapitalization();
 
@@ -322,7 +341,7 @@ namespace Pithos.Core.Agents
                 //
 
                 //If the hashes match, we are done
-                if (cloudHash == localHash)
+                if (cloudFile != ObjectInfo.Empty && cloudHash == localHash)
                 {
                     Log.InfoFormat("Skipping {0}, hashes match", downloadPath);
                     return;
@@ -333,7 +352,7 @@ namespace Pithos.Core.Agents
                 // If the previous tophash matches the local tophash, the file was only changed on the server. 
                 if (localHash == previousCloudHash)
                 {
-                    await DownloadCloudFile(accountInfo, cloudFile, downloadPath);
+                    await Downloader.DownloadCloudFile(accountInfo, cloudFile, downloadPath);
                 }
                 else
                 {
@@ -365,7 +384,7 @@ namespace Pithos.Core.Agents
                 throw new ArgumentException("The CloudAction.AccountInfo is empty","cloudAction");
             Contract.EndContractBlock();
 
-            _deleteAgent.ProceedEvent.Wait();
+            DeleteAgent.ProceedEvent.Wait();
 /*
 
             //If the action targets a local file, add a treehash calculation
@@ -394,7 +413,7 @@ namespace Pithos.Core.Agents
 */
             
             if (cloudAction is CloudDeleteAction)
-                _deleteAgent.Post((CloudDeleteAction)cloudAction);
+                DeleteAgent.Post((CloudDeleteAction)cloudAction);
             else
                 _agent.Post(cloudAction);
         }
@@ -407,18 +426,13 @@ namespace Pithos.Core.Agents
 
         public Task GetDeleteAwaiter()
         {
-            return _deleteAgent.ProceedEvent.WaitAsync();
+            return DeleteAgent.ProceedEvent.WaitAsync();
         }
         public CancellationToken CancellationToken
         {
             get { return _agent.CancellationToken; }
         }
 
-        private static FileAgent GetFileAgent(AccountInfo accountInfo)
-        {
-            return AgentLocator<FileAgent>.Get(accountInfo.AccountPath);
-        }
-
 
 
         private void RenameCloudFile(AccountInfo accountInfo,CloudMoveAction action)
@@ -471,531 +485,8 @@ namespace Pithos.Core.Agents
             }
         }
 
-        //Download a file.
-        private async Task DownloadCloudFile(AccountInfo accountInfo, ObjectInfo cloudFile , string filePath)
-        {
-            if (accountInfo == null)
-                throw new ArgumentNullException("accountInfo");
-            if (cloudFile == null)
-                throw new ArgumentNullException("cloudFile");
-            if (String.IsNullOrWhiteSpace(cloudFile.Account))
-                throw new ArgumentNullException("cloudFile");
-            if (String.IsNullOrWhiteSpace(cloudFile.Container))
-                throw new ArgumentNullException("cloudFile");
-            if (String.IsNullOrWhiteSpace(filePath))
-                throw new ArgumentNullException("filePath");
-            if (!Path.IsPathRooted(filePath))
-                throw new ArgumentException("The filePath must be rooted", "filePath");
-            Contract.EndContractBlock();
-
-            using (ThreadContext.Stacks["Operation"].Push("DownloadCloudFile"))
-            {
-
-                var localPath = Interfaces.FileInfoExtensions.GetProperFilePathCapitalization(filePath);
-                var relativeUrl = new Uri(cloudFile.Name, UriKind.Relative);
-
-                var url = relativeUrl.ToString();
-                if (cloudFile.Name.EndsWith(".ignore", StringComparison.InvariantCultureIgnoreCase))
-                    return;
-
-
-                //Are we already downloading or uploading the file? 
-                using (var gate = NetworkGate.Acquire(localPath, NetworkOperation.Downloading))
-                {
-                    if (gate.Failed)
-                        return;
-
-                    var client = new CloudFilesClient(accountInfo);
-                    var account = cloudFile.Account;
-                    var container = cloudFile.Container;
-
-                    if (cloudFile.IsDirectory)
-                    {
-                        if (!Directory.Exists(localPath))
-                            try
-                            {
-                                Directory.CreateDirectory(localPath);
-                                if (Log.IsDebugEnabled)
-                                    Log.DebugFormat("Created Directory [{0}]",localPath);
-                            }
-                            catch (IOException)
-                            {
-                                var localInfo = new FileInfo(localPath);
-                                if (localInfo.Exists && localInfo.Length == 0)
-                                {
-                                    Log.WarnFormat("Malformed directory object detected for [{0}]",localPath);
-                                    localInfo.Delete();
-                                    Directory.CreateDirectory(localPath);
-                                    if (Log.IsDebugEnabled)
-                                        Log.DebugFormat("Created Directory [{0}]", localPath);
-                                }
-                            }
-                    }
-                    else
-                    {
-                        var isChanged = IsObjectChanged(cloudFile, localPath);
-                        if (isChanged)
-                        {
-                            //Retrieve the hashmap from the server
-                            var serverHash = await client.GetHashMap(account, container, url);
-                            //If it's a small file
-                            if (serverHash.Hashes.Count == 1)
-                                //Download it in one go
-                                await
-                                    DownloadEntireFileAsync(accountInfo, client, cloudFile, relativeUrl, localPath,
-                                                            serverHash);
-                            //Otherwise download it block by block
-                            else
-                                await
-                                    DownloadWithBlocks(accountInfo, client, cloudFile, relativeUrl, localPath,
-                                                       serverHash);
-
-                            if (cloudFile.AllowedTo == "read")
-                            {
-                                var attributes = File.GetAttributes(localPath);
-                                File.SetAttributes(localPath, attributes | FileAttributes.ReadOnly);
-                            }
-                        }
-                    }
-
-                    //Now we can store the object's metadata without worrying about ghost status entries
-                    StatusKeeper.StoreInfo(localPath, cloudFile);
-
-                }
-            }
-        }
-
-        private bool IsObjectChanged(ObjectInfo cloudFile, string localPath)
-        {
-            //If the target is a directory, there are no changes to download
-            if (Directory.Exists(localPath))
-                return false;
-            //If the file doesn't exist, we have a chagne
-            if (!File.Exists(localPath)) 
-                return true;
-            //If there is no stored state, we have a change
-            var localState = StatusKeeper.GetStateByFilePath(localPath);
-            if (localState == null)
-                return true;
-
-            var info = new FileInfo(localPath);
-            var shortHash = info.ComputeShortHash();
-            //If the file is different from the stored state, we have a change
-            if (localState.ShortHash != shortHash)
-                return true;
-            //If the top hashes differ, we have a change
-            return (localState.Checksum != cloudFile.Hash);
-        }
-
-        //Download a small file with a single GET operation
-        private async Task DownloadEntireFileAsync(AccountInfo accountInfo, CloudFilesClient client, ObjectInfo cloudFile, Uri relativeUrl, string filePath,TreeHash serverHash)
-        {
-            if (client == null)
-                throw new ArgumentNullException("client");
-            if (cloudFile==null)
-                throw new ArgumentNullException("cloudFile");
-            if (relativeUrl == null)
-                throw new ArgumentNullException("relativeUrl");
-            if (String.IsNullOrWhiteSpace(filePath))
-                throw new ArgumentNullException("filePath");
-            if (!Path.IsPathRooted(filePath))
-                throw new ArgumentException("The localPath must be rooted", "filePath");
-            if (cloudFile.IsDirectory)
-                throw new ArgumentException("cloudFile is a directory, not a file","cloudFile");
-            Contract.EndContractBlock();
-
-            var localPath = Pithos.Interfaces.FileInfoExtensions.GetProperFilePathCapitalization(filePath);
-            StatusNotification.SetPithosStatus(PithosStatus.LocalSyncing,String.Format("Downloading {0}",Path.GetFileName(localPath)));
-            StatusNotification.Notify(new CloudNotification { Data = cloudFile });
-
-            var fileAgent = GetFileAgent(accountInfo);
-            //Calculate the relative file path for the new file
-            var relativePath = relativeUrl.RelativeUriToFilePath();
-            //The file will be stored in a temporary location while downloading with an extension .download
-            var tempPath = Path.Combine(fileAgent.CachePath, relativePath + ".download");
-            //Make sure the target folder exists. DownloadFileTask will not create the folder
-            var tempFolder = Path.GetDirectoryName(tempPath);
-            if (!Directory.Exists(tempFolder))
-                Directory.CreateDirectory(tempFolder);
-
-            //Download the object to the temporary location
-            await client.GetObject(cloudFile.Account, cloudFile.Container, relativeUrl.ToString(), tempPath);
-
-            //Create the local folder if it doesn't exist (necessary for shared objects)
-            var localFolder = Path.GetDirectoryName(localPath);
-            if (!Directory.Exists(localFolder))
-                try
-                {
-                    Directory.CreateDirectory(localFolder);
-                }
-                catch (IOException)
-                {
-                    //A file may already exist that has the same name as the new folder.
-                    //This may be an artifact of the way Pithos handles directories
-                    var fileInfo = new FileInfo(localFolder);
-                    if (fileInfo.Exists && fileInfo.Length == 0)
-                    {
-                        Log.WarnFormat("Malformed directory object detected for [{0}]", localFolder);
-                        fileInfo.Delete();
-                        Directory.CreateDirectory(localFolder);
-                    }
-                    else 
-                        throw;
-                }
-            //And move it to its actual location once downloading is finished
-            if (File.Exists(localPath))
-                File.Replace(tempPath,localPath,null,true);
-            else
-                File.Move(tempPath,localPath);
-            //Notify listeners that a local file has changed
-            StatusNotification.NotifyChangedFile(localPath);
-
-                       
-        }
 
-        //Download a file asynchronously using blocks
-        public async Task DownloadWithBlocks(AccountInfo accountInfo, CloudFilesClient client, ObjectInfo cloudFile, Uri relativeUrl, string filePath, TreeHash serverHash)
-        {
-            if (client == null)
-                throw new ArgumentNullException("client");
-            if (cloudFile == null)
-                throw new ArgumentNullException("cloudFile");
-            if (relativeUrl == null)
-                throw new ArgumentNullException("relativeUrl");
-            if (String.IsNullOrWhiteSpace(filePath))
-                throw new ArgumentNullException("filePath");
-            if (!Path.IsPathRooted(filePath))
-                throw new ArgumentException("The filePath must be rooted", "filePath");
-            if (serverHash == null)
-                throw new ArgumentNullException("serverHash");
-            if (cloudFile.IsDirectory)
-                throw new ArgumentException("cloudFile is a directory, not a file", "cloudFile");
-            Contract.EndContractBlock();
-            
-           var fileAgent = GetFileAgent(accountInfo);
-            var localPath = Interfaces.FileInfoExtensions.GetProperFilePathCapitalization(filePath);
-            
-            //Calculate the relative file path for the new file
-            var relativePath = relativeUrl.RelativeUriToFilePath();
-            var blockUpdater = new BlockUpdater(fileAgent.CachePath, localPath, relativePath, serverHash);
 
-            
-            StatusNotification.SetPithosStatus(PithosStatus.LocalSyncing,String.Format("Calculating hashmap for {0} before download",Path.GetFileName(localPath)));
-            //Calculate the file's treehash
-            var treeHash = await Signature.CalculateTreeHashAsync(localPath, serverHash.BlockSize, serverHash.BlockHash, 2);
-                
-            //And compare it with the server's hash
-            var upHashes = serverHash.GetHashesAsStrings();
-            var localHashes = treeHash.HashDictionary;
-            ReportDownloadProgress(Path.GetFileName(localPath),0,upHashes.Length,cloudFile.Bytes);
-            for (int i = 0; i < upHashes.Length; i++)
-            {
-                //For every non-matching hash
-                var upHash = upHashes[i];
-                if (!localHashes.ContainsKey(upHash))
-                {
-                    StatusNotification.Notify(new CloudNotification { Data = cloudFile });
-
-                    if (blockUpdater.UseOrphan(i, upHash))
-                    {
-                        Log.InfoFormat("[BLOCK GET] ORPHAN FOUND for {0} of {1} for {2}", i, upHashes.Length, localPath);
-                        continue;
-                    }
-                    Log.InfoFormat("[BLOCK GET] START {0} of {1} for {2}", i, upHashes.Length, localPath);
-                    var start = i*serverHash.BlockSize;
-                    //To download the last block just pass a null for the end of the range
-                    long? end = null;
-                    if (i < upHashes.Length - 1 )
-                        end= ((i + 1)*serverHash.BlockSize) ;
-                            
-                    //Download the missing block
-                    var block = await client.GetBlock(cloudFile.Account, cloudFile.Container, relativeUrl, start, end);
-
-                    //and store it
-                    blockUpdater.StoreBlock(i, block);
-
-
-                    Log.InfoFormat("[BLOCK GET] FINISH {0} of {1} for {2}", i, upHashes.Length, localPath);
-                }
-                ReportDownloadProgress(Path.GetFileName(localPath), i, upHashes.Length, cloudFile.Bytes);
-            }
-
-            //Want to avoid notifications if no changes were made
-            var hasChanges = blockUpdater.HasBlocks;
-            blockUpdater.Commit();
-            
-            if (hasChanges)
-                //Notify listeners that a local file has changed
-                StatusNotification.NotifyChangedFile(localPath);
-
-            Log.InfoFormat("[BLOCK GET] COMPLETE {0}", localPath);            
-        }
-
-
-        private async Task UploadCloudFile(CloudAction action)
-        {
-            if (action == null)
-                throw new ArgumentNullException("action");           
-            Contract.EndContractBlock();
-            using(ThreadContext.Stacks["Operation"].Push("UploadCloudFile"))
-            {
-                try
-                {
-
-                    var accountInfo = action.AccountInfo;
-
-                    var fileInfo = action.LocalFile;
-
-                    if (fileInfo.Extension.Equals("ignore", StringComparison.InvariantCultureIgnoreCase))
-                        return;
-                    
-                    //
-                    if (action.FileState == null)
-                        action.FileState = StatusKeeper.GetStateByFilePath(fileInfo.FullName);
-                    if (action.FileState == null)
-                    {
-                        Log.WarnFormat("File [{0}] has no local state. It was probably created by a download action",fileInfo.FullName);
-                        return;
-                    }
-                    //Do not upload files in conflict
-                    if (action.FileState.FileStatus == FileStatus.Conflict )
-                    {
-                        Log.InfoFormat("Skipping file in conflict [{0}]",fileInfo.FullName);
-                        return;
-                    }
-                    if (action.FileState.FileStatus == FileStatus.Forbidden)
-                    {
-                        Log.InfoFormat("Skipping forbidden file [{0}]",fileInfo.FullName);
-                        return;
-                    }
-
-                    var relativePath = fileInfo.AsRelativeTo(accountInfo.AccountPath);
-                    if (relativePath.StartsWith(FolderConstants.OthersFolder))
-                    {
-                        var parts = relativePath.Split('\\');
-                        var accountName = parts[1];
-                        var oldName = accountInfo.UserName;
-                        var absoluteUri = accountInfo.StorageUri.AbsoluteUri;
-                        var nameIndex = absoluteUri.IndexOf(oldName, StringComparison.Ordinal);
-                        var root = absoluteUri.Substring(0, nameIndex);
-
-                        accountInfo = new AccountInfo
-                                          {
-                                              UserName = accountName,
-                                              AccountPath = Path.Combine(accountInfo.AccountPath, parts[0], parts[1]),
-                                              StorageUri = new Uri(root + accountName),
-                                              BlockHash = accountInfo.BlockHash,
-                                              BlockSize = accountInfo.BlockSize,
-                                              Token = accountInfo.Token
-                                          };
-                    }
-
-
-                    var fullFileName = fileInfo.GetProperCapitalization();
-                    using (var gate = NetworkGate.Acquire(fullFileName, NetworkOperation.Uploading))
-                    {
-                        //Abort if the file is already being uploaded or downloaded
-                        if (gate.Failed)
-                            return;
-
-                        var cloudFile = action.CloudFile;
-                        var account = cloudFile.Account ?? accountInfo.UserName;
-                        try
-                        {
-
-                        var client = new CloudFilesClient(accountInfo);
-                        //Even if GetObjectInfo times out, we can proceed with the upload            
-                        var cloudInfo = client.GetObjectInfo(account, cloudFile.Container, cloudFile.Name);
-
-                        //If this is a read-only file, do not upload changes
-                        if (cloudInfo.AllowedTo == "read")
-                            return;
-
-                        //TODO: Check how a directory hash is calculated -> All dirs seem to have the same hash
-                            if (fileInfo is DirectoryInfo)
-                            {
-                                //If the directory doesn't exist the Hash property will be empty
-                                if (String.IsNullOrWhiteSpace(cloudInfo.Hash))
-                                    //Go on and create the directory
-                                    await
-                                        client.PutObject(account, cloudFile.Container, cloudFile.Name, fullFileName,
-                                                         String.Empty, "application/directory");
-                            }
-                            else
-                            {
-
-                                var cloudHash = cloudInfo.Hash.ToLower();
-
-                                StatusNotification.Notify(new StatusNotification(String.Format("Hashing {0} for Upload",fileInfo.Name)));
-
-                                //TODO: This is the same as the calculation for the Local Hash!
-                                //First, calculate the tree hash
-/*
-                                var treeHash = await Signature.CalculateTreeHashAsync(fullFileName, accountInfo.BlockSize,
-                                                                                      accountInfo.BlockHash, 2);
-*/
-
-
-                                var treeHash = action.TreeHash.Value;
-                                var topHash = treeHash.TopHash.ToHashString();
-                                
-                                //var topHash = action.TopHash.Value;
-
-                                //If the file hashes match, abort the upload
-                                if (topHash == cloudHash /*|| topHash == cloudHash*/)
-                                {
-                                    //but store any metadata changes 
-                                    StatusKeeper.StoreInfo(fullFileName, cloudInfo);
-                                    Log.InfoFormat("Skip upload of {0}, hashes match", fullFileName);
-                                    return;
-                                }
-
-
-                                //Mark the file as modified while we upload it
-                                StatusKeeper.SetFileOverlayStatus(fullFileName, FileOverlayStatus.Modified);
-                                //And then upload it
-
-                                //Upload even small files using the Hashmap. The server may already contain
-                                //the relevant block
-
-                                //TODO: If the upload fails with a 403, abort it and mark conflict
-
-                                await
-                                    UploadWithHashMap(accountInfo, cloudFile, fileInfo as FileInfo, cloudFile.Name, treeHash);
-                            }
-                            //If everything succeeds, change the file and overlay status to normal
-                            StatusKeeper.SetFileState(fullFileName, FileStatus.Unchanged, FileOverlayStatus.Normal);
-                        }
-                        catch (WebException exc)
-                        {
-                            var response=(exc.Response as HttpWebResponse);
-                            if (response == null)
-                                throw;
-                            if (response.StatusCode == HttpStatusCode.Forbidden)
-                            {
-                                StatusKeeper.SetFileState(fileInfo.FullName,FileStatus.Forbidden, FileOverlayStatus.Conflict);                                
-                            }
-                        }
-                    }
-                    //Notify the Shell to update the overlays
-                    NativeMethods.RaiseChangeNotification(fullFileName);
-                    StatusNotification.NotifyChangedFile(fullFileName);
-                }
-                catch (AggregateException ex)
-                {
-                    var exc = ex.InnerException as WebException;
-                    if (exc == null)
-                        throw ex.InnerException;
-                    if (HandleUploadWebException(action, exc))
-                        return;
-                    throw;
-                }
-                catch (WebException ex)
-                {
-                    if (HandleUploadWebException(action, ex))
-                        return;
-                    throw;
-                }
-                catch (Exception ex)
-                {
-                    Log.Error("Unexpected error while uploading file", ex);
-                    throw;
-                }
-            }
-        }
-
-
-
-        private bool HandleUploadWebException(CloudAction action, WebException exc)
-        {
-            var response = exc.Response as HttpWebResponse;
-            if (response == null)
-                throw exc;
-            if (response.StatusCode == HttpStatusCode.Unauthorized)
-            {
-                Log.Error("Not allowed to upload file", exc);
-                var message = String.Format("Not allowed to uplad file {0}", action.LocalFile.FullName);
-                StatusKeeper.SetFileState(action.LocalFile.FullName, FileStatus.Unchanged, FileOverlayStatus.Normal);
-                StatusNotification.NotifyChange(message, TraceLevel.Warning);
-                return true;
-            }
-            return false;
-        }
-
-        public async Task UploadWithHashMap(AccountInfo accountInfo,ObjectInfo cloudFile,FileInfo fileInfo,string url,TreeHash treeHash)
-        {
-            if (accountInfo == null)
-                throw new ArgumentNullException("accountInfo");
-            if (cloudFile==null)
-                throw new ArgumentNullException("cloudFile");
-            if (fileInfo == null)
-                throw new ArgumentNullException("fileInfo");
-            if (String.IsNullOrWhiteSpace(url))
-                throw new ArgumentNullException(url);
-            if (treeHash==null)
-                throw new ArgumentNullException("treeHash");
-            if (String.IsNullOrWhiteSpace(cloudFile.Container) )
-                throw new ArgumentException("Invalid container","cloudFile");
-            Contract.EndContractBlock();
-
-            StatusNotification.Notify(new StatusNotification(String.Format("Uploading {0}", fileInfo.Name)));
-
-            var fullFileName = fileInfo.GetProperCapitalization();
-
-            var account = cloudFile.Account ?? accountInfo.UserName;
-            var container = cloudFile.Container ;
-
-            var client = new CloudFilesClient(accountInfo);            
-            //Send the hashmap to the server            
-            var missingHashes =  await client.PutHashMap(account, container, url, treeHash);
-            int block = 0;
-            ReportUploadProgress(fileInfo.Name,block++, missingHashes.Count, fileInfo.Length);
-            //If the server returns no missing hashes, we are done
-            while (missingHashes.Count > 0)
-            {
-
-                var buffer = new byte[accountInfo.BlockSize];
-                foreach (var missingHash in missingHashes)
-                {
-                    //Find the proper block
-                    var blockIndex = treeHash.HashDictionary[missingHash];
-                    long offset = blockIndex*accountInfo.BlockSize;
-
-                    var read = fileInfo.Read(buffer, offset, accountInfo.BlockSize);
-
-                    try
-                    {
-                        //And upload the block                
-                        await client.PostBlock(account, container, buffer, 0, read);
-                        Log.InfoFormat("[BLOCK] Block {0} of {1} uploaded", blockIndex, fullFileName);
-                    }
-                    catch (Exception exc)
-                    {
-                        Log.Error(String.Format("Uploading block {0} of {1}", blockIndex, fullFileName), exc);
-                    }
-                    ReportUploadProgress(fileInfo.Name,block++, missingHashes.Count, fileInfo.Length);
-                }
-
-                //Repeat until there are no more missing hashes                
-                missingHashes = await client.PutHashMap(account, container, url, treeHash);
-            }
-
-            ReportUploadProgress(fileInfo.Name, missingHashes.Count, missingHashes.Count, fileInfo.Length);
-        }
-
-        private void ReportUploadProgress(string fileName,int block, int totalBlocks, long fileSize)
-        {
-            StatusNotification.Notify(totalBlocks == 0
-                                          ? new ProgressNotification(fileName, "Uploading", 1, 1, fileSize)
-                                          : new ProgressNotification(fileName, "Uploading", block, totalBlocks, fileSize));
-        }
-
-        private void ReportDownloadProgress(string fileName,int block, int totalBlocks, long fileSize)
-        {
-            StatusNotification.Notify(totalBlocks == 0
-                                          ? new ProgressNotification(fileName, "Downloading", 1, 1, fileSize)
-                                          : new ProgressNotification(fileName, "Downloading", block, totalBlocks, fileSize));
-        }
     }
 
    
index 299b41f..de8ed48 100644 (file)
@@ -107,9 +107,11 @@ namespace Pithos.Core.Agents
 
         private static void MigrateOldDb(string dbPath, string appDataPath)
         {
-            Contract.Requires(!String.IsNullOrWhiteSpace(dbPath));
-            Contract.Requires(!String.IsNullOrWhiteSpace(appDataPath));
-
+            if(String.IsNullOrWhiteSpace(dbPath))
+                throw new ArgumentNullException("dbPath");
+            if(String.IsNullOrWhiteSpace(appDataPath))
+                throw new ArgumentNullException("appDataPath");
+            Contract.EndContractBlock();
 
             var oldDbPath = Path.Combine(appDataPath, "Pithos", "pithos.db");
             var oldDbInfo = new FileInfo(oldDbPath);
diff --git a/trunk/Pithos.Core/Agents/Uploader.cs b/trunk/Pithos.Core/Agents/Uploader.cs
new file mode 100644 (file)
index 0000000..6d0f258
--- /dev/null
@@ -0,0 +1,279 @@
+using System;
+using System.ComponentModel.Composition;
+using System.Diagnostics;
+using System.Diagnostics.Contracts;
+using System.IO;
+using System.Net;
+using System.Reflection;
+using System.Threading.Tasks;
+using Pithos.Interfaces;
+using Pithos.Network;
+using log4net;
+
+namespace Pithos.Core.Agents
+{
+    [Export(typeof(Uploader))]
+    public class Uploader
+    {
+        private static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
+
+        [Import]
+        private IStatusKeeper StatusKeeper { get; set; }
+
+        
+        public IStatusNotification StatusNotification { get; set; }
+
+        public async Task UploadCloudFile(CloudAction action)
+        {
+            if (action == null)
+                throw new ArgumentNullException("action");
+            Contract.EndContractBlock();
+
+            using (ThreadContext.Stacks["Operation"].Push("UploadCloudFile"))
+            {
+                try
+                {
+                    var fileInfo = action.LocalFile;
+
+                    if (fileInfo.Extension.Equals("ignore", StringComparison.InvariantCultureIgnoreCase))
+                        return;
+
+                    //Try to load the action's local state, if it is empty
+                    if (action.FileState == null)
+                        action.FileState = StatusKeeper.GetStateByFilePath(fileInfo.FullName);
+                    if (action.FileState == null)
+                    {
+                        Log.WarnFormat("File [{0}] has no local state. It was probably created by a download action", fileInfo.FullName);
+                        return;
+                    }
+
+                    //Do not upload files in conflict
+                    if (action.FileState.FileStatus == FileStatus.Conflict)
+                    {
+                        Log.InfoFormat("Skipping file in conflict [{0}]", fileInfo.FullName);
+                        return;
+                    }
+                    //Do not upload files when we have no permission
+                    if (action.FileState.FileStatus == FileStatus.Forbidden)
+                    {
+                        Log.InfoFormat("Skipping forbidden file [{0}]", fileInfo.FullName);
+                        return;
+                    }
+
+                    //Are we targeting our own account or a sharer account?
+                    var relativePath = fileInfo.AsRelativeTo(action.AccountInfo.AccountPath);
+                    var accountInfo = relativePath.StartsWith(FolderConstants.OthersFolder) 
+                                                  ? GetSharerAccount(relativePath, action.AccountInfo) 
+                                                  : action.AccountInfo;
+
+
+
+                    var fullFileName = fileInfo.GetProperCapitalization();
+                    using (var gate = NetworkGate.Acquire(fullFileName, NetworkOperation.Uploading))
+                    {
+                        //Abort if the file is already being uploaded or downloaded
+                        if (gate.Failed)
+                            return;
+
+                        var cloudFile = action.CloudFile;
+                        var account = cloudFile.Account ?? accountInfo.UserName;
+                        try
+                        {
+
+                            var client = new CloudFilesClient(accountInfo);
+                            //Even if GetObjectInfo times out, we can proceed with the upload            
+                            var cloudInfo = client.GetObjectInfo(account, cloudFile.Container, cloudFile.Name);
+
+                            //If this is a read-only file, do not upload changes
+                            if (cloudInfo.AllowedTo == "read")
+                                return;
+
+                            if (fileInfo is DirectoryInfo)
+                            {
+                                //If the directory doesn't exist the Hash property will be empty
+                                if (String.IsNullOrWhiteSpace(cloudInfo.Hash))
+                                    //Go on and create the directory
+                                    await client.PutObject(account, cloudFile.Container, cloudFile.Name, fullFileName,
+                                                         String.Empty, "application/directory");
+                            }
+                            else
+                            {
+
+                                var cloudHash = cloudInfo.Hash.ToLower();
+
+                                StatusNotification.Notify(new StatusNotification(String.Format("Hashing {0} for Upload", fileInfo.Name)));
+
+                                var treeHash = action.TreeHash.Value;
+                                var topHash = treeHash.TopHash.ToHashString();
+
+                                //If the file hashes match, abort the upload
+                                if (cloudInfo != ObjectInfo.Empty && topHash == cloudHash)
+                                {
+                                    //but store any metadata changes 
+                                    StatusKeeper.StoreInfo(fullFileName, cloudInfo);
+                                    Log.InfoFormat("Skip upload of {0}, hashes match", fullFileName);
+                                    return;
+                                }
+
+
+                                //Mark the file as modified while we upload it
+                                StatusKeeper.SetFileOverlayStatus(fullFileName, FileOverlayStatus.Modified);
+                                //And then upload it
+
+                                //Upload even small files using the Hashmap. The server may already contain
+                                //the relevant block                                
+
+                                await UploadWithHashMap(accountInfo, cloudFile, fileInfo as FileInfo, cloudFile.Name, treeHash);
+                            }
+                            //If everything succeeds, change the file and overlay status to normal
+                            StatusKeeper.SetFileState(fullFileName, FileStatus.Unchanged, FileOverlayStatus.Normal);
+                        }
+                        catch (WebException exc)
+                        {
+                            var response = (exc.Response as HttpWebResponse);
+                            if (response == null)
+                                throw;
+                            if (response.StatusCode == HttpStatusCode.Forbidden)
+                            {
+                                StatusKeeper.SetFileState(fileInfo.FullName, FileStatus.Forbidden, FileOverlayStatus.Conflict);
+                            }
+
+                            //In any other case, propagate the error
+                            throw;
+                        }
+                    }
+                    //Notify the Shell to update the overlays
+                    NativeMethods.RaiseChangeNotification(fullFileName);
+                    StatusNotification.NotifyChangedFile(fullFileName);
+                }
+                catch (AggregateException ex)
+                {
+                    var exc = ex.InnerException as WebException;
+                    if (exc == null)
+                        throw ex.InnerException;
+                    if (HandleUploadWebException(action, exc))
+                        return;
+                    throw;
+                }
+                catch (WebException ex)
+                {
+                    if (HandleUploadWebException(action, ex))
+                        return;
+                    throw;
+                }
+                catch (Exception ex)
+                {
+                    Log.Error("Unexpected error while uploading file", ex);
+                    throw;
+                }
+            }
+        }
+
+        private static AccountInfo GetSharerAccount(string relativePath, AccountInfo accountInfo)
+        {
+            var parts = relativePath.Split('\\');
+            var accountName = parts[1];
+            var oldName = accountInfo.UserName;
+            var absoluteUri = accountInfo.StorageUri.AbsoluteUri;
+            var nameIndex = absoluteUri.IndexOf(oldName, StringComparison.Ordinal);
+            var root = absoluteUri.Substring(0, nameIndex);
+
+            accountInfo = new AccountInfo
+                              {
+                                  UserName = accountName,
+                                  AccountPath = Path.Combine(accountInfo.AccountPath, parts[0], parts[1]),
+                                  StorageUri = new Uri(root + accountName),
+                                  BlockHash = accountInfo.BlockHash,
+                                  BlockSize = accountInfo.BlockSize,
+                                  Token = accountInfo.Token
+                              };
+            return accountInfo;
+        }
+
+
+        public async Task UploadWithHashMap(AccountInfo accountInfo, ObjectInfo cloudFile, FileInfo fileInfo, string url, TreeHash treeHash)
+        {
+            if (accountInfo == null)
+                throw new ArgumentNullException("accountInfo");
+            if (cloudFile == null)
+                throw new ArgumentNullException("cloudFile");
+            if (fileInfo == null)
+                throw new ArgumentNullException("fileInfo");
+            if (String.IsNullOrWhiteSpace(url))
+                throw new ArgumentNullException(url);
+            if (treeHash == null)
+                throw new ArgumentNullException("treeHash");
+            if (String.IsNullOrWhiteSpace(cloudFile.Container))
+                throw new ArgumentException("Invalid container", "cloudFile");
+            Contract.EndContractBlock();
+
+            StatusNotification.Notify(new StatusNotification(String.Format("Uploading {0}", fileInfo.Name)));
+
+            var fullFileName = fileInfo.GetProperCapitalization();
+
+            var account = cloudFile.Account ?? accountInfo.UserName;
+            var container = cloudFile.Container;
+
+            var client = new CloudFilesClient(accountInfo);
+            //Send the hashmap to the server            
+            var missingHashes = await client.PutHashMap(account, container, url, treeHash);
+            int block = 0;
+            ReportUploadProgress(fileInfo.Name, block++, missingHashes.Count, fileInfo.Length);
+            //If the server returns no missing hashes, we are done
+            while (missingHashes.Count > 0)
+            {
+
+                var buffer = new byte[accountInfo.BlockSize];
+                foreach (var missingHash in missingHashes)
+                {
+                    //Find the proper block
+                    var blockIndex = treeHash.HashDictionary[missingHash];
+                    long offset = blockIndex * accountInfo.BlockSize;
+
+                    var read = fileInfo.Read(buffer, offset, accountInfo.BlockSize);
+
+                    try
+                    {
+                        //And upload the block                
+                        await client.PostBlock(account, container, buffer, 0, read);
+                        Log.InfoFormat("[BLOCK] Block {0} of {1} uploaded", blockIndex, fullFileName);
+                    }
+                    catch (Exception exc)
+                    {
+                        Log.Error(String.Format("Uploading block {0} of {1}", blockIndex, fullFileName), exc);
+                    }
+                    ReportUploadProgress(fileInfo.Name, block++, missingHashes.Count, fileInfo.Length);
+                }
+
+                //Repeat until there are no more missing hashes                
+                missingHashes = await client.PutHashMap(account, container, url, treeHash);
+            }
+
+            ReportUploadProgress(fileInfo.Name, missingHashes.Count, missingHashes.Count, fileInfo.Length);
+        }
+
+        private void ReportUploadProgress(string fileName, int block, int totalBlocks, long fileSize)
+        {
+            StatusNotification.Notify(totalBlocks == 0
+                                          ? new ProgressNotification(fileName, "Uploading", 1, 1, fileSize)
+                                          : new ProgressNotification(fileName, "Uploading", block, totalBlocks, fileSize));
+        }
+
+
+        private bool HandleUploadWebException(CloudAction action, WebException exc)
+        {
+            var response = exc.Response as HttpWebResponse;
+            if (response == null)
+                throw exc;
+            if (response.StatusCode == HttpStatusCode.Unauthorized)
+            {
+                Log.Error("Not allowed to upload file", exc);
+                var message = String.Format("Not allowed to uplad file {0}", action.LocalFile.FullName);
+                StatusKeeper.SetFileState(action.LocalFile.FullName, FileStatus.Unchanged, FileOverlayStatus.Normal);
+                StatusNotification.NotifyChange(message, TraceLevel.Warning);
+                return true;
+            }
+            return false;
+        }
+    }
+}
index 08e71f8..2c3869a 100644 (file)
@@ -430,7 +430,8 @@ namespace Pithos.Core
 
         public static FileState CreateFor(FileSystemInfo info)
         {
-            Contract.Requires(info!=null);
+            if(info==null)
+                throw new ArgumentNullException("info");
             Contract.EndContractBlock();
             
             if (info is DirectoryInfo)
index b7901c4..c2cf51a 100644 (file)
   <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|x64'">
     <DebugSymbols>true</DebugSymbols>
     <OutputPath>bin\x64\Debug\</OutputPath>
-    <DefineConstants>DEBUG;TRACE</DefineConstants>
+    <DefineConstants>TRACE;DEBUG;CONTRACTS_FULL</DefineConstants>
     <DebugType>full</DebugType>
     <PlatformTarget>x64</PlatformTarget>
     <CodeAnalysisLogFile>bin\Debug\Pithos.Core.dll.CodeAnalysisLog.xml</CodeAnalysisLogFile>
   <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|x86'">
     <DebugSymbols>true</DebugSymbols>
     <OutputPath>bin\x86\Debug\</OutputPath>
-    <DefineConstants>DEBUG;TRACE</DefineConstants>
+    <DefineConstants>TRACE;DEBUG</DefineConstants>
     <DebugType>full</DebugType>
     <PlatformTarget>x86</PlatformTarget>
     <CodeAnalysisLogFile>bin\Debug\Pithos.Core.dll.CodeAnalysisLog.xml</CodeAnalysisLogFile>
     <Compile Include="Agents\CloudTransferAction.cs" />
     <Compile Include="Agents\CollectionExtensions.cs" />
     <Compile Include="Agents\DeleteAgent.cs" />
+    <Compile Include="Agents\Downloader.cs" />
     <Compile Include="Agents\FileAgent.cs" />
     <Compile Include="Agents\BlockExtensions.cs" />
     <Compile Include="Agents\FileEventIdleBatch.cs" />
     <Compile Include="Agents\ObjectInfoComparer.cs" />
     <Compile Include="Agents\PollAgent.cs" />
     <Compile Include="Agents\SnapshotDifferencer.cs" />
+    <Compile Include="Agents\Uploader.cs" />
     <Compile Include="Agents\WorkflowAgent.cs" />
     <Compile Include="DynamicDictionary.cs" />
     <Compile Include="EnumerableExtensions.cs" />
diff --git a/trunk/Pithos.Installer/rnotes.0.7.20403.html b/trunk/Pithos.Installer/rnotes.0.7.20403.html
new file mode 100644 (file)
index 0000000..31d2c50
--- /dev/null
@@ -0,0 +1,13 @@
+<html>
+<body>
+<h2>Pithos MS Client v. 0.7.20403</h2>
+Release Date: Apr 03, 2012, 23:00
+<br/>
+Includes:
+<br/>
+<ul>
+<li> Fixes for empty file uploading, taskbar menus</li>
+<li> Refactoring of uploading/downloading code</li>
+</ul>
+</body>
+</html>
\ No newline at end of file
index 779f951..b5b16d4 100644 (file)
@@ -7,6 +7,17 @@
                <description></description>      \r
                <language>en</language>                         \r
                <item>            \r
+                       <title>Version 0.7.20403</title>\r
+                       <sparkle:releaseNotesLink>https://code.grnet.gr/projects/pithos-ms-client/repository/revisions/master/raw/trunk/Pithos.Installer/rnotes.0.7.20403.html</sparkle:releaseNotesLink>\r
+                       <pubDate>Tue, 03 Apr 2012 23:00:00 +0200</pubDate>\r
+                       <enclosure \r
+                               url="https://code.grnet.gr/attachments/download/1102/PithosPlus_Setupv0.7.20403.0.exe"\r
+                               length="4954238" \r
+                               type="application/octet-stream"\r
+                               sparkle:version="0.7.20403" \r
+                       />\r
+               </item>\r
+               <item>            \r
                        <title>Version 0.7.20401</title>\r
                        <sparkle:releaseNotesLink>https://code.grnet.gr/projects/pithos-ms-client/repository/revisions/master/raw/trunk/Pithos.Installer/rnotes.0.7.20401.html</sparkle:releaseNotesLink>\r
                        <pubDate>Fri, 02 Apr 2012 23:00:00 +0200</pubDate>\r
index 497bc15..3181c65 100644 (file)
@@ -1056,7 +1056,6 @@ namespace Pithos.Network
                 {
                     var ex = t.Exception.InnerException;
                     var we = ex as WebException;
-                    
                     var response = we.Response as HttpWebResponse;
                     if (response!=null && response.StatusCode==HttpStatusCode.Conflict)
                     {
@@ -1081,6 +1080,7 @@ namespace Pithos.Network
                     throw ex;
                     
                 }
+
                 //Any other status code is unexpected but there was no exception. We can probably continue processing
                 Log.WarnFormat("Unexcpected status code when putting map: {0} - {1}",client.StatusCode,client.StatusDescription);                    
                 
@@ -1250,7 +1250,6 @@ namespace Pithos.Network
             if (!File.Exists(fileName) && !Directory.Exists(fileName))
                 throw new FileNotFoundException("The file or directory does not exist",fileName);
 */
-            Contract.EndContractBlock();
             
             try
             {
index 6da39ba..e9a9e6a 100644 (file)
@@ -177,7 +177,6 @@ namespace Pithos.Network
         {
             if (String.IsNullOrWhiteSpace(filePath))
                 throw new ArgumentNullException("filePath");
-            Contract.EndContractBlock();
 
             var fileName = FileId.ToString("N");
             var path = Path.Combine(filePath, fileName);