public override Task WriteToStreamAsync(Type type, object value, Stream writeStream, HttpContent content, TransportContext transportContext) { if (type == null) { throw Error.ArgumentNull("type"); } if (writeStream == null) { throw Error.ArgumentNull("writeStream"); } if (_request == null) { throw Error.InvalidOperation(SRResources.WriteToStreamAsyncMustHaveRequest); } HttpContentHeaders contentHeaders = content == null ? null : content.Headers; return TaskHelpers.RunSynchronously(() => { // get the most appropriate serializer given that we support inheritance. IEdmModel model = _request.GetEdmModel(); if (model == null) { throw Error.InvalidOperation(SRResources.RequestMustHaveModel); } type = value == null ? type : value.GetType(); ODataSerializer serializer = _serializerProvider.GetODataPayloadSerializer(model, type); if (serializer == null) { string message = Error.Format(SRResources.TypeCannotBeSerialized, type.Name, typeof(ODataMediaTypeFormatter).Name); throw new SerializationException(message); } UrlHelper urlHelper = _request.GetUrlHelper(); Contract.Assert(urlHelper != null); ODataPath path = _request.GetODataPath(); IEdmEntitySet targetEntitySet = path == null ? null : path.EntitySet; // serialize a response HttpConfiguration configuration = _request.GetConfiguration(); if (configuration == null) { throw Error.InvalidOperation(SRResources.RequestMustContainConfiguration); } IODataResponseMessage responseMessage = new ODataMessageWrapper(writeStream, content.Headers); ODataMessageWriterSettings writerSettings = new ODataMessageWriterSettings() { BaseUri = GetBaseAddress(_request), Version = _version, Indent = true, DisableMessageStreamDisposal = true, MessageQuotas = MessageWriterQuotas }; // The MetadataDocumentUri is never required for errors. Additionally, it sometimes won't be available // for errors, such as when routing itself fails. In that case, the route data property is not // available on the request, and due to a bug with HttpRoute.GetVirtualPath (bug #669) we won't be able // to generate a metadata link. if (serializer.ODataPayloadKind != ODataPayloadKind.Error) { string metadataLink = urlHelper.ODataLink(new MetadataPathSegment()); if (metadataLink == null) { throw new SerializationException(SRResources.UnableToDetermineMetadataUrl); } writerSettings.SetMetadataDocumentUri(new Uri(metadataLink)); } MediaTypeHeaderValue contentType = null; if (contentHeaders != null && contentHeaders.ContentType != null) { contentType = contentHeaders.ContentType; } using (ODataMessageWriter messageWriter = new ODataMessageWriter(responseMessage, writerSettings, model)) { ODataSerializerContext writeContext = new ODataSerializerContext() { Request = _request, Url = urlHelper, EntitySet = targetEntitySet, Model = model, RootElementName = GetRootElementName(path) ?? "root", SkipExpensiveAvailabilityChecks = serializer.ODataPayloadKind == ODataPayloadKind.Feed, Path = path, MetadataLevel = ODataMediaTypes.GetMetadataLevel(contentType), }; serializer.WriteObject(value, messageWriter, writeContext); } }); }
private void WriteToStream(Type type, object value, Stream writeStream, HttpContent content, HttpContentHeaders contentHeaders) { IEdmModel model = Request.GetEdmModel(); if (model == null) { throw Error.InvalidOperation(SRResources.RequestMustHaveModel); } ODataSerializer serializer = GetSerializer(type, value, model, _serializerProvider); UrlHelper urlHelper = Request.GetUrlHelper(); Contract.Assert(urlHelper != null); ODataPath path = Request.GetODataPath(); IEdmEntitySet targetEntitySet = path == null ? null : path.EntitySet; // serialize a response HttpConfiguration configuration = Request.GetConfiguration(); if (configuration == null) { throw Error.InvalidOperation(SRResources.RequestMustContainConfiguration); } IODataResponseMessage responseMessage = new ODataMessageWrapper(writeStream, content.Headers); ODataMessageWriterSettings writerSettings = new ODataMessageWriterSettings(MessageWriterSettings) { BaseUri = GetBaseAddress(Request), Version = _version, }; // The MetadataDocumentUri is never required for errors. Additionally, it sometimes won't be available // for errors, such as when routing itself fails. In that case, the route data property is not // available on the request, and due to a bug with HttpRoute.GetVirtualPath (bug #669) we won't be able // to generate a metadata link. if (serializer.ODataPayloadKind != ODataPayloadKind.Error) { string metadataLink = urlHelper.ODataLink(new MetadataPathSegment()); if (metadataLink == null) { throw new SerializationException(SRResources.UnableToDetermineMetadataUrl); } string selectClause = GetSelectClause(Request); writerSettings.SetMetadataDocumentUri(new Uri(metadataLink), selectClause); } MediaTypeHeaderValue contentType = null; if (contentHeaders != null && contentHeaders.ContentType != null) { contentType = contentHeaders.ContentType; } using (ODataMessageWriter messageWriter = new ODataMessageWriter(responseMessage, writerSettings, model)) { ODataSerializerContext writeContext = new ODataSerializerContext() { Request = Request, RequestContext = Request.GetRequestContext(), Url = urlHelper, EntitySet = targetEntitySet, Model = model, RootElementName = GetRootElementName(path) ?? "root", SkipExpensiveAvailabilityChecks = serializer.ODataPayloadKind == ODataPayloadKind.Feed, Path = path, MetadataLevel = ODataMediaTypes.GetMetadataLevel(contentType), SelectExpandClause = Request.GetSelectExpandClause() }; serializer.WriteObject(value, type, messageWriter, writeContext); } }
public void ODataEntityReferenceLinkSerializer_Serializes_UrisAndEntityReferenceLinks_Json(object uris) { // Arrange ODataEntityReferenceLinksSerializer serializer = new ODataEntityReferenceLinksSerializer(); IEdmNavigationProperty navigationProperty = _customerSet.ElementType.NavigationProperties().First(); ODataPath path = new ODataPath(new EntitySetPathSegment(_customerSet), new KeyValuePathSegment("1"), new NavigationPathSegment(navigationProperty)); ODataSerializerContext writeContext = new ODataSerializerContext { Path = path }; MemoryStream stream = new MemoryStream(); IODataResponseMessage message = new ODataMessageWrapper(stream); ODataMessageWriterSettings settings = new ODataMessageWriterSettings { BaseUri = new Uri("http://any/") }; settings.SetMetadataDocumentUri(new Uri("http://any/$metadata")); settings.SetContentType(ODataFormat.Json); // Act serializer.WriteObject(uris, typeof(ODataEntityReferenceLinks), new ODataMessageWriter(message, settings), writeContext); stream.Seek(0, SeekOrigin.Begin); string result = new StreamReader(stream).ReadToEnd(); // Assert Assert.Equal( string.Format("{0},{1}", "{\"odata.metadata\":\"http://any/$metadata#Default.Container.Customers/$links/Orders\"", "\"value\":[{\"url\":\"http://uri1/\"},{\"url\":\"http://uri2/\"}]}"), result); }
private static ODataMessageWriterSettings CreateJsonLightSettings() { ODataMessageWriterSettings settings = new ODataMessageWriterSettings(); settings.SetContentType(ODataFormat.Json); settings.SetMetadataDocumentUri(CreateFakeUri()); return settings; }
public void ProcessRequest(HttpContext context) { if (!HttpContext.Current.Request.IsAuthenticated) { HttpContext.Current.GetOwinContext().Authentication.Challenge(new AuthenticationProperties { RedirectUri = HttpContext.Current.Request.FilePath }, "OAuth2Bearer"); return; } MSRAHttpResponseMessage message = new MSRAHttpResponseMessage(this.ContextBase.Response); message.StatusCode = 200; message.SetHeader(ODataConstants.ContentTypeHeader, "application/json"); // create the writer, indent for readability ODataMessageWriterSettings messageWriterSettings = new ODataMessageWriterSettings() { Indent = true, CheckCharacters = false, BaseUri = context.Request.Url }; messageWriterSettings.SetContentType(ODataFormat.Json); messageWriterSettings.SetMetadataDocumentUri(new Uri("http://localhost:31435/odata/MSRAQuery/$metadata")); if (string.IsNullOrEmpty(QueryId)) { AzureTestDBEntities db = new AzureTestDBEntities(); var queries = db.MsrRecurringQueries.ToList().Take(1); ODataWorkspace workSpace = new ODataWorkspace(); var collections = new List<ODataResourceCollectionInfo>(); foreach (MsrRecurringQuery recurringQuery in queries) { ODataResourceCollectionInfo collectionInfo = new ODataResourceCollectionInfo() { Name = "MsrRecurringQueries", Url = new Uri(context.Request.Url+"data/" + recurringQuery.RecurringQueryID.ToString(), UriKind.Absolute) }; collectionInfo.SetAnnotation<AtomResourceCollectionMetadata>(new AtomResourceCollectionMetadata() { Title = new AtomTextConstruct() { Text = "MsrRecurringQueries"//recurringQuery.RecurringQueryName }, }); collections.Add(collectionInfo); } workSpace.Collections = collections.AsEnumerable<ODataResourceCollectionInfo>(); using (ODataMessageWriter messageWriter = new ODataMessageWriter(message, messageWriterSettings)) { messageWriter.WriteServiceDocumentAsync(workSpace); } } else { EdmModel mainModel =(EdmModel) QueryMetadataHttpHandler.BuildODataModel(); using (ODataMessageWriter messageWriter = new ODataMessageWriter(message, messageWriterSettings, mainModel)) { var msrRecurringQueryResultType = new EdmEntityType("mainNS", "MsrRecurringQuery", null); IEdmPrimitiveType edmPrimitiveType1 = new MSRAEdmPrimitiveType("Int32", "Edm", EdmPrimitiveTypeKind.Int32, EdmSchemaElementKind.TypeDefinition, EdmTypeKind.Primitive); IEdmPrimitiveType edmPrimitiveType2 = new MSRAEdmPrimitiveType("String", "Edm", EdmPrimitiveTypeKind.String, EdmSchemaElementKind.TypeDefinition, EdmTypeKind.Primitive); IEdmPrimitiveType edmPrimitiveType3 = new MSRAEdmPrimitiveType("String", "Edm", EdmPrimitiveTypeKind.String, EdmSchemaElementKind.TypeDefinition, EdmTypeKind.Primitive); IEdmPrimitiveType edmPrimitiveType4 = new MSRAEdmPrimitiveType("String", "Edm", EdmPrimitiveTypeKind.String, EdmSchemaElementKind.TypeDefinition, EdmTypeKind.Primitive); IEdmPrimitiveType edmPrimitiveType5 = new MSRAEdmPrimitiveType("String", "Edm", EdmPrimitiveTypeKind.String, EdmSchemaElementKind.TypeDefinition, EdmTypeKind.Primitive); IEdmPrimitiveType edmPrimitiveType6 = new MSRAEdmPrimitiveType("Decimal", "Edm", EdmPrimitiveTypeKind.Decimal, EdmSchemaElementKind.TypeDefinition, EdmTypeKind.Primitive); msrRecurringQueryResultType.AddKeys(new EdmStructuralProperty(msrRecurringQueryResultType, "RowId", new EdmPrimitiveTypeReference(edmPrimitiveType1, false))); msrRecurringQueryResultType.AddProperty(new EdmStructuralProperty(msrRecurringQueryResultType, "RowId", new EdmPrimitiveTypeReference(edmPrimitiveType1, false))); msrRecurringQueryResultType.AddProperty(new EdmStructuralProperty(msrRecurringQueryResultType, "Pricing_Level", new EdmPrimitiveTypeReference(edmPrimitiveType2, false))); msrRecurringQueryResultType.AddProperty(new EdmStructuralProperty(msrRecurringQueryResultType, "Business_Summary", new EdmPrimitiveTypeReference(edmPrimitiveType3, false))); msrRecurringQueryResultType.AddProperty(new EdmStructuralProperty(msrRecurringQueryResultType, "Future_Flag", new EdmPrimitiveTypeReference(edmPrimitiveType4, false))); msrRecurringQueryResultType.AddProperty(new EdmStructuralProperty(msrRecurringQueryResultType, "Fiscal_Month", new EdmPrimitiveTypeReference(edmPrimitiveType5, false))); msrRecurringQueryResultType.AddProperty(new EdmStructuralProperty(msrRecurringQueryResultType, "MS_Sales_Amount_Const", new EdmPrimitiveTypeReference(edmPrimitiveType6, false))); ODataWriter feedWriter = messageWriter.CreateODataFeedWriter( mainModel.EntityContainers().Select(c => c.EntitySets().First()).First(), msrRecurringQueryResultType); ODataFeed feed = new ODataFeed() { Id = "MsrRecurringQueries", }; feedWriter.WriteStart(feed); AzureTestDBEntities db = new AzureTestDBEntities(); var queries = db.T_annooli_231161891 ; foreach (var recurringQuery in queries) { ODataEntry entry = this.GetODataEntry(recurringQuery); feedWriter.WriteStart(entry); feedWriter.WriteEnd(); } feedWriter.WriteEnd(); } } }