Ejemplo n.º 1
0
        public async Task StreamCrudTestAsync()
        {
            Cosmos.Database database = await this.CreateDatabaseStreamHelper();

            using (ResponseMessage response = await database.ReadStreamAsync())
            {
                Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
                Assert.IsNotNull(response.Headers);
                Assert.IsTrue(response.Headers.RequestCharge > 0);
            }

            using (ResponseMessage response = await database.DeleteStreamAsync())
            {
                Assert.AreEqual(HttpStatusCode.NoContent, response.StatusCode);
                Assert.IsNotNull(response.Headers);
                Assert.IsTrue(response.Headers.RequestCharge > 0);
            }
        }
Ejemplo n.º 2
0
        public void VerifySynchronizationContextDoesNotLock()
        {
            string databaseId = Guid.NewGuid().ToString();
            SynchronizationContext prevContext = SynchronizationContext.Current;

            try
            {
                TestSynchronizationContext syncContext = new TestSynchronizationContext();
                SynchronizationContext.SetSynchronizationContext(syncContext);
                syncContext.Post(_ =>
                {
                    using (CosmosClient client = TestCommon.CreateCosmosClient())
                    {
                        Cosmos.Database database = client.CreateDatabaseAsync(databaseId).GetAwaiter().GetResult();
                        database = client.CreateDatabaseIfNotExistsAsync(databaseId).GetAwaiter().GetResult();

                        database.ReadStreamAsync().ConfigureAwait(false).GetAwaiter().GetResult();
                        database.ReadAsync().ConfigureAwait(false).GetAwaiter().GetResult();

                        QueryDefinition databaseQuery = new QueryDefinition("select * from T where T.id = @id").WithParameter("@id", databaseId);
                        FeedIterator <DatabaseProperties> databaseIterator = client.GetDatabaseQueryIterator <DatabaseProperties>(databaseQuery);
                        while (databaseIterator.HasMoreResults)
                        {
                            databaseIterator.ReadNextAsync().GetAwaiter().GetResult();
                        }

                        Container container = database.CreateContainerAsync(Guid.NewGuid().ToString(), "/pk").GetAwaiter().GetResult();
                        container           = database.CreateContainerIfNotExistsAsync(container.Id, "/pk").GetAwaiter().GetResult();

                        ToDoActivity testItem = ToDoActivity.CreateRandomToDoActivity();
                        ItemResponse <ToDoActivity> response = container.CreateItemAsync <ToDoActivity>(item: testItem).ConfigureAwait(false).GetAwaiter().GetResult();
                        Assert.IsNotNull(response);
                        string diagnostics = response.Diagnostics.ToString();
                        Assert.IsTrue(diagnostics.Contains("SynchronizationContext"));

                        using CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();

                        try
                        {
                            ToDoActivity tempItem = ToDoActivity.CreateRandomToDoActivity();
                            CancellationToken cancellationToken = cancellationTokenSource.Token;
                            cancellationTokenSource.Cancel();
                            container.CreateItemAsync <ToDoActivity>(item: tempItem, cancellationToken: cancellationToken).ConfigureAwait(false).GetAwaiter().GetResult();
                            Assert.Fail("Should have thrown a cancellation token");
                        }catch (CosmosOperationCanceledException oe)
                        {
                            string exception = oe.ToString();
                            Assert.IsTrue(exception.Contains("SynchronizationContext"));
                        }

                        // Test read feed
                        container.GetItemLinqQueryable <ToDoActivity>(
                            allowSynchronousQueryExecution: true,
                            requestOptions: new QueryRequestOptions()
                        {
                        }).ToList();

                        FeedIterator feedIterator = container.GetItemLinqQueryable <ToDoActivity>()
                                                    .ToStreamIterator();

                        while (feedIterator.HasMoreResults)
                        {
                            feedIterator.ReadNextAsync().GetAwaiter().GetResult();
                        }

                        FeedIterator <ToDoActivity> feedIteratorTyped = container.GetItemLinqQueryable <ToDoActivity>()
                                                                        .ToFeedIterator <ToDoActivity>();

                        while (feedIteratorTyped.HasMoreResults)
                        {
                            feedIteratorTyped.ReadNextAsync().GetAwaiter().GetResult();
                        }

                        // Test query
                        container.GetItemLinqQueryable <ToDoActivity>(
                            allowSynchronousQueryExecution: true,
                            requestOptions: new QueryRequestOptions()
                        {
                        }).Where(item => item.id != "").ToList();

                        FeedIterator queryIterator = container.GetItemLinqQueryable <ToDoActivity>()
                                                     .Where(item => item.id != "").ToStreamIterator();

                        while (queryIterator.HasMoreResults)
                        {
                            queryIterator.ReadNextAsync().GetAwaiter().GetResult();
                        }

                        FeedIterator <ToDoActivity> queryIteratorTyped = container.GetItemLinqQueryable <ToDoActivity>()
                                                                         .Where(item => item.id != "").ToFeedIterator <ToDoActivity>();

                        while (queryIteratorTyped.HasMoreResults)
                        {
                            queryIteratorTyped.ReadNextAsync().GetAwaiter().GetResult();
                        }

                        double costAsync = container.GetItemLinqQueryable <ToDoActivity>()
                                           .Select(x => x.cost).SumAsync().GetAwaiter().GetResult();

                        double cost = container.GetItemLinqQueryable <ToDoActivity>(
                            allowSynchronousQueryExecution: true).Select(x => x.cost).Sum();

                        ItemResponse <ToDoActivity> deleteResponse = container.DeleteItemAsync <ToDoActivity>(partitionKey: new Cosmos.PartitionKey(testItem.pk), id: testItem.id).ConfigureAwait(false).GetAwaiter().GetResult();
                        Assert.IsNotNull(deleteResponse);
                    }
                }, state: null);
            }
            finally
            {
                SynchronizationContext.SetSynchronizationContext(prevContext);
                using (CosmosClient client = TestCommon.CreateCosmosClient())
                {
                    client.GetDatabase(databaseId).DeleteAsync().GetAwaiter().GetResult();
                }
            }
        }
