internal static void ExecuteAPMMethodWithCancellation <T>(int cancellationDelayInMS,
                                                                  ProxyBehavior[] behaviors,
                                                                  Func <IRequestOptions,
                                                                        OperationContext,
                                                                        AsyncCallback,
                                                                        object,
                                                                        ICancellableAsyncResult> begin,
                                                                  Func <IAsyncResult, T> end)
        {
            string           failMessage      = null;
            StorageException storageException = null;
            OperationContext opContext        = new OperationContext();

            using (HttpMangler proxy = new HttpMangler(false, behaviors))
            {
                Debug.WriteLine("Begin");
                using (ManualResetEvent completedEvent = new ManualResetEvent(false))
                {
                    ICancellableAsyncResult saveResult = begin(null
                                                               , opContext,
                                                               (resp) =>
                    {
                        try
                        {
                            end(resp);
                            failMessage = "Request succeeded even after cancellation";
                        }
                        catch (StorageException ex)
                        {
                            storageException = ex;
                        }
                        catch (Exception badEx)
                        {
                            failMessage = badEx.ToString();
                        }
                        finally
                        {
                            completedEvent.Set();
                        }
                    },
                                                               null);

                    Thread.Sleep(cancellationDelayInMS);
                    Debug.WriteLine("Cancelling Request");
                    saveResult.Cancel();

                    completedEvent.WaitOne();
                    TestHelper.AssertNAttempts(opContext, 1);
                }
            }

            // Do not use IsNull here so that test result contains failMessage
            Assert.AreEqual(null, failMessage);

            Assert.IsNotNull(storageException);
            Assert.AreEqual("A task was canceled.", storageException.Message);
            Assert.AreEqual(306, storageException.RequestInformation.HttpStatusCode);
            //TODO: Httpclient null or unused?
            Assert.AreEqual(null, storageException.RequestInformation.HttpStatusMessage);
        }
        public ICancellableAsyncResult BeginListBlobsSegmented(string prefix, bool useFlatBlobListing, BlobListingDetails blobListingDetails, int?maxResults, BlobContinuationToken currentToken, BlobRequestOptions options, OperationContext operationContext, AsyncCallback callback, object state)
        {
            string containerName;
            string listingPrefix;

            CloudBlobClient.ParseUserPrefix(prefix, out containerName, out listingPrefix);

            CloudBlobContainer container = this.GetContainerReference(containerName);
            ChainedAsyncResult <BlobResultSegment> result = new ChainedAsyncResult <BlobResultSegment>(callback, state);
            ICancellableAsyncResult asyncResult           = container.BeginListBlobsSegmented(
                listingPrefix,
                useFlatBlobListing,
                blobListingDetails,
                maxResults,
                currentToken,
                options,
                operationContext,
                ar =>
            {
                try
                {
                    result.Result = container.EndListBlobsSegmented(ar);
                    result.OnComplete();
                }
                catch (Exception e)
                {
                    result.OnComplete(e);
                }
            },
                null /* state */);

            result.CancelDelegate = asyncResult.Cancel;
            return(result);
        }
Example #3
0
        /// <summary>
        /// Downloads a blob to a local file asynchronously.
        /// </summary>
        /// <param name="localFile">The local file.</param>
        /// <exception cref="System.Exception">BlobTransfer already initiated. Create new BlobTransfer object to initiate a new file transfer.</exception>
        public ICancellableAsyncResult DownloadBlobAsync(string localFile)
        {
            lock (workingLock)
            {
                if (!working)
                {
                    working = true;
                }
                else
                {
                    throw new Exception("BlobTransfer already initiated. Create new BlobTransfer object to initiate a new file transfer.");
                }
            }

            // Create an async op in order to raise the events back to the client on the correct thread.
            asyncOp = AsyncOperationManager.CreateOperation(blob);

            TransferType = TransferTypeEnum.Download;
            fileName     = localFile;

            this.blob.FetchAttributes();

            FileStream     fs      = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.Write, FileShare.Read);
            ProgressStream pstream = new ProgressStream(fs);

            pstream.ProgressChanged += pstream_ProgressChanged;
            pstream.SetLength(this.blob.Properties.Length);
            this.blob.ServiceClient.ParallelOperationThreadCount = 10;
            asyncresult = this.blob.BeginDownloadToStream(pstream, BlobTransferCompletedCallback, new BlobTransferAsyncState(this.blob, pstream));
            return(asyncresult);
        }
