private async Task WriteLinkAsync(ODataWriter entryWriter, string typeName, string linkName, IEnumerable <ReferenceLink> links)
        {
            var navigationProperty = (_model.FindDeclaredType(typeName) as IEdmEntityType).NavigationProperties()
                                     .BestMatch(x => x.Name, linkName, _session.Settings.NameMatchResolver);
            var 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 ODataNestedResourceInfo()
            {
                Name         = linkName,
                IsCollection = isCollection,
                Url          = new Uri(ODataNamespace.Related + linkType, UriKind.Absolute),
            }).ConfigureAwait(false);

            foreach (var referenceLink in links)
            {
                var    linkKey   = linkTypeWithKey.DeclaredKey;
                var    linkEntry = referenceLink.LinkData.ToDictionary(TypeCache);
                var    contentId = GetContentId(referenceLink);
                string linkUri;
                if (contentId != null)
                {
                    linkUri = "$" + contentId;
                }
                else
                {
                    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 var isSingleton);
                    linkUri = linkedCollectionName + (isSingleton ? string.Empty : formattedKey);
                }
                var link = new ODataEntityReferenceLink
                {
                    Url = Utils.CreateAbsoluteUri(_session.Settings.BaseUri.AbsoluteUri, linkUri)
                };

                await entryWriter.WriteEntityReferenceLinkAsync(link).ConfigureAwait(false);
            }

            await entryWriter.WriteEndAsync().ConfigureAwait(false);
        }
        private void WriteResource(ODataWriter odataWriter, ResourceWrapper resource)
        {
            odataWriter.WriteStart(resource.Resource);
            var nestedResourceInfos = resource.NestedResourceInfos;

            if (nestedResourceInfos != null && nestedResourceInfos.Count > 0)
            {
                foreach (var nested in nestedResourceInfos)
                {
                    WriteNestedResourceInfo(odataWriter, nested);
                }
            }

            odataWriter.WriteEnd();
        }
Exemple #3
0
        private void WriteFeed(ODataWriter writer, ODataResourceSet resourceCollection)
        {
            writer.WriteStart(resourceCollection);
            var annotation = resourceCollection.GetAnnotation <ODataFeedEntriesObjectModelAnnotation>();

            if (annotation != null)
            {
                foreach (var entry in annotation)
                {
                    this.WriteEntry(writer, entry);
                }
            }

            writer.WriteEnd();
        }
        /// <summary>
        /// Writes an OData feed.
        /// </summary>
        /// <param name="writer">The ODataWriter that will write the feed.</param>
        /// <param name="entries">The items from the data store to write to the feed.</param>
        /// <param name="entitySet">The entity set in the model that the feed belongs to.</param>
        /// <param name="model">The data store model.</param>
        /// <param name="targetVersion">The OData version this segment is targeting.</param>
        /// <param name="expandedNavigationProperties">A list of navigation property names to expand.</param>
        public static void WriteFeed(ODataWriter writer, IEnumerable entries, IEdmEntitySet entitySet, IEdmModel model, ODataVersion targetVersion, IEnumerable <string> expandedNavigationProperties)
        {
            var feed = new ODataFeed {
                Id = new Uri(ServiceConstants.ServiceBaseUri, entitySet.Name)
            };

            writer.WriteStart(feed);

            foreach (var element in entries)
            {
                WriteEntry(writer, element, entitySet, model, targetVersion, expandedNavigationProperties);
            }

            writer.WriteEnd();
        }
