/// <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 ReadJsonLight()
        {
            // Arrange
            var deserializer = new ODataEntityReferenceLinkDeserializer();
            MockODataRequestMessage    requestMessage = new MockODataRequestMessage();
            ODataMessageWriterSettings writerSettings = new ODataMessageWriterSettings();

            writerSettings.SetContentType(ODataFormat.Json);
            IEdmModel          model         = CreateModel();
            ODataMessageWriter messageWriter = new ODataMessageWriter(requestMessage, writerSettings, model);

            messageWriter.WriteEntityReferenceLink(new ODataEntityReferenceLink {
                Url = new Uri("http://localhost/samplelink")
            });
            ODataMessageReader messageReader = new ODataMessageReader(new MockODataRequestMessage(requestMessage),
                                                                      new ODataMessageReaderSettings(), model);

            IEdmNavigationProperty navigationProperty = GetNavigationProperty(model);

            var request = RequestFactory.Create("Get", "http://localhost", opt => opt.AddModel("odata", model));

            request.ODataFeature().PrefixName = "odata";
            ODataDeserializerContext context  = new ODataDeserializerContext
            {
                Request = request,
                Path    = new ODataPath(new NavigationPropertySegment(navigationProperty, navigationSource: null))
            };

            // Act
            Uri uri = deserializer.Read(messageReader, typeof(Uri), context) as Uri;

            // Assert
            Assert.NotNull(uri);
            Assert.Equal("http://localhost/samplelink", uri.AbsoluteUri);
        }
        public override void WriteObject(object graph, 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);
            }

            IEdmNavigationProperty navigationProperty = GetNavigationProperty(writeContext.Path);

            if (navigationProperty == null)
            {
                throw new SerializationException(SRResources.NavigationPropertyMissingDuringSerialization);
            }

            messageWriter.WriteEntityReferenceLink(new ODataEntityReferenceLink { Url = graph as Uri }, entitySet,
                navigationProperty);
        }
        private string WriteAndVerifySingleLink(StreamResponseMessage responseMessage, ODataMessageWriter messageWriter, string mimeType)
        {
            var link = new ODataEntityReferenceLink()
            {
                Url = new Uri(this.ServiceUri + "Order(-10)")
            };

            messageWriter.WriteEntityReferenceLink(link);
            var stream = responseMessage.GetStream();

            if (!mimeType.Contains(MimeTypes.ODataParameterNoMetadata))
            {
                stream.Seek(0, SeekOrigin.Begin);
                var settings = new ODataMessageReaderSettings()
                {
                    BaseUri = this.ServiceUri
                };

                ODataMessageReader messageReader = new ODataMessageReader(responseMessage, settings, WritePayloadHelper.Model);

                ODataEntityReferenceLink linkRead = messageReader.ReadEntityReferenceLink();
                Assert.IsTrue(linkRead.Url.AbsoluteUri.Contains("Order(-10)"), "linkRead.Url");
            }

            return(WritePayloadHelper.ReadStreamContent(stream));
        }
Пример #5
0
#pragma warning disable 1998
        protected override async Task <Stream> WriteLinkContentAsync(string method, string commandText, string linkIdent)
        {
#if SILVERLIGHT
            IODataRequestMessage
#else
            IODataRequestMessageAsync
#endif
            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)
                };
                messageWriter.WriteEntityReferenceLink(link);

                if (IsBatch)
                {
                    return(null);
                }

#if SILVERLIGHT
                return(message.GetStream());
#else
                return(await message.GetStreamAsync());
#endif
            }
        }
        public void ReadJsonLight()
        {
            // Arrange
            var deserializer = new ODataEntityReferenceLinkDeserializer();
            MockODataRequestMessage    requestMessage = new MockODataRequestMessage();
            ODataMessageWriterSettings writerSettings = new ODataMessageWriterSettings();

            writerSettings.SetContentType(ODataFormat.Json);
            IEdmModel          model         = CreateModel();
            ODataMessageWriter messageWriter = new ODataMessageWriter(requestMessage, writerSettings, model);

            messageWriter.WriteEntityReferenceLink(new ODataEntityReferenceLink {
                Url = new Uri("http://localhost/samplelink")
            });
            ODataMessageReader messageReader = new ODataMessageReader(new MockODataRequestMessage(requestMessage),
                                                                      new ODataMessageReaderSettings(), model);

            IEdmNavigationProperty navigationProperty = GetNavigationProperty(model);

            ODataDeserializerContext context = new ODataDeserializerContext
            {
                Request = new HttpRequestMessage(),
                Path    = new ODataPath(new NavigationPathSegment(navigationProperty))
            };

            // Act
            Uri uri = deserializer.Read(messageReader, typeof(Uri), context) as Uri;

            // Assert
            Assert.NotNull(uri);
            Assert.Equal("http://localhost/samplelink", uri.AbsoluteUri);
        }
        public void ReadJsonLight()
        {
            // Arrange
            var deserializer = new ODataEntityReferenceLinkDeserializer();
            MockODataRequestMessage requestMessage = new MockODataRequestMessage();
            ODataMessageWriterSettings writerSettings = new ODataMessageWriterSettings();
            writerSettings.SetContentType(ODataFormat.Json);
            IEdmModel model = CreateModel();
            ODataMessageWriter messageWriter = new ODataMessageWriter(requestMessage, writerSettings, model);
            messageWriter.WriteEntityReferenceLink(new ODataEntityReferenceLink { Url = new Uri("http://localhost/samplelink") });
            ODataMessageReader messageReader = new ODataMessageReader(new MockODataRequestMessage(requestMessage),
                new ODataMessageReaderSettings(), model);

            IEdmNavigationProperty navigationProperty = GetNavigationProperty(model);

            ODataDeserializerContext context = new ODataDeserializerContext
            {
                Request = new HttpRequestMessage(),
                Path = new ODataPath(new NavigationPathSegment(navigationProperty))
            };

            // Act
            Uri uri = deserializer.Read(messageReader, typeof(Uri), context) as Uri;

            // Assert
            Assert.NotNull(uri);
            Assert.Equal("http://localhost/samplelink", uri.AbsoluteUri);
        }
        /// <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");
            }

            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);
            }
        }
