/// <summary>
 /// Constructor.
 /// </summary>
 /// <param name="format">The format for this output context.</param>
 /// <param name="messageStream">The message stream to write the payload to.</param>
 /// <param name="mediaType">The specific media type being written.</param>
 /// <param name="encoding">The encoding to use for the payload.</param>
 /// <param name="messageWriterSettings">Configuration settings of the OData writer.</param>
 /// <param name="writingResponse">true if writing a response message; otherwise false.</param>
 /// <param name="synchronous">true if the output should be written synchronously; false if it should be written asynchronously.</param>
 /// <param name="model">The model to use.</param>
 /// <param name="urlResolver">The optional URL resolver to perform custom URL resolution for URLs written to the payload.</param>
 internal ODataJsonLightOutputContext(ODataFormat format, Stream messageStream, ODataMediaType mediaType, Encoding encoding, ODataMessageWriterSettings messageWriterSettings, bool writingResponse, bool synchronous, IEdmModel model, IODataUrlResolver urlResolver)
     : base(format, messageStream, encoding, messageWriterSettings, writingResponse, synchronous, mediaType.HasIeee754CompatibleSetToTrue(), model, urlResolver)
 {
     Debug.Assert(messageStream != null, "messageStream != null");
     Debug.Assert(messageWriterSettings != null, "messageWriterSettings != null");
     Debug.Assert(mediaType != null, "mediaType != null");
     Uri metadataDocumentUri = messageWriterSettings.MetadataDocumentUri;
     this.metadataLevel = JsonLightMetadataLevel.Create(mediaType, metadataDocumentUri, model, writingResponse);
 }
 /// <summary>Constructor.</summary>
 /// <param name="format">The format for this input context.</param>
 /// <param name="messageStream">The stream to read data from.</param>
 /// <param name="contentType">The content type of the message to read.</param>
 /// <param name="encoding">The encoding to use to read the input.</param>
 /// <param name="messageReaderSettings">Configuration settings of the OData reader.</param>
 /// <param name="readingResponse">true if reading a response message; otherwise false.</param>
 /// <param name="synchronous">true if the input should be read synchronously; false if it should be read asynchronously.</param>
 /// <param name="model">The model to use.</param>
 /// <param name="urlResolver">The optional URL resolver to perform custom URL resolution for URLs read from the payload.</param>
 internal ODataJsonLightInputContext(
     ODataFormat format,
     Stream messageStream,
     ODataMediaType contentType,
     Encoding encoding,
     ODataMessageReaderSettings messageReaderSettings,
     bool readingResponse,
     bool synchronous,
     IEdmModel model,
     IODataUrlResolver urlResolver)
     : this(format, CreateTextReaderForMessageStreamConstructor(messageStream, encoding), contentType, messageReaderSettings, readingResponse, synchronous, model, urlResolver)
 {
 }
        /// <summary>
        /// Creates the appropriate metadata level based on the media type being written.
        /// </summary>
        /// <param name="mediaType">The full media type being written. This media type must have a type/subtype of "application/json".</param> 
        /// <param name="metadataDocumentUri">The metadata document uri from the writer settings.</param>
        /// <param name="model">The edm model.</param>
        /// <param name="writingResponse">true if we are writing a response, false otherwise.</param>
        /// <returns>The JSON Light metadata level being written.</returns>
        internal static JsonLightMetadataLevel Create(ODataMediaType mediaType, Uri metadataDocumentUri, IEdmModel model, bool writingResponse)
        {
            Debug.Assert(mediaType != null, "mediaType != null");

            Debug.Assert(
                string.Compare(mediaType.FullTypeName, MimeConstants.MimeApplicationJson, StringComparison.OrdinalIgnoreCase) == 0,
                "media type should be application/json at this point");

            if (writingResponse && mediaType.Parameters != null)
            {
                foreach (KeyValuePair<string, string> parameter in mediaType.Parameters)
                {
                    if (!HttpUtils.CompareMediaTypeParameterNames(parameter.Key, MimeConstants.MimeMetadataParameterName))
                    {
                        // Only look at the "odata" parameter.
                        continue;
                    }

                    if (string.Compare(parameter.Value, MimeConstants.MimeMetadataParameterValueMinimal, StringComparison.OrdinalIgnoreCase) == 0)
                    {
                        return new JsonMinimalMetadataLevel();
                    }

                    if (string.Compare(parameter.Value, MimeConstants.MimeMetadataParameterValueFull, StringComparison.OrdinalIgnoreCase) == 0)
                    {
                        return new JsonFullMetadataLevel(metadataDocumentUri, model);
                    }

                    if (string.Compare(parameter.Value, MimeConstants.MimeMetadataParameterValueNone, StringComparison.OrdinalIgnoreCase) == 0)
                    {
                        return new JsonNoMetadataLevel();
                    }

                    Debug.Assert(
                        string.Compare(parameter.Value, MimeConstants.MimeMetadataParameterValueVerbose, StringComparison.OrdinalIgnoreCase) != 0,
                        "media type should not indicate verbose json at this point.");
                }
            }

            // No "odata" media type parameter implies minimal metadata.
            return new JsonMinimalMetadataLevel();
        }
        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);
            }
        }
