Пример #1
0
 public CommandModel ToModel()
 {
     return(new CommandModel(GuidKey.Create(CommandID, CommandType), Payload)
     {
         RaisedAt = RaisedAt
     });
 }
Пример #2
0
        public void TestGuidKey()
        {
            var o = new GuidKey();

            Assert.IsTrue(Guid.Empty == o.Id);

            o.Name = "guid";
            o.Save();

            Assert.IsFalse(Guid.Empty == o.Id);

            GuidKey o1 = GuidKey.FindById(o.Id);

            Assert.AreEqual("guid", o1.Name);

            o.Name = "test";
            o.Save();

            GuidKey o2 = GuidKey.FindById(o.Id);

            Assert.AreEqual("test", o2.Name);

            o2.Delete();
            GuidKey o3 = GuidKey.FindById(o.Id);

            Assert.IsNull(o3);
        }
Пример #3
0
        protected override bool TryConvert(IKey source, out JObject target)
        {
            StringKey stringSource = source as StringKey;

            if (stringSource != null)
            {
                JToken token;
                if (Converts.Try <StringKey, JToken>(stringSource, out token))
                {
                    target = token as JObject;
                    return(target != null);
                }
            }

            GuidKey guidSource = source as GuidKey;

            if (guidSource != null)
            {
                JToken token;
                if (Converts.Try <GuidKey, JToken>(guidSource, out token))
                {
                    target = token as JObject;
                    return(target != null);
                }
            }

            target = null;
            return(false);
        }
Пример #4
0
        public bool TryParseNavigation(LaunchActivatedEventArgs e, out object parameter)
        {
            if (e.TileId.StartsWith(OutcomeCreatePrefix))
            {
                if (e.Arguments.Contains("CategoryKey="))
                {
                    string rawGuid = e.Arguments.Substring(e.Arguments.LastIndexOf('=') + 1);
                    Guid   guid;
                    if (Guid.TryParse(rawGuid, out guid))
                    {
                        parameter = new OutcomeParameter(GuidKey.Create(guid, KeyFactory.Empty(typeof(Category)).Type));
                    }
                    else
                    {
                        parameter = null;
                        return(false);
                    }
                }
                else
                {
                    parameter = new OutcomeParameter();
                }

                return(true);
            }

            parameter = null;
            return(false);
        }
Пример #5
0
        public void SaveAndLoadWithEntityRepository()
        {
            Converts.Repository
            .AddJsonKey()
            .AddJsonEnumSearchHandler()
            .AddJsonPrimitivesSearchHandler()
            .AddJsonObjectSearchHandler();

            ICompositeTypeProvider       compositeTypeProvider = new ReflectionCompositeTypeProvider(new ReflectionCompositeDelegateFactory());
            IFactory <ICompositeStorage> storageFactory        = new GetterFactory <ICompositeStorage>(() => new JsonCompositeStorage());

            EventSourcingContext context    = new EventSourcingContext(@"Data Source=.\sqlexpress; Initial Catalog=EventStore;Integrated Security=SSPI");
            EntityEventStore     eventStore = new EntityEventStore(context);

            PersistentEventDispatcher eventDispatcher = new PersistentEventDispatcher(eventStore);

            AggregateRootRepository <Order> repository = new AggregateRootRepository <Order>(
                eventStore,
                new CompositeEventFormatter(compositeTypeProvider, storageFactory),
                new ReflectionAggregateRootFactory <Order>(),
                eventDispatcher,
                new NoSnapshotProvider(),
                new EmptySnapshotStore()
                );

            PersistentCommandDispatcher commandDispatcher = new PersistentCommandDispatcher(
                new SerialCommandDistributor(),
                new EntityCommandStore(context),
                new CompositeCommandFormatter(compositeTypeProvider, storageFactory)
                );

            CreateOrderHandler  createHandler  = new CreateOrderHandler(repository);
            AddOrderItemHandler addItemHandler = new AddOrderItemHandler(repository);

            commandDispatcher.Handlers
            .Add <CreateOrder>(createHandler)
            .Add <AddOrderItem>(addItemHandler);

            CreateOrder create = new CreateOrder();

            commandDispatcher.HandleAsync(create);

            eventDispatcher.Handlers.Await <OrderPlaced>().Wait();

            IEnumerable <EventModel> serializedEvents = eventStore.Get(create.OrderKey).ToList();

            Assert.AreEqual(1, serializedEvents.Count());

            AddOrderItem addItem = new AddOrderItem(create.OrderKey, GuidKey.Create(Guid.NewGuid(), "Product"), 5);

            commandDispatcher.HandleAsync(Envelope.Create(addItem).AddDelay(TimeSpan.FromMinutes(1)));

            Task <OrderTotalRecalculated> task = eventDispatcher.Handlers.Await <OrderTotalRecalculated>();

            task.Wait();
            Console.WriteLine(task.Result);

            serializedEvents = eventStore.Get(create.OrderKey).ToList();
            Assert.AreEqual(4, serializedEvents.Count());
        }
