/// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="contentType">The parsed content type as <see cref="ODataMediaType"/>.</param>
        /// <param name="encoding">The encoding from the content type or the default encoding from <see cref="ODataMediaType" />.</param>
        /// <param name="messageReaderSettings">The <see cref="ODataMessageReaderSettings"/> being used for reading the message.</param>
        /// <param name="model">The <see cref="IEdmModel"/> for the payload.</param>
        internal ODataPayloadKindDetectionInfo(
            ODataMediaType contentType,
            Encoding encoding,
            ODataMessageReaderSettings messageReaderSettings, 
            IEdmModel model)
        {
            ExceptionUtils.CheckArgumentNotNull(contentType, "contentType");
            ExceptionUtils.CheckArgumentNotNull(messageReaderSettings, "readerSettings");

            this.contentType = contentType;
            this.encoding = encoding;
            this.messageReaderSettings = messageReaderSettings;
            this.model = model;
        }
Exemplo n.º 2
0
 public VCardInputContext(ODataFormat format,
     Stream messageStream,
     ODataMediaType contentType,
     Encoding encoding,
     ODataMessageReaderSettings messageReaderSettings,
     bool readingResponse,
     bool synchronous,
     IEdmModel model,
     IODataUrlResolver urlResolver)
     : base(format, messageReaderSettings, readingResponse, synchronous, model, urlResolver)
 {
     this.stream = messageStream;
     this.reader = new VCardReader(new StreamReader(messageStream, encoding));
     this.throwExceptionOnDuplicatedPropertyNames = false;
 }
