Ejemplo n.º 1
0
        public void Several_SaveChanges_for_the_same_document_in_single_transaction_should_allow_commit_without_concurrency_exception()
        {
            using (var documentStore = NewRemoteDocumentStore(runInMemory: false, requestedStorage: "esent"))
                using (var session = documentStore.OpenSession())
                {
                    session.Advanced.UseOptimisticConcurrency         = true;
                    session.Advanced.AllowNonAuthoritativeInformation = false;

                    Assert.DoesNotThrow(() =>
                    {
                        using (var transaction = new TransactionScope())
                        {
                            var newDoc = new TestDoc {
                                Data = "Foo"
                            };
                            session.Store(newDoc);
                            session.SaveChanges();

                            newDoc.Data = "Bar";
                            session.SaveChanges();

                            transaction.Complete();
                        }
                    });
                }
        }
Ejemplo n.º 2
0
        public async Task InvalidPathToEncrypt()
        {
            TestDoc testDoc = TestDoc.Create();
            List <EncryptionOptions> propertyEncryptionOptionsWithInvalidPath = new List <EncryptionOptions>();

            propertyEncryptionOptionsWithInvalidPath.Add(
                new EncryptionOptions()
            {
                DataEncryptionKeyId = PropertyEncryptionProcessorTests.pdekId,
                EncryptionAlgorithm = CosmosEncryptionAlgorithm.AEAD_AES_256_CBC_HMAC_SHA256,
                PathsToEncrypt      = new List <string>()
                {
                    "/Name", "/Invalid"
                }
            });

            try
            {
                await PropertyEncryptionProcessor.EncryptAsync(
                    testDoc.ToStream(),
                    PropertyEncryptionProcessorTests.mockEncryptor.Object,
                    propertyEncryptionOptionsWithInvalidPath,
                    new CosmosDiagnosticsContext(),
                    CancellationToken.None);

                Assert.Fail("Invalid path to encrypt didn't result in exception.");
            }
            catch (ArgumentException ex)
            {
                Assert.AreEqual("PathsToEncrypt includes a path: '/Invalid' which was not found.", ex.Message);
            }
        }
Ejemplo n.º 3
0
        public void CanQueryListWithContainsAll()
        {
            using (var store = NewDocumentStore())
            {
                using (var session = store.OpenSession())
                {
                    var doc = new TestDoc {
                        StringArray = new[] { "test", "doc", "foo" }
                    };
                    session.Store(doc);
                    session.SaveChanges();

                    session.Query <TestDoc>().Customize(x => x.WaitForNonStaleResultsAsOfNow()).ToList();

                    var items = new[] { "a", "b", "c" };
                    var test  = session.Query <TestDoc>()
                                .Where(ar => ar.StringArray.ContainsAll(items) &&
                                       ar.SomeProperty == "somethingElse")
                                .ToString();
                    Assert.Equal("(StringArray:a AND StringArray:b AND StringArray:c) AND SomeProperty:somethingElse", test);

                    var results = session.Query <TestDoc>()
                                  .Where(t => t.StringArray.ContainsAll(new[] { "test", "doc", "foo" }))
                                  .ToList();
                    Assert.Equal(1, results.Count);

                    var noResults = session.Query <TestDoc>()
                                    .Where(t => t.StringArray.ContainsAll(new[] { "test", "doc", "foo", "NOTmatch" }))
                                    .ToList();
                    Assert.Equal(0, noResults.Count);
                }
            }
        }
Ejemplo n.º 4
0
 private static void VerifyDecryptionSucceeded(
     JObject decryptedDoc,
     TestDoc expectedDoc)
 {
     Assert.AreEqual(expectedDoc.Name, decryptedDoc.Property(nameof(TestDoc.Name)).Value.Value <string>());
     Assert.IsNull(decryptedDoc.Property(Constants.EncryptedInfo));
 }
        public async Task BatchServerResponseTooLargeAsync()
        {
            Container container          = BatchTestBase.JsonContainer;
            const int operationCount     = 10;
            int       appxDocSizeInBytes = 1 * 1024 * 1024;

            TestDoc doc = await BatchTestBase.CreateJsonTestDocAsync(container, this.PartitionKey1, appxDocSizeInBytes);

            TransactionalBatch batch = new BatchCore((ContainerCore)container, BatchTestBase.GetPartitionKey(this.PartitionKey1));

            for (int i = 0; i < operationCount; i++)
            {
                batch.ReadItem(doc.Id);
            }

            TransactionalBatchResponse batchResponse = await batch.ExecuteAsync();

            BatchSinglePartitionKeyTests.VerifyBatchProcessed(
                batchResponse,
                numberOfOperations: operationCount,
                expectedStatusCode: HttpStatusCode.RequestEntityTooLarge);

            Assert.AreEqual((int)StatusCodes.FailedDependency, (int)batchResponse[0].StatusCode);
            Assert.AreEqual(HttpStatusCode.RequestEntityTooLarge, batchResponse[operationCount - 1].StatusCode);
        }
