internal EntryPropertiesValueCache(ODataEntry entry)
 {
     if (entry.Properties != null)
     {
         this.entryPropertiesCache = new List<ODataProperty>(entry.Properties);
     }
 }
        private ODataEntryAnnotations CreateAnnotations(Microsoft.Data.OData.ODataEntry odataEntry)
        {
            string id       = null;
            Uri    readLink = null;
            Uri    editLink = null;

            if (_session.Adapter.GetMetadata().IsTypeWithId(odataEntry.TypeName))
            {
                id       = odataEntry.Id;
                readLink = odataEntry.ReadLink;
                editLink = odataEntry.EditLink;
            }

            return(new ODataEntryAnnotations
            {
                Id = id,
                TypeName = odataEntry.TypeName,
                ReadLink = readLink,
                EditLink = editLink,
                ETag = odataEntry.ETag,
                AssociationLinks = odataEntry.AssociationLinks == null
                    ? null
                    : new List <ODataEntryAnnotations.AssociationLink>(
                    odataEntry.AssociationLinks.Select(x => new ODataEntryAnnotations.AssociationLink
                {
                    Name = x.Name,
                    Uri = x.Url,
                })),
                MediaResource = CreateAnnotations(odataEntry.MediaResource),
                InstanceAnnotations = odataEntry.InstanceAnnotations,
            });
        }
Beispiel #3
0
 private MaterializerEntry(ODataEntry entry, DataServiceProtocolVersion maxProtocolVersion)
 {
     this.entry = entry;
     this.entityDescriptor = new System.Data.Services.Client.EntityDescriptor(maxProtocolVersion);
     SerializationTypeNameAnnotation annotation = entry.GetAnnotation<SerializationTypeNameAnnotation>();
     this.entityDescriptor.ServerTypeName = (annotation != null) ? annotation.TypeName : (this.entityDescriptor.ServerTypeName = this.Entry.TypeName);
 }
        private void TryAnnotateV2FeedPackage(ODataEntry entry, EntityInstanceContext entityInstanceContext)
        {
            var instance = entityInstanceContext.EntityInstance as V2FeedPackage;
            if (instance != null)
            {
                // Set Atom entry metadata
                var atomEntryMetadata = new AtomEntryMetadata();
                atomEntryMetadata.Title = instance.Id;
                if (!string.IsNullOrEmpty(instance.Authors))
                {
                    atomEntryMetadata.Authors = new[] { new AtomPersonMetadata { Name = instance.Authors } };
                }
                if (instance.LastUpdated > DateTime.MinValue)
                {
                    atomEntryMetadata.Updated = instance.LastUpdated;
                }
                if (!string.IsNullOrEmpty(instance.Summary))
                {
                    atomEntryMetadata.Summary = instance.Summary;
                }
                entry.SetAnnotation(atomEntryMetadata);

                // Add package download link
                entry.MediaResource = new ODataStreamReferenceValue
                {
                    ContentType = ContentType,
                    ReadLink = BuildLinkForStreamProperty("v2", instance.Id, instance.Version, entityInstanceContext.Request)
                };
            }
        }
Beispiel #5
0
 protected override void EndEntry(ODataEntry entry)
 {
     if (entry != null)
     {
         ProjectedPropertiesAnnotation projectedProperties = entry.GetAnnotation<ProjectedPropertiesAnnotation>();
         this.jsonEntryAndFeedSerializer.WriteProperties(base.EntryEntityType, entry.Properties, false, base.DuplicatePropertyNamesChecker, projectedProperties);
         this.jsonOutputContext.JsonWriter.EndObjectScope();
     }
 }
        public void ConvertFeed(Uri relativeODataUri, Uri relativeSodaUri, JsonPayload jsonPayload,
		                        DateTimeOffset feedUpdateTime)
        {
            var jsonObject = jsonPayload.JsonObject;

            var entries = jsonObject.PropertyValue<JArray>("entries");
            var meta = jsonObject.PropertyValue<JObject>("meta");
            var view = meta.PropertyValue<JObject>("view");

            IList<string> fieldsToIgnore;
            var model = BuildModel(view, out fieldsToIgnore);

            var entitySet = model.EntityContainers.Single().EntitySets().Single();

            var settings = new ODataMessageWriterSettings
                           	{
                           		Indent = true,
                           	};

            using (var writer = new ODataMessageWriter(Message, settings, model))
            {
                var feedWriter = writer.CreateODataFeedWriter();

                var feed = new ODataFeed();

                feed.SetAnnotation(new AtomFeedMetadata
                                   	{
                                   		Updated = feedUpdateTime,
                                   	});

                feed.Id = new Uri(ODataEndpointUri, relativeODataUri.OriginalString).OriginalString;

                feedWriter.WriteStart(feed);
                foreach (var entry in entries.Cast<JObject>())
                {
                    var entryMetadata = new ODataEntry();
                    entryMetadata.Id = (string) ((JValue) entry.Property("id").Value).Value;
                    entryMetadata.TypeName = entitySet.ElementType.FullName();

                    entryMetadata.Properties = ConvertProperties(entry, fieldsToIgnore);

                    entryMetadata.SetAnnotation(new AtomEntryMetadata
                                                    {
                                                        Updated = ConvertDateTimeOffset(entry.PrimitivePropertyValue<long>("updated_at")),
                                                        Published = ConvertDateTimeOffset(entry.PrimitivePropertyValue<long>("created_at")),
                                                    });

                    feedWriter.WriteStart(entryMetadata);
                    feedWriter.WriteEnd();
                }

                feedWriter.WriteEnd();
            }
        }
