public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", Route = null)] HttpRequest req,
            [CosmosDB(ConnectionStringSetting = "DBConnectionString")] IDocumentClient client,
            ILogger log)
        {
            log.LogInformation("GetCounterDisplayFunction - Invoked");

            Uri tokenCollectUri = UriFactory.CreateDocumentCollectionUri("TokenManagerDB", "Token");
            var options         = new FeedOptions {
                EnableCrossPartitionQuery = true
            };
            List <CounterDisplay> counterDisplays = new List <CounterDisplay>();

            IDocumentQuery <Token> queryRes = client.CreateDocumentQuery <Token>(tokenCollectUri, options)
                                              .Where(token => token.Status == TokenStatusEnume.InCounter)
                                              .AsDocumentQuery();

            if (queryRes.HasMoreResults)
            {
                foreach (Token token in queryRes.ExecuteNextAsync().Result)
                {
                    var counterData = counterDisplays.Where(x => x.CounterNo == token.CounterNo);
                    if (counterData != null && counterData.Any())
                    {
                        counterData.First().TokenNo = token.TokenNo;
                    }
                    else
                    {
                        counterDisplays.Add(new CounterDisplay()
                        {
                            TokenNo = token.TokenNo, CounterNo = token.CounterNo.Value
                        });
                    }
                }
            }

            log.LogInformation("GetCounterDisplayFunction - Completed");

            return(new OkObjectResult(counterDisplays.OrderBy(x => x.CounterNo)));
        }
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequest request,
            [CosmosDB(ConnectionStringSetting = "DBConnectionString")] IDocumentClient client,
            ILogger log)
        {
            log.LogInformation("ServeTokenFunction - Invoked");

            TransactionTypeEnume transactionType;
            Token token = new Token();

            Enum.TryParse(request.Query["transactionType"], out transactionType);
            int counterNo = int.Parse(request.Query["CounterNo"]);

            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.TransactionType == transactionType && token.Status == TokenStatusEnume.InQueue)
                                              .OrderBy(token => token.TokenNo)
                                              .AsDocumentQuery();

            if (queryRes.HasMoreResults)
            {
                var data = queryRes.ExecuteNextAsync().Result;
                if (!data.Any())
                {
                    return(new OkObjectResult("No tokens in queue."));
                }
                token        = (Token)data.First();
                token.Status = TokenStatusEnume.InCounter;
                token.CurrentEstimatedWaitingTime = 0;
                token.CounterNo = counterNo;
                await client.UpsertDocumentAsync(tokenCollectUri, token);
            }

            log.LogInformation("ServeTokenFunction - Completed");
            return(new OkObjectResult(token));
        }
