public ODataEntryMetadataContextTest()
 {
     this.entry = new ODataEntry {TypeName = ActualEntityType.FullName()};
     this.typeContext = new TestFeedAndEntryTypeContext();
     this.entryMetadataContextWithoutModel = ODataEntryMetadataContext.Create(this.entry, this.typeContext, new ODataFeedAndEntrySerializationInfo(), /*actualEntityType*/null, new TestMetadataContext(), SelectedPropertiesNode.EntireSubtree);
     this.entryMetadataContextWithModel = ODataEntryMetadataContext.Create(this.entry, this.typeContext, /*serializationInfo*/null, ActualEntityType, new TestMetadataContext(), SelectedPropertiesNode.EntireSubtree);
 }
 public void ShouldBeAbleToSetTheEntrySerializationInfo()
 {
     ODataEntry entry = new ODataEntry();
     ODataFeedAndEntrySerializationInfo serializationInfo = new ODataFeedAndEntrySerializationInfo { NavigationSourceName = "Set", NavigationSourceEntityTypeName = "ns.base", ExpectedTypeName = "ns.expected" };
     entry.SetSerializationInfo(serializationInfo);
     entry.SerializationInfo.Should().BeSameAs(serializationInfo);
 }
        private static ODataEntry CreateEntryWithKeyAsSegmentConvention(bool addAnnotation, bool? useKeyAsSegment)
        {
            var model = new EdmModel();
            var container = new EdmEntityContainer("Fake", "Container");
            model.AddElement(container);
            if (addAnnotation)
            {
                model.AddVocabularyAnnotation(new EdmAnnotation(container, UrlConventionsConstants.ConventionTerm, UrlConventionsConstants.KeyAsSegmentAnnotationValue));                
            }
            
            EdmEntityType entityType = new EdmEntityType("Fake", "FakeType");
            entityType.AddKeys(entityType.AddStructuralProperty("Id", EdmPrimitiveTypeKind.Int32));
            model.AddElement(entityType);

            var entitySet = new EdmEntitySet(container, "FakeSet", entityType);
            container.AddElement(entitySet);

            var metadataContext = new ODataMetadataContext(
                true,
                ODataReaderBehavior.DefaultBehavior.OperationsBoundToEntityTypeMustBeContainerQualified,
                new EdmTypeReaderResolver(model, ODataReaderBehavior.DefaultBehavior),
                model,
                new Uri("http://temp.org/$metadata"),
                null /*requestUri*/);

            var thing = new ODataEntry {Properties = new[] {new ODataProperty {Name = "Id", Value = 1}}};
            thing.SetAnnotation(new ODataTypeAnnotation(entitySet, entityType));
            thing.MetadataBuilder = metadataContext.GetEntityMetadataBuilderForReader(new TestJsonLightReaderEntryState { Entry = thing, SelectedProperties = new SelectedPropertiesNode("*")}, useKeyAsSegment);
            return thing;
        }
        public void WriteCompletedAsyncResponse()
        {
            var asyncWriter = this.TestInit();

            var innerMessage = asyncWriter.CreateResponseMessage();
            innerMessage.StatusCode = 200;
            innerMessage.SetHeader("Content-Type", "application/json");

            var settings = new ODataMessageWriterSettings();
            settings.SetServiceDocumentUri(new Uri(ServiceDocumentUri));
            settings.DisableMessageStreamDisposal = true;

            using (var innerMessageWriter = new ODataMessageWriter(innerMessage, settings, this.userModel))
            {
                var entryWriter = innerMessageWriter.CreateODataEntryWriter(singleton, testType);
                var entry = new ODataEntry() {TypeName = "NS.Test", Properties = new[] {new ODataProperty() {Name = "Id", Value = 1}}};
                entryWriter.WriteStart(entry);
                entryWriter.WriteEnd();
            }

            asyncWriter.Flush();

            var payload = this.TestFinish();
            Assert.Equal("HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nOData-Version: 4.0\r\n\r\n{\"@odata.context\":\"http://host/service/$metadata#MySingleton\",\"Id\":1}", payload);
        }
 public void InjectMetadataBuilderShouldNotSetBuilderOnEntry()
 {
     var entry = new ODataEntry();
     var builder = new TestEntityMetadataBuilder(entry);
     testSubject.InjectMetadataBuilder(entry, builder);
     entry.MetadataBuilder.Should().BeOfType<NoOpEntityMetadataBuilder>();
 }
        public ODataNavigationLinkTests()
        {
            this.navigationLink = new ODataNavigationLink();

            var entry = new ODataEntry
            {
                TypeName = "ns.DerivedType",
                Properties = new[]
                {
                    new ODataProperty{Name = "Id", Value = 1, SerializationInfo = new ODataPropertySerializationInfo{PropertyKind = ODataPropertyKind.Key}},
                    new ODataProperty{Name = "Name", Value = "Bob", SerializationInfo = new ODataPropertySerializationInfo{PropertyKind = ODataPropertyKind.ETag}}
                }
            };

            var serializationInfo = new ODataFeedAndEntrySerializationInfo { NavigationSourceName = "Set", NavigationSourceEntityTypeName = "ns.BaseType", ExpectedTypeName = "ns.BaseType" };
            var typeContext = ODataFeedAndEntryTypeContext.Create(serializationInfo, null, null, null, EdmCoreModel.Instance, true);
            var metadataContext = new TestMetadataContext();
            var entryMetadataContext = ODataEntryMetadataContext.Create(entry, typeContext, serializationInfo, null, metadataContext, SelectedPropertiesNode.EntireSubtree);
            var metadataBuilder = new ODataConventionalEntityMetadataBuilder(entryMetadataContext, metadataContext, new ODataConventionalUriBuilder(ServiceUri, UrlConvention.CreateWithExplicitValue(false)));
            this.navigationLinkWithFullBuilder = new ODataNavigationLink { Name = "NavProp" };
            this.navigationLinkWithFullBuilder.MetadataBuilder = metadataBuilder;

            this.navigationLinkWithNoOpBuilder = new ODataNavigationLink { Name = "NavProp" };
            this.navigationLinkWithNoOpBuilder.MetadataBuilder = new NoOpEntityMetadataBuilder(entry);

            this.navigationLinkWithNullBuilder = new ODataNavigationLink { Name = "NavProp" };
            this.navigationLinkWithNullBuilder.MetadataBuilder = ODataEntityMetadataBuilder.Null;
        }
        public void EntryMetadataUrlRoundTrip()
        {
            var stream = new MemoryStream();
            var writerRequestMemoryMessage = new InMemoryMessage();
            writerRequestMemoryMessage.Stream = stream;
            writerRequestMemoryMessage.SetHeader("Content-Type", "application/json");

            var writerSettings = new ODataMessageWriterSettings() {Version = ODataVersion.V4, DisableMessageStreamDisposal = true};
            writerSettings.ODataUri = new ODataUri() {ServiceRoot = new Uri("http://christro.svc/")};

            var messageWriter = new ODataMessageWriter((IODataResponseMessage)writerRequestMemoryMessage, writerSettings, this.model);
            var organizationSetWriter = messageWriter.CreateODataEntryWriter(this.organizationsSet);
            var odataEntry = new ODataEntry(){ TypeName = ModelNamespace + ".Corporation" };
            odataEntry.Property("Id", 1);
            odataEntry.Property("Name", "");
            odataEntry.Property("TickerSymbol", "MSFT");

            organizationSetWriter.WriteStart(odataEntry);
            organizationSetWriter.WriteEnd();

            var readerPayloadInput = Encoding.UTF8.GetString(stream.GetBuffer());
            Console.WriteLine(readerPayloadInput);

            var readerResponseMemoryMessage = new InMemoryMessage();
            readerResponseMemoryMessage.Stream = new MemoryStream(stream.GetBuffer());
            readerResponseMemoryMessage.SetHeader("Content-Type", "application/json");

            var messageReader = new ODataMessageReader((IODataResponseMessage)readerResponseMemoryMessage, new ODataMessageReaderSettings() {MaxProtocolVersion = ODataVersion.V4, DisableMessageStreamDisposal = true}, this.model);
            var organizationReader = messageReader.CreateODataEntryReader(this.organizationsSet, this.organizationsSet.EntityType());
            organizationReader.Read().Should().Be(true);
            organizationReader.Item.As<ODataEntry>();
        }
 public void InjectMetadataBuilderShouldSetBuilderOnEntry()
 {
     var entry = new ODataEntry();
     var builder = new TestEntityMetadataBuilder(entry);
     testSubject.InjectMetadataBuilder(entry, builder);
     entry.MetadataBuilder.Should().BeSameAs(builder);
 }
        /// <summary>
        /// Returns a hash set of operation imports (actions and functions) in the given entry.
        /// </summary>
        /// <param name="entry">The entry in question.</param>
        /// <param name="model">The edm model to resolve operation imports.</param>
        /// <param name="metadataDocumentUri">The metadata document uri.</param>
        /// <returns>The hash set of operation imports (actions and functions) in the given entry.</returns>
        private static HashSet<IEdmOperation> GetOperationsInEntry(ODataEntry entry, IEdmModel model, Uri metadataDocumentUri)
        {
            Debug.Assert(entry != null, "entry != null");
            Debug.Assert(model != null, "model != null");
            Debug.Assert(metadataDocumentUri != null && metadataDocumentUri.IsAbsoluteUri, "metadataDocumentUri != null && metadataDocumentUri.IsAbsoluteUri");

            HashSet<IEdmOperation> edmOperationImportsInEntry = new HashSet<IEdmOperation>(EqualityComparer<IEdmOperation>.Default);
            IEnumerable<ODataOperation> operations = ODataUtilsInternal.ConcatEnumerables((IEnumerable<ODataOperation>)entry.NonComputedActions, (IEnumerable<ODataOperation>)entry.NonComputedFunctions);
            if (operations != null)
            {
                foreach (ODataOperation operation in operations)
                {
                    Debug.Assert(operation.Metadata != null, "operation.Metadata != null");
                    string operationMetadataString = UriUtils.UriToString(operation.Metadata);
                    Debug.Assert(
                        ODataJsonLightUtils.IsMetadataReferenceProperty(operationMetadataString),
                        "ODataJsonLightUtils.IsMetadataReferenceProperty(operationMetadataString)");
                    Debug.Assert(
                        operationMetadataString[0] == ODataConstants.ContextUriFragmentIndicator || metadataDocumentUri.IsBaseOf(operation.Metadata),
                        "operationMetadataString[0] == JsonLightConstants.ContextUriFragmentIndicator || metadataDocumentUri.IsBaseOf(operation.Metadata)");

                    string fullyQualifiedOperationName = ODataJsonLightUtils.GetUriFragmentFromMetadataReferencePropertyName(metadataDocumentUri, operationMetadataString);
                    IEnumerable<IEdmOperation> edmOperations = model.ResolveOperations(fullyQualifiedOperationName);
                    if (edmOperations != null)
                    {
                        foreach (IEdmOperation edmOperation in edmOperations)
                        {
                            edmOperationImportsInEntry.Add(edmOperation);
                        }
                    }
                }
            }

            return edmOperationImportsInEntry;
        }
 public void ReadLinkShouldNotBeOmittedWhenNotIdenticalToEditLink()
 {
     DateTimeOffset updatedTime = DateTimeOffset.UtcNow;
     var entry = new ODataEntry
     {
         Id = new Uri("http://test.org/EntitySet('1')"),
         EditLink = new Uri("http://test.org/EntitySet('1')/edit"),
         ReadLink = new Uri("http://test.org/EntitySet('1')/read")
     };
     entry.SetAnnotation(new AtomEntryMetadata() { Updated = updatedTime });
     string actual = this.WriteAtomEntry(entry);
     string expected = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
         "<entry xmlns=\"http://www.w3.org/2005/Atom\" xmlns:d=\"http://docs.oasis-open.org/odata/ns/data\" xmlns:m=\"http://docs.oasis-open.org/odata/ns/metadata\" xmlns:georss=\"http://www.georss.org/georss\" xmlns:gml=\"http://www.opengis.net/gml\" m:context=\"http://temp.org/$metadata#EntitySet/$entity\">" +
             "<id>http://test.org/EntitySet('1')</id>" +
             "<link rel=\"edit\" href=\"http://test.org/EntitySet('1')/edit\" />" +
             "<link rel=\"self\" href=\"http://test.org/EntitySet('1')/read\" />" +
             "<title />" +
             "<updated>" + ODataAtomConvert.ToAtomString(updatedTime) + "</updated>" +
             "<author>" +
                 "<name />" +
             "</author>" +
             "<content type=\"application/xml\" />" +
         "</entry>";
     Assert.Equal(expected, actual);
 }
 public void ShouldBeAbleToWriteTransientEntry()
 {
     IEdmEntityType entityType = GetEntityType();
     IEdmEntitySet entitySet = GetEntitySet(entityType);
     ODataEntry transientEntry = new ODataEntry() { IsTransient = true };
     var actual = WriteJsonLightEntry(true, null, false, transientEntry, entitySet, entityType);
     actual.Should().Contain("\"@odata.id\":null");
 }
        /// <summary>
        /// Creates a new Edm structured value from an OData entry.
        /// </summary>
        /// <param name="entry">The <see cref="ODataEntry"/> to create the structured value for.</param>
        internal ODataEdmStructuredValue(ODataEntry entry)
            : base(entry.GetEdmType())
        {
            Debug.Assert(entry != null, "entry != null");

            this.properties = entry.NonComputedProperties;
            this.structuredType = this.Type == null ? null : this.Type.AsStructured();
        }
 public void InjectMetadataBuilderShouldNotSetBuilderOnEntryMediaResource()
 {
     var entry = new ODataEntry();
     var builder = new TestEntityMetadataBuilder(entry);
     entry.MediaResource = new ODataStreamReferenceValue();
     testSubject.InjectMetadataBuilder(entry, builder);
     entry.MediaResource.GetMetadataBuilder().Should().BeNull();
 }
        /// <summary>
        /// Constructs an instance of <see cref="ODataEntryMetadataContext"/>.
        /// </summary>
        /// <param name="entry">The entry instance.</param>
        /// <param name="typeContext">The context object to answer basic questions regarding the type of the entry.</param>
        protected ODataEntryMetadataContext(ODataEntry entry, IODataFeedAndEntryTypeContext typeContext)
        {
            Debug.Assert(entry != null, "entry != null");
            Debug.Assert(typeContext != null, "typeContext != null");

            this.entry = entry;
            this.typeContext = typeContext;
        }
 public void GetIdShouldBeNullWhenEntryIsTransient()
 {
     Uri id = new Uri("http://example.com");
     ODataEntry odataEntry = new ODataEntry()
     {
         IsTransient = true,
         Id = id
     };
     new NoOpEntityMetadataBuilder(odataEntry).GetId().Should().BeNull();
 }
        /// <summary>
        /// Creates a new cache.
        /// </summary>
        /// <param name="entry">The entry for which to create the properties cache.</param>
        internal EntryPropertiesValueCache(ODataEntry entry)
        {
            Debug.Assert(entry != null, "entry != null");

            // Cache the entry properties right here as there's no point in delaying since we will enumerate those anyway.
            if (entry.Properties != null)
            {
                this.entryPropertiesCache = new List<ODataProperty>(entry.Properties);
            }
        }
        public void ValidateNoMetadataShouldThrow()
        {
            var model = CreateTestModel();
            var coreWriter = CreateODataWriterCore(ODataFormat.Json, true, model, null, null, false);

            var entry = new ODataEntry();
            Action test = () => coreWriter.ValidateEntityType2(entry);

            test.ShouldThrow<ODataException>().WithMessage(Strings.WriterValidationUtils_MissingTypeNameWithMetadata);
        }
        public void ValidateEntityTypeShouldAlwaysReturnSpecifiedTypeName()
        {
            var model = CreateTestModel();
            var set = model.EntityContainer.FindEntitySet("Objects");
            var objectType = (IEdmEntityType)model.FindDeclaredType("DefaultNamespace.Object");
            var coreWriter = CreateODataWriterCore(ODataFormat.Json, true, model, set, objectType, false);

            var entry = new ODataEntry() { TypeName = "DefaultNamespace.Person" };
            var entityType = coreWriter.ValidateEntityType2(entry);
            entityType.Should().BeSameAs(model.FindDeclaredType("DefaultNamespace.Person"));
        }
        /// <summary>
        /// Determines the entity type name to write to the payload.
        /// </summary>
        /// <param name="expectedTypeName">The expected type name, e.g. the base type of the set or the nav prop.</param>
        /// <param name="entry">The ODataEntry whose type is to be written.</param>
        /// <returns>Type name to write to the payload, or null if no type name should be written.</returns>
        internal override string GetEntryTypeNameForWriting(string expectedTypeName, ODataEntry entry)
        {
            Debug.Assert(entry != null, "entry != null");

            SerializationTypeNameAnnotation typeNameAnnotation = entry.GetAnnotation<SerializationTypeNameAnnotation>();
            if (typeNameAnnotation != null)
            {
                return typeNameAnnotation.TypeName;
            }

            return entry.TypeName;
        }
 /// <summary>
 /// Creates the metadata builder for the given entry. If such a builder is set, asking for payload
 /// metadata properties (like EditLink) of the entry may return a value computed by convention, 
 /// depending on the metadata level and whether the user manually set an edit link or not.
 /// </summary>
 /// <param name="entry">The entry to create the metadata builder for.</param>
 /// <param name="typeContext">The context object to answer basic questions regarding the type of the entry or feed.</param>
 /// <param name="serializationInfo">The serialization info for the entry.</param>
 /// <param name="actualEntityType">The entity type of the entry.</param>
 /// <param name="selectedProperties">The selected properties of this scope.</param>
 /// <param name="isResponse">true if the entity metadata builder to create should be for a response payload; false for a request.</param>
 /// <param name="keyAsSegment">true if keys should go in seperate segments in auto-generated URIs, false if they should go in parentheses.
 /// A null value means the user hasn't specified a preference and we should look for an annotation in the entity container, if available.</param>
 /// <param name="odataUri">The OData Uri.</param>
 /// <returns>The created metadata builder.</returns>
 internal override ODataEntityMetadataBuilder CreateEntityMetadataBuilder(
     ODataEntry entry, 
     IODataFeedAndEntryTypeContext typeContext, 
     ODataFeedAndEntrySerializationInfo serializationInfo, 
     IEdmEntityType actualEntityType, 
     SelectedPropertiesNode selectedProperties, 
     bool isResponse, 
     bool? keyAsSegment,
     ODataUri odataUri)
 {
     return ODataEntityMetadataBuilder.Null;
 }
        public void ValidateEntityTypeShouldReturnEntityTypeOfSet()
        {
            var model = CreateTestModel();
            var peopleSet = model.EntityContainer.FindEntitySet("People");
            var personType = (IEdmEntityType)model.FindDeclaredType("DefaultNamespace.Person");

            var coreWriter = CreateODataWriterCore(ODataFormat.Json, true, model, peopleSet, null, false);

            var entry = new ODataEntry();
            var entityType = coreWriter.ValidateEntityType2(entry);
            entityType.Should().BeSameAs(personType);
        }
        private byte[] ClientWriteAsyncBatchRequest()
        {
            var stream = new MemoryStream();

            IODataRequestMessage requestMessage = new InMemoryMessage { Stream = stream };
            requestMessage.SetHeader("Content-Type", batchContentType);

            using (var messageWriter = new ODataMessageWriter(requestMessage))
            {
                var batchWriter = messageWriter.CreateODataBatchWriter();

                batchWriter.WriteStartBatch();

                // Write a query operation.
                var queryOperationMessage = batchWriter.CreateOperationRequestMessage("GET", new Uri(serviceDocumentUri + "/Customers('ALFKI')"), /*contentId*/ null);

                // Write a changeset with multi update operation.
                batchWriter.WriteStartChangeset();

                // Create a creation operation in the changeset.
                var updateOperationMessage = batchWriter.CreateOperationRequestMessage("POST", new Uri(serviceDocumentUri + "/Customers"), "1");

                // Use a new message writer to write the body of this operation.
                using (var operationMessageWriter = new ODataMessageWriter(updateOperationMessage))
                {
                    var entryWriter = operationMessageWriter.CreateODataEntryWriter();
                    var entry = new ODataEntry() { TypeName = "MyNS.Customer", Properties = new[] { new ODataProperty() { Name = "Id", Value = "AFKIL" }, new ODataProperty() { Name = "Name", Value = "Bob" } } };
                    entryWriter.WriteStart(entry);
                    entryWriter.WriteEnd();
                }

                updateOperationMessage = batchWriter.CreateOperationRequestMessage("PATCH", new Uri(serviceDocumentUri + "/Customers('ALFKI')"), "2");

                using (var operationMessageWriter = new ODataMessageWriter(updateOperationMessage))
                {
                    var entryWriter = operationMessageWriter.CreateODataEntryWriter();
                    var entry = new ODataEntry() { TypeName = "MyNS.Customer", Properties = new[] { new ODataProperty() { Name = "Name", Value = "Jack" } } };
                    entryWriter.WriteStart(entry);
                    entryWriter.WriteEnd();
                }

                batchWriter.WriteEndChangeset();

                // Write a query operation.
                batchWriter.CreateOperationRequestMessage("GET", new Uri(serviceDocumentUri + "/Products"), /*contentId*/ null);

                batchWriter.WriteEndBatch();

                stream.Position = 0;
                return stream.ToArray();
            }
        }
        public AsyncRoundtripJsonLightTests()
        {
            entry = new ODataEntry
            {
                TypeName = "NS.Test",
                Properties = new[]
                {
                    new ODataProperty() { Name = "Id", Value = 1 },
                    new ODataProperty() { Name = "Dummy", Value = "null" }
                }
            };

            responseStream = new MemoryStream();
        }
 public void InjectMetadataBuilderShouldNotSetBuilderOnEntryNamedStreamProperties()
 {
     var entry = new ODataEntry();
     var builder = new TestEntityMetadataBuilder(entry);
     var stream1 = new ODataStreamReferenceValue();
     var stream2 = new ODataStreamReferenceValue();
     entry.Properties = new[]
         {
             new ODataProperty {Name = "Stream1", Value = stream1},
             new ODataProperty {Name = "Stream2", Value = stream2}
         };
     testSubject.InjectMetadataBuilder(entry, builder);
     stream1.GetMetadataBuilder().Should().BeNull();
     stream2.GetMetadataBuilder().Should().BeNull();
 }
 /// <summary>
 /// Creates the metadata builder for the given entry. If such a builder is set, asking for payload
 /// metadata properties (like EditLink) of the entry may return a value computed by convention, 
 /// depending on the metadata level and whether the user manually set an edit link or not.
 /// </summary>
 /// <param name="entry">The entry to create the metadata builder for.</param>
 /// <param name="typeContext">The context object to answer basic questions regarding the type of the entry or feed.</param>
 /// <param name="serializationInfo">The serialization info for the entry.</param>
 /// <param name="actualEntityType">The entity type of the entry.</param>
 /// <param name="selectedProperties">The selected properties of this scope.</param>
 /// <param name="isResponse">true if the entity metadata builder to create should be for a response payload; false for a request.</param>
 /// <param name="keyAsSegment">true if keys should go in separate segments in auto-generated URIs, false if they should go in parentheses.
 /// A null value means the user hasn't specified a preference and we should look for an annotation in the entity container, if available.</param>
 /// <param name="odataUri">The OData Uri.</param>
 /// <returns>The created metadata builder.</returns>
 internal override ODataEntityMetadataBuilder CreateEntityMetadataBuilder(
     ODataEntry entry, 
     IODataFeedAndEntryTypeContext typeContext, 
     ODataFeedAndEntrySerializationInfo serializationInfo, 
     IEdmEntityType actualEntityType, 
     SelectedPropertiesNode selectedProperties, 
     bool isResponse, 
     bool? keyAsSegment,
     ODataUri odataUri)
 {
     // For minimal metadata we don't want to change the metadata builder that's currently on the entry because the entry might come from a JSON light
     // reader and it would contain the metadata builder from the reader.  Until we give the user the ability to choose whether to write what was reported
     // by the reader versus what was on the wire, we no-op here so the writer will just write what's on the OM for now.
     return null;
 }
 public void WriteSingletonInstanceAnnotationTest()
 {
     var entry = new ODataEntry { TypeName = "NS.Web" };
     entry.Properties = new[]
     {
         new ODataProperty {Name = "WebId", Value = 10}
     };
     entry.InstanceAnnotations.Add(new ODataInstanceAnnotation("Is.Singleton", new ODataPrimitiveValue(true)));
     const string expectedPayload = "{" +
         "\"@odata.context\":\"http://odata.org/test/$metadata#MySingleton\"," +
         "\"@odata.type\":\"#NS.Web\"," +
         "\"@odata.id\":\"MySingleton\"," +
         "\"@odata.editLink\":\"MySingleton\"," +
         "\"@Is.Singleton\":true," +
         "\"WebId\":10}";
     this.WriteEntryAndValidatePayloadWithoutModel(entry, expectedPayload);
     this.WriteEntryAndValidatePayloadWithModel(entry, expectedPayload);
 }
 public void WriteSimpleSingletonTest()
 {
     var entry = new ODataEntry { TypeName = "NS.Web" };
     entry.Properties = new[]
     {
         new ODataProperty {Name = "WebId", Value = 10},
         new ODataProperty {Name = "Name", Value = "SingletonWeb" }, 
     };
     const string expectedPayload = "{" +
         "\"@odata.context\":\"http://odata.org/test/$metadata#MySingleton\"," +
         "\"@odata.type\":\"#NS.Web\"," +
         "\"@odata.id\":\"MySingleton\"," +
         "\"@odata.editLink\":\"MySingleton\"," +
         "\"WebId\":10," +
         "\"Name\":\"SingletonWeb\"}";
     this.WriteEntryAndValidatePayloadWithoutModel(entry, expectedPayload);
     this.WriteEntryAndValidatePayloadWithModel(entry, expectedPayload);
 }
        public void WriteEntryWithoutOperation()
        {
            Action<ODataJsonLightOutputContext> test = outputContext =>
            {
                var entry = new ODataEntry();
                entry.Properties = new List<ODataProperty>() { new ODataProperty() { Name = "ID", Value = 1 } };

                var parameterWriter = new ODataJsonLightParameterWriter(outputContext, operation: null);
                parameterWriter.WriteStart();
                var entryWriter = parameterWriter.CreateEntryWriter("entry");
                entryWriter.WriteStart(entry);
                entryWriter.WriteEnd();
                parameterWriter.WriteEnd();
                parameterWriter.Flush();
            };

            WriteAndValidate(test, "{\"entry\":{\"ID\":1}}", writingResponse: false);
        }
        public ODataMissingOperationGeneratorTests()
        {
            this.model = new EdmModel();
            this.container = new EdmEntityContainer("Fake", "Container");
            this.functionEdmMetadata = new EdmFunction("Fake", "FakeFunction", EdmCoreModel.Instance.GetInt32(false), true /*isBound*/, null, true /*isComposable*/);
            this.actionEdmMetadata = new EdmAction("Fake", "FakeAction", EdmCoreModel.Instance.GetInt32(false), true/*isBound*/, null /*entitySetPath*/);
            this.model.AddElement(this.container);
            this.model.AddElement(this.actionEdmMetadata);
            this.model.AddElement(this.functionEdmMetadata);

            this.allOperations = new EdmOperation[] { this.actionEdmMetadata, this.functionEdmMetadata };

            this.odataAction = new ODataAction {Metadata = new Uri("http://temp.org/$metadata#Fake.FakeAction")};
            this.odataFunction = new ODataFunction {Metadata = new Uri("http://temp.org/$metadata#Fake.FakeFunction")};

            this.entry = ReaderUtils.CreateNewEntry();
            this.entityType = new EdmEntityType("TestNamespace", "EntityType");
        }
