public async Task <TDoc> GetOneAsync <TDoc>(QueryDefinition query, Microsoft.Azure.Cosmos.PartitionKey partitionKey)
        {
            var container = await GetContainerAsync();

            List <TDoc>         results           = new List <TDoc>();
            FeedIterator <TDoc> resultSetIterator = container.GetItemQueryIterator <TDoc>(query,
                                                                                          requestOptions: new QueryRequestOptions()
            {
                PartitionKey = partitionKey
            });

            while (resultSetIterator.HasMoreResults)
            {
                Microsoft.Azure.Cosmos.FeedResponse <TDoc> response = await resultSetIterator.ReadNextAsync();

                results.AddRange(response);
                if (response.Diagnostics != null)
                {
                    _logger.LogError($"QueryWithSqlParameters Diagnostics: {response.Diagnostics.ToString()}");
                }
                break;
            }
            var item = results.FirstOrDefault();

            return(item);
        }
Ejemplo n.º 2
0
        public async Task <bool> DeleteItemAsync <T>(string documentId, PartitionKey partitionKey)
        {
            ItemResponse <T> itemResponse = await _container.DeleteItemAsync <T>(
                documentId, partitionKey);

            return(itemResponse.StatusCode == System.Net.HttpStatusCode.NoContent);
        }
        public async Task <ItemResponse <T> > DeleteItemAsync(string id)
        {
            var container = await GetContainerAsync();

            var pk = new Microsoft.Azure.Cosmos.PartitionKey(id);
            ItemResponse <T> response = await container.DeleteItemAsync <T>(partitionKey : pk, id : id);

            return(response);
        }
        public async Task <T> GetItemAsync(string id)
        {
            try
            {
                var container = await GetContainerAsync();

                var partitionKey = new Microsoft.Azure.Cosmos.PartitionKey(id);

                ItemResponse <T> response = await container.ReadItemAsync <T>(
                    partitionKey : partitionKey,
                    id : id);

                if (response.StatusCode.IsSuccess())
                {
                    T item = response;
                    // Read the same item but as a stream.
                    using (ResponseMessage responseMessage = await container.ReadItemStreamAsync(
                               partitionKey: partitionKey,
                               id: id))
                    {
                        // Item stream operations do not throw exceptions for better performance
                        if (responseMessage.IsSuccessStatusCode)
                        {
                            T streamResponse = responseMessage.Content.FromStream <T>();
                            return(streamResponse);
                        }
                        else
                        {
                            //                            Console.WriteLine($"Read item from stream failed. Status code: {responseMessage.StatusCode} Message: {responseMessage.ErrorMessage}");
                        }
                    }
                }

                return(null);
            }

            catch (DocumentClientException e)
            {
                if (e.StatusCode == System.Net.HttpStatusCode.NotFound)
                {
                    return(null);
                }
                else
                {
                    throw;
                }
            }
            catch (Exception ex)
            {
                return(null);
            }
        }
Ejemplo n.º 5
0
        public async Task SaveBulkAsync <T>(List <T> items) where T : MasterDocument
        {
            if (items?.Count <= 0)
            {
                new ArgumentNullException(nameof(items));
            }
            var firstItem = items.First();

            if (firstItem.Id.IsNullOrEmpty())
            {
                throw new ArgumentNullException($"First item {nameof(firstItem.Id)}.", items.GetType().Name);
            }

            var partitionId = firstItem.Id.IdToMasterPartitionId();

            foreach (var item in items)
            {
                item.PartitionId = partitionId;
                item.SetDataType();
                await item.ValidateObjectAsync();
            }

            double totalRU = 0;

            try
            {
                var partitionKey    = new Cosmos.PartitionKey(partitionId);
                var concurrentTasks = new List <Task>(items.Count);
                foreach (var item in items)
                {
                    concurrentTasks.Add(container.UpsertItemAsync(item, partitionKey)
                                        .ContinueWith(async(responseTask) =>
                    {
                        if (responseTask.Exception != null)
                        {
                            logger.Error(responseTask.Exception);
                        }
                        totalRU += (await responseTask).RequestCharge;
                    }));
                }

                await Task.WhenAll(concurrentTasks);
            }
            catch (Exception ex)
            {
                throw new CosmosDataException(partitionId, ex);
            }
            finally
            {
                logger.Metric($"CosmosDB RU, @master - save bulk count '{items.Count}' type '{typeof(T)}'.", totalRU);
            }
        }
