public async Task AddConversation(Conversation conversation)
 {
     try
     {
         var senderUsername   = "******" + conversation.Participants[0];
         var receiverUsername = "******" + conversation.Participants[1];
         var senderEntity     = ToEntity(senderUsername, conversation);
         var receiverEntity   = ToEntity(receiverUsername, conversation);
         try
         {
             await _documentClient.CreateDocumentAsync(DocumentCollectionUri, senderEntity);
         }
         catch (DocumentClientException e)
         {
             if (e.StatusCode != HttpStatusCode.Conflict)
             {
                 throw new StorageErrorException($"Failed to create conversation {conversation.Id}",
                                                 e, (int)e.StatusCode);
             }
         }
         await _documentClient.CreateDocumentAsync(DocumentCollectionUri, receiverEntity);
     }
     catch (DocumentClientException e)
     {
         if (e.StatusCode == HttpStatusCode.Conflict)
         {
             throw new ConversationAlreadyExistsException($"Conversation {conversation.Id} already exists");
         }
         throw new StorageErrorException($"Failed to create conversation {conversation.Id}",
                                         e, (int)e.StatusCode);
     }
 }
        /// <summary>
        /// Creates a document and its parent containers (database, collection) if they do not exist.
        /// </summary>
        /// <param name="dbId">Database id.</param>
        /// <param name="collectionId">Collection id.</param>
        /// <param name="document">Object to create.</param>
        /// <param name="partitionKeyField">Request options</param>
        /// <param name="requestOptions">Request options</param>
        /// <param name="disableIdGeneration">Disables automatic id generation</param>
        /// <returns>Created document</returns>
        public async Task <ResourceResponse <Document> > CreateDocumentAndContainersAsync(
            string dbId,
            string collectionId,
            object document,
            string partitionKeyField,
            RequestOptions requestOptions = null,
            bool disableIdGeneration      = false)
        {
            Code.ExpectsNotNullOrWhiteSpaceArgument(dbId, nameof(dbId), TaggingUtilities.ReserveTag(0x2381b161 /* tag_961f7 */));
            Code.ExpectsNotNullOrWhiteSpaceArgument(collectionId, nameof(collectionId), 0);
            Code.ExpectsArgument(document, nameof(document), TaggingUtilities.ReserveTag(0x2381b162 /* tag_961f8 */));

            Uri collectionUri = UriFactory.CreateDocumentCollectionUri(dbId, collectionId);

            IDocumentClient client = await GetDocumentClientAsync().ConfigureAwait(false);

            return(await DocumentDbAdapter.ExecuteAndLogAsync(TaggingUtilities.ReserveTag(0x2381b163 /* tag_961f9 */),
                                                              async() =>
            {
                try
                {
                    return await client.CreateDocumentAsync(collectionUri, document, requestOptions, disableIdGeneration).ConfigureAwait(false);
                }
                catch (DocumentClientException e) when(e.StatusCode == HttpStatusCode.NotFound)
                {
                    // We get NotFound exception either when db and/or collection is not yet created. We create the missing component before retrying to create the document.
                    await GetOrCreateDbAndCollectionAsync(dbId, collectionId, partitionKeyField).ConfigureAwait(false);

                    return await client.CreateDocumentAsync(collectionUri, document, requestOptions, disableIdGeneration).ConfigureAwait(false);
                }
            }).ConfigureAwait(false));
        }