Example #5
0
 internal static bool MediaTypeContains(ODataMediaType mediaType, string parameterName)
 {
     return(mediaType.Parameters != null && mediaType.Parameters.Any(p => String.Compare(p.Key, parameterName, StringComparison.OrdinalIgnoreCase) == 0));
 }
Example #6
0
        internal ODataJsonLightInputContext(
            ODataFormat format,
            TextReader reader,
            ODataMediaType contentType,
            ODataMessageReaderSettings messageReaderSettings,
            bool readingResponse,
            bool synchronous,
            IEdmModel model,
            IODataUrlResolver urlResolver)
            : base(format, messageReaderSettings, readingResponse, synchronous, model, urlResolver)
        {
            Debug.Assert(reader != null, "reader != null");
            Debug.Assert(contentType != null, "contentType != null");

            try
            {
                ExceptionUtils.CheckArgumentNotNull(format, "format");
                ExceptionUtils.CheckArgumentNotNull(messageReaderSettings, "messageReaderSettings");
            }
            catch (ArgumentNullException)
            {
                // Dispose the message stream if we failed to create the input context.
                reader.Dispose();
                throw;
            }

            try
            {
                this.textReader = reader;

                if (contentType.HasStreamingSetToTrue())
                {
                    this.jsonReader = new BufferingJsonReader(
                        this.textReader,
                        JsonLightConstants.ODataErrorPropertyName,
                        messageReaderSettings.MessageQuotas.MaxNestingDepth,
                        ODataFormat.Json,
                        contentType.HasIeee754CompatibleSetToTrue());
                }
                else
                {
                    // If we have a non-streaming Json Light content type we need to use the re-ordering Json reader
                    this.jsonReader = new ReorderingJsonReader(this.textReader, messageReaderSettings.MessageQuotas.MaxNestingDepth, contentType.HasIeee754CompatibleSetToTrue());
                }
            }
            catch (Exception e)
            {
                // Dispose the message stream if we failed to create the input context.
                if (ExceptionUtils.IsCatchableExceptionType(e) && reader != null)
                {
                    reader.Dispose();
                }

                throw;
            }

            // dont know how to get MetadataDocumentUri uri here, messageReaderSettings do not have one
            // Uri metadataDocumentUri = messageReaderSettings..MetadataDocumentUri == null ? null : messageReaderSettings.MetadataDocumentUri.BaseUri;
            // the uri here is used here to create the FullMetadataLevel can pass null in
            this.metadataLevel = JsonLight.JsonLightMetadataLevel.Create(contentType, null, model, readingResponse);
        }
        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);
        }
 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);
 }
 public JsonLightMetadataLevelTests()
 {
     this.parameterList = new List<KeyValuePair<string, string>>();
     this.applicationJsonMediaType = new ODataMediaType("application", "json", this.parameterList);
 }
        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);
        }
 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 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);
 }
        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));
        }
        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);
        }
        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);
        }
        internal ODataJsonLightInputContext(
            ODataFormat format,
            TextReader reader,
            ODataMediaType contentType,
            ODataMessageReaderSettings messageReaderSettings,
            bool readingResponse,
            bool synchronous,
            IEdmModel model,
            IODataUrlResolver urlResolver)
            : base(format, messageReaderSettings, readingResponse, synchronous, model, urlResolver)
        {
            Debug.Assert(reader != null, "reader != null");
            Debug.Assert(contentType != null, "contentType != null");

            try
            {
                ExceptionUtils.CheckArgumentNotNull(format, "format");
                ExceptionUtils.CheckArgumentNotNull(messageReaderSettings, "messageReaderSettings");
            }
            catch (ArgumentNullException)
            {
                // Dispose the message stream if we failed to create the input context.
                reader.Dispose();
                throw;
            }

            try
            {
                this.textReader = reader;

                if (contentType.HasStreamingSetToTrue())
                {
                    this.jsonReader = new BufferingJsonReader(
                        this.textReader,
                        JsonLightConstants.ODataErrorPropertyName,
                        messageReaderSettings.MessageQuotas.MaxNestingDepth,
                        ODataFormat.Json,
                        contentType.HasIeee754CompatibleSetToTrue());
                }
                else
                {
                    // If we have a non-streaming Json Light content type we need to use the re-ordering Json reader
                    this.jsonReader = new ReorderingJsonReader(this.textReader, messageReaderSettings.MessageQuotas.MaxNestingDepth, contentType.HasIeee754CompatibleSetToTrue());
                }
            }
            catch (Exception e)
            {
                // Dispose the message stream if we failed to create the input context.
                if (ExceptionUtils.IsCatchableExceptionType(e) && reader != null)
                {
                    reader.Dispose();
                }

                throw;
            }

            // dont know how to get MetadataDocumentUri uri here, messageReaderSettings do not have one
            // Uri metadataDocumentUri = messageReaderSettings..MetadataDocumentUri == null ? null : messageReaderSettings.MetadataDocumentUri.BaseUri;
            // the uri here is used here to create the FullMetadataLevel can pass null in
            this.metadataLevel = JsonLight.JsonLightMetadataLevel.Create(contentType, null, model, readingResponse);
        }
 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);
 }