예제 #3
0
        public async Task <List <T> > GetResult(Expression <Func <T, bool> > predicate)
        {
            try
            {
                var query = client.CreateDocumentQuery <T>(
                    UriFactory.CreateDocumentCollectionUri(DatabaseId, CollectionId),
                    new FeedOptions {
                    MaxItemCount = -1, EnableCrossPartitionQuery = true
                })
                            .Where(predicate)
                            .AsDocumentQuery();
                query.GetType();

                var results = new List <T>();
                results.AddRange(await query.ExecuteNextAsync <T>());
                return(results);
            }
            catch (Exception)
            {
                throw;
            }
        }
        public CollectionUpgradeManagerTests()
        {
            var factory = Substitute.For <ICosmosDbDistributedLockFactory>();
            var cosmosDbDistributedLock   = Substitute.For <ICosmosDbDistributedLock>();
            var collectionVersionWrappers = Substitute.For <IQueryable <CollectionVersion>, IDocumentQuery <CollectionVersion> >();
            var optionsMonitor            = Substitute.For <IOptionsMonitor <CosmosCollectionConfiguration> >();

            optionsMonitor.Get(Constants.CollectionConfigurationName).Returns(_cosmosCollectionConfiguration);

            factory.Create(Arg.Any <IDocumentClient>(), Arg.Any <Uri>(), Arg.Any <string>()).Returns(cosmosDbDistributedLock);
            cosmosDbDistributedLock.TryAcquireLock().Returns(true);

            _client = Substitute.For <IDocumentClient>();
            _client.CreateDocumentQuery <CollectionVersion>(Arg.Any <string>(), Arg.Any <SqlQuerySpec>(), Arg.Any <FeedOptions>())
            .Returns(collectionVersionWrappers);

            collectionVersionWrappers.AsDocumentQuery().ExecuteNextAsync <CollectionVersion>().Returns(new FeedResponse <CollectionVersion>(new List <CollectionVersion>()));

            var updaters = new IFhirCollectionUpdater[] { new FhirCollectionSettingsUpdater(_cosmosDataStoreConfiguration, optionsMonitor, NullLogger <FhirCollectionSettingsUpdater> .Instance), };

            _manager = new FhirCollectionUpgradeManager(updaters, _cosmosDataStoreConfiguration, optionsMonitor, factory, NullLogger <FhirCollectionUpgradeManager> .Instance);
        }
        private static async Task DeleteDocuments(IDocumentClient client)
        {
            Console.WriteLine(">>> Delete Documents <<<");
            Console.WriteLine();
            Console.WriteLine("Quering for documents to be deleted");

            //const string sql = "SELECT VALUE c._self FROM c WHERE STARTSWITH(c.name, 'Vasco') = true";
            const string sql            = "SELECT VALUE c._self FROM c";
            Uri          collectionLink = UriFactory.CreateDocumentCollectionUri(DatabaseId, CollectionId);

            List <string> documentLinks = client.CreateDocumentQuery <string>(collectionLink, sql, new FeedOptions {
                EnableCrossPartitionQuery = true
            }).ToList();

            //new RequestOptions {PartitionKey = new PartitionKey("Vasco")}
            Console.WriteLine($"Found {documentLinks.Count} documents to be deleted");
            foreach (var documentLink in documentLinks)
            {
                await client.DeleteDocumentAsync(documentLink);
            }
            Console.WriteLine($"Deleted {documentLinks.Count} documents");
        }
예제 #6
0
        public async Task <HGV> method(string id)
        {
            try
            {
                var PrimaryKey = Constants.PrimaryKey;
                var url        = Constants.Uri;
                _client = new DocumentClient(new Uri(url), PrimaryKey);
                //Inserting to cosmos
                var record = new HGV
                {
                    HGVName = "TestHGV",
                    Country = "United States",
                };
                var ans = await _client.CreateDatabaseIfNotExistsAsync(new Database { Id = DatabaseId });

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

                var document = await _client.CreateDocumentAsync(
                    UriFactory.CreateDocumentCollectionUri(DatabaseId, CollectionId)
                    , record);

                HGV hgvrecord = _client.CreateDocumentQuery <HGV>(
                    UriFactory.CreateDocumentCollectionUri(DatabaseId, CollectionId))
                                .Where(v => v.HGVName == "TestHGV")
                                .AsEnumerable()
                                .FirstOrDefault();

                //Getting data from cosmos based on id
                HGV document1 = _client.ReadDocumentAsync <HGV>(UriFactory.CreateDocumentUri(DatabaseId, CollectionId, id)).Result;
                return(document1);
            }
            catch (Exception e)
            {
                throw e;
            }
        }
예제 #7
0
        public async Task CreateMovie_creates_document_correctly(Movie movie)
        {
            // Arrange
            movie.ETag = default;
            IDocumentClient client = DocumentClient;
            var             sut    = new CosmosDbMovieRepository(client, Collection);

            // Act
            await sut.CreateMovie(movie);

            // Assert
            IQueryable <MovieDocument> query =
                from d in client.CreateDocumentQuery <MovieDocument>()
                where
                d.Discriminator == nameof(MovieDocument) &&
                d.Id == movie.Id
                select d;

            MovieDocument actual = await query.SingleOrDefault();

            actual.Should().BeEquivalentTo(new
            {
                movie.Id,
                movie.Title,
                Screenings = from s in movie.Screenings
                             select new
                {
                    s.Id,
                    s.TheaterId,
                    s.TheaterName,
                    s.Seats,
                    s.ScreeningTime,
                    s.DefaultFee,
                    s.ChildrenFee,
                    s.CreatedAt,
                },
                movie.CreatedAt,
            });
        }
