Table of Contents

Class Container

Namespace
Microsoft.Azure.Cosmos
Assembly
Microsoft.Azure.Cosmos.Client.dll

Operations for reading, replacing, or deleting a specific, existing container or item in a container by id. There are two different types of operations.

  1. The object operations where it serializes and deserializes the item on request/response
  2. The stream response which takes a Stream containing a JSON serialized object and returns a response containing a Stream See Database for creating new containers, and reading/querying all containers.
public abstract class Container
Inheritance
Container
Inherited Members
Extension Methods

Remarks

Note: all these operations make calls against a fixed budget. You should design your system such that these calls scale sub linearly with your application. For instance, do not call container.readAsync() before every single container.readItemAsync() call to ensure the container exists; do this once on application start up.

Constructors

Container()

protected Container()

Properties

Conflicts

Returns the conflicts

public abstract Conflicts Conflicts { get; }

Property Value

Conflicts

Database

Returns the parent Database reference

public abstract Database Database { get; }

Property Value

Database

Id

The Id of the Cosmos container

public abstract string Id { get; }

Property Value

string

Scripts

Returns the scripts

public abstract Scripts Scripts { get; }

Property Value

Scripts

Methods

CreateItemAsync<T>(T, PartitionKey?, ItemRequestOptions, CancellationToken)

Creates a item as an asynchronous operation in the Azure Cosmos service.

public abstract Task<ItemResponse<T>> CreateItemAsync<T>(T item, PartitionKey? partitionKey = null, ItemRequestOptions requestOptions = null, CancellationToken cancellationToken = default)

Parameters

item T

A JSON serializable object that must contain an id property. CosmosSerializer to implement a custom serializer

partitionKey PartitionKey?

PartitionKey for the item. If not specified will be populated by extracting from {T}

requestOptions ItemRequestOptions

(Optional) The options for the item request.

cancellationToken CancellationToken

(Optional) CancellationToken representing request cancellation.

Returns

Task<ItemResponse<T>>

The ItemResponse<T> that was created contained within a Task object representing the service response for the asynchronous operation.

Type Parameters

T

Examples

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.container.CreateItemAsync<ToDoActivity>(test, new PartitionKey(test.status));

CreateItemStreamAsync(Stream, PartitionKey, ItemRequestOptions, CancellationToken)

Creates a Item as an asynchronous operation in the Azure Cosmos service.

public abstract Task<ResponseMessage> CreateItemStreamAsync(Stream streamPayload, PartitionKey partitionKey, ItemRequestOptions requestOptions = null, CancellationToken cancellationToken = default)

Parameters

streamPayload Stream

A Stream containing the payload.

partitionKey PartitionKey

The partition key for the item.

requestOptions ItemRequestOptions

(Optional) The options for the item request.

cancellationToken CancellationToken

(Optional) CancellationToken representing request cancellation.

Returns

Task<ResponseMessage>

The ResponseMessage that was created contained within a Task object representing the service response for the asynchronous operation.

Examples

This example creates an item in a Cosmos container.

//Create the object in Cosmos
using (ResponseMessage response = await this.Container.CreateItemStreamAsync(partitionKey: new PartitionKey("streamPartitionKey"), streamPayload: stream))
{
    if (!response.IsSuccessStatusCode)
    {
        //Handle and log exception
        return;
    }

    //Read or do other operations with the stream
    using (StreamReader streamReader = new StreamReader(response.Content))
    {
        string responseContentAsString = await streamReader.ReadToEndAsync();
    }
}

Remarks

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.

CreateTransactionalBatch(PartitionKey)

Initializes a new instance of TransactionalBatch that can be used to perform operations across multiple items in the container with the provided partition key in a transactional manner.

public abstract TransactionalBatch CreateTransactionalBatch(PartitionKey partitionKey)

Parameters

partitionKey PartitionKey

The partition key for all items in the batch.

Returns

TransactionalBatch

A new instance of TransactionalBatch.

Remarks

DeleteContainerAsync(ContainerRequestOptions, CancellationToken)

Delete a ContainerProperties from the Azure Cosmos DB service as an asynchronous operation.

public abstract Task<ContainerResponse> DeleteContainerAsync(ContainerRequestOptions requestOptions = null, CancellationToken cancellationToken = default)

Parameters

requestOptions ContainerRequestOptions

(Optional) The options for the container request.

cancellationToken CancellationToken

(Optional) CancellationToken representing request cancellation.

Returns

Task<ContainerResponse>

A Task containing a ContainerResponse which will contain information about the request issued.

Examples

Container container = this.database.GetContainer("containerId");
ContainerResponse response = await container.DeleteContainerAsync();

DeleteContainerStreamAsync(ContainerRequestOptions, CancellationToken)

Delete a ContainerProperties from the Azure Cosmos DB service as an asynchronous operation.

public abstract Task<ResponseMessage> DeleteContainerStreamAsync(ContainerRequestOptions requestOptions = null, CancellationToken cancellationToken = default)

Parameters

requestOptions ContainerRequestOptions

(Optional) The options for the container request.

cancellationToken CancellationToken

(Optional) CancellationToken representing request cancellation.

Returns

Task<ResponseMessage>

A Task containing a ResponseMessage which will contain information about the request issued.

Examples

Container container = this.database.GetContainer("containerId");
ResponseMessage response = await container.DeleteContainerStreamAsync();

DeleteItemAsync<T>(string, PartitionKey, ItemRequestOptions, CancellationToken)

Delete a item from the Azure Cosmos service as an asynchronous operation.

public abstract Task<ItemResponse<T>> DeleteItemAsync<T>(string id, PartitionKey partitionKey, ItemRequestOptions requestOptions = null, CancellationToken cancellationToken = default)

Parameters

id string

The Cosmos item id

partitionKey PartitionKey

The partition key for the item.

requestOptions ItemRequestOptions

(Optional) The options for the item request.

cancellationToken CancellationToken

(Optional) CancellationToken representing request cancellation.

Returns

Task<ItemResponse<T>>

A Task containing a ItemResponse<T> which will contain information about the request issued.

Type Parameters

T

Examples

public class ToDoActivity{
    public string id {get; set;}
    public string status {get; set;}
}

ItemResponse item = await this.container.DeleteItemAsync<ToDoActivity>("id", new PartitionKey("partitionKey"));

Remarks

DeleteItemStreamAsync(string, PartitionKey, ItemRequestOptions, CancellationToken)

