public async Task BatchSingleServerResponseAsync()
        {
            List <TransactionalBatchOperationResult> expectedResults = new List <TransactionalBatchOperationResult>();
            CosmosJsonDotNetSerializer jsonSerializer = new CosmosJsonDotNetSerializer();
            TestItem testItem = new TestItem("tst");

            Stream       itemStream     = jsonSerializer.ToStream <TestItem>(testItem);
            MemoryStream resourceStream = itemStream as MemoryStream;

            if (resourceStream == null)
            {
                await itemStream.CopyToAsync(resourceStream);

                resourceStream.Position = 0;
            }

            expectedResults.Add(
                new TransactionalBatchOperationResult(HttpStatusCode.OK)
            {
                ETag           = "theETag",
                SubStatusCode  = (SubStatusCodes)1100,
                ResourceStream = resourceStream
            });
            expectedResults.Add(new TransactionalBatchOperationResult(HttpStatusCode.Conflict));

            double requestCharge = 3.6;

            TestHandler testHandler = new TestHandler(async(request, cancellationToken) =>
            {
                ResponseMessage responseMessage = new ResponseMessage(HttpStatusCode.OK, requestMessage: null, errorMessage: null)
                {
                    Content = await new BatchResponsePayloadWriter(expectedResults).GeneratePayloadAsync()
                };

                responseMessage.Headers.RequestCharge = requestCharge;
                return(responseMessage);
            });

            Container container = BatchUnitTests.GetContainer(testHandler);

            TransactionalBatchResponse batchResponse = await new BatchCore((ContainerInternal)container, new Cosmos.PartitionKey(BatchUnitTests.PartitionKey1))
                                                       .ReadItem("id1")
                                                       .ReadItem("id2")
                                                       .ExecuteAsync();

            Assert.AreEqual(HttpStatusCode.OK, batchResponse.StatusCode);
            Assert.AreEqual(requestCharge, batchResponse.RequestCharge);

            TransactionalBatchOperationResult <TestItem> result0 = batchResponse.GetOperationResultAtIndex <TestItem>(0);

            Assert.AreEqual(expectedResults[0].StatusCode, result0.StatusCode);
            Assert.AreEqual(expectedResults[0].SubStatusCode, result0.SubStatusCode);
            Assert.AreEqual(expectedResults[0].ETag, result0.ETag);
            Assert.AreEqual(testItem, result0.Resource);

            Assert.AreEqual(expectedResults[1].StatusCode, batchResponse[1].StatusCode);
            Assert.AreEqual(SubStatusCodes.Unknown, batchResponse[1].SubStatusCode);
            Assert.IsNull(batchResponse[1].ETag);
            Assert.IsNull(batchResponse[1].ResourceStream);
        }
