コード例 #1
0
        internal void SerializeAndDeserializeEdgeDocumentTest(JsonSerializationFormat jsonSerializationFormat)
        {
            // Constants to use for vertex document property key/values
            const string idName                = "id";
            const string idValue               = "e_0";
            const string pkValue               = "pk_0";
            const string labelName             = "label";
            const string labelValue            = "l_0";
            const string vertexIdValue         = "v_0";
            const string vertexLabelValue      = "l_1";
            const string sinkIdValue           = "v_1";
            const string sinkLabelValue        = "l_2";
            const string sinkPartitionValue    = "pk_1";
            const bool   isEdgeValue           = true;
            const bool   isPkEdgePropertyValue = true;
            const string boolName              = "myBool";
            const bool   boolValue             = true;
            const string intName               = "myInteger";
            const int    intValue              = 12345;
            const string longName              = "myLong";
            const long   longValue             = 67890L;
            const string floatName             = "myFloatingPoint";
            const float  floatValue            = 123.4f;
            const string doubleName            = "myDouble";
            const double doubleValue           = 56.78;
            const string stringName            = "myString";
            const string stringValue           = "str_0";

            Dictionary <string, CosmosElement> edgeDocumentProperties = new Dictionary <string, CosmosElement>()
            {
                { idName, CosmosString.Create(idValue) },
                { GremlinScenarioTests.PartitionKeyPropertyName, CosmosString.Create(pkValue) },
                { labelName, CosmosString.Create(labelValue) },
                { GremlinKeywords.KW_EDGEDOC_VERTEXID, CosmosString.Create(vertexIdValue) },
                { GremlinKeywords.KW_EDGEDOC_VERTEXLABEL, CosmosString.Create(vertexLabelValue) },
                { GremlinKeywords.KW_EDGE_SINKV, CosmosString.Create(sinkIdValue) },
                { GremlinKeywords.KW_EDGE_SINKV_LABEL, CosmosString.Create(sinkLabelValue) },
                { GremlinKeywords.KW_EDGE_SINKV_PARTITION, CosmosString.Create(sinkPartitionValue) },
                { GremlinKeywords.KW_EDGEDOC_IDENTIFIER, CosmosBoolean.Create(isEdgeValue) },
                { GremlinKeywords.KW_EDGEDOC_ISPKPROPERTY, CosmosBoolean.Create(isPkEdgePropertyValue) },
                { boolName, CosmosBoolean.Create(boolValue) },
                { intName, CosmosNumber64.Create(intValue) },
                { longName, CosmosNumber64.Create(longValue) },
                { floatName, CosmosNumber64.Create(floatValue) },
                { doubleName, CosmosNumber64.Create(doubleValue) },
                { stringName, CosmosString.Create(stringValue) },
            };

            CosmosObject edgeEagerObject = CosmosObject.Create(edgeDocumentProperties);

            // Serialize the edge object into a document using the specified serialization format
            IJsonWriter jsonWriter = JsonWriter.Create(jsonSerializationFormat);

            edgeEagerObject.WriteTo(jsonWriter);
            ReadOnlyMemory <byte> jsonResult = jsonWriter.GetResult();

            Assert.IsTrue(jsonResult.Length > 0, "IJsonWriter result data is empty.");

            // Navigate into the serialized edge document using lazy CosmosElements
            CosmosElement rootLazyElement = CosmosElement.CreateFromBuffer(jsonResult);

            // Validate the expected edge document structure/values

            // Root edge document object
            CosmosObject edgeLazyObject = rootLazyElement as CosmosObject;

            Assert.IsNotNull(edgeLazyObject, $"Edge document root is not {nameof(CosmosObject)}.");
            Assert.AreEqual(edgeDocumentProperties.Count, edgeLazyObject.Count);

            // Edge system document properties
            CosmosString idLazyString = this.GetAndAssertObjectProperty <CosmosString>(edgeLazyObject, idName);

            Assert.AreEqual(idValue, idLazyString.Value);

            CosmosString pkLazyString = this.GetAndAssertObjectProperty <CosmosString>(edgeLazyObject, GremlinScenarioTests.PartitionKeyPropertyName);

            Assert.AreEqual(pkValue, pkLazyString.Value);

            CosmosString labelLazyString = this.GetAndAssertObjectProperty <CosmosString>(edgeLazyObject, labelName);

            Assert.AreEqual(labelValue, labelLazyString.Value);

            CosmosString vertexIdLazyString = this.GetAndAssertObjectProperty <CosmosString>(edgeLazyObject, GremlinKeywords.KW_EDGEDOC_VERTEXID);

            Assert.AreEqual(vertexIdValue, vertexIdLazyString.Value);

            CosmosString vertexLabelLazyString = this.GetAndAssertObjectProperty <CosmosString>(edgeLazyObject, GremlinKeywords.KW_EDGEDOC_VERTEXLABEL);

            Assert.AreEqual(vertexLabelValue, vertexLabelLazyString.Value);

            CosmosString sinkIdLazyString = this.GetAndAssertObjectProperty <CosmosString>(edgeLazyObject, GremlinKeywords.KW_EDGE_SINKV);

            Assert.AreEqual(sinkIdValue, sinkIdLazyString.Value);

            CosmosString sinkLabelLazyString = this.GetAndAssertObjectProperty <CosmosString>(edgeLazyObject, GremlinKeywords.KW_EDGE_SINKV_LABEL);

            Assert.AreEqual(sinkLabelValue, sinkLabelLazyString.Value);

            CosmosString sinkPartitionLazyString = this.GetAndAssertObjectProperty <CosmosString>(edgeLazyObject, GremlinKeywords.KW_EDGE_SINKV_PARTITION);

            Assert.AreEqual(sinkPartitionValue, sinkPartitionLazyString.Value);

            CosmosBoolean isEdgeLazyBool = this.GetAndAssertObjectProperty <CosmosBoolean>(edgeLazyObject, GremlinKeywords.KW_EDGEDOC_IDENTIFIER);

            Assert.AreEqual(isEdgeValue, isEdgeLazyBool.Value);

            CosmosBoolean isPkEdgePropertyLazyBool = this.GetAndAssertObjectProperty <CosmosBoolean>(edgeLazyObject, GremlinKeywords.KW_EDGEDOC_ISPKPROPERTY);

            Assert.AreEqual(isPkEdgePropertyValue, isPkEdgePropertyLazyBool.Value);

            // Edge user properties

            CosmosBoolean boolValueLazyBool = this.GetAndAssertObjectProperty <CosmosBoolean>(edgeLazyObject, boolName);

            Assert.AreEqual(boolValue, boolValueLazyBool.Value);

            CosmosNumber intValueLazyNumber = this.GetAndAssertObjectProperty <CosmosNumber>(edgeLazyObject, intName);

            Assert.IsTrue(intValueLazyNumber is CosmosNumber64);
            Assert.IsTrue(intValueLazyNumber.Value.IsInteger);
            Assert.AreEqual((long)intValue, intValueLazyNumber.Value);

            CosmosNumber longValueLazyNumber = this.GetAndAssertObjectProperty <CosmosNumber>(edgeLazyObject, longName);

            Assert.IsTrue(intValueLazyNumber is CosmosNumber64);
            Assert.IsTrue(intValueLazyNumber.Value.IsInteger);
            Assert.AreEqual(longValue, longValueLazyNumber.Value);

            CosmosNumber floatValueLazyNumber = this.GetAndAssertObjectProperty <CosmosNumber>(edgeLazyObject, floatName);

            Assert.IsTrue(intValueLazyNumber is CosmosNumber64);
            Assert.IsTrue(floatValueLazyNumber.Value.IsDouble);
            Assert.AreEqual((double)floatValue, floatValueLazyNumber.Value);

            CosmosNumber doubleValueLazyNumber = this.GetAndAssertObjectProperty <CosmosNumber>(edgeLazyObject, doubleName);

            Assert.IsTrue(intValueLazyNumber is CosmosNumber64);
            Assert.IsTrue(doubleValueLazyNumber.Value.IsDouble);
            Assert.AreEqual((double)doubleValue, doubleValueLazyNumber.Value);

            CosmosString stringValueLazyString = this.GetAndAssertObjectProperty <CosmosString>(edgeLazyObject, stringName);

            Assert.AreEqual(stringValue, stringValueLazyString.Value);
        }