Exemple #5
0
        /// <summary>
        /// Writes a ReferenceLinks
        /// </summary>
        /// <param name="writer">The ODataWriter that will write the ReferenceLinks.</param>
        public static void WriteReferenceLinks(ODataWriter writer, IEnumerable element, IEdmNavigationSource entitySource, ODataVersion targetVersion, ODataNavigationLink navigationLink)
        {
            IEnumerable <ODataEntry> links = ODataObjectModelConverter.ConvertToODataEntityReferenceLinks(element, entitySource, targetVersion);
            var feed = new ODataFeed {
            };

            writer.WriteStart(feed);
            foreach (var entry in links)
            {
                entry.InstanceAnnotations.Add(new ODataInstanceAnnotation("Link.AnnotationByFeed", new ODataPrimitiveValue(true)));
                writer.WriteStart(entry);
                writer.WriteEnd();
            }
            writer.WriteEnd();
        }
        public static byte[] Serialize(this ITableEntity entity)
        {
            MemoryStream ms = new MemoryStream();

            using (var messageWriter = new ODataMessageWriter(new Message(ms), new ODataMessageWriterSettings()))
            {
                // Create an entry writer to write a top-level entry to the message.
                ODataWriter entryWriter      = messageWriter.CreateODataEntryWriter();
                var         writeODataEntity = typeof(TableConstants).Assembly.GetType("Microsoft.WindowsAzure.Storage.Table.Protocol.TableOperationHttpWebRequestFactory")
                                               .GetMethod("WriteOdataEntity", BindingFlags.NonPublic | BindingFlags.Static);

                writeODataEntity.Invoke(null, new object[] { entity, TableOperationType.Insert, null, entryWriter });
                return(ms.ToArray());
            }
        }
Exemple #7
0
        private void WriteFeed(ODataWriter writer, ODataFeed feed)
        {
            writer.WriteStart(feed);
            var annotation = feed.GetAnnotation <ODataFeedEntriesObjectModelAnnotation>();

            if (annotation != null)
            {
                foreach (var entry in annotation)
                {
                    this.WriteEntry(writer, entry);
                }
            }

            writer.WriteEnd();
        }
        private void WriteResourceSet(ODataWriter odataWriter, ResourceSetWrapper resourceSet)
        {
            odataWriter.WriteStart(resourceSet.ResourceSet);
            var resources = resourceSet.Resources;

            if (resources != null && resources.Count > 0)
            {
                foreach (var resource in resources)
                {
                    WriteResource(odataWriter, resource);
                }
            }

            odataWriter.WriteEnd();
        }
        private void WriteFeed(IEnumerable enumerable, IEdmTypeReference feedType, ODataWriter writer,
                               ODataSerializerContext writeContext)
        {
            IEdmEntityTypeReference elementType = null;

            if (feedType.IsCollection())
            {
                IEdmTypeReference refer = feedType.AsCollection().ElementType();
                if (refer.IsEntity())
                {
                    elementType = refer.AsEntity();
                }
            }
            Debug.Assert(elementType != null);

            ODataFeed feed = CreateODataFeed(enumerable, feedType.AsCollection(), writeContext);

            Debug.Assert(feed != null);

            ODataEdmTypeSerializer entrySerializer = SerializerProvider.GetEdmTypeSerializer(elementType);

            Debug.Assert(entrySerializer is CustomEntrySerializer);

            // save this for later to support JSON odata.streaming.
            Uri nextPageLink = feed.NextPageLink;

            feed.NextPageLink = null;

            writer.WriteStart(feed);

            foreach (object entry in enumerable)
            {
                entrySerializer.WriteObjectInline(entry, elementType, writer, writeContext);
            }

            // Subtle and suprising behavior: If the NextPageLink property is set before calling WriteStart(feed),
            // the next page link will be written early in a manner not compatible with odata.streaming=true. Instead, if
            // the next page link is not set when calling WriteStart(feed) but is instead set later on that feed
            // object before calling WriteEnd(), the next page link will be written at the end, as required for
            // odata.streaming=true support.

            if (nextPageLink != null)
            {
                feed.NextPageLink = nextPageLink;
            }

            writer.WriteEnd();
        }
