GetBlockBlobReference() public method

Returns a reference to a CloudBlockBlob with the specified address.
public GetBlockBlobReference ( string blobAddress ) : CloudBlockBlob
blobAddress string The absolute URI to the blob, or a relative URI beginning with the container name.
return CloudBlockBlob
Ejemplo n.º 1
1
        private static string GetBlobPath(HttpRequest request)
        {
            string hostName = request.Url.DnsSafeHost;
            if (hostName == "localdev")
            {
                hostName = "www.protonit.net";
            }
            string containerName = hostName.Replace('.', '-');
            string currServingFolder = "";
            try
            {
                // "/2013-03-20_08-27-28";
                CloudBlobClient publicClient = new CloudBlobClient("http://caloom.blob.core.windows.net/");
                string currServingPath = containerName + "/" + RenderWebSupport.CurrentToServeFileName;
                var currBlob = publicClient.GetBlockBlobReference(currServingPath);
                string currServingData = currBlob.DownloadText();
                string[] currServeArr = currServingData.Split(':');
                string currActiveFolder = currServeArr[0];
                var currOwner = VirtualOwner.FigureOwner(currServeArr[1]);
                InformationContext.Current.Owner = currOwner;
                currServingFolder = "/" + currActiveFolder;
            }
            catch
            {

            }
            return containerName + currServingFolder + request.Path;
        }
Ejemplo n.º 2
0
        private static void DeleteBlob(string packageUrl, string storageAccountName, string storageAccountKey)
        {
            OurTrace.TraceInfo(string.Format("Deleting blob {0}", packageUrl));

            var packageUri = new Uri(packageUrl);
            var baseAddress = packageUri.GetComponents(UriComponents.SchemeAndServer, UriFormat.UriEscaped);
            var credentials = new StorageCredentialsAccountAndKey(storageAccountName, storageAccountKey);

            var cloudBlobClient = new CloudBlobClient(baseAddress, credentials);
            var blobRef = cloudBlobClient.GetBlockBlobReference(packageUrl);
            blobRef.DeleteIfExists();
        }
Ejemplo n.º 3
0
        public void WriteData(string container, string blobName, string data)
        {
            StorageCredentialsAccountAndKey creds = new StorageCredentialsAccountAndKey(account, key);
            CloudBlobClient blobStorage = new CloudBlobClient(url, creds);

            // get blob container
            CloudBlobContainer blobContainer = blobStorage.GetContainerReference(container);
            if (blobContainer.CreateIfNotExist())
            {
                // configure container for public access
                var permissions = blobContainer.GetPermissions();
                permissions.PublicAccess = BlobContainerPublicAccessType.Container;
                blobContainer.SetPermissions(permissions);
            }

            CloudBlockBlob blob = blobStorage.GetBlockBlobReference(container + "/" + blobName);
            blob.UploadText(data);
        }
