public async Task PageBlobDownloadToStreamRangeTestAsync()
        {
            byte[] buffer = GetRandomBuffer(2 * 1024);

            CloudPageBlob blob = this.testContainer.GetPageBlobReference("blob1");
            using (MemoryStream wholeBlob = new MemoryStream(buffer))
            {
                await blob.UploadFromStreamAsync(wholeBlob.AsInputStream());

                byte[] testBuffer = new byte[1024];
                MemoryStream blobStream = new MemoryStream(testBuffer);
                Exception ex = await TestHelper.ExpectedExceptionAsync<Exception>(
                    async () => await blob.DownloadRangeToStreamAsync(blobStream.AsOutputStream(), 0, 0),
                    "Requesting 0 bytes when downloading range should not work");
                Assert.IsInstanceOfType(ex.InnerException.InnerException, typeof(ArgumentOutOfRangeException));
                await blob.DownloadRangeToStreamAsync(blobStream.AsOutputStream(), 0, 1024);
                Assert.AreEqual(blobStream.Position, 1024);
                TestHelper.AssertStreamsAreEqualAtIndex(blobStream, wholeBlob, 0, 0, 1024);

                CloudPageBlob blob2 = this.testContainer.GetPageBlobReference("blob1");
                MemoryStream blobStream2 = new MemoryStream(testBuffer);
                ex = await TestHelper.ExpectedExceptionAsync<Exception>(
                    async () => await blob2.DownloadRangeToStreamAsync(blobStream.AsOutputStream(), 1024, 0),
                    "Requesting 0 bytes when downloading range should not work");
                Assert.IsInstanceOfType(ex.InnerException.InnerException, typeof(ArgumentOutOfRangeException));
                await blob2.DownloadRangeToStreamAsync(blobStream2.AsOutputStream(), 1024, 1024);
                TestHelper.AssertStreamsAreEqualAtIndex(blobStream2, wholeBlob, 0, 1024, 1024);

                AssertAreEqual(blob, blob2);
            }
        }
示例#2
0
        public async Task InitializeAsync()
        {
            if (_isInitialized)
            {
                return;
            }

            IReadOnlyList<Size> availableCaptureResulotions =
                PhotoCaptureDevice.GetAvailableCaptureResolutions(CameraSensorLocation.Back);
            Device = await PhotoCaptureDevice.OpenAsync(CameraSensorLocation.Back, availableCaptureResulotions.First());
            
            InitParameters();
            Device.SetProperty(KnownCameraGeneralProperties.PlayShutterSoundOnCapture, true);

            _captureStream = new MemoryStream();
            _captureSequence = Device.CreateCaptureSequence(1);
            _captureSequence.Frames[0].CaptureStream = _captureStream.AsOutputStream();
            await Device.PrepareCaptureSequenceAsync(_captureSequence);

            CameraButtons.ShutterKeyHalfPressed += CameraButtons_ShutterKeyHalfPressed;
            CameraButtons.ShutterKeyPressed += CameraButtons_ShutterKeyPressed;
            CameraButtons.ShutterKeyReleased += CameraButtons_ShutterKeyReleased;

            _isInitialized = true;
        }
        public async Task FileOpenWriteTestAsync()
        {
            byte[] buffer = GetRandomBuffer(2 * 1024);
            CloudFileShare share = GetRandomShareReference();
            try
            {
                await share.CreateAsync();

                CloudFile file = share.GetRootDirectoryReference().GetFileReference("file1");
                using (ICloudFileStream fileStream = await file.OpenWriteAsync(2048))
                {
                    Stream fileStreamForWrite = fileStream.AsStreamForWrite();
                    await fileStreamForWrite.WriteAsync(buffer, 0, 2048);
                    await fileStreamForWrite.FlushAsync();

                    byte[] testBuffer = new byte[2048];
                    MemoryStream dstStream = new MemoryStream(testBuffer);
                    await file.DownloadRangeToStreamAsync(dstStream.AsOutputStream(), null, null);

                    MemoryStream memStream = new MemoryStream(buffer);
                    TestHelper.AssertStreamsAreEqual(memStream, dstStream);
                }
            }
            finally
            {
                share.DeleteIfExistsAsync().AsTask().Wait();
            }
        }
 public static async Task<string> DownloadTextAsync(CloudFile file, Encoding encoding, AccessCondition accessCondition = null, FileRequestOptions options = null, OperationContext operationContext = null)
 {
     using (MemoryStream stream = new MemoryStream())
     {
         await file.DownloadToStreamAsync(stream.AsOutputStream(), accessCondition, options, operationContext);
         return encoding.GetString(stream.ToArray(), 0, (int)stream.Length);
     }
 }
        public async Task FileDownloadToStreamRangeTestAsync()
        {
            byte[] buffer = GetRandomBuffer(2 * 1024);
            CloudFileShare share = GetRandomShareReference();
            try
            {
                await share.CreateAsync();

                CloudFile file = share.GetRootDirectoryReference().GetFileReference("file1");
                using (MemoryStream wholeFile = new MemoryStream(buffer))
                {
                    await file.UploadFromStreamAsync(wholeFile.AsInputStream());

                    byte[] testBuffer = new byte[1024];
                    MemoryStream fileStream = new MemoryStream(testBuffer);
                    Exception ex = await TestHelper.ExpectedExceptionAsync<Exception>(
                        async () => await file.DownloadRangeToStreamAsync(fileStream.AsOutputStream(), 0, 0),
                        "Requesting 0 bytes when downloading range should not work");
                    Assert.IsInstanceOfType(ex.InnerException.InnerException, typeof(ArgumentOutOfRangeException));
                    await file.DownloadRangeToStreamAsync(fileStream.AsOutputStream(), 0, 1024);
                    Assert.AreEqual(fileStream.Position, 1024);
                    TestHelper.AssertStreamsAreEqualAtIndex(fileStream, wholeFile, 0, 0, 1024);

                    CloudFile file2 = share.GetRootDirectoryReference().GetFileReference("file1");
                    MemoryStream fileStream2 = new MemoryStream(testBuffer);
                    ex = await TestHelper.ExpectedExceptionAsync<Exception>(
                        async () => await file2.DownloadRangeToStreamAsync(fileStream.AsOutputStream(), 1024, 0),
                        "Requesting 0 bytes when downloading range should not work");
                    Assert.IsInstanceOfType(ex.InnerException.InnerException, typeof(ArgumentOutOfRangeException));
                    await file2.DownloadRangeToStreamAsync(fileStream2.AsOutputStream(), 1024, 1024);
                    TestHelper.AssertStreamsAreEqualAtIndex(fileStream2, wholeFile, 0, 1024, 1024);

                    AssertAreEqual(file, file2);
                }
            }
            finally
            {
                share.DeleteIfExistsAsync().AsTask().Wait();
            }
        }