Beispiel #3
0
        /// <summary>
        /// Insert entity to database even though collection for this entity wasn't created yet.
        /// </summary>
        /// <typeparam name="T">Type of entity to insert</typeparam>
        /// <param name="entity">Entity to insert</param>
        public async Task <bool> InsertAsync <T>(T entity, string collectionName) where T : IBaseEntity
        {
            await GetDBClient();

            await _documentClient.CreateDocumentCollectionIfNotExistsAsync(UriFactory.CreateDatabaseUri(cosmosDBName),
                                                                           new DocumentCollection { Id = typeof(T).Name });

            var result = await _documentClient.CreateDocumentAsync(UriFactory.CreateDocumentCollectionUri(cosmosDBName, collectionName), entity);

            return(result.StatusCode == System.Net.HttpStatusCode.Created);
        }
        public async Task GivenACreateRequest_WithSessionConsistency_ThenTheResponseHeadersContainTheSessionToken()
        {
            _innerClient
            .CreateDocumentAsync("coll", (1, 2), Arg.Is <RequestOptions>(o => o.ConsistencyLevel == ConsistencyLevel.Session && o.SessionToken == "1"))
            .Returns(CosmosDbMockingHelper.CreateResourceResponse(new Document(), HttpStatusCode.OK, new NameValueCollection {
                { CosmosDbHeaders.SessionToken, "2" }
            }));

            _requestHeaders.Add(CosmosDbHeaders.ConsistencyLevel, "Session");
            _requestHeaders.Add(CosmosDbHeaders.SessionToken, "1");

            await _fhirClient.CreateDocumentAsync("coll", (1, 2));

            await _cosmosResponseProcessor.Received(1).ProcessResponse(Arg.Any <ResourceResponseBase>());
        }
Beispiel #5
0
        public async Task <TModel> CreateItemAsync(TModel item)
        {
            var documentUri      = UriFactory.CreateDocumentCollectionUri(DatabaseId, CollectionId);
            var resourceResponse = await documentClient.CreateDocumentAsync(documentUri, item);

            return((TModel)((dynamic)resourceResponse.Resource));
        }
Beispiel #6
0
        private static void InsertSession(IDocumentClient client)
        {
            //Create some data to store
            var session = CreateSession();

            client.CreateDocumentAsync(UriFactory.CreateDocumentCollectionUri(DatabaseName, CollectionName), session).GetAwaiter().GetResult();
        }
        public async Task <int> AddAsync <TDocument>(TDocument[] documents,
                                                     CancellationToken cancellationToken = default
                                                     )
            where TDocument : EventStoreDocument
        {
            await ExecuteAsync(async dbCol =>
            {
                foreach (var doc in documents)
                {
                    await _client.CreateDocumentAsync(dbCol.DocumentCollectionUri,
                                                      doc,
                                                      new RequestOptions
                    {
                        PartitionKey           = new PartitionKey(doc.StreamId),
                        JsonSerializerSettings = _jsonSettings
                    },
                                                      true,
                                                      cancellationToken
                                                      );
                }
            },
                               cancellationToken : cancellationToken
                               );

            return(documents.Length);
        }
Beispiel #8
0
 public async Task CreateDocumentAsync <T>(T document)
 {
     await _client.CreateDocumentAsync(UriFactory.CreateDocumentCollectionUri(
                                           _databaseId,
                                           typeof(T).Name),
                                       document);
 }
Beispiel #9
0
        private static async Task <bool> CheckList(IDocumentClient client, string link)
        {
            var CreateDatabase = Environment.GetEnvironmentVariable("CreateDatabase");

            if (CreateDatabase != null && CreateDatabase == "true")
            {
                var databaseDefinition = new Database {
                    Id = DatabaseId
                };
                await client.CreateDatabaseIfNotExistsAsync(databaseDefinition);

                var collectionDefinition = new DocumentCollection {
                    Id = CollectionId
                };
                await client.CreateDocumentCollectionIfNotExistsAsync(UriFactory.CreateDatabaseUri(DatabaseId),
                                                                      collectionDefinition);
            }

            var response = client.CreateDocumentQuery <Item>(UriFactory.CreateDocumentCollectionUri(DatabaseId, CollectionId), $"select * from c WHERE  c.Url='{link}'").ToList();

            if (response.Count > 0)
            {
                return(true);
            }

            await client.CreateDocumentAsync(
                UriFactory.CreateDocumentCollectionUri(DatabaseId, CollectionId),
                new Item()
            {
                Url = link
            });

            return(false);
        }
