private static void AppendToStream(IEventStoreConnection connection) { byte[] data = Encoding.UTF8.GetBytes("event data"); byte[] metadata = Encoding.UTF8.GetBytes("event metadata"); EventData eventData = new EventData(Guid.NewGuid(), "testEvent", false, data, metadata); connection.AppendToStreamAsync("test-stream", ExpectedVersion.Any, eventData).Wait(); }
private void Connect() { var settings = ConnectionSettings.Create(); var ip = new IPEndPoint(_ipAddress, _port); Log("Connecting to {0}:{1}...", _ipAddress, _port); _connection = EventStoreConnection.Create(settings, ip); _connection.ConnectAsync(); _connection.AppendToStreamAsync("hello", ExpectedVersion.Any, new EventData(Guid.NewGuid(), "Hello", false, new byte[0], new byte[0])); Log("Connected."); Log("Username to be used is: {0}", _userName); _credentials = new UserCredentials(_userName, _password); }
public override void SetUp() { base.SetUp(); _node = new MiniNode(PathName); _node.Start(); _connection = TestConnection.Create(_node.TcpEndPoint); _connection.ConnectAsync().Wait(); _connection.SetStreamMetadataAsync(Stream, ExpectedVersion.EmptyStream, StreamMetadata.Build().SetMaxCount(3)).Wait(); _testEvents = Enumerable.Range(0, 5).Select(x => TestEvent.NewTestEvent(data: x.ToString())).ToArray(); _connection.AppendToStreamAsync(Stream, ExpectedVersion.EmptyStream, _testEvents).Wait(); }
protected override void Given() { _serverEndPoint = new IPEndPoint(IPAddress.Loopback, PortsHelper.GetAvailablePort(IPAddress.Loopback)); _url = _HttpEndPoint.ToHttpUrl("/stats/tcp"); var settings = ConnectionSettings.Create(); _connection = EventStoreConnection.Create(settings, _node.TcpEndPoint); _connection.ConnectAsync().Wait(); var testEvent = new EventData(Guid.NewGuid(),"TestEvent",true,Encoding.ASCII.GetBytes("{'Test' : 'OneTwoThree'}"),null); _connection.AppendToStreamAsync("tests",ExpectedVersion.Any,testEvent).Wait(); _portableServer = new PortableServer(_serverEndPoint); _portableServer.SetUp(); }
public override void TestFixtureSetUp() { base.TestFixtureSetUp(); _node = new MiniNode(PathName, inMemDb: true); _node.Start(); _conn = BuildConnection(_node); _conn.ConnectAsync().Wait(); //Create 80000 events for(var i = 0; i < 80; i++) { _conn.AppendToStreamAsync(_streamName, ExpectedVersion.Any, CreateThousandEvents()).Wait(); } _settings = new CatchUpSubscriptionSettings(100, 1, false, true); }
public async Task <long> SaveAsync <TEntity>(IList <TEntity> entities, Guid correlationId, Func <TEntity, EventData> eventFactory) { var sent = 0; for (var page = 0; page < 1 + entities.Count() / _pageSize; ++page) { var events = entities .Skip(page * _pageSize) .Take(_pageSize) .Select(eventFactory) .ToList(); await _connection.AppendToStreamAsync("Portfolio", ExpectedVersion.Any, events); sent += events.Count; } return(sent); }
private async Task AppendOrderPreparedEvent(OrderCheckpoint orderCheckpoint) { var jsonStr = JsonConvert.SerializeObject(new { isPrepared = true }); var jsonBytes = Encoding.UTF8.GetBytes(jsonStr); await _esConnection.AppendToStreamAsync( $"order-{orderCheckpoint.OrderId}", orderCheckpoint.LastProcessedEventNumber, new EventData( Guid.NewGuid(), "OrderPrepared", true, jsonBytes, null)); }
public void SaveEvents(AggregateKey key, int expectedRevision, IEnumerable <DomainEvent> uncommittedEvents) { var commitHeaders = new Dictionary <string, object> { { CommitIdHeader, Guid.NewGuid() }, { AggregateClrTypeHeader, key.AggregateType.AssemblyQualifiedName } }; var streamName = _aggregateIdToStreamName(key.AggregateType, key.AggregateId); var newEvents = uncommittedEvents.Cast <object>().ToList(); var expectedVersion = expectedRevision <= 0 ? ExpectedVersion.NoStream : expectedRevision - 1; expectedVersion = ExpectedVersion.Any; var preparedEvents = PrepareEvents(newEvents, commitHeaders).ToList(); if (preparedEvents.Count < WritePageSize) { _eventStoreConnection .AppendToStreamAsync(streamName, expectedVersion, preparedEvents) .Wait(); } else { var transaction = _eventStoreConnection .StartTransactionAsync(streamName, expectedVersion) .Result; var position = 0; while (position < preparedEvents.Count) { var pageEvents = preparedEvents.Skip(position).Take(WritePageSize); transaction.WriteAsync(pageEvents).Wait(); position += WritePageSize; } transaction.CommitAsync().Wait(); } foreach (var @event in uncommittedEvents) { _publisher.Publish(@event); } }
public static async Task Maines() { var eventStream = "NetSuiteRevStream"; var eventtype = "NetSuiteRev"; var eventgroup = "ZoneSwitch"; //var conn = EventStoreConnection.Create(new Uri("tcp://*****:*****@localhost:1113")); //var conn = EventStoreConnection.Create(new Uri("wrong!!")); ConnectToEventStore(); //await _connection.ConnectAsync(); //var data = Encoding.UTF8.GetBytes("{\"a\":\"2\"}"); var data = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject( new NetSuiteRevEventData { Amount = 2, IsForAccount = true, BankCode = "025", BillingWindow = "BillingWindow - data", DateCreated = DateTime.Now, IsDeducted = true, Id = new Random(int.MaxValue).Next(), IsForCard = true, ReportGenerated = 3, SettlementBillingWindow = "try this" })); //var metadata = Encoding.UTF8.GetBytes("{}"); var metadata = Encoding.UTF8.GetBytes("{NetSuiteData:Netsuite data}"); var evt = new EventData(Guid.NewGuid(), eventtype, true, data, metadata); await _connection.AppendToStreamAsync(eventStream, ExpectedVersion.Any, evt); var streamEvents = await _connection.ReadStreamEventsForwardAsync(eventtype, 0, 1, false); var returnedEvent = streamEvents.Events[0].Event; Console.WriteLine( "Read event with data: {0}, metadata: {1}", Encoding.UTF8.GetString(returnedEvent.Data), Encoding.UTF8.GetString(returnedEvent.Metadata) ); }
/// <summary> /// Adds the events. /// </summary> /// <param name="eventStoreConnection">The event store connection.</param> /// <param name="stream">The stream.</param> /// <param name="numberOfEvents">The number of events.</param> private static async Task AddEvents(IEventStoreConnection eventStoreConnection, String stream, Int32 numberOfEvents) { List <EventData> events = new List <EventData>(); var @event = new { id = Guid.NewGuid() }; String json = JsonConvert.SerializeObject(@event); for (Int32 i = 0; i < numberOfEvents; i++) { events.Add(new EventData(Guid.NewGuid(), "AddedEvent", true, Encoding.Default.GetBytes(json), null)); } await eventStoreConnection.AppendToStreamAsync(stream, -2, events); }
public void Persist <TIdentity>(TIdentity identity, IReadOnlyCollection <EventEnvelope> events, int expectedVersion) where TIdentity : Identity { var eventData = events .Select(envelope => { var eventJsonBinary = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(envelope.Event)); var metadataJsonBinary = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(envelope.Metadata)); var eventType = envelope.Event.GetType().AssemblyQualifiedName; var messageIdentity = new { envelope.Metadata.DispatchedMessageId, envelope.Event }.ToGuid(); return(new EventData(messageIdentity, eventType, true, eventJsonBinary, metadataJsonBinary)); }) .ToList(); _eventStoreConnection.AppendToStreamAsync(identity.ToStringRepresentation(), expectedVersion, eventData).Wait(); //var transaction = _eventStoreConnection.StartTransactionAsync(identity.ToStringRepresentation(), expectedVersion).Result; //transaction.WriteAsync(eventData).Wait(); //transaction.CommitAsync().Wait(); }
public void SaveEvents <T>(Guid aggregateId, IEnumerable <Event> events, int expectedVersion) where T : AggregateRoot { try { var _ = Connection.AppendToStreamAsync(GetAggregateStreamName(typeof(T).FullName, aggregateId), expectedVersion, events.Select(x => _eventSerializer.CreateEvent(x.GetType().FullName, x))).Result; } catch (AggregateException ae) when(ae.InnerException is WrongExpectedVersionException) { throw new ConcurrencyException(); } foreach (var @event in events) { // publish current event to the bus for further processing by subscribers _publisher.Publish(@event); } }
public async Task AppendEvents(string id, IEnumerable <object> events, long expectedVersion) { await _connection.AppendToStreamAsync(id, expectedVersion - 1, CreateEvents()); IEnumerable <EventData> CreateEvents() { foreach (var domainEvent in events) { var @event = new EventData( Guid.NewGuid(), domainEvent.GetType().Name, true, domainEvent.ToJson().ToBytes(), new EventMetadata(domainEvent.GetType().AssemblyQualifiedName).ToJson().ToBytes() ); yield return(@event); } } }
protected override void Given() { _serverPort = PortsHelper.GetAvailablePort(IPAddress.Loopback); _serverEndPoint = new IPEndPoint(IPAddress.Loopback, _serverPort); _url = _HttpEndPoint.ToHttpUrl(EndpointExtensions.HTTP_SCHEMA, "/stats/tcp"); var settings = ConnectionSettings.Create(); _connection = EventStoreConnection.Create(settings, _node.TcpEndPoint, _clientConnectionName); _connection.ConnectAsync().Wait(); var testEvent = new EventData(Guid.NewGuid(), "TestEvent", true, Encoding.ASCII.GetBytes("{'Test' : 'OneTwoThree'}"), null); _connection.AppendToStreamAsync("tests", ExpectedVersion.Any, testEvent).Wait(); _portableServer = new PortableServer(_serverEndPoint); _portableServer.SetUp(); }
public async Task Method() { #region appendEvent 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); #endregion appendEvent }
public static async Task <int> SaveEvents(this IEventStoreConnection connection, string streamIdentifier, IEnumerable <object> events, int expectedVersion = ExpectedVersion.Any, object metadata = null) { var esEvents = events .Select(x => new EventData( Guid.NewGuid(), TypeMapping.GetTypeName(x.GetType()), true, JsonSerialisation.Serialize(x), JsonSerialisation.Serialize(metadata))); var result = await connection.AppendToStreamAsync(streamIdentifier, expectedVersion, esEvents); return(result.NextExpectedVersion); }
public async Task <HttpResponseMessage> Post(OuroSearchRequest request) { var id = Guid.NewGuid(); var resultStream = string.Format("searchresult-{0}", id.ToString("N")); var responseUri = string.Format("search-result/{0}", id.ToString("N")); //This will set the stream ACL to allow reads from all but only writes from //the admins group. With more secure data you may limit reads only to the user //that made the request and likely a backenduser who is likely not a member //of the $admins group for security purposes. // //await _eventStoreConnection.SetStreamMetadataAsync(resultStream, // ExpectedVersion.EmptyStream, // StreamMetadata.Build() // .SetMaxAge(TimeSpan.FromDays(90)) // .SetWriteRole("backenduser") // .SetReadRole(Request.User), // new UserCredentials("backenduser", "password")); // //This code also sets an expiration on the stream of 5 minutes. More than //likely in a production system you would not want such a short expiration //this is more so to be able to show the functionality of expiring the //results over time in a way that can actually be demoed. In most such //systems this would likely be months or possibly even never due to //operational needs of being able to see what happened with a given //request. await _eventStoreConnection.SetStreamMetadataAsync(resultStream, ExpectedVersion.EmptyStream, StreamMetadata.Build() .SetMaxAge(TimeSpan.FromMinutes(5)) .SetWriteRole("$admins") .SetReadRole("$all"), new UserCredentials("admin", "changeit")); await _eventStoreConnection.AppendToStreamAsync("incoming", ExpectedVersion.Any, request.ToEvent(resultStream).ToEventData("searchRequested")); var response = new HttpResponseMessage(HttpStatusCode.Accepted); response.Headers.Location = new Uri(responseUri, UriKind.Relative); return(response); }
protected override void SaveAggregate(Aggregate aggregate, Guid transactionId) { //Taken from https://github.com/pgermishuys/getting-started-with-event-store/blob/master/src/GetEventStoreRepository/GetEventStoreRepository.cs var commitHeaders = new Dictionary <string, object> { { CommitIdHeader, transactionId }, { AggregateClrTypeHeader, aggregate.GetType().AssemblyQualifiedName } }; IList <Event> newEvents = aggregate.GetUncommittedEvents(); int originalVersion = aggregate.Version - newEvents.Count; int expectedVersion = originalVersion; //http://stackoverflow.com/a/20204729 if (originalVersion == 0) { expectedVersion = ExpectedVersion.NoStream; } IEnumerable <EventData> eventsToSave = newEvents.Select(e => ToEventData(Guid.NewGuid(), e, commitHeaders)); string streamName = GetStreamName(aggregate.GetType(), aggregate.Id); if (eventsToSave.Count() < WritePageSize) { connection.AppendToStreamAsync(streamName, ExpectedVersion.Any, eventsToSave).Wait(); } else { var transaction = connection.StartTransactionAsync(streamName, expectedVersion).Result; var position = 0; while (position < eventsToSave.Count()) { var pageEvents = eventsToSave.Skip(position).Take(WritePageSize); transaction.WriteAsync(pageEvents).Wait(); position += WritePageSize; } transaction.CommitAsync().Wait(); } aggregate.ClearUncommittedEvents(); }
protected override async Task <IImmutableList <Exception> > WriteMessagesAsync( IEnumerable <AtomicWrite> atomicWrites) { var results = new List <Exception>(); foreach (var atomicWrite in atomicWrites) { var persistentMessages = (IImmutableList <IPersistentRepresentation>)atomicWrite.Payload; var persistenceId = atomicWrite.PersistenceId; var lowSequenceId = persistentMessages.Min(c => c.SequenceNr) - 2; try { var events = persistentMessages .Select(persistentMessage => _eventAdapter.Adapt(persistentMessage)).ToArray(); var pendingWrite = new { StreamId = persistenceId, ExpectedSequenceId = lowSequenceId, EventData = events, debugData = persistentMessages }; var expectedVersion = pendingWrite.ExpectedSequenceId < 0 ? ExpectedVersion.NoStream : (int)pendingWrite.ExpectedSequenceId; await _conn.AppendToStreamAsync(pendingWrite.StreamId, expectedVersion, pendingWrite.EventData); results.Add(null); } catch (Exception e) { results.Add(TryUnwrapException(e)); } } return(results.ToImmutableList()); }
/// <summary> /// Appends event to the event stream /// </summary> /// <param name="streamId">stream ID</param> /// <param name="version">version</param> /// <param name="events">events to append</param> /// <returns>async void task</returns> /// <exception cref="DuplicateTransitionException">When concurrency exception</exception> public async Task AppendEventsAsync(string streamId, int version, IEnumerable <IEvent> events) { var items = events.Select(x => _serializer.Serialize(x)); try { await Connection.AppendToStreamAsync(streamId, version, items, _credentials); } catch (WrongExpectedVersionException e) { throw new DuplicateTransitionException(streamId, version, e); } catch (AggregateException e) { if (e.InnerExceptions.Any(x => x is WrongExpectedVersionException)) { throw new DuplicateTransitionException(streamId, version, e); } } }
public async Task Save <T, TId>(T aggregate) where T : AggregateRoot <TId> where TId : Value <TId> { if (aggregate == null) { throw new ArgumentNullException(nameof(aggregate)); } var changes = GetChanges <T, TId>(aggregate).ToArray(); if (!changes.Any()) { return; } await connection.AppendToStreamAsync( GetStreamName <T, TId>(aggregate), aggregate.Version, changes); aggregate.ClearChanges(); }
/// <summary> /// Event store'a event gönderir /// </summary> /// <param name="aggregate"></param> /// <returns></returns> public async Task SaveAsync(T aggregate) { //ilgili event'leri alıyoruz, Event'ler eventstore'da EventData tipinde saklanır. var events = aggregate.GetChanges() .Select(c => new EventData( eventId: Guid.NewGuid(), type: c.GetType().Name, isJson: true, data: Encoding.UTF8.GetBytes(JsonSerializer.Serialize(c)), metadata: Encoding.UTF8.GetBytes(c.GetType().FullName)) // Eventleri deserialize ederken ilgili class'ı kullanmak için ilgili event'in class ismini verdik. ).ToArray(); if (!events.Any()) { return; } var streamName = $"{aggregate.GetType().Name}-{aggregate.Id}"; await _eventStore.AppendToStreamAsync(stream : streamName, expectedVersion : ExpectedVersion.Any, events : events); }
public async Task setting_metadata_for_existing_stream_works() { const string stream = "setting_metadata_for_existing_stream_works"; await _connection.AppendToStreamAsync(stream, ExpectedVersion.NoStream, TestEvent.NewTestEvent()); var metadata = StreamMetadata.Create(17, TimeSpan.FromSeconds(0xDEADBEEF), 10, TimeSpan.FromSeconds(0xABACABA)); await _connection.SetStreamMetadataAsync(stream, ExpectedVersion.NoStream, metadata); var meta = await _connection.GetStreamMetadataAsync(stream); Assert.AreEqual(stream, meta.Stream); Assert.AreEqual(false, meta.IsStreamDeleted); Assert.AreEqual(0, meta.MetastreamVersion); Assert.AreEqual(metadata.MaxCount, meta.StreamMetadata.MaxCount); Assert.AreEqual(metadata.MaxAge, meta.StreamMetadata.MaxAge); Assert.AreEqual(metadata.TruncateBefore, meta.StreamMetadata.TruncateBefore); Assert.AreEqual(metadata.CacheControl, meta.StreamMetadata.CacheControl); }
public async Task SaveAsync <T>(T aggregate) where T : Aggregate, new() { var events = aggregate.GetChanges() .Select(@event => new EventData( Guid.NewGuid(), @event.GetType().Name, true, Encoding.UTF8.GetBytes(JsonSerializer.Serialize(@event)), Encoding.UTF8.GetBytes(@event.GetType().FullName))) .ToArray(); if (!events.Any()) { return; } var streamName = GetStreamName(aggregate, aggregate.Id); var result = await _eventStore.AppendToStreamAsync(streamName, ExpectedVersion.Any, events); }
public override IEnumerable <IDomainEvent> Save <TAggregate>(TAggregate aggregate, bool isInitial = false) { var events = aggregate.UncommitedEvents().ToList(); //var expectedVersion = CalculateExpectedVersion(aggregate, events); var originalVersion = aggregate.Version - events.Count; var expectedVersion = originalVersion == -1 ? ExpectedVersion.NoStream : originalVersion; if (isInitial) { expectedVersion = ExpectedVersion.NoStream; } var eventData = events.Select(CreateEventData); var streamName = AggregateToStreamName(aggregate.GetType(), aggregate.AggregateId); connection.AppendToStreamAsync(streamName, expectedVersion, eventData); return(events); }
/// <summary> /// create stream for a Wallet /// </summary> /// <param name="connection">connection to ES</param> /// <param name="currency">ISO 3</param> /// <param name="accountHolder">Name of the Account owner</param> /// <param name="accountNr">Account Number</param> public static void CreateWalletStream(IEventStoreConnection connection, string currency, string accountHolder, string accountNr) { var streamName = $"acc-{(int)AccountTypes.Wallet}.{accountNr}".ToLower(); if (AccountManager.StreamExits(connection, streamName)) { return; } var genesisMutation = MutationEventManager.GenesisMutation(currency, accountHolder, streamName, AccountTypes.Wallet); // convert to json var json = Encoding.UTF8.GetBytes(Models.Mutation.ToJson(genesisMutation)); // create an event var myEvent = new EventData(Guid.Parse(genesisMutation.MutationId), EventTypes.CreatedWallet.ToString(), true, json, null); // Append Initial event connection.AppendToStreamAsync(streamName, -1, myEvent).Wait(); }
public async Task RaiseEvent <TAggregate>(TAggregate agg, params IEvent <TAggregate>[] events) where TAggregate : AggregateBase { await _conn.AppendToStreamAsync( agg.StreamId, agg.Version, events.Select(e => new EventData( Guid.NewGuid(), e.GetType().FullName, isJson: true, Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(e)), null ))); foreach (var @event in events) { @event.Apply(agg); await _bus.Publish(@event); } }
/// <summary> /// Inserts the events. /// </summary> /// <param name="streamName">Name of the stream.</param> /// <param name="expectedVersion">The expected version.</param> /// <param name="aggregateEvents">The aggregate events.</param> /// <returns></returns> public async Task InsertEvents(String streamName, Int32 expectedVersion, List <DomainEvent> aggregateEvents) { List <EventData> eventData = new List <EventData>(); JsonSerializerSettings s = new JsonSerializerSettings() { TypeNameHandling = TypeNameHandling.All }; IEventStoreConnection connection = await this.GetEventStoreConnection(); aggregateEvents.ForEach( @domainEvent => eventData.Add(new EventData(@domainEvent.EventId, @domainEvent.GetType().FullName, true, Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(@domainEvent, Formatting.None, s)), null))); await connection.AppendToStreamAsync(streamName, expectedVersion, eventData, this.UserCredentials); }
public override async Task Save( IAggregate aggregate, string bucketId, Guid commitId, Action <IDictionary <string, object> > updateHeaders, CancellationToken cancellationToken) { var changes = aggregate.TakeUncommittedEvents(); if (changes.Count == 0) { return; } if (changes.Count > PageSize) { throw new InvalidOperationException(string.Format("Number of events {0} exceeded the fixed page size {1}", changes.Count, PageSize)); } var streamId = aggregate.Id.FormatStreamIdWithBucket(bucketId); updateHeaders = updateHeaders ?? (_ => { }); var eventData = changes.Select(uncommittedEvent => { return(_serializer.SerializeEventData( uncommittedEvent.Event, uncommittedEvent.EventId, headers => { updateHeaders(headers); headers[EventMessageHeaders.CommitId] = commitId; })); }); var result = await _connection.AppendToStreamAsync(streamId, changes.OriginalVersion - 1, eventData).NotOnCapturedContext(); if (result.LogPosition == Position.End) { throw new Exception(); //TODO what is this? what are meant to do here / with this? } }
public async Task <long> SaveAsync(Aggregate aggregate, params KeyValuePair <string, string>[] extraHeaders) { var streamName = aggregate.Identifier.ToString(); var uncommittedEvents = aggregate.GetUncommittedEvents(); var originalVersion = aggregate.Version - uncommittedEvents.Count; try { WriteResult result; var commitHeaders = CreateCommitHeaders(aggregate, extraHeaders); var eventsToCommit = uncommittedEvents.Select(x => ToEventData(Guid.NewGuid(), x, commitHeaders)); var eventBatches = GetEventBatches(eventsToCommit); if (eventBatches.Count == 1) { result = await _eventStoreConnection.AppendToStreamAsync(streamName, originalVersion, eventBatches[0]); } else { using (var transaction = await _eventStoreConnection.StartTransactionAsync(streamName, originalVersion)) { foreach (var batch in eventBatches) { await transaction.WriteAsync(batch); } result = await transaction.CommitAsync(); } } aggregate.ClearUncommittedEvents(); return(result.NextExpectedVersion); } catch (Exception ex) { ExceptionDispatchInfo.Capture(ex).Throw(); } return(originalVersion + 1); }
public async Task SaveAsync <TAggregate>(TAggregate aggregate) where TAggregate : Aggregate { var commitHeaders = new Dictionary <string, object> { { CommitIdHeader, aggregate.Id }, { AggregateClrTypeHeader, aggregate.GetType().AssemblyQualifiedName } }; var streamName = AggregateIdToStreamName(aggregate.GetType(), aggregate.Id); var eventsToPublish = aggregate.GetUncommittedEvents(); var newEvents = eventsToPublish.Cast <object>().ToList(); var originalVersion = aggregate.Version - newEvents.Count(); var expectedVersion = originalVersion == -1 ? ExpectedVersion.NoStream : originalVersion; var eventsToSave = newEvents.Select(e => ToEventData(aggregate.Id, e, commitHeaders)).ToList(); if (eventsToSave.Count() < WritePageSize) { await eventStoreConnection.AppendToStreamAsync(streamName, expectedVersion, eventsToSave); } }
protected async void PostEvent(IGESEvent @event, Guid commitId, Dictionary <string, object> updateHeaders = null) { // standard data for metadata portion of persisted event var commitHeaders = new Dictionary <string, object> { // handy tracking id { CommitIdHeader, commitId }, { CommandClrTypeHeader, @event.GetType().AssemblyQualifiedName } }; // add extra data to metadata portion of presisted event commitHeaders = (updateHeaders ?? new Dictionary <string, object>()) .Concat(commitHeaders) .GroupBy(d => d.Key) .ToDictionary(d => d.Key, d => d.First().Value); // process command so they fit the expectations of GES var commandToSave = new[] { ToEventData(Guid.NewGuid(), @event, commitHeaders) }; // post to command stream await _eventStoreConnection.AppendToStreamAsync(EventStreamName, ExpectedVersion.Any, commandToSave); }
public static Task AppendEvents(this IEventStoreConnection connection, string streamName, long version, params object[] events) { if (events == null || !events.Any()) { return(Task.CompletedTask); } var preparedEvents = events .Select(@event => new EventData( eventId: Guid.NewGuid(), type: @event.GetType().Name, isJson: true, data: Serialize(@event), metadata: Serialize(new EventMetadata { CLRType = @event.GetType().AssemblyQualifiedName }) )).ToArray(); return(connection.AppendToStreamAsync(streamName, version, preparedEvents)); }
/// <summary> /// Adds the specified message. /// The message must have a 'streamId' and an 'eventNumber' in the message header bag. /// The 'streamId' is the name of the stream to append the message to. /// The 'eventNumber' should be one greater than the last event in the stream. /// </summary> /// <param name="message">The message.</param> /// <returns>Task.</returns> public void Add(Message message, int messageStoreTimeout = -1) { _logger.DebugFormat("Adding message to Event Store Message Store: {0}", JsonConvert.SerializeObject(message)); var eventBody = Encoding.UTF8.GetBytes(message.Body.Value); var headerBag = message.Header.Bag; var streamId = ExtractStreamIdFromHeader(headerBag, message.Id); var eventNumber = ExtractEventNumberFromHeader(headerBag, message.Id); var header = IdempotentlyRemoveEventStoreHeaderItems(headerBag); var headerBagJson = JsonConvert.SerializeObject(header, new KeyValuePairConverter()); var eventHeader = Encoding.UTF8.GetBytes(headerBagJson); var eventData = new[] { new EventData(message.Id, message.Header.Topic, true, eventBody, eventHeader) }; var numberOfPreviousEvent = eventNumber - 1; _eventStore.AppendToStreamAsync(streamId, numberOfPreviousEvent, eventData).Wait(); }
public override void SetUp() { base.SetUp(); _node = new MiniNode(PathName); _node.Start(); _firstEvent = TestEvent.NewTestEvent(); _connection = BuildConnection(_node); _connection.ConnectAsync().Wait(); Assert.AreEqual(2, _connection.AppendToStreamAsync("test-stream", ExpectedVersion.NoStream, _firstEvent, TestEvent.NewTestEvent(), TestEvent.NewTestEvent()).Result.NextExpectedVersion); using (var transaction = _connection.StartTransactionAsync("test-stream", 2).Result) { Assert.AreEqual(2, transaction.CommitAsync().Result.NextExpectedVersion); } }
public override void SetUp() { base.SetUp(); _node = new MiniNode(PathName); _node.Start(); _firstEvent = TestEvent.NewTestEvent(); _connection = TestConnection.Create(_node.TcpEndPoint); _connection.ConnectAsync().Wait(); Assert.AreEqual(2, _connection.AppendToStreamAsync("test-stream", ExpectedVersion.NoStream, _firstEvent, TestEvent.NewTestEvent(), TestEvent.NewTestEvent()).Result.NextExpectedVersion); using (var transaction = _connection.StartTransactionAsync("test-stream", 2).Result) { Assert.AreEqual(2, transaction.Commit().NextExpectedVersion); } }
private void WriteEvents(IEventStoreConnection connection) { for (int i = 0; i < 10; i++) { var id = Guid.NewGuid(); connection.AppendToStreamAsync(_stream, ExpectedVersion.Any, DefaultData.AdminCredentials, new EventData(id, "test", true, Encoding.UTF8.GetBytes("{'foo' : 'bar'}"), new byte[0])).Wait(); if (i == 4) _id = id; } }