示例#6
0
    private async void Button_Click_2(object sender, RoutedEventArgs e) {
      CameraCaptureSequence cameraCaptureSequence = _cam.CreateCaptureSequence(1);

      MemoryStream stream = new MemoryStream();
      cameraCaptureSequence.Frames[0].CaptureStream = stream.AsOutputStream();

      await _cam.PrepareCaptureSequenceAsync(cameraCaptureSequence);
      await cameraCaptureSequence.StartCaptureAsync();

      stream.Seek(0, SeekOrigin.Begin);

      var library = new MediaLibrary();
      library.SavePictureToCameraRoll("pic1.jpg", stream);


    }
示例#7
0
        public async Task RestoreAsync()
        {
            var file = await ApplicationData.Current.LocalFolder.GetFileAsync(SessionStateFileName);
            using (var inStream = await file.OpenSequentialReadAsync())
            {
                using (var memoryStream = new MemoryStream())
                {
                    var provider = new DataProtectionProvider("LOCAL=user");
                    await provider.UnprotectStreamAsync(inStream, memoryStream.AsOutputStream());
                    memoryStream.Seek(0, SeekOrigin.Begin);

                    var bytes = memoryStream.ToArray();
                    this.DeserializeState(bytes);
                }
            }

            this.LoadApplicationState();
        }
示例#8
0
        private async void Button_Click_1(object sender, RoutedEventArgs e)
        {
            CameraCaptureSequence seq;
            seq = captureDevice.CreateCaptureSequence(1);

            seq.Frames[0].DesiredProperties[KnownCameraPhotoProperties.SceneMode] = CameraSceneMode.Portrait;

            MemoryStream captureStream1 = new MemoryStream();

            seq.Frames[0].CaptureStream = captureStream1.AsOutputStream();
            await captureDevice.PrepareCaptureSequenceAsync(seq);

            await seq.StartCaptureAsync();
            captureStream1.Seek(0, SeekOrigin.Begin);
            MediaLibrary mediaLibrary = new MediaLibrary();
            mediaLibrary.SavePictureToCameraRoll( "1111.jpg", captureStream1);
 
        }
示例#9
0
        private async void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            using (MemoryStream stream = new MemoryStream())
            using (var camera = await PhotoCaptureDevice.OpenAsync(CameraSensorLocation.Back,
                    PhotoCaptureDevice.GetAvailableCaptureResolutions(CameraSensorLocation.Back).First()))
            {
                var sequence = camera.CreateCaptureSequence(1);
                sequence.Frames[0].CaptureStream = stream.AsOutputStream();
                camera.PrepareCaptureSequenceAsync(sequence);
                await sequence.StartCaptureAsync();

                stream.Seek(0, SeekOrigin.Begin);

                using (var library = new MediaLibrary())
                {
                    library.SavePictureToCameraRoll("currentImage.jpg", stream);

                    BitmapImage licoriceImage = new BitmapImage(new Uri("currentImage.jpg", UriKind.Relative));
                    imgPlace.Source = licoriceImage;
                }
            }
        }
        public async Task CloudBlockBlobDownloadToStreamCancelAsync()
        {
            byte[] buffer = GetRandomBuffer(1 * 1024 * 1024);
            CloudBlobContainer container = GetRandomContainerReference();
            try
            {
                await container.CreateAsync();

                CloudBlockBlob blob = container.GetBlockBlobReference("blob1");
                using (MemoryStream originalBlob = new MemoryStream(buffer))
                {
                    await blob.UploadFromStreamAsync(originalBlob.AsInputStream());

                    using (MemoryStream downloadedBlob = new MemoryStream())
                    {
                        OperationContext operationContext = new OperationContext();
                        IAsyncAction action = blob.DownloadToStreamAsync(downloadedBlob.AsOutputStream(), null, null, operationContext);
                        await Task.Delay(100);
                        action.Cancel();
                        try
                        {
                            await action;
                        }
                        catch (Exception)
                        {
                            Assert.AreEqual(operationContext.LastResult.Exception.Message, "A task was canceled.");
                            Assert.AreEqual(operationContext.LastResult.HttpStatusCode, 306);
                            //Assert.AreEqual(operationContext.LastResult.HttpStatusMessage, "Unused");
                        }
                        TestHelper.AssertNAttempts(operationContext, 1);
                    }
                }
            }
            finally
            {
                container.DeleteIfExistsAsync().AsTask().Wait();
            }
        }
        private async Task CloudPageBlobUploadFromStreamAsync(CloudBlobContainer container, int size, AccessCondition accessCondition, OperationContext operationContext, int startOffset)
        {
            byte[] buffer = GetRandomBuffer(size);

            CryptographicHash hasher = HashAlgorithmProvider.OpenAlgorithm("MD5").CreateHash();
            hasher.Append(buffer.AsBuffer(startOffset, buffer.Length - startOffset));
            string md5 = CryptographicBuffer.EncodeToBase64String(hasher.GetValueAndReset());

            CloudPageBlob blob = container.GetPageBlobReference("blob1");
            blob.StreamWriteSizeInBytes = 512;

            using (MemoryStream originalBlob = new MemoryStream())
            {
                originalBlob.Write(buffer, startOffset, buffer.Length - startOffset);

                using (MemoryStream sourceStream = new MemoryStream(buffer))
                {
                    sourceStream.Seek(startOffset, SeekOrigin.Begin);
                    BlobRequestOptions options = new BlobRequestOptions()
                    {
                        StoreBlobContentMD5 = true,
                    };
                    await blob.UploadFromStreamAsync(sourceStream.AsInputStream(), accessCondition, options, operationContext);
                }

                await blob.FetchAttributesAsync();
                Assert.AreEqual(md5, blob.Properties.ContentMD5);

                using (MemoryStream downloadedBlob = new MemoryStream())
                {
                    await blob.DownloadToStreamAsync(downloadedBlob.AsOutputStream());
                    TestHelper.AssertStreamsAreEqual(originalBlob, downloadedBlob);
                }
            }
        }
        public async Task BlobOpenWriteTestAsync()
        {
            byte[] buffer = GetRandomBuffer(2 * 1024);
            CloudBlobContainer container = GetRandomContainerReference();
            try
            {
                await container.CreateAsync();
                
                CloudPageBlob blob = container.GetPageBlobReference("blob1");
                using (ICloudBlobStream blobStream = await blob.OpenWriteAsync(2048))
                {
                    Stream blobStreamForWrite = blobStream.AsStreamForWrite();
                    await blobStreamForWrite.WriteAsync(buffer, 0, 2048);
                    await blobStreamForWrite.FlushAsync();

                    byte[] testBuffer = new byte[2048];
                    MemoryStream dstStream = new MemoryStream(testBuffer);
                    await blob.DownloadRangeToStreamAsync(dstStream.AsOutputStream(), null, null);
                    
                    MemoryStream memStream = new MemoryStream(buffer);
                    TestHelper.AssertStreamsAreEqual(memStream, dstStream);
                }
            }
            finally
            {
                container.DeleteIfExistsAsync().AsTask().Wait();
            }
        }
        public async Task CloudBlockBlobUploadDownloadNoDataAsync()
        {
            CloudBlobContainer container = GetRandomContainerReference();
            try
            {
                await container.CreateAsync();

                CloudBlockBlob blob = container.GetBlockBlobReference("blob");
                await TestHelper.ExpectedExceptionAsync<ArgumentNullException>(
                    async () => await blob.UploadFromStreamAsync(null),
                    "Uploading from a null stream should fail");

                using (MemoryStream stream = new MemoryStream())
                {
                    await blob.UploadFromStreamAsync(stream.AsInputStream());
                }

                await TestHelper.ExpectedExceptionAsync<ArgumentNullException>(
                    async () => await blob.DownloadToStreamAsync(null),
                    "Downloading to a null stream should fail");

                using (MemoryStream stream = new MemoryStream())
                {
                    await blob.DownloadToStreamAsync(stream.AsOutputStream());
                    Assert.AreEqual(0, stream.Length);
                }
            }
            finally
            {
                container.DeleteIfExistsAsync().AsTask().Wait();
            }
        }