Delete a item from the Azure Cosmos service as an asynchronous operation.

public abstract Task<ResponseMessage> DeleteItemStreamAsync(string id, PartitionKey partitionKey, ItemRequestOptions requestOptions = null, CancellationToken cancellationToken = default)

Parameters

id string

The Cosmos item id

partitionKey PartitionKey

The partition key for the item.

requestOptions ItemRequestOptions

(Optional) The options for the item request.

cancellationToken CancellationToken

(Optional) CancellationToken representing request cancellation.

Returns

Task<ResponseMessage>

A Task containing a ResponseMessage which wraps a Stream containing the delete resource record.

Examples

Delete an item from Cosmos

using(ResponseMessage response = await this.container.DeleteItemStreamAsync("itemId", new PartitionKey("itemPartitionKey")))
{
    if (!response.IsSuccessStatusCode)
    {
        //Handle and log exception
        return;
    }
}

Remarks

For delete operations, the Content will be null. Item content is not expected in the response.

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.

GetChangeFeedEstimator(string, Container)

Gets a ChangeFeedEstimator for change feed monitoring.

public abstract ChangeFeedEstimator GetChangeFeedEstimator(string processorName, Container leaseContainer)

Parameters

processorName string

The name of the Processor the Estimator is going to measure.

leaseContainer Container

Instance of a Cosmos Container that holds the leases.

Returns

ChangeFeedEstimator

An instance of ChangeFeedEstimator

Remarks

The goal of the Estimator is to measure progress of a particular processor. In order to do that, the processorName and other parameters, like the leases container, need to match that of the Processor to measure.

GetChangeFeedEstimatorBuilder(string, ChangesEstimationHandler, TimeSpan?)

Initializes a ChangeFeedProcessorBuilder for change feed monitoring.

public abstract ChangeFeedProcessorBuilder GetChangeFeedEstimatorBuilder(string processorName, Container.ChangesEstimationHandler estimationDelegate, TimeSpan? estimationPeriod = null)

Parameters

processorName string

The name of the Processor the Estimator is going to measure.

estimationDelegate Container.ChangesEstimationHandler

Delegate to receive estimation.

estimationPeriod TimeSpan?

Time interval on which to report the estimation. Default is 5 seconds.

Returns

ChangeFeedProcessorBuilder

An instance of ChangeFeedProcessorBuilder

Remarks

The goal of the Estimator is to measure progress of a particular processor. In order to do that, the processorName and other parameters, like the leases container, need to match that of the Processor to measure.

GetChangeFeedIterator<T>(ChangeFeedStartFrom, ChangeFeedMode, ChangeFeedRequestOptions)

This method creates an iterator to consume a Change Feed.

public abstract FeedIterator<T> GetChangeFeedIterator<T>(ChangeFeedStartFrom changeFeedStartFrom, ChangeFeedMode changeFeedMode, ChangeFeedRequestOptions changeFeedRequestOptions = null)

Parameters

changeFeedStartFrom ChangeFeedStartFrom

Where to start the changefeed from.

changeFeedMode ChangeFeedMode

Defines the mode on which to consume the change feed.

changeFeedRequestOptions ChangeFeedRequestOptions

(Optional) The options for the Change Feed consumption.

Returns

FeedIterator<T>

An iterator to go through the Change Feed.

Type Parameters

T

Examples

ChangeFeedRequestOptions options = new ChangeFeedRequestOptions()
{
    PageSizeHint = 10,
}

FeedIterator<MyItem> feedIterator = this.Container.GetChangeFeedIterator<MyItem>(
    ChangeFeedStartFrom.Beginning(),
    ChangeFeedMode.Incremental,
    options);

    while (feedIterator.HasMoreResults)
    {
        FeedResponse<MyItem> response = await feedIterator.ReadNextAsync();

        if (response.StatusCode == NotModified) 
        {
            // No new changes
            // Capture response.ContinuationToken and break or sleep for some time
        }
        else 
        {
            foreach (var item in response)
            {
                Console.WriteLine(item);
            }
        }
    }
See Also

GetChangeFeedProcessorBuilder(string, ChangeFeedStreamHandler)

Initializes a ChangeFeedProcessorBuilder for change feed processing.

public abstract ChangeFeedProcessorBuilder GetChangeFeedProcessorBuilder(string processorName, Container.ChangeFeedStreamHandler onChangesDelegate)

Parameters

processorName string

A name that identifies the Processor and the particular work it will do.

onChangesDelegate Container.ChangeFeedStreamHandler

Delegate to receive changes.

Returns

ChangeFeedProcessorBuilder

An instance of ChangeFeedProcessorBuilder

GetChangeFeedProcessorBuilderWithManualCheckpoint(string, ChangeFeedStreamHandlerWithManualCheckpoint)

Initializes a ChangeFeedProcessorBuilder for change feed processing with manual checkpoint.

public abstract ChangeFeedProcessorBuilder GetChangeFeedProcessorBuilderWithManualCheckpoint(string processorName, Container.ChangeFeedStreamHandlerWithManualCheckpoint onChangesDelegate)

Parameters

processorName string

A name that identifies the Processor and the particular work it will do.

onChangesDelegate Container.ChangeFeedStreamHandlerWithManualCheckpoint

Delegate to receive changes.

Returns

ChangeFeedProcessorBuilder

An instance of ChangeFeedProcessorBuilder

GetChangeFeedProcessorBuilderWithManualCheckpoint<T>(string, ChangeFeedHandlerWithManualCheckpoint<T>)

Initializes a ChangeFeedProcessorBuilder for change feed processing with manual checkpoint.

public abstract ChangeFeedProcessorBuilder GetChangeFeedProcessorBuilderWithManualCheckpoint<T>(string processorName, Container.ChangeFeedHandlerWithManualCheckpoint<T> onChangesDelegate)

Parameters

processorName string

A name that identifies the Processor and the particular work it will do.

onChangesDelegate Container.ChangeFeedHandlerWithManualCheckpoint<T>

Delegate to receive changes.

Returns

ChangeFeedProcessorBuilder

An instance of ChangeFeedProcessorBuilder

Type Parameters

T

GetChangeFeedProcessorBuilder<T>(string, ChangeFeedHandler<T>)

Initializes a ChangeFeedProcessorBuilder for change feed processing.