Пример #6
0
        public OutcomeOverviewModel ToOverviewModel(int version)
        {
            GuidKey outcomeKey  = GuidKey.Create(Id, KeyFactory.Empty(typeof(Outcome)).Type);
            GuidKey categoryKey = GuidKey.Create(Categories.First().CategoryId, KeyFactory.Empty(typeof(Category)).Type);
            Price   amount      = new Price(Amount, Currency);

            if (version == 1)
            {
                return(new OutcomeOverviewModel(
                           outcomeKey,
                           amount,
                           When,
                           Description,
                           categoryKey
                           ));
            }
            else if (version == 2)
            {
                return(new OutcomeOverviewModel(
                           outcomeKey,
                           amount,
                           When,
                           Description,
                           categoryKey,
                           IsFixed
                           ));
            }
            else
            {
                throw Ensure.Exception.InvalidOperation($"Invalid version '{version}' of expense overview model.");
            }
        }
Пример #7
0
        public static EventEntity FromModel(EventModel model)
        {
            Ensure.NotNull(model, "model");

            GuidKey aggregateKey = model.AggregateKey as GuidKey;

            if (aggregateKey == null)
            {
                throw Ensure.Exception.NotGuidKey(model.AggregateKey.GetType(), "aggregateKey");
            }

            GuidKey eventKey = model.EventKey as GuidKey;

            if (eventKey == null)
            {
                throw Ensure.Exception.NotGuidKey(model.EventKey.GetType(), "eventKey");
            }

            return(new EventEntity()
            {
                EventID = eventKey.Guid,
                EventType = eventKey.Type,

                AggregateID = aggregateKey.Guid,
                AggregateType = aggregateKey.Type,

                Payload = model.Payload,
                Version = model.Version
            });
        }
        public void AddVariousKeyClass()
        {
            Converts.Repository
            .AddStringTo <Guid>(Guid.TryParse);

            IKeyToParametersConverter converter = CreateConverter();

            KeyValueCollection parameters = new KeyValueCollection();

            converter.Add(parameters, Int32Key.Create(5, "Product"));

            Assert.AreEqual(2, parameters.Keys.Count());
            Assert.AreEqual(5, parameters.Get <int>("ID"));
            Assert.AreEqual("Product", parameters.Get <string>("Type"));

            parameters = new KeyValueCollection();
            converter.Add(parameters, StringKey.Create("abcdef", "Product"));

            Assert.AreEqual(2, parameters.Keys.Count());
            Assert.AreEqual("abcdef", parameters.Get <string>("Identifier"));
            Assert.AreEqual("Product", parameters.Get <string>("Type"));

            parameters = new KeyValueCollection();
            Guid guid = Guid.NewGuid();

            converter.Add(parameters, GuidKey.Create(guid, "Product"));

            Assert.AreEqual(2, parameters.Keys.Count());
            Assert.AreEqual(guid, parameters.Get <Guid>("Guid"));
            Assert.AreEqual("Product", parameters.Get <string>("Type"));
        }