Beispiel #10
0
        public async Task <ResourceResponse <Document> > LoadNoReplace(
            IAmDocument doc)
        {
            ResourceResponse <Document> r;

            try
            {
                r = await client.ReadDocumentAsync(
                    UriFactory.CreateDocumentUri(
                        databaseId,
                        collectionId,
                        doc.Id),
                    new RequestOptions {
                    PartitionKey = new PartitionKey(doc.PartitionKey)
                });
            }
            catch (DocumentClientException de)
            {
                if (de.StatusCode == HttpStatusCode.NotFound)
                {
                    r = await client.CreateDocumentAsync(
                        UriFactory.CreateDocumentCollectionUri(
                            databaseId,
                            collectionId),
                        doc);
                }
                else
                {
                    throw;
                }
            }

            return(r);
        }
        public async Task <TEntity> CreateAsync <TEntity>(TEntity entity, Domain.RequestOptions options = null) where TEntity : class
        {
            if (entity == null)
            {
                throw new ArgumentNullException(nameof(entity));
            }
            if (_databaseName == null)
            {
                throw new DataStoreException("Connect must be called to update CosmosDB");
            }

            try
            {
                var response = await _client.CreateDocumentAsync(UriFactory.CreateDocumentCollectionUri(_databaseName, _collectionName), entity, options.ToRequestOptions(), true, _cancellationToken);

                if (response.StatusCode == HttpStatusCode.OK || response.StatusCode == HttpStatusCode.Created)
                {
                    return(entity);
                }
                throw new DocumentUpdateException("Unable to create product. Invalid status returned from CosmosDB.");
            }
            catch (DocumentClientException e)
            {
                if (e.StatusCode == HttpStatusCode.NotFound)
                {
                    throw new DocumentUpdateException("Unable to create product. Invalid status returned from CosmosDB.");
                }
                throw;
            }
        }
 public async Task Put(T value)
 {
     if (Get(value) == null)
     {
         await _documentClient.CreateDocumentAsync(GetUri(), ValueObjectDocument <T> .Create(_valueType, value));
     }
 }
Beispiel #13
0
        public async Task <TModel> CreateItemAsync(TModel item)
        {
            var documentUri = UriFactory.CreateDocumentCollectionUri(DatabaseId, CollectionId);
            var model       = await documentClient.CreateDocumentAsync(documentUri, item);

            return(model as TModel);
        }
        //public async Task<IActionResult> Post([FromBody] Worker item)
        public async Task <System.Net.HttpStatusCode> Post([FromBody] Worker item)
        {
            var response = await _documentClient.CreateDocumentAsync(UriFactory.CreateDocumentCollectionUri(databaseId, collectionId), item);

            return(response.StatusCode);
            //return Ok();
        }
 public virtual async Task <TDocument> Create(TDocument document)
 {
     return((TDocument)(dynamic)(await _documentClient.CreateDocumentAsync(
                                     await _collectionProvider.GetCollectionDocumentsLink(),
                                     document))
            .Resource);
 }
        public async Task <IActionResult> Post([FromBody] Item item)
        {
            //we can add a try catch block or return a response from this block
            var response = await _documentClient.CreateDocumentAsync(UriFactory.CreateDocumentCollectionUri(databaseId, collectionId), item);

            return(Ok());
        }