Beispiel #7
0
 protected override void StartEntry(ODataEntry entry)
 {
     if (entry == null)
     {
         this.jsonOutputContext.JsonWriter.WriteValue((string) null);
     }
     else
     {
         this.jsonOutputContext.JsonWriter.StartObjectScope();
         ProjectedPropertiesAnnotation projectedProperties = entry.GetAnnotation<ProjectedPropertiesAnnotation>();
         this.jsonEntryAndFeedSerializer.WriteEntryMetadata(entry, projectedProperties, base.EntryEntityType, base.DuplicatePropertyNamesChecker);
     }
 }
        private void WriteLink(ODataWriter entryWriter, Microsoft.Data.OData.ODataEntry entry, string linkName, IEnumerable <ReferenceLink> links)
        {
            var navigationProperty = (_model.FindDeclaredType(entry.TypeName) as IEdmEntityType).NavigationProperties()
                                     .BestMatch(x => x.Name, linkName, _session.Settings.NameMatchResolver);
            bool isCollection = navigationProperty.Type.Definition.TypeKind == EdmTypeKind.Collection;

            var linkType        = GetNavigationPropertyEntityType(navigationProperty);
            var linkTypeWithKey = linkType;

            while (linkTypeWithKey.DeclaredKey == null && linkTypeWithKey.BaseEntityType() != null)
            {
                linkTypeWithKey = linkTypeWithKey.BaseEntityType();
            }

            entryWriter.WriteStart(new ODataNavigationLink()
            {
                Name         = linkName,
                IsCollection = isCollection,
                Url          = new Uri(ODataNamespace.Related + linkType, UriKind.Absolute),
            });

            foreach (var referenceLink in links)
            {
                var    linkKey   = linkTypeWithKey.DeclaredKey;
                var    linkEntry = referenceLink.LinkData.ToDictionary();
                var    contentId = GetContentId(referenceLink);
                string linkUri;
                if (contentId != null)
                {
                    linkUri = "$" + contentId;
                }
                else
                {
                    bool isSingleton;
                    var  formattedKey = _session.Adapter.GetCommandFormatter().ConvertKeyValuesToUriLiteral(
                        linkKey.ToDictionary(x => x.Name, x => linkEntry[x.Name]), true);
                    var linkedCollectionName = _session.Metadata.GetLinkedCollectionName(
                        referenceLink.LinkData.GetType().Name, linkTypeWithKey.Name, out isSingleton);
                    linkUri = linkedCollectionName + (isSingleton ? string.Empty : formattedKey);
                }
                var link = new ODataEntityReferenceLink
                {
                    Url = Utils.CreateAbsoluteUri(_session.Settings.BaseUri.AbsoluteUri, linkUri)
                };

                entryWriter.WriteEntityReferenceLink(link);
            }

            entryWriter.WriteEnd();
        }