Exemple #10
0
        /// <summary>
        /// Creates an ODataWriter for the specified format and the specified version and
        /// writes the payload in the descriptor to an in-memory stream. It then parses
        /// the written Xml and compares it to the expected result as specified in the descriptor.
        /// </summary>
        /// <param name="originalPayload">expectedPayload to write and</param>
        /// <param name="testConfiguration">Configuration for the test</param>
        protected void WriteAndVerifyODataPayloadElement(ODataPayloadElement originalPayload, WriterTestConfiguration testConfiguration)
        {
            this.Logger.LogConfiguration(testConfiguration);

            bool feedWriter = originalPayload.ElementType == ODataPayloadElementType.EntitySetInstance;

            using (var memoryStream = new TestStream())
            {
                using (var messageWriter = TestWriterUtils.CreateMessageWriter(memoryStream, testConfiguration, this.Assert))
                {
                    ODataWriter writer = messageWriter.CreateODataWriter(feedWriter);
                    Action <ODataPayloadElement> writeToStream = payload => this.PayloadElementWriter.WritePayload(writer, payload);
                    this.WriteAndLogODataPayload(originalPayload, messageWriter.Message, testConfiguration.Version, testConfiguration.Format, writeToStream);
                }
            }
        }
        public static void SetODataRequestContent(IODataRequestMessage requestMessage, IEdmModel model, IInventoryItem inventoryItem)
        {
            var setting = new ODataMessageWriterSettings();

            setting.SetContentType(ODataFormat.Atom);
            ODataMessageWriter oDatamessageWriter = new ODataMessageWriter(requestMessage, setting, model);
            ODataWriter        oDataEntrywriter   = oDatamessageWriter.CreateODataEntryWriter();

            oDataEntrywriter.WriteStart(new ODataEntry()
            {
                TypeName   = TypeName,
                Properties = GetODataProperties(inventoryItem)
            });

            oDataEntrywriter.WriteEnd();
        }