コード例 #2
0
        internal void SerializeAndDeserializeVertexDocumentTest(JsonSerializationFormat jsonSerializationFormat)
        {
            // Constants to use for vertex document property key/values
            const string idName             = "id";
            const string idValue            = "v_0";
            const string pkValue            = "pk_0";
            const string labelName          = "label";
            const string labelValue         = "l_0";
            const string boolName           = "myBool";
            const string boolId             = "3648bdcc-5113-43f8-86dd-c19fe793a2f8";
            const bool   boolValue          = true;
            const string intName            = "myInteger";
            const string intId              = "7546f541-a003-4e69-a25c-608372ed1321";
            const int    intValue           = 12345;
            const string longId             = "b119c62a-82a2-48b2-b293-9963fa99fbe2";
            const long   longValue          = 67890L;
            const string floatName          = "myFloatingPoint";
            const string floatId            = "98d27280-70ee-4edd-8461-7633a328539a";
            const float  floatValue         = 123.4f;
            const string doubleId           = "f9bfcc22-221a-4c92-b5b9-be53cdedb092";
            const double doubleValue        = 56.78;
            const string stringName         = "myString";
            const string stringId           = "6bb8ae5b-19ca-450e-b369-922a34c02729";
            const string stringValue        = "str_0";
            const string metaProperty0Name  = "myMetaProperty0";
            const string metaProperty0Value = "m_0";
            const string metaProperty1Name  = "myMetaProperty1";
            const int    metaProperty1Value = 123;

            // Compose the vertex document using eager CosmosElements
            Dictionary <string, CosmosElement> vertexDocumentProperties = new Dictionary <string, CosmosElement>()
            {
                { idName, CosmosString.Create(idValue) },
                { GremlinScenarioTests.PartitionKeyPropertyName, CosmosString.Create(pkValue) },
                { labelName, CosmosString.Create(labelValue) },
                {
                    boolName,
                    CosmosArray.Create(
                        new CosmosElement[]
                    {
                        this.CreateVertexPropertySingleComplexValue(CosmosString.Create(boolId), CosmosBoolean.Create(boolValue)),
                    }
                        )
                },
                {
                    intName,
                    CosmosArray.Create(
                        new CosmosElement[]
                    {
                        this.CreateVertexPropertySingleComplexValue(CosmosString.Create(intId), CosmosNumber64.Create(intValue)),
                        this.CreateVertexPropertySingleComplexValue(CosmosString.Create(longId), CosmosNumber64.Create(longValue)),
                    }
                        )
                },
                {
                    floatName,
                    CosmosArray.Create(
                        new CosmosElement[]
                    {
                        this.CreateVertexPropertySingleComplexValue(CosmosString.Create(floatId), CosmosNumber64.Create(floatValue)),
                        this.CreateVertexPropertySingleComplexValue(CosmosString.Create(doubleId), CosmosNumber64.Create(doubleValue)),
                    }
                        )
                },
                {
                    stringName,
                    CosmosArray.Create(
                        new CosmosElement[]
                    {
                        this.CreateVertexPropertySingleComplexValue(
                            CosmosString.Create(stringId),
                            CosmosString.Create(stringValue),
                            Tuple.Create <string, CosmosElement>(metaProperty0Name, CosmosString.Create(metaProperty0Value)),
                            Tuple.Create <string, CosmosElement>(metaProperty1Name, CosmosNumber64.Create(metaProperty1Value))),
                    }
                        )
                },
            };

            CosmosObject vertexEagerObject = CosmosObject.Create(vertexDocumentProperties);

            // Serialize the vertex object into a document using the specified serialization format
            IJsonWriter jsonWriter = JsonWriter.Create(jsonSerializationFormat);

            vertexEagerObject.WriteTo(jsonWriter);
            ReadOnlyMemory <byte> jsonResult = jsonWriter.GetResult();

            Assert.IsTrue(jsonResult.Length > 0, "IJsonWriter result data is empty.");

            // Navigate into the serialized vertex document using lazy CosmosElements
            CosmosElement rootLazyElement = CosmosElement.CreateFromBuffer(jsonResult);

            // Validate the expected vertex document structure/values

            // Root vertex document object
            CosmosObject vertexLazyObject = rootLazyElement as CosmosObject;

            Assert.IsNotNull(vertexLazyObject, $"Vertex document root is not {nameof(CosmosObject)}.");
            Assert.AreEqual(vertexDocumentProperties.Count, vertexLazyObject.Count);

            // Vertex system document properties
            CosmosString idLazyString = this.GetAndAssertObjectProperty <CosmosString>(vertexLazyObject, idName);

            Assert.AreEqual(idValue, idLazyString.Value);

            CosmosString pkLazyString = this.GetAndAssertObjectProperty <CosmosString>(vertexLazyObject, GremlinScenarioTests.PartitionKeyPropertyName);

            Assert.AreEqual(pkValue, pkLazyString.Value);

            CosmosString labelLazyString = this.GetAndAssertObjectProperty <CosmosString>(vertexLazyObject, labelName);

            Assert.AreEqual(labelValue, labelLazyString.Value);

            // Vertex user properties
            CosmosArray boolLazyArray = this.GetAndAssertObjectProperty <CosmosArray>(vertexLazyObject, boolName);

            Assert.AreEqual(1, boolLazyArray.Count);

            // Bool value(s)
            CosmosObject boolValue0LazyObject   = this.GetAndAssertArrayValue <CosmosObject>(boolLazyArray, 0);
            CosmosString boolValue0IdLazyString = this.GetAndAssertObjectProperty <CosmosString>(boolValue0LazyObject, GremlinKeywords.KW_PROPERTY_ID);

            Assert.AreEqual(boolId, boolValue0IdLazyString.Value);
            CosmosBoolean boolValue0ValueLazyBool = this.GetAndAssertObjectProperty <CosmosBoolean>(boolValue0LazyObject, GremlinKeywords.KW_PROPERTY_VALUE);

            Assert.AreEqual(boolValue, boolValue0ValueLazyBool.Value);

            CosmosArray intLazyArray = this.GetAndAssertObjectProperty <CosmosArray>(vertexLazyObject, intName);

            Assert.AreEqual(2, intLazyArray.Count);

            // Integer value(s)
            CosmosObject intValue0LazyObject   = this.GetAndAssertArrayValue <CosmosObject>(intLazyArray, 0);
            CosmosString intValue0IdLazyString = this.GetAndAssertObjectProperty <CosmosString>(intValue0LazyObject, GremlinKeywords.KW_PROPERTY_ID);

            Assert.AreEqual(intId, intValue0IdLazyString.Value);
            CosmosNumber intValue0ValueLazyNumber = this.GetAndAssertObjectProperty <CosmosNumber>(intValue0LazyObject, GremlinKeywords.KW_PROPERTY_VALUE);

            Assert.IsTrue(intValue0ValueLazyNumber is CosmosNumber64);
            Assert.IsTrue(intValue0ValueLazyNumber.Value.IsInteger);
            Assert.AreEqual((long)intValue, intValue0ValueLazyNumber.Value);

            CosmosObject intValue1LazyObject   = this.GetAndAssertArrayValue <CosmosObject>(intLazyArray, 1);
            CosmosString intValue1IdLazyString = this.GetAndAssertObjectProperty <CosmosString>(intValue1LazyObject, GremlinKeywords.KW_PROPERTY_ID);

            Assert.AreEqual(longId, intValue1IdLazyString.Value);
            CosmosNumber intValue1ValueLazyNumber = this.GetAndAssertObjectProperty <CosmosNumber>(intValue1LazyObject, GremlinKeywords.KW_PROPERTY_VALUE);

            Assert.IsTrue(intValue1ValueLazyNumber is CosmosNumber64);
            Assert.IsTrue(intValue1ValueLazyNumber.Value.IsInteger);
            Assert.AreEqual(longValue, intValue1ValueLazyNumber.Value);

            // Floating point value(s)
            CosmosArray floatLazyArray = this.GetAndAssertObjectProperty <CosmosArray>(vertexLazyObject, floatName);

            Assert.AreEqual(2, floatLazyArray.Count);

            CosmosObject floatValue0LazyObject   = this.GetAndAssertArrayValue <CosmosObject>(floatLazyArray, 0);
            CosmosString floatValue0IdLazyString = this.GetAndAssertObjectProperty <CosmosString>(floatValue0LazyObject, GremlinKeywords.KW_PROPERTY_ID);

            Assert.AreEqual(floatId, floatValue0IdLazyString.Value);
            CosmosNumber floatValue0ValueLazyNumber = this.GetAndAssertObjectProperty <CosmosNumber>(floatValue0LazyObject, GremlinKeywords.KW_PROPERTY_VALUE);

            Assert.IsTrue(floatValue0ValueLazyNumber is CosmosNumber64);
            Assert.IsTrue(floatValue0ValueLazyNumber.Value.IsDouble);
            Assert.AreEqual((double)floatValue, floatValue0ValueLazyNumber.Value);

            CosmosObject floatValue1LazyObject   = this.GetAndAssertArrayValue <CosmosObject>(floatLazyArray, 1);
            CosmosString floatValue1IdLazyString = this.GetAndAssertObjectProperty <CosmosString>(floatValue1LazyObject, GremlinKeywords.KW_PROPERTY_ID);

            Assert.AreEqual(doubleId, floatValue1IdLazyString.Value);
            CosmosNumber floatValue1ValueLazyNumber = this.GetAndAssertObjectProperty <CosmosNumber>(floatValue1LazyObject, GremlinKeywords.KW_PROPERTY_VALUE);

            Assert.IsTrue(floatValue1ValueLazyNumber is CosmosNumber64);
            Assert.IsTrue(floatValue1ValueLazyNumber.Value.IsDouble);
            Assert.AreEqual(doubleValue, floatValue1ValueLazyNumber.Value);

            // String value(s)
            CosmosArray stringLazyArray = this.GetAndAssertObjectProperty <CosmosArray>(vertexLazyObject, stringName);

            Assert.AreEqual(1, stringLazyArray.Count);

            CosmosObject stringValue0LazyObject   = this.GetAndAssertArrayValue <CosmosObject>(stringLazyArray, 0);
            CosmosString stringValue0IdLazyString = this.GetAndAssertObjectProperty <CosmosString>(stringValue0LazyObject, GremlinKeywords.KW_PROPERTY_ID);

            Assert.AreEqual(stringId, stringValue0IdLazyString.Value);
            CosmosString stringValue0ValueLazyString = this.GetAndAssertObjectProperty <CosmosString>(stringValue0LazyObject, GremlinKeywords.KW_PROPERTY_VALUE);

            Assert.AreEqual(stringValue, stringValue0ValueLazyString.Value);

            // String value meta-properties
            CosmosObject stringValue0MetaLazyObject = this.GetAndAssertObjectProperty <CosmosObject>(stringValue0LazyObject, GremlinKeywords.KW_PROPERTY_META);

            Assert.AreEqual(2, stringValue0MetaLazyObject.Count);

            CosmosString stringValue0MetaValue0LazyString = this.GetAndAssertObjectProperty <CosmosString>(stringValue0MetaLazyObject, metaProperty0Name);

            Assert.AreEqual(metaProperty0Value, stringValue0MetaValue0LazyString.Value);

            CosmosNumber stringValue0MetaValue1LazyNumber = this.GetAndAssertObjectProperty <CosmosNumber>(stringValue0MetaLazyObject, metaProperty1Name);

            Assert.IsTrue(stringValue0MetaValue1LazyNumber is CosmosNumber64);
            Assert.IsTrue(stringValue0MetaValue1LazyNumber.Value.IsInteger);
            Assert.AreEqual((long)metaProperty1Value, stringValue0MetaValue1LazyNumber.Value);
        }
