///// <summary>
        ///// Changes the replication mode to sync for server.
        ///// </summary>
        ///// <param name="fabricClient"></param>
        //internal static void SwitchServerToSyncReplication(COMMONNAMESPACE.IFabricClient fabricClient, string callingComponent)
        //{
        //    if (!IsCurrentReplicationModeAsync(fabricClient)["Server"])
        //    {
        //        return;
        //    }

        //    NamingServiceConfig.NamingServiceConfigurationWriter namingServiceWriter =
        //            new NamingServiceConfig.NamingServiceConfigurationWriter(fabricClient);

        //    NamingServiceConfig.DocumentServiceConfiguration config = new NamingServiceConfig.DocumentServiceConfiguration();
        //    config.DocumentServiceName = ConfigurationManager.AppSettings["DatabaseAccountId"];
        //    config.IsServerReplicationAsync = false;

        //    namingServiceWriter.UpdateDatabaseAccountConfigurationAsync(config).Wait();

        //    Task.Delay(TimeSpan.FromSeconds(ReplicationTests.ConfigurationRefreshIntervalInSec)).Wait();
        //    TestCommon.ForceRefreshNamingServiceConfigs(callingComponent, FabricServiceType.ServerService).Wait();
        //}

        ///// <summary>
        ///// Changes the replication mode to async for server.
        ///// </summary>
        ///// <param name="fabricClient"></param>
        //internal static void SwitchServerToAsyncReplication(COMMONNAMESPACE.IFabricClient fabricClient, string callingComponent)
        //{
        //    if (IsCurrentReplicationModeAsync(fabricClient)["Server"])
        //    {
        //        return;
        //    }

        //    NamingServiceConfig.NamingServiceConfigurationWriter namingServiceWriter =
        //        new NamingServiceConfig.NamingServiceConfigurationWriter(fabricClient);

        //    NamingServiceConfig.DocumentServiceConfiguration config = new NamingServiceConfig.DocumentServiceConfiguration();
        //    config.DocumentServiceName = ConfigurationManager.AppSettings["DatabaseAccountId"];
        //    config.IsServerReplicationAsync = true;

        //    namingServiceWriter.UpdateDatabaseAccountConfigurationAsync(config).Wait();

        //    Task.Delay(TimeSpan.FromSeconds(ReplicationTests.ConfigurationRefreshIntervalInSec)).Wait();
        //    TestCommon.ForceRefreshNamingServiceConfigs(callingComponent, FabricServiceType.ServerService).Wait();
        //}

        #endregion

        #region Environment Configuration Helpers

        internal static DocumentClient[] GetClientsLocked(bool useGateway = false, Protocol protocol = Protocol.Tcp, int timeoutInSeconds = 10, ConsistencyLevel?defaultConsistencyLevel = null, AuthorizationTokenType tokenType = AuthorizationTokenType.PrimaryMasterKey)
        {
            DocumentClient[] toReturn = new DocumentClient[TestCommon.ReplicationFactor];
            for (uint i = 0; i < toReturn.Length; i++)
            {
                toReturn[i] = TestCommon.CreateClient(useGateway, protocol, timeoutInSeconds, defaultConsistencyLevel, tokenType);
                toReturn[i].LockClient(i);
            }

            return(toReturn);
        }
Beispiel #2
0
        internal async Task TestEtagOnUpsertOperation(bool useGateway, Protocol protocol = Protocol.Tcp)
        {
            using (DocumentClient client = TestCommon.CreateClient(false, Protocol.Tcp))
            {
                Database db             = (await client.CreateDatabaseAsync(new Database()
                {
                    Id = Guid.NewGuid().ToString()
                })).Resource;
                DocumentCollection coll = await TestCommon.CreateCollectionAsync(client, db, new DocumentCollection()
                {
                    Id           = Guid.NewGuid().ToString(),
                    PartitionKey = new PartitionKeyDefinition()
                    {
                        Paths = new System.Collections.ObjectModel.Collection <string>()
                        {
                            "/id"
                        }
                    }
                });

                LinqGeneralBaselineTests.Book myBook = new LinqGeneralBaselineTests.Book();
                myBook.Id    = Guid.NewGuid().ToString();
                myBook.Title = "Azure DocumentDB 101";

                Document doc = (await client.CreateDocumentAsync(coll.SelfLink, myBook)).Resource;

                myBook.Title = "Azure DocumentDB 201";
                await client.ReplaceDocumentAsync(doc.SelfLink, myBook);

                AccessCondition condition = new AccessCondition();
                condition.Type      = AccessConditionType.IfMatch;
                condition.Condition = doc.ETag;

                RequestOptions requestOptions = new RequestOptions();
                requestOptions.AccessCondition = condition;

                myBook.Title = "Azure DocumentDB 301";

                try
                {
                    await client.UpsertDocumentAsync(coll.SelfLink, myBook, requestOptions);

                    Assert.Fail("Upsert Document should fail since the Etag is not matching.");
                }
                catch (Exception ex)
                {
                    DocumentClientException innerException = ex as DocumentClientException;
                    Assert.AreEqual(HttpStatusCode.PreconditionFailed, innerException.StatusCode, "Invalid status code");
                }
            }
        }
        public static void Initialize(TestContext textContext)
        {
            client = TestCommon.CreateClient(true);

            var db = new Database()
            {
                Id = nameof(LinqTranslationBaselineTests)
            };

            try
            {
                var response = client.DeleteDatabaseAsync(UriFactory.CreateDatabaseUri(db.Id)).Result;
            }
            catch { }
            testDb = client.CreateDatabaseAsync(db).Result;
        }