Example #4
0
        public void DownloadBlobAsync(ICloudBlob blob, string LocalFile)
        {
            // The class currently stores state in class level variables so calling UploadBlobAsync or DownloadBlobAsync a second time will cause problems.
            // A better long term solution would be to better encapsulate the state, but the current solution works for the needs of my primary client.
            // Throw an exception if UploadBlobAsync or DownloadBlobAsync has already been called.
            lock (WorkingLock)
            {
                if (!Working)
                {
                    Working = true;
                }
                else
                {
                    throw new Exception("BlobTransfer already initiated. Create new BlobTransfer object to initiate a new file transfer.");
                }
            }

            // Create an async op in order to raise the events back to the client on the correct thread.
            asyncOp = AsyncOperationManager.CreateOperation(blob);

            TransferType = TransferTypeEnum.Download;
            m_Blob       = blob;
            m_FileName   = LocalFile;

            m_Blob.FetchAttributes();

            FileStream     fs      = new FileStream(m_FileName, FileMode.OpenOrCreate, FileAccess.Write, FileShare.Read);
            ProgressStream pstream = new ProgressStream(fs);

            pstream.ProgressChanged += pstream_ProgressChanged;
            pstream.SetLength(m_Blob.Properties.Length);
            m_Blob.ServiceClient.DefaultRequestOptions.ParallelOperationThreadCount = 10;
            asyncresult = m_Blob.BeginDownloadToStream(pstream, BlobTransferCompletedCallback, new BlobTransferAsyncState(m_Blob, pstream));
        }
Example #5
0
        /// <summary>
        /// Uploads a file to an Azure blob asynchronously.
        /// </summary>
        /// <param name="localFile">The local file.</param>
        /// <exception cref="System.Exception">BlobTransfer already initiated. Create new BlobTransfer object to initiate a new file transfer.</exception>
        public ICancellableAsyncResult UploadBlobAsync(string localFile)
        {
            lock (workingLock)
            {
                if (!working)
                {
                    working = true;
                }
                else
                {
                    throw new Exception("BlobTransfer already initiated. Create new BlobTransfer object to initiate a new file transfer.");
                }
            }

            // Attempt to open the file first so that we throw an exception before getting into the async work
            using (var fstemp = new FileStream(localFile, FileMode.Open, FileAccess.Read)) { }

            // Create an async op in order to raise the events back to the client on the correct thread.
            asyncOp = AsyncOperationManager.CreateOperation(this.blob);

            TransferType = TransferTypeEnum.Upload;
            fileName     = localFile;

            var  file     = new FileInfo(fileName);
            long fileSize = file.Length;

            FileStream     fs      = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read);
            ProgressStream pstream = new ProgressStream(fs);

            pstream.ProgressChanged += pstream_ProgressChanged;
            pstream.SetLength(fileSize);
            this.blob.ServiceClient.ParallelOperationThreadCount = 10;
            asyncresult = this.blob.BeginUploadFromStream(pstream, BlobTransferCompletedCallback, new BlobTransferAsyncState(this.blob, pstream));
            return(asyncresult);
        }
        private async Task OnBinaryMessageReceived(WebSocketHandler handler, byte[] bytes, string conversationId, string watermark)
        {
            int musicId  = BitConverter.ToInt32(bytes, 0);
            int startIdx = BitConverter.ToInt32(bytes, sizeof(int));

            Trace.TraceInformation(String.Format("get id {0}", musicId));
            Trace.TraceInformation(String.Format("start from {0}", startIdx));

            Uri       uri  = new Uri(baseURL + String.Format("{0}.wav", musicId));
            CloudFile file = new CloudFile(uri, storageCredentials);

            Trace.TraceInformation(uri.AbsoluteUri);
            byte[] totalBytes = new byte[file.Properties.Length];
            try
            {
                using (AutoResetEvent waitHandle = new AutoResetEvent(false))
                {
                    ICancellableAsyncResult result = file.BeginDownloadRangeToByteArray(totalBytes, 0, null, null, ar => waitHandle.Set(), null);
                    waitHandle.WaitOne();
                }
            } catch (Exception ex)
            {
                Trace.TraceError(ex.ToString());
            }

            Trace.TraceInformation(String.Format("File length {0}", totalBytes.Length));
            totalBytes = totalBytes.Skip(startIdx).ToArray();
            await handler.SendBinary(totalBytes, cts.Token);
        }