コード例 #3
0
        internal void DeserializeModifyAndSerializeVertexDocumentTest(JsonSerializationFormat jsonSerializationFormat)
        {
            // Constants to use for vertex document property key/values
            const string idName            = "id";
            const string idValue           = "v_0";
            const string pkValue           = "pk_0";
            const string labelName         = "label";
            const string labelValue        = "l_0";
            const string property1Name     = "p_0";
            const string property1Value1Id = "3648bdcc-5113-43f8-86dd-c19fe793a2f8";
            const string property1Value1   = "p_0_v_0";
            const string property1Value2Id = "7546f541-a003-4e69-a25c-608372ed1321";
            const long   property1Value2   = 1234;
            const string property2Name     = "p_1";
            const string property2Value1Id = "b119c62a-82a2-48b2-b293-9963fa99fbe2";
            const double property2Value1   = 34.56;
            const string property3Name     = "p_2";
            const string property3Value1Id = "98d27280-70ee-4edd-8461-7633a328539a";
            const bool   property3Value1   = true;
            const string property4Name     = "p_3";
            const string property4Value1Id = "f9bfcc22-221a-4c92-b5b9-be53cdedb092";
            const string property4Value1   = "p_3_v_0";

            // Compose the initial vertex document using eager CosmosElements
            Dictionary <string, CosmosElement> initialVertexDocumentProperties = new Dictionary <string, CosmosElement>()
            {
                { idName, CosmosString.Create(idValue) },
                { GremlinScenarioTests.PartitionKeyPropertyName, CosmosString.Create(pkValue) },
                { labelName, CosmosString.Create(labelValue) },
                {
                    property1Name,
                    CosmosArray.Create(
                        new CosmosElement[]
                    {
                        this.CreateVertexPropertySingleComplexValue(CosmosString.Create(property1Value1Id), CosmosString.Create(property1Value1)),
                    }
                        )
                },
                {
                    property2Name,
                    CosmosArray.Create(
                        new CosmosElement[]
                    {
                        this.CreateVertexPropertySingleComplexValue(CosmosString.Create(property2Value1Id), CosmosNumber64.Create(property2Value1)),
                    }
                        )
                },
                {
                    property3Name,
                    CosmosArray.Create(
                        new CosmosElement[]
                    {
                        this.CreateVertexPropertySingleComplexValue(CosmosString.Create(property3Value1Id), CosmosBoolean.Create(property3Value1)),
                    }
                        )
                },
            };

            CosmosObject initialVertexEagerObject = CosmosObject.Create(initialVertexDocumentProperties);

            // Serialize the initial vertex object into a document using the specified serialization format
            IJsonWriter jsonWriter = JsonWriter.Create(jsonSerializationFormat);

            initialVertexEagerObject.WriteTo(jsonWriter);
            ReadOnlyMemory <byte> initialJsonWriterResult = jsonWriter.GetResult();

            Assert.IsTrue(initialJsonWriterResult.Length > 0, "IJsonWriter result data is empty.");

            // Navigate into the serialized vertex document using lazy CosmosElements
            CosmosElement rootLazyElement = CosmosElement.CreateFromBuffer(initialJsonWriterResult);

            // Root vertex document object
            CosmosObject vertexLazyObject = rootLazyElement as CosmosObject;

            Assert.IsNotNull(vertexLazyObject, $"Vertex document root is not {nameof(CosmosObject)}.");
            Assert.AreEqual(initialVertexDocumentProperties.Count, vertexLazyObject.Count);

            CosmosString idLazyString    = this.GetAndAssertObjectProperty <CosmosString>(vertexLazyObject, idName);
            CosmosString pkLazyString    = this.GetAndAssertObjectProperty <CosmosString>(vertexLazyObject, GremlinScenarioTests.PartitionKeyPropertyName);
            CosmosString labelLazyString = this.GetAndAssertObjectProperty <CosmosString>(vertexLazyObject, labelName);
            CosmosArray  property2Array  = this.GetAndAssertObjectProperty <CosmosArray>(vertexLazyObject, property2Name);

            // Compose a new vertex document using a combination of lazy and eager CosmosElements
            Dictionary <string, CosmosElement> modifiedVertexDocumentProperties = new Dictionary <string, CosmosElement>()
            {
                { idName, idLazyString },
                { GremlinScenarioTests.PartitionKeyPropertyName, pkLazyString },
                { labelName, labelLazyString },

                // Property 1 is modified with a new value
                {
                    property1Name,
                    CosmosArray.Create(
                        new CosmosElement[]
                    {
                        this.CreateVertexPropertySingleComplexValue(CosmosString.Create(property1Value2Id), CosmosNumber64.Create(property1Value2)),
                    }
                        )
                },

                // Property 2 is unmodified
                { property2Name, property2Array },

                // Property 3 is deleted

                // Property 4 is newly added
                {
                    property4Name,
                    CosmosArray.Create(
                        new CosmosElement[]
                    {
                        this.CreateVertexPropertySingleComplexValue(CosmosString.Create(property4Value1Id), CosmosString.Create(property4Value1)),
                    }
                        )
                },
            };

            CosmosObject modifiedVertexEagerObject = CosmosObject.Create(modifiedVertexDocumentProperties);

            // Serialize the modified vertex object into a document using the specified serialization format
            jsonWriter = JsonWriter.Create(jsonSerializationFormat);
            modifiedVertexEagerObject.WriteTo(jsonWriter);
            ReadOnlyMemory <byte> modifiedJsonWriterResult = jsonWriter.GetResult();

            Assert.IsTrue(modifiedJsonWriterResult.Length > 0, "IJsonWriter result data is empty.");

            // Compose an expected vertex document using eager CosmosElements
            Dictionary <string, CosmosElement> expectedVertexDocumentProperties = new Dictionary <string, CosmosElement>()
            {
                { idName, CosmosString.Create(idValue) },
                { GremlinScenarioTests.PartitionKeyPropertyName, CosmosString.Create(pkValue) },
                { labelName, CosmosString.Create(labelValue) },
                {
                    property1Name,
                    CosmosArray.Create(
                        new CosmosElement[]
                    {
                        this.CreateVertexPropertySingleComplexValue(CosmosString.Create(property1Value2Id), CosmosNumber64.Create(property1Value2)),
                    }
                        )
                },
                {
                    property2Name,
                    CosmosArray.Create(
                        new CosmosElement[]
                    {
                        this.CreateVertexPropertySingleComplexValue(CosmosString.Create(property2Value1Id), CosmosNumber64.Create(property2Value1)),
                    }
                        )
                },
                {
                    property4Name,
                    CosmosArray.Create(
                        new CosmosElement[]
                    {
                        this.CreateVertexPropertySingleComplexValue(CosmosString.Create(property4Value1Id), CosmosString.Create(property4Value1)),
                    }
                        )
                },
            };

            CosmosObject expectedVertexEagerObject = CosmosObject.Create(expectedVertexDocumentProperties);

            // Serialize the initial vertex object into a document using the specified serialization format
            jsonWriter = JsonWriter.Create(jsonSerializationFormat);
            expectedVertexEagerObject.WriteTo(jsonWriter);
            ReadOnlyMemory <byte> expectedJsonWriterResult = jsonWriter.GetResult();

            Assert.IsTrue(expectedJsonWriterResult.Length > 0, "IJsonWriter result data is empty.");

            // Verify that the modified serialized document matches the expected serialized document
            Assert.IsTrue(modifiedJsonWriterResult.Span.SequenceEqual(expectedJsonWriterResult.Span));
        }