Ejemplo n.º 6
0
        public async Task DeleteBulkAsync <T>(List <string> ids) where T : MasterDocument
        {
            if (ids?.Count <= 0)
            {
                new ArgumentNullException(nameof(ids));
            }
            var firstId = ids.First();

            if (firstId.IsNullOrEmpty())
            {
                throw new ArgumentNullException($"First id {nameof(firstId)}.", ids.GetType().Name);
            }

            var partitionId = firstId.IdToMasterPartitionId();

            double totalRU = 0;

            try
            {
                var partitionKey    = new Cosmos.PartitionKey(partitionId);
                var concurrentTasks = new List <Task>(ids.Count);
                foreach (var id in ids)
                {
                    concurrentTasks.Add(container.DeleteItemAsync <T>(id, partitionKey)
                                        .ContinueWith(async(responseTask) =>
                    {
                        if (responseTask.Exception != null)
                        {
                            logger.Error(responseTask.Exception);
                        }
                        totalRU += (await responseTask).RequestCharge;
                    }));
                }

                await Task.WhenAll(concurrentTasks);
            }
            catch (Exception ex)
            {
                throw new CosmosDataException(partitionId, ex);
            }
            finally
            {
                logger.Metric($"CosmosDB RU, @master - delete bulk count '{ids.Count}' type '{typeof(T)}'.", totalRU);
            }
        }
 /// <summary>
 /// Delete a conflict from the Azure Cosmos service as an asynchronous operation.
 /// </summary>
 /// <param name="conflict">The conflict to delete.</param>
 /// <param name="partitionKey">The partition key for the conflict.</param>
 /// <param name="cancellationToken">(Optional) <see cref="CancellationToken"/> representing request cancellation.</param>
 /// <returns>A Task representing the asynchronous operation.</returns>
 /// <exception>https://aka.ms/cosmosdb-dot-net-exceptions</exception>
 /// <seealso cref="ConflictProperties"/>
 public abstract Task <ResponseMessage> DeleteAsync(
     ConflictProperties conflict,
     PartitionKey partitionKey,
     CancellationToken cancellationToken = default);
Ejemplo n.º 8
0
 public FeedRangePartitionKey(PartitionKey partitionKey)
 {
     this.PartitionKey = partitionKey;
 }
 public abstract Task <ItemResponse <T> > PatchItemAsync <T>(
     string id,
     PartitionKey partitionKey,
     IReadOnlyList <PatchOperation> patchOperations,
     ItemRequestOptions requestOptions   = null,
     CancellationToken cancellationToken = default);
 public abstract Task <ResponseMessage> PatchItemStreamAsync(
     string id,
     PartitionKey partitionKey,
     IReadOnlyList <PatchOperation> patchOperations,
     PatchItemRequestOptions requestOptions = null,
     CancellationToken cancellationToken    = default);
Ejemplo n.º 11
0
 public override TransactionalBatch CreateTransactionalBatch(PartitionKey partitionKey)
 {
     return(base.CreateTransactionalBatch(partitionKey));
 }
Ejemplo n.º 12
0
 /// <summary>
 /// Creates a feed range that span only a single <see cref="PartitionKey"/> value.
 /// </summary>
 /// <param name="partitionKey">The partition key value to create a feed range from.</param>
 /// <returns>The feed range that spans the partition.</returns>
 public static FeedRange FromPartitionKey(PartitionKey partitionKey)
 {
     return(new FeedRangePartitionKey(partitionKey));
 }