Beispiel #4
0
        public void ValidateVersionHeader()
        {
            string correctVersion = HttpConstants.Versions.CurrentVersion;

            try
            {
                DocumentClient client = TestCommon.CreateClient(true);
                var            db     = client.CreateDatabaseAsync(new Database()
                {
                    Id = Guid.NewGuid().ToString()
                }).Result.Resource;
                PartitionKeyDefinition partitionKeyDefinition = new PartitionKeyDefinition {
                    Paths = new System.Collections.ObjectModel.Collection <string>(new[] { "/pk" }), Kind = PartitionKind.Hash
                };
                var coll = client.CreateDocumentCollectionAsync(db.SelfLink, new DocumentCollection()
                {
                    Id = Guid.NewGuid().ToString(), PartitionKey = partitionKeyDefinition
                }).Result.Resource;
                var doc = client.CreateDocumentAsync(coll.SelfLink, new Document()).Result.Resource;
                client = TestCommon.CreateClient(true);
                doc    = client.CreateDocumentAsync(coll.SelfLink, new Document()).Result.Resource;
                HttpConstants.Versions.CurrentVersion = "2015-01-01";
                client = TestCommon.CreateClient(true);
                try
                {
                    doc = client.CreateDocumentAsync(coll.SelfLink, new Document()).Result.Resource;
                    Assert.Fail("Should have faild because of version error");
                }
                catch (AggregateException exception)
                {
                    var dce = exception.InnerException as DocumentClientException;
                    if (dce != null)
                    {
                        Assert.AreEqual(dce.StatusCode, HttpStatusCode.BadRequest);
                    }
                    else
                    {
                        Assert.Fail("Should have faild because of version error with DocumentClientException BadRequest");
                    }
                }
            }
            finally
            {
                HttpConstants.Versions.CurrentVersion = correctVersion;
            }
        }
        private async Task <DocumentCollection> SetupSingleCollectionScenario()
        {
            DocumentClient client = TestCommon.CreateClient(true);
            await TestCommon.DeleteAllDatabasesAsync();

            Database database             = (await client.CreateDatabaseAsync(new Database {
                Id = this.DatabaseName
            })).Resource;
            DocumentCollection collection = (await client.CreateDocumentCollectionIfNotExistsAsync(database.SelfLink, new DocumentCollection {
                Id = this.CollectionName
            }, new RequestOptions {
                OfferThroughput = 10000
            })).Resource;

            //   await Task.Delay(30000);

            return(collection);
        }
Beispiel #6
0
        public async Task ResourceResponseStreamingTest()
        {
            using (DocumentClient client = TestCommon.CreateClient(true))
            {
                Database db             = (await client.CreateDatabaseAsync(new Database()
                {
                    Id = Guid.NewGuid().ToString()
                })).Resource;
                DocumentCollection coll = await TestCommon.CreateCollectionAsync(client, db, new DocumentCollection()
                {
                    Id           = Guid.NewGuid().ToString(),
                    PartitionKey = new PartitionKeyDefinition()
                    {
                        Paths = new System.Collections.ObjectModel.Collection <string>()
                        {
                            "/id"
                        }
                    }
                });

                ResourceResponse <Document> doc = await client.CreateDocumentAsync(coll.SelfLink, new Document()
                {
                    Id = Guid.NewGuid().ToString()
                });

                Assert.AreEqual(doc.ResponseStream.Position, 0);

                StreamReader streamReader = new StreamReader(doc.ResponseStream);
                string       text         = streamReader.ReadToEnd();

                Assert.AreEqual(doc.ResponseStream.Position, doc.ResponseStream.Length);

                try
                {
                    doc.Resource.ToString();
                    Assert.Fail("Deserializing Resource here should throw exception since the stream was already read");
                }
                catch (JsonReaderException ex)
                {
                    Console.WriteLine("Expected exception while deserializing Resource: " + ex.Message);
                }
            }
        }
