Beispiel #1
0
        internal ODataEntriesEntityMaterializer CreateODataEntriesEntityMaterializer(
            List <ODataResource> resources,
            Type resourceType,
            TestMaterializerContext materializerContext = null)
        {
            var clientEdmModel = new ClientEdmModel(ODataProtocolVersion.V4);
            var context        = new DataServiceContext();

            var resourceSet = new ODataResourceSet();

            MaterializerFeed.CreateFeed(resourceSet, resources);
            resources.ForEach(r =>
            {
                if (r == null)
                {
                    MaterializerEntry.CreateEmpty();
                }
                else
                {
                    MaterializerEntry.CreateEntry(r, ODataFormat.Json, true, clientEdmModel);
                }
            });
            materializerContext = materializerContext ?? new TestMaterializerContext()
            {
                Model = clientEdmModel, Context = context
            };
            var             adapter    = new EntityTrackingAdapter(new TestEntityTracker(), MergeOption.OverwriteChanges, clientEdmModel, context);
            QueryComponents components = new QueryComponents(new Uri("http://foo.com/Service"), new Version(4, 0), resourceType, null, new Dictionary <Expression, Expression>());

            return(new ODataEntriesEntityMaterializer(resources, materializerContext, adapter, components, resourceType, null, ODataFormat.Json));
        }
Beispiel #2
0
            public async Task SerializeAsync(OeEntryFactory entryFactory, Db.OeAsyncEnumerator asyncEnumerator, OeQueryContext queryContext)
            {
                var resourceSet = new ODataResourceSet()
                {
                    Count = asyncEnumerator.Count
                };

                _writer.WriteStart(resourceSet);

                Object buffer       = null;
                int    count        = 0;
                var    dbEnumerator = entryFactory.IsTuple ?
                                      (Db.IOeDbEnumerator) new Db.OeDbEnumerator(asyncEnumerator, entryFactory) : new Db.OeEntityDbEnumerator(asyncEnumerator, entryFactory);

                while (await dbEnumerator.MoveNextAsync().ConfigureAwait(false))
                {
                    Object value = dbEnumerator.Current;
                    await WriteEntry(dbEnumerator, value, _queryContext.NavigationNextLink).ConfigureAwait(false);

                    count++;
                    buffer = dbEnumerator.ClearBuffer();
                }

                if (queryContext.PageSize > 0 && count > 0 && (asyncEnumerator.Count ?? Int32.MaxValue) > count)
                {
                    resourceSet.NextPageLink = BuildNextPageLink(queryContext, buffer);
                }

                _writer.WriteEnd();
            }
Beispiel #3
0
        /// <summary>
        /// Writes an OData feed.
        /// </summary>
        /// <param name="writer">The ODataWriter that will write the feed.</param>
        /// <param name="entityType">The type of the entity in 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="targetVersion">The OData version this segment is targeting.</param>
        /// <param name="selectExpandClause">The SelectExpandClause.</param>
        public static void WriteFeed(ODataWriter writer, IEdmStructuredType entityType, IEnumerable entries, IEdmEntitySetBase entitySet, ODataVersion targetVersion, SelectExpandClause selectExpandClause, long?count, Uri deltaLink, Uri nextPageLink, Dictionary <string, string> incomingHeaders = null)
        {
            var feed = new ODataResourceSet
            {
                Id           = entitySet == null ? null : new Uri(ServiceConstants.ServiceBaseUri, entitySet.Name),
                DeltaLink    = deltaLink,
                NextPageLink = nextPageLink
            };

            if (entitySet == null)
            {
                feed.SetSerializationInfo(new ODataResourceSerializationInfo()
                {
                    NavigationSourceEntityTypeName = entityType.FullTypeName(),
                    NavigationSourceName           = null,
                    NavigationSourceKind           = EdmNavigationSourceKind.UnknownEntitySet,
                    IsFromCollection = true
                });
            }

            if (count.HasValue)
            {
                feed.Count = count;
            }

            writer.WriteStart(feed);

            foreach (var element in entries)
            {
                WriteEntry(writer, element, entitySet, targetVersion, selectExpandClause, incomingHeaders);
            }

            writer.WriteEnd();
        }
