/// <summary> /// Writes a single OData batch response. /// </summary> /// <param name="writer">The <see cref="ODataBatchWriter"/>.</param> /// <param name="response">The response message.</param> /// <param name="cancellationToken">The token to monitor for cancellation requests.</param> /// <returns>A task object representing writing the given batch response using the given writer.</returns> public static async Task WriteMessageAsync(ODataBatchWriter writer, HttpResponseMessage response, CancellationToken cancellationToken) { if (writer == null) { throw Error.ArgumentNull("writer"); } if (response == null) { throw Error.ArgumentNull("response"); } ODataBatchOperationResponseMessage batchResponse = writer.CreateOperationResponseMessage(); batchResponse.StatusCode = (int)response.StatusCode; foreach (KeyValuePair <string, IEnumerable <string> > header in response.Headers) { batchResponse.SetHeader(header.Key, String.Join(",", header.Value)); } if (response.Content != null) { foreach (KeyValuePair <string, IEnumerable <string> > header in response.Content.Headers) { batchResponse.SetHeader(header.Key, String.Join(",", header.Value)); } using (Stream stream = batchResponse.GetStream()) { cancellationToken.ThrowIfCancellationRequested(); await response.Content.CopyToAsync(stream); } } }
private async Task WriteOperation(ODataBatchWriter writer, OeOperationMessage operation) { ODataBatchOperationResponseMessage operationMessage = await writer.CreateOperationResponseMessageAsync(operation.ContentId); operationMessage.SetHeader("Location", operation.RequestUrl.AbsoluteUri); operationMessage.SetHeader(ODataConstants.ContentTypeHeader, operation.ContentType); operationMessage.StatusCode = (int)operation.StatusCode; if (operation.StatusCode != HttpStatusCode.NoContent) { using (Stream stream = await operationMessage.GetStreamAsync()) await WriteEntity(operation.EntitySet, operation.Entry, stream); } }
private void WriteOperation(ODataBatchWriter writer, OeOperationMessage operation) { ODataBatchOperationResponseMessage operationMessage = writer.CreateOperationResponseMessage(operation.ContentId); operationMessage.SetHeader("Location", operation.RequestUrl.AbsoluteUri); operationMessage.SetHeader(ODataConstants.ContentTypeHeader, operation.ContentType); operationMessage.StatusCode = (int)operation.StatusCode; if (operation.StatusCode != HttpStatusCode.NoContent) { using (Stream stream = operationMessage.GetStream()) WriteEntity(stream, operation.EntityItem); } }
/// <summary> /// Writes a single OData batch response. /// </summary> /// <param name="writer">The <see cref="ODataBatchWriter"/>.</param> /// <param name="context">The message context.</param> public static async Task WriteMessageAsync(ODataBatchWriter writer, HttpContext context) { if (writer == null) { throw Error.ArgumentNull("writer"); } if (context == null) { throw Error.ArgumentNull("context"); } string contentId = (context.Request != null) ? context.Request.GetODataContentId() : String.Empty; ODataBatchOperationResponseMessage batchResponse = writer.CreateOperationResponseMessage(contentId); batchResponse.StatusCode = context.Response.StatusCode; foreach (KeyValuePair <string, StringValues> header in context.Response.Headers) { batchResponse.SetHeader(header.Key, String.Join(",", header.Value.ToArray())); } if (context.Response.Body != null && context.Response.Body.Length != 0) { using (Stream stream = batchResponse.GetStream()) { context.RequestAborted.ThrowIfCancellationRequested(); context.Response.Body.Seek(0L, SeekOrigin.Begin); await context.Response.Body.CopyToAsync(stream); } } }
internal static void SetResponseHeadersForBatchRequests(ODataBatchOperationResponseMessage operationResponseMessage, BatchServiceHost batchHost) { IDataServiceHost2 host = batchHost; operationResponseMessage.StatusCode = host.ResponseStatusCode; if (batchHost.ContentId != null) { operationResponseMessage.SetHeader("Content-ID", batchHost.ContentId); } WebHeaderCollection responseHeaders = host.ResponseHeaders; foreach (string str in responseHeaders.AllKeys) { string str2 = responseHeaders[str]; if (!string.IsNullOrEmpty(str2)) { operationResponseMessage.SetHeader(str, str2); } } }
/// <summary> /// Writes a single OData batch response. /// </summary> /// <param name="writer">The <see cref="ODataBatchWriter"/>.</param> /// <param name="context">The message context.</param> /// <param name="asyncWriter">Whether or not the writer is in async mode. </param> public static async Task WriteMessageAsync(ODataBatchWriter writer, HttpContext context, bool asyncWriter) { if (writer == null) { throw Error.ArgumentNull("writer"); } if (context == null) { throw Error.ArgumentNull("context"); } string contentId = (context.Request != null) ? context.Request.GetODataContentId() : String.Empty; ODataBatchOperationResponseMessage batchResponse = asyncWriter ? await writer.CreateOperationResponseMessageAsync(contentId) : writer.CreateOperationResponseMessage(contentId); batchResponse.StatusCode = context.Response.StatusCode; foreach (KeyValuePair <string, StringValues> header in context.Response.Headers) { batchResponse.SetHeader(header.Key, String.Join(",", header.Value.ToArray())); } if (context.Response.Body != null && context.Response.Body.Length != 0) { using (Stream stream = asyncWriter ? await batchResponse.GetStreamAsync() : batchResponse.GetStream()) { context.RequestAborted.ThrowIfCancellationRequested(); context.Response.Body.Seek(0L, SeekOrigin.Begin); await context.Response.Body.CopyToAsync(stream); // Close and release the stream for the individual response ODataBatchStream batchStream = context.Response.Body as ODataBatchStream; if (batchStream != null) { if (asyncWriter) { await batchStream.InternalDisposeAsync(); } else { batchStream.InternalDispose(); } } } } }
private byte[] ServiceReadRequestAndWriterResponseForMultipartBatchVerifyDependsOnIds(string requestPayload, ODataVersion maxVersion) { byte[] responseBytes = null; IODataRequestMessage requestMessage = new InMemoryMessage() { Stream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(requestPayload)) }; requestMessage.SetHeader("Content-Type", batchContentTypeMultipartMime); ODataMessageReaderSettings settings = new ODataMessageReaderSettings { Version = maxVersion }; using (ODataMessageReader messageReader = new ODataMessageReader(requestMessage, settings, this.userModel)) { MemoryStream responseStream = new MemoryStream(); IODataResponseMessage responseMessage = new InMemoryMessage { Stream = responseStream }; // Client is expected to receive the response message in the same format as that is used in the request sent. responseMessage.SetHeader("Content-Type", batchContentTypeMultipartMime); using (ODataMessageWriter messageWriter = new ODataMessageWriter(responseMessage)) { ODataBatchWriter batchWriter = messageWriter.CreateODataBatchWriter(); batchWriter.WriteStartBatch(); ODataBatchReader batchReader = messageReader.CreateODataBatchReader(); while (batchReader.Read()) { switch (batchReader.State) { case ODataBatchReaderState.Operation: // Encountered an operation (either top-level or in a change set) ODataBatchOperationRequestMessage operationMessage = batchReader.CreateOperationRequestMessage(); // Verify DependsOnIds are set correctly IEnumerable <string> dependsOnIds = operationMessage.DependsOnIds; switch (operationMessage.ContentId) { case "1": case "2A": Assert.True(dependsOnIds.Count() == 0); break; case "2B": Assert.True(dependsOnIds.SequenceEqual(new List <string> { "2A" })); break; case "2C": Assert.True(dependsOnIds.SequenceEqual(new List <string> { "2A", "2B" })); break; case "3": Assert.True(dependsOnIds.SequenceEqual(new List <string> { "1" })); break; default: break; } ODataBatchOperationResponseMessage response = batchWriter.CreateOperationResponseMessage(operationMessage.ContentId); if (operationMessage.Method == "PATCH") { response.StatusCode = 204; response.SetHeader("Content-Type", "application/json;odata.metadata=none"); } else if (operationMessage.Method == "PUT") { response.StatusCode = 201; response.SetHeader("Content-Type", "application/json;"); } break; case ODataBatchReaderState.ChangesetStart: batchWriter.WriteStartChangeset(); break; case ODataBatchReaderState.ChangesetEnd: batchWriter.WriteEndChangeset(); break; } } batchWriter.WriteEndBatch(); responseStream.Position = 0; responseBytes = responseStream.ToArray(); } return(responseBytes); } }
private byte[] ServiceReadReferenceUriBatchRequestAndWriteResponse(byte[] requestPayload) { IODataRequestMessage requestMessage = new InMemoryMessage() { Stream = new MemoryStream(requestPayload) }; requestMessage.SetHeader("Content-Type", batchContentTypeApplicationJson); ODataMessageReaderSettings settings = new ODataMessageReaderSettings(); settings.BaseUri = new Uri(serviceDocumentUri); byte[] responseBytes = null; using (ODataMessageReader messageReader = new ODataMessageReader(requestMessage, settings, this.userModel)) { MemoryStream responseStream = new MemoryStream(); IODataResponseMessage responseMessage = new InMemoryMessage { Stream = responseStream }; // Client is expected to receive the response message in the same format as that is used in the request sent. responseMessage.SetHeader("Content-Type", batchContentTypeApplicationJson); using (ODataMessageWriter messageWriter = new ODataMessageWriter(responseMessage)) { ODataBatchWriter batchWriter = messageWriter.CreateODataBatchWriter(); batchWriter.WriteStartBatch(); ODataBatchReader batchReader = messageReader.CreateODataBatchReader(); while (batchReader.Read()) { switch (batchReader.State) { case ODataBatchReaderState.Operation: // Encountered an operation (either top-level or in a change set) ODataBatchOperationRequestMessage operationMessage = batchReader.CreateOperationRequestMessage(); ODataBatchOperationResponseMessage response = batchWriter.CreateOperationResponseMessage(operationMessage.ContentId); if (operationMessage.Method == "PUT") { using (ODataMessageReader operationMessageReader = new ODataMessageReader( operationMessage, new ODataMessageReaderSettings(), this.userModel)) { ODataReader reader = operationMessageReader.CreateODataResourceReader(); Assert.NotNull(reader); } response.StatusCode = 201; response.SetHeader("Content-Type", "application/json;odata.metadata=none"); } else if (operationMessage.Method == "PATCH") { using (ODataMessageReader operationMessageReader = new ODataMessageReader( operationMessage, new ODataMessageReaderSettings(), this.userModel)) { ODataReader reader = operationMessageReader.CreateODataResourceReader(); Assert.NotNull(reader); } response.StatusCode = 204; } else if (operationMessage.Method == "GET") { response.StatusCode = 200; response.SetHeader("Content-Type", "application/json;"); ODataMessageWriterSettings writerSettings = new ODataMessageWriterSettings(); writerSettings.ODataUri.ServiceRoot = new Uri(serviceDocumentUri); using ( ODataMessageWriter operationMessageWriter = new ODataMessageWriter(response, writerSettings, this.userModel)) { ODataWriter entryWriter = operationMessageWriter.CreateODataResourceWriter(this.singleton, this.webType); ODataResource entry = new ODataResource() { TypeName = "NS.Web", Properties = new[] { new ODataProperty() { Name = "WebId", Value = -1 }, new ODataProperty() { Name = "Name", Value = aVeryLongString } } }; entryWriter.WriteStart(entry); entryWriter.WriteEnd(); } } break; case ODataBatchReaderState.ChangesetStart: // Set the group Id on the writer side to correlate with request. string atomicGroupId = batchReader.CurrentGroupId; batchWriter.WriteStartChangeset(atomicGroupId); break; case ODataBatchReaderState.ChangesetEnd: batchWriter.WriteEndChangeset(); break; } } batchWriter.WriteEndBatch(); responseStream.Position = 0; responseBytes = responseStream.ToArray(); } return(responseBytes); } }
private byte[] ServiceReadBatchRequestAndWriterBatchResponse(byte[] requestPayload, BodyContentType bodyContentType) { IODataRequestMessage requestMessage = new InMemoryMessage() { Stream = new MemoryStream(requestPayload) }; requestMessage.SetHeader(ODataConstants.ContentTypeHeader, batchContentTypeApplicationJson); using (ODataMessageReader messageReader = new ODataMessageReader(requestMessage, new ODataMessageReaderSettings(), null)) { MemoryStream responseStream = new MemoryStream(); IODataResponseMessage responseMessage = new InMemoryMessage { Stream = responseStream }; // Client is expected to receive the response message in the same format as that is used in the request sent. responseMessage.SetHeader(ODataConstants.ContentTypeHeader, batchContentTypeApplicationJson); ODataMessageWriter messageWriter = new ODataMessageWriter(responseMessage); ODataBatchWriter batchWriter = messageWriter.CreateODataBatchWriter(); batchWriter.WriteStartBatch(); ODataBatchReader batchReader = messageReader.CreateODataBatchReader(); while (batchReader.Read()) { switch (batchReader.State) { case ODataBatchReaderState.Operation: ODataBatchOperationRequestMessage operationMessage = batchReader.CreateOperationRequestMessage(); if (operationMessage.Method == "PUT") { using (Stream operationMessageBodyStream = operationMessage.GetStream()) { // Verify the bytes in the request operation stream. byte[] sampleBytes = bodyContentType == BodyContentType.Textual ? Encoding.UTF8.GetBytes("\"" + this.textualSampleStringA + "\"") : binarySampleBytesA; Assert.Equal(operationMessageBodyStream.Length, sampleBytes.Length); foreach (byte samplebyte in sampleBytes) { Assert.Equal(samplebyte, operationMessageBodyStream.ReadByte()); } } // Create the response. ODataBatchOperationResponseMessage operationResponse = batchWriter.CreateOperationResponseMessage(operationMessage.ContentId); operationResponse.StatusCode = 201; operationResponse.SetHeader("CoNtEnT-TyPe", "application/json;odata.metadata=none"); } else if (operationMessage.Method == "GET") { ODataBatchOperationResponseMessage operationResponse = batchWriter.CreateOperationResponseMessage(operationMessage.ContentId); operationResponse.StatusCode = 200; operationResponse.SetHeader("CoNtEnT-TyPe", GetContentType(bodyContentType)); ODataMessageWriterSettings settings = new ODataMessageWriterSettings(); settings.SetServiceDocumentUri(new Uri(serviceDocumentUri)); using (ODataMessageWriter operationMessageWriter = new ODataMessageWriter(operationResponse, settings, null)) { operationMessageWriter.WriteValue(GetEncodedContentObject(bodyContentType, false)); } } break; case ODataBatchReaderState.ChangesetStart: batchWriter.WriteStartChangeset(); break; case ODataBatchReaderState.ChangesetEnd: batchWriter.WriteEndChangeset(); break; } } batchWriter.WriteEndBatch(); responseStream.Position = 0; return(responseStream.ToArray()); } }
private byte[] ServiceReadSingletonBatchRequestAndWriterBatchResponse(ODataJsonBatchPayloadTestCase testCase, ODataVersion version) { string requestPayload = testCase.RequestPayload; Action <ODataBatchOperationRequestMessage, IList <string> > requestOpMessageVerifier = testCase.RequestMessageDependsOnIdVerifier; IODataRequestMessage requestMessage = new InMemoryMessage() { Stream = new MemoryStream(Encoding.ASCII.GetBytes(requestPayload)) }; requestMessage.SetHeader("Content-Type", batchContentTypeApplicationJson); MemoryStream responseStream = new MemoryStream(); using (ODataMessageReader messageReader = new ODataMessageReader(requestMessage, new ODataMessageReaderSettings() { Version = version }, this.edmModel)) { IODataResponseMessage responseMessage = new InMemoryMessage { Stream = responseStream }; // Client is expected to receive the response message in the same format as that is used in the request sent. responseMessage.SetHeader("Content-Type", batchContentTypeApplicationJson); ODataMessageWriterSettings settings = new ODataMessageWriterSettings() { Version = version }; settings.SetServiceDocumentUri(new Uri(serviceDocumentUri)); ODataMessageWriter messageWriter = new ODataMessageWriter(responseMessage, settings, null); int operationIdx = 0; ODataBatchWriter batchWriter = messageWriter.CreateODataBatchWriter(); batchWriter.WriteStartBatch(); ODataBatchReader batchReader = messageReader.CreateODataBatchReader(); while (batchReader.Read()) { switch (batchReader.State) { case ODataBatchReaderState.Operation: // Encountered an operation (either top-level or in a change set) ODataBatchOperationRequestMessage operationMessage = batchReader.CreateOperationRequestMessage(); // Verify operation message if applicable. requestOpMessageVerifier?.Invoke(operationMessage, testCase.ListOfDependsOnIds.ElementAt(operationIdx)); if (operationMessage.Method == "POST") { ODataBatchOperationResponseMessage response = batchWriter.CreateOperationResponseMessage(operationMessage.ContentId); response.StatusCode = 201; response.SetHeader("Content-Type", batchContentTypeApplicationJson); } else if (operationMessage.Method == "GET") { ODataBatchOperationResponseMessage response = batchWriter.CreateOperationResponseMessage(operationMessage.ContentId); response.StatusCode = 200; response.SetHeader("Content-Type", batchContentTypeApplicationJson); using (ODataMessageWriter operationMessageWriter = new ODataMessageWriter(response, settings, this.edmModel)) { ODataWriter entryWriter = operationMessageWriter.CreateODataResourceWriter(this.singleton, this.userType); ODataResource entry = new ODataResource() { TypeName = "NS.User", Properties = new[] { new ODataProperty() { Name = "UserPrincipalName", Value = "*****@*****.**" }, new ODataProperty() { Name = "GivenName", Value = "Jon" } } }; entryWriter.WriteStart(entry); entryWriter.WriteEnd(); } } operationIdx++; break; case ODataBatchReaderState.ChangesetStart: batchWriter.WriteStartChangeset(); break; case ODataBatchReaderState.ChangesetEnd: batchWriter.WriteEndChangeset(); break; } } batchWriter.WriteEndBatch(); } responseStream.Position = 0; return(responseStream.ToArray()); }