예제 #8
0
        public static async Task <ActionResult <IList <ListTeam> > > ListTeams(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "teams")] HttpRequest req,
            [CosmosDB(
                 databaseName: "IdentityHistory",
                 collectionName: "SlackUsers",
                 ConnectionStringSetting = "CosmosDBConnection")] IDocumentClient client,
            ILogger log)
        {
            // XXX TeamId はパーティションキーのはずなんだが。
            // これかな?
            // https://github.com/Azure/azure-cosmos-dotnet-v2/issues/720

            /*
             * [2020/03/15 16:30:29] System.Private.CoreLib: Exception while executing function: ListTeams.
             * Microsoft.Azure.WebJobs.Host: Exception binding parameter 'teams'.
             * Microsoft.Azure.DocumentDB.Core: Distict query requires a matching order by in order to return a continuation token.
             * If you would like to serve this query through continuation tokens,
             * then please rewrite the query in the form
             * 'SELECT DISTINCT VALUE c.blah FROM c ORDER BY c.blah'
             * and please make sure that there is a range index on 'c.blah'.
             */
            log.LogInformation("C# HTTP trigger function processed a request.");

            // XXX いい感じにパーティション問い合わせができない。。。
            Uri collectionUri = UriFactory.CreateDocumentCollectionUri("IdentityHistory", "SlackUsers");
            IDocumentQuery <ListTeam> query = client.CreateDocumentQuery <ListTeam>(collectionUri)
                                              .AsDocumentQuery();

            // XXX 1件しかワークスペースサポートしていないので1件だけ取っておく。。。ありえん。
            IList <ListTeam> responseList = new List <ListTeam>();

            if (query.HasMoreResults)
            {
                responseList.Add((await query.ExecuteNextAsync <ListTeam>()).First());
            }

            return(new OkObjectResult(responseList));
        }
예제 #9
0
        private static async Task QueryDocumentsWithPaging(IDocumentClient client)
        {
            Console.WriteLine(">>> Query Documents (paged results) <<<");
            Console.WriteLine("Querying for all documents");

            const string sql     = "SELECT * FROM c";
            FeedOptions  options = new FeedOptions {
                EnableCrossPartitionQuery = true
            };

            IDocumentQuery <dynamic> query = client.CreateDocumentQuery(MyStoreCollectionUri, sql, options).AsDocumentQuery();

            while (query.HasMoreResults)
            {
                FeedResponse <dynamic> documents = await query.ExecuteNextAsync();

                foreach (dynamic document in documents)
                {
                    Console.WriteLine($" Id: {document.id}; Name: {document.name};");
                }
            }
            Console.WriteLine();
        }
        public async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "orders")] HttpRequest req,
            [CosmosDB(
                 databaseName: "%CosmosDbConfiguration:DatabaseName%",
                 collectionName: COLLECTIONNAME,
                 ConnectionStringSetting = "CosmosDbConfiguration:ConnectionString")] IDocumentClient documentClient,
            ILogger log)
        {
            string status = req.Query["status"];

            if (string.IsNullOrWhiteSpace(status))
            {
                status = DEFAULTSTATUS;
            }

            var result = new List <Order>();

            var db            = _cosmosDbConfiguration.DatabaseName;
            var collectionUri = UriFactory.CreateDocumentCollectionUri(db, COLLECTIONNAME);

            var orders = documentClient
                         .CreateDocumentQuery <Order>(collectionUri, new FeedOptions {
                EnableCrossPartitionQuery = true
            })
                         .Where(o => o.Status.Equals(status))
                         .AsDocumentQuery();

            while (orders.HasMoreResults)
            {
                foreach (var order in await orders.ExecuteNextAsync <Order>())
                {
                    result.Add(order);
                }
            }

            return(new OkObjectResult(result));
        }
예제 #11
0
        /// <summary>
        /// Gets all documents.
        /// </summary>
        /// <param name="dbId">Database id.</param>
        /// <param name="collectionId">Collection id.</param>
        /// <param name="feedOptions">Feed options.</param>
        /// <param name="queryFunc">Optional delegate to update the generated query before calling document db</param>
        /// <returns>List of objects of specified type returned from specified database and collection.</returns>
        public async Task <IReadOnlyList <T> > GetAllDocumentsAsync <T>(
            string dbId,
            string collectionId,
            FeedOptions feedOptions = null,
            Func <IQueryable <T>, IQueryable <T> > queryFunc = null)
        {
            Code.ExpectsNotNullOrWhiteSpaceArgument(dbId, nameof(dbId), TaggingUtilities.ReserveTag(0x2381b190 /* tag_961gq */));
            Code.ExpectsNotNullOrWhiteSpaceArgument(collectionId, nameof(collectionId), TaggingUtilities.ReserveTag(0x2381b191 /* tag_961gr */));

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

            IQueryable <T> queryable = client.CreateDocumentQuery <T>(
                UriFactory.CreateDocumentCollectionUri(dbId, collectionId), feedOptions);

            if (queryFunc != null)
            {
                queryable = queryFunc(queryable);
            }

            using (IDocumentQuery <T> query = queryable.AsDocumentQuery())
            {
                return(await QueryDocumentsAsync(query, feedOptions).ConfigureAwait(false));
            }
        }