Ejemplo n.º 4
0
        public IEnumerable<CloudBlob> Translate(IExpression expression, CloudBlobClient blobClient, MediaFolder mediaFolder)
        {
            this.Visite(expression);

            if (!string.IsNullOrEmpty(fileName))
            {
                var blob = blobClient.GetBlockBlobReference(mediaFolder.GetMediaFolderItemPath(fileName));
                if (!blob.Exists())
                {
                    return new CloudBlob[] { };
                }
                blob.FetchAttributes();
                return new[] { blob };
            }
            else
            {
                var maxResult = 1000;
                if (Take.HasValue)
                {
                    maxResult = Take.Value;
                }
                var take = maxResult;

                var skip = 0;
                if (Skip.HasValue)
                {
                    skip = Skip.Value;
                    maxResult += skip;
                }
                var blobPrefix = mediaFolder.GetMediaFolderItemPath(prefix);

                if (string.IsNullOrEmpty(prefix))
                {
                    blobPrefix += "/";
                }

                return blobClient.ListBlobsWithPrefixSegmented(blobPrefix, maxResult, null, new BlobRequestOptions() { BlobListingDetails = Microsoft.WindowsAzure.StorageClient.BlobListingDetails.Metadata, UseFlatBlobListing = false })
                    .Results.Skip(skip).Select(it => it as CloudBlob).Take(take);
            }
        }
        private void MoveDirectory(CloudBlobClient blobClient, string newPrefix, string oldPrefix)
        {
            var blobs = blobClient.ListBlobsWithPrefix(oldPrefix,
                new BlobRequestOptions() { BlobListingDetails = Microsoft.WindowsAzure.StorageClient.BlobListingDetails.Metadata, UseFlatBlobListing = false });
            foreach (var blob in blobs)
            {
                if (blob is CloudBlobDirectory)
                {
                    var dir = blob as CloudBlobDirectory;

                    var names = dir.Uri.ToString().Split('/');
                    for (var i = names.Length - 1; i >= 0; i--)
                    {
                        if (!string.IsNullOrEmpty(names[i]))
                        {
                            MoveDirectory(blobClient, newPrefix + StorageNamesEncoder.EncodeBlobName(names[i]) + "/", oldPrefix + StorageNamesEncoder.EncodeBlobName(names[i]) + "/");
                            break;
                        }
                    }
                }
                else if (blob is CloudBlob)
                {
                    var cloudBlob = blob as CloudBlob;

                    if (cloudBlob.Exists())
                    {
                        cloudBlob.FetchAttributes();
                        var newContentBlob = blobClient.GetBlockBlobReference(newPrefix + cloudBlob.Metadata["FileName"]);
                        try
                        {
                            newContentBlob.CopyFromBlob(cloudBlob);
                        }
                        catch (Exception e)
                        {
                            using (Stream stream = new MemoryStream())
                            {
                                cloudBlob.DownloadToStream(stream);
                                stream.Position = 0;
                                newContentBlob.UploadFromStream(stream);
                                stream.Dispose();
                            }
                        }
                        newContentBlob.Metadata["FileName"] = cloudBlob.Metadata["FileName"];

                        if (!string.IsNullOrEmpty(cloudBlob.Metadata["UserId"]))
                        {
                            newContentBlob.Metadata["UserId"] = cloudBlob.Metadata["UserId"];
                        }
                        if (!string.IsNullOrEmpty(cloudBlob.Metadata["Published"]))
                        {
                            newContentBlob.Metadata["Published"] = cloudBlob.Metadata["Published"];
                        }
                        if (!string.IsNullOrEmpty(cloudBlob.Metadata["Size"]))
                        {
                            newContentBlob.Metadata["Size"] = cloudBlob.Metadata["Size"];
                        }
                        if (cloudBlob.Metadata.AllKeys.Contains("AlternateText"))
                        {
                            newContentBlob.Metadata["AlternateText"] = cloudBlob.Metadata["AlternateText"];
                        }
                        if (cloudBlob.Metadata.AllKeys.Contains("Description"))
                        {
                            newContentBlob.Metadata["Description"] = cloudBlob.Metadata["Description"];
                        }
                        if (cloudBlob.Metadata.AllKeys.Contains("Title"))
                        {
                            newContentBlob.Metadata["Title"] = cloudBlob.Metadata["Title"];
                        }

                        newContentBlob.SetMetadata();
                        cloudBlob.DeleteIfExists();
                    }
                }
            }
        }
Ejemplo n.º 6
0
        private void ProcessAnonymousRequest(HttpRequest request, HttpResponse response)
        {
            CloudBlobClient publicClient = new CloudBlobClient("http://caloom.blob.core.windows.net/");
            string blobPath = GetBlobPath(request);
            if (blobPath.Contains("/MediaContent/"))
            {
                int lastIndexOfSlash = blobPath.LastIndexOf('/');
                var strippedPath = blobPath.Substring(0, lastIndexOfSlash);
                int lastIndexOfMediaContent = strippedPath.LastIndexOf("/MediaContent/");
                if (lastIndexOfMediaContent > 0) // Still found MediaContent after stripping the last slash
                    blobPath = strippedPath;
            }
            if (blobPath.EndsWith("/"))
            {
                string redirectBlobPath = blobPath + "RedirectFromFolder.red";
                CloudBlob redirectBlob = publicClient.GetBlockBlobReference(redirectBlobPath);
                string redirectToUrl = null;
                try
                {
                    redirectToUrl = redirectBlob.DownloadText();
                }
                catch
                {

                }
                if (redirectToUrl != null)
                {
                    response.Redirect(redirectToUrl, true);
                    return;
                }
            }

            CloudBlockBlob blob = publicClient.GetBlockBlobReference(blobPath);
            response.Clear();
            try
            {
                HandlePublicBlobRequestWithCacheSupport(HttpContext.Current, blob, response);
                return;
                blob.FetchAttributes();
                response.ContentType = StorageSupport.GetMimeType(blob.Name);
                //response.Cache.SetETag(blob.Properties.ETag);
                response.AddHeader("ETag", blob.Properties.ETag);
                response.Cache.SetMaxAge(TimeSpan.FromMinutes(0));
                response.Cache.SetLastModified(blob.Properties.LastModifiedUtc);
                response.Cache.SetCacheability(HttpCacheability.Private);
                string ifModifiedSince = request.Headers["If-Modified-Since"];
                if (ifModifiedSince != null)
                {
                    DateTime ifModifiedSinceValue;
                    if (DateTime.TryParse(ifModifiedSince, out ifModifiedSinceValue))
                    {
                        ifModifiedSinceValue = ifModifiedSinceValue.ToUniversalTime();
                        if (blob.Properties.LastModifiedUtc <= ifModifiedSinceValue)
                        {
                            response.StatusCode = 304;
                            return;
                        }
                    }
                }
                response.ContentType = StorageSupport.GetMimeType(blob.Name);
                blob.DownloadToStream(response.OutputStream);
            } catch(StorageClientException scEx)
            {
                if (scEx.ErrorCode == StorageErrorCode.BlobNotFound || scEx.ErrorCode == StorageErrorCode.ResourceNotFound || scEx.ErrorCode == StorageErrorCode.BadRequest)
                {
                    response.Write("Blob not found or bad request: " + blob.Name + " (original path: " + request.Path + ")");
                    response.StatusCode = (int)scEx.StatusCode;
                }
                else
                {
                    response.Write("Errorcode: " + scEx.ErrorCode.ToString() + Environment.NewLine);
                    response.Write(scEx.ToString());
                    response.StatusCode = (int) scEx.StatusCode;
                }
            } finally
            {
                response.End();
            }
        }