Exemple #12
0
        private static void WriteEntry(ODataWriter writer, object entity, IEnumerable <string> projectedProperties)
        {
            var entry = new ODataResource()
            {
                Id = new Uri("http://temp.org/" + Guid.NewGuid()),
                SerializationInfo = MySerializationInfo
            };

            entry.Properties = entity.GetType().GetProperties().Select(p => new ODataProperty()
            {
                Name = p.Name, Value = p.GetValue(entity, null)
            });

            writer.WriteStart(entry);
            writer.WriteEnd();
        }
        private void WriteEntry(object graph, ODataWriter writer, ODataSerializerContext writeContext)
        {
            Contract.Assert(writeContext != null);

            IEdmEntityType        entityType            = EntityType.EntityDefinition();
            EntityInstanceContext entityInstanceContext = new EntityInstanceContext(writeContext, entityType, graph);

            ODataEntry entry = CreateEntry(entityInstanceContext, writeContext);

            if (entry != null)
            {
                writer.WriteStart(entry);
                WriteNavigationLinks(entityInstanceContext, writer, writeContext);
                writer.WriteEnd();
            }
        }
        private static void WriteItem(ODataWriter writer, ODataItemWrapper odataItemWrapper)
        {
            var odataResourceWrapper = odataItemWrapper as ODataResourceWrapper;

            if (odataResourceWrapper != null)
            {
                WriteResource(writer, odataResourceWrapper);
            }

            var odataResourceSetWrapper = odataItemWrapper as ODataResourceSetWrapper;

            if (odataResourceSetWrapper != null)
            {
                WriteResourceSet(writer, odataResourceSetWrapper);
            }
        }
        private static void WriteItem(ODataWriter writer, my.ODataItemWrapper ODataItemWrapper)
        {
            var ODataResourceWrapper = ODataItemWrapper as my.ODataResourceWrapper;

            if (ODataResourceWrapper != null)
            {
                WriteResource(writer, ODataResourceWrapper);
            }

            var ODataResourceSetWrapper = ODataItemWrapper as my.ODataResourceSetWrapper;

            if (ODataResourceSetWrapper != null)
            {
                WriteResourceSet(writer, ODataResourceSetWrapper);
            }
        }
        private void WriteExpandedNavigationProperty(
            KeyValuePair <IEdmNavigationProperty, SelectExpandClause> navigationPropertyToExpand,
            EntityInstanceContext entityInstanceContext,
            ODataWriter writer)
        {
            Contract.Assert(entityInstanceContext != null);
            Contract.Assert(writer != null);

            IEdmNavigationProperty navigationProperty = navigationPropertyToExpand.Key;
            SelectExpandClause     selectExpandClause = navigationPropertyToExpand.Value;

            object propertyValue = entityInstanceContext.GetPropertyValue(navigationProperty.Name);

            if (propertyValue == null)
            {
                if (navigationProperty.Type.IsCollection())
                {
                    // A navigation property whose Type attribute specifies a collection, the collection always exists,
                    // it may just be empty.
                    // If a collection of entities can be related, it is represented as a JSON array. An empty
                    // collection of entities (one that contains no entities) is represented as an empty JSON array.
                    writer.WriteStart(new ODataFeed());
                }
                else
                {
                    // If at most one entity can be related, the value is null if no entity is currently related.
                    writer.WriteStart(entry: null);
                }

                writer.WriteEnd();
            }
            else
            {
                // create the serializer context for the expanded item.
                ODataSerializerContext nestedWriteContext = new ODataSerializerContext(entityInstanceContext, selectExpandClause, navigationProperty);

                // write object.
                ODataEdmTypeSerializer serializer = SerializerProvider.GetEdmTypeSerializer(navigationProperty.Type);
                if (serializer == null)
                {
                    throw new SerializationException(
                              Error.Format(SRResources.TypeCannotBeSerialized, navigationProperty.Type.ToTraceString(), typeof(ODataMediaTypeFormatter).Name));
                }

                serializer.WriteObjectInline(propertyValue, navigationProperty.Type, writer, nestedWriteContext);
            }
        }
        private void WriteComplexAndExpandedNavigationProperty(IEdmProperty edmProperty, SelectExpandClause selectExpandClause,
                                                               ResourceContext resourceContext,
                                                               ODataWriter writer)
        {
            Contract.Assert(edmProperty != null);
            Contract.Assert(resourceContext != null);
            Contract.Assert(writer != null);

            object propertyValue = resourceContext.GetPropertyValue(edmProperty.Name);

            if (propertyValue == null || propertyValue is NullEdmComplexObject)
            {
                if (edmProperty.Type.IsCollection())
                {
                    // A complex or navigation property whose Type attribute specifies a collection, the collection always exists,
                    // it may just be empty.
                    // If a collection of complex or entities can be related, it is represented as a JSON array. An empty
                    // collection of resources (one that contains no resource) is represented as an empty JSON array.
                    writer.WriteStart(new ODataResourceSet
                    {
                        TypeName = edmProperty.Type.FullName()
                    });
                }
                else
                {
                    // If at most one resource can be related, the value is null if no resource is currently related.
                    writer.WriteStart(resource: null);
                }

                writer.WriteEnd();
            }
            else
            {
                // create the serializer context for the complex and expanded item.
                ODataSerializerContext nestedWriteContext = new ODataSerializerContext(resourceContext, selectExpandClause, edmProperty);

                // write object.
                ODataEdmTypeSerializer serializer = SerializerProvider.GetEdmTypeSerializer(resourceContext.Context, edmProperty.Type);
                if (serializer == null)
                {
                    throw new SerializationException(
                              Error.Format(SRResources.TypeCannotBeSerialized, edmProperty.Type.ToTraceString(), typeof(ODataResourceSerializer).Name));
                }

                serializer.WriteObjectInline(propertyValue, edmProperty.Type, writer, nestedWriteContext);
            }
        }
        public void WritingSingleNavigationProppertyWithSameTypeAsNavigationPropertyTypeWithOrWithoutDerivedTypeConstraintWorks()
        {
            // Add a <NavigationProperty Name="FriendCustomer" Type="NS.Customer" />
            var navigationProperty = this.edmCustomerType.AddUnidirectionalNavigation(new EdmNavigationPropertyInfo
            {
                Target             = this.edmCustomerType,
                TargetMultiplicity = EdmMultiplicity.One,
                Name = "FriendCustomer"
            });

            ODataNestedResourceInfo nestedResourceInfo = new ODataNestedResourceInfo
            {
                Name         = "FriendCustomer",
                IsCollection = false
            };

            ODataResource nestedFriendCustomer = new ODataResource
            {
                TypeName   = "NS.Customer",
                Properties = new[] { new ODataProperty {
                                         Name = "Id", Value = 5
                                     } }
            };

            Action <ODataMessageWriter> writeNavigationPropertyAction = (messageWriter) =>
            {
                ODataWriter writer = messageWriter.CreateODataResourceWriter(this.edmCustomers, this.edmCustomerType); // entityset
                writer.WriteStart(this.odataCustomerResource);
                writer.WriteStart(nestedResourceInfo);
                writer.WriteStart(nestedFriendCustomer); // Customer
                writer.WriteEnd();
                writer.WriteEnd();
                writer.WriteEnd();
            };

            // Navigation property doesn't have the derived type constraint.
            string actual = GetWriterOutput(this.edmModel, writeNavigationPropertyAction);

            Assert.Contains("#Customers/$entity\",\"Id\":7,\"FriendCustomer\":{\"Id\":5}}", actual);

            // Navigation property has the derived type constraint.
            SetDerivedTypeAnnotation(this.edmModel, navigationProperty, "NS.VipCustomer");

            string actualWithDerivedTypeConstraint = GetWriterOutput(this.edmModel, writeNavigationPropertyAction);

            Assert.Equal(actual, actualWithDerivedTypeConstraint);
        }
        public override void WriteObject(object graph, ODataMessageWriter messageWriter, ODataSerializerContext writeContext)
        {
            if (messageWriter == null)
            {
                throw Error.ArgumentNull("messageWriter");
            }

            if (writeContext == null)
            {
                throw Error.ArgumentNull("writeContext");
            }

            ODataWriter writer = messageWriter.CreateODataEntryWriter();

            WriteObjectInline(graph, writer, writeContext);
            writer.Flush();
        }