Beispiel #9
0
 public static MaterializerEntry CreateEntry(ODataEntry entry, DataServiceProtocolVersion maxProtocolVersion)
 {
     MaterializerEntry annotation = new MaterializerEntry(entry, maxProtocolVersion);
     entry.SetAnnotation<MaterializerEntry>(annotation);
     if (entry.Id == null)
     {
         throw System.Data.Services.Client.Error.InvalidOperation(System.Data.Services.Client.Strings.Deserialize_MissingIdElement);
     }
     annotation.EntityDescriptor.Identity = entry.Id;
     annotation.EntityDescriptor.EditLink = entry.EditLink;
     annotation.EntityDescriptor.SelfLink = entry.ReadLink;
     annotation.EntityDescriptor.ETag = entry.ETag;
     return annotation;
 }
        ODataResponse IODataView.CreateView()
        {
            var oDataResponse = new ODataResponse();
            var messageWriter = new ODataMessageWriter(oDataResponse);

            var entryWriter = messageWriter.CreateODataFeedWriter();
            var feed = new ODataFeed() { Count = Videos.Count, Id = "Hypermedia-Learning" };
            var atomFeed = feed.Atom();
            atomFeed.Title = "Hypermedia API - " + PageTitle;

            entryWriter.WriteStart(feed);
            foreach (var video in Videos)
            {
                var oDataEntry = new ODataEntry() {};
                var atom = oDataEntry.Atom();

                atom.Title = "Video : " + video.Link.Title;
                atom.Summary = video.Description;
                entryWriter.WriteStart(oDataEntry);

                entryWriter.WriteEnd();

            }

            foreach (var item in Community)
            {
                var oDataEntry = new ODataEntry() { };
                var atom = oDataEntry.Atom();

                atom.Title = "Community : " + item.Link.Title;
                atom.Summary = item.Description;
                entryWriter.WriteStart(oDataEntry);

                entryWriter.WriteEnd();

            }

            entryWriter.WriteEnd();
            entryWriter.Flush();
            oDataResponse.GetStream().Position = 0;
            return oDataResponse;
        }
        private ODataEntryAnnotations CreateAnnotations(Microsoft.Data.OData.ODataEntry odataEntry)
        {
            string?id       = null;
            Uri?   readLink = null;
            Uri?   editLink = null;
            IEnumerable <ODataAssociationLink>?associationLinks = null;

            if (_session.Adapter.GetMetadata().IsTypeWithId(odataEntry.TypeName))
            {
                try
                {
                    id               = odataEntry.Id;
                    readLink         = odataEntry.ReadLink;
                    editLink         = odataEntry.EditLink;
                    associationLinks = odataEntry.AssociationLinks;
                }
                catch (ODataException)
                {
                    // Ignored
                }
            }

            return(new ODataEntryAnnotations
            {
                Id = id,
                TypeName = odataEntry.TypeName,
                ReadLink = readLink,
                EditLink = editLink,
                ETag = odataEntry.ETag,
                AssociationLinks = associationLinks == null
                                        ? null
                                        : new List <ODataEntryAnnotations.AssociationLink>(
                    odataEntry.AssociationLinks.Select(x => new ODataEntryAnnotations.AssociationLink
                {
                    Name = x.Name,
                    Uri = x.Url,
                })),
                MediaResource = CreateAnnotations(odataEntry.MediaResource),
                InstanceAnnotations = odataEntry.InstanceAnnotations,
            });
        }
        private void WriteEntry(object graph, IEnumerable<ODataProperty> propertyBag, ODataWriter writer, ODataSerializerContext writeContext)
        {
            IEdmEntityType entityType = _edmEntityTypeReference.EntityDefinition();
            EntityInstanceContext entityInstanceContext = new EntityInstanceContext(SerializerProvider.EdmModel, writeContext.EntitySet, entityType, writeContext.UrlHelper, graph, writeContext.SkipExpensiveAvailabilityChecks);

            ODataEntry entry = new ODataEntry
            {
                TypeName = _edmEntityTypeReference.FullName(),
                Properties = propertyBag,
                Actions = CreateActions(entityInstanceContext)
            };

            if (writeContext.EntitySet != null)
            {
                IEntitySetLinkBuilder linkBuilder = SerializerProvider.EdmModel.GetEntitySetLinkBuilder(writeContext.EntitySet);

                string idLink = linkBuilder.BuildIdLink(entityInstanceContext);
                if (idLink != null)
                {
                    entry.Id = idLink;
                }

                Uri readLink = linkBuilder.BuildReadLink(entityInstanceContext);
                if (readLink != null)
                {
                    entry.ReadLink = readLink;
                }

                Uri editLink = linkBuilder.BuildEditLink(entityInstanceContext);
                if (editLink != null)
                {
                    entry.EditLink = editLink;
                }
            }

            writer.WriteStart(entry);
            WriteNavigationLinks(entityInstanceContext, writer, writeContext);
            writer.WriteEnd();
        }
        private Microsoft.Data.OData.ODataEntry CreateODataEntry(string typeName, IDictionary <string, object> properties)
        {
            var entry = new Microsoft.Data.OData.ODataEntry()
            {
                TypeName = typeName
            };

            var typeProperties = (_model.FindDeclaredType(entry.TypeName) as IEdmEntityType).Properties();
            Func <string, string> findMatchingPropertyName = name =>
            {
                var property = typeProperties.BestMatch(y => y.Name, name, _session.Settings.NameMatchResolver);
                return(property != null ? property.Name : name);
            };

            entry.Properties = properties.Select(x => new ODataProperty()
            {
                Name  = findMatchingPropertyName(x.Key),
                Value = GetPropertyValue(typeProperties, x.Key, x.Value)
            }).ToList();

            return(entry);
        }
        private void createUpdateOperationRequestMessage(ref ODataBatchWriter writer, Change change, string tableName, string[] headers)
        {
            string id = this.getKeyType(tableName).IsString() ? "'" + change.id + "'" : change.id;
            Uri uri = new Uri(tableName + "(" + id + ")", UriKind.Relative);
            
            var updateOperaitonMessage = writer.CreateOperationRequestMessage("PATCH", uri);
            updateOperaitonMessage.SetHeader("Content-Type", "application/json");
             

            using (var operationMessageWriter = new ODataMessageWriter(updateOperaitonMessage))
            {
                var entityWriter = operationMessageWriter.CreateODataEntryWriter();
                var entry = new ODataEntry()
                {
                    Properties = createOperationProperties(change.data, tableName, headers),
                    TypeName = this.GetEntityTypeName(tableName)
                };
                entityWriter.WriteStart(entry);
                entityWriter.WriteEnd();
            }
        }
        public void AddTypeNameAnnotationAsNeeded_AddsAnnotation_InJsonLightMetadataMode()
        {
            // Arrange
            string expectedTypeName = "TypeName";
            ODataEntry entry = new ODataEntry
            {
                TypeName = expectedTypeName
            };

            // Act
            ODataEntityTypeSerializer.AddTypeNameAnnotationAsNeeded(entry, null, ODataMetadataLevel.MinimalMetadata);

            // Assert
            SerializationTypeNameAnnotation annotation = entry.GetAnnotation<SerializationTypeNameAnnotation>();
            Assert.NotNull(annotation); // Guard
            Assert.Equal(expectedTypeName, annotation.TypeName);
        }
        public void ShouldSuppressTypeNameSerialization(string entryType, string entitySetType,
            TestODataMetadataLevel metadataLevel, bool expectedResult)
        {
            // Arrange
            ODataEntry entry = new ODataEntry
            {
                // The caller uses a namespace-qualified name, which this test leaves empty.
                TypeName = "." + entryType
            };
            IEdmEntitySet entitySet = CreateEntitySetWithElementTypeName(entitySetType);

            // Act
            bool actualResult = ODataEntityTypeSerializer.ShouldSuppressTypeNameSerialization(entry, entitySet,
                (ODataMetadataLevel)metadataLevel);

            // Assert
            Assert.Equal(expectedResult, actualResult);
        }
        public void WriteObjectInline_WritesODataEntryFrom_CreateEntry()
        {
            // Arrange
            ODataEntry entry = new ODataEntry();
            Mock<ODataEntityTypeSerializer> serializer = new Mock<ODataEntityTypeSerializer>(_serializer.EdmType, _serializerProvider);
            Mock<ODataWriter> writer = new Mock<ODataWriter>();

            serializer.Setup(s => s.CreateEntry(It.IsAny<SelectExpandNode>(), It.IsAny<EntityInstanceContext>())).Returns(entry);
            serializer.CallBase = true;

            writer.Setup(s => s.WriteStart(entry)).Verifiable();

            // Act
            serializer.Object.WriteObjectInline(_customer, writer.Object, _writeContext);

            // Assert
            writer.Verify();
        }
        public void AddTypeNameAnnotationAsNeeded_DoesNotAddAnnotation_InDefaultMetadataMode()
        {
            // Arrange
            ODataEntry entry = new ODataEntry();

            // Act
            ODataEntityTypeSerializer.AddTypeNameAnnotationAsNeeded(entry, null, ODataMetadataLevel.Default);

            // Assert
            Assert.Null(entry.GetAnnotation<SerializationTypeNameAnnotation>());
        }
        /// <summary>
        /// Verifies that calling WriteStart entry is valid.
        /// </summary>
        /// <param name="synchronousCall">true if the call is to be synchronous; false otherwise.</param>
        /// <param name="entry">Entry/item to write.</param>
        private void VerifyCanWriteStartEntry(bool synchronousCall, ODataEntry entry)
        {
            this.VerifyNotDisposed();
            this.VerifyCallAllowed(synchronousCall);

            if (this.State != WriterState.NavigationLink)
            {
                ExceptionUtils.CheckArgumentNotNull(entry, "entry");
            }
        }
        /// <summary>
        /// Start writing an entry - implementation of the actual functionality.
        /// </summary>
        /// <param name="entry">Entry/item to write.</param>
        private void WriteStartEntryImplementation(ODataEntry entry)
        {
            this.StartPayloadInStartState();
            this.CheckForNavigationLinkWithContent(ODataPayloadKind.Entry);
            this.EnterScope(WriterState.Entry, entry);
            if (!this.SkipWriting)
            {
                this.IncreaseEntryDepth();
                this.InterceptException(() =>
                {
                    if (entry != null)
                    {
                        IEdmEntityType entityType = WriterValidationUtils.ValidateEntityTypeName(this.outputContext.Model, entry.TypeName);

                        // By default validate media resource
                        // In WCF DS Server mode, validate media resource (in writers)
                        // In WCF DS Client mode, do not validate media resource
                        bool validateMediaResource = this.outputContext.UseDefaultFormatBehavior || this.outputContext.UseServerFormatBehavior;
                        ValidationUtils.ValidateEntryMetadata(entry, entityType, this.outputContext.Model, validateMediaResource);

                        NavigationLinkScope parentNavigationLinkScope = this.ParentNavigationLinkScope;
                        if (parentNavigationLinkScope != null)
                        {
                            WriterValidationUtils.ValidateEntryInExpandedLink(entityType, parentNavigationLinkScope.NavigationPropertyType);
                        }

                        // Validate the consistenty of entity types in feeds
                        if (this.CurrentFeedValidator != null)
                        {
                            this.CurrentFeedValidator.ValidateEntry(entityType);
                        }

                        ((EntryScope)this.CurrentScope).EntityType = entityType;

                        WriterValidationUtils.ValidateEntryAtStart(entry);
                    }

                    this.StartEntry(entry);
                });
            }
        }
 /// <summary>
 /// Finish writing an entry.
 /// </summary>
 /// <param name="entry">The entry to write.</param>
 protected abstract void EndEntry(ODataEntry entry);
 /// <summary>
 /// Create a new entry scope.
 /// </summary>
 /// <param name="entry">The entry for the new scope.</param>
 /// <param name="skipWriting">true if the content of the scope to create should not be written.</param>
 /// <returns>The newly create scope.</returns>
 protected abstract EntryScope CreateEntryScope(ODataEntry entry, bool skipWriting);
        protected override async Task <Stream> WriteEntryContentAsync(string method, string collection, string commandText, IDictionary <string, object> entryData)
        {
#if SILVERLIGHT
            IODataRequestMessage
#else
            IODataRequestMessageAsync
#endif
            message = IsBatch
                ? await CreateOperationRequestMessageAsync(method, collection, entryData, commandText)
                : new ODataRequestMessage();

            var entityType = _model.FindDeclaredType(
                _session.Metadata.GetEntityCollectionQualifiedTypeName(collection)) as IEdmEntityType;
            var model = method == RestVerbs.Patch ? new EdmDeltaModel(_model, entityType, entryData.Keys) : _model;

            using (var messageWriter = new ODataMessageWriter(message, GetWriterSettings(), model))
            {
                if (method == RestVerbs.Get || method == RestVerbs.Delete)
                {
                    return(null);
                }

                var contentId = _deferredBatchWriter != null?_deferredBatchWriter.Value.GetContentId(entryData) : null;

                var entityCollection = _session.Metadata.GetEntityCollection(collection);
                var entryDetails     = _session.Metadata.ParseEntryDetails(entityCollection.Name, entryData, contentId);

                var entryWriter = messageWriter.CreateODataEntryWriter();
                var entry       = new Microsoft.Data.OData.ODataEntry();
                entry.TypeName = entityType.FullName();

                var typeProperties = (_model.FindDeclaredType(entry.TypeName) as IEdmEntityType).Properties();
                entry.Properties = entryDetails.Properties.Select(x => new ODataProperty()
                {
                    Name  = typeProperties.BestMatch(y => y.Name, x.Key, _session.Pluralizer).Name,
                    Value = GetPropertyValue(typeProperties, x.Key, x.Value)
                }).ToList();

                entryWriter.WriteStart(entry);

                if (entryDetails.Links != null)
                {
                    foreach (var link in entryDetails.Links)
                    {
                        if (link.Value.Any(x => x.LinkData != null))
                        {
                            WriteLink(entryWriter, entry, link.Key, link.Value);
                        }
                    }
                }

                entryWriter.WriteEnd();

                if (IsBatch)
                {
                    return(null);
                }

#if SILVERLIGHT
                return(message.GetStream());
#else
                return(await message.GetStreamAsync());
#endif
            }
        }
        internal static void AddTypeNameAnnotationAsNeeded(ODataEntry entry, IEdmEntitySet entitySet,
            ODataMetadataLevel metadataLevel)
        {
            // ODataLib normally has the caller decide whether or not to serialize properties by leaving properties
            // null when values should not be serialized. The TypeName property is different and should always be
            // provided to ODataLib to enable model validation. A separate annotation is used to decide whether or not
            // to serialize the type name (a null value prevents serialization).

            // Note that this annotation should not be used for Atom or JSON verbose formats, as it will interfere with
            // the correct default behavior for those formats.

            Contract.Assert(entry != null);

            // Only add an annotation if we want to override ODataLib's default type name serialization behavior.
            if (ShouldAddTypeNameAnnotation(metadataLevel))
            {
                string typeName;

                // Provide the type name to serialize (or null to force it not to serialize).
                if (ShouldSuppressTypeNameSerialization(entry, entitySet, metadataLevel))
                {
                    typeName = null;
                }
                else
                {
                    typeName = entry.TypeName;
                }

                entry.SetAnnotation<SerializationTypeNameAnnotation>(new SerializationTypeNameAnnotation
                {
                    TypeName = typeName
                });
            }
        }
        public void WriteObjectInline_WritesODataNavigationLinksFrom_CreateNavigationLinks()
        {
            // Arrange
            ODataNavigationLink[] navigationLinks = new[] { new ODataNavigationLink(), new ODataNavigationLink() };
            ODataEntry entry = new ODataEntry();
            Mock<ODataWriter> writer = new Mock<ODataWriter>();
            Mock<ODataEntityTypeSerializer> serializer = new Mock<ODataEntityTypeSerializer>(_serializer.EdmType, new DefaultODataSerializerProvider());

            writer.Setup(s => s.WriteStart(navigationLinks[0])).Verifiable();
            writer.Setup(s => s.WriteStart(navigationLinks[1])).Verifiable();
            serializer.Setup(s => s.CreateEntry(It.IsAny<EntityInstanceContext>(), _writeContext)).Returns(new ODataEntry());
            serializer.Setup(s => s.CreateNavigationLinks(It.IsAny<EntityInstanceContext>(), _writeContext)).Returns(navigationLinks);
            serializer.CallBase = true;

            // Act
            serializer.Object.WriteObjectInline(new object(), writer.Object, _writeContext);

            // Assert
            writer.Verify();
        }
        private static void WriteOdataEntity(ITableEntity entity, TableOperationType operationType, OperationContext ctx, ODataWriter writer)
        {
            ODataEntry entry = new ODataEntry()
            {
                Properties = GetPropertiesWithKeys(entity, ctx)
            };

            if (operationType != TableOperationType.Insert && operationType != TableOperationType.Retrieve)
            {
                entry.ETag = entity.ETag;
            }

            writer.WriteStart(entry);
            writer.WriteEnd();
            writer.Flush();
        }
        private ODataEntry CreateODataEntry(IGraph resultsGraph, string entryResource, string entryType)
        {
            var idPrefix = _map.GetResourceUriPrefix(entryType);
            if (!entryResource.StartsWith(idPrefix))
            {
                // Now we have a problem
                throw new Exception("Cannot create entry feed for resource " + entryResource +
                                    ". Resource URI does not start with the expected prefix " + idPrefix);
            }
            var resourceId = entryResource.Substring(idPrefix.Length);
            var odataLink = _baseUri + _map.GetTypeSet(entryType) + "('" + resourceId + "')";
            var entry = new ODataEntry
                {
                    TypeName = entryType,
                    ReadLink = new Uri(odataLink),
                    Id = odataLink
                };
            var subject = resultsGraph.CreateUriNode(UriFactory.Create(entryResource));
            var properties = new List<ODataProperty>();

            var identifierPropertyMapping = _map.GetIdentifierPropertyMapping(entryType);
            if (identifierPropertyMapping != null)
            {
                properties.Add(new ODataProperty{Name=identifierPropertyMapping.Name, Value=resourceId});
            }

            foreach (var propertyMapping in _map.GetStructuralPropertyMappings(entryType))
            {
                var predicate = resultsGraph.CreateUriNode(UriFactory.Create(propertyMapping.Uri));
                var match = resultsGraph.GetTriplesWithSubjectPredicate(subject, predicate).FirstOrDefault();
                if (match != null)
                {
                    if (match.Object is LiteralNode)
                    {
                        var newProperty = new ODataProperty
                            {
                                Name = propertyMapping.Name,
                                Value = GetValue(match.Object, propertyMapping.PropertyType)
                            };
                        properties.Add(newProperty);
                    }
                    else if (match.Object is UriNode && propertyMapping.PropertyType.IsPrimitive())
                    {
                        var newProperty = new ODataProperty()
                            {
                                Name = propertyMapping.Name,
                                Value = GetValue(match.Object, propertyMapping.PropertyType)
                            };
                        properties.Add(newProperty);
                    }
                }
            }

            

            if (_writerSettings.Version == null ||  _writerSettings.Version >= ODataVersion.V3)
            {
                var associationLinks = new List<ODataAssociationLink>();
                foreach (var assocMap in _map.GetAssociationPropertyMappings(entryType))
                {
                    var predicate = resultsGraph.CreateUriNode(UriFactory.Create(assocMap.Uri));
                    bool hasMatch = false;
                    if (assocMap.IsInverse)
                    {
                        hasMatch = resultsGraph.GetTriplesWithPredicateObject(predicate, subject).Any();
                    }
                    else
                    {
                        hasMatch = resultsGraph.GetTriplesWithSubjectPredicate(subject, predicate).Any();
                    }
                    // TODO: May need to be more specific here to catch inverse/forward versions of the same
                    // RDF property being mapped to two different OData properties (e.g. broader and narrower on a category)
                    // This quick hack will work for now though:
                    //bool hasMatch = resultsGraph.GetTriplesWithPredicate(resultsGraph.CreateUriNode(UriFactory.Create(assocMap.Uri))).Any();
                    if (hasMatch)
                    {
                        associationLinks.Add(new ODataAssociationLink
                            {
                                Name = assocMap.Name,
                                Url = new Uri(odataLink + "/$links/" + assocMap.Name)
                            });
                    }
                }
                entry.AssociationLinks = associationLinks;
            }

            entry.Properties = properties;
            return entry;
        }
        /// <summary>
        /// Creates the <see cref="ODataEntry"/> to be written while writing this entity.
        /// </summary>
        /// <param name="selectExpandNode">The <see cref="SelectExpandNode"/> describing the response graph.</param>
        /// <param name="entityInstanceContext">The context for the entity instance being written.</param>
        /// <returns>The created <see cref="ODataEntry"/>.</returns>
        public virtual ODataEntry CreateEntry(SelectExpandNode selectExpandNode, EntityInstanceContext entityInstanceContext)
        {
            if (selectExpandNode == null)
            {
                throw Error.ArgumentNull("selectExpandNode");
            }
            if (entityInstanceContext == null)
            {
                throw Error.ArgumentNull("entityInstanceContext");
            }

            string typeName = EntityType.FullName();

            ODataEntry entry = new ODataEntry
            {
                TypeName = typeName,
                Properties = CreateStructuralPropertyBag(selectExpandNode.SelectedStructuralProperties, entityInstanceContext),
                Actions = CreateODataActions(selectExpandNode.SelectedActions, entityInstanceContext)
            };

            AddTypeNameAnnotationAsNeeded(entry, entityInstanceContext.EntitySet, entityInstanceContext.SerializerContext.MetadataLevel);

            if (entityInstanceContext.EntitySet != null)
            {
                IEdmModel model = entityInstanceContext.SerializerContext.Model;
                EntitySetLinkBuilderAnnotation linkBuilder = model.GetEntitySetLinkBuilder(entityInstanceContext.EntitySet);
                EntitySelfLinks selfLinks = linkBuilder.BuildEntitySelfLinks(entityInstanceContext, entityInstanceContext.SerializerContext.MetadataLevel);

                if (selfLinks.IdLink != null)
                {
                    entry.Id = selfLinks.IdLink;
                }

                if (selfLinks.ReadLink != null)
                {
                    entry.ReadLink = selfLinks.ReadLink;
                }

                if (selfLinks.EditLink != null)
                {
                    entry.EditLink = selfLinks.EditLink;
                }
            }

            return entry;
        }
            /// <summary>
            /// Constructor to create a new entry scope.
            /// </summary>
            /// <param name="entry">The entry for the new scope.</param>
            /// <param name="skipWriting">true if the content of the scope to create should not be written.</param>
            /// <param name="writingResponse">true if we are writing a response, false if it's a request.</param>
            /// <param name="writerBehavior">The <see cref="ODataWriterBehavior"/> instance controlling the behavior of the writer.</param>
            internal EntryScope(ODataEntry entry, bool skipWriting, bool writingResponse, ODataWriterBehavior writerBehavior)
                : base(WriterState.Entry, entry, skipWriting)
            {
                DebugUtils.CheckNoExternalCallers();
                Debug.Assert(writerBehavior != null, "writerBehavior != null");

                if (entry != null)
                {
                    this.duplicatePropertyNamesChecker = new DuplicatePropertyNamesChecker(writerBehavior.AllowDuplicatePropertyNames, writingResponse);
                }
            }
        private static void WriteOdataEntity(ITableEntity entity, TableOperationType operationType, OperationContext ctx, ODataWriter writer, TableRequestOptions options)
        {
            ODataEntry entry = new ODataEntry()
            {
                Properties = GetPropertiesWithKeys(entity, ctx, operationType, options),
                TypeName = "account.sometype"
            };

            entry.SetAnnotation(new SerializationTypeNameAnnotation { TypeName = null });
            writer.WriteStart(entry);
            writer.WriteEnd();
            writer.Flush();
        }
 /// <summary>
 /// Start writing an entry.
 /// </summary>
 /// <param name="entry">Entry/item to write.</param>
 public sealed override void WriteStart(ODataEntry entry)
 {
     this.VerifyCanWriteStartEntry(true, entry);
     this.WriteStartEntryImplementation(entry);
 }
        /// <summary>
        /// Creates the <see cref="ODataEntry"/> to be written while writing this entity.
        /// </summary>
        /// <param name="entityInstanceContext">The context for the entity instance being written.</param>
        /// <param name="writeContext">The serializer write context.</param>
        /// <returns>The created <see cref="ODataEntry"/>.</returns>
        public virtual ODataEntry CreateEntry(EntityInstanceContext entityInstanceContext, ODataSerializerContext writeContext)
        {
            string typeName = EntityType.FullName();

            ODataEntry entry = new ODataEntry
            {
                TypeName = typeName,
                Properties = CreateStructuralPropertyBag(entityInstanceContext, writeContext),
                Actions = CreateODataActions(entityInstanceContext, writeContext)
            };

            AddTypeNameAnnotationAsNeeded(entry, writeContext.EntitySet, writeContext.MetadataLevel);

            if (writeContext.EntitySet != null)
            {
                IEdmModel model = writeContext.Model;
                EntitySetLinkBuilderAnnotation linkBuilder = model.GetEntitySetLinkBuilder(writeContext.EntitySet);
                EntitySelfLinks selfLinks = linkBuilder.BuildEntitySelfLinks(entityInstanceContext, writeContext.MetadataLevel);

                if (selfLinks.IdLink != null)
                {
                    entry.Id = selfLinks.IdLink;
                }

                if (selfLinks.ReadLink != null)
                {
                    entry.ReadLink = selfLinks.ReadLink;
                }

                if (selfLinks.EditLink != null)
                {
                    entry.EditLink = selfLinks.EditLink;
                }
            }

            return entry;
        }
 /// <summary>
 /// Asynchronously start writing an entry.
 /// </summary>
 /// <param name="entry">Entry/item to write.</param>
 /// <returns>A task instance that represents the asynchronous write operation.</returns>
 public sealed override Task WriteStartAsync(ODataEntry entry)
 {
     this.VerifyCanWriteStartEntry(false, entry);
     return TaskUtils.GetTaskForSynchronousOperation(() => this.WriteStartEntryImplementation(entry));
 }
        internal static bool ShouldSuppressTypeNameSerialization(ODataEntry entry, IEdmEntitySet entitySet,
            ODataMetadataLevel metadataLevel)
        {
            Contract.Assert(entry != null);

            Contract.Assert(metadataLevel != ODataMetadataLevel.Default);

            switch (metadataLevel)
            {
                case ODataMetadataLevel.NoMetadata:
                    return true;
                case ODataMetadataLevel.FullMetadata:
                    return false;
                case ODataMetadataLevel.MinimalMetadata:
                default: // All values already specified; just keeping the compiler happy.
                    string entitySetTypeName = GetElementTypeName(entitySet);
                    string entryTypeName = entry.TypeName;
                    return String.Equals(entryTypeName, entitySetTypeName, StringComparison.Ordinal);
            }
        }
 /// <summary>
 /// Start writing an entry.
 /// </summary>
 /// <param name="entry">The entry to write.</param>
 protected abstract void StartEntry(ODataEntry entry);