Beispiel #17
0
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequest request,
            [CosmosDB(ConnectionStringSetting = "DBConnectionString")] IDocumentClient client,
            ILogger log)
        {
            log.LogInformation("UpdateTokenFunction - Invoked");

            TokenStatusEnume status;
            Token            token = new Token();

            Enum.TryParse(request.Query["status"], out status);
            string tokenNo = request.Query["tokenNo"];

            Uri tokenCollectUri = UriFactory.CreateDocumentCollectionUri("TokenManagerDB", "Token");
            var options         = new FeedOptions {
                MaxItemCount = 1, EnableCrossPartitionQuery = true
            };

            IDocumentQuery <Token> queryRes = client.CreateDocumentQuery <Token>(tokenCollectUri, options)
                                              .Where(token => token.TokenNo == tokenNo)
                                              .AsDocumentQuery();

            if (queryRes.HasMoreResults)
            {
                token        = (Token)queryRes.ExecuteNextAsync().Result.First();
                token.Status = status;
                token.CurrentEstimatedWaitingTime = 0;
                await client.CreateDocumentAsync(tokenCollectUri, token);
            }

            log.LogInformation("UpdateTokenFunction - Completed");
            return(new OkObjectResult(token));
        }
Beispiel #18
0
        public static async Task <ResourceResponse <Document> > HandleEntityFeedInsertAsync(string tableName, IDocumentClient client, Document document, RequestOptions requestOptions, CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();
            Uri uri = UriFactory.CreateDocumentCollectionUri("TablesDB", tableName);

            return(await client.CreateDocumentAsync(uri.ToString(), document, requestOptions, disableAutomaticIdGeneration : true));
        }
Beispiel #19
0
        public async Task GivenACreateRequest_WithSessionConsistency_ThenTheResponseHeadersContainTheSessionToken()
        {
            _innerClient
            .CreateDocumentAsync("coll", (1, 2), Arg.Is <RequestOptions>(o => o.ConsistencyLevel == ConsistencyLevel.Session && o.SessionToken == "1"))
            .Returns(CreateResourceResponse(new Document(), HttpStatusCode.OK, new NameValueCollection {
                { CosmosDbHeaders.SessionToken, "2" }
            }));

            _requestHeaders.Add(CosmosDbHeaders.ConsistencyLevel, "Session");
            _requestHeaders.Add(CosmosDbHeaders.SessionToken, "1");

            await _fhirClient.CreateDocumentAsync("coll", (1, 2));

            Assert.True(_responseHeaders.TryGetValue(CosmosDbHeaders.SessionToken, out var values));
            Assert.Equal("2", values.ToString());
        }
        public async Task <Document> CreateDocumentAsync(object document, RequestOptions options = null,
                                                         bool disableAutomaticIdGeneration       = false, CancellationToken cancellationToken = default(CancellationToken))
        {
            var uri = UriFactory.CreateDocumentCollectionUri(_databaseName, _collectionName);

            return(await _documentClient.CreateDocumentAsync(uri, document, options, disableAutomaticIdGeneration, cancellationToken));
        }
        public async Task <ExportJobOutcome> CreateExportJobAsync(ExportJobRecord jobRecord, CancellationToken cancellationToken)
        {
            EnsureArg.IsNotNull(jobRecord, nameof(jobRecord));

            var cosmosExportJob = new CosmosExportJobRecordWrapper(jobRecord);

            try
            {
                ResourceResponse <Document> result = await _documentClient.CreateDocumentAsync(
                    _collectionUri,
                    cosmosExportJob,
                    new RequestOptions()
                {
                    PartitionKey = new PartitionKey(CosmosDbExportConstants.ExportJobPartitionKey)
                },
                    disableAutomaticIdGeneration : true,
                    cancellationToken : cancellationToken);

                return(new ExportJobOutcome(jobRecord, WeakETag.FromVersionId(result.Resource.ETag)));
            }
            catch (DocumentClientException dce)
            {
                if (dce.StatusCode == HttpStatusCode.RequestEntityTooLarge)
                {
                    throw new RequestRateExceededException(dce.RetryAfter);
                }

                _logger.LogError(dce, "Unhandled Document Client Exception");
                throw;
            }
        }
Beispiel #22
0
        public async Task <T> CreateAsync(T item)
        {
            var collectionUri = UriFactory.CreateDocumentCollectionUri(_databaseId, _collectionId);
            var result        = await _client.CreateDocumentAsync(collectionUri, item).ConfigureAwait(false);

            return(JsonConvert.DeserializeObject <T>(result.Resource.ToString()));
        }