Ejemplo n.º 6
0
        public void InListOver256Chars()
        {
            using (var store = NewRemoteDocumentStore())
            {
                using (var session = store.OpenSession())
                {
                    var nameList = new List <string>();
                    var count    = 0;

                    while (count < 0x100)
                    {
                        var doc = new TestDoc {
                            Name = Convert.ToBase64String(Guid.NewGuid().ToByteArray())
                        };
                        session.Store(doc);

                        nameList.Add(doc.Name);
                        count += (doc.Name.Length + 1);
                    }

                    session.SaveChanges();

                    var foundDocs = session.Query <TestDoc>().Customize(x => x.WaitForNonStaleResultsAsOfNow()).Where(doc => doc.Name.In(nameList)).ToList();

                    WaitForUserToContinueTheTest();

                    session.Query <TestDoc>().Customize(x => x.WaitForNonStaleResultsAsOfNow()).Where(doc => doc.Name.In(nameList)).ToList();
                    Assert.True(foundDocs.Count == nameList.Count);
                }
            }
        }
Ejemplo n.º 7
0
        protected internal virtual IList <TestDoc> GetRandomDocs(string[] tokens, int count, int numDims)
        {
            IList <TestDoc> docs = new List <TestDoc>();

            for (int i = 0; i < count; i++)
            {
                TestDoc doc = new TestDoc();
                docs.Add(doc);
                doc.content = PickToken(tokens);
                doc.dims    = new string[numDims];
                for (int j = 0; j < numDims; j++)
                {
                    doc.dims[j] = PickToken(tokens);
                    if (Random.Next(10) < 3)
                    {
                        break;
                    }
                }
                if (VERBOSE)
                {
                    Console.WriteLine("  doc " + i + ": content=" + doc.content);
                    for (int j = 0; j < numDims; j++)
                    {
                        if (doc.dims[j] != null)
                        {
                            Console.WriteLine("    dim[" + j + "]=" + doc.dims[j]);
                        }
                    }
                }
            }

            return(docs);
        }
Ejemplo n.º 8
0
        public async Task GetItemQuery()
        {
            TestDoc testDoc = TestDoc.Create();
            ItemResponse <TestDoc> createResponseb = await EncryptionContainerTests.propertyEncryptionContainer.CreateItemAsync(
                testDoc, new PartitionKey(testDoc.PK));

            TestDoc expectedDoc = new TestDoc(testDoc);

            await EncryptionContainerTests.ValidateQueryResultsAsync(
                EncryptionContainerTests.propertyEncryptionContainer,
                "SELECT * FROM c",
                expectedDoc);

            await EncryptionContainerTests.ValidateQueryResultsAsync(
                EncryptionContainerTests.propertyEncryptionContainer,
                string.Format(
                    "SELECT * FROM c where c.Name = {0}",
                    expectedDoc.Name),
                expectedDoc);

            await EncryptionContainerTests.ValidateQueryResultsAsync(
                EncryptionContainerTests.propertyEncryptionContainer,
                queryDefinition : new QueryDefinition(
                    "select * from c where c.Name = @Name")
                .WithParameter("@Name", expectedDoc.Name),
                expectedDoc : expectedDoc);
        }
Ejemplo n.º 9
0
		public void InListOver256Chars()
		{
			using (var store = NewRemoteDocumentStore())
			{
				using (var session = store.OpenSession())
				{
					var nameList = new List<string>();
					var count = 0;

					while (count < 0x100)
					{
						var doc = new TestDoc { Name = Convert.ToBase64String(Guid.NewGuid().ToByteArray()) };
						session.Store(doc);

						nameList.Add(doc.Name);
						count += (doc.Name.Length + 1);
					}

					session.SaveChanges();

					var foundDocs = session.Query<TestDoc>().Customize(x => x.WaitForNonStaleResultsAsOfNow()).Where(doc => doc.Name.In(nameList)).ToList();

					WaitForUserToContinueTheTest(store);

					session.Query<TestDoc>().Customize(x => x.WaitForNonStaleResultsAsOfNow()).Where(doc => doc.Name.In(nameList)).ToList();
					Assert.True(foundDocs.Count == nameList.Count);


				}
			}
		}
Ejemplo n.º 10
0
        public void InListOver256Chars2()
        {
            using (var store = GetDocumentStore())
            {
                using (var session = store.OpenSession())
                {
                    var nameList = new List <string>();
                    var count    = 0;
                    var index    = 0;
                    while (count < 0x100)
                    {
                        var doc = new TestDoc {
                            Name = new string('a', 300) + index
                        };
                        session.Store(doc);

                        nameList.Add(doc.Name);
                        count += (doc.Name.Length + 1);
                        index++;
                    }
                    session.SaveChanges();
                    Indexes.WaitForIndexing(store);

                    var foundDocs = session.Query <TestDoc>()
                                    .Customize(x => x.WaitForNonStaleResults())
                                    .Where(doc => doc.Name.In(nameList)).ToList();

                    Assert.Equal(nameList.Count, foundDocs.Count);
                }
            }
        }