示例#14
0
        private async Task StartCapturingAsync()
        {
            CameraCaptureSequence sequence = PhotoCaptureDevice.CreateCaptureSequence(1);
            var memoryStream = new MemoryStream();
            sequence.Frames[0].CaptureStream = memoryStream.AsOutputStream();

            try
            {
                PhotoCaptureDevice.SetProperty(KnownCameraPhotoProperties.FlashMode, FlashState.Off);
                PhotoCaptureDevice.SetProperty(KnownCameraPhotoProperties.SceneMode, CameraSceneMode.Macro);
            }
            catch
            {
                // one or more properties not supported
            }

            await PhotoCaptureDevice.PrepareCaptureSequenceAsync(sequence);
        }
        public async Task<IBuffer> TakePicture()
        {
            if (m_captureDevice == null || commandeRunning)
                return null;
            try
            {
                commandeRunning = true;
                int angle = (int)(m_orientationAngle + m_captureDevice.SensorRotationInDegrees);
                if (angle < 0) angle += 360;
                if (m_sensorLocation == CameraSensorLocation.Back)
                {
                    m_captureDevice.SetProperty(KnownCameraGeneralProperties.EncodeWithOrientation, angle);
                }
                else
                {
                    m_captureDevice.SetProperty(KnownCameraGeneralProperties.EncodeWithOrientation, -angle);
                }
                m_captureDevice.SetProperty(KnownCameraGeneralProperties.SpecifiedCaptureOrientation, 0);


                var cameraCaptureSequence = m_captureDevice.CreateCaptureSequence(1);
                var stream = new MemoryStream();
                cameraCaptureSequence.Frames[0].CaptureStream = stream.AsOutputStream();
                await m_captureDevice.PrepareCaptureSequenceAsync(cameraCaptureSequence);
                await cameraCaptureSequence.StartCaptureAsync();
                if (m_sensorLocation == CameraSensorLocation.Back)
                {
                    return stream.GetWindowsRuntimeBuffer();
                }
                else
                {
                    return await JpegTools.FlipAndRotateAsync(stream.GetWindowsRuntimeBuffer(), FlipMode.Horizontal, Rotation.Rotate0, JpegOperation.AllowLossy);
                }

            }
            finally
            {
                commandeRunning = false;
            }
            return null;
        }
        public async Task DisableContentMD5ValidationTestAsync()
        {
            byte[] buffer = new byte[1024];
            Random random = new Random();
            random.NextBytes(buffer);

            BlobRequestOptions optionsWithNoMD5 = new BlobRequestOptions()
            {
                DisableContentMD5Validation = true,
                StoreBlobContentMD5 = true,
            };
            BlobRequestOptions optionsWithMD5 = new BlobRequestOptions()
            {
                DisableContentMD5Validation = false,
                StoreBlobContentMD5 = true,
            };

            CloudBlobContainer container = GetRandomContainerReference();
            try
            {
                await container.CreateAsync();

                CloudBlockBlob blockBlob = container.GetBlockBlobReference("blob1");
                using (Stream stream = new NonSeekableMemoryStream(buffer))
                {
                    await blockBlob.UploadFromStreamAsync(stream.AsInputStream(), null, optionsWithMD5, null);
                }

                using (Stream stream = new MemoryStream())
                {
                    await blockBlob.DownloadToStreamAsync(stream.AsOutputStream(), null, optionsWithMD5, null);
                    await blockBlob.DownloadToStreamAsync(stream.AsOutputStream(), null, optionsWithNoMD5, null);

                    using (IRandomAccessStreamWithContentType blobStream = await blockBlob.OpenReadAsync(null, optionsWithMD5, null))
                    {
                        Stream blobStreamForRead = blobStream.AsStreamForRead();
                        int read;
                        do
                        {
                            read = await blobStreamForRead.ReadAsync(buffer, 0, buffer.Length);
                        }
                        while (read > 0);
                    }

                    using (IRandomAccessStreamWithContentType blobStream = await blockBlob.OpenReadAsync(null, optionsWithNoMD5, null))
                    {
                        Stream blobStreamForRead = blobStream.AsStreamForRead();
                        int read;
                        do
                        {
                            read = await blobStreamForRead.ReadAsync(buffer, 0, buffer.Length);
                        }
                        while (read > 0);
                    }

                    blockBlob.Properties.ContentMD5 = "MDAwMDAwMDA=";
                    await blockBlob.SetPropertiesAsync();

                    OperationContext opContext = new OperationContext();
                    await TestHelper.ExpectedExceptionAsync(
                        async () => await blockBlob.DownloadToStreamAsync(stream.AsOutputStream(), null, optionsWithMD5, opContext),
                        opContext,
                        "Downloading a blob with invalid MD5 should fail",
                        HttpStatusCode.OK);
                    await blockBlob.DownloadToStreamAsync(stream.AsOutputStream(), null, optionsWithNoMD5, null);

                    using (IRandomAccessStreamWithContentType blobStream = await blockBlob.OpenReadAsync(null, optionsWithMD5, null))
                    {
                        Stream blobStreamForRead = blobStream.AsStreamForRead();
                        TestHelper.ExpectedException<IOException>(
                            () =>
                            {
                                int read;
                                do
                                {
                                    read = blobStreamForRead.Read(buffer, 0, buffer.Length);
                                }
                                while (read > 0);
                            },
                            "Downloading a blob with invalid MD5 should fail");
                    }

                    using (IRandomAccessStreamWithContentType blobStream = await blockBlob.OpenReadAsync(null, optionsWithNoMD5, null))
                    {
                        Stream blobStreamForRead = blobStream.AsStreamForRead();
                        int read;
                        do
                        {
                            read = await blobStreamForRead.ReadAsync(buffer, 0, buffer.Length);
                        }
                        while (read > 0);
                    }
                }

                CloudPageBlob pageBlob = container.GetPageBlobReference("blob2");
                using (Stream stream = new MemoryStream(buffer))
                {
                    await pageBlob.UploadFromStreamAsync(stream.AsInputStream(), null, optionsWithMD5, null);
                }

                using (Stream stream = new MemoryStream())
                {
                    await pageBlob.DownloadToStreamAsync(stream.AsOutputStream(), null, optionsWithMD5, null);
                    await pageBlob.DownloadToStreamAsync(stream.AsOutputStream(), null, optionsWithNoMD5, null);

                    using (IRandomAccessStreamWithContentType blobStream = await pageBlob.OpenReadAsync(null, optionsWithMD5, null))
                    {
                        Stream blobStreamForRead = blobStream.AsStreamForRead();
                        int read;
                        do
                        {
                            read = await blobStreamForRead.ReadAsync(buffer, 0, buffer.Length);
                        }
                        while (read > 0);
                    }

                    using (IRandomAccessStreamWithContentType blobStream = await pageBlob.OpenReadAsync(null, optionsWithNoMD5, null))
                    {
                        Stream blobStreamForRead = blobStream.AsStreamForRead();
                        int read;
                        do
                        {
                            read = await blobStreamForRead.ReadAsync(buffer, 0, buffer.Length);
                        }
                        while (read > 0);
                    }

                    pageBlob.Properties.ContentMD5 = "MDAwMDAwMDA=";
                    await pageBlob.SetPropertiesAsync();

                    OperationContext opContext = new OperationContext();
                    await TestHelper.ExpectedExceptionAsync(
                        async () => await pageBlob.DownloadToStreamAsync(stream.AsOutputStream(), null, optionsWithMD5, opContext),
                        opContext,
                        "Downloading a blob with invalid MD5 should fail",
                        HttpStatusCode.OK);
                    await pageBlob.DownloadToStreamAsync(stream.AsOutputStream(), null, optionsWithNoMD5, null);

                    using (IRandomAccessStreamWithContentType blobStream = await pageBlob.OpenReadAsync(null, optionsWithMD5, null))
                    {
                        Stream blobStreamForRead = blobStream.AsStreamForRead();
                        TestHelper.ExpectedException<IOException>(
                            () =>
                            {
                                int read;
                                do
                                {
                                    read = blobStreamForRead.Read(buffer, 0, buffer.Length);
                                }
                                while (read > 0);
                            },
                            "Downloading a blob with invalid MD5 should fail");
                    }

                    using (IRandomAccessStreamWithContentType blobStream = await pageBlob.OpenReadAsync(null, optionsWithNoMD5, null))
                    {
                        Stream blobStreamForRead = blobStream.AsStreamForRead();
                        int read;
                        do
                        {
                            read = await blobStreamForRead.ReadAsync(buffer, 0, buffer.Length);
                        }
                        while (read > 0);
                    }
                }
            }
            finally
            {
                container.DeleteIfExistsAsync().AsTask().Wait();
            }
        }
        public async Task BlobUploadWithoutMD5ValidationAndStoreBlobContentTestAsync()
        {
            byte[] buffer = GetRandomBuffer(2 * 1024);
            CloudBlobContainer container = GetRandomContainerReference();
            try
            {
                await container.CreateAsync();

                CloudPageBlob blob = container.GetPageBlobReference("blob1");
                BlobRequestOptions options = new BlobRequestOptions();
                options.DisableContentMD5Validation = false;
                options.StoreBlobContentMD5 = false;
                OperationContext context = new OperationContext();
                using (MemoryStream srcStream = new MemoryStream(buffer))
                {
                    await blob.UploadFromStreamAsync(srcStream.AsInputStream(), null, options, context);
                    await blob.FetchAttributesAsync();
                    string md5 = blob.Properties.ContentMD5;
                    blob.Properties.ContentMD5 = "MDAwMDAwMDA=";
                    await blob.SetPropertiesAsync(null, options, context);
                    byte[] testBuffer = new byte[2048];
                    MemoryStream dstStream = new MemoryStream(testBuffer);
                    await TestHelper.ExpectedExceptionAsync(async () => await blob.DownloadRangeToStreamAsync(dstStream.AsOutputStream(), null, null, null, options, context),
                        context,
                        "Try to Download a stream with a corrupted md5 and DisableMD5Validation set to false",
                        HttpStatusCode.OK);

                    options.DisableContentMD5Validation = true;
                    await blob.SetPropertiesAsync(null, options, context);
                    byte[] testBuffer2 = new byte[2048];
                    MemoryStream dstStream2 = new MemoryStream(testBuffer2);
                    await blob.DownloadRangeToStreamAsync(dstStream2.AsOutputStream(), null, null, null, options, context);
                }
            }
            finally
            {
                container.DeleteIfExistsAsync().AsTask().Wait();
            }

        }
        public async Task BlockBlobWriteStreamFlushTestAsync()
        {
            byte[] buffer = GetRandomBuffer(512 * 1024);

            CloudBlobContainer container = GetRandomContainerReference();
            try
            {
                await container.CreateAsync();

                CloudBlockBlob blob = container.GetBlockBlobReference("blob1");
                blob.StreamWriteSizeInBytes = 1 * 1024 * 1024;
                using (MemoryStream wholeBlob = new MemoryStream())
                {
                    OperationContext opContext = new OperationContext();
                    using (var blobStream = await blob.OpenWriteAsync(null, null, opContext))
                    {
                        for (int i = 0; i < 3; i++)
                        {
                            await blobStream.WriteAsync(buffer.AsBuffer());
                            await wholeBlob.WriteAsync(buffer, 0, buffer.Length);
                        }

                        Assert.AreEqual(1, opContext.RequestResults.Count);

                        await blobStream.FlushAsync();

                        Assert.AreEqual(2, opContext.RequestResults.Count);

                        await blobStream.FlushAsync();

                        Assert.AreEqual(2, opContext.RequestResults.Count);

                        await blobStream.WriteAsync(buffer.AsBuffer());
                        await wholeBlob.WriteAsync(buffer, 0, buffer.Length);

                        Assert.AreEqual(2, opContext.RequestResults.Count);

                        await blobStream.CommitAsync();

                        Assert.AreEqual(4, opContext.RequestResults.Count);
                    }

                    Assert.AreEqual(4, opContext.RequestResults.Count);

                    using (MemoryStream downloadedBlob = new MemoryStream())
                    {
                        await blob.DownloadToStreamAsync(downloadedBlob.AsOutputStream());
                        TestHelper.AssertStreamsAreEqual(wholeBlob, downloadedBlob);
                    }
                }
            }
            finally
            {
                container.DeleteIfExistsAsync().AsTask().Wait();
            }
        }
        public async Task BlobUploadFromStreamTestAsync()
        {
            byte[] buffer = GetRandomBuffer(2 * 1024);

            CloudPageBlob blob = this.testContainer.GetPageBlobReference("blob1");
            using (MemoryStream srcStream = new MemoryStream(buffer))
            {
                await blob.UploadFromStreamAsync(srcStream.AsInputStream());
                byte[] testBuffer = new byte[2048];
                MemoryStream dstStream = new MemoryStream(testBuffer);
                await blob.DownloadRangeToStreamAsync(dstStream.AsOutputStream(), null, null);
                TestHelper.AssertStreamsAreEqual(srcStream, dstStream);
            }
        }
        public async Task CloudBlockBlobUploadFromStreamInBlocksAsync()
        {
            byte[] buffer = GetRandomBuffer(2 * 1024 * 1024);
            CloudBlobContainer container = GetRandomContainerReference();
            try
            {
                await container.CreateAsync();

                CloudBlockBlob blob = container.GetBlockBlobReference("blob1");
                blob.ServiceClient.SingleBlobUploadThresholdInBytes = 1 * 1024 * 1024;
                blob.StreamWriteSizeInBytes = 512 * 1024;
                using (MemoryStream originalBlob = new MemoryStream(buffer))
                {
                    await blob.UploadFromStreamAsync(originalBlob.AsInputStream());

                    using (MemoryStream downloadedBlob = new MemoryStream())
                    {
                        await blob.DownloadToStreamAsync(downloadedBlob.AsOutputStream());
                        TestHelper.AssertStreamsAreEqual(originalBlob, downloadedBlob);
                    }
                }
            }
            finally
            {
                container.DeleteIfExistsAsync().AsTask().Wait();
            }
        }
        public async Task BlobUploadFromStreamTestAsync()
        {
            byte[] buffer = GetRandomBuffer(2 * 1024);
            CloudBlobContainer container = GetRandomContainerReference();
            try
            {
                await container.CreateAsync();

                CloudPageBlob blob = container.GetPageBlobReference("blob1");
                using (MemoryStream srcStream = new MemoryStream(buffer))
                {
                    await blob.UploadFromStreamAsync(srcStream.AsInputStream());
                    byte[] testBuffer = new byte[2048];
                    MemoryStream dstStream = new MemoryStream(testBuffer);
                    await blob.DownloadRangeToStreamAsync(dstStream.AsOutputStream(), null, null);
                    TestHelper.AssertStreamsAreEqual(srcStream, dstStream);
                }
            }
            finally
            {
                container.DeleteIfExistsAsync().AsTask().Wait();
            }
        }
        private async Task CloudBlockBlobUploadFromStreamAsync(bool seekableSourceStream, int startOffset)
        {
            byte[] buffer = GetRandomBuffer(1 * 1024 * 1024);

            CryptographicHash hasher = HashAlgorithmProvider.OpenAlgorithm("MD5").CreateHash();
            hasher.Append(buffer.AsBuffer(startOffset, buffer.Length - startOffset));
            string md5 = CryptographicBuffer.EncodeToBase64String(hasher.GetValueAndReset());

            CloudBlobContainer container = GetRandomContainerReference();
            try
            {
                await container.CreateAsync();

                CloudBlockBlob blob = container.GetBlockBlobReference("blob1");

                using (MemoryStream originalBlob = new MemoryStream())
                {
                    originalBlob.Write(buffer, startOffset, buffer.Length - startOffset);

                    Stream sourceStream;
                    if (seekableSourceStream)
                    {
                        MemoryStream stream = new MemoryStream(buffer);
                        stream.Seek(startOffset, SeekOrigin.Begin);
                        sourceStream = stream;
                    }
                    else
                    {
                        NonSeekableMemoryStream stream = new NonSeekableMemoryStream(buffer);
                        stream.ForceSeek(startOffset, SeekOrigin.Begin);
                        sourceStream = stream;
                    }

                    using (sourceStream)
                    {
                        BlobRequestOptions options = new BlobRequestOptions()
                        {
                            StoreBlobContentMD5 = true,
                        };
                        await blob.UploadFromStreamAsync(sourceStream.AsInputStream(), null, options, null);
                    }

                    await blob.FetchAttributesAsync();
                    Assert.AreEqual(md5, blob.Properties.ContentMD5);

                    using (MemoryStream downloadedBlob = new MemoryStream())
                    {
                        await blob.DownloadToStreamAsync(downloadedBlob.AsOutputStream());
                        TestHelper.AssertStreamsAreEqual(originalBlob, downloadedBlob);
                    }
                }
            }
            finally
            {
                container.DeleteIfExistsAsync().AsTask().Wait();
            }
        }
        public async Task CloudPageBlobWritePagesAsync()
        {
            byte[] buffer = GetRandomBuffer(4 * 1024 * 1024);
#if ASPNET_K
            MD5 md5 = MD5.Create();
            string contentMD5 = Convert.ToBase64String(md5.ComputeHash(buffer));
#else
            CryptographicHash hasher = HashAlgorithmProvider.OpenAlgorithm("MD5").CreateHash();
            hasher.Append(buffer.AsBuffer());
            string contentMD5 = CryptographicBuffer.EncodeToBase64String(hasher.GetValueAndReset());
#endif

            CloudBlobContainer container = GetRandomContainerReference();
            try
            {
                await container.CreateAsync();

                CloudPageBlob blob = container.GetPageBlobReference("blob1");
                await blob.CreateAsync(4 * 1024 * 1024);

                using (MemoryStream memoryStream = new MemoryStream())
                {
                    await TestHelper.ExpectedExceptionAsync<ArgumentOutOfRangeException>(
                        async () => await blob.WritePagesAsync(memoryStream.AsInputStream(), 0, null),
                        "Zero-length WritePages should fail");

                    memoryStream.SetLength(4 * 1024 * 1024 + 1);
                    await TestHelper.ExpectedExceptionAsync<ArgumentOutOfRangeException>(
                        async () => await blob.WritePagesAsync(memoryStream.AsInputStream(), 0, null),
                        ">4MB WritePages should fail");
                }

                using (MemoryStream resultingData = new MemoryStream())
                {
                    using (MemoryStream memoryStream = new MemoryStream(buffer))
                    {
                        OperationContext opContext = new OperationContext();
                        await TestHelper.ExpectedExceptionAsync(
                            async () => await blob.WritePagesAsync(memoryStream.AsInputStream(), 512, null, null, null, opContext),
                            opContext,
                            "Writing out-of-range pages should fail",
                            HttpStatusCode.RequestedRangeNotSatisfiable,
                            "InvalidPageRange");

                        memoryStream.Seek(0, SeekOrigin.Begin);
                        await blob.WritePagesAsync(memoryStream.AsInputStream(), 0, contentMD5);
                        resultingData.Write(buffer, 0, buffer.Length);

                        int offset = buffer.Length - 1024;
                        memoryStream.Seek(offset, SeekOrigin.Begin);
                        await TestHelper.ExpectedExceptionAsync(
                            async () => await blob.WritePagesAsync(memoryStream.AsInputStream(), 0, contentMD5, null, null, opContext),
                            opContext,
                            "Invalid MD5 should fail with mismatch",
                            HttpStatusCode.BadRequest,
                            "Md5Mismatch");

                        memoryStream.Seek(offset, SeekOrigin.Begin);
                        await blob.WritePagesAsync(memoryStream.AsInputStream(), 0, null);
                        resultingData.Seek(0, SeekOrigin.Begin);
                        resultingData.Write(buffer, offset, buffer.Length - offset);

                        offset = buffer.Length - 2048;
                        memoryStream.Seek(offset, SeekOrigin.Begin);
                        await blob.WritePagesAsync(memoryStream.AsInputStream(), 1024, null);
                        resultingData.Seek(1024, SeekOrigin.Begin);
                        resultingData.Write(buffer, offset, buffer.Length - offset);
                    }

                    using (MemoryStream blobData = new MemoryStream())
                    {
                        await blob.DownloadToStreamAsync(blobData.AsOutputStream());
                        Assert.AreEqual(resultingData.Length, blobData.Length);
                        Assert.IsTrue(blobData.ToArray().SequenceEqual(resultingData.ToArray()));
                    }
                }
            }
            finally
            {
                container.DeleteIfExistsAsync().AsTask().Wait();
            }
        }
