public async Task <ItemResponse <T> > CreateItemAsync <T>(
            CosmosDiagnosticsContext diagnosticsContext,
            T item,
            PartitionKey?partitionKey           = null,
            ItemRequestOptions requestOptions   = null,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            if (item == null)
            {
                throw new ArgumentNullException(nameof(item));
            }

            ResponseMessage response = await this.ExtractPartitionKeyAndProcessItemStreamAsync(
                partitionKey : partitionKey,
                itemId : null,
                item : item,
                operationType : OperationType.Create,
                requestOptions : requestOptions,
                diagnosticsContext : diagnosticsContext,
                cancellationToken : cancellationToken);

            return(this.ClientContext.ResponseFactory.CreateItemResponse <T>(response));
        }
        public async Task <ItemResponse <T> > UpsertItemAsync <T>(
            T item,
            ITrace trace,
            PartitionKey?partitionKey           = null,
            ItemRequestOptions requestOptions   = null,
            CancellationToken cancellationToken = default)
        {
            if (item == null)
            {
                throw new ArgumentNullException(nameof(item));
            }

            ResponseMessage response = await this.ExtractPartitionKeyAndProcessItemStreamAsync(
                partitionKey : partitionKey,
                itemId : null,
                item : item,
                operationType : OperationType.Upsert,
                requestOptions : requestOptions,
                trace : trace,
                cancellationToken : cancellationToken);

            return(this.ClientContext.ResponseFactory.CreateItemResponse <T>(response));
        }
        private async Task <ResponseMessage> ProcessItemStreamAsync(
            PartitionKey?partitionKey,
            string itemId,
            Stream streamPayload,
            OperationType operationType,
            ItemRequestOptions requestOptions,
            CosmosDiagnosticsContext diagnosticsContext,
            CancellationToken cancellationToken)
        {
            if (diagnosticsContext == null)
            {
                throw new ArgumentNullException(nameof(diagnosticsContext));
            }

            if (requestOptions != null && requestOptions.IsEffectivePartitionKeyRouting)
            {
                partitionKey = null;
            }

            ContainerInternal.ValidatePartitionKey(partitionKey, requestOptions);
            string resourceUri = this.GetResourceUri(requestOptions, operationType, itemId);

            ResponseMessage responseMessage = await this.ClientContext.ProcessResourceOperationStreamAsync(
                resourceUri : resourceUri,
                resourceType : ResourceType.Document,
                operationType : operationType,
                requestOptions : requestOptions,
                cosmosContainerCore : this,
                partitionKey : partitionKey,
                itemId : itemId,
                streamPayload : streamPayload,
                requestEnricher : null,
                diagnosticsContext : diagnosticsContext,
                cancellationToken : cancellationToken);

            return(responseMessage);
        }
 /// <summary>
 /// Gets an iterator to go through all the items for the container as the original CosmosResponseMessage
 /// </summary>
 /// <param name="maxItemCount">(Optional) The max item count to return as part of the query</param>
 /// <param name="continuationToken">(Optional) The continuation token in the Azure Cosmos DB service.</param>
 /// <param name="requestOptions">(Optional) The options for the item query request <see cref="QueryRequestOptions"/></param>
 /// <example>
 /// Get an iterator for all the items under the cosmos container
 /// <code language="c#">
 /// <![CDATA[
 /// public class ToDoActivity{
 ///     public string id {get; set;}
 ///     public string status {get; set;}
 /// }
 ///
 /// FeedIterator feedIterator = this.Container.Items.GetItemsStreamIterator();
 /// while (feedIterator.HasMoreResults)
 /// {
 ///     using (CosmosResponseMessage iterator = await feedIterator.FetchNextSetAsync())
 ///     {
 ///         using (StreamReader sr = new StreamReader(iterator.Content))
 ///         {
 ///             string content = await sr.ReadToEndAsync();
 ///         }
 ///     }
 /// }
 /// ]]>
 /// </code>
 /// </example>
 /// <returns>An iterator to go through the items.</returns>
 public abstract FeedIterator GetItemsStreamIterator(
     int?maxItemCount                  = null,
     string continuationToken          = null,
     ItemRequestOptions requestOptions = null);
        internal static Result WriteOperation(ref RowWriter writer, TypeArgument typeArg, ItemBatchOperation operation)
        {
            bool   pkWritten = false;
            Result r         = writer.WriteInt32("operationType", (int)operation.OperationType);

            if (r != Result.Success)
            {
                return(r);
            }

            r = writer.WriteInt32("resourceType", (int)ResourceType.Document);
            if (r != Result.Success)
            {
                return(r);
            }

            if (operation.PartitionKeyJson != null)
            {
                r = writer.WriteString("partitionKey", operation.PartitionKeyJson);
                if (r != Result.Success)
                {
                    return(r);
                }

                pkWritten = true;
            }

            if (operation.Id != null)
            {
                r = writer.WriteString("id", operation.Id);
                if (r != Result.Success)
                {
                    return(r);
                }
            }

            if (!operation.ResourceBody.IsEmpty)
            {
                r = writer.WriteBinary("resourceBody", operation.ResourceBody.Span);
                if (r != Result.Success)
                {
                    return(r);
                }
            }

            if (operation.RequestOptions != null)
            {
                TransactionalBatchItemRequestOptions options = operation.RequestOptions;
                if (options.IndexingDirective.HasValue)
                {
                    string indexingDirectiveString = IndexingDirectiveStrings.FromIndexingDirective(options.IndexingDirective.Value);
                    r = writer.WriteString("indexingDirective", indexingDirectiveString);
                    if (r != Result.Success)
                    {
                        return(r);
                    }
                }

                if (ItemRequestOptions.ShouldSetNoContentHeader(
                        options.EnableContentResponseOnWrite,
                        options.EnableContentResponseOnRead,
                        operation.OperationType))
                {
                    r = writer.WriteBool("minimalReturnPreference", true);
                    if (r != Result.Success)
                    {
                        return(r);
                    }
                }

                if (options.IfMatchEtag != null)
                {
                    r = writer.WriteString("ifMatch", options.IfMatchEtag);
                    if (r != Result.Success)
                    {
                        return(r);
                    }
                }
                else if (options.IfNoneMatchEtag != null)
                {
                    r = writer.WriteString("ifNoneMatch", options.IfNoneMatchEtag);
                    if (r != Result.Success)
                    {
                        return(r);
                    }
                }

                if (options.Properties != null)
                {
                    if (options.Properties.TryGetValue(WFConstants.BackendHeaders.BinaryId, out object binaryIdObj))
                    {
                        if (binaryIdObj is byte[] binaryId)
                        {
                            r = writer.WriteBinary("binaryId", binaryId);
                            if (r != Result.Success)
                            {
                                return(r);
                            }
                        }
                    }

                    if (options.Properties.TryGetValue(WFConstants.BackendHeaders.EffectivePartitionKey, out object epkObj))
                    {
                        if (epkObj is byte[] epk)
                        {
                            r = writer.WriteBinary("effectivePartitionKey", epk);
                            if (r != Result.Success)
                            {
                                return(r);
                            }
                        }
                    }

                    if (!pkWritten && options.Properties.TryGetValue(
                            HttpConstants.HttpHeaders.PartitionKey,
                            out object pkStrObj))
                    {
                        if (pkStrObj is string pkString)
                        {
                            r = writer.WriteString("partitionKey", pkString);
                            if (r != Result.Success)
                            {
                                return(r);
                            }
                        }
                    }

                    if (options.Properties.TryGetValue(WFConstants.BackendHeaders.TimeToLiveInSeconds, out object ttlObj))
                    {
                        if (ttlObj is string ttlStr && int.TryParse(ttlStr, out int ttl))
                        {
                            r = writer.WriteInt32("timeToLiveInSeconds", ttl);
                            if (r != Result.Success)
                            {
                                return(r);
                            }
                        }
                    }
                }
            }

            return(Result.Success);
        }
        // Extracted partition key might be invalid as CollectionCache might be stale.
        // Stale collection cache is refreshed through PartitionKeyMismatchRetryPolicy
        // and partition-key is extracted again.
        private async Task <ResponseMessage> ExtractPartitionKeyAndProcessItemStreamAsync <T>(
            PartitionKey?partitionKey,
            string itemId,
            T item,
            OperationType operationType,
            ItemRequestOptions requestOptions,
            CosmosDiagnosticsContext diagnosticsContext,
            CancellationToken cancellationToken)
        {
            if (diagnosticsContext == null)
            {
                throw new ArgumentNullException(nameof(diagnosticsContext));
            }

            Stream itemStream;

            using (diagnosticsContext.CreateScope("ItemSerialize"))
            {
                itemStream = this.ClientContext.SerializerCore.ToStream <T>(item);
            }

            // User specified PK value, no need to extract it
            if (partitionKey.HasValue)
            {
                PartitionKeyDefinition pKeyDefinition = await this.GetPartitionKeyDefinitionAsync();

                if (partitionKey.HasValue && partitionKey.Value != PartitionKey.None && partitionKey.Value.InternalKey.Components.Count != pKeyDefinition.Paths.Count)
                {
                    throw new ArgumentException(RMResources.MissingPartitionKeyValue);
                }

                return(await this.ProcessItemStreamAsync(
                           partitionKey,
                           itemId,
                           itemStream,
                           operationType,
                           requestOptions,
                           diagnosticsContext : diagnosticsContext,
                           cancellationToken : cancellationToken));
            }

            PartitionKeyMismatchRetryPolicy requestRetryPolicy = null;

            while (true)
            {
                using (diagnosticsContext.CreateScope("ExtractPkValue"))
                {
                    partitionKey = await this.GetPartitionKeyValueFromStreamAsync(itemStream, cancellationToken);
                }

                ResponseMessage responseMessage = await this.ProcessItemStreamAsync(
                    partitionKey,
                    itemId,
                    itemStream,
                    operationType,
                    requestOptions,
                    diagnosticsContext : diagnosticsContext,
                    cancellationToken : cancellationToken);

                if (responseMessage.IsSuccessStatusCode)
                {
                    return(responseMessage);
                }

                if (requestRetryPolicy == null)
                {
                    requestRetryPolicy = new PartitionKeyMismatchRetryPolicy(await this.ClientContext.DocumentClient.GetCollectionCacheAsync(), null);
                }

                ShouldRetryResult retryResult = await requestRetryPolicy.ShouldRetryAsync(responseMessage, cancellationToken);

                if (!retryResult.ShouldRetry)
                {
                    return(responseMessage);
                }
            }
        }
 /// <summary>
 /// Patches an item in the Azure Cosmos service as an asynchronous operation.
 /// </summary>
 /// <remarks>
 /// By default, resource body will be returned as part of the response. User can request no content by setting <see cref="ItemRequestOptions.EnableContentResponseOnWrite"/> flag to false.
 /// </remarks>
 /// <param name="id">The Cosmos item id</param>
 /// <param name="partitionKey">The partition key for the item.</param>
 /// <param name="streamPayload">Represents a stream containing the list of operations to be sequentially applied to the referred Cosmos item.</param>
 /// <param name="requestOptions">(Optional) The options for the item request.</param>
 /// <param name="cancellationToken">(Optional) <see cref="CancellationToken"/> representing request cancellation.</param>
 /// <returns>
 /// A <see cref="Task"/> containing a <see cref="ResponseMessage"/> which wraps a <see cref="Stream"/> containing the patched resource record.
 /// </returns>
 public abstract Task <ResponseMessage> PatchItemStreamAsync(
     string id,
     PartitionKey partitionKey,
     Stream streamPayload,
     ItemRequestOptions requestOptions   = null,
     CancellationToken cancellationToken = default);
 public abstract Task <ItemResponse <T> > PatchItemAsync <T>(
     string id,
     PartitionKey partitionKey,
     IReadOnlyList <PatchOperation> patchOperations,
     ItemRequestOptions requestOptions   = null,
     CancellationToken cancellationToken = default);
        internal async Task <ResponseMessage> ProcessItemStreamAsync(
            PartitionKey?partitionKey,
            string itemId,
            Stream streamPayload,
            OperationType operationType,
            ItemRequestOptions requestOptions,
            CosmosDiagnosticsContext diagnosticsContext,
            CancellationToken cancellationToken)
        {
            if (requestOptions != null && requestOptions.IsEffectivePartitionKeyRouting)
            {
                partitionKey = null;
            }

            ContainerCore.ValidatePartitionKey(partitionKey, requestOptions);
            Uri resourceUri = this.GetResourceUri(requestOptions, operationType, itemId);

            if (diagnosticsContext == null)
            {
                diagnosticsContext = CosmosDiagnosticsContext.Create(requestOptions);
            }

            using (diagnosticsContext.CreateOverallScope("ProcessItemStream"))
            {
                if (requestOptions != null && requestOptions.EncryptionOptions != null)
                {
                    if (streamPayload == null)
                    {
                        throw new ArgumentException(ClientResources.InvalidRequestWithEncryptionOptions);
                    }

                    using (diagnosticsContext.CreateScope("Encrypt"))
                    {
                        streamPayload = await this.ClientContext.EncryptionProcessor.EncryptAsync(
                            streamPayload,
                            requestOptions.EncryptionOptions,
                            (DatabaseCore)this.Database,
                            this.ClientContext.ClientOptions.EncryptionKeyWrapProvider,
                            diagnosticsContext,
                            cancellationToken);
                    }
                }

                ResponseMessage responseMessage = await this.ClientContext.ProcessResourceOperationStreamAsync(
                    resourceUri : resourceUri,
                    resourceType : ResourceType.Document,
                    operationType : operationType,
                    requestOptions : requestOptions,
                    cosmosContainerCore : this,
                    partitionKey : partitionKey,
                    itemId : itemId,
                    streamPayload : streamPayload,
                    requestEnricher : null,
                    diagnosticsScope : diagnosticsContext,
                    cancellationToken : cancellationToken);

                if (responseMessage.Content != null && this.ClientContext.ClientOptions.EncryptionKeyWrapProvider != null)
                {
                    using (diagnosticsContext.CreateScope("Decrypt"))
                    {
                        responseMessage.Content = await this.ClientContext.EncryptionProcessor.DecryptAsync(
                            responseMessage.Content,
                            (DatabaseCore)this.Database,
                            this.ClientContext.ClientOptions.EncryptionKeyWrapProvider,
                            diagnosticsContext,
                            cancellationToken);
                    }
                }

                return(responseMessage);
            }
        }
 public abstract Task <ResponseMessage> PatchItemStreamAsync(
     string id,
     PartitionKey partitionKey,
     IReadOnlyList <PatchOperation> patchOperations,
     ItemRequestOptions requestOptions   = null,
     CancellationToken cancellationToken = default(CancellationToken));
 /// <summary>
 /// Creates a Item as an asynchronous operation in the Azure Cosmos service.
 /// </summary>
 /// <param name="partitionKey">The partition key for the item. <see cref="Microsoft.Azure.Documents.PartitionKey"/></param>
 /// <param name="streamPayload">A <see cref="Stream"/> containing the payload.</param>
 /// <param name="requestOptions">(Optional) The options for the item request <see cref="ItemRequestOptions"/></param>
 /// <param name="cancellationToken">(Optional) <see cref="CancellationToken"/> representing request cancellation.</param>
 /// <returns>The <see cref="CosmosResponseMessage"/> that was created contained within a <see cref="System.Threading.Tasks.Task"/> object representing the service response for the asynchronous operation.</returns>
 /// <exception>
 /// The Stream operation only throws on client side exceptions. This is to increase performance and prevent the overhead of throwing exceptions. Check the HTTP status code on the response to check if the operation failed.
 /// </exception>
 /// <example>
 /// This example creates an item in a Cosmos container.
 /// <code language="c#">
 /// <![CDATA[
 /// //Create the object in Cosmos
 /// using (CosmosResponseMessage response = await this.Container.CreateItemStreamAsync(partitionKey: "streamPartitionKey", streamPayload: stream))
 /// {
 ///     if (!response.IsSuccessStatusCode)
 ///     {
 ///         //Handle and log exception
 ///         return;
 ///     }
 ///
 ///     using (Stream responseStream = await response.ReadBodyAsync())
 ///     {
 ///         //Read or do other operations with the stream
 ///         using (StreamReader streamReader = new StreamReader(responseStream))
 ///         {
 ///             string responseContentAsString = await streamReader.ReadToEndAsync();
 ///         }
 ///     }
 /// }
 /// ]]>
 /// </code>
 /// </example>
 public abstract Task <CosmosResponseMessage> CreateItemStreamAsync(
     PartitionKey partitionKey,
     Stream streamPayload,
     ItemRequestOptions requestOptions   = null,
     CancellationToken cancellationToken = default(CancellationToken));
        // Extracted partition key might be invalid as CollectionCache might be stale.
        // Stale collection cache is refreshed through PartitionKeyMismatchRetryPolicy
        // and partition-key is extracted again.
        internal async Task <ResponseMessage> ExtractPartitionKeyAndProcessItemStreamAsync <T>(
            PartitionKey?partitionKey,
            string itemId,
            T item,
            OperationType operationType,
            ItemRequestOptions requestOptions,
            CancellationToken cancellationToken)
        {
            CosmosDiagnosticsContext diagnosticsContext = CosmosDiagnosticsContext.Create(requestOptions);

            using (diagnosticsContext.CreateOverallScope("ItemStream"))
            {
                Stream itemStream;
                using (diagnosticsContext.CreateScope("ItemSerialize"))
                {
                    itemStream = this.ClientContext.SerializerCore.ToStream <T>(item);
                }

                // User specified PK value, no need to extract it
                if (partitionKey.HasValue)
                {
                    return(await this.ProcessItemStreamAsync(
                               partitionKey,
                               itemId,
                               itemStream,
                               operationType,
                               requestOptions,
                               diagnosticsContext : diagnosticsContext,
                               cancellationToken : cancellationToken));
                }

                PartitionKeyMismatchRetryPolicy requestRetryPolicy = null;
                while (true)
                {
                    using (diagnosticsContext.CreateScope("ExtractPkValue"))
                    {
                        partitionKey = await this.GetPartitionKeyValueFromStreamAsync(itemStream, cancellationToken);
                    }

                    ResponseMessage responseMessage = await this.ProcessItemStreamAsync(
                        partitionKey,
                        itemId,
                        itemStream,
                        operationType,
                        requestOptions,
                        diagnosticsContext : diagnosticsContext,
                        cancellationToken : cancellationToken);

                    if (responseMessage.IsSuccessStatusCode)
                    {
                        return(responseMessage);
                    }

                    if (requestRetryPolicy == null)
                    {
                        requestRetryPolicy = new PartitionKeyMismatchRetryPolicy(await this.ClientContext.DocumentClient.GetCollectionCacheAsync(), null);
                    }

                    ShouldRetryResult retryResult = await requestRetryPolicy.ShouldRetryAsync(responseMessage, cancellationToken);

                    if (!retryResult.ShouldRetry)
                    {
                        return(responseMessage);
                    }
                }
            }
        }
 /// <summary>
 /// Delete a item from the Azure Cosmos service as an asynchronous operation.
 /// </summary>
 /// <param name="partitionKey">The partition key for the item. <see cref="Microsoft.Azure.Documents.PartitionKey"/></param>
 /// <param name="id">The cosmos item id</param>
 /// <param name="requestOptions">(Optional) The options for the item request <see cref="ItemRequestOptions"/></param>
 /// <param name="cancellationToken">(Optional) <see cref="CancellationToken"/> representing request cancellation.</param>
 /// <returns>A <see cref="Task"/> containing a <see cref="ItemResponse{T}"/> which will contain information about the request issued.</returns>
 /// <exception cref="CosmosException">
 /// This exception can encapsulate many different types of errors. To determine the specific error always look at the StatusCode property. Some common codes you may get when creating a Document are:
 /// <list type="table">
 ///     <listheader>
 ///         <term>StatusCode</term><description>Reason for exception</description>
 ///     </listheader>
 ///     <item>
 ///         <term>429</term><description>TooManyRequests - This means you have exceeded the number of request units per second.</description>
 ///     </item>
 /// </list>
 /// </exception>
 /// <example>
 /// <code language="c#">
 /// <![CDATA[
 /// public class ToDoActivity{
 ///     public string id {get; set;}
 ///     public string status {get; set;}
 /// }
 ///
 /// ItemResponse item = await this.cosmosContainer.DeleteItemAsync<ToDoActivity>("partitionKey", "id");
 /// ]]>
 /// </code>
 /// </example>
 public abstract Task <ItemResponse <T> > DeleteItemAsync <T>(
     PartitionKey partitionKey,
     string id,
     ItemRequestOptions requestOptions   = null,
     CancellationToken cancellationToken = default(CancellationToken));
 /// <summary>
 /// Creates a item as an asynchronous operation in the Azure Cosmos service.
 /// </summary>
 /// <param name="partitionKey">The partition key for the item. <see cref="Microsoft.Azure.Documents.PartitionKey"/></param>
 /// <param name="item">A JSON serializable object that must contain an id property. <see cref="CosmosJsonSerializer"/> to implement a custom serializer</param>
 /// <param name="requestOptions">(Optional) The options for the item request <see cref="ItemRequestOptions"/></param>
 /// <param name="cancellationToken">(Optional) <see cref="CancellationToken"/> representing request cancellation.</param>
 /// <returns>The <see cref="ItemResponse{T}"/> that was created contained within a <see cref="System.Threading.Tasks.Task"/> object representing the service response for the asynchronous operation.</returns>
 /// <exception cref="System.AggregateException">Represents a consolidation of failures that occurred during async processing. Look within InnerExceptions to find the actual exception(s)</exception>
 /// <exception cref="CosmosException">This exception can encapsulate many different types of errors. To determine the specific error always look at the StatusCode property. Some common codes you may get when creating a Document are:
 /// <list type="table">
 ///     <listheader>
 ///         <term>StatusCode</term><description>Reason for exception</description>
 ///     </listheader>
 ///     <item>
 ///         <term>400</term><description>BadRequest - This means something was wrong with the document supplied. </description>
 ///     </item>
 ///     <item>
 ///         <term>403</term><description>Forbidden - This likely means the collection in to which you were trying to create the document is full.</description>
 ///     </item>
 ///     <item>
 ///         <term>409</term><description>Conflict - This means a item with an id matching the id field of <paramref name="item"/> already existed</description>
 ///     </item>
 ///     <item>
 ///         <term>413</term><description>RequestEntityTooLarge - This means the item exceeds the current max entity size. Consult documentation for limits and quotas.</description>
 ///     </item>
 ///     <item>
 ///         <term>429</term><description>TooManyRequests - This means you have exceeded the number of request units per second.</description>
 ///     </item>
 /// </list>
 /// </exception>
 /// <example>
 /// <code language="c#">
 /// <![CDATA[
 /// public class ToDoActivity{
 ///     public string id {get; set;}
 ///     public string status {get; set;}
 /// }
 ///
 /// ToDoActivity test = new ToDoActivity()
 /// {
 ///    id = Guid.NewGuid().ToString(),
 ///    status = "InProgress"
 /// };
 ///
 /// ItemResponse item = this.cosmosContainer.Items.CreateItemAsync<ToDoActivity>(test.status, tests);
 /// ]]>
 /// </code>
 /// </example>
 public abstract Task <ItemResponse <T> > CreateItemAsync <T>(
     object partitionKey,
     T item,
     ItemRequestOptions requestOptions   = null,
     CancellationToken cancellationToken = default(CancellationToken));
 /// <summary>
 /// Replaces a item in the Azure Cosmos service as an asynchronous operation.
 /// </summary>
 /// <param name="id">The cosmos item id, which is expected to match the value within T.</param>
 /// <param name="item">A JSON serializable object that must contain an id property. <see cref="CosmosJsonSerializer"/> to implement a custom serializer.</param>
 /// <param name="partitionKey">Partitionkey for the item. If not specified will be populated by extracting from {T}</param>
 /// <param name="requestOptions">(Optional) The options for the item request <see cref="ItemRequestOptions"/></param>
 /// <param name="cancellationToken">(Optional) <see cref="CancellationToken"/> representing request cancellation.</param>
 /// <returns>
 /// A <see cref="Task"/> containing a <see cref="ItemResponse{T}"/> which wraps the updated resource record.
 /// </returns>
 /// <exception cref="ArgumentNullException">If either <paramref name="item"/> is not set.</exception>
 /// <exception cref="CosmosException">
 /// This exception can encapsulate many different types of errors. To determine the specific error always look at the StatusCode property.
 /// <list type="table">
 ///     <listheader>
 ///         <term>StatusCode</term><description>Reason for exception</description>
 ///     </listheader>
 ///     <item>
 ///         <term>400</term><description>BadRequest - This means something was wrong with the document supplied. </description>
 ///     </item>
 ///     <item>
 ///         <term>403</term><description>Forbidden - This likely means the collection in to which you were trying to create the document is full.</description>
 ///     </item>
 ///     <item>
 ///         <term>413</term><description>RequestEntityTooLarge - This means the item exceeds the current max entity size. Consult documentation for limits and quotas.</description>
 ///     </item>
 ///     <item>
 ///         <term>429</term><description>TooManyRequests - This means you have exceeded the number of request units per second.</description>
 ///     </item>
 /// </list>
 /// </exception>
 /// <example>
 /// <code language="c#">
 /// <![CDATA[
 /// public class ToDoActivity{
 ///     public string id {get; set;}
 ///     public string status {get; set;}
 /// }
 ///
 /// ToDoActivity test = new ToDoActivity()
 /// {
 ///    id = Guid.NewGuid().ToString(),
 ///    status = "InProgress"
 /// };
 ///
 /// ItemResponse item = await this.cosmosContainer.ReplaceItemAsync<ToDoActivity>(test.status, test.id, test);
 /// ]]>
 /// </code>
 /// </example>
 public abstract Task <ItemResponse <T> > ReplaceItemAsync <T>(
     string id,
     T item,
     PartitionKey partitionKey           = null,
     ItemRequestOptions requestOptions   = null,
     CancellationToken cancellationToken = default(CancellationToken));
 /// <summary>
 /// Upserts an item as an asynchronous operation in the Azure Cosmos service.
 /// </summary>
 /// <param name="item">A JSON serializable object that must contain an id property. <see cref="CosmosJsonSerializer"/> to implement a custom serializer</param>
 /// <param name="partitionKey">Partitionkey for the item. If not specified will be populated by extracting from {T}</param>
 /// <param name="requestOptions">(Optional) The options for the item request <see cref="ItemRequestOptions"/></param>
 /// <param name="cancellationToken">(Optional) <see cref="CancellationToken"/> representing request cancellation.</param>
 /// <returns>The <see cref="ItemResponse{T}"/> that was upserted contained within a <see cref="System.Threading.Tasks.Task"/> object representing the service response for the asynchronous operation.</returns>
 /// <exception cref="System.AggregateException">Represents a consolidation of failures that occurred during async processing. Look within InnerExceptions to find the actual exception(s)</exception>
 /// <exception cref="CosmosException">This exception can encapsulate many different types of errors. To determine the specific error always look at the StatusCode property. Some common codes you may get when creating a Document are:
 /// <list type="table">
 ///     <listheader>
 ///         <term>StatusCode</term><description>Reason for exception</description>
 ///     </listheader>
 ///     <item>
 ///         <term>400</term><description>BadRequest - This means something was wrong with the document supplied.</description>
 ///     </item>
 ///     <item>
 ///         <term>403</term><description>Forbidden - This likely means the collection in to which you were trying to upsert the document is full.</description>
 ///     </item>
 ///     <item>
 ///         <term>413</term><description>RequestEntityTooLarge - This means the item exceeds the current max entity size. Consult documentation for limits and quotas.</description>
 ///     </item>
 ///     <item>
 ///         <term>429</term><description>TooManyRequests - This means you have exceeded the number of request units per second. Consult the DocumentClientException.RetryAfter value to see how long you should wait before retrying this operation.</description>
 ///     </item>
 /// </list>
 /// </exception>
 /// <example>
 /// <code language="c#">
 /// <![CDATA[
 /// public class ToDoActivity{
 ///     public string id {get; set;}
 ///     public string status {get; set;}
 /// }
 ///
 /// ToDoActivity test = new ToDoActivity()
 /// {
 ///    id = Guid.NewGuid().ToString(),
 ///    status = "InProgress"
 /// };
 ///
 /// ItemResponse<ToDoActivity> item = await this.cosmosContainer.UpsertAsync<ToDoActivity>(test.status, test);
 /// ]]>
 /// </code>
 /// </example>
 public abstract Task <ItemResponse <T> > UpsertItemAsync <T>(
     T item,
     PartitionKey partitionKey           = null,
     ItemRequestOptions requestOptions   = null,
     CancellationToken cancellationToken = default(CancellationToken));
 /// <summary>
 /// Reads a item from the Azure Cosmos service as an asynchronous operation.
 /// </summary>
 /// <param name="partitionKey">The partition key for the item. <see cref="Microsoft.Azure.Documents.PartitionKey"/></param>
 /// <param name="id">The cosmos item id</param>
 /// <param name="requestOptions">(Optional) The options for the item request <see cref="ItemRequestOptions"/></param>
 /// <param name="cancellationToken">(Optional) <see cref="CancellationToken"/> representing request cancellation.</param>
 /// <returns>
 /// A <see cref="Task"/> containing a <see cref="CosmosResponseMessage"/> which wraps a <see cref="Stream"/> containing the read resource record.
 /// </returns>
 /// <exception>
 /// The Stream operation only throws on client side exceptions. This is to increase performance and prevent the overhead of throwing exceptions. Check the HTTP status code on the response to check if the operation failed.
 /// </exception>
 /// <example>
 /// Read a response as a stream.
 /// <code language="c#">
 /// <![CDATA[
 /// using(CosmosResponseMessage response = this.cosmosContainer.ReadItemStreamAsync("partitionKey", "id"))
 /// {
 ///     if (!response.IsSuccessStatusCode)
 ///     {
 ///         //Handle and log exception
 ///         return;
 ///     }
 ///
 ///     using(Stream stream = response.ReadBodyAsync())
 ///     {
 ///         //Read or do other operations with the stream
 ///         using (StreamReader streamReader = new StreamReader(stream))
 ///         {
 ///             string content =  streamReader.ReadToEndAsync();
 ///         }
 ///     }
 /// }
 ///
 /// ]]>
 /// </code>
 /// </example>
 public abstract Task <CosmosResponseMessage> ReadItemStreamAsync(
     PartitionKey partitionKey,
     string id,
     ItemRequestOptions requestOptions   = null,
     CancellationToken cancellationToken = default(CancellationToken));
 /// <summary>
 /// Delete a item from the Azure Cosmos service as an asynchronous operation.
 /// </summary>
 /// <param name="partitionKey">The partition key for the item. <see cref="Microsoft.Azure.Documents.PartitionKey"/></param>
 /// <param name="id">The cosmos item id</param>
 /// <param name="requestOptions">(Optional) The options for the item request <see cref="ItemRequestOptions"/></param>
 /// <param name="cancellationToken">(Optional) <see cref="CancellationToken"/> representing request cancellation.</param>
 /// <returns>
 /// A <see cref="Task"/> containing a <see cref="CosmosResponseMessage"/> which wraps a <see cref="Stream"/> containing the delete resource record.
 /// </returns>
 /// <exception>
 /// The Stream operation only throws on client side exceptions. This is to increase performance and prevent the overhead of throwing exceptions. Check the HTTP status code on the response to check if the operation failed.
 /// </exception>
 /// <example>
 /// Delete an item from Cosmos
 /// <code language="c#">
 /// <![CDATA[
 /// using(CosmosResponseMessage response = this.cosmosContainer.Items.DeleteItemAsStreamAsync(partitionKey: "itemPartitionKey", id: "itemId"))
 /// {
 ///     if (!response.IsSuccessStatusCode)
 ///     {
 ///         //Handle and log exception
 ///         return;
 ///     }
 /// }
 /// ]]>
 /// </code>
 /// </example>
 public abstract Task <CosmosResponseMessage> DeleteItemAsStreamAsync(
     object partitionKey,
     string id,
     ItemRequestOptions requestOptions   = null,
     CancellationToken cancellationToken = default(CancellationToken));
 /// <summary>
 /// Upserts an item stream as an asynchronous operation in the Azure Cosmos service.
 /// </summary>
 /// <param name="partitionKey">The partition key for the item. <see cref="Microsoft.Azure.Documents.PartitionKey"/></param>
 /// <param name="streamPayload">A <see cref="Stream"/> containing the payload.</param>
 /// <param name="requestOptions">(Optional) The options for the item request <see cref="ItemRequestOptions"/></param>
 /// <param name="cancellationToken">(Optional) <see cref="CancellationToken"/> representing request cancellation.</param>
 /// <returns>
 /// A <see cref="Task"/> containing a <see cref="CosmosResponseMessage"/> which wraps a <see cref="Stream"/> containing the read resource record.
 /// </returns>
 /// <exception>
 /// The Stream operation only throws on client side exceptions. This is to increase performance and prevent the overhead of throwing exceptions. Check the HTTP status code on the response to check if the operation failed.
 /// </exception>
 /// <example>
 /// Upsert a Stream containing the item to Cosmos
 /// <code language="c#">
 /// <![CDATA[
 /// using(CosmosResponseMessage response = this.cosmosContainer.Items.UpsertItemAsStreamAsync(partitionKey: "itemPartitionKey", streamPayload: stream))
 /// {
 ///     if (!response.IsSuccessStatusCode)
 ///     {
 ///         //Handle and log exception
 ///         return;
 ///     }
 ///
 ///     using(Stream stream = response.ReadBodyAsync())
 ///     {
 ///         //Read or do other operations with the stream
 ///         using (StreamReader  streamReader = new StreamReader(stream))
 ///         {
 ///             string content =  streamReader.ReadToEndAsync();
 ///         }
 ///     }
 /// }
 /// ]]>
 /// </code>
 /// </example>
 public abstract Task <CosmosResponseMessage> UpsertItemAsStreamAsync(
     object partitionKey,
     Stream streamPayload,
     ItemRequestOptions requestOptions   = null,
     CancellationToken cancellationToken = default(CancellationToken));