Ejemplo n.º 11
0
        public void DoesNotSupportStrings()
        {
            using (var store = NewDocumentStore())
            {
                using (var session = store.OpenSession())
                {
                    var doc = new TestDoc {
                        SomeProperty = "Ensure that Contains on IEumerable<Char> is not supported."
                    };
                    session.Store(doc);
                    session.SaveChanges();
                }

                using (var session = store.OpenSession())
                {
                    var otherDoc = new TestDoc {
                        SomeProperty = "Contains"
                    };
                    var exception = Assert.Throws <NotSupportedException>(() =>
                    {
                        session.Query <TestDoc>().FirstOrDefault(ar => ar.SomeProperty.Contains(otherDoc.SomeProperty));
                    });
                    Assert.Contains("Contains is not supported, doing a substring match", exception.Message);
                }
            }
        }
        public async Task BatchItemSessionTokenAsync()
        {
            Container container = BatchTestBase.JsonContainer;

            await this.CreateJsonTestDocsAsync(container);

            TestDoc testDocToCreate = BatchTestBase.PopulateTestDoc(this.PartitionKey1);

            TestDoc testDocToReplace = this.GetTestDocCopy(this.TestDocPk1ExistingA);

            testDocToReplace.Cost++;

            ItemResponse <TestDoc> readResponse = await BatchTestBase.JsonContainer.ReadItemAsync <TestDoc>(
                this.TestDocPk1ExistingA.Id,
                BatchTestBase.GetPartitionKey(this.PartitionKey1));

            ISessionToken beforeRequestSessionToken = BatchTestBase.GetSessionToken(readResponse.Headers.Session);

            TransactionalBatchResponse batchResponse = await new BatchCore((ContainerInlineCore)container, BatchTestBase.GetPartitionKey(this.PartitionKey1))
                                                       .CreateItem(testDocToCreate)
                                                       .ReplaceItem(testDocToReplace.Id, testDocToReplace)
                                                       .ExecuteAsync();

            BatchSinglePartitionKeyTests.VerifyBatchProcessed(batchResponse, numberOfOperations: 2);
            Assert.AreEqual(HttpStatusCode.Created, batchResponse[0].StatusCode);
            Assert.AreEqual(HttpStatusCode.OK, batchResponse[1].StatusCode);

            ISessionToken afterRequestSessionToken = BatchTestBase.GetSessionToken(batchResponse.Headers.Session);

            Assert.IsTrue(afterRequestSessionToken.LSN > beforeRequestSessionToken.LSN, "Response session token should be more than request session token");
        }
Ejemplo n.º 13
0
        public void CanQueryArrayWithAny()
        {
            using (var store = GetDocumentStore())
            {
                using (var session = store.OpenSession())
                {
                    var doc = new TestDoc {
                        StringArray = new[] { "test", "doc", "foo" }
                    };
                    session.Store(doc);
                    session.SaveChanges();
                }

                using (var session = store.OpenSession())
                {
                    var otherDoc = new TestDoc {
                        SomeProperty = "foo"
                    };
                    var doc = (from ar in session.Query <TestDoc>()
                               where ar.StringArray.Any(ac => ac == otherDoc.SomeProperty)
                               select ar).FirstOrDefault();
                    Assert.NotNull(doc);
                }
            }
        }
Ejemplo n.º 14
0
        public void CanQueryListWithContainsAll()
        {
            using (var store = GetDocumentStore())
            {
                using (var session = store.OpenSession())
                {
                    var doc = new TestDoc {
                        StringArray = new[] { "test", "doc", "foo" }
                    };
                    session.Store(doc);
                    session.SaveChanges();

                    session.Query <TestDoc>().Customize(x => x.WaitForNonStaleResults()).ToList();

                    var items = new[] { "a", "b", "c" };
                    var test  = session.Query <TestDoc>()
                                .Where(ar => ar.StringArray.ContainsAll(items) && ar.SomeProperty == "somethingElse");

                    var iq = RavenTestHelper.GetIndexQuery(test);
                    Assert.Equal("from TestDocs where StringArray all in ($p0) and SomeProperty = $p1", iq.Query);
                    Assert.Equal(items, iq.QueryParameters["p0"]);
                    Assert.Equal("somethingElse", iq.QueryParameters["p1"]);

                    var results = session.Query <TestDoc>()
                                  .Where(t => t.StringArray.ContainsAll(new[] { "test", "doc", "foo" }))
                                  .ToList();
                    Assert.Equal(1, results.Count);

                    var noResults = session.Query <TestDoc>()
                                    .Where(t => t.StringArray.ContainsAll(new[] { "test", "doc", "foo", "NOTmatch" }))
                                    .ToList();
                    Assert.Equal(0, noResults.Count);
                }
            }
        }
        public async Task BatchItemETagAsync()
        {
            Container container = BatchTestBase.JsonContainer;

            await this.CreateJsonTestDocsAsync(container);

            {
                TestDoc testDocToCreate = BatchTestBase.PopulateTestDoc(this.PartitionKey1);

                TestDoc testDocToReplace = this.GetTestDocCopy(this.TestDocPk1ExistingA);
                testDocToReplace.Cost++;

                ItemResponse <TestDoc> readResponse = await BatchTestBase.JsonContainer.ReadItemAsync <TestDoc>(
                    this.TestDocPk1ExistingA.Id,
                    BatchTestBase.GetPartitionKey(this.PartitionKey1));

                TransactionalBatchItemRequestOptions firstReplaceOptions = new TransactionalBatchItemRequestOptions()
                {
                    IfMatchEtag = readResponse.ETag
                };

                TransactionalBatchResponse batchResponse = await new BatchCore((ContainerCore)container, BatchTestBase.GetPartitionKey(this.PartitionKey1))
                                                           .CreateItem(testDocToCreate)
                                                           .ReplaceItem(testDocToReplace.Id, testDocToReplace, requestOptions: firstReplaceOptions)
                                                           .ExecuteAsync();

                BatchSinglePartitionKeyTests.VerifyBatchProcessed(batchResponse, numberOfOperations: 2);

                Assert.AreEqual(HttpStatusCode.Created, batchResponse[0].StatusCode);
                Assert.AreEqual(HttpStatusCode.OK, batchResponse[1].StatusCode);

                await BatchTestBase.VerifyByReadAsync(container, testDocToCreate, eTag : batchResponse[0].ETag);

                await BatchTestBase.VerifyByReadAsync(container, testDocToReplace, eTag : batchResponse[1].ETag);
            }

            {
                TestDoc testDocToReplace = this.GetTestDocCopy(this.TestDocPk1ExistingB);
                testDocToReplace.Cost++;

                TransactionalBatchItemRequestOptions replaceOptions = new TransactionalBatchItemRequestOptions()
                {
                    IfMatchEtag = BatchTestBase.Random.Next().ToString()
                };

                TransactionalBatchResponse batchResponse = await new BatchCore((ContainerCore)container, BatchTestBase.GetPartitionKey(this.PartitionKey1))
                                                           .ReplaceItem(testDocToReplace.Id, testDocToReplace, requestOptions: replaceOptions)
                                                           .ExecuteAsync();

                BatchSinglePartitionKeyTests.VerifyBatchProcessed(
                    batchResponse,
                    numberOfOperations: 1,
                    expectedStatusCode: HttpStatusCode.PreconditionFailed);

                Assert.AreEqual(HttpStatusCode.PreconditionFailed, batchResponse[0].StatusCode);

                // ensure the document was not updated
                await BatchTestBase.VerifyByReadAsync(container, this.TestDocPk1ExistingB);
            }
        }