Exemple #20
0
        /// <summary>
        /// Runs the specified action for all interesting writers.
        /// </summary>
        /// <param name="feedWriter">True if writing a feed; false if writing an entry.</param>
        /// <param name="action">The action to run.</param>
        private void ForWriters(bool feedWriter, Action <ODataWriter> action)
        {
            this.CombinatorialEngineProvider.RunCombinations(
                this.WriterTestConfigurationProvider.ExplicitFormatConfigurations,
                (testConfiguration) =>
            {
                testConfiguration = testConfiguration.Clone();
                testConfiguration.MessageWriterSettings.SetServiceDocumentUri(ServiceDocumentUri);

                using (TestStream stream = new TestStream())
                    using (var messageWriter = TestWriterUtils.CreateMessageWriter(stream, testConfiguration, this.Assert))
                    {
                        ODataWriter writer = messageWriter.CreateODataWriter(feedWriter);
                        action(writer);
                    }
            });
        }
Exemple #21
0
        public void DisposeAfterWritingNothingTest()
        {
            this.CombinatorialEngineProvider.RunCombinations(
                this.WriterTestConfigurationProvider.ExplicitFormatConfigurations,
                new bool[] { true, false },
                (testConfiguration, forFeed) =>
            {
                testConfiguration = testConfiguration.Clone();
                testConfiguration.MessageWriterSettings.SetServiceDocumentUri(ServiceDocumentUri);

                using (var stream = new TestStream())
                    using (var messageWriter = TestWriterUtils.CreateMessageWriter(stream, testConfiguration, this.Assert))
                    {
                        ODataWriter writer = messageWriter.CreateODataWriter(forFeed);
                    }
            });
        }
        private void WriteEntry(object graph, ODataWriter writer, ODataSerializerContext writeContext)
        {
            Contract.Assert(writeContext != null);

            IEdmEntityTypeReference entityType            = GetEntityType(graph, writeContext);
            EntityInstanceContext   entityInstanceContext = new EntityInstanceContext(writeContext, entityType, graph, null);
            SelectExpandNode        selectExpandNode      = CreateSelectExpandNode(entityInstanceContext);

            if (selectExpandNode != null)
            {
                ODataEntry entry = CreateEntry(selectExpandNode, entityInstanceContext);
                if (entry != null)
                {
                    WriteNode(writer, entry, selectExpandNode, entityInstanceContext);
                }
            }
        }