Beispiel #4
0
            private async Task SerializeBuffered(OeEntryFactory entryFactory, Db.OeEntityAsyncEnumerator asyncEnumerator, Stream stream)
            {
                var values = new List <Object>();

                while (await asyncEnumerator.MoveNextAsync().ConfigureAwait(false))
                {
                    values.Add(asyncEnumerator.Current);
                }

                var resourceSet = new ODataResourceSet();

                resourceSet.Count = values.Count;
                Writer.WriteStart(resourceSet);

                foreach (Object value in values)
                {
                    int?          dummy;
                    ODataResource entry = CreateEntry(entryFactory, entryFactory.GetValue(value, out dummy));
                    Writer.WriteStart(entry);
                    foreach (OeEntryFactory navigationLink in entryFactory.NavigationLinks)
                    {
                        WriteNavigationLink(value, navigationLink);
                    }
                    Writer.WriteEnd();
                }

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

                ODataNestedResourceInfo navLink = new ODataNestedResourceInfo {
                    Name = "ResourceSetNavigationProperty", IsCollection = true
                };

                odataWriter.WriteStart(navLink);

                var feedToWrite = new ODataResourceSet {
                    Id = new Uri("urn:feedId")
                };
                feedToWrite.InstanceAnnotations.Add(new ODataInstanceAnnotation("custom.StartFeedAnnotation", PrimitiveValue1));

                odataWriter.WriteStart(feedToWrite);
            };

            Action testResponse = () => this.WriteAnnotationsAndValidatePayload(action, EntitySet, format, null, request: false, createFeedWriter: false);

            testResponse.Throws <ODataException>(Strings.ODataJsonLightWriter_InstanceAnnotationNotSupportedOnExpandedResourceSet);

            Action testRequest = () => this.WriteAnnotationsAndValidatePayload(action, EntitySet, format, null, request: true, createFeedWriter: false);

            testRequest.Throws <ODataException>(Strings.ODataJsonLightWriter_InstanceAnnotationNotSupportedOnExpandedResourceSet);
        }
        public void CreateResource_Ignores_NextPageLink_ForInnerResourceSets()
        {
            // Arrange
            Mock <ODataSerializerProvider> serializerProvider = new Mock <ODataSerializerProvider>();
            ODataResourceSetSerializer     serializer         = new ODataResourceSetSerializer(serializerProvider.Object);
            Uri nextLink = new Uri("http://somelink");
            var request  = RequestFactory.Create();

            request.ODataFeature().NextLink = nextLink;
            var result = new object[0];
            IEdmNavigationProperty navProp            = _customerSet.EntityType().NavigationProperties().First();
            SelectExpandClause     selectExpandClause = new SelectExpandClause(new SelectItem[0], allSelected: true);
            ResourceContext        entity             = new ResourceContext
            {
                SerializerContext =
                    new ODataSerializerContext {
                    Request = request, NavigationSource = _customerSet, Model = _model
                }
            };
            ODataSerializerContext nestedContext = new ODataSerializerContext(entity, selectExpandClause, navProp);

            // Act
            ODataResourceSet resourceSet = serializer.CreateResourceSet(result, _customersType, nestedContext);

            // Assert
            Assert.Null(resourceSet.NextPageLink);
        }
        public async Task WriteObjectInlineAsync_Sets_CountQueryOption_OnWriteStartAsync()
        {
            // Arrange
            IEnumerable      instance    = new object[0];
            ODataResourceSet resourceSet = new ODataResourceSet {
                Count = 1000
            };
            Mock <ODataSerializerProvider> serializerProvider = new Mock <ODataSerializerProvider>();
            Mock <ODataResourceSerializer> resourceSerializer = new Mock <ODataResourceSerializer>(serializerProvider.Object);

            serializerProvider.Setup(s => s.GetEdmTypeSerializer(It.IsAny <IEdmTypeReference>())).Returns(resourceSerializer.Object);
            Mock <ODataResourceSetSerializer> serializer = new Mock <ODataResourceSetSerializer>(serializerProvider.Object);

            serializer.CallBase = true;
            serializer.Setup(s => s.CreateResourceSet(instance, _customersType, _writeContext)).Returns(resourceSet);
            var mockWriter = new Mock <ODataWriter>();

            mockWriter.Setup(m => m.WriteStartAsync(It.Is <ODataResourceSet>(f => f.Count == 1000))).Verifiable();

            // Act
            await serializer.Object.WriteObjectInlineAsync(instance, _customersType, mockWriter.Object, _writeContext);

            // Assert
            mockWriter.Verify();
        }
        public async Task WriteObjectInlineAsync_Sets_NextPageLink_OnWriteEndAsync()
        {
            // Arrange
            IEnumerable      instance    = new object[0];
            ODataResourceSet resourceSet = new ODataResourceSet {
                NextPageLink = new Uri("http://nextlink.com/")
            };
            Mock <ODataSerializerProvider> serializerProvider = new Mock <ODataSerializerProvider>();
            Mock <ODataResourceSerializer> resourceSerializer = new Mock <ODataResourceSerializer>(serializerProvider.Object);

            serializerProvider.Setup(s => s.GetEdmTypeSerializer(It.IsAny <IEdmTypeReference>())).Returns(resourceSerializer.Object);
            Mock <ODataResourceSetSerializer> serializer = new Mock <ODataResourceSetSerializer>(serializerProvider.Object);

            serializer.CallBase = true;
            serializer.Setup(s => s.CreateResourceSet(instance, _customersType, _writeContext)).Returns(resourceSet);
            var mockWriter = new Mock <ODataWriter>();

            mockWriter.Setup(m => m.WriteStartAsync(It.Is <ODataResourceSet>(f => f.NextPageLink == null))).Verifiable();
            mockWriter
            .Setup(m => m.WriteEndAsync())
            .Callback(() =>
            {
                Assert.Equal("http://nextlink.com/", resourceSet.NextPageLink.AbsoluteUri);
            })
            .Returns(Task.CompletedTask)
            .Verifiable();

            // Act
            await serializer.Object.WriteObjectInlineAsync(instance, _customersType, mockWriter.Object, _writeContext);

            // Assert
            mockWriter.Verify();
        }
