/// <inheritdoc />
 public ODataEntityTypeSerializer(ODataSerializerProvider serializerProvider)
     : base(ODataPayloadKind.Entry, serializerProvider)
 {
 }
 internal ODataMediaTypeFormatter(ODataVersion oDataVersion, ODataDeserializerProvider oDataDeserializerProvider, ODataSerializerProvider oDataSerializerProvider)
     : this(oDataDeserializerProvider, oDataSerializerProvider)
 {
     _defaultODataVersion = oDataVersion;
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="RestierCollectionSerializer" /> class.
 /// </summary>
 /// <param name="provider">The serializer provider.</param>
 public RestierCollectionSerializer(ODataSerializerProvider provider)
     : base(provider)
 {
 }
Esempio n. 4
0
 public AnnotatingEntitySerializer(ODataSerializerProvider serializerProvider)
     : base(serializerProvider)
 {
 }
Esempio n. 5
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ODataMediaTypeFormatter"/> class.
        /// </summary>
        /// <param name="deserializerProvider">The <see cref="ODataDeserializerProvider"/> to use.</param>
        /// <param name="serializerProvider">The <see cref="ODataSerializerProvider"/> to use.</param>
        /// <param name="payloadKinds">The kind of payloads this formatter supports.</param>
        public ODataMediaTypeFormatter(ODataDeserializerProvider deserializerProvider, ODataSerializerProvider serializerProvider,
                                       IEnumerable <ODataPayloadKind> payloadKinds)
        {
            if (deserializerProvider == null)
            {
                throw Error.ArgumentNull("deserializerProvider");
            }
            if (serializerProvider == null)
            {
                throw Error.ArgumentNull("serializerProvider");
            }
            if (payloadKinds == null)
            {
                throw Error.ArgumentNull("payloadKinds");
            }

            _deserializerProvider = deserializerProvider;
            _serializerProvider   = serializerProvider;
            _payloadKinds         = payloadKinds;

            // Maxing out the received message size as we depend on the hosting layer to enforce this limit.
            MessageWriterSettings = new ODataMessageWriterSettings
            {
                Indent = true,
                DisableMessageStreamDisposal = true,
                MessageQuotas = new ODataMessageQuotas {
                    MaxReceivedMessageSize = Int64.MaxValue
                }
            };
            MessageReaderSettings = new ODataMessageReaderSettings
            {
                DisableMessageStreamDisposal = true,
                MessageQuotas = new ODataMessageQuotas {
                    MaxReceivedMessageSize = Int64.MaxValue
                },
            };

            _version = HttpRequestMessageProperties.DefaultODataVersion;
        }
Esempio n. 6
0
        public override Task WriteResponseBodyAsync(OutputFormatterWriteContext context, Encoding selectedEncoding)
        {
            Type type = context.ObjectType;

            if (type == null)
            {
                throw Error.ArgumentNull("type");
            }
            type = TypeHelper.GetTaskInnerTypeOrSelf(type);

            HttpRequest request = context.HttpContext.Request;

            if (request == null)
            {
                throw Error.InvalidOperation(SRResources.WriteToStreamAsyncMustHaveRequest);
            }

            try
            {
#if !NETSTANDARD2_0
                var body = request.HttpContext.Features.Get <AspNetCore.Http.Features.IHttpBodyControlFeature>();
                if (body != null)
                {
                    body.AllowSynchronousIO = true;
                }
#endif

                HttpResponse         response    = context.HttpContext.Response;
                Uri                  baseAddress = GetBaseAddressInternal(request);
                MediaTypeHeaderValue contentType = GetContentType(response.Headers[HeaderNames.ContentType].FirstOrDefault());

                Func <ODataSerializerContext> getODataSerializerContext = () =>
                {
                    return(new ODataSerializerContext()
                    {
                        Request = request,
                    });
                };

                ODataSerializerProvider serializerProvider = request.GetRequestContainer().GetRequiredService <ODataSerializerProvider>();

                ODataOutputFormatterHelper.WriteToStream(
                    type,
                    context.Object,
                    request.GetModel(),
                    ResultHelpers.GetODataResponseVersion(request),
                    baseAddress,
                    contentType,
                    new WebApiUrlHelper(request.GetUrlHelper()),
                    new WebApiRequestMessage(request),
                    new WebApiRequestHeaders(request.Headers),
                    (services) => ODataMessageWrapperHelper.Create(response.Body, response.Headers, services),
                    (edmType) => serializerProvider.GetEdmTypeSerializer(edmType),
                    (objectType) => serializerProvider.GetODataPayloadSerializer(objectType, request),
                    getODataSerializerContext);

                return(TaskHelpers.Completed());
            }
            catch (Exception ex)
            {
                return(TaskHelpers.FromError(ex));
            }
        }
Esempio n. 7
0
 public CustomFeedSerializer(ODataSerializerProvider serializerProvider)
     : base(serializerProvider)
 {
 }
Esempio n. 8
0
 /// <summary>
 /// Initializes a new instance of the <see cref="RestierResourceSetSerializer" /> class.
 /// </summary>
 /// <param name="provider">The serializer provider.</param>
 public RestierResourceSetSerializer(ODataSerializerProvider provider)
     : base(provider)
 {
 }
Esempio n. 9
0
 /// <summary>
 /// Initializes a new instance of the <see cref="RestierComplexTypeSerializer" /> class.
 /// </summary>
 /// <param name="provider">The serializer provider.</param>
 public RestierComplexTypeSerializer(ODataSerializerProvider provider)
     : base(provider)
 {
 }
Esempio n. 10
0
 /// <summary>
 /// Initializes a new instance of the <see cref="RestierFeedSerializer" /> class.
 /// </summary>
 /// <param name="provider">The serializer provider.</param>
 public RestierFeedSerializer(ODataSerializerProvider provider)
     : base(provider)
 {
 }
 protected DefaultStreamAwareEntityTypeSerializer(ODataSerializerProvider serializerProvider)
     : base(serializerProvider)
 {
 }
Esempio n. 12
0
        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.NotSupported(SRResources.WriteToStreamAsyncMustHaveRequest);
            }

            HttpContentHeaders contentHeaders = content == null ? null : content.Headers;

            return(TaskHelpers.RunSynchronously(() =>
            {
                // Get the format and version to use from the ODataServiceVersion content header or if not available use the
                // values configured for the specialized formatter instance.
                ODataVersion version;
                if (contentHeaders == null)
                {
                    version = _defaultODataVersion;
                }
                else
                {
                    version = GetODataVersion(contentHeaders, ODataFormatterConstants.ODataServiceVersion) ?? _defaultODataVersion;
                }

                // get the most appropriate serializer given that we support inheritance.
                type = value == null ? type : value.GetType();
                ODataSerializer serializer = ODataSerializerProvider.GetODataPayloadSerializer(type);
                if (serializer == null)
                {
                    throw Error.InvalidOperation(SRResources.TypeCannotBeSerialized, type.Name, typeof(ODataMediaTypeFormatter).Name);
                }

                UrlHelper urlHelper = Request.GetUrlHelper();

                IEdmEntitySet targetEntitySet = null;
                ODataUriHelpers.TryGetEntitySetAndEntityType(Request.RequestUri, Model, out targetEntitySet);

                // serialize a response
                Uri baseAddress = new Uri(Request.RequestUri, Request.GetConfiguration().VirtualPathRoot);

                // TODO: Bug 467617: figure out the story for the operation name on the client side and server side.
                // This is clearly a workaround. We are assuming that the operation name is the last segment in the request uri
                // which works for most cases and fall back to the type name of the object being written.
                // We should rather use uri parser semantic tree to figure out the operation name from the request url.
                string operationName = ODataUriHelpers.GetOperationName(Request.RequestUri, baseAddress);
                operationName = operationName ?? type.Name;

                IODataResponseMessage responseMessage = new ODataMessageWrapper(writeStream);

                // TODO: Issue 483: http://aspnetwebstack.codeplex.com/workitem/483
                // We need to set the MetadataDocumentUri when this property is added to ODataMessageWriterSettings as
                // part of the JSON Light work.
                // This is required so ODataLib can coerce AbsoluteUri's into RelativeUri's when appropriate in JSON Light.
                ODataMessageWriterSettings writerSettings = new ODataMessageWriterSettings()
                {
                    BaseUri = baseAddress,
                    Version = version,
                    Indent = true,
                    DisableMessageStreamDisposal = true
                };

                if (contentHeaders != null && contentHeaders.ContentType != null)
                {
                    writerSettings.SetContentType(contentHeaders.ContentType.ToString(), Encoding.UTF8.WebName);
                }

                using (ODataMessageWriter messageWriter = new ODataMessageWriter(responseMessage, writerSettings, ODataDeserializerProvider.EdmModel))
                {
                    ODataSerializerContext writeContext = new ODataSerializerContext()
                    {
                        EntitySet = targetEntitySet,
                        UrlHelper = urlHelper,
                        ServiceOperationName = operationName,
                        SkipExpensiveAvailabilityChecks = serializer.ODataPayloadKind == ODataPayloadKind.Feed,
                        Request = Request
                    };

                    serializer.WriteObject(value, messageWriter, writeContext);
                }
            }));
        }