Пример #9
0
 public CategoryModel ToModel()
 {
     return(new CategoryModel(
                GuidKey.Create(Id, KeyFactory.Empty(typeof(Category)).Type),
                Name,
                Description,
                Color.FromArgb(ColorA, ColorR, ColorG, ColorB)
                ));
 }
Пример #10
0
 public OutcomeOverviewModel ToOverviewModel()
 {
     return(new OutcomeOverviewModel(
                GuidKey.Create(Id, KeyFactory.Empty(typeof(Outcome)).Type),
                new Price(Amount, Currency),
                When,
                Description
                ));
 }
Пример #11
0
 public EventModel ToModel()
 {
     return(new EventModel(
                GuidKey.Create(AggregateID, AggregateType),
                GuidKey.Create(EventID, EventType),
                Payload,
                Version
                ));
 }
Пример #12
0
 public CategoryModel ToModel()
 {
     return(new CategoryModel(
                GuidKey.Create(Id, KeyFactory.Empty(typeof(Category)).Type),
                Name,
                Description,
                ToColor(),
                Icon
                ));
 }
Пример #13
0
 public ExpenseTemplateModel ToModel() => new ExpenseTemplateModel(
     GuidKey.Create(Id, KeyFactory.Empty(typeof(ExpenseTemplate)).Type),
     Amount != null
         ? new Price(Amount.Value, Currency)
         : null,
     Description,
     CategoryId != null
         ? GuidKey.Create(CategoryId.Value, KeyFactory.Empty(typeof(Category)).Type)
         : GuidKey.Empty(KeyFactory.Empty(typeof(Category)).Type)
     );
Пример #14
0
        public Movie Create(string name)
        {
            Movie movie = new Movie(GuidKey.Create(Guid.NewGuid(), "Movie"), this)
            {
                Name = name
            };

            Movies.Add(movie);
            return(movie);
        }
Пример #15
0
        public OutcomeModel ToModel()
        {
            string categoryKeyType = KeyFactory.Empty(typeof(Category)).Type;

            return(new OutcomeModel(
                       GuidKey.Create(Id, KeyFactory.Empty(typeof(Outcome)).Type),
                       new Price(Amount, Currency),
                       When,
                       Description,
                       Categories.Select(c => GuidKey.Create(c.CategoryId, categoryKeyType)).ToList()
                       ));
        }
Пример #16
0
        public void SetGuidKeyWithTypeFullNameAndAssembly()
        {
            KeyFactory.SetGuidKeyWithTypeFullNameAndAssembly();
            GuidKey key = KeyFactory.Create(typeof(KeyFactory)).AsGuidKey();

            Assert.AreEqual("Neptuo.KeyFactory, Neptuo.EventSourcing.Domains", key.Type);

            Type keyFactoryType = Type.GetType(key.Type);

            Assert.IsNotNull(keyFactoryType);
            Assert.AreEqual(typeof(KeyFactory), keyFactoryType);
        }
Пример #17
0
        /// <summary>
        /// Creates a new empty key instance.
        /// </summary>
        /// <param name="targetType">A type for which key is generated.</param>
        /// <returns>A new empty key instance.</returns>
        public static IKey Empty(Type targetType)
        {
            Ensure.NotNull(targetType, "targetType");

            if (emptyFactory != null)
            {
                return(emptyFactory(targetType));
            }

            string keyType = (keyTypeProvider ?? TypeNameMapper.Default).Get(targetType);

            return(GuidKey.Empty(keyType));
        }