Esempio n. 2
0
        public async Task ContainerSettingsIndexTest()
        {
            string containerJsonString = "{\"indexingPolicy\":{\"automatic\":true,\"indexingMode\":\"Consistent\",\"includedPaths\":[{\"path\":\"/*\",\"indexes\":[{\"dataType\":\"Number\",\"precision\":-1,\"kind\":\"Range\"},{\"dataType\":\"String\",\"precision\":-1,\"kind\":\"Range\"}]}],\"excludedPaths\":[{\"path\":\"/\\\"_etag\\\"/?\"}],\"compositeIndexes\":[],\"spatialIndexes\":[]},\"id\":\"MigrationTest\",\"partitionKey\":{\"paths\":[\"/id\"],\"kind\":\"Hash\"}}";

            CosmosJsonDotNetSerializer serializerCore      = new CosmosJsonDotNetSerializer();
            ContainerProperties        containerProperties = null;

            using (MemoryStream memory = new MemoryStream(Encoding.UTF8.GetBytes(containerJsonString)))
            {
                containerProperties = serializerCore.FromStream <ContainerProperties>(memory);
            }

            Assert.IsNotNull(containerProperties);
            Assert.AreEqual("MigrationTest", containerProperties.Id);

            string containerJsonAfterConversion = null;

            using (Stream stream = serializerCore.ToStream <ContainerProperties>(containerProperties))
            {
                using (StreamReader sr = new StreamReader(stream))
                {
                    containerJsonAfterConversion = await sr.ReadToEndAsync();
                }
            }

            Assert.AreEqual(containerJsonString, containerJsonAfterConversion);
        }
        public void ValidateCustomSerializerSettings()
        {
            JsonSerializerSettings settings = new JsonSerializerSettings()
            {
                NullValueHandling = NullValueHandling.Ignore
            };

            ToDoActivity toDoActivityNoDescription = new ToDoActivity()
            {
                id          = "c1d433c1-369d-430e-91e5-14e3ce588f71",
                taskNum     = 42,
                cost        = double.MaxValue,
                description = null,
                status      = "TBD"
            };

            string toDoActivityJson = @"{""id"":""c1d433c1-369d-430e-91e5-14e3ce588f71"",""taskNum"":42,""cost"":1.7976931348623157E+308,""status"":""TBD""}";
            CosmosJsonDotNetSerializer cosmosDefaultJsonSerializer = new CosmosJsonDotNetSerializer(settings);

            using (Stream stream = cosmosDefaultJsonSerializer.ToStream <ToDoActivity>(toDoActivityNoDescription))
            {
                Assert.IsNotNull(stream);
                using (StreamReader reader = new StreamReader(stream))
                {
                    string responseAsString = reader.ReadToEnd();
                    Assert.IsNotNull(responseAsString);
                    Assert.AreEqual(toDoActivityJson, responseAsString);
                }
            }
        }
        private static void ValidateOperations <T>(PatchOperation patchOperation, PatchOperationType operationType, T value)
        {
            Assert.AreEqual(operationType, patchOperation.OperationType);
            Assert.AreEqual(path, patchOperation.Path);

            if (!operationType.Equals(PatchOperationType.Remove))
            {
                string           expected;
                CosmosSerializer cosmosSerializer = new CosmosJsonDotNetSerializer();
                using (Stream stream = cosmosSerializer.ToStream(value))
                {
                    using (StreamReader streamReader = new StreamReader(stream))
                    {
                        expected = streamReader.ReadToEnd();
                    }
                }

                Assert.IsTrue(patchOperation.TrySerializeValueParameter(new CustomSerializer(), out Stream valueParam));

                string actual;
                using (valueParam)
                {
                    using (StreamReader streamReader = new StreamReader(valueParam))
                    {
                        actual = streamReader.ReadToEnd();
                    }
                }

                Assert.AreEqual(expected, actual);
            }
        }
        public void ValidateJson()
        {
            CosmosJsonDotNetSerializer cosmosDefaultJsonSerializer = new CosmosJsonDotNetSerializer();

            using (Stream stream = cosmosDefaultJsonSerializer.ToStream <ToDoActivity>(this.toDoActivity))
            {
                Assert.IsNotNull(stream);
                using (StreamReader reader = new StreamReader(stream))
                {
                    string responseAsString = reader.ReadToEnd();
                    Assert.IsNotNull(responseAsString);
                    Assert.AreEqual(this.toDoActivityJson, responseAsString);
                }
            }
        }
        public void ValidateSerializer()
        {
            CosmosJsonDotNetSerializer cosmosDefaultJsonSerializer = new CosmosJsonDotNetSerializer();

            using (Stream stream = cosmosDefaultJsonSerializer.ToStream <ToDoActivity>(this.toDoActivity))
            {
                Assert.IsNotNull(stream);
                ToDoActivity result = cosmosDefaultJsonSerializer.FromStream <ToDoActivity>(stream);
                Assert.IsNotNull(result);
                Assert.AreEqual(this.toDoActivity.id, result.id);
                Assert.AreEqual(this.toDoActivity.taskNum, result.taskNum);
                Assert.AreEqual(this.toDoActivity.cost, result.cost);
                Assert.AreEqual(this.toDoActivity.description, result.description);
                Assert.AreEqual(this.toDoActivity.status, result.status);
            }
        }
        public async Task ContainerContractTest()
        {
            ClientEncryptionIncludedPath clientEncryptionIncludedPath1 = new ClientEncryptionIncludedPath()
            {
                Path = "/path",
                ClientEncryptionKeyId = "dekId",
                EncryptionAlgorithm   = "AEAD_AES_256_CBC_HMAC_SHA256",
                EncryptionType        = "Randomized"
            };

            Collection <ClientEncryptionIncludedPath> paths = new Collection <ClientEncryptionIncludedPath>()
            {
                clientEncryptionIncludedPath1
            };

            ContainerProperties containerProperties = new ContainerProperties(Guid.NewGuid().ToString(), "/users")
            {
                IndexingPolicy = new IndexingPolicy()
                {
                    Automatic     = true,
                    IndexingMode  = IndexingMode.Consistent,
                    IncludedPaths = new Collection <IncludedPath>()
                    {
                        new IncludedPath()
                        {
                            Path = "/*"
                        }
                    },
                    ExcludedPaths = new Collection <ExcludedPath>()
                    {
                        new ExcludedPath()
                        {
                            Path = "/test/*"
                        }
                    },
                    CompositeIndexes = new Collection <Collection <CompositePath> >()
                    {
                        new Collection <CompositePath>()
                        {
                            new CompositePath()
                            {
                                Path  = "/address/city",
                                Order = CompositePathSortOrder.Ascending
                            },
                            new CompositePath()
                            {
                                Path  = "/address/zipcode",
                                Order = CompositePathSortOrder.Descending
                            }
                        }
                    },
                    SpatialIndexes = new Collection <SpatialPath>()
                    {
                        new SpatialPath()
                        {
                            Path         = "/address/spatial/*",
                            SpatialTypes = new Collection <SpatialType>()
                            {
                                SpatialType.LineString
                            }
                        }
                    }
                },
                ClientEncryptionPolicy = new ClientEncryptionPolicy(paths)
            };

            CosmosJsonDotNetSerializer serializer = new CosmosJsonDotNetSerializer();
            Stream stream = serializer.ToStream(containerProperties);
            ContainerProperties deserialziedTest = serializer.FromStream <ContainerProperties>(stream);

            ContainerResponse response = await this.database.CreateContainerAsync(containerProperties);

            Assert.IsNotNull(response);
            Assert.IsTrue(response.RequestCharge > 0);
            Assert.IsNotNull(response.Headers);
            Assert.IsNotNull(response.Headers.ActivityId);

            ContainerProperties responseProperties = response.Resource;

            Assert.IsNotNull(responseProperties.Id);
            Assert.IsNotNull(responseProperties.ResourceId);
            Assert.IsNotNull(responseProperties.ETag);
            Assert.IsTrue(responseProperties.LastModified.HasValue);

            Assert.IsTrue(responseProperties.LastModified.Value > new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc), responseProperties.LastModified.Value.ToString());

            Assert.AreEqual(1, responseProperties.IndexingPolicy.IncludedPaths.Count);
            IncludedPath includedPath = responseProperties.IndexingPolicy.IncludedPaths.First();

            Assert.AreEqual("/*", includedPath.Path);

            Assert.AreEqual("/test/*", responseProperties.IndexingPolicy.ExcludedPaths.First().Path);

            Assert.AreEqual(1, responseProperties.IndexingPolicy.CompositeIndexes.Count);
            Assert.AreEqual(2, responseProperties.IndexingPolicy.CompositeIndexes.First().Count);
            CompositePath compositePath = responseProperties.IndexingPolicy.CompositeIndexes.First().First();

            Assert.AreEqual("/address/city", compositePath.Path);
            Assert.AreEqual(CompositePathSortOrder.Ascending, compositePath.Order);

            Assert.AreEqual(1, responseProperties.IndexingPolicy.SpatialIndexes.Count);
            SpatialPath spatialPath = responseProperties.IndexingPolicy.SpatialIndexes.First();

            Assert.AreEqual("/address/spatial/*", spatialPath.Path);
            Assert.AreEqual(4, spatialPath.SpatialTypes.Count); // All SpatialTypes are returned

            Assert.AreEqual(1, responseProperties.ClientEncryptionPolicy.IncludedPaths.Count());
            Assert.AreEqual(1, responseProperties.ClientEncryptionPolicy.PolicyFormatVersion);
            ClientEncryptionIncludedPath clientEncryptionIncludedPath = responseProperties.ClientEncryptionPolicy.IncludedPaths.First();

            Assert.IsTrue(this.VerifyClientEncryptionIncludedPath(clientEncryptionIncludedPath1, clientEncryptionIncludedPath));
        }
