Skip to content
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
43 changes: 15 additions & 28 deletions sdk/eventhub/event-hubs/samples/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ The samples in this folder are for version 5.0.0 and above of this library. If y

Run the below in your samples folder to install the npm package for Event Hubs library.
```bash
npm install @azure/event-hubs@next
npm install
```

## Get connection string & Event Hubs name
Expand All @@ -20,35 +20,22 @@ npm install @azure/event-hubs@next

Before running a sample, update it with the connection string and the Event Hub name you have noted above.

## Running a sample
## Running samples

Start by copying the sample into a npm project.
```bash
mkdir event-hubs-samples
cd event-hubs-samples
npm init
# copy sample into this directory
```
1. Copy this folder to your machine.
2. Install dependencies for the samples project.

```bash
npm install
```

If you don't have Typescript installed, then use `npm` to install it first.
```bash
npm install -g typescript
```

Install the `@azure/event-hubs@next` package into your project, as well as any other dependencies you might need.
```bash
npm install --save @azure/event-hubs@next
```

One way to run Typescript samples is to use `ts-node`. To install `ts-node`, run the below in your sample folder
```bash
npm install ts-node
```

Use `ts-node` to run the sample copied previously.
```bash
ts-node sample.ts
```
3. Rename the `sample.env` file to `.env`
4. Open the `.env` file in a text editor and fill in values related to the
sample you'd like to run.
5. Run the samples:

```bash
npm run samples
```

![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-js%2Fsdk%2Feventhub%2Fevent-hubs%2Fsamples%2FREADME.png)
41 changes: 41 additions & 0 deletions sdk/eventhub/event-hubs/samples/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
{
"name": "azure-event-hubs-samples",
Comment thread
richardpark-msft marked this conversation as resolved.
"private": true,
"version": "1.0.0",
"description": "The samples in this folder are for version 5.0.0 and above of this library. If you are using version 2.1.0 or lower, then please use [samples for v2.1.0](https://github.com/Azure/azure-sdk-for-js/tree/%40azure/event-hubs_2.1.0/sdk/eventhub/event-hubs/samples) instead",
"main": "dist-esm/runsamples.js",
"scripts": {
"samples": "ts-node ./runsamples.ts",
"build": "tsc -p ."
},
"keywords": [
"Azure",
"EventHubs",
"CheckpointStore",
"Node.js",
"TypeScript"
],
"author": "Microsoft Corporation",
"license": "MIT",
"bugs": {
"url": "https://github.com/Azure/azure-sdk-for-js/issues"
},
"homepage": "https://github.com/Azure/azure-sdk-for-js#readme",
"devDependencies": {
"ts-node": "^8.5.4",
"typescript": "^3.7.2",
"@types/node": "^12.12.17"
},
"dependencies": {
Comment thread
richardpark-msft marked this conversation as resolved.
"@azure/core-amqp": "next",
Comment thread
richardpark-msft marked this conversation as resolved.
"@azure/event-hubs": "next",
"@azure/eventhubs-checkpointstore-blob": "next",
"@types/dotenv": "^8.2.0",
"@types/ws": "^6.0.4",
"dotenv": "^8.2.0",
"https-proxy-agent": "^3.0.1",
"rhea-promise": "^1.0.0",
"tslib": "^1.9.3",
"ws": "^7.2.0"
}
}
25 changes: 12 additions & 13 deletions sdk/eventhub/event-hubs/samples/receiveEvents.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,15 +12,18 @@
https://github.com/Azure/azure-sdk-for-js/tree/%40azure/event-hubs_2.1.0/sdk/eventhub/event-hubs/samples instead.
*/

import { runSample, cleanupAfterWaiting } from './sampleHelpers';
import {
EventHubConsumerClient
} from "@azure/event-hubs";

const connectionString = "";
const eventHubName = "";
const consumerGroup = "";
const connectionString = process.env["EVENTHUB_CONNECTION_STRING"] || "";
const eventHubName = process.env["EVENTHUB_NAME"] || "";
const consumerGroup = process.env["CONSUMER_GROUP_NAME"] || "";