Beispiel #9
0
        public void WriteEndOnExpandedFeedWithDeltaLinkShouldThrow()
        {
            Action <ODataWriter> deltaLinkAtWriteEnd = (odataWriter) =>
            {
                var entryToWrite = new ODataResource {
                    Properties = new[] { new ODataProperty {
                                             Name = "ID", Value = 1
                                         } }
                };
                odataWriter.WriteStart(entryToWrite);

                ODataNestedResourceInfo navLink = new ODataNestedResourceInfo {
                    Name = "ResourceSetNavigationProperty", IsCollection = true
                };
                odataWriter.WriteStart(navLink);

                var feedToWrite = new ODataResourceSet();
                odataWriter.WriteStart(feedToWrite);
                feedToWrite.DeltaLink = new Uri("relative", UriKind.Relative);
                odataWriter.WriteEnd();
            };

            Action requestTest = () => WriteAnnotationsAndValidatePayload(deltaLinkAtWriteEnd, ODataFormat.Json, string.Empty, request: true, createFeedWriter: false);

            requestTest.ShouldThrow <ODataException>().WithMessage(Strings.ODataWriterCore_DeltaLinkNotSupportedOnExpandedResourceSet);

            Action responseTest = () => WriteAnnotationsAndValidatePayload(deltaLinkAtWriteEnd, ODataFormat.Json, string.Empty, request: false, createFeedWriter: false);

            responseTest.ShouldThrow <ODataException>().WithMessage(Strings.ODataWriterCore_DeltaLinkNotSupportedOnExpandedResourceSet);
        }
        public void SetFeedSerializationInfoShouldThrowOnNullFeed()
        {
            ODataResourceSet resourceCollection = null;
            Action           action             = () => resourceCollection.SetSerializationInfo(null);

            action.ShouldThrow <ArgumentNullException>().Where(e => e.Message.Contains("resourceSet"));
        }