Exemplo n.º 3
0
        internal ODataAvroInputContext(
            ODataFormat format,
            Stream messageStream,
            ODataMediaType contentType,
            Encoding encoding,
            ODataMessageReaderSettings messageReaderSettings,
            bool readingResponse,
            bool synchronous,
            IEdmModel model,
            IODataUrlResolver urlResolver)
            : base(format, messageReaderSettings, readingResponse, synchronous, model, urlResolver)
        {
            this.stream = messageStream;

            MemoryStream st = new MemoryStream();
            stream.CopyTo(st);
            st.Seek(0, SeekOrigin.Begin);
            this.AvroReader = new AvroReader(AvroContainer.CreateGenericReader(st));
        }
 private void WriteNoMetadataResponseWithoutModelAndValidatePayload(ODataItem[] nestedItemToWrite, string expectedPayload, bool setMetadataDocumentUri = true)
 {
     // without model, write response
     // (when entityType==null: nonemetadata or (serviceDocumentUri==null && writingResponse==false) -> avoid the below exception. pls refer to ODataContextUriBuilder method)
     // "When writing a JSON response, a user model must be specified and the entity set and entity type must be passed to the ODataMessageWriter.CreateEntryWriter method or the ODataFeedAndEntrySerializationInfo must be set on the ODataEntry or ODataFeed that is being writen."
     // so here use nonemetadata:
     ODataMediaType mediaType = new ODataMediaType("application", "json", new KeyValuePair<string, string>(MimeConstants.MimeMetadataParameterName, MimeConstants.MimeMetadataParameterValueNone));
     var stream = new MemoryStream();
     var outputContext = CreateJsonLightOutputContext(stream, mediaType, true, null, setMetadataDocumentUri ? this.serviceDocumentUri : null);
     var writer = new ODataJsonLightWriter(outputContext, null, null, nestedItemToWrite[0] is ODataFeed);
     WriteNestedItems(nestedItemToWrite, writer);
     ValidateWrittenPayload(stream, writer, expectedPayload);
 }
 private void WriteResponseWithModelAndValidatePayload(ODataMediaType mediaType, ODataItem[] nestedItemToWrite, string expectedPayload, bool setMetadataDocumentUri = true)
 {
     // with model
     // write response
     var stream = new MemoryStream();
     var outputContext = CreateJsonLightOutputContext(stream, mediaType, true, this.userModel, setMetadataDocumentUri ? this.serviceDocumentUri : null);
     var writer = new ODataJsonLightWriter(outputContext, this.entitySet, this.entityType, nestedItemToWrite[0] is ODataFeed);
     WriteNestedItems(nestedItemToWrite, writer);
     ValidateWrittenPayload(stream, writer, expectedPayload);
 }
        private void WriteMinimalMetadataRequestWithoutModelAndValidatePayload(ODataItem[] nestedItemToWrite, string expectedPayload, bool setMetadataDocumentUri = true)
        {
            // without model, write request (JsonLightMetadataLevel.Create method will internally use MinimalMetadata for writing request)
            ODataMediaType mediaType = new ODataMediaType("application", "json", new KeyValuePair<string, string>(MimeConstants.MimeMetadataParameterName, MimeConstants.MimeMetadataParameterValueMinimal));

            // 1. CreateEntityContainerElementContextUri(): no entitySetName --> no context uri is output.
            // 2. but odata.type will be output because of no model. JsonMinimalMetadataTypeNameOracle.GetEntryTypeNameForWriting method: // We only write entity type names in Json Light if it's more derived (different) from the expected type name.
            var stream = new MemoryStream();
            var outputContext = CreateJsonLightOutputContext(stream, mediaType, false, null, setMetadataDocumentUri ? this.serviceDocumentUri : null);
            var writer = new ODataJsonLightWriter(outputContext, null, null, nestedItemToWrite[0] is ODataFeed);
            WriteNestedItems(nestedItemToWrite, writer);
            ValidateWrittenPayload(stream, writer, expectedPayload);
        }
        public void FlagsEnumAsEntityProperty_NullAsValue_NonNullable_WithModelMinimalMetadata_NullError()
        {
            var entry = new ODataEntry
            {
                TypeName = "NS.MyEntityType",
                Properties = new[]
                {
                    new ODataProperty { Name = "ColorFlags", Value = null }
                }
            };

            var nestedItemToWrite = new ODataItem[] { entry };
            ODataMediaType mediaType = new ODataMediaType("application", "json", new KeyValuePair<string, string>(MimeConstants.MimeMetadataParameterName, MimeConstants.MimeMetadataParameterValueMinimal));
            string fullName = this.entityType.FindProperty("ColorFlags").Type.FullName();

            // with model: write response
            Action action = () => { this.WriteResponseWithModelAndValidatePayload(mediaType, nestedItemToWrite, "no_expectedPayload", true); };
            action.ShouldThrow<ODataException>().WithMessage(Strings.WriterValidationUtils_NonNullablePropertiesMustNotHaveNullValue("ColorFlags", fullName));

            // with model: write request
            action = () => { this.WriteMinimalRequestWithModelAndValidatePayload(mediaType, nestedItemToWrite, "no_expectedPayload", true); };
            action.ShouldThrow<ODataException>().WithMessage(Strings.WriterValidationUtils_NonNullablePropertiesMustNotHaveNullValue("ColorFlags", fullName));
        }
 private void WriteMinimalRequestWithModelAndValidatePayload(ODataMediaType mediaType, ODataItem[] nestedItemToWrite, string expectedPayload, bool setMetadataDocumentUri = true)
 {
     // with model
     // write request (JsonLightMetadataLevel.Create method will internally use MinimalMetadata for writing request)
     var stream = new MemoryStream();
     var outputContext = CreateJsonLightOutputContext(stream, mediaType, false, this.userModel, setMetadataDocumentUri ? this.serviceDocumentUri : null);
     var writer = new ODataJsonLightWriter(outputContext, this.entitySet, this.entityType, nestedItemToWrite[0] is ODataFeed);
     WriteNestedItems(nestedItemToWrite, writer);
     ValidateWrittenPayload(stream, writer, expectedPayload);
 }