Ejemplo n.º 16
0
        public void Several_SaveChanges_for_the_same_document_in_single_transaction_and_the_same_session_should_work()
        {
            using (var documentStore = NewRemoteDocumentStore(runInMemory: false, requestedStorage: "esent"))
                using (var session = documentStore.OpenSession())
                {
                    if (documentStore.DatabaseCommands.GetStatistics().SupportsDtc == false)
                    {
                        return;
                    }

                    session.Advanced.UseOptimisticConcurrency         = true;
                    session.Advanced.AllowNonAuthoritativeInformation = false;

                    using (var transaction = new TransactionScope())
                    {
                        var newDoc = new TestDoc {
                            Data = "Foo"
                        };
                        session.Store(newDoc);
                        session.SaveChanges();

                        newDoc.Data = "Bar";
                        session.SaveChanges();

                        newDoc.Data = "Foo-Bar!";

                        Assert.DoesNotThrow(() => session.SaveChanges());//should not throw concurrency exception
                        transaction.Complete();
                    }
                }
        }
Ejemplo n.º 17
0
        public async Task EncryptionResourceTokenAuth()
        {
            User user = EncryptionTests.databaseCore.GetUser(Guid.NewGuid().ToString());
            await EncryptionTests.databaseCore.CreateUserAsync(user.Id);

            PermissionProperties permission = await user.CreatePermissionAsync(
                new PermissionProperties(Guid.NewGuid().ToString(), PermissionMode.All, EncryptionTests.container));

            TestDoc testDoc = await EncryptionTests.CreateItemAsync(EncryptionTests.containerCore, EncryptionTests.dekId, TestDoc.PathsToEncrypt);

            (string endpoint, string _) = TestCommon.GetAccountInfo();
            CosmosClient resourceTokenBasedClient = new CosmosClientBuilder(endpoint, permission.Token)
                                                    .WithEncryptionKeyWrapProvider(new TestKeyWrapProvider())
                                                    .Build();

            DatabaseCore databaseForTokenClient  = (DatabaseInlineCore)resourceTokenBasedClient.GetDatabase(EncryptionTests.databaseCore.Id);
            Container    containerForTokenClient = databaseForTokenClient.GetContainer(EncryptionTests.container.Id);

            await EncryptionTests.PerformForbiddenOperationAsync(() =>
                                                                 databaseForTokenClient.GetDataEncryptionKey(EncryptionTests.dekId).ReadAsync(), "DEK.ReadAsync");

            await EncryptionTests.PerformForbiddenOperationAsync(() =>
                                                                 containerForTokenClient.ReadItemAsync <TestDoc>(testDoc.Id, new PartitionKey(testDoc.PK)), "ReadItemAsync");

            await EncryptionTests.PerformForbiddenOperationAsync(() =>
                                                                 containerForTokenClient.ReadItemStreamAsync(testDoc.Id, new PartitionKey(testDoc.PK)), "ReadItemStreamAsync");
        }
