コード例 #1
0
        private static CosmosRequestMessage GenerateCosmosRequestMessage(
            Uri resourceUri,
            ResourceType resourceType,
            OperationType operationType,
            CosmosRequestOptions requestOptions,
            Object partitionKey,
            Stream streamPayload,
            Action <CosmosRequestMessage> requestEnricher)
        {
            HttpMethod method = ExecUtils.GetHttpMethod(operationType);

            CosmosRequestMessage request = new CosmosRequestMessage(method, resourceUri);

            request.OperationType  = operationType;
            request.ResourceType   = resourceType;
            request.RequestOptions = requestOptions;
            request.Content        = streamPayload;

            if (partitionKey != null)
            {
                PartitionKey pk = new PartitionKey(partitionKey);
                request.Headers.PartitionKey = pk.InternalKey.ToJsonString();
            }

            if (operationType == OperationType.Upsert)
            {
                request.Headers.IsUpsert = bool.TrueString;
            }

            requestEnricher?.Invoke(request);

            return(request);
        }
コード例 #2
0
        internal static Task <T> ProcessResourceOperationAsync <T>(
            CosmosClient client,
            Uri resourceUri,
            ResourceType resourceType,
            OperationType operationType,
            CosmosRequestOptions requestOptions,
            Object partitionKey,
            Stream streamPayload,
            Action <CosmosRequestMessage> requestEnricher,
            Func <CosmosResponseMessage, T> responseCreator,
            CancellationToken cancellationToken)
        {
            CosmosRequestMessage request = ExecUtils.GenerateCosmosRequestMessage(
                client,
                resourceUri,
                resourceType,
                operationType,
                requestOptions,
                partitionKey,
                streamPayload,
                requestEnricher);

            return(client.RequestHandler.SendAsync(request, cancellationToken)
                   .ContinueWith(task => responseCreator(task.Result), cancellationToken));
        }
コード例 #3
0
        /// <summary>
        /// Used internally by friends ensrue robust argument and
        /// exception-less handling, with container information
        /// </summary>
        internal static Task <T> ProcessResourceOperationAsync <T>(
            CosmosClient client,
            Uri resourceUri,
            ResourceType resourceType,
            OperationType operationType,
            RequestOptions requestOptions,
            ContainerCore cosmosContainerCore,
            PartitionKey partitionKey,
            Stream streamPayload,
            Action <RequestMessage> requestEnricher,
            Func <ResponseMessage, T> responseCreator,
            CancellationToken cancellationToken)
        {
            if (client == null)
            {
                throw new ArgumentNullException(nameof(client));
            }

            return(ExecUtils.ProcessResourceOperationAsync(
                       requestHandler: client.RequestHandler,
                       resourceUri: resourceUri,
                       resourceType: resourceType,
                       operationType: operationType,
                       requestOptions: requestOptions,
                       cosmosContainerCore: cosmosContainerCore,
                       partitionKey: partitionKey,
                       streamPayload: streamPayload,
                       requestEnricher: requestEnricher,
                       responseCreator: responseCreator,
                       cancellationToken: cancellationToken));
        }
        internal virtual Task <CosmosResponseMessage> NextResultSetDelegate(
            string continuationToken,
            string partitionKeyRangeId,
            int?maxItemCount,
            CosmosChangeFeedRequestOptions options,
            CancellationToken cancellationToken)
        {
            Uri resourceUri = this.cosmosContainer.LinkUri;

            return(ExecUtils.ProcessResourceOperationAsync <CosmosResponseMessage>(
                       client: this.cosmosContainer.Database.Client,
                       resourceUri: resourceUri,
                       resourceType: Documents.ResourceType.Document,
                       operationType: Documents.OperationType.ReadFeed,
                       requestOptions: options,
                       requestEnricher: request => {
                CosmosChangeFeedRequestOptions.FillContinuationToken(request, continuationToken);
                CosmosChangeFeedRequestOptions.FillMaxItemCount(request, maxItemCount);
                CosmosChangeFeedRequestOptions.FillPartitionKeyRangeId(request, partitionKeyRangeId);
            },
                       responseCreator: response => response,
                       partitionKey: null,
                       streamPayload: null,
                       cancellationToken: cancellationToken));
        }
コード例 #5
0
 internal static Task <T> ProcessResourceOperationAsync <T>(
     CosmosClient client,
     string resourceUri,
     ResourceType resourceType,
     OperationType operationType,
     RequestOptions requestOptions,
     Stream streamPayload,
     Func <ResponseMessage, T> responseCreator,
     ITrace trace,
     CancellationToken cancellationToken)
 {
     return(ExecUtils.ProcessResourceOperationAsync(
                client,
                resourceUri,
                resourceType,
                operationType,
                requestOptions,
                cosmosContainerCore: null,
                feedRange: null,
                streamPayload: streamPayload,
                requestEnricher: null,
                responseCreator: responseCreator,
                trace: trace,
                cancellationToken: cancellationToken));
 }