Exemplo n.º 9
0
        /// <summary>Gets the best encoding available for the specified charset request.</summary>
        /// <param name="acceptableCharsets">
        /// The Accept-Charset header value (eg: "iso-8859-5, unicode-1-1;q=0.8").
        /// </param>
        /// <param name="mediaType">The media type used to compute the default encoding for the payload.</param>
        /// <param name="utf8Encoding">The encoding to use for UTF-8 charsets; we use the one without the BOM.</param>
        /// <param name="defaultEncoding">The encoding to use if no encoding could be computed from the <paramref name="acceptableCharsets"/> or <paramref name="mediaType"/>.</param>
        /// <returns>An Encoding object appropriate to the specifed charset request.</returns>
        internal static Encoding EncodingFromAcceptableCharsets(string acceptableCharsets, ODataMediaType mediaType, Encoding utf8Encoding, Encoding defaultEncoding)
        {
            Debug.Assert(mediaType != null, "mediaType != null");

            // Determines the appropriate encoding mapping according to
            // RFC 2616.14.2 (http://tools.ietf.org/html/rfc2616#section-14.2).
            Encoding result = null;
            if (!string.IsNullOrEmpty(acceptableCharsets))
            {
                // PERF: in the future if we find that computing the encoding from the accept charsets is
                //       too expensive we could introduce a cache of original strings to resolved encoding.
                CharsetPart[] parts = new List<CharsetPart>(AcceptCharsetParts(acceptableCharsets)).ToArray();

                // NOTE: List<T>.Sort uses an unstable sort algorithm; if charsets have the same quality value
                //       we want to pick the first one specified so we need a stable sort.
                KeyValuePair<int, CharsetPart>[] sortedParts = parts.StableSort(delegate(CharsetPart x, CharsetPart y)
                {
                    return y.Quality - x.Quality;
                });

                foreach (KeyValuePair<int, CharsetPart> sortedPart in sortedParts)
                {
                    CharsetPart part = sortedPart.Value;
                    if (part.Quality > 0)
                    {
                        // When UTF-8 is specified, select the version that doesn't use the BOM.
                        if (String.Compare("utf-8", part.Charset, StringComparison.OrdinalIgnoreCase) == 0)
                        {
                            result = utf8Encoding;
                            break;
                        }
                        else
                        {
                            result = GetEncodingFromCharsetName(part.Charset);
                            if (result != null)
                            {
                                break;
                            }

                            // If the charset is not supported it is ignored so other possible charsets are evaluated.
                        }
                    }
                }
            }

            // No Charset was specifed, or if charsets were specified, no valid charset was found.
            // Returning a different charset is also valid. Get the default encoding for the media type.
            if (result == null)
            {
                result = mediaType.SelectEncoding();
                if (result == null)
                {
                    return defaultEncoding;
                }
            }

            return result;
        }
        public void FlagsEnumAsEntityProperty_StrAsValue_StrAsTypeName_NoMetadata()
        {
            Func<ODataEntry> entryClone = () => new ODataEntry
            {
                TypeName = "NS.MyEntityType",
                Properties = new[]
                        {
                            new ODataProperty
                            {
                                Name = "FloatId",
                                Value = new ODataPrimitiveValue(12.3D)
                            },
                            new ODataProperty
                            {
                                Name = "ColorFlags",
                                Value = new ODataEnumValue(ColorFlags.Green.ToString(), "Fully.Qualified.Namespace.ColorFlags")
                            }
                        }
            };

            ODataMediaType mediaType = new ODataMediaType("application", "json", new KeyValuePair<string, string>(MimeConstants.MimeMetadataParameterName, MimeConstants.MimeMetadataParameterValueNone));

            // NoModel-request (request: forced MinimalMetadata)
            string expectedPayload = "{\"@odata.context\":\"http://odata.org/test/$metadata#MySet/$entity\",\"FloatId\":12.3,\"ColorFlags\":\"Green\"}";
            this.WriteMinimalRequestWithModelAndValidatePayload(mediaType: mediaType, nestedItemToWrite: new[] { entryClone() }, expectedPayload: expectedPayload);

            // model-reseponse
            expectedPayload = expectedPayload = "{\"FloatId\":12.3,\"ColorFlags\":\"Green\"}";
            this.WriteResponseWithModelAndValidatePayload(mediaType: mediaType, nestedItemToWrite: new[] { entryClone() }, expectedPayload: expectedPayload);

            // NoModel-request (request: forced MinimalMetadata)
            expectedPayload = "{\"@odata.type\":\"#NS.MyEntityType\",\"FloatId\":12.3,\"[email protected]\":\"#Fully.Qualified.Namespace.ColorFlags\",\"ColorFlags\":\"Green\"}";
            this.WriteMinimalMetadataRequestWithoutModelAndValidatePayload(nestedItemToWrite: new[] { entryClone() }, expectedPayload: expectedPayload);

            // NoModel-response (using NoMetadata)
            expectedPayload = "{\"FloatId\":12.3,\"ColorFlags\":\"Green\"}";
            this.WriteNoMetadataResponseWithoutModelAndValidatePayload(nestedItemToWrite: new[] { entryClone() }, expectedPayload: expectedPayload);
        }