public abstract ChangeFeedProcessorBuilder GetChangeFeedProcessorBuilder<T>(string processorName, Container.ChangeFeedHandler<T> onChangesDelegate)

Parameters

processorName string

A name that identifies the Processor and the particular work it will do.

onChangesDelegate Container.ChangeFeedHandler<T>

Delegate to receive changes.

Returns

ChangeFeedProcessorBuilder

An instance of ChangeFeedProcessorBuilder

Type Parameters

T

GetChangeFeedProcessorBuilder<T>(string, ChangesHandler<T>)

Initializes a ChangeFeedProcessorBuilder for change feed processing.

public abstract ChangeFeedProcessorBuilder GetChangeFeedProcessorBuilder<T>(string processorName, Container.ChangesHandler<T> onChangesDelegate)

Parameters

processorName string

A name that identifies the Processor and the particular work it will do.

onChangesDelegate Container.ChangesHandler<T>

Delegate to receive changes.

Returns

ChangeFeedProcessorBuilder

An instance of ChangeFeedProcessorBuilder

Type Parameters

T

GetChangeFeedStreamIterator(ChangeFeedStartFrom, ChangeFeedMode, ChangeFeedRequestOptions)

This method creates an iterator to consume a Change Feed.

public abstract FeedIterator GetChangeFeedStreamIterator(ChangeFeedStartFrom changeFeedStartFrom, ChangeFeedMode changeFeedMode, ChangeFeedRequestOptions changeFeedRequestOptions = null)

Parameters

changeFeedStartFrom ChangeFeedStartFrom

Where to start the changefeed from.

changeFeedMode ChangeFeedMode

Defines the mode on which to consume the change feed.

changeFeedRequestOptions ChangeFeedRequestOptions

(Optional) The options for the Change Feed consumption.

Returns

FeedIterator

An iterator to go through the Change Feed.

Examples

ChangeFeedRequestOptions options = new ChangeFeedRequestOptions()
{
    PageSizeHint = 10,
}

FeedIterator feedIterator = this.Container.GetChangeFeedStreamIterator(
    ChangeFeedStartFrom.Beginning(),
    ChangeFeedMode.Incremental,
    options);

while (feedIterator.HasMoreResults)
{
    using (ResponseMessage response = await feedIterator.ReadNextAsync())
    {
        if (response.StatusCode == NotModified) 
        {
            // No new changes
            // Capture response.ContinuationToken and break or sleep for some time
        }
        else 
        {
            using (StreamReader sr = new StreamReader(response.Content))
            using (JsonTextReader jtr = new JsonTextReader(sr))
            {
                JObject result = JObject.Load(jtr);
            }
        }
    }
}
See Also

GetFeedRangesAsync(CancellationToken)

Obtains a list of FeedRange that can be used to parallelize Feed operations.

public abstract Task<IReadOnlyList<FeedRange>> GetFeedRangesAsync(CancellationToken cancellationToken = default)

Parameters

cancellationToken CancellationToken

(Optional) CancellationToken representing request cancellation.

Returns

Task<IReadOnlyList<FeedRange>>

A list of FeedRange.

GetItemLinqQueryable<T>(bool, string, QueryRequestOptions, CosmosLinqSerializerOptions)

This method creates a LINQ query for items under a container in an Azure Cosmos DB service. IQueryable extension method ToFeedIterator() should be use for asynchronous execution with FeedIterator, please refer to example 2.

public abstract IOrderedQueryable<T> GetItemLinqQueryable<T>(bool allowSynchronousQueryExecution = false, string continuationToken = null, QueryRequestOptions requestOptions = null, CosmosLinqSerializerOptions linqSerializerOptions = null)

Parameters

allowSynchronousQueryExecution bool

(Optional)the option which allows the query to be executed synchronously via IOrderedQueryable.

continuationToken string

(Optional) The continuation token in the Azure Cosmos DB service.

requestOptions QueryRequestOptions

(Optional) The options for the item query request.

linqSerializerOptions CosmosLinqSerializerOptions

(Optional) The options to configure Linq Serializer Properties. This overrides properties in CosmosSerializerOptions while creating client

Returns

IOrderedQueryable<T>

(Optional) An IOrderedQueryable{T} that can evaluate the query.

Type Parameters

T

The type of object to query.

Examples

  1. This example below shows LINQ query generation and blocked execution.
public class Book 
{
    public string Title {get; set;}

    public Author Author {get; set;}

    public int Price {get; set;}
}

public class Author
{
    public string FirstName {get; set;}
    public string LastName {get; set;}
}

// Query by the Title property
Book book = container.GetItemLinqQueryable<Book>(true)
                     .Where(b => b.Title == "War and Peace")
                     .AsEnumerable()
                     .FirstOrDefault();

// Query a nested property
Book otherBook = container.GetItemLinqQueryable<Book>(true)
                          .Where(b => b.Author.FirstName == "Leo")
                          .AsEnumerable()
                          .FirstOrDefault();

// Perform iteration on books
foreach (Book matchingBook in container.GetItemLinqQueryable<Book>(true)
                           .Where(b => b.Price > 100))
{
    // Iterate through books
}
  1. This example below shows LINQ query generation and asynchronous execution with FeedIterator.
// LINQ query generation
using (FeedIterator<Book> setIterator = container.GetItemLinqQueryable<Book>()
                     .Where(b => b.Title == "War and Peace")
                     .ToFeedIterator())
{                   
    //Asynchronous query execution
    while (setIterator.HasMoreResults)
    {
        foreach(var item in await setIterator.ReadNextAsync())
        {
            Console.WriteLine(item.Price); 
        }
    }
}

Remarks

LINQ execution is synchronous which will cause issues related to blocking calls. It is recommended to always use ToFeedIterator(), and to do the asynchronous execution.

See Also

GetItemQueryIterator<T>(FeedRange, QueryDefinition, string, QueryRequestOptions)

This method creates a query for items under a container in an Azure Cosmos database using a SQL statement with parameterized values. It returns a FeedIterator. For more information on preparing SQL statements with parameterized values, please see QueryDefinition.

public abstract FeedIterator<T> GetItemQueryIterator<T>(FeedRange feedRange, QueryDefinition queryDefinition, string continuationToken = null, QueryRequestOptions requestOptions = null)

Parameters

feedRange FeedRange

A FeedRange obtained from GetFeedRangesAsync(CancellationToken).

queryDefinition QueryDefinition

The Cosmos SQL query definition.

continuationToken string