Ejemplo n.º 18
0
        protected static async Task VerifyByReadAsync(Container container, TestDoc doc, bool isStream = false, bool isSchematized = false, bool useEpk = false, string eTag = null)
        {
            Cosmos.PartitionKey partitionKey = BatchTestBase.GetPartitionKey(doc.Status);

            if (isStream)
            {
                string             id             = BatchTestBase.GetId(doc, isSchematized);
                ItemRequestOptions requestOptions = BatchTestBase.GetItemRequestOptions(doc, isSchematized, useEpk);
                ResponseMessage    response       = await container.ReadItemStreamAsync(id, partitionKey, requestOptions);

                Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
                Assert.AreEqual(doc, BatchTestBase.StreamToTestDoc(response.Content, isSchematized));

                if (eTag != null)
                {
                    Assert.AreEqual(eTag, response.Headers.ETag);
                }
            }
            else
            {
                ItemResponse <TestDoc> response = await container.ReadItemAsync <TestDoc>(doc.Id, partitionKey);

                Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
                Assert.AreEqual(doc, response.Resource);

                if (eTag != null)
                {
                    Assert.AreEqual(eTag, response.Headers.ETag);
                }
            }
        }
Ejemplo n.º 19
0
        public void ComparingDictionariesReturnTwoDifferencesForSameKey()
        {
            var oldDoc = new TestDoc()
            {
                Fields =
                {
                    ["a"] = 1,
                    ["b"] = 2,
                },
            };

            var newDoc = new TestDoc()
            {
                Fields =
                {
                    ["a"] = 3,
                    ["c"] = 5
                },
            };

            CompareLogic compareLogic = new CompareLogic();

            compareLogic.Config.MaxDifferences = int.MaxValue;

            var result = compareLogic.Compare(oldDoc, newDoc);

            Console.WriteLine(result.DifferencesString);
            Assert.IsTrue(result.Differences.Count == 3);
        }
Ejemplo n.º 20
0
        private static bool PopulateRequestOptions(RequestOptions requestOptions, TestDoc doc, bool isSchematized, bool useEpk, int?ttlInSeconds)
        {
            if (isSchematized)
            {
                requestOptions.Properties.Add(WFConstants.BackendHeaders.BinaryId, Encoding.UTF8.GetBytes(doc.Id));

                if (ttlInSeconds.HasValue)
                {
                    requestOptions.Properties.Add(WFConstants.BackendHeaders.TimeToLiveInSeconds, ttlInSeconds.Value.ToString());
                }

                if (useEpk)
                {
                    string epk = new Microsoft.Azure.Documents.PartitionKey(doc.Status)
                                 .InternalKey
                                 .GetEffectivePartitionKeyString(BatchTestBase.PartitionKeyDefinition);

                    requestOptions.Properties.Add(WFConstants.BackendHeaders.EffectivePartitionKeyString, epk);
                    requestOptions.Properties.Add(WFConstants.BackendHeaders.EffectivePartitionKey, BatchTestBase.HexStringToBytes(epk));
                    requestOptions.IsEffectivePartitionKeyRouting = true;
                }

                return(true);
            }

            return(false);
        }
Ejemplo n.º 21
0
        private static async Task VerifyItemByReadAsync(Container container, TestDoc testDoc)
        {
            ItemResponse <TestDoc> readResponse = await container.ReadItemAsync <TestDoc>(testDoc.Id, new PartitionKey(testDoc.PK));

            Assert.AreEqual(HttpStatusCode.OK, readResponse.StatusCode);
            Assert.AreEqual(testDoc, readResponse.Resource);
        }
Ejemplo n.º 22
0
 public TestDoc(TestDoc other)
 {
     this.Id           = other.Id;
     this.PK           = other.PK;
     this.NonSensitive = other.NonSensitive;
     this.Sensitive    = other.Sensitive;
 }
