Class DocumentClient
Provides a client-side logical representation for the Azure Cosmos DB service. This client is used to configure and execute requests against the service.
public sealed class DocumentClient : IDisposable, IDocumentClient
- Inheritance
-
DocumentClient
- Implements
- Inherited Members
- Extension Methods
Remarks
The service client that encapsulates the endpoint and credentials and connection policy used to access the Azure Cosmos DB service. It is recommended to cache and reuse this instance within your application rather than creating a new instance for every operation.
When your app uses DocumentClient, you should call its IDisposable.Dispose implementation when you are finished using it. Depending on your programming technique, you can do this in one of two ways:
1. By using a language construct such as the using statement in C#. The using statement is actually a syntactic convenience. At compile time, the language compiler implements the intermediate language (IL) for a try/catch block.
using (IDocumentClient client = new DocumentClient(new Uri("endpoint"), "authKey"))
{
...
}
2. By wrapping the call to the IDisposable.Dispose implementation in a try/catch block. The following example replaces the using block in the previous example with a try/catch/finally block.
IDocumentClient client = new DocumentClient(new Uri("endpoint"), "authKey"))
try{
...
}
finally{
if (client != null) client.Dispose();
}
Constructors
DocumentClient(Uri, IDictionary<string, string>, ConnectionPolicy, ConsistencyLevel?)
Initializes a new instance of the Microsoft.Azure.Documents.Client.DocumentClient class using the specified Azure Cosmos DB service endpoint, a dictionary of resource tokens and a connection policy.
[Obsolete("Please use the constructor that takes a permission list or a resource token list.")]
public DocumentClient(Uri serviceEndpoint, IDictionary<string, string> resourceTokens, ConnectionPolicy connectionPolicy = null, ConsistencyLevel? desiredConsistencyLevel = null)
Parameters
serviceEndpoint
UriThe service endpoint to use to create the client.
resourceTokens
IDictionary<string, string>A dictionary of resource ids and resource tokens.
connectionPolicy
ConnectionPolicy(Optional) The connection policy for the client.
desiredConsistencyLevel
ConsistencyLevel?(Optional) The default consistency policy for client operations.
Remarks
Using Direct connectivity, wherever possible, is recommended
- See Also
-
Uri
DocumentClient(Uri, IList<Permission>, ConnectionPolicy, ConsistencyLevel?)
Initializes a new instance of the DocumentClient class using the specified Azure Cosmos DB service endpoint for the Azure Cosmos DB service, a list of permission objects and a connection policy.
public DocumentClient(Uri serviceEndpoint, IList<Permission> permissionFeed, ConnectionPolicy connectionPolicy = null, ConsistencyLevel? desiredConsistencyLevel = null)
Parameters
serviceEndpoint
UriThe service endpoint to use to create the client.
permissionFeed
IList<Permission>A list of Permission objects to use to create the client.
connectionPolicy
ConnectionPolicy(Optional) The ConnectionPolicy to use for this connection.
desiredConsistencyLevel
ConsistencyLevel?(Optional) The default consistency policy for client operations.
Remarks
If no connectionPolicy
is provided, then the default ConnectionPolicy will be used.
Using Direct connectivity, wherever possible, is recommended.
Exceptions
- ArgumentNullException
If
permissionFeed
is not supplied.- ArgumentException
If
permissionFeed
is not a valid permission link.
- See Also
-
Uri
DocumentClient(Uri, SecureString, ConnectionPolicy, ConsistencyLevel?)
Initializes a new instance of the DocumentClient class using the specified Azure Cosmos DB service endpoint, key, and connection policy for the Azure Cosmos DB service.
public DocumentClient(Uri serviceEndpoint, SecureString authKey, ConnectionPolicy connectionPolicy = null, ConsistencyLevel? desiredConsistencyLevel = null)
Parameters
serviceEndpoint
UriThe service endpoint to use to create the client.
authKey
SecureStringThe list of Permission objects to use to create the client.
connectionPolicy
ConnectionPolicy(Optional) The connection policy for the client. If none is passed, the default is used ConnectionPolicy
desiredConsistencyLevel
ConsistencyLevel?(Optional) This can be used to weaken the database account consistency level for read operations. If this is not set the database account consistency level will be used for all requests.
Remarks
The service endpoint and the authorization key can be obtained from the Azure Management Portal. The authKey used here is encrypted for privacy when being used, and deleted from computer memory when no longer needed
Using Direct connectivity, wherever possible, is recommended
- See Also
-
Uri
DocumentClient(Uri, SecureString, ConnectionPolicy, ConsistencyLevel?, JsonSerializerSettings)
Initializes a new instance of the DocumentClient class using the specified Azure Cosmos DB service endpoint, key, connection policy and a custom JsonSerializerSettings for the Azure Cosmos DB service.
[Obsolete("Please use the constructor that takes JsonSerializerSettings as the third parameter.")]
public DocumentClient(Uri serviceEndpoint, SecureString authKey, ConnectionPolicy connectionPolicy, ConsistencyLevel? desiredConsistencyLevel, JsonSerializerSettings serializerSettings)
Parameters
serviceEndpoint
UriThe service endpoint to use to create the client.
authKey
SecureStringThe list of Permission objects to use to create the client.
connectionPolicy
ConnectionPolicyThe connection policy for the client.
desiredConsistencyLevel
ConsistencyLevel?This can be used to weaken the database account consistency level for read operations. If this is not set the database account consistency level will be used for all requests.
serializerSettings
JsonSerializerSettingsThe custom JsonSerializer settings to be used for serialization/derialization.
Remarks
The service endpoint and the authorization key can be obtained from the Azure Management Portal. The authKey used here is encrypted for privacy when being used, and deleted from computer memory when no longer needed
Using Direct connectivity, wherever possible, is recommended
- See Also
-
UriJsonSerializerSettings
DocumentClient(Uri, SecureString, JsonSerializerSettings, ConnectionPolicy, ConsistencyLevel?)
Initializes a new instance of the DocumentClient class using the specified Azure Cosmos DB service endpoint, key, connection policy and a custom JsonSerializerSettings for the Azure Cosmos DB service.
public DocumentClient(Uri serviceEndpoint, SecureString authKey, JsonSerializerSettings serializerSettings, ConnectionPolicy connectionPolicy = null, ConsistencyLevel? desiredConsistencyLevel = null)
Parameters
serviceEndpoint
UriThe service endpoint to use to create the client.
authKey
SecureStringThe list of Permission objects to use to create the client.
serializerSettings
JsonSerializerSettingsThe custom JsonSerializer settings to be used for serialization/derialization.
connectionPolicy
ConnectionPolicy(Optional) The connection policy for the client. If none is passed, the default is used ConnectionPolicy
desiredConsistencyLevel
ConsistencyLevel?(Optional) This can be used to weaken the database account consistency level for read operations. If this is not set the database account consistency level will be used for all requests.
Remarks
The service endpoint and the authorization key can be obtained from the Azure Management Portal. The authKey used here is encrypted for privacy when being used, and deleted from computer memory when no longer needed
Using Direct connectivity, wherever possible, is recommended
- See Also
-
UriJsonSerializerSettings
DocumentClient(Uri, string, ConnectionPolicy, ConsistencyLevel?)
Initializes a new instance of the DocumentClient class using the specified service endpoint, an authorization key (or resource token) and a connection policy for the Azure Cosmos DB service.
public DocumentClient(Uri serviceEndpoint, string authKeyOrResourceToken, ConnectionPolicy connectionPolicy = null, ConsistencyLevel? desiredConsistencyLevel = null)
Parameters
serviceEndpoint
UriThe service endpoint to use to create the client.
authKeyOrResourceToken
stringThe authorization key or resource token to use to create the client.
connectionPolicy
ConnectionPolicy(Optional) The connection policy for the client.
desiredConsistencyLevel
ConsistencyLevel?(Optional) The default consistency policy for client operations.
Remarks
The service endpoint can be obtained from the Azure Management Portal.
If you are connecting using one of the Master Keys, these can be obtained along with the endpoint from the Azure Management Portal
If however you are connecting as a specific Azure Cosmos DB User, the value passed to authKeyOrResourceToken
is the ResourceToken obtained from the permission feed for the user.
Using Direct connectivity, wherever possible, is recommended.
- See Also
-
Uri
DocumentClient(Uri, string, ConnectionPolicy, ConsistencyLevel?, JsonSerializerSettings)
Initializes a new instance of the DocumentClient class using the specified service endpoint, an authorization key (or resource token), a connection policy and a custom JsonSerializerSettings for the Azure Cosmos DB service.
[Obsolete("Please use the constructor that takes JsonSerializerSettings as the third parameter.")]
public DocumentClient(Uri serviceEndpoint, string authKeyOrResourceToken, ConnectionPolicy connectionPolicy, ConsistencyLevel? desiredConsistencyLevel, JsonSerializerSettings serializerSettings)
Parameters
serviceEndpoint
UriThe service endpoint to use to create the client.
authKeyOrResourceToken
stringThe authorization key or resource token to use to create the client.
connectionPolicy
ConnectionPolicyThe connection policy for the client.
desiredConsistencyLevel
ConsistencyLevel?The default consistency policy for client operations.
serializerSettings
JsonSerializerSettingsThe custom JsonSerializer settings to be used for serialization/derialization.
Remarks
The service endpoint can be obtained from the Azure Management Portal.
If you are connecting using one of the Master Keys, these can be obtained along with the endpoint from the Azure Management Portal
If however you are connecting as a specific Azure Cosmos DB User, the value passed to authKeyOrResourceToken
is the ResourceToken obtained from the permission feed for the user.
Using Direct connectivity, wherever possible, is recommended.
- See Also
-
UriJsonSerializerSettings
DocumentClient(Uri, string, JsonSerializerSettings, ConnectionPolicy, ConsistencyLevel?)
Initializes a new instance of the DocumentClient class using the specified service endpoint, an authorization key (or resource token), a connection policy and a custom JsonSerializerSettings for the Azure Cosmos DB service.
public DocumentClient(Uri serviceEndpoint, string authKeyOrResourceToken, JsonSerializerSettings serializerSettings, ConnectionPolicy connectionPolicy = null, ConsistencyLevel? desiredConsistencyLevel = null)
Parameters
serviceEndpoint
UriThe service endpoint to use to create the client.
authKeyOrResourceToken
stringThe authorization key or resource token to use to create the client.
serializerSettings
JsonSerializerSettingsThe custom JsonSerializer settings to be used for serialization/derialization.
connectionPolicy
ConnectionPolicy(Optional) The connection policy for the client.
desiredConsistencyLevel
ConsistencyLevel?(Optional) The default consistency policy for client operations.
Remarks
The service endpoint can be obtained from the Azure Management Portal.
If you are connecting using one of the Master Keys, these can be obtained along with the endpoint from the Azure Management Portal
If however you are connecting as a specific Azure Cosmos DB User, the value passed to authKeyOrResourceToken
is the ResourceToken obtained from the permission feed for the user.
Using Direct connectivity, wherever possible, is recommended.
- See Also
-
UriJsonSerializerSettings
DocumentClient(Uri, string, HttpMessageHandler, ConnectionPolicy, ConsistencyLevel?)
Initializes a new instance of the DocumentClient class using the specified service endpoint, an authorization key (or resource token) and a connection policy for the Azure Cosmos DB service.
public DocumentClient(Uri serviceEndpoint, string authKeyOrResourceToken, HttpMessageHandler handler, ConnectionPolicy connectionPolicy = null, ConsistencyLevel? desiredConsistencyLevel = null)
Parameters
serviceEndpoint
UriThe service endpoint to use to create the client.
authKeyOrResourceToken
stringThe authorization key or resource token to use to create the client.
handler
HttpMessageHandlerThe HTTP handler stack to use for sending requests (e.g., HttpClientHandler).
connectionPolicy
ConnectionPolicy(Optional) The connection policy for the client.
desiredConsistencyLevel
ConsistencyLevel?(Optional) The default consistency policy for client operations.
Remarks
The service endpoint can be obtained from the Azure Management Portal.
If you are connecting using one of the Master Keys, these can be obtained along with the endpoint from the Azure Management Portal
If however you are connecting as a specific Azure Cosmos DB User, the value passed to authKeyOrResourceToken
is the ResourceToken obtained from the permission feed for the user.
Using Direct connectivity, wherever possible, is recommended.
- See Also
-
Uri
Properties
AuthKey
Gets the AuthKey used by the client from the Azure Cosmos DB service.
public SecureString AuthKey { get; }
Property Value
- SecureString
The AuthKey used by the client.
- See Also
ConnectionPolicy
Gets the Connection policy used by the client from the Azure Cosmos DB service.
public ConnectionPolicy ConnectionPolicy { get; }
Property Value
- ConnectionPolicy
The Connection policy used by the client.
- See Also
ConsistencyLevel
Gets the configured consistency level of the client from the Azure Cosmos DB service.
public ConsistencyLevel ConsistencyLevel { get; }
Property Value
- ConsistencyLevel
The configured ConsistencyLevel of the client.
- See Also
PartitionResolvers
Partition resolvers are a dictionary of database links to IPartitionResolver to be used in partitioning for the Azure Cosmos DB service.
[Obsolete("Support for IPartitionResolver is now obsolete. It's recommended that you use partitioned collections for higher storage and throughput.")]
public IDictionary<string, IPartitionResolver> PartitionResolvers { get; }
Property Value
Remarks
Support for IPartitionResolver is now obsolete. It's recommended that you use Partitioned Collections for higher storage and throughput.
ReadEndpoint
Gets the current read endpoint chosen based on availability and preference from the Azure Cosmos DB service.
public Uri ReadEndpoint { get; }
Property Value
- Uri
ResourceTokens
Gets a dictionary of resource tokens used by the client from the Azure Cosmos DB service.
[Obsolete]
public IDictionary<string, string> ResourceTokens { get; }
Property Value
- IDictionary<string, string>
A dictionary of resource tokens used by the client.
- See Also
-
IDictionary<TKey, TValue>
ServiceEndpoint
Gets the endpoint Uri for the service endpoint from the Azure Cosmos DB service.
public Uri ServiceEndpoint { get; }
Property Value
- Uri
The Uri for the service endpoint.
- See Also
-
Uri
Session
Gets or sets the session object used for session consistency version tracking in the Azure Cosmos DB service.
public object Session { get; set; }
Property Value
Remarks
WriteEndpoint
Gets the current write endpoint chosen based on availability and preference from the Azure Cosmos DB service.
public Uri WriteEndpoint { get; }
Property Value
- Uri
Methods
CreateAttachmentAsync(string, Stream, MediaOptions, RequestOptions, CancellationToken)
Creates an Attachment with the contents of the provided mediaStream
as an asynchronous operation
in the Azure Cosmos DB service.
public Task<ResourceResponse<Attachment>> CreateAttachmentAsync(string attachmentsLink, Stream mediaStream, MediaOptions options = null, RequestOptions requestOptions = null, CancellationToken cancellationToken = default)
Parameters
attachmentsLink
stringThe attachments link for the document. E.g. dbs/db_rid/colls/col_rid/docs/doc_rid/attachments/
mediaStream
Streamthe Stream of the attachment media.
options
MediaOptionsthe MediaOptions for the request.
requestOptions
RequestOptionsRequest options.
cancellationToken
CancellationToken(Optional) A CancellationToken that can be used by other objects or threads to receive notice of cancellation.
Returns
- Task<ResourceResponse<Attachment>>
The task object representing the service response for the asynchronous operation.
Examples
//This attachment could be any binary you want to attach. Like images, videos, word documents, pdfs etc. it doesn't matter
using (FileStream fileStream = new FileStream(@".\something.pdf", FileMode.Open))
{
//Create the attachment
Attachment attachment = await client.CreateAttachmentAsync("dbs/db_rid/colls/coll_rid/docs/doc_rid/attachments/",
fileStream,
new MediaOptions
{
ContentType = "application/pdf",
Slug = "something.pdf"
});
}
Exceptions
- ArgumentNullException
If either
attachmentsLink
ormediaStream
is not set.
- See Also
-
ResourceResponse<TResource>
CreateAttachmentAsync(string, object, RequestOptions, CancellationToken)
Creates an attachment as an asychronous operation in the Azure Cosmos DB service.
public Task<ResourceResponse<Attachment>> CreateAttachmentAsync(string documentLink, object attachment, RequestOptions options = null, CancellationToken cancellationToken = default)
Parameters
documentLink
stringThe link of the parent document for this new attachment. E.g. dbs/db_rid/colls/col_rid/docs/doc_rid/
attachment
objectThe attachment object.
options
RequestOptions(Optional) The request options for the request.
cancellationToken
CancellationToken(Optional) A CancellationToken that can be used by other objects or threads to receive notice of cancellation.
Returns
- Task<ResourceResponse<Attachment>>
The Task object representing the service response for the asynchronous operation.
Examples
The example below creates a new document, and then creates a new attachment for that document
dynamic d = new
{
id = "DOC1800243243470"
};
Document doc = await client.CreateDocumentAsync(collectionSelfLink, d);
//Create an Attachment which links to binary content stored somewhere else
//Use the MediaLink property of Attachment to set where the binary resides
//MediaLink can also point at another Attachment within Azure Cosmos DB.
Attachment a = await client.CreateAttachmentAsync(doc.SelfLink, new Attachment { Id = "foo", ContentType = "text/plain", MediaLink = "link to your media" });
//Because Attachment is a Dynamic object you can use SetPropertyValue method to any property you like
//Even if that property doesn't exist. Here we are creating two new properties on the Attachment we created above.
a.SetPropertyValue("Foo", "some value");
a.SetPropertyValue("Bar", "some value");
//Now update the Attachment object in the database to persist the new properties on the object
client.ReplaceAttachmentAsync(a);
//Let's now create another Attachment except this time we're going to use a Dynamic object instead
//of a <see cref="Microsoft.Azure.Documents.Attachment"/> as we did above.
var b = await client.CreateAttachmentAsync(doc.SelfLink, new { id = "foo", contentType = "text/plain", media="link to your media", a = 5, b = 6 });
//Now you will have a Document in your database with two attachments.
- See Also
-
ResourceResponse<TResource>
CreateAttachmentAsync(Uri, Stream, MediaOptions, RequestOptions, CancellationToken)
Creates an attachment as an asynchronous operation in the Azure Cosmos DB service.
public Task<ResourceResponse<Attachment>> CreateAttachmentAsync(Uri documentUri, Stream mediaStream, MediaOptions options = null, RequestOptions requestOptions = null, CancellationToken cancellationToken = default)
Parameters
documentUri
Urithe URI of the document to create an attachment for.
mediaStream
Streamthe stream of the attachment media.
options
MediaOptionsthe media options for the request.
requestOptions
RequestOptionsThe request options for the request.
cancellationToken
CancellationToken(Optional) CancellationToken representing request cancellation.
Returns
- Task<ResourceResponse<Attachment>>
The task object representing the service response for the asynchronous operation.
CreateAttachmentAsync(Uri, object, RequestOptions, CancellationToken)
Creates an attachment as an asychronous operation in the Azure Cosmos DB service.
public Task<ResourceResponse<Attachment>> CreateAttachmentAsync(Uri documentUri, object attachment, RequestOptions options = null, CancellationToken cancellationToken = default)
Parameters
documentUri
Urithe URI of the document to create an attachment for.
attachment
objectthe attachment object.
options
RequestOptionsThe request options for the request.
cancellationToken
CancellationToken(Optional) CancellationToken representing request cancellation.
Returns
- Task<ResourceResponse<Attachment>>
The task object representing the service response for the asynchronous operation.
CreateAttachmentQuery(string, FeedOptions)
Overloaded. This method creates a query for attachments in the Azure Cosmos DB service. It returns an IOrderedQueryable{Attachment}.
public IOrderedQueryable<Attachment> CreateAttachmentQuery(string documentLink, FeedOptions feedOptions = null)
Parameters
documentLink
stringThe link to the parent document
feedOptions
FeedOptionsThe options for processing the query result feed. For details, see FeedOptions
Returns
- IOrderedQueryable<Attachment>
An IOrderedQueryable{Attachments} that can evaluate the query with the provided SQL statement.
Examples
This example below queries for plain text attachments using LINQ.
foreach (Attachment attachment in client.CreateAttachmentQuery(document.SelfLink).Where(a => a.ContentType == "text/plain"))
{
Console.WriteLine("Id: {0}, MediaLink:{1}", attachment.Id, attachment.MediaLink);
}
- See Also
CreateAttachmentQuery(string, SqlQuerySpec, FeedOptions)
Overloaded. This method creates a query for attachments in the Azure Cosmos DB service by using a SQL statement with parameterized values. It returns an IQueryable{dynamic}. For more information on preparing SQL statements with parameterized values, please see SqlQuerySpec.
public IQueryable<dynamic> CreateAttachmentQuery(string documentLink, SqlQuerySpec querySpec, FeedOptions feedOptions = null)
Parameters
documentLink
stringThe link to the parent document resource.
querySpec
SqlQuerySpecThe SqlQuerySpec instance containing the SQL expression.
feedOptions
FeedOptionsThe options for processing the query result feed. For details, see FeedOptions
Returns
- IQueryable<dynamic>
An IQueryable{dynamic} that can evaluate the query with the provided SQL statement.
Examples
This example below queries for plain text attachments using a parameterized SQL query string.
var query = new SqlQuerySpec(
"SELECT * FROM attachments a WHERE a.priority = @priority",
new SqlParameterCollection(new SqlParameter[] { new SqlParameter { Name = "@priority", Value = 0 } }));
foreach (dynamic attachment in client.CreateAttachmentQuery<dynamic>(document.SelfLink, query))
{
Console.WriteLine("Id: {0}, Priority:{1}", attachment.id, attachment.priority);
}
Remarks
Refer to https://msdn.microsoft.com/en-us/library/azure/dn782250.aspx and http://azure.microsoft.com/documentation/articles/documentdb-sql-query/ for syntax and examples.
- See Also
CreateAttachmentQuery(string, string, FeedOptions)
Overloaded. This method creates a query for attachments in the Azure Cosmos DB service by using a SQL statement. It returns an IQueryable{dynamic}.
public IQueryable<dynamic> CreateAttachmentQuery(string documentLink, string sqlExpression, FeedOptions feedOptions = null)
Parameters
documentLink
stringThe link to the parent document.
sqlExpression
stringThe SQL statement.
feedOptions
FeedOptionsThe options for processing the query result feed. For details, see FeedOptions
Returns
- IQueryable<dynamic>
An IQueryable{dynamic} that can evaluate the query with the provided SQL statement.
Examples
foreach (Attachment attachment in client.CreateAttachmentQuery<dynamic>(
document.SelfLink,
"SELECT * FROM attachments a WHERE a.priority = 0"))
{
Console.WriteLine("Id: {0}, Priority:{1}", attachment.id, attachment.priority);
}
Remarks
Refer to https://msdn.microsoft.com/en-us/library/azure/dn782250.aspx and http://azure.microsoft.com/documentation/articles/documentdb-sql-query/ for syntax and examples.
- See Also
CreateAttachmentQuery(Uri, FeedOptions)
Extension method to create a query for attachments in the Azure Cosmos DB service.
public IOrderedQueryable<Attachment> CreateAttachmentQuery(Uri attachmentsUri, FeedOptions feedOptions = null)
Parameters
attachmentsUri
Urithe URI to the attachments.
feedOptions
FeedOptionsThe options for processing the query results feed.
Returns
- IOrderedQueryable<Attachment>
The query result set.
CreateAttachmentQuery(Uri, SqlQuerySpec, FeedOptions)
Extension method to create a query for attachments in the Azure Cosmos DB service.
public IQueryable<dynamic> CreateAttachmentQuery(Uri attachmentsUri, SqlQuerySpec querySpec, FeedOptions feedOptions = null)
Parameters
attachmentsUri
Urithe URI to the attachments.
querySpec
SqlQuerySpecThe sql query.
feedOptions
FeedOptionsThe options for processing the query results feed.
Returns
- IQueryable<dynamic>
The query result set.
CreateAttachmentQuery(Uri, string, FeedOptions)
Extension method to create a query for attachments in the Azure Cosmos DB service.
public IQueryable<dynamic> CreateAttachmentQuery(Uri attachmentsUri, string sqlExpression, FeedOptions feedOptions = null)
Parameters
attachmentsUri
Urithe URI to the attachments.
sqlExpression
stringThe sql query.
feedOptions
FeedOptionsThe options for processing the query results feed.
Returns
- IQueryable<dynamic>
The query result set.
CreateAttachmentQuery<T>(string, FeedOptions)
Overloaded. This method creates a query for attachments in the Azure Cosmos DB service.
public IOrderedQueryable<T> CreateAttachmentQuery<T>(string documentLink, FeedOptions feedOptions = null)
Parameters
documentLink
stringThe link of the parent document.
feedOptions
FeedOptionsThe options for processing the query result feed. For details, see FeedOptions
Returns
- IOrderedQueryable<T>
An IOrderedQueryable{T} that can evaluate the query.
Type Parameters
T
The type of object to query.
Examples
This example below queries against attachments of custom types.
public class PriorityAttachment : Attachment
{
[JsonProperty("priority")]
public int Priority;
}
foreach (PriorityAttachment attachment in
client.CreateAttachmentQuery<PriorityAttachment>(document.SelfLink).Where(a => a.Priority == 0))
{
Console.WriteLine("Id: {0}, MediaLink:{1}", attachment.Id, attachment.MediaLink);
}
- See Also
CreateAttachmentQuery<T>(string, SqlQuerySpec, FeedOptions)
Overloaded. This method creates a query for attachments in the Azure Cosmos DB service by using a SQL statement with parameterized values. For more information on preparing SQL statements with parameterized values, please see SqlQuerySpec.
public IQueryable<T> CreateAttachmentQuery<T>(string documentLink, SqlQuerySpec querySpec, FeedOptions feedOptions = null)
Parameters
documentLink
stringThe link of the parent document.
querySpec
SqlQuerySpecThe SqlQuerySpec instance containing the SQL expression.
feedOptions
FeedOptionsThe options for processing the query result feed. For details, see FeedOptions
Returns
- IQueryable<T>
An IQueryable{T} that can evaluate the query with the provided SQL statement.
Type Parameters
T
Examples
This example below queries for plain text attachments using a parameterized SQL query string.
var query = new SqlQuerySpec(
"SELECT * FROM attachments a WHERE a.contentType = @contentType",
new SqlParameterCollection(new SqlParameter[] { new SqlParameter { Name = "@contentType", Value = "text/plain" } }));
foreach (Attachment attachment in client.CreateAttachmentQuery(document.SelfLink, query))
{
Console.WriteLine("Id: {0}, MediaLink:{1}", attachment.Id, attachment.MediaLink);
}
Remarks
Refer to https://msdn.microsoft.com/en-us/library/azure/dn782250.aspx and http://azure.microsoft.com/documentation/articles/documentdb-sql-query/ for syntax and examples.
- See Also
CreateAttachmentQuery<T>(string, string, FeedOptions)
Overloaded. This method creates a query for attachments in the Azure Cosmos DB service by using a SQL statement.
public IQueryable<T> CreateAttachmentQuery<T>(string documentLink, string sqlExpression, FeedOptions feedOptions = null)
Parameters
documentLink
stringThe link of the parent document.
sqlExpression
stringThe SQL statement.
feedOptions
FeedOptionsThe options for processing the query result feed. For details, see FeedOptions
Returns
- IQueryable<T>
An IQueryable{T} that can evaluate the query with the provided SQL statement.
Type Parameters
T
Examples
This example below queries for plain text attachments using a SQL query string.
foreach (Attachment attachment in client.CreateAttachmentQuery(
document.SelfLink,
"SELECT * FROM attachments a WHERE a.contentType = 'text/plain'"))
{
Console.WriteLine("Id: {0}, MediaLink:{1}", attachment.Id, attachment.MediaLink);
}
Remarks
Refer to https://msdn.microsoft.com/en-us/library/azure/dn782250.aspx and http://azure.microsoft.com/documentation/articles/documentdb-sql-query/ for syntax and examples.
- See Also
CreateAttachmentQuery<T>(Uri, FeedOptions)
Extension method to create a query for attachments in the Azure Cosmos DB service.
public IOrderedQueryable<T> CreateAttachmentQuery<T>(Uri attachmentsUri, FeedOptions feedOptions = null)
Parameters
attachmentsUri
Urithe URI to the attachments.
feedOptions
FeedOptionsThe options for processing the query results feed.
Returns
- IOrderedQueryable<T>
The query result set.
Type Parameters
T
the type of object to query.
CreateAttachmentQuery<T>(Uri, SqlQuerySpec, FeedOptions)
Extension method to create a query for attachments in the Azure Cosmos DB service.
public IQueryable<T> CreateAttachmentQuery<T>(Uri attachmentsUri, SqlQuerySpec querySpec, FeedOptions feedOptions = null)
Parameters
attachmentsUri
Urithe URI to the attachments.
querySpec
SqlQuerySpecThe sql query.
feedOptions
FeedOptionsThe options for processing the query results feed.
Returns
- IQueryable<T>
The query result set.
Type Parameters
T
CreateAttachmentQuery<T>(Uri, string, FeedOptions)
Extension method to create a query for attachments in the Azure Cosmos DB service.
public IQueryable<T> CreateAttachmentQuery<T>(Uri attachmentsUri, string sqlExpression, FeedOptions feedOptions = null)
Parameters
attachmentsUri
Urithe URI to the attachments.
sqlExpression
stringThe sql query.
feedOptions
FeedOptionsThe options for processing the query results feed.
Returns
- IQueryable<T>
The query result set.
Type Parameters
T
CreateConflictQuery(string, FeedOptions)
Overloaded. This method creates a query for conflicts under a collection in an Azure Cosmos DB service. It returns An IOrderedQueryable{Conflict}.
public IOrderedQueryable<Conflict> CreateConflictQuery(string collectionLink, FeedOptions feedOptions = null)
Parameters
collectionLink
stringThe link to the parent collection resource.
feedOptions
FeedOptionsThe options for processing the query result feed. For details, see FeedOptions
Returns
- IOrderedQueryable<Conflict>
An IOrderedQueryable{Conflict} that can evaluate the query with the provided SQL statement.
Examples
This example below queries for conflicts by id.
Conflict conflict = client.CreateConflictQuery(collectionLink).Where(c => c.Id == "summary").AsEnumerable().FirstOrDefault();
- See Also
CreateConflictQuery(string, SqlQuerySpec, FeedOptions)
Overloaded. This method creates a query for conflicts under a collection in an Azure Cosmos DB database with parameterized values. It returns an IQueryable{dynamic}. For more information on preparing SQL statements with parameterized values, please see SqlQuerySpec.
public IQueryable<dynamic> CreateConflictQuery(string collectionLink, SqlQuerySpec querySpec, FeedOptions feedOptions = null)
Parameters
collectionLink
stringThe link to the parent collection resource.
querySpec
SqlQuerySpecThe SqlQuerySpec instance containing the SQL expression.
feedOptions
FeedOptionsThe options for processing the query result feed. For details, see FeedOptions
Returns
- IQueryable<dynamic>
An IQueryable{dynamic} that can evaluate the query with the provided SQL statement.
Examples
This example below queries for conflicts by id.
var query = new SqlQuerySpec("SELECT * FROM conflicts c WHERE c.id = @id", new SqlParameterCollection(new SqlParameter[] { new SqlParameter { Name = "@id", Value = "summary" }}));
dynamic conflict = client.CreateConflictQuery<dynamic>(collectionLink, query).AsEnumerable().FirstOrDefault();
Remarks
Refer to https://msdn.microsoft.com/en-us/library/azure/dn782250.aspx and http://azure.microsoft.com/documentation/articles/documentdb-sql-query/ for syntax and examples.
- See Also
CreateConflictQuery(string, string, FeedOptions)
Overloaded. This method creates a query for conflicts under a collection in an Azure Cosmos DB service. It returns an IQueryable{Conflict}.
public IQueryable<dynamic> CreateConflictQuery(string collectionLink, string sqlExpression, FeedOptions feedOptions = null)
Parameters
collectionLink
stringThe link to the parent collection resource.
sqlExpression
stringThe SQL statement.
feedOptions
FeedOptionsThe options for processing the query result feed. For details, see FeedOptions
Returns
- IQueryable<dynamic>
An IQueryable{dynamic} that can evaluate the query with the the provided SQL statement.
Examples
This example below queries for conflicts by id.
var query = new SqlQuerySpec("SELECT * FROM conflicts c WHERE c.id = @id", new SqlParameterCollection(new SqlParameter[] { new SqlParameter { Name = "@id", Value = "summary" }}));
Conflict conflict = client.CreateConflictQuery(collectionLink, query).AsEnumerable().FirstOrDefault();
Remarks
Refer to https://msdn.microsoft.com/en-us/library/azure/dn782250.aspx and http://azure.microsoft.com/documentation/articles/documentdb-sql-query/ for syntax and examples.
- See Also
CreateConflictQuery(Uri, FeedOptions)
Extension method to create a query for conflicts in the Azure Cosmos DB service.
public IOrderedQueryable<Conflict> CreateConflictQuery(Uri conflictsUri, FeedOptions feedOptions = null)
Parameters
conflictsUri
Urithe URI to the conflicts.
feedOptions
FeedOptionsThe options for processing the query results feed.
Returns
- IOrderedQueryable<Conflict>
The query result set.
CreateConflictQuery(Uri, SqlQuerySpec, FeedOptions)
Extension method to create a query for conflicts in the Azure Cosmos DB service.
public IQueryable<dynamic> CreateConflictQuery(Uri conflictsUri, SqlQuerySpec querySpec, FeedOptions feedOptions = null)
Parameters
conflictsUri
Urithe URI to the conflicts.
querySpec
SqlQuerySpecThe sql query.
feedOptions
FeedOptionsThe options for processing the query results feed.
Returns
- IQueryable<dynamic>
The query result set.
CreateConflictQuery(Uri, string, FeedOptions)
Extension method to create a query for conflicts in the Azure Cosmos DB service.
public IQueryable<dynamic> CreateConflictQuery(Uri conflictsUri, string sqlExpression, FeedOptions feedOptions = null)
Parameters
conflictsUri
Urithe URI to the conflicts.
sqlExpression
stringThe sql query.
feedOptions
FeedOptionsThe options for processing the query results feed.
Returns
- IQueryable<dynamic>
The query result set.
CreateDatabaseAsync(Database, RequestOptions)
Creates a database resource as an asychronous operation in the Azure Cosmos DB service.
public Task<ResourceResponse<Database>> CreateDatabaseAsync(Database database, RequestOptions options = null)
Parameters
database
DatabaseThe specification for the Database to create.
options
RequestOptions(Optional) The RequestOptions for the request.
Returns
- Task<ResourceResponse<Database>>
The Database that was created within a task object representing the service response for the asynchronous operation.
Examples
The example below creates a new Database with an Id property of 'MyDatabase' This code snippet is intended to be used from within an asynchronous method as it uses the await keyword
using (IDocumentClient client = new DocumentClient(new Uri("service endpoint"), "auth key"))
{
Database db = await client.CreateDatabaseAsync(new Database { Id = "MyDatabase" });
}
If you would like to construct a Database from within a synchronous method then you need to use the following code
using (IDocumentClient client = new DocumentClient(new Uri("service endpoint"), "auth key"))
{
Database db = client.CreateDatabaseAsync(new Database { Id = "MyDatabase" }).Result;
}
Exceptions
- ArgumentNullException
If
database
is not set.- AggregateException
Represents a consolidation of failures that occured during async processing. Look within InnerExceptions to find the actual exception(s).
- DocumentClientException
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 Database are:
StatusCode Reason for exception 400 BadRequest - This means something was wrong with the database object supplied. It is likely that an id was not supplied for the new Database. 409 Conflict - This means a Database with an id matching the id field of database
already existed.
- See Also
-
ResourceResponse<TResource>
CreateDatabaseIfNotExistsAsync(Database, RequestOptions)
Creates(if doesn't exist) or gets(if already exists) a database resource as an asychronous operation in the Azure Cosmos DB service. You can check the status code from the response to determine whether the database was newly created(201) or existing database was returned(200)
public Task<ResourceResponse<Database>> CreateDatabaseIfNotExistsAsync(Database database, RequestOptions options = null)
Parameters
database
DatabaseThe specification for the Database to create.
options
RequestOptions(Optional) The RequestOptions for the request.
Returns
- Task<ResourceResponse<Database>>
The Database that was created within a task object representing the service response for the asynchronous operation.
Examples
The example below creates a new Database with an Id property of 'MyDatabase' This code snippet is intended to be used from within an asynchronous method as it uses the await keyword
using (IDocumentClient client = new DocumentClient(new Uri("service endpoint"), "auth key"))
{
Database db = await client.CreateDatabaseIfNotExistsAsync(new Database { Id = "MyDatabase" });
}
If you would like to construct a Database from within a synchronous method then you need to use the following code
using (IDocumentClient client = new DocumentClient(new Uri("service endpoint"), "auth key"))
{
Database db = client.CreateDatabaseIfNotExistsAsync(new Database { Id = "MyDatabase" }).Result;
}
Exceptions
- ArgumentNullException
If
database
is not set.- AggregateException
Represents a consolidation of failures that occured during async processing. Look within InnerExceptions to find the actual exception(s).
- DocumentClientException
This exception can encapsulate many different types of errors. To determine the specific error always look at the StatusCode property.
- See Also
-
ResourceResponse<TResource>
CreateDatabaseQuery(FeedOptions)
Overloaded. This method creates a query for database resources under an account in the Azure Cosmos DB service. It returns An IOrderedQueryable{Database}.
public IOrderedQueryable<Database> CreateDatabaseQuery(FeedOptions feedOptions = null)
Parameters
feedOptions
FeedOptionsThe options for processing the query result feed. For details, see FeedOptions
Returns
- IOrderedQueryable<Database>
An IOrderedQueryable{Database} that can evaluate the query with the provided SQL statement.
Examples
This example below queries for databases by id.
Database database = client.CreateDatabaseQuery().Where(d => d.Id == "mydb").AsEnumerable().FirstOrDefault();
- See Also
CreateDatabaseQuery(SqlQuerySpec, FeedOptions)
Overloaded. This method creates a query for database resources under an Azure Cosmos DB database account by using a SQL statement with parameterized values. It returns an IQueryable{dynamic}. For more information on preparing SQL statements with parameterized values, please see SqlQuerySpec.
public IQueryable<dynamic> CreateDatabaseQuery(SqlQuerySpec querySpec, FeedOptions feedOptions = null)
Parameters
querySpec
SqlQuerySpecThe SqlQuerySpec instance containing the SQL expression.
feedOptions
FeedOptionsThe options for processing the query result feed. For details, see FeedOptions
Returns
- IQueryable<dynamic>
An IQueryable{dynamic} that can evaluate the query with the provided SQL statement.
Examples
This example below queries for databases by id.
var query = new SqlQuerySpec("SELECT * FROM dbs d WHERE d.id = @id",
new SqlParameterCollection(new SqlParameter[] { new SqlParameter { Name = "@id", Value = "mydb" }}));
dynamic database = client.CreateDatabaseQuery<dynamic>(query).AsEnumerable().FirstOrDefault();
Remarks
Refer to https://msdn.microsoft.com/en-us/library/azure/dn782250.aspx and http://azure.microsoft.com/documentation/articles/documentdb-sql-query/ for syntax and examples.
- See Also
CreateDatabaseQuery(string, FeedOptions)
Overloaded. This method creates a query for database resources under an Azure Cosmos DB database account by using a SQL statement. It returns an IQueryable{dynamic}.
public IQueryable<dynamic> CreateDatabaseQuery(string sqlExpression, FeedOptions feedOptions = null)
Parameters
sqlExpression
stringThe SQL statement.
feedOptions
FeedOptionsThe options for processing the query result feed. For details, see FeedOptions
Returns
- IQueryable<dynamic>
An IQueryable{dynamic} that can evaluate the query with the provided SQL statement.
Examples
This example below queries for databases by id.
Database database = client.CreateDatabaseQuery("SELECT * FROM dbs d WHERE d.id = 'mydb'").AsEnumerable().FirstOrDefault();
Remarks
Refer to https://msdn.microsoft.com/en-us/library/azure/dn782250.aspx and http://azure.microsoft.com/documentation/articles/documentdb-sql-query/ for syntax and examples.
- See Also
CreateDocumentAsync(string, object, RequestOptions, bool, CancellationToken)
Creates a Document as an asychronous operation in the Azure Cosmos DB service.
public Task<ResourceResponse<Document>> CreateDocumentAsync(string documentsFeedOrDatabaseLink, object document, RequestOptions options = null, bool disableAutomaticIdGeneration = false, CancellationToken cancellationToken = default)
Parameters
documentsFeedOrDatabaseLink
stringThe link of the DocumentCollection to create the document in. E.g. dbs/db_rid/colls/coll_rid/
document
objectThe document object to create.
options
RequestOptions(Optional) Any request options you wish to set. E.g. Specifying a Trigger to execute when creating the document. RequestOptions
disableAutomaticIdGeneration
bool(Optional) Disables the automatic id generation, If this is True the system will throw an exception if the id property is missing from the Document.
cancellationToken
CancellationToken(Optional) A CancellationToken that can be used by other objects or threads to receive notice of cancellation.
Returns
- Task<ResourceResponse<Document>>
The Document that was created contained within a Task object representing the service response for the asynchronous operation.
Examples
Azure Cosmos DB supports a number of different ways to work with documents. A document can extend Resource
public class MyObject : Resource
{
public string MyProperty {get; set;}
}
using (IDocumentClient client = new DocumentClient(new Uri("service endpoint"), "auth key"))
{
Document doc = await client.CreateDocumentAsync("dbs/db_rid/colls/coll_rid/", new MyObject { MyProperty = "A Value" });
}</code></pre>
A document can be any POCO object that can be serialized to JSON, even if it doesn't extend from Resource
public class MyPOCO
{
public string MyProperty {get; set;}
}
using (IDocumentClient client = new DocumentClient(new Uri("service endpoint"), "auth key"))
{
Document doc = await client.CreateDocumentAsync("dbs/db_rid/colls/coll_rid/", new MyPOCO { MyProperty = "A Value" });
}</code></pre>
Finally, a Document can also be a dynamic object
using (IDocumentClient client = new DocumentClient(new Uri("service endpoint"), "auth key"))
{
Document doc = await client.CreateDocumentAsync("dbs/db_rid/colls/coll_rid/", new { SomeProperty = "A Value" } );
}
Create a Document and execute a Pre and Post Trigger
using (IDocumentClient client = new DocumentClient(new Uri("service endpoint"), "auth key"))
{
Document doc = await client.CreateDocumentAsync(
"dbs/db_rid/colls/coll_rid/",
new { id = "DOC123213443" },
new RequestOptions
{
PreTriggerInclude = new List<string> { "MyPreTrigger" },
PostTriggerInclude = new List<string> { "MyPostTrigger" }
});
}
Exceptions
- ArgumentNullException
If either
documentsFeedOrDatabaseLink
ordocument
is not set.- AggregateException
Represents a consolidation of failures that occured during async processing. Look within InnerExceptions to find the actual exception(s)
- DocumentClientException
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:
StatusCode Reason for exception 400 BadRequest - This means something was wrong with the document supplied. It is likely that disableAutomaticIdGeneration
was true and an id was not supplied403 Forbidden - This likely means the collection in to which you were trying to create the document is full. 409 Conflict - This means a Document with an id matching the id field of document
already existed413 RequestEntityTooLarge - This means the Document exceeds the current max entity size. Consult documentation for limits and quotas. 429 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.
- See Also
-
ResourceResponse<TResource>
CreateDocumentAsync(Uri, object, RequestOptions, bool, CancellationToken)
Creates a document as an asychronous operation in the Azure Cosmos DB service.
public Task<ResourceResponse<Document>> CreateDocumentAsync(Uri documentCollectionUri, object document, RequestOptions options = null, bool disableAutomaticIdGeneration = false, CancellationToken cancellationToken = default)
Parameters
documentCollectionUri
Urithe URI of the document collection to create the document in.
document
objectthe document object.
options
RequestOptionsThe request options for the request.
disableAutomaticIdGeneration
boolDisables the automatic id generation, will throw an exception if id is missing.
cancellationToken
CancellationToken(Optional) CancellationToken representing request cancellation.
Returns
- Task<ResourceResponse<Document>>
The task object representing the service response for the asynchronous operation.
CreateDocumentChangeFeedQuery(string, ChangeFeedOptions)
Overloaded. This method creates a change feed query for documents under a collection in an Azure Cosmos DB service.
public IDocumentQuery<Document> CreateDocumentChangeFeedQuery(string collectionLink, ChangeFeedOptions feedOptions)
Parameters
collectionLink
stringSpecifies the collection to read documents from.
feedOptions
ChangeFeedOptionsThe options for processing the query results feed.
Returns
- IDocumentQuery<Document>
the query result set.
Examples
string partitionKeyRangeId = "0"; // Use client.ReadPartitionKeyRangeFeedAsync() to obtain the ranges.
string checkpointContinuation = null;
ChangeFeedOptions options = new ChangeFeedOptions
{
PartitionKeyRangeId = partitionKeyRangeId,
RequestContinuation = checkpointContinuation,
StartFromBeginning = true,
};
using(var query = client.CreateDocumentChangeFeedQuery(collection.SelfLink, options))
{
while (true)
{
do
{
var response = await query.ExecuteNextAsync<Document>();
if (response.Count > 0)
{
var docs = new List<Document>();
docs.AddRange(response);
// Process the documents.
// Checkpoint response.ResponseContinuation.
}
}
while (query.HasMoreResults);
Task.Delay(TimeSpan.FromMilliseconds(500)); // Or break here and use checkpointed continuation token later.
}
}
Remarks
ChangeFeedOptions.PartitionKeyRangeId must be provided.
- See Also
CreateDocumentChangeFeedQuery(Uri, ChangeFeedOptions)
Extension method to create a change feed query for documents in the Azure Cosmos DB service.
public IDocumentQuery<Document> CreateDocumentChangeFeedQuery(Uri collectionLink, ChangeFeedOptions feedOptions)
Parameters
collectionLink
UriSpecifies the collection to read documents from.
feedOptions
ChangeFeedOptionsThe options for processing the query results feed.
Returns
- IDocumentQuery<Document>
the query result set.
CreateDocumentCollectionAsync(string, DocumentCollection, RequestOptions)
Creates a collection as an asychronous operation in the Azure Cosmos DB service.
public Task<ResourceResponse<DocumentCollection>> CreateDocumentCollectionAsync(string databaseLink, DocumentCollection documentCollection, RequestOptions options = null)
Parameters
databaseLink
stringThe link of the database to create the collection in. E.g. dbs/db_rid/.
documentCollection
DocumentCollectionThe DocumentCollection object.
options
RequestOptions(Optional) Any RequestOptions you wish to provide when creating a Collection. E.g. RequestOptions.OfferThroughput = 400.
Returns
- Task<ResourceResponse<DocumentCollection>>
The DocumentCollection that was created contained within a Task object representing the service response for the asynchronous operation.
Examples
using (IDocumentClient client = new DocumentClient(new Uri("service endpoint"), "auth key"))
{
//Create a new collection with an OfferThroughput set to 10000
//Not passing in RequestOptions.OfferThroughput will result in a collection with the default OfferThroughput set.
DocumentCollection coll = await client.CreateDocumentCollectionAsync(databaseLink,
new DocumentCollection { Id = "My Collection" },
new RequestOptions { OfferThroughput = 10000} );
}
Exceptions
- ArgumentNullException
If either
databaseLink
ordocumentCollection
is not set.- AggregateException
Represents a consolidation of failures that occured during async processing. Look within InnerExceptions to find the actual exception(s).
- DocumentClientException
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 collection are:
StatusCode Reason for exception 400 BadRequest - This means something was wrong with the request supplied. It is likely that an id was not supplied for the new collection. 403 Forbidden - This means you attempted to exceed your quota for collections. Contact support to have this quota increased. 409 Conflict - This means a DocumentCollection with an id matching the id you supplied already existed.
- See Also
-
ResourceResponse<TResource>
CreateDocumentCollectionAsync(Uri, DocumentCollection, RequestOptions)
Creates a collection as an asychronous operation in the Azure Cosmos DB service.
public Task<ResourceResponse<DocumentCollection>> CreateDocumentCollectionAsync(Uri databaseUri, DocumentCollection documentCollection, RequestOptions options = null)
Parameters
databaseUri
Urithe URI of the database to create the collection in.
documentCollection
DocumentCollectionthe Microsoft.Azure.Documents.DocumentCollection object.
options
RequestOptionsThe request options for the request.
Returns
- Task<ResourceResponse<DocumentCollection>>
The task object representing the service response for the asynchronous operation.
CreateDocumentCollectionIfNotExistsAsync(string, DocumentCollection, RequestOptions)
Creates (if doesn't exist) or gets (if already exists) a collection as an asychronous operation in the Azure Cosmos DB service. You can check the status code from the response to determine whether the collection was newly created (201) or existing collection was returned (200).
public Task<ResourceResponse<DocumentCollection>> CreateDocumentCollectionIfNotExistsAsync(string databaseLink, DocumentCollection documentCollection, RequestOptions options = null)
Parameters
databaseLink
stringThe link of the database to create the collection in. E.g. dbs/db_rid/.
documentCollection
DocumentCollectionThe DocumentCollection object.
options
RequestOptions(Optional) Any RequestOptions you wish to provide when creating a Collection. E.g. RequestOptions.OfferThroughput = 400.
Returns
- Task<ResourceResponse<DocumentCollection>>
The DocumentCollection that was created contained within a Task object representing the service response for the asynchronous operation.
Examples
using (IDocumentClient client = new DocumentClient(new Uri("service endpoint"), "auth key"))
{
//Create a new collection with an OfferThroughput set to 10000
//Not passing in RequestOptions.OfferThroughput will result in a collection with the default OfferThroughput set.
DocumentCollection coll = await client.CreateDocumentCollectionIfNotExistsAsync(databaseLink,
new DocumentCollection { Id = "My Collection" },
new RequestOptions { OfferThroughput = 10000} );
}
Exceptions
- ArgumentNullException
If either
databaseLink
ordocumentCollection
is not set.- AggregateException
Represents a consolidation of failures that occured during async processing. Look within InnerExceptions to find the actual exception(s).
- DocumentClientException
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 DocumentCollection are:
StatusCode Reason for exception 400 BadRequest - This means something was wrong with the request supplied. It is likely that an id was not supplied for the new collection. 403 Forbidden - This means you attempted to exceed your quota for collections. Contact support to have this quota increased.
- See Also
-
ResourceResponse<TResource>
CreateDocumentCollectionIfNotExistsAsync(Uri, DocumentCollection, RequestOptions)
Creates(if doesn't exist) or gets(if already exists) a collection as an asychronous operation in the Azure Cosmos DB service.
public Task<ResourceResponse<DocumentCollection>> CreateDocumentCollectionIfNotExistsAsync(Uri databaseUri, DocumentCollection documentCollection, RequestOptions options = null)
Parameters
databaseUri
Urithe URI of the database to create the collection in.
documentCollection
DocumentCollectionThe DocumentCollection object.
options
RequestOptions(Optional) Any RequestOptions you wish to provide when creating a Collection. E.g. RequestOptions.OfferThroughput = 400.
Returns
- Task<ResourceResponse<DocumentCollection>>
The DocumentCollection that was created contained within a Task object representing the service response for the asynchronous operation.
CreateDocumentCollectionQuery(string, FeedOptions)
Overloaded. This method creates a query for collections under an Azure Cosmos DB database. It returns An IOrderedQueryable{DocumentCollection}.
public IOrderedQueryable<DocumentCollection> CreateDocumentCollectionQuery(string databaseLink, FeedOptions feedOptions = null)
Parameters
databaseLink
stringThe link to the parent database resource.
feedOptions
FeedOptionsThe options for processing the query result feed. For details, see FeedOptions
Returns
- IOrderedQueryable<DocumentCollection>
An IOrderedQueryable{DocumentCollection} that can evaluate the query with the provided SQL statement.
Examples
This example below queries for collections by id.
DocumentCollection collection = client.CreateDocumentCollectionQuery(databaseLink).Where(c => c.Id == "myColl").AsEnumerable().FirstOrDefault();
- See Also
CreateDocumentCollectionQuery(string, SqlQuerySpec, FeedOptions)
Overloaded. This method creates a query for collections under an Azure Cosmos DB database using a SQL statement with parameterized values. It returns an IQueryable{dynamic}. For more information on preparing SQL statements with parameterized values, please see SqlQuerySpec.
public IQueryable<dynamic> CreateDocumentCollectionQuery(string databaseLink, SqlQuerySpec querySpec, FeedOptions feedOptions = null)
Parameters
databaseLink
stringThe link to the parent database resource.
querySpec
SqlQuerySpecThe SqlQuerySpec instance containing the SQL expression.
feedOptions
FeedOptionsThe options for processing the query result feed. For details, see FeedOptions
Returns
- IQueryable<dynamic>
An IQueryable{dynamic} that can evaluate the query with the provided SQL statement.
Examples
This example below queries for collections by id.
var query = new SqlQuerySpec("SELECT * FROM colls c WHERE c.id = @id", new SqlParameterCollection(new SqlParameter[] { new SqlParameter { Name = "@id", Value = "mycoll" }}));
DocumentCollection collection = client.CreateDocumentCollectionQuery(databaseLink, query).AsEnumerable().FirstOrDefault();
Remarks
Refer to https://msdn.microsoft.com/en-us/library/azure/dn782250.aspx and http://azure.microsoft.com/documentation/articles/documentdb-sql-query/ for syntax and examples.
- See Also
CreateDocumentCollectionQuery(string, string, FeedOptions)
Overloaded. This method creates a query for collections under an Azure Cosmos DB database using a SQL statement. It returns an IQueryable{DocumentCollection}.
public IQueryable<dynamic> CreateDocumentCollectionQuery(string databaseLink, string sqlExpression, FeedOptions feedOptions = null)
Parameters
databaseLink
stringThe link to the parent database resource.
sqlExpression
stringThe SQL statement.
feedOptions
FeedOptionsThe options for processing the query result feed. For details, see FeedOptions
Returns
- IQueryable<dynamic>
An IQueryable{dynamic} that can evaluate the query with the provided SQL statement.
Examples
This example below queries for collections by id.
DocumentCollection collection = client.CreateDocumentCollectionQuery(databaseLink, "SELECT * FROM colls c WHERE c.id = 'mycoll'").AsEnumerable().FirstOrDefault();
Remarks
Refer to https://msdn.microsoft.com/en-us/library/azure/dn782250.aspx and http://azure.microsoft.com/documentation/articles/documentdb-sql-query/ for syntax and examples.
- See Also
CreateDocumentCollectionQuery(Uri, FeedOptions)
Extension method to create a query for document collections in the Azure Cosmos DB service.
public IOrderedQueryable<DocumentCollection> CreateDocumentCollectionQuery(Uri databaseUri, FeedOptions feedOptions = null)
Parameters
databaseUri
Urithe URI to the database.
feedOptions
FeedOptionsThe options for processing the query results feed.
Returns
- IOrderedQueryable<DocumentCollection>
The query result set.
CreateDocumentCollectionQuery(Uri, SqlQuerySpec, FeedOptions)
Extension method to create a query for document collections in the Azure Cosmos DB service.
public IQueryable<dynamic> CreateDocumentCollectionQuery(Uri databaseUri, SqlQuerySpec querySpec, FeedOptions feedOptions = null)
Parameters
databaseUri
Urithe URI to the database.
querySpec
SqlQuerySpecThe sql query.
feedOptions
FeedOptionsThe options for processing the query results feed.
Returns
- IQueryable<dynamic>
The query result set.
CreateDocumentCollectionQuery(Uri, string, FeedOptions)
Extension method to create a query for document collections in the Azure Cosmos DB service.
public IQueryable<dynamic> CreateDocumentCollectionQuery(Uri databaseUri, string sqlExpression, FeedOptions feedOptions = null)
Parameters
databaseUri
Urithe URI to the database.
sqlExpression
stringThe sql query.
feedOptions
FeedOptionsThe options for processing the query results feed.
Returns
- IQueryable<dynamic>
The query result set.
CreateDocumentQuery(string, FeedOptions)
Overloaded. This method creates a query for documents under a collection in an Azure Cosmos DB service. It returns IOrderedQueryable{Document}.
public IOrderedQueryable<Document> CreateDocumentQuery(string collectionLink, FeedOptions feedOptions = null)
Parameters
collectionLink
stringThe link to the parent document collection.
feedOptions
FeedOptionsThe options for processing the query result feed. For details, see FeedOptions
Returns
- IOrderedQueryable<Document>
An IOrderedQueryable{Document} that can evaluate the query.
Examples
This example below queries for documents by id.
Document document = client.CreateDocumentQuery<Document>(collectionLink)
.Where(d => d.Id == "War and Peace").AsEnumerable().FirstOrDefault();
Remarks
This overload should be used when the schema of the queried documents is unknown or when querying by ID and replacing/deleting documents. Since Document is a DynamicObject, it can be dynamically cast back to the original C# object.
- See Also
CreateDocumentQuery(string, FeedOptions, object)
Overloaded. This method creates a query for documents under a collection in an Azure Cosmos DB service. It returns IOrderedQueryable{Document}.
[Obsolete("Support for IPartitionResolver based method overloads is now obsolete. It's recommended that you use partitioned collections for higher storage and throughput. Please use the override that does not take a partitionKey parameter.")]
public IOrderedQueryable<Document> CreateDocumentQuery(string collectionLink, FeedOptions feedOptions, object partitionKey)
Parameters
collectionLink
stringThe link to the parent document collection. Alternatively, this can be a path link to the database when using an IPartitionResolver.
feedOptions
FeedOptionsThe options for processing the query result feed. For details, see FeedOptions
partitionKey
objectOptional partition key that can be used with an IPartitionResolver.
Returns
- IOrderedQueryable<Document>
An IOrderedQueryable{Document} that can evaluate the query.
Remarks
Support for IPartitionResolver based method overloads is now obsolete. It's recommended that you use Partitioned Collections for higher storage and throughput.
CreateDocumentQuery(string, SqlQuerySpec, FeedOptions)
Overloaded. This method creates a query for documents under a collection in an Azure Cosmos DB database using a SQL statement with parameterized values. It returns an IQueryable{dynamic}. For more information on preparing SQL statements with parameterized values, please see SqlQuerySpec.
public IQueryable<dynamic> CreateDocumentQuery(string collectionLink, SqlQuerySpec querySpec, FeedOptions feedOptions = null)
Parameters
collectionLink
stringThe link to the parent document collection.
querySpec
SqlQuerySpecThe SqlQuerySpec instance containing the SQL expression.
feedOptions
FeedOptionsThe options for processing the query result feed. For details, see FeedOptions
Returns
- IQueryable<dynamic>
an IQueryable{dynamic> that can evaluate the query.
Examples
This example below queries for book documents.
// SQL querying allows dynamic property access
var query = new SqlQuerySpec(
"SELECT * FROM books b WHERE b.title = @title",
new SqlParameterCollection(new SqlParameter[] { new SqlParameter { Name = "@title", Value = "War and Peace" }}));
dynamic document = client.CreateDocumentQuery<dynamic>(collectionLink, query).AsEnumerable().FirstOrDefault();
Remarks
Refer to https://msdn.microsoft.com/en-us/library/azure/dn782250.aspx and http://azure.microsoft.com/documentation/articles/documentdb-sql-query/ for syntax and examples.
- See Also
CreateDocumentQuery(string, SqlQuerySpec, FeedOptions, object)
Overloaded. This method creates a query for documents under a collection in an Azure Cosmos DB database using a SQL statement with parameterized values. It returns an IQueryable{dynamic}. For more information on preparing SQL statements with parameterized values, please see SqlQuerySpec.
[Obsolete("Support for IPartitionResolver based method overloads is now obsolete. It's recommended that you use partitioned collections for higher storage and throughput. Please use the override that does not take a partitionKey parameter.")]
public IQueryable<dynamic> CreateDocumentQuery(string collectionLink, SqlQuerySpec querySpec, FeedOptions feedOptions, object partitionKey)
Parameters
collectionLink
stringThe link to the parent document collection. Alternatively, this can be a path link to the database when using an IPartitionResolver, e.g. dbs/db_rid/
querySpec
SqlQuerySpecThe SqlQuerySpec instance containing the SQL expression.
feedOptions
FeedOptionsThe options for processing the query result feed. For details, see FeedOptions
partitionKey
objectThe partition key that can be used with an IPartitionResolver.
Returns
- IQueryable<dynamic>
an IQueryable{dynamic> that can evaluate the query.
Remarks
Support for IPartitionResolver based method overloads is now obsolete. It's recommended that you use Partitioned Collections for higher storage and throughput.
CreateDocumentQuery(string, string, FeedOptions)
Overloaded. This method creates a query for documents under a collection in an Azure Cosmos DB database using a SQL statement. It returns an IQueryable{dynamic}.
public IQueryable<dynamic> CreateDocumentQuery(string collectionLink, string sqlExpression, FeedOptions feedOptions = null)
Parameters
collectionLink
stringThe link to the parent document collection.
sqlExpression
stringThe SQL statement.
feedOptions
FeedOptionsThe options for processing the query result feed. For details, see FeedOptions
Returns
- IQueryable<dynamic>
an IQueryable{dynamic> that can evaluate the query.
Examples
This example below queries for book documents.
// SQL querying allows dynamic property access
dynamic document = client.CreateDocumentQuery<dynamic>(collectionLink,
"SELECT * FROM books b WHERE b.title == 'War and Peace'").AsEnumerable().FirstOrDefault();
Remarks
Refer to https://msdn.microsoft.com/en-us/library/azure/dn782250.aspx and http://azure.microsoft.com/documentation/articles/documentdb-sql-query/ for syntax and examples.
- See Also
CreateDocumentQuery(string, string, FeedOptions, object)
Overloaded. This method creates a query for documents under a collection in an Azure Cosmos DB database using a SQL statement. It returns an IQueryable{dynamic}.
[Obsolete("Support for IPartitionResolver based method overloads is now obsolete. It's recommended that you use partitioned collections for higher storage and throughput. Please use the override that does not take a partitionKey parameter.")]
public IQueryable<dynamic> CreateDocumentQuery(string collectionLink, string sqlExpression, FeedOptions feedOptions, object partitionKey)
Parameters
collectionLink
stringThe link of the parent document collection. Alternatively, this can be a path link to the database when using an IPartitionResolver, e.g. dbs/db_rid/
sqlExpression
stringThe SQL statement.
feedOptions
FeedOptionsThe options for processing the query result feed. For details, see FeedOptions
partitionKey
objectThe partition key that can be used with an IPartitionResolver.
Returns
- IQueryable<dynamic>
an IQueryable{dynamic> that can evaluate the query.
Remarks
Support for IPartitionResolver based method overloads is now obsolete. It's recommended that you use Partitioned Collections for higher storage and throughput.
CreateDocumentQuery(Uri, FeedOptions)
Extension method to create a query for documents in the Azure Cosmos DB service.
public IOrderedQueryable<Document> CreateDocumentQuery(Uri documentCollectionOrDatabaseUri, FeedOptions feedOptions = null)
Parameters
documentCollectionOrDatabaseUri
UriThe URI of the document collection.
feedOptions
FeedOptionsThe options for processing the query results feed.
Returns
- IOrderedQueryable<Document>
The query result set.
CreateDocumentQuery(Uri, FeedOptions, object)
Extension method to create a query for documents in the Azure Cosmos DB service.
[Obsolete("Support for IPartitionResolver based method overloads is now obsolete. It's recommended that you use partitioned collections for higher storage and throughput. Please use the override that does not take a partitionKey parameter.")]
public IOrderedQueryable<Document> CreateDocumentQuery(Uri documentCollectionOrDatabaseUri, FeedOptions feedOptions, object partitionKey)
Parameters
documentCollectionOrDatabaseUri
UriThe URI of the document collection, e.g. dbs/db_rid/colls/coll_rid/. Alternatively, this can be a URI of the database when using an IPartitionResolver, e.g. dbs/db_rid/
feedOptions
FeedOptionsThe options for processing the query results feed.
partitionKey
objectThe partition key that can be used with an IPartitionResolver.
Returns
- IOrderedQueryable<Document>
The query result set.
Remarks
Support for IPartitionResolver based method overloads is now obsolete. It's recommended that you use Partitioned Collections for higher storage and throughput.
CreateDocumentQuery(Uri, SqlQuerySpec, FeedOptions)
Extension method to create a query for documents in the Azure Cosmos DB service.
public IQueryable<dynamic> CreateDocumentQuery(Uri documentCollectionOrDatabaseUri, SqlQuerySpec querySpec, FeedOptions feedOptions = null)
Parameters
documentCollectionOrDatabaseUri
UriThe URI of the document collection.
querySpec
SqlQuerySpecThe sql query.
feedOptions
FeedOptionsThe options for processing the query results feed.
Returns
- IQueryable<dynamic>
The query result set.
CreateDocumentQuery(Uri, SqlQuerySpec, FeedOptions, object)
Extension method to create a query for documents in the Azure Cosmos DB service.
[Obsolete("Support for IPartitionResolver based method overloads is now obsolete. It's recommended that you use partitioned collections for higher storage and throughput. Please use the override that does not take a partitionKey parameter.")]
public IQueryable<dynamic> CreateDocumentQuery(Uri documentCollectionOrDatabaseUri, SqlQuerySpec querySpec, FeedOptions feedOptions, object partitionKey)
Parameters
documentCollectionOrDatabaseUri
UriThe URI of the document collection, e.g. dbs/db_rid/colls/coll_rid/. Alternatively, this can be a URI of the database when using an IPartitionResolver, e.g. dbs/db_rid/
querySpec
SqlQuerySpecThe sql query.
feedOptions
FeedOptionsThe options for processing the query results feed.
partitionKey
objectThe partition key that can be used with an IPartitionResolver.
Returns
- IQueryable<dynamic>
The query result set.
Remarks
Support for IPartitionResolver based method overloads is now obsolete. It's recommended that you use Partitioned Collections for higher storage and throughput.
CreateDocumentQuery(Uri, string, FeedOptions)
Extension method to create a query for documents in the Azure Cosmos DB service.
public IQueryable<dynamic> CreateDocumentQuery(Uri documentCollectionOrDatabaseUri, string sqlExpression, FeedOptions feedOptions = null)
Parameters
documentCollectionOrDatabaseUri
UriThe URI of the document collection.
sqlExpression
stringThe sql query.
feedOptions
FeedOptionsThe options for processing the query results feed.
Returns
- IQueryable<dynamic>
The query result set.
CreateDocumentQuery(Uri, string, FeedOptions, object)
Extension method to create a query for documents in the Azure Cosmos DB service.
[Obsolete("Support for IPartitionResolver based method overloads is now obsolete. It's recommended that you use partitioned collections for higher storage and throughput. Please use the override that does not take a partitionKey parameter.")]
public IQueryable<dynamic> CreateDocumentQuery(Uri documentCollectionOrDatabaseUri, string sqlExpression, FeedOptions feedOptions, object partitionKey)
Parameters
documentCollectionOrDatabaseUri
UriThe URI of the document collection, e.g. dbs/db_rid/colls/coll_rid/. Alternatively, this can be a URI of the database when using an IPartitionResolver, e.g. dbs/db_rid/
sqlExpression
stringThe sql query.
feedOptions
FeedOptionsThe options for processing the query results feed.
partitionKey
objectThe partition key that can be used with an IPartitionResolver.
Returns
- IQueryable<dynamic>
The query result set.
Remarks
Support for IPartitionResolver based method overloads is now obsolete. It's recommended that you use Partitioned Collections for higher storage and throughput.
CreateDocumentQuery<T>(string, FeedOptions)
Overloaded. This method creates a query for documents under a collection in an Azure Cosmos DB service.
public IOrderedQueryable<T> CreateDocumentQuery<T>(string collectionLink, FeedOptions feedOptions = null)
Parameters
collectionLink
stringThe link to the parent collection resource.
feedOptions
FeedOptionsThe options for processing the query result feed. For details, see FeedOptions
Returns
- IOrderedQueryable<T>
An IOrderedQueryable{T} that can evaluate the query.
Type Parameters
T
The type of object to query.
Examples
This example below queries for some book documents.
public class Book
{
[JsonProperty("title")]
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 = client.CreateDocumentQuery<Book>(collectionLink).Where(b => b.Title == "War and Peace").AsEnumerable().FirstOrDefault();
// Query a nested property
Book otherBook = client.CreateDocumentQuery<Book>(collectionLink).Where(b => b.Author.FirstName == "Leo").AsEnumerable().FirstOrDefault();
// Perform a range query (needs an IndexType.Range on price or FeedOptions.EnableScansInQuery)
foreach (Book matchingBook in client.CreateDocumentQuery<Book>(collectionLink).Where(b => b.Price > 100))
{
// Iterate through books
}
// Query asychronously. Optionally set FeedOptions.MaxItemCount to control page size
using (var queryable = client.CreateDocumentQuery<Book>(
collectionLink,
new FeedOptions { MaxItemCount = 10 })
.Where(b => b.Title == "War and Peace")
.AsDocumentQuery())
{
while (queryable.HasMoreResults)
{
foreach(Book b in await queryable.ExecuteNextAsync<Book>())
{
// Iterate through books
}
}
}
Remarks
The Azure Cosmos DB LINQ provider compiles LINQ to SQL statements. Refer to http://azure.microsoft.com/documentation/articles/documentdb-sql-query/#linq-to-documentdb-sql for the list of expressions supported by the Azure Cosmos DB LINQ provider. ToString() on the generated IQueryable returns the translated SQL statement. The Azure Cosmos DB provider translates JSON.NET and DataContract serialization attributes for members to their JSON property names.
- See Also
CreateDocumentQuery<T>(string, FeedOptions, object)
Overloaded. This method creates a query for documents under a collection in an Azure Cosmos DB service.
[Obsolete("Support for IPartitionResolver based method overloads is now obsolete. It's recommended that you use partitioned collections for higher storage and throughput. Please use the override that does not take a partitionKey parameter.")]
public IOrderedQueryable<T> CreateDocumentQuery<T>(string documentsFeedOrDatabaseLink, FeedOptions feedOptions, object partitionKey)
Parameters
documentsFeedOrDatabaseLink
stringThe path link for the documents under a collection, e.g. dbs/db_rid/colls/coll_rid/docs/. Alternatively, this can be a path link to the database when using an IPartitionResolver, e.g. dbs/db_rid/
feedOptions
FeedOptionsThe options for processing the query result feed. For details, see FeedOptions
partitionKey
objectThe partition key that can be used with an IPartitionResolver.
Returns
- IOrderedQueryable<T>
An IOrderedQueryable{T} that can evaluate the query.
Type Parameters
T
The type of object to query.
Remarks
Support for IPartitionResolver based method overloads is now obsolete. It's recommended that you use Partitioned Collections for higher storage and throughput.
CreateDocumentQuery<T>(string, SqlQuerySpec, FeedOptions)
Overloaded. This method creates a query for documents under a collection in an Azure Cosmos DB database using a SQL statement with parameterized values. It returns an IQueryable{T}. For more information on preparing SQL statements with parameterized values, please see SqlQuerySpec.
public IQueryable<T> CreateDocumentQuery<T>(string collectionLink, SqlQuerySpec querySpec, FeedOptions feedOptions = null)
Parameters
collectionLink
stringThe link to the parent document collection.
querySpec
SqlQuerySpecThe SqlQuerySpec instance containing the SQL expression.
feedOptions
FeedOptionsThe options for processing the query result feed. For details, see FeedOptions
Returns
- IQueryable<T>
An IQueryable{T} that can evaluate the query.
Type Parameters
T
The type of object to query.
Examples
This example below queries for some book documents.
public class Book
{
[JsonProperty("title")]
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 using Title
Book book, otherBook;
var query = new SqlQuerySpec(
"SELECT * FROM books b WHERE b.title = @title",
new SqlParameterCollection(new SqlParameter[] { new SqlParameter { Name = "@title", Value = "War and Peace" }}));
book = client.CreateDocumentQuery<Book>(collectionLink, query).AsEnumerable().FirstOrDefault();
// Query a nested property
query = new SqlQuerySpec(
"SELECT * FROM books b WHERE b.Author.FirstName = @firstName",
new SqlParameterCollection(new SqlParameter[] { new SqlParameter { Name = "@firstName", Value = "Leo" }}));
otherBook = client.CreateDocumentQuery<Book>(collectionLink, query).AsEnumerable().FirstOrDefault();
// Perform a range query (needs an IndexType.Range on price or FeedOptions.EnableScansInQuery)
query = new SqlQuerySpec(
"SELECT * FROM books b WHERE b.Price > @minPrice",
new SqlParameterCollection(new SqlParameter[] { new SqlParameter { Name = "@minPrice", Value = 1000 }}));
foreach (Book b in client.CreateDocumentQuery<Book>(
collectionLink, query))
{
// Iterate through books
}
// Query asychronously. Optionally set FeedOptions.MaxItemCount to control page size
query = new SqlQuerySpec(
"SELECT * FROM books b WHERE b.title = @title",
new SqlParameterCollection(new SqlParameter[] { new SqlParameter { Name = "@title", Value = "War and Peace" }}));
using (var queryable = client.CreateDocumentQuery<Book>(collectionLink, query,
new FeedOptions { MaxItemCount = 10 }).AsDocumentQuery())
{
while (queryable.HasMoreResults)
{
foreach(Book b in await queryable.ExecuteNextAsync<Book>())
{
// Iterate through books
}
}
}
Remarks
Refer to https://msdn.microsoft.com/en-us/library/azure/dn782250.aspx and http://azure.microsoft.com/documentation/articles/documentdb-sql-query/ for syntax and examples.
- See Also
CreateDocumentQuery<T>(string, SqlQuerySpec, FeedOptions, object)
Overloaded. This method creates a query for documents under a collection in an Azure Cosmos DB database using a SQL statement with parameterized values. It returns an IQueryable{T}. For more information on preparing SQL statements with parameterized values, please see SqlQuerySpec.
[Obsolete("Support for IPartitionResolver based method overloads is now obsolete. It's recommended that you use partitioned collections for higher storage and throughput. Please use the override that does not take a partitionKey parameter.")]
public IQueryable<T> CreateDocumentQuery<T>(string collectionLink, SqlQuerySpec querySpec, FeedOptions feedOptions, object partitionKey)
Parameters
collectionLink
stringThe link to the parent document collection. Alternatively, this can be a path link to the database when using an IPartitionResolver.
querySpec
SqlQuerySpecThe SqlQuerySpec instance containing the SQL expression.
feedOptions
FeedOptionsThe options for processing the query result feed. For details, see FeedOptions
partitionKey
objectThe partition key that can be used with an IPartitionResolver.
Returns
- IQueryable<T>
An IQueryable{T} that can evaluate the query.
Type Parameters
T
The type of object to query.
Remarks
Support for IPartitionResolver based method overloads is now obsolete. It's recommended that you use Partitioned Collections for higher storage and throughput.
CreateDocumentQuery<T>(string, string, FeedOptions)
Overloaded. This method creates a query for documents under a collection in an Azure Cosmos DB database using a SQL statement. It returns an IQueryable{T}.
public IQueryable<T> CreateDocumentQuery<T>(string collectionLink, string sqlExpression, FeedOptions feedOptions = null)
Parameters
collectionLink
stringThe link to the parent collection.
sqlExpression
stringThe SQL statement.
feedOptions
FeedOptionsThe options for processing the query result feed. For details, see FeedOptions
Returns
- IQueryable<T>
An IQueryable{T} that can evaluate the query.
Type Parameters
T
The type of object to query.
Examples
This example below queries for some book documents.
public class Book
{
[JsonProperty("title")]
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 = client.CreateDocumentQuery<Book>(collectionLink,
"SELECT * FROM books b WHERE b.title = 'War and Peace'").AsEnumerable().FirstOrDefault();
// Query a nested property
Book otherBook = client.CreateDocumentQuery<Book>(collectionLink,
"SELECT * FROM books b WHERE b.Author.FirstName = 'Leo'").AsEnumerable().FirstOrDefault();
// Perform a range query (needs an IndexType.Range on price or FeedOptions.EnableScansInQuery)
foreach (Book matchingBook in client.CreateDocumentQuery<Book>(
collectionLink, "SELECT * FROM books b where b.Price > 1000"))
{
// Iterate through books
}
// Query asychronously. Optionally set FeedOptions.MaxItemCount to control page size
using (var queryable = client.CreateDocumentQuery<Book>(collectionLink,
"SELECT * FROM books b WHERE b.title = 'War and Peace'",
new FeedOptions { MaxItemCount = 10 }).AsDocumentQuery())
{
while (queryable.HasMoreResults)
{
foreach(Book b in await queryable.ExecuteNextAsync<Book>())
{
// Iterate through books
}
}
}
Remarks
Refer to https://msdn.microsoft.com/en-us/library/azure/dn782250.aspx and http://azure.microsoft.com/documentation/articles/documentdb-sql-query/ for syntax and examples.
- See Also
CreateDocumentQuery<T>(string, string, FeedOptions, object)
Overloaded. This method creates a query for documents under a collection in an Azure Cosmos DB database using a SQL statement. It returns an IQueryable{T}.
[Obsolete("Support for IPartitionResolver based method overloads is now obsolete. It's recommended that you use partitioned collections for higher storage and throughput. Please use the override that does not take a partitionKey parameter.")]
public IQueryable<T> CreateDocumentQuery<T>(string collectionLink, string sqlExpression, FeedOptions feedOptions, object partitionKey)
Parameters
collectionLink
stringThe path link for the documents under a collection, e.g. dbs/db_rid/colls/coll_rid/docs/. Alternatively, this can be a path link to the database when using an IPartitionResolver, e.g. dbs/db_rid/
sqlExpression
stringThe SQL statement.
feedOptions
FeedOptionsThe options for processing the query result feed. For details, see FeedOptions
partitionKey
objectThe partition key that can be used with an IPartitionResolver.
Returns
- IQueryable<T>
An IQueryable{T} that can evaluate the query.
Type Parameters
T
The type of object to query.
Remarks
Support for IPartitionResolver based method overloads is now obsolete. It's recommended that you use Partitioned Collections for higher storage and throughput.
CreateDocumentQuery<T>(Uri, FeedOptions)
Extension method to create a query for documents in the Azure Cosmos DB service.
public IOrderedQueryable<T> CreateDocumentQuery<T>(Uri documentCollectionUri, FeedOptions feedOptions = null)
Parameters
documentCollectionUri
UriThe URI of the document collection.
feedOptions
FeedOptionsThe options for processing the query results feed.
Returns
- IOrderedQueryable<T>
The query result set.
Type Parameters
T
the type of object to query.
CreateDocumentQuery<T>(Uri, FeedOptions, object)
Extension method to create a query for documents in the Azure Cosmos DB service.
[Obsolete("Support for IPartitionResolver based method overloads is now obsolete. Please use the override that does not take a partitionKey parameter.")]
public IOrderedQueryable<T> CreateDocumentQuery<T>(Uri documentCollectionOrDatabaseUri, FeedOptions feedOptions, object partitionKey)
Parameters
documentCollectionOrDatabaseUri
UriThe URI of the document collection, e.g. dbs/db_rid/colls/coll_rid/. Alternatively, this can be a URI of the database when using an IPartitionResolver, e.g. dbs/db_rid/
feedOptions
FeedOptionsThe options for processing the query results feed.
partitionKey
objectThe partition key that can be used with an IPartitionResolver.
Returns
- IOrderedQueryable<T>
The query result set.
Type Parameters
T
the type of object to query.
Remarks
Support for IPartitionResolver based method overloads is now obsolete. It's recommended that you use Partitioned Collections for higher storage and throughput.
CreateDocumentQuery<T>(Uri, SqlQuerySpec, FeedOptions)
Extension method to create a query for documents in the Azure Cosmos DB service.
public IQueryable<T> CreateDocumentQuery<T>(Uri documentCollectionOrDatabaseUri, SqlQuerySpec querySpec, FeedOptions feedOptions = null)
Parameters
documentCollectionOrDatabaseUri
UriThe URI of the document collection.
querySpec
SqlQuerySpecThe sql query.
feedOptions
FeedOptionsThe options for processing the query results feed.
Returns
- IQueryable<T>
The query result set.
Type Parameters
T
The type of object to query.
CreateDocumentQuery<T>(Uri, SqlQuerySpec, FeedOptions, object)
Extension method to create a query for documents for the Azure Cosmos DB service.
[Obsolete("Support for IPartitionResolver based method overloads is now obsolete. It's recommended that you use partitioned collections for higher storage and throughput. Please use the override that does not take a partitionKey parameter.")]
public IQueryable<T> CreateDocumentQuery<T>(Uri documentCollectionOrDatabaseUri, SqlQuerySpec querySpec, FeedOptions feedOptions, object partitionKey)
Parameters
documentCollectionOrDatabaseUri
UriThe URI of the document collection, e.g. dbs/db_rid/colls/coll_rid/. Alternatively, this can be a URI of the database when using an IPartitionResolver, e.g. dbs/db_rid/
querySpec
SqlQuerySpecThe sql query.
feedOptions
FeedOptionsThe options for processing the query results feed.
partitionKey
objectThe partition key that can be used with an IPartitionResolver.
Returns
- IQueryable<T>
The query result set.
Type Parameters
T
The type of object to query.
Remarks
Support for IPartitionResolver based method overloads is now obsolete. It's recommended that you use Partitioned Collections for higher storage and throughput.
CreateDocumentQuery<T>(Uri, string, FeedOptions)
Extension method to create a query for documents in the Azure Cosmos DB service.
public IQueryable<T> CreateDocumentQuery<T>(Uri documentCollectionOrDatabaseUri, string sqlExpression, FeedOptions feedOptions = null)
Parameters
documentCollectionOrDatabaseUri
UriThe URI of the document collection.
sqlExpression
stringThe sql query.
feedOptions
FeedOptionsThe options for processing the query results feed.
Returns
- IQueryable<T>
The query result set.
Type Parameters
T
the type of object to query.
CreateDocumentQuery<T>(Uri, string, FeedOptions, object)
Extension method to create a query for documents in the Azure Cosmos DB service.
[Obsolete("Support for IPartitionResolver based method overloads is now obsolete. It's recommended that you use partitioned collections for higher storage and throughput. Please use the override that does not take a partitionKey parameter.")]
public IQueryable<T> CreateDocumentQuery<T>(Uri documentCollectionOrDatabaseUri, string sqlExpression, FeedOptions feedOptions, object partitionKey)
Parameters
documentCollectionOrDatabaseUri
UriThe URI of the document collection, e.g. dbs/db_rid/colls/coll_rid/. Alternatively, this can be a URI of the database when using an IPartitionResolver, e.g. dbs/db_rid/
sqlExpression
stringThe sql query.
feedOptions
FeedOptionsThe options for processing the query results feed.
partitionKey
objectThe partition key that can be used with an IPartitionResolver.
Returns
- IQueryable<T>
The query result set.
Type Parameters
T
The type of object to query.
Remarks
Support for IPartitionResolver based method overloads is now obsolete. It's recommended that you use Partitioned Collections for higher storage and throughput.
CreateOfferQuery(FeedOptions)
Overloaded. This method creates a query for offers under an Azure Cosmos DB database account. It returns IOrderedQueryable{Offer}.
public IOrderedQueryable<Offer> CreateOfferQuery(FeedOptions feedOptions = null)
Parameters
feedOptions
FeedOptionsThe options for processing the query result feed. For details, see FeedOptions
Returns
- IOrderedQueryable<Offer>
An IOrderedQueryable{Offer} that can evaluate the query.
Examples
This example below queries for offers
// Find the offer for the collection by SelfLink
Offer offer = client.CreateOfferQuery().Where(o => o.Resource == collectionSelfLink).AsEnumerable().FirstOrDefault();
Remarks
Refer to https://msdn.microsoft.com/en-us/library/azure/dn782250.aspx and http://azure.microsoft.com/documentation/articles/documentdb-sql-query/ for syntax and examples.
- See Also
CreateOfferQuery(SqlQuerySpec, FeedOptions)
Overloaded. This method creates a query for offers under an Azure Cosmos DB database account using a SQL statement with parameterized values. It returns IQueryable{dynamic}. For more information on preparing SQL statements with parameterized values, please see SqlQuerySpec.
public IQueryable<dynamic> CreateOfferQuery(SqlQuerySpec querySpec, FeedOptions feedOptions = null)
Parameters
querySpec
SqlQuerySpecThe SqlQuerySpec instance containing the SQL expression.
feedOptions
FeedOptionsThe options for processing the query result feed. For details, see FeedOptions
Returns
- IQueryable<dynamic>
an IQueryable{dynamic} that can evaluate the query.
Examples
This example below queries for offers
// Find the offer for the collection by SelfLink
Offer offer = client.CreateOfferQuery("SELECT * FROM offers o WHERE o.resource = @collectionSelfLink",
new SqlParameterCollection(new SqlParameter[] { new SqlParameter { Name = "@collectionSelfLink", Value = collection.SelfLink }}))
.AsEnumerable().FirstOrDefault();
Remarks
Refer to https://msdn.microsoft.com/en-us/library/azure/dn782250.aspx and http://azure.microsoft.com/documentation/articles/documentdb-sql-query/ for syntax and examples.
- See Also
CreateOfferQuery(string, FeedOptions)
Overloaded. This method creates a query for offers under an Azure Cosmos DB database account using a SQL statement. It returns IQueryable{dynamic}.
public IQueryable<dynamic> CreateOfferQuery(string sqlExpression, FeedOptions feedOptions = null)
Parameters
sqlExpression
stringThe SQL statement.
feedOptions
FeedOptionsThe options for processing the query result feed. For details, see FeedOptions
Returns
- IQueryable<dynamic>
an IQueryable{dynamic} that can evaluate the query.
Examples
This example below queries for offers
// Find the offer for the collection by SelfLink
Offer offer = client.CreateOfferQuery(
string.Format("SELECT * FROM offers o WHERE o.resource = '{0}'", collectionSelfLink)).AsEnumerable().FirstOrDefault();
Remarks
Refer to https://msdn.microsoft.com/en-us/library/azure/dn782250.aspx and http://azure.microsoft.com/documentation/articles/documentdb-sql-query/ for syntax and examples.
- See Also
CreatePermissionAsync(string, Permission, RequestOptions)
Creates a permission on a user object as an asychronous operation in the Azure Cosmos DB service.
public Task<ResourceResponse<Permission>> CreatePermissionAsync(string userLink, Permission permission, RequestOptions options = null)
Parameters
userLink
stringThe link of the user to create the permission for. E.g. dbs/db_rid/users/user_rid/
permission
PermissionThe Permission object.
options
RequestOptions(Optional) The request options for the request.
Returns
- Task<ResourceResponse<Permission>>
A task object representing the service response for the asynchronous operation which contains the created Permission object.
Examples
//Create a read-only permission object for a specific user
Permission p = await client.CreatePermissionAsync(userLink, new Permission { Id = "ReadPermission", PermissionMode = PermissionMode.Read });
Exceptions
- ArgumentNullException
If either
userLink
orpermission
is not set.- AggregateException
Represents a consolidation of failures that occured during async processing. Look within InnerExceptions to find the actual exception(s)
- DocumentClientException
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:
StatusCode Reason for exception 400 BadRequest - This means something was wrong with the request supplied. 403 Forbidden - You have reached your quota of permission objects. Contact support to have this quota increased. 409 Conflict - This means a Permission with an id matching the id you supplied already existed.
- See Also
-
ResourceResponse<TResource>
CreatePermissionAsync(Uri, Permission, RequestOptions)
Creates a permission as an asychronous operation in the Azure Cosmos DB service.
public Task<ResourceResponse<Permission>> CreatePermissionAsync(Uri userUri, Permission permission, RequestOptions options = null)
Parameters
userUri
Urithe URI of the user to create the permission for.
permission
Permissionthe Microsoft.Azure.Documents.Permission object.
options
RequestOptionsThe request options for the request.
Returns
- Task<ResourceResponse<Permission>>
The task object representing the service response for the asynchronous operation.
CreatePermissionQuery(string, FeedOptions)
Overloaded. This method creates a query for permissions under a user in an Azure Cosmos DB service. It returns IOrderedQueryable{Permission}.
public IOrderedQueryable<Permission> CreatePermissionQuery(string permissionsLink, FeedOptions feedOptions = null)
Parameters
permissionsLink
stringThe path link for the persmissions under a user, e.g. dbs/db_rid/users/user_rid/permissions/.
feedOptions
FeedOptionsThe options for processing the query result feed. For details, see FeedOptions
Returns
- IOrderedQueryable<Permission>
An IOrderedQueryable{Permission} that can evaluate the query.
Examples
This example below queries for permissions by id.
Permission perm = client.CreatePermissionQuery(userLink).Where(p => p.id == "readonly").AsEnumerable().FirstOrDefault();
- See Also
CreatePermissionQuery(string, SqlQuerySpec, FeedOptions)
Overloaded. This method creates a query for permissions under a user in an Azure Cosmos DB database using a SQL statement with parameterized values. It returns an IQueryable{dynamic}. For more information on preparing SQL statements with parameterized values, please see SqlQuerySpec.
public IQueryable<dynamic> CreatePermissionQuery(string permissionsLink, SqlQuerySpec querySpec, FeedOptions feedOptions = null)
Parameters
permissionsLink
stringThe path link for the persmissions under a user, e.g. dbs/db_rid/users/user_rid/permissions/.
querySpec
SqlQuerySpecThe SqlQuerySpec instance containing the SQL expression.
feedOptions
FeedOptionsThe options for processing the query result feed. For details, see FeedOptions
Returns
- IQueryable<dynamic>
an IQueryable{dynamic} that can evaluate the query.
Examples
This example below queries for permissions by id.
var query = new SqlQuerySpec(
"SELECT * FROM perms p WHERE p.id = @id",
new SqlParameterCollection(new SqlParameter[] { new SqlParameter { Name = "@id", Value = "readonly" }}));
Permission perm = client.CreatePermissionQuery(usersLink, query).AsEnumerable().FirstOrDefault();
Remarks
Refer to https://msdn.microsoft.com/en-us/library/azure/dn782250.aspx and http://azure.microsoft.com/documentation/articles/documentdb-sql-query/ for syntax and examples.
- See Also
CreatePermissionQuery(string, string, FeedOptions)
Overloaded. This method creates a query for permissions under a user in an Azure Cosmos DB database using a SQL statement. It returns IQueryable{dynamic}.
public IQueryable<dynamic> CreatePermissionQuery(string permissionsLink, string sqlExpression, FeedOptions feedOptions = null)
Parameters
permissionsLink
stringThe path link for the persmissions under a user, e.g. dbs/db_rid/users/user_rid/permissions/.
sqlExpression
stringThe SQL statement.
feedOptions
FeedOptionsThe options for processing the query result feed. For details, see FeedOptions
Returns
- IQueryable<dynamic>
an IQueryable{dynamic} that can evaluate the query.
Examples
This example below queries for permissions by id.
Permission perm = client.CreatePermissionQuery(userLink,
"SELECT * FROM perms p WHERE p.id = 'readonly'").AsEnumerable().FirstOrDefault();
Remarks
Refer to https://msdn.microsoft.com/en-us/library/azure/dn782250.aspx and http://azure.microsoft.com/documentation/articles/documentdb-sql-query/ for syntax and examples.
- See Also
CreatePermissionQuery(Uri, FeedOptions)
Extension method to create a query for permissions in the Azure Cosmos DB service.
public IOrderedQueryable<Permission> CreatePermissionQuery(Uri permissionsUri, FeedOptions feedOptions = null)
Parameters
permissionsUri
Urithe URI to the permissions.
feedOptions
FeedOptionsThe options for processing the query results feed.
Returns
- IOrderedQueryable<Permission>
The query result set.
CreatePermissionQuery(Uri, SqlQuerySpec, FeedOptions)
Extension method to create a query for permissions in the Azure Cosmos DB service.
public IQueryable<dynamic> CreatePermissionQuery(Uri permissionsUri, SqlQuerySpec querySpec, FeedOptions feedOptions = null)
Parameters
permissionsUri
Urithe URI to the permissions.
querySpec
SqlQuerySpecThe sql query.
feedOptions
FeedOptionsThe options for processing the query results feed.
Returns
- IQueryable<dynamic>
The query result set.
CreatePermissionQuery(Uri, string, FeedOptions)
Extension method to create a query for permissions in the Azure Cosmos DB service.
public IQueryable<dynamic> CreatePermissionQuery(Uri permissionsUri, string sqlExpression, FeedOptions feedOptions = null)
Parameters
permissionsUri
Urithe URI to the permissions.
sqlExpression
stringThe sql query.
feedOptions
FeedOptionsThe options for processing the query results feed.
Returns
- IQueryable<dynamic>
The query result set.
CreateStoredProcedureAsync(string, StoredProcedure, RequestOptions)
Creates a stored procedure as an asychronous operation in the Azure Cosmos DB service.
public Task<ResourceResponse<StoredProcedure>> CreateStoredProcedureAsync(string collectionLink, StoredProcedure storedProcedure, RequestOptions options = null)
Parameters
collectionLink
stringThe link of the collection to create the stored procedure in. E.g. dbs/db_rid/colls/col_rid/
storedProcedure
StoredProcedureThe StoredProcedure object to create.
options
RequestOptions(Optional) Any RequestOptionsfor this request.
Returns
- Task<ResourceResponse<StoredProcedure>>
The StoredProcedure that was created contained within a Task object representing the service response for the asynchronous operation.
Examples
//Create a new stored procedure called "HelloWorldSproc" that takes in a single param called "name".
StoredProcedure sproc = await client.CreateStoredProcedureAsync(collectionLink, new StoredProcedure
{
Id = "HelloWorldSproc",
Body = @"function (name){
var response = getContext().getResponse();
response.setBody('Hello ' + name);
}"
});
Exceptions
- ArgumentNullException
If either
collectionLink
orstoredProcedure
is not set.- AggregateException
Represents a consolidation of failures that occured during async processing. Look within InnerExceptions to find the actual exception(s)
- DocumentClientException
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:
StatusCode Reason for exception 400 BadRequest - This means something was wrong with the request supplied. It is likely that an Id was not supplied for the stored procedure or the Body was malformed. 403 Forbidden - You have reached your quota of stored procedures for the collection supplied. Contact support to have this quota increased. 409 Conflict - This means a StoredProcedure with an id matching the id you supplied already existed. 413 RequestEntityTooLarge - This means the body of the StoredProcedure you tried to create was too large.
- See Also
-
ResourceResponse<TResource>
CreateStoredProcedureAsync(Uri, StoredProcedure, RequestOptions)
Creates a stored procedure as an asychronous operation in the Azure Cosmos DB service.
public Task<ResourceResponse<StoredProcedure>> CreateStoredProcedureAsync(Uri documentCollectionUri, StoredProcedure storedProcedure, RequestOptions options = null)
Parameters
documentCollectionUri
Urithe URI of the document collection to create the stored procedure in.
storedProcedure
StoredProcedurethe Microsoft.Azure.Documents.StoredProcedure object.
options
RequestOptionsThe request options for the request.
Returns
- Task<ResourceResponse<StoredProcedure>>
The task object representing the service response for the asynchronous operation.
CreateStoredProcedureQuery(string, FeedOptions)
Overloaded. This method creates a query for stored procedures under a collection in an Azure Cosmos DB service. It returns An IOrderedQueryable{StoredProcedure}.
public IOrderedQueryable<StoredProcedure> CreateStoredProcedureQuery(string collectionLink, FeedOptions feedOptions = null)
Parameters
collectionLink
stringThe link to the parent collection resource.
feedOptions
FeedOptionsThe options for processing the query result feed. For details, see FeedOptions
Returns
- IOrderedQueryable<StoredProcedure>
An IOrderedQueryable{StoredProcedure} that can evaluate the query with the provided SQL statement.
Examples
This example below queries for stored procedures by id.
StoredProcedure storedProcedure = client.CreateStoredProcedureQuery(collectionLink).Where(c => c.Id == "helloWorld").AsEnumerable().FirstOrDefault();
- See Also
CreateStoredProcedureQuery(string, SqlQuerySpec, FeedOptions)
Overloaded. This method creates a query for stored procedures under a collection in an Azure Cosmos DB database using a SQL statement using a SQL statement with parameterized values. It returns an IQueryable{dynamic}. For more information on preparing SQL statements with parameterized values, please see SqlQuerySpec.
public IQueryable<dynamic> CreateStoredProcedureQuery(string collectionLink, SqlQuerySpec querySpec, FeedOptions feedOptions = null)
Parameters
collectionLink
stringThe link to the parent collection resource.
querySpec
SqlQuerySpecThe SqlQuerySpec instance containing the SQL expression.
feedOptions
FeedOptionsThe options for processing the query result feed. For details, see FeedOptions
Returns
- IQueryable<dynamic>
An IQueryable{dynamic} that can evaluate the query with the provided SQL statement.
Examples
This example below queries for stored procedures by id.
var query = new SqlQuerySpec("SELECT * FROM sprocs s WHERE s.id = @id", new SqlParameterCollection(new SqlParameter[] { new SqlParameter { Name = "@id", Value = "HelloWorld" }}));
StoredProcedure storedProcedure = client.CreateStoredProcedureQuery(collectionLink, query).AsEnumerable().FirstOrDefault();
Remarks
Refer to https://msdn.microsoft.com/en-us/library/azure/dn782250.aspx and http://azure.microsoft.com/documentation/articles/documentdb-sql-query/ for syntax and examples.
- See Also
CreateStoredProcedureQuery(string, string, FeedOptions)
Overloaded. This method creates a query for stored procedures under a collection in an Azure Cosmos DB database using a SQL statement. It returns an IQueryable{dynamic}.
public IQueryable<dynamic> CreateStoredProcedureQuery(string collectionLink, string sqlExpression, FeedOptions feedOptions = null)
Parameters
collectionLink
stringThe link to the parent collection resource.
sqlExpression
stringThe SQL statement.
feedOptions
FeedOptionsThe options for processing the query result feed. For details, see FeedOptions
Returns
- IQueryable<dynamic>
An IQueryable{dynamic} that can evaluate the query with the provided SQL statement.
Examples
This example below queries for stored procedures by id.
StoredProcedure storedProcedure = client.CreateStoredProcedureQuery(collectionLink, "SELECT * FROM sprocs s WHERE s.id = 'HelloWorld'").AsEnumerable().FirstOrDefault();
Remarks
Refer to https://msdn.microsoft.com/en-us/library/azure/dn782250.aspx and http://azure.microsoft.com/documentation/articles/documentdb-sql-query/ for syntax and examples.
- See Also
CreateStoredProcedureQuery(Uri, FeedOptions)
Extension method to create query for stored procedures in the Azure Cosmos DB service.
public IOrderedQueryable<StoredProcedure> CreateStoredProcedureQuery(Uri storedProceduresUri, FeedOptions feedOptions = null)
Parameters
storedProceduresUri
Urithe URI to the stored procedures.
feedOptions
FeedOptionsThe options for processing the query results feed.
Returns
- IOrderedQueryable<StoredProcedure>
The query result set.
CreateStoredProcedureQuery(Uri, SqlQuerySpec, FeedOptions)
Extension method to create query for stored procedures in the Azure Cosmos DB service.
public IQueryable<dynamic> CreateStoredProcedureQuery(Uri storedProceduresUri, SqlQuerySpec querySpec, FeedOptions feedOptions = null)
Parameters
storedProceduresUri
Urithe URI to the stored procedures.
querySpec
SqlQuerySpecThe sql query.
feedOptions
FeedOptionsThe options for processing the query results feed.
Returns
- IQueryable<dynamic>
The query result set.
CreateStoredProcedureQuery(Uri, string, FeedOptions)
Extension method to create query for stored procedures in the Azure Cosmos DB service.
public IQueryable<dynamic> CreateStoredProcedureQuery(Uri storedProceduresUri, string sqlExpression, FeedOptions feedOptions = null)
Parameters
storedProceduresUri
Urithe URI to the stored procedures.
sqlExpression
stringThe sql query.
feedOptions
FeedOptionsThe options for processing the query results feed.
Returns
- IQueryable<dynamic>
The query result set.
CreateTriggerAsync(string, Trigger, RequestOptions)
Creates a trigger as an asychronous operation in the Azure Cosmos DB service.
public Task<ResourceResponse<Trigger>> CreateTriggerAsync(string collectionLink, Trigger trigger, RequestOptions options = null)
Parameters
collectionLink
stringThe link of the DocumentCollection to create the trigger in. E.g. dbs/db_rid/colls/col_rid/
trigger
TriggerThe Trigger object to create.
options
RequestOptions(Optional) Any RequestOptionsfor this request.
Returns
- Task<ResourceResponse<Trigger>>
A task object representing the service response for the asynchronous operation.
Examples
//Create a trigger that validates the contents of a document as it is created and adds a 'timestamp' property if one was not found.
Trigger trig = await client.CreateTriggerAsync(collectionLink, new Trigger
{
Id = "ValidateDocuments",
Body = @"function validate() {
var context = getContext();
var request = context.getRequest();
var documentToCreate = request.getBody();
// validate properties
if (!('timestamp' in documentToCreate)) {
var ts = new Date();
documentToCreate['timestamp'] = ts.getTime();
}
// update the document that will be created
request.setBody(documentToCreate);
}",
TriggerType = TriggerType.Pre,
TriggerOperation = TriggerOperation.Create
});
Exceptions
- ArgumentNullException
If either
collectionLink
ortrigger
is not set.- AggregateException
Represents a consolidation of failures that occured during async processing. Look within InnerExceptions to find the actual exception(s)
- DocumentClientException
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:
StatusCode Reason for exception 400 BadRequest - This means something was wrong with the request supplied. It is likely that an Id was not supplied for the new trigger or that the Body was malformed. 403 Forbidden - You have reached your quota of triggers for the collection supplied. Contact support to have this quota increased. 409 Conflict - This means a Trigger with an id matching the id you supplied already existed. 413 RequestEntityTooLarge - This means the body of the Trigger you tried to create was too large.
- See Also
-
ResourceResponse<TResource>
CreateTriggerAsync(Uri, Trigger, RequestOptions)
Creates a trigger as an asychronous operation in the Azure Cosmos DB service.
public Task<ResourceResponse<Trigger>> CreateTriggerAsync(Uri documentCollectionUri, Trigger trigger, RequestOptions options = null)
Parameters
documentCollectionUri
Urithe URI of the document collection to create the trigger in.
trigger
Triggerthe Microsoft.Azure.Documents.Trigger object.
options
RequestOptionsThe request options for the request.
Returns
- Task<ResourceResponse<Trigger>>
The task object representing the service response for the asynchronous operation.
CreateTriggerQuery(string, FeedOptions)
Overloaded. This method creates a query for triggers under a collection in an Azure Cosmos DB service. It returns An IOrderedQueryable{Trigger}.
public IOrderedQueryable<Trigger> CreateTriggerQuery(string collectionLink, FeedOptions feedOptions = null)
Parameters
collectionLink
stringThe link to the parent collection resource.
feedOptions
FeedOptionsThe options for processing the query result feed. For details, see FeedOptions
Returns
- IOrderedQueryable<Trigger>
An IOrderedQueryable{Trigger} that can evaluate the query with the provided SQL statement.
Examples
This example below queries for triggers by id.
Trigger trigger = client.CreateTriggerQuery(collectionLink).Where(t => t.Id == "validate").AsEnumerable().FirstOrDefault();
- See Also
CreateTriggerQuery(string, SqlQuerySpec, FeedOptions)
Overloaded. This method creates a query for triggers under a collection in an Azure Cosmos DB database using a SQL statement with parameterized values. It returns an IQueryable{dynamic}. For more information on preparing SQL statements with parameterized values, please see SqlQuerySpec.
public IQueryable<dynamic> CreateTriggerQuery(string collectionLink, SqlQuerySpec querySpec, FeedOptions feedOptions = null)
Parameters
collectionLink
stringThe link to the parent collection resource.
querySpec
SqlQuerySpecThe SqlQuerySpec instance containing the SQL expression.
feedOptions
FeedOptionsThe options for processing the query result feed. For details, see FeedOptions
Returns
- IQueryable<dynamic>
An IQueryable{Trigger} that can evaluate the query with the provided SQL statement.
Examples
This example below queries for triggers by id.
var query = new SqlQuerySpec("SELECT * FROM triggers t WHERE t.id = @id", new SqlParameterCollection(new SqlParameter[] { new SqlParameter { Name = "@id", Value = "HelloWorld" }}));
Trigger trigger = client.CreateTriggerQuery(collectionLink, query).AsEnumerable().FirstOrDefault();
Remarks
Refer to https://msdn.microsoft.com/en-us/library/azure/dn782250.aspx and http://azure.microsoft.com/documentation/articles/documentdb-sql-query/ for syntax and examples.
- See Also
CreateTriggerQuery(string, string, FeedOptions)
Overloaded. This method creates a query for triggers under a collection in an Azure Cosmos DB service. It returns an IQueryable{dynamic}.
public IQueryable<dynamic> CreateTriggerQuery(string collectionLink, string sqlExpression, FeedOptions feedOptions = null)
Parameters
collectionLink
stringThe link to the parent collection resource.
sqlExpression
stringThe SQL statement.
feedOptions
FeedOptionsThe options for processing the query result feed. For details, see FeedOptions
Returns
- IQueryable<dynamic>
An IQueryable{dynamic} that can evaluate the query with the provided SQL statement.
Examples
This example below queries for triggers by id.
Trigger trigger = client.CreateTriggerQuery(collectionLink, "SELECT * FROM triggers t WHERE t.id = 'validate'").AsEnumerable().FirstOrDefault();
Remarks
Refer to https://msdn.microsoft.com/en-us/library/azure/dn782250.aspx and http://azure.microsoft.com/documentation/articles/documentdb-sql-query/ for syntax and examples.
- See Also
CreateTriggerQuery(Uri, FeedOptions)
Extension method to create query for triggers in the Azure Cosmos DB service.
public IOrderedQueryable<Trigger> CreateTriggerQuery(Uri triggersUri, FeedOptions feedOptions = null)
Parameters
triggersUri
Urithe URI to the triggers.
feedOptions
FeedOptionsThe options for processing the query results feed.
Returns
- IOrderedQueryable<Trigger>
The query result set.
CreateTriggerQuery(Uri, SqlQuerySpec, FeedOptions)
Extension method to create query for triggers in the Azure Cosmos DB service.
public IQueryable<dynamic> CreateTriggerQuery(Uri triggersUri, SqlQuerySpec querySpec, FeedOptions feedOptions = null)
Parameters
triggersUri
Urithe URI to the triggers.
querySpec
SqlQuerySpecThe sql query.
feedOptions
FeedOptionsThe options for processing the query results feed.
Returns
- IQueryable<dynamic>
The query result set.
CreateTriggerQuery(Uri, string, FeedOptions)
Extension method to create query for triggers in the Azure Cosmos DB service.
public IQueryable<dynamic> CreateTriggerQuery(Uri triggersUri, string sqlExpression, FeedOptions feedOptions = null)
Parameters
triggersUri
Urithe URI to the triggers.
sqlExpression
stringThe sql query.
feedOptions
FeedOptionsThe options for processing the query results feed.
Returns
- IQueryable<dynamic>
The query result set.
CreateUserAsync(string, User, RequestOptions)
Creates a user object as an asychronous operation in the Azure Cosmos DB service.
public Task<ResourceResponse<User>> CreateUserAsync(string databaseLink, User user, RequestOptions options = null)
Parameters
databaseLink
stringThe link of the database to create the user in. E.g. dbs/db_rid/
user
UserThe User object to create.
options
RequestOptions(Optional) The request options for the request.
Returns
- Task<ResourceResponse<User>>
A task object representing the service response for the asynchronous operation which contains the created User object.
Examples
//Create a new user called joeBloggs in the specified database
User user = await client.CreateUserAsync(databaseLink, new User { Id = "joeBloggs" });
Exceptions
- ArgumentNullException
If either
databaseLink
oruser
is not set.- AggregateException
Represents a consolidation of failures that occured during async processing. Look within InnerExceptions to find the actual exception(s)
- DocumentClientException
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:
StatusCode Reason for exception 400 BadRequest - This means something was wrong with the request supplied. 403 Forbidden - You have reached your quota of user objects for this database. Contact support to have this quota increased. 409 Conflict - This means a User with an id matching the id you supplied already existed.
- See Also
-
ResourceResponse<TResource>
CreateUserAsync(Uri, User, RequestOptions)
Creates a user as an asychronous operation in the Azure Cosmos DB service.
public Task<ResourceResponse<User>> CreateUserAsync(Uri databaseUri, User user, RequestOptions options = null)
Parameters
databaseUri
Urithe URI of the database to create the user in.
user
Userthe Microsoft.Azure.Documents.User object.
options
RequestOptionsThe request options for the request.
Returns
- Task<ResourceResponse<User>>
The task object representing the service response for the asynchronous operation.
CreateUserDefinedFunctionAsync(string, UserDefinedFunction, RequestOptions)
Creates a user defined function as an asychronous operation in the Azure Cosmos DB service.
public Task<ResourceResponse<UserDefinedFunction>> CreateUserDefinedFunctionAsync(string collectionLink, UserDefinedFunction function, RequestOptions options = null)
Parameters
collectionLink
stringThe link of the DocumentCollection to create the user defined function in. E.g. dbs/db_rid/colls/col_rid/
function
UserDefinedFunctionThe UserDefinedFunction object to create.
options
RequestOptions(Optional) Any RequestOptionsfor this request.
Returns
- Task<ResourceResponse<UserDefinedFunction>>
A task object representing the service response for the asynchronous operation.
Examples
//Create a user defined function that converts a string to upper case
UserDefinedFunction udf = client.CreateUserDefinedFunctionAsync(collectionLink, new UserDefinedFunction
{
Id = "ToUpper",
Body = @"function toUpper(input) {
return input.toUpperCase();
}",
});
Exceptions
- ArgumentNullException
If either
collectionLink
orfunction
is not set.- AggregateException
Represents a consolidation of failures that occured during async processing. Look within InnerExceptions to find the actual exception(s)
- DocumentClientException
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:
StatusCode Reason for exception 400 BadRequest - This means something was wrong with the request supplied. It is likely that an Id was not supplied for the new user defined function or that the Body was malformed. 403 Forbidden - You have reached your quota of user defined functions for the collection supplied. Contact support to have this quota increased. 409 Conflict - This means a UserDefinedFunction with an id matching the id you supplied already existed. 413 RequestEntityTooLarge - This means the body of the UserDefinedFunction you tried to create was too large.
- See Also
-
ResourceResponse<TResource>
CreateUserDefinedFunctionAsync(Uri, UserDefinedFunction, RequestOptions)
Creates a user defined function as an asychronous operation in the Azure Cosmos DB service.
public Task<ResourceResponse<UserDefinedFunction>> CreateUserDefinedFunctionAsync(Uri documentCollectionUri, UserDefinedFunction function, RequestOptions options = null)
Parameters
documentCollectionUri
Urithe URI of the document collection to create the user defined function in.
function
UserDefinedFunctionthe Microsoft.Azure.Documents.UserDefinedFunction object.
options
RequestOptionsThe request options for the request.
Returns
- Task<ResourceResponse<UserDefinedFunction>>
The task object representing the service response for the asynchronous operation.
CreateUserDefinedFunctionQuery(string, FeedOptions)
Overloaded. This method creates a query for udfs under a collection in an Azure Cosmos DB service. It returns An IOrderedQueryable{UserDefinedFunction}.
public IOrderedQueryable<UserDefinedFunction> CreateUserDefinedFunctionQuery(string collectionLink, FeedOptions feedOptions = null)
Parameters
collectionLink
stringThe link to the parent collection resource.
feedOptions
FeedOptionsThe options for processing the query result feed. For details, see FeedOptions
Returns
- IOrderedQueryable<UserDefinedFunction>
An IOrderedQueryable{UserDefinedFunction} that can evaluate the query with the provided SQL statement.
Examples
This example below queries for user-defined functions by id.
UserDefinedFunction udf = client.CreateUserDefinedFunctionQuery(collectionLink).Where(u => u.Id == "sqrt").AsEnumerable().FirstOrDefault();
- See Also
CreateUserDefinedFunctionQuery(string, SqlQuerySpec, FeedOptions)
Overloaded. This method creates a query for udfs under a collection in an Azure Cosmos DB database with parameterized values. It returns an IQueryable{dynamic}. For more information on preparing SQL statements with parameterized values, please see SqlQuerySpec.
public IQueryable<dynamic> CreateUserDefinedFunctionQuery(string collectionLink, SqlQuerySpec querySpec, FeedOptions feedOptions = null)
Parameters
collectionLink
stringThe link to the parent collection resource.
querySpec
SqlQuerySpecThe SqlQuerySpec instance containing the SQL expression.
feedOptions
FeedOptionsThe options for processing the query result feed. For details, see FeedOptions
Returns
- IQueryable<dynamic>
An IQueryable{dynamic} that can evaluate the query with the provided SQL statement.
Examples
This example below queries for user-defined functions by id.
var query = new SqlQuerySpec("SELECT * FROM udfs u WHERE u.id = @id", new SqlParameterCollection(new SqlParameter[] { new SqlParameter { Name = "@id", Value = "sqrt" }}));
UserDefinedFunction udf = client.CreateUserDefinedFunctionQuery(collectionLink, query).AsEnumerable().FirstOrDefault();
Remarks
Refer to https://msdn.microsoft.com/en-us/library/azure/dn782250.aspx and http://azure.microsoft.com/documentation/articles/documentdb-sql-query/ for syntax and examples.
- See Also
CreateUserDefinedFunctionQuery(string, string, FeedOptions)
Overloaded. This method creates a query for udfs under a collection in an Azure Cosmos DB database using a SQL statement. It returns an IQueryable{dynamic}.
public IQueryable<dynamic> CreateUserDefinedFunctionQuery(string collectionLink, string sqlExpression, FeedOptions feedOptions = null)
Parameters
collectionLink
stringThe link to the parent collection resource.
sqlExpression
stringThe SQL statement.
feedOptions
FeedOptionsThe options for processing the query result feed. For details, see FeedOptions
Returns
- IQueryable<dynamic>
An IQueryable{dynamic} that can evaluate the query with the provided SQL statement.
Examples
This example below queries for user-defined functions by id.
UserDefinedFunction udf = client.CreateUserDefinedFunctionQuery(collectionLink, "SELECT * FROM udfs u WHERE u.id = 'sqrt'").AsEnumerable().FirstOrDefault();
Remarks
Refer to https://msdn.microsoft.com/en-us/library/azure/dn782250.aspx and http://azure.microsoft.com/documentation/articles/documentdb-sql-query/ for syntax and examples.
- See Also
CreateUserDefinedFunctionQuery(Uri, FeedOptions)
Extension method to create a query for user-defined functions in the Azure Cosmos DB service.
public IOrderedQueryable<UserDefinedFunction> CreateUserDefinedFunctionQuery(Uri userDefinedFunctionsUri, FeedOptions feedOptions = null)
Parameters
userDefinedFunctionsUri
Urithe URI to the user-defined functions.
feedOptions
FeedOptionsThe options for processing the query results feed.
Returns
- IOrderedQueryable<UserDefinedFunction>
The query result set.
CreateUserDefinedFunctionQuery(Uri, SqlQuerySpec, FeedOptions)
Extension method to create a query for user-defined functions in the Azure Cosmos DB service.
public IQueryable<dynamic> CreateUserDefinedFunctionQuery(Uri userDefinedFunctionsUri, SqlQuerySpec querySpec, FeedOptions feedOptions = null)
Parameters
userDefinedFunctionsUri
Urithe URI to the user-defined functions.
querySpec
SqlQuerySpecThe sql query.
feedOptions
FeedOptionsThe options for processing the query results feed.
Returns
- IQueryable<dynamic>
The query result set.
CreateUserDefinedFunctionQuery(Uri, string, FeedOptions)
Extension method to create a query for user-defined functions in the Azure Cosmos DB service.
public IQueryable<dynamic> CreateUserDefinedFunctionQuery(Uri userDefinedFunctionsUri, string sqlExpression, FeedOptions feedOptions = null)
Parameters
userDefinedFunctionsUri
Urithe URI to the user-defined functions.
sqlExpression
stringThe sql query.
feedOptions
FeedOptionsThe options for processing the query results feed.
Returns
- IQueryable<dynamic>
The query result set.
CreateUserQuery(string, FeedOptions)
Overloaded. This method creates a query for users under an Azure Cosmos DB service. It returns IOrderedQueryable{User}.
public IOrderedQueryable<User> CreateUserQuery(string usersLink, FeedOptions feedOptions = null)
Parameters
usersLink
stringThe path link for the users under a database, e.g. dbs/db_rid/users/.
feedOptions
FeedOptionsThe options for processing the query result feed. For details, see FeedOptions
Returns
- IOrderedQueryable<User>
An IOrderedQueryable{User} that can evaluate the query.
Examples
This example below queries for users by id.
User user = client.CreateUserQuery(usersLink).Where(u => u.Id == "userid5").AsEnumerable().FirstOrDefault();
- See Also
CreateUserQuery(string, SqlQuerySpec, FeedOptions)
Overloaded. This method creates a query for users under an Azure Cosmos DB database using a SQL statement with parameterized values. It returns an IQueryable{dynamic}. For more information on preparing SQL statements with parameterized values, please see SqlQuerySpec.
public IQueryable<dynamic> CreateUserQuery(string usersLink, SqlQuerySpec querySpec, FeedOptions feedOptions = null)
Parameters
usersLink
stringThe path link for the users under a database, e.g. dbs/db_rid/users/.
querySpec
SqlQuerySpecThe SqlQuerySpec instance containing the SQL expression.
feedOptions
FeedOptionsThe options for processing the query result feed. For details, see FeedOptions
Returns
- IQueryable<dynamic>
an IQueryable{dynamic> that can evaluate the query.
Examples
This example below queries for users by id.
var query = new SqlQuerySpec(
"SELECT * FROM users u WHERE u.id = @id",
new SqlParameterCollection(new SqlParameter[] { new SqlParameter { Name = "@id", Value = "userid5" }}));
User user = client.CreateUserQuery(usersLink, query).AsEnumerable().FirstOrDefault();
Remarks
Refer to https://msdn.microsoft.com/en-us/library/azure/dn782250.aspx and http://azure.microsoft.com/documentation/articles/documentdb-sql-query/ for syntax and examples.
- See Also
CreateUserQuery(string, string, FeedOptions)
Overloaded. This method creates a query for users under an Azure Cosmos DB service. It returns IQueryable{dynamic}.
public IQueryable<dynamic> CreateUserQuery(string usersLink, string sqlExpression, FeedOptions feedOptions = null)
Parameters
usersLink
stringThe path link for the users under a database, e.g. dbs/db_rid/users/.
sqlExpression
stringThe SQL statement.
feedOptions
FeedOptionsThe options for processing the query result feed. For details, see FeedOptions
Returns
- IQueryable<dynamic>
an IQueryable{dynamic} that can evaluate the query.
Examples
This example below queries for users by id.
User user = client.CreateUserQuery(usersLink, "SELECT * FROM users u WHERE u.id = 'userid5'").AsEnumerable().FirstOrDefault();
Remarks
Refer to https://msdn.microsoft.com/en-us/library/azure/dn782250.aspx and http://azure.microsoft.com/documentation/articles/documentdb-sql-query/ for syntax and examples.
- See Also
CreateUserQuery(Uri, FeedOptions)
Extension method to create a query for users in the Azure Cosmos DB service.
public IOrderedQueryable<User> CreateUserQuery(Uri usersUri, FeedOptions feedOptions = null)
Parameters
usersUri
Urithe URI to the users.
feedOptions
FeedOptionsThe options for processing the query results feed.
Returns
- IOrderedQueryable<User>
The query result set.
CreateUserQuery(Uri, SqlQuerySpec, FeedOptions)
Extension method to create a query for users in the Azure Cosmos DB service.
public IQueryable<dynamic> CreateUserQuery(Uri usersUri, SqlQuerySpec querySpec, FeedOptions feedOptions = null)
Parameters
usersUri
Urithe URI to the users.
querySpec
SqlQuerySpecThe sql query.
feedOptions
FeedOptionsThe options for processing the query results feed.
Returns
- IQueryable<dynamic>
The query result set.
CreateUserQuery(Uri, string, FeedOptions)
Extension method to create a query for users in the Azure Cosmos DB service.
public IQueryable<dynamic> CreateUserQuery(Uri usersUri, string sqlExpression, FeedOptions feedOptions = null)
Parameters
usersUri
Urithe URI to the users.
sqlExpression
stringThe sql query.
feedOptions
FeedOptionsThe options for processing the query results feed.
Returns
- IQueryable<dynamic>
The query result set.
DeleteAttachmentAsync(string, RequestOptions, CancellationToken)
Delete an Attachment from the the Azure Cosmos DB service as an asynchronous operation.
public Task<ResourceResponse<Attachment>> DeleteAttachmentAsync(string attachmentLink, RequestOptions options = null, CancellationToken cancellationToken = default)
Parameters
attachmentLink
stringThe link of the Attachment to delete. E.g. dbs/db_rid/colls/col_rid/docs/doc_rid/attachments/attachment_rid/
options
RequestOptions(Optional) Any options you wish to set for this request.
cancellationToken
CancellationToken(Optional) A CancellationToken that can be used by other objects or threads to receive notice of cancellation.
Returns
Examples
//Delete an attachment using its selfLink property
//To get the attachmentLink you would have to query for the Attachment, using CreateAttachmentQuery(), and then refer to its .SelfLink property
await client.DeleteAttachmentAsync(attachmentLink);
Exceptions
- ArgumentNullException
If
attachmentLink
is not set.- DocumentClientException
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:
StatusCode Reason for exception 404 NotFound - This means the resource you tried to delete did not exist.
- See Also
-
ResourceResponse<TResource>
DeleteAttachmentAsync(Uri, RequestOptions, CancellationToken)
Delete an attachment as an asynchronous operation from the Azure Cosmos DB service.
public Task<ResourceResponse<Attachment>> DeleteAttachmentAsync(Uri attachmentUri, RequestOptions options = null, CancellationToken cancellationToken = default)
Parameters
attachmentUri
Urithe URI of the attachment to delete.
options
RequestOptionsThe request options for the request.
cancellationToken
CancellationToken(Optional) CancellationToken representing request cancellation.
Returns
- Task<ResourceResponse<Attachment>>
The task object representing the service response for the asynchronous operation.
DeleteConflictAsync(string, RequestOptions)
Delete a Conflict from the Azure Cosmos DB service as an asynchronous operation.
public Task<ResourceResponse<Conflict>> DeleteConflictAsync(string conflictLink, RequestOptions options = null)
Parameters
conflictLink
stringThe link of the Conflict to delete. E.g. dbs/db_rid/colls/coll_rid/conflicts/
options
RequestOptions(Optional) The request options for the request.
Returns
- Task<ResourceResponse<Conflict>>
A System.Threading.Tasks containing a ResourceResponse<TResource> which will contain information about the request issued.
Examples
//Delete a conflict using its selfLink property.
//To get the conflictLink you would have to query for the Conflict object, using CreateConflictQuery(), and then refer to its .SelfLink property
await client.DeleteConflictAsync(conflictLink);
Exceptions
- ArgumentNullException
If
conflictLink
is not set.- DocumentClientException
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:
StatusCode Reason for exception 404 NotFound - This means the resource you tried to delete did not exist.
- See Also
-
ResourceResponse<TResource>
DeleteConflictAsync(Uri, RequestOptions)
Delete a conflict as an asynchronous operation from the Azure Cosmos DB service.
public Task<ResourceResponse<Conflict>> DeleteConflictAsync(Uri conflictUri, RequestOptions options = null)
Parameters
conflictUri
Urithe URI of the conflict to delete.
options
RequestOptionsThe request options for the request.
Returns
- Task<ResourceResponse<Conflict>>
The task object representing the service response for the asynchronous operation.
DeleteDatabaseAsync(string, RequestOptions)
Delete a Database from the Azure Cosmos DB service as an asynchronous operation.
public Task<ResourceResponse<Database>> DeleteDatabaseAsync(string databaseLink, RequestOptions options = null)
Parameters
databaseLink
stringThe link of the Database to delete. E.g. dbs/db_rid/
options
RequestOptions(Optional) The request options for the request.
Returns
- Task<ResourceResponse<Database>>
A System.Threading.Tasks containing a ResourceResponse<TResource> which will contain information about the request issued.
Examples
//Delete a database using its selfLink property
//To get the databaseLink you would have to query for the Database, using CreateDatabaseQuery(), and then refer to its .SelfLink property
await client.DeleteDatabaseAsync(databaseLink);
Exceptions
- ArgumentNullException
If
databaseLink
is not set.- DocumentClientException
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:
StatusCode Reason for exception 404 NotFound - This means the resource you tried to delete did not exist.
- See Also
-
ResourceResponse<TResource>
DeleteDatabaseAsync(Uri, RequestOptions)
Delete a database as an asynchronous operation from the Azure Cosmos DB service.
public Task<ResourceResponse<Database>> DeleteDatabaseAsync(Uri databaseUri, RequestOptions options = null)
Parameters
databaseUri
Urithe URI of the database to delete.
options
RequestOptionsThe request options for the request.
Returns
- Task<ResourceResponse<Database>>
The task object representing the service response for the asynchronous operation.
DeleteDocumentAsync(string, RequestOptions, CancellationToken)
Delete a Document from the Azure Cosmos DB service as an asynchronous operation.
public Task<ResourceResponse<Document>> DeleteDocumentAsync(string documentLink, RequestOptions options = null, CancellationToken cancellationToken = default)
Parameters
documentLink
stringThe link of the Document to delete. E.g. dbs/db_rid/colls/col_rid/docs/doc_rid/
options
RequestOptions(Optional) The request options for the request.
cancellationToken
CancellationToken(Optional) A CancellationToken that can be used by other objects or threads to receive notice of cancellation.
Returns
- Task<ResourceResponse<Document>>
A System.Threading.Tasks containing a ResourceResponse<TResource> which will contain information about the request issued.
Examples
//Delete a document using its selfLink property
//To get the documentLink you would have to query for the Document, using CreateDocumentQuery(), and then refer to its .SelfLink property
await client.DeleteDocumentAsync(documentLink);
Exceptions
- ArgumentNullException
If
documentLink
is not set.- DocumentClientException
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:
StatusCode Reason for exception 404 NotFound - This means the resource you tried to delete did not exist.
- See Also
-
ResourceResponse<TResource>
DeleteDocumentAsync(Uri, RequestOptions, CancellationToken)
Delete a document as an asynchronous operation from the Azure Cosmos DB service.
public Task<ResourceResponse<Document>> DeleteDocumentAsync(Uri documentUri, RequestOptions options = null, CancellationToken cancellationToken = default)
Parameters
documentUri
Urithe URI of the document to delete.
options
RequestOptionsThe request options for the request.
cancellationToken
CancellationToken(Optional) CancellationToken representing request cancellation.
Returns
- Task<ResourceResponse<Document>>
The task object representing the service response for the asynchronous operation.
DeleteDocumentCollectionAsync(string, RequestOptions)
Delete a DocumentCollection from the Azure Cosmos DB service as an asynchronous operation.
public Task<ResourceResponse<DocumentCollection>> DeleteDocumentCollectionAsync(string documentCollectionLink, RequestOptions options = null)
Parameters
documentCollectionLink
stringThe link of the Document to delete. E.g. dbs/db_rid/colls/col_rid/
options
RequestOptions(Optional) The request options for the request.
Returns
- Task<ResourceResponse<DocumentCollection>>
A System.Threading.Tasks containing a ResourceResponse<TResource> which will contain information about the request issued.
Examples
//Delete a collection using its selfLink property
//To get the collectionLink you would have to query for the Collection, using CreateDocumentCollectionQuery(), and then refer to its .SelfLink property
await client.DeleteDocumentCollectionAsync(collectionLink);
Exceptions
- ArgumentNullException
If
documentCollectionLink
is not set.- DocumentClientException
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:
StatusCode Reason for exception 404 NotFound - This means the resource you tried to delete did not exist.
- See Also
-
ResourceResponse<TResource>
DeleteDocumentCollectionAsync(Uri, RequestOptions)
Delete a collection as an asynchronous operation from the Azure Cosmos DB service.
public Task<ResourceResponse<DocumentCollection>> DeleteDocumentCollectionAsync(Uri documentCollectionUri, RequestOptions options = null)
Parameters
documentCollectionUri
Urithe URI of the document collection to delete.
options
RequestOptionsThe request options for the request.
Returns
- Task<ResourceResponse<DocumentCollection>>
The task object representing the service response for the asynchronous operation.
DeletePermissionAsync(string, RequestOptions)
Delete a Permission from the Azure Cosmos DB service as an asynchronous operation.
public Task<ResourceResponse<Permission>> DeletePermissionAsync(string permissionLink, RequestOptions options = null)
Parameters
permissionLink
stringThe link of the Permission to delete. E.g. dbs/db_rid/users/user_rid/permissions/permission_rid/
options
RequestOptions(Optional) The request options for the request.
Returns
- Task<ResourceResponse<Permission>>
A System.Threading.Tasks containing a ResourceResponse<TResource> which will contain information about the request issued.
Examples
//Delete a permission using its selfLink property.
//To get the permissionLink you would have to query for the Permission object, using CreateStoredProcedureQuery(), and then refer to its .SelfLink property
await client.DeletePermissionAsync(permissionLink);
Exceptions
- ArgumentNullException
If
permissionLink
is not set.- DocumentClientException
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:
StatusCode Reason for exception 404 NotFound - This means the resource you tried to delete did not exist.
- See Also
-
ResourceResponse<TResource>
DeletePermissionAsync(Uri, RequestOptions)
Delete a permission as an asynchronous operation from the Azure Cosmos DB service.
public Task<ResourceResponse<Permission>> DeletePermissionAsync(Uri permissionUri, RequestOptions options = null)
Parameters
permissionUri
Urithe URI of the permission to delete.
options
RequestOptionsThe request options for the request.
Returns
- Task<ResourceResponse<Permission>>
The task object representing the service response for the asynchronous operation.
DeleteStoredProcedureAsync(string, RequestOptions)
Delete a StoredProcedure from the Azure Cosmos DB service as an asynchronous operation.
public Task<ResourceResponse<StoredProcedure>> DeleteStoredProcedureAsync(string storedProcedureLink, RequestOptions options = null)
Parameters
storedProcedureLink
stringThe link of the StoredProcedure to delete. E.g. dbs/db_rid/colls/col_rid/sprocs/sproc_rid/
options
RequestOptions(Optional) The request options for the request.
Returns
- Task<ResourceResponse<StoredProcedure>>
A System.Threading.Tasks containing a ResourceResponse<TResource> which will contain information about the request issued.
Examples
//Delete a stored procedure using its selfLink property.
//To get the sprocLink you would have to query for the Stored Procedure, using CreateStoredProcedureQuery(), and then refer to its .SelfLink property
await client.DeleteStoredProcedureAsync(sprocLink);
Exceptions
- ArgumentNullException
If
storedProcedureLink
is not set.- DocumentClientException
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:
StatusCode Reason for exception 404 NotFound - This means the resource you tried to delete did not exist.
- See Also
-
ResourceResponse<TResource>
DeleteStoredProcedureAsync(Uri, RequestOptions)
Delete a stored procedure as an asynchronous operation from the Azure Cosmos DB service.
public Task<ResourceResponse<StoredProcedure>> DeleteStoredProcedureAsync(Uri storedProcedureUri, RequestOptions options = null)
Parameters
storedProcedureUri
Urithe URI of the stored procedure to delete.
options
RequestOptionsThe request options for the request.
Returns
- Task<ResourceResponse<StoredProcedure>>
The task object representing the service response for the asynchronous operation.
DeleteTriggerAsync(string, RequestOptions)
Delete a Trigger from the Azure Cosmos DB service as an asynchronous operation.
public Task<ResourceResponse<Trigger>> DeleteTriggerAsync(string triggerLink, RequestOptions options = null)
Parameters
triggerLink
stringThe link of the Trigger to delete. E.g. dbs/db_rid/colls/col_rid/triggers/trigger_rid/
options
RequestOptions(Optional) The request options for the request.
Returns
- Task<ResourceResponse<Trigger>>
A System.Threading.Tasks containing a ResourceResponse<TResource> which will contain information about the request issued.
Examples
//Delete a trigger using its selfLink property.
//To get the triggerLink you would have to query for the Trigger, using CreateTriggerQuery(), and then refer to its .SelfLink property
await client.DeleteTriggerAsync(triggerLink);
Exceptions
- ArgumentNullException
If
triggerLink
is not set.- DocumentClientException
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:
StatusCode Reason for exception 404 NotFound - This means the resource you tried to delete did not exist.
- See Also
-
ResourceResponse<TResource>
DeleteTriggerAsync(Uri, RequestOptions)
Delete a trigger as an asynchronous operation from the Azure Cosmos DB service.
public Task<ResourceResponse<Trigger>> DeleteTriggerAsync(Uri triggerUri, RequestOptions options = null)
Parameters
triggerUri
Urithe URI of the trigger to delete.
options
RequestOptionsThe request options for the request.
Returns
- Task<ResourceResponse<Trigger>>
The task object representing the service response for the asynchronous operation.
DeleteUserAsync(string, RequestOptions)
Delete a User from the Azure Cosmos DB service as an asynchronous operation.
public Task<ResourceResponse<User>> DeleteUserAsync(string userLink, RequestOptions options = null)
Parameters
userLink
stringThe link of the User to delete. E.g. dbs/db_rid/users/user_rid/
options
RequestOptions(Optional) The request options for the request.
Returns
- Task<ResourceResponse<User>>
A System.Threading.Tasks containing a ResourceResponse<TResource> which will contain information about the request issued.
Examples
//Delete a user using its selfLink property.
//To get the userLink you would have to query for the User object, using CreateUserQuery(), and then refer to its .SelfLink property
await client.DeleteUserAsync(userLink);
Exceptions
- ArgumentNullException
If
userLink
is not set.- DocumentClientException
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:
StatusCode Reason for exception 404 NotFound - This means the resource you tried to delete did not exist.
- See Also
-
ResourceResponse<TResource>
DeleteUserAsync(Uri, RequestOptions)
Delete a user as an asynchronous operation from the Azure Cosmos DB service.
public Task<ResourceResponse<User>> DeleteUserAsync(Uri userUri, RequestOptions options = null)
Parameters
userUri
Urithe URI of the user to delete.
options
RequestOptionsThe request options for the request.
Returns
- Task<ResourceResponse<User>>
The task object representing the service response for the asynchronous operation.
DeleteUserDefinedFunctionAsync(string, RequestOptions)
Delete a UserDefinedFunction from the Azure Cosmos DB service as an asynchronous operation.
public Task<ResourceResponse<UserDefinedFunction>> DeleteUserDefinedFunctionAsync(string functionLink, RequestOptions options = null)
Parameters
functionLink
stringThe link of the UserDefinedFunction to delete. E.g. dbs/db_rid/colls/col_rid/udfs/udf_rid/
options
RequestOptions(Optional) The request options for the request.
Returns
- Task<ResourceResponse<UserDefinedFunction>>
A System.Threading.Tasks containing a ResourceResponse<TResource> which will contain information about the request issued.
Examples
//Delete a user defined function using its selfLink property.
//To get the functionLink you would have to query for the User Defined Function, using CreateUserDefinedFunctionQuery(), and then refer to its .SelfLink property
await client.DeleteUserDefinedFunctionAsync(functionLink);
Exceptions
- ArgumentNullException
If
functionLink
is not set.- DocumentClientException
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:
StatusCode Reason for exception 404 NotFound - This means the resource you tried to delete did not exist.
- See Also
-
ResourceResponse<TResource>
DeleteUserDefinedFunctionAsync(Uri, RequestOptions)
Delete a user defined function as an asynchronous operation from the Azure Cosmos DB service.
public Task<ResourceResponse<UserDefinedFunction>> DeleteUserDefinedFunctionAsync(Uri functionUri, RequestOptions options = null)
Parameters
functionUri
Urithe URI of the user defined function to delete.
options
RequestOptionsThe request options for the request.
Returns
- Task<ResourceResponse<UserDefinedFunction>>
The task object representing the service response for the asynchronous operation.
Dispose()
Disposes the client for the Azure Cosmos DB service.
public void Dispose()
Examples
IDocumentClient client = new DocumentClient(new Uri("service endpoint"), "auth key");
if (client != null) client.Dispose();
ExecuteStoredProcedureAsync<TValue>(string, RequestOptions, params dynamic[])
Executes a stored procedure against a partitioned collection in the Azure Cosmos DB service as an asynchronous operation, specifiying a target partition.
public Task<StoredProcedureResponse<TValue>> ExecuteStoredProcedureAsync<TValue>(string storedProcedureLink, RequestOptions options, params dynamic[] procedureParams)
Parameters
storedProcedureLink
stringThe link to the stored procedure to execute.
options
RequestOptions(Optional) The request options for the request.
procedureParams
dynamic[](Optional) An array of dynamic objects representing the parameters for the stored procedure.
Returns
- Task<StoredProcedureResponse<TValue>>
The task object representing the service response for the asynchronous operation which would contain any response set in the stored procedure.
Type Parameters
TValue
The type of the stored procedure's return value.
Examples
//Execute a StoredProcedure with ResourceId of "sproc_rid" that takes two "Player" documents, does some stuff, and returns a bool
StoredProcedureResponse<bool> sprocResponse = await client.ExecuteStoredProcedureAsync<bool>(
"/dbs/db_rid/colls/col_rid/sprocs/sproc_rid/",
new RequestOptions { PartitionKey = new PartitionKey(1) },
new Player { id="1", name="joe" } ,
new Player { id="2", name="john" }
);
if (sprocResponse.Response) Console.WriteLine("Congrats, the stored procedure did some stuff");
Exceptions
- ArgumentNullException
If
storedProcedureLink
is not set.
- See Also
-
StoredProcedureResponse<TValue>
ExecuteStoredProcedureAsync<TValue>(string, RequestOptions, CancellationToken, params dynamic[])
Executes a stored procedure against a partitioned collection in the Azure Cosmos DB service as an asynchronous operation, specifiying a target partition.
public Task<StoredProcedureResponse<TValue>> ExecuteStoredProcedureAsync<TValue>(string storedProcedureLink, RequestOptions options, CancellationToken cancellationToken, params dynamic[] procedureParams)
Parameters
storedProcedureLink
stringThe link to the stored procedure to execute.
options
RequestOptions(Optional) The request options for the request.
cancellationToken
CancellationToken(Optional) A CancellationToken that can be used by other objects or threads to receive notice of cancellation.
procedureParams
dynamic[](Optional) An array of dynamic objects representing the parameters for the stored procedure.
Returns
- Task<StoredProcedureResponse<TValue>>
The task object representing the service response for the asynchronous operation which would contain any response set in the stored procedure.
Type Parameters
TValue
The type of the stored procedure's return value.
Examples
//Execute a StoredProcedure with ResourceId of "sproc_rid" that takes two "Player" documents, does some stuff, and returns a bool
StoredProcedureResponse<bool> sprocResponse = await client.ExecuteStoredProcedureAsync<bool>(
"/dbs/db_rid/colls/col_rid/sprocs/sproc_rid/",
new RequestOptions { PartitionKey = new PartitionKey(1) },
new Player { id="1", name="joe" } ,
new Player { id="2", name="john" }
);
if (sprocResponse.Response) Console.WriteLine("Congrats, the stored procedure did some stuff");
Exceptions
- ArgumentNullException
If
storedProcedureLink
is not set.
- See Also
-
StoredProcedureResponse<TValue>
ExecuteStoredProcedureAsync<TValue>(string, params dynamic[])
Executes a stored procedure against a collection as an asynchronous operation in the Azure Cosmos DB service.
public Task<StoredProcedureResponse<TValue>> ExecuteStoredProcedureAsync<TValue>(string storedProcedureLink, params dynamic[] procedureParams)
Parameters
storedProcedureLink
stringThe link to the stored procedure to execute.
procedureParams
dynamic[](Optional) An array of dynamic objects representing the parameters for the stored procedure.
Returns
- Task<StoredProcedureResponse<TValue>>
The task object representing the service response for the asynchronous operation which would contain any response set in the stored procedure.
Type Parameters
TValue
The type of the stored procedure's return value.
Examples
//Execute a StoredProcedure with ResourceId of "sproc_rid" that takes two "Player" documents, does some stuff, and returns a bool
StoredProcedureResponse<bool> sprocResponse = await client.ExecuteStoredProcedureAsync<bool>(
"/dbs/db_rid/colls/col_rid/sprocs/sproc_rid/",
new Player { id="1", name="joe" } ,
new Player { id="2", name="john" }
);
if (sprocResponse.Response) Console.WriteLine("Congrats, the stored procedure did some stuff");
Exceptions
- ArgumentNullException
If
storedProcedureLink
is not set.
- See Also
-
StoredProcedureResponse<TValue>
ExecuteStoredProcedureAsync<TValue>(Uri, RequestOptions, params dynamic[])
Executes a stored procedure against a collection as an asynchronous operation from the Azure Cosmos DB service.
public Task<StoredProcedureResponse<TValue>> ExecuteStoredProcedureAsync<TValue>(Uri storedProcedureUri, RequestOptions options, params dynamic[] procedureParams)
Parameters
storedProcedureUri
Urithe URI of the stored procedure to be executed.
options
RequestOptionsThe request options for the request.
procedureParams
dynamic[]the parameters for the stored procedure execution.
Returns
- Task<StoredProcedureResponse<TValue>>
The task object representing the service response for the asynchronous operation.
Type Parameters
TValue
the type of the stored procedure's return value.
ExecuteStoredProcedureAsync<TValue>(Uri, RequestOptions, CancellationToken, params dynamic[])
Executes a stored procedure against a collection as an asynchronous operation from the Azure Cosmos DB service.
public Task<StoredProcedureResponse<TValue>> ExecuteStoredProcedureAsync<TValue>(Uri storedProcedureUri, RequestOptions options, CancellationToken cancellationToken = default, params dynamic[] procedureParams)
Parameters
storedProcedureUri
Urithe URI of the stored procedure to be executed.
options
RequestOptionsThe request options for the request.
cancellationToken
CancellationToken(Optional) CancellationToken representing request cancellation.
procedureParams
dynamic[]the parameters for the stored procedure execution.
Returns
- Task<StoredProcedureResponse<TValue>>
The task object representing the service response for the asynchronous operation.
Type Parameters
TValue
the type of the stored procedure's return value.
ExecuteStoredProcedureAsync<TValue>(Uri, params dynamic[])
Executes a stored procedure against a collection as an asynchronous operation from the Azure Cosmos DB service.
public Task<StoredProcedureResponse<TValue>> ExecuteStoredProcedureAsync<TValue>(Uri storedProcedureUri, params dynamic[] procedureParams)
Parameters
storedProcedureUri
Urithe URI of the stored procedure to be executed.
procedureParams
dynamic[]the parameters for the stored procedure execution.
Returns
- Task<StoredProcedureResponse<TValue>>
The task object representing the service response for the asynchronous operation.
Type Parameters
TValue
the type of the stored procedure's return value.
GetDatabaseAccountAsync()
Read the DatabaseAccount from the Azure Cosmos DB service as an asynchronous operation.
public Task<DatabaseAccount> GetDatabaseAccountAsync()
Returns
- Task<DatabaseAccount>
A DatabaseAccount wrapped in a Task object.
OpenAsync(CancellationToken)
Open the connection to validate that the client initialization is successful in the Azure Cosmos DB service.
public Task OpenAsync(CancellationToken cancellationToken = default)
Parameters
cancellationToken
CancellationToken
Returns
Examples
using (IDocumentClient client = new DocumentClient(new Uri("service endpoint"), "auth key"))
{
await client.OpenAsync();
}
Remarks
This method is recommended to be called, after the constructor, but before calling any other methods on the DocumentClient instance. If there are any initialization exceptions, this method will throw them (set on the task). Alternately, calling any API will throw initialization exception at the first call.
ReadAttachmentAsync(string, RequestOptions, CancellationToken)
Reads an Attachment from the Azure Cosmos DB service as an asynchronous operation.
public Task<ResourceResponse<Attachment>> ReadAttachmentAsync(string attachmentLink, RequestOptions options = null, CancellationToken cancellationToken = default)
Parameters
attachmentLink
stringThe link to the attachment to be read.
options
RequestOptions(Optional) The request options for the request.
cancellationToken
CancellationToken(Optional) A CancellationToken that can be used by other objects or threads to receive notice of cancellation.
Returns
- Task<ResourceResponse<Attachment>>
A System.Threading.Tasks containing a ResourceResponse<TResource> which wraps a Attachment containing the read resource record.
Examples
//Reads an Attachment resource where
// - sample_db is the ID property of the Database
// - sample_coll is the ID property of the DocumentCollection
// - sample_doc is the ID property of the Document
// - attachment_id is the ID property of the Attachment resource you wish to read.
var attachLink = "/dbs/sample_db/colls/sample_coll/docs/sample_doc/attachments/attachment_id/";
Attachment attachment = await client.ReadAttachmentAsync(attachLink);
Remarks
Doing a read of a resource is the most efficient way to get a resource from the service. If you know the resource's ID, do a read instead of a query by ID.
The example shown uses ID-based links, where the link is composed of the ID properties used when the resources were created.
You can still use the SelfLink property of the Database if you prefer. A self-link is a URI for a resource that is made up of Resource Identifiers (or the _rid properties).
ID-based links and SelfLink will both work.
The format for attachmentLink
is always "/dbs/{db identifier}/colls/{coll identifier}/docs/{doc identifier}/attachments/{attachment identifier}" only
the values within the {} change depending on which method you wish to use to address the resource.
Exceptions
- ArgumentNullException
If
attachmentLink
is not set.- DocumentClientException
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:
StatusCode Reason for exception 404 NotFound - This means the resource you tried to read did not exist. 429 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.
- See Also
-
ResourceResponse<TResource>Uri
ReadAttachmentAsync(Uri, RequestOptions, CancellationToken)
Reads an Attachment as an asynchronous operation from the Azure Cosmos DB service.
public Task<ResourceResponse<Attachment>> ReadAttachmentAsync(Uri attachmentUri, RequestOptions options = null, CancellationToken cancellationToken = default)
Parameters
attachmentUri
UriA URI to the Attachment resource to be read.
options
RequestOptionsThe request options for the request.
cancellationToken
CancellationToken(Optional) CancellationToken representing request cancellation.
Returns
- Task<ResourceResponse<Attachment>>
A System.Threading.Tasks containing a ResourceResponse<TResource> which wraps an Attachment containing the read resource record.
Examples
//Reads an Attachment resource where
// - db_id is the ID property of the Database
// - coll_id is the ID property of the DocumentCollection
// - doc_id is the ID property of the Document
// - attachment_id is the ID property of the Attachment resource you wish to read.
var attachLink = UriFactory.CreateAttachmentUri("db_id", "coll_id", "doc_id", "attachment_id");
Attachment attachment = await client.ReadAttachmentAsync(attachLink);
Remarks
Doing a read of a resource is the most efficient way to get a resource from the service. If you know the resource's ID, do a read instead of a query by ID.
Exceptions
- ArgumentNullException
If
attachmentUri
is not set.- DocumentClientException
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:
StatusCode Reason for exception 404 NotFound - This means the resource you tried to read did not exist. 429 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.
- See Also
-
ResourceResponse<TResource>
ReadAttachmentFeedAsync(string, FeedOptions, CancellationToken)
Reads the feed (sequence) of Attachment for a document from the Azure Cosmos DB service as an asynchronous operation.
public Task<FeedResponse<Attachment>> ReadAttachmentFeedAsync(string attachmentsLink, FeedOptions options = null, CancellationToken cancellationToken = default)
Parameters
attachmentsLink
stringThe SelfLink of the resources to be read. E.g. /dbs/db_rid/colls/coll_rid/docs/doc_rid/attachments/
options
FeedOptions(Optional) The request options for the request.
cancellationToken
CancellationToken(Optional) A CancellationToken that can be used by other objects or threads to receive notice of cancellation.
Returns
- Task<FeedResponse<Attachment>>
A System.Threading.Tasks containing a ResourceResponse<TResource> which wraps a Attachment containing the read resource record.
Examples
int count = 0;
string continuation = string.Empty;
do
{
// Read Attachment feed 10 items at a time until there are no more to read
FeedResponse<Attachment> response = await client.ReadAttachmentFeedAsync("/dbs/db_rid/colls/coll_rid/docs/doc_rid/attachments/ ",
new FeedOptions
{
MaxItemCount = 10,
RequestContinuation = continuation
});
// Append the item count
count += response.Count;
// Get the continuation so that we know when to stop.
continuation = response.ResponseContinuation;
} while (!string.IsNullOrEmpty(continuation));
Exceptions
- ArgumentNullException
If
attachmentsLink
is not set.- DocumentClientException
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:
StatusCode Reason for exception 404 NotFound - This means the resource feed you tried to read did not exist. Check the parent rids are correct. 429 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.
- See Also
-
ResourceResponse<TResource>
ReadAttachmentFeedAsync(Uri, FeedOptions, CancellationToken)
Reads the feed (sequence) of attachments for a document as an asynchronous operation from the Azure Cosmos DB service.
public Task<FeedResponse<Attachment>> ReadAttachmentFeedAsync(Uri attachmentsUri, FeedOptions options = null, CancellationToken cancellationToken = default)
Parameters
attachmentsUri
Urithe URI for the attachments.
options
FeedOptionsThe request options for the request.
cancellationToken
CancellationToken(Optional) CancellationToken representing request cancellation.
Returns
- Task<FeedResponse<Attachment>>
The task object representing the service response for the asynchronous operation.
ReadConflictAsync(string, RequestOptions)
Reads a Conflict from the Azure Cosmos DB service as an asynchronous operation.
public Task<ResourceResponse<Conflict>> ReadConflictAsync(string conflictLink, RequestOptions options = null)
Parameters
conflictLink
stringThe link to the Conflict to be read.
options
RequestOptions(Optional) The request options for the request.
Returns
- Task<ResourceResponse<Conflict>>
A System.Threading.Tasks containing a ResourceResponse<TResource> which wraps a Conflict containing the read resource record.
Examples
//Reads a Conflict resource from a Database
// - sample_database is the ID of the database
// - sample_collection is the ID of the collection
// - conflict_id is the ID of the conflict to be read
var conflictLink = "/dbs/sample_database/colls/sample_collection/conflicts/conflict_id";
Conflict conflict = await client.ReadConflictAsync(conflictLink);
Remarks
Doing a read of a resource is the most efficient way to get a resource from the Database. If you know the resource's ID, do a read instead of a query by ID.
The example shown uses ID-based links, where the link is composed of the ID properties used when the resources were created.
You can still use the SelfLink property of the Conflict if you prefer. A self-link is a URI for a resource that is made up of Resource Identifiers (or the _rid properties).
ID-based links and SelfLink will both work.
The format for conflictLink
is always "/dbs/{db identifier}/colls/{collectioon identifier}/conflicts/{conflict identifier}"
only the values within the {...} change depending on which method you wish to use to address the resource.
Exceptions
- ArgumentNullException
If
conflictLink
is not set.- DocumentClientException
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:
StatusCode Reason for exception 404 NotFound - This means the resource you tried to read did not exist. 429 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.
- See Also
-
ResourceResponse<TResource>Uri
ReadConflictAsync(Uri, RequestOptions)
Reads a Conflict as an asynchronous operation from the Azure Cosmos DB service.
public Task<ResourceResponse<Conflict>> ReadConflictAsync(Uri conflictUri, RequestOptions options = null)
Parameters
conflictUri
UriA URI to the Conflict resource to be read.
options
RequestOptionsThe request options for the request.
Returns
- Task<ResourceResponse<Conflict>>
A System.Threading.Tasks containing a ResourceResponse<TResource> which wraps a Conflict containing the read resource record.
Examples
//Reads a Conflict resource where
// - db_id is the ID property of the Database
// - coll_id is the ID property of the DocumentCollection
// - conflict_id is the ID property of the Conflict you wish to read.
var conflictLink = UriFactory.CreateConflictUri("db_id", "coll_id", "conflict_id");
Conflict conflict = await client.ReadConflictAsync(conflictLink);
Remarks
Doing a read of a resource is the most efficient way to get a resource from the service. If you know the resource's ID, do a read instead of a query by ID.
Exceptions
- ArgumentNullException
If
conflictUri
is not set.- DocumentClientException
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:
StatusCode Reason for exception 404 NotFound - This means the resource you tried to read did not exist. 429 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.
- See Also
-
ResourceResponse<TResource>
ReadConflictFeedAsync(string, FeedOptions)
Reads the feed (sequence) of Conflict for a collection from the Azure Cosmos DB service as an asynchronous operation.
public Task<FeedResponse<Conflict>> ReadConflictFeedAsync(string conflictsLink, FeedOptions options = null)
Parameters
conflictsLink
stringThe SelfLink of the resources to be read. E.g. /dbs/db_rid/colls/coll_rid/conflicts/
options
FeedOptions(Optional) The request options for the request.
Returns
- Task<FeedResponse<Conflict>>
A System.Threading.Tasks containing a ResourceResponse<TResource> which wraps a Conflict containing the read resource record.
Examples
int count = 0;
string continuation = string.Empty;
do
{
// Read the feed 10 items at a time until there are no more items to read
FeedResponse<Conflict> response = await client.ReadConflictAsync("/dbs/db_rid/colls/coll_rid/conflicts/",
new FeedOptions
{
MaxItemCount = 10,
RequestContinuation = continuation
});
// Append the item count
count += response.Count;
// Get the continuation so that we know when to stop.
continuation = response.ResponseContinuation;
} while (!string.IsNullOrEmpty(continuation));
Exceptions
- ArgumentNullException
If
conflictsLink
is not set.- DocumentClientException
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:
StatusCode Reason for exception 404 NotFound - This means the resource feed you tried to read did not exist. Check the parent rids are correct. 429 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.
- See Also
-
ResourceResponse<TResource>
ReadConflictFeedAsync(Uri, FeedOptions)
Reads the feed (sequence) of conflicts for a collection as an asynchronous operation from the Azure Cosmos DB service.
public Task<FeedResponse<Conflict>> ReadConflictFeedAsync(Uri conflictsUri, FeedOptions options = null)
Parameters
conflictsUri
Urithe URI for the conflicts.
options
FeedOptionsThe request options for the request.
Returns
- Task<FeedResponse<Conflict>>
The task object representing the service response for the asynchronous operation.
ReadDatabaseAsync(string, RequestOptions)
Reads a Database from the Azure Cosmos DB service as an asynchronous operation.
public Task<ResourceResponse<Database>> ReadDatabaseAsync(string databaseLink, RequestOptions options = null)
Parameters
databaseLink
stringThe link of the Database resource to be read.
options
RequestOptions(Optional) The request options for the request.
Returns
- Task<ResourceResponse<Database>>
A System.Threading.Tasks containing a ResourceResponse<TResource> which wraps a Database containing the read resource record.
Examples
//Reads a Database resource where
// - database_id is the ID property of the Database resource you wish to read.
var dbLink = "/dbs/database_id";
Database database = await client.ReadDatabaseAsync(dbLink);
Remarks
Doing a read of a resource is the most efficient way to get a resource from the Database. If you know the resource's ID, do a read instead of a query by ID.
The example shown uses ID-based links, where the link is composed of the ID properties used when the resources were created.
You can still use the SelfLink property of the Database if you prefer. A self-link is a URI for a resource that is made up of Resource Identifiers (or the _rid properties).
ID-based links and SelfLink will both work.
The format for databaseLink
is always "/dbs/{db identifier}" only
the values within the {} change depending on which method you wish to use to address the resource.
Exceptions
- ArgumentNullException
If
databaseLink
is not set.- DocumentClientException
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:
StatusCode Reason for exception 404 NotFound - This means the resource you tried to read did not exist. 429 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.
- See Also
-
ResourceResponse<TResource>Uri
ReadDatabaseAsync(Uri, RequestOptions)
Reads a Database as an asynchronous operation from the Azure Cosmos DB service.
public Task<ResourceResponse<Database>> ReadDatabaseAsync(Uri databaseUri, RequestOptions options = null)
Parameters
databaseUri
UriA URI to the Database resource to be read.
options
RequestOptionsThe request options for the request.
Returns
- Task<ResourceResponse<Database>>
A System.Threading.Tasks containing a ResourceResponse<TResource> which wraps a Database containing the read resource record.
Examples
//Reads a Database resource where
// - db_id is the ID property of the Database you wish to read.
var dbLink = UriFactory.CreateDatabaseUri("db_id");
Database database = await client.ReadDatabaseAsync(dbLink);
Remarks
Doing a read of a resource is the most efficient way to get a resource from the service. If you know the resource's ID, do a read instead of a query by ID.
Exceptions
- ArgumentNullException
If
databaseUri
is not set.- DocumentClientException
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:
StatusCode Reason for exception 404 NotFound - This means the resource you tried to read did not exist. 429 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.
- See Also
-
ResourceResponse<TResource>
ReadDatabaseFeedAsync(FeedOptions)
Reads the feed (sequence) of Database for a database account from the Azure Cosmos DB service as an asynchronous operation.
public Task<FeedResponse<Database>> ReadDatabaseFeedAsync(FeedOptions options = null)
Parameters
options
FeedOptions(Optional) The request options for the request.
Returns
- Task<FeedResponse<Database>>
A System.Threading.Tasks containing a ResourceResponse<TResource> which wraps a Database containing the read resource record.
Examples
int count = 0;
string continuation = string.Empty;
do
{
// Read the feed 10 items at a time until there are no more items to read
FeedResponse<Database> response = await client.ReadDatabaseFeedAsync(new FeedOptions
{
MaxItemCount = 10,
RequestContinuation = continuation
});
// Append the item count
count += response.Count;
// Get the continuation so that we know when to stop.
continuation = response.ResponseContinuation;
} while (!string.IsNullOrEmpty(continuation));
Exceptions
- DocumentClientException
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:
StatusCode Reason for exception 429 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.
- See Also
-
ResourceResponse<TResource>
ReadDocumentAsync(string, RequestOptions, CancellationToken)
Reads a Document from the Azure Cosmos DB service as an asynchronous operation.
public Task<ResourceResponse<Document>> ReadDocumentAsync(string documentLink, RequestOptions options = null, CancellationToken cancellationToken = default)
Parameters
documentLink
stringThe link for the document to be read.
options
RequestOptions(Optional) The request options for the request.
cancellationToken
CancellationToken(Optional) A CancellationToken that can be used by other objects or threads to receive notice of cancellation.
Returns
- Task<ResourceResponse<Document>>
A System.Threading.Tasks containing a ResourceResponse<TResource> which wraps a Document containing the read resource record.
Examples
//This reads a document record from a database & collection where
// - sample_database is the ID of the database
// - sample_collection is the ID of the collection
// - document_id is the ID of the document resource
var docLink = "dbs/sample_database/colls/sample_collection/docs/document_id";
Document doc = await client.ReadDocumentAsync(docLink);
Remarks
Doing a read of a resource is the most efficient way to get a resource from the Database. If you know the resource's ID, do a read instead of a query by ID.
The example shown uses ID-based links, where the link is composed of the ID properties used when the resources were created.
You can still use the SelfLink property of the Document if you prefer. A self-link is a URI for a resource that is made up of Resource Identifiers (or the _rid properties).
ID-based links and SelfLink will both work.
The format for documentLink
is always "dbs/{db identifier}/colls/{coll identifier}/docs/{doc identifier}" only
the values within the {} change depending on which method you wish to use to address the resource.
Exceptions
- ArgumentNullException
If
documentLink
is not set.- DocumentClientException
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:
StatusCode Reason for exception 404 NotFound - This means the resource you tried to read did not exist. 429 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.
- See Also
-
ResourceResponse<TResource>Uri
ReadDocumentAsync(Uri, RequestOptions, CancellationToken)
Reads a Document as an asynchronous operation from the Azure Cosmos DB service.
public Task<ResourceResponse<Document>> ReadDocumentAsync(Uri documentUri, RequestOptions options = null, CancellationToken cancellationToken = default)
Parameters
documentUri
UriA URI to the Document resource to be read.
options
RequestOptionsThe request options for the request.
cancellationToken
CancellationToken(Optional) CancellationToken representing request cancellation.
Returns
- Task<ResourceResponse<Document>>
A System.Threading.Tasks containing a ResourceResponse<TResource> which wraps a Document containing the read resource record.
Examples
//Reads a Document resource where
// - db_id is the ID property of the Database
// - coll_id is the ID property of the DocumentCollection
// - doc_id is the ID property of the Document you wish to read.
var docUri = UriFactory.CreateDocumentUri("db_id", "coll_id", "doc_id");
Document document = await client.ReadDocumentAsync(docUri);
Remarks
Doing a read of a resource is the most efficient way to get a resource from the service. If you know the resource's ID, do a read instead of a query by ID.
Exceptions
- ArgumentNullException
If
documentUri
is not set.- DocumentClientException
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 reading a Document are:
StatusCode Reason for exception 404 NotFound - This means the resource you tried to read did not exist. 429 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.
- See Also
-
ResourceResponse<TResource>
ReadDocumentAsync<T>(string, RequestOptions, CancellationToken)
Reads a Document as a generic type T from the Azure Cosmos DB service as an asynchronous operation.
public Task<DocumentResponse<T>> ReadDocumentAsync<T>(string documentLink, RequestOptions options = null, CancellationToken cancellationToken = default)
Parameters
documentLink
stringThe link for the document to be read.
options
RequestOptions(Optional) The request options for the request.
cancellationToken
CancellationToken(Optional) A CancellationToken that can be used by other objects or threads to receive notice of cancellation.
Returns
- Task<DocumentResponse<T>>
A System.Threading.Tasks containing a DocumentResponse<TDocument> which wraps a Document containing the read resource record.
Type Parameters
T
Examples
//This reads a document record from a database & collection where
// - sample_database is the ID of the database
// - sample_collection is the ID of the collection
// - document_id is the ID of the document resource
var docLink = "dbs/sample_database/colls/sample_collection/docs/document_id";
Customer customer = await client.ReadDocumentAsync<Customer>(docLink);
Remarks
Doing a read of a resource is the most efficient way to get a resource from the Database. If you know the resource's ID, do a read instead of a query by ID.
The example shown uses ID-based links, where the link is composed of the ID properties used when the resources were created.
You can still use the SelfLink property of the Document if you prefer. A self-link is a URI for a resource that is made up of Resource Identifiers (or the _rid properties).
ID-based links and SelfLink will both work.
The format for documentLink
is always "dbs/{db identifier}/colls/{coll identifier}/docs/{doc identifier}" only
the values within the {} change depending on which method you wish to use to address the resource.
Exceptions
- ArgumentNullException
If
documentLink
is not set.- DocumentClientException
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:
StatusCode Reason for exception 404 NotFound - This means the resource you tried to read did not exist. 429 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.
- See Also
-
DocumentResponse<TDocument>Uri
ReadDocumentAsync<T>(Uri, RequestOptions, CancellationToken)
Reads a Document as a generic type T from the Azure Cosmos DB service as an asynchronous operation.
public Task<DocumentResponse<T>> ReadDocumentAsync<T>(Uri documentUri, RequestOptions options = null, CancellationToken cancellationToken = default)
Parameters
documentUri
UriA URI to the Document resource to be read.
options
RequestOptionsThe request options for the request.
cancellationToken
CancellationToken(Optional) CancellationToken representing request cancellation.
Returns
- Task<DocumentResponse<T>>
A System.Threading.Tasks containing a DocumentResponse<TDocument> which wraps a Document containing the read resource record.
Type Parameters
T
Examples
//Reads a Document resource where
// - db_id is the ID property of the Database
// - coll_id is the ID property of the DocumentCollection
// - doc_id is the ID property of the Document you wish to read.
var docUri = UriFactory.CreateDocumentUri("db_id", "coll_id", "doc_id");
Customer customer = await client.ReadDocumentAsync<Customer>(docUri);
Remarks
Doing a read of a resource is the most efficient way to get a resource from the service. If you know the resource's ID, do a read instead of a query by ID.
Exceptions
- ArgumentNullException
If
documentUri
is not set.- DocumentClientException
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 reading a Document are:
StatusCode Reason for exception 404 NotFound - This means the resource you tried to read did not exist. 429 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.
- See Also
-
DocumentResponse<TDocument>
ReadDocumentCollectionAsync(string, RequestOptions)
Reads a DocumentCollection from the Azure Cosmos DB service as an asynchronous operation.
public Task<ResourceResponse<DocumentCollection>> ReadDocumentCollectionAsync(string documentCollectionLink, RequestOptions options = null)
Parameters
documentCollectionLink
stringThe link for the DocumentCollection to be read.
options
RequestOptions(Optional) The request options for the request.
Returns
- Task<ResourceResponse<DocumentCollection>>
A System.Threading.Tasks containing a ResourceResponse<TResource> which wraps a DocumentCollection containing the read resource record.
Examples
//This reads a DocumentCollection record from a database where
// - sample_database is the ID of the database
// - collection_id is the ID of the collection resource to be read
var collLink = "/dbs/sample_database/colls/collection_id";
DocumentCollection coll = await client.ReadDocumentCollectionAsync(collLink);
Remarks
Doing a read of a resource is the most efficient way to get a resource from the Database. If you know the resource's ID, do a read instead of a query by ID.
The example shown uses ID-based links, where the link is composed of the ID properties used when the resources were created.
You can still use the SelfLink property of the DocumentCollection if you prefer. A self-link is a URI for a resource that is made up of Resource Identifiers (or the _rid properties).
ID-based links and SelfLink will both work.
The format for documentCollectionLink
is always "/dbs/{db identifier}/colls/{coll identifier}" only
the values within the {} change depending on which method you wish to use to address the resource.
Exceptions
- ArgumentNullException
If
documentCollectionLink
is not set.- DocumentClientException
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:
StatusCode Reason for exception 404 NotFound - This means the resource you tried to read did not exist. 429 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.
- See Also
-
ResourceResponse<TResource>Uri
ReadDocumentCollectionAsync(Uri, RequestOptions)
Reads a DocumentCollection as an asynchronous operation from the Azure Cosmos DB service.
public Task<ResourceResponse<DocumentCollection>> ReadDocumentCollectionAsync(Uri documentCollectionUri, RequestOptions options = null)
Parameters
documentCollectionUri
UriA URI to the DocumentCollection resource to be read.
options
RequestOptionsThe request options for the request.
Returns
- Task<ResourceResponse<DocumentCollection>>
A System.Threading.Tasks containing a ResourceResponse<TResource> which wraps a DocumentCollection containing the read resource record.
Examples
//Reads a Document resource where
// - db_id is the ID property of the Database
// - coll_id is the ID property of the DocumentCollection you wish to read.
var collLink = UriFactory.CreateCollectionUri("db_id", "coll_id");
DocumentCollection coll = await client.ReadDocumentCollectionAsync(collLink);
Remarks
Doing a read of a resource is the most efficient way to get a resource from the service. If you know the resource's ID, do a read instead of a query by ID.
Exceptions
- ArgumentNullException
If
documentCollectionUri
is not set.- DocumentClientException
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:
StatusCode Reason for exception 404 NotFound - This means the resource you tried to read did not exist. 429 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.
- See Also
-
ResourceResponse<TResource>
ReadDocumentCollectionFeedAsync(string, FeedOptions)
Reads the feed (sequence) of DocumentCollection for a database from the Azure Cosmos DB service as an asynchronous operation.
public Task<FeedResponse<DocumentCollection>> ReadDocumentCollectionFeedAsync(string collectionsLink, FeedOptions options = null)
Parameters
collectionsLink
stringThe SelfLink of the resources to be read. E.g. /dbs/db_rid/colls/
options
FeedOptions(Optional) The request options for the request.
Returns
- Task<FeedResponse<DocumentCollection>>
A System.Threading.Tasks containing a ResourceResponse<TResource> which wraps a DocumentCollection containing the read resource record.
Examples
int count = 0;
string continuation = string.Empty;
do
{
// Read the feed 10 items at a time until there are no more items to read
FeedResponse<DocumentCollection> response = await client.ReadDocumentCollectionFeedAsync("/dbs/db_rid/colls/",
new FeedOptions
{
MaxItemCount = 10,
RequestContinuation = continuation
});
// Append the item count
count += response.Count;
// Get the continuation so that we know when to stop.
continuation = response.ResponseContinuation;
} while (!string.IsNullOrEmpty(continuation));
Exceptions
- ArgumentNullException
If
collectionsLink
is not set.- DocumentClientException
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:
StatusCode Reason for exception 404 NotFound - This means the resource feed you tried to read did not exist. Check the parent rids are correct. 429 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.
- See Also
-
ResourceResponse<TResource>
ReadDocumentCollectionFeedAsync(Uri, FeedOptions)
Reads the feed (sequence) of collections for a database as an asynchronous operation from the Azure Cosmos DB service.
public Task<FeedResponse<DocumentCollection>> ReadDocumentCollectionFeedAsync(Uri documentCollectionsUri, FeedOptions options = null)
Parameters
documentCollectionsUri
Urithe URI for the document collections.
options
FeedOptionsThe request options for the request.
Returns
- Task<FeedResponse<DocumentCollection>>
The task object representing the service response for the asynchronous operation.
ReadDocumentFeedAsync(string, FeedOptions, CancellationToken)
Reads the feed (sequence) of documents for a specified collection from the Azure Cosmos DB service. This takes returns a ResourceResponse<TResource> which will contain an enumerable list of dynamic objects.
public Task<FeedResponse<dynamic>> ReadDocumentFeedAsync(string documentsLink, FeedOptions options = null, CancellationToken cancellationToken = default)
Parameters
documentsLink
stringThe SelfLink of the resources to be read. E.g. /dbs/db_rid/colls/coll_rid/docs/
options
FeedOptions(Optional) The request options for the request.
cancellationToken
CancellationToken(Optional) A CancellationToken that can be used by other objects or threads to receive notice of cancellation.
Returns
- Task<FeedResponse<dynamic>>
A System.Threading.Tasks containing a ResourceResponse<TResource> containing dynamic objects representing the items in the feed.
Examples
int count = 0;
string continuation = string.Empty;
do
{
// Read the feed 10 items at a time until there are no more items to read
FeedResponse<dynamic> response = await client.ReadDocumentFeedAsync("/dbs/db_rid/colls/coll_rid/docs/",
new FeedOptions
{
MaxItemCount = 10,
RequestContinuation = continuation
});
// Append the item count
count += response.Count;
// Get the continuation so that we know when to stop.
continuation = response.ResponseContinuation;
} while (!string.IsNullOrEmpty(continuation));
Remarks
Instead of FeedResponse{Document} this method takes advantage of dynamic objects in .NET. This way a single feed result can contain any kind of Document, or POCO object. This is important becuse a DocumentCollection can contain different kinds of documents.
Exceptions
- ArgumentNullException
If
documentsLink
is not set.- DocumentClientException
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:
StatusCode Reason for exception 404 NotFound - This means the resource feed you tried to read did not exist. Check the parent rids are correct. 429 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.
- See Also
-
ResourceResponse<TResource>
ReadDocumentFeedAsync(Uri, FeedOptions, CancellationToken)
Reads the feed (sequence) of documents for a collection as an asynchronous operation from the Azure Cosmos DB service.
public Task<FeedResponse<dynamic>> ReadDocumentFeedAsync(Uri documentsUri, FeedOptions options = null, CancellationToken cancellationToken = default)
Parameters
documentsUri
Urithe URI for the documents.
options
FeedOptionsThe request options for the request.
cancellationToken
CancellationToken(Optional) CancellationToken representing request cancellation.
Returns
- Task<FeedResponse<dynamic>>
The task object representing the service response for the asynchronous operation.
ReadMediaAsync(string, CancellationToken)
Retrieves the specified attachment content (aka media) from the Azure Cosmos DB service.
public Task<MediaResponse> ReadMediaAsync(string mediaLink, CancellationToken cancellationToken = default)
Parameters
mediaLink
stringThe link for the media to read. E.g. /media/media_rid
cancellationToken
CancellationToken(Optional) A CancellationToken that can be used by other objects or threads to receive notice of cancellation.
Returns
- Task<MediaResponse>
The task object representing the service response for the asynchronous operation.
Exceptions
- ArgumentNullException
If
mediaLink
is not set.- ArgumentException
If
mediaLink
is not in the form of /media/{mediaId}.
- See Also
ReadMediaMetadataAsync(string)
Retrieves the metadata associated with the specified attachment content (aka media) as an asynchronous operation from the Azure Cosmos DB service.
public Task<MediaResponse> ReadMediaMetadataAsync(string mediaLink)
Parameters
mediaLink
stringThe link for the media to read metadata for. E.g. /media/media_rid
Returns
- Task<MediaResponse>
The task object representing the service response for the asynchronous operation.
Exceptions
- ArgumentNullException
If
mediaLink
is not set.- ArgumentException
If
mediaLink
is not in the form of /media/{mediaId}.
- See Also
ReadOfferAsync(string)
Reads an Offer from the Azure Cosmos DB service as an asynchronous operation.
public Task<ResourceResponse<Offer>> ReadOfferAsync(string offerLink)
Parameters
offerLink
stringThe link to the Offer to be read.
Returns
- Task<ResourceResponse<Offer>>
A System.Threading.Tasks containing a ResourceResponse<TResource> which wraps a Offer containing the read resource record.
Examples
//Reads an Offer resource from a Database
// - offer_id is the ID of the offer to be read
var offerLink = "/offers/offer_id";
Offer offer = await client.ReadOfferAsync(offerLink);
Remarks
Doing a read of a resource is the most efficient way to get a resource from the Database. If you know the resource's ID, do a read instead of a query by ID.
For an Offer, id is always generated internally by the system when the linked resource is created. id and _rid are always the same for Offer.
Refer to https://docs.microsoft.com/en-us/azure/cosmos-db/how-to-provision-container-throughput to learn more about minimum throughput of a Cosmos container (or a database) To retrieve the minimum throughput for a collection/database, use the following sample
// Find the offer for the collection by SelfLink
Offer offer = client.CreateOfferQuery(
string.Format("SELECT * FROM offers o WHERE o.resource = '{0}'", collectionSelfLink)).AsEnumerable().FirstOrDefault();
ResourceResponse<Offer> response = await client.ReadOfferAsync(offer.SelfLink);
string minimumRUsForCollection = response.ResponseHeaders["x-ms-cosmos-min-throughput"];
Exceptions
- ArgumentNullException
If
offerLink
is not set.- DocumentClientException
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:
StatusCode Reason for exception 404 NotFound - This means the resource you tried to read did not exist. 429 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.
- See Also
-
ResourceResponse<TResource>Uri
ReadOffersFeedAsync(FeedOptions)
Reads the feed (sequence) of Offer for a database account from the Azure Cosmos DB service as an asynchronous operation.
public Task<FeedResponse<Offer>> ReadOffersFeedAsync(FeedOptions options = null)
Parameters
options
FeedOptions(Optional) The request options for the request.
Returns
- Task<FeedResponse<Offer>>
A System.Threading.Tasks containing a ResourceResponse<TResource> which wraps a Offer containing the read resource record.
Examples
int count = 0;
string continuation = string.Empty;
do
{
// Read the feed 10 items at a time until there are no more items to read
FeedResponse<Offer> response = await client.ReadOfferAsync(new FeedOptions
{
MaxItemCount = 10,
RequestContinuation = continuation
});
// Append the item count
count += response.Count;
// Get the continuation so that we know when to stop.
continuation = response.ResponseContinuation;
} while (!string.IsNullOrEmpty(continuation));
Exceptions
- DocumentClientException
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:
StatusCode Reason for exception 429 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.
- See Also
-
ResourceResponse<TResource>
ReadPartitionKeyRangeFeedAsync(string, FeedOptions)
Reads the feed (sequence) of PartitionKeyRange for a database account from the Azure Cosmos DB service as an asynchronous operation.
public Task<FeedResponse<PartitionKeyRange>> ReadPartitionKeyRangeFeedAsync(string partitionKeyRangesOrCollectionLink, FeedOptions options = null)
Parameters
partitionKeyRangesOrCollectionLink
stringThe link of the resources to be read, or owner collection link, SelfLink or AltLink. E.g. /dbs/db_rid/colls/coll_rid/pkranges
options
FeedOptions(Optional) The request options for the request.
Returns
- Task<FeedResponse<PartitionKeyRange>>
A System.Threading.Tasks containing a ResourceResponse<TResource> which wraps a Database containing the read resource record.
Examples
FeedResponse<PartitionKeyRange> response = null;
List<string> ids = new List<string>();
do
{
response = await client.ReadPartitionKeyRangeFeedAsync(collection.SelfLink, new FeedOptions { MaxItemCount = 1000 });
foreach (var item in response)
{
ids.Add(item.Id);
}
}
while (!string.IsNullOrEmpty(response.ResponseContinuation));
Exceptions
- DocumentClientException
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:
StatusCode Reason for exception 429 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.
- See Also
-
FeedResponse<T>
ReadPartitionKeyRangeFeedAsync(Uri, FeedOptions)
Reads the feed (sequence) of PartitionKeyRange for a database account from the Azure Cosmos DB service as an asynchronous operation.
public Task<FeedResponse<PartitionKeyRange>> ReadPartitionKeyRangeFeedAsync(Uri partitionKeyRangesOrCollectionUri, FeedOptions options = null)
Parameters
partitionKeyRangesOrCollectionUri
UriThe Uri for partition key ranges, or owner collection.
options
FeedOptions(Optional) The request options for the request.
Returns
- Task<FeedResponse<PartitionKeyRange>>
A System.Threading.Tasks containing a ResourceResponse<TResource> which wraps a PartitionKeyRange containing the read resource record.
Examples
Uri partitionKeyRangesUri = UriFactory.CreatePartitionKeyRangesUri(database.Id, collection.Id);
FeedResponse<PartitionKeyRange> response = null;
List<string> ids = new List<string>();
do
{
response = await client.ReadPartitionKeyRangeFeedAsync(partitionKeyRangesUri, new FeedOptions { MaxItemCount = 1000 });
foreach (var item in response)
{
ids.Add(item.Id);
}
}
while (!string.IsNullOrEmpty(response.ResponseContinuation));
- See Also
-
FeedResponse<T>
ReadPermissionAsync(string, RequestOptions)
Reads a Permission from the Azure Cosmos DB service as an asynchronous operation.
public Task<ResourceResponse<Permission>> ReadPermissionAsync(string permissionLink, RequestOptions options = null)
Parameters
permissionLink
stringThe link for the Permission resource to be read.
options
RequestOptions(Optional) The request options for the request.
Returns
- Task<ResourceResponse<Permission>>
A System.Threading.Tasks containing a ResourceResponse<TResource> which wraps a Permission containing the read resource record.
Examples
//Reads a Permission resource from a Database and User where
// - sample_database is the ID of the database
// - sample_user is the ID of the user
// - permission_id is the ID of the permission to be read
var permissionLink = "/dbs/sample_database/users/sample_user/permissions/permission_id";
Permission permission = await client.ReadPermissionAsync(permissionLink);
Remarks
Doing a read of a resource is the most efficient way to get a resource from the Database. If you know the resource's ID, do a read instead of a query by ID.
The example shown uses ID-based links, where the link is composed of the ID properties used when the resources were created.
You can still use the SelfLink property of the Permission if you prefer. A self-link is a URI for a resource that is made up of Resource Identifiers (or the _rid properties).
ID-based links and SelfLink will both work.
The format for permissionLink
is always "/dbs/{db identifier}/users/{user identifier}/permissions/{permission identifier}"
only the values within the {...} change depending on which method you wish to use to address the resource.
Exceptions
- ArgumentNullException
If
permissionLink
is not set.- DocumentClientException
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:
StatusCode Reason for exception 404 NotFound - This means the resource you tried to read did not exist. 429 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.
- See Also
-
ResourceResponse<TResource>Uri
ReadPermissionAsync(Uri, RequestOptions)
Reads a Permission resource as an asynchronous operation from the Azure Cosmos DB service.
public Task<ResourceResponse<Permission>> ReadPermissionAsync(Uri permissionUri, RequestOptions options = null)
Parameters
permissionUri
UriA URI to the Permission resource to be read.
options
RequestOptionsThe request options for the request.
Returns
- Task<ResourceResponse<Permission>>
A System.Threading.Tasks containing a ResourceResponse<TResource> which wraps a Permission containing the read resource record.
Examples
//Reads a Permission resource where
// - db_id is the ID property of the Database
// - user_id is the ID property of the User
// - permission_id is the ID property of the Permission you wish to read.
var permissionLink = UriFactory.CreatePermissionUri("db_id", "coll_id", "user_id");
Permission permission = await client.ReadPermissionAsync(permissionLink);
Remarks
Doing a read of a resource is the most efficient way to get a resource from the service. If you know the resource's ID, do a read instead of a query by ID.
Exceptions
- ArgumentNullException
If
permissionUri
is not set.- DocumentClientException
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:
StatusCode Reason for exception 404 NotFound - This means the resource you tried to read did not exist. 429 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.
- See Also
-
ResourceResponse<TResource>
ReadPermissionFeedAsync(string, FeedOptions)
Reads the feed (sequence) of Permission for a user from the Azure Cosmos DB service as an asynchronous operation.
public Task<FeedResponse<Permission>> ReadPermissionFeedAsync(string permissionsLink, FeedOptions options = null)
Parameters
permissionsLink
stringThe SelfLink of the resources to be read. E.g. /dbs/db_rid/users/user_rid/permissions/
options
FeedOptions(Optional) The request options for the request.
Returns
- Task<FeedResponse<Permission>>
A System.Threading.Tasks containing a ResourceResponse<TResource> which wraps a Permission containing the read resource record.
Examples
int count = 0;
string continuation = string.Empty;
do
{
// Read the feed 10 items at a time until there are no more items to read
FeedResponse<Permission> response = await client.ReadPermissionFeedAsync("/dbs/db_rid/users/user_rid/permissions/",
new FeedOptions
{
MaxItemCount = 10,
RequestContinuation = continuation
});
// Append the item count
count += response.Count;
// Get the continuation so that we know when to stop.
continuation = response.ResponseContinuation;
} while (!string.IsNullOrEmpty(continuation));
Exceptions
- ArgumentNullException
If
permissionsLink
is not set.- DocumentClientException
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:
StatusCode Reason for exception 404 NotFound - This means the resource feed you tried to read did not exist. Check the parent rids are correct. 429 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.
- See Also
-
ResourceResponse<TResource>
ReadPermissionFeedAsync(Uri, FeedOptions)
Reads the feed (sequence) of permissions for a user as an asynchronous operation from the Azure Cosmos DB service.
public Task<FeedResponse<Permission>> ReadPermissionFeedAsync(Uri permissionsUri, FeedOptions options = null)
Parameters
permissionsUri
Urithe URI for the permissions.
options
FeedOptionsThe request options for the request.
Returns
- Task<FeedResponse<Permission>>
The task object representing the service response for the asynchronous operation.
ReadStoredProcedureAsync(string, RequestOptions)
Reads a StoredProcedure from the Azure Cosmos DB service as an asynchronous operation.
public Task<ResourceResponse<StoredProcedure>> ReadStoredProcedureAsync(string storedProcedureLink, RequestOptions options = null)
Parameters
storedProcedureLink
stringThe link of the stored procedure to be read.
options
RequestOptions(Optional) The request options for the request.
Returns
- Task<ResourceResponse<StoredProcedure>>
A System.Threading.Tasks containing a ResourceResponse<TResource> which wraps a StoredProcedure containing the read resource record.
Examples
//Reads a StoredProcedure from a Database and DocumentCollection where
// - sample_database is the ID of the database
// - sample_collection is the ID of the collection
// - sproc_id is the ID of the stored procedure to be read
var sprocLink = "/dbs/sample_database/colls/sample_collection/sprocs/sproc_id";
StoredProcedure sproc = await client.ReadStoredProcedureAsync(sprocLink);
Remarks
Doing a read of a resource is the most efficient way to get a resource from the Database. If you know the resource's ID, do a read instead of a query by ID.
The example shown uses ID-based links, where the link is composed of the ID properties used when the resources were created.
You can still use the SelfLink property of the Stored Procedure if you prefer. A self-link is a URI for a resource that is made up of Resource Identifiers (or the _rid properties).
ID-based links and SelfLink will both work.
The format for storedProcedureLink
is always "/dbs/{db identifier}/colls/{coll identifier}/sprocs/{sproc identifier}"
only the values within the {...} change depending on which method you wish to use to address the resource.
Exceptions
- ArgumentNullException
If
storedProcedureLink
is not set.- DocumentClientException
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:
StatusCode Reason for exception 404 NotFound - This means the resource you tried to read did not exist. 429 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.
- See Also
-
ResourceResponse<TResource>Uri
ReadStoredProcedureAsync(Uri, RequestOptions)
Reads a StoredProcedure as an asynchronous operation from the Azure Cosmos DB service.
public Task<ResourceResponse<StoredProcedure>> ReadStoredProcedureAsync(Uri storedProcedureUri, RequestOptions options = null)
Parameters
storedProcedureUri
UriA URI to the StoredProcedure resource to be read.
options
RequestOptionsThe request options for the request.
Returns
- Task<ResourceResponse<StoredProcedure>>
A System.Threading.Tasks containing a ResourceResponse<TResource> which wraps a StoredProcedure containing the read resource record.
Examples
//Reads a StoredProcedure resource where
// - db_id is the ID property of the Database
// - coll_id is the ID property of the DocumentCollection
// - sproc_id is the ID property of the StoredProcedure you wish to read.
var sprocLink = UriFactory.CreateStoredProcedureUri("db_id", "coll_id", "sproc_id");
StoredProcedure sproc = await client.ReadStoredProcedureAsync(sprocLink);
Remarks
Doing a read of a resource is the most efficient way to get a resource from the service. If you know the resource's ID, do a read instead of a query by ID.
Exceptions
- ArgumentNullException
If
storedProcedureUri
is not set.- DocumentClientException
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:
StatusCode Reason for exception 404 NotFound - This means the resource you tried to read did not exist. 429 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.
- See Also
-
ResourceResponse<TResource>
ReadStoredProcedureFeedAsync(string, FeedOptions)
Reads the feed (sequence) of StoredProcedure for a collection from the Azure Cosmos DB service as an asynchronous operation.
public Task<FeedResponse<StoredProcedure>> ReadStoredProcedureFeedAsync(string storedProceduresLink, FeedOptions options = null)
Parameters
storedProceduresLink
stringThe SelfLink of the resources to be read. E.g. /dbs/db_rid/colls/col_rid/sprocs/
options
FeedOptions(Optional) The request options for the request.
Returns
- Task<FeedResponse<StoredProcedure>>
A System.Threading.Tasks containing a ResourceResponse<TResource> which wraps a StoredProcedure containing the read resource record.
Examples
int count = 0;
string continuation = string.Empty;
do
{
// Read the feed 10 items at a time until there are no more items to read
FeedResponse<StoredProcedure> response = await client.ReadStoredProcedureFeedAsync("/dbs/db_rid/colls/col_rid/sprocs/",
new FeedOptions
{
MaxItemCount = 10,
RequestContinuation = continuation
});
// Append the item count
count += response.Count;
// Get the continuation so that we know when to stop.
continuation = response.ResponseContinuation;
} while (!string.IsNullOrEmpty(continuation));
Exceptions
- ArgumentNullException
If
storedProceduresLink
is not set.- DocumentClientException
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:
StatusCode Reason for exception 404 NotFound - This means the resource feed you tried to read did not exist. Check the parent rids are correct. 429 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.
- See Also
-
ResourceResponse<TResource>
ReadStoredProcedureFeedAsync(Uri, FeedOptions)
Reads the feed (sequence) of stored procedures for a collection as an asynchronous operation from the Azure Cosmos DB service.
public Task<FeedResponse<StoredProcedure>> ReadStoredProcedureFeedAsync(Uri storedProceduresUri, FeedOptions options = null)
Parameters
storedProceduresUri
Urithe URI for the stored procedures.
options
FeedOptionsThe request options for the request.
Returns
- Task<FeedResponse<StoredProcedure>>
The task object representing the service response for the asynchronous operation.
ReadTriggerAsync(string, RequestOptions)
Reads a Trigger from the Azure Cosmos DB service as an asynchronous operation.
public Task<ResourceResponse<Trigger>> ReadTriggerAsync(string triggerLink, RequestOptions options = null)
Parameters
triggerLink
stringThe link to the Trigger to be read.
options
RequestOptions(Optional) The request options for the request.
Returns
- Task<ResourceResponse<Trigger>>
A System.Threading.Tasks containing a ResourceResponse<TResource> which wraps a Trigger containing the read resource record.
Examples
//Reads a Trigger from a Database and DocumentCollection where
// - sample_database is the ID of the database
// - sample_collection is the ID of the collection
// - trigger_id is the ID of the trigger to be read
var triggerLink = "/dbs/sample_database/colls/sample_collection/triggers/trigger_id";
Trigger trigger = await client.ReadTriggerAsync(triggerLink);
Remarks
Doing a read of a resource is the most efficient way to get a resource from the Database. If you know the resource's ID, do a read instead of a query by ID.
The example shown uses ID-based links, where the link is composed of the ID properties used when the resources were created.
You can still use the SelfLink property of the Trigger if you prefer. A self-link is a URI for a resource that is made up of Resource Identifiers (or the _rid properties).
ID-based links and SelfLink will both work.
The format for triggerLink
is always "/dbs/{db identifier}/colls/{coll identifier}/triggers/{trigger identifier}"
only the values within the {...} change depending on which method you wish to use to address the resource.
Exceptions
- ArgumentNullException
If
triggerLink
is not set.- DocumentClientException
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:
StatusCode Reason for exception 404 NotFound - This means the resource you tried to read did not exist. 429 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.
- See Also
-
ResourceResponse<TResource>Uri
ReadTriggerAsync(Uri, RequestOptions)
Reads a Trigger as an asynchronous operation from the Azure Cosmos DB service.
public Task<ResourceResponse<Trigger>> ReadTriggerAsync(Uri triggerUri, RequestOptions options = null)
Parameters
triggerUri
UriA URI to the Trigger resource to be read.
options
RequestOptionsThe request options for the request.
Returns
- Task<ResourceResponse<Trigger>>
A System.Threading.Tasks containing a ResourceResponse<TResource> which wraps a Trigger containing the read resource record.
Examples
//Reads a Trigger resource where
// - db_id is the ID property of the Database
// - coll_id is the ID property of the DocumentCollection
// - trigger_id is the ID property of the Trigger you wish to read.
var triggerLink = UriFactory.CreateTriggerUri("db_id", "coll_id", "trigger_id");
Trigger trigger = await client.ReadTriggerAsync(triggerLink);
Remarks
Doing a read of a resource is the most efficient way to get a resource from the service. If you know the resource's ID, do a read instead of a query by ID.
Exceptions
- ArgumentNullException
If
triggerUri
is not set.- DocumentClientException
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:
StatusCode Reason for exception 404 NotFound - This means the resource you tried to read did not exist. 429 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.
- See Also
-
ResourceResponse<TResource>
ReadTriggerFeedAsync(string, FeedOptions)
Reads the feed (sequence) of Trigger for a collection from the Azure Cosmos DB service as an asynchronous operation.
public Task<FeedResponse<Trigger>> ReadTriggerFeedAsync(string triggersLink, FeedOptions options = null)
Parameters
triggersLink
stringThe SelfLink of the resources to be read. E.g. /dbs/db_rid/colls/col_rid/triggers/
options
FeedOptions(Optional) The request options for the request.
Returns
- Task<FeedResponse<Trigger>>
A System.Threading.Tasks containing a ResourceResponse<TResource> which wraps a Trigger containing the read resource record.
Examples
int count = 0;
string continuation = string.Empty;
do
{
// Read the feed 10 items at a time until there are no more items to read
FeedResponse<Trigger> response = await client.ReadTriggerFeedAsync("/dbs/db_rid/colls/col_rid/triggers/",
new FeedOptions
{
MaxItemCount = 10,
RequestContinuation = continuation
});
// Append the item count
count += response.Count;
// Get the continuation so that we know when to stop.
continuation = response.ResponseContinuation;
} while (!string.IsNullOrEmpty(continuation));
Exceptions
- ArgumentNullException
If
triggersLink
is not set.- DocumentClientException
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:
StatusCode Reason for exception 404 NotFound - This means the resource feed you tried to read did not exist. Check the parent rids are correct. 429 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.
- See Also
-
ResourceResponse<TResource>
ReadTriggerFeedAsync(Uri, FeedOptions)
Reads the feed (sequence) of triggers for a collection as an asynchronous operation from the Azure Cosmos DB service.
public Task<FeedResponse<Trigger>> ReadTriggerFeedAsync(Uri triggersUri, FeedOptions options = null)
Parameters
triggersUri
Urithe URI for the triggers.
options
FeedOptionsThe request options for the request.
Returns
- Task<FeedResponse<Trigger>>
The task object representing the service response for the asynchronous operation.
ReadUserAsync(string, RequestOptions)
Reads a User from the Azure Cosmos DB service as an asynchronous operation.
public Task<ResourceResponse<User>> ReadUserAsync(string userLink, RequestOptions options = null)
Parameters
userLink
stringThe link to the User resource to be read.
options
RequestOptions(Optional) The request options for the request.
Returns
- Task<ResourceResponse<User>>
A System.Threading.Tasks containing a ResourceResponse<TResource> which wraps a User containing the read resource record.
Examples
//Reads a User resource from a Database
// - sample_database is the ID of the database
// - user_id is the ID of the user to be read
var userLink = "/dbs/sample_database/users/user_id";
User user = await client.ReadUserAsync(userLink);
Remarks
Doing a read of a resource is the most efficient way to get a resource from the Database. If you know the resource's ID, do a read instead of a query by ID.
The example shown uses ID-based links, where the link is composed of the ID properties used when the resources were created.
You can still use the SelfLink property of the User if you prefer. A self-link is a URI for a resource that is made up of Resource Identifiers (or the _rid properties).
ID-based links and SelfLink will both work.
The format for userLink
is always "/dbs/{db identifier}/users/{user identifier}"
only the values within the {...} change depending on which method you wish to use to address the resource.
Exceptions
- ArgumentNullException
If
userLink
is not set.- DocumentClientException
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:
StatusCode Reason for exception 404 NotFound - This means the resource you tried to read did not exist. 429 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.
- See Also
-
ResourceResponse<TResource>Uri
ReadUserAsync(Uri, RequestOptions)
Reads a User as an asynchronous operation from the Azure Cosmos DB service.
public Task<ResourceResponse<User>> ReadUserAsync(Uri userUri, RequestOptions options = null)
Parameters
userUri
UriA URI to the User resource to be read.
options
RequestOptionsThe request options for the request.
Returns
- Task<ResourceResponse<User>>
A System.Threading.Tasks containing a ResourceResponse<TResource> which wraps a User containing the read resource record.
Examples
//Reads a User resource where
// - db_id is the ID property of the Database
// - user_id is the ID property of the User you wish to read.
var userLink = UriFactory.CreateUserUri("db_id", "user_id");
User user = await client.ReadUserAsync(userLink);
Remarks
Doing a read of a resource is the most efficient way to get a resource from the service. If you know the resource's ID, do a read instead of a query by ID.
Exceptions
- ArgumentNullException
If
userUri
is not set.- DocumentClientException
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:
StatusCode Reason for exception 404 NotFound - This means the resource you tried to read did not exist. 429 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.
- See Also
-
ResourceResponse<TResource>
ReadUserDefinedFunctionAsync(string, RequestOptions)
Reads a UserDefinedFunction from the Azure Cosmos DB service as an asynchronous operation.
public Task<ResourceResponse<UserDefinedFunction>> ReadUserDefinedFunctionAsync(string functionLink, RequestOptions options = null)
Parameters
functionLink
stringThe link to the User Defined Function to be read.
options
RequestOptions(Optional) The request options for the request.
Returns
- Task<ResourceResponse<UserDefinedFunction>>
A System.Threading.Tasks containing a ResourceResponse<TResource> which wraps a UserDefinedFunction containing the read resource record.
Examples
//Reads a User Defined Function from a Database and DocumentCollection where
// - sample_database is the ID of the database
// - sample_collection is the ID of the collection
// - udf_id is the ID of the user-defined function to be read
var udfLink = "/dbs/sample_database/colls/sample_collection/udfs/udf_id";
UserDefinedFunction udf = await client.ReadUserDefinedFunctionAsync(udfLink);
Remarks
Doing a read of a resource is the most efficient way to get a resource from the Database. If you know the resource's ID, do a read instead of a query by ID.
The example shown uses ID-based links, where the link is composed of the ID properties used when the resources were created.
You can still use the SelfLink property of the User Defined Function if you prefer. A self-link is a URI for a resource that is made up of Resource Identifiers (or the _rid properties).
ID-based links and SelfLink will both work.
The format for functionLink
is always "/dbs/{db identifier}/colls/{coll identifier}/udfs/{udf identifier}"
only the values within the {...} change depending on which method you wish to use to address the resource.
Exceptions
- ArgumentNullException
If
functionLink
is not set.- DocumentClientException
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:
StatusCode Reason for exception 404 NotFound - This means the resource you tried to read did not exist. 429 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.
- See Also
-
ResourceResponse<TResource>Uri
ReadUserDefinedFunctionAsync(Uri, RequestOptions)
Reads a UserDefinedFunction as an asynchronous operation from the Azure Cosmos DB service.
public Task<ResourceResponse<UserDefinedFunction>> ReadUserDefinedFunctionAsync(Uri functionUri, RequestOptions options = null)
Parameters
functionUri
UriA URI to the User Defined Function resource to be read.
options
RequestOptionsThe request options for the request.
Returns
- Task<ResourceResponse<UserDefinedFunction>>
A System.Threading.Tasks containing a ResourceResponse<TResource> which wraps a UserDefinedFunction containing the read resource record.
Examples
//Reads a UserDefinedFunction resource where
// - db_id is the ID property of the Database
// - coll_id is the ID property of the DocumentCollection
// - udf_id is the ID property of the UserDefinedFunction you wish to read.
var udfLink = UriFactory.CreateUserDefinedFunctionUri("db_id", "coll_id", "udf_id");
UserDefinedFunction udf = await client.ReadUserDefinedFunctionAsync(udfLink);
Remarks
Doing a read of a resource is the most efficient way to get a resource from the service. If you know the resource's ID, do a read instead of a query by ID.
Exceptions
- ArgumentNullException
If
functionUri
is not set.- DocumentClientException
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:
StatusCode Reason for exception 404 NotFound - This means the resource you tried to read did not exist. 429 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.
- See Also
-
ResourceResponse<TResource>
ReadUserDefinedFunctionFeedAsync(string, FeedOptions)
Reads the feed (sequence) of UserDefinedFunction for a collection from the Azure Cosmos DB service as an asynchronous operation.
public Task<FeedResponse<UserDefinedFunction>> ReadUserDefinedFunctionFeedAsync(string userDefinedFunctionsLink, FeedOptions options = null)
Parameters
userDefinedFunctionsLink
stringThe SelfLink of the resources to be read. E.g. /dbs/db_rid/colls/col_rid/udfs/
options
FeedOptions(Optional) The request options for the request.
Returns
- Task<FeedResponse<UserDefinedFunction>>
A System.Threading.Tasks containing a ResourceResponse<TResource> which wraps a UserDefinedFunction containing the read resource record.
Examples
int count = 0;
string continuation = string.Empty;
do
{
// Read the feed 10 items at a time until there are no more items to read
FeedResponse<UserDefinedFunction> response = await client.ReadUserDefinedFunctionFeedAsync("/dbs/db_rid/colls/col_rid/udfs/",
new FeedOptions
{
MaxItemCount = 10,
RequestContinuation = continuation
});
// Append the item count
count += response.Count;
// Get the continuation so that we know when to stop.
continuation = response.ResponseContinuation;
} while (!string.IsNullOrEmpty(continuation));
Exceptions
- ArgumentNullException
If
userDefinedFunctionsLink
is not set.- DocumentClientException
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:
StatusCode Reason for exception 404 NotFound - This means the resource feed you tried to read did not exist. Check the parent rids are correct. 429 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.
- See Also
-
ResourceResponse<TResource>
ReadUserDefinedFunctionFeedAsync(Uri, FeedOptions)
Reads the feed (sequence) of user defined functions for a collection as an asynchronous operation from the Azure Cosmos DB service.
public Task<FeedResponse<UserDefinedFunction>> ReadUserDefinedFunctionFeedAsync(Uri userDefinedFunctionsUri, FeedOptions options = null)
Parameters
userDefinedFunctionsUri
Urithe URI for the user defined functions.
options
FeedOptionsThe request options for the request.
Returns
- Task<FeedResponse<UserDefinedFunction>>
The task object representing the service response for the asynchronous operation.
ReadUserFeedAsync(string, FeedOptions)
Reads the feed (sequence) of User for a database from the Azure Cosmos DB service as an asynchronous operation.
public Task<FeedResponse<User>> ReadUserFeedAsync(string usersLink, FeedOptions options = null)
Parameters
usersLink
stringThe SelfLink of the resources to be read. E.g. /dbs/db_rid/users/
options
FeedOptions(Optional) The request options for the request.
Returns
- Task<FeedResponse<User>>
A System.Threading.Tasks containing a ResourceResponse<TResource> which wraps a User containing the read resource record.
Examples
int count = 0;
string continuation = string.Empty;
do
{
// Read the feed 10 items at a time until there are no more items to read
FeedResponse<User> response = await client.ReadUserFeedAsync("/dbs/db_rid/users/",
new FeedOptions
{
MaxItemCount = 10,
RequestContinuation = continuation
});
// Append the item count
count += response.Count;
// Get the continuation so that we know when to stop.
continuation = response.ResponseContinuation;
} while (!string.IsNullOrEmpty(continuation));
Exceptions
- ArgumentNullException
If
usersLink
is not set.- DocumentClientException
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:
StatusCode Reason for exception 404 NotFound - This means the resource feed you tried to read did not exist. Check the parent rids are correct. 429 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.
- See Also
-
ResourceResponse<TResource>
ReadUserFeedAsync(Uri, FeedOptions)
Reads the feed (sequence) of users for a database as an asynchronous operation from the Azure Cosmos DB service.
public Task<FeedResponse<User>> ReadUserFeedAsync(Uri usersUri, FeedOptions options = null)
Parameters
usersUri
Urithe URI for the users.
options
FeedOptionsThe request options for the request.
Returns
- Task<FeedResponse<User>>
The task object representing the service response for the asynchronous operation.
ReplaceAttachmentAsync(Attachment, RequestOptions, CancellationToken)
Replaces a Attachment in the Azure Cosmos DB service as an asynchronous operation.
public Task<ResourceResponse<Attachment>> ReplaceAttachmentAsync(Attachment attachment, RequestOptions options = null, CancellationToken cancellationToken = default)
Parameters
attachment
AttachmentThe updated Attachment to replace the existing resource with.
options
RequestOptions(Optional) The request options for the request.
cancellationToken
CancellationToken(Optional) A CancellationToken that can be used by other objects or threads to receive notice of cancellation.
Returns
- Task<ResourceResponse<Attachment>>
A System.Threading.Tasks containing a ResourceResponse<TResource> which wraps a Attachment containing the updated resource record.
Examples
//Fetch the item to be updated
Attachment attachment = client.CreateAttachmentQuery(attachmentLink)
.Where(r => r.Id == "attachment id")
.AsEnumerable()
.SingleOrDefault();
//Update some properties on the found resource
attachment.MediaLink = "updated value";
//Now persist these changes to the database by replacing the original resource
Attachment updated = await client.ReplaceAttachmentAsync(attachment);
Exceptions
- ArgumentNullException
If
attachment
is not set.- DocumentClientException
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:
StatusCode Reason for exception 404 NotFound - This means the resource you tried to delete did not exist.
- See Also
-
ResourceResponse<TResource>
ReplaceAttachmentAsync(Uri, Attachment, RequestOptions, CancellationToken)
Replaces an attachment as an asynchronous operation in the Azure Cosmos DB service.
public Task<ResourceResponse<Attachment>> ReplaceAttachmentAsync(Uri attachmentUri, Attachment attachment, RequestOptions options = null, CancellationToken cancellationToken = default)
Parameters
attachmentUri
Urithe URI of the attachment to be updated.
attachment
Attachmentthe attachment resource.
options
RequestOptionsThe request options for the request.
cancellationToken
CancellationToken(Optional) CancellationToken representing request cancellation.
Returns
- Task<ResourceResponse<Attachment>>
The task object representing the service response for the asynchronous operation.
ReplaceDocumentAsync(Document, RequestOptions, CancellationToken)
Replaces a Document in the Azure Cosmos DB service as an asynchronous operation.
public Task<ResourceResponse<Document>> ReplaceDocumentAsync(Document document, RequestOptions options = null, CancellationToken cancellationToken = default)
Parameters
document
DocumentThe updated Document to replace the existing resource with.
options
RequestOptions(Optional) The request options for the request.
cancellationToken
CancellationToken(Optional) A CancellationToken that can be used by other objects or threads to receive notice of cancellation.
Returns
- Task<ResourceResponse<Document>>
A System.Threading.Tasks containing a ResourceResponse<TResource> which wraps a Document containing the updated resource record.
Examples
This example uses Document and takes advantage of the fact that it is a dynamic object and uses SetProperty to dynamically update properties on the document
//Fetch the Document to be updated
Document doc = client.CreateDocumentQuery<Document>(collectionLink)
.Where(r => r.Id == "doc id")
.AsEnumerable()
.SingleOrDefault();
//Update some properties on the found resource
doc.SetPropertyValue("MyProperty", "updated value");
//Now persist these changes to the database by replacing the original resource
Document updated = await client.ReplaceDocumentAsync(doc);
Exceptions
- ArgumentNullException
If
document
is not set.- DocumentClientException
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:
StatusCode Reason for exception 404 NotFound - This means the resource you tried to delete did not exist.
- See Also
-
ResourceResponse<TResource>
ReplaceDocumentAsync(string, object, RequestOptions, CancellationToken)
Replaces a Document in the Azure Cosmos DB service as an asynchronous operation.
public Task<ResourceResponse<Document>> ReplaceDocumentAsync(string documentLink, object document, RequestOptions options = null, CancellationToken cancellationToken = default)
Parameters
documentLink
stringThe link of the document to be updated. E.g. dbs/db_rid/colls/col_rid/docs/doc_rid/
document
objectThe updated Document to replace the existing resource with.
options
RequestOptions(Optional) The request options for the request.
cancellationToken
CancellationToken(Optional) A CancellationToken that can be used by other objects or threads to receive notice of cancellation.
Returns
- Task<ResourceResponse<Document>>
A System.Threading.Tasks containing a ResourceResponse<TResource> which wraps a Document containing the updated resource record.
Examples
In this example, instead of using a strongly typed Document, we will work with our own POCO object and not rely on the dynamic nature of the Document class.
public class MyPoco
{
public string Id {get; set;}
public string MyProperty {get; set;}
}
//Get the doc back as a Document so you have access to doc.SelfLink
Document doc = client.CreateDocumentQuery<Document>(collectionLink)
.Where(r => r.Id == "doc id")
.AsEnumerable()
.SingleOrDefault();
//Now dynamically cast doc back to your MyPoco
MyPoco poco = (dynamic)doc;
//Update some properties of the poco object
poco.MyProperty = "updated value";
//Now persist these changes to the database using doc.SelLink and the update poco object
Document updated = await client.ReplaceDocumentAsync(doc.SelfLink, poco);
Exceptions
- ArgumentNullException
If either
documentLink
ordocument
is not set.- DocumentClientException
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:
StatusCode Reason for exception 404 NotFound - This means the resource you tried to delete did not exist.
- See Also
-
ResourceResponse<TResource>
ReplaceDocumentAsync(Uri, object, RequestOptions, CancellationToken)
Replaces a document as an asynchronous operation in the Azure Cosmos DB service.
public Task<ResourceResponse<Document>> ReplaceDocumentAsync(Uri documentUri, object document, RequestOptions options = null, CancellationToken cancellationToken = default)
Parameters
documentUri
Urithe URI of the document to be updated.
document
objectthe updated document.
options
RequestOptionsThe request options for the request.
cancellationToken
CancellationToken(Optional) CancellationToken representing request cancellation.
Returns
- Task<ResourceResponse<Document>>
The task object representing the service response for the asynchronous operation.
ReplaceDocumentCollectionAsync(DocumentCollection, RequestOptions)
Replaces a document collection in the Azure Cosmos DB service as an asynchronous operation.
public Task<ResourceResponse<DocumentCollection>> ReplaceDocumentCollectionAsync(DocumentCollection documentCollection, RequestOptions options = null)
Parameters
documentCollection
DocumentCollectionthe updated document collection.
options
RequestOptionsthe request options for the request.
Returns
- Task<ResourceResponse<DocumentCollection>>
A System.Threading.Tasks containing a ResourceResponse<TResource> which wraps a DocumentCollection containing the updated resource record.
ReplaceDocumentCollectionAsync(Uri, DocumentCollection, RequestOptions)
Replaces a document collection as an asynchronous operation in the Azure Cosmos DB service.
public Task<ResourceResponse<DocumentCollection>> ReplaceDocumentCollectionAsync(Uri documentCollectionUri, DocumentCollection documentCollection, RequestOptions options = null)
Parameters
documentCollectionUri
Urithe URI of the document collection to be updated.
documentCollection
DocumentCollectionthe updated document collection.
options
RequestOptionsThe request options for the request.
Returns
- Task<ResourceResponse<DocumentCollection>>
The task object representing the service response for the asynchronous operation.
ReplaceOfferAsync(Offer)
Replaces a Offer in the Azure Cosmos DB service as an asynchronous operation.
public Task<ResourceResponse<Offer>> ReplaceOfferAsync(Offer offer)
Parameters
Returns
- Task<ResourceResponse<Offer>>
A System.Threading.Tasks containing a ResourceResponse<TResource> which wraps a Offer containing the updated resource record.
Examples
//Fetch the resource to be updated
Offer offer = client.CreateOfferQuery()
.Where(r => r.ResourceLink == "collection selfLink")
.AsEnumerable()
.SingleOrDefault();
//Create a new offer with the changed throughput
OfferV2 newOffer = new OfferV2(offer, 5000);
//Now persist these changes to the database by replacing the original resource
Offer updated = await client.ReplaceOfferAsync(newOffer);
Exceptions
- ArgumentNullException
If
offer
is not set.- DocumentClientException
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:
StatusCode Reason for exception 404 NotFound - This means the resource you tried to delete did not exist. 423 Locked - This means the scale operation cannot be performed because another scale operation is in progress.
- See Also
-
ResourceResponse<TResource>
ReplacePermissionAsync(Permission, RequestOptions)
Replaces a Permission in the Azure Cosmos DB service as an asynchronous operation.
public Task<ResourceResponse<Permission>> ReplacePermissionAsync(Permission permission, RequestOptions options = null)
Parameters
permission
PermissionThe updated Permission to replace the existing resource with.
options
RequestOptions(Optional) The request options for the request.
Returns
- Task<ResourceResponse<Permission>>
A System.Threading.Tasks containing a ResourceResponse<TResource> which wraps a Permission containing the updated resource record.
Examples
//Fetch the resource to be updated
Permission permission = client.CreatePermissionQuery(permissionsLink)
.Where(r => r.Id == "permission id")
.AsEnumerable()
.SingleOrDefault();
//Change the permission mode to All
permission.PermissionMode = PermissionMode.All;
//Now persist these changes to the database by replacing the original resource
Permission updated = await client.ReplacePermissionAsync(permission);
Exceptions
- ArgumentNullException
If
permission
is not set.- DocumentClientException
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:
StatusCode Reason for exception 404 NotFound - This means the resource you tried to delete did not exist.
- See Also
-
ResourceResponse<TResource>
ReplacePermissionAsync(Uri, Permission, RequestOptions)
Replaces a permission as an asynchronous operation in the Azure Cosmos DB service.
public Task<ResourceResponse<Permission>> ReplacePermissionAsync(Uri permissionUri, Permission permission, RequestOptions options = null)
Parameters
permissionUri
Urithe URI for the permission to be updated.
permission
Permissionthe updated permission.
options
RequestOptionsThe request options for the request.
Returns
- Task<ResourceResponse<Permission>>
The task object representing the service response for the asynchronous operation.
ReplaceStoredProcedureAsync(StoredProcedure, RequestOptions)
Replaces a StoredProcedure in the Azure Cosmos DB service as an asynchronous operation.
public Task<ResourceResponse<StoredProcedure>> ReplaceStoredProcedureAsync(StoredProcedure storedProcedure, RequestOptions options = null)
Parameters
storedProcedure
StoredProcedureThe updated StoredProcedure to replace the existing resource with.
options
RequestOptions(Optional) The request options for the request.
Returns
- Task<ResourceResponse<StoredProcedure>>
A System.Threading.Tasks containing a ResourceResponse<TResource> which wraps a StoredProcedure containing the updated resource record.
Examples
//Fetch the resource to be updated
StoredProcedure sproc = client.CreateStoredProcedureQuery(sprocsLink)
.Where(r => r.Id == "sproc id")
.AsEnumerable()
.SingleOrDefault();
//Update some properties on the found resource
sproc.Body = "function () {new javascript body for sproc}";
//Now persist these changes to the database by replacing the original resource
StoredProcedure updated = await client.ReplaceStoredProcedureAsync(sproc);
Exceptions
- ArgumentNullException
If
storedProcedure
is not set.- DocumentClientException
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:
StatusCode Reason for exception 404 NotFound - This means the resource you tried to delete did not exist.
- See Also
-
ResourceResponse<TResource>
ReplaceStoredProcedureAsync(Uri, StoredProcedure, RequestOptions)
Replace the specified stored procedure in the Azure Cosmos DB service.
public Task<ResourceResponse<StoredProcedure>> ReplaceStoredProcedureAsync(Uri storedProcedureUri, StoredProcedure storedProcedure, RequestOptions options = null)
Parameters
storedProcedureUri
Urithe URI for the stored procedure to be updated.
storedProcedure
StoredProcedurethe updated stored procedure.
options
RequestOptionsThe request options for the request.
Returns
- Task<ResourceResponse<StoredProcedure>>
The task object representing the service response for the asynchronous operation.
ReplaceTriggerAsync(Trigger, RequestOptions)
Replaces a Trigger in the Azure Cosmos DB service as an asynchronous operation.
public Task<ResourceResponse<Trigger>> ReplaceTriggerAsync(Trigger trigger, RequestOptions options = null)
Parameters
trigger
TriggerThe updated Trigger to replace the existing resource with.
options
RequestOptions(Optional) The request options for the request.
Returns
- Task<ResourceResponse<Trigger>>
A System.Threading.Tasks containing a ResourceResponse<TResource> which wraps a Trigger containing the updated resource record.
Examples
//Fetch the resource to be updated
Trigger trigger = client.CreateTriggerQuery(sprocsLink)
.Where(r => r.Id == "trigger id")
.AsEnumerable()
.SingleOrDefault();
//Update some properties on the found resource
trigger.Body = "function () {new javascript body for trigger}";
//Now persist these changes to the database by replacing the original resource
Trigger updated = await client.ReplaceTriggerAsync(sproc);
Exceptions
- ArgumentNullException
If
trigger
is not set.- DocumentClientException
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:
StatusCode Reason for exception 404 NotFound - This means the resource you tried to delete did not exist.
- See Also
-
ResourceResponse<TResource>
ReplaceTriggerAsync(Uri, Trigger, RequestOptions)
Replaces a trigger as an asynchronous operation in the Azure Cosmos DB service.
public Task<ResourceResponse<Trigger>> ReplaceTriggerAsync(Uri triggerUri, Trigger trigger, RequestOptions options = null)
Parameters
triggerUri
Urithe URI for the trigger to be updated.
trigger
Triggerthe updated trigger.
options
RequestOptionsThe request options for the request.
Returns
- Task<ResourceResponse<Trigger>>
The task object representing the service response for the asynchronous operation.
ReplaceUserAsync(User, RequestOptions)
Replaces a User in the Azure Cosmos DB service as an asynchronous operation.
public Task<ResourceResponse<User>> ReplaceUserAsync(User user, RequestOptions options = null)
Parameters
user
UserThe updated User to replace the existing resource with.
options
RequestOptions(Optional) The request options for the request.
Returns
- Task<ResourceResponse<User>>
A System.Threading.Tasks containing a ResourceResponse<TResource> which wraps a User containing the updated resource record.
Examples
//Fetch the resource to be updated
User user = client.CreateUserQuery(usersLink)
.Where(r => r.Id == "user id")
.AsEnumerable()
.SingleOrDefault();
//Change the user mode to All
user.Id = "some new method";
//Now persist these changes to the database by replacing the original resource
User updated = await client.ReplaceUserAsync(user);
Exceptions
- ArgumentNullException
If
user
is not set.- DocumentClientException
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:
StatusCode Reason for exception 404 NotFound - This means the resource you tried to delete did not exist.
- See Also
-
ResourceResponse<TResource>
ReplaceUserAsync(Uri, User, RequestOptions)
Replaces a user as an asynchronous operation in the Azure Cosmos DB service.
public Task<ResourceResponse<User>> ReplaceUserAsync(Uri userUri, User user, RequestOptions options = null)
Parameters
userUri
Urithe URI for the user to be updated.
user
Userthe updated user.
options
RequestOptionsThe request options for the request.
Returns
- Task<ResourceResponse<User>>
The task object representing the service response for the asynchronous operation.
ReplaceUserDefinedFunctionAsync(UserDefinedFunction, RequestOptions)
Replaces a UserDefinedFunction in the Azure Cosmos DB service as an asynchronous operation.
public Task<ResourceResponse<UserDefinedFunction>> ReplaceUserDefinedFunctionAsync(UserDefinedFunction function, RequestOptions options = null)
Parameters
function
UserDefinedFunctionThe updated UserDefinedFunction to replace the existing resource with.
options
RequestOptions(Optional) The request options for the request.
Returns
- Task<ResourceResponse<UserDefinedFunction>>
A System.Threading.Tasks containing a ResourceResponse<TResource> which wraps a UserDefinedFunction containing the updated resource record.
Examples
//Fetch the resource to be updated
UserDefinedFunction udf = client.CreateUserDefinedFunctionQuery(functionsLink)
.Where(r => r.Id == "udf id")
.AsEnumerable()
.SingleOrDefault();
//Update some properties on the found resource
udf.Body = "function () {new javascript body for udf}";
//Now persist these changes to the database by replacing the original resource
UserDefinedFunction updated = await client.ReplaceUserDefinedFunctionAsync(udf);
Exceptions
- ArgumentNullException
If
function
is not set.- DocumentClientException
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:
StatusCode Reason for exception 404 NotFound - This means the resource you tried to delete did not exist.
- See Also
-
ResourceResponse<TResource>
ReplaceUserDefinedFunctionAsync(Uri, UserDefinedFunction, RequestOptions)
Replaces a user defined function as an asynchronous operation in the Azure Cosmos DB service.
public Task<ResourceResponse<UserDefinedFunction>> ReplaceUserDefinedFunctionAsync(Uri userDefinedFunctionUri, UserDefinedFunction function, RequestOptions options = null)
Parameters
userDefinedFunctionUri
Urithe URI for the user defined function to be updated.
function
UserDefinedFunctionthe updated user defined function.
options
RequestOptionsThe request options for the request.
Returns
- Task<ResourceResponse<UserDefinedFunction>>
The task object representing the service response for the asynchronous operation.
UpdateMediaAsync(string, Stream, MediaOptions, CancellationToken)
Replaces the specified media's content as an asynchronous operation in the Azure Cosmos DB service.
public Task<MediaResponse> UpdateMediaAsync(string mediaLink, Stream mediaStream, MediaOptions options = null, CancellationToken cancellationToken = default)
Parameters
mediaLink
stringThe link for the media to be updated. /media/media_rid
mediaStream
StreamThe Stream of the attachment media.
options
MediaOptionsThe MediaOptions for the request.
cancellationToken
CancellationToken(Optional) A CancellationToken that can be used by other objects or threads to receive notice of cancellation.
Returns
- Task<MediaResponse>
The task object representing the service response for the asynchronous operation.
Examples
//This attachment could be any binary you want to attach. Like images, videos, word documents, pdfs etc. it doesn't matter
using (FileStream fileStream = new FileStream(@".\something.pdf", FileMode.Open))
{
//Update the attachment media
await client.UpdateMediaAsync("/media/media_rid", fileStream,
new MediaOptions
{
ContentType = "application/pdf",
Slug = "something.pdf"
});
}
Exceptions
- ArgumentNullException
If either
mediaLink
ormediaStream
is not set.- ArgumentException
If
mediaLink
is not in the form of /media/{mediaId}.
- See Also
UpsertAttachmentAsync(string, Stream, MediaOptions, RequestOptions, CancellationToken)
Upserts an Attachment with the contents of the provided mediaStream
as an asynchronous operation
in the Azure Cosmos DB service.
public Task<ResourceResponse<Attachment>> UpsertAttachmentAsync(string attachmentsLink, Stream mediaStream, MediaOptions options = null, RequestOptions requestOptions = null, CancellationToken cancellationToken = default)
Parameters
attachmentsLink
stringThe attachments link for the document. E.g. dbs/db_rid/colls/col_rid/docs/doc_rid/attachments/
mediaStream
Streamthe Stream of the attachment media.
options
MediaOptionsthe MediaOptions for the request.
requestOptions
RequestOptionsthe RequestOptions for the request.
cancellationToken
CancellationToken(Optional) A CancellationToken that can be used by other objects or threads to receive notice of cancellation.
Returns
- Task<ResourceResponse<Attachment>>
The task object representing the service response for the asynchronous operation.
Examples
//This attachment could be any binary you want to attach. Like images, videos, word documents, pdfs etc. it doesn't matter
using (FileStream fileStream = new FileStream(@".\something.pdf", FileMode.Open))
{
//Upsert the attachment
Attachment attachment = await client.UpsertAttachmentAsync("dbs/db_rid/colls/coll_rid/docs/doc_rid/attachments/",
fileStream,
new MediaOptions
{
ContentType = "application/pdf",
Slug = "something.pdf"
});
}
Exceptions
- ArgumentNullException
If either
attachmentsLink
ormediaStream
is not set.
- See Also
-
ResourceResponse<TResource>
UpsertAttachmentAsync(string, object, RequestOptions, CancellationToken)
Upserts an attachment as an asychronous operation in the Azure Cosmos DB service.
public Task<ResourceResponse<Attachment>> UpsertAttachmentAsync(string documentLink, object attachment, RequestOptions options = null, CancellationToken cancellationToken = default)
Parameters
documentLink
stringThe link of the parent document for this new attachment. E.g. dbs/db_rid/colls/col_rid/docs/doc_rid/
attachment
objectThe attachment object.
options
RequestOptions(Optional) The request options for the request.
cancellationToken
CancellationToken(Optional) A CancellationToken that can be used by other objects or threads to receive notice of cancellation.
Returns
- Task<ResourceResponse<Attachment>>
The Task object representing the service response for the asynchronous operation.
Examples
The example below creates a new document, and then upserts a new attachment for that document
dynamic d = new
{
id = "DOC1800243243470"
};
Document doc = await client.CreateDocumentAsync(collectionSelfLink, d);
//Upsert an Attachment which links to binary content stored somewhere else
//Use the MediaLink property of Attachment to set where the binary resides
//MediaLink can also point at another Attachment within Azure Cosmos DB.
Attachment a = await client.UpsertAttachmentAsync(doc.SelfLink, new Attachment { Id = "foo", ContentType = "text/plain", MediaLink = "link to your media" });
- See Also
-
ResourceResponse<TResource>
UpsertAttachmentAsync(Uri, Stream, MediaOptions, RequestOptions, CancellationToken)
Upserts an attachment as an asynchronous operation in the Azure Cosmos DB service.
public Task<ResourceResponse<Attachment>> UpsertAttachmentAsync(Uri documentUri, Stream mediaStream, MediaOptions options = null, RequestOptions requestOptions = null, CancellationToken cancellationToken = default)
Parameters
documentUri
Urithe URI of the document to upsert an attachment for.
mediaStream
Streamthe stream of the attachment media.
options
MediaOptionsthe media options for the request.
requestOptions
RequestOptionsRequest options for the request.
cancellationToken
CancellationToken(Optional) CancellationToken representing request cancellation.
Returns
- Task<ResourceResponse<Attachment>>
The task object representing the service response for the asynchronous operation.
UpsertAttachmentAsync(Uri, object, RequestOptions, CancellationToken)
Upserts an attachment as an asynchronous operation in the Azure Cosmos DB service.
public Task<ResourceResponse<Attachment>> UpsertAttachmentAsync(Uri documentUri, object attachment, RequestOptions options = null, CancellationToken cancellationToken = default)
Parameters
documentUri
Urithe URI of the document to upsert an attachment for.
attachment
objectthe attachment object.
options
RequestOptionsThe request options for the request.
cancellationToken
CancellationToken(Optional) CancellationToken representing request cancellation.
Returns
- Task<ResourceResponse<Attachment>>
The task object representing the service response for the asynchronous operation.
UpsertDocumentAsync(string, object, RequestOptions, bool, CancellationToken)
Upserts a Document as an asychronous operation in the Azure Cosmos DB service.
public Task<ResourceResponse<Document>> UpsertDocumentAsync(string documentsFeedOrDatabaseLink, object document, RequestOptions options = null, bool disableAutomaticIdGeneration = false, CancellationToken cancellationToken = default)
Parameters
documentsFeedOrDatabaseLink
stringThe link of the DocumentCollection to upsert the document in. E.g. dbs/db_rid/colls/coll_rid/
document
objectThe document object to upsert.
options
RequestOptions(Optional) Any request options you wish to set. E.g. Specifying a Trigger to execute when creating the document. RequestOptions
disableAutomaticIdGeneration
bool(Optional) Disables the automatic id generation, If this is True the system will throw an exception if the id property is missing from the Document.
cancellationToken
CancellationToken(Optional) A CancellationToken that can be used by other objects or threads to receive notice of cancellation.
Returns
- Task<ResourceResponse<Document>>
The Document that was upserted contained within a Task object representing the service response for the asynchronous operation.
Examples
Azure Cosmos DB supports a number of different ways to work with documents. A document can extend Resource
public class MyObject : Resource
{
public string MyProperty {get; set;}
}
using (IDocumentClient client = new DocumentClient(new Uri("service endpoint"), "auth key"))
{
Document doc = await client.UpsertDocumentAsync("dbs/db_rid/colls/coll_rid/", new MyObject { MyProperty = "A Value" });
}</code></pre>
A document can be any POCO object that can be serialized to JSON, even if it doesn't extend from Resource
public class MyPOCO
{
public string MyProperty {get; set;}
}
using (IDocumentClient client = new DocumentClient(new Uri("service endpoint"), "auth key"))
{
Document doc = await client.UpsertDocumentAsync("dbs/db_rid/colls/coll_rid/", new MyPOCO { MyProperty = "A Value" });
}</code></pre>
A Document can also be a dynamic object
using (IDocumentClient client = new DocumentClient(new Uri("service endpoint"), "auth key"))
{
Document doc = await client.UpsertDocumentAsync("dbs/db_rid/colls/coll_rid/", new { SomeProperty = "A Value" } );
}
Upsert a Document and execute a Pre and Post Trigger
using (IDocumentClient client = new DocumentClient(new Uri("service endpoint"), "auth key"))
{
Document doc = await client.UpsertDocumentAsync(
"dbs/db_rid/colls/coll_rid/",
new { id = "DOC123213443" },
new RequestOptions
{
PreTriggerInclude = new List<string> { "MyPreTrigger" },
PostTriggerInclude = new List<string> { "MyPostTrigger" }
});
}
Exceptions
- ArgumentNullException
If either
documentsFeedOrDatabaseLink
ordocument
is not set.- AggregateException
Represents a consolidation of failures that occured during async processing. Look within InnerExceptions to find the actual exception(s)
- DocumentClientException
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:
StatusCode Reason for exception 400 BadRequest - This means something was wrong with the document supplied. It is likely that disableAutomaticIdGeneration
was true and an id was not supplied403 Forbidden - This likely means the collection in to which you were trying to upsert the document is full. 409 Conflict - This means a Document with an id matching the id field of document
already existed413 RequestEntityTooLarge - This means the Document exceeds the current max entity size. Consult documentation for limits and quotas. 429 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.
- See Also
-
ResourceResponse<TResource>
UpsertDocumentAsync(Uri, object, RequestOptions, bool, CancellationToken)
Upserts a document as an asynchronous operation in the Azure Cosmos DB service.
public Task<ResourceResponse<Document>> UpsertDocumentAsync(Uri documentCollectionUri, object document, RequestOptions options = null, bool disableAutomaticIdGeneration = false, CancellationToken cancellationToken = default)
Parameters
documentCollectionUri
Urithe URI of the document collection to upsert the document in.
document
objectthe document object.
options
RequestOptionsThe request options for the request.
disableAutomaticIdGeneration
boolDisables the automatic id generation, will throw an exception if id is missing.
cancellationToken
CancellationToken(Optional) CancellationToken representing request cancellation.
Returns
- Task<ResourceResponse<Document>>
The task object representing the service response for the asynchronous operation.
UpsertPermissionAsync(string, Permission, RequestOptions)
Upserts a permission on a user object in the Azure Cosmos DB service as an asychronous operation.
public Task<ResourceResponse<Permission>> UpsertPermissionAsync(string userLink, Permission permission, RequestOptions options = null)
Parameters
userLink
stringThe link of the user to Upsert the permission for. E.g. dbs/db_rid/users/user_rid/
permission
PermissionThe Permission object.
options
RequestOptions(Optional) The request options for the request.
Returns
- Task<ResourceResponse<Permission>>
A task object representing the service response for the asynchronous operation which contains the upserted Permission object.
Examples
//Upsert a read-only permission object for a specific user
Permission p = await client.UpsertPermissionAsync(userLink, new Permission { Id = "ReadPermission", PermissionMode = PermissionMode.Read });
Exceptions
- ArgumentNullException
If either
userLink
orpermission
is not set.- AggregateException
Represents a consolidation of failures that occured during async processing. Look within InnerExceptions to find the actual exception(s)
- DocumentClientException
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:
StatusCode Reason for exception 400 BadRequest - This means something was wrong with the request supplied. 403 Forbidden - You have reached your quota of permission objects. Contact support to have this quota increased. 409 Conflict - This means a Permission with an id matching the id you supplied already existed.
- See Also
-
ResourceResponse<TResource>
UpsertPermissionAsync(Uri, Permission, RequestOptions)
Upserts a permission as an asynchronous operation in the Azure Cosmos DB service.
public Task<ResourceResponse<Permission>> UpsertPermissionAsync(Uri userUri, Permission permission, RequestOptions options = null)
Parameters
userUri
Urithe URI of the user to upsert the permission for.
permission
Permissionthe Microsoft.Azure.Documents.Permission object.
options
RequestOptionsThe request options for the request.
Returns
- Task<ResourceResponse<Permission>>
The task object representing the service response for the asynchronous operation.
UpsertStoredProcedureAsync(string, StoredProcedure, RequestOptions)
Upserts a stored procedure as an asychronous operation in the Azure Cosmos DB service.
public Task<ResourceResponse<StoredProcedure>> UpsertStoredProcedureAsync(string collectionLink, StoredProcedure storedProcedure, RequestOptions options = null)
Parameters
collectionLink
stringThe link of the collection to upsert the stored procedure in. E.g. dbs/db_rid/colls/col_rid/
storedProcedure
StoredProcedureThe StoredProcedure object to upsert.
options
RequestOptions(Optional) Any RequestOptionsfor this request.
Returns
- Task<ResourceResponse<StoredProcedure>>
The StoredProcedure that was upserted contained within a Task object representing the service response for the asynchronous operation.
Examples
//Upsert a new stored procedure called "HelloWorldSproc" that takes in a single param called "name".
StoredProcedure sproc = await client.UpsertStoredProcedureAsync(collectionLink, new StoredProcedure
{
Id = "HelloWorldSproc",
Body = @"function (name){
var response = getContext().getResponse();
response.setBody('Hello ' + name);
}"
});
Exceptions
- ArgumentNullException
If either
collectionLink
orstoredProcedure
is not set.- AggregateException
Represents a consolidation of failures that occured during async processing. Look within InnerExceptions to find the actual exception(s)
- DocumentClientException
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:
StatusCode Reason for exception 400 BadRequest - This means something was wrong with the request supplied. It is likely that an Id was not supplied for the stored procedure or the Body was malformed. 403 Forbidden - You have reached your quota of stored procedures for the collection supplied. Contact support to have this quota increased. 409 Conflict - This means a StoredProcedure with an id matching the id you supplied already existed. 413 RequestEntityTooLarge - This means the body of the StoredProcedure you tried to upsert was too large.
- See Also
-
ResourceResponse<TResource>
UpsertStoredProcedureAsync(Uri, StoredProcedure, RequestOptions)
Upserts a stored procedure as an asynchronous operation in the Azure Cosmos DB service.
public Task<ResourceResponse<StoredProcedure>> UpsertStoredProcedureAsync(Uri documentCollectionUri, StoredProcedure storedProcedure, RequestOptions options = null)
Parameters
documentCollectionUri
Urithe URI of the document collection to upsert the stored procedure in.
storedProcedure
StoredProcedurethe Microsoft.Azure.Documents.StoredProcedure object.
options
RequestOptionsThe request options for the request.
Returns
- Task<ResourceResponse<StoredProcedure>>
The task object representing the service response for the asynchronous operation.
UpsertTriggerAsync(string, Trigger, RequestOptions)
Upserts a trigger as an asychronous operation in the Azure Cosmos DB service.
public Task<ResourceResponse<Trigger>> UpsertTriggerAsync(string collectionLink, Trigger trigger, RequestOptions options = null)
Parameters
collectionLink
stringThe link of the DocumentCollection to upsert the trigger in. E.g. dbs/db_rid/colls/col_rid/
trigger
TriggerThe Trigger object to upsert.
options
RequestOptions(Optional) Any RequestOptionsfor this request.
Returns
- Task<ResourceResponse<Trigger>>
A task object representing the service response for the asynchronous operation.
Examples
//Upsert a trigger that validates the contents of a document as it is created and adds a 'timestamp' property if one was not found.
Trigger trig = await client.UpsertTriggerAsync(collectionLink, new Trigger
{
Id = "ValidateDocuments",
Body = @"function validate() {
var context = getContext();
var request = context.getRequest();
var documentToCreate = request.getBody();
// validate properties
if (!('timestamp' in documentToCreate)) {
var ts = new Date();
documentToCreate['timestamp'] = ts.getTime();
}
// update the document that will be created
request.setBody(documentToCreate);
}",
TriggerType = TriggerType.Pre,
TriggerOperation = TriggerOperation.Create
});
Exceptions
- ArgumentNullException
If either
collectionLink
ortrigger
is not set.- AggregateException
Represents a consolidation of failures that occured during async processing. Look within InnerExceptions to find the actual exception(s)
- DocumentClientException
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:
StatusCode Reason for exception 400 BadRequest - This means something was wrong with the request supplied. It is likely that an Id was not supplied for the new trigger or that the Body was malformed. 403 Forbidden - You have reached your quota of triggers for the collection supplied. Contact support to have this quota increased. 409 Conflict - This means a Trigger with an id matching the id you supplied already existed. 413 RequestEntityTooLarge - This means the body of the Trigger you tried to upsert was too large.
- See Also
-
ResourceResponse<TResource>
UpsertTriggerAsync(Uri, Trigger, RequestOptions)
Upserts a trigger as an asynchronous operation in the Azure Cosmos DB service.
public Task<ResourceResponse<Trigger>> UpsertTriggerAsync(Uri documentCollectionUri, Trigger trigger, RequestOptions options = null)
Parameters
documentCollectionUri
Urithe URI of the document collection to upsert the trigger in.
trigger
Triggerthe Microsoft.Azure.Documents.Trigger object.
options
RequestOptionsThe request options for the request.
Returns
- Task<ResourceResponse<Trigger>>
The task object representing the service response for the asynchronous operation.
UpsertUserAsync(string, User, RequestOptions)
Upserts a permission on a user object in the Azure Cosmos DB service as an asychronous operation.
public Task<ResourceResponse<User>> UpsertUserAsync(string databaseLink, User user, RequestOptions options = null)
Parameters
databaseLink
stringThe link of the database to upsert the user in. E.g. dbs/db_rid/
user
UserThe User object to upsert.
options
RequestOptions(Optional) The request options for the request.
Returns
- Task<ResourceResponse<User>>
A task object representing the service response for the asynchronous operation which contains the upserted User object.
Examples
//Upsert a new user called joeBloggs in the specified database
User user = await client.UpsertUserAsync(databaseLink, new User { Id = "joeBloggs" });
Exceptions
- ArgumentNullException
If either
databaseLink
oruser
is not set.- AggregateException
Represents a consolidation of failures that occured during async processing. Look within InnerExceptions to find the actual exception(s)
- DocumentClientException
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:
StatusCode Reason for exception 400 BadRequest - This means something was wrong with the request supplied. 403 Forbidden - You have reached your quota of user objects for this database. Contact support to have this quota increased. 409 Conflict - This means a User with an id matching the id you supplied already existed.
- See Also
-
ResourceResponse<TResource>
UpsertUserAsync(Uri, User, RequestOptions)
Upserts a user as an asynchronous operation in the Azure Cosmos DB service.
public Task<ResourceResponse<User>> UpsertUserAsync(Uri databaseUri, User user, RequestOptions options = null)
Parameters
databaseUri
Urithe URI of the database to upsert the user in.
user
Userthe Microsoft.Azure.Documents.User object.
options
RequestOptionsThe request options for the request.
Returns
- Task<ResourceResponse<User>>
The task object representing the service response for the asynchronous operation.
UpsertUserDefinedFunctionAsync(string, UserDefinedFunction, RequestOptions)
Upserts a user defined function as an asychronous operation in the Azure Cosmos DB service.
public Task<ResourceResponse<UserDefinedFunction>> UpsertUserDefinedFunctionAsync(string collectionLink, UserDefinedFunction function, RequestOptions options = null)
Parameters
collectionLink
stringThe link of the DocumentCollection to upsert the user defined function in. E.g. dbs/db_rid/colls/col_rid/
function
UserDefinedFunctionThe UserDefinedFunction object to upsert.
options
RequestOptions(Optional) Any RequestOptionsfor this request.
Returns
- Task<ResourceResponse<UserDefinedFunction>>
A task object representing the service response for the asynchronous operation.
Examples
//Upsert a user defined function that converts a string to upper case
UserDefinedFunction udf = client.UpsertUserDefinedFunctionAsync(collectionLink, new UserDefinedFunction
{
Id = "ToUpper",
Body = @"function toUpper(input) {
return input.toUpperCase();
}",
});
Exceptions
- ArgumentNullException
If either
collectionLink
orfunction
is not set.- AggregateException
Represents a consolidation of failures that occured during async processing. Look within InnerExceptions to find the actual exception(s)
- DocumentClientException
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:
StatusCode Reason for exception 400 BadRequest - This means something was wrong with the request supplied. It is likely that an Id was not supplied for the new user defined function or that the Body was malformed. 403 Forbidden - You have reached your quota of user defined functions for the collection supplied. Contact support to have this quota increased. 409 Conflict - This means a UserDefinedFunction with an id matching the id you supplied already existed. 413 RequestEntityTooLarge - This means the body of the UserDefinedFunction you tried to upsert was too large.
- See Also
-
ResourceResponse<TResource>
UpsertUserDefinedFunctionAsync(Uri, UserDefinedFunction, RequestOptions)
Upserts a user defined function as an asynchronous operation in the Azure Cosmos DB service.
public Task<ResourceResponse<UserDefinedFunction>> UpsertUserDefinedFunctionAsync(Uri documentCollectionUri, UserDefinedFunction function, RequestOptions options = null)
Parameters
documentCollectionUri
Urithe URI of the document collection to upsert the user defined function in.
function
UserDefinedFunctionthe Microsoft.Azure.Documents.UserDefinedFunction object.
options
RequestOptionsThe request options for the request.
Returns
- Task<ResourceResponse<UserDefinedFunction>>
The task object representing the service response for the asynchronous operation.