Exemple #23
0
        private void WriteFeed(ODataWriter writer, Lazy <ODataReader> lazyReader, ODataFeed feed)
        {
            this.WriteStart(writer, feed);
            var annotation = feed.GetAnnotation <ODataFeedEntriesObjectModelAnnotation>();

            if (annotation != null)
            {
                int count = annotation.Count;
                for (int i = 0; i < count; ++i)
                {
                    this.WriteEntry(writer, lazyReader, annotation[i]);
                }
            }

            this.WriteEnd(writer, ODataReaderState.FeedEnd);
            this.Read(lazyReader);
        }
Exemple #24
0
        private static void WriteNested(IEdmModel model, ODataWriter odataWriter, object value, PropertyInfo property)
        {
            ODataNestedResourceInfo nestedResourceInfo = new ODataNestedResourceInfo
            {
                Name = property.Name
            };

            Type propType     = property.PropertyType;
            bool isCollection = IsCollection(propType, out Type elementType);

            nestedResourceInfo.IsCollection = isCollection;

            object propValue = property.GetValue(value);

            odataWriter.WriteStart(nestedResourceInfo);

            if (propValue == null)
            {
                if (isCollection)
                {
                    odataWriter.WriteStart(new ODataResourceSet
                    {
                        TypeName = "Collection(" + elementType.FullName + ")"
                    });
                }
                else
                {
                    odataWriter.WriteStart(resource: null);
                }

                odataWriter.WriteEnd();
            }
            else
            {
                if (isCollection)
                {
                    WriteResourceSet(model, odataWriter, propValue);
                }
                else
                {
                    WriteResource(model, odataWriter, propValue);
                }
            }

            odataWriter.WriteEnd();
        }
        protected void WriteAnnotationsAndValidatePayload(Action <ODataWriter> action, ODataFormat format, string expectedPayload, bool request, bool createFeedWriter)
        {
            var writerSettings = new ODataMessageWriterSettings {
                DisableMessageStreamDisposal = true, EnableAtom = true
            };

            writerSettings.SetContentType(format);
            writerSettings.SetServiceDocumentUri(new Uri("http://www.example.com/"));

            MemoryStream stream = new MemoryStream();

            if (request)
            {
                IODataRequestMessage requestMessageToWrite = new InMemoryMessage {
                    Method = "GET", Stream = stream
                };
                using (var messageWriter = new ODataMessageWriter(requestMessageToWrite, writerSettings, Model))
                {
                    ODataWriter odataWriter = createFeedWriter ? messageWriter.CreateODataFeedWriter(EntitySet, EntityType) : messageWriter.CreateODataEntryWriter(EntitySet, EntityType);
                    action(odataWriter);
                }
            }
            else
            {
                IODataResponseMessage responseMessageToWrite = new InMemoryMessage {
                    StatusCode = 200, Stream = stream
                };
                using (var messageWriter = new ODataMessageWriter(responseMessageToWrite, writerSettings, Model))
                {
                    ODataWriter odataWriter = createFeedWriter ? messageWriter.CreateODataFeedWriter(EntitySet, EntityType) : messageWriter.CreateODataEntryWriter(EntitySet, EntityType);
                    action(odataWriter);
                }
            }

            stream.Position = 0;
            string payload = (new StreamReader(stream)).ReadToEnd();

            if (format == ODataFormat.Atom)
            {
                // The <updated> element is computed dynamically, so we remove it from the both the baseline and the actual payload.
                payload         = Regex.Replace(payload, "<updated>[^<]*</updated>", "");
                expectedPayload = Regex.Replace(expectedPayload, "<updated>[^<]*</updated>", "");
            }

            Assert.AreEqual(expectedPayload, payload);
        }
        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);

            await entryWriter.WriteStartAsync(new ODataNavigationLink()
            {
                Name         = linkName,
                IsCollection = isCollection,
                Url          = new Uri("http://schemas.microsoft.com/ado/2007/08/dataservices/related/" + linkType, UriKind.Absolute),
            });

            foreach (var referenceLink in links)
            {
                var    linkKey   = linkType.DeclaredKey;
                var    linkEntry = referenceLink.LinkData.ToDictionary();
                var    contentId = GetContentId(referenceLink);
                string linkUri;
                if (contentId != null)
                {
                    linkUri = "$" + contentId;
                }
                else
                {
                    var linkSet = _model.SchemaElements
                                  .Where(x => x.SchemaElementKind == EdmSchemaElementKind.EntityContainer)
                                  .SelectMany(x => (x as IEdmEntityContainer).EntitySets())
                                  .BestMatch(x => x.EntityType().Name, linkType.Name, _session.Pluralizer);
                    var formattedKey = _session.Adapter.ConvertKeyValuesToUriLiteral(
                        linkKey.ToDictionary(x => x.Name, x => linkEntry[x.Name]), true);
                    linkUri = linkSet.Name + formattedKey;
                }
                var link = new ODataEntityReferenceLink
                {
                    Url = Utils.CreateAbsoluteUri(_session.Settings.UrlBase, linkUri)
                };

                await entryWriter.WriteEntityReferenceLinkAsync(link);
            }

            await entryWriter.WriteEndAsync();
        }