Пример #9
0
        /// <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 targetResourceEditLink;
                if (null != targetResource.GetLatestIdentity())
                {
                    // When we write the uri in the payload, we need to make sure that we write the edit
                    // link in the payload, since the request uri is the edit link of the parent entity.
                    // Think of a read/write service - since the uri is the target link to the parent entity
                    // its better that we write the edit link of the child entity in the payload.
                    targetResourceEditLink = targetResource.GetResourceUri(this.requestInfo.BaseUriResolver, false /*queryLink*/);
                }
                else
                {
#if DEBUG
                    Debug.Assert(isBatch, "we should be cross-referencing entities only in batch scenarios");
#endif
                    targetResourceEditLink = UriUtil.CreateUri("$" + targetResource.ChangeOrder.ToString(CultureInfo.InvariantCulture), UriKind.Relative);
                }

                ODataEntityReferenceLink referenceLink = new ODataEntityReferenceLink();
                referenceLink.Url = targetResourceEditLink;
                messageWriter.WriteEntityReferenceLink(referenceLink);
            }
        }
        public override void WriteObject(object graph, ODataMessageWriter messageWriter, ODataSerializerContext writeContext)
        {
            if (messageWriter == null)
            {
                throw Error.ArgumentNull("messageWriter");
            }

            messageWriter.WriteEntityReferenceLink(new ODataEntityReferenceLink { Url = graph as Uri });
        }
        public override void WriteObject(object graph, ODataMessageWriter messageWriter, ODataSerializerContext writeContext)
        {
            if (messageWriter == null)
            {
                throw Error.ArgumentNull("messageWriter");
            }

            messageWriter.WriteEntityReferenceLink(new ODataEntityReferenceLink {
                Url = graph as Uri
            });
        }
        /// <inheritdoc/>
        public override void WriteObject(object graph, 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);
            }
        }
        public void Read()
        {
            // Arrange
            var deserializer = new ODataEntityReferenceLinkDeserializer();
            MockODataRequestMessage requestMessage = new MockODataRequestMessage();
            ODataMessageWriter messageWriter = new ODataMessageWriter(requestMessage);
            messageWriter.WriteEntityReferenceLink(new ODataEntityReferenceLink { Url = new Uri("http://localhost/samplelink") });
            ODataMessageReader messageReader = new ODataMessageReader(new MockODataRequestMessage(requestMessage));

            // Act
            Uri uri = deserializer.Read(messageReader, new ODataDeserializerContext()) as Uri;

            // Assert
            Assert.NotNull(uri);
            Assert.Equal("http://localhost/samplelink", uri.AbsoluteUri);
        }
        /// <inheritdoc/>
        public override void WriteObject(object graph, 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);
            }
        }
        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));
            }
        }
        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.UrlBase, linkIdent)
                };
                messageWriter.WriteEntityReferenceLink(link);

#if SILVERLIGHT
                return(message.GetStream());
#else
                return(await message.GetStreamAsync());
#endif
            }
        }
Пример #17
0
        public void TestWriteEntityReferenceLink_InJsonLight_WithEntitySetButNotNavigationProperty_Throws()
        {
            // Arrange
            IODataResponseMessage      response = CreateResponse();
            ODataMessageWriterSettings settings = CreateJsonLightSettings();
            IEdmModel model = CreateModel();
            ODataEntityReferenceLink link = new ODataEntityReferenceLink
            {
                Url = CreateFakeUri()
            };
            IEdmEntitySet entitySet = model.EntityContainers().Single().EntitySets().First();

            using (ODataMessageWriter writer = new ODataMessageWriter(response, settings, model))
            {
                // Act & Assert
                Assert.Throws <ODataException>(() => writer.WriteEntityReferenceLink(link, entitySet, null));
            }
        }