Ejemplo n.º 13
0
 public override TransactionalBatch CreateTransactionalBatch(PartitionKey partitionKey)
 {
     return(new BatchCore(this, partitionKey));
 }
 /// <summary>
 /// Upserts an item as an asynchronous operation in the Azure Cosmos service.
 /// </summary>
 /// <param name="item">A JSON serializable object that must contain an id property. <see cref="CosmosJsonSerializer"/> to implement a custom serializer</param>
 /// <param name="partitionKey">Partitionkey for the item. If not specified will be populated by extracting from {T}</param>
 /// <param name="requestOptions">(Optional) The options for the item request <see cref="ItemRequestOptions"/></param>
 /// <param name="cancellationToken">(Optional) <see cref="CancellationToken"/> representing request cancellation.</param>
 /// <returns>The <see cref="ItemResponse{T}"/> that was upserted contained within a <see cref="System.Threading.Tasks.Task"/> object representing the service response for the asynchronous operation.</returns>
 /// <exception cref="System.AggregateException">Represents a consolidation of failures that occurred during async processing. Look within InnerExceptions to find the actual exception(s)</exception>
 /// <exception cref="CosmosException">This exception can encapsulate many different types of errors. To determine the specific error always look at the StatusCode property. Some common codes you may get when creating a Document are:
 /// <list type="table">
 ///     <listheader>
 ///         <term>StatusCode</term><description>Reason for exception</description>
 ///     </listheader>
 ///     <item>
 ///         <term>400</term><description>BadRequest - This means something was wrong with the document supplied.</description>
 ///     </item>
 ///     <item>
 ///         <term>403</term><description>Forbidden - This likely means the collection in to which you were trying to upsert the document is full.</description>
 ///     </item>
 ///     <item>
 ///         <term>413</term><description>RequestEntityTooLarge - This means the item exceeds the current max entity size. Consult documentation for limits and quotas.</description>
 ///     </item>
 ///     <item>
 ///         <term>429</term><description>TooManyRequests - This means you have exceeded the number of request units per second. Consult the DocumentClientException.RetryAfter value to see how long you should wait before retrying this operation.</description>
 ///     </item>
 /// </list>
 /// </exception>
 /// <example>
 /// <code language="c#">
 /// <![CDATA[
 /// public class ToDoActivity{
 ///     public string id {get; set;}
 ///     public string status {get; set;}
 /// }
 ///
 /// ToDoActivity test = new ToDoActivity()
 /// {
 ///    id = Guid.NewGuid().ToString(),
 ///    status = "InProgress"
 /// };
 ///
 /// ItemResponse<ToDoActivity> item = await this.cosmosContainer.UpsertAsync<ToDoActivity>(test.status, test);
 /// ]]>
 /// </code>
 /// </example>
 public abstract Task <ItemResponse <T> > UpsertItemAsync <T>(
     T item,
     PartitionKey partitionKey           = null,
     ItemRequestOptions requestOptions   = null,
     CancellationToken cancellationToken = default(CancellationToken));
 /// <summary>
 /// Reads a item from the Azure Cosmos service as an asynchronous operation.
 /// </summary>
 /// <param name="partitionKey">The partition key for the item. <see cref="Microsoft.Azure.Documents.PartitionKey"/></param>
 /// <param name="id">The cosmos item id</param>
 /// <param name="requestOptions">(Optional) The options for the item request <see cref="ItemRequestOptions"/></param>
 /// <param name="cancellationToken">(Optional) <see cref="CancellationToken"/> representing request cancellation.</param>
 /// <returns>
 /// A <see cref="Task"/> containing a <see cref="CosmosResponseMessage"/> which wraps a <see cref="Stream"/> containing the read resource record.
 /// </returns>
 /// <exception>
 /// The Stream operation only throws on client side exceptions. This is to increase performance and prevent the overhead of throwing exceptions. Check the HTTP status code on the response to check if the operation failed.
 /// </exception>
 /// <example>
 /// Read a response as a stream.
 /// <code language="c#">
 /// <![CDATA[
 /// using(CosmosResponseMessage response = this.cosmosContainer.ReadItemStreamAsync("partitionKey", "id"))
 /// {
 ///     if (!response.IsSuccessStatusCode)
 ///     {
 ///         //Handle and log exception
 ///         return;
 ///     }
 ///
 ///     using(Stream stream = response.ReadBodyAsync())
 ///     {
 ///         //Read or do other operations with the stream
 ///         using (StreamReader streamReader = new StreamReader(stream))
 ///         {
 ///             string content =  streamReader.ReadToEndAsync();
 ///         }
 ///     }
 /// }
 ///
 /// ]]>
 /// </code>
 /// </example>
 public abstract Task <CosmosResponseMessage> ReadItemStreamAsync(
     PartitionKey partitionKey,
     string id,
     ItemRequestOptions requestOptions   = null,
     CancellationToken cancellationToken = default(CancellationToken));