Ejemplo n.º 7
0
        private void MoveDirectory(CloudBlobClient blobClient, string newPrefix, string oldPrefix)
        {
            var blobs = blobClient.ListBlobsWithPrefix(oldPrefix,
                new BlobRequestOptions() { BlobListingDetails = Microsoft.WindowsAzure.StorageClient.BlobListingDetails.Metadata, UseFlatBlobListing = false });
            foreach (var blob in blobs)
            {
                if (blob is CloudBlobDirectory)
                {
                    var dir = blob as CloudBlobDirectory;

                    var names = dir.Uri.ToString().Split('/');
                    for (var i = names.Length - 1; i >= 0; i--)
                    {
                        if (!string.IsNullOrEmpty(names[i]))
                        {
                            MoveDirectory(blobClient, newPrefix + names[i] + "/", oldPrefix + names[i] + "/");
                            break;
                        }
                    }
                }
                else if (blob is CloudBlob)
                {
                    var cloudBlob = blob as CloudBlob;

                    if (cloudBlob.Exists())
                    {
                        cloudBlob.FetchAttributes();
                        var newContentBlob = blobClient.GetBlockBlobReference(newPrefix + cloudBlob.Metadata["FileName"]);
                        newContentBlob.CopyFromBlob(cloudBlob);
                        newContentBlob.Metadata["FileName"] = cloudBlob.Metadata["FileName"];
                        newContentBlob.SetMetadata();
                        cloudBlob.DeleteIfExists();
                    }
                }
            }
        }
Ejemplo n.º 8
0
        private static void UploadBlob(string packageFileName, string packageUrl, string storageAccountName, string storageAccountKey)
        {
            OurTrace.TraceInfo(string.Format("Uploading blob from {0} to {1}", packageFileName, packageUrl));

            var packageUri = new Uri(packageUrl);
            var baseAddress = packageUri.GetComponents(UriComponents.SchemeAndServer, UriFormat.UriEscaped);
            var credentials = new StorageCredentialsAccountAndKey(storageAccountName, storageAccountKey);

            RetryPolicy myRetryPolicy = () =>
            {
                var shouldRetryInner = RetryPolicies.Retry(10, TimeSpan.Zero)();
                return (int rc, Exception ex, out TimeSpan d) =>
                {
                    var result = shouldRetryInner(rc, ex, out d);
                    if (result)
                        OurTrace.TraceWarning(string.Format("Retrying per retry policy (retry {0}, delay {1}) for exception:\n{2}", rc, ex, d));
                    return result;
                };
            };

            var cloudBlobClient = new CloudBlobClient(baseAddress, credentials)
            {
                RetryPolicy = myRetryPolicy,
                Timeout = TimeSpan.FromMinutes(15),
            };

            var blobRef = cloudBlobClient.GetBlockBlobReference(packageUrl);
            blobRef.Container.CreateIfNotExist();
            blobRef.UploadFile(packageFileName);
        }