Пример #18
0
        /// <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");
            }

            if (graph != null)
            {
                ODataEntityReferenceLink entityReferenceLink = GetEntityReferenceLink(graph);
                messageWriter.WriteEntityReferenceLink(entityReferenceLink);
            }
        }
Пример #19
0
        public void Read()
        {
            // Arrange
            var deserializer = new ODataEntityReferenceLinkDeserializer();
            MockODataRequestMessage requestMessage = new MockODataRequestMessage();
            ODataMessageWriter      messageWriter  = new ODataMessageWriter(requestMessage);

            messageWriter.WriteEntityReferenceLink(new ODataEntityReferenceLink {
                Url = new Uri("http://localhost/samplelink")
            });
            ODataMessageReader messageReader = new ODataMessageReader(new MockODataRequestMessage(requestMessage));

            // Act
            Uri uri = deserializer.Read(messageReader, new ODataDeserializerReadContext()) as Uri;

            // Assert
            Assert.NotNull(uri);
            Assert.Equal("http://localhost/samplelink", uri.AbsoluteUri);
        }
        public void Read()
        {
            // Arrange
            var deserializer = new ODataEntityReferenceLinkDeserializer();
            MockODataRequestMessage requestMessage = new MockODataRequestMessage();
            ODataMessageWriter messageWriter = new ODataMessageWriter(requestMessage);
            messageWriter.WriteEntityReferenceLink(new ODataEntityReferenceLink { Url = new Uri("http://localhost/samplelink") });
            ODataMessageReader messageReader = new ODataMessageReader(new MockODataRequestMessage(requestMessage));
            ODataDeserializerContext context = new ODataDeserializerContext
            {
                Path = new ODataPath(new NavigationPathSegment(GetNavigationProperty(CreateModel())))
            };

            // Act
            Uri uri = deserializer.Read(messageReader, context) as Uri;

            // Assert
            Assert.NotNull(uri);
            Assert.Equal("http://localhost/samplelink", uri.AbsoluteUri);
        }
Пример #21
0
 internal void WriteEntityReferenceLink(LinkDescriptor binding, ODataRequestMessageWrapper requestMessage)
 {
     using (ODataMessageWriter writer = CreateMessageWriter(requestMessage, this.requestInfo))
     {
         Uri resourceUri;
         EntityDescriptor entityDescriptor = this.requestInfo.EntityTracker.GetEntityDescriptor(binding.Target);
         if (entityDescriptor.GetLatestIdentity() != null)
         {
             resourceUri = entityDescriptor.GetResourceUri(this.requestInfo.BaseUriResolver, false);
         }
         else
         {
             resourceUri = Util.CreateUri("$" + entityDescriptor.ChangeOrder.ToString(CultureInfo.InvariantCulture), UriKind.Relative);
         }
         ODataEntityReferenceLink link = new ODataEntityReferenceLink {
             Url = resourceUri
         };
         writer.WriteEntityReferenceLink(link);
     }
 }
Пример #22
0
    protected async override Task <Stream> WriteLinkContentAsync(string method, string commandText, string linkIdent)
    {
        var message = IsBatch
                        ? await CreateBatchOperationMessageAsync(method, null, null, commandText, false).ConfigureAwait(false)
                        : new ODataRequestMessage();

        using var messageWriter = new ODataMessageWriter(message, GetWriterSettings(), _model);
        var link = new ODataEntityReferenceLink
        {
            Url = Utils.CreateAbsoluteUri(_session.Settings.BaseUri.AbsoluteUri, linkIdent)
        };

        messageWriter.WriteEntityReferenceLink(link);

        if (IsBatch)
        {
            return(null);
        }

        return(await message.GetStreamAsync().ConfigureAwait(false));
    }