コード例 #6
0
        internal static Task <T> ProcessCollectionCreateAsync <T>(
            CosmosContainerSettings containerSettings,
            CosmosDatabase database,
            int?throughput,
            Func <CosmosResponseMessage, T> responseCreator,
            CosmosRequestOptions requestOptions = null,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            if (containerSettings == null)
            {
                throw new ArgumentNullException(nameof(containerSettings));
            }

            containerSettings.ValidateRequiredProperties();
            database.Client.DocumentClient.ValidateResource(containerSettings);
            return(ExecUtils.ProcessResourceOperationAsync <T>(
                       database.Client,
                       database.LinkUri,
                       ResourceType.Collection,
                       OperationType.Create,
                       requestOptions,
                       partitionKey: null,
                       streamPayload: containerSettings.GetResourceStream(),
                       requestEnricher: (httpRequestMessage) => httpRequestMessage.AddThroughputHeader(throughput),
                       responseCreator: responseCreator,
                       cancellationToken: cancellationToken));
        }
コード例 #7
0
        /// <summary>
        /// Creates a stored procedure as an asynchronous operation in the Azure Cosmos DB service.
        /// </summary>
        /// <param name="id">The cosmos stored procedure id</param>
        /// <param name="body">The JavaScript function that is the body of the stored procedure</param>
        /// <param name="requestOptions">(Optional) The options for the stored procedure request <see cref="CosmosRequestOptions"/></param>
        /// <param name="cancellationToken">(Optional) <see cref="CancellationToken"/> representing request cancellation.</param>
        /// <returns>The <see cref="CosmosStoredProcedureSettings"/> that was created contained within a <see cref="Task"/> object representing the service response for the asynchronous operation.</returns>
        /// <exception cref="ArgumentNullException">If either <paramref name="id"/> or <paramref name="body"/> is not set.</exception>
        /// <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 request supplied. It is likely that an Id was not supplied for the stored procedure or the Body was malformed.</description>
        ///     </item>
        ///     <item>
        ///         <term>403</term><description>Forbidden - You have reached your quota of stored procedures for the collection supplied. Contact support to have this quota increased.</description>
        ///     </item>
        ///     <item>
        ///         <term>409</term><description>Conflict - This means a <see cref="CosmosStoredProcedureSettings"/> with an id matching the id you supplied already existed.</description>
        ///     </item>
        ///     <item>
        ///         <term>413</term><description>RequestEntityTooLarge - This means the body of the <see cref="CosmosStoredProcedureSettings"/> you tried to create was too large.</description>
        ///     </item>
        /// </list>
        /// </exception>
        /// <example>
        ///  This creates and executes a stored procedure that appends a string to the first item returned from the query.
        /// <code language="c#">
        /// <![CDATA[
        /// string sprocBody = @"function simple(prefix)
        ///    {
        ///        var collection = getContext().getCollection();
        ///
        ///        // Query documents and take 1st item.
        ///        var isAccepted = collection.queryDocuments(
        ///        collection.getSelfLink(),
        ///        'SELECT * FROM root r',
        ///        function(err, feed, options) {
        ///            if (err)throw err;
        ///
        ///            // Check the feed and if it's empty, set the body to 'no docs found',
        ///            // Otherwise just take 1st element from the feed.
        ///            if (!feed || !feed.length) getContext().getResponse().setBody(""no docs found"");
        ///            else getContext().getResponse().setBody(prefix + JSON.stringify(feed[0]));
        ///        });
        ///
        ///        if (!isAccepted) throw new Error(""The query wasn't accepted by the server. Try again/use continuation token between API and script."");
        ///    }";
        ///
        /// CosmosStoredProcedure cosmosStoredProcedure = await this.container.StoredProcedures.CreateStoredProcedureAsync(
        ///         id: "appendString",
        ///         body: sprocBody);
        ///
        /// // Execute the stored procedure
        /// CosmosItemResponse<string> sprocResponse = await storedProcedure.ExecuteAsync<string, string>(testPartitionId, "Item as a string: ");
        /// Console.WriteLine("sprocResponse.Resource");
        /// ]]>
        /// </code>
        /// </example>
        public virtual Task <CosmosStoredProcedureResponse> CreateStoredProcedureAsync(
            string id,
            string body,
            CosmosRequestOptions requestOptions = null,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            if (string.IsNullOrEmpty(id))
            {
                throw new ArgumentNullException(nameof(id));
            }

            if (string.IsNullOrEmpty(body))
            {
                throw new ArgumentNullException(nameof(body));
            }

            CosmosStoredProcedureSettings storedProcedureSettings = new CosmosStoredProcedureSettings();

            storedProcedureSettings.Id   = id;
            storedProcedureSettings.Body = body;

            Task <CosmosResponseMessage> response = ExecUtils.ProcessResourceOperationStreamAsync(
                this.container.Database.Client,
                this.container.LinkUri,
                ResourceType.StoredProcedure,
                OperationType.Create,
                requestOptions,
                partitionKey: null,
                streamPayload: storedProcedureSettings.GetResourceStream(),
                requestEnricher: null,
                cancellationToken: cancellationToken);

            return(this.client.ResponseFactory.CreateStoredProcedureResponse(this[id], response));
        }
