Skip to content
This repository has been archived by the owner on Jan 24, 2021. It is now read-only.

WIP - First stab at creating a BodyDelegate type #2577

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
6 changes: 3 additions & 3 deletions src/Nancy.Hosting.Aspnet/NancyHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ public async Task ProcessRequest(HttpContextBase httpContext)

using(var nancyContext = await this.engine.HandleRequest(request).ConfigureAwait(false))
{
SetNancyResponseToHttpResponse(httpContext, nancyContext.Response);
await SetNancyResponseToHttpResponse(httpContext, nancyContext.Response);
}
}

Expand Down Expand Up @@ -118,7 +118,7 @@ private static long GetExpectedRequestLength(IDictionary<string, IEnumerable<str
return contentLength;
}

public static void SetNancyResponseToHttpResponse(HttpContextBase context, Response response)
public static Task SetNancyResponseToHttpResponse(HttpContextBase context, Response response)
{
SetHttpResponseHeaders(context, response);

Expand All @@ -139,7 +139,7 @@ public static void SetNancyResponseToHttpResponse(HttpContextBase context, Respo
context.Response.StatusDescription = response.ReasonPhrase;
}

response.Contents.Invoke(new NancyResponseStream(context.Response));
return response.Contents.Body.Invoke(new NancyResponseStream(context.Response));
}

private static bool IsOutputBufferDisabled()
Expand Down
31 changes: 31 additions & 0 deletions src/Nancy.MSBuild/BodyDelegate.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
namespace Nancy
Copy link
Member

@jchannon jchannon Sep 28, 2016

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is in the wrong location, needs to be under ./Nancy

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

shrug VS2015 is garbage, what can I say? :)

{
using System;
using System.IO;
using System.Threading.Tasks;

public class BodyDelegate
{
public Func<Stream, Task> Body { get; set; }

public static implicit operator BodyDelegate(Func<Stream, Task> body)
{
return new BodyDelegate { Body = body };
}

public static implicit operator BodyDelegate(Action<Stream> body)
{
return new BodyDelegate { Body = Wrap(body) };
}

private static Func<Stream, Task> Wrap(Action<Stream> body)
{
return s =>
{
body.Invoke(s);

return Task.FromResult(new object());
};
}
}
}
19 changes: 10 additions & 9 deletions src/Nancy.MSBuild/Nancy.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -356,15 +356,15 @@
<Compile Include="..\Nancy\Helpers\ExceptionExtensions.cs">
<Link>Helpers\ExceptionExtensions.cs</Link>
</Compile>
<Compile Include="..\Nancy\HttpLink.cs">
<Link>HttpLink.cs</Link>
</Compile>
<Compile Include="..\Nancy\HttpLinkBuilder.cs">
<Link>HttpLinkBuilder.cs</Link>
</Compile>
<Compile Include="..\Nancy\HttpLinkRelation.cs">
<Link>HttpLinkRelation.cs</Link>
</Compile>
<Compile Include="..\Nancy\HttpLink.cs">
<Link>HttpLink.cs</Link>
</Compile>
<Compile Include="..\Nancy\HttpLinkBuilder.cs">
<Link>HttpLinkBuilder.cs</Link>
</Compile>
<Compile Include="..\Nancy\HttpLinkRelation.cs">
<Link>HttpLinkRelation.cs</Link>
</Compile>
<Compile Include="..\Nancy\IAssemblyCatalog.cs">
<Link>IAssemblyCatalog.cs</Link>
</Compile>
Expand Down Expand Up @@ -1376,6 +1376,7 @@
<Compile Include="..\Nancy\Routing\Route.cs">
<Link>Routing\Route.cs</Link>
</Compile>
<Compile Include="BodyDelegate.cs" />
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

../Nancy required

</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="..\Nancy\Diagnostics\Views\Dashboard.sshtml">
Expand Down
3 changes: 2 additions & 1 deletion src/Nancy/Bootstrapper/NancyBootstrapperBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;

