public static TableOperation Retrieve <TElement>(string partitionKey, string rowkey, List <string> selectColumns = null)
            where TElement : ITableEntity
        {
            CommonUtility.AssertNotNull("partitionKey", partitionKey);
            CommonUtility.AssertNotNull("rowkey", rowkey);

            // Create and return the table operation.
            return(new TableOperation(null /* entity */, TableOperationType.Retrieve)
            {
                RetrievePartitionKey = partitionKey,
                RetrieveRowKey = rowkey,
                SelectColumns = selectColumns,
                RetrieveResolver =
                    (pk, rk, ts, prop, etag) => EntityUtilities.ResolveEntityByType <TElement>(
                        pk,
                        rk,
                        ts,
                        prop,
                        etag),
                PropertyResolverType = typeof(TElement)
            });
        }
Esempio n. 2
0
        /// <summary>
        /// Generates a <see cref="RESTCommand{T}"/> for releasing a lease.
        /// </summary>
        /// <param name="blob">The blob.</param>
        /// <param name="attributes">The attributes.</param>
        /// <param name="accessCondition">An <see cref="AccessCondition"/> object that represents the condition that must be met in order for the request to proceed. If <c>null</c>, no condition is used.</param>
        /// <param name="options">A <see cref="BlobRequestOptions"/> object that specifies additional options for the request.</param>
        /// <returns>
        /// A <see cref="RESTCommand{T}"/> implementing the release lease operation.
        /// </returns>
        /// <exception cref="System.ArgumentException">accessCondition</exception>
        internal static RESTCommand <NullType> ReleaseLeaseImpl(ICloudBlob blob, BlobAttributes attributes, AccessCondition accessCondition, BlobRequestOptions options)
        {
            CommonUtility.AssertNotNull("accessCondition", accessCondition);
            if (accessCondition.LeaseId == null)
            {
                throw new ArgumentException(SR.MissingLeaseIDReleasing, "accessCondition");
            }

            RESTCommand <NullType> putCmd = new RESTCommand <NullType>(blob.ServiceClient.Credentials, attributes.StorageUri);

            options.ApplyToStorageCommand(putCmd);
            putCmd.BuildRequestDelegate = (uri, builder, serverTimeout, useVersionHeader, ctx) => BlobHttpWebRequestFactory.Lease(uri, serverTimeout, LeaseAction.Release, null /* proposedLeaseId */, null /* leaseDuration */, null /* leaseBreakPeriod */, accessCondition, useVersionHeader, ctx);
            putCmd.SignRequest          = blob.ServiceClient.AuthenticationHandler.SignRequest;
            putCmd.PreProcessResponse   = (cmd, resp, ex, ctx) =>
            {
                HttpResponseParsers.ProcessExpectedStatusCodeNoException(HttpStatusCode.OK, resp, NullType.Value, cmd, ex);
                CloudBlobSharedImpl.UpdateETagLMTLengthAndSequenceNumber(attributes, resp, false);
                return(NullType.Value);
            };

            return(putCmd);
        }
        /// <summary>
        /// Generates XML representing the given delete retention policy.
        /// </summary>
        /// <param name="deleteRetentionPolicy">The DeleteRetentionPolicy properties.</param>
        /// <returns>An XML logging element.</returns>
        private static XElement GenerateDeleteRetentionPolicyXml(DeleteRetentionPolicy deleteRetentionPolicy)
        {
            CommonUtility.AssertNotNull("deleteRetentionPolicy", deleteRetentionPolicy);

            bool     enabled = deleteRetentionPolicy.Enabled;
            XElement xml     = new XElement(DeleteRetentionPolicyName, new XElement(EnabledName, enabled));

            if (!enabled)
            {
                return(xml);
            }

            if (!deleteRetentionPolicy.RetentionDays.HasValue || deleteRetentionPolicy.RetentionDays.Value < 1 ||
                deleteRetentionPolicy.RetentionDays > Constants.MaximumAllowedRetentionDays)
            {
                throw new ArgumentException(SR.InvalidDeleteRetentionDaysValue);
            }

            xml.Add(new XElement(DaysName, (int)deleteRetentionPolicy.RetentionDays));

            return(xml);
        }
Esempio n. 4
0
        /// <summary>
        /// Constructs a <see cref="SharedAccessTablePermissions"/> object from a permissions string.
        /// </summary>
        /// <param name="input">The shared access permissions in string format.</param>
        /// <returns>A set of shared access permissions.</returns>
        public static SharedAccessTablePermissions PermissionsFromString(string input)
        {
            CommonUtility.AssertNotNull("input", input);

            SharedAccessTablePermissions permissions = 0;

            foreach (char c in input)
            {
                switch (c)
                {
                case 'r':
                    permissions |= SharedAccessTablePermissions.Query;
                    break;

                case 'a':
                    permissions |= SharedAccessTablePermissions.Add;
                    break;

                case 'u':
                    permissions |= SharedAccessTablePermissions.Update;
                    break;

                case 'd':
                    permissions |= SharedAccessTablePermissions.Delete;
                    break;

                default:
                    throw new ArgumentOutOfRangeException("input");
                }
            }

            // Incase we ever change none to be something other than 0
            if (permissions == 0)
            {
                permissions |= SharedAccessTablePermissions.None;
            }

            return(permissions);
        }
Esempio n. 5
0
        /// <summary>
        /// Gets the container's properties from the response.
        /// </summary>
        /// <param name="response">The web response.</param>
        /// <returns>The container's attributes.</returns>
        public static BlobContainerProperties GetProperties(HttpWebResponse response)
        {
            CommonUtility.AssertNotNull("response", response);

            // Set the container properties
            BlobContainerProperties containerProperties = new BlobContainerProperties();

            containerProperties.ETag = HttpResponseParsers.GetETag(response);

#if WINDOWS_PHONE
            containerProperties.LastModified = HttpResponseParsers.GetLastModified(response);
#else
            containerProperties.LastModified = response.LastModified.ToUniversalTime();
#endif

            // Get lease properties
            containerProperties.LeaseStatus   = BlobHttpResponseParsers.GetLeaseStatus(response);
            containerProperties.LeaseState    = BlobHttpResponseParsers.GetLeaseState(response);
            containerProperties.LeaseDuration = BlobHttpResponseParsers.GetLeaseDuration(response);

            return(containerProperties);
        }
