public TestingContext(Action <ICosmosDbBuilder> builderCallback, Action <ICosmosDbRepositoryBuilder> repoBuilderCallback)
        {
            var services = TestFramework.Services;

            DbConfig   = services.GetRequiredService <IOptions <CosmosDbConfig> >().Value;
            TestConfig = services.GetRequiredService <IOptions <TestConfig> >().Value.Clone();
            EnvConfig  = services.GetRequiredService <IOptions <EnvironmentConfig> >().Value;

            if (EnvConfig.RandomizeCollectionName)
            {
                TestConfig.CollectionName = $"{TestConfig.CollectionName}{Guid.NewGuid()}";
            }

            DbClient = new DocumentClient(new Uri(DbConfig.DbEndPoint), DbConfig.DbKey);
            var builder = new CosmosDbBuilder()
                          .WithId(DbConfig.DbName)
                          .WithDefaultThroughput(400)
                          .AddCollection <T>(TestConfig.CollectionName, repoBuilderCallback);

            builderCallback?.Invoke(builder);

            CosmosDb = builder.Build(DbClient);

            Repo = CosmosDb.Repository <T>();
        }
Example #2
0
        public void Repository_WithClassNamedCollection_Success()
        {
            var services = TestFramework.Services;
            var dbConfig = services.GetRequiredService <IOptions <CosmosDbConfig> >().Value;

            using (var dbClient = new DocumentClient(new Uri(dbConfig.DbEndPoint), dbConfig.DbKey))
            {
                var db = new CosmosDbBuilder()
                         .WithId("MyDatabase")
                         .WithDefaultThroughput(400)
                         .AddCollection <TestClass2>()
                         .Build(dbClient);

                db.Repository <TestClass2>();
            }
        }
        static async Task Main(string[] args)
        {
            // This is my simple testable wrapper around the
            var client = new DocumentClient(new Uri("https://localhost:8081"), "C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw==", JsonConvert.DefaultSettings());

            var cosmosDb = new CosmosDbBuilder()
                           .WithId("upsertFailure")
                           .AddCollection <DateTimeError>("datetimeerror", builder =>
            {
                builder.IncludeIndexPath("/*", Index.Range(DataType.Number, -1), Index.Range(DataType.String, -1));
            })
                           .Build(client);

            var repo = cosmosDb.Repository <DateTimeError>();

            var orig = new DateTimeError
            {
                Id   = Guid.NewGuid(),
                Date = DateTimeOffset.UtcNow
            };

            // round the time to hundredths of a second to expose formatting problems
            orig.Date = new DateTimeOffset(orig.Date.Ticks - orig.Date.Ticks % (TimeSpan.TicksPerSecond / 100), TimeSpan.Zero);

            await repo.AddAsync(orig);

            var successfulFind = await repo.FindFirstOrDefaultAsync(dte => dte.Date == orig.Date);

            successfulFind.Should().BeEquivalentTo(orig);

            await repo.UpsertAsync(orig);

            var unsuccessfulUpsertFind = await repo.FindFirstOrDefaultAsync(dte => dte.Date == orig.Date);

            unsuccessfulUpsertFind.Should().BeNull();

            await repo.ReplaceAsync(orig);

            var unsuccessfulReplaceFind = await repo.FindFirstOrDefaultAsync(dte => dte.Date == orig.Date);

            unsuccessfulReplaceFind.Should().BeNull();

            var successfulGet = await repo.GetAsync(orig.Id);

            successfulGet.Should().BeEquivalentTo(orig);
        }
Example #4
0
        public static void Cleanup()
        {
            if (Services != null)
            {
                var envConfig = Services.GetRequiredService <IOptions <EnvironmentConfig> >().Value;

                if (envConfig.DeleteDatabaseOnClose)
                {
                    var dbConfig = Services.GetRequiredService <IOptions <CosmosDbConfig> >().Value;

                    var client = new DocumentClient(new Uri(dbConfig.DbEndPoint), dbConfig.DbKey);
                    var repo   = new CosmosDbBuilder()
                                 .WithId(dbConfig.DbName)
                                 .WithDefaultThroughput(400)
                                 .Build(client);

                    repo.DeleteAsync().Wait();
                }
            }
        }