using Nancy.Configuration;
Expand Down Expand Up @@ -313,7 +314,7 @@ public void Initialise()
{
ContentType = "image/vnd.microsoft.icon",
StatusCode = HttpStatusCode.OK,
Contents = s => s.Write(this.FavIcon, 0, this.FavIcon.Length)
Contents = (Action<Stream>)(s => s.Write(this.FavIcon, 0, this.FavIcon.Length))
};

response.Headers["Cache-Control"] = "public, max-age=604800, must-revalidate";
Expand Down
2 changes: 1 addition & 1 deletion src/Nancy/Diagnostics/DiagnosticsViewRenderer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ private static Stream GetBodyStream(string name)

var stream = new MemoryStream();

view.Contents.Invoke(stream);
view.Contents.Body.Invoke(stream).Wait();
stream.Position = 0;
return stream;
}
Expand Down
5 changes: 3 additions & 2 deletions src/Nancy/ErrorHandling/DefaultStatusCodeHandler.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
namespace Nancy.ErrorHandling
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
Expand Down Expand Up @@ -127,13 +128,13 @@ private void ModifyResponse(HttpStatusCode statusCode, NancyContext context, Def
}

context.Response.ContentType = "text/html";
context.Response.Contents = s =>
context.Response.Contents = (Action<Stream>)(s =>
{
using (var writer = new StreamWriter(new UnclosableStreamWrapper(s), Encoding.UTF8))
{
writer.Write(contents);
}
};
});
}

private static string LoadResource(string filename)
Expand Down
10 changes: 5 additions & 5 deletions src/Nancy/HeadResponse.cs
Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,11 @@ public class HeadResponse : Response
public HeadResponse(Response response)
{
this.innerResponse = response;
this.Contents = stream =>
this.Contents = (Func<Stream, Task>)(async stream =>
{
this.CheckAndSetContentLength(this.innerResponse);
await this.CheckAndSetContentLength(this.innerResponse);
GetStringContents(string.Empty)(stream);
};
});
this.ContentType = response.ContentType;
this.Headers = response.Headers;
this.StatusCode = response.StatusCode;
Expand All @@ -48,7 +48,7 @@ public override Task PreExecute(NancyContext context)
return this.innerResponse.PreExecute(context);
}

private void CheckAndSetContentLength(Response response)
private async Task CheckAndSetContentLength(Response response)
{
if (this.Headers.ContainsKey(ContentLength))
{
Expand All @@ -57,7 +57,7 @@ private void CheckAndSetContentLength(Response response)

using (var nullStream = new NullStream())
{
response.Contents.Invoke(nullStream);
await response.Contents.Body.Invoke(nullStream);

this.Headers[ContentLength] = nullStream.Length.ToString(CultureInfo.InvariantCulture);
}
Expand Down
7 changes: 4 additions & 3 deletions src/Nancy/Jsonp.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Nancy.Bootstrapper;
using Nancy.Configuration;
using Nancy.Json;
Expand Down Expand Up @@ -73,7 +74,7 @@ private static void PrepareJsonp(NancyContext context)
// http://stackoverflow.com/questions/111302/best-content-type-to-serve-jsonp
context.Response.ContentType = string.Concat("application/javascript", Encoding);

context.Response.Contents = stream =>
context.Response.Contents = (Func<Stream, Task>)(async stream =>
{
// disposing of stream is handled elsewhere
var writer = new StreamWriter(stream)
Expand All @@ -82,9 +83,9 @@ private static void PrepareJsonp(NancyContext context)
};

writer.Write("{0}(", callback);
original(stream);
await original.Body.Invoke(stream);
writer.Write(");");
};
});
}
}
}
9 changes: 4 additions & 5 deletions src/Nancy/Owin/NancyMiddleware.cs
Original file line number Diff line number Diff line change
Expand Up @@ -152,16 +152,15 @@ public static MidFunc UseNancy(NancyOptions options = null)
.ToArray();
}

nancyResponse.Contents(owinResponseBody);
using (context)
{
return nancyResponse.Contents.Body.Invoke(owinResponseBody);
}
}
else
{
return next(environment);
}

context.Dispose();

return TaskHelpers.CompletedTask;
}