예제 #12
0
        private void Parse(IEnumerable <DocumentCollection> migratecolls)
        {
            try
            {
                foreach (var coll in migratecolls)
                {
                    var docs = _documentClient.CreateDocumentQuery(coll.DocumentsLink);

                    foreach (var doc in docs)
                    {
                        if (!Directory.Exists(Path.Combine(Directory.GetCurrentDirectory(), "documents", coll.Id)))
                        {
                            Directory.CreateDirectory(Path.Combine(Directory.GetCurrentDirectory(), "documents", coll.Id));
                        }
                        var path       = Path.Combine(Path.Combine(Directory.GetCurrentDirectory(), "documents", coll.Id), doc.Id + ".json");
                        var fileStream = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write);
                        doc.SaveTo(fileStream, SerializationFormattingPolicy.Indented);
                    }
                }
            }
            catch (DocumentQueryException)
            {
            }
        }
예제 #13
0
        public async Task <CosmosResult <T> > GetItemsAsync(Expression <Func <T, bool> > filter)
        {
            IDocumentQuery <T> query = client.CreateDocumentQuery <T>(
                UriFactory.CreateDocumentCollectionUri(DatabaseId, CollectionId),
                new FeedOptions {
                MaxItemCount = -1, EnableCrossPartitionQuery = true
            })
                                       .Where(filter)
                                       .AsDocumentQuery();

            var result = await query.ExecuteNextAsync <T>();

            var      requestChargeTotal = result.RequestCharge;
            List <T> results            = result.ToList();

            while (query.HasMoreResults)
            {
                result = await query.ExecuteNextAsync <T>();

                requestChargeTotal += result.RequestCharge;
                results.AddRange(result.ToList());
            }
            return(new CosmosResult <T>(requestChargeTotal, results));
        }
        public virtual async Task <TUser> FindByIdAsync(string userId, CancellationToken token)
        {
            if (UsesPartitioning)
            {
                return(_Client.CreateDocumentQuery <TUser>(_Users.DocumentsLink, GetFeedOptions(userId))
                       .Where(u => u.DocId == "user").AsEnumerable().FirstOrDefault());
            }

            return(_Client.CreateDocumentQuery <TUser>(_Users.DocumentsLink)
                   .Where(u => u.Type == TypeEnum.User && u.DocId == userId).AsEnumerable().FirstOrDefault());
        }
