public void SerializationRunsAndDoesNotLeak1Byte() { var serializer = new EventSerializer(); bool hasMetadata; var meta = serializer.Serialize(out hasMetadata, new User()); serializer.ProcessMetadataLog(meta); long baselineMemory = 0; for (int i = 0; i < 100; i++) { serializer.Serialize(out hasMetadata, new User()); Assert.False(hasMetadata); if (i == 2) { GC.Collect(2); GC.WaitForPendingFinalizers(); GC.Collect(2); baselineMemory = GC.GetTotalMemory(false); } } GC.Collect(2); GC.WaitForPendingFinalizers(); GC.Collect(2); Assert.InRange(GC.GetTotalMemory(false), 0, baselineMemory + 400); }
public void EventSerializeTestAttributeListAsInt() { Dictionary <string, object> timeseries = new Dictionary <string, object>(); timeseries.Add("list", new List <int>() { 1, 2 }); Event eventBuilt = new Event.Builder() { Timeseries = new Dictionary <string, object>() { { "list", new List <int>() { 1, 2 } } }, EventType = "test" }; string json = EventSerializer.SerializeEvent(eventBuilt); Assert.AreEqual("{\"x_event_type\":\"test\",\"list\":[1,2]}", json); }
public void CanMigrateListInDict() { var obj = PassThroughEventStorage(new EventDictListRoot { Items = new Dictionary <ulong, IList <Item> > { { 1, new List <Item> { new Item { Field = "A" } } } } }, new FullNameTypeMapper()); var serializer = new EventSerializer(); bool hasMetadata; var meta = serializer.Serialize(out hasMetadata, obj).ToAsyncSafe(); serializer.ProcessMetadataLog(meta); var data = serializer.Serialize(out hasMetadata, obj); var deserializer = new EventDeserializer(); object obj2; Assert.False(deserializer.Deserialize(out obj2, data)); deserializer.ProcessMetadataLog(meta); Assert.True(deserializer.Deserialize(out obj2, data)); }
public void DeserializesClassWithIList() { var serializer = new EventSerializer(); bool hasMetadata; var obj = new ObjectWithIList { Items = new List <int> { 1 } }; var meta = serializer.Serialize(out hasMetadata, obj).ToAsyncSafe(); serializer.ProcessMetadataLog(meta); var data = serializer.Serialize(out hasMetadata, obj); var deserializer = new EventDeserializer(); object obj2; Assert.False(deserializer.Deserialize(out obj2, data)); deserializer.ProcessMetadataLog(meta); Assert.True(deserializer.Deserialize(out obj2, data)); Assert.Equal(obj, obj2); deserializer = new EventDeserializer(); deserializer.ProcessMetadataLog(meta); Assert.True(deserializer.Deserialize(out obj2, data)); Assert.Equal(obj, obj2); }
public IdempotentCommandHandlerModuleProcessor( Func <IAddresses> getAddresses, ConcurrentUnitOfWork concurrentUnitOfWork, IPersistentLocalIdGenerator persistentLocalIdGenerator, Func <IStreamStore> getStreamStore, EventMapping eventMapping, EventSerializer eventSerializer, AddressProvenanceFactory addressProvenanceFactory, CrabAddressProvenanceFactory crabProvenanceFactory, AddressPersistentLocalIdentifierProvenanceFactory addressPersistentLocalIdentifierProvenanceFactory) { _getAddresses = getAddresses; _concurrentUnitOfWork = concurrentUnitOfWork; _provenanceFactory = crabProvenanceFactory.CreateFrom; _addressPersistentLocalIdProvenanceFactory = addressPersistentLocalIdentifierProvenanceFactory.CreateFrom; _addressCommandHandlerModule = new AddressCommandHandlerModule( _getAddresses, () => concurrentUnitOfWork, persistentLocalIdGenerator, getStreamStore, eventMapping, eventSerializer, addressProvenanceFactory, crabProvenanceFactory, addressPersistentLocalIdentifierProvenanceFactory); }
static void Main(string[] args) { var settings = ConnectionSettings.Create() .SetDefaultUserCredentials(new UserCredentials("admin", "changeit")) .Build(); var connection = EventStoreConnection.Create(settings, new IPEndPoint(IPAddress.Loopback, 1113)); connection.ConnectAsync().Wait(); connection.CreateObservable(StreamId) .DeserializeWithPosition <MyEvent>() .HandleEvent(e => Console.WriteLine("handled : " + e.Property)) .Subscribe(pos => Console.WriteLine("last position handled : " + pos)); var serializer = new EventSerializer(); while (true) { var key = Console.ReadKey().KeyChar; Console.Write("\b"); var @event = new MyEvent { Property = key.ToString() }; var eventData = new EventData(Guid.NewGuid(), nameof(MyEvent), true, serializer.Serialize(@event), null); connection.AppendToStreamAsync(StreamId, ExpectedVersion.Any, eventData).Wait(); } }
public void LoadEventsFromJson(string events_json) { print(events_json); EventRaws = JsonUtility.FromJson <EventSerializer>(events_json); LoadEventsFromRawEvents(); print(EventRaws); }
public void SetUp() { EventSerializer.Register(typeof(__).Assembly); _writer = Console.Out; Indented = new IndentedTextWriter(_writer); Console.SetOut(Indented); }
public void Apply(AggregateEvent aggregateEvent) { State.Version = aggregateEvent.AggregateVersion; //State.Modified = aggregateEvent.Created; State.Modified = System.DateTime.UtcNow; var accountEvent = EventSerializer.DeserializeEvent(aggregateEvent); switch (accountEvent) { case Deposited deposited: State.Balance += deposited.Amount; break; case Withdrawn withdrawn: State.Balance -= withdrawn.Amount; break; case TransferCredited transferCredited: State.Balance -= transferCredited.Amount; break; case TransferDebited transferDebited: State.Balance += transferDebited.Amount; break; default: break; } }
public async Task OneTimeSetUp() { _eventIdProvider = new InMemoryEventIdProvider(); _serializer = new JsonNetSerializer(); _eventSerializer = new EventSerializer(_serializer); _eventCache = new InMemoryEventCache(_eventIdProvider, _eventSerializer); var brokerConfiguration = new BrokerageServiceConfiguration() { HeartbeatEndpoint = HeartbeatEndpoint, StateOfTheWorldEndpoint = StateOfTheWorldEndpoint, ToSubscribersEndpoint = ToSubscribersEndpoint, ToPublisherEndpoint = ToPublishersEndpoint }; _broker = new BrokerageService(brokerConfiguration, LoggerForTests <BrokerageService> .Default(), _eventCache, _serializer); await _broker.Run(); JsonConvert.DefaultSettings = () => { var settings = new JsonSerializerSettings { Formatting = Formatting.Indented, TypeNameHandling = TypeNameHandling.Objects, ContractResolver = new CamelCasePropertyNamesContractResolver() }; return(settings); }; await Task.Delay(1000); }
private Task EventAppeared(EventStoreCatchUpSubscription sub, ResolvedEvent @event) { var processedEvent = EventSerializer.DeserializeResolvedEvent(@event); if (processedEvent != null) { try { _handleEvent(processedEvent); } catch (Exception ex) { //TODO: handle } } if ([email protected]) { throw new ArgumentException("ResolvedEvent didn't come off a subscription to all (has no position)."); } _lastProcessedPosition = new Position(@event.OriginalPosition.Value.CommitPosition, @event.OriginalPosition.Value.PreparePosition); try { _lastProcessedUpdatedAction?.Invoke(@event.OriginalPosition.Value.CommitPosition, @event.OriginalPosition.Value.PreparePosition); } catch (Exception ex) { //TODO: handle } return(Task.CompletedTask); }
public void Try_deserialize_event_with_not_found_ClrType() { var textSerializer = new JsonTextSerializer(); var eventSerializer = new EventSerializer(textSerializer); var serializedData = textSerializer.Serialize(new SpokeSomething("Hi")); var metadata = new EventSource.Metadata(new[] { new KeyValuePair <string, object>(MetadataKeys.AggregateId, Guid.NewGuid().ToString()), new KeyValuePair <string, object>(MetadataKeys.StreamSequenceNumber, 1.ToString()), new KeyValuePair <string, object>(MetadataKeys.EventClrType, "Cars.UnitTests.EventSerializerTests+NotFoundClrType, Cars.UnitTests, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null") }); var mockCommitedEvent = new Mock <ICommitedEvent>(); mockCommitedEvent.Setup(e => e.Version).Returns(1); mockCommitedEvent.Setup(e => e.AggregateId).Returns(Guid.NewGuid); mockCommitedEvent.Setup(e => e.SerializedData).Returns(serializedData); mockCommitedEvent.Setup(e => e.SerializedMetadata).Returns(textSerializer.Serialize(metadata)); Action act = () => eventSerializer.Deserialize(mockCommitedEvent.Object); act.ShouldThrowExactly <EventTypeNotFoundException>(); }
public void CreateDependencies() { var store = new InMemoryStreamStore(); var eventMapping = new EventMapping(new Dictionary <string, Type> { { "SomethingHappened", typeof(SomethingHappened) }, { "SomethingElseHappened", typeof(SomethingElseHappened) }, }); var eventSerializer = new EventSerializer(JsonConvert.SerializeObject); var eventDeserializer = new EventDeserializer(JsonConvert.DeserializeObject); _factRepository = new StreamStoreFactRepository(store, eventMapping, eventSerializer, eventDeserializer); _handlerFactory = (eventType, @events) => async(command) => { long position = 0; foreach (var @event in events) { position = (await store.AppendToStream( (command as DoSomething).Identifier, ExpectedVersion.Any, new NewStreamMessage(Guid.NewGuid(), eventType, eventSerializer.SerializeObject(@event)), CancellationToken.None) ).CurrentPosition; } return(position); }; _handlerResolver = new Mocking <IHandlerResolver, HandlerResolverSetup>(); //_handlerResolver.When().ResolvesHandler(_handlerFactory); }
public IdempotentCommandHandlerModuleProcessor( Func <IParcels> getParcels, IParcelFactory parcelFactory, ConcurrentUnitOfWork concurrentUnitOfWork, Func <IStreamStore> getStreamStore, EventMapping eventMapping, EventSerializer eventSerializer, ParcelProvenanceFactory provenanceFactory) { _getParcels = getParcels; _parcelFactory = parcelFactory; _concurrentUnitOfWork = concurrentUnitOfWork; _provenanceFactory = provenanceFactory.CreateFrom; var fixGrar1475ProvenanceFactory = new FixGrar1475ProvenanceFactory(); _fixGrar1475ProvenanceFactory = fixGrar1475ProvenanceFactory.CreateFrom; var fixGrar1637ProvenanceFactory = new FixGrar1637ProvenanceFactory(); _fixGrar1637ProvenanceFactory = fixGrar1637ProvenanceFactory.CreateFrom; _parcelCommandHandlerModule = new ParcelCommandHandlerModule( getParcels, parcelFactory, () => concurrentUnitOfWork, getStreamStore, eventMapping, eventSerializer, provenanceFactory, fixGrar1475ProvenanceFactory, fixGrar1637ProvenanceFactory); }
private void Produce() { var eventSerializer = new EventSerializer(); _publisherSocket = new PublisherSocket(); _publisherSocket.Options.SendHighWatermark = 1000; _publisherSocket.Bind(_producerConfiguration.Endpoint); while (!_cancel.IsCancellationRequested) { var next = Next(); var topic = eventSerializer.Serialize(next); var message = new TransportMessage() { MessageType = next.GetType(), MessageId = Guid.NewGuid(), Message = Encoding.UTF32.GetBytes(JsonConvert.SerializeObject(next, _settings)), }; var msg = Encoding.UTF32.GetBytes(JsonConvert.SerializeObject(message, _settings)); _publisherSocket.SendMoreFrame(topic).SendFrame(msg); Task.Delay(_rand.Next(250, 500)).Wait(); } }
public PostalInformationCommandHandlerModule( Func <IPostalInformationSet> getPostalInformationSet, Func <ConcurrentUnitOfWork> getUnitOfWork, Func <IStreamStore> getStreamStore, EventMapping eventMapping, EventSerializer eventSerializer, BPostPostalInformationProvenanceFactory bpostProvenanceFactory, CrabPostalInformationProvenanceFactory crabProvenanceFactory) { For <ImportPostalInformationFromBPost>() .AddSqlStreamStore(getStreamStore, getUnitOfWork, eventMapping, eventSerializer) .AddProvenance(getUnitOfWork, bpostProvenanceFactory) .Handle(async(message, ct) => { var postalCode = message.Command.PostalCode; var postalInformationSet = getPostalInformationSet(); var postalInformation = await postalInformationSet.GetOptionalAsync(postalCode, ct); if (!postalInformation.HasValue) { postalInformation = new Optional <PostalInformation>(PostalInformation.Register(postalCode)); postalInformationSet.Add(postalCode, postalInformation.Value); } postalInformation.Value.ImportPostalInformationFromBPost( message.Command.PostalCode, message.Command.PostalNames, message.Command.IsSubMunicipality, message.Command.Province, message.Command.Modification); }); For <ImportPostalInformationFromCrab>() .AddSqlStreamStore(getStreamStore, getUnitOfWork, eventMapping, eventSerializer) .AddProvenance(getUnitOfWork, crabProvenanceFactory) .Handle(async(mesage, ct) => { // need to use the subcanton => in crab postcode = 1030, subcanton = 1031 // in bpost postcode = 1031 var postalCode = new PostalCode(mesage.Command.SubCantonCode); var postalInformation = await getPostalInformationSet().GetOptionalAsync(postalCode, ct); if (!postalInformation.HasValue) // Crab has possible outdated postalcodes { return; } postalInformation.Value.ImportPostalInformationFromCrab( mesage.Command.PostalCode, mesage.Command.SubCantonId, mesage.Command.SubCantonCode, mesage.Command.NisCode, mesage.Command.MunicipalityName, mesage.Command.Lifetime, mesage.Command.Timestamp, mesage.Command.Operator, mesage.Command.Modification, mesage.Command.Organisation); }); }
public AccountCommandHandlerModule( Func <IStreamStore> getStreamStore, Func <ConcurrentUnitOfWork> getUnitOfWork, EventMapping eventMapping, EventSerializer eventSerializer, Func <IAccounts> getAccounts) { For <NameAccount>() .AddSqlStreamStore(getStreamStore, getUnitOfWork, eventMapping, eventSerializer) .Handle(async(message, ct) => { var accounts = getAccounts(); var accountId = message.Command.AccountId; var possibleAccount = await accounts.GetOptionalAsync(accountId, ct); if (!possibleAccount.HasValue) { possibleAccount = new Optional <Account>(Account.Register(accountId)); accounts.Add(accountId, possibleAccount.Value); } var account = possibleAccount.Value; account.NameAccount(message.Command.AccountName); }); }
public EventStoreTests() { var eventSerializer = new EventSerializer(new JsonTextSerializer()); _inMemoryDomainEventStore = new InMemoryEventStore(); _mockEventPublisher = new Mock <IEventPublisher>(); _mockEventPublisher.Setup(e => e.EnqueueAsync(It.IsAny <IEnumerable <IDomainEvent> >())).Returns(Task.CompletedTask); var loggerFactory = new LoggerFactory(); var session = new Session(loggerFactory, _inMemoryDomainEventStore, _mockEventPublisher.Object, eventSerializer); _repository = new Repository(loggerFactory, session); var unitOfWorkMock = new Mock <ISession>(); unitOfWorkMock.Setup(e => e.CommitAsync()) .Callback(async() => { await session.CommitAsync(); }) .Returns(Task.CompletedTask); _session = unitOfWorkMock.Object; }
public void Scenario1() { using (var ms = new MemoryStream()) { var stream = new WORMStream(ms); var serializer = new EventSerializer(); var store = new WormEventStore(stream, serializer); var framework = new Framework <InventoryState>(store); var id1 = framework .Execute(new CreateProduct("test1")) .Select(ev => ev.EntityId) .First(); framework.Execute(new BuyProduct(id1, 10m, 20m)); var products = framework .State .Products .ToList(); Assert.AreEqual(1, products.Count); Assert.AreEqual("test1", products[0].Name); var stocks = framework .State .Stock .ToList(); Assert.AreEqual(1, stocks.Count); Assert.AreEqual(products[0], stocks[0].Product); Assert.AreEqual(10m, stocks[0].Quantity); Assert.AreEqual(20m, stocks[0].Price); } }
public EventStoreTests() { var eventSerializer = new EventSerializer(new JsonTextSerializer()); var snapshotSerializer = new SnapshotSerializer(new JsonTextSerializer()); _inMemoryDomainEventStore = new InMemoryEventStore(); var mockLogger = new Mock <ILogger>(); mockLogger.Setup(e => e.IsEnabled(It.IsAny <LogLevel>())).Returns(true); mockLogger.Setup(e => e.Log(It.IsAny <LogLevel>(), It.IsAny <string>(), It.IsAny <Exception>())); var mockLoggerFactory = new Mock <ILoggerFactory>(); mockLoggerFactory.Setup(e => e.Create(It.IsAny <string>())).Returns(mockLogger.Object); _mockEventPublisher = new Mock <IEventPublisher>(); _mockEventPublisher.Setup(e => e.PublishAsync(It.IsAny <IEnumerable <IDomainEvent> >())).Returns(Task.CompletedTask); var session = new Session(mockLoggerFactory.Object, _inMemoryDomainEventStore, _mockEventPublisher.Object, eventSerializer, snapshotSerializer); _repository = new Repository(mockLoggerFactory.Object, session); var unitOfWorkMock = new Mock <IUnitOfWork>(); unitOfWorkMock.Setup(e => e.CommitAsync()) .Callback(async() => { await session.SaveChangesAsync().ConfigureAwait(false); }) .Returns(Task.CompletedTask); _unitOfWork = unitOfWorkMock.Object; }
public ExampleAggregateCommandHandlerModule( Func <IStreamStore> getStreamStore, Func <ConcurrentUnitOfWork> getUnitOfWork, EventMapping eventMapping, EventSerializer eventSerializer, Func <IExampleAggregates> getExampleAggregates) { For <NameExampleAggregate>() .AddSqlStreamStore(getStreamStore, getUnitOfWork, eventMapping, eventSerializer) .Handle(async(message, ct) => { var exampleAggregates = getExampleAggregates(); var exampleAggregateId = message.Command.ExampleAggregateId; var possibleExampleAggregate = await exampleAggregates.GetOptionalAsync(exampleAggregateId, ct); if (!possibleExampleAggregate.HasValue) { possibleExampleAggregate = new Optional <ExampleAggregate>(ExampleAggregate.Register(exampleAggregateId)); exampleAggregates.Add(exampleAggregateId, possibleExampleAggregate.Value); } var exampleAggregate = possibleExampleAggregate.Value; exampleAggregate.NameExampleAggregate(message.Command.ExampleAggregateName); }); }
public EventStore(ILogger <EventStore> logger, IEventPublisher publisher, IOptions <EventStoreOptions> options) { _publisher = publisher; var assemblyNameFilter = options.Value.EventAssembliesPrefix ?? DefaultEventAssembliesPrefix; _eventSerializer = new EventSerializer( new DependencyContextFinder(assemblyNameFilter)); // Preferred since it doesn't require a path but will be incompatible with .NET Standard 2.0 //new RuntimeLoaderFinder(new System.IO.DirectoryInfo(@".\bin\Debug\netcoreapp1.0"), assemblyNameFilter)); try { Connection = EventStoreConnection.Create(Settings, new Uri(options.Value.ServerUri ?? DefaultServerUri)); Connection.Disconnected += (s, e) => logger.LogError("EventStore Disconnected"); Connection.Reconnecting += (s, e) => logger.LogError("EventStore Reconnecting"); Connection.ErrorOccurred += (s, e) => logger.LogError("EventStore ErrorOccurred"); Connection.ConnectAsync().Wait(); } catch (Exception ex) { logger.LogError(0, ex, "EventStore Exception"); } }
public async Task Projection_is_rebuilt_by_denormalizer() { //Need to create an aggregate here. var serializer = new EventSerializer(new BsonTextSerializer()); DenormAggregate aggregate; using (var eventStore = new MongoEventStore(_mongoClient, _defaultSettings)) { aggregate = new DenormAggregate(Guid.NewGuid()); for (int i = 0; i < 10; i++) { aggregate.DoThing("Thing_" + i); } var session = new Session(new LoggerFactory(), eventStore, new EventPublisher(StubEventRouter.Ok()), serializer); session.Add(aggregate); await session.CommitAsync(); } var projectionRepository = new MongoProjectionRepository(_mongoClient, _defaultSettings); using (var eventStore = new MongoEventStore(_mongoClient, _defaultSettings)) { var testDenormalizer = new TestDenormalizer(projectionRepository, eventStore, serializer); await testDenormalizer.RebuildAsync(); } var projection = await projectionRepository.RetrieveAsync <TestProjection>("TestDenormalizedProjection"); projection.LastThing.Should().Be(aggregate.LastThing); }
public void CanMigrateListWithNewFields() { var parentMapper = new FullNameTypeMapper(); var mapper = new EventStoreTest.OverloadableTypeMapper(typeof(Item2), parentMapper.ToName(typeof(Item)), new EventStoreTest.OverloadableTypeMapper(typeof(EventRoot2), parentMapper.ToName(typeof(EventRoot)), parentMapper )); var obj = PassThroughEventStorage(new EventRoot { Items = new List <Item> { new Item { Field = "A" } } }, mapper); var serializer = new EventSerializer(mapper); bool hasMetadata; var meta = serializer.Serialize(out hasMetadata, obj).ToAsyncSafe(); serializer.ProcessMetadataLog(meta); var data = serializer.Serialize(out hasMetadata, obj); var deserializer = new EventDeserializer(mapper); object obj2; Assert.False(deserializer.Deserialize(out obj2, data)); deserializer.ProcessMetadataLog(meta); Assert.True(deserializer.Deserialize(out obj2, data)); }
public void Serialize_WithEmptyGuid_ShouldReturnNilUUID() { var result = EventSerializer.Serialize(Guid.Empty); Assert.Equal(16, result.Length); Assert.All(result, b => Assert.Equal(0, b)); }
public void DeserializesClassWithIListArray() { var serializer = new EventSerializer(); bool hasMetadata; var obj = new ObjectWithIList2 { Items = new ObjectDbTest.Person[] { new ObjectDbTest.Person { Name = "A", Age = 1 } } }; var meta = serializer.Serialize(out hasMetadata, obj).ToAsyncSafe(); Assert.Equal(99, meta.Length); serializer.ProcessMetadataLog(meta); var data = serializer.Serialize(out hasMetadata, obj); serializer = new EventSerializer(); serializer.ProcessMetadataLog(meta); var data2 = serializer.Serialize(out hasMetadata, obj); var deserializer = new EventDeserializer(); object obj2; Assert.False(deserializer.Deserialize(out obj2, data)); deserializer.ProcessMetadataLog(meta); Assert.True(deserializer.Deserialize(out obj2, data)); Assert.Equal(obj, obj2); deserializer = new EventDeserializer(); deserializer.ProcessMetadataLog(meta); Assert.True(deserializer.Deserialize(out obj2, data)); Assert.Equal(obj, obj2); }
public void Serialize_WithRandomGuid_ShouldSerializeSuccess() { for (var i = 0; i < 10; i++) { EventSerializer.Serialize(Guid.NewGuid()); } }
public void EventDeserializeTest() { DateTime now = TestUtils.GetNowIgnoringMilis(); string json = "{\"x_event_type\":\"type\"," + "\"x_timestamp\":\"" + now.ToString(DatetimeFormat) + "\"," + "\"age\": 89," + "\"weight\": 125.5," + "\"married\": true," + "\"counter\": -13582," + "\"list_SmartObject\": [\"val1\",\"val2\",\"val3\"]," + "\"x_object\" : { \"x_device_id\":\"deviceID\",\"sometrash\":8888}," + "\"event_id\":\"46aabccd-4442-6665-a1f0-49889330eaf3\"}"; var attributes = ImmutableDictionary.CreateBuilder <string, object>(); attributes.Add("age", 89); attributes.Add("weight", 125.5); attributes.Add("married", true); attributes.Add("counter", -13582); attributes.Add("list_SmartObject", (Object) new string[] { "val1", "val2", "val3" }); Event eventBuilt = EventSerializer.DeserializeEvent(json); Assert.AreEqual(eventBuilt.EventId.ToString(), "46aabccd-4442-6665-a1f0-49889330eaf3"); Assert.AreEqual(eventBuilt.EventType, "type"); Assert.AreEqual(eventBuilt.DeviceId, "deviceID"); Assert.AreEqual(eventBuilt.Timestamp.Value.ToString(DatetimeFormat), now.ToString(DatetimeFormat)); CollectionAssert.AreEqual(eventBuilt.Timeseries, attributes.ToImmutable()); }
public void SetUp() { _model = new Model(); var eventDeserializer = new EventDeserializer(SimpleJson.DeserializeObject); var eventSerializer = new EventSerializer(SimpleJson.SerializeObject); var eventMapping = new EventMapping(new Dictionary <string, Type> { { typeof(SnapshotStub).AssemblyQualifiedName, typeof(SnapshotStub) }, { typeof(EventStub).AssemblyQualifiedName, typeof(EventStub) }, }); var snapshotContainer = new SnapshotContainer { Info = { Position = 4, Type = typeof(SnapshotStub).AssemblyQualifiedName }, Data = eventSerializer.SerializeObject(new SnapshotStub(1)) }; _sut = new RepositoryScenarioBuilder(eventMapping, eventDeserializer) .ScheduleAppendToStream(_model.KnownIdentifier, new EventStub(0)) .ScheduleAppendToStream(_model.KnownIdentifier, new EventStub(1)) .ScheduleAppendToStream(_model.KnownIdentifier, new EventStub(2)) .ScheduleAppendToStream(_model.KnownIdentifier, new EventStub(3)) .ScheduleAppendToStream(_model.KnownIdentifier, new EventStub(4)) .ScheduleAppendToStream($"{_model.KnownIdentifier}-snapshots", snapshotContainer) .ScheduleAppendToStream(_model.KnownIdentifier, new EventStub(5)) .ScheduleAppendToStream(_model.KnownIdentifier, new EventStub(6)) .BuildForRepository <AggregateRootEntitySnapshotableStub>(); }
private static async Task <long> AddSqlStreamStore( Func <IStreamStore> getStreamStore, Func <ConcurrentUnitOfWork> getUnitOfWork, EventMapping eventMapping, EventSerializer eventSerializer, CommandMessage message, CancellationToken ct) { var aggregate = getUnitOfWork().GetChanges().SingleOrDefault(); if (aggregate == null) { return(-1L); } if (!message.Metadata.ContainsKey("CommandId")) { message.Metadata.Add("CommandId", message.CommandId); } var i = 1; var result = await getStreamStore().AppendToStream( aggregate.Identifier, aggregate.ExpectedVersion, aggregate.Root.GetChangesWithMetadata() .Select(o => new NewStreamMessage( messageId: Deterministic.Create(Deterministic.Namespaces.Events, $"{message.CommandId}-{i++}"), type: eventMapping.GetEventName(o.Event.GetType()), jsonData: eventSerializer.SerializeObject(o.Event), jsonMetadata: eventSerializer.SerializeObject(GetMetadata(message.Metadata, o.Metadata)))) .ToArray(), ct); return(result.CurrentPosition); }
internal static List<Event> getEvents() { Utils.log("getEvents()"); List<Event> result = new List<Event>(); //Read all event lines from storage (and delete the file) String allEvents = StorageManager.read(FILE_NAME, true); if (allEvents != null) { //Split event lines String[] allEventsLines = allEvents.Split(Environment.NewLine.ToCharArray(), StringSplitOptions.RemoveEmptyEntries); foreach (String eventStr in allEventsLines) { //Base64 decode byte[] eventData = Convert.FromBase64String(eventStr); //Protobuf deserialize MemoryStream stream = new MemoryStream(eventData); Event e = new Event(); Type type = e.GetType(); EventSerializer serializer = new EventSerializer(); serializer.Deserialize(stream, e, type); //Recalculate checksum e.calculateChecksum(SDK.publicKey, SDK.privateKey, SDK.uniqueUserID, SDK.uniqueHardwareID); //Set new ID e.setNewID(); Utils.log("Restored " + e.name + " event with (new) ID " + e._id); //Add to result set result.Add(e); } } else { Utils.log("No stored events found"); } return result; }