private static T Get<T>(IDictionary<string, object> env, string key)
Expand Down
2 changes: 1 addition & 1 deletion src/Nancy/Response.cs
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ public string ContentType
/// </summary>
/// <value>An <see cref="Action{T}"/> delegate, containing the code that will render contents to the response stream.</value>
/// <remarks>The host of Nancy will pass in the output stream after the response has been handed back to it by Nancy.</remarks>
public Action<Stream> Contents { get; set; }
public BodyDelegate Contents { get; set; }

/// <summary>
/// Gets the collection of HTTP response headers that should be sent back to the client.
Expand Down
7 changes: 4 additions & 3 deletions src/Nancy/Responses/EmbeddedFileResponse.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

/// <summary>
/// Represent an HTML response with embeded file content.
Expand Down Expand Up @@ -42,17 +43,17 @@ public EmbeddedFileResponse(Assembly assembly, string resourcePath, string name)
content.Seek(0, SeekOrigin.Begin);
}

this.Contents = stream =>
this.Contents = (Func<Stream, Task>)(async stream =>
{
if (content != null)
{
content.CopyTo(stream);
await content.CopyToAsync(stream);
}
else
{
stream.Write(ErrorText, 0, ErrorText.Length);
}
};
});
}

private Stream GetResourceContent(Assembly assembly, string resourcePath, string name)
Expand Down
15 changes: 8 additions & 7 deletions src/Nancy/Responses/MaterialisingResponse.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,15 +25,16 @@ public class MaterialisingResponse : Response
/// <returns>
/// Task for completion/erroring
/// </returns>
public override Task PreExecute(NancyContext context)
public override async Task PreExecute(NancyContext context)
{
using (var memoryStream = new MemoryStream())
{
this.sourceResponse.Contents.Invoke(memoryStream);
await this.sourceResponse.Contents.Body.Invoke(memoryStream);

this.oldResponseOutput = memoryStream.ToArray();
}

return base.PreExecute(context);
await base.PreExecute(context);
}

/// <summary>
Expand All @@ -49,18 +50,18 @@ public MaterialisingResponse(Response sourceResponse)
this.StatusCode = sourceResponse.StatusCode;
this.ReasonPhrase = sourceResponse.ReasonPhrase;

this.Contents = WriteContents;
this.Contents = (Func<Stream, Task>)WriteContents;
}

private void WriteContents(Stream stream)
private async Task WriteContents(Stream stream)
{
if (this.oldResponseOutput == null)
{
this.sourceResponse.Contents.Invoke(stream);
await this.sourceResponse.Contents.Body.Invoke(stream);
}
else
{
stream.Write(this.oldResponseOutput, 0, this.oldResponseOutput.Length);
await stream.WriteAsync(this.oldResponseOutput, 0, this.oldResponseOutput.Length);
}
}
}
Expand Down
6 changes: 4 additions & 2 deletions src/Nancy/Responses/Negotiation/XmlProcessor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Mime;

/// <summary>
/// Processes the model for xml media types and extension.
Expand Down Expand Up @@ -83,13 +85,13 @@ private static Response CreateResponse(dynamic model, ISerializer serializer)
{
return new Response
{
Contents = stream =>
Contents = (Action<Stream>)(stream =>
{
if (model != null)
{
serializer.Serialize("application/xml", model, stream);
}
},
}),
ContentType = "application/xml",
StatusCode = HttpStatusCode.OK
};
Expand Down
10 changes: 6 additions & 4 deletions src/Nancy/Responses/TextResponse.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
namespace Nancy.Responses
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

using Nancy.Cookies;
Expand Down Expand Up @@ -36,11 +38,11 @@ public TextResponse(string contents, string contentType = null, Encoding encodin

if (contents != null)
{
this.Contents = stream =>
this.Contents = (Action<Stream>)(stream =>
{
var data = encoding.GetBytes(contents);
stream.Write(data, 0, data.Length);
};
});
}
}

Expand All @@ -66,11 +68,11 @@ public TextResponse(HttpStatusCode statusCode = HttpStatusCode.OK, string conten

if (contents != null)
{
this.Contents = stream =>
this.Contents = (Action<Stream>)(stream =>
{
var data = encoding.GetBytes(contents);
stream.Write(data, 0, data.Length);
};
});
}

if (headers != null)
Expand Down