Example #7
0
        public async Task <IList <TableResult> > InsertBatchAsync(IEnumerable <UserMedia> entities, CancellationToken ct = default(CancellationToken))
        {
            var tasks = new List <IList <TableResult> >();

            var entityBatches = entities.GroupAndSlice <UserMedia, string>(
                _maxBatchEntityCount,
                um => um.PartitionKey,
                KeyGroupPredicate
                );


            foreach (var entityBatch in entityBatches)
            {
                var tbo = new TableBatchOperation();

                foreach (var entity in entityBatch)
                {
                    tbo.Add(TableOperation.Insert(entity));
                }

                ICancellableAsyncResult ar = _cloudTable.BeginExecuteBatch(tbo, null, null);
                ct.Register(ar.Cancel);

                var batchTask = await Task.Factory.FromAsync <IList <TableResult> >(ar, _cloudTable.EndExecuteBatch).ConfigureAwait(false);

                tasks.Add(batchTask);
            }

            return(tasks.SelectMany(t => t).ToList());
        }
Example #8
0
        public static Task DeleteAsync(this CloudTable tbl, TableRequestOptions opt, OperationContext ctx, CancellationToken token)
        {
            ICancellableAsyncResult result = null;

            if (opt == null && ctx == null)
            {
                result = tbl.BeginDelete(null, null);
            }
            else
            {
                result = tbl.BeginDelete(opt, ctx, null, null);
            }

            var cancellationRegistration = token.Register(result.Cancel);

            return(Task.Factory.FromAsync(result, ar =>
            {
                cancellationRegistration.Dispose();
                try
                {
                    tbl.EndDelete(ar);
                }
                catch (StorageException se)
                {
                    // Todo: Use the PnP azure retry block here for transient exceptions
                    throw;
                }
            }));
        }
        public override ICancellableAsyncResult BeginCommit(AsyncCallback callback, object state)
        {
            StorageAsyncResult <NullType> storageAsyncResult = new StorageAsyncResult <NullType>(callback, state);
            ICancellableAsyncResult       result             = this.BeginFlush(this.CommitFlushCallback, storageAsyncResult);

            storageAsyncResult.CancelDelegate = result.Cancel;
            return(storageAsyncResult);
        }
        public static Task <bool> CreateIfNotExistsAsync(this CloudTable table,
                                                         CancellationToken ct = default(CancellationToken))
        {
            ICancellableAsyncResult ar = table.BeginCreateIfNotExists(null, null);

            ct.Register(ar.Cancel);

            return(Task.Factory.FromAsync <bool>(ar, table.EndCreateIfNotExists));
        }
Example #11
0
        public async Task <TableResult> InsertAsync(UserMedia entity, CancellationToken ct = default(CancellationToken))
        {
            var insertOperation = TableOperation.Insert(entity);

            ICancellableAsyncResult ar = _cloudTable.BeginExecute(insertOperation, null, null);

            ct.Register(ar.Cancel);

            return(await Task.Factory.FromAsync <TableResult>(ar, _cloudTable.EndExecute).ConfigureAwait(false));
        }
Example #12
0
        /// <summary>
        /// Adds a task to be run on the main UI thread and blocks this thread until the task completes.
        /// The task is pumped at the given interval
        /// </summary>
        public static void ExecuteTask(TaskForUIThread task, object context, TimeSpan interval)
        {
            ICancellableAsyncResult result = BeginExecuteTask(task, context, interval);

            if (!result.IsCompleted)
            {
                // block forever waiting!
                result.AsyncWaitHandle.WaitOne();
            }
        }