Ejemplo n.º 16
0
        internal static void FillPartitionKey(RequestMessage request, PartitionKey partitionKey)
        {
            Debug.Assert(request != null);

            request.Headers.PartitionKey = partitionKey.ToJsonString();
        }
Ejemplo n.º 17
0
 public override TransactionalBatch CreateTransactionalBatch(PartitionKey partitionKey)
 {
     return(this.container.CreateTransactionalBatch(partitionKey));
 }
 public override FeedIterator <T> GetChangeFeedIterator <T>(
     PartitionKey partitionKey,
     ChangeFeedRequestOptions changeFeedRequestOptions = null)
 {
     return(this.container.GetChangeFeedIterator <T>(partitionKey, changeFeedRequestOptions));
 }
 /// <summary>
 /// Reads the item that originated the conflict.
 /// </summary>
 /// <param name="conflict">The conflict for which we want to read the item.</param>
 /// <param name="partitionKey">The partition key for the item.</param>
 /// <param name="cancellationToken">(Optional) <see cref="CancellationToken"/> representing request cancellation.</param>
 /// <returns>The current state of the item associated with the conflict.</returns>
 /// <exception>https://aka.ms/cosmosdb-dot-net-exceptions</exception>
 /// <seealso cref="ConflictProperties"/>
 /// <example>
 /// <code language="c#">
 /// <![CDATA[
 /// using (FeedIterator<ConflictProperties> conflictIterator = conflicts.GetConflictQueryIterator())
 /// {
 ///     while (conflictIterator.HasMoreResults)
 ///     {
 ///         foreach(ConflictProperties item in await conflictIterator.ReadNextAsync())
 ///         {
 ///             MyClass intendedChanges = conflicts.ReadConflictContent<MyClass>(item);
 ///             ItemResponse<MyClass> currentState = await conflicts.ReadCurrentAsync<MyClass>(item, intendedChanges.MyPartitionKey);
 ///         }
 ///     }
 /// }
 /// ]]>
 /// </code>
 /// </example>
 public abstract Task <ItemResponse <T> > ReadCurrentAsync <T>(
     ConflictProperties conflict,
     PartitionKey partitionKey,
     CancellationToken cancellationToken = default);
 /// <summary>
 /// Replaces a item in the Azure Cosmos service as an asynchronous operation.
 /// </summary>
 /// <param name="id">The cosmos item id, which is expected to match the value within T.</param>
 /// <param name="item">A JSON serializable object that must contain an id property. <see cref="CosmosJsonSerializer"/> to implement a custom serializer.</param>
 /// <param name="partitionKey">Partitionkey for the item. If not specified will be populated by extracting from {T}</param>
 /// <param name="requestOptions">(Optional) The options for the item request <see cref="ItemRequestOptions"/></param>
 /// <param name="cancellationToken">(Optional) <see cref="CancellationToken"/> representing request cancellation.</param>
 /// <returns>
 /// A <see cref="Task"/> containing a <see cref="ItemResponse{T}"/> which wraps the updated resource record.
 /// </returns>
 /// <exception cref="ArgumentNullException">If either <paramref name="item"/> is not set.</exception>
 /// <exception cref="CosmosException">
 /// This exception can encapsulate many different types of errors. To determine the specific error always look at the StatusCode property.
 /// <list type="table">
 ///     <listheader>
 ///         <term>StatusCode</term><description>Reason for exception</description>
 ///     </listheader>
 ///     <item>
 ///         <term>400</term><description>BadRequest - This means something was wrong with the document supplied. </description>
 ///     </item>
 ///     <item>
 ///         <term>403</term><description>Forbidden - This likely means the collection in to which you were trying to create the document is full.</description>
 ///     </item>
 ///     <item>
 ///         <term>413</term><description>RequestEntityTooLarge - This means the item exceeds the current max entity size. Consult documentation for limits and quotas.</description>
 ///     </item>
 ///     <item>
 ///         <term>429</term><description>TooManyRequests - This means you have exceeded the number of request units per second.</description>
 ///     </item>
 /// </list>
 /// </exception>
 /// <example>
 /// <code language="c#">
 /// <![CDATA[
 /// public class ToDoActivity{
 ///     public string id {get; set;}
 ///     public string status {get; set;}
 /// }
 ///
 /// ToDoActivity test = new ToDoActivity()
 /// {
 ///    id = Guid.NewGuid().ToString(),
 ///    status = "InProgress"
 /// };
 ///
 /// ItemResponse item = await this.cosmosContainer.ReplaceItemAsync<ToDoActivity>(test.status, test.id, test);
 /// ]]>
 /// </code>
 /// </example>
 public abstract Task <ItemResponse <T> > ReplaceItemAsync <T>(
     string id,
     T item,
     PartitionKey partitionKey           = null,
     ItemRequestOptions requestOptions   = null,
     CancellationToken cancellationToken = default(CancellationToken));