コード例 #8
0
        private Task <CosmosQueryResponse <CosmosDatabaseSettings> > DatabaseFeedRequestExecutor(
            int?maxItemCount,
            string continuationToken,
            CosmosRequestOptions options,
            object state,
            CancellationToken cancellationToken)
        {
            Debug.Assert(state == null);

            Uri resourceUri = new Uri(Paths.Databases_Root, UriKind.Relative);

            return(ExecUtils.ProcessResourceOperationAsync <CosmosQueryResponse <CosmosDatabaseSettings> >(
                       this.client,
                       resourceUri,
                       ResourceType.Database,
                       OperationType.ReadFeed,
                       options,
                       request =>
            {
                CosmosQueryRequestOptions.FillContinuationToken(request, continuationToken);
                CosmosQueryRequestOptions.FillMaxItemCount(request, maxItemCount);
            },
                       response => this.client.ResponseFactory.CreateResultSetQueryResponse <CosmosDatabaseSettings>(response),
                       cancellationToken));
        }
コード例 #9
0
        public override Task <CosmosItemResponse <TOutput> > ExecuteAsync <TInput, TOutput>(
            object partitionKey,
            TInput input,
            CosmosStoredProcedureRequestOptions requestOptions = null,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            CosmosItemsCore.ValidatePartitionKey(partitionKey, requestOptions);

            Stream parametersStream;

            if (input != null && !input.GetType().IsArray)
            {
                parametersStream = this.Client.CosmosJsonSerializer.ToStream <TInput[]>(new TInput[1] {
                    input
                });
            }
            else
            {
                parametersStream = this.Client.CosmosJsonSerializer.ToStream <TInput>(input);
            }

            Task <CosmosResponseMessage> response = ExecUtils.ProcessResourceOperationStreamAsync(
                this.Client,
                this.LinkUri,
                ResourceType.StoredProcedure,
                OperationType.ExecuteJavaScript,
                requestOptions,
                partitionKey,
                parametersStream,
                null,
                cancellationToken);

            return(this.Client.ResponseFactory.CreateItemResponse <TOutput>(response));
        }
コード例 #10
0
 internal override Task <T> ProcessResourceOperationAsync <T>(
     Uri resourceUri,
     ResourceType resourceType,
     OperationType operationType,
     CosmosRequestOptions requestOptions,
     CosmosContainerCore cosmosContainerCore,
     Object partitionKey,
     Stream streamPayload,
     Action <CosmosRequestMessage> requestEnricher,
     Func <CosmosResponseMessage, T> responseCreator,
     CancellationToken cancellationToken)
 {
     return(ExecUtils.ProcessResourceOperationAsync <T>(
                requestHandler: this.RequestHandler,
                resourceUri: resourceUri,
                resourceType: resourceType,
                operationType: operationType,
                requestOptions: requestOptions,
                cosmosContainerCore: cosmosContainerCore,
                partitionKey: partitionKey,
                streamPayload: streamPayload,
                requestEnricher: requestEnricher,
                responseCreator: responseCreator,
                cancellationToken: cancellationToken));
 }
コード例 #11
0
        private Task <CosmosQueryResponse <T> > ItemFeedRequestExecutor <T>(
            int?maxItemCount,
            string continuationToken,
            CosmosRequestOptions options,
            object state,
            CancellationToken cancellationToken)
        {
            Uri resourceUri = this.container.LinkUri;

            return(ExecUtils.ProcessResourceOperationAsync <CosmosQueryResponse <T> >(
                       client: this.container.Database.Client,
                       resourceUri: resourceUri,
                       resourceType: ResourceType.Document,
                       operationType: OperationType.ReadFeed,
                       requestOptions: options,
                       requestEnricher: request =>
            {
                CosmosQueryRequestOptions.FillContinuationToken(request, continuationToken);
                CosmosQueryRequestOptions.FillMaxItemCount(request, maxItemCount);
            },
                       responseCreator: response => this.client.ResponseFactory.CreateResultSetQueryResponse <T>(response),
                       partitionKey: null,
                       streamPayload: null,
                       cancellationToken: cancellationToken));
        }
コード例 #12
0
 private Task <CosmosResponseMessage> ProcessAsync(
     OperationType operationType,
     CosmosRequestOptions requestOptions = null,
     CancellationToken cancellationToken = default(CancellationToken))
 {
     return(ExecUtils.ProcessResourceOperationStreamAsync(
                client: this.Client,
                resourceUri: this.LinkUri,
                resourceType: ResourceType.Database,
                operationType: operationType,
                requestOptions: requestOptions,
                partitionKey: null,
                streamPayload: null,
                requestEnricher: null,
                cancellationToken: cancellationToken));
 }