Beispiel #11
0
        private async Task SerializeAsync(ODataWriter writer, OeMetadataLevel metadataLevel)
        {
            ClrPropertiesInfo clrPropertiesInfo = GetClrPropertiesInfo(_edmModel, _odataUri.SelectAndExpand, metadataLevel, typeof(T), null);

            var resourceSet = new ODataResourceSet()
            {
                Count = Count
            };

            writer.WriteStart(resourceSet);

            int count  = 0;
            T   entity = default;

            while (await _entities.MoveNext())
            {
                entity = _entities.Current;
                _stack.Add(entity);
                WriteEntry(writer, entity, clrPropertiesInfo);
                _stack.Remove(entity);
                count++;
            }

            if (PageSize > 0 && count > 0 && (Count ?? Int32.MaxValue) > count)
            {
                resourceSet.NextPageLink = BuildNextPageLink(OeSkipTokenParser.GetSkipToken(_edmModel, GetKeys(entity)));
            }

            writer.WriteEnd();
        }
        public void CreateResourceSet_SetsODataOperations()
        {
            // Arrange
            IEdmModel model = GetEdmModelWithOperations(out IEdmEntityType customerType, out IEdmEntitySet customers);
            IEdmCollectionTypeReference customersType = new EdmCollectionTypeReference(new EdmCollectionType(customerType.AsReference()));

            Mock <ODataSerializerProvider> serializerProvider = new Mock <ODataSerializerProvider>();
            ODataResourceSetSerializer     serializer         = new ODataResourceSetSerializer(serializerProvider.Object);
            var request = RequestFactory.Create(method: "get", uri: "http://IgnoreMetadataPath", opt => opt.AddModel(model));

            ODataSerializerContext context = new ODataSerializerContext
            {
                NavigationSource = customers,
                Request          = request,
                Model            = model,
                MetadataLevel    = ODataMetadataLevel.Full,
            };
            var result = new object[0];

            // Act
            ODataResourceSet resourceSet = serializer.CreateResourceSet(result, customersType, context);

            // Assert
            Assert.Single(resourceSet.Actions);
            Assert.Equal(3, resourceSet.Functions.Count());
        }
Beispiel #13
0
        /// <summary>
        /// Read the resource set.
        /// </summary>
        /// <param name="reader">The OData reader.</param>
        /// <param name="itemsStack">The item stack.</param>
        /// <param name="topLevelItem">The top level item.</param>
        private static void ReadResourceSet(ODataReader reader, Stack <ODataItemWrapper> itemsStack, ref ODataItemWrapper topLevelItem)
        {
            Contract.Assert(reader != null);
            Contract.Assert(itemsStack != null);
            Contract.Assert(ODataReaderState.ResourceSetStart == reader.State);

            ODataResourceSet resourceSet = (ODataResourceSet)reader.Item;

            Contract.Assert(resourceSet != null, "ResourceSet should never be null.");

            ODataResourceSetWrapper resourceSetWrapper = new ODataResourceSetWrapper(resourceSet);

            if (itemsStack.Count > 0)
            {
                ODataNestedResourceInfoWrapper parentNestedResourceInfo = (ODataNestedResourceInfoWrapper)itemsStack.Peek();
                Contract.Assert(parentNestedResourceInfo != null, "this has to be an inner resource set. inner resource sets always have a nested resource info.");
                Contract.Assert(parentNestedResourceInfo.NestedResourceInfo.IsCollection == true, "Only collection nested properties can contain resource set as their child.");
                Contract.Assert(parentNestedResourceInfo.NestedItems.Count == 0, "Each nested property can contain only one resource set as its direct child.");
                parentNestedResourceInfo.NestedItems.Add(resourceSetWrapper);
            }
            else
            {
                topLevelItem = resourceSetWrapper;
            }

            itemsStack.Push(resourceSetWrapper);
        }
Beispiel #14
0
        public static void WriteResourceSet(IEdmModel model, ODataWriter odataWriter, object value)
        {
            Type valueType = value.GetType();

            IsCollection(valueType, out Type elementType);

            IEdmStructuredType structruedType = model.FindDeclaredType(valueType.FullName) as IEdmStructuredType;

            ODataResourceSet resourceSet = new ODataResourceSet
            {
                TypeName = "Collection(" + elementType.FullName + ")"
            };

            odataWriter.WriteStart(resourceSet);
            IEnumerable items = value as IEnumerable;

            foreach (object item in items)
            {
                if (item == null)
                {
                    odataWriter.WriteStart(resource: null);
                    odataWriter.WriteEnd();
                }
                else
                {
                    WriteResource(model, odataWriter, item);
                }
            }

            odataWriter.WriteEnd();
        }
