Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cncf namespace samples #44994

Merged
merged 11 commits into from
Jul 15, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
1 change: 1 addition & 0 deletions eng/Packages.Data.props
Original file line number Diff line number Diff line change
Expand Up @@ -273,6 +273,7 @@
<PackageReference Update="BenchmarkDotNet" Version="0.13.4" />
<PackageReference Update="BenchmarkDotNet.Diagnostics.Windows" Version="0.13.4" />
<PackageReference Update="Castle.Core" Version="5.1.0" />
<PackageReference Update="CloudNative.CloudEvents.SystemTextJson" Version="2.0.0" />
<PackageReference Update="CommandLineParser" Version="2.8.0" />
<PackageReference Update="FluentAssertions" Version="5.10.3" />
<PackageReference Update="FsCheck.Xunit" Version="2.14.0" />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,13 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Azure.Messaging.EventGrid.N
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Azure.Messaging.EventGrid.Namespaces.Tests", "tests\Azure.Messaging.EventGrid.Namespaces.Tests.csproj", "{1F1CD1D4-9932-4B73-99D8-C252A67D4B46}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Samples", "Samples", "{5E3752BC-2C04-499F-B2C4-28426B3C344A}"
ProjectSection(SolutionItems) = preProject
JoshLove-msft marked this conversation as resolved.
Show resolved Hide resolved
samples\README.md = samples\README.md
samples\Sample1_Namespaces.md = samples\Sample1_Namespaces.md
samples\Sample2_CNCF.md = samples\Sample2_CNCF.md
EndProjectSection
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,5 @@
"AssetsRepo": "Azure/azure-sdk-assets",
"AssetsRepoPrefixPath": "net",
"TagPrefix": "net/eventgrid/Azure.Messaging.EventGrid.Namespaces",
"Tag": "net/eventgrid/Azure.Messaging.EventGrid.Namespaces_dcc4c4a164"
"Tag": "net/eventgrid/Azure.Messaging.EventGrid.Namespaces_bf72309699"
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,4 @@ description: Samples for the Azure.Messaging.EventGrid.Namespaces client library
Before starting, take a look at the Azure Event Grid [README](https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/eventgrid/Azure.Messaging.EventGrid.Namespaces/README.md) for more information on how to create an Event Grid custom topic or domain using the Azure portal/Azure CLI, and retrieving the designated endpoint and credential.

- [Using Namespace Topics](https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/eventgrid/Azure.Messaging.EventGrid.Namespaces/samples/Sample1_Namespaces.md)
- [Using the Cloud Native CloudEvent type]
JoshLove-msft marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
# Using the Cloud Native CloudEvent type