Example #13
0
        public Task <TableResult> GetEntityAsync(string partitionKey, string rowKey, CancellationToken ct = default(CancellationToken))
        {
            // Retrieval of entity by exact match, PartitionKey and RowKey, full primary key, the fastest search
            TableOperation operation = TableOperation.Retrieve <UserMedia>(partitionKey, rowKey);

            ICancellableAsyncResult ar = _cloudTable.BeginExecute(operation, null, null);

            ct.Register(ar.Cancel);

            return(Task.Factory.FromAsync <TableResult>(ar, _cloudTable.EndExecute));
        }
        public static Task <IList <TableResult> > ExecuteBatchAsync(
            this CloudTable table,
            TableBatchOperation operation,
            CancellationToken ct = default(CancellationToken))
        {
            ICancellableAsyncResult ar = table.BeginExecuteBatch(operation, null, null);

            ct.Register(ar.Cancel);

            return(Task.Factory.FromAsync <IList <TableResult> >(ar, table.EndExecuteBatch));
        }
        public static Task <TableResultSegment> ListTablesAsync(
            this CloudTableClient client,
            TableContinuationToken token,
            CancellationToken ct = default(CancellationToken))
        {
            ICancellableAsyncResult ar = client.BeginListTablesSegmented(token, null, null);

            ct.Register(ar.Cancel);

            return(Task.Factory.FromAsync <TableResultSegment>(ar, client.EndListTablesSegmented));
        }
Example #16
0
        private static Task <TResult> FromCancellableAsync <TArg1, TResult>(Func <TArg1, AsyncCallback, object, ICancellableAsyncResult> beginMethod, Func <IAsyncResult, TResult> endMethod, TArg1 arg1, CancellationToken token)
        {
            ICancellableAsyncResult result = beginMethod(arg1, null, null);
            var cancellationRegistration   = token.Register(result.Cancel);


            return(Task.Factory.FromAsync(result, asyncResult =>
            {
                cancellationRegistration.Dispose();
                return endMethod(asyncResult);
            }));
        }
Example #17
0
        /// <summary>
        ///     Executes the query async.
        /// </summary>
        /// <typeparam name="T">
        ///     Requsted type
        /// </typeparam>
        /// <param name="table">
        ///     The table.
        /// </param>
        /// <param name="query">
        ///     The query.
        /// </param>
        /// <param name="token">
        ///     The token.
        /// </param>
        /// <param name="cancellationToken">
        ///     The cancellation token.
        /// </param>
        /// <returns>
        ///     Task{TableQuerySegment{``0}}.
        /// </returns>
        private static Task <TableQuerySegment <T> > ExecuteQueryAsync <T>(
            this CloudTable table,
            TableQuery <T> query,
            TableContinuationToken token,
            CancellationToken cancellationToken = default(CancellationToken)) where T : ITableEntity, new()
        {
            ICancellableAsyncResult ar = table.BeginExecuteQuerySegmented(query, token, null, null);

            cancellationToken.Register(ar.Cancel);

            return(Task.Factory.FromAsync <TableQuerySegment <T> >(ar, table.EndExecuteQuerySegmented <T>));
        }
        public override ICancellableAsyncResult BeginCommit(AsyncCallback callback, object state)
        {
            if (this.committed)
            {
                throw new InvalidOperationException(SR.FileStreamAlreadyCommitted);
            }

            StorageAsyncResult <NullType> storageAsyncResult = new StorageAsyncResult <NullType>(callback, state);
            ICancellableAsyncResult       result             = this.BeginFlush(this.CommitFlushCallback, storageAsyncResult);

            storageAsyncResult.CancelDelegate = result.Cancel;
            return(storageAsyncResult);
        }