Beispiel #15
0
        public async Task WriteAsync(OeEntryFactory entryFactory, IAsyncEnumerator <Object> asyncEnumerator)
        {
            var resourceSet = new ODataResourceSet()
            {
                Count = _queryContext.TotalCountOfItems
            };
            await _writer.WriteStartAsync(resourceSet).ConfigureAwait(false);

            Object?rawValue  = null;
            int    readCount = 0;

            Db.IOeDbEnumerator dbEnumerator = entryFactory.IsTuple ?
                                              (Db.IOeDbEnumerator) new Db.OeDbEnumerator(asyncEnumerator, entryFactory) : new Db.OeEntityDbEnumerator(asyncEnumerator, entryFactory);
            while (await dbEnumerator.MoveNextAsync().ConfigureAwait(false))
            {
                await WriteEntry(dbEnumerator, dbEnumerator.Current).ConfigureAwait(false);

                readCount++;
                rawValue = dbEnumerator.RawValue;
                dbEnumerator.ClearBuffer();
            }

            if (rawValue != null)
            {
                var nextPageLinkBuilder = new OeNextPageLinkBuilder(_queryContext);
                resourceSet.NextPageLink = nextPageLinkBuilder.GetNextPageLinkRoot(entryFactory, readCount, _queryContext.TotalCountOfItems, rawValue);
            }

            await _writer.WriteEndAsync().ConfigureAwait(false);
        }
Beispiel #16
0
        /// <summary>
        /// Applies the values of a nested <paramref name="feed"/> to the collection
        /// <paramref name="property"/> of the specified <paramref name="entry"/>.
        /// </summary>
        /// <param name="entry">Entry with collection to be modified.</param>
        /// <param name="property">Collection property on the entry.</param>
        /// <param name="feed">Values to apply onto the collection.</param>
        /// <param name="includeLinks">Whether links that are expanded should be materialized.</param>
        private void ApplyFeedToCollection(
            MaterializerEntry entry,
            ClientPropertyAnnotation property,
            ODataResourceSet feed,
            bool includeLinks)
        {
            Debug.Assert(entry.Entry != null, "entry != null");
            Debug.Assert(property != null, "property != null");
            Debug.Assert(feed != null, "feed != null");

            ClientEdmModel       edmModel       = this.MaterializerContext.Model;
            ClientTypeAnnotation collectionType = edmModel.GetClientTypeAnnotation(edmModel.GetOrCreateEdmType(property.ResourceSetItemType));

            IEnumerable <ODataResource> entries = MaterializerFeed.GetFeed(feed).Entries;

            foreach (ODataResource feedEntry in entries)
            {
                this.Materialize(MaterializerEntry.GetEntry(feedEntry), collectionType.ElementType, includeLinks);
            }

            ProjectionPlan continuationPlan = includeLinks ?
                                              ODataEntityMaterializer.CreatePlanForDirectMaterialization(property.ResourceSetItemType) :
                                              ODataEntityMaterializer.CreatePlanForShallowMaterialization(property.ResourceSetItemType);

            this.ApplyItemsToCollection(
                entry,
                property,
                entries.Select(e => MaterializerEntry.GetEntry(e).ResolvedObject),
                feed.NextPageLink,
                continuationPlan,
                false);
        }
        public void SetFeedSerializationInfoShouldThrowOnNullFeed()
        {
            ODataResourceSet resourceCollection = null;
            Action           action             = () => resourceCollection.SetSerializationInfo(null);

            Assert.Throws <ArgumentNullException>("resourceSet", action);
        }
Beispiel #18
0
        private async Task WriteNavigationNextLink(OeEntryFactory parentEntryFactory, ExpandedNavigationSelectItem item, Object value)
        {
            Uri?nextPageLink = new OeNextPageLinkBuilder(_queryContext).GetNavigationUri(parentEntryFactory, item, value);

            if (nextPageLink == null)
            {
                return;
            }

            var  segment      = (NavigationPropertySegment)item.PathToNavigationProperty.LastSegment;
            bool isCollection = segment.NavigationProperty.Type.IsCollection();
            var  resourceInfo = new ODataNestedResourceInfo()
            {
                IsCollection = isCollection,
                Name         = segment.NavigationProperty.Name
            };
            await _writer.WriteStartAsync(resourceInfo).ConfigureAwait(false);

            if (isCollection)
            {
                var resourceSet = new ODataResourceSet()
                {
                    NextPageLink = nextPageLink
                };
                await _writer.WriteStartAsync(resourceSet).ConfigureAwait(false);

                await _writer.WriteEndAsync().ConfigureAwait(false);
            }
            else
            {
                resourceInfo.Url = nextPageLink;
            }

            await _writer.WriteEndAsync().ConfigureAwait(false);
        }