Ejemplo n.º 23
0
        public void CanQueryListWithContainsAny()
        {
            using (var store = NewDocumentStore())
            {
                using (var session = store.OpenSession())
                {
                    var doc = new TestDoc { StringArray = new[] { "test", "doc", "foo" } };
                    session.Store(doc);
                    session.SaveChanges();

                    session.Query<TestDoc>().Customize(x => x.WaitForNonStaleResultsAsOfNow()).ToList();

                    var items = new[] { "a", "b", "c" };
                    var test = session.Query<TestDoc>()
                                .Where(ar => ar.StringArray.ContainsAny(items) &&
                                             ar.SomeProperty == "somethingElse")
                                .ToString();
                    Assert.Equal("(StringArray:a OR StringArray:b OR StringArray:c) AND SomeProperty:somethingElse", test);

                    var results = session.Query<TestDoc>()
                                         .Where(t => t.StringArray.ContainsAny(new[] { "test", "NOTmatch" }))
                                         .ToList();
                    Assert.Equal(1, results.Count);

                    var noResults = session.Query<TestDoc>()
                                         .Where(t => t.StringArray.ContainsAny(new[] { "NOTmatch", "random" }))
                                         .ToList();
                    Assert.Equal(0, noResults.Count);
                }
            }
        }
        public async Task EncryptionResourceTokenAuthRestricted()
        {
            TestDoc testDoc = await EncryptionTests.CreateItemAsync(EncryptionTests.itemContainerCore, EncryptionTests.dekId, TestDoc.PathsToEncrypt);

            User restrictedUser = EncryptionTests.databaseCore.GetUser(Guid.NewGuid().ToString());
            await EncryptionTests.databaseCore.CreateUserAsync(restrictedUser.Id);

            PermissionProperties restrictedUserPermission = await restrictedUser.CreatePermissionAsync(
                new PermissionProperties(Guid.NewGuid().ToString(), PermissionMode.All, EncryptionTests.itemContainer));

            CosmosDataEncryptionKeyProvider dekProvider = new CosmosDataEncryptionKeyProvider(new TestKeyWrapProvider());
            TestEncryptor encryptor = new TestEncryptor(dekProvider);

            (string endpoint, string _) = TestCommon.GetAccountInfo();
            CosmosClient clientForRestrictedUser = new CosmosClientBuilder(endpoint, restrictedUserPermission.Token)
                                                   .WithEncryptor(encryptor)
                                                   .Build();

            Database  databaseForRestrictedUser  = clientForRestrictedUser.GetDatabase(EncryptionTests.databaseCore.Id);
            Container containerForRestrictedUser = databaseForRestrictedUser.GetContainer(EncryptionTests.itemContainer.Id);

            await EncryptionTests.PerformForbiddenOperationAsync(() =>
                                                                 dekProvider.InitializeAsync(databaseForRestrictedUser, EncryptionTests.keyContainer.Id), "CosmosDekProvider.InitializeAsync");

            await EncryptionTests.PerformOperationOnUninitializedDekProviderAsync(() =>
                                                                                  dekProvider.DataEncryptionKeyContainer.ReadDataEncryptionKeyAsync(EncryptionTests.dekId), "DEK.ReadAsync");

            await EncryptionTests.PerformOperationOnUninitializedDekProviderAsync(() =>
                                                                                  containerForRestrictedUser.ReadItemAsync <TestDoc>(testDoc.Id, new PartitionKey(testDoc.PK)), "ReadItemAsync");

            await EncryptionTests.PerformOperationOnUninitializedDekProviderAsync(() =>
                                                                                  containerForRestrictedUser.ReadItemStreamAsync(testDoc.Id, new PartitionKey(testDoc.PK)), "ReadItemStreamAsync");
        }
        public async Task BatchOrderedAsync()
        {
            Container container = BatchTestBase.JsonContainer;

            await this.CreateJsonTestDocsAsync(container);

            TestDoc firstDoc = BatchTestBase.PopulateTestDoc(this.PartitionKey1);

            TestDoc replaceDoc = this.GetTestDocCopy(firstDoc);

            replaceDoc.Cost += 20;

            TransactionalBatchResponse batchResponse = await new BatchCore((ContainerCore)container, BatchTestBase.GetPartitionKey(this.PartitionKey1))
                                                       .CreateItem(firstDoc)
                                                       .ReplaceItem(replaceDoc.Id, replaceDoc)
                                                       .ExecuteAsync();

            BatchSinglePartitionKeyTests.VerifyBatchProcessed(batchResponse, numberOfOperations: 2);

            Assert.AreEqual(HttpStatusCode.Created, batchResponse[0].StatusCode);
            Assert.AreEqual(HttpStatusCode.OK, batchResponse[1].StatusCode);

            // Ensure that the replace overwrote the doc from the first operation
            await BatchTestBase.VerifyByReadAsync(container, replaceDoc);
        }
        private async Task <Container> RunWithErrorAsync(
            Container container,
            Action <TransactionalBatch> appendOperation,
            HttpStatusCode expectedFailedOperationStatusCode)
        {
            TestDoc testDocToCreate        = BatchTestBase.PopulateTestDoc(this.PartitionKey1);
            TestDoc anotherTestDocToCreate = BatchTestBase.PopulateTestDoc(this.PartitionKey1);

            TransactionalBatch batch = new BatchCore((ContainerCore)container, BatchTestBase.GetPartitionKey(this.PartitionKey1))
                                       .CreateItem(testDocToCreate);

            appendOperation(batch);

            TransactionalBatchResponse batchResponse = await batch
                                                       .CreateItem(anotherTestDocToCreate)
                                                       .ExecuteAsync();

            BatchSinglePartitionKeyTests.VerifyBatchProcessed(
                batchResponse,
                numberOfOperations: 3,
                expectedStatusCode: expectedFailedOperationStatusCode);

            Assert.AreEqual((HttpStatusCode)StatusCodes.FailedDependency, batchResponse[0].StatusCode);
            Assert.AreEqual(expectedFailedOperationStatusCode, batchResponse[1].StatusCode);
            Assert.AreEqual((HttpStatusCode)StatusCodes.FailedDependency, batchResponse[2].StatusCode);

            await BatchTestBase.VerifyNotFoundAsync(container, testDocToCreate);

            await BatchTestBase.VerifyNotFoundAsync(container, anotherTestDocToCreate);

            return(container);
        }