Beispiel #7
0
        private async Task <CosmosContainerSettings> SetupSingleCollectionScenario()
        {
            DocumentClient client = TestCommon.CreateClient(true);

            TestCommon.DeleteAllDatabasesAsync(client).Wait();

            CosmosDatabaseSettings database    = (await client.CreateDatabaseAsync(new CosmosDatabaseSettings {
                Id = this.DatabaseName
            })).Resource;
            CosmosContainerSettings collection = (await client.CreateDocumentCollectionIfNotExistsAsync(database.SelfLink, new CosmosContainerSettings {
                Id = this.CollectionName
            }, new RequestOptions {
                OfferThroughput = 10000
            })).Resource;

            //   await Task.Delay(30000);

            return(collection);
        }
        public void ValidateVersionHeader()
        {
            string correctVersion = HttpConstants.Versions.CurrentVersion;

            try
            {
                DocumentClient client = TestCommon.CreateClient(true);
                var            db     = client.CreateDatabaseAsync(new CosmosDatabaseSettings()
                {
                    Id = Guid.NewGuid().ToString()
                }).Result.Resource;
                var coll = client.CreateDocumentCollectionAsync(db.SelfLink, new CosmosContainerSettings()
                {
                    Id = Guid.NewGuid().ToString()
                }).Result.Resource;
                var doc = client.CreateDocumentAsync(coll.SelfLink, new Document()).Result.Resource;
                client = TestCommon.CreateClient(true);
                doc    = client.CreateDocumentAsync(coll.SelfLink, new Document()).Result.Resource;
                HttpConstants.Versions.CurrentVersion = "2015-01-01";
                client = TestCommon.CreateClient(true);
                try
                {
                    doc = client.CreateDocumentAsync(coll.SelfLink, new Document()).Result.Resource;
                    Assert.Fail("Should have faild because of version error");
                }
                catch (AggregateException exception)
                {
                    var dce = exception.InnerException as DocumentClientException;
                    if (dce != null)
                    {
                        Assert.AreEqual(dce.StatusCode, HttpStatusCode.BadRequest);
                    }
                    else
                    {
                        Assert.Fail("Should have faild because of version error with DocumentClientException BadRequest");
                    }
                }
            }
            finally
            {
                HttpConstants.Versions.CurrentVersion = correctVersion;
            }
        }
        public void ValidateDynamicAttachmentQuery() //Ensure query on custom property of attachment.
        {
            DocumentClient client = TestCommon.CreateClient(true);

            var myDocument = new Document();

            IOrderedQueryable <SpecialAttachment2> attachmentQuery = new DocumentQuery <SpecialAttachment2>(client, ResourceType.Attachment, typeof(Attachment), null, null);

            //Simple Equality on custom property.
            IQueryable <dynamic> docQuery = from attachment in attachmentQuery
                                            where attachment.Title == "My Book Title2"
                                            select attachment;

            this.VerifyQueryTranslation(docQuery, "SELECT * FROM root WHERE (root[\"Title\"] = \"My Book Title2\") ");

            docQuery = from attachment in attachmentQuery
                       where attachment.Title == "My Book Title"
                       select attachment;

            this.VerifyQueryTranslation(docQuery, "SELECT * FROM root WHERE (root[\"Title\"] = \"My Book Title\") ");
        }
Beispiel #10
0
        public async Task TestInitialize()
        {
            this.cancellationTokenSource = new CancellationTokenSource();
            this.cancellationToken       = this.cancellationTokenSource.Token;

            this.cosmosClient = TestCommon.CreateCosmosClient();
            this.database     = await this.cosmosClient.CreateDatabaseAsync(Guid.NewGuid().ToString(),
                                                                            cancellationToken : this.cancellationToken);

            this.documentClient = TestCommon.CreateClient(true, defaultConsistencyLevel: Documents.ConsistencyLevel.Session);

            string            PartitionKey = "/partitionKey";
            ContainerResponse response     = await this.database.CreateContainerAsync(
                new ContainerProperties(id : Guid.NewGuid().ToString(), partitionKeyPath : PartitionKey),
                cancellationToken : this.cancellationToken);

            Assert.IsNotNull(response);
            Assert.IsNotNull(response.Container);
            Assert.IsNotNull(response.Resource);
            this.Container = (ContainerCore)response;
        }
        public static void Initialize(TestContext textContext)
        {
            client = TestCommon.CreateClient(false, defaultConsistencyLevel: ConsistencyLevel.Session);

            // Set a callback to get the handle of the last executed query to do the verification
            // This is neede because aggregate queries return type is a scalar so it can't be used
            // to verify the translated LINQ directly as other queries type.
            client.OnExecuteScalarQueryCallback = q => LinqAggregateFunctionBaselineTests.lastExecutedScalarQuery = q;

            string databaseName = $"{nameof(LinqAggregateFunctionBaselineTests)}-{Guid.NewGuid().ToString("N")}";

            databaseUri = UriFactory.CreateDatabaseUri(databaseName);
            CosmosDatabaseSettings testDb = client.CreateDatabaseAsync(new CosmosDatabaseSettings()
            {
                Id = databaseName
            }).Result;

            CosmosContainerSettings collection;

            getQuery       = LinqTestsCommon.GenerateSimpleData(client, testDb, out collection);
            getQueryFamily = LinqTestsCommon.GenerateFamilyData(client, testDb, out collection);
        }
        public void TestInitialize()
        {
            this.DatabaseName   = Guid.NewGuid().ToString();
            this.CollectionName = Guid.NewGuid().ToString();

            this.read0 = TestCommon.CreateClient(false, enableEndpointDiscovery: false, tokenType: AuthorizationTokenType.SystemAll, createForGeoRegion: true);
            read0.LockClient(0);

            this.read1 = TestCommon.CreateClient(false, enableEndpointDiscovery: false, tokenType: AuthorizationTokenType.SystemAll, createForGeoRegion: true);
            read1.LockClient(1);

            this.read2 = TestCommon.CreateClient(false, enableEndpointDiscovery: false, tokenType: AuthorizationTokenType.SystemAll, createForGeoRegion: true);
            read2.LockClient(2);

            this.write0 = TestCommon.CreateClient(false, enableEndpointDiscovery: false, tokenType: AuthorizationTokenType.SystemAll, createForGeoRegion: false);
            write0.LockClient(0);

            this.write1 = TestCommon.CreateClient(false, enableEndpointDiscovery: false, tokenType: AuthorizationTokenType.SystemAll, createForGeoRegion: false);
            write1.LockClient(1);

            this.write2 = TestCommon.CreateClient(false, enableEndpointDiscovery: false, tokenType: AuthorizationTokenType.SystemAll, createForGeoRegion: false);
            write2.LockClient(2);
        }