Example #30
0
        public void Write(Stream stream, IEnumerable<Contact> contacts)
        {
            var message = new ODataStreamResponseMessage(stream);
            var settings = new ODataWriterSettings { Indent = true, CheckCharacters = false, BaseUri = new Uri(this.rootUri), Version = ODataVersion.V3 };
            settings.SetContentType(ODataFormat.Atom);
            var messageWriter = new ODataMessageWriter(message, settings);
            var writerTask = messageWriter.CreateODataFeedWriterAsync();
            writerTask.Wait();
            using (var writer = writerTask.Result)
            {
                writer.WriteStart(
                    new ODataFeed()
                    {
                        Count = contacts.Count(),
                        Id = "Contacts"
                    });

                foreach (var contact in contacts)
                {
                    var entry = new ODataEntry()
                    {
                        Id = string.Format("urn:Contacts(\"{0}\"", contact.ContactId),
                        EditLink = new Uri(string.Format("{1}", this.rootUri, contact.ContactId), UriKind.Relative),
                        TypeName = "Contacts.Contact",
                        Properties =
                            new List<ODataProperty>()
                                    {
                                        new ODataProperty() { Value = contact.ContactId, Name = "ContactId" },
                                        new ODataProperty() { Value = contact.Name, Name = "Name" },
                                        new ODataProperty() { Value = contact.Address, Name = "Address" },
                                        new ODataProperty() { Value = contact.City, Name = "City" },
                                        new ODataProperty() { Value = contact.State, Name = "State" },
                                        new ODataProperty() { Value = contact.Zip, Name = "Zip" },
                                        new ODataProperty() { Value = contact.Email, Name = "Email" },
                                        new ODataProperty() { Value = contact.Twitter, Name = "Twitter" }
                                    }
                    };
                    writer.WriteStart(entry);
                    writer.WriteEnd();
                }
                writer.WriteEnd();
                writer.FlushAsync().Wait();
            }
        }