Example #5
0
        private static async Task Main(string[] args)
        {
            var configuration = new ConfigurationBuilder()
                                .SetBasePath(Directory.GetCurrentDirectory())
                                .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                                .AddEnvironmentVariables()
                                .AddUserSecrets <DocumentClientSettings>()
                                .Build();

            var services = new ServiceCollection()
                           .Configure <DocumentClientSettings>(configuration.GetSection("DocumentClientSettings"))
                           .AddOptions()
                           .BuildServiceProvider();

            var clientSettings = services.GetRequiredService <IOptions <DocumentClientSettings> >().Value;

            // get the Azure DocumentDB client
            var client = new DocumentClient(new Uri(clientSettings.EndpointUrl), clientSettings.AuthorizationKey, clientSettings.ConnectionPolicy);

            // Run demo
            var documentDb = new CosmosDbBuilder()
                             .WithId("Demo")
                             .WithDefaultThroughput(400)
                             .AddCollection <Person>(func: cb =>
            {
                cb
                .IncludeIndexPath("/*", Index.Range(DataType.Number), Index.Hash(DataType.String, 3), Index.Spatial(DataType.Point))
                .IncludeIndexPath("/Birthday/?", Index.Range(DataType.Number))
                .ExcludeIndexPath("/FirstName/?", "/LastName/?")
                .StoredProcedure("test",
                                 @"// SAMPLE STORED PROCEDURE
function sample() {
    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 empty, set the body to 'no docs found', 
        // else take 1st element from feed
        if (!feed || !feed.length) {
            var response = getContext().getResponse();
            response.setBody('no docs found');
        }
        else {
            var response = getContext().getResponse();
            response.setBody(feed);
        }
    });

    if (!isAccepted) throw new Error('The query was not accepted by the server.');
}");
            })
                             .Build(client);

            // create repository for persons and set Person.FullName property as identity field (overriding default Id property name)
            var repo = documentDb.Repository <Person>();

            var sp = repo.StoredProcedure <Person[]>("test");

            // output all persons in our database, nothing there yet
            PrintPersonCollection(await repo.FindAsync());

            // create a new person
            Person matt = new Person
            {
                FirstName    = "Matt",
                LastName     = "TBA",
                Birthday     = new DateTime(1990, 10, 10),
                PhoneNumbers =
                    new Collection <PhoneNumber>
                {
                    new PhoneNumber {
                        Number = "555", Type = "Mobile"
                    },
                    new PhoneNumber {
                        Number = "777", Type = "Landline"
                    }
                }
            };

            // add person to database's collection (if collection doesn't exist it will be created and named as class name -it's a convenction, that can be configured during initialization of the repository)
            matt = await repo.UpsertAsync(matt);

            matt = await repo.GetAsync(matt);

            var mod = matt.Modified;

            var matt2 = await repo.FindAsync(r => r.Modified == mod);

            matt = await repo.ReplaceAsync(matt);

            await repo.DeleteDocumentAsync(matt);

            // create another person
            Person jack = new Person
            {
                FirstName    = "Jack",
                LastName     = "Smith",
                Birthday     = new DateTime(1990, 10, 10),
                PhoneNumbers = new Collection <PhoneNumber>()
            };

            // add jack to collection
            jack = await repo.UpsertAsync(jack);

            // should output person and his two phone numbers
            PrintPersonCollection(await repo.FindAsync());

            // change birth date
            matt.Birthday -= new TimeSpan(500, 0, 0, 0);

            // remove landline phone number
            matt.PhoneNumbers.RemoveAt(1);

            // should update person
            matt = await repo.UpsertAsync(matt);

            // should output Matt with just one phone number
            PrintPersonCollection(await repo.FindAsync());

            // get Matt by his Id
            Person justMatt = await repo.GetAsync(matt.FullName);

            Console.WriteLine("GetByIdAsync result: " + justMatt);

            // ... or by his first name
            Person firstMatt = await repo.FindFirstOrDefaultAsync(p => p.FirstName.ToLower() == "matt");

            Console.WriteLine("First: " + firstMatt);

            // query all the smiths
            var smiths = (await repo.FindAsync(p => p.LastName.Equals("Smith"))).ToList();

            Console.WriteLine(smiths.Count);

            // use IQueryable, as for now supported expressions are 'Queryable.Where', 'Queryable.Select' & 'Queryable.SelectMany'
            var allSmithsPhones =
                (await repo.FindAsync()).SelectMany(p => p.PhoneNumbers).Select(p => p.Type);

            foreach (var phone in allSmithsPhones)
            {
                Console.WriteLine(phone);
            }

            // count all persons
            var personsCount = await repo.FindAsync();

            // count all jacks
            var jacksCount = await repo.FindAsync(p => p.FirstName == "Jack");

            PrintPersonCollection(await sp.ExecuteAsync());

            Console.ReadKey(true);

            // remove matt from collection
            await repo.DeleteDocumentAsync(matt.FullName);

            // remove jack from collection
            await repo.DeleteDocumentAsync(jack.FullName);

            // should output nothing
            PrintPersonCollection(await repo.FindAsync());

            // remove collection
            await repo.DeleteAsync();

            await documentDb.DeleteAsync();

            Console.ReadKey(true);
        }