(Optional) The continuation token in the Azure Cosmos DB service.

requestOptions QueryRequestOptions

(Optional) The options for the item query request.

Returns

FeedIterator<T>

An iterator to go through the items.

Type Parameters

T

Examples

Create a query to get all the ToDoActivity that have a cost greater than 9000 for the specified partition

public class ToDoActivity{
    public string id {get; set;}
    public string status {get; set;}
    public int cost {get; set;}
}
IReadOnlyList<FeedRange> feedRanges = await this.Container.GetFeedRangesAsync();
// Distribute feedRanges across multiple compute units and pass each one to a different iterator
QueryDefinition queryDefinition = new QueryDefinition("select * from ToDos t where t.cost > @expensive")
    .WithParameter("@expensive", 9000);
using (FeedIterator<ToDoActivity> feedIterator = this.Container.GetItemQueryIterator<ToDoActivity>(
    feedRanges[0],
    queryDefinition,
    null,
    new QueryRequestOptions() { }))
{
    while (feedIterator.HasMoreResults)
    {
        foreach(var item in await feedIterator.ReadNextAsync())
        {
            Console.WriteLine(item.cost); 
        }
    }
}

GetItemQueryIterator<T>(QueryDefinition, string, QueryRequestOptions)

This method creates a query for items under a container in an Azure Cosmos database using a SQL statement with parameterized values. It returns a FeedIterator. For more information on preparing SQL statements with parameterized values, please see QueryDefinition.

public abstract FeedIterator<T> GetItemQueryIterator<T>(QueryDefinition queryDefinition, string continuationToken = null, QueryRequestOptions requestOptions = null)

Parameters

queryDefinition QueryDefinition

The Cosmos SQL query definition.

continuationToken string

(Optional) The continuation token in the Azure Cosmos DB service.

requestOptions QueryRequestOptions

(Optional) The options for the item query request.

Returns

FeedIterator<T>

An iterator to go through the items.

Type Parameters

T

Examples

Create a query to get all the ToDoActivity that have a cost greater than 9000

public class ToDoActivity{
    public string id {get; set;}
    public string status {get; set;}
    public int cost {get; set;}
}

QueryDefinition queryDefinition = new QueryDefinition("select * from ToDos t where t.cost > @expensive")
    .WithParameter("@expensive", 9000);
using (FeedIterator<ToDoActivity> feedIterator = this.Container.GetItemQueryIterator<ToDoActivity>(
    queryDefinition,
    null,
    new QueryRequestOptions() { PartitionKey = new PartitionKey("Error")}))
{
    while (feedIterator.HasMoreResults)
    {
        foreach(var item in await feedIterator.ReadNextAsync())
        {
            Console.WriteLine(item.cost); 
        }
    }
}

GetItemQueryIterator<T>(string, string, QueryRequestOptions)

This method creates a query for items under a container in an Azure Cosmos database using a SQL statement. It returns a FeedIterator.

public abstract FeedIterator<T> GetItemQueryIterator<T>(string queryText = null, string continuationToken = null, QueryRequestOptions requestOptions = null)

Parameters

queryText string

The Cosmos SQL query text.

continuationToken string

(Optional) The continuation token in the Azure Cosmos DB service.

requestOptions QueryRequestOptions

(Optional) The options for the item query request.

Returns

FeedIterator<T>

An iterator to go through the items.

Type Parameters

T

Examples

  1. Create a query to get all the ToDoActivity that have a cost greater than 9000
public class ToDoActivity{
    public string id {get; set;}
    public string status {get; set;}
    public int cost {get; set;}
}

using (FeedIterator<ToDoActivity> feedIterator = this.Container.GetItemQueryIterator<ToDoActivity>(
    "select * from ToDos t where t.cost > 9000",
    null,
    new QueryRequestOptions() { PartitionKey = new PartitionKey("Error")}))
{
    while (feedIterator.HasMoreResults)
    {
        foreach(var item in await feedIterator.ReadNextAsync())
        {
            Console.WriteLine(item.cost);
        }
    }
}
  1. Create a FeedIterator to get all the ToDoActivity.
public class ToDoActivity{
    public string id {get; set;}
    public string status {get; set;}
    public int cost {get; set;}
}

using (FeedIterator<ToDoActivity> feedIterator = this.Container.GetItemQueryIterator<ToDoActivity>(
    null,
    null,
    new QueryRequestOptions() { PartitionKey = new PartitionKey("Error")}))
{
    while (feedIterator.HasMoreResults)
    {
        foreach(var item in await feedIterator.ReadNextAsync())
        {
            Console.WriteLine(item.cost); 
        }
    }
}

GetItemQueryStreamIterator(FeedRange, QueryDefinition, string, QueryRequestOptions)

This method creates a query for items under a container in an Azure Cosmos database using a SQL statement with parameterized values. It returns a FeedIterator. For more information on preparing SQL statements with parameterized values, please see QueryDefinition.

public abstract FeedIterator GetItemQueryStreamIterator(FeedRange feedRange, QueryDefinition queryDefinition, string continuationToken, QueryRequestOptions requestOptions = null)

Parameters

feedRange FeedRange

A FeedRange obtained from GetFeedRangesAsync(CancellationToken)

queryDefinition QueryDefinition

The Cosmos SQL query definition.

continuationToken string

(Optional) The continuation token in the Azure Cosmos DB service.

requestOptions QueryRequestOptions

(Optional) The options for the item query request.

Returns

FeedIterator

An iterator to go through the items.

Examples

Create a query to get all the ToDoActivity that have a cost greater than 9000 for the specified partition

public class ToDoActivity{
    public string id {get; set;}
    public string status {get; set;}
    public int cost {get; set;}
}
IReadOnlyList<FeedRange> feedRanges = await this.Container.GetFeedRangesAsync();
// Distribute feedRanges across multiple compute units and pass each one to a different iterator
QueryDefinition queryDefinition = new QueryDefinition("select * from ToDos t where t.cost > @expensive")
    .WithParameter("@expensive", 9000);
using (FeedIterator feedIterator = this.Container.GetItemQueryStreamIterator(
    feedRanges[0],
    queryDefinition,
    null,
    new QueryRequestOptions() { }))
{
    while (feedIterator.HasMoreResults)
    {
        using (ResponseMessage response = await feedIterator.ReadNextAsync())
        {
            using (StreamReader sr = new StreamReader(response.Content))
            using (JsonTextReader jtr = new JsonTextReader(sr))
            {
                JObject result = JObject.Load(jtr);
            }
        }
    }
}