Пример #23
0
        /// <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);
            }
        }
        public void Read_RoundTrips()
        {
            // Arrange
            IEdmModel model        = CreateModel();
            var       deserializer = new ODataEntityReferenceLinkDeserializer();
            MockODataRequestMessage    requestMessage = new MockODataRequestMessage();
            ODataMessageWriterSettings settings       = new ODataMessageWriterSettings()
            {
                ODataUri = new ODataUri {
                    ServiceRoot = new Uri("http://any/")
                }
            };

            settings.SetContentType(ODataFormat.Json);

            ODataMessageWriter messageWriter = new ODataMessageWriter(requestMessage, settings);

            messageWriter.WriteEntityReferenceLink(new ODataEntityReferenceLink {
                Url = new Uri("http://localhost/samplelink")
            });

            var config  = RoutingConfigurationFactory.CreateWithRootContainer("OData");
            var request = RequestFactory.Create(config, "OData");
            ODataMessageReaderSettings readSettings  = new ODataMessageReaderSettings();
            ODataMessageReader         messageReader = new ODataMessageReader(new MockODataRequestMessage(requestMessage), readSettings, model);
            ODataDeserializerContext   context       = new ODataDeserializerContext
            {
                Request = request,
                Path    = new ODataPath(new NavigationPropertySegment(GetNavigationProperty(model), navigationSource: null))
            };

            // Act
            Uri uri = deserializer.Read(messageReader, typeof(Uri), context) as Uri;

            // Assert
            Assert.NotNull(uri);
            Assert.Equal("http://localhost/samplelink", uri.AbsoluteUri);
        }
        public void Read_RoundTrips()
        {
            // Arrange
            var deserializer = new ODataEntityReferenceLinkDeserializer();
            MockODataRequestMessage requestMessage = new MockODataRequestMessage();
            ODataMessageWriterSettings settings = new ODataMessageWriterSettings();
            settings.SetContentType(ODataFormat.Atom);
            ODataMessageWriter messageWriter = new ODataMessageWriter(requestMessage, settings);
            messageWriter.WriteEntityReferenceLink(new ODataEntityReferenceLink { Url = new Uri("http://localhost/samplelink") });
            ODataMessageReader messageReader = new ODataMessageReader(new MockODataRequestMessage(requestMessage));
            ODataDeserializerContext context = new ODataDeserializerContext
            {
                Request = new HttpRequestMessage(),
                Path = new ODataPath(new NavigationPathSegment(GetNavigationProperty(CreateModel())))
            };

            // Act
            Uri uri = deserializer.Read(messageReader, typeof(Uri), context) as Uri;

            // Assert
            Assert.NotNull(uri);
            Assert.Equal("http://localhost/samplelink", uri.AbsoluteUri);
        }
        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.EntityContainer.EntitySets().First();

            Assert.NotNull(entitySet);
            IEdmNavigationProperty navigationProperty =
                model.EntityContainer.EntitySets().First().NavigationPropertyBindings.First().NavigationProperty;

            Assert.NotNull(navigationProperty);

            using (ODataMessageWriter writer = new ODataMessageWriter(response, settings, model))
            {
                // Act & Assert
                Assert.DoesNotThrow(() => writer.WriteEntityReferenceLink(link));
            }
        }
        public void Read_RoundTrips()
        {
            // Arrange
            var deserializer = new ODataEntityReferenceLinkDeserializer();
            MockODataRequestMessage requestMessage = new MockODataRequestMessage();
            ODataMessageWriter      messageWriter  = new ODataMessageWriter(requestMessage);

            messageWriter.WriteEntityReferenceLink(new ODataEntityReferenceLink {
                Url = new Uri("http://localhost/samplelink")
            });
            ODataMessageReader       messageReader = new ODataMessageReader(new MockODataRequestMessage(requestMessage));
            ODataDeserializerContext context       = new ODataDeserializerContext
            {
                Request = new HttpRequestMessage(),
                Path    = new ODataPath(new NavigationPathSegment(GetNavigationProperty(CreateModel())))
            };

            // Act
            Uri uri = deserializer.Read(messageReader, typeof(Uri), context) as Uri;

            // Assert
            Assert.NotNull(uri);
            Assert.Equal("http://localhost/samplelink", uri.AbsoluteUri);
        }