コード例 #4
0
        internal void GetDeserializedObjectsFromQueryResponseTest(JsonSerializationFormat jsonSerializationFormat)
        {
            // Constants to use for vertex document property key/values
            const string vertex1Id             = "v_0";
            const string vertex2Id             = "v_1";
            const string vertex1Label          = "l_0";
            const string vertex2Label          = "l_1";
            const string vertex1PkValue        = "pk_0";
            const string vertex2PkValue        = "pk_1";
            const string property1Name         = "p_0";
            const string vertex1Property1Value = "v_0_p_0_v_0";
            const string vertex2Property1Value = "v_1_p_0_v_0";
            const string property2Name         = "p_1";
            const double vertex1Property2Value = 12.34;
            const long   vertex2Property2Value = 5678;

            // Compose two initial vertex documents using eager CosmosElements
            CosmosObject initialVertex1EagerObject = this.CreateVertexDocument(
                vertex1Id,
                vertex1Label,
                GremlinScenarioTests.PartitionKeyPropertyName,
                vertex1PkValue,
                new Tuple <string, IEnumerable <object> >[]
            {
                Tuple.Create <string, IEnumerable <object> >(property1Name, new object[] { vertex1Property1Value }),
                Tuple.Create <string, IEnumerable <object> >(property2Name, new object[] { vertex1Property2Value }),
            });
            CosmosObject initialVertex2EagerObject = this.CreateVertexDocument(
                vertex2Id,
                vertex2Label,
                GremlinScenarioTests.PartitionKeyPropertyName,
                vertex2PkValue,
                new Tuple <string, IEnumerable <object> >[]
            {
                Tuple.Create <string, IEnumerable <object> >(property1Name, new object[] { vertex2Property1Value }),
                Tuple.Create <string, IEnumerable <object> >(property2Name, new object[] { vertex2Property2Value }),
            });

            // Serialize the initial vertex object into a document using the specified serialization format
            IJsonWriter jsonWriter = JsonWriter.Create(jsonSerializationFormat);

            initialVertex1EagerObject.WriteTo(jsonWriter);
            ReadOnlyMemory <byte> vertex1JsonWriterResult = jsonWriter.GetResult();

            Assert.IsTrue(vertex1JsonWriterResult.Length > 0, "IJsonWriter result data is empty.");

            jsonWriter = JsonWriter.Create(jsonSerializationFormat);
            initialVertex2EagerObject.WriteTo(jsonWriter);
            ReadOnlyMemory <byte> vertex2JsonWriterResult = jsonWriter.GetResult();

            Assert.IsTrue(vertex2JsonWriterResult.Length > 0, "IJsonWriter result data is empty.");

            // Navigate into the serialized vertex documents using lazy CosmosElements
            CosmosElement vertex1LazyObject = CosmosElement.CreateFromBuffer(vertex1JsonWriterResult);
            CosmosElement vertex2LazyObject = CosmosElement.CreateFromBuffer(vertex2JsonWriterResult);

            // Create a dynamically-typed QueryResponse backed by the vertex document CosmosElements
            CosmosArray vertexArray = CosmosArray.Create(
                new CosmosElement[]
            {
                vertex1LazyObject,
                vertex2LazyObject,
            });
            QueryResponse queryResponse = QueryResponse.CreateSuccess(
                vertexArray,
                count: 2,
                responseLengthBytes: vertex1JsonWriterResult.Length + vertex2JsonWriterResult.Length,
                serializationOptions: null,
                responseHeaders: CosmosQueryResponseMessageHeaders.ConvertToQueryHeaders(
                    sourceHeaders: null,
                    resourceType: ResourceType.Document,
                    containerRid: GremlinScenarioTests.CreateRandomString(10)),
                diagnostics: new CosmosDiagnosticsContextCore());
            QueryResponse <dynamic> cosmosElementQueryResponse =
                QueryResponse <dynamic> .CreateResponse <dynamic>(
                    queryResponse,
                    MockCosmosUtil.Serializer);

            // Assert that other objects (anything besides the lazy CosmosElements that we created earlier) are deserialized
            // from the backing CosmosElement contents rather than being directly returned as CosmosElements
            List <dynamic> responseCosmosElements = new List <dynamic>(cosmosElementQueryResponse.Resource);

            Assert.AreEqual(vertexArray.Count, responseCosmosElements.Count);
            Assert.AreNotSame(vertex1LazyObject, responseCosmosElements[0]);
            Assert.AreNotSame(vertex2LazyObject, responseCosmosElements[1]);
        }
