public async Task <List <Product> > GetProductsAsync(string Id)
        {
            Shop res = null;

            try
            {
                res = await client.ReadDocumentAsync <Shop>(UriFactory.CreateDocumentUri(databaseName, collectionName, Id));
            }
            catch
            {
                throw new System.Exception($"Shop with id:{Id} was not found");
            }
            return(res.Products.Values.ToList());
        }
Ejemplo n.º 2
0
        public async Task Send <T>(ConsumeContext <T> context, ISagaPolicy <TSaga, T> policy, IPipe <SagaConsumeContext <TSaga, T> > next)
            where T : class
        {
            if (!context.CorrelationId.HasValue)
            {
                throw new SagaException("The CorrelationId was not specified", typeof(TSaga), typeof(T));
            }

            Document document = null;

            if (policy.PreInsertInstance(context, out var instance))
            {
                document = await PreInsertSagaInstance(context, instance).ConfigureAwait(false);
            }

            if (instance == null)
            {
                try
                {
                    ResourceResponse <Document> response = await _client
                                                           .ReadDocumentAsync(UriFactory.CreateDocumentUri(_databaseName, _collectionName, context.CorrelationId.ToString()), _requestOptions)
                                                           .ConfigureAwait(false);

                    document = response.Resource;
                }
                catch (DocumentClientException e) when(e.StatusCode == System.Net.HttpStatusCode.NotFound)
                {
                    // Couldn't find the document, swallowing exception
                }

                if (document != null)
                {
                    instance = JsonConvert.DeserializeObject <TSaga>(document.ToString());
                }
            }

            if (instance == null)
            {
                var missingSagaPipe =
                    new MissingPipe <TSaga, T>(_client, _databaseName, _collectionName, next, _documentDbSagaConsumeContextFactory, _requestOptions);

                await policy.Missing(context, missingSagaPipe).ConfigureAwait(false);
            }
            else
            {
                await SendToInstance(context, policy, next, instance, document).ConfigureAwait(false);
            }
        }
Ejemplo n.º 3
0
        public async Task <TModel> FetchItemAsync(string id)
        {
            var documentUri      = UriFactory.CreateDocumentUri(DatabaseId, CollectionId, id);
            var resourceResponse = await documentClient.ReadDocumentAsync(documentUri);

            return((TModel)((dynamic)resourceResponse.Resource));
        }