Esempio n. 8
0
        public async Task ContainerContractTest()
        {
            ContainerProperties containerProperties = new ContainerProperties(Guid.NewGuid().ToString(), "/users")
            {
                IndexingPolicy = new IndexingPolicy()
                {
                    Automatic     = true,
                    IndexingMode  = IndexingMode.Consistent,
                    IncludedPaths = new Collection <IncludedPath>()
                    {
                        new IncludedPath()
                        {
                            Path = "/*"
                        }
                    },
                    ExcludedPaths = new Collection <ExcludedPath>()
                    {
                        new ExcludedPath()
                        {
                            Path = "/test/*"
                        }
                    },
                    CompositeIndexes = new Collection <Collection <CompositePath> >()
                    {
                        new Collection <CompositePath>()
                        {
                            new CompositePath()
                            {
                                Path  = "/address/city",
                                Order = CompositePathSortOrder.Ascending
                            },
                            new CompositePath()
                            {
                                Path  = "/address/zipcode",
                                Order = CompositePathSortOrder.Descending
                            }
                        }
                    },
                    SpatialIndexes = new Collection <SpatialPath>()
                    {
                        new SpatialPath()
                        {
                            Path         = "/address/spatial/*",
                            SpatialTypes = new Collection <SpatialType>()
                            {
                                SpatialType.LineString
                            }
                        }
                    }
                }
            };

            var    serializer = new CosmosJsonDotNetSerializer();
            Stream stream     = serializer.ToStream(containerProperties);
            ContainerProperties deserialziedTest = serializer.FromStream <ContainerProperties>(stream);

            ContainerResponse response = await this.database.CreateContainerAsync(containerProperties);

            Assert.IsNotNull(response);
            Assert.IsTrue(response.RequestCharge > 0);
            Assert.IsNotNull(response.Headers);
            Assert.IsNotNull(response.Headers.ActivityId);

            ContainerProperties responseProperties = response.Resource;

            Assert.IsNotNull(responseProperties.Id);
            Assert.IsNotNull(responseProperties.ResourceId);
            Assert.IsNotNull(responseProperties.ETag);
            Assert.IsTrue(responseProperties.LastModified.HasValue);

            Assert.IsTrue(responseProperties.LastModified.Value > new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc), responseProperties.LastModified.Value.ToString());

            Assert.AreEqual(1, responseProperties.IndexingPolicy.IncludedPaths.Count);
            IncludedPath includedPath = responseProperties.IndexingPolicy.IncludedPaths.First();

            Assert.AreEqual("/*", includedPath.Path);

            Assert.AreEqual("/test/*", responseProperties.IndexingPolicy.ExcludedPaths.First().Path);

            Assert.AreEqual(1, responseProperties.IndexingPolicy.CompositeIndexes.Count);
            Assert.AreEqual(2, responseProperties.IndexingPolicy.CompositeIndexes.First().Count);
            CompositePath compositePath = responseProperties.IndexingPolicy.CompositeIndexes.First().First();

            Assert.AreEqual("/address/city", compositePath.Path);
            Assert.AreEqual(CompositePathSortOrder.Ascending, compositePath.Order);

            Assert.AreEqual(1, responseProperties.IndexingPolicy.SpatialIndexes.Count);
            SpatialPath spatialPath = responseProperties.IndexingPolicy.SpatialIndexes.First();

            Assert.AreEqual("/address/spatial/*", spatialPath.Path);
            Assert.AreEqual(1, spatialPath.SpatialTypes.Count);
            Assert.AreEqual(SpatialType.LineString, spatialPath.SpatialTypes.First());
        }
