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"));
        }
Ejemplo n.º 2
0
        public static async Task InitializeAsync(UserManager <ApplicationUser> userManager, ICommandDispatcher commands)
        {
            IdentityResult userResult = await userManager.CreateAsync(
                new ApplicationUser(ClaimsPrincipalExtensions.DemoUserName),
                ClaimsPrincipalExtensions.DemoUserPassword
                );

            if (!userResult.Succeeded)
            {
                throw Ensure.Exception.InvalidOperation("Unnable to create demo user.");
            }

            ApplicationUser user = await userManager.FindByNameAsync(ClaimsPrincipalExtensions.DemoUserName);

            if (user == null)
            {
                throw Ensure.Exception.InvalidOperation("Unnable find created demo user.");
            }

            IKey userKey = StringKey.Create(user.Id, "User");

            await commands.HandleAsync(WrapCommand(userKey, new CreateCurrency("USD", "$")));

            await commands.HandleAsync(WrapCommand(userKey, new CreateCategory("Car", "Gas etc.", Color.FromArgb(255, 145, 206, 234))));

            await commands.HandleAsync(WrapCommand(userKey, new CreateCategory("Home", "DIY", Color.FromArgb(255, 207, 180, 141))));

            await commands.HandleAsync(WrapCommand(userKey, new CreateCategory("Food", "Ingredients for home made meals", Color.FromArgb(255, 155, 237, 144))));
        }
Ejemplo n.º 3
0
        public static Task Execute <T, TRepository>(this AggregateRootCommandExecutor <T, TRepository> executor, Envelope envelope, Func <IKey, T> handler)
            where T : AggregateRoot
            where TRepository : IRepository <T, IKey>
        {
            return(executor.Execute(() =>
            {
                IKey userKey;
                if (!envelope.Metadata.TryGet("UserKey", out userKey))
                {
                    if (envelope.Metadata.TryGet("UserId", out string userId))
                    {
                        userKey = StringKey.Create(userId, "User");
                    }
                    else
                    {
                        userKey = StringKey.Empty("User");
                    }
                }

                T model = handler(userKey);

                foreach (IEvent item in model.Events)
                {
                    if (item is UserEvent payload)
                    {
                        payload.UserKey = userKey;
                    }
                }

                return model;
            }));
        }
Ejemplo n.º 4
0
        private (string connectionId, IKey key) GetUserInfo()
        {
            string connectionId = Context.ConnectionId;
            string userId       = Context.User.FindFirstValue(ClaimTypes.NameIdentifier);
            IKey   userKey      = StringKey.Create(userId, "User");

            return(connectionId, userKey);
        }
Ejemplo n.º 5
0
        public Task <TOutput> QueryAsync <TOutput>(IQuery <TOutput> query)
        {
            if (query is UserQuery userQuery)
            {
                string userId = httpContext.User.FindFirstValue(ClaimTypes.NameIdentifier);
                if (!String.IsNullOrEmpty(userId))
                {
                    userQuery.UserKey = StringKey.Create(userId, "User");
                }
            }

            return(inner.QueryAsync(query));
        }
Ejemplo n.º 6
0
        private (string connectionId, IKey key) GetUserInfo()
        {
            string connectionId = Context.ConnectionId;
            string userId       = Context.User.FindFirstValue(ClaimTypes.NameIdentifier);

            if (userId == null)
            {
                throw new UnauthorizedAccessException();
            }

            IKey userKey = StringKey.Create(userId, "User");

            return(connectionId, userKey);
        }
Ejemplo n.º 7
0
        public void StringKey_Equal()
        {
            StringKey key1 = StringKey.Create("1", "Product");
            StringKey key2 = StringKey.Create("1", "Product");

            Assert.AreEqual(key1, key2);

            key1 = StringKey.Create("1", "Product");
            key2 = StringKey.Create("2", "Product");
            Assert.AreNotEqual(key1, key2);

            key1 = StringKey.Create("1", "Product");
            key2 = StringKey.Create("1", "Term");
            Assert.AreNotEqual(key1, key2);
        }
Ejemplo n.º 8
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);
        }
Ejemplo n.º 9
0
        public Task HandleAsync <TCommand>(TCommand command)
        {
            Envelope envelope = command as Envelope;

            if (envelope == null)
            {
                envelope = Envelope.Create <TCommand>(command);
            }

            string userId = httpContext.User.FindFirstValue(ClaimTypes.NameIdentifier);

            if (!String.IsNullOrEmpty(userId))
            {
                IKey userKey = StringKey.Create(userId, "User");
                envelope.Metadata.Add("UserKey", userKey);

                if (command is ICommand esCommand)
                {
                    hub.AddCommand(esCommand.Key, userKey);
                }
            }

            return(inner.HandleAsync(envelope));
        }
Ejemplo n.º 10
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);
        }
        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);
        }