async function main() {
export async function main() {
console.log(`Running receiveEvents sample`);

const consumerClient = new EventHubConsumerClient(consumerGroup, connectionString, eventHubName);

const subscription = consumerClient.subscribe({
Expand All @@ -37,16 +40,12 @@ async function main() {
}
});

// after 30 seconds, stop processing
await new Promise((resolve) => {
setTimeout(async () => {
await cleanupAfterWaiting(async () => {
await subscription.close();
await consumerClient.close();
resolve();
}, 30000);
});
}, 30);

Comment thread
chradek marked this conversation as resolved.
console.log(`Exiting receiveEvents sample`);
}

main().catch((err) => {
console.log("Error occurred: ", err);
});
runSample(main);
Original file line number Diff line number Diff line change
Expand Up @@ -16,31 +16,33 @@
https://github.com/Azure/azure-sdk-for-js/tree/%40azure/event-hubs_2.1.0/sdk/eventhub/event-hubs/samples instead.
*/

import { runSample, cleanupAfterWaiting } from './sampleHelpers';
import {
EventHubConsumerClient, CheckpointStore,
} from "@azure/event-hubs";

import { ContainerClient } from "@azure/storage-blob";
import { BlobCheckpointStore } from "@azure/eventhubs-checkpointstore-blob";

const connectionString = "";
const eventHubName = "";
const storageConnectionString = "";
const containerName = "";
const consumerGroup = "";
const connectionString = process.env["EVENTHUB_CONNECTION_STRING"] || "";
const eventHubName = process.env["EVENTHUB_NAME"] || "";
const consumerGroup = process.env["CONSUMER_GROUP_NAME"] || "";
const storageConnectionString = process.env["STORAGE_CONNECTION_STRING"] || "";
const containerName = process.env["STORAGE_CONTAINER_NAME"] || "";

export async function main() {
console.log(`Running receiveEventsUsingCheckpointStore sample`);

async function main() {
// this client will be used by our eventhubs-checkpointstore-blob, which
// persists any checkpoints from this session in Azure Storage
const containerClient = new ContainerClient(storageConnectionString, containerName);

if (!containerClient.exists()) {
if (!(await containerClient.exists())) {
await containerClient.create();
}

const checkpointStore : CheckpointStore = new BlobCheckpointStore(containerClient);


const consumerClient = new EventHubConsumerClient(consumerGroup, connectionString, eventHubName, checkpointStore);

const subscription = consumerClient.subscribe({
Expand All @@ -58,7 +60,7 @@ async function main() {
};

console.log(
`Successfully checkpointed event with sequence number: ${events[events.length - 1].sequenceNumber} from partition: 'partitionContext.partitionId'`
`Successfully checkpointed event with sequence number: ${events[events.length - 1].sequenceNumber} from partition: '${context.partitionId}'`
);
},
processError: async (err, context) => {
Expand All @@ -68,15 +70,13 @@ async function main() {
);

// after 30 seconds, stop processing
await new Promise((resolve) => {
setTimeout(async () => {
await subscription.close();
await consumerClient.close();
resolve();
}, 30000);
});
await cleanupAfterWaiting(async () => {
await subscription.close();
await consumerClient.close();
}, 30);

console.log(`Exiting receiveEventsUsingCheckpointStore sample`);
}

main().catch((err) => {
console.log("Error occurred: ", err);
});
runSample(main);

30 changes: 30 additions & 0 deletions sdk/eventhub/event-hubs/samples/runsamples.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

import * as dotenv from "dotenv";
Comment thread
richardpark-msft marked this conversation as resolved.

dotenv.config();
Comment thread
richardpark-msft marked this conversation as resolved.

// don't have the samples execute - we'll run them manually in `main` below
process.env["DO_NOT_EXECUTE_SAMPLE"] = "1";

import { main as sendEventsMain } from "./sendEvents";
import { main as receiveEventsMain } from "./receiveEvents";
import { main as receiveEventsUsingCheckpointStoreMain } from "./receiveEventsUsingCheckpointStore";
import { main as useWithIotHubMain } from "./useWithIotHub";
import { main as usingAadAuthMain } from "./usingAadAuth";
import { main as websocketsMain } from "./websockets";

async function main() {
Comment thread
richardpark-msft marked this conversation as resolved.
await sendEventsMain();
await receiveEventsMain();
await receiveEventsUsingCheckpointStoreMain();
await useWithIotHubMain();
await usingAadAuthMain();
await websocketsMain();
}

main().catch(err => {
console.log(err);
process.exit(1);
})
28 changes: 28 additions & 0 deletions sdk/eventhub/event-hubs/samples/sample.env
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
# Used in most samples
EVENTHUB_CONNECTION_STRING=<connection string WITHOUT an EntityPath>
EVENTHUB_NAME=<name of a single eventhub>
EVENTHUB_FQDN=<your-eventhubs-namespace>.servicebus.windows.net
CONSUMER_GROUP_NAME=<name of a consumer group>

# Used in the receiveEventsUsingCheckpointStore.ts sample
STORAGE_CONTAINER_NAME=<storage account connection string for checkpoints>

# Used in the useWithIotHub.ts sample
IOTHUB_CONNECTION_STRING=<connection string with EntityPath>

# Used in the usingAadAuth.ts sample
# Setup :
# Please ensure that your Azure Event Hubs resource is in US East, US East 2, or West Europe
# region. AAD Role Based Access Control is not supported in other regions yet.
# Register a new application in AAD and assign the "Azure Event Hubs Data Owner (Preview)" role to it
# - See https://docs.microsoft.com/en-us/azure/active-directory/develop/quickstart-register-app
# to register a new application in the Azure Active Directory.
# - Note down the CLIENT_ID and TENANT_ID from the above step.
# - In the "Certificates & Secrets" tab, create a secret and note that down.
# - In the Azure portal, go to your Even Hubs resource and click on the Access control (IAM)
# tab. Here, assign the "Azure Event Hubs Data Owner (Preview)" role to the registered application.
# - For more information on Event Hubs RBAC setup, learn more at
# https://docs.microsoft.com/en-us/azure/event-hubs/event-hubs-role-based-access-control)
AZURE_CLIENT_ID=
AZURE_TENANT_ID=
AZURE_CLIENT_SECRET=
42 changes: 42 additions & 0 deletions sdk/eventhub/event-hubs/samples/sampleHelpers.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

import * as dotenv from "dotenv";

// initialize using the .env file in the current folder
dotenv.config();

/**
* Runs the async sample function, exiting if needed if it fails.
* @param main The 'main' function for the sample.
*/
export function runSample(main: () => Promise<void>) {
if (process.env["DO_NOT_EXECUTE_SAMPLE"]) {
return Promise.resolve();
}

return main().catch((err) => {
console.log("Error occurred: ", err);
process.exit(1);
});
}

/**
* Runs your cleanupFn after waiting for `timeToWaitInSeconds` seconds
* @param cleanupFn Cleanup function to run.
* @param timeToWaitInSeconds Seconds to wait.
*/
export function cleanupAfterWaiting(cleanupFn: () => Promise<void>, timeToWaitInSeconds: number): Promise<void> {
return new Promise((resolve, reject) => {
console.log(`Waiting for ${timeToWaitInSeconds} seconds...`)

setTimeout(async () => {
try {
await cleanupFn();
resolve();
} catch (err) {
reject(err);
}
}, timeToWaitInSeconds * 1000);
});
}
Loading