Пример #18
0
        /// <summary>
        /// Creates a new instance of a key implementing <see cref="IKey"/> for the <paramref name="targetType"/>.
        /// </summary>
        /// <param name="targetType">A type for which key is generated.</param>
        /// <returns>A newly generated key for the <paramref name="targetType"/>.</returns>
        public static IKey Create(Type targetType)
        {
            Ensure.NotNull(targetType, "targetType");

            if (keyFactory != null)
            {
                return(keyFactory(targetType));
            }

            string keyType = (keyTypeProvider ?? TypeNameMapper.Default).Get(targetType);

            return(GuidKey.Create(Guid.NewGuid(), keyType));
        }
        public void Create_Adds_Entity_To_The_Table_And_Sets_Guid_Key()
        {
            InMemoryDb db = new InMemoryDb();
            InMemoryDbTable <Guid, GuidKey> table = db.GetTable <Guid, GuidKey>();
            Repository <Guid, GuidKey>      repo  = new Repository <Guid, GuidKey>(table);

            GuidKey entity = new GuidKey();

            // create
            Assert.IsTrue(repo.Add(entity));
            Assert.IsTrue(table.Count() == 1);
            Assert.IsTrue(entity.Id != Guid.Empty);
        }
Пример #20
0
        protected override async Task OnInitializedAsync()
        {
            await base.OnInitializedAsync();

            StartYear    = new YearModel(DateTime.Today.Year - 8);
            CategoryKey  = GuidKey.Create(CategoryGuid, KeyFactory.Empty(typeof(Category)).Type);
            CategoryName = await Queries.QueryAsync(new GetCategoryName(CategoryKey));

            CategoryColor = await Queries.QueryAsync(new GetCategoryColor(CategoryKey));

            CurrencyFormatter = await CurrencyFormatterFactory.CreateAsync();

            await LoadAsync();
        }
Пример #21
0
        public void RegisteringInterfaceHandlers()
        {
            Order order1 = new Order(KeyFactory.Create(typeof(Order)));

            order1.AddItem(GuidKey.Create(Guid.NewGuid(), "Product"), 5);

            IEnumerator <object> eventEnumerator = order1.Events.GetEnumerator();

            Assert.AreEqual(true, eventEnumerator.MoveNext());
            Assert.AreEqual(typeof(OrderPlaced), eventEnumerator.Current.GetType());
            Assert.AreEqual(true, eventEnumerator.MoveNext());
            Assert.AreEqual(typeof(OrderItemAdded), eventEnumerator.Current.GetType());
            Assert.AreEqual(true, eventEnumerator.MoveNext());
            Assert.AreEqual(typeof(OrderTotalRecalculated), eventEnumerator.Current.GetType());
            Assert.AreEqual(false, eventEnumerator.MoveNext());
        }
Пример #22
0
        public IEnumerable <EventModel> Get(IKey aggregateKey, int version)
        {
            Ensure.Condition.NotEmptyKey(aggregateKey, "aggregateKey");

            GuidKey key = aggregateKey as GuidKey;

            if (key == null)
            {
                throw Ensure.Exception.NotGuidKey(aggregateKey.GetType(), "aggregateKey");
            }

            IEnumerable <EventEntity> entities = contextFactory().Events
                                                 .Where(e => e.AggregateType == key.Type && e.AggregateID == key.Guid && e.Version > version)
                                                 .OrderBy(e => e.Version);

            return(entities.Select(e => e.ToModel()));
        }
Пример #23
0
        public void GuidKey_Equal()
        {
            Guid    guid1 = Guid.NewGuid();
            Guid    guid2 = Guid.NewGuid();
            GuidKey key1  = GuidKey.Create(guid1, "Product");
            GuidKey key2  = GuidKey.Create(guid1, "Product");

            Assert.AreEqual(key1, key2);

            key1 = GuidKey.Create(guid1, "Product");
            key2 = GuidKey.Create(guid2, "Product");
            Assert.AreNotEqual(key1, key2);

            key1 = GuidKey.Create(guid1, "Product");
            key2 = GuidKey.Create(guid1, "Term");
            Assert.AreNotEqual(key1, key2);
        }
        public Task PublishedAsync(IKey key)
        {
            GuidKey commandKey = key as GuidKey;

            if (commandKey == null)
            {
                throw Ensure.Exception.NotGuidKey(commandKey.GetType(), "key");
            }

            UnPublishedCommandEntity entity = context.UnPublishedCommands.FirstOrDefault(e => e.Command.CommandType == commandKey.Type && e.Command.CommandID == commandKey.Guid);

            if (entity == null)
            {
                return(Task.FromResult(true));
            }

            entity.IsHandled = true;
            return(context.SaveAsync());
        }