예제 #15
0
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "stripe")] HttpRequest req,
            [CosmosDB(ConnectionStringSetting = "CosmosDBConnection")] IDocumentClient client,
            ILogger log, ExecutionContext context)
        {
            var config = new ConfigurationBuilder().SetBasePath(context.FunctionAppDirectory)
                         .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true)
                         .AddEnvironmentVariables()
                         .Build();

            var secret = config["Stripe:WebhookSecret"];

            string json = await new StreamReader(req.Body).ReadToEndAsync();

            try
            {
                var stripeEvent = EventUtility.ConstructEvent(json,
                                                              req.Headers["Stripe-Signature"], secret);

                if (stripeEvent.Type == Events.CheckoutSessionCompleted)
                {
                    var session = stripeEvent.Data.Object as Stripe.Checkout.Session;

                    log.LogInformation($"Searching for inschrijving with: {session.Id}");

                    Uri collectionUri = UriFactory.CreateDocumentCollectionUri("sinterklaas", "inschrijvingen");

                    var inschrijving = client.CreateDocumentQuery <InschrijvingDataModel>(collectionUri,
                                                                                          new FeedOptions()
                    {
                        PartitionKey = new Microsoft.Azure.Documents.PartitionKey("Sinterklaas")
                    })
                                       .Where(i => i.SessionId.Contains(session.Id))
                                       .AsEnumerable()
                                       .SingleOrDefault();

                    inschrijving.Betaald      = true;
                    inschrijving.BetaaldOpUtc = DateTime.UtcNow;
                    await client.ReplaceDocumentAsync(inschrijving._self, inschrijving);

                    var mailService            = new MailgunMailService(config["MailgunApiKey"], log);
                    var mailConfigConfirmEmail = config.GetSection("ConfirmEmail");
                    var mailModelConfirmEmail  = new InschrijvingEmailModel {
                        Naam               = inschrijving.Naam,
                        Email              = inschrijving.Email,
                        KindOpSchool       = inschrijving.KindOpSchool,
                        LidVanClub         = inschrijving.LidVanClub,
                        Lidmaatschap       = (!inschrijving.KindOpSchool && !inschrijving.LidVanClub) || inschrijving.GratisLidmaatschap,
                        GratisLidmaatschap = inschrijving.GratisLidmaatschap,
                        Straatnaam         = inschrijving.Straatnaam,
                        Postcode           = inschrijving.Postcode,
                        Plaats             = inschrijving.Plaats,
                        Telefoon           = inschrijving.Telefoon,
                        AantalKinderen     = inschrijving.Kinderen.Length,
                        Kinderen           = inschrijving.Kinderen.Select(k => new KindEmailModel {
                            Roepnaam   = k.Voornaam,
                            Achternaam = k.Achternaam,
                            Leeftijd   = k.Leeftijd,
                            Geslacht   = k.Geslacht,
                            Anekdote   = k.Anekdote
                        }).ToArray(),
                        Commentaar = inschrijving.Commentaar
                    };

                    await mailService.SendMailAsync(mailConfigConfirmEmail["FromName"],
                                                    mailConfigConfirmEmail["FromEmail"],
                                                    inschrijving.Naam,
                                                    inschrijving.Email,
                                                    mailConfigConfirmEmail["Bcc"],
                                                    mailConfigConfirmEmail["Subject"],
                                                    mailConfigConfirmEmail["TemplateId"],
                                                    mailModelConfirmEmail);


                    if ((!inschrijving.KindOpSchool && !inschrijving.LidVanClub) || inschrijving.GratisLidmaatschap)
                    {
                        var mailConfigMembershipEmail = config.GetSection("MembershipEmail");
                        var mailModelMembershipEmail  = new LidmaatschapEmailViewModel {
                            Naam  = inschrijving.Naam,
                            Email = inschrijving.Email,
                            GratisLidmaatschap = inschrijving.GratisLidmaatschap,
                            Straatnaam         = inschrijving.Straatnaam,
                            Postcode           = inschrijving.Postcode,
                            Plaats             = inschrijving.Plaats,
                            Telefoon           = inschrijving.Telefoon
                        };
                        await mailService.SendMailAsync(mailConfigMembershipEmail["FromName"],
                                                        mailConfigMembershipEmail["FromEmail"],
                                                        mailConfigMembershipEmail["ToName"],
                                                        mailConfigMembershipEmail["ToEmail"],
                                                        mailConfigMembershipEmail["Bcc"],
                                                        mailConfigMembershipEmail["Subject"],
                                                        mailConfigMembershipEmail["TemplateId"],
                                                        mailModelMembershipEmail);
                    }
                }
            }
            catch (Exception e)
            {
                log.LogError(e, "Error in Stripe Webhook");
                return(new BadRequestResult());
            }

            return(new OkResult());
        }
예제 #16
0
        public IOrderedQueryable <T> CreateQuery <T>(IDocumentClient client, StorageConfig cfg)
        {
            var collectionLink = $"/dbs/{cfg.DocumentDbDatabase}/colls/{cfg.DocumentDbCollection}";

            return(client.CreateDocumentQuery <T>(collectionLink));
        }
예제 #17
0
 /// <inheritdoc/>
 public IReadOnlyList <T> Query(string sqlExpression) =>
 _client.CreateDocumentQuery <T>(_documentCollectionUri, sqlExpression)
 .ToList();
예제 #18
0
 public virtual IQueryable <TDocument> CreateQuery(FeedOptions feedOptions = null)
 {
     return(DocumentClient.CreateDocumentQuery <TDocument>(UriFactory.CreateDocumentCollectionUri(DatabaseName, CollectionName), feedOptions));
 }
