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); }
/// <inheritdoc/> 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) { ODataEntityReferenceLink entityReferenceLink = graph as ODataEntityReferenceLink; if (entityReferenceLink == null) { Uri uri = graph as Uri; if (uri == null) { throw new SerializationException(Error.Format(SRResources.CannotWriteType, GetType().Name, graph.GetType().FullName)); } entityReferenceLink = new ODataEntityReferenceLink { Url = uri }; } messageWriter.WriteEntityReferenceLink(entityReferenceLink); } return Task.FromResult(true); }
public void InstanceAnnotationsPropertyShouldReturnAWritableCollectionAtCreation() { ODataEntityReferenceLink referencelink = new ODataEntityReferenceLink(); referencelink.InstanceAnnotations.Should().NotBeNull(); referencelink.InstanceAnnotations.Add(new ODataInstanceAnnotation("TestNamespace.name", new ODataPrimitiveValue("value"))); referencelink.InstanceAnnotations.Count.Should().Be(1); }
/// <summary> /// Initializes a new instance of the <see cref="WritingEntityReferenceLinkArgs"/> class. /// </summary> /// <param name="entityReferenceLink">The entity reference link.</param> /// <param name="source">The source.</param> /// <param name="target">The target.</param> public WritingEntityReferenceLinkArgs(ODataEntityReferenceLink entityReferenceLink, object source, object target) { Util.CheckArgumentNull(entityReferenceLink, "entityReferenceLink"); Util.CheckArgumentNull(source, "source"); Util.CheckArgumentNull(target, "target"); this.EntityReferenceLink = entityReferenceLink; this.Source = source; this.Target = target; }
public void PropertySettersNullTest() { ODataEntityReferenceLink entityReferenceLink = new ODataEntityReferenceLink() { Url = null, }; this.Assert.IsNull(entityReferenceLink.Url, "Expected null value for property 'Url'."); }
public void ShouldBeAbleToSetAndClearIdOnEntityReferenceLink() { ODataEntityReferenceLink referencelink = new ODataEntityReferenceLink(); referencelink.Url.Should().BeNull(); referencelink.Url = new Uri("http://my/Id"); referencelink.Url.ToString().Should().Be("http://my/Id"); referencelink.Url = null; referencelink.Url.Should().BeNull(); }
/// <summary> /// Validates an entity reference link. /// </summary> /// <param name="link">The entity reference link to check.</param> internal static void ValidateEntityReferenceLink(ODataEntityReferenceLink link) { Debug.Assert(link != null, "link != null"); if (link.Url == null) { throw new ODataException(Strings.ReaderValidationUtils_EntityReferenceLinkMissingUri); } }
protected override async Task<Stream> WriteLinkContentAsync(string linkIdent) { var message = new ODataRequestMessage(); using (var messageWriter = new ODataMessageWriter(message, GetWriterSettings(), _model)) { var link = new ODataEntityReferenceLink { Url = Utils.CreateAbsoluteUri(_session.Settings.BaseUri.AbsoluteUri, linkIdent) }; await messageWriter.WriteEntityReferenceLinkAsync(link); return await message.GetStreamAsync(); } }
public void PropertyGettersAndSettersTest() { Uri link = new Uri("http://odatalib.org/entityreferencelink"); ODataEntityReferenceLink entityReferenceLink = new ODataEntityReferenceLink() { Url = link, }; this.Assert.AreSame(link, entityReferenceLink.Url, "Expected reference equal values for property 'Url'."); }
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); }
protected override async Task<Stream> WriteLinkContentAsync(string method, string commandText, string linkIdent) { var message = IsBatch ? await CreateBatchOperationMessageAsync(method, null, null, commandText, false) : new ODataRequestMessage(); using (var messageWriter = new ODataMessageWriter(message, GetWriterSettings(), _model)) { var link = new ODataEntityReferenceLink { Url = Utils.CreateAbsoluteUri(_session.Settings.BaseUri.AbsoluteUri, linkIdent) }; await messageWriter.WriteEntityReferenceLinkAsync(link); return IsBatch ? null : await message.GetStreamAsync(); } }
/// <inheritdoc/> 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) { ODataEntityReferenceLink entityReferenceLink = graph as ODataEntityReferenceLink; if (entityReferenceLink == null) { Uri uri = graph as Uri; if (uri == null) { throw new SerializationException(Error.Format(SRResources.CannotWriteType, GetType().Name, graph.GetType().FullName)); } entityReferenceLink = new ODataEntityReferenceLink { Url = uri }; } messageWriter.WriteEntityReferenceLink(entityReferenceLink, entitySet, navigationProperty); } }
private async Task WriteLinkAsync(ODataWriter entryWriter, Microsoft.OData.Core.ODataEntry entry, string linkName, IEnumerable<ReferenceLink> links) { var navigationProperty = (_model.FindDeclaredType(entry.TypeName) as IEdmEntityType).NavigationProperties() .BestMatch(x => x.Name, linkName, _session.Pluralizer); bool isCollection = navigationProperty.Type.Definition.TypeKind == EdmTypeKind.Collection; var linkType = GetNavigationPropertyEntityType(navigationProperty); var linkTypeWithKey = linkType; while (linkTypeWithKey.DeclaredKey == null && linkTypeWithKey.BaseEntityType() != null) { linkTypeWithKey = linkTypeWithKey.BaseEntityType(); } await entryWriter.WriteStartAsync(new ODataNavigationLink() { Name = linkName, IsCollection = isCollection, Url = new Uri(ODataNamespace.Related + linkType, UriKind.Absolute), }); foreach (var referenceLink in links) { var linkKey = linkTypeWithKey.DeclaredKey; var linkEntry = referenceLink.LinkData.ToDictionary(); var contentId = GetContentId(referenceLink); string linkUri; if (contentId != null) { linkUri = "$" + contentId; } else { bool isSingleton; var formattedKey = _session.Adapter.GetCommandFormatter().ConvertKeyValuesToUriLiteral( linkKey.ToDictionary(x => x.Name, x => linkEntry[x.Name]), true); var linkedCollectionName = _session.Metadata.GetLinkedCollectionName( referenceLink.LinkData.GetType().Name, linkTypeWithKey.Name, out isSingleton); linkUri = linkedCollectionName + (isSingleton ? string.Empty : formattedKey); } var link = new ODataEntityReferenceLink { Url = Utils.CreateAbsoluteUri(_session.Settings.BaseUri.AbsoluteUri, linkUri) }; await entryWriter.WriteEntityReferenceLinkAsync(link); } await entryWriter.WriteEndAsync(); }
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); } } }
public void TestWriteEntityReferenceLink_InJsonLight_WithEntityAndNavigationProperty_DoesNotThrow() { // Arrange IODataResponseMessage response = CreateResponse(); ODataMessageWriterSettings settings = CreateJsonLightSettings(); IEdmModel model = CreateModel(); ODataEntityReferenceLink link = new ODataEntityReferenceLink { Url = CreateFakeUri() }; IEdmEntitySet entitySet = model.EntityContainers().Single().EntitySets().First(); IEdmNavigationProperty navigationProperty = model.EntityContainers().Single().EntitySets().First().NavigationPropertyBindings.First().NavigationProperty; using (ODataMessageWriter writer = new ODataMessageWriter(response, settings, model)) { // Act & Assert Assert.DoesNotThrow(() => writer.WriteEntityReferenceLink(link, entitySet, navigationProperty)); } }
/// <summary> /// Visits an entity reference link. /// </summary> /// <param name="entityReferenceLink">The entity reference link to visit.</param> protected override void VisitEntityReferenceLink(ODataEntityReferenceLink entityReferenceLink) { this.ValidateUri(entityReferenceLink.Url); base.VisitEntityReferenceLink(entityReferenceLink); }
/// <summary> /// Write an entity reference link into a navigation link content. /// </summary> /// <param name="parentNavigationLink">The parent navigation link which is being written around the entity reference link.</param> /// <param name="entityReferenceLink">The entity reference link to write.</param> protected abstract void WriteEntityReferenceInNavigationLinkContent(ODataNavigationLink parentNavigationLink, ODataEntityReferenceLink entityReferenceLink);
public void TestWriteEntityReferenceLink_InJsonLight_WithoutEntitySetOrNavigationProperty_DoesNotThrow() { // Arrange IODataResponseMessage response = CreateResponse(); ODataMessageWriterSettings settings = CreateJsonLightSettings(); IEdmModel model = CreateModel(); ODataEntityReferenceLink link = new ODataEntityReferenceLink { Url = CreateFakeUri() }; using (ODataMessageWriter writer = new ODataMessageWriter(response, settings, model)) { // Act & Assert Assert.DoesNotThrow(() => writer.WriteEntityReferenceLink(link)); } }
/// <summary> /// Writes an entity reference link, which is used to represent binding to an existing resource in a request payload. /// </summary> /// <param name="entityReferenceLink">The entity reference link to write.</param> /// <remarks> /// This method can only be called for writing request messages. The entity reference link must be surrounded /// by a navigation link written through WriteStart/WriteEnd. /// The <see cref="ODataNavigationLink.Url"/> will be ignored in that case and the Uri from the <see cref="ODataEntityReferenceLink.Url"/> will be used /// as the binding URL to be written. /// </remarks> public sealed override void WriteEntityReferenceLink(ODataEntityReferenceLink entityReferenceLink) { this.VerifyCanWriteEntityReferenceLink(entityReferenceLink, true); this.WriteEntityReferenceLinkImplementation(entityReferenceLink); }
/// <summary> /// Initializes a new instance of <see cref="ODataEntityReferenceLinkBase"/>. /// </summary> /// <param name="item">The wrapped item.</param> public ODataEntityReferenceLinkBase(ODataEntityReferenceLink item) : base(item) { }
/// <summary> /// Verifies that calling WriteEntityReferenceLink is valid. /// </summary> /// <param name="entityReferenceLink">The entity reference link to write.</param> /// <param name="synchronousCall">true if the call is to be synchronous; false otherwise.</param> private void VerifyCanWriteEntityReferenceLink(ODataEntityReferenceLink entityReferenceLink, bool synchronousCall) { ExceptionUtils.CheckArgumentNotNull(entityReferenceLink, "entityReferenceLink"); this.VerifyNotDisposed(); this.VerifyCallAllowed(synchronousCall); }
/// <summary> /// Write an entity reference link. /// </summary> /// <param name="entityReferenceLink">The entity reference link to write.</param> private void WriteEntityReferenceLinkImplementation(ODataEntityReferenceLink entityReferenceLink) { Debug.Assert(entityReferenceLink != null, "entityReferenceLink != null"); if (this.outputContext.WritingResponse) { this.ThrowODataException(Strings.ODataWriterCore_EntityReferenceLinkInResponse, null); } this.CheckForNavigationLinkWithContent(ODataPayloadKind.EntityReferenceLink); Debug.Assert( this.CurrentScope.Item is ODataNavigationLink, "The CheckForNavigationLinkWithContent should have verified that entity reference link can only be written inside a navigation link."); if (!this.SkipWriting) { this.InterceptException(() => { WriterValidationUtils.ValidateEntityReferenceLink(entityReferenceLink); this.WriteEntityReferenceInNavigationLinkContent((ODataNavigationLink)this.CurrentScope.Item, entityReferenceLink); }); } }
/// <summary> /// Asynchronously writes a singleton result of a $ref query as the message payload. /// </summary> /// <param name="link">The link result to write as message payload.</param> /// <returns>A running task representing the writing of the link.</returns> /// <remarks>It is the responsibility of this method to flush the output before the task finishes.</remarks> internal virtual Task WriteEntityReferenceLinkAsync(ODataEntityReferenceLink link) { throw this.CreatePayloadKindNotSupportedException(ODataPayloadKind.EntityReferenceLink); }
public override void WriteEntityReferenceLink(ODataEntityReferenceLink entityReferenceLink) { throw new System.NotImplementedException(); }
/// <summary> /// Validates that the specified <paramref name="entityReferenceLink"/> is not null. /// </summary> /// <param name="entityReferenceLink">The entity reference link to validate.</param> /// <remarks>This should be called only for entity reference links inside the ODataEntityReferenceLinks.Links collection.</remarks> internal static void ValidateEntityReferenceLinkNotNull(ODataEntityReferenceLink entityReferenceLink) { if (entityReferenceLink == null) { throw new ODataException(Strings.WriterValidationUtils_EntityReferenceLinksLinkMustNotBeNull); } }
/// <summary> /// Writes an entity reference link. /// </summary> /// <param name="binding">The link descriptor.</param> /// <param name="requestMessage">The request message used for writing the payload.</param> internal void WriteEntityReferenceLink(LinkDescriptor binding, ODataRequestMessageWrapper requestMessage) #endif { using (ODataMessageWriter messageWriter = Serializer.CreateMessageWriter(requestMessage, this.requestInfo, false /*isParameterPayload*/)) { EntityDescriptor targetResource = this.requestInfo.EntityTracker.GetEntityDescriptor(binding.Target); Uri targetReferenceLink = targetResource.GetLatestIdentity(); if (targetReferenceLink == null) { #if DEBUG Debug.Assert(isBatch, "we should be cross-referencing entities only in batch scenarios"); #endif targetReferenceLink = UriUtil.CreateUri("$" + targetResource.ChangeOrder.ToString(CultureInfo.InvariantCulture), UriKind.Relative); } ODataEntityReferenceLink referenceLink = new ODataEntityReferenceLink(); referenceLink.Url = targetReferenceLink; messageWriter.WriteEntityReferenceLink(referenceLink); } }
/// <summary> /// Asynchronously writes an entity reference link, which is used to represent binding to an existing resource in a request payload. /// </summary> /// <param name="entityReferenceLink">The entity reference link to write.</param> /// <returns>A task instance that represents the asynchronous write operation.</returns> /// <remarks> /// This method can only be called for writing request messages. The entity reference link must be surrounded /// by a navigation link written through WriteStart/WriteEnd. /// The <see cref="ODataNavigationLink.Url"/> will be ignored in that case and the Uri from the <see cref="ODataEntityReferenceLink.Url"/> will be used /// as the binding URL to be written. /// </remarks> public sealed override Task WriteEntityReferenceLinkAsync(ODataEntityReferenceLink entityReferenceLink) { this.VerifyCanWriteEntityReferenceLink(entityReferenceLink, false); return TaskUtils.GetTaskForSynchronousOperation(() => this.WriteEntityReferenceLinkImplementation(entityReferenceLink)); }
/// <summary> /// Converts the object to ODataEntry or ODataEntityReferenceLink. /// </summary> /// <param name="value">The value of the <see cref="UriOperationParameter"/>.</param> /// <param name="elementType">The type 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 ConvertToEntityValue(object value, Type elementType, bool useEntityReference) { object valueInODataFormat; if (!useEntityReference) { valueInODataFormat = this.propertyConverter.CreateODataEntry(elementType, value); ODataEntry entry = (ODataEntry)valueInODataFormat; SerializationTypeNameAnnotation serializedTypeNameAnnotation = entry.GetAnnotation<SerializationTypeNameAnnotation>(); if (serializedTypeNameAnnotation == null || string.IsNullOrEmpty(serializedTypeNameAnnotation.TypeName)) { throw Error.InvalidOperation(Strings.DataServiceException_GeneralError); } } else { EntityDescriptor resource = this.requestInfo.EntityTracker.GetEntityDescriptor(value); Uri link = resource.GetLatestIdentity(); valueInODataFormat = new ODataEntityReferenceLink() { Url = link, }; } return valueInODataFormat; }
public override System.Threading.Tasks.Task WriteEntityReferenceLinkAsync(ODataEntityReferenceLink entityReferenceLink) { throw new System.NotImplementedException(); }
/// <summary> /// Validates an entity reference link instance. /// </summary> /// <param name="entityReferenceLink">The entity reference link to validate.</param> internal static void ValidateEntityReferenceLink(ODataEntityReferenceLink entityReferenceLink) { Debug.Assert(entityReferenceLink != null, "entityReferenceLink != null"); if (entityReferenceLink.Url == null) { throw new ODataException(Strings.WriterValidationUtils_EntityReferenceLinkUrlMustNotBeNull); } }
/// <summary> /// Validates an entity reference link instance. /// </summary> /// <param name="entityReferenceLink">The entity reference link to validate.</param> public void ValidateEntityReferenceLink(ODataEntityReferenceLink entityReferenceLink) { WriterValidationUtils.ValidateEntityReferenceLink(entityReferenceLink); }