Fixes to hashing
[pithos-ms-client] / trunk / Pithos.Network / CloudFilesClient.cs
index 8afffb2..2b11626 100644 (file)
@@ -57,6 +57,7 @@ using System.Net;
 using System.Reflection;
 using System.Security.Cryptography;
 using System.Text;
+using System.Threading;
 using System.Threading.Tasks;
 using Newtonsoft.Json;
 using Pithos.Interfaces;
@@ -787,7 +788,8 @@ namespace Pithos.Network
                                                    Account = account,
                                                    Container = container,
                                                    Name = objectName,
-                                                   Hash = client.GetHeaderValue("ETag"),
+                                                   ETag = client.GetHeaderValue("ETag"),
+                                                   X_Object_Hash = client.GetHeaderValue("X-Object-Hash"),
                                                    Content_Type = client.GetHeaderValue("Content-Type"),
                                                    Bytes = Convert.ToInt64(client.GetHeaderValue("Content-Length",true)),
                                                    Tags = tags,
@@ -947,7 +949,7 @@ namespace Pithos.Network
         /// <remarks>This method should have no timeout or a very long one</remarks>
         //Asynchronously download the object specified by *objectName* in a specific *container* to 
         // a local file
-        public Task GetObject(string account, string container, string objectName, string fileName)
+        public async Task GetObject(string account, string container, string objectName, string fileName,CancellationToken cancellationToken)
         {
             if (String.IsNullOrWhiteSpace(container))
                 throw new ArgumentNullException("container", "The container property can't be empty");
@@ -961,50 +963,40 @@ namespace Pithos.Network
                 //object to avoid concurrency errors.
                 //
                 //Download operations take a long time therefore they have no timeout.
-                var client = new RestClient(_baseClient) { Timeout = 0 };
-                if (!String.IsNullOrWhiteSpace(account))
-                    client.BaseAddress = GetAccountUrl(account);
+                using(var client = new RestClient(_baseClient) { Timeout = 0 })
+                {
+                    if (!String.IsNullOrWhiteSpace(account))
+                        client.BaseAddress = GetAccountUrl(account);
 
-                //The container and objectName are relative names. They are joined with the client's
-                //BaseAddress to create the object's absolute address
-                var builder = client.GetAddressBuilder(container, objectName);
-                var uri = builder.Uri;
+                    //The container and objectName are relative names. They are joined with the client's
+                    //BaseAddress to create the object's absolute address
+                    var builder = client.GetAddressBuilder(container, objectName);
+                    var uri = builder.Uri;
 
-                //Download progress is reported to the Trace log
-                Log.InfoFormat("[GET] START {0}", objectName);
-                client.DownloadProgressChanged += (sender, args) => 
-                    Log.InfoFormat("[GET PROGRESS] {0} {1}% {2} of {3}",
-                                    fileName, args.ProgressPercentage,
-                                    args.BytesReceived,
-                                    args.TotalBytesToReceive);                                
+                    //Download progress is reported to the Trace log
+                    Log.InfoFormat("[GET] START {0}", objectName);
+                    client.DownloadProgressChanged += (sender, args) =>
+                                                      Log.InfoFormat("[GET PROGRESS] {0} {1}% {2} of {3}",
+                                                                     fileName, args.ProgressPercentage,
+                                                                     args.BytesReceived,
+                                                                     args.TotalBytesToReceive);
 
+                    
+                    //Start downloading the object asynchronously
+                    await client.DownloadFileTaskAsync(uri, fileName,cancellationToken);
 
-                //Start downloading the object asynchronously
-                var downloadTask = client.DownloadFileTask(uri, fileName);
-                
-                //Once the download completes
-                return downloadTask.ContinueWith(download =>
-                                      {
-                                          //Delete the local client object
-                                          client.Dispose();
-                                          //And report failure or completion
-                                          if (download.IsFaulted)
-                                          {
-                                              Log.ErrorFormat("[GET] FAIL for {0} with \r{1}", objectName,
-                                                               download.Exception);
-                                          }
-                                          else
-                                          {
-                                              Log.InfoFormat("[GET] END {0}", objectName);                                             
-                                          }
-                                      });
+                    //Once the download completes
+                    //Delete the local client object
+                }
+                //And report failure or completion
             }
             catch (Exception exc)
             {
-                Log.ErrorFormat("[GET] END {0} with {1}", objectName, exc);
+                Log.ErrorFormat("[GET] FAIL {0} with {1}", objectName, exc);
                 throw;
             }
 