Esempio n. 13
0
 protected SampleODataResourceSerializer(ODataSerializerProvider serializerProvider)
     : base(serializerProvider)
 {
 }
 public MediaEntityTypeSerializer(ODataSerializerProvider serializerProvider)
     : base(serializerProvider)
 {
 }
Esempio n. 15
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ODataCollectionSerializer"/> class.
 /// </summary>
 /// <param name="serializerProvider">The serializer provider to use to serialize nested objects.</param>
 public ODataCollectionSerializer(ODataSerializerProvider serializerProvider)
     : base(ODataPayloadKind.Collection, serializerProvider)
 {
 }
Esempio n. 16
0
 public NuGetEntityTypeSerializer(ODataSerializerProvider serializerProvider)
     : base(serializerProvider)
 {
     ContentType = "application/zip";
 }
 public SkipNullValueEntitySerializer(ODataSerializerProvider serializerProvider) : base(serializerProvider)
 {
 }
 /// <summary>
 /// constructor
 /// </summary>
 /// <param name="provider"></param>
 public IgnoreEmptyListsResourceSetSerializer(ODataSerializerProvider provider) : base(provider)
 {
 }
Esempio n. 19
0
        /// <inheritdoc/>
        public override bool CanWriteResult(OutputFormatterCanWriteContext context)
        {
            if (context == null)
            {
                throw Error.ArgumentNull("context");
            }

            // Ensure we have a valid request.
            HttpRequest request = context.HttpContext.Request;

            if (request == null)
            {
                throw Error.InvalidOperation(SRResources.ReadFromStreamAsyncMustHaveRequest);
            }

            // Ignore non-OData requests.
            if (request.ODataFeature().Path == null)
            {
                return(false);
            }

            // Allow the base class to make its determination, which includes
            // checks for SupportedMediaTypes.
            bool suportedMediaTypeFound = false;

            if (SupportedMediaTypes.Any())
            {
                suportedMediaTypeFound = base.CanWriteResult(context);
            }

            // See if the request satisfies any mappings.
            IEnumerable <MediaTypeMapping> matchedMappings = (MediaTypeMappings == null) ? null : MediaTypeMappings
                                                             .Where(m => (m.TryMatchMediaType(request) > 0));

            // Now pick the best content type. If a media mapping was found, use that and override the
            // value specified by the controller, if any. Otherwise, let the base class decide.
            if (matchedMappings != null && matchedMappings.Any())
            {
                context.ContentType = matchedMappings.First().MediaType.ToString();
            }
            else if (!suportedMediaTypeFound)
            {
                return(false);
            }

            // We need the type in order to write it.
            Type type = context.ObjectType ?? context.Object?.GetType();

            if (type == null)
            {
                return(false);
            }
            type = TypeHelper.GetTaskInnerTypeOrSelf(type);

            ODataSerializerProvider serializerProvider = request.GetRequestContainer().GetRequiredService <ODataSerializerProvider>();

            // See if this type is a SingleResult or is derived from SingleResult.
            bool isSingleResult = false;

            if (type.IsGenericType)
            {
                Type genericType = type.GetGenericTypeDefinition();
                Type baseType    = TypeHelper.GetBaseType(type);
                isSingleResult = (genericType == typeof(SingleResult <>) || baseType == typeof(SingleResult));
            }

            return(ODataOutputFormatterHelper.CanWriteType(
                       type,
                       _payloadKinds,
                       isSingleResult,
                       new WebApiRequestMessage(request),
                       (objectType) => serializerProvider.GetODataPayloadSerializer(objectType, request)));
        }