Пример #28
0
        public void WriteEntryWithWrongSerializationInfo()
        {
            foreach (var mimeType in this.testMimeTypes)
            {
                var settings = new ODataMessageWriterSettings();
                settings.ODataUri = new ODataUri()
                {
                    ServiceRoot = this.ServiceUri
                };

                // wrong EntitySetName for entry
                var responseMessageWithoutModel = new StreamResponseMessage(new MemoryStream());
                responseMessageWithoutModel.SetHeader("Content-Type", mimeType);
                using (var messageWriter = new ODataMessageWriter(responseMessageWithoutModel, settings))
                {
                    var odataWriter = messageWriter.CreateODataEntryWriter();
                    var entry       = this.CreatePersonEntryWithoutSerializationInfo();

                    entry.SetSerializationInfo(new ODataFeedAndEntrySerializationInfo()
                    {
                        NavigationSourceName = "Parsen", NavigationSourceEntityTypeName = NameSpace + "Person"
                    });
                    odataWriter.WriteStart(entry);
                    odataWriter.WriteEnd();
                    var result = WritePayloadHelper.ReadStreamContent(responseMessageWithoutModel.GetStream());
                    Assert.IsTrue(result.Contains("Person(-5)\",\"PersonId\":-5"));
                    if (!mimeType.Contains(MimeTypes.ODataParameterNoMetadata))
                    {
                        // no metadata does not write odata.metadata
                        Assert.IsTrue(result.Contains("$metadata#Parsen/$entity"));
                    }
                }

                // wrong EntitySetName for feed
                responseMessageWithoutModel = new StreamResponseMessage(new MemoryStream());
                responseMessageWithoutModel.SetHeader("Content-Type", mimeType);
                using (var messageWriter = new ODataMessageWriter(responseMessageWithoutModel, settings))
                {
                    var odataWriter = messageWriter.CreateODataFeedWriter();

                    var feed = this.CreatePersonFeed();
                    feed.SetSerializationInfo(new ODataFeedAndEntrySerializationInfo()
                    {
                        NavigationSourceName = "Parsen", NavigationSourceEntityTypeName = NameSpace + "Person"
                    });
                    var entry = this.CreatePersonEntryWithoutSerializationInfo();
                    odataWriter.WriteStart(feed);
                    odataWriter.WriteStart(entry);
                    odataWriter.WriteEnd();
                    odataWriter.WriteEnd();
                    var result = WritePayloadHelper.ReadStreamContent(responseMessageWithoutModel.GetStream());
                    Assert.IsTrue(result.Contains("Person(-5)\",\"PersonId\":-5"));
                    if (!mimeType.Contains(MimeTypes.ODataParameterNoMetadata))
                    {
                        // no metadata does not write odata.metadata
                        Assert.IsTrue(result.Contains("$metadata#Parsen\""));
                    }
                }

                // wrong collection type name
                responseMessageWithoutModel = new StreamResponseMessage(new MemoryStream());
                responseMessageWithoutModel.SetHeader("Content-Type", mimeType);
                using (var messageWriter = new ODataMessageWriter(responseMessageWithoutModel, settings))
                {
                    var odataWriter    = messageWriter.CreateODataCollectionWriter();
                    var collctionStart = new ODataCollectionStart()
                    {
                        Name = "BackupContactInfo"
                    };
                    collctionStart.SetSerializationInfo(new ODataCollectionStartSerializationInfo()
                    {
                        CollectionTypeName = "Collection(" + NameSpace + "ContactDETAIL)"
                    });

                    odataWriter.WriteStart(collctionStart);
                    odataWriter.WriteItem(
                        WritePayloadHelper.CreatePrimaryContactODataComplexValue());
                    odataWriter.WriteEnd();
                    var result = WritePayloadHelper.ReadStreamContent(responseMessageWithoutModel.GetStream());
                    Assert.IsTrue(result.Contains("value\":[{\"EmailBag\":["));
                    if (!mimeType.Contains(MimeTypes.ODataParameterNoMetadata))
                    {
                        // no metadata does not write odata.metadata
                        Assert.IsTrue(result.Contains("$metadata#Collection(" + NameSpace + "ContactDETAIL)"));
                    }
                }

                // The following two cases of wrong reference link info is no longer active. The ODataEntityReferenceLinkSerializationInfo is ignored when writer writes the payload.
                // Consider removing them.

                // wrong reference link info
                responseMessageWithoutModel = new StreamResponseMessage(new MemoryStream());
                responseMessageWithoutModel.SetHeader("Content-Type", mimeType);
                using (var messageWriter = new ODataMessageWriter(responseMessageWithoutModel, settings))
                {
                    var link = new ODataEntityReferenceLink()
                    {
                        Url = new Uri(this.ServiceUri + "Order(-10)")
                    };
                    messageWriter.WriteEntityReferenceLink(link);
                    var result = WritePayloadHelper.ReadStreamContent(responseMessageWithoutModel.GetStream());
                    Assert.IsTrue(result.Contains(this.ServiceUri + "Order(-10)"));
                    if (!mimeType.Contains(MimeTypes.ODataParameterNoMetadata))
                    {
                        // no metadata does not write odata.context
                        Assert.IsTrue(result.Contains("$metadata#$ref"));
                    }
                }

                // wrong reference links info
                responseMessageWithoutModel = new StreamResponseMessage(new MemoryStream());
                responseMessageWithoutModel.SetHeader("Content-Type", mimeType);
                using (var messageWriter = new ODataMessageWriter(responseMessageWithoutModel, settings))
                {
                    var links = new ODataEntityReferenceLinks()
                    {
                        Links = new[]
                        {
                            new ODataEntityReferenceLink()
                            {
                                Url = new Uri(this.ServiceUri + "Order(-10)")
                            }
                        },
                    };

                    messageWriter.WriteEntityReferenceLinks(links);
                    var result = WritePayloadHelper.ReadStreamContent(responseMessageWithoutModel.GetStream());
                    Assert.IsTrue(result.Contains(this.ServiceUri + "Order(-10)"));
                    if (!mimeType.Contains(MimeTypes.ODataParameterNoMetadata))
                    {
                        // no metadata does not write odata.metadata
                        Assert.IsTrue(result.Contains("$metadata#Collection($ref)"));
                    }
                }
            }
        }
Пример #29
0
        public void WriteEntryWithWrongSerializationInfo()
        {
            foreach (var mimeType in this.testMimeTypes)
            {
                var settings = new ODataMessageWriterSettings();
                settings.ODataUri = new ODataUri()
                {
                    ServiceRoot = this.ServiceUri
                };

                // wrong EntitySetName for entry
                var responseMessageWithoutModel = new StreamResponseMessage(new MemoryStream());
                responseMessageWithoutModel.SetHeader("Content-Type", mimeType);
                using (var messageWriter = new ODataMessageWriter(responseMessageWithoutModel, settings))
                {
                    var odataWriter = messageWriter.CreateODataResourceWriter();
                    var entry       = this.CreatePersonEntryWithoutSerializationInfo();

                    entry.SetSerializationInfo(new ODataResourceSerializationInfo()
                    {
                        NavigationSourceName = "Parsen", NavigationSourceEntityTypeName = NameSpace + "Person"
                    });
                    odataWriter.WriteStart(entry);
                    odataWriter.WriteEnd();
                    var result = WritePayloadHelper.ReadStreamContent(responseMessageWithoutModel.GetStream());
                    Assert.IsTrue(result.Contains("\"PersonId\":-5"));
                    if (!mimeType.Contains(MimeTypes.ODataParameterNoMetadata))
                    {
                        // no metadata does not write odata.metadata
                        Assert.IsTrue(result.Contains("$metadata#Parsen/$entity"));
                        Assert.IsTrue(result.Contains("Person(-5)\",\"PersonId\":-5"));
                    }
                    else
                    {
                        Assert.IsFalse(result.Contains("Person(-5)\",\"PersonId\":-5"));
                    }
                }

                // wrong EntitySetName for feed
                responseMessageWithoutModel = new StreamResponseMessage(new MemoryStream());
                responseMessageWithoutModel.SetHeader("Content-Type", mimeType);
                using (var messageWriter = new ODataMessageWriter(responseMessageWithoutModel, settings))
                {
                    var odataWriter = messageWriter.CreateODataResourceSetWriter();

                    var feed = this.CreatePersonFeed();
                    feed.SetSerializationInfo(new ODataResourceSerializationInfo()
                    {
                        NavigationSourceName = "Parsen", NavigationSourceEntityTypeName = NameSpace + "Person"
                    });
                    var entry = this.CreatePersonEntryWithoutSerializationInfo();
                    odataWriter.WriteStart(feed);
                    odataWriter.WriteStart(entry);
                    odataWriter.WriteEnd();
                    odataWriter.WriteEnd();
                    var result = WritePayloadHelper.ReadStreamContent(responseMessageWithoutModel.GetStream());
                    Assert.IsTrue(result.Contains("\"PersonId\":-5"));
                    if (!mimeType.Contains(MimeTypes.ODataParameterNoMetadata))
                    {
                        // no metadata does not write odata.metadata
                        Assert.IsTrue(result.Contains("$metadata#Parsen\""));
                        Assert.IsTrue(result.Contains("Person(-5)\",\"PersonId\":-5"));
                    }
                    else
                    {
                        Assert.IsFalse(result.Contains("Person(-5)\",\"PersonId\":-5"));
                    }
                }

                // wrong complex collection type name
                responseMessageWithoutModel = new StreamResponseMessage(new MemoryStream());
                responseMessageWithoutModel.SetHeader("Content-Type", mimeType);
                using (var messageWriter = new ODataMessageWriter(responseMessageWithoutModel, settings))
                {
                    var odataWriter       = messageWriter.CreateODataResourceSetWriter();
                    var complexCollection = new ODataResourceSetWrapper()
                    {
                        ResourceSet = new ODataResourceSet(),
                        Resources   = new List <ODataResourceWrapper>()
                        {
                            WritePayloadHelper.CreatePrimaryContactODataWrapper()
                        }
                    };

                    complexCollection.ResourceSet.SetSerializationInfo(new ODataResourceSerializationInfo()
                    {
                        ExpectedTypeName = NameSpace + "ContactDETAIL"
                    });
                    ODataWriterHelper.WriteResourceSet(odataWriter, complexCollection);
                    var result = WritePayloadHelper.ReadStreamContent(responseMessageWithoutModel.GetStream());
                    if (!mimeType.Contains(MimeTypes.ODataParameterNoMetadata))
                    {
                        // [{"@odata.type":"#Microsoft.Test.OData.Services.AstoriaDefaultService.ContactDetails","*****@*****.**":"#Collection(String)"...
                        Assert.IsTrue(result.Contains("\"value\":[{\"@odata.type\":\"#Microsoft.Test.OData.Services.AstoriaDefaultService.ContactDetails\",\"EmailBag"));

                        // no metadata does not write odata.metadata
                        Assert.IsTrue(result.Contains("$metadata#Collection(" + NameSpace + "ContactDETAIL)"));
                    }
                    else
                    {
                        Assert.IsFalse(result.Contains("\"@odata.type\":\"#Microsoft.Test.OData.Services.AstoriaDefaultService.ContactDetails\""));
                    }
                }

                // The following two cases of wrong reference link info is no longer active. The ODataEntityReferenceLinkSerializationInfo is ignored when writer writes the payload.
                // Consider removing them.

                // wrong reference link info
                responseMessageWithoutModel = new StreamResponseMessage(new MemoryStream());
                responseMessageWithoutModel.SetHeader("Content-Type", mimeType);
                using (var messageWriter = new ODataMessageWriter(responseMessageWithoutModel, settings))
                {
                    var link = new ODataEntityReferenceLink()
                    {
                        Url = new Uri(this.ServiceUri + "Order(-10)")
                    };
                    messageWriter.WriteEntityReferenceLink(link);
                    var result = WritePayloadHelper.ReadStreamContent(responseMessageWithoutModel.GetStream());
                    Assert.IsTrue(result.Contains(this.ServiceUri + "Order(-10)"));
                    if (!mimeType.Contains(MimeTypes.ODataParameterNoMetadata))
                    {
                        // no metadata does not write odata.context
                        Assert.IsTrue(result.Contains("$metadata#$ref"));
                    }
                }

                // wrong reference links info
                responseMessageWithoutModel = new StreamResponseMessage(new MemoryStream());
                responseMessageWithoutModel.SetHeader("Content-Type", mimeType);
                using (var messageWriter = new ODataMessageWriter(responseMessageWithoutModel, settings))
                {
                    var links = new ODataEntityReferenceLinks()
                    {
                        Links = new[]
                        {
                            new ODataEntityReferenceLink()
                            {
                                Url = new Uri(this.ServiceUri + "Order(-10)")
                            }
                        },
                    };

                    messageWriter.WriteEntityReferenceLinks(links);
                    var result = WritePayloadHelper.ReadStreamContent(responseMessageWithoutModel.GetStream());
                    Assert.IsTrue(result.Contains(this.ServiceUri + "Order(-10)"));
                    if (!mimeType.Contains(MimeTypes.ODataParameterNoMetadata))
                    {
                        // no metadata does not write odata.metadata
                        Assert.IsTrue(result.Contains("$metadata#Collection($ref)"));
                    }
                }
            }
        }