Example #31
0
        public void ReadOpenCollectionPropertyValue()
        {
            EdmModel              model      = new EdmModel();
            EdmEntityType         entityType = new EdmEntityType("NS", "MyTestEntity", null, false, true);
            EdmStructuralProperty key        = entityType.AddStructuralProperty("LongId", EdmPrimitiveTypeKind.Int64, false);

            entityType.AddKeys(key);

            EdmComplexType complexType = new EdmComplexType("NS", "MyTestComplexType");

            complexType.AddStructuralProperty("CLongId", EdmPrimitiveTypeKind.Int64, false);
            model.AddElement(complexType);

            EdmEntityContainer container = new EdmEntityContainer("EntityNs", "MyContainer_sub");
            EdmEntitySet       entitySet = container.AddEntitySet("MyTestEntitySet", entityType);

            model.AddElement(container);

            const string payload =
                "{" +
                "\"@odata.context\":\"http://www.example.com/$metadata#EntityNs.MyContainer.MyTestEntitySet/$entity\"," +
                "\"@odata.id\":\"http://mytest\"," +
                "\"[email protected]\":\"Collection(Edm.Int32)\"," +
                "\"OpenPrimitiveCollection\":[0,1,2]," +
                "\"[email protected]\":\"Collection(NS.MyTestComplexType)\"," +
                "\"OpenComplexTypeCollection\":[{\"CLongId\":\"1\"},{\"CLongId\":\"1\"}]" +
                "}";

            IEdmModel  mainModel = TestUtils.WrapReferencedModelsToMainModel("EntityNs", "MyContainer", model);
            ODataEntry entry     = null;

            this.ReadEntryPayload(mainModel, payload, entitySet, entityType, reader => { entry = entry ?? reader.Item as ODataEntry; });
            Assert.NotNull(entry);

            var intCollection = entry.Properties.FirstOrDefault(
                s => string.Equals(
                    s.Name,
                    "OpenPrimitiveCollection",
                    StringComparison.OrdinalIgnoreCase)).Value.As <ODataCollectionValue>();
            var list = new List <int?>();

            foreach (var val in intCollection.Items)
            {
                list.Add(val as int?);
            }

            Assert.Equal(0, list[0]);
            Assert.Equal(1, (int)list[1]);
            Assert.Equal(2, (int)list[2]);

            var complexCollection = entry.Properties.FirstOrDefault(
                s => string.Equals(
                    s.Name,
                    "OpenComplexTypeCollection",
                    StringComparison.OrdinalIgnoreCase)).Value.As <ODataCollectionValue>();

            foreach (var val in complexCollection.Items)
            {
                ((ODataComplexValue)val).Properties.FirstOrDefault(s => string.Equals(s.Name, "CLongId", StringComparison.OrdinalIgnoreCase)).Value.ShouldBeEquivalentTo(1L, "value should be in correct type.");
            }
        }
