public void PropertyGettersAndSettersTest() { ODataEntityReferenceLink link1 = new ODataEntityReferenceLink { Url = new Uri("http://odatalib.org/entityreferencelink1") }; ODataEntityReferenceLink link2 = new ODataEntityReferenceLink { Url = new Uri("http://odatalib.org/entityreferencelink2") }; ODataEntityReferenceLink link3 = new ODataEntityReferenceLink { Url = new Uri("http://odatalib.org/entityreferencelink3") }; ODataEntityReferenceLink[] links = new ODataEntityReferenceLink[] { link1, link2, link3 }; int inlineCount = 3; Uri nextLink = new Uri("http://odatalib.org/nextlink"); ODataEntityReferenceLinks entityReferenceLinks = new ODataEntityReferenceLinks() { Count = inlineCount, NextPageLink = nextLink, Links = links, }; this.Assert.AreEqual(inlineCount, entityReferenceLinks.Count, "Expected equal values for property 'Count'."); this.Assert.AreEqual(nextLink, entityReferenceLinks.NextPageLink, "Expected reference equal values for property 'NextPageLink'."); VerificationUtils.VerifyEnumerationsAreEqual( links, entityReferenceLinks.Links, (first, second, assert) => assert.AreSame(first, second, "Expected reference equal values for entity reference links."), (link) => link.Url.OriginalString, this.Assert); }
public void DefaultValuesTest() { ODataEntityReferenceLinks entityReferenceLinks = new ODataEntityReferenceLinks(); this.Assert.IsNull(entityReferenceLinks.Count, "Expected null default value for property 'Count'."); this.Assert.IsNull(entityReferenceLinks.NextPageLink, "Expected null default value for property 'NextPageLink'."); this.Assert.IsNull(entityReferenceLinks.Links, "Expected null default value for property 'Links'."); }
/// <inheridoc /> public override void WriteObject(object graph, Type type, ODataMessageWriter messageWriter, ODataSerializerContext writeContext) { if (messageWriter == null) { throw Error.ArgumentNull("messageWriter"); } if (writeContext == null) { throw Error.ArgumentNull("writeContext"); } if (graph != null) { ODataEntityReferenceLinks entityReferenceLinks = graph as ODataEntityReferenceLinks; if (entityReferenceLinks == null) { IEnumerable<Uri> uris = graph as IEnumerable<Uri>; if (uris == null) { throw new SerializationException(Error.Format(SRResources.CannotWriteType, GetType().Name, graph.GetType().FullName)); } entityReferenceLinks = new ODataEntityReferenceLinks { Links = uris.Select(uri => new ODataEntityReferenceLink { Url = uri }) }; } messageWriter.WriteEntityReferenceLinks(entityReferenceLinks); } }
public void PropertySettersNullTest() { ODataEntityReferenceLinks entityReferenceLinks = new ODataEntityReferenceLinks() { Count = null, NextPageLink = null, Links = null, }; this.Assert.IsNull(entityReferenceLinks.Count, "Expected null default value for property 'Count'."); this.Assert.IsNull(entityReferenceLinks.NextPageLink, "Expected null default value for property 'NextPageLink'."); this.Assert.IsNull(entityReferenceLinks.Links, "Expected null default value for property 'Links'."); }
public void ShouldBeAbleToSetLinksReferenceLinks() { ODataEntityReferenceLink link = new ODataEntityReferenceLink { Url = new Uri("http://host/Customers(1)") }; ODataEntityReferenceLinks referencelinks = new ODataEntityReferenceLinks() { Links = new[] { link } }; referencelinks.Should().NotBeNull(); referencelinks.Links.Should().NotBeNull(); referencelinks.Links.Count().Should().Be(1); }
/// <summary> /// Visits an entity reference links item. /// </summary> /// <param name="entityReferenceLinks">The entity reference links item to visit.</param> /// <returns>An ODataPayloadElement representing the entity reference links.</returns> protected override ODataPayloadElement VisitEntityReferenceLinks(ODataEntityReferenceLinks entityReferenceLinks) { ExceptionUtilities.CheckArgumentNotNull(entityReferenceLinks, "entityReferenceLinks"); LinkCollection linkCollection = (LinkCollection)base.VisitEntityReferenceLinks(entityReferenceLinks); AtomLinkMetadata atomMetadata = entityReferenceLinks.GetAnnotation<AtomLinkMetadata>(); if (atomMetadata != null) { ConvertAtomLinkMetadata(atomMetadata, linkCollection); } return linkCollection; }
/// <inheridoc /> public override void WriteObject(object graph, Type type, ODataMessageWriter messageWriter, ODataSerializerContext writeContext) { if (messageWriter == null) { throw Error.ArgumentNull("messageWriter"); } if (writeContext == null) { throw Error.ArgumentNull("writeContext"); } IEdmEntitySet entitySet = writeContext.EntitySet; if (entitySet == null) { throw new SerializationException(SRResources.EntitySetMissingDuringSerialization); } if (writeContext.Path == null) { throw new SerializationException(SRResources.ODataPathMissing); } IEdmNavigationProperty navigationProperty = writeContext.Path.GetNavigationProperty(); if (navigationProperty == null) { throw new SerializationException(SRResources.NavigationPropertyMissingDuringSerialization); } if (graph != null) { ODataEntityReferenceLinks entityReferenceLinks = graph as ODataEntityReferenceLinks; if (entityReferenceLinks == null) { IEnumerable<Uri> uris = graph as IEnumerable<Uri>; if (uris == null) { throw new SerializationException(Error.Format(SRResources.CannotWriteType, GetType().Name, graph.GetType().FullName)); } entityReferenceLinks = new ODataEntityReferenceLinks { Links = uris.Select(uri => new ODataEntityReferenceLink { Url = uri }) }; } messageWriter.WriteEntityReferenceLinks(entityReferenceLinks, entitySet, navigationProperty); } }
/// <inheridoc /> public override Task WriteObjectAsync(object graph, Type type, ODataMessageWriter messageWriter, ODataSerializerContext writeContext) { if (messageWriter == null) { throw Error.ArgumentNull("messageWriter"); } if (writeContext == null) { throw Error.ArgumentNull("writeContext"); } if (graph != null) { ODataEntityReferenceLinks entityReferenceLinks = graph as ODataEntityReferenceLinks; if (entityReferenceLinks == null) { IEnumerable<Uri> uris = graph as IEnumerable<Uri>; if (uris == null) { throw new SerializationException(Error.Format(SRResources.CannotWriteType, GetType().Name, graph.GetType().FullName)); } entityReferenceLinks = new ODataEntityReferenceLinks { Links = uris.Select(uri => new ODataEntityReferenceLink { Url = uri }) }; if (writeContext.Request != null) { entityReferenceLinks.Count = writeContext.Request.ODataProperties().TotalCount; } } messageWriter.WriteEntityReferenceLinks(entityReferenceLinks); } return Task.FromResult(true); }
private static void WriteTopLevelEntityReferenceLinks() { Console.WriteLine("WriteTopLevelEntityReferenceLinks"); var msg = ODataSamplesUtil.CreateMessage(); msg.PreferenceAppliedHeader().AnnotationFilter = "*"; var settings = new ODataMessageWriterSettings(BaseSettings) { ODataUri = new ODataUri() { ServiceRoot = new Uri("http://demo/odata.svc/") }, }; var link1 = new ODataEntityReferenceLink() { Url = new Uri("http://demo/odata.svc/People(3)") }; var link2 = new ODataEntityReferenceLink() { Url = new Uri("http://demo/odata.svc/People(4)") }; var links = new ODataEntityReferenceLinks() { Links = new[] { link1, link2 } }; using (var omw = new ODataMessageWriter((IODataResponseMessage)msg, settings, ExtModel.Model)) { omw.WriteEntityReferenceLinks(links); } Console.WriteLine(ODataSamplesUtil.MessageToString(msg)); }
public void UseWriterOnceTests() { Uri baseUri = new Uri("http://www.odata.org/"); ODataError error = new ODataError(); ODataEntityReferenceLink link = new ODataEntityReferenceLink { Url = new Uri("http://www.odata.org") }; ODataEntityReferenceLinks links = new ODataEntityReferenceLinks { Links = new ODataEntityReferenceLink[] { link, link, link }, }; ODataServiceDocument serviceDocument = ObjectModelUtils.CreateDefaultWorkspace(); ODataProperty property = new ODataProperty() { Name = "FirstName", Value = "Bill" }; object rawValue = 42; // TODO: add WriteMetadataDocumentAsync() here once implemented. UseWriterOnceTestCase[] messageWriterOperations = new UseWriterOnceTestCase[] { new UseWriterOnceTestCase { WriterMethod = (messageWriter) => messageWriter.CreateODataCollectionWriter() }, new UseWriterOnceTestCase { WriterMethod = (messageWriter) => messageWriter.CreateODataEntryWriter() }, new UseWriterOnceTestCase { WriterMethod = (messageWriter) => messageWriter.CreateODataEntryWriter() }, new UseWriterOnceTestCase { WriterMethod = (messageWriter) => messageWriter.WriteError(error, false), IsWriteError = true }, new UseWriterOnceTestCase { WriterMethod = (messageWriter) => messageWriter.WriteEntityReferenceLink(link) }, new UseWriterOnceTestCase { WriterMethod = (messageWriter) => messageWriter.WriteEntityReferenceLinks(links) }, new UseWriterOnceTestCase { WriterMethod = (messageWriter) => messageWriter.WriteProperty(property) }, new UseWriterOnceTestCase { WriterMethod = (messageWriter) => messageWriter.WriteServiceDocument(serviceDocument) }, new UseWriterOnceTestCase { WriterMethod = (messageWriter) => messageWriter.WriteValue(rawValue), IsWriteValue = true }, }; var testCases = messageWriterOperations.Combinations(2); this.CombinatorialEngineProvider.RunCombinations( testCases, this.WriterTestConfigurationProvider.AtomFormatConfigurations.Where(tc => !tc.IsRequest), (testCase, testConfiguration) => { ODataMessageWriterSettings settingsWithBaseUri = testConfiguration.MessageWriterSettings.Clone(); settingsWithBaseUri.PayloadBaseUri = baseUri; settingsWithBaseUri.SetServiceDocumentUri(ServiceDocumentUri); using (var memoryStream = new TestStream()) { TestMessage testMessage; using (ODataMessageWriterTestWrapper messageWriter = TestWriterUtils.CreateMessageWriter(memoryStream, testConfiguration, this.Assert, out testMessage, settingsWithBaseUri)) { testCase[0].WriterMethod(messageWriter); string expectedException = "The ODataMessageWriter has already been used to write a message payload. An ODataMessageWriter can only be used once to write a payload for a given message."; if (testCase[0].IsWriteValue && testCase[1].IsWriteError) { expectedException = "The WriteError method or the WriteErrorAsync method on ODataMessageWriter cannot be called after the WriteValue method or the WriteValueAsync method is called. In OData, writing an in-stream error for raw values is not supported."; } else if (!testCase[0].IsWriteError && testCase[1].IsWriteError) { expectedException = null; } TestExceptionUtils.ExpectedException<ODataException>(this.Assert, () => testCase[1].WriterMethod(messageWriter), expectedException); } } }); }
public void ShouldReadForEntityReferenceLinksWithSingleLink() { ODataEntityReferenceLink link = new ODataEntityReferenceLink { Url = new Uri("http://host/Customers(1)") }; link.InstanceAnnotations.Add(new ODataInstanceAnnotation("Is.New", new ODataPrimitiveValue(true))); ODataEntityReferenceLinks referencelinks = new ODataEntityReferenceLinks() { Links = new[] { link } }; var deserializer = this.CreateJsonLightEntryAndFeedDeserializer("{\"@odata.context\":\"http://odata.org/test/$metadata#Collection($ref)\",\"value\":[{\"@odata.id\":\"http://host/Customers(1)\",\"@Is.New\":true}]}"); ODataEntityReferenceLinks links = deserializer.ReadEntityReferenceLinks(); SameEntityReferenceLinks(referencelinks, links); }
public void ShouldWriteForEntityReferenceLinksWithSingleLink() { ODataEntityReferenceLink link = new ODataEntityReferenceLink { Url = new Uri("http://host/Customers(1)") }; link.InstanceAnnotations.Add(new ODataInstanceAnnotation("Is.New", new ODataPrimitiveValue(true))); ODataEntityReferenceLinks referencelinks = new ODataEntityReferenceLinks() { Links = new[] { link } }; string expectedPayload = "{\"@odata.context\":\"http://odata.org/test/$metadata#Collection($ref)\",\"value\":[{\"@odata.id\":\"http://host/Customers(1)\",\"@Is.New\":true}]}"; WriteAndValidate(referencelinks, expectedPayload, writingResponse: false); WriteAndValidate(referencelinks, expectedPayload, writingResponse: true); }
public override void Process(IODataRequestMessage requestMessage, IODataResponseMessage responseMessage) { if (this.TryDispatch(requestMessage, responseMessage)) { return; } this.QueryContext.InitializeServerDrivenPaging(this.PreferenceContext); this.QueryContext.InitializeTrackingChanges(this.PreferenceContext); object queryResults = this.QueryContext.ResolveQuery(this.DataSource); if (queryResults == null) { // For individual property or $value if (this.QueryContext.Target.Property != null) { // Protocol 9.1.4 Response Code 204 No Content // A request returns 204 No Content if the requested resource has the null value, // or if the service applies a return=minimal preference. In this case, the response body MUST be empty. ResponseWriter.WriteEmptyResponse(responseMessage); return; } else { throw Utility.BuildException(HttpStatusCode.NotFound); } } // Handle the prefer of "odata.include-annotations", including it in response header if (!string.IsNullOrEmpty(this.PreferenceContext.IncludeAnnotations)) { responseMessage.AddPreferenceApplied(string.Format("{0}={1}", ServiceConstants.Preference_IncludeAnnotations, this.PreferenceContext.IncludeAnnotations)); } if (this.PreferenceContext.MaxPageSize.HasValue) { responseMessage.AddPreferenceApplied(string.Format("{0}={1}", ServiceConstants.Preference_MaxPageSize, this.QueryContext.appliedPageSize.Value)); } if (this.PreferenceContext.TrackingChanges) { responseMessage.AddPreferenceApplied(ServiceConstants.Preference_TrackChanging); } responseMessage.SetStatusCode(HttpStatusCode.OK); using (var messageWriter = this.CreateMessageWriter(responseMessage)) { IEdmNavigationSource navigationSource = this.QueryContext.Target.NavigationSource; IEnumerable iEnumerableResults = queryResults as IEnumerable; if (this.QueryContext.Target.IsReference && this.QueryContext.Target.TypeKind == EdmTypeKind.Collection) { // Query a $ref collection IList<ODataEntityReferenceLink> links = new List<ODataEntityReferenceLink>(); foreach (var iEnumerableResult in iEnumerableResults) { var link = new ODataEntityReferenceLink { Url = Utility.BuildLocationUri(this.QueryContext, iEnumerableResult), }; links.Add(link); } ODataEntityReferenceLinks linksCollection = new ODataEntityReferenceLinks() { Links = links, NextPageLink = this.QueryContext.NextLink }; linksCollection.InstanceAnnotations.Add(new ODataInstanceAnnotation("Links.Annotation", new ODataPrimitiveValue(true))); messageWriter.WriteEntityReferenceLinks(linksCollection); } else if (this.QueryContext.Target.IsReference && this.QueryContext.Target.TypeKind == EdmTypeKind.Entity) { // Query a $ref var link = new ODataEntityReferenceLink { Url = Utility.BuildLocationUri(this.QueryContext, queryResults), }; link.InstanceAnnotations.Add(new ODataInstanceAnnotation("Link.Annotation", new ODataPrimitiveValue(true))); messageWriter.WriteEntityReferenceLink(link); } else if (this.QueryContext.Target.NavigationSource != null && this.QueryContext.Target.TypeKind == EdmTypeKind.Collection) { // Query a feed IEdmEntitySetBase entitySet = navigationSource as IEdmEntitySetBase; IEdmEntityType entityType = this.QueryContext.Target.ElementType as IEdmEntityType; if (entitySet == null || entityType == null) { throw new InvalidOperationException("Invalid target when query feed."); } ODataWriter resultWriter = messageWriter.CreateODataFeedWriter(entitySet, entityType); ResponseWriter.WriteFeed(resultWriter, entityType, iEnumerableResults, entitySet, ODataVersion.V4, this.QueryContext.QuerySelectExpandClause, this.QueryContext.TotalCount, this.QueryContext.DeltaLink, this.QueryContext.NextLink, this.RequestHeaders); resultWriter.Flush(); } else if (this.QueryContext.Target.NavigationSource != null && this.QueryContext.Target.TypeKind == EdmTypeKind.Entity) { var currentETag = Utility.GetETagValue(queryResults); // if the current entity has ETag field if (currentETag != null) { string requestETag; if (Utility.TryGetIfNoneMatch(this.RequestHeaders, out requestETag) && (requestETag == ServiceConstants.ETagValueAsterisk || requestETag == currentETag)) { ResponseWriter.WriteEmptyResponse(responseMessage, HttpStatusCode.NotModified); return; } responseMessage.SetHeader(ServiceConstants.HttpHeaders.ETag, currentETag); } // Query a single entity IEdmEntityType entityType = this.QueryContext.Target.Type as IEdmEntityType; ODataWriter resultWriter = messageWriter.CreateODataEntryWriter(navigationSource, entityType); ResponseWriter.WriteEntry(resultWriter, queryResults, navigationSource, ODataVersion.V4, this.QueryContext.QuerySelectExpandClause, this.RequestHeaders); resultWriter.Flush(); } else if (this.QueryContext.Target.Property != null && !this.QueryContext.Target.IsRawValue) { // Query a individual property ODataProperty property = ODataObjectModelConverter.CreateODataProperty(queryResults, this.QueryContext.Target.Property.Name); messageWriter.WriteProperty(property); } else if (this.QueryContext.Target.IsRawValue) { // Query a $value or $count var propertyValue = ODataObjectModelConverter.CreateODataValue(queryResults); messageWriter.WriteValue(propertyValue); } else { throw Utility.BuildException(HttpStatusCode.NotImplemented); } } }
/// <summary> /// Asynchronously writes the result of a $ref query as the message payload. /// </summary> /// <param name="links">The entity reference links to write as message payload.</param> /// <returns>A task representing the asynchronous writing of the entity reference links.</returns> /// <remarks>It is the responsibility of this method to flush the output before the task finishes.</remarks> internal virtual Task WriteEntityReferenceLinksAsync(ODataEntityReferenceLinks links) { throw this.CreatePayloadKindNotSupportedException(ODataPayloadKind.EntityReferenceLinks); }
/// <summary> /// Visits an entity reference link collection. /// </summary> /// <param name="entityReferenceLinks">The entity reference link collection to visit.</param> protected override void VisitEntityReferenceLinks(ODataEntityReferenceLinks entityReferenceLinks) { this.ValidateUri(entityReferenceLinks.NextPageLink); base.VisitEntityReferenceLinks(entityReferenceLinks); }
public void AsyncShouldWriteContextUriForEntityReferenceLinksRequest() { ODataEntityReferenceLink referenceLink = new ODataEntityReferenceLink { Url = new Uri("http://host/Orders(1)") }; ODataEntityReferenceLinks referenceLinks = new ODataEntityReferenceLinks { Links = new[] { referenceLink } }; WriteAndValidate(outputContext => outputContext.WriteEntityReferenceLinksAsync(referenceLinks).Wait(), "{\"@odata.context\":\"http://odata.org/test/$metadata#Collection($ref)\",\"value\":[{\"@odata.id\":\"http://host/Orders(1)\"}]}", writingResponse: false, synchronous: false); WriteAndValidate(outputContext => outputContext.WriteEntityReferenceLinksAsync(referenceLinks).Wait(), "{\"@odata.context\":\"http://odata.org/test/$metadata#Collection($ref)\",\"value\":[{\"@odata.id\":\"http://host/Orders(1)\"}]}", writingResponse: true, synchronous: false); }
public void WriteTopLevelEntityReferenceLinks() { ODataEntityReferenceLink link1 = new ODataEntityReferenceLink { Url = new Uri("http://host/Customers(1)") }; link1.InstanceAnnotations.Add(new ODataInstanceAnnotation("Is.New", new ODataPrimitiveValue(true))); ODataEntityReferenceLink link2 = new ODataEntityReferenceLink { Url = new Uri("http://host/Customers(2)") }; link2.InstanceAnnotations.Add(new ODataInstanceAnnotation("TestNamespace.unknown", new ODataPrimitiveValue(123))); link2.InstanceAnnotations.Add(new ODataInstanceAnnotation("custom.annotation", new ODataPrimitiveValue(456))); ODataEntityReferenceLinks referencelinks = new ODataEntityReferenceLinks() { Links = new[] { link1, link2 } }; var writerSettings = new ODataMessageWriterSettings { DisableMessageStreamDisposal = true }; writerSettings.SetContentType(ODataFormat.Json); writerSettings.SetServiceDocumentUri(new Uri("http://odata.org/test")); MemoryStream stream = new MemoryStream(); IODataResponseMessage requestMessageToWrite = new InMemoryMessage { StatusCode = 200, Stream = stream }; requestMessageToWrite.PreferenceAppliedHeader().AnnotationFilter = "*"; using (var messageWriter = new ODataMessageWriter(requestMessageToWrite, writerSettings, EdmModel)) { messageWriter.WriteEntityReferenceLinks(referencelinks); } stream.Position = 0; string payload = (new StreamReader(stream)).ReadToEnd(); string expectedPayload = "{\"@odata.context\":\"http://odata.org/test/$metadata#Collection($ref)\",\"value\":[{\"@odata.id\":\"http://host/Customers(1)\",\"@Is.New\":true},{\"@odata.id\":\"http://host/Customers(2)\",\"@TestNamespace.unknown\":123,\"@custom.annotation\":456}]}"; Assert.AreEqual(expectedPayload, payload); }
private static void SameEntityReferenceLinks(ODataEntityReferenceLinks links1, ODataEntityReferenceLinks links2) { links1.Should().NotBeNull(); links2.Should().NotBeNull(); links1.Links.Should().NotBeNull(); links2.Links.Should().NotBeNull(); links1.Links.Count().Should().Equals(links2.Links.Count()); for (var i = 0; i < links1.Links.Count(); ++i) { SameEntityReferenceLink(links1.Links.ElementAt(i), links2.Links.ElementAt(i)); } SameInstanceAnnotations(links1.InstanceAnnotations, links2.InstanceAnnotations); }
public void ShouldWriteAndReadForEntityReferenceLinksWithReferenceLinksAnnotation() { ODataEntityReferenceLink link1 = new ODataEntityReferenceLink { Url = new Uri("http://host/Customers(1)") }; link1.InstanceAnnotations.Add(new ODataInstanceAnnotation("Is.New", new ODataPrimitiveValue(true))); ODataEntityReferenceLink link2 = new ODataEntityReferenceLink { Url = new Uri("http://host/Customers(2)") }; link2.InstanceAnnotations.Add(new ODataInstanceAnnotation("TestNamespace.unknown", new ODataPrimitiveValue(123))); link2.InstanceAnnotations.Add(new ODataInstanceAnnotation("custom.annotation", new ODataPrimitiveValue(456))); ODataEntityReferenceLinks referencelinks = new ODataEntityReferenceLinks() { Links = new[] { link1, link2 } }; referencelinks.InstanceAnnotations.Add(new ODataInstanceAnnotation("TestNamespace.name", new ODataPrimitiveValue(321))); referencelinks.InstanceAnnotations.Add(new ODataInstanceAnnotation("custom.name", new ODataPrimitiveValue(654))); string midplayoad = WriteToString(referencelinks, writingResponse: false); var deserializer = this.CreateJsonLightEntryAndFeedDeserializer(midplayoad); ODataEntityReferenceLinks links = deserializer.ReadEntityReferenceLinks(); SameEntityReferenceLinks(referencelinks, links); }
public void WriteForEntityReferenceLinksWithDuplicateAnnotationNameShouldThrow() { ODataEntityReferenceLink link1 = new ODataEntityReferenceLink { Url = new Uri("http://host/Customers(1)") }; link1.InstanceAnnotations.Add(new ODataInstanceAnnotation("Is.New", new ODataPrimitiveValue(true))); ODataEntityReferenceLink link2 = new ODataEntityReferenceLink { Url = new Uri("http://host/Customers(2)") }; link2.InstanceAnnotations.Add(new ODataInstanceAnnotation("TestNamespace.unknown", new ODataPrimitiveValue(123))); link2.InstanceAnnotations.Add(new ODataInstanceAnnotation("custom.annotation", new ODataPrimitiveValue(456))); ODataEntityReferenceLinks referencelinks = new ODataEntityReferenceLinks() { Links = new[] { link1, link2 } }; referencelinks.InstanceAnnotations.Add(new ODataInstanceAnnotation("TestNamespace.name", new ODataPrimitiveValue(321))); referencelinks.InstanceAnnotations.Add(new ODataInstanceAnnotation("TestNamespace.name", new ODataPrimitiveValue(654))); string expectedPayload = "{\"@odata.context\":\"http://odata.org/test/$metadata#Collection($ref)\",\"@TestNamespace.name\":321,\"@TestNamespace.name\":654,\"value\":[{\"@odata.id\":\"http://host/Customers(1)\",\"@Is.New\":true},{\"@odata.id\":\"http://host/Customers(2)\",\"@TestNamespace.unknown\":123,\"@custom.annotation\":456}]}"; Action writeResult = () => WriteAndValidate(referencelinks, expectedPayload, writingResponse: false); writeResult.ShouldThrow<ODataException>().WithMessage(ODataErrorStrings.JsonLightInstanceAnnotationWriter_DuplicateAnnotationNameInCollection("TestNamespace.name")); writeResult = () => WriteAndValidate(referencelinks, expectedPayload, writingResponse: true); writeResult.ShouldThrow<ODataException>().WithMessage(ODataErrorStrings.JsonLightInstanceAnnotationWriter_DuplicateAnnotationNameInCollection("TestNamespace.name")); }
public void ShouldReadForEntityReferenceLinksWithReferenceLinksAnnotations() { ODataEntityReferenceLink link1 = new ODataEntityReferenceLink { Url = new Uri("http://host/Customers(1)") }; link1.InstanceAnnotations.Add(new ODataInstanceAnnotation("Is.New", new ODataPrimitiveValue(true))); ODataEntityReferenceLink link2 = new ODataEntityReferenceLink { Url = new Uri("http://host/Customers(2)") }; link2.InstanceAnnotations.Add(new ODataInstanceAnnotation("TestNamespace.unknown", new ODataPrimitiveValue(123))); link2.InstanceAnnotations.Add(new ODataInstanceAnnotation("custom.annotation", new ODataPrimitiveValue(456))); ODataEntityReferenceLinks referencelinks = new ODataEntityReferenceLinks() { Links = new[] { link1, link2 } }; referencelinks.InstanceAnnotations.Add(new ODataInstanceAnnotation("TestNamespace.name", new ODataPrimitiveValue(321))); referencelinks.InstanceAnnotations.Add(new ODataInstanceAnnotation("custom.name", new ODataPrimitiveValue(654))); string payload = "{\"@odata.context\":\"http://odata.org/test/$metadata#Collection($ref)\",\"@TestNamespace.name\":321,\"value\":[{\"@odata.id\":\"http://host/Customers(1)\",\"@Is.New\":true},{\"@odata.id\":\"http://host/Customers(2)\",\"@TestNamespace.unknown\":123,\"@custom.annotation\":456}],\"@custom.name\":654}"; var deserializer = this.CreateJsonLightEntryAndFeedDeserializer(payload); ODataEntityReferenceLinks links = deserializer.ReadEntityReferenceLinks(); SameEntityReferenceLinks(referencelinks, links); }
/// <summary> /// Throws a NotSupportedException as the ODataWriter does not support link collections. /// </summary> /// <param name="payloadElement">The link collection to process.</param> public override void Visit(LinkCollection payloadElement) { var newLinks = new List<ODataEntityReferenceLink>(); foreach (var link in payloadElement) { newLinks.Add(new ODataEntityReferenceLink() { Url = new Uri(link.UriString) }); } var links = new ODataEntityReferenceLinks() { Count = payloadElement.Count, Links = newLinks, NextPageLink = new Uri(payloadElement.NextLink) }; this.items.Push(links); }
public void TheNewEntityReferenceLinksShouldNotBeNull() { ODataEntityReferenceLinks referencelinks = new ODataEntityReferenceLinks(); referencelinks.Should().NotBeNull(); referencelinks.Links.Should().BeNull(); }
public void CollectionOfEntityReferences() { ODataEntityReferenceLink referenceLink = new ODataEntityReferenceLink { Url = new Uri(TestBaseUri + "/Companys(1)") }; ODataEntityReferenceLinks referenceLinks = new ODataEntityReferenceLinks { Links = new[] { referenceLink } }; foreach (ODataFormat mimeType in mimeTypes) { string payload, contentType; this.WriteAndValidateContextUri(mimeType, model, omWriter => omWriter.WriteEntityReferenceLinks(referenceLinks), string.Format("\"{0}$metadata#Collection($ref)\"", TestBaseUri), out payload, out contentType); this.ReadPayload(payload, contentType, model, omReader => omReader.ReadEntityReferenceLinks()); } }
public void InstanceAnnotationsPropertyShouldNotBeNullAtCreation() { ODataEntityReferenceLinks referencelinks = new ODataEntityReferenceLinks(); referencelinks.InstanceAnnotations.Should().NotBeNull(); referencelinks.InstanceAnnotations.Count.Should().Be(0); }
/// <summary> /// Asynchronously writes the result of a $ref query as the message payload. /// </summary> /// <param name="links">The entity reference links to write as message payload.</param> /// <returns>A task representing the asynchronous writing of the entity reference links.</returns> /// <remarks>It is the responsibility of this method to flush the output before the task finishes.</remarks> internal virtual Task WriteEntityReferenceLinksAsync(ODataEntityReferenceLinks links) { throw this.CreatePayloadKindNotSupportedException(ODataPayloadKind.EntityReferenceLinks); }
private void WriteEntityReferenceLinks(ODataMessageWriterTestWrapper messageWriter, ODataEntityReferenceLinks referenceLinks) { messageWriter.WriteEntityReferenceLinks(referenceLinks); }
private static string WriteToString(ODataEntityReferenceLinks referencelinks, bool writingResponse = true, bool synchronous = true) { MemoryStream stream = new MemoryStream(); var outputContext = CreateJsonLightOutputContext(stream, writingResponse, synchronous); outputContext.WriteEntityReferenceLinks(referencelinks); stream.Seek(0, SeekOrigin.Begin); return (new StreamReader(stream)).ReadToEnd(); }
public void ShouldWriteForEntityReferenceLinksWithReferenceLinksAnnotaions() { ODataEntityReferenceLink link1 = new ODataEntityReferenceLink { Url = new Uri("http://host/Customers(1)") }; link1.InstanceAnnotations.Add(new ODataInstanceAnnotation("Is.New", new ODataPrimitiveValue(true))); ODataEntityReferenceLink link2 = new ODataEntityReferenceLink { Url = new Uri("http://host/Customers(2)") }; link2.InstanceAnnotations.Add(new ODataInstanceAnnotation("TestNamespace.unknown", new ODataPrimitiveValue(123))); link2.InstanceAnnotations.Add(new ODataInstanceAnnotation("custom.annotation", new ODataPrimitiveValue(456))); ODataEntityReferenceLinks referencelinks = new ODataEntityReferenceLinks() { Links = new[] { link1, link2 } }; referencelinks.InstanceAnnotations.Add(new ODataInstanceAnnotation("TestNamespace.name", new ODataPrimitiveValue(321))); referencelinks.InstanceAnnotations.Add(new ODataInstanceAnnotation("custom.name", new ODataPrimitiveValue(654))); string expectedPayload = "{\"@odata.context\":\"http://odata.org/test/$metadata#Collection($ref)\",\"@TestNamespace.name\":321,\"@custom.name\":654,\"value\":[{\"@odata.id\":\"http://host/Customers(1)\",\"@Is.New\":true},{\"@odata.id\":\"http://host/Customers(2)\",\"@TestNamespace.unknown\":123,\"@custom.annotation\":456}]}"; WriteAndValidate(referencelinks, expectedPayload, writingResponse: false); WriteAndValidate(referencelinks, expectedPayload, writingResponse: true); }
/// <summary> /// Converts the object to ODataCollectionValue, ODataEntityReferenceLinks, or /// a list of ODataEntry. /// </summary> /// <param name="paramName">The name of the <see cref="UriOperationParameter"/>. Used for error reporting.</param> /// <param name="value">The value of the <see cref="UriOperationParameter"/>.</param> /// <param name="itemTypeAnnotation">The client type annotation of the value.</param> /// <param name="useEntityReference">If true, use entity reference, instead of entity to serialize the parameter.</param> /// <returns>The converted result.</returns> private object ConvertToCollectionValue(string paramName, object value, ClientTypeAnnotation itemTypeAnnotation, bool useEntityReference) { object valueInODataFormat; switch (itemTypeAnnotation.EdmType.TypeKind) { case EdmTypeKind.Primitive: case EdmTypeKind.Enum: case EdmTypeKind.Complex: valueInODataFormat = this.propertyConverter.CreateODataCollection(itemTypeAnnotation.ElementType, null, value, null, false, false); break; case EdmTypeKind.Entity: if (useEntityReference) { var list = value as IEnumerable; var links = (from object o in list select new ODataEntityReferenceLink() { Url = this.requestInfo.EntityTracker.GetEntityDescriptor(o).GetLatestIdentity(), }).ToList(); valueInODataFormat = new ODataEntityReferenceLinks() { Links = links, }; } else { valueInODataFormat = this.propertyConverter.CreateODataEntries( itemTypeAnnotation.ElementType, value); } break; default: throw new NotSupportedException(Strings.Serializer_InvalidCollectionParamterItemType(paramName, itemTypeAnnotation.EdmType.TypeKind)); } return valueInODataFormat; }
private static void WriteAndValidate(ODataEntityReferenceLinks referencelinks, string expectedPayload, bool writingResponse = true, bool synchronous = true) { string payload = WriteToString(referencelinks, writingResponse, synchronous); Console.WriteLine(payload); Console.WriteLine(expectedPayload); payload.Should().Be(expectedPayload); }