DownloadToStream() public method

Downloads the contents of a blob to a stream.
public DownloadToStream ( Stream target ) : void
target Stream The target stream.
return void
        /// <summary>
        /// Возвращает поток с файлом из хранилища.
        /// </summary>
        /// <param name="localUri"> Адрес файла </param>
        /// <returns> Поток </returns>
        public Stream Get(string localUri)
        {
            CloudBlob blob = new CloudBlob(localUri, _client);

            MemoryStream stream = new MemoryStream();
            blob.DownloadToStream(stream, new BlobRequestOptions()
            {
                RetryPolicy = RetryPolicies.RetryExponential(
                    RetryPolicies.DefaultClientRetryCount,
                    RetryPolicies.DefaultClientBackoff)
            });
            stream.Seek(0, SeekOrigin.Begin);

            return stream;
        }
Exemplo n.º 2
0
 public static IInformationObject RetrieveInformationWithBlob(string relativeLocation, Type typeToRetrieve, out CloudBlob blob, string eTag = null, IContainerOwner owner = null)
 {
     if (owner != null)
         relativeLocation = GetBlobOwnerAddress(owner, relativeLocation);
     blob = CurrActiveContainer.GetBlobReference(relativeLocation);
     MemoryStream memoryStream = new MemoryStream();
     string blobEtag = null;
     try
     {
         BlobRequestOptions options = new BlobRequestOptions();
         options.RetryPolicy = RetryPolicies.Retry(10, TimeSpan.FromSeconds(3));
         if (eTag != null)
             options.AccessCondition = AccessCondition.IfMatch(eTag);
         blob.DownloadToStream(memoryStream, options);
         blobEtag = blob.Properties.ETag;
     }
     catch (StorageClientException stEx)
     {
         if (stEx.ErrorCode == StorageErrorCode.BlobNotFound)
             return null;
         throw;
     }
     //if (memoryStream.Length == 0)
     //    return null;
     memoryStream.Seek(0, SeekOrigin.Begin);
     DataContractSerializer serializer = new DataContractSerializer(typeToRetrieve);
     IInformationObject informationObject = (IInformationObject)serializer.ReadObject(memoryStream);
     informationObject.ETag = blobEtag;
     //informationObject.RelativeLocation = blob.Attributes.Metadata["RelativeLocation"];
     informationObject.SetInstanceTreeValuesAsUnmodified();
     Debug.WriteLine(String.Format("Read: {0} ID {1}", informationObject.GetType().Name,
         informationObject.ID));
     return informationObject;
 }
Exemplo n.º 3
0
 private static void HandlePublicBlobRequestWithCacheSupport(HttpContext context, CloudBlob blob, HttpResponse response)
 {
     // Set the cache request properties as IIS will include them regardless for now
     // even when we wouldn't want them on 304 response...
     response.Cache.SetMaxAge(TimeSpan.FromMinutes(0));
     response.Cache.SetCacheability(HttpCacheability.Private);
     var request = context.Request;
     blob.FetchAttributes();
     string ifNoneMatch = request.Headers["If-None-Match"];
     string ifModifiedSince = request.Headers["If-Modified-Since"];
     if (ifNoneMatch != null)
     {
         if (ifNoneMatch == blob.Properties.ETag)
         {
             response.ClearContent();
             response.StatusCode = 304;
             return;
         }
     }
     else if (ifModifiedSince != null)
     {
         DateTime ifModifiedSinceValue;
         if (DateTime.TryParse(ifModifiedSince, out ifModifiedSinceValue))
         {
             ifModifiedSinceValue = ifModifiedSinceValue.ToUniversalTime();
             if (blob.Properties.LastModifiedUtc <= ifModifiedSinceValue)
             {
                 response.ClearContent();
                 response.StatusCode = 304;
                 return;
             }
         }
     }
     var fileName = blob.Name.Contains("/MediaContent/") ?
         request.Path : blob.Name;
     response.ContentType = StorageSupport.GetMimeType(fileName);
     //response.Cache.SetETag(blob.Properties.ETag);
     response.Headers.Add("ETag", blob.Properties.ETag);
     response.Cache.SetLastModified(blob.Properties.LastModifiedUtc);
     blob.DownloadToStream(response.OutputStream);
 }
Exemplo n.º 4
0
        // Deserialize NameValueCollection from Blob
        private static NameValueCollection DeserializeNameValueCollectionFromBlob(CloudBlob blob)
        {
            NameValueCollection collection = null;
            try
            {
                using (MemoryStream memoryStream = new MemoryStream())
                {
                    SoapFormatter ser = new SoapFormatter();
                    blob.DownloadToStream(memoryStream);
                    memoryStream.Seek(0, SeekOrigin.Begin);
                    collection = ser.Deserialize(memoryStream) as NameValueCollection;
                }
            }
            catch (Exception ex)
            {
                Trace.TraceError("Failed to DeserializeNameValueCollectionFromBlob. Error: {0}", ex.Message);
            }

            return collection;
        }