Example #18
0
 public JsonLightMetadataLevelTests()
 {
     this.parameterList            = new List <KeyValuePair <string, string> >();
     this.applicationJsonMediaType = new ODataMediaType("application", "json", this.parameterList);
 }
        /// <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>());
        }
        private static ODataJsonLightOutputContext CreateJsonLightOutputContext(MemoryStream stream, IEdmModel userModel, bool fullMetadata = false, ODataUri uri = null)
        {
            ODataMessageWriterSettings settings = new ODataMessageWriterSettings { Version = ODataVersion.V4, AutoComputePayloadMetadataInJson = true, ShouldIncludeAnnotation = ODataUtils.CreateAnnotationFilter("*") };
            settings.SetServiceDocumentUri(new Uri("http://host/service"));
            if (uri != null)
            {
                settings.ODataUri = uri;
            }

            IEnumerable<KeyValuePair<string, string>> parameters;
            if (fullMetadata)
            {
                parameters = new[] { new KeyValuePair<string, string>("odata.metadata", "full") };
            }
            else
            {
                parameters = new List<KeyValuePair<string, string>>();
            }

            ODataMediaType mediaType = new ODataMediaType("application", "json", parameters);
            return new ODataJsonLightOutputContext(
                ODataFormat.Json,
                new NonDisposingStream(stream),
                mediaType,
                Encoding.UTF8,
                settings,
                /*writingResponse*/ true,
                /*synchronous*/ true,
                userModel ?? EdmCoreModel.Instance,
                /*urlResolver*/ null);
        }
Example #21
0
        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));
        }
        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);
        }
        /// <summary>
        /// Convert to a literal value in JSON Light format.
        /// </summary>
        /// <param name="model">EDM Model to use for validation and type lookups.</param>
        /// <param name="writeAction">Delegate to use to actually write the value.</param>
        /// <returns>The literal value string.</returns>
        private static string ConverToJsonLightLiteral(IEdmModel model, Action<ODataOutputContext> writeAction)
        {
            using (MemoryStream stream = new MemoryStream())
            {
                ODataMessageWriterSettings messageWriterSettings = new ODataMessageWriterSettings()
                {
                    Version = ODataVersion.V4,
                    Indent = false
                };

                ODataMediaType mediaType = new ODataMediaType(MimeConstants.MimeApplicationType, MimeConstants.MimeJsonSubType);

                using (ODataJsonLightOutputContext jsonOutputContext = new ODataJsonLightOutputContext(ODataFormat.Json, stream, mediaType, Encoding.UTF8, messageWriterSettings, false, true, model, null))
                {
                    writeAction(jsonOutputContext);
                    stream.Position = 0;
                    return new StreamReader(stream).ReadToEnd();
                }
            }
        }