diff --git a/Microsoft.Azure.Cosmos/tests/Microsoft.Azure.Cosmos.EmulatorTests/GatewayTests.cs b/Microsoft.Azure.Cosmos/tests/Microsoft.Azure.Cosmos.EmulatorTests/GatewayTests.cs index 50e7f78484..c7c55163b9 100644 --- a/Microsoft.Azure.Cosmos/tests/Microsoft.Azure.Cosmos.EmulatorTests/GatewayTests.cs +++ b/Microsoft.Azure.Cosmos/tests/Microsoft.Azure.Cosmos.EmulatorTests/GatewayTests.cs @@ -48,7 +48,7 @@ public GatewayTests() this.masterKey = Utils.ConfigurationManager.AppSettings["MasterKey"]; } - private static Document CreateDocument(DocumentClient client, Uri baseUri, DocumentCollection collection, string documentName, string property1, int property2, string pretrigger = null, string posttrigger = null) + private static async Task CreateDocument(DocumentClient client, Uri baseUri, DocumentCollection collection, string documentName, string property1, int property2, string pretrigger = null, string posttrigger = null) { dynamic document = new Document { @@ -69,25 +69,18 @@ private static Document CreateDocument(DocumentClient client, Uri baseUri, Docum options.PostTriggerInclude = new[] { posttrigger }; } - try - { - return client.CreateDocumentAsync(collection, (Document)document, options).Result; - } - catch (AggregateException ex) - { - throw ex.InnerException; - } + return await client.CreateDocumentAsync(collection, (Document)document, options); } - internal static TValue CreateExecuteAndDeleteProcedure(DocumentClient client, DocumentCollection collection, string transientProcedure, string partitionKey = null) + internal static async Task CreateExecuteAndDeleteProcedureAsync(DocumentClient client, DocumentCollection collection, string transientProcedure, string partitionKey = null) { - return GatewayTests.CreateExecuteAndDeleteProcedure(client, collection, transientProcedure, out StoredProcedureResponse ignored, partitionKey); + (TValue result, _) = await GatewayTests.CreateExecuteAndDeleteProcedureCoreAsync(client, collection, transientProcedure, partitionKey); + return result; } - internal static TValue CreateExecuteAndDeleteProcedure(DocumentClient client, + internal static async Task<(TValue result, StoredProcedureResponse response)> CreateExecuteAndDeleteProcedureCoreAsync(DocumentClient client, DocumentCollection collection, string transientProcedure, - out StoredProcedureResponse response, string partitionKey = null) { // create @@ -96,31 +89,31 @@ internal static TValue CreateExecuteAndDeleteProcedure(DocumentClient cl Id = "storedProcedure" + Guid.NewGuid().ToString(), Body = transientProcedure }; - StoredProcedure retrievedStoredProcedure = client.CreateStoredProcedureAsync(collection, storedProcedure).Result; + StoredProcedure retrievedStoredProcedure = await client.CreateStoredProcedureAsync(collection, storedProcedure); // execute + StoredProcedureResponse response; if (partitionKey != null) { RequestOptions requestOptions = new RequestOptions { PartitionKey = new Documents.PartitionKey(partitionKey) }; - response = client.ExecuteStoredProcedureAsync(retrievedStoredProcedure, requestOptions).Result; + response = await client.ExecuteStoredProcedureAsync(retrievedStoredProcedure, requestOptions); } else { - response = client.ExecuteStoredProcedureAsync(retrievedStoredProcedure).Result; + response = await client.ExecuteStoredProcedureAsync(retrievedStoredProcedure); } // delete client.Delete(retrievedStoredProcedure.GetIdOrFullName()); - return response.Response; + return (response.Response, response); } - internal static TValue CreateExecuteAndDeleteCosmosProcedure(Container collection, + internal static async Task CreateExecuteAndDeleteCosmosProcedureAsync(Container collection, string transientProcedure, - out StoredProcedureExecuteResponse response, string partitionKey = null) { // create @@ -129,26 +122,26 @@ internal static TValue CreateExecuteAndDeleteCosmosProcedure(Container c Id = "storedProcedure" + Guid.NewGuid().ToString(), Body = transientProcedure }; - StoredProcedureResponse retrievedStoredProcedure = collection.Scripts.CreateStoredProcedureAsync(storedProcedure).Result; + StoredProcedureResponse retrievedStoredProcedure = await collection.Scripts.CreateStoredProcedureAsync(storedProcedure); Assert.IsNotNull(retrievedStoredProcedure); Assert.AreEqual(storedProcedure.Id, retrievedStoredProcedure.Resource.Id); - response = collection.Scripts.ExecuteStoredProcedureAsync( - storedProcedure.Id, + StoredProcedureExecuteResponse response = await collection.Scripts.ExecuteStoredProcedureAsync( + storedProcedure.Id, new Cosmos.PartitionKey(partitionKey), - null).Result; + null); Assert.IsNotNull(response); // delete - StoredProcedureResponse deleteResponse = collection.Scripts.DeleteStoredProcedureAsync(storedProcedure.Id).Result; + StoredProcedureResponse deleteResponse = await collection.Scripts.DeleteStoredProcedureAsync(storedProcedure.Id); Assert.IsNotNull(deleteResponse); - return response; + return response.Resource; } - internal static TValue GetStoredProcedureExecutionResult(DocumentClient client, StoredProcedure storedProcedure, params dynamic[] paramsList) + internal static async Task GetStoredProcedureExecutionResultAsync(DocumentClient client, StoredProcedure storedProcedure, params dynamic[] paramsList) { - return client.ExecuteStoredProcedureAsync(storedProcedure, paramsList).Result; + return await client.ExecuteStoredProcedureAsync(storedProcedure, paramsList); } private static IEnumerable GetDynamicMembers(object d) @@ -247,7 +240,7 @@ internal async Task> CreateCollectionsAsync(DocumentCl return documentCollections; } - private void Retry(Action action) + private async Task RetryAsync(Func asyncAction) { Queue timeouts = new Queue(new[] { 500, 1000, 1000, 1000, 1000, 1000, 5000, 10000 }); @@ -255,8 +248,7 @@ private void Retry(Action action) { try { - action(); - return; + await asyncAction(); } catch (Exception) { @@ -266,7 +258,7 @@ private void Retry(Action action) } int retryMilliseconds = timeouts.Dequeue(); Logger.LogLine("Retry {0} milliseconds", retryMilliseconds); - Task.Delay(retryMilliseconds); + await Task.Delay(retryMilliseconds); } } } @@ -305,7 +297,7 @@ internal async Task ValidateStoredProcedureCrudAsync(ConsistencyLevel consistenc }; Logger.LogLine("Adding StoredProcedure"); - StoredProcedure retrievedStoredProcedure = client.CreateStoredProcedureAsync(collection1, storedProcedure).Result; + StoredProcedure retrievedStoredProcedure = await client.CreateStoredProcedureAsync(collection1, storedProcedure); Assert.IsNotNull(retrievedStoredProcedure); Assert.IsTrue(retrievedStoredProcedure.Id.Equals(storedProcedureName, StringComparison.OrdinalIgnoreCase), "Mismatch in storedProcedure name"); Assert.IsTrue(retrievedStoredProcedure.Body.Equals("function() {var x = 10;}", StringComparison.OrdinalIgnoreCase), "Mismatch in storedProcedure content"); @@ -319,18 +311,18 @@ internal async Task ValidateStoredProcedureCrudAsync(ConsistencyLevel consistenc int count = 0; while (feedReader.HasMoreResults) { - count += feedReader.ExecuteNextAsync().Result.Count; + count += (await feedReader.ExecuteNextAsync()).Count; } Assert.AreEqual(storedProcedureCollection1.Count + 1, count, "StoredProcedure Collections count dont match for feedReader"); Logger.LogLine("Querying StoredProcedure"); - this.Retry(() => + await this.RetryAsync(async () => { IDocumentQuery queryService = client.CreateStoredProcedureQuery(collection1.StoredProceduresLink, @"select * from root r where r.id=""" + storedProcedureName + @"""").AsDocumentQuery(); - DocumentFeedResponse storedProcedureCollection3 = queryService.ExecuteNextAsync().Result; + DocumentFeedResponse storedProcedureCollection3 = await queryService.ExecuteNextAsync(); Assert.IsNotNull(storedProcedureCollection3, "Query result is null"); Assert.AreNotEqual(0, storedProcedureCollection3.Count, "Collection count dont match"); @@ -349,12 +341,12 @@ internal async Task ValidateStoredProcedureCrudAsync(ConsistencyLevel consistenc Assert.IsTrue(retrievedStoredProcedure2.Body.Equals("function() {var x = 20;}", StringComparison.OrdinalIgnoreCase), "Mismatch in storedProcedure content"); Logger.LogLine("Querying StoredProcedure"); - this.Retry(() => + await this.RetryAsync(async () => { IDocumentQuery queryService = client.CreateStoredProcedureQuery(collection1.StoredProceduresLink, @"select * from root r where r.id=""" + storedProcedureName + @"""").AsDocumentQuery(); - DocumentFeedResponse storedProcedureCollection4 = queryService.ExecuteNextAsync().Result; + DocumentFeedResponse storedProcedureCollection4 = await queryService.ExecuteNextAsync(); Assert.AreEqual(1, storedProcedureCollection4.Count); // name is always indexed }); @@ -412,20 +404,20 @@ internal async Task ValidateStoredProcedureCrudAsync(ConsistencyLevel consistenc } [TestMethod] - public void ValidateTriggerCrud_SessionGW() + public async Task ValidateTriggerCrud_SessionGW() { - this.ValidateTriggerCrud(ConsistencyLevel.Session, + await this.ValidateTriggerCrud(ConsistencyLevel.Session, new ConnectionPolicy { ConnectionMode = ConnectionMode.Gateway }); } [TestMethod] - public void ValidateTriggerCrud_SessionDirectTcp() + public async Task ValidateTriggerCrud_SessionDirectTcp() { - this.ValidateTriggerCrud(ConsistencyLevel.Session, + await this.ValidateTriggerCrud(ConsistencyLevel.Session, new ConnectionPolicy { ConnectionMode = ConnectionMode.Direct, ConnectionProtocol = Protocol.Tcp }); } - internal void ValidateTriggerCrud(ConsistencyLevel consistencyLevel, ConnectionPolicy connectionPolicy) + internal async Task ValidateTriggerCrud(ConsistencyLevel consistencyLevel, ConnectionPolicy connectionPolicy) { DocumentClient client = TestCommon.CreateClient(connectionPolicy.ConnectionMode == ConnectionMode.Gateway, connectionPolicy.ConnectionProtocol, @@ -447,7 +439,7 @@ internal void ValidateTriggerCrud(ConsistencyLevel consistencyLevel, ConnectionP }; Logger.LogLine("Adding Trigger"); - Trigger retrievedTrigger = client.CreateTriggerAsync(collection1, trigger).Result; + Trigger retrievedTrigger = await client.CreateTriggerAsync(collection1, trigger); Assert.IsNotNull(retrievedTrigger); Assert.IsTrue(retrievedTrigger.Id.Equals(triggerName, StringComparison.OrdinalIgnoreCase), "Mismatch in trigger name"); Assert.IsTrue(retrievedTrigger.Body.Equals("function() {var x = 10;}", StringComparison.OrdinalIgnoreCase), "Mismatch in trigger content"); @@ -463,19 +455,19 @@ internal void ValidateTriggerCrud(ConsistencyLevel consistencyLevel, ConnectionP int count = 0; while (feedReader.HasMoreResults) { - count += feedReader.ExecuteNextAsync().Result.Count; + count += (await feedReader.ExecuteNextAsync()).Count; } Assert.AreEqual(triggerCollection1.Count + 1, count, "Trigger Collections count dont match for feedReader"); Logger.LogLine("Querying Trigger"); - this.Retry(() => + await this.RetryAsync(async () => { IDocumentQuery queryService = client.CreateTriggerQuery(collection1.TriggersLink, @"select * from root r where r.id=""" + triggerName + @"""").AsDocumentQuery(); - DocumentFeedResponse triggerCollection3 = queryService.ExecuteNextAsync().Result; + DocumentFeedResponse triggerCollection3 = await queryService.ExecuteNextAsync(); Assert.IsNotNull(triggerCollection3, "Query result is null"); Assert.AreNotEqual(0, triggerCollection3.Count, "Collection count dont match"); @@ -504,12 +496,12 @@ internal void ValidateTriggerCrud(ConsistencyLevel consistencyLevel, ConnectionP } Logger.LogLine("Querying Trigger"); - this.Retry(() => + await this.RetryAsync(async () => { IDocumentQuery queryService = client.CreateTriggerQuery(collection1.TriggersLink, @"select * from root r where r.id=""" + triggerName + @"""").AsDocumentQuery(); - DocumentFeedResponse triggerCollection4 = queryService.ExecuteNextAsync().Result; + DocumentFeedResponse triggerCollection4 = await queryService.ExecuteNextAsync(); Assert.AreEqual(1, triggerCollection4.Count); // name is always indexed }); @@ -539,21 +531,21 @@ internal void ValidateTriggerCrud(ConsistencyLevel consistencyLevel, ConnectionP } [TestMethod] - public void ValidateUserDefinedFunctionCrud_SessionGW() + public async Task ValidateUserDefinedFunctionCrud_SessionGW() { - this.ValidateUserDefinedFunctionCrud(ConsistencyLevel.Session, + await this.ValidateUserDefinedFunctionCrud(ConsistencyLevel.Session, new ConnectionPolicy { ConnectionMode = ConnectionMode.Gateway }); } [TestMethod] - public void ValidateUserDefinedFunctionCrud_SessionDirectTcp() + public async Task ValidateUserDefinedFunctionCrud_SessionDirectTcp() { - this.ValidateUserDefinedFunctionCrud(ConsistencyLevel.Session, + await this.ValidateUserDefinedFunctionCrud(ConsistencyLevel.Session, new ConnectionPolicy { ConnectionMode = ConnectionMode.Direct, ConnectionProtocol = Protocol.Tcp }); } [TestMethod] - public void ValidateUserDefinedFunctionTimeout() + public async Task ValidateUserDefinedFunctionTimeout() { try { @@ -570,20 +562,19 @@ public void ValidateUserDefinedFunctionTimeout() Body = @"function infinite_loop() { while(1 == 1) { a = 5; b = 6; c = a + b; } }", }; - UserDefinedFunction retrievedUdfInfinite = client.CreateUserDefinedFunctionAsync(collection1.UserDefinedFunctionsLink, udfInfinite).Result; + UserDefinedFunction retrievedUdfInfinite = await client.CreateUserDefinedFunctionAsync(collection1.UserDefinedFunctionsLink, udfInfinite); IDocumentQuery docServiceQuery1 = client.CreateDocumentQuery(collection1.DocumentsLink, string.Format(CultureInfo.CurrentCulture, "select udf.{0}() as infinite", udfName)).AsDocumentQuery(); - DocumentFeedResponse docCollectionShouldTimeout = docServiceQuery1.ExecuteNextAsync().Result; + DocumentFeedResponse docCollectionShouldTimeout = await docServiceQuery1.ExecuteNextAsync(); Assert.Fail("Should have thrown exception in previous statement"); } - catch (AggregateException e) + catch (DocumentClientException e) { - DocumentClientException dce = e.InnerException as DocumentClientException; - Assert.IsTrue(HttpStatusCode.RequestTimeout == dce.StatusCode || HttpStatusCode.Forbidden == dce.StatusCode, "ValidateUserDefinedFunctionTimeout should fail with RequestTimeout"); + Assert.IsTrue(HttpStatusCode.RequestTimeout == e.StatusCode || HttpStatusCode.Forbidden == e.StatusCode, "ValidateUserDefinedFunctionTimeout should fail with RequestTimeout"); } } - internal void ValidateUserDefinedFunctionCrud(ConsistencyLevel consistencyLevel, ConnectionPolicy connectionPolicy) + internal async Task ValidateUserDefinedFunctionCrud(ConsistencyLevel consistencyLevel, ConnectionPolicy connectionPolicy) { DocumentClient client = TestCommon.CreateClient(connectionPolicy.ConnectionMode == ConnectionMode.Gateway, connectionPolicy.ConnectionProtocol, @@ -607,7 +598,7 @@ internal void ValidateUserDefinedFunctionCrud(ConsistencyLevel consistencyLevel, try { - retrievedUserDefinedFunction = client.CreateUserDefinedFunctionAsync(collection1, userDefinedFunction).Result; + retrievedUserDefinedFunction = await client.CreateUserDefinedFunctionAsync(collection1, userDefinedFunction); Assert.IsNotNull(retrievedUserDefinedFunction); Assert.IsTrue(retrievedUserDefinedFunction.Id.Equals(userDefinedFunctionName, StringComparison.OrdinalIgnoreCase), "Mismatch in userDefinedFunction name"); Assert.IsTrue(retrievedUserDefinedFunction.Body.Equals("function userDefinedFunction() {var x = 10;}", StringComparison.OrdinalIgnoreCase), "Mismatch in userDefinedFunction content"); @@ -626,18 +617,18 @@ internal void ValidateUserDefinedFunctionCrud(ConsistencyLevel consistencyLevel, int count = 0; while (feedReader.HasMoreResults) { - count += feedReader.ExecuteNextAsync().Result.Count; + count += (await feedReader.ExecuteNextAsync()).Count; } Assert.AreEqual(userDefinedFunctionCollection1.Count + 1, count, "UserDefinedFunctions Collections count dont match for feedReader"); Logger.LogLine("Querying UserDefinedFunction"); - this.Retry(() => + await this.RetryAsync(async () => { IDocumentQuery queryService = client.CreateUserDefinedFunctionQuery(collection1, @"select * from root r where r.id=""" + userDefinedFunctionName + @"""").AsDocumentQuery(); - DocumentFeedResponse userDefinedFunctionCollection3 = queryService.ExecuteNextAsync().Result; + DocumentFeedResponse userDefinedFunctionCollection3 = await queryService.ExecuteNextAsync(); Assert.IsNotNull(userDefinedFunctionCollection3, "Query result is null"); Assert.AreNotEqual(0, userDefinedFunctionCollection3.Count, "Collection count dont match"); @@ -656,12 +647,12 @@ internal void ValidateUserDefinedFunctionCrud(ConsistencyLevel consistencyLevel, Assert.IsTrue(retrievedUserDefinedFunction2.Body.Equals("function userDefinedFunction() {var x = 20;}", StringComparison.OrdinalIgnoreCase), "Mismatch in userDefinedFunction content"); Logger.LogLine("Querying UserDefinedFunction"); - this.Retry(() => + await this.RetryAsync(async () => { IDocumentQuery queryService = client.CreateUserDefinedFunctionQuery(collection1, @"select * from root r where r.id=""" + userDefinedFunctionName + @"""").AsDocumentQuery(); - DocumentFeedResponse userDefinedFunctionCollection4 = queryService.ExecuteNextAsync().Result; + DocumentFeedResponse userDefinedFunctionCollection4 = await queryService.ExecuteNextAsync(); Assert.AreEqual(1, userDefinedFunctionCollection4.Count); // name is always indexed }); @@ -691,14 +682,14 @@ internal void ValidateUserDefinedFunctionCrud(ConsistencyLevel consistencyLevel, } [TestMethod] - public void ValidateTriggersNameBased() + public async Task ValidateTriggersNameBased() { DocumentClient client = TestCommon.CreateClient(false); - TestCommon.DeleteAllDatabasesAsync().Wait(); + await TestCommon.DeleteAllDatabasesAsync(); Documents.Database database = TestCommon.CreateOrGetDatabase(client); PartitionKeyDefinition partitionKeyDefinition = new PartitionKeyDefinition { Paths = new System.Collections.ObjectModel.Collection(new[] { "/pk" }), Kind = PartitionKind.Hash }; - DocumentCollection collection1 = TestCommon.CreateCollectionAsync(client, database.SelfLink, new DocumentCollection { Id = "TestTriggers" + Guid.NewGuid().ToString(), PartitionKey = partitionKeyDefinition }).Result; + DocumentCollection collection1 = await TestCommon.CreateCollectionAsync(client, database.SelfLink, new DocumentCollection { Id = "TestTriggers" + Guid.NewGuid().ToString(), PartitionKey = partitionKeyDefinition }); // uppercase name Trigger t1 = new Trigger @@ -712,7 +703,7 @@ public void ValidateTriggersNameBased() TriggerType = Documents.TriggerType.Pre, TriggerOperation = Documents.TriggerOperation.All }; - Trigger retrievedTrigger = this.CreateTriggerAndValidateAsync(client, collection1, t1).Result; + Trigger retrievedTrigger = await this.CreateTriggerAndValidateAsync(client, collection1, t1); string docId = Guid.NewGuid().ToString(); dynamic document = new Document @@ -723,7 +714,7 @@ public void ValidateTriggersNameBased() document.CustomProperty1 = "a"; document.CustomProperty2 = "b"; - ResourceResponse docResponse = client.CreateDocumentAsync(collection1.AltLink, document, new Documents.Client.RequestOptions { PreTriggerInclude = new List { "t1" } }).Result; + ResourceResponse docResponse = await client.CreateDocumentAsync(collection1.AltLink, document, new Documents.Client.RequestOptions { PreTriggerInclude = new List { "t1" } }); Assert.IsTrue((docId + "t1").Equals(docResponse.Resource.Id, StringComparison.OrdinalIgnoreCase)); } @@ -754,7 +745,7 @@ internal async Task ValidateTriggersInternal(Protocol protocol = Protocol.Https, #if !DIRECT_MODE using DocumentClient client = TestCommon.CreateClient(true, defaultConsistencyLevel: consistencyLevel); #endif - TestCommon.DeleteAllDatabasesAsync().Wait(); + await TestCommon.DeleteAllDatabasesAsync(); Documents.Database database = TestCommon.CreateOrGetDatabase(client); PartitionKeyDefinition partitionKeyDefinition = new PartitionKeyDefinition { Paths = new System.Collections.ObjectModel.Collection(new[] { "/pk" }), Kind = PartitionKind.Hash }; DocumentCollection collection1 = await TestCommon.CreateCollectionAsync(client, database, new DocumentCollection { Id = "TestTriggers" + Guid.NewGuid().ToString(), PartitionKey = partitionKeyDefinition }); @@ -775,7 +766,7 @@ internal async Task ValidateTriggersInternal(Protocol protocol = Protocol.Https, }; Trigger retrievedTrigger = await this.CreateTriggerAndValidateAsync(client, collection1, t1); - dynamic doct1 = GatewayTests.CreateDocument(client, this.baseUri, collection1, "Doc1", "empty", 0, pretrigger: "t1"); + dynamic doct1 = await GatewayTests.CreateDocument(client, this.baseUri, collection1, "Doc1", "empty", 0, pretrigger: "t1"); Assert.AreEqual("DOC1t1", doct1.Id); // post trigger - get @@ -793,7 +784,7 @@ internal async Task ValidateTriggersInternal(Protocol protocol = Protocol.Https, }; retrievedTrigger = await this.CreateTriggerAndValidateAsync(client, collection1, response1); - dynamic docresponse1 = GatewayTests.CreateDocument(client, this.baseUri, collection1, "testing post trigger", "empty", 0, pretrigger: "t1", posttrigger: "response1"); + dynamic docresponse1 = await GatewayTests.CreateDocument(client, this.baseUri, collection1, "testing post trigger", "empty", 0, pretrigger: "t1", posttrigger: "response1"); Assert.AreEqual("TESTING POST TRIGGERt1", docresponse1.Id); // post trigger response @@ -811,7 +802,7 @@ internal async Task ValidateTriggersInternal(Protocol protocol = Protocol.Https, }; retrievedTrigger = await this.CreateTriggerAndValidateAsync(client, collection1, response2); - dynamic docresponse2 = GatewayTests.CreateDocument(client, this.baseUri, collection1, "post trigger output", "empty", 0, pretrigger: "t1", posttrigger: "response2"); + dynamic docresponse2 = await GatewayTests.CreateDocument(client, this.baseUri, collection1, "post trigger output", "empty", 0, pretrigger: "t1", posttrigger: "response2"); Assert.AreEqual("POST TRIGGER OUTPUTt1POST TRIGGER OUTPUTt1response2", docresponse2.Id); // post trigger cannot set anything in request, cannot set headers in response @@ -844,10 +835,10 @@ internal async Task ValidateTriggersInternal(Protocol protocol = Protocol.Https, }; retrievedTrigger = await this.CreateTriggerAndValidateAsync(client, collection1, response3); - dynamic docresponse3 = GatewayTests.CreateDocument(client, this.baseUri, collection1, "testing post trigger2", "empty", 0, pretrigger: "t1", posttrigger: "response3"); + dynamic docresponse3 = await GatewayTests.CreateDocument(client, this.baseUri, collection1, "testing post trigger2", "empty", 0, pretrigger: "t1", posttrigger: "response3"); Assert.AreEqual("TESTING POST TRIGGER2t1", docresponse3.Id); - DocumentCollection collection2 = TestCommon.CreateCollectionAsync(client, database, new DocumentCollection { Id = "TestTriggers" + Guid.NewGuid().ToString(), PartitionKey = partitionKeyDefinition }).Result; + DocumentCollection collection2 = await TestCommon.CreateCollectionAsync(client, database, new DocumentCollection { Id = "TestTriggers" + Guid.NewGuid().ToString(), PartitionKey = partitionKeyDefinition }); // empty trigger Trigger t2 = new Trigger @@ -859,7 +850,7 @@ internal async Task ValidateTriggersInternal(Protocol protocol = Protocol.Https, }; retrievedTrigger = await this.CreateTriggerAndValidateAsync(client, collection2, t2); - dynamic doct2 = GatewayTests.CreateDocument(client, this.baseUri, collection2, "Doc2", "Prop1Value", 101, pretrigger: "t2"); + dynamic doct2 = await GatewayTests.CreateDocument(client, this.baseUri, collection2, "Doc2", "Prop1Value", 101, pretrigger: "t2"); Assert.AreEqual("Doc2", doct2.Id); // lowercase name @@ -876,7 +867,7 @@ internal async Task ValidateTriggersInternal(Protocol protocol = Protocol.Https, }; retrievedTrigger = await this.CreateTriggerAndValidateAsync(client, collection2, t3); - dynamic doct3 = GatewayTests.CreateDocument(client, this.baseUri, collection2, "Doc3", "empty", 0, pretrigger: "t3"); + dynamic doct3 = await GatewayTests.CreateDocument(client, this.baseUri, collection2, "Doc3", "empty", 0, pretrigger: "t3"); Assert.AreEqual("doc3t3", doct3.Id); // trigger type mismatch - failure case @@ -892,7 +883,7 @@ internal async Task ValidateTriggersInternal(Protocol protocol = Protocol.Https, bool exceptionThrown = false; try { - dynamic doctriggertype = GatewayTests.CreateDocument(client, this.baseUri, collection2, "Docoptype", "empty", 0, pretrigger: "triggerTypeMismatch"); + dynamic doctriggertype = await GatewayTests.CreateDocument(client, this.baseUri, collection2, "Docoptype", "empty", 0, pretrigger: "triggerTypeMismatch"); } catch (DocumentClientException e) { @@ -913,7 +904,7 @@ internal async Task ValidateTriggersInternal(Protocol protocol = Protocol.Https, try { - GatewayTests.CreateDocument(client, this.baseUri, collection2, "Docoptype", "empty", 0, pretrigger: "preTriggerThatThrows"); + await GatewayTests.CreateDocument(client, this.baseUri, collection2, "Docoptype", "empty", 0, pretrigger: "preTriggerThatThrows"); Assert.Fail("Should throw and not get here."); } catch (DocumentClientException e) @@ -935,7 +926,7 @@ internal async Task ValidateTriggersInternal(Protocol protocol = Protocol.Https, try { - GatewayTests.CreateDocument(client, this.baseUri, collection2, "Docoptype", "empty", 0, posttrigger: "postTriggerThatThrows"); + await GatewayTests.CreateDocument(client, this.baseUri, collection2, "Docoptype", "empty", 0, posttrigger: "postTriggerThatThrows"); Assert.Fail("Should throw and not get here."); } catch (DocumentClientException e) @@ -1094,7 +1085,7 @@ internal async Task ValidateTriggersInternal(Protocol protocol = Protocol.Https, }; retrievedTrigger = await this.CreateTriggerAndValidateAsync(client, collection2, request1); - dynamic docrequest1 = GatewayTests.CreateDocument(client, this.baseUri, collection2, "abc", "empty", 0, pretrigger: "request1"); + dynamic docrequest1 = await GatewayTests.CreateDocument(client, this.baseUri, collection2, "abc", "empty", 0, pretrigger: "request1"); Assert.AreEqual("def", docrequest1.Id); DocumentCollection collection3 = await TestCommon.CreateCollectionAsync(client, database, new DocumentCollection { Id = "TestTriggers" + Guid.NewGuid().ToString(), PartitionKey = partitionKeyDefinition }); @@ -1116,7 +1107,7 @@ internal async Task ValidateTriggersInternal(Protocol protocol = Protocol.Https, }; retrievedTrigger = await this.CreateTriggerAndValidateAsync(client, collection3, request2); - dynamic docrequest2 = GatewayTests.CreateDocument(client, this.baseUri, collection3, "doc", "empty", 0, pretrigger: "request2"); + dynamic docrequest2 = await GatewayTests.CreateDocument(client, this.baseUri, collection3, "doc", "empty", 0, pretrigger: "request2"); Assert.AreEqual(203, docrequest2.Id.Length); // no response in pre-trigger @@ -1138,7 +1129,7 @@ internal async Task ValidateTriggersInternal(Protocol protocol = Protocol.Https, }; retrievedTrigger = await this.CreateTriggerAndValidateAsync(client, collection3, request3); - dynamic docrequest3 = GatewayTests.CreateDocument(client, this.baseUri, collection3, "noname", "empty", 0, pretrigger: "request3"); + dynamic docrequest3 = await GatewayTests.CreateDocument(client, this.baseUri, collection3, "noname", "empty", 0, pretrigger: "request3"); Assert.AreEqual("noresponse", docrequest3.Id); // not allowed to set headers in pre-trigger @@ -1201,7 +1192,7 @@ internal async Task ValidateTriggersInternal(Protocol protocol = Protocol.Https, exceptionThrown = false; try { - dynamic docoptype = GatewayTests.CreateDocument(client, this.baseUri, collection3, "Docoptype", "empty", 0, null, posttrigger: "triggerOpType"); + dynamic docoptype = await GatewayTests.CreateDocument(client, this.baseUri, collection3, "Docoptype", "empty", 0, null, posttrigger: "triggerOpType"); } catch (DocumentClientException e) { @@ -1223,7 +1214,7 @@ internal async Task ValidateTriggersInternal(Protocol protocol = Protocol.Https, exceptionThrown = false; try { - dynamic docabort = GatewayTests.CreateDocument(client, this.baseUri, collection3, "Docabort", "empty", 0, null, posttrigger: "triggerAbortTransaction"); + dynamic docabort = await GatewayTests.CreateDocument(client, this.baseUri, collection3, "Docabort", "empty", 0, null, posttrigger: "triggerAbortTransaction"); } catch { @@ -1279,7 +1270,7 @@ function callback(err, docFeed, responseOptions) dynamic docDeletePostTrigger = null; try { - docDeletePostTrigger = GatewayTests.CreateDocument(client, this.baseUri, collection4, "Doc4", "Prop1Value", 101, null, posttrigger: "deletePostTrigger"); + docDeletePostTrigger = await GatewayTests.CreateDocument(client, this.baseUri, collection4, "Doc4", "Prop1Value", 101, null, posttrigger: "deletePostTrigger"); } catch (Exception e) { @@ -1496,7 +1487,7 @@ internal async Task ValidateSystemSprocInternal(bool useGateway, Protocol protoc string result = string.Empty; try { - result = scripts.ExecuteStoredProcedureAsync("__.sys.echo", new Cosmos.PartitionKey("anyPk"), new dynamic[] { input }).Result; + result = await scripts.ExecuteStoredProcedureAsync("__.sys.echo", new Cosmos.PartitionKey("anyPk"), new dynamic[] { input }); } catch (DocumentClientException exception) { @@ -2270,26 +2261,24 @@ public async Task ValidateStoredProceduresBlacklistingInternal() Id = "storedProcedure" + Guid.NewGuid().ToString(), Body = badScript }; - StoredProcedure retrievedStoredProcedure = client.CreateStoredProcedureAsync(collection, storedProcedure).Result; + StoredProcedure retrievedStoredProcedure = await client.CreateStoredProcedureAsync(collection, storedProcedure); Documents.Client.RequestOptions requestOptions = new Documents.Client.RequestOptions { PartitionKey = new Documents.PartitionKey("test") }; for (int numExec = 0; numExec < 6; numExec++) { - client.ExecuteStoredProcedureAsync(retrievedStoredProcedure, requestOptions).Wait(); + await client.ExecuteStoredProcedureAsync(retrievedStoredProcedure, requestOptions); } bool isBlacklisted = false; try { // 3 strikes and then out - client.ExecuteStoredProcedureAsync(retrievedStoredProcedure, requestOptions).Wait(); + await client.ExecuteStoredProcedureAsync(retrievedStoredProcedure, requestOptions); } - catch (Exception e) + catch (DocumentClientException de) { - Assert.IsNotNull(e); - DocumentClientException de = e.InnerException as DocumentClientException; Assert.IsNotNull(de); Assert.AreEqual(HttpStatusCode.Forbidden.ToString(), de.Error.Code); Assert.IsTrue(de.Message.Contains("is blocked for execution because it has violated its allowed resource limit several times.")); @@ -2332,12 +2321,12 @@ public async Task ValidateUserDefinedFunctions() }; UserDefinedFunction retrievedUdf = await client.CreateUserDefinedFunctionAsync(collection.UserDefinedFunctionsLink, udf1); - this.Retry(() => + await this.RetryAsync(async () => { IDocumentQuery docServiceQuery = secondary1Client.CreateDocumentQuery(collection.DocumentsLink, @"select * from root r where udf.udf1(r.id, ""Romulan"") = true", new FeedOptions { EnableCrossPartitionQuery = true }).AsDocumentQuery(); - DocumentFeedResponse docCollection = docServiceQuery.ExecuteNextAsync().Result; + DocumentFeedResponse docCollection = await docServiceQuery.ExecuteNextAsync(); Logger.LogLine("Documents queried with token: {0}", docCollection.SessionToken); @@ -2373,7 +2362,7 @@ public async Task ValidateUserDefinedFunctions() Id = "udfThatThrows", Body = @"function() { throw new Error(32766, 'Error'); };", }; - retrievedUdf = client.CreateUserDefinedFunctionAsync(collection.UserDefinedFunctionsLink, udfThatThrows).Result; + retrievedUdf = await client.CreateUserDefinedFunctionAsync(collection.UserDefinedFunctionsLink, udfThatThrows); { IDocumentQuery docServiceQuery = secondary1Client.CreateDocumentQuery(collection.DocumentsLink, @@ -2381,13 +2370,13 @@ public async Task ValidateUserDefinedFunctions() try { - DocumentFeedResponse docCollection = docServiceQuery.ExecuteNextAsync().Result; + DocumentFeedResponse docCollection = await docServiceQuery.ExecuteNextAsync(); Assert.Fail("Should throw and not get here"); } - catch (AggregateException ex) + catch (DocumentClientException ex) { - Assert.AreEqual(HttpStatusCode.BadRequest, ((DocumentClientException)ex.InnerException).StatusCode); - Assert.AreEqual(32766, (int)((DocumentClientException)ex.InnerException).GetSubStatus()); + Assert.AreEqual(HttpStatusCode.BadRequest, ex.StatusCode); + Assert.AreEqual(32766, (int)ex.GetSubStatus()); Assert.IsFalse(string.IsNullOrEmpty(ex.Message)); } } @@ -3044,23 +3033,22 @@ public async Task ValidateStoredProcedureExecutionWithPartitionKey() new Documents.Client.RequestOptions { OfferThroughput = 12000 }); StoredProcedure sproc = - client.CreateStoredProcedureAsync(UriFactory.CreateDocumentCollectionUri(database.Id, collection.Id), + await client.CreateStoredProcedureAsync(UriFactory.CreateDocumentCollectionUri(database.Id, collection.Id), new StoredProcedure { Id = "HelloWorld", Body = @"function(name) { getContext().getResponse().setBody('Hello World, ' + name + '!'); }" - }) - .Result; + }); // Execute stored procedure by passing in stored procedure self-link - string output = client.ExecuteStoredProcedureAsync(sproc.SelfLink, - new Documents.Client.RequestOptions { PartitionKey = new Documents.PartitionKey("1") }, "DocumentDB").Result; + string output = await client.ExecuteStoredProcedureAsync(sproc.SelfLink, + new Documents.Client.RequestOptions { PartitionKey = new Documents.PartitionKey("1") }, "DocumentDB"); Assert.IsTrue(string.CompareOrdinal(output, "Hello World, DocumentDB!") == 0); // Execute stored procedure by passing in stored procedure URI - output = client.ExecuteStoredProcedureAsync( + output = await client.ExecuteStoredProcedureAsync( UriFactory.CreateStoredProcedureUri(database.Id, collection.Id, "HelloWorld"), - new Documents.Client.RequestOptions { PartitionKey = new Documents.PartitionKey("1") }, "DocumentDB").Result; + new Documents.Client.RequestOptions { PartitionKey = new Documents.PartitionKey("1") }, "DocumentDB"); Assert.IsTrue(string.CompareOrdinal(output, "Hello World, DocumentDB!") == 0); await client.DeleteStoredProcedureAsync(UriFactory.CreateStoredProcedureUri(database.Id, collection.Id, sproc.Id)); @@ -3194,7 +3182,7 @@ public async Task ValidatePOCODocumentSerialization() { Document cusomerBookDoc = Resource.LoadFrom(ms); - ResourceResponse returnedDoc = client.CreateDocumentAsync(collection1, cusomerBookDoc).Result; + ResourceResponse returnedDoc = await client.CreateDocumentAsync(collection1, cusomerBookDoc); CustomerPOCO poco2 = (CustomerPOCO)JsonConvert.DeserializeObject(returnedDoc.Resource.ToString(), typeof(CustomerPOCO), settings); @@ -3207,7 +3195,7 @@ public async Task ValidatePOCODocumentSerialization() // 2. poco using our own serialization. poco.id = Guid.NewGuid().ToString(); - ResourceResponse pocoReturned = client.CreateDocumentAsync(collection1, poco).Result; + ResourceResponse pocoReturned = await client.CreateDocumentAsync(collection1, poco); CustomerPOCO pocoBack = (CustomerPOCO)JsonConvert.DeserializeObject(pocoReturned.Resource.ToString(), typeof(CustomerPOCO), settings); Assert.AreEqual(poco.BookId, pocoBack.BookId, "BookId dont match"); Assert.AreEqual(poco.PUBLISHTIME, pocoBack.PUBLISHTIME, "PUBLISHTIME dont match"); @@ -3233,7 +3221,7 @@ public async Task ValidatePOCODocumentSerialization() inheritFromDocument.authors.Add("Mark Twain"); inheritFromDocument.authors.Add("Ernest Hemingway"); - ResourceResponse inheritFromDocumentReturned = client.CreateDocumentAsync(collection1, inheritFromDocument).Result; + ResourceResponse inheritFromDocumentReturned = await client.CreateDocumentAsync(collection1, inheritFromDocument); IEnumerable dynamicMembers2 = GetDynamicMembers(inheritFromDocumentReturned.Resource); // three dynamic member, Assert.AreEqual(5, dynamicMembers2.Count()); @@ -3249,12 +3237,12 @@ public async Task ValidatePOCODocumentSerialization() { PartitionKey = new Documents.PartitionKey("test") }; - CustomerObjectFromDocument inheritFromDocumentReturned3 = (dynamic)client.ReadDocumentAsync(inheritFromDocumentReturned, requestOptions).Result.Resource; + CustomerObjectFromDocument inheritFromDocumentReturned3 = (dynamic)(await client.ReadDocumentAsync(inheritFromDocumentReturned, requestOptions)).Resource; inheritFromDocumentReturned3.BookId = "isbn56789"; inheritFromDocumentReturned3.pk = "test"; string tostring = inheritFromDocumentReturned3.ToString(); - CustomerObjectFromDocument inheritFromDocumentReturned4 = (dynamic)client.ReplaceDocumentExAsync(inheritFromDocumentReturned3).Result.Resource; + CustomerObjectFromDocument inheritFromDocumentReturned4 = (dynamic)(await client.ReplaceDocumentExAsync(inheritFromDocumentReturned3)).Resource; Assert.AreEqual(inheritFromDocumentReturned4.BookId, inheritFromDocumentReturned3.BookId); Assert.IsFalse(tostring.Contains("PUBLISHTIME")); @@ -3285,7 +3273,7 @@ public async Task ValidatePOCODocumentSerialization() IDocumentQuery docServiceQuery1 = client.CreateDocumentQuery(collection1.DocumentsLink, string.Format(CultureInfo.CurrentCulture, @"select * from root r where r.id=""{0}""", inheritFromDocument.Id), options).AsDocumentQuery(); - DocumentFeedResponse queryFeed = docServiceQuery1.ExecuteNextAsync().Result; + DocumentFeedResponse queryFeed = await docServiceQuery1.ExecuteNextAsync(); dynamic queryResult = queryFeed.ElementAt(0); IEnumerable dynamicMembersQueryResult = GetDynamicMembers(queryResult); // there are 6 system properties plus three user defined properties. @@ -3297,7 +3285,7 @@ public async Task ValidatePOCODocumentSerialization() { TestProperty = "Test5" }; - CustomerObjectFromDocumentEx doc5 = (dynamic)client.CreateDocumentAsync(collection1, testobject5).Result.Resource; + CustomerObjectFromDocumentEx doc5 = (dynamic)(await client.CreateDocumentAsync(collection1, testobject5)).Resource; Assert.AreEqual(doc5.TestProperty, testobject5.TestProperty); Assert.IsFalse(doc5.ToString().Contains("TestProperty")); @@ -3410,7 +3398,7 @@ private async Task ValidateCollectionQuotaTestsWithFailure(bool useGateway) { Logger.LogLine("ValidateCollectionQuotaTestsWithFailure"); Logger.LogLine("Deleting all databases in the system"); - database = client.CreateDatabaseAsync(new Documents.Database { Id = Guid.NewGuid().ToString() }).Result; + database = await client.CreateDatabaseAsync(new Documents.Database { Id = Guid.NewGuid().ToString() }); string duplicateCollectionName = Guid.NewGuid().ToString("N"); List documentCollections = new List(); @@ -3440,7 +3428,7 @@ private async Task ValidateCollectionQuotaTestsWithFailure(bool useGateway) } } - long collectionUsage = client.ReadDocumentCollectionFeedAsync(database).Result.CollectionUsage; + long collectionUsage = (await client.ReadDocumentCollectionFeedAsync(database)).CollectionUsage; // the quota count should be equal to the successful create requests Assert.AreEqual(10 - failedCollectionCount, collectionUsage); diff --git a/Microsoft.Azure.Cosmos/tests/Microsoft.Azure.Cosmos.EmulatorTests/Linq/LinqGeneralBaselineTests.cs b/Microsoft.Azure.Cosmos/tests/Microsoft.Azure.Cosmos.EmulatorTests/Linq/LinqGeneralBaselineTests.cs index a5cdf0c837..4540146446 100644 --- a/Microsoft.Azure.Cosmos/tests/Microsoft.Azure.Cosmos.EmulatorTests/Linq/LinqGeneralBaselineTests.cs +++ b/Microsoft.Azure.Cosmos/tests/Microsoft.Azure.Cosmos.EmulatorTests/Linq/LinqGeneralBaselineTests.cs @@ -3244,8 +3244,7 @@ function callback(err, docCreated) { }; client.createDocument(client.getSelfLink(), { id: 'testDoc' + output, title : 'My Book'}, {}, callback); }"; - StoredProcedureExecuteResponse scriptResponse = null; - int totalNumberOfDocuments = GatewayTests.CreateExecuteAndDeleteCosmosProcedure(collection, script, out scriptResponse, "My Book"); + int totalNumberOfDocuments = await GatewayTests.CreateExecuteAndDeleteCosmosProcedureAsync(collection, script, "My Book"); IOrderedQueryable linqQueryable = collection.GetItemLinqQueryable(allowSynchronousQueryExecution: true); int totalHit = linqQueryable.Where(book => book.Title == "My Book").Count();