Beispiel #23
0
        private async Task StoreConfigRecordAsync(
            IDocumentClient client,
            DocumentDbConfig dbConfig,
            ServiceConfigRecord newRecord,
            Document existingDocument)
        {
            var collectionUri = GetDocumentCollectionUri(dbConfig);

            if (existingDocument == null)
            {
                // No record exists yet. Use the creation method to ensure failure if another process has modified the
                // record that a failure is produced.
                await client.CreateDocumentAsync(collectionUri, newRecord);
            }
            else
            {
                // Add IfMatch header to ensure the record has not been changed by another process.
                RequestOptions options = new RequestOptions
                {
                    AccessCondition = new AccessCondition
                    {
                        Condition = existingDocument.ETag,
                        Type      = AccessConditionType.IfMatch
                    }
                };

                await client.UpsertDocumentAsync(collectionUri, newRecord, options);
            }
        }
Beispiel #24
0
        public async Task <Map> Create(Map map)
        {
            var mapDocument = new MapDocument
            {
                Id    = map.Id,
                Nodes = map.Nodes.Values.Select(ToNodeDocument),
                Edges = map.Nodes.Values.SelectMany(ToEdgeDocuments)
            };

            var collectionUri = UriFactory.CreateDocumentCollectionUri(_databaseId, CollectionId);

            try
            {
                await _documentClient.CreateDocumentAsync(collectionUri, mapDocument);
            }
            catch (DocumentClientException dce)
            {
                if (dce.Error.Code == "Conflict")
                {
                    return(null); // map with the same ID already exists
                }

                throw;
            }

            return(map);
        }
        public async Task <string> CreateTodoAsync(Todo todo)
        {
            var document = await documentClient.CreateDocumentAsync(
                UriFactory.CreateDocumentCollectionUri(dbName, collectionName),
                todo);

            return(document.Resource.Id);
        }
Beispiel #26
0
        public async Task <T> CreateItem(T item)
        {
            item.CreatedUtc = DateTime.UtcNow;

            var document = await _client.CreateDocumentAsync(_collectionUri, item);

            return((T)(dynamic)document.Resource);
        }
        /// <inheritdoc/>
        public async Task <T> CreateAsync <T>(T item)
        {
            Document document = await _documentClient.CreateDocumentAsync(_collectionUri, item);

            T obj = (dynamic)document;

            return(obj);
        }
Beispiel #28
0
        public async Task <TModel> CreateItemAsync(TKey partitionKey, TModel item)
        {
            var documentUri      = UriFactory.CreateDocumentCollectionUri(DatabaseId, CollectionId);
            var resourceResponse = await documentClient.CreateDocumentAsync(documentUri, item, BuildRequestOptions(partitionKey));

            logger.LogDebug($"Create cost (in RU/s) : {resourceResponse.RequestCharge}");
            return((TModel)((dynamic)resourceResponse.Resource));
        }
        public async Task <DataResult <string> > CreateNewItem(T item)
        {
            var response = await _documentClient.CreateDocumentAsync(_documentCollectionUri, item);

            var isSuccessful = response.StatusCode == HttpStatusCode.Created;

            return(new DataResult <string>(isSuccessful, response.ActivityId));
        }
Beispiel #30
0
        public async Task <IResourceResponse <Document> > CreateAsync(
            IDocumentClient client,
            StorageConfig cfg,
            Resource resource)
        {
            var collectionLink = $"/dbs/{cfg.DocumentDbDatabase}/colls/{cfg.DocumentDbCollection}";

            return(await client.CreateDocumentAsync(collectionLink, resource));
        }
Beispiel #31
0
 private static void InsertSession(IDocumentClient client)
 {
     //Create some data to store
     var session = CreateSession();
     client.CreateDocumentAsync(UriFactory.CreateDocumentCollectionUri(DatabaseName, CollectionName), session).GetAwaiter().GetResult();
 }