Ejemplo n.º 21
0
 /// <summary>
 /// Patches an item in the Azure Cosmos service as an asynchronous operation.
 /// </summary>
 /// <remarks>
 /// By default, resource body will be returned as part of the response. User can request no content by setting <see cref="ItemRequestOptions.EnableContentResponseOnWrite"/> flag to false.
 /// </remarks>
 /// <param name="id">The Cosmos item id</param>
 /// <param name="partitionKey">The partition key for the item.</param>
 /// <param name="streamPayload">Represents a stream containing the list of operations to be sequentially applied to the referred Cosmos item.</param>
 /// <param name="requestOptions">(Optional) The options for the item request.</param>
 /// <param name="cancellationToken">(Optional) <see cref="CancellationToken"/> representing request cancellation.</param>
 /// <returns>
 /// A <see cref="Task"/> containing a <see cref="ResponseMessage"/> which wraps a <see cref="Stream"/> containing the patched resource record.
 /// </returns>
 public abstract Task <ResponseMessage> PatchItemStreamAsync(
     string id,
     PartitionKey partitionKey,
     Stream streamPayload,
     ItemRequestOptions requestOptions   = null,
     CancellationToken cancellationToken = default);
        public override object ReadJson(
            JsonReader reader,
            Type objectType,
            object existingValue,
            JsonSerializer serializer)
        {
            if (reader.TokenType == JsonToken.Null)
            {
                return(null);
            }

            if (reader.TokenType != JsonToken.StartObject)
            {
                throw new JsonSerializationException(ClientResources.FeedToken_UnknownFormat);
            }

            JObject jObject = JObject.Load(reader);

            if (!jObject.TryGetValue(FeedTokenInternalConverter.TypePropertyName, out JToken typeJtoken) ||
                !Enum.TryParse(typeJtoken.Value <int>().ToString(), ignoreCase: true, out FeedTokenType feedTokenType))
            {
                throw new JsonSerializationException(ClientResources.FeedToken_UnknownFormat);
            }

            switch (feedTokenType)
            {
            case FeedTokenType.EPKRange:
            {
                if (!jObject.TryGetValue(FeedTokenInternalConverter.RidPropertyName, out JToken ridJToken) ||
                    string.IsNullOrEmpty(ridJToken.Value <string>()))
                {
                    throw new JsonSerializationException(ClientResources.FeedToken_UnknownFormat);
                }

                if (!jObject.TryGetValue(FeedTokenInternalConverter.ContinuationPropertyName, out JToken continuationJToken))
                {
                    throw new JsonSerializationException(ClientResources.FeedToken_UnknownFormat);
                }

                if (!jObject.TryGetValue(FeedTokenInternalConverter.RangePropertyName, out JToken rangeJToken))
                {
                    throw new JsonSerializationException(ClientResources.FeedToken_UnknownFormat);
                }

                List <CompositeContinuationToken> ranges        = serializer.Deserialize <List <CompositeContinuationToken> >(continuationJToken.CreateReader());
                Documents.Routing.Range <string>  completeRange = serializer.Deserialize <Documents.Routing.Range <string> >(rangeJToken.CreateReader());
                return(new FeedTokenEPKRange(ridJToken.Value <string>(), completeRange, ranges));
            }

            case FeedTokenType.PartitionKeyValue:
            {
                if (!jObject.TryGetValue(FeedTokenInternalConverter.ContinuationPropertyName, out JToken continuationJToken))
                {
                    throw new JsonSerializationException(ClientResources.FeedToken_UnknownFormat);
                }

                if (!jObject.TryGetValue(FeedTokenInternalConverter.PartitionKeyPropertyName, out JToken pkJToken))
                {
                    throw new JsonSerializationException(ClientResources.FeedToken_UnknownFormat);
                }

                if (!PartitionKey.TryParseJsonString(pkJToken.Value <string>(), out PartitionKey partitionKey))
                {
                    throw new JsonSerializationException(ClientResources.FeedToken_UnknownFormat);
                }

                FeedTokenPartitionKey feedTokenPartitionKey = new FeedTokenPartitionKey(partitionKey);
                feedTokenPartitionKey.UpdateContinuation(continuationJToken.Value <string>());
                return(feedTokenPartitionKey);
            }

            case FeedTokenType.PartitionKeyRangeId:
            {
                if (!jObject.TryGetValue(FeedTokenInternalConverter.ContinuationPropertyName, out JToken continuationJToken))
                {
                    throw new JsonSerializationException(ClientResources.FeedToken_UnknownFormat);
                }

                if (!jObject.TryGetValue(FeedTokenInternalConverter.PartitionKeyRangeIdPropertyName, out JToken pkJToken))
                {
                    throw new JsonSerializationException(ClientResources.FeedToken_UnknownFormat);
                }

                FeedTokenPartitionKeyRange feedTokenPartitionKeyRange = new FeedTokenPartitionKeyRange(pkJToken.Value <string>());
                feedTokenPartitionKeyRange.UpdateContinuation(continuationJToken.Value <string>());
                return(feedTokenPartitionKeyRange);
            }
            }

            throw new JsonSerializationException(ClientResources.FeedToken_UnknownFormat);
        }