Example #19
0
        internal Task <TableQuerySegment <T> > ExecuteQueryAsync(
            TableQuery <T> query,
            TableContinuationToken token = default(TableContinuationToken),
            CancellationToken ct         = default(CancellationToken))
        {
            token = token ?? new TableContinuationToken();

            ICancellableAsyncResult ar = CloudTable.Value.BeginExecuteQuerySegmented(query, token, null, null);

            ct.Register(ar.Cancel);

            return(Task.Factory.FromAsync <TableQuerySegment <T> >(ar, CloudTable.Value.EndExecuteQuerySegmented <T>));
        }
        public void CloudBlockBlobDownloadToStreamAPMCancel()
        {
            byte[]             buffer    = GetRandomBuffer(1 * 1024 * 1024);
            CloudBlobContainer container = GetRandomContainerReference();

            try
            {
                container.Create();

                CloudBlockBlob blob = container.GetBlockBlobReference("blob1");
                using (MemoryStream originalBlob = new MemoryStream(buffer))
                {
                    using (AutoResetEvent waitHandle = new AutoResetEvent(false))
                    {
                        ICancellableAsyncResult result = blob.BeginUploadFromStream(originalBlob,
                                                                                    ar => waitHandle.Set(),
                                                                                    null);
                        waitHandle.WaitOne();
                        blob.EndUploadFromStream(result);

                        using (MemoryStream downloadedBlob = new MemoryStream())
                        {
                            OperationContext operationContext = new OperationContext();
                            result = blob.BeginDownloadToStream(downloadedBlob, null, null, operationContext,
                                                                ar => waitHandle.Set(),
                                                                null);
                            Thread.Sleep(100);
                            result.Cancel();
                            waitHandle.WaitOne();
                            try
                            {
                                blob.EndDownloadToStream(result);
                            }
                            catch (StorageException ex)
                            {
                                Assert.AreEqual(ex.Message, "Operation was canceled by user.");
                                Assert.AreEqual(ex.RequestInformation.HttpStatusCode, 306);
                                Assert.AreEqual(ex.RequestInformation.HttpStatusMessage, "Unused");
                            }
                            TestHelper.AssertNAttempts(operationContext, 1);
                        }
                    }
                }
            }
            finally
            {
                container.DeleteIfExists();
            }
        }
Example #21
0
        /// <summary>
        ///     Gets the properties of the table service asynchronously.
        /// </summary>
        /// <param name="tableClient">Cloud table client.</param>
        /// <param name="cancellationToken">Cancellation token.</param>
        /// <returns>Task.</returns>
        public static Task <ServiceProperties> GetServicePropertiesAsync(
            this CloudTableClient tableClient,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            ICancellableAsyncResult       asyncResult  = tableClient.BeginGetServiceProperties(null, null);
            CancellationTokenRegistration registration = cancellationToken.Register(p => asyncResult.Cancel(), null);

            return(Task <ServiceProperties> .Factory.FromAsync(
                       asyncResult,
                       result =>
            {
                registration.Dispose();
                return tableClient.EndGetServiceProperties(result);
            }));
        }
Example #22
0
        /// <summary>
        ///     Deletes the table if it exists asynchronously.
        /// </summary>
        /// <param name="cloudTable">Cloud table.</param>
        /// <param name="cancellationToken">Cancellation token.</param>
        /// <returns>
        ///     <c>true</c> if the table was deleted; otherwise, <c>false</c>.
        /// </returns>
        public static Task <bool> DeleteIfExistsAsync(
            this CloudTable cloudTable,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            ICancellableAsyncResult       asyncResult  = cloudTable.BeginDeleteIfExists(null, null);
            CancellationTokenRegistration registration = cancellationToken.Register(p => asyncResult.Cancel(), null);

            return(Task <bool> .Factory.FromAsync(
                       asyncResult,
                       result =>
            {
                registration.Dispose();
                return cloudTable.EndDeleteIfExists(result);
            }));
        }
Example #23
0
        /// <summary>
        ///     Gets the permissions settings for the table asynchronously.
        /// </summary>
        /// <param name="cloudTable">Cloud table.</param>
        /// <param name="cancellationToken">Cancellation token.</param>
        /// <returns>
        ///     The table's permissions.
        /// </returns>
        public static Task <TablePermissions> GetPermissionsAsync(
            this CloudTable cloudTable,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            ICancellableAsyncResult       asyncResult  = cloudTable.BeginGetPermissions(null, null);
            CancellationTokenRegistration registration = cancellationToken.Register(p => asyncResult.Cancel(), null);

            return(Task <TablePermissions> .Factory.FromAsync(
                       asyncResult,
                       result =>
            {
                registration.Dispose();
                return cloudTable.EndGetPermissions(result);
            }));
        }