示例#24
0
 public static async Task<string> DownloadTextAsync(CloudBlob blob, Encoding encoding, AccessCondition accessCondition = null, BlobRequestOptions options = null, OperationContext operationContext = null)
 {
     using (MemoryStream stream = new MemoryStream())
     {
         await blob.DownloadToStreamAsync(stream.AsOutputStream(), accessCondition, options, operationContext);
         byte[] buffer = stream.ToArray();
         return encoding.GetString(buffer, 0, buffer.Length);
     }
 }
        public async Task RestoreSessionStateAsync()
        {
            _sessionState = new Dictionary<string, Dictionary<String, Object>>();

            try
            {
                // Get the input stream for the SessionState file
                StorageFile file = await ApplicationData.Current.LocalFolder.GetFileAsync(Constants.SessionStateFileName);
                using (IInputStream inStream = await file.OpenSequentialReadAsync())
                {
                    var memoryStream = new MemoryStream();
                    var provider = new DataProtectionProvider("LOCAL=user");

                    // Decrypt the prevously saved session data.
                    await provider.UnprotectStreamAsync(inStream, memoryStream.AsOutputStream());
                    memoryStream.Seek(0, SeekOrigin.Begin);
                    // Deserialize the Session State
                    DataContractSerializer serializer = new DataContractSerializer(typeof(Dictionary<string, Dictionary<string, object>>),
                                                                                   _knownTypes);
                    _sessionState = (Dictionary<string, Dictionary<string, object>>)serializer.ReadObject(memoryStream);
                }
            }
            catch (Exception e)
            {
                throw new SessionStateServiceException(e);
            }
        }
        public async Task BlockBlobWriteStreamBasicTestAsync()
        {
            byte[] buffer = GetRandomBuffer(3 * 1024 * 1024);

            CryptographicHash hasher = HashAlgorithmProvider.OpenAlgorithm("MD5").CreateHash();
            CloudBlobClient blobClient = GenerateCloudBlobClient();
            blobClient.ParallelOperationThreadCount = 2;
            string name = GetRandomContainerName();
            CloudBlobContainer container = blobClient.GetContainerReference(name);
            try
            {
                await container.CreateAsync();

                CloudBlockBlob blob = container.GetBlockBlobReference("blob1");
                using (MemoryStream wholeBlob = new MemoryStream())
                {
                    BlobRequestOptions options = new BlobRequestOptions()
                    {
                        StoreBlobContentMD5 = true,
                    };
                    using (IOutputStream writeStream = await blob.OpenWriteAsync(null, options, null))
                    {
                        Stream blobStream = writeStream.AsStreamForWrite();
                        for (int i = 0; i < 3; i++)
                        {
                            await blobStream.WriteAsync(buffer, 0, buffer.Length);
                            await wholeBlob.WriteAsync(buffer, 0, buffer.Length);
                            Assert.AreEqual(wholeBlob.Position, blobStream.Position);
                            hasher.Append(buffer.AsBuffer());
                        }
                    }

                    string md5 = CryptographicBuffer.EncodeToBase64String(hasher.GetValueAndReset());
                    await blob.FetchAttributesAsync();
                    Assert.AreEqual(md5, blob.Properties.ContentMD5);

                    using (MemoryStream downloadedBlob = new MemoryStream())
                    {
                        await blob.DownloadToStreamAsync(downloadedBlob.AsOutputStream());
                        TestHelper.AssertStreamsAreEqual(wholeBlob, downloadedBlob);
                    }
                }
            }
            finally
            {
                container.DeleteAsync().AsTask().Wait();
            }
        }
        public async Task CloudBlockBlobPutBlockAsync()
        {
            byte[] buffer = GetRandomBuffer(4 * 1024 * 1024);
#if ASPNET_K
            MD5 md5 = MD5.Create();
            string contentMD5 = Convert.ToBase64String(md5.ComputeHash(buffer));
#else
            CryptographicHash hasher = HashAlgorithmProvider.OpenAlgorithm("MD5").CreateHash();
            hasher.Append(buffer.AsBuffer());
            string contentMD5 = CryptographicBuffer.EncodeToBase64String(hasher.GetValueAndReset());
#endif

            CloudBlobContainer container = GetRandomContainerReference();
            try
            {
                await container.CreateAsync();

                CloudBlockBlob blob = container.GetBlockBlobReference("blob1");
                List<string> blockList = GetBlockIdList(2);

                using (MemoryStream resultingData = new MemoryStream())
                {
                    using (MemoryStream memoryStream = new MemoryStream(buffer))
                    {
                        memoryStream.Seek(0, SeekOrigin.Begin);
                        await blob.PutBlockAsync(blockList[0], memoryStream.AsInputStream(), contentMD5);
                        resultingData.Write(buffer, 0, buffer.Length);

                        int offset = buffer.Length - 1024;
                        memoryStream.Seek(offset, SeekOrigin.Begin);
                        OperationContext opContext = new OperationContext();
                        await TestHelper.ExpectedExceptionAsync(
                            async () => await blob.PutBlockAsync(blockList[1], memoryStream.AsInputStream(), contentMD5, null, null, opContext),
                            opContext,
                            "Invalid MD5 should fail with mismatch",
                            HttpStatusCode.BadRequest,
                            "Md5Mismatch");

                        memoryStream.Seek(offset, SeekOrigin.Begin);
                        await blob.PutBlockAsync(blockList[1], memoryStream.AsInputStream(), null);
                        resultingData.Write(buffer, offset, buffer.Length - offset);
                    }

                    await blob.PutBlockListAsync(blockList);

                    using (MemoryStream blobData = new MemoryStream())
                    {
                        await blob.DownloadToStreamAsync(blobData.AsOutputStream());
                        Assert.AreEqual(resultingData.Length, blobData.Length);
                        Assert.IsTrue(blobData.ToArray().SequenceEqual(resultingData.ToArray()));
                    }
                }
            }
            finally
            {
                container.DeleteIfExistsAsync().AsTask().Wait();
            }
        }
        public async Task PageBlobWriteStreamBasicTestAsync()
        {
            byte[] buffer = GetRandomBuffer(6 * 512);

            CryptographicHash hasher = HashAlgorithmProvider.OpenAlgorithm("MD5").CreateHash();
            CloudBlobContainer container = GetRandomContainerReference();
            container.ServiceClient.ParallelOperationThreadCount = 2;

            try
            {
                await container.CreateAsync();

                CloudPageBlob blob = container.GetPageBlobReference("blob1");
                blob.StreamWriteSizeInBytes = 8 * 512;

                using (MemoryStream wholeBlob = new MemoryStream())
                {
                    BlobRequestOptions options = new BlobRequestOptions()
                    {
                        StoreBlobContentMD5 = true,
                    };

                    using (IOutputStream writeStream = await blob.OpenWriteAsync(buffer.Length * 3, null, options, null))
                    {
                        Stream blobStream = writeStream.AsStreamForWrite();

                        for (int i = 0; i < 3; i++)
                        {
                            await blobStream.WriteAsync(buffer, 0, buffer.Length);
                            await wholeBlob.WriteAsync(buffer, 0, buffer.Length);
                            Assert.AreEqual(wholeBlob.Position, blobStream.Position);
                            hasher.Append(buffer.AsBuffer());
                        }
                    }

                    string md5 = CryptographicBuffer.EncodeToBase64String(hasher.GetValueAndReset());
                    await blob.FetchAttributesAsync();
                    Assert.AreEqual(md5, blob.Properties.ContentMD5);

                    using (MemoryStream downloadedBlob = new MemoryStream())
                    {
                        await blob.DownloadToStreamAsync(downloadedBlob.AsOutputStream());
                        TestHelper.AssertStreamsAreEqual(wholeBlob, downloadedBlob);
                    }

                    await TestHelper.ExpectedExceptionAsync<ArgumentException>(
                        async () => await blob.OpenWriteAsync(null, null, options, null),
                        "OpenWrite with StoreBlobContentMD5 on an existing page blob should fail");

                    using (IOutputStream writeStream = await blob.OpenWriteAsync(null))
                    {
                        Stream blobStream = writeStream.AsStreamForWrite();
                        blobStream.Seek(buffer.Length / 2, SeekOrigin.Begin);
                        wholeBlob.Seek(buffer.Length / 2, SeekOrigin.Begin);

                        for (int i = 0; i < 2; i++)
                        {
                            blobStream.Write(buffer, 0, buffer.Length);
                            wholeBlob.Write(buffer, 0, buffer.Length);
                            Assert.AreEqual(wholeBlob.Position, blobStream.Position);
                        }

                        wholeBlob.Seek(0, SeekOrigin.End);
                    }

                    await blob.FetchAttributesAsync();
                    Assert.AreEqual(md5, blob.Properties.ContentMD5);

                    using (MemoryStream downloadedBlob = new MemoryStream())
                    {
                        options.DisableContentMD5Validation = true;
                        await blob.DownloadToStreamAsync(downloadedBlob.AsOutputStream(), null, options, null);
                        TestHelper.AssertStreamsAreEqual(wholeBlob, downloadedBlob);
                    }
                }
            }
            finally
            {
                container.DeleteAsync().AsTask().Wait();
            }
        }
        public async Task CloudBlockBlobSetPropertiesAsync()
        {
            CloudBlobContainer container = GetRandomContainerReference();
            try
            {
                await container.CreateAsync();

                CloudBlockBlob blob = container.GetBlockBlobReference("blob1");
                await CreateForTestAsync(blob, 1, 1024);
                string eTag = blob.Properties.ETag;
                DateTimeOffset lastModified = blob.Properties.LastModified.Value;

                await Task.Delay(1000);

                blob.Properties.CacheControl = "no-transform";
                blob.Properties.ContentDisposition = "attachment";
#if !ASPNET_K
                blob.Properties.ContentEncoding = "gzip";
#endif
                blob.Properties.ContentLanguage = "tr,en";
                blob.Properties.ContentMD5 = "MDAwMDAwMDA=";
                blob.Properties.ContentType = "text/html";
                await blob.SetPropertiesAsync();
                Assert.IsTrue(blob.Properties.LastModified > lastModified);
                Assert.AreNotEqual(eTag, blob.Properties.ETag);

                CloudBlockBlob blob2 = container.GetBlockBlobReference("blob1");
                await blob2.FetchAttributesAsync();
                Assert.AreEqual("no-transform", blob2.Properties.CacheControl);
                Assert.AreEqual("attachment", blob2.Properties.ContentDisposition);
#if !ASPNET_K
                Assert.AreEqual("gzip", blob2.Properties.ContentEncoding);
#endif
                Assert.AreEqual("tr,en", blob2.Properties.ContentLanguage);
                Assert.AreEqual("MDAwMDAwMDA=", blob2.Properties.ContentMD5);
                Assert.AreEqual("text/html", blob2.Properties.ContentType);

                CloudBlockBlob blob3 = container.GetBlockBlobReference("blob1");
                using (MemoryStream stream = new MemoryStream())
                {
                    BlobRequestOptions options = new BlobRequestOptions()
                    {
                        DisableContentMD5Validation = true,
                    };
                    await blob3.DownloadToStreamAsync(stream.AsOutputStream(), null, options, null);
                }
                AssertAreEqual(blob2.Properties, blob3.Properties);

                BlobResultSegment results = await container.ListBlobsSegmentedAsync(null);
                CloudBlockBlob blob4 = (CloudBlockBlob)results.Results.First();
                AssertAreEqual(blob2.Properties, blob4.Properties);
            }
            finally
            {
                container.DeleteIfExistsAsync().AsTask().Wait();
            }
        }
        public async Task PageBlobWriteStreamRandomSeekTestAsync()
        {
            byte[] buffer = GetRandomBuffer(3 * 1024 * 1024);

            CloudBlobContainer container = GetRandomContainerReference();
            container.ServiceClient.ParallelOperationThreadCount = 2;
            try
            {
                await container.CreateAsync();

                CloudPageBlob blob = container.GetPageBlobReference("blob1");
                using (MemoryStream wholeBlob = new MemoryStream())
                {
                    using (IOutputStream writeStream = await blob.OpenWriteAsync(buffer.Length))
                    {
                        Stream blobStream = writeStream.AsStreamForWrite();
                        TestHelper.ExpectedException<ArgumentOutOfRangeException>(
                            () => blobStream.Seek(1, SeekOrigin.Begin),
                            "Page blob stream should not allow unaligned seeks");

                        await blobStream.WriteAsync(buffer, 0, buffer.Length);
                        await wholeBlob.WriteAsync(buffer, 0, buffer.Length);
                        Random random = new Random();
                        for (int i = 0; i < 10; i++)
                        {
                            int offset = random.Next(buffer.Length / 512) * 512;
                            SeekRandomly(blobStream, offset);
                            await blobStream.WriteAsync(buffer, 0, buffer.Length - offset);
                            wholeBlob.Seek(offset, SeekOrigin.Begin);
                            await wholeBlob.WriteAsync(buffer, 0, buffer.Length - offset);
                        }
                    }

                    wholeBlob.Seek(0, SeekOrigin.End);
                    await blob.FetchAttributesAsync();
                    Assert.IsNull(blob.Properties.ContentMD5);

                    using (MemoryStream downloadedBlob = new MemoryStream())
                    {
                        await blob.DownloadToStreamAsync(downloadedBlob.AsOutputStream());
                        TestHelper.AssertStreamsAreEqual(wholeBlob, downloadedBlob);
                    }
                }
            }
            finally
            {
                container.DeleteIfExistsAsync().AsTask().Wait();
            }
        }