Ejemplo n.º 23
0
 public FeedTokenPartitionKey(PartitionKey partitionKey)
 {
     this.PartitionKey = partitionKey;
 }
 /// <summary>
 /// Reads the item that originated the conflict.
 /// </summary>
 /// <param name="partitionKey">The partition key for the item.</param>
 /// <param name="cosmosConflict">The conflict for which we want to read the item.</param>
 /// <param name="cancellationToken">(Optional) <see cref="CancellationToken"/> representing request cancellation.</param>
 /// <returns>The current state of the item associated with the conflict.</returns>
 /// <seealso cref="CosmosConflictSettings"/>
 /// <example>
 /// <code language="c#">
 /// <![CDATA[
 /// FeedIterator<CosmosConflictSettings> conflictIterator = await cosmosContainer.Conflicts.GetConflictsIterator();
 /// while (conflictIterator.HasMoreResults)
 /// {
 ///     foreach(CosmosConflictSettings item in await conflictIterator.FetchNextSetAsync())
 ///     {
 ///         MyClass intendedChanges = cosmosContainer.Conflicts.ReadConflictContent<MyClass>(item);
 ///         ItemResponse<MyClass> currentState = await cosmosContainer.Conflicts.ReadCurrentAsync<MyClass>(intendedChanges.MyPartitionKey, item);
 ///     }
 /// }
 /// ]]>
 /// </code>
 /// </example>
 public abstract Task <ItemResponse <T> > ReadCurrentAsync <T>(
     PartitionKey partitionKey,
     CosmosConflictSettings cosmosConflict,
     CancellationToken cancellationToken = default(CancellationToken));