GetItemQueryStreamIterator(QueryDefinition, string, QueryRequestOptions)

This method creates a query for items under a container in an Azure Cosmos database using a SQL statement with parameterized values. It returns a FeedIterator. For more information on preparing SQL statements with parameterized values, please see QueryDefinition.

public abstract FeedIterator GetItemQueryStreamIterator(QueryDefinition queryDefinition, string continuationToken = null, QueryRequestOptions requestOptions = null)

Parameters

queryDefinition QueryDefinition

The Cosmos SQL query definition.

continuationToken string

(Optional) The continuation token in the Azure Cosmos DB service.

requestOptions QueryRequestOptions

(Optional) The options for the item query request.

Returns

FeedIterator

An iterator to go through the items.

Examples

Create a query to get all the ToDoActivity that have a cost greater than 9000 for the specified partition

public class ToDoActivity{
    public string id {get; set;}
    public string status {get; set;}
    public int cost {get; set;}
}

QueryDefinition queryDefinition = new QueryDefinition("select * from ToDos t where t.cost > @expensive")
    .WithParameter("@expensive", 9000);
using (FeedIterator feedIterator = this.Container.GetItemQueryStreamIterator(
    queryDefinition,
    null,
    new QueryRequestOptions() { PartitionKey = new PartitionKey("Error")}))
{
    while (feedIterator.HasMoreResults)
    {
        using (ResponseMessage response = await feedIterator.ReadNextAsync())
        {
            using (StreamReader sr = new StreamReader(response.Content))
            using (JsonTextReader jtr = new JsonTextReader(sr))
            {
                JObject result = JObject.Load(jtr);
            }
        }
    }
}

GetItemQueryStreamIterator(string, string, QueryRequestOptions)

This method creates a query for items under a container in an Azure Cosmos database using a SQL statement. It returns a FeedIterator.

public abstract FeedIterator GetItemQueryStreamIterator(string queryText = null, string continuationToken = null, QueryRequestOptions requestOptions = null)

Parameters

queryText string

The Cosmos SQL query text.

continuationToken string

(Optional) The continuation token in the Azure Cosmos DB service.

requestOptions QueryRequestOptions

(Optional) The options for the item query request.

Returns

FeedIterator

An iterator to go through the items.

Examples

  1. Create a query to get all the ToDoActivity that have a cost greater than 9000 for the specified partition
public class ToDoActivity{
    public string id {get; set;}
    public string status {get; set;}
    public int cost {get; set;}
}

using (FeedIterator feedIterator = this.Container.GetItemQueryStreamIterator(
    "select * from ToDos t where t.cost > 9000",
    null,
    new QueryRequestOptions() { PartitionKey = new PartitionKey("Error")}))
{
    while (feedIterator.HasMoreResults)
    {
        using (ResponseMessage response = await feedIterator.ReadNextAsync())
        {
            using (StreamReader sr = new StreamReader(response.Content))
            using (JsonTextReader jtr = new JsonTextReader(sr))
            {
                JObject result = JObject.Load(jtr);
            }
        }
    }
}
  1. Creates a FeedIterator to get all the ToDoActivity.
public class ToDoActivity{
    public string id {get; set;}
    public string status {get; set;}
    public int cost {get; set;}
}

using (FeedIterator feedIterator = this.Container.GetItemQueryStreamIterator(
    null,
    null,
    new QueryRequestOptions() { PartitionKey = new PartitionKey("Error")}))
{
    while (feedIterator.HasMoreResults)
    {
        using (ResponseMessage response = await feedIterator.ReadNextAsync())
        {
            using (StreamReader sr = new StreamReader(response.Content))
            using (JsonTextReader jtr = new JsonTextReader(sr))
            {
                JObject result = JObject.Load(jtr);
            }
        }
    }
}

PatchItemAsync<T>(string, PartitionKey, IReadOnlyList<PatchOperation>, PatchItemRequestOptions, CancellationToken)

Patches an item in the Azure Cosmos service as an asynchronous operation.

public abstract Task<ItemResponse<T>> PatchItemAsync<T>(string id, PartitionKey partitionKey, IReadOnlyList<PatchOperation> patchOperations, PatchItemRequestOptions requestOptions = null, CancellationToken cancellationToken = default)

Parameters

id string

The Cosmos item id of the item to be patched.

partitionKey PartitionKey

PartitionKey for the item

patchOperations IReadOnlyList<PatchOperation>

Represents a list of operations to be sequentially applied to the referred Cosmos item.

requestOptions PatchItemRequestOptions

(Optional) The options for the item request.

cancellationToken CancellationToken

(Optional) CancellationToken representing request cancellation.

Returns

Task<ItemResponse<T>>

A Task containing a ItemResponse<T> which wraps the updated resource record.

Type Parameters

T

Examples

public class ToDoActivity{
    public string id {get; set;}
    public string status {get; set;}
    public string description {get; set;}
    public int frequency {get; set;}
}

ToDoActivity toDoActivity = await this.container.ReadItemAsync<ToDoActivity>("id", new PartitionKey("partitionKey"));
/* toDoActivity = {
    "id" : "someId",
    "status" : "someStatusPK",
    "description" : "someDescription",
    "frequency" : 7
}*/

List<PatchOperation> patchOperations = new List<PatchOperation>()
{
    PatchOperation.Add("/daysOfWeek", new string[]{"Monday", "Thursday"}),
    PatchOperation.Replace("/frequency", 2),
    PatchOperation.Remove("/description")
};

ItemResponse<dynamic> item = await this.container.PatchItemAsync<dynamic>(toDoActivity.id, new PartitionKey(toDoActivity.status), patchOperations);
/* item.Resource = {
    "id" : "someId",
    "status" : "someStatusPK",
    "description" : null,
    "frequency" : 2,
    "daysOfWeek" : ["Monday", "Thursday"]
}*/

Remarks

The item's partition key value is immutable. To change an item's partition key value you must delete the original item and insert a new item. The patch operations are atomic and are executed sequentially. By default, resource body will be returned as part of the response. User can request no content by setting EnableContentResponseOnWrite flag to false. Note that, this API does not support the usage of IfMatchEtag property at the moment.

See Also

PatchItemStreamAsync(string, PartitionKey, IReadOnlyList<PatchOperation>, PatchItemRequestOptions, CancellationToken)