Example #24
0
        /// <summary>
        ///     Creates a table asynchronously.
        /// </summary>
        /// <param name="cloudTable">Cloud table.</param>
        /// <param name="cancellationToken">Cancellation token.</param>
        /// <returns>Task.</returns>
        public static Task CreateAsync(
            this CloudTable cloudTable,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            ICancellableAsyncResult       asyncResult  = cloudTable.BeginCreate(null, null);
            CancellationTokenRegistration registration = cancellationToken.Register(p => asyncResult.Cancel(), null);

            return(Task.Factory.FromAsync(
                       asyncResult,
                       result =>
            {
                registration.Dispose();
                cloudTable.EndCreate(result);
            }));
        }
Example #25
0
        // asynchronously get first 1000 entities in a given partition, pass in continuation token
        // to retreive next 1000 entities and cancellation token to be able to signal to stop processing
        // externally.  Cancellation token is optional.
        public async Task <TableQuerySegment <UserMedia> > GetPartitionAsync(string partitionKey, TableContinuationToken token = null, CancellationToken ct = default(CancellationToken))
        {
            var tableQuery = new TableQuery <UserMedia>();

            // Create and Set PartitionKey filter
            var filter = CreatePartitionKeyFilter(partitionKey);

            tableQuery = tableQuery.Where(filter);

            ICancellableAsyncResult ar = _cloudTable.BeginExecuteQuerySegmented(tableQuery, token, null, null);

            ct.Register(ar.Cancel);

            return(await Task.Factory.FromAsync <TableQuerySegment <UserMedia> >(ar, _cloudTable.EndExecuteQuerySegmented <UserMedia>).ConfigureAwait(false));
        }
Example #26
0
        /// <summary>
        ///     Executes a batch of operations on a table asynchronously.
        /// </summary>
        /// <param name="cloudTable">Cloud table.</param>
        /// <param name="tableBatchOperation">
        ///     The <see cref="T:Microsoft.WindowsAzure.Storage.Table.TableBatchOperation" /> object representing the operations to execute on the table.
        /// </param>
        /// <param name="cancellationToken">Cancalltion token.</param>
        /// <returns>
        ///     An enumerable collection of <see cref="T:Microsoft.WindowsAzure.Storage.Table.TableResult" /> objects that contains the results, in order, of each operation in the
        ///     <see cref="T:Microsoft.WindowsAzure.Storage.Table.TableBatchOperation" />
        ///     on the table.
        /// </returns>
        public static Task <IList <TableResult> > ExecuteBatchAsync(
            this CloudTable cloudTable,
            TableBatchOperation tableBatchOperation,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            ICancellableAsyncResult       asyncResult  = cloudTable.BeginExecuteBatch(tableBatchOperation, null, null);
            CancellationTokenRegistration registration = cancellationToken.Register(p => asyncResult.Cancel(), null);

            return(Task <IList <TableResult> > .Factory.FromAsync(
                       asyncResult,
                       result =>
            {
                registration.Dispose();
                return cloudTable.EndExecuteBatch(result);
            }));
        }
Example #27
0
        // Similar to TaskFactory.FromAsync, except it supports cancellation using ICancellableAsyncResult.
        public static Task FromAsync(Func <AsyncCallback, object, ICancellableAsyncResult> beginMethod,
                                     Action <IAsyncResult> endMethod, CancellationToken cancellationToken)
        {
            TaskCompletionSource <object> source = new TaskCompletionSource <object>();

            CancellationTokenRegistration cancellationRegistration = new CancellationTokenRegistration();
            bool   cancellationRegistrationDisposed = false;
            object cancellationRegistrationLock     = new object();

            ICancellableAsyncResult result = beginMethod.Invoke((ar) =>
            {
                lock (cancellationRegistrationLock)
                {
                    cancellationRegistration.Dispose();
                    cancellationRegistrationDisposed = true;
                }

                try
                {
                    endMethod.Invoke(ar);
                    source.SetResult(null);
                }
                catch (OperationCanceledException)
                {
                    source.SetCanceled();
                }
                catch (Exception exception)
                {
                    source.SetException(exception);
                }
            }, null);

            lock (cancellationRegistrationLock)
            {
                if (!cancellationRegistrationDisposed)
                {
                    cancellationRegistration = cancellationToken.Register(result.Cancel);
                }
            }

            if (result.CompletedSynchronously)
            {
                System.Diagnostics.Debug.Assert(source.Task.IsCompleted);
            }

            return(source.Task);
        }