Ejemplo n.º 25
0
 public override Batch CreateBatch(PartitionKey partitionKey)
 {
     return(new BatchCore(this, partitionKey));
 }
 /// <summary>
 ///  This method creates a query for items under a container in an Azure Cosmos database using a SQL statement with parameterized values. It returns a FeedIterator.
 ///  For more information on preparing SQL statements with parameterized values, please see <see cref="CosmosSqlQueryDefinition"/>.
 /// </summary>
 /// <param name="sqlQueryText">The cosmos SQL query text.</param>
 /// <param name="partitionKey">The partition key for the item. <see cref="Microsoft.Azure.Documents.PartitionKey"/></param>
 /// <param name="maxItemCount">(Optional) The max item count to return as part of the query</param>
 /// <param name="continuationToken">(Optional) The continuation token in the Azure Cosmos DB service.</param>
 /// <param name="requestOptions">(Optional) The options for the item query request <see cref="QueryRequestOptions"/></param>
 /// <example>
 /// Create a query to get all the ToDoActivity that have a cost greater than 9000
 /// <code language="c#">
 /// <![CDATA[
 /// public class ToDoActivity{
 ///     public string id {get; set;}
 ///     public string status {get; set;}
 ///     public int cost {get; set;}
 /// }
 ///
 /// FeedIterator<ToDoActivity> feedIterator = this.Container.CreateItemQuery<ToDoActivity>(
 ///     sqlQueryText: "select * from ToDos t where t.cost > 9000",
 ///     partitionKey: "Error");
 ///
 /// while (feedIterator.HasMoreResults)
 /// {
 ///     foreach(var item in await feedIterator.FetchNextSetAsync()){
 ///     {
 ///         Console.WriteLine(item.cost);
 ///     }
 /// }
 /// ]]>
 /// </code>
 /// </example>
 /// <returns>An iterator to go through the items.</returns>
 public abstract FeedIterator <T> CreateItemQuery <T>(
     string sqlQueryText,
     PartitionKey partitionKey,
     int?maxItemCount                   = null,
     string continuationToken           = null,
     QueryRequestOptions requestOptions = null);
 /// <summary>
 /// Delete a item from the Azure Cosmos service as an asynchronous operation.
 /// </summary>
 /// <param name="partitionKey">The partition key for the item. <see cref="Microsoft.Azure.Documents.PartitionKey"/></param>
 /// <param name="id">The cosmos item id</param>
 /// <param name="requestOptions">(Optional) The options for the item request <see cref="ItemRequestOptions"/></param>
 /// <param name="cancellationToken">(Optional) <see cref="CancellationToken"/> representing request cancellation.</param>
 /// <returns>A <see cref="Task"/> containing a <see cref="ItemResponse{T}"/> which will contain information about the request issued.</returns>
 /// <exception cref="CosmosException">
 /// This exception can encapsulate many different types of errors. To determine the specific error always look at the StatusCode property. Some common codes you may get when creating a Document are:
 /// <list type="table">
 ///     <listheader>
 ///         <term>StatusCode</term><description>Reason for exception</description>
 ///     </listheader>
 ///     <item>
 ///         <term>429</term><description>TooManyRequests - This means you have exceeded the number of request units per second.</description>
 ///     </item>
 /// </list>
 /// </exception>
 /// <example>
 /// <code language="c#">
 /// <![CDATA[
 /// public class ToDoActivity{
 ///     public string id {get; set;}
 ///     public string status {get; set;}
 /// }
 ///
 /// ItemResponse item = await this.cosmosContainer.DeleteItemAsync<ToDoActivity>("partitionKey", "id");
 /// ]]>
 /// </code>
 /// </example>
 public abstract Task <ItemResponse <T> > DeleteItemAsync <T>(
     PartitionKey partitionKey,
     string id,
     ItemRequestOptions requestOptions   = null,
     CancellationToken cancellationToken = default(CancellationToken));