Patches an item in the Azure Cosmos service as an asynchronous operation.

public abstract Task<ResponseMessage> PatchItemStreamAsync(string id, PartitionKey partitionKey, IReadOnlyList<PatchOperation> patchOperations, PatchItemRequestOptions requestOptions = null, CancellationToken cancellationToken = default)

Parameters

id string

The Cosmos item id

partitionKey PartitionKey

The partition key for the item.

patchOperations IReadOnlyList<PatchOperation>

Represents a list of operations to be sequentially applied to the referred Cosmos item.

requestOptions PatchItemRequestOptions

(Optional) The options for the item request.

cancellationToken CancellationToken

(Optional) CancellationToken representing request cancellation.

Returns

Task<ResponseMessage>

A Task containing a ResponseMessage which wraps a Stream containing the patched resource record.

Examples

PatchItemAsync<T>(string, PartitionKey, IReadOnlyList<PatchOperation>, PatchItemRequestOptions, CancellationToken)

Remarks

The item's partition key value is immutable. To change an item's partition key value you must delete the original item and insert a new item. The patch operations are atomic and are executed sequentially. By default, resource body will be returned as part of the response. User can request no content by setting EnableContentResponseOnWrite flag to false.

See Also

ReadContainerAsync(ContainerRequestOptions, CancellationToken)

Reads a ContainerProperties from the Azure Cosmos service as an asynchronous operation.

public abstract Task<ContainerResponse> ReadContainerAsync(ContainerRequestOptions requestOptions = null, CancellationToken cancellationToken = default)

Parameters

requestOptions ContainerRequestOptions

(Optional) The options for the container request.

cancellationToken CancellationToken

(Optional) CancellationToken representing request cancellation.

Returns

Task<ContainerResponse>

A Task containing a ContainerResponse which wraps a ContainerProperties containing the read resource record.

Examples

Container container = this.database.GetContainer("containerId");
ContainerProperties containerProperties = await container.ReadContainerAsync();

ReadContainerStreamAsync(ContainerRequestOptions, CancellationToken)

Reads a ContainerProperties from the Azure Cosmos service as an asynchronous operation.

public abstract Task<ResponseMessage> ReadContainerStreamAsync(ContainerRequestOptions requestOptions = null, CancellationToken cancellationToken = default)

Parameters

requestOptions ContainerRequestOptions

(Optional) The options for the container request.

cancellationToken CancellationToken

(Optional) CancellationToken representing request cancellation.

Returns

Task<ResponseMessage>

A Task containing a ResponseMessage containing the read resource record.

Examples

Container container = this.database.GetContainer("containerId");
ResponseMessage response = await container.ReadContainerStreamAsync();

ReadItemAsync<T>(string, PartitionKey, ItemRequestOptions, CancellationToken)

Reads a item from the Azure Cosmos service as an asynchronous operation.

public abstract Task<ItemResponse<T>> ReadItemAsync<T>(string id, PartitionKey partitionKey, ItemRequestOptions requestOptions = null, CancellationToken cancellationToken = default)

Parameters

id string

The Cosmos item id

partitionKey PartitionKey

The partition key for the item.

requestOptions ItemRequestOptions

(Optional) The options for the item request.

cancellationToken CancellationToken

(Optional) CancellationToken representing request cancellation.

Returns

Task<ItemResponse<T>>

A Task containing a ItemResponse<T> which wraps the read resource record.

Type Parameters

T

Examples

public class ToDoActivity{
    public string id {get; set;}
    public string status {get; set;}
}

ToDoActivity toDoActivity = await this.container.ReadItemAsync<ToDoActivity>("id", new PartitionKey("partitionKey"));

Remarks

Items contain meta data that can be obtained by mapping these meta data attributes to properties in T.

  • "_ts": Gets the last modified time stamp associated with the item from the Azure Cosmos DB service.
  • "_etag": Gets the entity tag associated with the item from the Azure Cosmos DB service.
  • "ttl": Gets the time to live in seconds of the item in the Azure Cosmos DB service. Note that, this API does not support the usage of IfMatchEtag property at the moment.

ReadItemStreamAsync(string, PartitionKey, ItemRequestOptions, CancellationToken)

Reads a item from the Azure Cosmos service as an asynchronous operation.

public abstract Task<ResponseMessage> ReadItemStreamAsync(string id, PartitionKey partitionKey, ItemRequestOptions requestOptions = null, CancellationToken cancellationToken = default)

Parameters

id string

The Cosmos item id

partitionKey PartitionKey

The partition key for the item.

requestOptions ItemRequestOptions

(Optional) The options for the item request.

cancellationToken CancellationToken

(Optional) CancellationToken representing request cancellation.

Returns

Task<ResponseMessage>

A Task containing a ResponseMessage which wraps a Stream containing the read resource record.

Examples

Read a response as a stream.

using(ResponseMessage response = await this.container.ReadItemStreamAsync("id", new PartitionKey("partitionKey")))
{
    if (!response.IsSuccessStatusCode)
    {
        //Handle and log exception
        return;
    }

    //Read or do other operations with the stream
    using (StreamReader streamReader = new StreamReader(response.Content))
    {
        string content = await streamReader.ReadToEndAsync();
    }
}

Remarks

https://aka.ms/cosmosdb-dot-net-exceptions#stream-api 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.

ReadManyItemsAsync<T>(IReadOnlyList<(string id, PartitionKey partitionKey)>, ReadManyRequestOptions, CancellationToken)

Reads multiple items from a container using Id and PartitionKey values.

public abstract Task<FeedResponse<T>> ReadManyItemsAsync<T>(IReadOnlyList<(string id, PartitionKey partitionKey)> items, ReadManyRequestOptions readManyRequestOptions = null, CancellationToken cancellationToken = default)

Parameters

items IReadOnlyList<(string id, PartitionKey partitionKey)>

List of item.Id and PartitionKey

readManyRequestOptions ReadManyRequestOptions

Request Options for ReadMany Operation

cancellationToken CancellationToken

(Optional) CancellationToken representing request cancellation.

Returns

Task<FeedResponse<T>>

A Task containing a FeedResponse<T> which wraps the typed items.

Type Parameters

T

Examples

public class ToDoActivity{
    public string id {get; set;}
    public string status {get; set;}
}