Example #28
0
        /// <summary>
        ///     Executes an operation to query a table in segmented mode asynchronously.
        /// </summary>
        /// <param name="cloudTable">Cloud table.</param>
        /// <param name="tableQuery">
        ///     A <see cref="T:Microsoft.WindowsAzure.Storage.Table.TableQuery" /> instance specifying the table to query and the query parameters to use, specialized for a type <c>TElement</c>.
        /// </param>
        /// <param name="continuationToken">
        ///     A <see cref="T:Microsoft.WindowsAzure.Storage.Table.TableContinuationToken" /> object representing a continuation token from the server when the operation returns a partial result.
        /// </param>
        /// <param name="cancellationToken">Cancellation token.</param>
        /// <returns>
        ///     A <see cref="T:Microsoft.WindowsAzure.Storage.Table.TableQuerySegment`1" /> containing the projection into type <c>R</c> of the results of executing the query.
        /// </returns>
        public static Task <TableQuerySegment <DynamicTableEntity> > ExecuteQuerySegmentedAsync(
            this CloudTable cloudTable,
            TableQuery tableQuery,
            TableContinuationToken continuationToken,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            ICancellableAsyncResult asyncResult = cloudTable.BeginExecuteQuerySegmented(
                tableQuery, continuationToken, null, null);
            CancellationTokenRegistration registration = cancellationToken.Register(p => asyncResult.Cancel(), null);

            return(Task <TableQuerySegment <DynamicTableEntity> > .Factory.FromAsync(
                       asyncResult,
                       result =>
            {
                registration.Dispose();
                return cloudTable.EndExecuteQuerySegmented(result);
            }));
        }
Example #29
0
        internal static Task TaskFromVoidApm <T1, T2>(Func <T1, T2, AsyncCallback, object, ICancellableAsyncResult> beginMethod, Action <IAsyncResult> endMethod, T1 arg1, T2 arg2, CancellationToken cancellationToken)
        {
            TaskCompletionSource <object> taskCompletionSource = new TaskCompletionSource <object>();

            if (cancellationToken.IsCancellationRequested)
            {
                taskCompletionSource.TrySetCanceled();
            }
            else
            {
                CancellableOperationBase      cancellableOperation;
                CancellationTokenRegistration?registration = RegisterCancellationToken(cancellationToken, out cancellableOperation);
                ICancellableAsyncResult       result       = beginMethod(arg1, arg2, CreateCallbackVoid(taskCompletionSource, registration, endMethod), null /* state */);
                AssignCancellableOperation(cancellableOperation, result, cancellationToken);
            }

            return(taskCompletionSource.Task);
        }
Example #30
0
        internal static Task <TResult> TaskFromApm <T1, T2, T3, T4, T5, T6, T7, TResult>(Func <T1, T2, T3, T4, T5, T6, T7, AsyncCallback, object, ICancellableAsyncResult> beginMethod, Func <IAsyncResult, TResult> endMethod, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, CancellationToken cancellationToken)
        {
            TaskCompletionSource <TResult> taskCompletionSource = new TaskCompletionSource <TResult>();

            if (cancellationToken.IsCancellationRequested)
            {
                taskCompletionSource.TrySetCanceled();
            }
            else
            {
                CancellableOperationBase      cancellableOperation;
                CancellationTokenRegistration?registration = RegisterCancellationToken(cancellationToken, out cancellableOperation);
                ICancellableAsyncResult       result       = beginMethod(arg1, arg2, arg3, arg4, arg5, arg6, arg7, CreateCallback(taskCompletionSource, registration, endMethod), null /* state */);
                AssignCancellableOperation(cancellableOperation, result, cancellationToken);
            }

            return(taskCompletionSource.Task);
        }
