Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 12 additions & 6 deletions .vscode/launch.json
Original file line number Diff line number Diff line change
@@ -1,9 +1,15 @@
{
// Use IntelliSense to find out which attributes exist for C# debugging
// Use hover for the description of the existing attributes
// For further information visit https://github.com/OmniSharp/omnisharp-vscode/blob/master/debugger-launchjson.md
"version": "0.2.0",
"configurations": [
// Use IntelliSense to find out which attributes exist for C# debugging
// Use hover for the description of the existing attributes
// For further information visit https://github.com/OmniSharp/omnisharp-vscode/blob/master/debugger-launchjson.md
"version": "0.2.0",
"configurations": [
{
"name": "ASP.NET Core Sample Launch",
"type": "dotnet",
"request": "launch",
"projectPath": "${workspaceFolder}/samples/CloudNative.CloudEvents.AspNetCoreSample/CloudNative.CloudEvents.AspNetCoreSample.csproj"
},
{
"name": ".NET Core Launch (console)",
"type": "coreclr",
Expand All @@ -24,5 +30,5 @@
"request": "attach",
"processId": "${command:pickProcess}"
}
,]
]
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
// Copyright (c) Cloud Native Foundation.
// Licensed under the Apache 2.0 license.
// See LICENSE file in the project root for full license information.

using CloudNative.CloudEvents.AspNetCore;
using CloudNative.CloudEvents.Core;
using CloudNative.CloudEvents.SystemTextJson;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.HttpResults;
using Microsoft.Extensions.DependencyInjection;
using System.Reflection;
using System.Threading.Tasks;

namespace CloudNative.CloudEvents.AspNetCoreSample;

public class CloudEventBinding : IBindableFromHttpContext<CloudEventBinding>
{
public CloudEvent Value { get; init; }

public ProblemHttpResult Error { get; init; }

public static async ValueTask<CloudEventBinding> BindAsync(HttpContext context, ParameterInfo parameter)
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Just as a heads-up, I'm really not familiar with IBindableFromHttpContext. I'm mostly following along, but I could easily miss things.

{
Validation.CheckNotNull(context, nameof(context));
Validation.CheckNotNull(parameter, nameof(parameter));

var request = context.Request;

// Even though we're not allowing non-JSON content in this binding,
// types such as "text/xml" could still be parsed with the current JsonEventFormatter,
// but it's just not making it strongly typed, or anything structured (XmlNode).
// Depending on your use-case, it may or may not be desirable to allow that.
if (request.ContentLength != 0 && !request.HasJsonContentType())
{
return new CloudEventBinding
{
Error = TypedResults.Problem(
statusCode: StatusCodes.Status415UnsupportedMediaType,
title: "Unsupported media type",
detail: "Request content type is not JSON and not fully supported in this binding. " +
"Please note: the CloudEvents specification does allow for any data content, " +
"as long as it adheres to the provided datacontenttype."
)
};
}

var formatter = context.RequestServices.GetRequiredService<JsonEventFormatter>();

var cloudEvent = await request.ToCloudEventAsync(formatter);

return new CloudEventBinding
{
Value = cloudEvent
};
}
}

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
// Copyright (c) Cloud Native Foundation.
// Licensed under the Apache 2.0 license.
// See LICENSE file in the project root for full license information.

using CloudNative.CloudEvents.AspNetCore;
using CloudNative.CloudEvents.SystemTextJson;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.HttpResults;
using System;
using System.Linq;
using System.Threading.Tasks;

namespace CloudNative.CloudEvents.AspNetCoreSample;

public static class CloudEventOperations
{
public static async Task<Results<ProblemHttpResult, JsonHttpResult<object>>> ReceiveCloudEvent(CloudEventBinding cloudEventBinding)
{
if (cloudEventBinding.Error is not null)
{
return cloudEventBinding.Error;
}

var cloudEvent = cloudEventBinding.Value;

var cloudEventAttributes = cloudEvent.GetPopulatedAttributes()
.ToDictionary(pair => pair.Key.Name, pair => pair.Key.Format(pair.Value));

return TypedResults.Json<object>(new
{
note = "wow, such event, much disassembling, very skill",
cloudEvent.SpecVersion.VersionId,
cloudEventAttributes,
cloudEvent.Data
});
}

/// <summary>
/// Generates a CloudEvent.
/// </summary>
public static async Task GenerateCloudEvent(HttpResponse response, JsonEventFormatter formatter, ContentMode contentMode = ContentMode.Structured)
{
var evt = new CloudEvent
{
Type = "CloudNative.CloudEvents.AspNetCoreSample",
Source = new Uri("https://github.com/cloudevents/sdk-csharp"),
Time = DateTimeOffset.Now,
DataContentType = "application/json",
Id = Guid.NewGuid().ToString(),
Data = new
{
Language = "C#",
EnvironmentVersion = Environment.Version.ToString()
}
};

response.StatusCode = StatusCodes.Status200OK;
await evt.CopyToHttpResponseAsync(response, contentMode, formatter);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
<ItemGroup>
<ProjectReference Include="..\..\src\CloudNative.CloudEvents.AspNetCore\CloudNative.CloudEvents.AspNetCore.csproj" />
<ProjectReference Include="..\..\src\CloudNative.CloudEvents\CloudNative.CloudEvents.csproj" />
<ProjectReference Include="..\..\src\CloudNative.CloudEvents.NewtonsoftJson\CloudNative.CloudEvents.NewtonsoftJson.csproj" />
<ProjectReference Include="..\..\src\CloudNative.CloudEvents.SystemTextJson\CloudNative.CloudEvents.SystemTextJson.csproj" />
</ItemGroup>

</Project>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,16 +1,56 @@
@HostAddress = https://localhost:5001

### Send via Structured mode

POST {{HostAddress}}/api/events/receive
Content-Type: application/cloudevents+json; charset=utf-8

{
"specversion": "1.0",
"type": "com.example.myevent",
"source": "urn:example-com:mysource:abc",
"id": "{{$guid}}",
"data": {
"message": "Hello world!"
}
}

### Send via Binary mode

POST {{HostAddress}}/api/events/receive
Content-Type: application/json
CE-SpecVersion: 1.0
CE-Type: "com.example.myevent"
CE-Source: "urn:example-com:mysource:abc"
CE-Id: "c457b7c5-c038-4be9-98b9-938cb64a4fbf"
CE-Id: "{{$guid}}"

{
"message": "Hello world!"
}

###
### Send content-less via Binary mode

POST {{HostAddress}}/api/events/receive
CE-SpecVersion: 1.0
CE-Type: "com.example.myevent"
CE-Source: "urn:example-com:mysource:abc"
CE-Id: "{{$guid}}"

### Send unsupported media type (XML) via Binary mode

POST {{HostAddress}}/api/events/receive
Content-Type: text/xml
CE-SpecVersion: 1.0
CE-Type: "com.example.myevent"
CE-Source: "urn:example-com:mysource:abc"
CE-Id: "{{$guid}}"

<message>Hello world!</message>

### Generate via Structured mode

GET {{HostAddress}}/api/events/generate

### Generate via Binary mode

GET {{HostAddress}}/api/events/generate?contentMode=Binary

This file was deleted.

11 changes: 7 additions & 4 deletions samples/CloudNative.CloudEvents.AspNetCoreSample/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,18 +3,21 @@
// See LICENSE file in the project root for full license information.

using CloudNative.CloudEvents.AspNetCoreSample;
using CloudNative.CloudEvents.SystemTextJson;
using Microsoft.AspNetCore.Builder;
using CloudNative.CloudEvents.NewtonsoftJson;
using Microsoft.Extensions.DependencyInjection;
using System.Text.Json;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllers(opts =>
opts.InputFormatters.Insert(0, new CloudEventJsonInputFormatter(new JsonEventFormatter())));
JsonSerializerOptions jsonOptions = new() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase };
builder.Services.AddSingleton(new JsonEventFormatter(jsonOptions, new JsonDocumentOptions()));

var app = builder.Build();

app.MapControllers();
var apiEvents = app.MapGroup("/api/events");
apiEvents.MapPost("/receive", CloudEventOperations.ReceiveCloudEvent);
apiEvents.MapGet("/generate", CloudEventOperations.GenerateCloudEvent);

app.Run();

Expand Down
2 changes: 1 addition & 1 deletion samples/HttpSend/HttpSend.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
<ItemGroup>
<PackageReference Include="McMaster.Extensions.CommandLineUtils" />
<ProjectReference Include="..\..\src\CloudNative.CloudEvents\CloudNative.CloudEvents.csproj" />
<ProjectReference Include="..\..\src\CloudNative.CloudEvents.NewtonsoftJson\CloudNative.CloudEvents.NewtonsoftJson.csproj" />
<ProjectReference Include="..\..\src\CloudNative.CloudEvents.SystemTextJson\CloudNative.CloudEvents.SystemTextJson.csproj" />
</ItemGroup>

</Project>
Expand Down
Loading