This commit is contained in:
Serkant Karaca 2019-06-27 16:13:13 -07:00
Родитель 742d8d8a7e
Коммит 9c355e98e2
9 изменённых файлов: 318 добавлений и 5 удалений

Просмотреть файл

@ -10,11 +10,11 @@ namespace SampleEphReceiver
public class Program
{
private const string EventHubConnectionString = "Event Hubs connection string";
private const string EventHubName = "event hub name";
private const string StorageContainerName = "Storage account container name";
private const string StorageAccountName = "Storage account name";
private const string StorageAccountKey = "Storage account key";
private const string EventHubConnectionString = "Endpoint=sb://serkant-demo.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=y2w71RLNTpUjrFA6OM83v55/e0pcY+R5VqjKnXn57nc=";
private const string EventHubName = "myeh";
private const string StorageAccountName = "serkantdemo";
private const string StorageAccountKey = "cShMcVIyns73iJ6yN/a2/OMPc7SmIJiPO7jIrgg1zkdYZzXD92WCrJGLyeg5e0z/u+HqrFaGB2VJwXO1uxaF0A==";
private const string StorageContainerName = "democontainer";
private static readonly string StorageConnectionString = string.Format("DefaultEndpointsProtocol=https;AccountName={0};AccountKey={1}", StorageAccountName, StorageAccountKey);

Просмотреть файл

@ -0,0 +1,21 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netcoreapp2.2</TargetFramework>
<AssemblyName>CustomRole</AssemblyName>
<OutputType>Exe</OutputType>
<PackageId>CustomRole</PackageId>
<RuntimeFrameworkVersion>2.2.0</RuntimeFrameworkVersion>
<GenerateAssemblyConfigurationAttribute>false</GenerateAssemblyConfigurationAttribute>
<GenerateAssemblyCompanyAttribute>false</GenerateAssemblyCompanyAttribute>
<GenerateAssemblyProductAttribute>false</GenerateAssemblyProductAttribute>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Azure.EventHubs" Version="3.0.0-dev.20190627.1" />
<PackageReference Include="Microsoft.Azure.EventHubs.Processor" Version="3.0.0-dev.20190627.1" />
<PackageReference Include="Microsoft.Azure.Storage.Blob" Version="10.0.3" />
<PackageReference Include="Microsoft.Identity.Client" Version="4.0.0" />
</ItemGroup>
</Project>

Просмотреть файл

@ -0,0 +1,25 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.26730.10
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "CustomRole", "CustomRole.csproj", "{679DFCC5-76BD-4725-A51E-AFBB01565401}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{679DFCC5-76BD-4725-A51E-AFBB01565401}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{679DFCC5-76BD-4725-A51E-AFBB01565401}.Debug|Any CPU.Build.0 = Debug|Any CPU
{679DFCC5-76BD-4725-A51E-AFBB01565401}.Release|Any CPU.ActiveCfg = Release|Any CPU
{679DFCC5-76BD-4725-A51E-AFBB01565401}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {4190FE18-2881-43ED-9A45-6AECB8D3314A}
EndGlobalSection
EndGlobal

Просмотреть файл

@ -0,0 +1,94 @@
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace CustomRole
{
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure.EventHubs;
using Microsoft.Azure.EventHubs.Processor;
using Microsoft.Azure.Storage;
using Microsoft.Azure.Storage.Auth;
using Microsoft.Identity.Client;
public class Program
{
static readonly string TenantId = "";
static readonly string ClientId = "";
static readonly string ClientSecret = "";
static readonly string EventHubNamespace = "";
static readonly string EventHubName = "";
static readonly string StorageContainerName = "";
public static void Main(string[] args)
{
MainAsync(args).GetAwaiter().GetResult();
}
private static async Task MainAsync(string[] args)
{
// Create Azure Storage Client with token provider.
var tokenAndFrequency = await StorageTokenRenewerAsync(null, CancellationToken.None);
var tokenCredential = new TokenCredential(tokenAndFrequency.Token, StorageTokenRenewerAsync, null, tokenAndFrequency.Frequency.Value);
var storageCredentials = new StorageCredentials(tokenCredential);
var cloudStorageAccount = new CloudStorageAccount(storageCredentials, false);
// Create Azure Active Directory token provider for Event Hubs access.
TokenProvider tokenProvider = TokenProvider.CreateAzureActiveDirectoryTokenProvider(
async (audience, authority, state) =>
{
IConfidentialClientApplication app = ConfidentialClientApplicationBuilder.Create(ClientId)
.WithTenantId(TenantId)
.WithClientSecret(ClientSecret)
.Build();
var authResult = await app.AcquireTokenForClient(new string[] { $"{audience}/.default" }).ExecuteAsync();
return authResult.AccessToken;
});
Console.WriteLine("Registering EventProcessor...");
var eventProcessorHost = new EventProcessorHost(
new Uri(EventHubNamespace),
EventHubName,
PartitionReceiver.DefaultConsumerGroupName,
tokenProvider,
null,
StorageContainerName);
// Registers the Event Processor Host and starts receiving messages
await eventProcessorHost.RegisterEventProcessorAsync<SimpleEventProcessor>();
Console.WriteLine("Receiving. Press enter key to stop worker.");
Console.ReadLine();
// Disposes of the Event Processor Host
await eventProcessorHost.UnregisterEventProcessorAsync();
}
static async Task<NewTokenAndFrequency> StorageTokenRenewerAsync(object state, CancellationToken cancellationToken)
{
// Specify the resource ID for requesting Azure AD tokens for Azure Storage.
const string StorageResource = "https://storage.azure.com/";
IConfidentialClientApplication app = ConfidentialClientApplicationBuilder.Create(ClientId)
.WithTenantId(TenantId)
.WithClientSecret(ClientSecret)
.Build();
var authResult = await app.AcquireTokenForClient(new string[] { $"{StorageResource}/.default" }).ExecuteAsync(cancellationToken);
// Renew the token 5 minutes before it expires.
var next = (authResult.ExpiresOn - DateTimeOffset.UtcNow) - TimeSpan.FromMinutes(5);
if (next.Ticks < 0)
{
next = default(TimeSpan);
Console.WriteLine("Renewing token...");
}
// Return the new token and the next refresh time.
return new NewTokenAndFrequency(authResult.AccessToken, next);
}
}
}

Просмотреть файл

@ -0,0 +1,21 @@
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("SampleReceiver")]
[assembly: AssemblyTrademark("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("679dfcc5-76bd-4725-a51e-afbb01565401")]

Просмотреть файл

@ -0,0 +1,44 @@
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace CustomRole
{
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Azure.EventHubs;
using Microsoft.Azure.EventHubs.Processor;
public class SimpleEventProcessor : IEventProcessor
{
public Task CloseAsync(PartitionContext context, CloseReason reason)
{
Console.WriteLine($"Processor Shutting Down. Partition '{context.PartitionId}', Reason: '{reason}'.");
return Task.CompletedTask;
}
public Task OpenAsync(PartitionContext context)
{
Console.WriteLine($"SimpleEventProcessor initialized. Partition: '{context.PartitionId}'");
return Task.CompletedTask;
}
public Task ProcessErrorAsync(PartitionContext context, Exception error)
{
Console.WriteLine($"Error on Partition: {context.PartitionId}, Error: {error.Message}");
return Task.CompletedTask;
}
public Task ProcessEventsAsync(PartitionContext context, IEnumerable<EventData> messages)
{
foreach (var eventData in messages)
{
var data = Encoding.UTF8.GetString(eventData.Body.Array, eventData.Body.Offset, eventData.Body.Count);
Console.WriteLine($"Message received. Partition: '{context.PartitionId}', Data: '{data}', Partition Key: '{eventData.SystemProperties.PartitionKey}'");
}
return context.CheckpointAsync();
}
}
}

Просмотреть файл

@ -0,0 +1,36 @@
# Receive events with the Event Processor Host in .NET Standard
This sample shows how to write a .NET Core console application that receives a set of events from an event hub by using the **Event Processor Host** library. You can run the solution as-is, replacing the strings with your event hub and storage account values. The sample is also [available as a tutorial](https://docs.microsoft.com/en-us/azure/event-hubs/event-hubs-dotnet-standard-getstarted-receive-eph).
## Prerequisites
* [Microsoft Visual Studio 2015 or 2017](http://www.visualstudio.com).
* [.NET Core Visual Studio 2015 or 2017 tools](http://www.microsoft.com/net/core).
* An Azure subscription.
* [An event hub namespace and an event hub](event-hubs-quickstart-namespace-portal.md).
* An Azure Storage account.
## Run the sample
To run the sample, follow these steps:
1. Clone or download this GitHub repo.
2. [Create an Event Hubs namespace and an event hub](event-hubs-quickstart-namespace-portal.md).
3. In Visual Studio, select **File**, then **Open Project/Solution**. Navigate to the \azure-event-hubs\samples\DotNet\Microsoft.Azure.EventHubs\SampleEphReceiver folder.
4. Load the SampleEphReceiver.sln solution file into Visual Studio.
5. Add the [Microsoft.Azure.EventHubs](https://www.nuget.org/packages/Microsoft.Azure.EventHubs/) and [Microsoft.Azure.EventHubs.Processor](https://www.nuget.org/packages/Microsoft.Azure.EventHubs.Processor/) NuGet packages to the project.
6. In Program.cs, replace the following constants with the corresponding values for the event hub connection string, event hub name:
```csharp
private const string EventHubConnectionString = "Event Hubs connection string";
private const string EventHubName = "Event Hub name";
```
7. Create a Storage account to host a blob container, needed for lease management by the Event Processor Host.
8. In Program.cs, replace the storage account container name, storage account name, and storage account key (the container will be created if not present):
```
private const string StorageContainerName = "Storage account container name";
private const string StorageAccountName = "Storage account name";
private const string StorageAccountKey = "Storage account key";
```
9. Run the program, and ensure that there are no errors.
Congratulations! You have now received events from an event hub by using the Event Processor Host. To send events, see the [SampleSender](https://github.com/Azure/azure-event-hubs/tree/master/samples/DotNet/Microsoft.Azure.EventHubs/SampleSender) sample.

Просмотреть файл

@ -0,0 +1,69 @@
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.2"/>
</startup>
<appSettings>
<add key="tenantId" value=""/>
<add key="clientId" value=""/>
<add key="eventHubNamespaceFQDN" value=""/>
<add key="eventHubName" value=""/>
<add key="thumbPrint" value=""/>
<add key="clientSecret" value=""/>
<add key="userName" value=""/>
<add key="password" value=""/>
</appSettings>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="Microsoft.IdentityModel.Clients.ActiveDirectory" publicKeyToken="31bf3856ad364e35" culture="neutral"/>
<bindingRedirect oldVersion="0.0.0.0-3.19.8.16603" newVersion="3.19.8.16603"/>
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.IdentityModel.Clients.ActiveDirectory.Platform" publicKeyToken="31bf3856ad364e35" culture="neutral"/>
<bindingRedirect oldVersion="0.0.0.0-3.19.8.16603" newVersion="3.19.8.16603"/>
</dependentAssembly>
</assemblyBinding>
</runtime>
<system.serviceModel>
<extensions>
<!-- In this extension section we are introducing all known service bus extensions. User can remove the ones they don't need. -->
<behaviorExtensions>
<add name="connectionStatusBehavior"
type="Microsoft.ServiceBus.Configuration.ConnectionStatusElement, Microsoft.ServiceBus, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
<add name="transportClientEndpointBehavior"
type="Microsoft.ServiceBus.Configuration.TransportClientEndpointBehaviorElement, Microsoft.ServiceBus, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
<add name="serviceRegistrySettings"
type="Microsoft.ServiceBus.Configuration.ServiceRegistrySettingsElement, Microsoft.ServiceBus, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
</behaviorExtensions>
<bindingElementExtensions>
<add name="netMessagingTransport"
type="Microsoft.ServiceBus.Messaging.Configuration.NetMessagingTransportExtensionElement, Microsoft.ServiceBus, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
<add name="tcpRelayTransport"
type="Microsoft.ServiceBus.Configuration.TcpRelayTransportElement, Microsoft.ServiceBus, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
<add name="httpRelayTransport"
type="Microsoft.ServiceBus.Configuration.HttpRelayTransportElement, Microsoft.ServiceBus, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
<add name="httpsRelayTransport"
type="Microsoft.ServiceBus.Configuration.HttpsRelayTransportElement, Microsoft.ServiceBus, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
<add name="onewayRelayTransport"
type="Microsoft.ServiceBus.Configuration.RelayedOnewayTransportElement, Microsoft.ServiceBus, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
</bindingElementExtensions>
<bindingExtensions>
<add name="basicHttpRelayBinding"
type="Microsoft.ServiceBus.Configuration.BasicHttpRelayBindingCollectionElement, Microsoft.ServiceBus, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
<add name="webHttpRelayBinding"
type="Microsoft.ServiceBus.Configuration.WebHttpRelayBindingCollectionElement, Microsoft.ServiceBus, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
<add name="ws2007HttpRelayBinding"
type="Microsoft.ServiceBus.Configuration.WS2007HttpRelayBindingCollectionElement, Microsoft.ServiceBus, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
<add name="netTcpRelayBinding"
type="Microsoft.ServiceBus.Configuration.NetTcpRelayBindingCollectionElement, Microsoft.ServiceBus, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
<add name="netOnewayRelayBinding"
type="Microsoft.ServiceBus.Configuration.NetOnewayRelayBindingCollectionElement, Microsoft.ServiceBus, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
<add name="netEventRelayBinding"
type="Microsoft.ServiceBus.Configuration.NetEventRelayBindingCollectionElement, Microsoft.ServiceBus, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
<add name="netMessagingBinding"
type="Microsoft.ServiceBus.Messaging.Configuration.NetMessagingBindingCollectionElement, Microsoft.ServiceBus, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
</bindingExtensions>
</extensions>
</system.serviceModel>
</configuration>

Просмотреть файл

@ -0,0 +1,3 @@
# Role based access sample #
For more information on Role based access (RBAC) and how to run this sample follow [this](https://docs.microsoft.com/en-us/azure/event-hubs/event-hubs-role-based-access-control) link.