コード例 #13
0
 private Task <CosmosDatabaseResponse> ProcessAsync(
     OperationType operationType,
     CosmosRequestOptions requestOptions = null,
     CancellationToken cancellationToken = default(CancellationToken))
 {
     return(ExecUtils.ProcessResourceOperationAsync <CosmosDatabaseResponse>(
                this.Client,
                this.LinkUri,
                ResourceType.Database,
                operationType,
                requestOptions,
                streamPayload: null,
                responseCreator: response =>
                this.Client.ResponseFactory.CreateDatabaseResponse(response, this),
                cancellationToken: cancellationToken));
 }
コード例 #14
0
        private static async Task <CosmosRequestMessage> GenerateCosmosRequestMessage(
            Uri resourceUri,
            ResourceType resourceType,
            OperationType operationType,
            CosmosRequestOptions requestOptions,
            CosmosContainerCore cosmosContainerCore,
            Object partitionKey,
            Stream streamPayload,
            Action <CosmosRequestMessage> requestEnricher)
        {
            HttpMethod method = ExecUtils.GetHttpMethod(operationType);

            CosmosRequestMessage request = new CosmosRequestMessage(method, resourceUri);

            request.OperationType  = operationType;
            request.ResourceType   = resourceType;
            request.RequestOptions = requestOptions;
            request.Content        = streamPayload;

            if (partitionKey != null)
            {
                if (cosmosContainerCore == null && partitionKey.Equals(PartitionKey.None))
                {
                    throw new ArgumentException($"{nameof(cosmosContainerCore)} can not be null with partition key as PartitionKey.None");
                }
                else if (partitionKey.Equals(PartitionKey.None))
                {
                    PartitionKeyInternal partitionKeyInternal = await cosmosContainerCore.GetNonePartitionKeyValue();

                    request.Headers.PartitionKey = partitionKeyInternal.ToJsonString();
                }
                else
                {
                    PartitionKey pk = new PartitionKey(partitionKey);
                    request.Headers.PartitionKey = pk.InternalKey.ToJsonString();
                }
            }

            if (operationType == OperationType.Upsert)
            {
                request.Headers.IsUpsert = bool.TrueString;
            }

            requestEnricher?.Invoke(request);

            return(request);
        }
コード例 #15
0
 internal Task <CosmosResponseMessage> ProcessCollectionCreateAsync(
     Stream streamPayload,
     int?throughput,
     CosmosRequestOptions requestOptions = null,
     CancellationToken cancellationToken = default(CancellationToken))
 {
     return(ExecUtils.ProcessResourceOperationStreamAsync(
                client: this.client,
                resourceUri: this.database.LinkUri,
                resourceType: ResourceType.Collection,
                operationType: OperationType.Create,
                partitionKey: null,
                streamPayload: streamPayload,
                requestOptions: requestOptions,
                requestEnricher: (httpRequestMessage) => httpRequestMessage.AddThroughputHeader(throughput),
                cancellationToken: cancellationToken));
 }
コード例 #16
0
 private Task <CosmosContainerResponse> ProcessAsync(
     CosmosContainerSettings containerSettings,
     OperationType operationType,
     CosmosContainerRequestOptions requestOptions = null,
     CancellationToken cancellationToken          = default(CancellationToken))
 {
     return(ExecUtils.ProcessResourceOperationAsync <CosmosContainerResponse>(
                this.Client,
                this.LinkUri,
                ResourceType.Collection,
                operationType,
                requestOptions,
                containerSettings?.GetResourceStream(),
                response =>
                this.Client.ResponseFactory.CreateContainerResponse(response, this),
                cancellationToken));
 }