Beispiel #19
0
        public void CreateResourceSet_Ignores_CountValue_ForInnerResourceSets()
        {
            // Arrange
            ODataResourceSetSerializer serializer = new ODataResourceSetSerializer(_serializerProvider);
            var request = RequestFactory.Create();

            request.ODataContext().TotalCount = 42;
            var result = new object[0];
            IEdmNavigationProperty navProp            = _customerSet.EntityType().NavigationProperties().First();
            SelectExpandClause     selectExpandClause = new SelectExpandClause(new SelectItem[0], allSelected: true);
            ResourceContext        entity             = new ResourceContext
            {
                SerializerContext =
                    new ODataSerializerContext {
                    Request = request, NavigationSource = _customerSet, Model = _model
                }
            };
            ODataSerializerContext nestedContext = new ODataSerializerContext(entity, selectExpandClause, navProp);

            // Act
            ODataResourceSet resourceSet = serializer.CreateResourceSet(result, _customersType, nestedContext);

            // Assert
            Assert.Null(resourceSet.Count);
        }
Beispiel #20
0
        public void CreateResourceSet_SetsODataOperations()
        {
            // Arrange
            var config  = RoutingConfigurationFactory.CreateWithRootContainer("OData");
            var request = RequestFactory.Create(config, "OData");
            CustomersModelWithInheritance model         = new CustomersModelWithInheritance();
            IEdmCollectionTypeReference   customersType = new EdmCollectionTypeReference(new EdmCollectionType(model.Customer.AsReference()));
            ODataResourceSetSerializer    serializer    = new ODataResourceSetSerializer(_serializerProvider);
            ODataSerializerContext        context       = new ODataSerializerContext
            {
                NavigationSource = model.Customers,
                Request          = request,
                Model            = model.Model,
                MetadataLevel    = ODataMetadataLevel.FullMetadata,
                Url = CreateMetadataLinkFactory("http://IgnoreMetadataPath", request)
            };

            var result = new object[0];

            // Act
            ODataResourceSet resourceSet = serializer.CreateResourceSet(result, customersType, context);

            // Assert
            Assert.Single(resourceSet.Actions);
            Assert.Equal(3, resourceSet.Functions.Count());
        }
Beispiel #21
0
        public void CreateResourceSet_SetsNextPageLink_WhenWritingTruncatedCollection_ForExpandedProperties()
        {
            // Arrange
            CustomersModelWithInheritance model              = new CustomersModelWithInheritance();
            IEdmCollectionTypeReference   customersType      = new EdmCollectionTypeReference(new EdmCollectionType(model.Customer.AsReference()));
            ODataResourceSetSerializer    serializer         = new ODataResourceSetSerializer(_serializerProvider);
            SelectExpandClause            selectExpandClause = new SelectExpandClause(new SelectItem[0], allSelected: true);
            IEdmNavigationProperty        ordersProperty     = model.Customer.NavigationProperties().First();
            ResourceContext entity = new ResourceContext
            {
                SerializerContext = new ODataSerializerContext {
                    NavigationSource = model.Customers, Model = model.Model
                }
            };
            ODataSerializerContext      nestedContext = new ODataSerializerContext(entity, selectExpandClause, ordersProperty);
            TruncatedCollection <Order> orders        = new TruncatedCollection <Order>(new[] { new Order(), new Order() }, pageSize: 1);

            NavigationSourceLinkBuilderAnnotation linkBuilder = new NavigationSourceLinkBuilderAnnotation();

            linkBuilder.AddNavigationPropertyLinkBuilder(ordersProperty,
                                                         new NavigationLinkBuilder((entityContext, navigationProperty) => new Uri("http://navigation-link/"),
                                                                                   false));

            model.Model.SetNavigationSourceLinkBuilder(model.Customers, linkBuilder);
            model.Model.SetNavigationSourceLinkBuilder(model.Orders, new NavigationSourceLinkBuilderAnnotation());

            // Act
            ODataResourceSet resourceSet = serializer.CreateResourceSet(orders, _customersType, nestedContext);

            // Assert
            Assert.Equal("http://navigation-link/?$skip=1", resourceSet.NextPageLink.AbsoluteUri);
        }