Exemplo n.º 5
0
        public AzureIndexInput(AzureDirectory azuredirectory, CloudBlob blob)
        {
            _name = blob.Uri.Segments[blob.Uri.Segments.Length - 1];

            #if FULLDEBUG
            Debug.WriteLine(String.Format("opening {0} ", _name));
            #endif
            _fileMutex = new Mutex(false, _name);
            _fileMutex.WaitOne();
            try
            {
                _azureDirectory = azuredirectory;
                _blobContainer = azuredirectory.BlobContainer;
                _blob = blob;

                string fileName = _name;

                bool fFileNeeded = false;
                if (!CacheDirectory.FileExists(fileName))
                {
                    fFileNeeded = true;
                }
                else
                {
                    long cachedLength = CacheDirectory.FileLength(fileName);
                    long blobLength = blob.Properties.Length;
                    long.TryParse(blob.Metadata["CachedLength"], out blobLength);

                    long longLastModified = 0;
                    DateTime blobLastModifiedUTC = blob.Properties.LastModifiedUtc;
                    if (long.TryParse(blob.Metadata["CachedLastModified"], out longLastModified))
                        blobLastModifiedUTC = new DateTime(longLastModified).ToUniversalTime();

                    if (cachedLength != blobLength)
                        fFileNeeded = true;
                    else
                    {
                        // there seems to be an error of 1 tick which happens every once in a while
                        // for now we will say that if they are within 1 tick of each other and same length
                        DateTime cachedLastModifiedUTC = new DateTime(CacheDirectory.FileModified(fileName), DateTimeKind.Local).ToUniversalTime();
                        if (cachedLastModifiedUTC != blobLastModifiedUTC)
                        {
                            TimeSpan timeSpan = blobLastModifiedUTC.Subtract(cachedLastModifiedUTC);
                            if (timeSpan.TotalSeconds > 1)
                                fFileNeeded = true;
                            else
                            {
            #if FULLDEBUG
                                Debug.WriteLine(timeSpan.TotalSeconds);
            #endif
                                // file not needed
                            }
                        }
                    }
                }

                // if the file does not exist
                // or if it exists and it is older then the lastmodified time in the blobproperties (which always comes from the blob storage)
                if (fFileNeeded)
                {
            #if COMPRESSBLOBS
                    if (_azureDirectory.ShouldCompressFile(_name))
                    {
                        // then we will get it fresh into local deflatedName
                        // StreamOutput deflatedStream = new StreamOutput(CacheDirectory.CreateOutput(deflatedName));
                        MemoryStream deflatedStream = new MemoryStream();

                        // get the deflated blob
                        _blob.DownloadToStream(deflatedStream);

                        Debug.WriteLine(string.Format("GET {0} RETREIVED {1} bytes", _name, deflatedStream.Length));

                        // seek back to begininng
                        deflatedStream.Seek(0, SeekOrigin.Begin);

                        // open output file for uncompressed contents
                        StreamOutput fileStream = _azureDirectory.CreateCachedOutputAsStream(fileName);

                        // create decompressor
                        DeflateStream decompressor = new DeflateStream(deflatedStream, CompressionMode.Decompress);

                        byte[] bytes = new byte[65535];
                        int nRead = 0;
                        do
                        {
                            nRead = decompressor.Read(bytes, 0, 65535);
                            if (nRead > 0)
                                fileStream.Write(bytes, 0, nRead);
                        } while (nRead == 65535);
                        decompressor.Close(); // this should close the deflatedFileStream too

                        fileStream.Close();

                    }
                    else
            #endif
                    {
                        StreamOutput fileStream = _azureDirectory.CreateCachedOutputAsStream(fileName);

                        // get the blob
                        _blob.DownloadToStream(fileStream);

                        fileStream.Flush();
                        Debug.WriteLine(string.Format("GET {0} RETREIVED {1} bytes", _name, fileStream.Length));

                        fileStream.Close();
                    }

                    // and open it as an input
                    _indexInput = CacheDirectory.OpenInput(fileName);
                }
                else
                {
            #if FULLDEBUG
                    Debug.WriteLine(String.Format("Using cached file for {0}", _name));
            #endif

                    // open the file in read only mode
                    _indexInput = CacheDirectory.OpenInput(fileName);
                }
            }
            finally
            {
                _fileMutex.ReleaseMutex();
            }
        }