Example #32
0
        public void ReadingTypeDefinitionPayloadWithTypeAnnotationJsonLight()
        {
            EdmModel model = new EdmModel();

            EdmEntityType entityType = new EdmEntityType("NS", "Person");

            entityType.AddStructuralProperty("Id", EdmPrimitiveTypeKind.Int32);

            EdmTypeDefinition          weightType    = new EdmTypeDefinition("NS", "Weight", EdmPrimitiveTypeKind.Int32);
            EdmTypeDefinitionReference weightTypeRef = new EdmTypeDefinitionReference(weightType, false);

            entityType.AddStructuralProperty("Weight", weightTypeRef);
            entityType.AddStructuralProperty("Height", EdmPrimitiveTypeKind.Int32);

            EdmComplexType          complexType    = new EdmComplexType("NS", "OpenAddress");
            EdmComplexTypeReference complexTypeRef = new EdmComplexTypeReference(complexType, true);

            EdmTypeDefinition          addressType    = new EdmTypeDefinition("NS", "Address", EdmPrimitiveTypeKind.String);
            EdmTypeDefinitionReference addressTypeRef = new EdmTypeDefinitionReference(addressType, false);

            complexType.AddStructuralProperty("CountryRegion", addressTypeRef);

            entityType.AddStructuralProperty("Address", complexTypeRef);

            model.AddElement(weightType);
            model.AddElement(addressType);
            model.AddElement(complexType);
            model.AddElement(entityType);

            EdmEntityContainer container = new EdmEntityContainer("EntityNs", "MyContainer");
            EdmEntitySet       entitySet = container.AddEntitySet("People", entityType);

            model.AddElement(container);

            const string payload =
                "{" +
                "\"@odata.context\":\"http://www.example.com/$metadata#EntityNs.MyContainer.People/$entity\"," +
                "\"@odata.id\":\"http://mytest\"," +
                "\"Id\":0," +
                "\"[email protected]\":\"#NS.Weight\"," +
                "\"Weight\":60," +
                "\"[email protected]\":\"#NS.Weight\"," +
                "\"Height\":180," +
                "\"Address\":{\"[email protected]\":\"#NS.Address\",\"CountryRegion\":\"China\"}" +
                "}";

            ODataEntry entry = null;

            this.ReadEntryPayload(model, payload, entitySet, entityType, reader => { entry = entry ?? reader.Item as ODataEntry; });
            Assert.NotNull(entry);

            IList <ODataProperty> propertyList = entry.Properties.ToList();

            propertyList[1].Name.Should().Be("Weight");
            propertyList[1].Value.Should().Be(60);

            propertyList[2].Name.Should().Be("Height");
            propertyList[2].Value.Should().Be(180);

            var address = propertyList[3].Value as ODataComplexValue;

            address.Properties.FirstOrDefault(s => string.Equals(s.Name, "CountryRegion", StringComparison.OrdinalIgnoreCase)).Value.Should().Be("China");
        }
