Beispiel #1
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);
        }
Beispiel #2
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());
        }
Beispiel #3
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.");
            }
        }
        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"));
        }
Beispiel #5
0
 public CommandModel ToModel()
 {
     return(new CommandModel(GuidKey.Create(CommandID, CommandType), Payload)
     {
         RaisedAt = RaisedAt
     });
 }
Beispiel #6
0
 public CategoryModel ToModel()
 {
     return(new CategoryModel(
                GuidKey.Create(Id, KeyFactory.Empty(typeof(Category)).Type),
                Name,
                Description,
                Color.FromArgb(ColorA, ColorR, ColorG, ColorB)
                ));
 }
Beispiel #7
0
 public EventModel ToModel()
 {
     return(new EventModel(
                GuidKey.Create(AggregateID, AggregateType),
                GuidKey.Create(EventID, EventType),
                Payload,
                Version
                ));
 }
Beispiel #8
0
 public OutcomeOverviewModel ToOverviewModel()
 {
     return(new OutcomeOverviewModel(
                GuidKey.Create(Id, KeyFactory.Empty(typeof(Outcome)).Type),
                new Price(Amount, Currency),
                When,
                Description
                ));
 }
Beispiel #9
0
 public CategoryModel ToModel()
 {
     return(new CategoryModel(
                GuidKey.Create(Id, KeyFactory.Empty(typeof(Category)).Type),
                Name,
                Description,
                ToColor(),
                Icon
                ));
 }
 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)
     );
Beispiel #11
0
        public Movie Create(string name)
        {
            Movie movie = new Movie(GuidKey.Create(Guid.NewGuid(), "Movie"), this)
            {
                Name = name
            };

            Movies.Add(movie);
            return(movie);
        }
Beispiel #12
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()
                       ));
        }
Beispiel #13
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));
        }
Beispiel #14
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();
        }
Beispiel #15
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());
        }
Beispiel #16
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);
        }
Beispiel #17
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);
        }
Beispiel #18
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
                       ));
        }
Beispiel #19
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();
        }
Beispiel #20
0
 public IKey CreateMovieKey()
 {
     return(GuidKey.Create(Guid.NewGuid(), "Movie"));
 }
Beispiel #21
0
 public IncomeOverviewModel ToOverviewModel(ListMonthIncome query) => new IncomeOverviewModel(
     GuidKey.Create(Id, KeyFactory.Empty(typeof(Income)).Type),
     new Price(Amount, Currency),
     When,
     Description
     );
Beispiel #22
0
 /// <summary>
 /// Sets key factory to use <see cref="GuidKey"/> and type fullname with assembly name (without version and public key).
 /// </summary>
 public static void SetGuidKeyWithTypeFullNameAndAssembly()
 {
     keyFactory   = targetType => GuidKey.Create(Guid.NewGuid(), targetType.FullName + ", " + targetType.Assembly.GetName().Name);
     emptyFactory = targetType => GuidKey.Empty(targetType.FullName + ", " + targetType.Assembly.GetName().Name);
 }
        public bool TryGet <T>(string key, out T value)
        {
            if (storage.TryGetValue(key, out object target))
            {
                if (target == null)
                {
                    value = default(T);
                    return(true);
                }

                log.Debug($"Get: Key: '{key}', RequiredType: '{typeof(T).FullName}', ActualType: '{target.GetType().FullName}'.");

                if (target is T targetValue)
                {
                    value = targetValue;
                    return(true);
                }

                JsonElement element = (JsonElement)target;

                if (typeof(T) == typeof(string))
                {
                    value = (T)(object)element.GetString();
                    return(true);
                }

                if (typeof(T) == typeof(int))
                {
                    value = (T)(object)element.GetInt32();
                    return(true);
                }

                if (typeof(T) == typeof(long))
                {
                    value = (T)(object)element.GetInt64();
                    return(true);
                }

                if (typeof(T) == typeof(decimal))
                {
                    value = (T)(object)element.GetDecimal();
                    return(true);
                }

                if (typeof(T) == typeof(double))
                {
                    value = (T)(object)element.GetDouble();
                    return(true);
                }

                if (typeof(T) == typeof(bool))
                {
                    value = (T)(object)element.GetBoolean();
                    return(true);
                }

                if (typeof(T) == typeof(IKey))
                {
                    if (element.ValueKind == JsonValueKind.Null)
                    {
                        value = default(T);
                        return(true);
                    }

                    string type = element.GetProperty("Type").GetString();
                    if (element.TryGetProperty("Guid", out JsonElement rawGuid))
                    {
                        string rawGuidValue = rawGuid.GetString();
                        if (rawGuidValue == null)
                        {
                            value = (T)(object)GuidKey.Empty(type);
                        }
                        else
                        {
                            value = (T)(object)GuidKey.Create(Guid.Parse(rawGuidValue), type);
                        }

                        return(true);
                    }
                    else if (element.TryGetProperty("Identifier", out JsonElement rawIdentifier))
                    {
                        string rawIdentifierValue = rawIdentifier.GetString();
                        if (rawIdentifierValue == null)
                        {
                            value = (T)(object)StringKey.Empty(type);
                        }
                        else
                        {
                            value = (T)(object)StringKey.Create(rawIdentifierValue, type);
                        }

                        return(true);
                    }
                }

                if (typeof(T) == typeof(Color))
                {
                    byte[] parts = element.GetString().Split(new char[] { ';' }).Select(p => Byte.Parse(p)).ToArray();
                    value = (T)(object)Color.FromArgb(parts[0], parts[1], parts[2], parts[3]);
                    log.Debug($"Get: Color: '{value}'.");
                    return(true);
                }

                if (typeof(T) == typeof(Price))
                {
                    log.Debug($"Get: Price value type: '{element.GetProperty("Value").GetType().FullName}'.");
                    decimal priceValue    = element.GetProperty("Value").GetDecimal();
                    string  priceCurrency = element.GetProperty("Currency").GetString();
                    value = (T)(object)new Price(priceValue, priceCurrency);
                    return(true);
                }

                if (typeof(T) == typeof(DateTime))
                {
                    string rawDateTime = element.GetString();
                    if (DateTime.TryParse(rawDateTime, out DateTime dateTime))
                    {
                        value = (T)(object)dateTime;
                        return(true);
                    }
                    else
                    {
                        log.Warning($"Get: Key: '{key}' not parseable to datetime from value '{rawDateTime}'.");
                        value = default(T);
                        return(false);
                    }
                }
            }

            log.Debug($"Get: Key: '{key}' NOT FOUND. Storage: '{JsonSerializer.Serialize(storage)}'.");
            value = default(T);
            return(false);
        }