コード例 #5
0
        private static void TestCosmosElementVisitabilityFromJson(string json)
        {
            ReadOnlyMemory <byte> payload = LazyCosmosElementTests.ConvertStringToBinary(json);

            CosmosElement cosmosElement = CosmosElement.CreateFromBuffer(payload);

            IJsonWriter jsonWriterIndexer    = Microsoft.Azure.Cosmos.Json.JsonWriter.Create(JsonSerializationFormat.Binary);
            IJsonWriter jsonWriterEnumerable = Microsoft.Azure.Cosmos.Json.JsonWriter.Create(JsonSerializationFormat.Binary);

            LazyCosmosElementTests.VisitCosmosElementIndexer(cosmosElement, jsonWriterIndexer);
            LazyCosmosElementTests.VisitCosmosElementEnumerable(cosmosElement, jsonWriterEnumerable);

            CosmosElement cosmosElementFromIndexer    = CosmosElement.CreateFromBuffer(jsonWriterIndexer.GetResult());
            CosmosElement cosmosElementFromEnumerable = CosmosElement.CreateFromBuffer(jsonWriterEnumerable.GetResult());

            Assert.AreEqual(cosmosElement, cosmosElementFromIndexer);
            Assert.AreEqual(cosmosElement, cosmosElementFromEnumerable);
        }