+            Log.InfoFormat("[GET] END {0}", objectName);                                             
 
 
         }
@@ -1093,8 +1085,8 @@ namespace Pithos.Network
 
         }
 
-        
-        public Task<byte[]> GetBlock(string account, string container, Uri relativeUrl, long start, long? end)
+
+        public async Task<byte[]> GetBlock(string account, string container, Uri relativeUrl, long start, long? end, CancellationToken cancellationToken)
         {
             if (String.IsNullOrWhiteSpace(Token))
                 throw new InvalidOperationException("Invalid Token");
@@ -1102,29 +1094,26 @@ namespace Pithos.Network
                 throw new InvalidOperationException("Invalid Storage Url");
             if (String.IsNullOrWhiteSpace(container))
                 throw new ArgumentNullException("container");
-            if (relativeUrl== null)
+            if (relativeUrl == null)
                 throw new ArgumentNullException("relativeUrl");
-            if (end.HasValue && end<0)
+            if (end.HasValue && end < 0)
                 throw new ArgumentOutOfRangeException("end");
-            if (start<0)
+            if (start < 0)
                 throw new ArgumentOutOfRangeException("start");
             Contract.EndContractBlock();
 
-
             //Don't use a timeout because putting the hashmap may be a long process
-            var client = new RestClient(_baseClient) {Timeout = 0, RangeFrom = start, RangeTo = end};
-            if (!String.IsNullOrWhiteSpace(account))
-                client.BaseAddress = GetAccountUrl(account);
+            using (var client = new RestClient(_baseClient) {Timeout = 0, RangeFrom = start, RangeTo = end})
+            {
+                if (!String.IsNullOrWhiteSpace(account))
+                    client.BaseAddress = GetAccountUrl(account);
 
-            var builder = client.GetAddressBuilder(container, relativeUrl.ToString());
-            var uri = builder.Uri;
+                var builder = client.GetAddressBuilder(container, relativeUrl.ToString());
+                var uri = builder.Uri;
 
-            return client.DownloadDataTask(uri)
-                .ContinueWith(t=>
-                                  {
-                                      client.Dispose();
-                                      return t.Result;
-                                  });
+                var result = await client.DownloadDataTaskAsync(uri, cancellationToken);
+                return result;
+            }
         }
 
 
@@ -1150,7 +1139,7 @@ namespace Pithos.Network
 
             //Don't use a timeout because putting the hashmap may be a long process
                 using (var client = new RestClient(_baseClient) { Timeout = 0 })
-                {
+                {                    
                     if (!String.IsNullOrWhiteSpace(account))
                         client.BaseAddress = GetAccountUrl(account);
 
@@ -1173,7 +1162,7 @@ namespace Pithos.Network
                     var buffer = new byte[count];
                     Buffer.BlockCopy(block, offset, buffer, 0, count);
                     //Send the block
-                    await client.UploadDataTask(uri, "POST", buffer);
+                    await client.UploadDataTaskAsync(uri, "POST", buffer);                    
                     Log.InfoFormat("[BLOCK POST] END");
                 }
             }
@@ -1289,7 +1278,7 @@ namespace Pithos.Network
                                                           {
                                                               Log.InfoFormat("Completed {0}", fileName);
                                                           }
-                                                      };
+                                                      };                    
                     if (contentType=="application/directory")
                         await client.UploadDataTaskAsync(uri, "PUT", new byte[0]);
                     else
@@ -1416,16 +1405,14 @@ namespace Pithos.Network
                     client.PutWithRetry(fileUrl, 3, @"application/octet-stream");
 
                     var expectedCodes = new[] { HttpStatusCode.OK, HttpStatusCode.NoContent, HttpStatusCode.Created};
-                    return (expectedCodes.Contains(client.StatusCode));
+                    var result=(expectedCodes.Contains(client.StatusCode));
+                    DeleteObject(account, cloudFile.Container, fileUrl);
+                    return result;
                 }
                 catch
                 {
                     return false;
                 }
-                finally
-                {
-                    DeleteObject(account,cloudFile.Container,fileUrl);                    
-                }                
             }
         }
     }