Beispiel #13
0
        public void ValidateEmitVerboseTracesInQueryHttps()
        {
            var client = TestCommon.CreateClient(false, Protocol.Https);

            ValidateEmitVerboseTracesInQuery(client, true);
        }
Beispiel #14
0
        public void ValidateEmitVerboseTracesInQueryGateway()
        {
            var client = TestCommon.CreateClient(true);

            ValidateEmitVerboseTracesInQuery(client);
        }
Beispiel #15
0
        public void ValidateEnableLowPrecisionOrderByGateway()
        {
            var client = TestCommon.CreateClient(true);

            ValidateEnableLowPrecisionOrderBy(client);
        }
Beispiel #16
0
 public async Task Startup()
 {
     //var client = TestCommon.CreateClient(false, Protocol.Tcp);
     var client = TestCommon.CreateClient(true);
     await TestCommon.DeleteAllDatabasesAsync();
 }
Beispiel #17
0
        public void ValidateEnableScanInQueryGateway()
        {
            var client = TestCommon.CreateClient(true);

            ValidateEnableScanInQuery(client);
        }
Beispiel #18
0
        public void ValidateIndexingDirectiveGateway()
        {
            var client = TestCommon.CreateClient(true);

            ValidateIndexingDirective(client);
        }
Beispiel #19
0
        public async Task ValidateCollectionIndexProgressHeadersGateway()
        {
            var client = TestCommon.CreateClient(true);

            await ValidateCollectionIndexProgressHeaders(client);
        }
 protected CustomSerializationTests()
 {
     this.hostUri        = new Uri(ConfigurationManager.AppSettings["GatewayEndpoint"]);
     this.masterKey      = ConfigurationManager.AppSettings["MasterKey"];
     this.documentClient = TestCommon.CreateClient(true);
 }
 public void TestInitialize()
 {
     this.client   = TestCommon.CreateClient(true);
     this.database = TestCommon.CreateOrGetDatabase(this.client);
 }