コード例 #17
0
 /// <summary>
 /// Creates a user defined function as an asynchronous operation in the Azure Cosmos DB service.
 /// </summary>
 /// <param name="userDefinedFunctionSettings">The <see cref="CosmosUserDefinedFunctionSettings"/> object.</param>
 /// <param name="requestOptions">(Optional) The options for the user defined function request <see cref="CosmosRequestOptions"/></param>
 /// <param name="cancellationToken">(Optional) <see cref="CancellationToken"/> representing request cancellation.</param>
 /// <returns>A task object representing the service response for the asynchronous operation.</returns>
 /// <exception cref="ArgumentNullException">If <paramref name="userDefinedFunctionSettings"/> is not set.</exception>
 /// <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 user defined function 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 request supplied. It is likely that an Id was not supplied for the new user defined function or that the Body was malformed.</description>
 ///     </item>
 ///     <item>
 ///         <term>403</term><description>Forbidden - You have reached your quota of user defined functions for the collection supplied. Contact support to have this quota increased.</description>
 ///     </item>
 ///     <item>
 ///         <term>409</term><description>Conflict - This means a <see cref="CosmosUserDefinedFunctionSettings"/> with an id matching the id you supplied already existed.</description>
 ///     </item>
 ///     <item>
 ///         <term>413</term><description>RequestEntityTooLarge - This means the body of the <see cref="CosmosUserDefinedFunctionSettings"/> you tried to create was too large.</description>
 ///     </item>
 /// </list>
 /// </exception>
 /// <example>
 ///  This creates a user defined function then uses the function in an item query.
 /// <code language="c#">
 /// <![CDATA[
 ///
 /// await this.container.UserDefinedFunctions.CreateUserDefinedFunctionAsync(
 ///     new CosmosUserDefinedFunctionSettings
 ///     {
 ///         Id = "calculateTax",
 ///         Body = @"function(amt) { return amt * 0.05; }"
 ///     });
 ///
 /// CosmosSqlQueryDefinition sqlQuery = new CosmosSqlQueryDefinition(
 ///     "SELECT VALUE udf.calculateTax(t.cost) FROM toDoActivity t where t.cost > @expensive and t.status = @status")
 ///     .UseParameter("@expensive", 9000)
 ///     .UseParameter("@status", "Done");
 ///
 /// CosmosResultSetIterator<double> setIterator = this.container.Items.CreateItemQuery<double>(
 ///     sqlQueryDefinition: sqlQuery,
 ///     partitionKey: "Done");
 ///
 /// while (setIterator.HasMoreResults)
 /// {
 ///     foreach (var tax in await setIterator.FetchNextSetAsync())
 ///     {
 ///         Console.WriteLine(tax);
 ///     }
 /// }
 /// ]]>
 /// </code>
 /// </example>
 public virtual Task <CosmosUserDefinedFunctionResponse> CreateUserDefinedFunctionAsync(
     CosmosUserDefinedFunctionSettings userDefinedFunctionSettings,
     CosmosRequestOptions requestOptions = null,
     CancellationToken cancellationToken = default(CancellationToken))
 {
     return(ExecUtils.ProcessResourceOperationAsync <CosmosUserDefinedFunctionResponse>(
                this.container.Database.Client,
                this.container.LinkUri,
                ResourceType.UserDefinedFunction,
                OperationType.Create,
                requestOptions,
                partitionKey: null,
                streamPayload: userDefinedFunctionSettings.GetResourceStream(),
                requestEnricher: null,
                responseCreator: response => this.client.ResponseFactory.CreateUserDefinedFunctionResponse(response, new CosmosUserDefinedFunction(this.container, userDefinedFunctionSettings.Id)),
                cancellationToken: cancellationToken));
 }
コード例 #18
0
        /// <summary>
        /// Creates a trigger as an asynchronous operation in the Azure Cosmos DB service.
        /// </summary>
        /// <param name="triggerSettings">The <see cref="CosmosTriggerSettings"/> object.</param>
        /// <param name="requestOptions">(Optional) The options for the stored procedure request <see cref="CosmosRequestOptions"/></param>
        /// <param name="cancellationToken">(Optional) <see cref="CancellationToken"/> representing request cancellation.</param>
        /// <returns>A task object representing the service response for the asynchronous operation.</returns>
        /// <exception cref="ArgumentNullException">If <paramref name="triggerSettings"/> is not set.</exception>
        /// <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 request supplied. It is likely that an Id was not supplied for the new trigger or that the Body was malformed.</description>
        ///     </item>
        ///     <item>
        ///         <term>403</term><description>Forbidden - You have reached your quota of triggers for the collection supplied. Contact support to have this quota increased.</description>
        ///     </item>
        ///     <item>
        ///         <term>409</term><description>Conflict - This means a <see cref="CosmosTriggerSettings"/> with an id matching the id you supplied already existed.</description>
        ///     </item>
        ///     <item>
        ///         <term>413</term><description>RequestEntityTooLarge - This means the body of the <see cref="CosmosTriggerSettings"/> you tried to create was too large.</description>
        ///     </item>
        /// </list>
        /// </exception>
        /// <example>
        ///  This creates a trigger then uses the trigger in a create item.
        /// <code language="c#">
        /// <![CDATA[
        /// CosmosTrigger cosmosTrigger = await this.container.Triggers.CreateTriggerAsync(
        ///     new CosmosTriggerSettings
        ///     {
        ///         Id = "addTax",
        ///         Body = @"function AddTax() {
        ///             var item = getContext().getRequest().getBody();
        ///
        ///             // calculate the tax.
        ///             item.tax = item.cost * .15;
        ///
        ///             // Update the request -- this is what is going to be inserted.
        ///             getContext().getRequest().setBody(item);
        ///         }",
        ///         TriggerOperation = TriggerOperation.All,
        ///         TriggerType = TriggerType.Pre
        ///     });
        ///
        /// CosmosItemRequestOptions options = new CosmosItemRequestOptions()
        /// {
        ///     PreTriggers = new List<string>() { cosmosTrigger.Id },
        /// };
        ///
        /// // Create a new item with trigger set in the request options
        /// CosmosItemResponse<dynamic> createdItem = await this.container.Items.CreateItemAsync<dynamic>(item.status, item, options);
        /// double itemTax = createdItem.Resource.tax;
        /// ]]>
        /// </code>
        /// </example>
        public virtual Task <CosmosTriggerResponse> CreateTriggerAsync(
            CosmosTriggerSettings triggerSettings,
            CosmosRequestOptions requestOptions = null,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            Task <CosmosResponseMessage> response = ExecUtils.ProcessResourceOperationStreamAsync(
                this.container.Database.Client,
                this.container.LinkUri,
                ResourceType.Trigger,
                OperationType.Create,
                requestOptions,
                partitionKey: null,
                streamPayload: triggerSettings.GetResourceStream(),
                requestEnricher: null,
                cancellationToken: cancellationToken);

            return(this.client.ResponseFactory.CreateTriggerResponse(this[triggerSettings.Id], response));
        }