コード例 #6
0
        public void NumberTest()
        {
            int         integerValue  = 42;
            IJsonWriter integerWriter = JsonWriter.Create(JsonSerializationFormat.Binary);

            integerWriter.WriteNumber64Value(integerValue);
            ReadOnlyMemory <byte> integerBuffer = integerWriter.GetResult();

            {
                TryCatch <sbyte> tryDeserialize = JsonSerializer.Monadic.Deserialize <sbyte>(integerBuffer);
                Assert.IsTrue(tryDeserialize.Succeeded);
                Assert.AreEqual((long)integerValue, (long)tryDeserialize.Result);
            }

            {
                TryCatch <byte> tryDeserialize = JsonSerializer.Monadic.Deserialize <byte>(integerBuffer);
                Assert.IsTrue(tryDeserialize.Succeeded);
                Assert.AreEqual((long)integerValue, (long)tryDeserialize.Result);
            }

            {
                TryCatch <short> tryDeserialize = JsonSerializer.Monadic.Deserialize <short>(integerBuffer);
                Assert.IsTrue(tryDeserialize.Succeeded);
                Assert.AreEqual((long)integerValue, (long)tryDeserialize.Result);
            }

            {
                TryCatch <int> tryDeserialize = JsonSerializer.Monadic.Deserialize <int>(integerBuffer);
                Assert.IsTrue(tryDeserialize.Succeeded);
                Assert.AreEqual((long)integerValue, (long)tryDeserialize.Result);
            }

            {
                TryCatch <long> tryDeserialize = JsonSerializer.Monadic.Deserialize <long>(integerBuffer);
                Assert.IsTrue(tryDeserialize.Succeeded);
                Assert.AreEqual((long)integerValue, (long)tryDeserialize.Result);
            }

            {
                TryCatch <ushort> tryDeserialize = JsonSerializer.Monadic.Deserialize <ushort>(integerBuffer);
                Assert.IsTrue(tryDeserialize.Succeeded);
                Assert.AreEqual((long)integerValue, (long)tryDeserialize.Result);
            }

            {
                TryCatch <uint> tryDeserialize = JsonSerializer.Monadic.Deserialize <uint>(integerBuffer);
                Assert.IsTrue(tryDeserialize.Succeeded);
                Assert.AreEqual((long)integerValue, (long)tryDeserialize.Result);
            }

            {
                TryCatch <ulong> tryDeserialize = JsonSerializer.Monadic.Deserialize <ulong>(integerBuffer);
                Assert.IsTrue(tryDeserialize.Succeeded);
                Assert.AreEqual((long)integerValue, (long)tryDeserialize.Result);
            }

            {
                TryCatch <decimal> tryDeserialize = JsonSerializer.Monadic.Deserialize <decimal>(integerBuffer);
                Assert.IsTrue(tryDeserialize.Succeeded);
                Assert.AreEqual((long)integerValue, (long)tryDeserialize.Result);
            }

            {
                TryCatch <float> tryDeserialize = JsonSerializer.Monadic.Deserialize <float>(integerBuffer);
                Assert.IsFalse(tryDeserialize.Succeeded);
            }

            {
                TryCatch <double> tryDeserialize = JsonSerializer.Monadic.Deserialize <double>(integerBuffer);
                Assert.IsFalse(tryDeserialize.Succeeded);
            }

            float       doubleValue  = 42.1337f;
            IJsonWriter doubleWriter = JsonWriter.Create(JsonSerializationFormat.Binary);

            doubleWriter.WriteNumber64Value(doubleValue);
            ReadOnlyMemory <byte> doubleBuffer = doubleWriter.GetResult();

            {
                TryCatch <sbyte> tryDeserialize = JsonSerializer.Monadic.Deserialize <sbyte>(doubleBuffer);
                Assert.IsFalse(tryDeserialize.Succeeded);
            }

            {
                TryCatch <byte> tryDeserialize = JsonSerializer.Monadic.Deserialize <byte>(doubleBuffer);
                Assert.IsFalse(tryDeserialize.Succeeded);
            }

            {
                TryCatch <short> tryDeserialize = JsonSerializer.Monadic.Deserialize <short>(doubleBuffer);
                Assert.IsFalse(tryDeserialize.Succeeded);
            }

            {
                TryCatch <int> tryDeserialize = JsonSerializer.Monadic.Deserialize <int>(doubleBuffer);
                Assert.IsFalse(tryDeserialize.Succeeded);
            }

            {
                TryCatch <long> tryDeserialize = JsonSerializer.Monadic.Deserialize <long>(doubleBuffer);
                Assert.IsFalse(tryDeserialize.Succeeded);
            }

            {
                TryCatch <ushort> tryDeserialize = JsonSerializer.Monadic.Deserialize <ushort>(doubleBuffer);
                Assert.IsFalse(tryDeserialize.Succeeded);
            }

            {
                TryCatch <uint> tryDeserialize = JsonSerializer.Monadic.Deserialize <uint>(doubleBuffer);
                Assert.IsFalse(tryDeserialize.Succeeded);
            }

            {
                TryCatch <ulong> tryDeserialize = JsonSerializer.Monadic.Deserialize <ulong>(doubleBuffer);
                Assert.IsFalse(tryDeserialize.Succeeded);
            }

            {
                TryCatch <decimal> tryDeserialize = JsonSerializer.Monadic.Deserialize <decimal>(doubleBuffer);
                Assert.IsTrue(tryDeserialize.Succeeded);
                Assert.AreEqual((decimal)(double)doubleValue, tryDeserialize.Result);
            }

            {
                TryCatch <float> tryDeserialize = JsonSerializer.Monadic.Deserialize <float>(doubleBuffer);
                Assert.IsTrue(tryDeserialize.Succeeded);
                Assert.AreEqual(doubleValue, tryDeserialize.Result);
            }

            {
                TryCatch <double> tryDeserialize = JsonSerializer.Monadic.Deserialize <double>(doubleBuffer);
                Assert.IsTrue(tryDeserialize.Succeeded);
                Assert.AreEqual(doubleValue, tryDeserialize.Result);
            }
        }