Example #31
0
        /// <summary>
        /// Uploads a file to an Azure blob asynchronously.
        /// </summary>
        /// <param name="localFile">The local file.</param>
        /// <exception cref="System.Exception">BlobTransfer already initiated. Create new BlobTransfer object to initiate a new file transfer.</exception>
        public ICancellableAsyncResult UploadBlobAsync(string localFile)
        {
            lock (workingLock)
            {
                if (!working)
                    working = true;
                else
                    throw new Exception("BlobTransfer already initiated. Create new BlobTransfer object to initiate a new file transfer.");
            }

            // Attempt to open the file first so that we throw an exception before getting into the async work
            using (var fstemp = new FileStream(localFile, FileMode.Open, FileAccess.Read)) { }

            // Create an async op in order to raise the events back to the client on the correct thread.
            asyncOp = AsyncOperationManager.CreateOperation(this.blob);

            TransferType = TransferTypeEnum.Upload;
            fileName = localFile;

            var file = new FileInfo(fileName);
            long fileSize = file.Length;

            FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read);
            ProgressStream pstream = new ProgressStream(fs);
            pstream.ProgressChanged += pstream_ProgressChanged;
            pstream.SetLength(fileSize);
            this.blob.ServiceClient.ParallelOperationThreadCount = 10;
            asyncresult = this.blob.BeginUploadFromStream(pstream, BlobTransferCompletedCallback, new BlobTransferAsyncState(this.blob, pstream));
            return asyncresult;
        }
        public void UploadBlobAsync(ICloudBlob blob, string LocalFile)
        {
            // The class currently stores state in class level variables so calling UploadBlobAsync or DownloadBlobAsync a second time will cause problems.
            // A better long term solution would be to better encapsulate the state, but the current solution works for the needs of my primary client.
            // Throw an exception if UploadBlobAsync or DownloadBlobAsync has already been called.
            lock (WorkingLock)
            {
                if (!Working)
                    Working = true;
                else
                    throw new Exception("BlobTransfer already initiated. Create new BlobTransfer object to initiate a new file transfer.");
            }

            // Attempt to open the file first so that we throw an exception before getting into the async work
            using (FileStream fstemp = new FileStream(LocalFile, FileMode.Open, FileAccess.Read)) { }

            // Create an async op in order to raise the events back to the client on the correct thread.
            asyncOp = AsyncOperationManager.CreateOperation(blob);

            TransferType = TransferTypeEnum.Upload;
            m_Blob = blob;
            m_FileName = LocalFile;

            var file = new FileInfo(m_FileName);
            long fileSize = file.Length;

            FileStream fs = new FileStream(m_FileName, FileMode.Open, FileAccess.Read, FileShare.Read);
            ProgressStream pstream = new ProgressStream(fs);
            pstream.ProgressChanged += pstream_ProgressChanged;
            pstream.SetLength(fileSize);
            m_Blob.ServiceClient.ParallelOperationThreadCount = 10;
            asyncresult = m_Blob.BeginUploadFromStream(pstream, BlobTransferCompletedCallback, new BlobTransferAsyncState(m_Blob, pstream));
        }
Example #33
0
        /// <summary>
        /// Downloads a blob to a local file asynchronously.
        /// </summary>
        /// <param name="localFile">The local file.</param>
        /// <exception cref="System.Exception">BlobTransfer already initiated. Create new BlobTransfer object to initiate a new file transfer.</exception>
        public ICancellableAsyncResult DownloadBlobAsync(string localFile)
        {
            lock (workingLock)
            {
                if (!working)
                    working = true;
                else
                    throw new Exception("BlobTransfer already initiated. Create new BlobTransfer object to initiate a new file transfer.");
            }

            // Create an async op in order to raise the events back to the client on the correct thread.
            asyncOp = AsyncOperationManager.CreateOperation(blob);

            TransferType = TransferTypeEnum.Download;
            fileName = localFile;

            this.blob.FetchAttributes();

            FileStream fs = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.Write, FileShare.Read);
            ProgressStream pstream = new ProgressStream(fs);
            pstream.ProgressChanged += pstream_ProgressChanged;
            pstream.SetLength(this.blob.Properties.Length);
            this.blob.ServiceClient.ParallelOperationThreadCount = 10;
            asyncresult = this.blob.BeginDownloadToStream(pstream, BlobTransferCompletedCallback, new BlobTransferAsyncState(this.blob, pstream));
            return asyncresult;
        }