Пример #30
0
        public void WriteWithoutSerializationInfo()
        {
            foreach (var mimeType in this.testMimeTypes)
            {
                var settings = new ODataMessageWriterSettings();
                settings.ODataUri = new ODataUri()
                {
                    ServiceRoot = this.ServiceUri
                };

                // write entry without serialization info
                var responseMessageWithoutModel = new StreamResponseMessage(new MemoryStream());
                responseMessageWithoutModel.SetHeader("Content-Type", mimeType);
                using (var messageWriter = new ODataMessageWriter(responseMessageWithoutModel, settings))
                {
                    var odataWriter   = messageWriter.CreateODataResourceWriter();
                    var entry         = this.CreatePersonEntryWithoutSerializationInfo();
                    var expectedError = mimeType.Contains(MimeTypes.ODataParameterNoMetadata)
                                               ? null
                                               : "ODataResourceTypeContext_MetadataOrSerializationInfoMissing";
                    AssertThrows <ODataException>(() => odataWriter.WriteStart(entry), expectedError);
                }

                // write feed without serialization info
                responseMessageWithoutModel = new StreamResponseMessage(new MemoryStream());
                responseMessageWithoutModel.SetHeader("Content-Type", mimeType);
                using (var messageWriter = new ODataMessageWriter(responseMessageWithoutModel, settings))
                {
                    var odataWriter = messageWriter.CreateODataResourceSetWriter();
                    var feed        = this.CreatePersonFeed();
                    var entry       = this.CreatePersonEntryWithoutSerializationInfo();
                    entry.SetSerializationInfo(new ODataResourceSerializationInfo()
                    {
                        NavigationSourceName = "Person", NavigationSourceEntityTypeName = NameSpace + "Person"
                    });
                    var expectedError = mimeType.Contains(MimeTypes.ODataParameterNoMetadata)
                                               ? null
                                               : "ODataResourceTypeContext_MetadataOrSerializationInfoMissing";
                    AssertThrows <ODataException>(() => odataWriter.WriteStart(feed), expectedError);
                }

                // write collection without serialization info
                responseMessageWithoutModel = new StreamResponseMessage(new MemoryStream());
                responseMessageWithoutModel.SetHeader("Content-Type", mimeType);
                using (var messageWriter = new ODataMessageWriter(responseMessageWithoutModel, settings))
                {
                    var odataWriter     = messageWriter.CreateODataCollectionWriter();
                    var collectionStart = new ODataCollectionStart()
                    {
                        Name = "BackupContactInfo"
                    };
                    var expectedError = mimeType.Contains(MimeTypes.ODataParameterNoMetadata)
                                               ? null
                                               : "ODataContextUriBuilder_TypeNameMissingForTopLevelCollection";
                    AssertThrows <ODataException>(() => odataWriter.WriteStart(collectionStart), expectedError);
                }

                // write a reference link without serialization info
                responseMessageWithoutModel = new StreamResponseMessage(new MemoryStream());
                responseMessageWithoutModel.SetHeader("Content-Type", mimeType);
                using (var messageWriter = new ODataMessageWriter(responseMessageWithoutModel, settings))
                {
                    var link = new ODataEntityReferenceLink()
                    {
                        Url = new Uri(this.ServiceUri + "Order(-10)")
                    };
                    messageWriter.WriteEntityReferenceLink(link);

                    // No exception is expected. Simply verify the writing succeeded.
                    if (!mimeType.Contains(MimeTypes.ODataParameterNoMetadata))
                    {
                        Stream stream = responseMessageWithoutModel.GetStream();
                        Assert.IsTrue(WritePayloadHelper.ReadStreamContent(stream).Contains("$metadata#$ref"));
                    }
                }

                // write reference links without serialization info
                responseMessageWithoutModel = new StreamResponseMessage(new MemoryStream());
                responseMessageWithoutModel.SetHeader("Content-Type", mimeType);
                using (var messageWriter = new ODataMessageWriter(responseMessageWithoutModel, settings))
                {
                    var links = new ODataEntityReferenceLinks()
                    {
                        Links = new[]
                        {
                            new ODataEntityReferenceLink()
                            {
                                Url = new Uri(this.ServiceUri + "Order(-10)")
                            }
                        },
                    };
                    messageWriter.WriteEntityReferenceLinks(links);

                    // No exception is expected. Simply verify the writing succeeded.
                    if (!mimeType.Contains(MimeTypes.ODataParameterNoMetadata))
                    {
                        Stream stream = responseMessageWithoutModel.GetStream();
                        Assert.IsTrue(WritePayloadHelper.ReadStreamContent(stream).Contains("$metadata#Collection($ref)"));
                    }
                }

                // write request message containing an entry
                var requestMessageWithoutModel = new StreamRequestMessage(new MemoryStream(),
                                                                          new Uri(this.ServiceUri + "Person"), "POST");
                requestMessageWithoutModel.SetHeader("Content-Type", mimeType);
                using (var messageWriter = new ODataMessageWriter(requestMessageWithoutModel, settings))
                {
                    var odataWriter = messageWriter.CreateODataResourceWriter();
                    var entry       = this.CreatePersonEntryWithoutSerializationInfo();
                    odataWriter.WriteStart(entry);
                    odataWriter.WriteEnd();
                    Stream stream = requestMessageWithoutModel.GetStream();
                    Assert.IsTrue(WritePayloadHelper.ReadStreamContent(stream).Contains("Person(-5)\",\"PersonId\":-5,\"Name\":\"xhsdckkeqzvlnprheujeycqrglfehtdocildrequohlffazfgtvmddyqsaxrojqxrsckohrakdxlrghgmzqnyruzu\""));
                }
            }
        }