Beispiel #24
0
        public bool TryGet <T>(string key, out T value)
        {
            if (storage.TryGetValue(key, out object target))
            {
                if (target == null)
                {
                    value = default(T);
                    return(true);
                }

                log.Debug($"Get: Key: '{key}', RequiredType: '{typeof(T).FullName}', ActualType: '{target.GetType().FullName}'.");
                if (target is T targetValue)
                {
                    value = targetValue;
                    return(true);
                }

                if (typeof(T) == typeof(int) && target.GetType() == typeof(long))
                {
                    value = (T)(object)(int)(long)target;
                    return(true);
                }

                if (typeof(T) == typeof(decimal) && target.GetType() == typeof(double))
                {
                    value = (T)(object)(decimal)(double)target;
                    return(true);
                }

                if (typeof(T) == typeof(IKey) && target is JsonObject json)
                {
                    string type = (string)json["Type"];
                    if (json.TryGetValue("Guid", out object rawGuid))
                    {
                        if (rawGuid == null)
                        {
                            value = (T)(object)GuidKey.Empty(type);
                        }
                        else
                        {
                            value = (T)(object)GuidKey.Create(Guid.Parse((string)rawGuid), type);
                        }

                        return(true);
                    }
                    else if (json.TryGetValue("Identifier", out object rawIdentifier))
                    {
                        if (rawIdentifier == null)
                        {
                            value = (T)(object)StringKey.Empty(type);
                        }
                        else
                        {
                            value = (T)(object)StringKey.Create((string)rawIdentifier, type);
                        }

                        return(true);
                    }
                }

                if (typeof(T) == typeof(Color) && target is string rawColor)
                {
                    byte[] parts = rawColor.Split(new char[] { ';' }).Select(p => Byte.Parse(p)).ToArray();
                    value = (T)(object)Color.FromArgb(parts[0], parts[1], parts[2], parts[3]);
                    log.Debug($"Get: Color: '{value}'.");
                    return(true);
                }

                if (typeof(T) == typeof(Price) && target is JsonObject priceJson)
                {
                    log.Debug($"Get: Price value type: '{priceJson["Value"].GetType().FullName}'.");
                    decimal priceValue    = (decimal)(double)priceJson["Value"];
                    string  priceCurrency = (string)priceJson["Currency"];
                    value = (T)(object)new Price(priceValue, priceCurrency);
                    return(true);
                }

                if (typeof(T) == typeof(DateTime) && target is string rawDateTime)
                {
                    if (DateTime.TryParse(rawDateTime, out DateTime dateTime))
                    {
                        value = (T)(object)dateTime;
                        return(true);
                    }
                    else
                    {
                        log.Warning($"Get: Key: '{key}' not parseable to datetime from value '{rawDateTime}'.");
                        value = default(T);
                        return(false);
                    }
                }
            }

            log.Debug($"Get: Key: '{key}' NOT FOUND.");
            value = default(T);
            return(false);
        }