Пример #25
0
        public Task PublishedAsync(IKey key, string handlerIdentifier)
        {
            GuidKey eventKey = key as GuidKey;

            if (eventKey == null)
            {
                throw Ensure.Exception.NotGuidKey(eventKey.GetType(), "key");
            }

            IEventContext          context = contextFactory();
            UnPublishedEventEntity entity  = context.UnPublishedEvents.FirstOrDefault(e => e.Event.EventType == eventKey.Type && e.Event.EventID == eventKey.Guid);

            if (entity == null)
            {
                return(Task.FromResult(true));
            }

            entity.PublishedToHandlers.Add(new EventPublishedToHandlerEntity(handlerIdentifier));
            return(context.SaveAsync());
        }
Пример #26
0
        public static CommandEntity FromModel(CommandModel model)
        {
            Ensure.NotNull(model, "model");

            GuidKey commandKey = model.CommandKey as GuidKey;

            if (commandKey == null)
            {
                throw Ensure.Exception.NotGuidKey(model.CommandKey.GetType(), "commandKey");
            }

            return(new CommandEntity()
            {
                CommandID = commandKey.Guid,
                CommandType = commandKey.Type,

                Payload = model.Payload,
                RaisedAt = model.RaisedAt
            });
        }
Пример #27
0
        private IKey LoadMovieKey(XmlStructure structure, XElement element, XName attributeName)
        {
            string id = element.Attribute(attributeName)?.Value;

            if (id == null)
            {
                throw Ensure.Exception.InvalidOperation($"Missing attribute '{structure.MovieId}' on element '{element}'.");
            }

            IKey key = null;

            if (Guid.TryParse(id, out Guid guid))
            {
                key = GuidKey.Create(guid, "Movie");
            }
            else
            {
                key = StringKey.Create(id, "Movie");
            }

            return(key);
        }
Пример #28
0
        public CategoryModel ToModel(bool includeIsDeletedFlag)
        {
            GuidKey key = GuidKey.Create(Id, KeyFactory.Empty(typeof(Category)).Type);

            if (includeIsDeletedFlag)
            {
                return(new CategoryModel(
                           key,
                           Name,
                           Description,
                           ToColor(),
                           Icon,
                           IsDeleted
                           ));
            }

            return(new CategoryModel(
                       key,
                       Name,
                       Description,
                       ToColor(),
                       Icon
                       ));
        }
Пример #29
0
        protected override async Task OnInitAsync()
        {
            BindEvents();
            Delete.Confirmed += async model => await Commands.HandleAsync(new DeleteOutcome(model.Key));

            Delete.MessageFormatter = model => $"Do you really want to delete outcome '{model.Description}'?";

            CategoryKey = Guid.TryParse(CategoryGuid, out var categoryGuid) ? GuidKey.Create(categoryGuid, KeyFactory.Empty(typeof(Category)).Type) : KeyFactory.Empty(typeof(Category));
            MonthModel  = new MonthModel(Int32.Parse(Year), Int32.Parse(Month));

            if (!CategoryKey.IsEmpty)
            {
                CategoryName = await Queries.QueryAsync(new GetCategoryName(CategoryKey));

                Title = $"{CategoryName} outcomes in {MonthModel}";
            }
            else
            {
                Title = $"Outcomes in {MonthModel}";
            }

            formatter = new CurrencyFormatter(await Queries.QueryAsync(new ListAllCurrency()));
            await LoadDataAsync();
        }
Пример #30
0
 public IKey CreateMovieKey()
 {
     return(GuidKey.Create(Guid.NewGuid(), "Movie"));
 }