Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

POC for writing instance annotations and odata.count for expanded resource sets #2194

Draft
wants to merge 5 commits into
base: release-7.x
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -1103,11 +1103,22 @@ in resourceState.PropertyAndAnnotationCollector.GetODataPropertyAnnotations(nest
nestedResourceInfo.TypeAnnotation = new ODataTypeAnnotation((string)propertyAnnotation.Value);
break;

case ODataAnnotationNames.ODataCount:
Debug.Assert(propertyAnnotation.Value is long, "The odata.count annotation should have been parsed as a 64 bit integer.");
nestedResourceInfo.Count = (long?)propertyAnnotation.Value;
break;

default:
// TODO: Update Error message
throw new ODataException(ODataErrorStrings.ODataJsonLightResourceDeserializer_UnexpectedDeferredLinkPropertyAnnotation(nestedResourceInfo.Name, propertyAnnotation.Key));
}
}

foreach (var instanceAnnotation in resourceState.PropertyAndAnnotationCollector.GetCustomPropertyAnnotations(nestedResourceInfo.Name))
{
nestedResourceInfo.InstanceAnnotations.Add(new ODataInstanceAnnotation(instanceAnnotation.Key, instanceAnnotation.Value.ToODataValue(), /*isCustomAnnotation*/ true));
}

return ODataJsonLightReaderNestedResourceInfo.CreateDeferredLinkInfo(nestedResourceInfo, navigationProperty);
}

Expand Down
10 changes: 10 additions & 0 deletions src/Microsoft.OData.Core/JsonLight/ODataJsonLightWriter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1008,6 +1008,16 @@ protected override void WriteDeferredNestedResourceInfo(ODataNestedResourceInfo

// A deferred nested resource info is just the link metadata, no value.
this.jsonLightResourceSerializer.WriteNavigationLinkMetadata(nestedResourceInfo, this.DuplicatePropertyNameChecker);

// Only write count when the ODataNestedResourceInfo represents a collection.
if (nestedResourceInfo.IsCollection != null && nestedResourceInfo.IsCollection == true)
{
// Write the inline count if it's available.
this.WriteResourceSetCount(nestedResourceInfo.Count, nestedResourceInfo.Name);
}

// Write custom instance annotations
this.instanceAnnotationWriter.WriteInstanceAnnotations(nestedResourceInfo.GetInstanceAnnotations(), nestedResourceInfo.Name);
}

/// <summary>
Expand Down
1 change: 1 addition & 0 deletions src/Microsoft.OData.Core/Microsoft.OData.Core.cs
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ internal sealed class TextRes {
internal const string ODataWriterCore_StreamNotDisposed = "ODataWriterCore_StreamNotDisposed";
internal const string ODataWriterCore_DeltaResourceWithoutIdOrKeyProperties = "ODataWriterCore_DeltaResourceWithoutIdOrKeyProperties";
internal const string ODataWriterCore_QueryCountInRequest = "ODataWriterCore_QueryCountInRequest";
internal const string ODataWriterCore_QueryCountInODataNestedResourceInfo = "ODataWriterCore_QueryCountInODataNestedResourceInfo";
internal const string ODataWriterCore_QueryNextLinkInRequest = "ODataWriterCore_QueryNextLinkInRequest";
internal const string ODataWriterCore_QueryDeltaLinkInRequest = "ODataWriterCore_QueryDeltaLinkInRequest";
internal const string ODataWriterCore_CannotWriteDeltaWithResourceSetWriter = "ODataWriterCore_CannotWriteDeltaWithResourceSetWriter";
Expand Down
1 change: 1 addition & 0 deletions src/Microsoft.OData.Core/Microsoft.OData.Core.txt
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ ODataWriterCore_StreamNotDisposed=ODataWriter.Write or ODataWriter.WriteEnd was

ODataWriterCore_DeltaResourceWithoutIdOrKeyProperties=No Id or key properties were found. A resource in a delta payload requires an ID or key properties be specified.
ODataWriterCore_QueryCountInRequest=The ODataResourceSet.Count must be null for request payloads. Query counts are only supported in responses.
ODataWriterCore_QueryCountInODataNestedResourceInfo=The ODataNestedResourceInfo.Count must be null when ODataNestedResourceInfo.IsCollection is false.
ODataWriterCore_QueryNextLinkInRequest=The NextPageLink must be null for request payloads. Next page links are only supported in responses.
ODataWriterCore_QueryDeltaLinkInRequest=The DeltaLink must be null for request payloads. Delta links are only supported in responses.
ODataWriterCore_CannotWriteDeltaWithResourceSetWriter=Cannot write a deleted resource, link, deleted link, or nested delta resource set to a non-delta payload. Please use a delta resource set writer, or a request resource writer.
Expand Down
35 changes: 35 additions & 0 deletions src/Microsoft.OData.Core/ODataNestedResourceInfo.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,9 @@ namespace Microsoft.OData
{
#region Namespaces
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using Microsoft.OData.Evaluation;
#endregion Namespaces

Expand All @@ -33,6 +35,9 @@ public sealed class ODataNestedResourceInfo : ODataItem
/// <summary>true if the association link has been set by the user or seen on the wire or computed by the metadata builder, false otherwise.</summary>
private bool hasAssociationUrl;

/// <summary>The number of items in the resource set.</summary>
private long? count;

/// <summary>Gets or sets a value that indicates whether the nested resource info represents a collection or a resource.</summary>
/// <returns>true if the nested resource info represents a collection; false if the navigation represents a resource.</returns>
public bool? IsCollection
Expand Down Expand Up @@ -92,6 +97,36 @@ public Uri AssociationLinkUrl
}
}

/// <summary>Gets or sets the number of items in the resource set.</summary>
/// <returns>The number of items in the resource set.</returns>
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Noet: you don't really need the section for a property -- you cover what it returns in the summary.

public long? Count
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

what about if the nested resource info is single?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I have added a validation!

{
get
{
return this.count;
}

set
{
if (IsCollection != null && (bool)IsCollection == false)
{
throw new ODataException(Strings.ODataWriterCore_QueryCountInODataNestedResourceInfo);
}

this.count = value;
}
}

/// <summary>
/// Collection of custom instance annotations.
/// </summary>
[SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly", Justification = "We want to allow the same instance annotation collection instance to be shared across ODataLib OM instances.")]
public ICollection<ODataInstanceAnnotation> InstanceAnnotations
{
get { return this.GetInstanceAnnotations(); }
set { this.SetInstanceAnnotations(value); }
}

/// <summary>Gets or sets the context url for this nested resource info.</summary>
/// <returns>The URI representing the context url of the nested resource info.</returns>
internal Uri ContextUrl { get; set; }
Expand Down
11 changes: 11 additions & 0 deletions src/Microsoft.OData.Core/Parameterized.Microsoft.OData.Core.cs
Original file line number Diff line number Diff line change
Expand Up @@ -304,6 +304,17 @@ internal static string ODataWriterCore_QueryCountInRequest
}
}

/// <summary>
/// A string like "The ODataNestedResourceInfo.Count must be null when ODataNestedResourceInfo.IsCollection is false."
/// </summary>
internal static string ODataWriterCore_QueryCountInODataNestedResourceInfo
{
get
{
return Microsoft.OData.TextRes.GetString(Microsoft.OData.TextRes.ODataWriterCore_QueryCountInODataNestedResourceInfo);
}
}

/// <summary>
/// A string like "The NextPageLink must be null for request payloads. Next page links are only supported in responses."
/// </summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -555,6 +555,54 @@ private void WriteAnnotationAtEndExpandedFeedShouldFail(ODataFormat format)
testRequestOfSingleton.Throws<ODataException>(Strings.ODataJsonLightWriter_InstanceAnnotationNotSupportedOnExpandedResourceSet);
}

[Fact]
public void WriteAnnotationAndCountAtStartExpandedFeedShouldPassInJsonLight()
{
string expectedPayload =
"{" +
"\"@odata.context\":\"http://www.example.com/$metadata#TestEntitySet/$entity\"," +
"\"ID\":1," +
"\"[email protected]\":\"http://service/navLink\"," +
"\"[email protected]\":10," +
"\"[email protected]\":123" +
"}";

Action<ODataWriter> action = (odataWriter) =>
{
var entryToWrite = new ODataResource { Properties = new[] { new ODataProperty { Name = "ID", Value = 1 } } };
odataWriter.WriteStart(entryToWrite);

ODataNestedResourceInfo navLink = new ODataNestedResourceInfo { Name = "ResourceSetNavigationProperty", Url = new Uri("http://service/navLink", UriKind.RelativeOrAbsolute), IsCollection = true };
navLink.Count = 10;
navLink.InstanceAnnotations.Add(new ODataInstanceAnnotation("custom.StartFeedAnnotation", PrimitiveValue1));
odataWriter.WriteStart(navLink);

odataWriter.WriteEnd();
odataWriter.WriteEnd();
};

this.WriteAnnotationsAndValidatePayload(action, EntitySet, ODataFormat.Json, expectedPayload, request: false, createFeedWriter: false);
}