コード例 #19
0
        /// <summary>
        /// Creates a user defined function as an asynchronous operation in the Azure Cosmos DB service.
        /// </summary>
        /// <param name="userDefinedFunctionSettings">The <see cref="CosmosUserDefinedFunctionSettings"/> object.</param>
        /// <param name="requestOptions">(Optional) The options for the user defined function request <see cref="CosmosRequestOptions"/></param>
        /// <param name="cancellationToken">(Optional) <see cref="CancellationToken"/> representing request cancellation.</param>
        /// <returns>A task object representing the service response for the asynchronous operation.</returns>
        /// <exception cref="ArgumentNullException">If <paramref name="userDefinedFunctionSettings"/> is not set.</exception>
        /// <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 user defined function 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 request supplied. It is likely that an Id was not supplied for the new user defined function or that the Body was malformed.</description>
        ///     </item>
        ///     <item>
        ///         <term>403</term><description>Forbidden - You have reached your quota of user defined functions for the collection supplied. Contact support to have this quota increased.</description>
        ///     </item>
        ///     <item>
        ///         <term>409</term><description>Conflict - This means a <see cref="CosmosUserDefinedFunctionSettings"/> with an id matching the id you supplied already existed.</description>
        ///     </item>
        ///     <item>
        ///         <term>413</term><description>RequestEntityTooLarge - This means the body of the <see cref="CosmosUserDefinedFunctionSettings"/> you tried to create was too large.</description>
        ///     </item>
        /// </list>
        /// </exception>
        /// <example>
        ///  This creates a user defined function then uses the function in an item query.
        /// <code language="c#">
        /// <![CDATA[
        ///
        /// await this.container.UserDefinedFunctions.CreateUserDefinedFunctionAsync(
        ///     new CosmosUserDefinedFunctionSettings
        ///     {
        ///         Id = "calculateTax",
        ///         Body = @"function(amt) { return amt * 0.05; }"
        ///     });
        ///
        /// CosmosSqlQueryDefinition sqlQuery = new CosmosSqlQueryDefinition(
        ///     "SELECT VALUE udf.calculateTax(t.cost) FROM toDoActivity t where t.cost > @expensive and t.status = @status")
        ///     .UseParameter("@expensive", 9000)
        ///     .UseParameter("@status", "Done");
        ///
        /// CosmosResultSetIterator<double> setIterator = this.container.Items.CreateItemQuery<double>(
        ///     sqlQueryDefinition: sqlQuery,
        ///     partitionKey: "Done");
        ///
        /// while (setIterator.HasMoreResults)
        /// {
        ///     foreach (var tax in await setIterator.FetchNextSetAsync())
        ///     {
        ///         Console.WriteLine(tax);
        ///     }
        /// }
        /// ]]>
        /// </code>
        /// </example>
        public virtual Task <CosmosUserDefinedFunctionResponse> CreateUserDefinedFunctionAsync(
            CosmosUserDefinedFunctionSettings userDefinedFunctionSettings,
            CosmosRequestOptions requestOptions = null,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            Task <CosmosResponseMessage> response = ExecUtils.ProcessResourceOperationStreamAsync(
                this.container.Database.Client,
                this.container.LinkUri,
                ResourceType.UserDefinedFunction,
                OperationType.Create,
                requestOptions,
                partitionKey: null,
                streamPayload: CosmosResource.ToStream(userDefinedFunctionSettings),
                requestEnricher: null,
                cancellationToken: cancellationToken);

            return(this.client.ResponseFactory.CreateUserDefinedFunctionResponse(this[userDefinedFunctionSettings.Id], response));
        }
コード例 #20
0
 internal virtual Task <CosmosUserDefinedFunctionResponse> ProcessAsync(
     object partitionKey,
     Stream streamPayload,
     OperationType operationType,
     CosmosRequestOptions requestOptions,
     CancellationToken cancellationToken)
 {
     return(ExecUtils.ProcessResourceOperationAsync <CosmosUserDefinedFunctionResponse>(
                this.Client,
                this.LinkUri,
                ResourceType.UserDefinedFunction,
                operationType,
                requestOptions,
                partitionKey,
                streamPayload,
                null,
                response => this.Client.ResponseFactory.CreateUserDefinedFunctionResponse(response, this),
                cancellationToken));
 }