Example #33
0
        public void ReadingComplexInheritInCollection()
        {
            EdmModel              model      = new EdmModel();
            EdmEntityType         entityType = new EdmEntityType("NS", "MyTestEntity");
            EdmStructuralProperty key        = entityType.AddStructuralProperty("LongId", EdmPrimitiveTypeKind.Int64, false);

            entityType.AddKeys(key);

            EdmComplexType complexType = new EdmComplexType("NS", "MyComplexType");

            complexType.AddStructuralProperty("CLongId", EdmPrimitiveTypeKind.Int64, false);

            EdmComplexType derivedComplexType = new EdmComplexType("NS", "MyDerivedComplexType", complexType, false);

            derivedComplexType.AddStructuralProperty("CFloatId", EdmPrimitiveTypeKind.Single, false);

            model.AddElement(complexType);
            model.AddElement(derivedComplexType);

            EdmComplexTypeReference complexTypeRef = new EdmComplexTypeReference(complexType, true);

            entityType.AddStructuralProperty("ComplexCollectionProperty", new EdmCollectionTypeReference(new EdmCollectionType(complexTypeRef)));
            model.AddElement(entityType);

            EdmEntityContainer container = new EdmEntityContainer("EntityNs", "MyContainer_sub");
            EdmEntitySet       entitySet = container.AddEntitySet("MyTestEntitySet", entityType);

            model.AddElement(container);

            const string payload =
                "{" +
                "\"@odata.context\":\"http://www.example.com/$metadata#EntityNs.MyContainer.MyTestEntitySet/$entity\"," +
                "\"@odata.id\":\"http://MyTestEntity\"," +
                "\"LongId\":\"12\"," +
                "\"ComplexCollectionProperty\":[{\"@odata.type\":\"#NS.MyDerivedComplexType\",\"CLongId\":\"1\",\"CFloatId\":1},{\"CLongId\":\"1\"},{\"CLongId\":\"1\",\"CFloatId\":1,\"@odata.type\":\"#NS.MyDerivedComplexType\"}]" +
                "}";

            IEdmModel  mainModel = TestUtils.WrapReferencedModelsToMainModel("EntityNs", "MyContainer", model);
            ODataEntry entry     = null;

            this.ReadEntryPayload(mainModel, payload, entitySet, entityType, reader => { entry = entry ?? reader.Item as ODataEntry; });
            Assert.NotNull(entry);

            var intCollection = entry.Properties.FirstOrDefault(
                s => string.Equals(
                    s.Name,
                    "ComplexCollectionProperty",
                    StringComparison.OrdinalIgnoreCase)).Value.As <ODataCollectionValue>();
            var list = new List <int?>();

            Boolean derived = true;

            foreach (var val in intCollection.Items)
            {
                var complextProperty = val as ODataComplexValue;
                complextProperty.Properties.FirstOrDefault(s => string.Equals(s.Name, "CLongId", StringComparison.OrdinalIgnoreCase)).Value.ShouldBeEquivalentTo(1L, "value should be in correct type.");
                if (derived)
                {
                    complextProperty.Properties.FirstOrDefault(s => string.Equals(s.Name, "CFloatId", StringComparison.OrdinalIgnoreCase)).Value.ShouldBeEquivalentTo(1.0F, "value should be in correct type.");
                }
                derived = false;
            }
        }