Esempio n. 6
0
        /// <summary>
        /// Extracts a <see cref="CopyState"/> object from the headers of a web response.
        /// </summary>
        /// <param name="response">The HTTP web response.</param>
        /// <returns>A <see cref="CopyState"/> object, or null if the web response does not contain a copy status.</returns>
        public static CopyState GetCopyAttributes(HttpResponseMessage response)
        {
            CommonUtility.AssertNotNull("response", response);

            string copyStatusString = response.Headers.GetHeaderSingleValueOrDefault(Constants.HeaderConstants.CopyStatusHeader);

            if (!string.IsNullOrEmpty(copyStatusString))
            {
                return(GetCopyAttributes(
                           copyStatusString,
                           response.Headers.GetHeaderSingleValueOrDefault(Constants.HeaderConstants.CopyIdHeader),
                           response.Headers.GetHeaderSingleValueOrDefault(Constants.HeaderConstants.CopySourceHeader),
                           response.Headers.GetHeaderSingleValueOrDefault(Constants.HeaderConstants.CopyProgressHeader),
                           response.Headers.GetHeaderSingleValueOrDefault(Constants.HeaderConstants.CopyCompletionTimeHeader),
                           response.Headers.GetHeaderSingleValueOrDefault(Constants.HeaderConstants.CopyDescriptionHeader),
                           response.Headers.GetHeaderSingleValueOrDefault(Constants.HeaderConstants.CopyDestinationSnapshotHeader)));
            }
            else
            {
                return(null);
            }
        }
        /// <summary>
        /// Generates a <see cref="RESTCommand{T}" /> for changing a lease ID.
        /// </summary>
        /// <param name="blob">The blob.</param>
        /// <param name="attributes">The attributes.</param>
        /// <param name="proposedLeaseId">The proposed new lease ID.</param>
        /// <param name="accessCondition">An object that represents the access conditions for the blob. If null, no condition is used.</param>
        /// <param name="options">An object that specifies additional options for the request.</param>
        /// <returns>
        /// A <see cref="RESTCommand{T}" /> implementing the change lease ID operation.
        /// </returns>
        /// <exception cref="System.ArgumentException">accessCondition</exception>
        internal static RESTCommand <string> ChangeLeaseImpl(ICloudBlob blob, BlobAttributes attributes, string proposedLeaseId, AccessCondition accessCondition, BlobRequestOptions options)
        {
            CommonUtility.AssertNotNull("accessCondition", accessCondition);
            CommonUtility.AssertNotNull("proposedLeaseId", proposedLeaseId);
            if (accessCondition.LeaseId == null)
            {
                throw new ArgumentException(SR.MissingLeaseIDChanging, "accessCondition");
            }

            RESTCommand <string> putCmd = new RESTCommand <string>(blob.ServiceClient.Credentials, attributes.Uri);

            putCmd.ApplyRequestOptions(options);
            putCmd.BuildRequestDelegate = (uri, builder, serverTimeout, ctx) => BlobHttpWebRequestFactory.Lease(uri, serverTimeout, LeaseAction.Change, proposedLeaseId, null /* leaseDuration */, null /* leaseBreakPeriod */, accessCondition, ctx);
            putCmd.SignRequest          = blob.ServiceClient.AuthenticationHandler.SignRequest;
            putCmd.PreProcessResponse   = (cmd, resp, ex, ctx) =>
            {
                HttpResponseParsers.ProcessExpectedStatusCodeNoException(HttpStatusCode.OK, resp, null /* retVal */, cmd, ex);
                return(BlobHttpResponseParsers.GetLeaseId(resp));
            };

            return(putCmd);
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="BlobProperties"/> class based on an existing instance.
        /// </summary>
        /// <param name="other">A <see cref="BlobProperties"/> object.</param>
        /// <remarks>Lease-related properties will not be cloned, because a lease associated with the base blob is not copied to the snapshot.</remarks>
        public BlobProperties(BlobProperties other)
        {
            CommonUtility.AssertNotNull("other", other);

            this.BlobType           = other.BlobType;
            this.ContentType        = other.ContentType;
            this.ContentDisposition = other.ContentDisposition;
            this.ContentEncoding    = other.ContentEncoding;
            this.ContentLanguage    = other.ContentLanguage;
            this.CacheControl       = other.CacheControl;
            this.ContentMD5         = other.ContentMD5;
            this.Length             = other.Length;
            this.ETag                          = other.ETag;
            this.LastModified                  = other.LastModified;
            this.PageBlobSequenceNumber        = other.PageBlobSequenceNumber;
            this.AppendBlobCommittedBlockCount = other.AppendBlobCommittedBlockCount;
            this.IsServerEncrypted             = other.IsServerEncrypted;
            this.IsIncrementalCopy             = other.IsIncrementalCopy;
            this.PremiumPageBlobTier           = other.PremiumPageBlobTier;
            this.StandardBlobTier              = other.StandardBlobTier;
            this.RehydrationStatus             = other.RehydrationStatus;
        }
        /// <summary>
        /// Constructs a web request to set system properties for a file.
        /// </summary>
        /// <param name="uri">The absolute URI to the file.</param>
        /// <param name="timeout">The server timeout interval.</param>
        /// <param name="properties">The file's properties.</param>
        /// <param name="accessCondition">The access condition to apply to the request.</param>
        /// <returns>A web request to use to perform the operation.</returns>
        public static StorageRequestMessage SetProperties(Uri uri, int?timeout, FileProperties properties, AccessCondition accessCondition, HttpContent content, OperationContext operationContext, ICanonicalizer canonicalizer, StorageCredentials credentials)
        {
            CommonUtility.AssertNotNull("properties", properties);
            UriQueryBuilder builder = new UriQueryBuilder();

            builder.Add(Constants.QueryConstants.Component, "properties");

            StorageRequestMessage request = HttpRequestMessageFactory.CreateRequestMessage(HttpMethod.Put, uri, timeout, builder, content, operationContext, canonicalizer, credentials);

            if (properties != null)
            {
                request.AddOptionalHeader(Constants.HeaderConstants.FileCacheControlHeader, properties.CacheControl);
                request.AddOptionalHeader(Constants.HeaderConstants.FileContentDispositionRequestHeader, properties.ContentDisposition);
                request.AddOptionalHeader(Constants.HeaderConstants.FileContentEncodingHeader, properties.ContentEncoding);
                request.AddOptionalHeader(Constants.HeaderConstants.FileContentLanguageHeader, properties.ContentLanguage);
                request.AddOptionalHeader(Constants.HeaderConstants.FileContentMD5Header, properties.ContentMD5);
                request.AddOptionalHeader(Constants.HeaderConstants.FileContentTypeHeader, properties.ContentType);
            }

            request.ApplyAccessCondition(accessCondition);
            return(request);
        }
        /// <summary>
        /// Get the complete query builder for creating the Shared Access Signature query.
        /// </summary>
        /// <param name="policy">The shared access policy to hash.</param>
        /// <param name="tableName">The name of the table associated with this shared access signature.</param>
        /// <param name="accessPolicyIdentifier">An optional identifier for the policy.</param>
        /// <param name="startPartitionKey">The start partition key, or null.</param>
        /// <param name="startRowKey">The start row key, or null.</param>
        /// <param name="endPartitionKey">The end partition key, or null.</param>
        /// <param name="endRowKey">The end row key, or null.</param>
        /// <param name="signature">The signature to use.</param>
        /// <param name="accountKeyName">The name of the key used to create the signature, or null if the key is implicit.</param>
        /// <returns>The finished query builder.</returns>
        internal static UriQueryBuilder GetSignature(
            SharedAccessTablePolicy policy,
            string tableName,
            string accessPolicyIdentifier,
            string startPartitionKey,
            string startRowKey,
            string endPartitionKey,
            string endRowKey,
            string signature,
            string accountKeyName)
        {
            CommonUtility.AssertNotNull("signature", signature);

            UriQueryBuilder builder = new UriQueryBuilder();

            AddEscapedIfNotNull(builder, Constants.QueryConstants.SignedVersion, Constants.HeaderConstants.TargetStorageVersion);
            AddEscapedIfNotNull(builder, Constants.QueryConstants.SasTableName, tableName);
            AddEscapedIfNotNull(builder, Constants.QueryConstants.StartPartitionKey, startPartitionKey);
            AddEscapedIfNotNull(builder, Constants.QueryConstants.StartRowKey, startRowKey);
            AddEscapedIfNotNull(builder, Constants.QueryConstants.EndPartitionKey, endPartitionKey);
            AddEscapedIfNotNull(builder, Constants.QueryConstants.EndRowKey, endRowKey);
            AddEscapedIfNotNull(builder, Constants.QueryConstants.SignedIdentifier, accessPolicyIdentifier);
            AddEscapedIfNotNull(builder, Constants.QueryConstants.SignedKey, accountKeyName);
            AddEscapedIfNotNull(builder, Constants.QueryConstants.Signature, signature);

            if (policy != null)
            {
                AddEscapedIfNotNull(builder, Constants.QueryConstants.SignedStart, GetDateTimeOrNull(policy.SharedAccessStartTime));
                AddEscapedIfNotNull(builder, Constants.QueryConstants.SignedExpiry, GetDateTimeOrNull(policy.SharedAccessExpiryTime));

                string permissions = SharedAccessTablePolicy.PermissionsToString(policy.Permissions);
                if (!string.IsNullOrEmpty(permissions))
                {
                    AddEscapedIfNotNull(builder, Constants.QueryConstants.SignedPermissions, permissions);
                }
            }

            return(builder);
        }
        public TableServiceContext(CloudTableClient client)
            : base(client.BaseUri)
        {
            CommonUtility.AssertNotNull("client", client);

            if (client.BaseUri == null)
            {
                throw new ArgumentNullException("client");
            }

            if (!client.BaseUri.IsAbsoluteUri)
            {
                string errorMessage = string.Format(CultureInfo.CurrentCulture, SR.RelativeAddressNotPermitted, client.BaseUri.ToString());

                throw new ArgumentException(errorMessage, "client");
            }

            this.SendingRequest += this.TableServiceContext_SendingRequest;

            this.IgnoreMissingProperties = true;
            this.MergeOption             = MergeOption.PreserveChanges;
            this.ServiceClient           = client;
        }
        /// <summary>
        /// Constructs a web request to set system properties for a file.
        /// </summary>
        /// <param name="uri">The absolute URI to the file.</param>
        /// <param name="timeout">The server timeout interval.</param>
        /// <param name="properties">The file's properties.</param>
        /// <param name="accessCondition">The access condition to apply to the request.</param>
        /// <param name="useVersionHeader">A boolean value indicating whether to set the <i>x-ms-version</i> HTTP header.</param>
        /// <param name="operationContext">An <see cref="OperationContext" /> object for tracking the current operation.</param>
        /// <returns>A <see cref="System.Net.HttpWebRequest"/> object.</returns>
        public static HttpWebRequest SetProperties(Uri uri, int?timeout, FileProperties properties, AccessCondition accessCondition, bool useVersionHeader, OperationContext operationContext)
        {
            CommonUtility.AssertNotNull("properties", properties);

            UriQueryBuilder builder = new UriQueryBuilder();

            builder.Add(Constants.QueryConstants.Component, "properties");

            HttpWebRequest request = HttpWebRequestFactory.CreateWebRequest(WebRequestMethods.Http.Put, uri, timeout, builder, useVersionHeader, operationContext);

            if (properties != null)
            {
                request.AddOptionalHeader(Constants.HeaderConstants.FileCacheControlHeader, properties.CacheControl);
                request.AddOptionalHeader(Constants.HeaderConstants.FileContentEncodingHeader, properties.ContentEncoding);
                request.AddOptionalHeader(Constants.HeaderConstants.FileContentDispositionRequestHeader, properties.ContentDisposition);
                request.AddOptionalHeader(Constants.HeaderConstants.FileContentLanguageHeader, properties.ContentLanguage);
                request.AddOptionalHeader(Constants.HeaderConstants.FileContentMD5Header, properties.ContentMD5);
                request.AddOptionalHeader(Constants.HeaderConstants.FileContentTypeHeader, properties.ContentType);
            }

            request.ApplyAccessCondition(accessCondition);
            return(request);
        }
Esempio n. 13
0
        /// <summary>
        /// Gets the share's properties from the response.
        /// </summary>
        /// <param name="response">The web response.</param>
        /// <returns>The share's attributes.</returns>
        public static FileShareProperties GetProperties(HttpWebResponse response)
        {
            CommonUtility.AssertNotNull("response", response);

            // Set the share properties
            FileShareProperties shareProperties = new FileShareProperties();

            shareProperties.ETag = HttpResponseParsers.GetETag(response);

#if WINDOWS_PHONE
            shareProperties.LastModified = HttpResponseParsers.GetLastModified(response);
#else
            shareProperties.LastModified = response.LastModified.ToUniversalTime();
#endif

            string quota = response.Headers[Constants.HeaderConstants.ShareQuota];
            if (!string.IsNullOrEmpty(quota))
            {
                shareProperties.Quota = int.Parse(quota, CultureInfo.InvariantCulture);
            }

            return(shareProperties);
        }
        /// <summary>
        /// Converts the specified HTTP request data into a standard form appropriate for signing.
        /// </summary>
        /// <param name="request">The HTTP request that needs to be signed.</param>
        /// <param name="accountName">The name of the storage account that the HTTP request will access.</param>
        /// <returns>The canonicalized string containing the HTTP request data in a standard form appropriate for signing.</returns>
        /// <seealso href="http://msdn.microsoft.com/en-us/library/windowsazure/dd179428.aspx">Authentication for the Windows Azure Storage Services</seealso>
        public string CanonicalizeHttpRequest(HttpWebRequest request, string accountName)
        {
            CommonUtility.AssertNotNull("request", request);

            // Add the method (GET, POST, PUT, or HEAD).
            CanonicalizedString canonicalizedString = new CanonicalizedString(request.Method, ExpectedCanonicalizedStringLength);

            // Add the Content-* HTTP headers. Empty values are allowed.
            canonicalizedString.AppendCanonicalizedElement(request.Headers[HttpRequestHeader.ContentMd5]);
            canonicalizedString.AppendCanonicalizedElement(request.ContentType);

            // Add the Date HTTP header (only if the x-ms-date header is not being used)
            AuthenticationUtility.AppendCanonicalizedDateHeader(canonicalizedString, request);

            // Add any custom headers
            AuthenticationUtility.AppendCanonicalizedCustomHeaders(canonicalizedString, request);

            // Add the canonicalized URI element
            string resourceString = AuthenticationUtility.GetCanonicalizedResourceString(request.RequestUri, accountName, true);
            canonicalizedString.AppendCanonicalizedElement(resourceString);

            return canonicalizedString.ToString();
        }
Esempio n. 15
0
        /// <summary>
        /// Return an encrypted base64 encoded message along with encryption related metadata given a plain text message.
        /// </summary>
        /// <param name="inputMessage">The input message in bytes.</param>
        /// <returns>The encrypted message that will be uploaded to the service.</returns>
        internal string EncryptMessage(byte[] inputMessage)
        {
            CommonUtility.AssertNotNull("inputMessage", inputMessage);

            if (this.Key == null)
            {
                throw new InvalidOperationException(SR.KeyMissingError, null);
            }

            CloudQueueEncryptedMessage encryptedMessage = new CloudQueueEncryptedMessage();
            EncryptionData             encryptionData   = new EncryptionData();

            encryptionData.EncryptionAgent     = new EncryptionAgent(Constants.EncryptionConstants.EncryptionProtocolV1, EncryptionAlgorithm.AES_CBC_256);
            encryptionData.KeyWrappingMetadata = new Dictionary <string, string>();
            encryptionData.KeyWrappingMetadata[Constants.EncryptionConstants.AgentMetadataKey] = Constants.EncryptionConstants.AgentMetadataValue;

#if WINDOWS_DESKTOP && !WINDOWS_PHONE
            using (AesCryptoServiceProvider myAes = new AesCryptoServiceProvider())
#else
            using (AesManaged myAes = new AesManaged())
#endif
            {
                encryptionData.ContentEncryptionIV = myAes.IV;

                // Wrap always happens locally, irrespective of local or cloud key. So it is ok to call it synchronously.
                Tuple <byte[], string> wrappedKey = CommonUtility.RunWithoutSynchronizationContext(() => this.Key.WrapKeyAsync(myAes.Key, null /* algorithm */, CancellationToken.None).GetAwaiter().GetResult());
                encryptionData.WrappedContentKey = new WrappedKey(this.Key.Kid, wrappedKey.Item1, wrappedKey.Item2);

                using (ICryptoTransform encryptor = myAes.CreateEncryptor())
                {
                    encryptedMessage.EncryptedMessageContents = Convert.ToBase64String(encryptor.TransformFinalBlock(inputMessage, 0, inputMessage.Length));
                }

                encryptedMessage.EncryptionData = encryptionData;
                return(JsonConvert.SerializeObject(encryptedMessage));
            }
        }
Esempio n. 16
0
        /// <summary>
        /// Initializes a new instance of the <see cref="CloudBlobClient"/> class.
        /// </summary>
        /// <param name="usePathStyleUris">True to use path style Uris.</param>
        /// <param name="baseUri">The Blob service endpoint to use to create the client.</param>
        /// <param name="credentials">The account credentials.</param>
        internal CloudBlobClient(bool?usePathStyleUris, Uri baseUri, StorageCredentials credentials)
        {
            CommonUtility.AssertNotNull("baseUri", baseUri);

            if (credentials == null)
            {
                credentials = new StorageCredentials();
            }

            if (baseUri == null)
            {
                throw new ArgumentNullException("baseUri");
            }

            if (!baseUri.IsAbsoluteUri)
            {
                string errorMessage = string.Format(CultureInfo.CurrentCulture, SR.RelativeAddressNotPermitted, baseUri.ToString());
                throw new ArgumentException(errorMessage, "baseUri");
            }

            this.BaseUri              = baseUri;
            this.Credentials          = credentials;
            this.RetryPolicy          = new ExponentialRetry();
            this.ServerTimeout        = Constants.DefaultServerSideTimeout;
            this.DefaultDelimiter     = NavigationHelper.Slash;
            this.AuthenticationScheme = AuthenticationScheme.SharedKey;

            if (usePathStyleUris.HasValue)
            {
                this.UsePathStyleUris = usePathStyleUris.Value;
            }
            else
            {
                // Automatically decide whether to use host style uri or path style uri
                this.UsePathStyleUris = CommonUtility.UsePathStyleAddressing(this.BaseUri);
            }
        }
Esempio n. 17
0
        /// <summary>
        /// Tries to translate the specified exception into a storage exception.
        /// Note: we can probably combine this with the above CoreTranslate, this doesn't need to be async.
        /// </summary>
        /// <param name="ex">The exception to translate.</param>
        /// <param name="reqResult">The request result.</param>
        /// <param name="parseError">The delegate used to parse the error to get extended error information.</param>
        /// <returns>The storage exception or <c>null</c>.</returns>
        private static StorageException CoreTranslateAsync(Exception ex, RequestResult reqResult, CancellationToken token)
        {
            CommonUtility.AssertNotNull("reqResult", reqResult);
            CommonUtility.AssertNotNull("ex", ex);

            // Dont re-wrap storage exceptions
            if (ex is StorageException)
            {
                return((StorageException)ex);
            }
            else if (ex is TimeoutException)
            {
                reqResult.HttpStatusMessage        = null;
                reqResult.HttpStatusCode           = (int)HttpStatusCode.RequestTimeout;
                reqResult.ExtendedErrorInformation = null;
                return(new StorageException(reqResult, ex.Message, ex));
            }
            else if (ex is ArgumentException)
            {
                reqResult.HttpStatusMessage        = null;
                reqResult.HttpStatusCode           = (int)HttpStatusCode.Unused;
                reqResult.ExtendedErrorInformation = null;
                return(new StorageException(reqResult, ex.Message, ex)
                {
                    IsRetryable = false
                });
            }
            else if (ex is OperationCanceledException)
            {
                reqResult.HttpStatusMessage        = null;
                reqResult.HttpStatusCode           = 306; // unused
                reqResult.ExtendedErrorInformation = null;
                return(new StorageException(reqResult, ex.Message, ex));
            }
            // return null and check in the caller
            return(null);
        }
Esempio n. 18
0
        /// <summary>
        /// Reads the bytes from the current stream and writes them to another stream. This method writes directly to the destination stream,
        /// rather than copying the data into a temporary buffer.
        /// </summary>
        /// <param name="destination">The stream to which the contents of the current stream will be copied.</param>
        /// <param name="expiryTime">A DateTime indicating the expiry time.</param>
        public void FastCopyTo(Stream destination, DateTime?expiryTime)
        {
            CommonUtility.AssertNotNull("destination", destination);

            // Maximum amount you can read is from current spot to the end.
            long leftToRead = this.Length - this.Position;

            try
            {
                while (leftToRead != 0)
                {
                    if (expiryTime.HasValue && DateTime.Now.CompareTo(expiryTime.Value) > 0)
                    {
                        throw new TimeoutException();
                    }

                    ArraySegment <byte> currentBlock = this.GetCurrentBlock();

                    // Copy the block
                    int blockReadLength = (int)Math.Min(leftToRead, currentBlock.Count);
                    destination.Write(currentBlock.Array, currentBlock.Offset, blockReadLength);

                    this.AdvancePosition(ref leftToRead, blockReadLength);
                }
            }
            catch (Exception)
            {
                if (expiryTime.HasValue && DateTime.Now.CompareTo(expiryTime.Value) > 0)
                {
                    throw new TimeoutException();
                }
                else
                {
                    throw;
                }
            }
        }
Esempio n. 19
0
        /// <summary>
        /// Gets the directory's properties from the response.
        /// </summary>
        /// <param name="response">The web response.</param>
        /// <returns>The directory's attributes.</returns>
        public static FileDirectoryProperties GetProperties(HttpResponseMessage response)
        {
            CommonUtility.AssertNotNull("response", response);

            // Set the directory properties
            FileDirectoryProperties directoryProperties = new FileDirectoryProperties();

            directoryProperties.ETag = (response.Headers.ETag == null) ? null :
                                       response.Headers.ETag.ToString();
            string directoryEncryption = response.Headers.GetHeaderSingleValueOrDefault(Constants.HeaderConstants.ServerEncrypted);

            directoryProperties.IsServerEncrypted = string.Equals(directoryEncryption, Constants.HeaderConstants.TrueHeader, StringComparison.OrdinalIgnoreCase);

            if (response.Content != null)
            {
                directoryProperties.LastModified = response.Content.Headers.LastModified;
            }
            else
            {
                directoryProperties.LastModified = null;
            }

            return(directoryProperties);
        }
Esempio n. 20
0
        internal IEnumerable <TResult> Execute <TResult>(CloudTableClient client, string tableName, EntityResolver <TResult> resolver, TableRequestOptions requestOptions, OperationContext operationContext)
        {
            CommonUtility.AssertNotNullOrEmpty("tableName", tableName);
            CommonUtility.AssertNotNull("resolver", resolver);

            TableRequestOptions modifiedOptions = TableRequestOptions.ApplyDefaults(requestOptions, client);

            operationContext = operationContext ?? new OperationContext();

            IEnumerable <TResult> enumerable =
                CommonUtility.LazyEnumerable <TResult>(
                    (continuationToken) =>
            {
                TableQuerySegment <TResult> seg = CommonUtility.RunWithoutSynchronizationContext(() => this.ExecuteQuerySegmentedAsync((TableContinuationToken)continuationToken, client, tableName, resolver, modifiedOptions, operationContext).Result);

                return(new ResultSegment <TResult>(seg.Results)
                {
                    ContinuationToken = seg.ContinuationToken
                });
            },
                    this.takeCount.HasValue ? this.takeCount.Value : long.MaxValue);

            return(enumerable);
        }
Esempio n. 21
0
        /// <summary>
        /// Asynchronously reads a sequence of bytes from the current stream, advances the
        /// position within the stream by the number of bytes read, and monitors cancellation requests.
        /// </summary>
        /// <remarks>In the returned <see cref="Task{TElement}"/> object, the value of the integer
        /// parameter contains the total number of bytes read into the buffer. The result value can be
        /// less than the number of bytes requested if the number of bytes currently available is less
        /// than the requested number, or it can be 0 (zero) if the end of the stream has been reached.</remarks>
        /// <param name="buffer">The buffer to read the data into.</param>
        /// <param name="offset">The byte offset in buffer at which to begin writing
        /// data read from the stream.</param>
        /// <param name="count">The maximum number of bytes to read.</param>
        /// <param name="cancellationToken">The token to monitor for cancellation requests.</param>
        /// <returns>A task that represents the asynchronous read operation.</returns>
        public override async Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
        {
            CommonUtility.AssertNotNull("buffer", buffer);
            CommonUtility.AssertInBounds("offset", offset, 0, buffer.Length);
            CommonUtility.AssertInBounds("count", count, 0, buffer.Length - offset);

            if (this.lastException != null)
            {
                throw this.lastException;
            }

            if ((this.currentOffset == this.Length) || (count == 0))
            {
                return 0;
            }

            int readCount = this.ConsumeBuffer(buffer, offset, count);
            if (readCount > 0)
            {
                return readCount;
            }

            return await this.DispatchReadAsync(buffer, offset, count);
        }
Esempio n. 22
0
        /// <summary>
        /// Generates a <see cref="RESTCommand"/> for changing a lease ID.
        /// </summary>
        /// <param name="blob">The blob object that is calling this method.</param>
        /// <param name="attributes">The blob's attributes.</param>
        /// <param name="proposedLeaseId">The proposed new lease ID.</param>
        /// <param name="accessCondition">An object that represents the access conditions for the blob. If null, no condition is used.</param>
        /// <param name="options">An object that specifies additional options for the request.</param>
        /// <returns>A <see cref="RESTCommand"/> implementing the change lease ID operation.</returns>
        internal static RESTCommand <string> ChangeLeaseImpl(ICloudBlob blob, BlobAttributes attributes, string proposedLeaseId, AccessCondition accessCondition, BlobRequestOptions options)
        {
            CommonUtility.AssertNotNull("accessCondition", accessCondition);
            CommonUtility.AssertNotNull("proposedLeaseId", proposedLeaseId);
            if (accessCondition.LeaseId == null)
            {
                throw new ArgumentException(SR.MissingLeaseIDChanging, "accessCondition");
            }

            RESTCommand <string> putCmd = new RESTCommand <string>(blob.ServiceClient.Credentials, attributes.StorageUri);

            options.ApplyToStorageCommand(putCmd);
            putCmd.Handler            = blob.ServiceClient.AuthenticationHandler;
            putCmd.BuildClient        = HttpClientFactory.BuildHttpClient;
            putCmd.BuildRequest       = (cmd, uri, builder, cnt, serverTimeout, ctx) => BlobHttpRequestMessageFactory.Lease(uri, serverTimeout, LeaseAction.Change, proposedLeaseId, null /* leaseDuration */, null /* leaseBreakPeriod */, accessCondition, cnt, ctx);
            putCmd.PreProcessResponse = (cmd, resp, ex, ctx) =>
            {
                HttpResponseParsers.ProcessExpectedStatusCodeNoException(HttpStatusCode.OK, resp, null /* retVal */, cmd, ex);
                CloudBlobSharedImpl.UpdateETagLMTAndSequenceNumber(attributes, resp);
                return(BlobHttpResponseParsers.GetLeaseId(resp));
            };

            return(putCmd);
        }
        /// <summary>
        /// Generates XML representing the given static website properties.
        /// </summary>
        /// <param name="staticWebsiteProperties">The static website properties.</param>
        /// <returns>An XML element corresponding to the input properties.</returns>
        private static XElement GenerateStaticWebsitePropertiesXml(StaticWebsiteProperties staticWebsiteProperties)
        {
            CommonUtility.AssertNotNull("staticWebsiteProperties", staticWebsiteProperties);

            bool     enabled = staticWebsiteProperties.Enabled;
            XElement xml     = new XElement(StaticWebsiteName, new XElement(StaticWebsiteEnabledName, enabled));

            if (!enabled)
            {
                return(xml);
            }

            if (!string.IsNullOrWhiteSpace(staticWebsiteProperties.IndexDocument))
            {
                xml.Add(new XElement(StaticWebsiteIndexDocumentName, staticWebsiteProperties.IndexDocument));
            }

            if (!string.IsNullOrWhiteSpace(staticWebsiteProperties.ErrorDocument404Path))
            {
                xml.Add(new XElement(StaticWebsiteErrorDocument404PathName, staticWebsiteProperties.ErrorDocument404Path));
            }

            return(xml);
        }
Esempio n. 24
0
        internal KeyRotationEntity(DynamicTableEntity dte)
        {
            CommonUtility.AssertNotNull("properties", dte.Properties);

            // Store the information about this entity.  Make a copy of the properties list, in case the caller decides to reuse the list.
            this.PartitionKey = dte.PartitionKey;
            this.RowKey       = dte.RowKey;
            this.Timestamp    = dte.Timestamp;
            this.ETag         = dte.ETag;
            if (!dte.Properties.ContainsKey(Constants.EncryptionConstants.TableEncryptionKeyDetails))
            {
                // This should only be possible if RequireEncryption is true, otherwise the entity would have been filtered out in the query.
                throw new InvalidOperationException(SR.KeyRotationNoEncryptionMetadata);
            }
            else
            {
                this.encryptionMetadataJson = dte.Properties[Constants.EncryptionConstants.TableEncryptionKeyDetails].StringValue;
            }
            Dictionary <string, EntityProperty> properties = new Dictionary <string, EntityProperty>(dte.Properties);

            properties.Remove(Constants.EncryptionConstants.TableEncryptionKeyDetails);
            properties.Remove(Constants.EncryptionConstants.TableEncryptionPropertyDetails);
            this.Properties = new System.Collections.ObjectModel.ReadOnlyDictionary <string, EntityProperty>(properties);
        }
        /// <summary>
        /// Constructs a web request to return a specified range of the file's content, together with its properties and metadata.
        /// </summary>
        /// <param name="uri">The absolute URI to the file.</param>
        /// <param name="timeout">The server timeout interval, in seconds.</param>
        /// <param name="offset">The byte offset at which to begin returning content.</param>
        /// <param name="count">The number of bytes to return, or null to return all bytes through the end of the file.</param>
        /// <param name="shareSnapshot">A <see cref="DateTimeOffset"/> specifying the share snapshot timestamp, if the share is a snapshot.</param>
        /// <param name="accessCondition">The access condition to apply to the request.</param>
        /// <returns>A web request to use to perform the operation.</returns>
        public static StorageRequestMessage Get(Uri uri, int?timeout, long?offset, long?count, bool rangeContentMD5, DateTimeOffset?shareSnapshot, AccessCondition accessCondition, HttpContent content, OperationContext operationContext, ICanonicalizer canonicalizer, StorageCredentials credentials)
        {
            if (offset.HasValue && offset.Value < 0)
            {
                CommonUtility.ArgumentOutOfRange("offset", offset);
            }

            if (offset.HasValue && rangeContentMD5)
            {
                CommonUtility.AssertNotNull("count", count);
                CommonUtility.AssertInBounds("count", count.Value, 1, Constants.MaxRangeGetContentMD5Size);
            }

            StorageRequestMessage request = Get(uri, timeout, shareSnapshot, accessCondition, content, operationContext, canonicalizer, credentials);

            AddRange(request, offset, count);

            if (offset.HasValue && rangeContentMD5)
            {
                request.Headers.Add(Constants.HeaderConstants.RangeContentMD5Header, Constants.HeaderConstants.TrueHeader);
            }

            return(request);
        }
        /// <summary>
        /// Constructs a web request to return a specified range of the blob's content, together with its properties and metadata.
        /// </summary>
        /// <param name="uri">The absolute URI to the blob.</param>
        /// <param name="timeout">The server timeout interval, in seconds.</param>
        /// <param name="snapshot">The snapshot version, if the blob is a snapshot.</param>
        /// <param name="offset">The byte offset at which to begin returning content.</param>
        /// <param name="count">The number of bytes to return, or null to return all bytes through the end of the blob.</param>
        /// <param name="accessCondition">The access condition to apply to the request.</param>
        /// <returns>A web request to use to perform the operation.</returns>
        public static HttpRequestMessage Get(Uri uri, int?timeout, DateTimeOffset?snapshot, long?offset, long?count, bool rangeContentMD5, AccessCondition accessCondition, HttpContent content, OperationContext operationContext)
        {
            if (offset.HasValue && offset.Value < 0)
            {
                CommonUtility.ArgumentOutOfRange("offset", offset);
            }

            if (offset.HasValue && rangeContentMD5)
            {
                CommonUtility.AssertNotNull("count", count);
                CommonUtility.AssertInBounds("count", count.Value, 1, Constants.MaxBlockSize);
            }

            HttpRequestMessage request = Get(uri, timeout, snapshot, accessCondition, content, operationContext);

            AddRange(request, offset, count);

            if (offset.HasValue && rangeContentMD5)
            {
                request.Headers.Add(Constants.HeaderConstants.RangeContentMD5Header, Constants.HeaderConstants.TrueHeader);
            }

            return(request);
        }
Esempio n. 27
0
        /// <summary>
        /// Constructs a web request to set system properties for a directory.
        /// </summary>
        /// <param name="uri">The absolute URI to the file.</param>
        /// <param name="timeout">The server timeout interval.</param>
        /// <param name="properties">The directory's properties.</param>
        /// <param name="filePermissionToSet">The file's file permission</param>
        /// <param name="content">HttpContent for the request</param>
        /// <param name="operationContext">An <see cref="OperationContext" /> object for tracking the current operation.</param>
        /// <param name="canonicalizer">A canonicalizer that converts HTTP request data into a standard form appropriate for signing.</param>
        /// <param name="credentials">A <see cref="StorageCredentials"/> object providing credentials for the request.</param>
        /// <returns>A web request to use to perform the operation.</returns>
        public static StorageRequestMessage SetProperties(
            Uri uri,
            int?timeout,
            FileDirectoryProperties properties,
            string filePermissionToSet,
            HttpContent content,
            OperationContext operationContext,
            ICanonicalizer canonicalizer,
            StorageCredentials credentials)
        {
            CommonUtility.AssertNotNull("properties", properties);
            UriQueryBuilder builder = GetDirectoryUriQueryBuilder();

            builder.Add(Constants.QueryConstants.Component, "properties");

            StorageRequestMessage request = HttpRequestMessageFactory.CreateRequestMessage(HttpMethod.Put, uri, timeout, builder, content, operationContext, canonicalizer, credentials);

            AddFilePermissionOrFilePermissionKey(request, filePermissionToSet, properties, Constants.HeaderConstants.Preserve);
            AddNtfsFileAttributes(request, properties, Constants.HeaderConstants.Preserve);
            AddCreationTime(request, properties, Constants.HeaderConstants.Preserve);
            AddLastWriteTime(request, properties, Constants.HeaderConstants.Preserve);

            return(request);
        }
        protected override SharedAccessTablePolicy ParseElement(XElement accessPolicyElement)
        {
            CommonUtility.AssertNotNull("accessPolicyElement", accessPolicyElement);
            SharedAccessTablePolicy sharedAccessTablePolicy = new SharedAccessTablePolicy();
            string text = (string)accessPolicyElement.Element("Start");

            if (!string.IsNullOrEmpty(text))
            {
                sharedAccessTablePolicy.SharedAccessStartTime = Uri.UnescapeDataString(text).ToUTCTime();
            }
            string text2 = (string)accessPolicyElement.Element("Expiry");

            if (!string.IsNullOrEmpty(text2))
            {
                sharedAccessTablePolicy.SharedAccessExpiryTime = Uri.UnescapeDataString(text2).ToUTCTime();
            }
            string text3 = (string)accessPolicyElement.Element("Permission");

            if (!string.IsNullOrEmpty(text3))
            {
                sharedAccessTablePolicy.Permissions = SharedAccessTablePolicy.PermissionsFromString(text3);
            }
            return(sharedAccessTablePolicy);
        }
Esempio n. 29
0
        /// <summary>
        /// Initializes a new instance of the <see cref="FileProperties"/> class based on an existing instance.
        /// </summary>
        /// <param name="other">The set of file properties to clone.</param>
        public FileProperties(FileProperties other)
        {
            CommonUtility.AssertNotNull("other", other);

            this.ContentType           = other.ContentType;
            this.ContentDisposition    = other.ContentDisposition;
            this.ContentEncoding       = other.ContentEncoding;
            this.ContentLanguage       = other.ContentLanguage;
            this.CacheControl          = other.CacheControl;
            this.ContentChecksum.MD5   = other.ContentChecksum.MD5;
            this.ContentChecksum.CRC64 = other.ContentChecksum.CRC64;
            this.Length                 = other.Length;
            this.ETag                   = other.ETag;
            this.LastModified           = other.LastModified;
            this.IsServerEncrypted      = other.IsServerEncrypted;
            this.filePermissionKey      = other.filePermissionKey;
            this.ntfsAttributes         = other.ntfsAttributes;
            this.creationTime           = other.creationTime;
            this.lastWriteTime          = other.lastWriteTime;
            this.filePermissionKeyToSet = other.filePermissionKeyToSet;
            this.ntfsAttributesToSet    = other.ntfsAttributesToSet;
            this.creationTimeToSet      = other.creationTimeToSet;
            this.lastWriteTimeToSet     = other.lastWriteTimeToSet;
        }
Esempio n. 30
0
        /// <summary>
        /// Constructs a web request to set system properties for a file.
        /// </summary>
        /// <param name="uri">The absolute URI to the file.</param>
        /// <param name="timeout">The server timeout interval.</param>
        /// <param name="properties">The file's properties.</param>
        /// <param name="filePermissionToSet">The file's file permission</param>
        /// <param name="accessCondition">The access condition to apply to the request.</param>
        /// <param name="content">HttpContent for the request</param>
        /// <param name="operationContext">An <see cref="OperationContext" /> object for tracking the current operation.</param>
        /// <param name="canonicalizer">A canonicalizer that converts HTTP request data into a standard form appropriate for signing.</param>
        /// <param name="credentials">A <see cref="StorageCredentials"/> object providing credentials for the request.</param>
        /// <returns>A web request to use to perform the operation.</returns>
        public static StorageRequestMessage SetProperties(
            Uri uri,
            int?timeout,
            FileProperties properties,
            string filePermissionToSet,
            AccessCondition accessCondition,
            HttpContent content,
            OperationContext operationContext,
            ICanonicalizer canonicalizer,
            StorageCredentials credentials)
        {
            CommonUtility.AssertNotNull("properties", properties);
            UriQueryBuilder builder = new UriQueryBuilder();

            builder.Add(Constants.QueryConstants.Component, "properties");

            StorageRequestMessage request = HttpRequestMessageFactory.CreateRequestMessage(HttpMethod.Put, uri, timeout, builder, content, operationContext, canonicalizer, credentials);

            if (properties != null)
            {
                request.AddOptionalHeader(Constants.HeaderConstants.FileCacheControlHeader, properties.CacheControl);
                request.AddOptionalHeader(Constants.HeaderConstants.FileContentDispositionRequestHeader, properties.ContentDisposition);
                request.AddOptionalHeader(Constants.HeaderConstants.FileContentEncodingHeader, properties.ContentEncoding);
                request.AddOptionalHeader(Constants.HeaderConstants.FileContentLanguageHeader, properties.ContentLanguage);
                request.AddOptionalHeader(Constants.HeaderConstants.FileContentTypeHeader, properties.ContentType);
                request.ApplyFileContentChecksumHeaders(properties.ContentChecksum);
            }

            AddFilePermissionOrFilePermissionKey(request, filePermissionToSet, properties, Constants.HeaderConstants.Preserve);
            AddNtfsFileAttributes(request, properties, Constants.HeaderConstants.Preserve);
            AddCreationTime(request, properties, Constants.HeaderConstants.Preserve);
            AddLastWriteTime(request, properties, Constants.HeaderConstants.Preserve);

            request.ApplyAccessCondition(accessCondition);
            return(request);
        }