Beispiel #22
0
        public void WriteObjectInline_Sets_NextPageLink_OnWriteEnd()
        {
            // Arrange
            IEnumerable      instance    = new object[0];
            ODataResourceSet resourceSet = new ODataResourceSet {
                NextPageLink = new Uri("http://nextlink.com/")
            };
            Mock <ODataResourceSetSerializer> serializer = new Mock <ODataResourceSetSerializer>(_serializerProvider);

            serializer.CallBase = true;
            serializer.Setup(s => s.CreateResourceSet(instance, _customersType, _writeContext)).Returns(resourceSet);
            var mockWriter = new Mock <ODataWriter>();

            mockWriter.Setup(m => m.WriteStart(It.Is <ODataResourceSet>(f => f.NextPageLink == null))).Verifiable();
            mockWriter
            .Setup(m => m.WriteEnd())
            .Callback(() =>
            {
                Assert.Equal("http://nextlink.com/", resourceSet.NextPageLink.AbsoluteUri);
            })
            .Verifiable();

            // Act
            serializer.Object.WriteObjectInline(instance, _customersType, mockWriter.Object, _writeContext);

            // Assert
            mockWriter.Verify();
        }
Beispiel #23
0
        private async Task SerializeAsync(ODataWriter writer)
        {
            var resourceSet = new ODataResourceSet()
            {
                Count = Count
            };

            writer.WriteStart(resourceSet);

            int count  = 0;
            T   entity = default;
            EntityPropertiesInfo entityPropertiesInfo = default;

            while (await _entities.MoveNext())
            {
                entity = _entities.Current;
                _stack.Add(entity);
                WriteEntry(writer, entity, ref entityPropertiesInfo);
                _stack.Remove(entity);
                count++;
            }

            if (PageSize > 0 && count > 0 && (Count ?? Int32.MaxValue) > count)
            {
                resourceSet.NextPageLink = BuildNextPageLink(OeSkipTokenParser.GetSkipToken(_edmModel, GetKeys(entity)));
            }

            writer.WriteEnd();
        }
 private static void WriteAndValidate(ODataResourceSet collectionStart, IEnumerable <ODataResource> items, string expectedPayload, bool writingResponse = true, IEdmTypeReference itemTypeReference = null)
 {
     WriteAndValidateSync(itemTypeReference, collectionStart, items, expectedPayload, writingResponse);
     WriteAndValidateAsync(itemTypeReference, collectionStart, items, expectedPayload, writingResponse);
     WriteAndValidatePrimitivesSync(itemTypeReference, collectionStart, items, expectedPayload, writingResponse);
     WriteAndValidatePrimitivesAsync(itemTypeReference, collectionStart, items, expectedPayload, writingResponse);
 }
Beispiel #25
0
            /// <summary>
            /// Visits a feed item.
            /// </summary>
            /// <param name="feed">The feed to visit.</param>
            protected override ODataPayloadElement VisitFeed(ODataResourceSet resourceCollection)
            {
                ExceptionUtilities.CheckArgumentNotNull(resourceCollection, "feed");

                EntitySetInstance entitySet = new EntitySetInstance()
                {
                    InlineCount = resourceCollection.Count,
                    NextLink    = resourceCollection.NextPageLink == null ? null : resourceCollection.NextPageLink.OriginalString
                };

                if (resourceCollection.Id != null)
                {
                    entitySet.AtomId(UriUtils.UriToString(resourceCollection.Id));
                }

                // now check for the entries annotation on the feed
                IEnumerable <ODataResource> entries = resourceCollection.Entries();

                if (entries != null)
                {
                    foreach (ODataResource entry in entries)
                    {
                        entitySet.Add(this.Visit(entry));
                    }
                }

                return(entitySet);
            }
Beispiel #26
0
        public void DefaultValuesTest()
        {
            ODataResourceSet resourceCollection = new ODataResourceSet();

            this.Assert.IsNull(resourceCollection.Count, "Expected null default value for property 'Count'.");
            this.Assert.IsNull(resourceCollection.NextPageLink, "Expected null default value for property 'NextPageLink'.");
        }