Пример #31
0
#pragma warning disable 1998
        protected override async Task<Stream> WriteLinkContentAsync(string method, string commandText, string linkIdent)
        {
#if SILVERLIGHT
            IODataRequestMessage
#else
            IODataRequestMessageAsync
#endif
 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)
                };
                messageWriter.WriteEntityReferenceLink(link);

                if (IsBatch)
                    return null;

#if SILVERLIGHT
                return message.GetStream();
#else
                return await message.GetStreamAsync();
#endif
            }
        }
#pragma warning disable 1998
        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) };
                messageWriter.WriteEntityReferenceLink(link);

#if SILVERLIGHT
                return message.GetStream();
#else
                return await message.GetStreamAsync();
#endif
            }
        }
        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().NavigationTargets.First().NavigationProperty;

            using (ODataMessageWriter writer = new ODataMessageWriter(response, settings, model))
            {
                // Act & Assert
                Assert.DoesNotThrow(() => writer.WriteEntityReferenceLink(link, entitySet, navigationProperty));
            }
        }
        public void TestWriteEntityReferenceLink_InJsonLight_WithoutEntitySetOrNavigationProperty_Throws()
        {
            // 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.Throws<ODataException>(() => writer.WriteEntityReferenceLink(link));
            }
        }
        private string WriteAndVerifySingleLink(StreamResponseMessage responseMessage, ODataMessageWriter messageWriter, string mimeType)
        {
            var link = new ODataEntityReferenceLink() { Url = new Uri(this.ServiceUri + "Order(-10)") };

            messageWriter.WriteEntityReferenceLink(link);
            var stream = responseMessage.GetStream();
            if (!mimeType.Contains(MimeTypes.ODataParameterNoMetadata))
            {
                stream.Seek(0, SeekOrigin.Begin);
                var settings = new ODataMessageReaderSettings() { BaseUri = this.ServiceUri };

                ODataMessageReader messageReader = new ODataMessageReader(responseMessage, settings, WritePayloadHelper.Model);

                ODataEntityReferenceLink linkRead = messageReader.ReadEntityReferenceLink();
                Assert.IsTrue(linkRead.Url.AbsoluteUri.Contains("Order(-10)"), "linkRead.Url");
            }

            return WritePayloadHelper.ReadStreamContent(stream);
        }