本文整理汇总了C#中Microsoft.OData.Core.ODataEntry.SetSerializationInfo方法的典型用法代码示例。如果您正苦于以下问题:C# ODataEntry.SetSerializationInfo方法的具体用法?C# ODataEntry.SetSerializationInfo怎么用?C# ODataEntry.SetSerializationInfo使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Microsoft.OData.Core.ODataEntry
的用法示例。
在下文中一共展示了ODataEntry.SetSerializationInfo方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: ShouldBeAbleToClearTheEntrySerializationInfo
public void ShouldBeAbleToClearTheEntrySerializationInfo()
{
ODataEntry entry = new ODataEntry();
ODataFeedAndEntrySerializationInfo serializationInfo = new ODataFeedAndEntrySerializationInfo { NavigationSourceName = "Set", NavigationSourceEntityTypeName = "ns.base", ExpectedTypeName = "ns.expected" };
entry.SerializationInfo = serializationInfo;
entry.SetSerializationInfo(null);
entry.SerializationInfo.Should().BeNull();
}
示例2: WriteAndVerifyRequestMessage
private string WriteAndVerifyRequestMessage(ODataMessageWriterSettings settings, string mimeType, bool hasModel)
{
// create an order entry to POST
var order = new ODataEntry()
{
TypeName = NameSpace + "Order"
};
var orderP1 = new ODataProperty { Name = "OrderId", Value = -10 };
var orderp2 = new ODataProperty { Name = "CustomerId", Value = 8212 };
var orderp3 = new ODataProperty { Name = "Concurrency", Value = null };
order.Properties = new[] { orderP1, orderp2, orderp3 };
if (!hasModel)
{
order.SetSerializationInfo(new ODataFeedAndEntrySerializationInfo() { NavigationSourceName = "Order", NavigationSourceEntityTypeName = NameSpace + "Order" });
orderP1.SetSerializationInfo(new ODataPropertySerializationInfo() { PropertyKind = ODataPropertyKind.Key });
}
Dictionary<string, object> expectedOrderObject = WritePayloadHelper.ComputeExpectedFullMetadataEntryObject(WritePayloadHelper.OrderType, "Order(-10)", order, hasModel);
// write the request message and read using ODL reader
var requestMessage = new StreamRequestMessage(new MemoryStream(), new Uri(this.ServiceUri + "Order"), "POST");
requestMessage.SetHeader("Content-Type", mimeType);
string result = string.Empty;
using (var messageWriter = this.CreateODataMessageWriter(requestMessage, settings, hasModel))
{
var odataWriter = this.CreateODataEntryWriter(messageWriter, WritePayloadHelper.OrderSet, WritePayloadHelper.OrderType, hasModel);
odataWriter.WriteStart(order);
odataWriter.WriteEnd();
Stream stream = requestMessage.GetStream();
result = WritePayloadHelper.ReadStreamContent(stream);
if (!mimeType.Contains(MimeTypes.ODataParameterNoMetadata))
{
stream.Seek(0, SeekOrigin.Begin);
var readerSetting = new ODataMessageReaderSettings() { BaseUri = this.ServiceUri };
ODataMessageReader messageReader = new ODataMessageReader(requestMessage, readerSetting, WritePayloadHelper.Model);
ODataReader reader = messageReader.CreateODataEntryReader(WritePayloadHelper.OrderSet, WritePayloadHelper.OrderType);
bool verifyEntryCalled = false;
while (reader.Read())
{
if (reader.State == ODataReaderState.EntryEnd)
{
ODataEntry entry = reader.Item as ODataEntry;
Assert.AreEqual(3, entry.Properties.Count(), "entry.Properties.Count");
verifyEntryCalled = true;
}
}
Assert.AreEqual(ODataReaderState.Completed, reader.State);
Assert.IsTrue(verifyEntryCalled, "verifyEntryCalled");
}
}
// For Json light, verify the resulting metadata is as expected
if (mimeType != MimeTypes.ApplicationAtomXml)
{
JavaScriptSerializer jScriptSerializer = new JavaScriptSerializer();
Dictionary<string, object> resultObject = jScriptSerializer.DeserializeObject(result) as Dictionary<string, object>;
// AutoComputePayloadMetadataInJson has no effect on request message metadata
Assert.AreEqual(this.ServiceUri + "$metadata#Order/$entity", resultObject.Single(e => e.Key == JsonLightConstants.ODataContextAnnotationName).Value);
resultObject.Remove(JsonLightConstants.ODataContextAnnotationName);
foreach (var pair in resultObject)
{
Assert.IsFalse(pair.Key.Contains("odata.") || pair.Key.StartsWith("#"));
}
}
return result;
}
示例3: Process
public override void Process(IODataRequestMessage requestMessage, IODataResponseMessage responseMessage)
{
var token = HttpUtility.ParseQueryString(RequestUri.Query).Get("$token");
if (string.IsNullOrEmpty(token))
{
deltaToken = "common";
}
else
{
deltaToken = token;
}
if (deltaToken == "common")
{
originalUri = new Uri(ServiceConstants.ServiceBaseUri, "Customers?$expand=Orders");
using (var messageWriter = this.CreateMessageWriter(responseMessage))
{
var entitySet = this.DataSource.Model.FindDeclaredEntitySet("Customers");
var entityType = entitySet.EntityType();
ODataDeltaWriter deltaWriter = messageWriter.CreateODataDeltaWriter(entitySet, entityType);
var deltaFeed = new ODataDeltaFeed();
var deltaEntry = new ODataEntry
{
Id = new Uri(ServiceConstants.ServiceBaseUri, entitySet.Name + "(1)"),
Properties = new[] {new ODataProperty {Name = "FirstName", Value = "GGGG"}}
};
var deletedLink = new ODataDeltaDeletedLink(
new Uri(ServiceConstants.ServiceBaseUri, entitySet.Name + "(1)"), new Uri(ServiceConstants.ServiceBaseUri, "Orders(8)"), "Orders");
var addedLink = new ODataDeltaLink(
new Uri(ServiceConstants.ServiceBaseUri, entitySet.Name + "(1)"), new Uri(ServiceConstants.ServiceBaseUri, "Orders(7)"), "Orders");
var navigationEntry = new ODataEntry
{
Id = new Uri(ServiceConstants.ServiceBaseUri, "Orders(100)"),
TypeName = "Microsoft.Test.OData.Services.ODataWCFService.Order",
Properties = new[]
{
new ODataProperty {Name = "OrderID", Value = 100},
new ODataProperty {Name = "OrderDate", Value = new DateTimeOffset(DateTime.Now)}
}
};
navigationEntry.SetSerializationInfo(new ODataFeedAndEntrySerializationInfo
{
NavigationSourceEntityTypeName = "Microsoft.Test.OData.Services.ODataWCFService.Order",
NavigationSourceKind = EdmNavigationSourceKind.EntitySet,
NavigationSourceName = "Orders"
});
var deletedEntry = new ODataDeltaDeletedEntry(
new Uri(ServiceConstants.ServiceBaseUri, entitySet.Name + "(2)").AbsoluteUri, DeltaDeletedEntryReason.Deleted);
deltaFeed.DeltaLink = new Uri(ServiceConstants.ServiceBaseUri, "$delta?$token=common");
deltaWriter.WriteStart(deltaFeed);
deltaWriter.WriteStart(deltaEntry);
deltaWriter.WriteEnd();
deltaWriter.WriteDeltaDeletedLink(deletedLink);
deltaWriter.WriteDeltaLink(addedLink);
deltaWriter.WriteStart(navigationEntry);
deltaWriter.WriteEnd();
deltaWriter.WriteDeltaDeletedEntry(deletedEntry);
deltaWriter.WriteEnd();
}
}
else if (deltaToken == "containment")
{
originalUri = new Uri(ServiceConstants.ServiceBaseUri, "Accounts(103)/MyPaymentInstruments?$expand=BillingStatements");
using (var messageWriter = this.CreateMessageWriter(responseMessage))
{
var accountsSet = this.DataSource.Model.FindDeclaredEntitySet("Accounts");
var accountType = accountsSet.EntityType();
var myPisNav = accountType.FindProperty("MyPaymentInstruments") as IEdmNavigationProperty;
var piSet = accountsSet.FindNavigationTarget(myPisNav);
var piType = piSet.EntityType();
ODataDeltaWriter deltaWriter = messageWriter.CreateODataDeltaWriter(piSet as IEdmContainedEntitySet, piType);
var deltaFeed = new ODataDeltaFeed();
var deltaEntry = new ODataEntry
{
Id = new Uri(ServiceConstants.ServiceBaseUri, "Accounts(103)/MyPaymentInstruments(103901)"),
Properties = new[] { new ODataProperty { Name = "FriendlyName", Value = "GGGG" } }
};
var deletedEntry = new ODataDeltaDeletedEntry(
new Uri(ServiceConstants.ServiceBaseUri, "Accounts(103)/MyPaymentInstruments(103901)/BillingStatements(103901001)").AbsoluteUri,
DeltaDeletedEntryReason.Deleted);
deletedEntry.SetSerializationInfo(new ODataDeltaSerializationInfo()
{
NavigationSourceName = "Accounts(103)/MyPaymentInstruments(103901)/BillingStatements"
});
var deletedLink = new ODataDeltaDeletedLink(
new Uri(ServiceConstants.ServiceBaseUri, "Accounts(103)/MyPaymentInstruments(103901)"),
new Uri(ServiceConstants.ServiceBaseUri, "Accounts(103)/MyPaymentInstruments(103901)/BillingStatements(103901001)"),
"BillingStatements");
var navigationEntry = new ODataEntry
{
Id = new Uri(ServiceConstants.ServiceBaseUri, "Accounts(103)/MyPaymentInstruments(103901)/BillingStatements(103901005)"),
TypeName = "Microsoft.Test.OData.Services.ODataWCFService.Statement",
//.........这里部分代码省略.........
示例4: CreateCarEntryNoMetadata
public static ODataEntry CreateCarEntryNoMetadata(bool hasModel)
{
var carEntry = new ODataEntry()
{
TypeName = NameSpace + "Car",
};
// properties and named streams
var carEntryP1 = new ODataProperty { Name = "VIN", Value = 11 };
var carEntryP2 = new ODataProperty
{
Name = "Description",
Value = "cenbviijieljtrtdslbuiqubcvhxhzenidqdnaopplvlqc"
};
carEntry.Properties = new[] { carEntryP1, carEntryP2 };
carEntry.InstanceAnnotations.Add(new ODataInstanceAnnotation("carEntry.AnnotationName",
new ODataPrimitiveValue(
"carEntryAnnotationValue")));
if (!hasModel)
{
carEntry.SetSerializationInfo(new ODataFeedAndEntrySerializationInfo() { NavigationSourceName = "Car", NavigationSourceEntityTypeName = NameSpace + "Car" });
carEntryP1.SetSerializationInfo(new ODataPropertySerializationInfo()
{
PropertyKind = ODataPropertyKind.Key
});
}
return carEntry;
}
示例5: ShouldBeAbleToWriteFeedAndEntryResponseInJsonLightWithoutModel
public void ShouldBeAbleToWriteFeedAndEntryResponseInJsonLightWithoutModel()
{
const string expectedPayload =
"{" +
"\"@odata.context\":\"http://www.example.com/$metadata#Customers/NS.VIPCustomer\"," +
"\"value\":[" +
"{" +
"\"Name\":\"Bob\"," +
"\"[email protected]\":\"MostRecentOrder\"," +
"\"MostRecentOrder\":{\"OrderId\":101}" +
"}" +
"]" +
"}";
var writerSettings = new ODataMessageWriterSettings { DisableMessageStreamDisposal = true };
writerSettings.SetContentType(ODataFormat.Json);
writerSettings.ODataUri = new ODataUri() { ServiceRoot = new Uri("http://www.example.com") };
MemoryStream stream = new MemoryStream();
IODataResponseMessage responseMessage = new InMemoryMessage { StatusCode = 200, Stream = stream };
// Write payload
using (var messageWriter = new ODataMessageWriter(responseMessage, writerSettings))
{
var odataWriter = messageWriter.CreateODataFeedWriter();
// Create customers feed with serializtion info to write odata.metadata.
var customersFeed = new ODataFeed();
customersFeed.SetSerializationInfo(new ODataFeedAndEntrySerializationInfo { NavigationSourceName = "Customers", NavigationSourceEntityTypeName = "NS.Customer", ExpectedTypeName = "NS.VIPCustomer" });
// Write customers feed.
odataWriter.WriteStart(customersFeed);
// Write VIP customer
{
// Create VIP customer, don't need to pass in serialization info since the writer knows the context from the feed scope.
var vipCustomer = new ODataEntry { TypeName = "NS.VIPCustomer" };
var customerKey = new ODataProperty { Name = "Name", Value = "Bob" };
// Provide serialization info at the property level to compute the edit link.
customerKey.SetSerializationInfo(new ODataPropertySerializationInfo { PropertyKind = ODataPropertyKind.Key });
vipCustomer.Properties = new[] { customerKey };
// Write customer entry.
odataWriter.WriteStart(vipCustomer);
// Write expanded most recent order
{
// No API to set serialization info on ODataNavigationLink since what we are adding on ODataFeed and ODataEntry should be sufficient for the 5.5 release.
var navigationLink = new ODataNavigationLink { Name = "MostRecentOrder", IsCollection = false, Url = new Uri("MostRecentOrder", UriKind.Relative) };
odataWriter.WriteStart(navigationLink);
// Write the most recent customer.
{
var mostRecentOrder = new ODataEntry { TypeName = "NS.Order" };
// Add serialization info so we can computer links.
mostRecentOrder.SetSerializationInfo(new ODataFeedAndEntrySerializationInfo { NavigationSourceName = "Orders", NavigationSourceEntityTypeName = "NS.Order", ExpectedTypeName = "NS.Order" });
var orderKey = new ODataProperty { Name = "OrderId", Value = 101 };
// Provide serialization info at the property level to compute the edit link.
orderKey.SetSerializationInfo(new ODataPropertySerializationInfo { PropertyKind = ODataPropertyKind.Key });
mostRecentOrder.Properties = new[] { orderKey };
// Write order entry.
odataWriter.WriteStart(mostRecentOrder);
odataWriter.WriteEnd();
}
// End navigationLink.
odataWriter.WriteEnd();
}
// End customer entry.
odataWriter.WriteEnd();
}
// End customers feed.
odataWriter.WriteEnd();
}
stream.Position = 0;
string payload = (new StreamReader(stream)).ReadToEnd();
payload.Should().Be(expectedPayload);
}
示例6: ShouldWritePayloadWhenExpandedFeedAndEntryHasSerializationInfo
public void ShouldWritePayloadWhenExpandedFeedAndEntryHasSerializationInfo()
{
List<ODataItem> itemsToWrite = new List<ODataItem>();
var entry1 = new ODataEntry();
entry1.SetSerializationInfo(new ODataFeedAndEntrySerializationInfo { NavigationSourceName = "MySet", NavigationSourceEntityTypeName = "NS.MyEntityType" });
itemsToWrite.Add(entry1);
itemsToWrite.Add(new ODataNavigationLink { Name = "EntitySetReferenceProperty", IsCollection = true });
var feed = new ODataFeed();
feed.SetSerializationInfo(new ODataFeedAndEntrySerializationInfo { NavigationSourceName = "MySet", NavigationSourceEntityTypeName = "NS.MyEntityType" });
itemsToWrite.Add(feed);
var entry2 = new ODataEntry();
entry2.SetSerializationInfo(new ODataFeedAndEntrySerializationInfo { NavigationSourceName = "MySet2", NavigationSourceEntityTypeName = "NS.MyEntityType2" });
itemsToWrite.Add(entry2);
const string expectedPayload = "{\"@odata.context\":\"http://odata.org/test/$metadata#MySet/$entity\",\"EntitySetReferenceProperty\":[{}]}";
this.WriteNestedItemsAndValidatePayload(entitySetFullName: null, derivedEntityTypeFullName: null, nestedItemToWrite: itemsToWrite.ToArray(), expectedPayload: expectedPayload, writingResponse: true);
}
示例7: CreateCustomerEntryNoMetadata
public static ODataEntry CreateCustomerEntryNoMetadata(bool hasModel)
{
var customerEntry = new ODataEntry()
{
TypeName = NameSpace + "Customer"
};
var customerEntryP1 = new ODataProperty { Name = "CustomerId", Value = -9 };
var customerEntryP2 = new ODataProperty { Name = "Name", Value = "CustomerName" };
var customerEntryP3 = new ODataProperty
{
Name = "PrimaryContactInfo",
Value = CreatePrimaryContactODataComplexValue()
};
var customerEntryP4 = new ODataProperty
{
Name = "BackupContactInfo",
Value = CreateBackupContactODataCollectionValue()
};
var customerEntryP5 = new ODataProperty
{
Name = "Auditing",
Value = CreateAuditInforODataComplexValue()
};
customerEntry.Properties = new[]
{
customerEntryP1, customerEntryP2, customerEntryP3, customerEntryP4, customerEntryP5,
};
if (!hasModel)
{
customerEntry.SetSerializationInfo(new ODataFeedAndEntrySerializationInfo() { NavigationSourceName = "Customer", NavigationSourceEntityTypeName = NameSpace + "Customer" });
customerEntryP1.SetSerializationInfo(new ODataPropertySerializationInfo()
{
PropertyKind = ODataPropertyKind.Key
});
}
return customerEntry;
}
示例8: FeedWriteReadNormal
public static void FeedWriteReadNormal()
{
Console.WriteLine("FeedWriteReadNormal");
ODataFeed Feed = new ODataFeed();
Feed.SetSerializationInfo(new ODataFeedAndEntrySerializationInfo()
{
NavigationSourceName = "Mails",
NavigationSourceEntityTypeName = "NS.Mail",
NavigationSourceKind = EdmNavigationSourceKind.ContainedEntitySet
});
ODataEntry Entry = new ODataEntry()
{
Properties = new[]
{
new ODataProperty() {Name = "Id", Value = 2},
},
EditLink = new Uri("http://example/Web/Users(3)"),
};
Entry.SetSerializationInfo(new ODataFeedAndEntrySerializationInfo()
{
NavigationSourceName = "MyLogin",
NavigationSourceEntityTypeName = "NS.Person",
NavigationSourceKind = EdmNavigationSourceKind.ContainedEntitySet
});
// Parse the full request Uri
ODataPath path = new ODataUriParser(
CraftModel.Model,
new Uri("http://example.org/svc/"),
new Uri("http://example.org/svc/MyLogin/Mails")).ParsePath();
// Alternatively, construct the normal path for the contained entity manually.
//ODataPath path = new ODataPath(
// new ODataPathSegment[]
// {
// new SingletonSegment(CraftModel.MyLogin), new NavigationPropertySegment(CraftModel.MailBox, CraftModel.MyLogin)
// });
var stream = new MemoryStream();
var wsetting = new ODataMessageWriterSettings()
{
DisableMessageStreamDisposal = true,
ODataUri = new ODataUri()
{
ServiceRoot = new Uri("http://example.org/svc/"),
Path = path
}
};
IODataResponseMessage msg = new Message()
{
Stream = stream,
};
var omw = new ODataMessageWriter(msg, wsetting);
var writer = omw.CreateODataFeedWriter();
writer.WriteStart(Feed);
writer.WriteStart(Entry);
writer.WriteEnd();
writer.WriteEnd();
stream.Seek(0, SeekOrigin.Begin);
var payload = new StreamReader(stream).ReadToEnd();
// {"@odata.context":"http://example.org/svc/$metadata#Web/Items","value":[{"@odata.editLink":"http://example/Web/Users(3)","Id":2}]}
Console.WriteLine(payload);
//Read
ODataEntry entry = null;
stream.Seek(0, SeekOrigin.Begin);
var rsetting = new ODataMessageReaderSettings();
var omr = new ODataMessageReader(msg, rsetting, CraftModel.Model);
var reader = omr.CreateODataFeedReader();
while (reader.Read())
{
if (reader.State == ODataReaderState.EntryEnd)
{
entry = (ODataEntry)reader.Item;
break;
}
}
//Id=2
foreach (var prop in entry.Properties)
{
Console.WriteLine("{0}={1}", prop.Name, prop.Value);
}
}
示例9: ShouldWritePayloadWhenFeedAndEntryHasSerializationInfo
public void ShouldWritePayloadWhenFeedAndEntryHasSerializationInfo()
{
var feed = new ODataFeed();
feed.SetSerializationInfo(new ODataFeedAndEntrySerializationInfo { NavigationSourceName = "MySet", NavigationSourceEntityTypeName = "NS.MyEntityType" });
var entry = new ODataEntry();
entry.SetSerializationInfo(new ODataFeedAndEntrySerializationInfo { NavigationSourceName = "MySet2", NavigationSourceEntityTypeName = "NS.MyEntityType2" });
List<ODataItem> itemsToWrite = new List<ODataItem>() { feed, entry };
const string expectedPayload = "{\"@odata.context\":\"http://odata.org/test/$metadata#MySet\",\"value\":[{}]}";
this.WriteNestedItemsAndValidatePayload(entitySetFullName: null, derivedEntityTypeFullName: null, nestedItemToWrite: itemsToWrite.ToArray(), expectedPayload: expectedPayload, writingResponse: true);
}
示例10: WriteEntry
/// <summary>Write the entry element.</summary>
/// <param name="expanded">Expanded result provider for the specified <paramref name="element"/>.</param>
/// <param name="element">Element representing the entry element.</param>
/// <param name="resourceInstanceInFeed">true if the resource instance being serialized is inside a feed; false otherwise.</param>
/// <param name="expectedType">Expected type of the entry element.</param>
private void WriteEntry(IExpandedResult expanded, object element, bool resourceInstanceInFeed, ResourceType expectedType)
{
Debug.Assert(element != null, "element != null");
Debug.Assert(expectedType != null && expectedType.ResourceTypeKind == ResourceTypeKind.EntityType, "expectedType != null && expectedType.ResourceTypeKind == ResourceTypeKind.EntityType");
this.IncrementSegmentResultCount();
ODataEntry entry = new ODataEntry();
if (!resourceInstanceInFeed)
{
entry.SetSerializationInfo(new ODataFeedAndEntrySerializationInfo { NavigationSourceName = this.CurrentContainer.Name, NavigationSourceEntityTypeName = this.CurrentContainer.ResourceType.FullName, ExpectedTypeName = expectedType.FullName });
}
string title = expectedType.Name;
#pragma warning disable 618
if (this.contentFormat == ODataFormat.Atom)
#pragma warning restore 618
{
AtomEntryMetadata entryAtom = new AtomEntryMetadata();
entryAtom.EditLink = new AtomLinkMetadata { Title = title };
entry.SetAnnotation(entryAtom);
}
ResourceType actualResourceType = WebUtil.GetNonPrimitiveResourceType(this.Provider, element);
if (actualResourceType.ResourceTypeKind != ResourceTypeKind.EntityType)
{
// making sure that the actual resource type is an entity type
throw new DataServiceException(500, Microsoft.OData.Service.Strings.BadProvider_InconsistentEntityOrComplexTypeUsage(actualResourceType.FullName));
}
EntityToSerialize entityToSerialize = this.WrapEntity(element, actualResourceType);
// populate the media resource, if the entity is a MLE.
entry.MediaResource = this.GetMediaResource(entityToSerialize, title);
// Write the type name
this.PayloadMetadataPropertyManager.SetTypeName(entry, this.CurrentContainer.ResourceType.FullName, actualResourceType.FullName);
// Write Id element
this.PayloadMetadataPropertyManager.SetId(entry, () => entityToSerialize.SerializedKey.Identity);
// Write "edit" link
this.PayloadMetadataPropertyManager.SetEditLink(entry, () => entityToSerialize.SerializedKey.RelativeEditLink);
// Write the etag property, if the type has etag properties
this.PayloadMetadataPropertyManager.SetETag(entry, () => this.GetETagValue(element, actualResourceType));
IEnumerable<ProjectionNode> projectionNodes = this.GetProjections();
if (projectionNodes != null)
{
// Filter the projection nodes for the actual type of the entity
// The projection node might refer to the property in a derived type. If the TargetResourceType of
// the projection node is not a super type, then we do not want to serialize this property.
projectionNodes = projectionNodes.Where(projectionNode => projectionNode.TargetResourceType.IsAssignableFrom(actualResourceType));
// Because we are going to enumerate through these multiple times, create a list.
projectionNodes = projectionNodes.ToList();
// And add the annotation to tell ODataLib which properties to write into content (the projections)
entry.SetAnnotation(new ProjectedPropertiesAnnotation(projectionNodes.Select(p => p.PropertyName)));
}
// Populate the advertised actions
IEnumerable<ODataAction> actions;
if (this.TryGetAdvertisedActions(entityToSerialize, resourceInstanceInFeed, out actions))
{
foreach (ODataAction action in actions)
{
entry.AddAction(action);
}
}
// Populate all the normal properties
entry.Properties = this.GetEntityProperties(entityToSerialize, projectionNodes);
// And start the entry
var args = new DataServiceODataWriterEntryArgs(entry, element, this.Service.OperationContext);
this.dataServicesODataWriter.WriteStart(args);
// Now write all the navigation properties
this.WriteNavigationProperties(expanded, entityToSerialize, resourceInstanceInFeed, projectionNodes);
// And write the end of the entry
this.dataServicesODataWriter.WriteEnd(args);
#if ASTORIA_FF_CALLBACKS
this.Service.InternalOnWriteItem(target, element);
#endif
}
示例11: WriteContainedEntityInDeltaFeedWithSelectExpand
public void WriteContainedEntityInDeltaFeedWithSelectExpand()
{
this.TestInit(this.GetModel());
ODataDeltaFeed feed = new ODataDeltaFeed();
ODataEntry entry = new ODataEntry()
{
TypeName = "MyNS.Product",
Properties = new[]
{
new ODataProperty {Name = "Id", Value = new ODataPrimitiveValue(1)},
new ODataProperty {Name = "Name", Value = new ODataPrimitiveValue("Car")},
},
};
ODataEntry containedEntry = new ODataEntry()
{
TypeName = "MyNS.ProductDetail",
Properties = new[]
{
new ODataProperty {Name = "Id", Value = new ODataPrimitiveValue(1)},
new ODataProperty {Name = "Detail", Value = new ODataPrimitiveValue("made in china")},
},
};
containedEntry.SetSerializationInfo(new ODataFeedAndEntrySerializationInfo()
{
NavigationSourceEntityTypeName = "MyNS.ProductDetail",
NavigationSourceName = "Products(1)/Details",
NavigationSourceKind = EdmNavigationSourceKind.ContainedEntitySet
});
var result = new ODataQueryOptionParser(this.GetModel(), this.GetProductType(), this.GetProducts(), new Dictionary<string, string> { { "$expand", "Details($select=Detail)" }, { "$select", "Name" } }).ParseSelectAndExpand();
ODataUri odataUri = new ODataUri()
{
ServiceRoot = new Uri("http://host/service"),
SelectAndExpand = result
};
var outputContext = CreateJsonLightOutputContext(this.stream, this.GetModel(), odataUri);
ODataJsonLightDeltaWriter writer = new ODataJsonLightDeltaWriter(outputContext, this.GetProducts(), this.GetProductType());
writer.WriteStart(feed);
writer.WriteStart(containedEntry);
writer.WriteEnd();
writer.WriteStart(entry);
writer.WriteEnd();
writer.WriteEnd();
writer.Flush();
string payload = this.TestFinish();
payload.Should().Be("{\"@odata.context\":\"http://host/service/$metadata#Products(Name,Details,Details(Detail))/$delta\",\"value\":[{\"@odata.context\":\"http://host/service/$metadata#Products(1)/Details/$entity\",\"Id\":1,\"Detail\":\"made in china\"},{\"Id\":1,\"Name\":\"Car\"}]}");
}
示例12: WriteContainedEntityInDeltaFeed
public void WriteContainedEntityInDeltaFeed()
{
this.TestInit(this.GetModel());
ODataDeltaFeed feed = new ODataDeltaFeed();
ODataEntry containedEntry = new ODataEntry()
{
TypeName = "MyNS.ProductDetail",
Properties = new[]
{
new ODataProperty {Name = "Id", Value = new ODataPrimitiveValue(1)},
new ODataProperty {Name = "Detail", Value = new ODataPrimitiveValue("made in china")},
},
};
containedEntry.SetSerializationInfo(new ODataFeedAndEntrySerializationInfo()
{
NavigationSourceEntityTypeName = "MyNS.ProductDetail",
NavigationSourceName = "Products(1)/Details",
NavigationSourceKind = EdmNavigationSourceKind.ContainedEntitySet
});
ODataEntry containedInContainedEntity = new ODataEntry()
{
TypeName = "MyNS.ProductDetailItem",
Properties = new[]
{
new ODataProperty {Name = "ItemId", Value = new ODataPrimitiveValue(1)},
new ODataProperty {Name = "Description", Value = new ODataPrimitiveValue("made by HCC")},
},
};
containedInContainedEntity.SetSerializationInfo(new ODataFeedAndEntrySerializationInfo()
{
NavigationSourceEntityTypeName = "MyNS.ProductDetailItem",
NavigationSourceName = "Products(1)/Details(1)/Items",
NavigationSourceKind = EdmNavigationSourceKind.ContainedEntitySet
});
ODataJsonLightDeltaWriter writer = new ODataJsonLightDeltaWriter(outputContext, this.GetProducts(), this.GetProductType());
writer.WriteStart(feed);
writer.WriteStart(containedEntry);
writer.WriteEnd();
writer.WriteStart(containedInContainedEntity);
writer.WriteEnd();
writer.WriteEnd();
writer.Flush();
string payload = this.TestFinish();
payload.Should().Be("{\"@odata.context\":\"http://host/service/$metadata#Products/$delta\",\"value\":[{\"@odata.context\":\"http://host/service/$metadata#Products(1)/Details/$entity\",\"Id\":1,\"Detail\":\"made in china\"},{\"@odata.context\":\"http://host/service/$metadata#Products(1)/Details(1)/Items/$entity\",\"ItemId\":1,\"Description\":\"made by HCC\"}]}");
}
示例13: SerializeEntryInFullMetadataJson
private string SerializeEntryInFullMetadataJson(
bool? useKeyAsSegment,
IEdmModel edmModel,
IEdmEntityType entityType = null,
IEdmEntitySet entitySet = null)
{
var settings = new ODataMessageWriterSettings
{
AutoComputePayloadMetadataInJson = true,
UseKeyAsSegment = useKeyAsSegment,
};
settings.SetServiceDocumentUri(new Uri("http://example.com/"));
var outputStream = new MemoryStream();
var responseMessage = new InMemoryMessage {Stream = outputStream};
responseMessage.SetHeader("Content-Type", "application/json;odata.metadata=full");
string output;
using(var messageWriter = new ODataMessageWriter((IODataResponseMessage)responseMessage, settings, edmModel))
{
var entryWriter = messageWriter.CreateODataEntryWriter(entitySet, entityType);
ODataProperty keyProperty = new ODataProperty() {Name = "Key", Value = "KeyValue"};
var entry = new ODataEntry {Properties = new[] {keyProperty}, TypeName = "Namespace.Person"};
if (edmModel == null)
{
keyProperty.SetSerializationInfo(new ODataPropertySerializationInfo
{
PropertyKind = ODataPropertyKind.Key
});
entry.SetSerializationInfo(new ODataFeedAndEntrySerializationInfo
{
NavigationSourceEntityTypeName = "Namespace.Person",
NavigationSourceName = "People",
ExpectedTypeName = "Namespace.Person"
});
}
entryWriter.WriteStart(entry);
entryWriter.WriteEnd();
entryWriter.Flush();
outputStream.Seek(0, SeekOrigin.Begin);
output = new StreamReader(outputStream).ReadToEnd();
}
return output;
}
开发者ID:rossjempson,项目名称:odata.net,代码行数:51,代码来源:AutoGeneratedUrlsShouldPutKeyValueInDedicatedSegmentTests.cs
示例14: WriteAndVerifyRequestMessage
private string WriteAndVerifyRequestMessage(StreamRequestMessage requestMessageWithoutModel,
ODataWriter odataWriter, bool hasModel, string mimeType)
{
var order = new ODataEntry()
{
Id = new Uri(this.ServiceUri + "Order(-10)"),
TypeName = NameSpace + "Order"
};
var orderP1 = new ODataProperty { Name = "OrderId", Value = -10 };
var orderp2 = new ODataProperty { Name = "CustomerId", Value = 8212 };
var orderp3 = new ODataProperty { Name = "Concurrency", Value = null };
order.Properties = new[] { orderP1, orderp2, orderp3 };
if (!hasModel)
{
order.SetSerializationInfo(new ODataFeedAndEntrySerializationInfo() { NavigationSourceName = "Order", NavigationSourceEntityTypeName = NameSpace + "Order" });
orderP1.SetSerializationInfo(new ODataPropertySerializationInfo() { PropertyKind = ODataPropertyKind.Key });
}
odataWriter.WriteStart(order);
odataWriter.WriteEnd();
Stream stream = requestMessageWithoutModel.GetStream();
if (!mimeType.Contains(MimeTypes.ODataParameterNoMetadata))
{
stream.Seek(0, SeekOrigin.Begin);
var settings = new ODataMessageReaderSettings() { BaseUri = this.ServiceUri };
ODataMessageReader messageReader = new ODataMessageReader(requestMessageWithoutModel, settings,
WritePayloadHelper.Model);
ODataReader reader = messageReader.CreateODataEntryReader(WritePayloadHelper.OrderSet, WritePayloadHelper.OrderType);
bool verifyEntryCalled = false;
while (reader.Read())
{
if (reader.State == ODataReaderState.EntryEnd)
{
ODataEntry entry = reader.Item as ODataEntry;
Assert.IsTrue(entry.Id.ToString().Contains("Order(-10)"), "entry.Id");
Assert.AreEqual(3, entry.Properties.Count(), "entry.Properties.Count");
verifyEntryCalled = true;
}
}
Assert.AreEqual(ODataReaderState.Completed, reader.State);
Assert.IsTrue(verifyEntryCalled, "verifyEntryCalled");
}
return WritePayloadHelper.ReadStreamContent(stream);
}