Ejemplo n.º 28
0
        public static string GetPartitionKeyRangeId(PartitionKey partitionKey, PartitionKeyDefinition partitionKeyDefinition, Routing.CollectionRoutingMap collectionRoutingMap)
        {
            string effectivePartitionKey = partitionKey.InternalKey.GetEffectivePartitionKeyString(partitionKeyDefinition);

            return(collectionRoutingMap.GetRangeByEffectivePartitionKey(effectivePartitionKey).Id);
        }
 /// <summary>
 /// Creates a Item as an asynchronous operation in the Azure Cosmos service.
 /// </summary>
 /// <param name="partitionKey">The partition key for the item. <see cref="Microsoft.Azure.Documents.PartitionKey"/></param>
 /// <param name="streamPayload">A <see cref="Stream"/> containing the payload.</param>
 /// <param name="requestOptions">(Optional) The options for the item request <see cref="ItemRequestOptions"/></param>
 /// <param name="cancellationToken">(Optional) <see cref="CancellationToken"/> representing request cancellation.</param>
 /// <returns>The <see cref="CosmosResponseMessage"/> that was created contained within a <see cref="System.Threading.Tasks.Task"/> object representing the service response for the asynchronous operation.</returns>
 /// <exception>
 /// The Stream operation only throws on client side exceptions. This is to increase performance and prevent the overhead of throwing exceptions. Check the HTTP status code on the response to check if the operation failed.
 /// </exception>
 /// <example>
 /// This example creates an item in a Cosmos container.
 /// <code language="c#">
 /// <![CDATA[
 /// //Create the object in Cosmos
 /// using (CosmosResponseMessage response = await this.Container.CreateItemStreamAsync(partitionKey: "streamPartitionKey", streamPayload: stream))
 /// {
 ///     if (!response.IsSuccessStatusCode)
 ///     {
 ///         //Handle and log exception
 ///         return;
 ///     }
 ///
 ///     using (Stream responseStream = await response.ReadBodyAsync())
 ///     {
 ///         //Read or do other operations with the stream
 ///         using (StreamReader streamReader = new StreamReader(responseStream))
 ///         {
 ///             string responseContentAsString = await streamReader.ReadToEndAsync();
 ///         }
 ///     }
 /// }
 /// ]]>
 /// </code>
 /// </example>
 public abstract Task <CosmosResponseMessage> CreateItemStreamAsync(
     PartitionKey partitionKey,
     Stream streamPayload,
     ItemRequestOptions requestOptions   = null,
     CancellationToken cancellationToken = default(CancellationToken));
 /// <summary>
 /// Delete a conflict from the Azure Cosmos service as an asynchronous operation.
 /// </summary>
 /// <param name="partitionKey">The partition key for the conflict.</param>
 /// <param name="conflict">The conflict to delete.</param>
 /// <param name="cancellationToken">(Optional) <see cref="CancellationToken"/> representing request cancellation.</param>
 /// <returns>A Task representing the asynchronous operation.</returns>
 /// <seealso cref="CosmosConflictSettings"/>
 public abstract Task <CosmosResponseMessage> DeleteConflictAsync(
     PartitionKey partitionKey,
     CosmosConflictSettings conflict,
     CancellationToken cancellationToken = default(CancellationToken));