Quick tour
This is a quick tour into the basic operations with EventStoreDB using the TCP client. We will look at creating a connection, appending an event and reading an event.
WARNING
The TCP client is considered legacy. We recommend migrating to the latest client. Check the migration guide to learn more.
Requirements
These examples have the following requirements:
- At least .NET Core SDK 3.1
- Docker
- A reference to the EventStore.Client NuGet package
Run the server
To run the EventStoreDB, create a new file called docker-compose.yml
and copy the following contents into it:
version: '3.7'
services:
eventstore:
container_name: esdb-docs
image: eventstore/eventstore:23.10.1-bookworm-slim
ports:
- '2113:2113'
- '1113:1113'
environment:
EVENTSTORE_EXT_HTTP_PORT: 2113
EVENTSTORE_EXT_TCP_PORT: 1113
EVENTSTORE_RUN_PROJECTIONS: all
EVENTSTORE_START_STANDARD_PROJECTIONS: 'true'
PROJECTION_THREADS: 8
Then run the command.
docker-compose up
This will launch a new instance of the EventStoreDB server.
Connect to EventStoreDB
Install the .NET client API package to your project using your preferred method.
And require it in your code:
using EventStore.ClientAPI;
using EventStore.ClientAPI.Projections;
using EventStore.ClientAPI.SystemData;
To use a client API, you use port 1113
and create a connection:
var connection = EventStoreConnection.Create(
new Uri("tcp://admin:changeit@localhost:1113")
);
await connection.ConnectAsync();
It will create a connection to EventStoreDB running locally in Docker container using the TCP protocol.
Appending events
The most basic operation is to append a single event to the database:
const string streamName = "newstream";
const string eventType = "event-type";
const string data = "{ \"a\":\"2\"}";
const string metadata = "{}";
var eventPayload = new EventData(
eventId: Guid.NewGuid(),
type: eventType,
isJson: true,
data: Encoding.UTF8.GetBytes(data),
metadata: Encoding.UTF8.GetBytes(metadata)
);
var result = await conn.AppendToStreamAsync(streamName, ExpectedVersion.Any, eventPayload);
Reading events
After you wrote an event to the database, you can then read it back. Use the following method passing the stream name, the start point in the stream, the number of events to read and whether to follow links to the event data:
var readEvents = await conn.ReadStreamEventsForwardAsync(streamName, 0, 10, true);
foreach (var evt in readEvents.Events)
{
Console.WriteLine(Encoding.UTF8.GetString(evt.Event.Data));
}