Exemple #27
0
        private void WriteEntry(ODataWriter writer, Object entity, ref EntityPropertiesInfo entityPropertiesInfo)
        {
            if (entityPropertiesInfo.EdmEntityType == null)
            {
                entityPropertiesInfo = GetProperties(entity);
            }

            ODataResource entry = OeDataContext.CreateEntry(entity, entityPropertiesInfo.Structurals);

            writer.WriteStart(entry);

            foreach (PropertyInfo navigationProperty in entityPropertiesInfo.Navigations)
            {
                WriteNavigationProperty(writer, entity, navigationProperty);
            }

            writer.WriteEnd();
        }
Exemple #28
0
        private async Task WriteNestedCollectionAsync(ODataWriter entryWriter, string entryName, ODataCollectionValue collection)
        {
            await entryWriter.WriteStartAsync(new ODataNestedResourceInfo()
            {
                Name         = entryName,
                IsCollection = true,
            }).ConfigureAwait(false);

            await entryWriter.WriteStartAsync(new ODataResourceSet());

            foreach (var item in collection.Items)
            {
                await WriteEntryPropertiesAsync(entryWriter, item as ODataResource, null);
            }
            await entryWriter.WriteEndAsync().ConfigureAwait(false);

            await entryWriter.WriteEndAsync().ConfigureAwait(false);
        }
        /// <summary>
        /// Writes an OData Feed with number <see cref="numberOfEntries"/> of entries <see cref="entry"/>
        /// </summary>
        /// <param name="writeStream"></param>
        /// <param name="edmModel"></param>
        /// <param name="numberOfEntries"></param>
        /// <param name="innerWrite"></param>
        /// <param name="entitySet"></param>
        /// <returns>The payload size</returns>
        protected Int64 WriteFeed(Stream writeStream, IEdmModel edmModel, long numberOfEntries, Action <ODataWriter> innerWrite, IEdmEntitySetBase entitySet)
        {
            using (var messageWriter = ODataMessageHelper.CreateMessageWriter(writeStream, edmModel))
            {
                ODataWriter writer = messageWriter.CreateODataResourceSetWriter(entitySet);
                writer.WriteStart(new ODataResourceSet {
                    Id = new Uri("http://www.odata.org/Perf.svc")
                });
                for (long i = 0; i < numberOfEntries; ++i)
                {
                    innerWrite(writer);
                }
                writer.WriteEnd();
                writer.Flush();
            }

            return(writeStream.Length); // return payload size
        }