Beispiel #27
0
        private ODataResourceSet GetResourceSet(IEnumerable enumerable, IEdmTypeReference resourceSetType, IEdmStructuredTypeReference elementType,
                                                ODataSerializerContext writeContext)
        {
            ODataResourceSet resourceSet = CreateResourceSet(enumerable, resourceSetType.AsCollection(), writeContext);

            if (resourceSet == null)
            {
                throw new SerializationException(Error.Format(SRResources.CannotSerializerNull, ResourceSet));
            }

            IEdmEntitySetBase entitySet = writeContext.NavigationSource as IEdmEntitySetBase;

            if (entitySet == null)
            {
                resourceSet.SetSerializationInfo(new ODataResourceSerializationInfo
                {
                    IsFromCollection = true,
                    NavigationSourceEntityTypeName = elementType.FullName(),
                    NavigationSourceKind           = EdmNavigationSourceKind.UnknownEntitySet,
                    NavigationSourceName           = null
                });
            }

            return(resourceSet);
        }
Beispiel #28
0
        public void ComplexTypeCollectionRoundtripJsonLightTest()
        {
            ODataResource subject0 = new ODataResource()
            {
                TypeName = "NS.Subject", Properties = new[] { new ODataProperty()
                                                              {
                                                                  Name = "Name", Value = "English"
                                                              }, new ODataProperty()
                                                              {
                                                                  Name = "Score", Value = (Int16)98
                                                              } }
            };
            ODataResource subject1 = new ODataResource()
            {
                TypeName = "NS.Subject", Properties = new[] { new ODataProperty()
                                                              {
                                                                  Name = "Name", Value = "Math"
                                                              }, new ODataProperty()
                                                              {
                                                                  Name = "Score", Value = (Int16)90
                                                              } }
            };
            ODataResourceSet complexCollection = new ODataResourceSet {
                TypeName = "Collection(NS.Subject)"
            };

            this.VerifyComplexRoundtrip("Subjects", complexCollection, subject0, subject1);
        }
        private void WriteEntry(ODataWriter odataWriter, int dataSizeKb)
        {
            var entry = new ODataResource
            {
                Id         = new Uri("http://www.odata.org/Perf.svc/Item(1)"),
                EditLink   = new Uri("Item(1)", UriKind.Relative),
                ReadLink   = new Uri("Item(1)", UriKind.Relative),
                TypeName   = "PerformanceServices.Edm.ExchangeAttachment.Item",
                Properties = new[]
                {
                    new ODataProperty {
                        Name = "HasAttachments", Value = false
                    },
                }
            };

            var attachmentsP = new ODataNestedResourceInfo()
            {
                Name = "Attachments", IsCollection = true
            };

            var attachmentsResourceSet = new ODataResourceSet()
            {
                TypeName = "Collection(PerformanceServices.Edm.ExchangeAttachment.Attachment)"
            };

            var attachment = dataSizeKb == 0 ? null
                : new ODataResource()
            {
                TypeName   = "PerformanceServices.Edm.ExchangeAttachment.Attachment",
                Properties = new[]
                {
                    new ODataProperty {
                        Name = "Name", Value = "attachment"
                    },
                    new ODataProperty {
                        Name = "IsInline", Value = false
                    },
                    new ODataProperty {
                        Name = "LastModifiedTime", Value = new DateTimeOffset(1987, 6, 5, 4, 3, 21, 0, new TimeSpan(0, 0, 3, 0))
                    },
                    new ODataProperty {
                        Name = "Content", Value = new byte[dataSizeKb * 1024]
                    },
                }
            };

            odataWriter.WriteStart(entry);
            odataWriter.WriteStart(attachmentsP);
            odataWriter.WriteStart(attachmentsResourceSet);
            if (attachment != null)
            {
                odataWriter.WriteStart(attachment);
                odataWriter.WriteEnd();
            }
            odataWriter.WriteEnd();
            odataWriter.WriteEnd();
            odataWriter.WriteEnd();
        }
 internal void SetId(ODataResourceSet feed, Func <Uri> computeIdentity)
 {
     Debug.Assert(feed != null, "feed != null");
     if (this.interpreter.ShouldIncludeFeedMetadata(PayloadMetadataKind.Feed.Id))
     {
         feed.Id = computeIdentity();
     }
 }