Ejemplo n.º 27
0
        public async Task EncryptionBulkCrud()
        {
            TestDoc docToReplace = await EncryptionTests.CreateItemAsync(EncryptionTests.containerCore, EncryptionTests.dekId, TestDoc.PathsToEncrypt);

            docToReplace.NonSensitive = Guid.NewGuid().ToString();
            docToReplace.Sensitive    = Guid.NewGuid().ToString();

            TestDoc docToUpsert = await EncryptionTests.CreateItemAsync(EncryptionTests.containerCore, EncryptionTests.dekId, TestDoc.PathsToEncrypt);

            docToUpsert.NonSensitive = Guid.NewGuid().ToString();
            docToUpsert.Sensitive    = Guid.NewGuid().ToString();

            TestDoc docToDelete = await EncryptionTests.CreateItemAsync(EncryptionTests.containerCore, EncryptionTests.dekId, TestDoc.PathsToEncrypt);

            (string endpoint, string authKey) = TestCommon.GetAccountInfo();
            CosmosClient clientWithBulk = new CosmosClientBuilder(endpoint, authKey)
                                          .WithEncryptionKeyWrapProvider(new TestKeyWrapProvider())
                                          .WithBulkExecution(true)
                                          .Build();

            DatabaseCore  databaseWithBulk  = (DatabaseInlineCore)clientWithBulk.GetDatabase(EncryptionTests.databaseCore.Id);
            ContainerCore containerWithBulk = (ContainerInlineCore)databaseWithBulk.GetContainer(EncryptionTests.container.Id);

            List <Task> tasks = new List <Task>();

            tasks.Add(EncryptionTests.CreateItemAsync(containerWithBulk, EncryptionTests.dekId, TestDoc.PathsToEncrypt));
            tasks.Add(EncryptionTests.UpsertItemAsync(containerWithBulk, TestDoc.Create(), EncryptionTests.dekId, TestDoc.PathsToEncrypt, HttpStatusCode.Created));
            tasks.Add(EncryptionTests.ReplaceItemAsync(containerWithBulk, docToReplace, EncryptionTests.dekId, TestDoc.PathsToEncrypt));
            tasks.Add(EncryptionTests.UpsertItemAsync(containerWithBulk, docToUpsert, EncryptionTests.dekId, TestDoc.PathsToEncrypt, HttpStatusCode.OK));
            tasks.Add(EncryptionTests.DeleteItemAsync(containerWithBulk, docToDelete));
            await Task.WhenAll(tasks);
        }
        public async Task BatchItemTimeToLiveAsync()
        {
            // Verify with schematized containers where we are allowed to send TTL as a header
            const bool isSchematized = true;
            const bool isStream      = true;
            Container  container     = BatchTestBase.SchematizedContainer;

            await this.CreateSchematizedTestDocsAsync(container);

            {
                TestDoc testDocToCreate        = BatchTestBase.PopulateTestDoc(this.PartitionKey1);
                TestDoc anotherTestDocToCreate = BatchTestBase.PopulateTestDoc(this.PartitionKey1);

                TestDoc testDocToReplace = this.GetTestDocCopy(this.TestDocPk1ExistingA);
                testDocToReplace.Cost++;

                const int ttlInSeconds = 3;
                const int infiniteTtl  = -1;

                TestDoc testDocToUpsert = await BatchTestBase.CreateSchematizedTestDocAsync(container, this.PartitionKey1, ttlInSeconds : ttlInSeconds);

                testDocToUpsert.Cost++;

                BatchCore batch = (BatchCore)(new BatchCore((ContainerCore)container, BatchTestBase.GetPartitionKey(this.PartitionKey1))
                                              .CreateItemStream(
                                                  BatchTestBase.TestDocToStream(testDocToCreate, isSchematized),
                                                  BatchTestBase.GetBatchItemRequestOptions(testDocToCreate, isSchematized, ttlInSeconds: ttlInSeconds))
                                              .CreateItemStream(
                                                  BatchTestBase.TestDocToStream(anotherTestDocToCreate, isSchematized),
                                                  BatchTestBase.GetBatchItemRequestOptions(anotherTestDocToCreate, isSchematized))
                                              .ReplaceItemStream(
                                                  BatchTestBase.GetId(testDocToReplace, isSchematized),
                                                  BatchTestBase.TestDocToStream(testDocToReplace, isSchematized),
                                                  BatchTestBase.GetBatchItemRequestOptions(testDocToReplace, isSchematized, ttlInSeconds: ttlInSeconds))
                                              .UpsertItemStream(
                                                  BatchTestBase.TestDocToStream(testDocToUpsert, isSchematized),
                                                  BatchTestBase.GetBatchItemRequestOptions(testDocToUpsert, isSchematized, ttlInSeconds: infiniteTtl)));

                TransactionalBatchResponse batchResponse = await batch.ExecuteAsync(BatchTestBase.GetUpdatedBatchRequestOptions(isSchematized: true));

                BatchSinglePartitionKeyTests.VerifyBatchProcessed(batchResponse, numberOfOperations: 4);

                Assert.AreEqual(HttpStatusCode.Created, batchResponse[0].StatusCode);
                Assert.AreEqual(HttpStatusCode.Created, batchResponse[1].StatusCode);
                Assert.AreEqual(HttpStatusCode.OK, batchResponse[2].StatusCode);
                Assert.AreEqual(HttpStatusCode.OK, batchResponse[3].StatusCode);

                // wait for TTL to expire
                await Task.Delay(TimeSpan.FromSeconds(ttlInSeconds + 1));

                await BatchTestBase.VerifyNotFoundAsync(container, testDocToCreate, isSchematized);

                await BatchTestBase.VerifyByReadAsync(container, anotherTestDocToCreate, isStream, isSchematized);

                await BatchTestBase.VerifyNotFoundAsync(container, testDocToReplace, isSchematized);

                await BatchTestBase.VerifyByReadAsync(container, testDocToUpsert, isStream, isSchematized);
            }
        }