Beispiel #22
0
        private async Task ValidatePartitionedCollectionCRUDAsync()
        {
            using (DocumentClient writeRegionClient = TestCommon.CreateClient(true, createForGeoRegion: false))
            {
                using (DocumentClient readRegionClient = TestCommon.CreateClient(true, defaultConsistencyLevel: ConsistencyLevel.Session, createForGeoRegion: true, enableEndpointDiscovery: false))
                {
                    string databaseName       = "geocollcruddb-" + Guid.NewGuid();
                    CosmosDatabaseSettings db = new CosmosDatabaseSettings
                    {
                        Id = databaseName,
                    };

                    ResourceResponse <CosmosDatabaseSettings> dbResponse = await writeRegionClient.CreateDatabaseAsync(db);

                    Assert.AreEqual(HttpStatusCode.Created, dbResponse.StatusCode, "Status code should be Created (201)");
                    Util.ValidateCommonCustomHeaders(dbResponse.Headers);
                    this.ValidateDatabaseResponseBody(dbResponse.Resource, databaseName);

                    string databaseSelfLink = dbResponse.Resource.SelfLink;

                    // Add some delay since we do async replication between geo-regions
                    await Task.Delay(GlobalDatabaseAccountTests.WaitDurationForAsyncReplication);

                    ResourceResponse <CosmosDatabaseSettings> readRegionDbResponse = await readRegionClient.ReadDatabaseAsync(databaseSelfLink);

                    this.ValidateDatabaseResponseBody(readRegionDbResponse.Resource, databaseName);
                    Assert.AreEqual(dbResponse.Resource.ETag, readRegionDbResponse.Resource.ETag);
                    Assert.AreEqual(dbResponse.Resource.ResourceId, readRegionDbResponse.Resource.ResourceId);
                    Assert.AreEqual(dbResponse.Resource.SelfLink, readRegionDbResponse.Resource.SelfLink);

                    string collectionName = "geocollcrudcoll-" + Guid.NewGuid();
                    CosmosContainerSettings collection = new CosmosContainerSettings()
                    {
                        Id           = collectionName,
                        PartitionKey = new PartitionKeyDefinition
                        {
                            Paths = new Collection <string> {
                                "/id"
                            }
                        }
                    };
                    ResourceResponse <CosmosContainerSettings> collResponse = await writeRegionClient.CreateDocumentCollectionAsync(databaseSelfLink, collection, new RequestOptions { OfferThroughput = 12000 });

                    Assert.AreEqual(HttpStatusCode.Created, collResponse.StatusCode, "Status code should be Created (201)");

                    string collectionSelfLink = collResponse.Resource.SelfLink;

                    // Add some delay since we do async replication between geo-regions
                    await Task.Delay(GlobalDatabaseAccountTests.WaitDurationForAsyncReplication);

                    ResourceResponse <CosmosContainerSettings> readRegionCollResponse = await readRegionClient.ReadDocumentCollectionAsync(collectionSelfLink, new RequestOptions { SessionToken = collResponse.SessionToken });

                    Assert.AreEqual(collectionName, readRegionCollResponse.Resource.Id);
                    Assert.AreEqual(collResponse.Resource.ETag, readRegionCollResponse.Resource.ETag);
                    Assert.AreEqual(collResponse.Resource.ResourceId, readRegionCollResponse.Resource.ResourceId);
                    Assert.AreEqual(collResponse.Resource.SelfLink, readRegionCollResponse.Resource.SelfLink);

                    // Create a document
                    string   documentName = "geocollcruddoc-" + Guid.NewGuid();
                    Document document     = new Document()
                    {
                        Id = documentName,
                    };
                    ResourceResponse <Document> docResponse = await writeRegionClient.CreateDocumentAsync(collectionSelfLink, document);

                    Assert.AreEqual(HttpStatusCode.Created, docResponse.StatusCode, "Status code should be Created (201)");
                    Util.ValidateCommonCustomHeaders(docResponse.Headers);

                    string documentSelfLink = docResponse.Resource.SelfLink;

                    // Add some delay since we do async replication between geo-regions
                    await Task.Delay(GlobalDatabaseAccountTests.WaitDurationForAsyncReplication);

                    ResourceResponse <Document> readRegionDocResponse = await readRegionClient.ReadDocumentAsync(documentSelfLink, new RequestOptions { PartitionKey = new PartitionKey(document.Id), SessionToken = docResponse.SessionToken });

                    Assert.AreEqual(documentName, readRegionDocResponse.Resource.Id);
                    Assert.AreEqual(docResponse.Resource.ETag, readRegionDocResponse.Resource.ETag);
                    Assert.AreEqual(docResponse.Resource.ResourceId, readRegionDocResponse.Resource.ResourceId);
                    Assert.AreEqual(docResponse.Resource.SelfLink, readRegionDocResponse.Resource.SelfLink);

                    // Delete document from write region
                    await writeRegionClient.DeleteDocumentAsync(documentSelfLink, new RequestOptions { PartitionKey = new PartitionKey(document.Id) });

                    await Task.Delay(GlobalDatabaseAccountTests.WaitDurationForAsyncReplication);

                    // Try reading document from read region
                    try
                    {
                        await readRegionClient.ReadDocumentAsync(documentSelfLink, new RequestOptions { PartitionKey = new PartitionKey(document.Id), SessionToken = docResponse.SessionToken });

                        Assert.Fail("Expected exception when reading deleted document from read region");
                    }
                    catch (DocumentClientException clientException)
                    {
                        TestCommon.AssertException(clientException, HttpStatusCode.NotFound);
                    }

                    // Create another document
                    documentName = "geocolldeltestdoc-" + Guid.NewGuid();
                    document     = new Document()
                    {
                        Id = documentName,
                    };
                    docResponse = await writeRegionClient.CreateDocumentAsync(collectionSelfLink, document);

                    Assert.AreEqual(HttpStatusCode.Created, docResponse.StatusCode, "Status code should be Created (201)");
                    Util.ValidateCommonCustomHeaders(docResponse.Headers);

                    documentSelfLink = docResponse.Resource.SelfLink;

                    // Add some delay since we do async replication between geo-regions
                    await Task.Delay(GlobalDatabaseAccountTests.WaitDurationForAsyncReplication);

                    readRegionDocResponse = await readRegionClient.ReadDocumentAsync(documentSelfLink, new RequestOptions { PartitionKey = new PartitionKey(document.Id), SessionToken = docResponse.SessionToken });

                    Assert.AreEqual(documentName, readRegionDocResponse.Resource.Id);
                    Assert.AreEqual(docResponse.Resource.ETag, readRegionDocResponse.Resource.ETag);
                    Assert.AreEqual(docResponse.Resource.ResourceId, readRegionDocResponse.Resource.ResourceId);
                    Assert.AreEqual(docResponse.Resource.SelfLink, readRegionDocResponse.Resource.SelfLink);


                    ResourceResponse <CosmosContainerSettings> replaceCollResponse = await writeRegionClient.ReplaceDocumentCollectionAsync(collResponse.Resource);

                    // TODO: Collection delete is not working, and that is why if you have this test as the last test, it will cause problem to other tests
                    // Delete collection from write region
                    await writeRegionClient.DeleteDocumentCollectionAsync(collectionSelfLink);

                    await Task.Delay(GlobalDatabaseAccountTests.WaitDurationForAsyncReplication);

                    // Try reading collection from write region
                    try
                    {
                        await writeRegionClient.ReadDocumentCollectionAsync(collectionSelfLink, new RequestOptions { SessionToken = replaceCollResponse.SessionToken });

                        Assert.Fail("Expected exception when reading deleted collection from write region");
                    }
                    catch (DocumentClientException clientException)
                    {
                        TestCommon.AssertException(clientException, HttpStatusCode.NotFound);
                    }

                    //TODO: Aditya, Investigate
                    // Try reading collection from read region
                    //try
                    //{
                    //    await readRegionClient.ReadDocumentCollectionAsync(collectionSelfLink, new RequestOptions { SessionToken = replaceCollResponse.SessionToken });
                    //    Assert.Fail("Expected exception when reading deleted collection from read region");
                    //}
                    //catch (DocumentClientException clientException)
                    //{
                    //    TestCommon.AssertException(clientException, HttpStatusCode.NotFound);
                    //}

                    // Now try reading the document from both the regions
                    try
                    {
                        await writeRegionClient.ReadDocumentAsync(documentSelfLink, new RequestOptions { PartitionKey = new PartitionKey(document.Id), SessionToken = docResponse.SessionToken });

                        Assert.Fail("Expected exception when reading document of a deleted collection from write region");
                    }
                    catch (DocumentClientException clientException)
                    {
                        TestCommon.AssertException(clientException, HttpStatusCode.NotFound);
                    }

                    //TODO: Aditya, Investigate
                    //try
                    //{
                    //    await readRegionClient.ReadDocumentAsync(documentSelfLink, new RequestOptions { PartitionKey = new PartitionKey(document.Id), SessionToken = docResponse.SessionToken });
                    //    Assert.Fail("Expected exception when reading document of a deleted collection from read region");
                    //}
                    //catch (DocumentClientException clientException)
                    //{
                    //    TestCommon.AssertException(clientException, HttpStatusCode.NotFound);
                    //}

                    // Delete the database
                    await writeRegionClient.DeleteDatabaseAsync(databaseSelfLink);

                    // Add some delay since we do async replication between geo-regions
                    await Task.Delay(GlobalDatabaseAccountTests.WaitDurationForAsyncReplication);

                    // Try reading from read region
                    try
                    {
                        await readRegionClient.ReadDatabaseAsync(databaseSelfLink);

                        Assert.Fail("Expected exception when reading deleted database from read region");
                    }
                    catch (DocumentClientException clientException)
                    {
                        TestCommon.AssertException(clientException, HttpStatusCode.NotFound);
                    }
                }
            }
        }
        public void ValidateTransformQuery()
        {
            DocumentClient client = TestCommon.CreateClient(true);

            IQueryable <dynamic> dbQuery = client.CreateDatabaseQuery(@"select * from root r where r.id=""db123""").AsQueryable();

            foreach (CosmosDatabaseSettings db in dbQuery)
            {
                TestCommon.Delete <CosmosDatabaseSettings>(client, db.ResourceId);
            }

            CosmosDatabaseSettings database = client.Create <CosmosDatabaseSettings>(null,
                                                                                     new CosmosDatabaseSettings {
                Id = "db123"
            });

            dbQuery = client.CreateDatabaseQuery(@"select * from root r where r.id=""db123""").AsQueryable();
            foreach (CosmosDatabaseSettings db in dbQuery)
            {
                Assert.AreEqual(db.Id, "db123");
            }
            Assert.AreNotEqual(0, System.Linq.Dynamic.Core.DynamicQueryableExtensions.AsEnumerable(dbQuery).Count());

            IQueryable <dynamic> dbIdQuery = client.CreateDatabaseQuery(@"select r._rid from root r where r.id=""db123""").AsQueryable();

            Assert.AreNotEqual(0, System.Linq.Dynamic.Core.DynamicQueryableExtensions.AsEnumerable(dbIdQuery).Count());

            CosmosContainerSettings collection = new CosmosContainerSettings
            {
                Id = Guid.NewGuid().ToString("N")
            };

            collection.IndexingPolicy.IndexingMode = IndexingMode.Consistent;

            collection = client.Create <CosmosContainerSettings>(database.ResourceId, collection);
            int documentsToCreate = 100;

            for (int i = 0; i < documentsToCreate; i++)
            {
                dynamic myDocument = new Document();
                myDocument.Id        = "doc" + i;
                myDocument.Title     = "MyBook"; //Simple Property.
                myDocument.Languages = new Language[] { new Language {
                                                            Name = "English", Copyright = "London Publication"
                                                        }, new Language {
                                                            Name = "French", Copyright = "Paris Publication"
                                                        } };                                                                                                                                      //Array Property
                myDocument.Author = new Author {
                    Name = "Don", Location = "France"
                };                                                                    //Complex Property
                myDocument.Price = 9.99;
                myDocument       = client.CreateDocumentAsync(collection.DocumentsLink, myDocument).Result;
            }

            //Read response as dynamic.
            IQueryable <dynamic> docQuery = client.CreateDocumentQuery(collection.DocumentsLink, @"select * from root r where r.Title=""MyBook""", null);

            IDocumentQuery <dynamic> DocumentQuery = docQuery.AsDocumentQuery();
            FeedResponse <dynamic>   queryResponse = DocumentQuery.ExecuteNextAsync().Result;

            Assert.IsNotNull(queryResponse.ResponseHeaders, "ResponseHeaders is null");
            Assert.IsNotNull(queryResponse.ActivityId, "ActivityId is null");
            Assert.AreEqual(documentsToCreate, queryResponse.Count);

            foreach (dynamic myBook in queryResponse)
            {
                Assert.AreEqual(myBook.Title, "MyBook");
            }

            client.DeleteDocumentCollectionAsync(collection.SelfLink).Wait();
        }