Esempio n. 9
0
        public async Task ContainerV2CompatTest()
        {
            string             containerId        = "SerializeContainerTest";
            DocumentCollection documentCollection = new DocumentCollection()
            {
                Id           = containerId,
                PartitionKey = new PartitionKeyDefinition()
                {
                    Paths = new Collection <string>()
                    {
                        "/pkPath"
                    }
                },
                IndexingPolicy = new IndexingPolicy()
                {
                    IncludedPaths = new Collection <IncludedPath>()
                    {
                        new IncludedPath()
                        {
                            Path = "/*"
                        }
                    },
                    CompositeIndexes = new Collection <Collection <CompositePath> >()
                    {
                        new Collection <CompositePath>()
                        {
                            new CompositePath()
                            {
                                Path  = "/address/test/*",
                                Order = CompositePathSortOrder.Ascending
                            },
                            new CompositePath()
                            {
                                Path  = "/address/test2/*",
                                Order = CompositePathSortOrder.Ascending
                            }
                        }
                    },
                    SpatialIndexes = new Collection <SpatialSpec>()
                    {
                        new SpatialSpec()
                        {
                            Path         = "/name/first/*",
                            SpatialTypes = new Collection <SpatialType>()
                            {
                                SpatialType.LineString
                            }
                        }
                    }
                },
            };


            string documentJsonString = null;

            using (MemoryStream memoryStream = new MemoryStream())
            {
                documentCollection.SaveTo(memoryStream);
                memoryStream.Position = 0;
                using (StreamReader sr = new StreamReader(memoryStream))
                {
                    documentJsonString = await sr.ReadToEndAsync();
                }
            }

            Assert.IsNotNull(documentJsonString);

            string cosmosJsonString = null;

            using (MemoryStream memoryStream = new MemoryStream())
            {
                documentCollection.SaveTo(memoryStream);
                memoryStream.Position = 0;

                CosmosJsonDotNetSerializer serializerCore      = new CosmosJsonDotNetSerializer();
                ContainerProperties        containerProperties = serializerCore.FromStream <ContainerProperties>(memoryStream);

                Assert.IsNotNull(containerProperties);
                Assert.AreEqual(containerId, containerProperties.Id);

                using (Stream stream = serializerCore.ToStream <ContainerProperties>(containerProperties))
                {
                    using (StreamReader sr = new StreamReader(stream))
                    {
                        cosmosJsonString = await sr.ReadToEndAsync();
                    }
                }
            }

            JObject jObjectDocumentCollection = JObject.Parse(documentJsonString);
            JObject jObjectContainer          = JObject.Parse(cosmosJsonString);

            Assert.IsTrue(JToken.DeepEquals(jObjectDocumentCollection, jObjectContainer), $"v2:{documentJsonString}; v3:{cosmosJsonString}");
        }
        public void ValidateSqlQuerySpecSerializer()
        {
            List <SqlQuerySpec> sqlQuerySpecs = new List <SqlQuerySpec>();

            sqlQuerySpecs.Add(new SqlQuerySpec()
            {
                QueryText = "SELECT root._rid, [{\"item\": root[\"NumberField\"]}] AS orderByItems, root AS payload\nFROM root\nWHERE (true)\nORDER BY root[\"NumberField\"] DESC"
            });

            sqlQuerySpecs.Add(new SqlQuerySpec()
            {
                QueryText = "Select * from something"
            });

            sqlQuerySpecs.Add(new SqlQuerySpec()
            {
                QueryText  = "Select * from something",
                Parameters = new SqlParameterCollection()
            });

            SqlParameterCollection sqlParameters = new SqlParameterCollection();

            sqlParameters.Add(new SqlParameter("@id", "test1"));

            sqlQuerySpecs.Add(new SqlQuerySpec()
            {
                QueryText  = "Select * from something",
                Parameters = sqlParameters
            });

            sqlParameters = new SqlParameterCollection();
            sqlParameters.Add(new SqlParameter("@id", "test2"));
            sqlParameters.Add(new SqlParameter("@double", 42.42));
            sqlParameters.Add(new SqlParameter("@int", 9001));
            sqlParameters.Add(new SqlParameter("@null", null));
            sqlParameters.Add(new SqlParameter("@datetime", DateTime.UtcNow));

            sqlQuerySpecs.Add(new SqlQuerySpec()
            {
                QueryText  = "Select * from something",
                Parameters = sqlParameters
            });

            CosmosJsonDotNetSerializer userSerializer       = new CosmosJsonDotNetSerializer();
            CosmosJsonDotNetSerializer propertiesSerializer = new CosmosJsonDotNetSerializer();

            CosmosSerializer sqlQuerySpecSerializer = CosmosSqlQuerySpecJsonConverter.CreateSqlQuerySpecSerializer(
                userSerializer,
                propertiesSerializer);

            foreach (SqlQuerySpec sqlQuerySpec in sqlQuerySpecs)
            {
                Stream stream = propertiesSerializer.ToStream <SqlQuerySpec>(sqlQuerySpec);
                string result1;
                using (StreamReader sr = new StreamReader(stream))
                {
                    result1 = sr.ReadToEnd();
                    Assert.IsNotNull(result1);
                }

                stream = sqlQuerySpecSerializer.ToStream(sqlQuerySpec);
                string result2;
                using (StreamReader sr = new StreamReader(stream))
                {
                    result2 = sr.ReadToEnd();
                    Assert.IsNotNull(result2);
                }

                Assert.AreEqual(result1, result2);
            }
        }