コード例 #7
0
            public override string GetContinuationToken()
            {
                IJsonWriter jsonWriter = JsonWriter.Create(JsonSerializationFormat.Binary);

                jsonWriter.WriteObjectStart();

                jsonWriter.WriteFieldName(UnorderdDistinctMap.NumbersName);
                jsonWriter.WriteArrayStart();
                foreach (Number64 number in this.numbers)
                {
                    jsonWriter.WriteNumberValue(number);
                }
                jsonWriter.WriteArrayEnd();

                jsonWriter.WriteFieldName(UnorderdDistinctMap.StringsLength4Name);
                jsonWriter.WriteArrayStart();
                foreach (uint stringLength4 in this.stringsLength4)
                {
                    jsonWriter.WriteUInt32Value(stringLength4);
                }
                jsonWriter.WriteArrayEnd();

                jsonWriter.WriteFieldName(UnorderdDistinctMap.StringsLength8Name);
                jsonWriter.WriteArrayStart();
                foreach (ulong stringLength8 in this.stringsLength8)
                {
                    jsonWriter.WriteInt64Value((long)stringLength8);
                }
                jsonWriter.WriteArrayEnd();

                jsonWriter.WriteFieldName(UnorderdDistinctMap.StringsLength16Name);
                jsonWriter.WriteArrayStart();
                foreach (UInt128 stringLength16 in this.stringsLength16)
                {
                    jsonWriter.WriteBinaryValue(UInt128.ToByteArray(stringLength16));
                }
                jsonWriter.WriteArrayEnd();

                jsonWriter.WriteFieldName(UnorderdDistinctMap.StringsLength16PlusName);
                jsonWriter.WriteArrayStart();
                foreach (UInt128 stringLength16Plus in this.stringsLength16Plus)
                {
                    jsonWriter.WriteBinaryValue(UInt128.ToByteArray(stringLength16Plus));
                }
                jsonWriter.WriteArrayEnd();

                jsonWriter.WriteFieldName(UnorderdDistinctMap.ArraysName);
                jsonWriter.WriteArrayStart();
                foreach (UInt128 array in this.arrays)
                {
                    jsonWriter.WriteBinaryValue(UInt128.ToByteArray(array));
                }
                jsonWriter.WriteArrayEnd();

                jsonWriter.WriteFieldName(UnorderdDistinctMap.ObjectName);
                jsonWriter.WriteArrayStart();
                foreach (UInt128 objectHash in this.objects)
                {
                    jsonWriter.WriteBinaryValue(UInt128.ToByteArray(objectHash));
                }
                jsonWriter.WriteArrayEnd();

                jsonWriter.WriteFieldName(UnorderdDistinctMap.SimpleValuesName);
                jsonWriter.WriteStringValue(this.simpleValues.ToString());

                jsonWriter.WriteObjectEnd();

                ReadOnlyMemory <byte> memory = jsonWriter.GetResult();

                if (!MemoryMarshal.TryGetArray(memory, out ArraySegment <byte> buffer))
                {
                    buffer = new ArraySegment <byte>(memory.ToArray());
                }

                return(Convert.ToBase64String(buffer.Array, buffer.Offset, buffer.Count));
            }