IReadOnlyList<(string, PartitionKey)> itemList = new List<(string, PartitionKey)>
{
    ("Id1", new PartitionKey("pkValue1")),
    ("Id2", new PartitionKey("pkValue2")),
    ("Id3", new PartitionKey("pkValue3"))
};

FeedResponse<ToDoActivity> feedResponse = this.Container.ReadManyItemsAsync<ToDoActivity>(itemList);

Remarks

ReadManyItemsAsync<T>(IReadOnlyList<(string id, PartitionKey partitionKey)>, ReadManyRequestOptions, CancellationToken) is meant to perform better latency-wise than a query with IN statements to fetch a large number of independent items.

ReadManyItemsStreamAsync(IReadOnlyList<(string id, PartitionKey partitionKey)>, ReadManyRequestOptions, CancellationToken)

Reads multiple items from a container using Id and PartitionKey values.

public abstract Task<ResponseMessage> ReadManyItemsStreamAsync(IReadOnlyList<(string id, PartitionKey partitionKey)> items, ReadManyRequestOptions readManyRequestOptions = null, CancellationToken cancellationToken = default)

Parameters

items IReadOnlyList<(string id, PartitionKey partitionKey)>

List of item.Id and PartitionKey

readManyRequestOptions ReadManyRequestOptions

Request Options for ReadMany Operation

cancellationToken CancellationToken

(Optional) CancellationToken representing request cancellation.

Returns

Task<ResponseMessage>

A Task containing a ResponseMessage which wraps a Stream containing the response.

Examples

IReadOnlyList<(string, PartitionKey)> itemList = new List<(string, PartitionKey)>
{
    ("Id1", new PartitionKey("pkValue1")),
    ("Id2", new PartitionKey("pkValue2")),
    ("Id3", new PartitionKey("pkValue3"))
};

using (ResponseMessage response = await this.Container.ReadManyItemsStreamAsync(itemList))
{
    if (!response.IsSuccessStatusCode)
    {
        //Handle and log exception
        return;
    }

    //Read or do other operations with the stream
    using (StreamReader streamReader = new StreamReader(response.Content))
    {
        string content = streamReader.ReadToEndAsync();
    }

}

Remarks

ReadManyItemsStreamAsync(IReadOnlyList<(string id, PartitionKey partitionKey)>, ReadManyRequestOptions, CancellationToken) is meant to perform better latency-wise than a query with IN statements to fetch a large number of independent items.

ReadThroughputAsync(RequestOptions, CancellationToken)

Gets container throughput in measurement of request units per second in the Azure Cosmos service.

public abstract Task<ThroughputResponse> ReadThroughputAsync(RequestOptions requestOptions, CancellationToken cancellationToken = default)

Parameters

requestOptions RequestOptions

The options for the throughput request.

cancellationToken CancellationToken

(Optional) CancellationToken representing request cancellation.

Returns

Task<ThroughputResponse>

The throughput response

Examples

The following example shows how to get the throughput

RequestOptions requestOptions = new RequestOptions();
ThroughputProperties throughputProperties = await container.ReadThroughputAsync(requestOptions);
Console.WriteLine($"Throughput: {throughputProperties?.Throughput}");

The following example shows how to get throughput, MinThroughput and is replace in progress

RequestOptions requestOptions = new RequestOptions();
ThroughputResponse response = await container.ReadThroughputAsync(requestOptions);
Console.WriteLine($"Throughput: {response.Resource?.Throughput}");
Console.WriteLine($"MinThroughput: {response.MinThroughput}");
Console.WriteLine($"IsReplacePending: {response.IsReplacePending}");
See Also

ReadThroughputAsync(CancellationToken)

Gets container throughput in measurement of request units per second in the Azure Cosmos service.

public abstract Task<int?> ReadThroughputAsync(CancellationToken cancellationToken = default)

Parameters

cancellationToken CancellationToken

(Optional) CancellationToken representing request cancellation.

Returns

Task<int?>

Provisioned throughput in request units per second

Examples

The following example shows how to get the throughput.

int? throughput = await container.ReadThroughputAsync();

Remarks

Null value indicates a container with no throughput provisioned.

See Also

ReplaceContainerAsync(ContainerProperties, ContainerRequestOptions, CancellationToken)

Replace a ContainerProperties from the Azure Cosmos service as an asynchronous operation.

public abstract Task<ContainerResponse> ReplaceContainerAsync(ContainerProperties containerProperties, ContainerRequestOptions requestOptions = null, CancellationToken cancellationToken = default)

Parameters

containerProperties ContainerProperties

The ContainerProperties object.

requestOptions ContainerRequestOptions

(Optional) The options for the container request.

cancellationToken CancellationToken

(Optional) CancellationToken representing request cancellation.

Returns

Task<ContainerResponse>

A Task containing a ContainerResponse which wraps a ContainerProperties containing the replace resource record.

Examples

Update the container to disable automatic indexing

ContainerProperties containerProperties = containerReadResponse;
containerProperties.IndexingPolicy.Automatic = false;
ContainerResponse response = await container.ReplaceContainerAsync(containerProperties);
ContainerProperties replacedProperties = response;

ReplaceContainerStreamAsync(ContainerProperties, ContainerRequestOptions, CancellationToken)

Replace a ContainerProperties from the Azure Cosmos service as an asynchronous operation.

public abstract Task<ResponseMessage> ReplaceContainerStreamAsync(ContainerProperties containerProperties, ContainerRequestOptions requestOptions = null, CancellationToken cancellationToken = default)

Parameters

containerProperties ContainerProperties

The ContainerProperties.

requestOptions ContainerRequestOptions

(Optional) The options for the container request.

cancellationToken CancellationToken

(Optional) CancellationToken representing request cancellation.

Returns

Task<ResponseMessage>

A Task containing a ResponseMessage containing the replace resource record.

Examples

https://aka.ms/cosmosdb-dot-net-exceptions#stream-api

ContainerProperties containerProperties = containerReadResponse;
containerProperties.IndexingPolicy.Automatic = false;
ResponseMessage response = await container.ReplaceContainerStreamAsync(containerProperties);

ReplaceItemAsync<T>(T, string, PartitionKey?, ItemRequestOptions, CancellationToken)

Replaces a item in the Azure Cosmos service as an asynchronous operation.

public abstract Task<ItemResponse<T>> ReplaceItemAsync<T>(T item, string id, PartitionKey? partitionKey = null, ItemRequestOptions requestOptions = null, CancellationToken cancellationToken = default)

