本文整理匯總了C#中System.Web.OData.Formatter.Serialization.ODataSerializerContext類的典型用法代碼示例。如果您正苦於以下問題:C# ODataSerializerContext類的具體用法?C# ODataSerializerContext怎麽用?C# ODataSerializerContext使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。
ODataSerializerContext類屬於System.Web.OData.Formatter.Serialization命名空間,在下文中一共展示了ODataSerializerContext類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的C#代碼示例。
示例1: ODataEntityReferenceLinkSerializer_Serializes_UrisAndEntityReferenceLinks
public void ODataEntityReferenceLinkSerializer_Serializes_UrisAndEntityReferenceLinks(object uris)
{
// Arrange
ODataEntityReferenceLinksSerializer serializer = new ODataEntityReferenceLinksSerializer();
ODataSerializerContext writeContext = new ODataSerializerContext();
MemoryStream stream = new MemoryStream();
IODataResponseMessage message = new ODataMessageWrapper(stream);
ODataMessageWriterSettings settings = new ODataMessageWriterSettings
{
ODataUri = new ODataUri { ServiceRoot = new Uri("http://any/") }
};
settings.SetContentType(ODataFormat.Json);
ODataMessageWriter writer = new ODataMessageWriter(message, settings);
// Act
serializer.WriteObject(uris, typeof(ODataEntityReferenceLinks), writer, writeContext);
stream.Seek(0, SeekOrigin.Begin);
string result = new StreamReader(stream).ReadToEnd();
// Assert
Assert.Equal("{\"@odata.context\":\"http://any/$metadata#Collection($ref)\"," +
"\"value\":[{\"@odata.id\":\"http://uri1/\"},{\"@odata.id\":\"http://uri2/\"}]}",
result);
}
示例2: WriteObject_WritesValueReturnedFrom_CreateODataCollectionValue
public void WriteObject_WritesValueReturnedFrom_CreateODataCollectionValue()
{
// Arrange
MemoryStream stream = new MemoryStream();
IODataResponseMessage message = new ODataMessageWrapper(stream);
ODataMessageWriterSettings settings = new ODataMessageWriterSettings();
settings.SetContentType(ODataFormat.Atom);
ODataMessageWriter messageWriter = new ODataMessageWriter(message, settings);
Mock<ODataCollectionSerializer> serializer = new Mock<ODataCollectionSerializer>(new DefaultODataSerializerProvider());
ODataSerializerContext writeContext = new ODataSerializerContext { RootElementName = "CollectionName", Model = _model };
IEnumerable enumerable = new object[0];
ODataCollectionValue collectionValue = new ODataCollectionValue { TypeName = "NS.Name", Items = new[] { 0, 1, 2 } };
serializer.CallBase = true;
serializer
.Setup(s => s.CreateODataCollectionValue(enumerable, It.Is<IEdmTypeReference>(e => e.Definition == _edmIntType.Definition), writeContext))
.Returns(collectionValue).Verifiable();
// Act
serializer.Object.WriteObject(enumerable, typeof(int[]), messageWriter, writeContext);
// Assert
serializer.Verify();
stream.Seek(0, SeekOrigin.Begin);
XElement element = XElement.Load(stream);
Assert.Equal("value", element.Name.LocalName);
Assert.Equal(3, element.Descendants().Count());
Assert.Equal(new[] { "0", "1", "2" }, element.Descendants().Select(e => e.Value));
}
示例3: SelectExpandNode
/// <summary>
/// Creates a new instance of the <see cref="SelectExpandNode"/> class describing the set of structural properties,
/// navigation properties, and actions to select and expand for the given <paramref name="writeContext"/>.
/// </summary>
/// <param name="entityType">The entity type of the entry that would be written.</param>
/// <param name="writeContext">The serializer context to be used while creating the collection.</param>
/// <remarks>The default constructor is for unit testing only.</remarks>
public SelectExpandNode(IEdmEntityType entityType, ODataSerializerContext writeContext)
: this(writeContext.SelectExpandClause, entityType, writeContext.Model)
{
var queryOptionParser = new ODataQueryOptionParser(
writeContext.Model,
entityType,
writeContext.NavigationSource,
_extraQueryParameters);
var selectExpandClause = queryOptionParser.ParseSelectAndExpand();
if (selectExpandClause != null)
{
foreach (SelectItem selectItem in selectExpandClause.SelectedItems)
{
ExpandedNavigationSelectItem expandItem = selectItem as ExpandedNavigationSelectItem;
if (expandItem != null)
{
ValidatePathIsSupported(expandItem.PathToNavigationProperty);
NavigationPropertySegment navigationSegment = (NavigationPropertySegment)expandItem.PathToNavigationProperty.LastSegment;
IEdmNavigationProperty navigationProperty = navigationSegment.NavigationProperty;
if (!ExpandedNavigationProperties.ContainsKey(navigationProperty))
{
ExpandedNavigationProperties.Add(navigationProperty, expandItem.SelectAndExpand);
}
}
}
}
SelectedNavigationProperties.ExceptWith(ExpandedNavigationProperties.Keys);
}
示例4: WriteObject
/// <inheridoc />
public override void WriteObject(object graph, Type type, ODataMessageWriter messageWriter, ODataSerializerContext writeContext)
{
if (messageWriter == null)
{
throw Error.ArgumentNull("messageWriter");
}
if (writeContext == null)
{
throw Error.ArgumentNull("writeContext");
}
if (graph != null)
{
ODataEntityReferenceLinks entityReferenceLinks = graph as ODataEntityReferenceLinks;
if (entityReferenceLinks == null)
{
IEnumerable<Uri> uris = graph as IEnumerable<Uri>;
if (uris == null)
{
throw new SerializationException(Error.Format(SRResources.CannotWriteType, GetType().Name, graph.GetType().FullName));
}
entityReferenceLinks = new ODataEntityReferenceLinks
{
Links = uris.Select(uri => new ODataEntityReferenceLink { Url = uri })
};
}
messageWriter.WriteEntityReferenceLinks(entityReferenceLinks);
}
}
示例5: WriteObjectInline
/// <inheritdoc />
public override void WriteObjectInline(object graph, IEdmTypeReference expectedType, ODataWriter writer,
ODataSerializerContext writeContext)
{
if (writer == null)
{
throw Error.ArgumentNull("writer");
}
if (writeContext == null)
{
throw Error.ArgumentNull("writeContext");
}
if (expectedType == null)
{
throw Error.ArgumentNull("expectedType");
}
if (graph == null)
{
throw new SerializationException(Error.Format(SRResources.CannotSerializerNull, Feed));
}
IEnumerable enumerable = graph as IEnumerable; // Data to serialize
if (enumerable == null)
{
throw new SerializationException(
Error.Format(SRResources.CannotWriteType, GetType().Name, graph.GetType().FullName));
}
WriteFeed(enumerable, expectedType, writer, writeContext);
}
示例6: CreateODataEnumValue
/// <summary>
/// Creates an <see cref="ODataEnumValue"/> for the object represented by <paramref name="graph"/>.
/// </summary>
/// <param name="graph">The enum value.</param>
/// <param name="enumType">The EDM enum type of the value.</param>
/// <param name="writeContext">The serializer write context.</param>
/// <returns>The created <see cref="ODataEnumValue"/>.</returns>
public virtual ODataEnumValue CreateODataEnumValue(object graph, IEdmEnumTypeReference enumType,
ODataSerializerContext writeContext)
{
if (graph == null)
{
return null;
}
string value = null;
if (graph.GetType().IsEnum)
{
value = graph.ToString();
}
else
{
if (graph.GetType() == typeof(EdmEnumObject))
{
value = ((EdmEnumObject)graph).Value;
}
}
ODataEnumValue enumValue = new ODataEnumValue(value, enumType.FullName());
ODataMetadataLevel metadataLevel = writeContext != null
? writeContext.MetadataLevel
: ODataMetadataLevel.MinimalMetadata;
AddTypeNameAnnotationAsNeeded(enumValue, enumType, metadataLevel);
return enumValue;
}
示例7: WriteObject
/// <inheritdoc />
public override void WriteObject(object graph, Type type, ODataMessageWriter messageWriter, ODataSerializerContext writeContext)
{
if (messageWriter == null)
{
throw Error.ArgumentNull("messageWriter");
}
if (writeContext == null)
{
throw Error.ArgumentNull("writeContext");
}
IEdmEntitySetBase entitySet = writeContext.NavigationSource as IEdmEntitySetBase;
if (entitySet == null)
{
throw new SerializationException(SRResources.EntitySetMissingDuringSerialization);
}
IEdmTypeReference feedType = writeContext.GetEdmType(graph, type);
Contract.Assert(feedType != null);
IEdmEntityTypeReference entityType = GetEntityType(feedType);
ODataWriter writer = messageWriter.CreateODataFeedWriter(entitySet, entityType.EntityDefinition());
WriteObjectInline(graph, feedType, writer, writeContext);
}
示例8: WriteObjectInline
public override void WriteObjectInline(object graph, IEdmTypeReference expectedType, ODataWriter writer, ODataSerializerContext writeContext)
{
if (graph != null)
{
base.WriteObjectInline(graph, expectedType, writer, writeContext);
}
}
示例9: WriteObject
/// <inheritdoc />
public override void WriteObject(object graph, Type type, ODataMessageWriter messageWriter,
ODataSerializerContext writeContext)
{
if (messageWriter == null)
{
throw Error.ArgumentNull("messageWriter");
}
if (writeContext == null)
{
throw Error.ArgumentNull("writeContext");
}
IEdmNavigationSource navigationSource = writeContext.NavigationSource;
if (navigationSource == null)
{
throw new SerializationException(SRResources.NavigationSourceMissingDuringSerialization);
}
var path = writeContext.Path;
if (path == null)
{
throw new SerializationException(SRResources.ODataPathMissing);
}
ODataWriter writer = messageWriter.CreateODataEntryWriter(navigationSource, path.EdmType as IEdmEntityType);
WriteObjectInline(graph, navigationSource.EntityType().ToEdmTypeReference(isNullable: false), writer, writeContext);
}
示例10: WriteObject
/// <summary>
/// Writes the entity result to the response message.
/// </summary>
/// <param name="graph">The entity result to write.</param>
/// <param name="type">The type of the entity.</param>
/// <param name="messageWriter">The message writer.</param>
/// <param name="writeContext">The writing context.</param>
public override void WriteObject(
object graph,
Type type,
ODataMessageWriter messageWriter,
ODataSerializerContext writeContext)
{
RawResult rawResult = graph as RawResult;
if (rawResult != null)
{
graph = rawResult.Result;
type = rawResult.Type;
}
if (writeContext != null)
{
graph = RestierPrimitiveSerializer.ConvertToPayloadValue(graph, writeContext);
}
if (graph == null)
{
// This is to make ODataRawValueSerializer happily serialize null value.
graph = string.Empty;
}
base.WriteObject(graph, type, messageWriter, writeContext);
}
示例11: CanSerializerSingleton
public void CanSerializerSingleton()
{
// Arrange
const string expect = "{" +
"\"@odata.context\":\"http://localhost/odata/$metadata#Boss\"," +
"\"@odata.id\":\"http://localhost/odata/Boss\"," +
"\"@odata.editLink\":\"http://localhost/odata/Boss\"," +
"\"EmployeeId\":987,\"EmployeeName\":\"John Mountain\"}";
IEdmModel model = GetEdmModel();
IEdmSingleton singleton = model.EntityContainer.FindSingleton("Boss");
HttpRequestMessage request = GetRequest(model, singleton);
ODataSerializerContext readContext = new ODataSerializerContext()
{
Url = new UrlHelper(request),
Path = request.ODataProperties().Path,
Model = model,
NavigationSource = singleton
};
ODataSerializerProvider serializerProvider = new DefaultODataSerializerProvider();
EmployeeModel boss = new EmployeeModel {EmployeeId = 987, EmployeeName = "John Mountain"};
MemoryStream bufferedStream = new MemoryStream();
// Act
ODataEntityTypeSerializer serializer = new ODataEntityTypeSerializer(serializerProvider);
serializer.WriteObject(boss, typeof(EmployeeModel), GetODataMessageWriter(model, bufferedStream), readContext);
// Assert
string result = Encoding.UTF8.GetString(bufferedStream.ToArray());
Assert.Equal(expect, result);
}
示例12: CreateODataPrimitiveValue
/// <summary>
/// Creates an <see cref="ODataPrimitiveValue"/> for the object represented by <paramref name="graph"/>.
/// </summary>
/// <param name="graph">The primitive value.</param>
/// <param name="primitiveType">The EDM primitive type of the value.</param>
/// <param name="writeContext">The serializer write context.</param>
/// <returns>The created <see cref="ODataPrimitiveValue"/>.</returns>
public override ODataPrimitiveValue CreateODataPrimitiveValue(
object graph,
IEdmPrimitiveTypeReference primitiveType,
ODataSerializerContext writeContext)
{
// The EDM type of the "graph" would override the EDM type of the property when
// OData Web API infers the primitiveType. Thus for "graph" of System.DateTime,
// the primitiveType is always Edm.DateTimeOffset.
//
// In EF, System.DateTime is used for SqlDate, SqlDateTime and SqlDateTime2.
// All of them have no time zone information thus it is safe to clear the time
// zone when converting the "graph" to a DateTimeOffset.
if (primitiveType != null && primitiveType.IsDateTimeOffset() && graph is DateTime)
{
// If DateTime.Kind equals Local, offset should equal the offset of the system's local time zone
if (((DateTime)graph).Kind == DateTimeKind.Local)
{
graph = new DateTimeOffset((DateTime)graph, TimeZoneInfo.Local.GetUtcOffset((DateTime)graph));
}
else
{
graph = new DateTimeOffset((DateTime)graph, TimeSpan.Zero);
}
}
return base.CreateODataPrimitiveValue(graph, primitiveType, writeContext);
}
示例13: WriteObject_WritesValueReturnedFrom_CreateODataCollectionValue
public void WriteObject_WritesValueReturnedFrom_CreateODataCollectionValue()
{
// Arrange
MemoryStream stream = new MemoryStream();
IODataResponseMessage message = new ODataMessageWrapper(stream);
ODataMessageWriterSettings settings = new ODataMessageWriterSettings()
{
ODataUri = new ODataUri { ServiceRoot = new Uri("http://any/") }
};
settings.SetContentType(ODataFormat.Json);
ODataMessageWriter messageWriter = new ODataMessageWriter(message, settings);
Mock<ODataCollectionSerializer> serializer = new Mock<ODataCollectionSerializer>(new DefaultODataSerializerProvider());
ODataSerializerContext writeContext = new ODataSerializerContext { RootElementName = "CollectionName", Model = _model };
IEnumerable enumerable = new object[0];
ODataCollectionValue collectionValue = new ODataCollectionValue { TypeName = "NS.Name", Items = new[] { 0, 1, 2 } };
serializer.CallBase = true;
serializer
.Setup(s => s.CreateODataCollectionValue(enumerable, It.Is<IEdmTypeReference>(e => e.Definition == _edmIntType.Definition), writeContext))
.Returns(collectionValue).Verifiable();
// Act
serializer.Object.WriteObject(enumerable, typeof(int[]), messageWriter, writeContext);
// Assert
serializer.Verify();
stream.Seek(0, SeekOrigin.Begin);
string result = new StreamReader(stream).ReadToEnd();
Assert.Equal("{\"@odata.context\":\"http://any/$metadata#Collection(Edm.Int32)\",\"value\":[0,1,2]}", result);
}
示例14: Singleton_CanOnlyConfigureIdLinkViaIdLinkFactory
public void Singleton_CanOnlyConfigureIdLinkViaIdLinkFactory()
{
// Arrange
ODataModelBuilder builder = GetSingletonModel();
const string ExpectedEditLink = "http://server/service/Exchange";
var product = builder.Singleton<SingletonProduct>("Exchange");
product.HasIdLink(c => new Uri("http://server/service/Exchange"),
followsConventions: false);
var exchange = builder.Singletons.Single();
var model = builder.GetEdmModel();
var productType = model.SchemaElements.OfType<IEdmEntityType>().Single();
var singleton = model.SchemaElements.OfType<IEdmEntityContainer>().Single().FindSingleton("Exchange");
var singletonInstance = new SingletonProduct { ID = 15 };
var serializerContext = new ODataSerializerContext { Model = model, NavigationSource = singleton };
var entityContext = new EntityInstanceContext(serializerContext, productType.AsReference(), singletonInstance);
var linkBuilderAnnotation = new NavigationSourceLinkBuilderAnnotation(exchange);
// Act
var selfLinks = linkBuilderAnnotation.BuildEntitySelfLinks(entityContext, ODataMetadataLevel.FullMetadata);
// Assert
Assert.NotNull(selfLinks.IdLink);
Assert.Equal(ExpectedEditLink, selfLinks.IdLink.ToString());
Assert.Null(selfLinks.ReadLink);
Assert.Null(selfLinks.EditLink);
}
示例15: Ctor_ThatBuildsNestedContext_CopiesProperties
public void Ctor_ThatBuildsNestedContext_CopiesProperties()
{
// Arrange
CustomersModelWithInheritance model = new CustomersModelWithInheritance();
ODataSerializerContext context = new ODataSerializerContext
{
NavigationSource = model.Customers,
MetadataLevel = ODataMetadataLevel.FullMetadata,
Model = model.Model,
Path = new ODataPath(),
Request = new HttpRequestMessage(),
RootElementName = "somename",
SelectExpandClause = new SelectExpandClause(new SelectItem[0], allSelected: true),
SkipExpensiveAvailabilityChecks = true,
Url = new UrlHelper()
};
EntityInstanceContext entity = new EntityInstanceContext { SerializerContext = context };
SelectExpandClause selectExpand = new SelectExpandClause(new SelectItem[0], allSelected: true);
IEdmNavigationProperty navProp = model.Customer.NavigationProperties().First();
// Act
ODataSerializerContext nestedContext = new ODataSerializerContext(entity, selectExpand, navProp);
// Assert
Assert.Equal(context.MetadataLevel, nestedContext.MetadataLevel);
Assert.Same(context.Model, nestedContext.Model);
Assert.Same(context.Path, nestedContext.Path);
Assert.Same(context.Request, nestedContext.Request);
Assert.Equal(context.RootElementName, nestedContext.RootElementName);
Assert.Equal(context.SkipExpensiveAvailabilityChecks, nestedContext.SkipExpensiveAvailabilityChecks);
Assert.Same(context.Url, nestedContext.Url);
}