예제 #19
0
 public IOrderedQueryable <T> GetAll() => _client.CreateDocumentQuery <T>(_collectionUri, DefaultFeedOptions);
예제 #20
0
 public IQueryable <Document> ReadDocumentsByQuery(string query, FeedOptions options,
                                                   CancellationToken cancellationToken = default(CancellationToken))
 {
     return(_documentClient.CreateDocumentQuery <Document>(
                UriFactory.CreateDocumentCollectionUri(_databaseName, _collectionName), query, options));
 }
예제 #21
0
        private IOrderedQueryable <User> UserQuery()
        {
            var query = client.CreateDocumentQuery <User>(usersUri, DefaultOptions);

            return(query);
        }
예제 #22
0
 public static IQueryable <T> CreateTypedDocumentQuery <T>(this IDocumentClient client, Uri collectionUri, string documentType = null, FeedOptions options = null)
 {
     documentType = GetDocumentType <T>(documentType);
     return(client.CreateDocumentQuery <T>(collectionUri, options).Where(d => ((DocumentType)(object)d).Type == documentType).AsQueryable());
 }
예제 #23
0
 public IQueryable <itemEntry> Get()
 {
     return(_documentClient.CreateDocumentQuery <itemEntry>(UriFactory.CreateDocumentCollectionUri(databaseId, collectionId)));
 }
예제 #24
0
 public static IQueryable <Document> CreateTypedDocumentQuery(this IDocumentClient client, string collectionLink, string documentType, FeedOptions options = null)
 {
     return(client.CreateDocumentQuery(collectionLink, options).Where(d => ((DocumentType)(object)d).Type == documentType).AsQueryable());
 }
 public IEnumerable <T> Query(Expression <Func <T, bool> >?predicate = null)
 => _documentClient
 .CreateDocumentQuery <EntityDocument <T> >(GetUri())
 .Where(x => x.Type == _entityType)
 .Select(x => x.Entity)
 .Where(predicate ?? (x => true));