Ejemplo n.º 3
0
        public async Task ValidateAzureKeyCredentialDirectModeUpdateAsync()
        {
            string authKey  = ConfigurationManager.AppSettings["MasterKey"];
            string endpoint = ConfigurationManager.AppSettings["GatewayEndpoint"];

            AzureKeyCredential masterKeyCredential = new AzureKeyCredential(authKey);

            using (CosmosClient client = new CosmosClient(
                       endpoint,
                       masterKeyCredential))
            {
                string databaseName = Guid.NewGuid().ToString();

                try
                {
                    Cosmos.Database database        = client.GetDatabase(databaseName);
                    ResponseMessage responseMessage = await database.ReadStreamAsync();

                    Assert.AreEqual(HttpStatusCode.NotFound, responseMessage.StatusCode);

                    {
                        // Random key: Next set of actions are expected to fail => 401 (UnAuthorized)
                        masterKeyCredential.Update(Convert.ToBase64String(Encoding.UTF8.GetBytes(Guid.NewGuid().ToString())));

                        responseMessage = await database.ReadStreamAsync();

                        Assert.AreEqual(HttpStatusCode.Unauthorized, responseMessage.StatusCode);

                        string diagnostics = responseMessage.Diagnostics.ToString();
                        Assert.IsTrue(diagnostics.Contains("AuthProvider LifeSpan InSec"), diagnostics.ToString());
                    }

                    {
                        // Resetting back to master key => 404 (NotFound)
                        masterKeyCredential.Update(authKey);
                        responseMessage = await database.ReadStreamAsync();

                        Assert.AreEqual(HttpStatusCode.NotFound, responseMessage.StatusCode);
                    }


                    // Test with resource token interchageability
                    masterKeyCredential.Update(authKey);
                    database = await client.CreateDatabaseAsync(databaseName);

                    string            containerId       = Guid.NewGuid().ToString();
                    ContainerResponse containerResponse = await database.CreateContainerAsync(containerId, "/id");

                    Assert.AreEqual(HttpStatusCode.Created, containerResponse.StatusCode);


                    {
                        // Resource token with ALL permissoin's
                        string       userId       = Guid.NewGuid().ToString();
                        UserResponse userResponse = await database.CreateUserAsync(userId);

                        Cosmos.User user = userResponse.User;
                        Assert.AreEqual(HttpStatusCode.Created, userResponse.StatusCode);
                        Assert.AreEqual(userId, user.Id);

                        string permissionId = Guid.NewGuid().ToString();
                        PermissionProperties permissionProperties = new PermissionProperties(permissionId, Cosmos.PermissionMode.All, client.GetContainer(databaseName, containerId));
                        PermissionResponse   permissionResponse   = await database.GetUser(userId).CreatePermissionAsync(permissionProperties);

                        Assert.AreEqual(HttpStatusCode.Created, permissionResponse.StatusCode);
                        Assert.AreEqual(permissionId, permissionResponse.Resource.Id);
                        Assert.AreEqual(Cosmos.PermissionMode.All, permissionResponse.Resource.PermissionMode);
                        Assert.IsNotNull(permissionResponse.Resource.Token);
                        SelflinkValidator.ValidatePermissionSelfLink(permissionResponse.Resource.SelfLink);

                        // Valdiate ALL on contianer
                        masterKeyCredential.Update(permissionResponse.Resource.Token);
                        ToDoActivity item = ToDoActivity.CreateRandomToDoActivity();

                        Cosmos.Container container = client.GetContainer(databaseName, containerId);

                        responseMessage = await container.ReadContainerStreamAsync();

                        Assert.AreEqual(HttpStatusCode.OK, responseMessage.StatusCode);

                        responseMessage = await container.CreateItemStreamAsync(TestCommon.SerializerCore.ToStream(item), new Cosmos.PartitionKey(item.id));

                        Assert.AreEqual(HttpStatusCode.Created, responseMessage.StatusCode); // Read Only resorce token
                    }

                    // Reset to master key for new permission creation
                    masterKeyCredential.Update(authKey);

                    {
                        // Resource token with Read-ONLY permissoin's
                        string       userId       = Guid.NewGuid().ToString();
                        UserResponse userResponse = await database.CreateUserAsync(userId);

                        Cosmos.User user = userResponse.User;
                        Assert.AreEqual(HttpStatusCode.Created, userResponse.StatusCode);
                        Assert.AreEqual(userId, user.Id);

                        string permissionId = Guid.NewGuid().ToString();
                        PermissionProperties permissionProperties = new PermissionProperties(permissionId, Cosmos.PermissionMode.Read, client.GetContainer(databaseName, containerId));
                        PermissionResponse   permissionResponse   = await database.GetUser(userId).CreatePermissionAsync(permissionProperties);

                        //Backend returns Created instead of OK
                        Assert.AreEqual(HttpStatusCode.Created, permissionResponse.StatusCode);
                        Assert.AreEqual(permissionId, permissionResponse.Resource.Id);
                        Assert.AreEqual(Cosmos.PermissionMode.Read, permissionResponse.Resource.PermissionMode);

                        // Valdiate read on contianer
                        masterKeyCredential.Update(permissionResponse.Resource.Token);
                        ToDoActivity item = ToDoActivity.CreateRandomToDoActivity();

                        Cosmos.Container container = client.GetContainer(databaseName, containerId);

                        responseMessage = await container.ReadContainerStreamAsync();

                        Assert.AreEqual(HttpStatusCode.OK, responseMessage.StatusCode);

                        responseMessage = await container.CreateItemStreamAsync(TestCommon.SerializerCore.ToStream(item), new Cosmos.PartitionKey(item.id));

                        Assert.AreEqual(HttpStatusCode.Forbidden, responseMessage.StatusCode); // Read Only resorce token
                    }

                    {
                        // Reset to master key for new permission creation
                        masterKeyCredential.Update(Convert.ToBase64String(Encoding.UTF8.GetBytes(Guid.NewGuid().ToString())));

                        ToDoActivity     item      = ToDoActivity.CreateRandomToDoActivity();
                        Cosmos.Container container = client.GetContainer(databaseName, containerId);

                        responseMessage = await container.CreateItemStreamAsync(TestCommon.SerializerCore.ToStream(item), new Cosmos.PartitionKey(item.id));

                        Assert.AreEqual(HttpStatusCode.Unauthorized, responseMessage.StatusCode); // Read Only resorce token

                        string diagnostics = responseMessage.Diagnostics.ToString();
                        Assert.IsTrue(diagnostics.Contains("AuthProvider LifeSpan InSec"), diagnostics.ToString());
                    }
                }
                finally
                {
                    // Reset to master key for clean-up
                    masterKeyCredential.Update(authKey);
                    await TestCommon.DeleteDatabaseAsync(client, client.GetDatabase(databaseName));
                }
            }
        }