Beispiel #24
0
        public void ValidatePageSizeGatway()
        {
            var client = TestCommon.CreateClient(true);

            ValidatePageSize(client);
        }
        public void ValidateDynamicDocumentQuery() //Ensure query on custom property of document.
        {
            DocumentClient client = TestCommon.CreateClient(true);

            Book myDocument = new Book();

            myDocument.Id        = Guid.NewGuid().ToString();
            myDocument.Title     = "My Book"; //Simple Property.
            myDocument.Languages = new Language[] { new Language {
                                                        Name = "English", Copyright = "London Publication"
                                                    }, new Language {
                                                        Name = "French", Copyright = "Paris Publication"
                                                    } };                                                                                                                                      //Array Property
            myDocument.Author = new Author {
                Name = "Don", Location = "France"
            };                                                                    //Complex Property
            myDocument.Price    = 9.99;
            myDocument.Editions = new List <Edition>()
            {
                new Edition()
                {
                    Name = "First", Year = 2001
                }, new Edition()
                {
                    Name = "Second", Year = 2005
                }
            };

            //Create second document to make sure we have atleast one document which are filtered out of query.
            Book secondDocument = new Book
            {
                Id        = Guid.NewGuid().ToString(),
                Title     = "My Second Book",
                Languages = new Language[] { new Language {
                                                 Name = "Spanish", Copyright = "Mexico Publication"
                                             } },
                Author = new Author {
                    Name = "Carlos", Location = "Cancun"
                },
                Price    = 25,
                Editions = new List <Edition>()
                {
                    new Edition()
                    {
                        Name = "First", Year = 1970
                    }
                }
            };

            //Unfiltered execution.
            DocumentQuery <Book> bookDocQuery = new DocumentQuery <Book>(client, ResourceType.Document, typeof(Document), null, null);

            //Simple Equality on custom property.
            IQueryable <dynamic> docQuery = from book in bookDocQuery
                                            where book.Title == "My Book"
                                            select book;

            this.VerifyQueryTranslation(docQuery, "SELECT * FROM root WHERE (root[\"title\"] = \"My Book\") ");

            //Nested Property access
            docQuery = from book in bookDocQuery
                       where book.Author.Name == "Don"
                       select book;

            this.VerifyQueryTranslation(docQuery, "SELECT * FROM root WHERE (root[\"Author\"][\"id\"] = \"Don\") ");

            //Array references & Project Author out..
            docQuery = from book in bookDocQuery
                       where book.Languages[0].Name == "English"
                       select book.Author;

            this.VerifyQueryTranslation(docQuery, "SELECT VALUE root[\"Author\"] FROM root WHERE (root[\"Languages\"][0][\"Name\"] = \"English\") ");

            //SelectMany
            docQuery = bookDocQuery.SelectMany(
                book => book.Languages).Where(lang => lang.Name == "French").Select(lang => lang.Copyright);
            this.VerifyQueryTranslation(docQuery, "SELECT VALUE tmp[\"Copyright\"] FROM root JOIN tmp IN root[\"Languages\"] WHERE (tmp[\"Name\"] = \"French\") ");

            //NumericRange query
            docQuery = from book in bookDocQuery
                       where book.Price < 10
                       select book.Author;

            this.VerifyQueryTranslation(docQuery, "SELECT VALUE root[\"Author\"] FROM root WHERE (root[\"Price\"] < 10.0) ");

            //Or query
            docQuery = from book in bookDocQuery
                       where book.Title == "My Book" || book.Author.Name == "Don"
                       select book;

            this.VerifyQueryTranslation(docQuery, "SELECT * FROM root WHERE ((root[\"title\"] = \"My Book\") OR (root[\"Author\"][\"id\"] = \"Don\")) ");

            //SelectMany query on a List type.
            docQuery = bookDocQuery
                       .SelectMany(book => book.Editions)
                       .Select(ed => ed.Name);

            this.VerifyQueryTranslation(docQuery, "SELECT VALUE tmp[\"Name\"] FROM root JOIN tmp IN root[\"Editions\"] ");

            // Below samples are strictly speaking not Any equivalent. But they join and filter "all"
            // subchildren which match predicate. When SQL BE supports ANY, we can replace these with Any Flavor.
            docQuery = bookDocQuery
                       .SelectMany(book =>
                                   book.Languages
                                   .Where(lng => lng.Name == "English")
                                   .Select(lng => book.Author));
            this.VerifyQueryTranslation(docQuery, "SELECT VALUE root[\"Author\"] FROM root JOIN lng IN root[\"Languages\"] WHERE (lng[\"Name\"] = \"English\") ");

            //Any query on a List type.
            docQuery = bookDocQuery
                       .SelectMany(book =>
                                   book.Editions
                                   .Where(edition => edition.Year == 2001)
                                   .Select(lng => book.Author));
            this.VerifyQueryTranslation(docQuery, "SELECT VALUE root[\"Author\"] FROM root JOIN edition IN root[\"Editions\"] WHERE (edition[\"Year\"] = 2001) ");
        }