コード例 #8
0
        public async Task ItemQueryStreamSerializationSetting()
        {
            IList <ToDoActivity> deleteList = new List <ToDoActivity>();

            try
            {
                deleteList = await CreateRandomItems(101, randomPartitionKey : true);

                CosmosSqlQueryDefinition   sql     = new CosmosSqlQueryDefinition("SELECT * FROM toDoActivity t ORDER BY t.taskNum");
                CosmosSerializationOptions options = new CosmosSerializationOptions(
                    ContentSerializationFormat.CosmosBinary.ToString(),
                    (content) => JsonNavigator.Create(content),
                    () => JsonWriter.Create(JsonSerializationFormat.Binary));

                CosmosQueryRequestOptions requestOptions = new CosmosQueryRequestOptions()
                {
                    CosmosSerializationOptions = options
                };

                List <ToDoActivity> resultList      = new List <ToDoActivity>();
                double totalRequstCharge            = 0;
                CosmosResultSetIterator setIterator =
                    this.Container.Items.CreateItemQueryAsStream(sql, maxConcurrency: 5, maxItemCount: 5, requestOptions: requestOptions);
                while (setIterator.HasMoreResults)
                {
                    using (CosmosQueryResponse iter = await setIterator.FetchNextSetAsync())
                    {
                        Assert.IsTrue(iter.IsSuccess);
                        Assert.IsNull(iter.ErrorMessage);
                        Assert.IsTrue(iter.Count <= 5);
                        totalRequstCharge += iter.RequestCharge;
                        IJsonReader reader     = JsonReader.Create(iter.Content);
                        IJsonWriter textWriter = JsonWriter.Create(JsonSerializationFormat.Text);
                        textWriter.WriteAll(reader);
                        string json = Encoding.UTF8.GetString(textWriter.GetResult());
                        Assert.IsNotNull(json);
                        ToDoActivity[] responseActivities = JsonConvert.DeserializeObject <ToDoActivity[]>(json);
                        resultList.AddRange(responseActivities);
                    }
                }

                Assert.AreEqual(deleteList.Count, resultList.Count);
                Assert.IsTrue(totalRequstCharge > 0);

                List <ToDoActivity> verifiedOrderBy = deleteList.OrderBy(x => x.taskNum).ToList();
                for (int i = 0; i < verifiedOrderBy.Count(); i++)
                {
                    Assert.AreEqual(verifiedOrderBy[i].taskNum, resultList[i].taskNum);
                    Assert.AreEqual(verifiedOrderBy[i].id, resultList[i].id);
                }
            }
            finally
            {
                foreach (ToDoActivity delete in deleteList)
                {
                    CosmosResponseMessage deleteResponse = await this.Container.Items.DeleteItemStreamAsync(delete.status, delete.id);

                    deleteResponse.Dispose();
                }
            }
        }
コード例 #9
0
        private static void PerformRoundTrip(
            SerializationFormat sourceFormat,
            SerializationFormat destinationFormat,
            string json,
            bool writeAsRootNode)
        {
            IJsonReader reader = sourceFormat switch
            {
                SerializationFormat.Text => JsonReader.Create(Encoding.UTF8.GetBytes(json)),
                SerializationFormat.Binary => JsonReader.Create(JsonTestUtils.ConvertTextToBinary(json)),
                SerializationFormat.NewtonsoftText => NewtonsoftToCosmosDBReader.CreateFromString(json),
                _ => throw new ArgumentException($"Unexpected {nameof(sourceFormat)} of type: {sourceFormat}"),
            };

            IJsonNavigator navigator = sourceFormat switch
            {
                SerializationFormat.Text => JsonNavigator.Create(Encoding.UTF8.GetBytes(json)),
                SerializationFormat.Binary => JsonNavigator.Create(JsonTestUtils.ConvertTextToBinary(json)),
                SerializationFormat.NewtonsoftText => new JsonNewtonsoftNavigator(json),
                _ => throw new ArgumentException($"Unexpected {nameof(sourceFormat)} of type: {sourceFormat}"),
            };

            foreach (object source in new object[] { reader, navigator })
            {
                IJsonWriter writer = destinationFormat switch
                {
                    SerializationFormat.Text => JsonWriter.Create(JsonSerializationFormat.Text),
                    SerializationFormat.Binary => JsonWriter.Create(JsonSerializationFormat.Binary),
                    SerializationFormat.NewtonsoftText => NewtonsoftToCosmosDBWriter.CreateTextWriter(),
                    _ => throw new ArgumentException($"Unexpected {nameof(destinationFormat)} of type: {destinationFormat}"),
                };

                switch (source)
                {
                case IJsonReader sourceReader:
                    sourceReader.WriteAll(writer);
                    break;

                case IJsonNavigator sourceNavigator:
                    if (writeAsRootNode)
                    {
                        sourceNavigator.WriteNode(sourceNavigator.GetRootNode(), writer);
                    }
                    else
                    {
                        IJsonNavigatorNode rootNode     = sourceNavigator.GetRootNode();
                        JsonNodeType       jsonNodeType = sourceNavigator.GetNodeType(rootNode);
                        switch (jsonNodeType)
                        {
                        case JsonNodeType.Array:
                            writer.WriteArrayStart();

                            foreach (IJsonNavigatorNode arrayItem in sourceNavigator.GetArrayItems(rootNode))
                            {
                                sourceNavigator.WriteNode(arrayItem, writer);
                            }

                            writer.WriteArrayEnd();
                            break;

                        case JsonNodeType.Object:
                            writer.WriteObjectStart();

                            foreach (ObjectProperty objectProperty in sourceNavigator.GetObjectProperties(rootNode))
                            {
                                sourceNavigator.WriteNode(objectProperty.NameNode, writer);
                                sourceNavigator.WriteNode(objectProperty.ValueNode, writer);
                            }

                            writer.WriteObjectEnd();
                            break;

                        default:
                            sourceNavigator.WriteNode(sourceNavigator.GetRootNode(), writer);
                            break;
                        }
                    }
                    break;

                default:
                    Assert.Fail("Failed to downcast source type.");
                    break;
                }

                string result = writer.SerializationFormat switch
                {
                    JsonSerializationFormat.Text => Utf8String.UnsafeFromUtf8BytesNoValidation(writer.GetResult()).ToString(),
                    JsonSerializationFormat.Binary => JsonTestUtils.ConvertBinaryToText(writer.GetResult()),
                    _ => throw new ArgumentException(),
                };
                string normalizedResult = JsonRoundTripsTests.NewtonsoftFormat(result);
                string normalizedJson   = JsonRoundTripsTests.NewtonsoftFormat(json);

                Assert.AreEqual(normalizedJson, normalizedResult);
            }
        }