コード例 #21
0
        /// <summary>
        /// Send a request for creating a database.
        ///
        /// A database manages users, permissions and a set of containers.
        /// Each Azure Cosmos DB Database Account is able to support multiple independent named databases,
        /// with the database being the logical container for data.
        ///
        /// Each Database consists of one or more containers, each of which in turn contain one or more
        /// documents. Since databases are an administrative resource, the Service Master Key will be
        /// required in order to access and successfully complete any action using the User APIs.
        /// </summary>
        /// <param name="streamPayload">The database id.</param>
        /// <param name="throughput">(Optional) The throughput provisioned for a collection in measurement of Requests-per-Unit in the Azure Cosmos DB service.</param>
        /// <param name="requestOptions">(Optional) A set of options that can be set.</param>
        /// <param name="cancellationToken">(Optional) <see cref="CancellationToken"/> representing request cancellation.</param>
        /// <returns>A <see cref="Task"/> containing a <see cref="CosmosDatabaseResponse"/> which wraps a <see cref="CosmosDatabaseSettings"/> containing the resource record.</returns>
        internal virtual Task <CosmosResponseMessage> CreateDatabaseStreamAsync(
            Stream streamPayload,
            int?throughput = null,
            CosmosRequestOptions requestOptions = null,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            Uri resourceUri = new Uri(Paths.Databases_Root, UriKind.Relative);

            return(ExecUtils.ProcessResourceOperationStreamAsync(
                       this.client,
                       resourceUri,
                       ResourceType.Database,
                       OperationType.Create,
                       requestOptions,
                       partitionKey: null,
                       streamPayload: streamPayload,
                       requestEnricher: (httpRequestMessage) => httpRequestMessage.AddThroughputHeader(throughput),
                       cancellationToken: cancellationToken));
        }
コード例 #22
0
        internal static async Task <T> ProcessResourceOperationAsync <T>(
            CosmosRequestHandler requestHandler,
            Uri resourceUri,
            ResourceType resourceType,
            OperationType operationType,
            CosmosRequestOptions requestOptions,
            CosmosContainerCore cosmosContainerCore,
            Object partitionKey,
            Stream streamPayload,
            Action <CosmosRequestMessage> requestEnricher,
            Func <CosmosResponseMessage, T> responseCreator,
            CancellationToken cancellationToken)
        {
            if (requestHandler == null)
            {
                throw new ArgumentException(nameof(requestHandler));
            }

            if (resourceUri == null)
            {
                throw new ArgumentNullException(nameof(resourceUri));
            }

            if (responseCreator == null)
            {
                throw new ArgumentNullException(nameof(responseCreator));
            }

            CosmosRequestMessage request = await ExecUtils.GenerateCosmosRequestMessage(
                resourceUri,
                resourceType,
                operationType,
                requestOptions,
                cosmosContainerCore,
                partitionKey,
                streamPayload,
                requestEnricher);

            CosmosResponseMessage response = await requestHandler.SendAsync(request, cancellationToken);

            return(responseCreator(response));
        }
コード例 #23
0
        internal Task <CosmosStoredProcedureResponse> ProcessAsync(
            object partitionKey,
            Stream streamPayload,
            OperationType operationType,
            CosmosRequestOptions requestOptions,
            CancellationToken cancellationToken)
        {
            Task <CosmosResponseMessage> response = ExecUtils.ProcessResourceOperationStreamAsync(
                this.Client,
                this.LinkUri,
                ResourceType.StoredProcedure,
                operationType,
                requestOptions,
                partitionKey,
                streamPayload,
                null,
                cancellationToken);

            return(this.Client.ResponseFactory.CreateStoredProcedureResponse(this, response));
        }
コード例 #24
0
 internal static Task <T> ProcessResourceOperationAsync <T>(
     CosmosClient client,
     Uri resourceUri,
     ResourceType resourceType,
     OperationType operationType,
     CosmosRequestOptions requestOptions,
     Func <CosmosResponseMessage, T> responseCreator,
     CancellationToken cancellationToken)
 {
     return(ExecUtils.ProcessResourceOperationAsync(
                client,
                resourceUri,
                resourceType,
                operationType,
                requestOptions,
                partitionKey: null,
                streamPayload: null,
                requestEnricher: null,
                responseCreator: responseCreator,
                cancellationToken: cancellationToken));
 }