Ejemplo n.º 4
0
        public async Task <Document> ReadDocumentAsync(string documentId, RequestOptions options = null,
                                                       CancellationToken cancellationToken       = default(CancellationToken))
        {
            var uri = UriFactory.CreateDocumentUri(_databaseName, _collectionName, documentId);

            return(await _documentClient.ReadDocumentAsync(uri, options, cancellationToken));
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Generic version of ReadDocumentAsync that returns the queried document deserialized into the given generic type
        /// </summary>
        /// <typeparam name="T">The Type of the Document to read from DocumentDb</typeparam>
        /// <param name="client">The <see cref="IDocumentClient"/> this extension method is executed on</param>
        /// <param name="documentUri">The <see cref="Uri"/> of the document to read from DocumentDB</param>
        /// <param name="requestOptions">The <see cref="RequestOptions"/> used for calling DocumentDB</param>
        /// <returns>The Document read from DocumentDB, deserialized into the given generic Type</returns>
        internal static async Task <T> ReadDocumentAsync <T>(this IDocumentClient client, Uri documentUri, RequestOptions requestOptions)
        {
            ResourceResponse <Document> response;

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

            try
            {
                response = await client.ReadDocumentAsync(documentUri, requestOptions);
            }
            catch (DocumentClientException dce)
            {
                if (dce.StatusCode == HttpStatusCode.NotFound)
                {
                    return(default(T));
                }

                throw;
            }

            return(JsonConvert.DeserializeObject <T>(response.Resource.ToString()));
        }
Ejemplo n.º 6
0
        /// <inheritdoc/>
        public async Task <T> GetAsync <T>(string id)
            where T : BaseEntity
        {
            Uri documentUri = UriFactory.CreateDocumentUri(_database, _collection, id);

            return(await _documentClient.ReadDocumentAsync <T>(documentUri, new RequestOptions { PartitionKey = new PartitionKey(_partitionKey) }));
        }
Ejemplo n.º 7
0
        /// <inheritdoc/>
        public async Task <T> GetAsync <T>(string id)
            where T : BaseEntity
        {
            Uri documentUri = UriFactory.CreateDocumentUri(_database, _collection, id);

            return(await _documentClient.ReadDocumentAsync <T>(documentUri));
        }
Ejemplo n.º 8
0
        public async Task <ResourceResponse <Document> > UpdateState(DeviceState source, ILogger log)
        {
            log.LogInformation("Processing change message for device ID {DeviceId}", source.DeviceId);

            DeviceState target = null;

            try
            {
                var response = await client.ReadDocumentAsync(UriFactory.CreateDocumentUri(cosmosDBDatabase, cosmosDBCollection, source.DeviceId),
                                                              new RequestOptions { PartitionKey = new PartitionKey(source.DeviceId) });

                target = (DeviceState)(dynamic)response.Resource;

                // Merge properties
                target.Battery         = source.Battery ?? target.Battery;
                target.FlightMode      = source.FlightMode ?? target.FlightMode;
                target.Latitude        = source.Latitude ?? target.Latitude;
                target.Longitude       = source.Longitude ?? target.Longitude;
                target.Altitude        = source.Altitude ?? target.Altitude;
                target.AccelerometerOK = source.AccelerometerOK ?? target.AccelerometerOK;
                target.GyrometerOK     = source.GyrometerOK ?? target.GyrometerOK;
                target.MagnetometerOK  = source.MagnetometerOK ?? target.MagnetometerOK;
            }
            catch (DocumentClientException ex)
            {
                if (ex.StatusCode == System.Net.HttpStatusCode.NotFound)
                {
                    target = source;
                }
            }

            var collectionLink = UriFactory.CreateDocumentCollectionUri(cosmosDBDatabase, cosmosDBCollection);

            return(await client.UpsertDocumentAsync(collectionLink, target));
        }
Ejemplo n.º 9
0
        public async Task <TModel> FetchItemAsync(string id)
        {
            var documentUri = UriFactory.CreateDocumentUri(DatabaseId, CollectionId, id);
            var document    = await documentClient.ReadDocumentAsync(documentUri);

            return(document as TModel);
        }
Ejemplo n.º 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 <TResult> QueryById <TResult>(string id, Domain.RequestOptions options = null) where TResult : class
        {
            if (_databaseName == null)
            {
                throw new DataStoreException("Connect must be called to query CosmosDB");
            }

            try
            {
                var response = await _client.ReadDocumentAsync(UriFactory.CreateDocumentUri(_databaseName, _collectionName, id), options.ToRequestOptions(), _cancellationToken);

                if (response.StatusCode != HttpStatusCode.OK)
                {
                    return(null);
                }
                return((TResult)(dynamic)response.Resource);
            }
            catch (DocumentClientException e)
            {
                if (e.StatusCode == HttpStatusCode.NotFound)
                {
                    return(null);
                }
                throw;
            }
        }
        async Task<BotData> IBotDataStore<BotData>.LoadAsync(IAddress key, BotStoreType botStoreType,
            CancellationToken cancellationToken)
        {
            try
            {
                var entityKey = DocDbBotDataEntity.GetEntityKey(key, botStoreType);

                var response = await documentClient.ReadDocumentAsync(UriFactory.CreateDocumentUri(databaseId, collectionId, entityKey));

                // The Resource property of the response, of type IDynamicMetaObjectProvider, has a dynamic nature, 
                // similar to DynamicTableEntity in Azure storage. When casting to a static type, properties that exist in the static type will be 
                // populated from the dynamic type.
                DocDbBotDataEntity entity = (dynamic)response.Resource;
                return new BotData(response?.Resource.ETag, entity?.Data);
            }
            catch (DocumentClientException e)
            {
                if (e.StatusCode.HasValue && e.StatusCode.Value == HttpStatusCode.NotFound)
                {
                    return new BotData(string.Empty, null);
                }

                throw new HttpException(e.StatusCode.HasValue ? (int)e.StatusCode.Value : 0, e.Message, e);
            }
        }
Ejemplo n.º 13
0
        public async Task <LocationRecord> Get(Guid memberId, Guid recordId)
        {
            var result = await _documentClient.ReadDocumentAsync(GetLocationsDocumentUri(recordId),
                                                                 new RequestOptions { PartitionKey = new PartitionKey(memberId.ToString()) });

            return((LocationRecord)(dynamic)result.Resource);
        }
Ejemplo n.º 14
0
        public async Task <IActionResult> Get(string id)
        {
            var link = UriFactory.CreateDocumentUri("social", "results", id);

            try
            {
                var doc = await _documentClient.ReadDocumentAsync(link);

                var result = new Result()
                {
                    id    = id,
                    score = doc.Resource.GetPropertyValue <double>("score")
                };
                return(Ok(result));
            }
            catch (DocumentClientException ex)
            {
                if (ex.StatusCode == System.Net.HttpStatusCode.NotFound)
                {
                    // Text Analytics result is not ready yet
                    return(Ok(null));
                }

                throw ex;
            }
        }
Ejemplo n.º 15
0
        public static async Task <ResourceResponse <Document> > HandleEntityRetrieveAsync(string tableName, string partitionKey, string rowKey, IDocumentClient client, RequestOptions requestOptions, CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();
            Uri uri = UriFactory.CreateDocumentUri("TablesDB", tableName, rowKey);

            requestOptions = SetPartitionKey(requestOptions, partitionKey);
            return(await client.ReadDocumentAsync(uri.ToString(), requestOptions, cancellationToken));
        }
Ejemplo n.º 16
0
        public async Task <Recipe> GetAsync(Guid id)
        {
            var response = await client.ReadDocumentAsync(UriFactory.CreateDocumentUri(DatabaseId, CollectionId, id.ToString()));

            Recipe recipe = (dynamic)response.Resource;

            return(recipe);
        }
Ejemplo n.º 17
0
        public async Task <TModel> FetchItemAsync(TKey partitionKey, string id)
        {
            var documentUri      = UriFactory.CreateDocumentUri(DatabaseId, CollectionId, id);
            var resourceResponse = await documentClient.ReadDocumentAsync(documentUri, BuildRequestOptions(partitionKey));

            logger.LogDebug($"Read cost (in RU/s) : {resourceResponse.RequestCharge}");
            return((TModel)((dynamic)resourceResponse.Resource));
        }
Ejemplo n.º 18
0
        public async Task <T> Get <T>(string id) where T : class, IDocument
        {
            try
            {
                var response = await _client.ReadDocumentAsync(UriFactory.CreateDocumentUri(_databaseId, _documentCollection.Id, GenerateDocumentId <T>(id)));

                var adapter = JsonConvert.DeserializeObject <DocumentAdapter <T> >(response.Resource.ToString());
                return(adapter?.Document);
            }
            catch (DocumentClientException exception)
            {
                if (exception.StatusCode == HttpStatusCode.NotFound)
                {
                    return(null);
                }
                throw;
            }
        }
        public async Task <DataResult <T> > Get(string id)
        {
            var documentUri = UriFactory.CreateDocumentUri(_dataAccessOptions.DatabaseName, _dataAccessOptions.CollectionName, id);
            var response    = await _documentClient.ReadDocumentAsync <T>(documentUri);

            var isSuccessful = true;

            return(new DataResult <T>(isSuccessful, response.Document));
        }
Ejemplo n.º 20
0
        public async Task <IResourceResponse <Document> > ReadAsync(
            IDocumentClient client,
            StorageConfig cfg,
            string docId)
        {
            var collectionLink = $"/dbs/{cfg.DocumentDbDatabase}/colls/{cfg.DocumentDbCollection}";

            return(await client.ReadDocumentAsync($"{collectionLink}/docs/{docId}"));
        }
        public async Task <Todo> GetTodoAsync(string userId, string id)
        {
            var doc = await documentClient.ReadDocumentAsync <Todo>(UriFactory.CreateDocumentUri(dbName, collectionName, id)
                                                                    , new RequestOptions()
            {
                PartitionKey = new PartitionKey(userId)
            });

            return(doc.Document);
        }
Ejemplo n.º 22
0
        public async Task UpdateAvailableInventoryAsync(IDocumentClient documentClient, OrderLineItem lineItem)
        {
            var documentUri = UriFactory.CreateDocumentUri(_databaseName, _containerName, lineItem.ProductId);

            var productResponse = await documentClient.ReadDocumentAsync <Product>(documentUri, new RequestOptions { PartitionKey = new PartitionKey(lineItem.Category) });

            productResponse.Document.AvailableInventory -= lineItem.Quantity;

            await documentClient.UpsertDocumentAsync(_containerUri, productResponse.Document);
        }
Ejemplo n.º 23
0
 public async Task <TEntity> Get(string id)
 {
     try
     {
         return((await _documentClient.ReadDocumentAsync <TEntity>(CreateDocumentUri(id), RequestOptions)).Document);
     }
     catch (DocumentClientException e) when(e.StatusCode == HttpStatusCode.NotFound)
     {
         return(null);
     }
 }
        public async Task <T> Read(string id)
        {
            try
            {
                var response = await _documentClient.ReadDocumentAsync(GetUri(id));

                EntityDocument <T> responseDocument = (dynamic)response.Resource;
                return(responseDocument.Entity);
            }
            catch (DocumentClientException dce) when(dce.StatusCode == HttpStatusCode.NotFound)
            {
                return(default !);
Ejemplo n.º 25
0
        public async Task <Stop> GetStop(string stopId)
        {
            var stop = await _client.ReadDocumentAsync <Stop>(
                UriFactory.CreateDocumentUri(_settings.CosmosDatabaseName, _settings.CosmosCollectionName, stopId),
                new RequestOptions
            {
                PartitionKey = new PartitionKey("TFStop")
            }
                );

            return(stop.Document);
        }
Ejemplo n.º 26
0
        public virtual async Task <TDocument> GetById(Guid id, RequestOptions requestOptions = null, CancellationToken cancellationToken = default)
        {
            try
            {
                var response = await DocumentClient.ReadDocumentAsync <TDocument>(UriFactory.CreateDocumentUri(DatabaseName, CollectionName, id.ToString()), requestOptions, cancellationToken).ConfigureAwait(false);

                return(response.Document);
            }
            catch (DocumentClientException ex)
            {
                if (ex.StatusCode == HttpStatusCode.NotFound)
                {
                    return(default);
        public async Task <IActionResult> GetProduct(string id)
        {
            try
            {
                var documentResponse = await _cosmosClient.ReadDocumentAsync <Product>(UriFactory.CreateDocumentUri(Constants.CosmosDBName, CosmosCollectionName, id));

                return(Ok(documentResponse.Document));
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error getting document with id <{id}>: {ex.ToString()}");
                return(StatusCode(501));
            }
        }
        public virtual async Task <T> GetAsync(string id)
        {
            try
            {
                Document document =
                    await _client.ReadDocumentAsync(_settings.CreateDocumentUri(id));

                return((T)(dynamic)document);
            }
            catch (DocumentClientException e)
                when(e.StatusCode == HttpStatusCode.NotFound)
                {
                    return(null);
                }
        }
        public async Task PerformTest(IDocumentClient documentClient, CosmosDataStoreConfiguration configuration, CosmosCollectionConfiguration cosmosCollectionConfiguration)
        {
            var requestOptions = new RequestOptions {
                ConsistencyLevel = ConsistencyLevel.Session, PartitionKey = _partitionKey
            };

            ResourceResponse <Document> resourceResponse = await documentClient.UpsertDocumentAsync(
                configuration.GetRelativeCollectionUri(cosmosCollectionConfiguration.CollectionId),
                _document,
                requestOptions);

            requestOptions.SessionToken = resourceResponse.SessionToken;

            await documentClient.ReadDocumentAsync(resourceResponse.Resource.SelfLink, requestOptions);
        }
        public async Task <Account> GetAccount(string email)
        {
            try
            {
                var entity = await _documentClient.ReadDocumentAsync <DocumentDbAccountEntity>(
                    CreateDocumentUri(email),
                    new RequestOptions { PartitionKey = new PartitionKey("FYP") });

                return(ToAccount(entity));
            }
            catch (DocumentClientException e)
            {
                throw new StorageErrorException($"Failed to fetch account with email {email}", (int)e.StatusCode);
            }
        }