[Fact]
public void WriteCountOnExpandedEntryShouldFail()
{
Action<ODataWriter> action = (odataWriter) =>
{
var entryToWrite = new ODataResource { Properties = new[] { new ODataProperty { Name = "ID", Value = 1 } } };
odataWriter.WriteStart(entryToWrite);

ODataNestedResourceInfo navLink = new ODataNestedResourceInfo { Name = "ResourceNavigationProperty", IsCollection = false };
navLink.Count = 10;

odataWriter.WriteStart(navLink);
odataWriter.WriteEnd();
odataWriter.WriteEnd();
};

Action testResponse = () => this.WriteAnnotationsAndValidatePayload(action, EntitySet, ODataFormat.Json, null, request: false, createFeedWriter: false);
testResponse.Throws<ODataException>(Strings.ODataWriterCore_QueryCountInODataNestedResourceInfo);
}
#endregion Writing instance annotations on expanded feeds

#region Write Delta Feed
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,20 @@ static CustomInstanceAnnotationAcceptanceTests()
"\"@Custom.FeedEndAnnotation\":1" +
"}";

const string JsonLightExpandedResourceSetPayloadWithCountAndCustomInstanceAnnotations =
"{" +
"\"@odata.context\":\"http://www.example.com/service.svc/$metadata#TestEntitySet\"," +
"\"value\":[" +
"{" +
"\"ID\":1," +
"\"[email protected]\":\"http://example.com/multiple\"," +
"\"[email protected]\":10," +
"\"[email protected]\":\"123\"," +
"\"[email protected]\":123" +
"}" +
"]" +
"}";

[Fact]
public void CustomInstanceAnnotationFromFeedAndEntryInJsonLightShouldBeSkippedByTheReaderByDefault()
{
Expand Down Expand Up @@ -121,6 +135,48 @@ public void CustomInstanceAnnotationFromFeedAndEntryInJsonLightShouldBeSkippedBy
}
}

[Fact]
public void ShouldBeAbleToReadCountAndCustomInstanceAnnotationsFromExpandedResourceSetsInJsonLight()
{
var stream = new MemoryStream(Encoding.UTF8.GetBytes(JsonLightExpandedResourceSetPayloadWithCountAndCustomInstanceAnnotations));
var readerSettings = new ODataMessageReaderSettings { EnableMessageStreamDisposal = true };

IODataResponseMessage messageToRead = new InMemoryMessage { StatusCode = 200, Stream = stream };
messageToRead.SetHeader("Content-Type", "application/json;odata.streaming=true");

// Enable reading custom instance annotations.
//messageToRead.PreferenceAppliedHeader().AnnotationFilter = "Custom.*";
messageToRead.PreferenceAppliedHeader().AnnotationFilter = "*";

using (var messageReader = new ODataMessageReader(messageToRead, readerSettings, Model))
{
var odataReader = messageReader.CreateODataResourceSetReader(EntitySet, EntityType);
while (odataReader.Read())
{
switch (odataReader.State)
{
case ODataReaderState.NestedResourceInfoStart:
break;
case ODataReaderState.NestedResourceInfoEnd:
ODataNestedResourceInfo navigationLink = (ODataNestedResourceInfo)odataReader.Item;

if (navigationLink.Name == "ResourceSetNavigationProperty")
{
Assert.Equal("ResourceSetNavigationProperty", navigationLink.Name);
Assert.Equal(10, navigationLink.Count);
Assert.Equal(2, navigationLink.InstanceAnnotations.Count);
Assert.Equal("custom.MyAnnotation", navigationLink.InstanceAnnotations.First().Name);
Assert.Equal("custom.StartFeedAnnotation", navigationLink.InstanceAnnotations.Last().Name);
Assert.Equal(true, navigationLink.IsCollection);
Assert.Equal(new Uri("http://example.com/multiple"), navigationLink.Url);
Assert.Equal(new Uri("http://www.example.com/service.svc/TestEntitySet(1)/ResourceSetNavigationProperty/$ref"), navigationLink.AssociationLinkUrl);
}
break;
}
}
}
}

[Fact]
public void ShouldBeAbleToReadCustomInstanceAnnotationFromFeedAndEntryInJsonLight()
{
Expand Down