Exemplo n.º 11
0
        /// <summary>
        /// Detects the payload kind(s) from the message stream.
        /// </summary>
        /// <param name="contentType">The content type of the message.</param>
        /// <returns>An enumerable of zero, one or more payload kinds that were detected from looking at the payload in the message stream.</returns>
        private static IEnumerable<ODataPayloadKind> DetectPayloadKindImplementation(ODataMediaType contentType)
        {
            // NOTE: for batch payloads we only use the content type header of the message to detect the payload kind.
            //       We assume a valid batch payload if the content type is multipart/mixed and a boundary parameter exists
            // Require 'multipart/mixed' content type with a boundary parameter to be considered batch.
            if (HttpUtils.CompareMediaTypeNames(MimeConstants.MimeMultipartType, contentType.Type) &&
                HttpUtils.CompareMediaTypeNames(MimeConstants.MimeMixedSubType, contentType.SubType) &&
                contentType.Parameters != null &&
                contentType.Parameters.Any(kvp => HttpUtils.CompareMediaTypeParameterNames(ODataConstants.HttpMultipartBoundary, kvp.Key)))
            {
                return new ODataPayloadKind[] { ODataPayloadKind.Batch };
            }

            return Enumerable.Empty<ODataPayloadKind>();
        }
Exemplo n.º 12
0
 /// <summary>
 /// Constructor for<see cref="ODataMediaTypeFormat"/>
 /// </summary>
 /// <param name="mediaType">MediaType to be used.</param>
 /// <param name="format">Associated format.</param>
 public ODataMediaTypeFormat(ODataMediaType mediaType, ODataFormat format)
 {
     this.MediaType = mediaType;
     this.Format = format;
 }
 public void Initialize()
 {
     this.parameterList = new List<KeyValuePair<string, string>>();
     this.applicationJsonMediaType = new ODataMediaType("application", "json", this.parameterList);
 }
Exemplo n.º 14
0
        public void TestCustomMediaTypeGetFormatFromContentType()
        {
            var resolver = new MyMediaTypeResolver();
            foreach (var payloadKind in Enum.GetValues(typeof(ODataPayloadKind)).Cast<ODataPayloadKind>())
            {
                if (payloadKind == ODataPayloadKind.Unsupported)
                {
                    continue;
                }

                string contentType = "text/x-A";
                string expectedBoundary = null;
                ODataMediaType expectedMediaType = MyFormat.MediaTypeWithFormatA.MediaType;
                if (payloadKind == ODataPayloadKind.Batch)
                {
                    expectedBoundary = "ba_" + Guid.NewGuid();
                    contentType += ";boundary=" + expectedBoundary;
                    expectedMediaType = new ODataMediaType("text", "x-A", new KeyValuePair<string, string>("boundary", expectedBoundary));
                }

                ODataMediaType mediaType;
                Encoding encoding;
                ODataPayloadKind selectedPayloadKind;
                string batchBoundary;
                ODataFormat actual = MediaTypeUtils.GetFormatFromContentType(contentType, new[] { payloadKind }, resolver, out mediaType, out encoding, out selectedPayloadKind, out batchBoundary);

                Console.WriteLine(payloadKind);
                actual.ShouldBeEquivalentTo(MyFormat.Instance);
                mediaType.ShouldBeEquivalentTo(expectedMediaType);
                encoding.ShouldBeEquivalentTo(payloadKind == ODataPayloadKind.BinaryValue ? null : Encoding.UTF8);
                selectedPayloadKind.ShouldBeEquivalentTo(payloadKind);
                batchBoundary.ShouldBeEquivalentTo(expectedBoundary);
            }
        }
Exemplo n.º 15
0
        /// <summary>Builds a Content-Type header which includes media type and encoding information.</summary>
        /// <param name="mediaType">Media type to be used.</param>
        /// <param name="encoding">Encoding to be used in response, possibly null.</param>
        /// <returns>The value for the Content-Type header.</returns>
        internal static string BuildContentType(ODataMediaType mediaType, Encoding encoding)
        {
            Debug.Assert(mediaType != null, "mediaType != null");

            return(mediaType.ToText(encoding));
        }
