/// <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="groupPolicyIdentifier">An optional identifier for the policy.</param>
        /// <param name="resourceType">Either "b" for blobs or "c" for containers.</param>
        /// <param name="signature">The signature to use.</param>
        /// <returns>The finished query builder.</returns>
        internal static UriQueryBuilder GetShareAccessSignatureImpl(
            SharedAccessPolicy policy,
            string groupPolicyIdentifier,
            string resourceType,
            string signature)
        {
            CommonUtils.AssertNotNull("policy", policy);
            CommonUtils.AssertNotNullOrEmpty("resourceType", resourceType);
            CommonUtils.AssertNotNull("signature", signature);

            UriQueryBuilder builder = new UriQueryBuilder();

            // FUTURE blob for blob and container for container
            string permissions = SharedAccessPolicy.PermissionsToString(policy.Permissions);
            if (String.IsNullOrEmpty(permissions))
            {
                permissions = null;
            }

            AddEscapedIfNotNull(builder, Constants.QueryConstants.SignedStart, GetDateTimeOrNull(policy.SharedAccessStartTime));
            AddEscapedIfNotNull(builder, Constants.QueryConstants.SignedExpiry, GetDateTimeOrNull(policy.SharedAccessExpiryTime));
            builder.Add(Constants.QueryConstants.SignedResource, resourceType);
            AddEscapedIfNotNull(builder, Constants.QueryConstants.SignedPermissions, permissions);
            AddEscapedIfNotNull(builder, Constants.QueryConstants.SignedIdentifier, groupPolicyIdentifier);
            AddEscapedIfNotNull(builder, Constants.QueryConstants.Signature, signature);

            return builder;
        }
        /// <summary>
        /// Get the signature hash embedded inside the Shared Access Signature.
        /// </summary>
        /// <param name="policy">The shared access policy to hash.</param>
        /// <param name="groupPolicyIdentifier">An optional identifier for the policy.</param>
        /// <param name="resourceName">The canonical resource string, unescaped.</param>
        /// <param name="client">The client whose credentials are to be used for signing.</param>
        /// <returns>The signed hash.</returns>
        internal static string GetSharedAccessSignatureHashImpl(
            SharedAccessPolicy policy,
            string groupPolicyIdentifier,
            string resourceName,
            CloudBlobClient client)
        {
            CommonUtils.AssertNotNull("policy", policy);
            CommonUtils.AssertNotNullOrEmpty("resourceName", resourceName);
            CommonUtils.AssertNotNull("client", client);

            ////StringToSign = signedpermissions + "\n"
            ////               signedstart + "\n"
            ////               signedexpiry + "\n"
            ////               canonicalizedresource + "\n"
            ////               signedidentifier
            ////HMAC-SHA256(URL.Decode(UTF8.Encode(StringToSign)))

            string stringToSign = string.Format(
                "{0}\n{1}\n{2}\n{3}\n{4}",
                SharedAccessPolicy.PermissionsToString(policy.Permissions),
                GetDateTimeOrEmpty(policy.SharedAccessStartTime),
                GetDateTimeOrEmpty(policy.SharedAccessExpiryTime),
                resourceName,
                groupPolicyIdentifier);

            string signature = client.Credentials.ComputeHmac(stringToSign);

            return signature;
        }
 public PolicyView(string name, SharedAccessPolicy policy)
 {
     PolicyName = name;
     Policy = policy;
     StartTime = Policy.SharedAccessStartTime.ToString();
     ExpiryTime = Policy.SharedAccessExpiryTime.ToString();
 }
        public static string GenerateSAS(string containerName, string blobUri)
        {
            string res = null;

            if ((string.IsNullOrEmpty(containerName)) || (string.IsNullOrEmpty(blobUri)))
                throw new ArgumentException("Both container name and blob Uri must containt valid values");

            var storageAccount = CloudStorageAccount.FromConfigurationSetting("DataConnectionString");
            var blobClient = storageAccount.CreateCloudBlobClient();

            CloudBlobContainer container = blobClient.GetContainerReference(containerName);
            CloudBlob blob = blobClient.GetBlobReference(blobUri);
            container.CreateIfNotExist();

            try
            {
                BlobContainerPermissions permissions = new BlobContainerPermissions();
                // The container itself doesn't allow public access.
                permissions.PublicAccess = BlobContainerPublicAccessType.Off;
                // The container itself doesn't allow SAS access.
                SharedAccessPolicy containerPolicy = new SharedAccessPolicy() { Permissions = SharedAccessPermissions.None };
                permissions.SharedAccessPolicies.Clear();
                permissions.SharedAccessPolicies.Add("SASPolicy", containerPolicy);
                container.SetPermissions(permissions);
                // Generate an SAS for the blob.
                SharedAccessPolicy blobPolicy = new SharedAccessPolicy()
                {
                    Permissions = SharedAccessPermissions.Read,
                    SharedAccessExpiryTime = DateTime.UtcNow.AddDays(1d)
                };

                res = blob.GetSharedAccessSignature(blobPolicy, "SASPolicy");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            return res;
        }
 /// <summary>
 /// Returns a shared access signature for the blob.
 /// </summary>
 /// <param name="policy">The access policy for the shared access signature.</param>
 /// <returns>A shared access signature.</returns>
 /// <exception cref="InvalidOperationException">Thrown if the current credentials don't support creating a shared access signature.</exception>
 /// <exception cref="NotSupportedException">Thrown if blob is a snapshot.</exception>
 public string GetSharedAccessSignature(SharedAccessPolicy policy)
 {
     return this.GetSharedAccessSignature(policy, null);
 }
        private static void SetReadOnlySharedAccessPolicy(CloudBlobContainer container)
        {
            var blobSASExperiationTime = int.Parse(ConfigReader.GetConfigValue("BlobSASExperiationTime"), NumberStyles.Integer, CultureInfo.InvariantCulture);
            var permissions = container.GetPermissions();
            var options = new BlobRequestOptions
            {
                // Fail if someone else has already changed the container before we do.
                AccessCondition = AccessCondition.IfMatch(container.Properties.ETag)
            };
            var sharedAccessPolicy = new SharedAccessPolicy
            {
                Permissions = SharedAccessPermissions.Read,
                SharedAccessExpiryTime = DateTime.UtcNow + TimeSpan.FromDays(blobSASExperiationTime)
            };

            permissions.SharedAccessPolicies.Remove("readonly");
            permissions.SharedAccessPolicies.Add("readonly", sharedAccessPolicy);

            container.SetPermissions(permissions, options);
        }
 public static void TestBlobStorage8()
 {
     BlobUtilities BlobUtilities = new
     BlobUtilities("DefaultEndpointsProtocol=http;AccountName=" + YOURSTORAGEACCOUNT + ";AccountKey=" + YOURKEY + "");
     try
     {
         string signature = String.Empty;
         SharedAccessPolicy policy1 = new SharedAccessPolicy()
         {
             Permissions = SharedAccessPermissions.List | SharedAccessPermissions.Read |
             SharedAccessPermissions.Write | SharedAccessPermissions.Delete,
             SharedAccessStartTime = DateTime.UtcNow,
             SharedAccessExpiryTime = DateTime.UtcNow.AddHours(1)
         };
         Console.Write("Create shared access signature ");
         if (BlobUtilities.GenerateSharedAccessSignature("samplecontainer1", policy1, out signature))
             Console.WriteLine("true " + signature);
         else
             Console.WriteLine("false");
         Separator();
         signature = String.Empty;
         Console.Write("Create shared access signature from access policy ");
         if (BlobUtilities.GenerateSharedAccessSignature("samplecontainer1", "Policy1", out signature))
             Console.WriteLine("true " + signature);
         else
             Console.WriteLine("false");
         Separator();
         signature = String.Empty;
         Console.Write("Create shared access signature from access policy 2 ");
         if (BlobUtilities.GenerateSharedAccessSignature("samplecontainer1", "Policy2", out signature))
             Console.WriteLine("true " + signature);
         else
             Console.WriteLine("false");
         Separator();
     }
     catch (Exception ex)
     {
         Console.WriteLine("EXCEPTION " + ex.ToString());
     }
 }
 public static void TestBlobStorage7()
 {
     BlobUtilities BlobUtilities = new
     BlobUtilities("DefaultEndpointsProtocol=http;AccountName=" + YOURSTORAGEACCOUNT + ";AccountKey=" + YOURKEY + "");
     try
     {
         string accessLevel;
         // Get container access control.Return true on success, false if not found, throw exception on
         //error. Access level set to container|blob|private.
         Console.Write("Get container ACL ");
         if (BlobUtilities.GetContainerACL("samplecontainer1", out accessLevel))
             Console.WriteLine("true " + accessLevel);
         else
             Console.WriteLine("false");
         Separator();
         SortedList<string, SharedAccessPolicy> policies = new SortedList<string, SharedAccessPolicy>();
         SharedAccessPolicy policy1 = new SharedAccessPolicy()
         {
             Permissions = SharedAccessPermissions.List | SharedAccessPermissions.Read |
             SharedAccessPermissions.Write | SharedAccessPermissions.Delete,
             SharedAccessStartTime = DateTime.UtcNow,
             SharedAccessExpiryTime = DateTime.UtcNow.AddHours(1)
         };
         policies.Add("Policy1", policy1);
         policies.Add("Policy2", new SharedAccessPolicy()
         {
             Permissions = SharedAccessPermissions.Read,
             SharedAccessStartTime = DateTime.Parse("2010-01-01T09:38:05Z"),
             SharedAccessExpiryTime = DateTime.Parse("2012-12-31T09:38:05Z")
         });
         Console.Write("Set container access policy ");
         if (BlobUtilities.SetContainerAccessPolicy("samplecontainer1", policies))
             Console.WriteLine("true");
         else
             Console.WriteLine("false");
         Separator();
         Console.Write("Get container access policy ");
         if (BlobUtilities.GetContainerAccessPolicy("samplecontainer1", out policies))
         {
             Console.WriteLine("true");
             if (policies != null)
             {
                 foreach (KeyValuePair<string, SharedAccessPolicy> policy in policies)
                 {
                     Console.WriteLine("Policy " + policy.Key);
                 }
             }
         }
         else
             Console.WriteLine("false");
         Separator();
     }
     catch (Exception ex)
     {
         Console.WriteLine("EXCEPTION " + ex.ToString());
     }
 }
        private static void SetReadOnlySharedAccessPolicy(CloudBlobContainer container)
        {
            var permissions = container.GetPermissions();
            var options = new BlobRequestOptions
            {
                // Fail if someone else has already changed the container before we do.
                AccessCondition = AccessCondition.IfMatch(container.Properties.ETag)
            };
            var sharedAccessPolicy = new SharedAccessPolicy
            {
                Permissions = SharedAccessPermissions.Read,
                SharedAccessExpiryTime = DateTime.UtcNow + TimeSpan.FromDays(StorageServicesContext.Current.Configuration.BlobsSasExpirationTime)
            };

            permissions.SharedAccessPolicies.Remove("readonly");
            permissions.SharedAccessPolicies.Add("readonly", sharedAccessPolicy);

            container.SetPermissions(permissions, options);
        }
 public static void TestBlobStorage8()
 {
     BlobUtilities blobUtilities = new BlobUtilities(CONNECTION_STRING);
     try
     {
         string signature = String.Empty;
         SharedAccessPolicy policy1 = new SharedAccessPolicy()
         {
             Permissions = SharedAccessPermissions.List | SharedAccessPermissions.Read |
             SharedAccessPermissions.Write | SharedAccessPermissions.Delete,
             SharedAccessStartTime = DateTime.UtcNow,
             SharedAccessExpiryTime = DateTime.UtcNow.AddHours(1)
         };
         Console.Write("Create shared access signature ");
         if (blobUtilities.GenerateSharedAccessSignature("samplecontainer1", policy1, out signature))
             Console.WriteLine("true " + signature);
         else
             Console.WriteLine("false");
         Separator();
         signature = String.Empty;
         Console.Write("Create shared access signature from access policy ");
         if (blobUtilities.GenerateSharedAccessSignature("samplecontainer1", "Policy1", out signature))
             Console.WriteLine("true " + signature);
         else
             Console.WriteLine("false");
         Separator();
         signature = String.Empty;
         Console.Write("Create shared access signature from access policy 2 ");
         if (blobUtilities.GenerateSharedAccessSignature("samplecontainer1", "Policy2", out signature))
             Console.WriteLine("true " + signature);
         else
             Console.WriteLine("false");
         Separator();
     }
     catch (Exception ex)
     {
         Console.WriteLine("EXCEPTION " + ex.ToString());
     }
 }
 internal bool GenerateSharedAccessSignature(string containerName, SharedAccessPolicy policy, out string signature)
 {
     try
     {
         var container = _client.GetContainerReference(containerName);
         signature = container.GetSharedAccessSignature(policy);
         return true;
     }
     catch (StorageClientException)
     {
         signature = null;
         return false;
     }
 }
        /// <summary>Returns a shared access signature for the container.</summary>
        /// <param name="policy">The access policy for the shared access signature. </param>
        /// <param name="groupPolicyIdentifier">A container-level access policy. </param>
        /// <returns>A shared access signature. </returns>
        public string GetSharedAccessSignature(SharedAccessPolicy policy, string groupPolicyIdentifier)
        {
            if (!this.ServiceClient.Credentials.CanSignRequest)
            {
                var errorMessage = string.Format(CultureInfo.CurrentCulture, SR.CannotCreateSASWithoutAccountKey);
                throw new InvalidOperationException(errorMessage);
            }

            var resourceName = this.GetSharedAccessCanonicalName();

            var signature = SharedAccessSignatureHelper.GetSharedAccessSignatureHashImpl(
                policy, groupPolicyIdentifier, resourceName, this.ServiceClient);

            // Future resource type changes from "c" => "container"
            var builder = SharedAccessSignatureHelper.GetShareAccessSignatureImpl(
                policy, groupPolicyIdentifier, "c", signature);

            return builder.ToString();
        }
 public bool GenerateSharedAccessSignature(string samplecontainer1, SharedAccessPolicy policy1, out string signature) // 1de2
 {
     throw new NotImplementedException();
 }
        public string GenerateSharedAccessSignature(string containerName, string blobName, 
            bool read, bool write, bool delete, bool list, DateTime startTime, DateTime endTime)
        {
            CloudBlobClient client = CloudStorageAccount.CreateCloudBlobClient();
            client.RetryPolicy = RetryPolicies.Retry(20, TimeSpan.Zero);
            CloudBlobContainer container = client.GetContainerReference(containerName);

            string path;

            if (string.IsNullOrEmpty(blobName))
            {
                path = container.Attributes.Uri.AbsoluteUri;
            }
            else
            {
                CloudBlob blob = container.GetBlobReference(blobName);
                path = blob.Attributes.Uri.AbsoluteUri;
            }

            SharedAccessPermissions permissions = new SharedAccessPermissions();
            if (read) permissions |= SharedAccessPermissions.Read;
            if (write) permissions |= SharedAccessPermissions.Write;
            if (delete) permissions |= SharedAccessPermissions.Delete;
            if (list) permissions |= SharedAccessPermissions.List;

            SharedAccessPolicy policy = new SharedAccessPolicy()
            {
                Permissions = permissions,
                SharedAccessStartTime = startTime,
                SharedAccessExpiryTime = endTime
            };

            string queryString = container.GetSharedAccessSignature(policy);

            return path + queryString;
        }
        /// <summary>
        /// Returns a shared access signature for the blob.
        /// </summary>
        /// <param name="policy">The access policy for the shared access signature.</param>
        /// <param name="groupPolicyIdentifier">A container-level access policy.</param>
        /// <returns>A shared access signature.</returns>
        /// <exception cref="InvalidOperationException">Thrown if the current credentials don't support creating a shared access signature.</exception>
        /// <exception cref="NotSupportedException">Thrown if blob is a snapshot.</exception>
        public string GetSharedAccessSignature(SharedAccessPolicy policy, string groupPolicyIdentifier)
        {
            if (!this.ServiceClient.Credentials.CanSignRequest)
            {
                string errorMessage = string.Format(CultureInfo.CurrentCulture, SR.CannotCreateSASWithoutAccountKey);
                throw new InvalidOperationException(errorMessage);
            }

            if (this.SnapshotTime != null)
            {
                string errorMessage = string.Format(CultureInfo.CurrentCulture, SR.CannotCreateSASForSnapshot);
                throw new NotSupportedException(errorMessage);
            }

            string resourceName = this.GetCanonicalName(true);

            string signature = SharedAccessSignatureHelper.GetSharedAccessSignatureHashImpl(policy, groupPolicyIdentifier, resourceName, this.ServiceClient);

            // Future resource type changes from "b" => "blob"
            var builder = SharedAccessSignatureHelper.GetShareAccessSignatureImpl(policy, groupPolicyIdentifier, "b", signature);

            return builder.ToString();
        }
        // Generate a shared access signature for a policy.
        // Return true on success, false if not found, throw exception on error.
        public bool GenerateSharedAccessSignature(string containerName, SharedAccessPolicy policy, out string signature)
        {
            signature = null;

            try
            {
                CloudBlobContainer container = BlobClient.GetContainerReference(containerName);
                signature = container.GetSharedAccessSignature(policy);
                return true;
            }
            catch (StorageClientException ex)
            {
                if ((int)ex.StatusCode == 404)
                {
                    return false;
                }

                throw;
            }
        }
        public Expense GetExpenseById(string username, string expenseId)
        {
            var context = new ExpenseDataContext(this.account) { MergeOption = MergeOption.NoTracking };

            string expenseRowKey = KeyGenerator.ExpenseEntityRowKey(expenseId);
            char charAfterSeparator = Convert.ToChar((Convert.ToInt32('_') + 1));
            var nextExpenseRowId = expenseRowKey + charAfterSeparator;
            string expenseItemRowKey = string.Format(CultureInfo.InvariantCulture, "{0}{1}", ExpenseItemEntity.RowKeyPrefix, expenseId);
            var nextExpenseItemRowId = expenseItemRowKey + charAfterSeparator;
            // TODO: Update to only have to compare to the expense id key and not the entire row
            var expenseQuery = (from e in context.ExpenseExpenseItem
                                where e.PartitionKey == username.EncodePartitionAndRowKey()
                                      && ((e.RowKey.CompareTo(expenseRowKey) >= 0
                                           && e.RowKey.CompareTo(nextExpenseRowId) < 0)
                                          || (e.RowKey.CompareTo(expenseItemRowKey) >= 0
                                              && e.RowKey.CompareTo(nextExpenseItemRowId) < 0))
                                select e).AsTableServiceQuery();

            Expense expense = null;
            var items = new List<ExpenseItem>();
            try
            {
                foreach (var entity in expenseQuery.Execute())
                {
                    switch (entity.ToEnum<TableKinds>())
                    {
                        case TableKinds.Expense:
                            expense = entity.ToKind<IExpenseEntity>().ToModel();
                            break;
                        case TableKinds.ExpenseItem:
                            items.Add(entity.ToKind<IExpenseItemEntity>().ToModel());
                            break;
                    }
                }
            }
            catch (InvalidOperationException e)
            {
                Log.Write(EventKind.Error, e.Message);
                throw;
            }

            if (expense == null)
            {
                return expense;
            }

            items.ForEach(x => expense.Details.Add(x));

            var policy = new SharedAccessPolicy
                             {
                                 Permissions = SharedAccessPermissions.Read,
                                 SharedAccessExpiryTime = DateTime.UtcNow + this.sharedSignatureValiditySpan
                             };
            var client = this.account.CreateCloudBlobClient();
            var container = client.GetContainerReference(AzureStorageNames.ReceiptContainerName);
            foreach (var item in expense.Details)
            {
                if (item.ReceiptUrl != null)
                {
                    CloudBlob receiptBlob = container.GetBlobReference(item.ReceiptUrl.ToString());
                    item.ReceiptUrl = new Uri(item.ReceiptUrl.AbsoluteUri + receiptBlob.GetSharedAccessSignature(policy));
                }
                else
                {
                    item.ReceiptUrl = new Uri("/Styling/Images/no_receipt.png", UriKind.Relative);
                }

                if (item.ReceiptThumbnailUrl != null)
                {
                    CloudBlob receiptThumbnailBlob = container.GetBlobReference(item.ReceiptThumbnailUrl.ToString());
                    item.ReceiptThumbnailUrl = new Uri(item.ReceiptThumbnailUrl.AbsoluteUri + receiptThumbnailBlob.GetSharedAccessSignature(policy));
                }
                else
                {
                    item.ReceiptThumbnailUrl = new Uri("/Styling/Images/no_receipt.png", UriKind.Relative);
                }
            }

            return expense;
        }