예제 #26
0
        public async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequest req,
            ILogger logger,
            CancellationToken token)
        {
            return(await req.Wrap <ReindeerRescueRequest>(logger, async request =>
            {
                if (request == null)
                {
                    return new BadRequestErrorMessageResult("Request is empty.");
                }

                if (string.IsNullOrWhiteSpace(request.Id))
                {
                    return new BadRequestErrorMessageResult($"Missing required value for property '{nameof(ReindeerRescueRequest.Id)}'.");
                }

                if (!Guid.TryParse(request.Id, out Guid id))
                {
                    return new BadRequestErrorMessageResult($"Value for property '{nameof(ReindeerRescueRequest.Id)}' is not a valid ID or has an invalid format (example of valid value and format for Unique Identifier (GUID): '135996C9-3090-4399-85DB-1F5041DF1DDD').");
                }

                Attempt attempt = await _attemptService.Get(id, 2, token);

                if (attempt == null)
                {
                    return new NotFoundResult();
                }

                if (!attempt.SantaRescueAt.HasValue)
                {
                    return new BadRequestErrorMessageResult($"It looks like you're reusing an old ID from a previous failed attempt created {attempt.Created} - you need to start all over again - remember not to hard code any IDs in your application.");
                }

                if (attempt.ReindeerInZones == null)
                {
                    throw new InvalidOperationException($"Missing value for '{nameof(attempt.ReindeerInZones)}' on attempt with Id '{attempt.Id}'.");
                }

                var messages = new List <string>();

                if (request.Locations == null)
                {
                    messages.Add($"Missing required value for property '{nameof(ReindeerRescueRequest.Locations).WithFirstCharToLowercase()}'.");
                }
                else if (request.Locations.Length > attempt.ReindeerInZones.Length)
                {
                    messages.Add($"Invalid value for property '{nameof(ReindeerRescueRequest.Locations).WithFirstCharToLowercase()}'. Expected a maximum number of locations to be {attempt.ReindeerInZones.Length} - but was {request.Locations.Length}.");
                }
                else
                {
                    for (int i = 0; i < attempt.ReindeerInZones.Length; i++)
                    {
                        ReindeerInZone zone = attempt.ReindeerInZones[i];
                        ReindeerRescueRequest.ReindeerLocation locationInRequest = request.Locations?.ElementAtOrDefault(i);

                        if (locationInRequest == null)
                        {
                            messages.Add($"Missing required value for property '{nameof(ReindeerRescueRequest.Locations).WithFirstCharToLowercase()}[{i}]'.");
                        }
                        else if (string.IsNullOrWhiteSpace(locationInRequest.Name))
                        {
                            messages.Add($"Missing required value for property '{nameof(ReindeerRescueRequest.Locations).WithFirstCharToLowercase()}[{i}].{nameof(ReindeerRescueRequest.ReindeerLocation.Name).WithFirstCharToLowercase()}'");
                        }
                        else if (locationInRequest.Name.Length >= 100)
                        {
                            messages.Add($"Invalid value for property '{nameof(ReindeerRescueRequest.Locations).WithFirstCharToLowercase()}[{i}].{nameof(ReindeerRescueRequest.ReindeerLocation.Name).WithFirstCharToLowercase()}' - length exceeds maximum of 100 characters.");
                        }
                        else if (!string.Equals(locationInRequest.Name, zone.Reindeer.ToString()))
                        {
                            messages.Add($"Expected name of Reindeer for '{nameof(ReindeerRescueRequest.Locations).WithFirstCharToLowercase()}[{i}].{nameof(ReindeerRescueRequest.ReindeerLocation.Name).WithFirstCharToLowercase()}' to be '{zone.Reindeer}' - but was '{locationInRequest.Name}'.");
                        }
                        else if (locationInRequest.Position == null)
                        {
                            messages.Add($"Missing required value for property '{nameof(ReindeerRescueRequest.Locations).WithFirstCharToLowercase()}[{i}].{nameof(ReindeerRescueRequest.ReindeerLocation.Position).WithFirstCharToLowercase()}'");
                        }
                        else
                        {
                            Point center = new Point(zone.Center.Lon, zone.Center.Lat);
                            double radiusInMeter = zone.Radius.InMeter();
                            string name = zone.Reindeer.ToString();

                            var feedOptions = new FeedOptions
                            {
                                PartitionKey = new PartitionKey(zone.CountryCode),
                                MaxItemCount = 1
                            };

                            ObjectInLocationForCosmosDb actualReindeer = _documentClient
                                                                         .CreateDocumentQuery <ObjectInLocationForCosmosDb>(UriFactory.CreateDocumentCollectionUri("World", "Objects"), feedOptions)
                                                                         .Where(u => u.Name == name && center.Distance(u.Location) <= radiusInMeter)
                                                                         .AsEnumerable()
                                                                         .FirstOrDefault();

                            if (actualReindeer == null)
                            {
                                throw new InvalidOperationException($"Reindeer '{name}' not found for zone {zone.Center}, Country {zone.CountryCode}.");
                            }

                            GeoPoint actualPosition = actualReindeer.GetLocation();

                            if (!actualPosition.Equals(locationInRequest.Position))
                            {
                                messages.Add($"Invalid value for property '{nameof(ReindeerRescueRequest.Locations).WithFirstCharToLowercase()}[{i}].{nameof(ReindeerRescueRequest.ReindeerLocation.Position).WithFirstCharToLowercase()}'. Reindeer '{zone.Reindeer}' was not found at {locationInRequest.Position} - actual position is {actualPosition}.");
                            }
                        }
                    }
                }

                if (messages.Count > 0)
                {
                    attempt.InvalidReindeerRescue = messages.ToArray();

                    await _attemptService.Save(attempt, 3, token);

                    return new BadRequestErrorMessageResult($@"Unfortunately one or more reindeer was not at the specified locations. 
Below is the detailed rescue report from the extraction team:

{string.Join(Environment.NewLine, messages.Select(x => $"\t - {x}"))}

Please try again - and remember since the reindeer has probably moved their locations by now, you'll have to start all over again.");
                }

                attempt.ReindeersRescueAt = DateTimeOffset.UtcNow;

                Uri problemUri = await _toyDistributionProblemRepository.Save(attempt, ToyDistributionProblem.Create(), token);

                await _attemptService.Save(attempt, 3, token);

                return new OkObjectResult(new ReindeerRescueResponse(problemUri));
            }));
        }
예제 #27
0
 public static IOrderedQueryable <T> CreateDocumentQuery <T>(
     this IDocumentClient client)
 {
     return(client.CreateDocumentQuery <T>(CollectionUri));
 }
예제 #28
0
 public IQueryable <Item> Get()
 {
     return(_documentClient.CreateDocumentQuery <Item>(UriFactory.CreateDocumentCollectionUri(databaseID, collectionID), new FeedOptions {
         MaxItemCount = 20
     }));
 }
예제 #29
0
        public static async Task <IActionResult> PagedQuery(
            [HttpTrigger(AuthorizationLevel.Function, "get", Route = "{database}/{collection}")] HttpRequest req,
            string database,
            string collection,
            [CosmosDB("{database}", "{collection}", ConnectionStringSetting = "CosmosDBConnection")] IDocumentClient client,
            ILogger log,
            ExecutionContext context)
        {
            var functionName = context.FunctionName;
            var queryString  = req.GetQueryParameterDictionary();
            var headers      = req.GetTypedHeaders();
            var pageSize     = int.Parse(queryString.ContainsKey("pageSize") ? queryString["pageSize"] : DefaultPageSize.ToString());
            var continuation = queryString.ContainsKey("continuation") ? queryString["continuation"] : null;

            var results = new List <dynamic>();

            var cosmosQuery = JObject.Parse(queryString["q"]);
            var querySpec   = new SqlQuerySpec(cosmosQuery["QueryText"]?.ToString(), JsonConvert.DeserializeObject <SqlParameterCollection>(cosmosQuery["Parameters"]?.ToString()));

            try
            {
                Uri collectionUri = UriFactory.CreateDocumentCollectionUri(database, collection);

                if (string.IsNullOrEmpty(querySpec.QueryText))
                {
                    throw new ArgumentNullException("Please provide a query!");
                }

                var response = new PagedResults();

                // Loop through partition key ranges
                foreach (var pkRange in await client.ReadPartitionKeyRangeFeedAsync(collectionUri))
                {
                    try
                    {
                        var options = new FeedOptions()
                        {
                            PartitionKeyRangeId = pkRange.Id,
                            RequestContinuation = continuation,
                            MaxItemCount        = pageSize - results.Count,
                            ResponseContinuationTokenLimitInKb = ResponseContinuationTokenLimit,
                            EnableCrossPartitionQuery          = EnableCrossPartitionQuery
                        };

                        using (var query = client
                                           .CreateDocumentQuery <dynamic>(collectionUri, querySpec, options)
                                           .AsDocumentQuery())
                        {
                            while (query.HasMoreResults && results.Count < pageSize)
                            {
                                // Get results
                                FeedResponse <dynamic> recordSet = await query.ExecuteNextAsync();

                                foreach (var record in recordSet)
                                {
                                    results.Add(record);
                                }

                                // Create Response Object
                                response.Pagination.ContinuationToken = recordSet.ResponseContinuation;

                                // Set Links
                                var referrer = headers.Referer ?? new Uri(req.GetEncodedUrl());
                                response.Links.Self = referrer.OriginalString;

                                NameValueCollection qc = HttpUtility.ParseQueryString(referrer.Query, Encoding.UTF8);
                                qc.Remove("continuation");

                                if (!string.IsNullOrEmpty(recordSet.ResponseContinuation))
                                {
                                    qc.Add("continuation", recordSet.ResponseContinuation);
                                    response.Links.Next = $"{req.Scheme}://{req.Host}{req.Path}?{string.Join("&", qc.AllKeys.Select(k => string.Format("{0}={1}", k, Uri.EscapeDataString(qc[k]))))}";
                                }
                                else
                                {
                                    response.Links.Next = null;
                                }
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        if (e.Message.Contains("Microsoft.Azure.Documents.Query.CompositeContinuationToken"))
                        {
                            log.LogDebug("Skipping partition key range.");
                        }
                        else
                        {
                            throw;
                        }
                    }
                }

                response.Data = results;

                return(new OkObjectResult(response));
            }
            catch (Exception e)
            {
                log.LogError($"{functionName} failed", e);

                var response = new
                {
                    e.Message,
                };

                return(new BadRequestObjectResult(response));
            }
        }
예제 #30
0
 private IDocumentQuery <T> CreateDocumentQuery()
 {
     return(_client.CreateDocumentQuery <T>(_collection.SelfLink, _queryBuilder.GetFeedOptions()).AsDocumentQuery <T>());
 }