Example #34
0
        public void ReadingPayloadInt64SingleDoubleDecimalWithoutSuffix()
        {
            EdmModel              model      = new EdmModel();
            EdmEntityType         entityType = new EdmEntityType("NS", "MyTestEntity");
            EdmStructuralProperty key        = entityType.AddStructuralProperty("LongId", EdmPrimitiveTypeKind.Int64, false);

            entityType.AddKeys(key);
            entityType.AddStructuralProperty("FloatId", EdmPrimitiveTypeKind.Single, false);
            entityType.AddStructuralProperty("DoubleId", EdmPrimitiveTypeKind.Double, false);
            entityType.AddStructuralProperty("DecimalId", EdmPrimitiveTypeKind.Decimal, false);

            EdmComplexType complexType = new EdmComplexType("NS", "MyTestComplexType");

            complexType.AddStructuralProperty("CLongId", EdmPrimitiveTypeKind.Int64, false);
            complexType.AddStructuralProperty("CFloatId", EdmPrimitiveTypeKind.Single, false);
            complexType.AddStructuralProperty("CDoubleId", EdmPrimitiveTypeKind.Double, false);
            complexType.AddStructuralProperty("CDecimalId", EdmPrimitiveTypeKind.Decimal, false);
            model.AddElement(complexType);
            EdmComplexTypeReference complexTypeRef = new EdmComplexTypeReference(complexType, true);

            entityType.AddStructuralProperty("ComplexProperty", complexTypeRef);

            entityType.AddStructuralProperty("LongNumbers", new EdmCollectionTypeReference(new EdmCollectionType(EdmCoreModel.Instance.GetInt64(false))));
            entityType.AddStructuralProperty("FloatNumbers", new EdmCollectionTypeReference(new EdmCollectionType(EdmCoreModel.Instance.GetSingle(false))));
            entityType.AddStructuralProperty("DoubleNumbers", new EdmCollectionTypeReference(new EdmCollectionType(EdmCoreModel.Instance.GetDouble(false))));
            entityType.AddStructuralProperty("DecimalNumbers", new EdmCollectionTypeReference(new EdmCollectionType(EdmCoreModel.Instance.GetDecimal(false))));
            model.AddElement(entityType);

            EdmEntityContainer container = new EdmEntityContainer("EntityNs", "MyContainer_sub");
            EdmEntitySet       entitySet = container.AddEntitySet("MyTestEntitySet", entityType);

            model.AddElement(container);

            const string payload =
                "{" +
                "\"@odata.context\":\"http://www.example.com/$metadata#EntityNs.MyContainer.MyTestEntitySet/$entity\"," +
                "\"@odata.id\":\"http://MyTestEntity\"," +
                "\"LongId\":\"12\"," +
                "\"FloatId\":34.98," +
                "\"DoubleId\":56.01," +
                "\"DecimalId\":\"78.62\"," +
                "\"LongNumbers\":[\"-1\",\"-9223372036854775808\",\"9223372036854775807\"]," +
                "\"FloatNumbers\":[-1,-3.40282347E+38,3.40282347E+38,\"INF\",\"-INF\",\"NaN\"]," +
                "\"DoubleNumbers\":[1.0,-1.7976931348623157E+308,1.7976931348623157E+308,\"INF\",\"-INF\",\"NaN\"]," +
                "\"DecimalNumbers\":[\"0\",\"-79228162514264337593543950335\",\"79228162514264337593543950335\"]," +
                "\"ComplexProperty\":{\"CLongId\":\"1\",\"CFloatId\":1,\"CDoubleId\":-1.0,\"CDecimalId\":\"0.0\"}" +
                "}";

            IEdmModel  mainModel = TestUtils.WrapReferencedModelsToMainModel("EntityNs", "MyContainer", model);
            ODataEntry entry     = null;

            this.ReadEntryPayload(mainModel, payload, entitySet, entityType, reader => { entry = entry ?? reader.Item as ODataEntry; });
            Assert.NotNull(entry);
            entry.Properties.FirstOrDefault(s => string.Equals(s.Name, "LongId", StringComparison.OrdinalIgnoreCase)).Value.ShouldBeEquivalentTo(12L, "value should be in correct type.");
            entry.Properties.FirstOrDefault(s => string.Equals(s.Name, "FloatId", StringComparison.OrdinalIgnoreCase)).Value.ShouldBeEquivalentTo(34.98f, "value should be in correct type.");
            entry.Properties.FirstOrDefault(s => string.Equals(s.Name, "DoubleId", StringComparison.OrdinalIgnoreCase)).Value.ShouldBeEquivalentTo(56.01d, "value should be in correct type.");
            entry.Properties.FirstOrDefault(s => string.Equals(s.Name, "DecimalId", StringComparison.OrdinalIgnoreCase)).Value.ShouldBeEquivalentTo(78.62m, "value should be in correct type.");

            var complextProperty = entry.Properties.FirstOrDefault(s => string.Equals(s.Name, "ComplexProperty", StringComparison.OrdinalIgnoreCase)).Value as ODataComplexValue;

            complextProperty.Properties.FirstOrDefault(s => string.Equals(s.Name, "CLongId", StringComparison.OrdinalIgnoreCase)).Value.ShouldBeEquivalentTo(1L, "value should be in correct type.");
            complextProperty.Properties.FirstOrDefault(s => string.Equals(s.Name, "CFloatId", StringComparison.OrdinalIgnoreCase)).Value.ShouldBeEquivalentTo(1.0F, "value should be in correct type.");
            complextProperty.Properties.FirstOrDefault(s => string.Equals(s.Name, "CDoubleId", StringComparison.OrdinalIgnoreCase)).Value.ShouldBeEquivalentTo(-1.0D, "value should be in correct type.");
            complextProperty.Properties.FirstOrDefault(s => string.Equals(s.Name, "CDecimalId", StringComparison.OrdinalIgnoreCase)).Value.ShouldBeEquivalentTo(0.0M, "value should be in correct type.");

            var longCollection = entry.Properties.FirstOrDefault(s => string.Equals(s.Name, "LongNumbers", StringComparison.OrdinalIgnoreCase)).Value.As <ODataCollectionValue>();

            longCollection.Items.Should().Contain(-1L).And.Contain(long.MinValue).And.Contain(long.MaxValue);
            var floatCollection = entry.Properties.FirstOrDefault(s => string.Equals(s.Name, "FloatNumbers", StringComparison.OrdinalIgnoreCase)).Value.As <ODataCollectionValue>();

            floatCollection.Items.Should().Contain(-1F).And.Contain(float.MinValue).And.Contain(float.MaxValue).And.Contain(float.PositiveInfinity).And.Contain(float.NegativeInfinity).And.Contain(float.NaN);
            var doubleCollection = entry.Properties.FirstOrDefault(s => string.Equals(s.Name, "DoubleNumbers", StringComparison.OrdinalIgnoreCase)).Value.As <ODataCollectionValue>();

            doubleCollection.Items.Should().Contain(1.0D).And.Contain(double.MinValue).And.Contain(double.MaxValue).And.Contain(double.PositiveInfinity).And.Contain(double.NegativeInfinity).And.Contain(double.NaN);
            var decimalCollection = entry.Properties.FirstOrDefault(s => string.Equals(s.Name, "DecimalNumbers", StringComparison.OrdinalIgnoreCase)).Value.As <ODataCollectionValue>();

            decimalCollection.Items.Should().Contain(0M).And.Contain(decimal.MinValue).And.Contain(decimal.MaxValue);
        }