Parameters

item T

A JSON serializable object that must contain an id property. CosmosSerializer to implement a custom serializer.

id string

The Cosmos item id of the existing item.

partitionKey PartitionKey?

PartitionKey for the item. If not specified will be populated by extracting from {T}

requestOptions ItemRequestOptions

(Optional) The options for the item request.

cancellationToken CancellationToken

(Optional) CancellationToken representing request cancellation.

Returns

Task<ItemResponse<T>>

A Task containing a ItemResponse<T> which wraps the updated resource record.

Type Parameters

T

Examples

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.container.ReplaceItemAsync<ToDoActivity>(test, test.id, new PartitionKey(test.status));

Remarks

The item's partition key value is immutable. To change an item's partition key value you must delete the original item and insert a new item.

ReplaceItemStreamAsync(Stream, string, PartitionKey, ItemRequestOptions, CancellationToken)

Replaces a item in the Azure Cosmos service as an asynchronous operation.

public abstract Task<ResponseMessage> ReplaceItemStreamAsync(Stream streamPayload, string id, PartitionKey partitionKey, ItemRequestOptions requestOptions = null, CancellationToken cancellationToken = default)

Parameters

streamPayload Stream

A Stream containing the payload.

id string

The Cosmos item id

partitionKey PartitionKey

The partition key for the item.

requestOptions ItemRequestOptions

(Optional) The options for the item request.

cancellationToken CancellationToken

(Optional) CancellationToken representing request cancellation.

Returns

Task<ResponseMessage>

A Task containing a ResponseMessage which wraps a Stream containing the replace resource record.

Examples

Replace an item in Cosmos

using(ResponseMessage response = await this.container.ReplaceItemStreamAsync(stream, "itemId", new PartitionKey("itemPartitionKey"))
{
    if (!response.IsSuccessStatusCode)
    {
        //Handle and log exception
        return;
    }

    //Read or do other operations with the stream
    using (StreamReader streamReader = new StreamReader(response.Content))
    {
        string content = await streamReader.ReadToEndAsync();
    }
}

Remarks

The item's partition key value is immutable. To change an item's partition key value you must delete the original item and insert a new item.

ReplaceThroughputAsync(ThroughputProperties, RequestOptions, CancellationToken)

Sets throughput provisioned for a container in measurement of request units per second in the Azure Cosmos service.

public abstract Task<ThroughputResponse> ReplaceThroughputAsync(ThroughputProperties throughputProperties, RequestOptions requestOptions = null, CancellationToken cancellationToken = default)

Parameters

throughputProperties ThroughputProperties

The Cosmos container throughput expressed in Request Units per second.

requestOptions RequestOptions

(Optional) The options for the throughput request.

cancellationToken CancellationToken

(Optional) CancellationToken representing request cancellation.

Returns

Task<ThroughputResponse>

The throughput response.

Examples

The following example shows how to replace the fixed throughput.

ThroughputResponse throughput = await this.cosmosContainer.ReplaceThroughputAsync(
    ThroughputProperties.CreateManualThroughput(10000));

The following example shows how to replace the autoscale provisioned throughput

ThroughputResponse throughput = await this.cosmosContainer.ReplaceThroughputAsync(
    ThroughputProperties.CreateAutoscaleThroughput(10000));

Remarks

ReplaceThroughputAsync(int, RequestOptions, CancellationToken)

Sets throughput provisioned for a container in measurement of request units per second in the Azure Cosmos service.

public abstract Task<ThroughputResponse> ReplaceThroughputAsync(int throughput, RequestOptions requestOptions = null, CancellationToken cancellationToken = default)

Parameters

throughput int

The Cosmos container throughput, expressed in Request Units per second.

requestOptions RequestOptions

(Optional) The options for the throughput request.

cancellationToken CancellationToken

(Optional) CancellationToken representing request cancellation.

Returns

Task<ThroughputResponse>

The throughput response.

Examples

The following example shows how to get the throughput.

ThroughputResponse throughput = await this.cosmosContainer.ReplaceThroughputAsync(400);
See Also

UpsertItemAsync<T>(T, PartitionKey?, ItemRequestOptions, CancellationToken)

Upserts an item as an asynchronous operation in the Azure Cosmos service.

public abstract Task<ItemResponse<T>> UpsertItemAsync<T>(T item, PartitionKey? partitionKey = null, ItemRequestOptions requestOptions = null, CancellationToken cancellationToken = default)

Parameters

item T

A JSON serializable object that must contain an id property. CosmosSerializer to implement a custom serializer

partitionKey PartitionKey?

PartitionKey for the item. If not specified will be populated by extracting from {T}

requestOptions ItemRequestOptions

(Optional) The options for the item request.

cancellationToken CancellationToken

(Optional) CancellationToken representing request cancellation.

Returns

Task<ItemResponse<T>>

The ItemResponse<T> that was upserted contained within a Task object representing the service response for the asynchronous operation.

Type Parameters

T

Examples

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.container.UpsertItemAsync<ToDoActivity>(test, new PartitionKey(test.status));

Remarks

Upsert result i.e. creation or replace can be identified by the status code: 201 - item created 200 - item replaced

UpsertItemStreamAsync(Stream, PartitionKey, ItemRequestOptions, CancellationToken)

Upserts an item stream as an asynchronous operation in the Azure Cosmos service.

public abstract Task<ResponseMessage> UpsertItemStreamAsync(Stream streamPayload, PartitionKey partitionKey, ItemRequestOptions requestOptions = null, CancellationToken cancellationToken = default)

Parameters

streamPayload Stream

A Stream containing the payload.

partitionKey PartitionKey

The partition key for the item.

requestOptions ItemRequestOptions

(Optional) The options for the item request.

cancellationToken CancellationToken

(Optional) CancellationToken representing request cancellation.

Returns

Task<ResponseMessage>

A Task containing a ResponseMessage which wraps a Stream containing the read resource record.

Examples

Upsert a Stream containing the item to Cosmos

using(ResponseMessage response = await this.container.UpsertItemStreamAsync(stream, new PartitionKey("itemPartitionKey")))
{
    if (!response.IsSuccessStatusCode)
    {
        //Handle and log exception
        return;
    }

    //Read or do other operations with the stream
    using (StreamReader streamReader = new StreamReader(response.Content))
    {
        string content = await streamReader.ReadToEndAsync();
    }
}

Remarks

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.