Esempio n. 20
0
 public CustomFeedSerializer(IEdmCollectionTypeReference edmType, ODataSerializerProvider serializerProvider)
     : base(edmType, serializerProvider)
 {
 }
Esempio n. 21
0
 public CustomEntrySerializer(ODataSerializerProvider serializerProvider)
     : base(serializerProvider)
 {
 }
Esempio n. 22
0
        public override Task WriteToStreamAsync(Type type, object value, Stream writeStream, HttpContent content,
                                                TransportContext transportContext, CancellationToken cancellationToken)
        {
            if (type == null)
            {
                throw Error.ArgumentNull("type");
            }
            if (writeStream == null)
            {
                throw Error.ArgumentNull("writeStream");
            }
            if (Request == null)
            {
                throw Error.InvalidOperation(SRResources.WriteToStreamAsyncMustHaveRequest);
            }
            if (cancellationToken.IsCancellationRequested)
            {
                return(TaskHelpers.Canceled());
            }

            try
            {
                if (typeof(Stream).IsAssignableFrom(type))
                {
                    // Ideally, it should go into the "ODataRawValueSerializer",
                    // However, OData lib doesn't provide the method to overwrite/copyto stream
                    // So, Here's the workaround
                    Stream objStream = value as Stream;
                    return(CopyStreamAsync(objStream, writeStream));
                }

                HttpConfiguration configuration = Request.GetConfiguration();
                if (configuration == null)
                {
                    throw Error.InvalidOperation(SRResources.RequestMustContainConfiguration);
                }

                HttpContentHeaders contentHeaders = (content == null) ? null : content.Headers;
                UrlHelper          urlHelper      = Request.GetUrlHelper() ?? new UrlHelper(Request);

                Func <ODataSerializerContext> getODataSerializerContext = () =>
                {
                    return(new ODataSerializerContext()
                    {
                        Request = Request,
                        Url = urlHelper,
                    });
                };

                ODataSerializerProvider serializerProvider = Request.GetRequestContainer()
                                                             .GetRequiredService <ODataSerializerProvider>();

                ODataOutputFormatterHelper.WriteToStream(
                    type,
                    value,
                    Request.GetModel(),
                    ResultHelpers.GetODataResponseVersion(Request),
                    GetBaseAddressInternal(Request),
                    contentHeaders == null ? null : contentHeaders.ContentType,
                    new WebApiUrlHelper(urlHelper),
                    new WebApiRequestMessage(Request),
                    new WebApiRequestHeaders(Request.Headers),
                    (services) => ODataMessageWrapperHelper.Create(writeStream, contentHeaders, services),
                    (edmType) => serializerProvider.GetEdmTypeSerializer(edmType),
                    (objectType) => serializerProvider.GetODataPayloadSerializer(objectType, Request),
                    getODataSerializerContext);

                return(TaskHelpers.Completed());
            }
            catch (Exception ex)
            {
                return(TaskHelpers.FromError(ex));
            }
        }