Exemplo n.º 16
0
        /// <summary>Gets the best encoding available for the specified charset request.</summary>
        /// <param name="acceptableCharsets">
        /// The Accept-Charset header value (eg: "iso-8859-5, unicode-1-1;q=0.8").
        /// </param>
        /// <param name="mediaType">The media type used to compute the default encoding for the payload.</param>
        /// <param name="utf8Encoding">The encoding to use for UTF-8 charsets; we use the one without the BOM.</param>
        /// <param name="defaultEncoding">The encoding to use if no encoding could be computed from the <paramref name="acceptableCharsets"/> or <paramref name="mediaType"/>.</param>
        /// <returns>An Encoding object appropriate to the specifed charset request.</returns>
        internal static Encoding EncodingFromAcceptableCharsets(string acceptableCharsets, ODataMediaType mediaType, Encoding utf8Encoding, Encoding defaultEncoding)
        {
            Debug.Assert(mediaType != null, "mediaType != null");

            // Determines the appropriate encoding mapping according to
            // RFC 2616.14.2 (http://tools.ietf.org/html/rfc2616#section-14.2).
            Encoding result = null;

            if (!string.IsNullOrEmpty(acceptableCharsets))
            {
                // PERF: in the future if we find that computing the encoding from the accept charsets is
                //       too expensive we could introduce a cache of original strings to resolved encoding.
                CharsetPart[] parts = new List <CharsetPart>(AcceptCharsetParts(acceptableCharsets)).ToArray();

                // NOTE: List<T>.Sort uses an unstable sort algorithm; if charsets have the same quality value
                //       we want to pick the first one specified so we need a stable sort.
                KeyValuePair <int, CharsetPart>[] sortedParts = parts.StableSort(delegate(CharsetPart x, CharsetPart y)
                {
                    return(y.Quality - x.Quality);
                });

                foreach (KeyValuePair <int, CharsetPart> sortedPart in sortedParts)
                {
                    CharsetPart part = sortedPart.Value;
                    if (part.Quality > 0)
                    {
                        // When UTF-8 is specified, select the version that doesn't use the BOM.
                        if (String.Compare("utf-8", part.Charset, StringComparison.OrdinalIgnoreCase) == 0)
                        {
                            result = utf8Encoding;
                            break;
                        }
                        else
                        {
                            result = GetEncodingFromCharsetName(part.Charset);
                            if (result != null)
                            {
                                break;
                            }

                            // If the charset is not supported it is ignored so other possible charsets are evaluated.
                        }
                    }
                }
            }

            // No Charset was specifed, or if charsets were specified, no valid charset was found.
            // Returning a different charset is also valid. Get the default encoding for the media type.
            if (result == null)
            {
                result = mediaType.SelectEncoding();
                if (result == null)
                {
                    return(defaultEncoding);
                }
            }

            return(result);
        }
Exemplo n.º 17
0
 /// <summary>
 /// Constructor for<see cref="ODataMediaTypeFormat"/>
 /// </summary>
 /// <param name="mediaType">MediaType to be used.</param>
 /// <param name="format">Associated format.</param>
 public ODataMediaTypeFormat(ODataMediaType mediaType, ODataFormat format)
 {
     this.MediaType = mediaType;
     this.Format    = format;
 }