Beispiel #26
0
        public void ValidateIfNonMatchGateway()
        {
            var client = TestCommon.CreateClient(true);

            ValidateIfNonMatch(client);
        }
Beispiel #27
0
        public void ValidateConsistencyLevelGateway()
        {
            var client = TestCommon.CreateClient(true);

            ValidateCosistencyLevel(client);
        }
Beispiel #28
0
        public async Task ValidateCollectionIndexProgressHeadersRntbd()
        {
            var client = TestCommon.CreateClient(false, Protocol.Tcp);

            await ValidateCollectionIndexProgressHeaders(client);
        }
 public SpatialTest()
 {
     this.client = TestCommon.CreateClient(true, defaultConsistencyLevel: ConsistencyLevel.Session);
     this.CleanUp();
 }
        private async Task ValidateServerSideQueryEvalWithPaginationScenario()
        {
            DocumentClient client = TestCommon.CreateClient(false, defaultConsistencyLevel: ConsistencyLevel.Session);

            CosmosDatabaseSettings  database   = TestCommon.CreateOrGetDatabase(client);
            CosmosContainerSettings collection = new CosmosContainerSettings
            {
                Id = "ConsistentCollection"
            };

            collection.IndexingPolicy.IndexingMode = IndexingMode.Consistent;

            collection = client.Create <CosmosContainerSettings>(
                database.ResourceId,
                collection);

            //Do script post to insert as many document as we could in a tight loop.
            string script = @"function() {
                var output = 0;
                var client = getContext().getCollection();
                function callback(err, docCreated) {
                    if(err) throw 'Error while creating document';
                    output++;
                    getContext().getResponse().setBody(output);
                    if(output < 50) 
                        client.createDocument(client.getSelfLink(), { id: 'testDoc' + output, title : 'My Book'}, {}, callback);                       
                };
                client.createDocument(client.getSelfLink(), { id: 'testDoc' + output, title : 'My Book'}, {}, callback); }";


            StoredProcedureResponse <int> scriptResponse = null;
            int totalNumberOfDocuments = GatewayTests.CreateExecuteAndDeleteProcedure(client, collection, script, out scriptResponse);

            int pageSize = 5;
            int totalHit = 0;
            IDocumentQuery <Book> documentQuery =
                (from book in client.CreateDocumentQuery <Book>(
                     collection.SelfLink, new FeedOptions {
                MaxItemCount = pageSize
            })
                 where book.Title == "My Book"
                 select book).AsDocumentQuery();

            while (documentQuery.HasMoreResults)
            {
                FeedResponse <dynamic> pagedResult = await documentQuery.ExecuteNextAsync();

                string isUnfiltered = pagedResult.ResponseHeaders[HttpConstants.HttpHeaders.IsFeedUnfiltered];
                Assert.IsTrue(string.IsNullOrEmpty(isUnfiltered), "Query is evaulated in client");
                Assert.IsTrue(pagedResult.Count <= pageSize, "Page size is not honored in client site eval");

                if (totalHit != 0 && documentQuery.HasMoreResults)
                {
                    //Except first page and last page we should have seen client continuation token.
                    Assert.IsFalse(pagedResult.ResponseHeaders[HttpConstants.HttpHeaders.Continuation].Contains(HttpConstants.Delimiters.ClientContinuationDelimiter),
                                   "Client continuation is missing from the response continuation");
                }
                totalHit += pagedResult.Count;
            }
            Assert.AreEqual(totalHit, totalNumberOfDocuments, "Didnt get all the documents");

            //Do with default pagination.
            documentQuery =
                (from book in client.CreateDocumentQuery <Book>(
                     collection.SelfLink)
                 where book.Title == "My Book"
                 select book).AsDocumentQuery();

            totalHit = 0;

            while (documentQuery.HasMoreResults)
            {
                FeedResponse <dynamic> pagedResult = await documentQuery.ExecuteNextAsync();

                string isUnfiltered = pagedResult.ResponseHeaders[HttpConstants.HttpHeaders.IsFeedUnfiltered];
                Assert.IsTrue(string.IsNullOrEmpty(isUnfiltered), "Query is evaulated in client");
                Assert.IsTrue(pagedResult.Count == totalNumberOfDocuments, "Page size is not honored in client site eval");
                totalHit += pagedResult.Count;
            }
            Assert.AreEqual(totalHit, totalNumberOfDocuments, "Didnt get all the documents");
        }