Esempio n. 23
0
        private ODataSerializer GetSerializer(Type type, object value, IEdmModel model, ODataSerializerProvider serializerProvider)
        {
            ODataSerializer serializer;

            IEdmObject edmObject = value as IEdmObject;

            if (edmObject != null)
            {
                IEdmTypeReference edmType = edmObject.GetEdmType();
                if (edmType == null)
                {
                    throw new SerializationException(Error.Format(SRResources.EdmTypeCannotBeNull,
                                                                  edmObject.GetType().FullName, typeof(IEdmObject).Name));
                }

                serializer = serializerProvider.GetEdmTypeSerializer(edmType);
                if (serializer == null)
                {
                    string message = Error.Format(SRResources.TypeCannotBeSerialized, edmType.ToTraceString(), typeof(ODataMediaTypeFormatter).Name);
                    throw new SerializationException(message);
                }
            }
            else
            {
                // get the most appropriate serializer given that we support inheritance.
                type       = value == null ? type : value.GetType();
                serializer = serializerProvider.GetODataPayloadSerializer(model, type, Request);
                if (serializer == null)
                {
                    string message = Error.Format(SRResources.TypeCannotBeSerialized, type.Name, typeof(ODataMediaTypeFormatter).Name);
                    throw new SerializationException(message);
                }
            }

            return(serializer);
        }
        /// <inheritdoc/>
        public override bool CanWriteResult(OutputFormatterCanWriteContext context)
        {
            if (context == null)
            {
                throw Error.ArgumentNull("context");
            }

            // Ensure we have a valid request.
            HttpRequest request = context.HttpContext.Request;

            if (request == null)
            {
                throw Error.InvalidOperation(SRResources.ReadFromStreamAsyncMustHaveRequest);
            }

            // Ignore non-OData requests.
            if (request.ODataFeature().Path == null)
            {
                return(false);
            }

            // Be noted: Before coming here (.NET 5), the ContentType is reset as empty as:
            // formatterContext.ContentType = new StringSegment();

            // Allow the base class to make its determination, which includes
            // checks for SupportedMediaTypes.
            bool suportedMediaTypeFound = false;

            if (SupportedMediaTypes.Any())
            {
                suportedMediaTypeFound = base.CanWriteResult(context);
            }

            // See if the request satisfies any mappings.
            IEnumerable <MediaTypeMapping> matchedMappings = (MediaTypeMappings == null) ? null : MediaTypeMappings
                                                             .Where(m => m.TryMatchMediaType(request) > 0);

            // Now pick the best content type. If a media mapping was found, use that and override the
            // value specified by the controller, if any. Otherwise, let the base class decide.
            if (matchedMappings != null && matchedMappings.Any())
            {
                context.ContentType = matchedMappings.First().MediaType.ToString();
            }
            else if (!suportedMediaTypeFound)
            {
                return(false);
            }

            // We need the type in order to write it.
            Type type = context.ObjectType ?? context.Object?.GetType();

            if (type == null)
            {
                return(false);
            }
            type = TypeHelper.GetTaskInnerTypeOrSelf(type);

            ODataSerializerProvider serializerProvider = request.GetSubServiceProvider().GetRequiredService <ODataSerializerProvider>();

            // See if this type is a SingleResult or is derived from SingleResult.
            bool isSingleResult = false;

            if (type.IsGenericType)
            {
                Type genericType = type.GetGenericTypeDefinition();
                Type baseType    = type.BaseType;
                isSingleResult = (genericType == typeof(SingleResult <>) || baseType == typeof(SingleResult));
            }

            ODataPayloadKind?payloadKind;

            Type elementType;

            if (typeof(IEdmObject).IsAssignableFrom(type) ||
                (TypeHelper.IsCollection(type, out elementType) && typeof(IEdmObject).IsAssignableFrom(elementType)))
            {
                payloadKind = GetEdmObjectPayloadKind(type, request);
            }
            else
            {
                payloadKind = GetClrObjectResponsePayloadKind(type, isSingleResult, serializerProvider, request);
            }

            return(payloadKind == null ? false : _payloadKinds.Contains(payloadKind.Value));
        }
        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.NotSupported(SRResources.WriteToStreamAsyncMustHaveRequest);
            }

            HttpContentHeaders contentHeaders = content == null ? null : content.Headers;

            return(TaskHelpers.RunSynchronously(() =>
            {
                // Get the format and version to use from the ODataServiceVersion content header or if not available use the
                // values configured for the specialized formatter instance.
                ODataVersion version;
                ODataFormat odataFormat;
                if (contentHeaders == null)
                {
                    version = _defaultODataVersion;
                    odataFormat = ODataFormatterConstants.DefaultODataFormat;
                }
                else
                {
                    version = GetODataVersion(contentHeaders, ODataFormatterConstants.ODataServiceVersion) ?? _defaultODataVersion;
                    odataFormat = GetODataFormat(contentHeaders);
                }

                ODataSerializer serializer = ODataSerializerProvider.GetODataPayloadSerializer(type);
                if (serializer == null)
                {
                    throw Error.InvalidOperation(SRResources.TypeCannotBeSerialized, type.Name, typeof(ODataMediaTypeFormatter).Name);
                }

                UrlHelper urlHelper = Request.GetUrlHelper();
                NameValueCollection queryStringValues = Request.RequestUri.ParseQueryString();

                IEdmEntitySet targetEntitySet = null;
                ODataUriHelpers.TryGetEntitySetAndEntityType(Request.RequestUri, Model, out targetEntitySet);

                ODataQueryProjectionNode rootProjectionNode = null;
                if (targetEntitySet != null)
                {
                    // TODO: Bug 467621: Move to ODataUriParser once it is done.
                    rootProjectionNode = ODataUriHelpers.GetODataQueryProjectionNode(queryStringValues["$select"], queryStringValues["$expand"], targetEntitySet);
                }

                // serialize a response
                Uri baseAddress = new Uri(Request.RequestUri, Request.GetConfiguration().VirtualPathRoot);

                // TODO: Bug 467617: figure out the story for the operation name on the client side and server side.
                // This is clearly a workaround. We are assuming that the operation name is the last segment in the request uri
                // which works for most cases and fall back to the type name of the object being written.
                // We should rather use uri parser semantic tree to figure out the operation name from the request url.
                string operationName = ODataUriHelpers.GetOperationName(Request.RequestUri, baseAddress);
                operationName = operationName ?? type.Name;

                IODataResponseMessage responseMessage = new ODataMessageWrapper(writeStream);

                ODataMessageWriterSettings writerSettings = new ODataMessageWriterSettings()
                {
                    BaseUri = baseAddress,
                    Version = version,
                    Indent = true,
                    DisableMessageStreamDisposal = true,
                };
                if (contentHeaders != null && contentHeaders.ContentType != null)
                {
                    writerSettings.SetContentType(contentHeaders.ContentType.ToString(), Encoding.UTF8.WebName);
                }

                using (ODataMessageWriter messageWriter = new ODataMessageWriter(responseMessage, writerSettings, ODataDeserializerProvider.EdmModel))
                {
                    ODataSerializerContext writeContext = new ODataSerializerContext()
                    {
                        EntitySet = targetEntitySet,
                        UrlHelper = urlHelper,
                        RootProjectionNode = rootProjectionNode,
                        CurrentProjectionNode = rootProjectionNode,
                        ServiceOperationName = operationName
                    };

                    serializer.WriteObject(value, messageWriter, writeContext);
                }
            }));
        }
        public override Task WriteToStreamAsync(Type type, object value, Stream writeStream, HttpContent content,
                                                TransportContext transportContext, CancellationToken cancellationToken)
        {
            if (type == null)
            {
                throw Error.ArgumentNull("type");
            }
            if (writeStream == null)
            {
                throw Error.ArgumentNull("writeStream");
            }
            if (Request == null)
            {
                throw Error.InvalidOperation(SRResources.WriteToStreamAsyncMustHaveRequest);
            }
            if (cancellationToken.IsCancellationRequested)
            {
                return(TaskHelpers.Canceled());
            }

            try
            {
                HttpConfiguration configuration = Request.GetConfiguration();
                if (configuration == null)
                {
                    throw Error.InvalidOperation(SRResources.RequestMustContainConfiguration);
                }

                HttpContentHeaders contentHeaders = (content == null) ? null : content.Headers;
                UrlHelper          urlHelper      = Request.GetUrlHelper() ?? new UrlHelper(Request);

                Func <ODataSerializerContext> getODataSerializerContext = () =>
                {
                    return(new ODataSerializerContext()
                    {
                        Request = Request,
                        Url = urlHelper,
                    });
                };

                ODataSerializerProvider serializerProvider = Request.GetRequestContainer()
                                                             .GetRequiredService <ODataSerializerProvider>();

                ODataOutputFormatterHelper.WriteToStream(
                    type,
                    value,
                    Request.GetModel(),
                    _version,
                    GetBaseAddressInternal(Request),
                    contentHeaders == null ? null : contentHeaders.ContentType,
                    new WebApiUrlHelper(urlHelper),
                    new WebApiRequestMessage(Request),
                    new WebApiRequestHeaders(Request.Headers),
                    (services) => ODataMessageWrapperHelper.Create(writeStream, contentHeaders, services),
                    (edmType) => serializerProvider.GetEdmTypeSerializer(edmType),
                    (objectType) => serializerProvider.GetODataPayloadSerializer(objectType, Request),
                    getODataSerializerContext);

                return(TaskHelpers.Completed());
            }
            catch (Exception ex)
            {
                return(TaskHelpers.FromError(ex));
            }
        }
        internal ODataMediaTypeFormatter(ODataDeserializerProvider oDataDeserializerProvider, ODataSerializerProvider oDataSerializerProvider)
        {
            ODataDeserializerProvider = oDataDeserializerProvider;
            Model = oDataDeserializerProvider.EdmModel;
            ODataSerializerProvider = oDataSerializerProvider;

            SupportedMediaTypes.Add(ODataFormatterConstants.ApplicationAtomXmlMediaType);
            SupportedMediaTypes.Add(ODataFormatterConstants.ApplicationJsonMediaType);
            SupportedMediaTypes.Add(ODataFormatterConstants.ApplicationXmlMediaType);

            SupportedEncodings.Add(new UnicodeEncoding(bigEndian: false, byteOrderMark: true, throwOnInvalidBytes: true));
            SupportedEncodings.Add(new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true));
        }
 public MyODataResourceSerializer(ODataSerializerProvider serializerProvider)
     : base(serializerProvider)
 {
 }