Exemplo n.º 18
0
        /// <summary>
        /// Configure the media type tables so that Json Light is the first JSON format in the table.
        /// </summary>
        /// <remarks>
        /// This is only used in V4 and beyond.
        /// </remarks>
        private void AddJsonLightMediaTypes()
        {
            var optionalParameters = new[]
            {
                new
                {
                    ParameterName = MimeConstants.MimeMetadataParameterName,
                    Values = new[] { MimeConstants.MimeMetadataParameterValueMinimal, MimeConstants.MimeMetadataParameterValueFull, MimeConstants.MimeMetadataParameterValueNone }
                },
                new
                {
                    ParameterName = MimeConstants.MimeStreamingParameterName,
                    Values = new[] { MimeConstants.MimeParameterValueTrue, MimeConstants.MimeParameterValueFalse }
                },
                new
                {
                    ParameterName = MimeConstants.MimeIeee754CompatibleParameterName,
                    Values = new[] { MimeConstants.MimeParameterValueFalse, MimeConstants.MimeParameterValueTrue }
                },
            };

            // initial seed for the list will be extended in breadth-first passes over the optional parameters
            var mediaTypesToAdd = new LinkedList<ODataMediaType>();
            mediaTypesToAdd.AddFirst(ApplicationJsonMediaType);

            foreach (var optionalParameter in optionalParameters)
            {
                // go through each one so far and extend it
                for (LinkedListNode<ODataMediaType> currentNode = mediaTypesToAdd.First; currentNode != null; currentNode = currentNode.Next)
                {
                    ODataMediaType typeToExtend = currentNode.Value;
                    foreach (string valueToAdd in optionalParameter.Values)
                    {
                        var extendedParameters = new List<KeyValuePair<string, string>>(typeToExtend.Parameters ?? Enumerable.Empty<KeyValuePair<string, string>>())
                        {
                            new KeyValuePair<string, string>(optionalParameter.ParameterName, valueToAdd)
                        };

                        var extendedMediaType = new ODataMediaType(typeToExtend.Type, typeToExtend.SubType, extendedParameters);

                        // always match more specific things first
                        mediaTypesToAdd.AddBefore(currentNode, extendedMediaType);
                    }
                }
            }

            List<ODataMediaTypeFormat> mediaTypeWithFormat = mediaTypesToAdd.Select(mediaType => new ODataMediaTypeFormat(mediaType, ODataFormat.Json)).ToList();

            foreach (ODataPayloadKind kind in JsonPayloadKinds)
            {
                this.mediaTypesForPayloadKind[(int)kind].InsertRange(0, mediaTypeWithFormat);
            }
        }
Exemplo n.º 19
0
        /// <summary>Builds a Content-Type header which includes media type and encoding information.</summary>
        /// <param name="mediaType">Media type to be used.</param>
        /// <param name="encoding">Encoding to be used in response, possibly null.</param>
        /// <returns>The value for the Content-Type header.</returns>
        internal static string BuildContentType(ODataMediaType mediaType, Encoding encoding)
        {
            Debug.Assert(mediaType != null, "mediaType != null");

            return mediaType.ToText(encoding);
        }
        private static ODataJsonLightOutputContext CreateJsonLightOutputContext(MemoryStream stream, bool writingResponse = true, IEdmModel userModel = null, Uri serviceDocumentUri = null)
        {
            ODataMessageWriterSettings settings = new ODataMessageWriterSettings { Version = ODataVersion.V4, AutoComputePayloadMetadataInJson = true, ShouldIncludeAnnotation = ODataUtils.CreateAnnotationFilter("*") };
            if (serviceDocumentUri != null)
            {
                settings.SetServiceDocumentUri(serviceDocumentUri);
            }

            ODataMediaType mediaType = new ODataMediaType("application", "json", new KeyValuePair<string, string>("odata.metadata", "full"));
            return new ODataJsonLightOutputContext(
                ODataFormat.Json,
                new NonDisposingStream(stream),
                mediaType,
                Encoding.UTF8,
                settings,
                writingResponse,
                /*synchronous*/ true,
                userModel ?? EdmCoreModel.Instance,
                /*urlResolver*/ null);
        }
        public void FlagsEnumAsOpenCollectionPropertyElement_StrAsValue_StrAsTypeName_FullMetadata()
        {
            Func<ODataEntry> entryClone = () => new ODataEntry
            {
                TypeName = "NS.MyEntityType",
                Properties = new[]
                {
                    new ODataProperty{Name = "FloatId", Value = new ODataPrimitiveValue(12.3D)},       
                    new ODataProperty{Name = "Color", Value = new ODataEnumValue(Color.Green.ToString())},
                    new ODataProperty
                    {
                        Name = "MyOpenCollectionType",
                        Value = new ODataCollectionValue { TypeName = "Collection(NS.ColorFlags)", Items = new[] {  new ODataEnumValue(Color.Red.ToString(),"NS.EnumUndefinedTypename"), new ODataEnumValue(Color.Green.ToString(),"NS.EnumUndefinedTypename")} }
                    }
                }
            };

            ODataMediaType mediaType = new ODataMediaType("application", "json", new KeyValuePair<string, string>(MimeConstants.MimeMetadataParameterName, MimeConstants.MimeMetadataParameterValueFull));

            // Model-request (request: forced MinimalMetadata)
            string expectedPayload = "{\"@odata.context\":\"http://odata.org/test/$metadata#MySet/$entity\",\"FloatId\":12.3,\"Color\":\"Green\",\"[email protected]\":\"#Collection(NS.ColorFlags)\",\"MyOpenCollectionType\":[\"Red\",\"Green\"]}";
            this.WriteMinimalRequestWithModelAndValidatePayload(mediaType: mediaType, nestedItemToWrite: new[] { entryClone() }, expectedPayload: expectedPayload);

            // Model-reseponse
            expectedPayload = "{\"@odata.context\":\"http://odata.org/test/$metadata#MySet/$entity\",\"@odata.type\":\"#NS.MyEntityType\",\"@odata.id\":\"MySet(12.3)\",\"@odata.editLink\":\"MySet(12.3)\",\"FloatId\":12.3,\"Color\":\"Green\",\"[email protected]\":\"#Collection(NS.ColorFlags)\",\"MyOpenCollectionType\":[\"Red\",\"Green\"]}";
            this.WriteResponseWithModelAndValidatePayload(mediaType: mediaType, nestedItemToWrite: new[] { entryClone() }, expectedPayload: expectedPayload);

            // NoModel-request (request: forced MinimalMetadata)
            expectedPayload = "{\"@odata.type\":\"#NS.MyEntityType\",\"FloatId\":12.3,\"Color\":\"Green\",\"[email protected]\":\"#Collection(NS.ColorFlags)\",\"MyOpenCollectionType\":[\"Red\",\"Green\"]}";
            this.WriteMinimalMetadataRequestWithoutModelAndValidatePayload(nestedItemToWrite: new[] { entryClone() }, expectedPayload: expectedPayload);

            // NoModel-response (using NoMetadata)
            expectedPayload = "{\"FloatId\":12.3,\"Color\":\"Green\",\"MyOpenCollectionType\":[\"Red\",\"Green\"]}";
            this.WriteNoMetadataResponseWithoutModelAndValidatePayload(nestedItemToWrite: new[] { entryClone() }, expectedPayload: expectedPayload);
        }