Ejemplo n.º 29
0
        public async Task DecryptQueryResultMultipleDocsTest()
        {
            TestDoc testDoc1 = await EncryptionTests.CreateItemAsync(EncryptionTests.containerCore, EncryptionTests.dekId, TestDoc.PathsToEncrypt);

            TestDoc testDoc2 = await EncryptionTests.CreateItemAsync(EncryptionTests.containerCore, EncryptionTests.dekId, TestDoc.PathsToEncrypt);

            await ValidateQueryResultsMultipleDocumentsAsync(EncryptionTests.containerCore, testDoc1, testDoc2);
        }
Ejemplo n.º 30
0
        protected static async Task <TestDoc> CreateJsonTestDocAsync(Container container, object partitionKey, int minDesiredSize = 20)
        {
            TestDoc doc = BatchTestBase.PopulateTestDoc(partitionKey, minDesiredSize);
            ItemResponse <TestDoc> createResponse = await container.CreateItemAsync(doc, BatchTestBase.GetPartitionKey(partitionKey));

            Assert.AreEqual(HttpStatusCode.Created, createResponse.StatusCode);
            return(doc);
        }
        public async Task EncryptionDecryptQueryValueResponse()
        {
            TestDoc testDoc = await EncryptionTests.CreateItemAsync(EncryptionTests.itemContainerCore, EncryptionTests.dekId, TestDoc.PathsToEncrypt);

            string query = "SELECT VALUE COUNT(1) FROM c";

            await EncryptionTests.ValidateQueryResponseAsync(EncryptionTests.itemContainerCore, query);
        }
Ejemplo n.º 32
0
        protected static string GetId(TestDoc doc, bool isSchematized)
        {
            if (isSchematized)
            {
                return("cdbBinaryIdRequest");
            }

            return(doc.Id);
        }
Ejemplo n.º 33
0
		public void LoadExistingDocAsync_Test_embedded()
		{
			using (var store = NewDocumentStore())
			{
				var testDoc1 = new TestDoc
				{
					Name = "Jacob"
				};
				using (var session = store.OpenAsyncSession())
				{
					session.StoreAsync(testDoc1).Wait();
					session.SaveChangesAsync().Wait();

					var existingDoc = session.LoadAsync<TestDoc>(testDoc1.Id).Result;
					Assert.Equal(existingDoc.Name, "Jacob");
				}
			}
		}
Ejemplo n.º 34
0
		public void CanQueryLongCount()
		{
			using (var store = NewDocumentStore())
			{
				using (var session = store.OpenSession())
				{
					var doc = new TestDoc { Name = "foo" };
					session.Store(doc);
					session.SaveChanges();
				}

				using (var session = store.OpenSession())
				{
					long count = session.Query<TestDoc>()
						.Customize(x=>x.WaitForNonStaleResults())
						.LongCount();
					Assert.Equal(1, count);
				}
			}
		}
Ejemplo n.º 35
0
        public void CanQueryArrayWithContains()
        {
            using (var store = NewDocumentStore())
            {
                using (var session = store.OpenSession())
                {
                    var doc = new TestDoc {StringArray = new[] {"test", "doc", "foo"}};
                    session.Store(doc);
                    session.SaveChanges();
                }

                using (var session = store.OpenSession())
                {
                    var otherDoc = new TestDoc {SomeProperty = "foo"};
                    var doc = session.Query<TestDoc>()
                        .FirstOrDefault(ar => ar.StringArray.Contains(otherDoc.SomeProperty));
                    Assert.NotNull(doc);
                }
            }
        }
Ejemplo n.º 36
0
		public void CanQueryArrayWithAny()
		{
			using (var store = NewDocumentStore())
			{
				using (var session = store.OpenSession())
				{
					var doc = new TestDoc {StringArray = new [] {"test", "doc", "foo"}};
					session.Store(doc);
					session.SaveChanges();
				}

				using (var session = store.OpenSession())
				{
					var otherDoc = new TestDoc {SomeProperty = "foo"};
					var doc = (from ar in session.Query<TestDoc>()
							   where ar.StringArray.Any(ac => ac == otherDoc.SomeProperty)
							   select ar).FirstOrDefault();
					Assert.NotNull(doc);
				}
			}
		}
Ejemplo n.º 37
0
		public void DoesNotSupportStrings()
		{
			using (var store = NewDocumentStore())
			{
				using (var session = store.OpenSession())
				{
					var doc = new TestDoc {SomeProperty = "Ensure that Contains on IEnumerable<Char> is not supported."};
					session.Store(doc);
					session.SaveChanges();
				}

				using (var session = store.OpenSession())
				{
					var otherDoc = new TestDoc {SomeProperty = "Contains"};
					var exception = Assert.Throws<NotSupportedException>(() =>
					{
						session.Query<TestDoc>().FirstOrDefault(ar => ar.SomeProperty.Contains(otherDoc.SomeProperty));
					});
					Assert.Contains("Contains is not supported, doing a substring match", exception.InnerException.Message);
				}
			}
		}