Esempio n. 29
0
        internal static async Task WriteToStreamAsync(
            Type type,
            object value,
            IEdmModel model,
            ODataVersion version,
            Uri baseAddress,
            MediaTypeHeaderValue contentType,
            HttpRequest request,
            IHeaderDictionary requestHeaders,
            ODataSerializerProvider serializerProvider)
        {
            if (model == null)
            {
                throw Error.InvalidOperation(SRResources.RequestMustHaveModel);
            }

            ODataSerializer serializer = GetSerializer(type, value, request, serializerProvider);

            ODataPath            path = request.ODataFeature().Path;
            IEdmNavigationSource targetNavigationSource = GetTargetNavigationSource(path, model);
            HttpResponse         response = request.HttpContext.Response;

            // serialize a response
            string preferHeader     = RequestPreferenceHelpers.GetRequestPreferHeader(requestHeaders);
            string annotationFilter = null;

            if (!string.IsNullOrEmpty(preferHeader))
            {
                ODataMessageWrapper messageWrapper = ODataMessageWrapperHelper.Create(response.Body, response.Headers);
                messageWrapper.SetHeader(RequestPreferenceHelpers.PreferHeaderName, preferHeader);
                annotationFilter = messageWrapper.PreferHeader().AnnotationFilter;
            }

            IODataResponseMessageAsync responseMessage = ODataMessageWrapperHelper.Create(new StreamWrapper(response.Body), response.Headers, request.GetSubServiceProvider());

            if (annotationFilter != null)
            {
                responseMessage.PreferenceAppliedHeader().AnnotationFilter = annotationFilter;
            }

            ODataMessageWriterSettings writerSettings = request.GetWriterSettings();

            writerSettings.BaseUri     = baseAddress;
            writerSettings.Version     = version;
            writerSettings.Validations = writerSettings.Validations & ~ValidationKinds.ThrowOnUndeclaredPropertyForNonOpenType;

            string metadataLink = request.CreateODataLink(MetadataSegment.Instance);

            if (metadataLink == null)
            {
                throw new SerializationException(SRResources.UnableToDetermineMetadataUrl);
            }

            // Set this variable if the SelectExpandClause is different from the processed clause on the Query options
            SelectExpandClause selectExpandDifferentFromQueryOptions = null;
            ODataQueryOptions  queryOptions = request.GetQueryOptions();
            SelectExpandClause processedSelectExpandClause = request.ODataFeature().SelectExpandClause;

            if (queryOptions != null && queryOptions.SelectExpand != null)
            {
                if (queryOptions.SelectExpand.ProcessedSelectExpandClause != processedSelectExpandClause)
                {
                    selectExpandDifferentFromQueryOptions = processedSelectExpandClause;
                }
            }
            else if (processedSelectExpandClause != null)
            {
                selectExpandDifferentFromQueryOptions = processedSelectExpandClause;
            }

            writerSettings.ODataUri = new ODataUri
            {
                ServiceRoot = baseAddress,

                // TODO: 1604 Convert webapi.odata's ODataPath to ODL's ODataPath, or use ODL's ODataPath.
                SelectAndExpand = processedSelectExpandClause,
                Apply           = request.ODataFeature().ApplyClause,
                Path            = path
            };

            ODataMetadataLevel metadataLevel = ODataMetadataLevel.Minimal;

            if (contentType != null)
            {
                IEnumerable <KeyValuePair <string, string> > parameters =
                    contentType.Parameters.Select(val => new KeyValuePair <string, string>(val.Name.ToString(),
                                                                                           val.Value.ToString()));
                metadataLevel = ODataMediaTypes.GetMetadataLevel(contentType.MediaType.ToString(), parameters);
            }

            using (ODataMessageWriter messageWriter = new ODataMessageWriter(responseMessage, writerSettings, model))
            {
                ODataSerializerContext writeContext = BuildSerializerContext(request);
                writeContext.NavigationSource = targetNavigationSource;
                writeContext.Model            = model;
                writeContext.RootElementName  = GetRootElementName(path) ?? "root";
                writeContext.SkipExpensiveAvailabilityChecks = serializer.ODataPayloadKind == ODataPayloadKind.ResourceSet;
                writeContext.Path          = path;
                writeContext.MetadataLevel = metadataLevel;
                writeContext.QueryOptions  = queryOptions;

                //Set the SelectExpandClause on the context if it was explicitly specified.
                if (selectExpandDifferentFromQueryOptions != null)
                {
                    writeContext.SelectExpandClause = selectExpandDifferentFromQueryOptions;
                }

                await serializer.WriteObjectAsync(value, type, messageWriter, writeContext).ConfigureAwait(false);
            }
        }
Esempio n. 30
0
 public MySerializer(ODataSerializerProvider sp) : base(sp)
 {
 }
 /// <summary>
 /// Initializes a new instance of <see cref="ODataDeltaFeedSerializer"/>.
 /// </summary>
 /// <param name="serializerProvider">The <see cref="ODataSerializerProvider"/> to use to write nested entries.</param>
 public ODataDeltaFeedSerializer(ODataSerializerProvider serializerProvider)
     : base(ODataPayloadKind.Delta, serializerProvider)
 {
 }
 public MockContainer()
 {
     serializerProvider   = new DefaultODataSerializerProvider(this);
     collectionSerializer = new ODataCollectionSerializer(serializerProvider);
     primitiveSerializer  = new ODataPrimitiveSerializer();
 }
Esempio n. 33
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ODataComplexTypeSerializer"/> class.
 /// </summary>
 /// <param name="serializerProvider">The serializer provider to use to serialize nested objects.</param>
 public ODataComplexTypeSerializer(ODataSerializerProvider serializerProvider)
     : base(ODataPayloadKind.Property, serializerProvider)
 {
 }
 public DefaultODataEnumSerializer(ODataSerializerProvider serializerProvider)
     : base(serializerProvider)
 {
 }