internal ODataMetadataOutputContext( ODataFormat format, Stream messageStream, Encoding encoding, ODataMessageWriterSettings messageWriterSettings, bool writingResponse, bool synchronous, IEdmModel model, IODataUrlResolver urlResolver) : base(format, messageWriterSettings, writingResponse, synchronous, model, urlResolver) { Debug.Assert(messageStream != null, "messageStream != null"); Debug.Assert(synchronous, "Metadata output context is only supported in synchronous operations."); try { this.messageOutputStream = messageStream; this.xmlWriter = ODataAtomWriterUtils.CreateXmlWriter(messageStream, messageWriterSettings, encoding); } catch (Exception e) { // Dispose the message stream if we failed to create the output context. if (ExceptionUtils.IsCatchableExceptionType(e) && messageStream != null) { messageStream.Dispose(); } throw; } }
private static string GetLiteralValue(object value, ODataFormat format, PayloadGeneratorSettings settings) { JsonPayloadGenerator generator; if (format == ODataFormat.Json) { generator = new JsonLightPayloadGenerator(settings); } else { Assert.Fail("Format not supported by UriOperationParameterGenerator."); return null; } var payloadBuilder = value as PayloadBuilder; if (payloadBuilder != null) { return generator.GenerateLiteral(payloadBuilder); } var collectionBuilder = value as CollectionPropertyPayloadBuilder; if (collectionBuilder != null) { return generator.GenerateLiteral(collectionBuilder); } // Use the key syntax since that will give us single quotes and other formatting that is not used for literals as property values return JsonPrimitiveTypesUtil.PrimitiveToKeyString(value, value.GetType()); }
/// <summary>Sets the acceptable media types and character sets from which the content type will be computed when writing the payload.</summary> /// <param name="acceptableMediaTypes">The acceptable media types used to determine the content type of the message. This is a comma separated list of content types as specified in RFC 2616, Section 14.1.</param> /// <param name="acceptableCharSets"> The acceptable charsets to use to determine the encoding of the message. This is a comma separated list of charsets as specified in RFC 2616, Section 14.2 </param> /// <remarks>Calling this method replaces any previously set content-type settings.</remarks> public void SetContentType(string acceptableMediaTypes, string acceptableCharSets) { this.acceptMediaTypes = acceptableMediaTypes; this.acceptCharSets = acceptableCharSets; this.format = null; this.useFormat = false; }
/// <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="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 ODataRawOutputContext( ODataFormat format, Stream messageStream, Encoding encoding, ODataMessageWriterSettings messageWriterSettings, bool writingResponse, bool synchronous, IEdmModel model, IODataUrlResolver urlResolver) : base(format, messageWriterSettings, writingResponse, synchronous, model, urlResolver) { Debug.Assert(messageStream != null, "messageStream != null"); try { this.messageOutputStream = messageStream; this.encoding = encoding; if (synchronous) { this.outputStream = messageStream; } else { this.asynchronousOutputStream = new AsyncBufferedStream(messageStream); this.outputStream = this.asynchronousOutputStream; } } catch { messageStream.Dispose(); throw; } }
/// <summary>Initializes a new instance of the <see cref="T:Microsoft.OData.Core.ODataMessageWriterSettings" /> class with specified settings.</summary> /// <param name="other">The specified settings.</param> public ODataMessageWriterSettings(ODataMessageWriterSettings other) : base(other) { ExceptionUtils.CheckArgumentNotNull(other, "other"); this.acceptCharSets = other.acceptCharSets; this.acceptMediaTypes = other.acceptMediaTypes; this.PayloadBaseUri = other.PayloadBaseUri; this.DisableMessageStreamDisposal = other.DisableMessageStreamDisposal; this.format = other.format; this.useFormat = other.useFormat; this.Version = other.Version; this.JsonPCallback = other.JsonPCallback; this.shouldIncludeAnnotation = other.shouldIncludeAnnotation; this.AutoComputePayloadMetadataInJson = other.AutoComputePayloadMetadataInJson; this.UseKeyAsSegment = other.UseKeyAsSegment; this.alwaysUseDefaultXmlNamespaceForRootElement = other.alwaysUseDefaultXmlNamespaceForRootElement; this.ODataUri = other.ODataUri; // NOTE: writer behavior is immutable; copy by reference is ok. this.writerBehavior = other.writerBehavior; this.EnableAtom = other.EnableAtom; this.EnableFullValidation = other.EnableFullValidation; this.mediaTypeResolver = other.mediaTypeResolver; this.ODataSimplified = other.ODataSimplified; }
/// <summary>Sets the format to be used when writing the payload. This will automatically set a compatible content type header.</summary> /// <param name="payloadFormat">The format to use for writing the payload.</param> /// <remarks>Calling this method replaces any previously set content-type settings.</remarks> public void SetContentType(ODataFormat payloadFormat) { this.acceptCharSets = null; this.acceptMediaTypes = null; this.format = payloadFormat; this.useFormat = true; }
internal ODataRawInputContext( ODataFormat format, Stream messageStream, Encoding encoding, ODataMessageReaderSettings messageReaderSettings, bool readingResponse, bool synchronous, IEdmModel model, IODataUrlResolver urlResolver, ODataPayloadKind readerPayloadKind) : base(format, messageReaderSettings, readingResponse, synchronous, model, urlResolver) { Debug.Assert(messageStream != null, "stream != null"); Debug.Assert(readerPayloadKind != ODataPayloadKind.Unsupported, "readerPayloadKind != ODataPayloadKind.Unsupported"); ExceptionUtils.CheckArgumentNotNull(format, "format"); ExceptionUtils.CheckArgumentNotNull(messageReaderSettings, "messageReaderSettings"); try { this.stream = messageStream; this.encoding = encoding; this.readerPayloadKind = readerPayloadKind; } catch (Exception e) { // Dispose the message stream if we failed to create the input context. if (ExceptionUtils.IsCatchableExceptionType(e) && messageStream != null) { messageStream.Dispose(); } throw; } }
/// <summary> /// Constructor. /// </summary> /// <param name="format">The format used for the test.</param> /// <param name="messageWriterSettings">The message writer settings used for the test.</param> /// <param name="IsRequest">True if the test is writing a request. Otherwise false if it's writing a response.</param> /// <param name="synchronous">True if the test should be ran using synchronous API. Otherwise false if it should be ran using asynchronous APIs.</param> public WriterTestConfiguration(ODataFormat format, ODataMessageWriterSettings messageWriterSettings, bool IsRequest, bool synchronous) : base(format, messageWriterSettings.Version.Value, IsRequest, TestODataBehaviorKind.Default) { Debug.Assert(messageWriterSettings != null, "messageWriterSettings != null"); this.Synchronous = synchronous; this.MessageWriterSettings = messageWriterSettings; }
/// <summary> /// Constructor. /// </summary> /// <param name="format">The format used for the test.</param> /// <param name="version">The OData protocol version to be used for the payload.</param> /// <param name="request">True if the test is reading a request. Otherwise false if it's reading a response.</param> public TestConfiguration(ODataFormat format, ODataVersion version, bool request, TestODataBehaviorKind behaviorKind) { this.Format = format; this.Version = version; this.IsRequest = request; this.RunBehaviorKind = behaviorKind; }
/// <summary>Sets the acceptable media types and character sets from which the content type will be computed when writing the payload.</summary> /// <param name="acceptableMediaTypes">The acceptable media types used to determine the content type of the message. This is a comma separated list of content types as specified in RFC 2616, Section 14.1.</param> /// <param name="acceptableCharSets"> The acceptable charsets to use to determine the encoding of the message. This is a comma separated list of charsets as specified in RFC 2616, Section 14.2 </param> /// <remarks>Calling this method replaces any previously set content-type settings.</remarks> public void SetContentType(string acceptableMediaTypes, string acceptableCharSets) { // Should accept json as application/json this.acceptMediaTypes = string.Equals(acceptableMediaTypes, MimeConstants.MimeJsonSubType, StringComparison.OrdinalIgnoreCase) ? MimeConstants.MimeApplicationJson : acceptableMediaTypes; this.acceptCharSets = acceptableCharSets; this.format = null; this.useFormat = false; }
/// <summary> /// Constructor. /// </summary> /// <param name="format">The format used for the test.</param> /// <param name="messageReaderSettings">The message reader settings used for the test.</param> /// <param name="readerRequest">True if the test is reading a request. Otherwise false if it's reading a response.</param> /// <param name="synchronous">True if the test should be ran using synchronous API. Otherwise false if it should be ran using asynchronous APIs.</param> /// <param name="version">The OData protocol version to be used for reading the payload.</param> public ReaderTestConfiguration(ODataFormat format, ODataMessageReaderSettings messageReaderSettings, bool IsRequest, bool synchronous,ODataVersion version = ODataVersion.V4) :base(format, version, IsRequest, TestODataBehaviorKind.Default) { Debug.Assert(messageReaderSettings != null, "readerSettings != null"); this.MessageReaderSettings = messageReaderSettings; this.Synchronous = synchronous; }
/// <summary> /// Creates a new instance of MaterializerEntry using the given entity descriptor for LoadProperty. /// </summary> /// <param name="entityDescriptor">Entity descriptor.</param> /// <param name="format">OData Format.</param> /// <param name="isTracking">Whether this entity is being tracked.</param> /// <remarks>Use this constructor only for LoadProperty scenario.</remarks> private MaterializerEntry(EntityDescriptor entityDescriptor, ODataFormat format, bool isTracking) { this.entityDescriptor = entityDescriptor; this.Format = format; #pragma warning disable 618 this.isAtomOrTracking = isTracking || this.Format == ODataFormat.Atom; #pragma warning restore 618 this.SetFlagValue(EntryFlags.ShouldUpdateFromPayload | EntryFlags.EntityHasBeenResolved | EntryFlags.ForLoadProperty, true); }
/// <summary> /// Initializes a new instance of the <see cref="ODataFormatWithParameters"/> class. /// </summary> /// <param name="format">The format to extend.</param> internal ODataFormatWithParameters(ODataFormat format) { Debug.Assert(format != null, "format != null"); this.Format = format; #pragma warning disable 618 this.IsAtom = this.Format == ODataFormat.Atom; #pragma warning restore 618 this.IsJsonLight = this.Format == ODataFormat.Json; }
/// <summary> /// Initializes a new instance of the <see cref="FeedAndEntryMaterializerAdapter"/> class. Used for tests so no ODataMessageReader is required /// </summary> /// <param name="odataFormat">The format of the reader.</param> /// <param name="reader">The reader.</param> /// <param name="model">The model.</param> /// <param name="mergeOption">The mergeOption.</param> internal FeedAndEntryMaterializerAdapter(ODataFormat odataFormat, ODataReaderWrapper reader, ClientEdmModel model, MergeOption mergeOption) { this.readODataFormat = odataFormat; this.clientEdmModel = model; this.mergeOption = mergeOption; this.reader = reader; this.currentEntry = null; this.currentFeed = null; this.feedEntries = null; }
public CsvOutputContext( ODataFormat format, ODataMessageWriterSettings settings, ODataMessageInfo messageInfo, bool synchronous) : base(format, settings, messageInfo.IsResponse, synchronous, messageInfo.Model, messageInfo.UrlResolver) { this.stream = messageInfo.GetMessageStream(); this.Writer = new StreamWriter(this.stream); }
private ODataEntry CreateEntryWithMaterializerEntry(ODataFormat format, object resolvedObject) { var entry = new ODataEntry(); entry.Id = new Uri("http://www.odata.org/Northwind.Svc/Customer(1)"); entry.Properties = new ODataProperty[] { new ODataProperty() { Name = "ID", Value = 1 } }; var materializerEntry = MaterializerEntry.CreateEntry(entry, format, true, this.clientModel); materializerEntry.ResolvedObject = resolvedObject; return entry; }
/// <summary> /// Initializes a new instance of the <see cref="ODataEntriesEntityMaterializer" /> class. /// </summary> /// <param name="entries">The entries.</param> /// <param name="materializerContext">The materializer context.</param> /// <param name="entityTrackingAdapter">The entity tracking adapter.</param> /// <param name="queryComponents">The query components.</param> /// <param name="expectedType">The expected type.</param> /// <param name="materializeEntryPlan">The materialize entry plan.</param> /// <param name="format">The format.</param> public ODataEntriesEntityMaterializer( IEnumerable<ODataEntry> entries, IODataMaterializerContext materializerContext, EntityTrackingAdapter entityTrackingAdapter, QueryComponents queryComponents, Type expectedType, ProjectionPlan materializeEntryPlan, ODataFormat format) : base(materializerContext, entityTrackingAdapter, queryComponents, expectedType, materializeEntryPlan) { this.format = format; this.feedEntries = entries.GetEnumerator(); }
/// <summary>Initializes a new EntitySerializer instance.</summary> /// <param name="requestDescription">Request description.</param> /// <param name="absoluteServiceUri">Absolute URI to the service entry point.</param> /// <param name="service">Service with configuration and provider from which metadata should be gathered.</param> /// <param name="httpETagHeaderValue">HTTP ETag header value.</param> /// <param name="messageWriter">ODataMessageWriter instance which needs to be used to write the response.</param> /// <param name="contentFormat">The content format.</param> internal EntitySerializer( RequestDescription requestDescription, Uri absoluteServiceUri, IDataService service, string httpETagHeaderValue, ODataMessageWriter messageWriter, ODataFormat contentFormat) : base(requestDescription, absoluteServiceUri, service, httpETagHeaderValue) { Debug.Assert(service != null, "service != null"); this.messageWriter = messageWriter; this.contentFormat = contentFormat; }
internal ODataAvroOutputContext( ODataFormat format, Stream messageStream, Encoding encoding, ODataMessageWriterSettings messageWriterSettings, bool writingResponse, bool synchronous, IEdmModel model, IODataUrlResolver urlResolver) : base(format, messageWriterSettings, writingResponse, synchronous, model, urlResolver) { this.outputStream = messageStream; this.AvroWriter = new AvroWriter(new StreamWrapper(outputStream)); }
internal VCardOutputContext( ODataFormat format, Stream messageStream, Encoding encoding, ODataMessageWriterSettings messageWriterSettings, bool writingResponse, bool synchronous, IEdmModel model, IODataUrlResolver urlResolver) : base(format, messageWriterSettings, writingResponse, synchronous, model, urlResolver) { this.writer = new VCardWriter(new StreamWriter(messageStream, new UTF8Encoding(false))); this.outputStream = messageStream; }
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; }
/// <summary> /// Fixes up payload based on format /// </summary> /// <param name="payloadElement">The payload element to fix.</param> /// <param name="format">The format to fix up for.</param> public string Fixup(ODataPayloadElement payload, ODataFormat format) { if (format == ODataFormat.Json) { return this.JsonFixup(payload); } else if (format == ODataFormat.Atom) { return this.AtomFixup(payload); } else if (format == null && (payload is BatchRequestPayload || payload is BatchResponsePayload)) { return this.DefaultFixup(payload); } return MimeTypes.ApplicationXml; }
/// <summary> /// Initializes a new instance of the <see cref="PayloadMetadataParameterInterpreter"/> class. /// NOTE: This constructor is for unit-testing only. /// </summary> /// <param name="format">The response format.</param> /// <param name="rawParameterValue">The parameter value.</param> internal PayloadMetadataParameterInterpreter(ODataFormat format, string rawParameterValue) { this.isJsonLight = format == ODataFormat.Json; // NOTE: we explicitly allow the format passed in to be null, because it implies that no response payload // can possibly be written. In this case, it is treated exactly the same as any other non-json-light format. if (this.isJsonLight) { this.metadataParameterValue = ParseMetadataParameterForJsonLight(rawParameterValue); this.metadataParameterValueForTypeNames = this.metadataParameterValue; } else { Debug.Assert(rawParameterValue == null || rawParameterValue == "verbose", "Only JSON-Light allows the the amount of metadata to be controlled."); this.metadataParameterValue = MetadataParameterValue.Full; this.metadataParameterValueForTypeNames = MetadataParameterValue.Minimal; } }
/// <summary> /// Constructor. /// </summary> /// <param name="format">The format for this output context.</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> protected ODataOutputContext( ODataFormat format, ODataMessageWriterSettings messageWriterSettings, bool writingResponse, bool synchronous, IEdmModel model, IODataUrlResolver urlResolver) { ExceptionUtils.CheckArgumentNotNull(format, "format"); ExceptionUtils.CheckArgumentNotNull(messageWriterSettings, "messageWriterSettings"); this.format = format; this.messageWriterSettings = messageWriterSettings; this.writingResponse = writingResponse; this.synchronous = synchronous; this.model = model ?? EdmCoreModel.Instance; this.urlResolver = urlResolver; this.edmTypeResolver = EdmTypeWriterResolver.Instance; }
/// <summary> /// Constructor. /// </summary> /// <param name="format">The format for this input context.</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> protected ODataInputContext( ODataFormat format, ODataMessageReaderSettings messageReaderSettings, bool readingResponse, bool synchronous, IEdmModel model, IODataUrlResolver urlResolver) { ExceptionUtils.CheckArgumentNotNull(format, "format"); ExceptionUtils.CheckArgumentNotNull(messageReaderSettings, "messageReaderSettings"); this.format = format; this.messageReaderSettings = messageReaderSettings; this.readingResponse = readingResponse; this.synchronous = synchronous; this.model = model; this.urlResolver = urlResolver; this.edmTypeResolver = new EdmTypeReaderResolver(this.Model, this.MessageReaderSettings.ReaderBehavior); }
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)); }
/// <summary> /// Initializes a new instance of the <see cref="OperationSerializer"/> class. /// </summary> /// <param name="payloadMetadataParameterInterpreter">The metadata query option interpreter </param> /// <param name="metadataPropertyManager">The metadata property manager.</param> /// <param name="advertiseServiceAction">The callback to use for determining whether an action should be advertised. Should wrap a call to IDataServiceActionProvider.AdvertiseServiceAction.</param> /// <param name="namespaceName">Namespace of the operation.</param> /// <param name="format">The current format being serialized into.</param> /// <param name="metadataUri">The metadata uri of the service.</param> internal OperationSerializer( PayloadMetadataParameterInterpreter payloadMetadataParameterInterpreter, PayloadMetadataPropertyManager metadataPropertyManager, AdvertiseServiceActionCallback advertiseServiceAction, string namespaceName, ODataFormat format, Uri metadataUri) { Debug.Assert(metadataPropertyManager != null, "metadataPropertyManager != null"); Debug.Assert(payloadMetadataParameterInterpreter != null, "payloadMetadataParameterInterpreter != null"); Debug.Assert(advertiseServiceAction != null, "advertiseServiceAction != null"); this.payloadMetadataParameterInterpreter = payloadMetadataParameterInterpreter; this.metadataPropertyManager = metadataPropertyManager; this.operationLinkBuilder = new OperationLinkBuilder(namespaceName, metadataUri); this.format = format; this.metadataUri = metadataUri; this.advertiseServiceAction = advertiseServiceAction; }
/// <summary> /// Constructor. /// </summary> /// <param name="format">The format for this output context.</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> protected ODataOutputContext( ODataFormat format, ODataMessageWriterSettings messageWriterSettings, bool writingResponse, bool synchronous, IEdmModel model, IODataUrlResolver urlResolver) { ExceptionUtils.CheckArgumentNotNull(format, "format"); ExceptionUtils.CheckArgumentNotNull(messageWriterSettings, "messageWriterSettings"); this.format = format; this.messageWriterSettings = messageWriterSettings; this.writingResponse = writingResponse; this.synchronous = synchronous; this.model = model ?? EdmCoreModel.Instance; this.urlResolver = urlResolver; this.edmTypeResolver = EdmTypeWriterResolver.Instance; this.payloadValueConverter = this.model.GetPayloadValueConverter(); this.writerValidator = ValidatorFactory.CreateWriterValidator(messageWriterSettings.EnableFullValidation); }
internal ODataMetadataInputContext( ODataFormat format, Stream messageStream, Encoding encoding, ODataMessageReaderSettings messageReaderSettings, bool readingResponse, bool synchronous, IEdmModel model, IODataUrlResolver urlResolver) : base(format, messageReaderSettings, readingResponse, synchronous, model, urlResolver) { Debug.Assert(messageStream != null, "stream != null"); ExceptionUtils.CheckArgumentNotNull(format, "format"); ExceptionUtils.CheckArgumentNotNull(messageReaderSettings, "messageReaderSettings"); try { // Which encoding do we use when reading XML payloads this.baseXmlReader = ODataAtomReaderUtils.CreateXmlReader(messageStream, encoding, messageReaderSettings); // We use the buffering reader here only for in-stream error detection (not for buffering). this.xmlReader = new BufferingXmlReader( this.baseXmlReader, /*parentXmlReader*/ null, messageReaderSettings.BaseUri, /*disableXmlBase*/ false, messageReaderSettings.MessageQuotas.MaxNestingDepth); } catch (Exception e) { // Dispose the message stream if we failed to create the input context. if (ExceptionUtils.IsCatchableExceptionType(e) && messageStream != null) { messageStream.Dispose(); } throw; } }
/// <summary> /// Converts a spatial value into a string representation suitable for the specified format. If specified, injects a type name into the JSON format(s). /// </summary> /// <param name="format">The format to create the spatial value string representation for.</param> /// <param name="spatial">The spatial value.</param> /// <param name="typeName">The (optional) type name to inject into a JSON string representation.</param> /// <returns>The string representation of the spatial value in the specified format.</returns> /// <remarks>When using a type name with the JSON Light format, the resulting string representation will be invalid /// (since the odata.type annotation is not supported inside of spatial values); only used for error tests.</remarks> public static string GetSpatialStringValue(ODataFormat format, ISpatial spatial, string typeName = null) { if (format == ODataFormat.Atom) { return GmlFormatter.Create().Write(spatial); } IDictionary<string, object> dictionary = GeoJsonObjectFormatter.Create().Write(spatial); var converter = new DictionaryToJsonObjectConverter(); ExceptionUtilities.CheckAllRequiredDependencies(converter); var jsonObject = converter.Convert(dictionary); if (typeName != null) { // NOTE: using a type name with the JSON Light format will produce invalid payloads and is only used // for error tests. jsonObject.Insert(0, new JsonProperty(JsonLightConstants.ODataPropertyAnnotationSeparator + JsonLightConstants.ODataTypeAnnotationName, new JsonPrimitiveValue(typeName))); } return jsonObject.ToText(format == ODataFormat.Json, indent:false); }
internal static string Generate(OperationUriBuilder operationUriBuilder, ODataFormat format, PayloadGeneratorSettings settings) { var uriStringBuilder = new StringBuilder(); bool first = true; foreach (var parameter in operationUriBuilder.Parameters) { if (!first) { uriStringBuilder.Append(","); } string literalValue = GetLiteralValue(parameter.Value, format, settings); if (parameter.EscapeGeneratedValue) { literalValue = Uri.EscapeDataString(literalValue); } uriStringBuilder.Append(string.Format("{0}={1}", parameter.Name, literalValue)); first = false; } return uriStringBuilder.ToString(); }
protected void WriteAnnotationsAndValidatePayload(Action<ODataWriter> action, ODataFormat format, string expectedPayload, bool request, bool createFeedWriter) { var writerSettings = new ODataMessageWriterSettings { DisableMessageStreamDisposal = true, EnableAtom = true }; writerSettings.SetContentType(format); writerSettings.SetServiceDocumentUri(new Uri("http://www.example.com/")); MemoryStream stream = new MemoryStream(); if (request) { IODataRequestMessage requestMessageToWrite = new InMemoryMessage { Method = "GET", Stream = stream }; using (var messageWriter = new ODataMessageWriter(requestMessageToWrite, writerSettings, Model)) { ODataWriter odataWriter = createFeedWriter ? messageWriter.CreateODataFeedWriter(EntitySet, EntityType) : messageWriter.CreateODataEntryWriter(EntitySet, EntityType); action(odataWriter); } } else { IODataResponseMessage responseMessageToWrite = new InMemoryMessage { StatusCode = 200, Stream = stream }; using (var messageWriter = new ODataMessageWriter(responseMessageToWrite, writerSettings, Model)) { ODataWriter odataWriter = createFeedWriter ? messageWriter.CreateODataFeedWriter(EntitySet, EntityType) : messageWriter.CreateODataEntryWriter(EntitySet, EntityType); action(odataWriter); } } stream.Position = 0; string payload = (new StreamReader(stream)).ReadToEnd(); if (format == ODataFormat.Atom) { // The <updated> element is computed dynamically, so we remove it from the both the baseline and the actual payload. payload = Regex.Replace(payload, "<updated>[^<]*</updated>", ""); expectedPayload = Regex.Replace(expectedPayload, "<updated>[^<]*</updated>", ""); } Assert.AreEqual(expectedPayload, payload); }
/// <summary> /// Creates a new instance of MaterializerEntry. /// </summary> /// <param name="entry">The entry.</param> /// <param name="format">The format the entry was read in.</param> /// <param name="isTracking">True if the contents of the entry will be tracked in the context, otherwise False.</param> /// <param name="model">The client model.</param> private MaterializerEntry(ODataEntry entry, ODataFormat format, bool isTracking, ClientEdmModel model) { Debug.Assert(entry != null, "entry != null"); this.entry = entry; this.Format = format; this.entityDescriptor = new EntityDescriptor(model); #pragma warning disable 618 this.isAtomOrTracking = isTracking || this.Format == ODataFormat.Atom; #pragma warning restore 618 string serverTypeName = this.Entry.TypeName; SerializationTypeNameAnnotation serializationTypeNameAnnotation = entry.GetAnnotation<SerializationTypeNameAnnotation>(); if (serializationTypeNameAnnotation != null) { // If the annotation has a value use it. Otherwise, in JSON-Light, the types can be inferred from the // context URI even if they are not present on the wire, so just use the type name from the entry. if (serializationTypeNameAnnotation.TypeName != null || this.Format != ODataFormat.Json) { serverTypeName = serializationTypeNameAnnotation.TypeName; } } this.entityDescriptor.ServerTypeName = serverTypeName; }
internal ODataRawInputContext( ODataFormat format, Stream messageStream, Encoding encoding, ODataMessageReaderSettings messageReaderSettings, ODataVersion version, bool readingResponse, bool synchronous, IEdmModel model, IODataUrlResolver urlResolver, ODataPayloadKind readerPayloadKind) : base(format, messageReaderSettings, version, readingResponse, synchronous, model, urlResolver) { Debug.Assert(messageStream != null, "stream != null"); Debug.Assert(readerPayloadKind != ODataPayloadKind.Unsupported, "readerPayloadKind != ODataPayloadKind.Unsupported"); ExceptionUtils.CheckArgumentNotNull(format, "format"); ExceptionUtils.CheckArgumentNotNull(messageReaderSettings, "messageReaderSettings"); try { this.stream = messageStream; this.encoding = encoding; this.readerPayloadKind = readerPayloadKind; } catch (Exception e) { // Dispose the message stream if we failed to create the input context. if (ExceptionUtils.IsCatchableExceptionType(e) && messageStream != null) { messageStream.Dispose(); } throw; } }
/// <summary> /// Constructor. /// </summary> /// <param name="format">The format used for the test.</param> /// <param name="version">The OData protocol version to be used for the payload.</param> /// <param name="request">True if the test is reading a request. Otherwise false if it's reading a response.</param> public TestConfiguration(ODataFormat format, bool request) { this.Format = format; this.Version = ODataVersion.V4; this.IsRequest = request; }
internal static void ValidateServiceDocumentElement(ODataServiceDocumentElement serviceDocumentElement, ODataFormat format) { if (serviceDocumentElement == null) { throw new ODataException(Strings.ValidationUtils_WorkspaceResourceMustNotContainNullItem); } // The resource collection URL must not be null; if (serviceDocumentElement.Url == null) { throw new ODataException(Strings.ValidationUtils_ResourceMustSpecifyUrl); } if (format == ODataFormat.Json && string.IsNullOrEmpty(serviceDocumentElement.Name)) { throw new ODataException(Strings.ValidationUtils_ResourceMustSpecifyName(serviceDocumentElement.Url.ToString())); } }
/// <summary> /// Validates a element in service document. /// </summary> /// <param name="serviceDocumentElement">The element in service document to validate.</param> /// <param name="format">Format that is being validated.</param> public void ValidateServiceDocumentElement(ODataServiceDocumentElement serviceDocumentElement, ODataFormat format) { }
/// <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; }
/// <summary> /// Validates a element in service document. /// </summary> /// <param name="serviceDocumentElement">The element in service document to validate.</param> /// <param name="format">Format that is being validated.</param> public void ValidateServiceDocumentElement(ODataServiceDocumentElement serviceDocumentElement, ODataFormat format) { ValidationUtils.ValidateServiceDocumentElement(serviceDocumentElement, format); }
/// <summary> /// Inserts the specified media type before the first occurrence of <paramref name="beforeFormat"/>. /// </summary> /// <param name="mediaTypeList">The media type list to insert into.</param> /// <param name="mediaTypeToInsert">The media type to insert.</param> /// <param name="beforeFormat">The format of the media type before which <paramref name="mediaTypeToInsert"/> should be inserted.</param> private static void AddMediaTypeEntryOrdered(IList <MediaTypeWithFormat> mediaTypeList, MediaTypeWithFormat mediaTypeToInsert, ODataFormat beforeFormat) { Debug.Assert(mediaTypeList != null, "mediaTypeList != null"); Debug.Assert(mediaTypeToInsert != null, "mediaTypeToInsert != null"); Debug.Assert(beforeFormat != null, "beforeFormat != null"); // Go through the list and find the first entry that has the specified format to insert before. for (int i = 0; i < mediaTypeList.Count; ++i) { if (mediaTypeList[i].Format == beforeFormat) { mediaTypeList.Insert(i, mediaTypeToInsert); return; } } mediaTypeList.Add(mediaTypeToInsert); }