Exemple #30
0
        private void WriteEntry(ODataWriter writer, ODataResource entry)
        {
            writer.WriteStart(entry);
            var annotation = entry.GetAnnotation <ODataEntryNavigationLinksObjectModelAnnotation>();
            ODataNestedResourceInfo navLink = null;

            if (annotation != null)
            {
                for (int i = 0; i < annotation.Count; ++i)
                {
                    bool found = annotation.TryGetNavigationLinkAt(i, out navLink);
                    ExceptionUtilities.Assert(found, "Navigation links should be ordered sequentially for writing");
                    this.WriteNavigationLink(writer, navLink);
                }
            }

            writer.WriteEnd();
        }
 /// <summary>
 /// Constructor to create an <see cref="JsonLightExpandedNavigationPropertyWriter"/>.
 /// </summary>
 /// <param name="navigationSource">The navigation source of the parent delta entry.</param>
 /// <param name="entityType">The entity type of the parent delta entry.</param>
 /// <param name="parentDeltaEntry">The parent delta entry.</param>
 /// <param name="jsonLightOutputContext">The output context for Json.</param>
 public JsonLightExpandedNavigationPropertyWriter(IEdmNavigationSource navigationSource, IEdmEntityType entityType,
     ODataEntry parentDeltaEntry, ODataJsonLightOutputContext jsonLightOutputContext)
 {
     this.parentDeltaEntry = parentDeltaEntry;
     this.entryWriter = new ODataJsonLightWriter(jsonLightOutputContext, navigationSource, entityType, /*writingFeed*/ false, writingDelta: true);
 }
        private void WriteFeed(ODataWriter writer, ODataItem[] itemsToWrite, ref int currentIdx)
        {
            if (currentIdx < itemsToWrite.Length)
            {
                ODataFeed feed = (ODataFeed)itemsToWrite[currentIdx++];
                writer.WriteStart(feed);
                while (currentIdx < itemsToWrite.Length && itemsToWrite[currentIdx] is ODataEntry)
                {
                    this.WriteEntry(writer, itemsToWrite, ref currentIdx);
                }

                writer.WriteEnd();
            }
        }
        private void WriteLink(ODataWriter writer, ODataItem[] itemsToWrite, ref int currentIdx)
        {
            if (currentIdx < itemsToWrite.Length)
            {
                ODataNavigationLink link = (ODataNavigationLink)itemsToWrite[currentIdx++];
                writer.WriteStart(link);
                if (currentIdx < itemsToWrite.Length)
                {
                    if (itemsToWrite[currentIdx] is ODataEntry)
                    {
                        this.WriteEntry(writer, itemsToWrite, ref currentIdx);
                    }
                    else if (itemsToWrite[currentIdx] is ODataFeed)
                    {
                        this.WriteFeed(writer, itemsToWrite, ref currentIdx);
                    }
                }

                writer.WriteEnd();
            }
        }
        private void WriteEntry(ODataWriter writer, ODataItem[] itemsToWrite, ref int currentIdx)
        {
            if (currentIdx < itemsToWrite.Length)
            {
                ODataEntry entry = (ODataEntry)itemsToWrite[currentIdx++];
                writer.WriteStart(entry);
                while (currentIdx < itemsToWrite.Length)
                {
                    if (itemsToWrite[currentIdx] is ODataNavigationLink)
                    {
                        this.WriteLink(writer, itemsToWrite, ref currentIdx);
                    }
                    else if (itemsToWrite[currentIdx] is ODataNavigationLinkEnd)
                    {
                        currentIdx++;
                        writer.WriteEnd();
                        return;
                    }
                    else
                    {
                        break;
                    }
                }

                writer.WriteEnd();
            }
        }