コード例 #25
0
        internal static Task <CosmosResponseMessage> ProcessResourceOperationStreamAsync(
            CosmosClient client,
            Uri resourceUri,
            ResourceType resourceType,
            OperationType operationType,
            CosmosRequestOptions requestOptions,
            Object partitionKey,
            Stream streamPayload,
            Action <CosmosRequestMessage> requestEnricher,
            CancellationToken cancellationToken)
        {
            CosmosRequestMessage request = ExecUtils.GenerateCosmosRequestMessage(
                resourceUri,
                resourceType,
                operationType,
                requestOptions,
                partitionKey,
                streamPayload,
                requestEnricher);

            return(client.RequestHandler.SendAsync(request, cancellationToken));
        }
コード例 #26
0
        internal Task <CosmosResponseMessage> ProcessItemStreamAsync(
            object partitionKey,
            string itemId,
            Stream streamPayload,
            OperationType operationType,
            CosmosRequestOptions requestOptions,
            CancellationToken cancellationToken)
        {
            CosmosItemsCore.ValidatePartitionKey(partitionKey, requestOptions);
            Uri resourceUri = this.GetResourceUri(requestOptions, operationType, itemId);

            return(ExecUtils.ProcessResourceOperationStreamAsync(
                       this.container.Database.Client,
                       resourceUri,
                       ResourceType.Document,
                       operationType,
                       requestOptions,
                       partitionKey,
                       streamPayload,
                       null,
                       cancellationToken));
        }
コード例 #27
0
 private Task <CosmosResponseMessage> ContainerStreamFeedRequestExecutor(
     int?maxItemCount,
     string continuationToken,
     CosmosRequestOptions requestOptions,
     object state,
     CancellationToken cancellationToken)
 {
     return(ExecUtils.ProcessResourceOperationStreamAsync(
                client: this.client,
                resourceUri: this.database.LinkUri,
                resourceType: ResourceType.Collection,
                operationType: OperationType.ReadFeed,
                partitionKey: null,
                streamPayload: null,
                requestOptions: requestOptions,
                requestEnricher: request =>
     {
         CosmosQueryRequestOptions.FillContinuationToken(request, continuationToken);
         CosmosQueryRequestOptions.FillMaxItemCount(request, maxItemCount);
     },
                cancellationToken: cancellationToken));
 }
コード例 #28
0
        private Task <CosmosQueryResponse <CosmosUserDefinedFunctionSettings> > ContainerFeedRequestExecutor(
            int?maxItemCount,
            string continuationToken,
            CosmosRequestOptions options,
            object state,
            CancellationToken cancellationToken)
        {
            Debug.Assert(state == null);

            return(ExecUtils.ProcessResourceOperationAsync <CosmosQueryResponse <CosmosUserDefinedFunctionSettings> >(
                       this.container.Database.Client,
                       this.container.LinkUri,
                       ResourceType.UserDefinedFunction,
                       OperationType.ReadFeed,
                       options,
                       request =>
            {
                CosmosQueryRequestOptions.FillContinuationToken(request, continuationToken);
                CosmosQueryRequestOptions.FillMaxItemCount(request, maxItemCount);
            },
                       response => this.client.ResponseFactory.CreateResultSetQueryResponse <CosmosUserDefinedFunctionSettings>(response),
                       cancellationToken));
        }
コード例 #29
0
        private Task <CosmosQueryResponse <CosmosStoredProcedureSettings> > StoredProcedureFeedRequestExecutor(
            int?maxItemCount,
            string continuationToken,
            CosmosRequestOptions options,
            object state,
            CancellationToken cancellationToken)
        {
            Uri resourceUri = this.container.LinkUri;

            return(ExecUtils.ProcessResourceOperationAsync <CosmosQueryResponse <CosmosStoredProcedureSettings> >(
                       this.container.Database.Client,
                       resourceUri,
                       ResourceType.StoredProcedure,
                       OperationType.ReadFeed,
                       options,
                       request =>
            {
                CosmosQueryRequestOptions.FillContinuationToken(request, continuationToken);
                CosmosQueryRequestOptions.FillMaxItemCount(request, maxItemCount);
            },
                       response => this.client.ResponseFactory.CreateResultSetQueryResponse <CosmosStoredProcedureSettings>(response),
                       cancellationToken));
        }
コード例 #30
0
        internal static Task <T> CreateDatabaseCoreAsync <T>(
            CosmosDatabaseSettings databaseSettings,
            CosmosClient client,
            Func <CosmosResponseMessage, T> responseCreator,
            CosmosRequestOptions requestOptions = null,
            int?throughput = null,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            client.DocumentClient.ValidateResource(databaseSettings);

            Uri resourceUri = new Uri(Paths.Databases_Root, UriKind.Relative);

            return(ExecUtils.ProcessResourceOperationAsync <T>(
                       client,
                       resourceUri,
                       ResourceType.Database,
                       OperationType.Create,
                       requestOptions,
                       partitionKey: null,
                       streamPayload: databaseSettings.GetResourceStream(),
                       requestEnricher: (httpRequestMessage) => httpRequestMessage.AddThroughputHeader(throughput),
                       responseCreator: responseCreator,
                       cancellationToken: cancellationToken));
        }