Exemplo n.º 1
0
        /// <summary>
        ///   Finds all js and css files in a container and creates a gzip compressed
        ///   copy of the file with ".gzip" appended to the existing blob name
        /// </summary>
        public static void EnsureGzipFiles(
            CloudBlobContainer container,
            int cacheControlMaxAgeSeconds)
        {
            string cacheControlHeader = "public, max-age=" + cacheControlMaxAgeSeconds.ToString();

            var blobInfos = container.ListBlobs(
                new BlobRequestOptions()
            {
                UseFlatBlobListing = true
            });

            Parallel.ForEach(blobInfos, (blobInfo) =>
            {
                string blobUrl = blobInfo.Uri.ToString();
                CloudBlob blob = container.GetBlobReference(blobUrl);

                // only create gzip copies for css and js files
                string extension = Path.GetExtension(blobInfo.Uri.LocalPath);
                if (extension != ".css" && extension != ".js")
                {
                    return;
                }

                // see if the gzip version already exists
                string gzipUrl     = blobUrl + ".gzip";
                CloudBlob gzipBlob = container.GetBlobReference(gzipUrl);
                if (gzipBlob.Exists())
                {
                    return;
                }

                // create a gzip version of the file
                using (MemoryStream memoryStream = new MemoryStream())
                {
                    // push the original blob into the gzip stream
                    using (GZipStream gzipStream = new GZipStream(
                               memoryStream, CompressionMode.Compress, CompressionLevel.BestCompression))
                        using (BlobStream blobStream = blob.OpenRead())
                        {
                            blobStream.CopyTo(gzipStream);
                        }

                    // the gzipStream MUST be closed before its safe to read from the memory stream
                    byte[] compressedBytes = memoryStream.ToArray();

                    // upload the compressed bytes to the new blob
                    gzipBlob.UploadByteArray(compressedBytes);

                    // set the blob headers
                    gzipBlob.Properties.CacheControl    = cacheControlHeader;
                    gzipBlob.Properties.ContentType     = GetContentType(extension);
                    gzipBlob.Properties.ContentEncoding = "gzip";
                    gzipBlob.SetProperties();
                }
            });
        }
Exemplo n.º 2
0
        public virtual void CopyTo(Stream output)
        {
            if (output == null)
            {
                throw new ArgumentNullException(nameof(output));
            }

            using (var blob = new BlobStream(this))
            {
                blob.CopyTo(output);
            }
        }