It is possible to publish and receive the CloudNative CloudEvent type found in the [CloudNative.CloudEvents library](https://www.nuget.org/packages/CloudNative.CloudEvents) using the Azure Event Grid Namespaces client library.
First we create a `CloudEvent` object and publish it to the namespace topic using the `EventGridSenderClient`.

```C# Snippet:SendCNCFEvent
var evt = new CloudNative.CloudEvents.CloudEvent
{
Source = new Uri("http://localHost"),
Type = "type",
Data = new TestModel { Name = "Bob", Age = 18 },
Id = Recording.Random.NewGuid().ToString()
};
var jsonFormatter = new JsonEventFormatter();
var sender = new EventGridSenderClient(new Uri(namespaceTopicHost), topicName, new AzureKeyCredential(namespaceKey));
await sender.SendEventAsync(RequestContent.Create(jsonFormatter.EncodeStructuredModeMessage(evt, out _)));
```

Next, we receive the events using the `EventGridReceiverClient`.

```C# Snippet:ReceiveCNCFEvent
var receiver = new EventGridReceiverClient(new Uri(namespaceTopicHost), topicName, subscriptionName, new AzureKeyCredential(namespaceKey));
Response response = await receiver.ReceiveAsync(maxEvents: 1, maxWaitTime: TimeSpan.FromSeconds(10), new RequestContext());

var eventResponse = response.Content.ToDynamicFromJson(JsonPropertyNames.CamelCase).Value[0];
var receivedCloudEvent = jsonFormatter.DecodeStructuredModeMessage(
Encoding.UTF8.GetBytes(eventResponse.Event.ToString()),
new ContentType("application/cloudevents+json"),
null);
```

Finally, we acknowledge the event using the lock token.

```C# Snippet:AcknowledgeCNCFEvent
AcknowledgeResult acknowledgeResult = await receiver.AcknowledgeAsync(new string[] { eventResponse.BrokerProperties.LockToken.ToString() });
```
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
<PackageReference Include="NUnit3TestAdapter" />
<PackageReference Include="Microsoft.NET.Test.Sdk" />
<PackageReference Include="Moq" />
<PackageReference Include="CloudNative.CloudEvents.SystemTextJson" />
</ItemGroup>

<ItemGroup>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,16 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Azure.Core;
using Azure.Core.Serialization;
using Azure.Core.TestFramework;
using Azure.Identity;
using Azure.Messaging.EventGrid.Namespaces;
using CloudNative.CloudEvents.SystemTextJson;
using NUnit.Framework;
using ContentType = System.Net.Mime.ContentType;

namespace Azure.Messaging.EventGrid.Tests
{
Expand Down Expand Up @@ -284,6 +289,54 @@ public async Task Acknowledge()
Assert.IsEmpty(acknowledgeResult.FailedLockTokens);
}

[RecordedTest]
public async Task RoundTripCNCFEvent()
{
var namespaceTopicHost = TestEnvironment.NamespaceTopicHost;
var namespaceKey = TestEnvironment.NamespaceKey;
var topicName = TestEnvironment.NamespaceTopicName;
var subscriptionName = TestEnvironment.NamespaceSubscriptionName;

#region Snippet:SendCNCFEvent
var evt = new CloudNative.CloudEvents.CloudEvent
{
Source = new Uri("http://localHost"),
Type = "type",
Data = new TestModel { Name = "Bob", Age = 18 },
Id = Recording.Random.NewGuid().ToString()
};
var jsonFormatter = new JsonEventFormatter();
#if SNIPPET
var sender = new EventGridSenderClient(new Uri(namespaceTopicHost), topicName, new AzureKeyCredential(namespaceKey));
#else
var sender = InstrumentClient(new EventGridSenderClient(new Uri(namespaceTopicHost), topicName, new AzureKeyCredential(namespaceKey), InstrumentClientOptions(new EventGridSenderClientOptions())));
#endif
await sender.SendEventAsync(RequestContent.Create(jsonFormatter.EncodeStructuredModeMessage(evt, out _)));
#endregion
#region Snippet:ReceiveCNCFEvent
#if SNIPPET
var receiver = new EventGridReceiverClient(new Uri(namespaceTopicHost), topicName, subscriptionName, new AzureKeyCredential(namespaceKey));
#else
var receiver = InstrumentClient(new EventGridReceiverClient(new Uri(namespaceTopicHost), topicName, subscriptionName, new AzureKeyCredential(namespaceKey), InstrumentClientOptions(new EventGridReceiverClientOptions())));
#endif
Response response = await receiver.ReceiveAsync(maxEvents: 1, maxWaitTime: TimeSpan.FromSeconds(10), new RequestContext());

var eventResponse = response.Content.ToDynamicFromJson(JsonPropertyNames.CamelCase).Value[0];
var receivedCloudEvent = jsonFormatter.DecodeStructuredModeMessage(
Encoding.UTF8.GetBytes(eventResponse.Event.ToString()),
new ContentType("application/cloudevents+json"),
null);
#endregion
Assert.AreEqual(evt.Source, receivedCloudEvent.Source);
Assert.AreEqual(evt.Type, receivedCloudEvent.Type);
Assert.AreEqual(evt.Id, receivedCloudEvent.Id);

#region Snippet:AcknowledgeCNCFEvent
AcknowledgeResult acknowledgeResult = await receiver.AcknowledgeAsync(new string[] { eventResponse.BrokerProperties.LockToken.ToString() });
#endregion
Assert.IsEmpty(acknowledgeResult.FailedLockTokens);
}

public class TestModel
{
public string Name { get; set; }
Expand Down
Loading