Exemplo n.º 22
0
        /// <summary>
        /// Append default values required by OData to specified HTTP header.
        /// 
        /// When header name is ODataConstants.ContentTypeHeader:
        ///     If header value is application/json, append the following default values:
        ///         odata.metadata=minimal
        ///         odata.streaming=true
        ///         IEEE754Compatible=false
        /// </summary>
        /// <param name="headerName">The name of the header to append default values.</param>
        /// <param name="headerValue">The original header value string.</param>
        /// <returns>The header value string with appended default values.</returns>
        public static string AppendDefaultHeaderValue(string headerName, string headerValue)
        {
            if (string.CompareOrdinal(headerName, ODataConstants.ContentTypeHeader) != 0)
            {
                return headerValue;
            }

            if (headerValue == null)
            {
                return null;
            }

            var mediaTypeList = HttpUtils.MediaTypesFromString(headerValue);
            var mediaType = mediaTypeList.Single().Key;
            var encoding = HttpUtils.GetEncodingFromCharsetName(mediaTypeList.Single().Value);

            if (string.CompareOrdinal(mediaType.FullTypeName, MimeConstants.MimeApplicationJson) != 0)
            {
                return headerValue;
            }

            var extendedParameters = new List<KeyValuePair<string, string>>();
            var extendedMediaType = new ODataMediaType(mediaType.Type, mediaType.SubType, extendedParameters);

            var hasMetadata = false;
            var hasStreaming = false;
            var hasIeee754Compatible = false;

            if (mediaType.Parameters != null)
            {
                foreach (var parameter in mediaType.Parameters)
                {
                    extendedParameters.Add(parameter);

                    if (string.CompareOrdinal(parameter.Key, MimeConstants.MimeMetadataParameterName) == 0)
                    {
                        hasMetadata = true;
                    }

                    if (string.CompareOrdinal(parameter.Key, MimeConstants.MimeStreamingParameterName) == 0)
                    {
                        hasStreaming = true;
                    }

                    if (string.CompareOrdinal(parameter.Key, MimeConstants.MimeIeee754CompatibleParameterName) == 0)
                    {
                        hasIeee754Compatible = true;
                    }
                }
            }

            if (!hasMetadata)
            {
                extendedParameters.Add(new KeyValuePair<string, string>(
                    MimeConstants.MimeMetadataParameterName,
                    MimeConstants.MimeMetadataParameterValueMinimal));
            }

            if (!hasStreaming)
            {
                extendedParameters.Add(new KeyValuePair<string, string>(
                    MimeConstants.MimeStreamingParameterName,
                    MimeConstants.MimeParameterValueTrue));
            }

            if (!hasIeee754Compatible)
            {
                extendedParameters.Add(new KeyValuePair<string, string>(
                    MimeConstants.MimeIeee754CompatibleParameterName,
                    MimeConstants.MimeParameterValueFalse));
            }

            return extendedMediaType.ToText(encoding);
        }
        public void FlagsEnumAsEntityProperty_EmptyStrAsValue_NullAsTypeName_MinimalMetadata()
        {
            Func<ODataEntry> entryClone = () => new ODataEntry
            {
                TypeName = "NS.MyEntityType",
                Properties = new[]
                        {
                            new ODataProperty
                            {
                                Name = "ColorFlags",
                                Value = new ODataEnumValue("")
                            }
                        }
            };
            ODataMediaType mediaType = new ODataMediaType("application", "json", new KeyValuePair<string, string>(MimeConstants.MimeMetadataParameterName, MimeConstants.MimeMetadataParameterValueMinimal));

            // Model-request (request: forced MinimalMetadata)
            string expectedPayload = "{\"@odata.context\":\"http://odata.org/test/$metadata#MySet/$entity\",\"ColorFlags\":\"\"}";
            this.WriteMinimalRequestWithModelAndValidatePayload(mediaType: mediaType, nestedItemToWrite: new[] { entryClone() }, expectedPayload: expectedPayload);

            // Model-reseponse
            expectedPayload = "{\"@odata.context\":\"http://odata.org/test/$metadata#MySet/$entity\",\"ColorFlags\":\"\"}";
            this.WriteResponseWithModelAndValidatePayload(mediaType: mediaType, nestedItemToWrite: new[] { entryClone() }, expectedPayload: expectedPayload);

            // NoModel-request (request: forced MinimalMetadata)
            expectedPayload = "{\"@odata.type\":\"#NS.MyEntityType\",\"ColorFlags\":\"\"}";
            this.WriteMinimalMetadataRequestWithoutModelAndValidatePayload(nestedItemToWrite: new[] { entryClone() }, expectedPayload: expectedPayload);

            // NoModel-response (using NoMetadata)
            expectedPayload = "{\"ColorFlags\":\"\"}";
            this.WriteNoMetadataResponseWithoutModelAndValidatePayload(nestedItemToWrite: new[] { entryClone() }, expectedPayload: expectedPayload);
        }
 private static ODataAtomOutputContext CreateAtomOutputContext(MemoryStream stream, ODataMediaType mediaType, bool writingResponse = true, IEdmModel userModel = null)
 {
     ODataMessageWriterSettings settings = new ODataMessageWriterSettings { Version = ODataVersion.V4, AutoComputePayloadMetadataInJson = true };
     settings.SetServiceDocumentUri(ServiceDocumentUri);
     return new ODataAtomOutputContext(
         ODataFormat.Atom,
         new NonDisposingStream(stream),
         Encoding.UTF8,
         settings,
         writingResponse,
         /*synchronous*/ true,
         userModel ?? EdmCoreModel.Instance,
         /*urlResolver*/ null);
 }
Exemplo n.º 25
0
        /// <summary>
        /// Detects the payload kind(s) from the message stream.
        /// </summary>
        /// <param name="contentType">The content type of the message.</param>
        /// <returns>An enumerable of zero, one or more payload kinds that were detected from looking at the payload in the message stream.</returns>
        private static IEnumerable<ODataPayloadKind> DetectPayloadKindImplementation(ODataMediaType contentType)
        {
            Debug.Assert(contentType != null, "contentType != null");

            if (HttpUtils.CompareMediaTypeNames(MimeConstants.MimeTextType, contentType.Type) &&
                HttpUtils.CompareMediaTypeNames(MimeConstants.MimeTextPlain, contentType.SubType))
            {
                return new ODataPayloadKind[] { ODataPayloadKind.Value };
            }

            return new ODataPayloadKind[] { ODataPayloadKind.BinaryValue };
        }