Skip to content

Instantly share code, notes, and snippets.

@jasonmitchell
Last active November 24, 2016 22:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jasonmitchell/92b23be8e914bf6b91dc4ec87e0c1635 to your computer and use it in GitHub Desktop.
Save jasonmitchell/92b23be8e914bf6b91dc4ec87e0c1635 to your computer and use it in GitHub Desktop.
[Fact]
public async Task ReadsEventsFromStream()
{
// Create a connection to the embedded event store.
using (var connection = EmbeddedEventStoreConnection.Create(_node, _connectionSettingsBuilder))
{
// Write some events - omitted for clarity
// When reading from a stream you can specify the start position and how many events to read.
// The maximum number of events that can be read in one call is 4096 to large streams would require reading in pages.
var eventsInStream = await connection.ReadStreamEventsForwardAsync("test_stream", StreamPosition.Start, 4096, true);
Assert.Equal(3, eventsInStream.Events.Length);
}
}
public class SomeEvent
{
public SomeEvent(Guid a, int b, string c)
{
A = a;
B = b;
C = c;
}
public Guid A { get; }
public int B { get; }
public string C { get; }
}
[Fact]
public async Task WritesEventsToStream()
{
// Create a connection to the embedded event store.
using (var connection = EmbeddedEventStoreConnection.Create(_node, _connectionSettingsBuilder))
{
// Events can have metadata associated with them.
// I like to include a Guid as a commit id to link events saved at the same time.
var commitMetadata = new Dictionary<string, object> {{"CommitId", Guid.NewGuid()}};
var events = new[]
{
new SomeEvent(Guid.NewGuid(), 1, "One"),
new SomeEvent(Guid.NewGuid(), 2, "Two"),
new SomeEvent(Guid.NewGuid(), 3, "Three"),
};
// Events and metadata need to be wrapped in an EventData instance
var eventData = events.Select(e => ToEventData(Guid.NewGuid(), e, commitMetadata)).ToList();
// An expected stream version can be provided as a concurrency check.
// This example allows any stream version but later examples will make use of this.
await connection.AppendToStreamAsync("test_stream", ExpectedVersion.Any, eventData);
}
}
// Serialise a single event and its metadata and create an instance of EventData
private static EventData ToEventData(Guid eventId, object e, IDictionary<string, object> metadata)
{
var encodedEvent = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(e));
var encodedMetadata = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(metadata));
var typeName = e.GetType().Name;
return new EventData(eventId, typeName, true, encodedEvent, encodedMetadata);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment