Ejemplo n.º 1
0
 public async Task <List <Product> > GetAllProductsDataAsync()
 {
     using (var context = _factory.GetContext())
     {
         return(await context.Products.ToListAsync());
     }
 }
Ejemplo n.º 2
0
        private IEnumerable <LabelEntity> MarkLabelsAsProcessedAndGetMissing(DatabaseConnectionModel connectionModel1,
                                                                             DatabaseConnectionModel connectionModel2,
                                                                             LabelsGeneratorDbTables tables,
                                                                             DateTime date)
        {
            using (var context1 = _contextFactory.GetContext(connectionModel1, tables))
                using (var context2 = _contextFactory.GetContext(connectionModel2, tables))
                {
                    var reportId = Guid.NewGuid();

                    var startDate = date.StartOfDay();
                    var endDate   = date.EndOfDayForDatabase();

                    var labels           = context1.Set <LabelEntity>().Where(x => x.Status == 0 && x.CreateDate >= startDate && x.CreateDate <= endDate).ToArray();
                    var labelIdentifiers = labels.Select(x => x.UniqueID.Trim()).ToArray();

                    var identifiers = context2.Set <CustomerEntity>().Where(x => labelIdentifiers.Contains(x.UniqueID.Trim())).Select(x => x.UniqueID.Trim()).ToArray();
                    var foundLabels = labels.Where(x => identifiers.Contains(x.UniqueID.Trim())).ToArray();
                    foreach (var label in foundLabels)
                    {
                        label.Status = 1;
                    }
                    context1.SaveChanges();

                    var notFoundLabels = labels.Where(x => !identifiers.Contains(x.UniqueID.Trim())).ToArray();
                    return(notFoundLabels);
                }
        }
Ejemplo n.º 3
0
 public List <Product> GetAllProductsData()
 {
     using (var context = _factory.GetContext())
     {
         return(context.Products.ToList());
     }
 }
Ejemplo n.º 4
0
        public async Task<int> AddBalanceEntry(Balance balance)
        {
            var context = _context.GetContext();
            context.Balances.Add(balance);

            await context.SaveChangesAsync();
            return balance.Id;
        }
Ejemplo n.º 5
0
        public string GetMap(string domainKey)
        {
            IContext       ctx        = contextFactory.GetContext(domainKey);
            IDomainMap     domainMap  = ctx.DomainMap;
            IDomainMap     stripped   = DomainMapStripper.StripDomainMap(domainMap);
            IMapSerializer serializer = new DefaultMapSerializer();

            return(serializer.Serialize(stripped));
        }
Ejemplo n.º 6
0
 public Feed AddFeed(Feed feed)
 {
     using (var context = contextFactory.GetContext())
     {
         feed.DateCreated = DateTime.Now;
         feed             = context.Feeds.Add(feed);
         context.SaveChanges();
         return(feed);
     }
 }
        public async Task <int> AddTransaction(TransferTransaction model)
        {
            var context = _context.GetContext();

            context.TransferTransactions.Add(model);

            await context.SaveChangesAsync();

            return(model.Id);
        }
Ejemplo n.º 8
0
 public void AddUser(string id)
 {
     using (var context = contextFactory.GetContext())
     {
         context.Add(context.UsersRepository, new UserContract()
         {
             Id = id
         });
         context.Save();
     }
 }
Ejemplo n.º 9
0
        public async Task <int> AddItemAsync(HistoryDto item)
        {
            using (var context = _contextFactory.GetContext())
            {
                var entity = _mapper.Map <History>(item);
                context.Histories.Add(entity);

                await context.SaveChangesAsync();

                return(await Task.FromResult(entity.Id));
            }
        }
Ejemplo n.º 10
0
 public void AddTag(int postId, Tag tag)
 {
     using (var context = contextFactory.GetContext())
     {
         var         post   = context.PostsRepository.Where(x => x.Id == postId).FirstOrDefault();
         TagContract newTag = new TagContract {
             Id = tag.Id, Name = tag.Name
         };
         post.Tags.Add(newTag);
         context.Save();
     }
 }
        public async Task <int> AddItemAsync(IntervalTemplateDto item)
        {
            using (var context = _contextFactory.GetContext())
            {
                var entity = _mapper.Map <IntervalTemplate>(item);
                context.Intervals.Add(entity);

                await context.SaveChangesAsync();

                return(await Task.FromResult(entity.Id));
            }
        }
Ejemplo n.º 12
0
        public async Task <int> AddUser(User user)
        {
            var context = _context.GetContext();

            user.PasswordHash = PasswordHashHelper.HashPassword(user.PasswordHash);
            user.CreationDate = DateTime.Now;
            context.Users.Add(user);

            await context.SaveChangesAsync();

            return(user.Id);
        }
Ejemplo n.º 13
0
 public void AddComment(Comment comment, int postId)
 {
     using (var context = contextFactory.GetContext())
     {
         context.Add(context.CommentsRepository, new CommentContract()
         {
             Id        = comment.Id,
             Content   = comment.Content,
             PostId    = postId,
             StudentId = comment.StudentId
         });
         context.Save();
     }
 }
Ejemplo n.º 14
0
        public string Format(List <object> arguments, string separator, string itemFormat)
        {
            var formattedValues = new StringBuilder();

            var i = 0;

            foreach (var argument in arguments)
            {
                if (argument is DObject obj)
                {
                    var formatter = new NumeratorMultiValueFormatter <T>(_keywordProvider, _templates, _contextFactory);
                    var formatted = formatter.Format(_contextFactory.GetContext(obj), itemFormat);
                    formattedValues.Append(formatted);
                }
                else
                {
                    if (string.IsNullOrEmpty(itemFormat))
                    {
                        formattedValues.Append(argument);
                    }
                    else
                    {
                        formattedValues.Append(string.Format("{" + $"0:{itemFormat}" + "}", argument));
                    }
                }
                if (i < arguments.Count - 1)
                {
                    formattedValues.Append(separator);
                    i++;
                }
            }

            return(formattedValues.ToString());
        }
Ejemplo n.º 15
0
 /// <inheritdoc cref="GetAllProductsData"/>
 public async Task <List <Product> > GetAllProductsData()
 {
     using (var context = _factory.GetContext())
     {
         return(await Task.Run(() => context.Products.ToList()));
     }
 }
Ejemplo n.º 16
0
        public async Task Handle(DeleteTransactionsAndGroupsAssignedToRuleCommand command)
        {
            using var context = contextFactory.GetContext();

            var group = await context.Groups
                        .Where(g => g.Rule.Id == command.Rule.Id)
                        .SingleOrDefaultAsync();

            if (group == null)
            {
                logger.LogInformation($"Group {command.Rule.GroupName} doesn't exist, continuing");
                return;
            }

            using (var scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                await context.BankTransactionGroups
                .Where(b => b.GroupId == group.Id)
                .DeleteAsync();

                context.Groups.Remove(group);
                await context.SaveChangesAsync();

                scope.Complete();
            }
        }
Ejemplo n.º 17
0
        public void AddPost(Post post, string userId)
        {
            using (var context = contextFactory.GetContext())
            {
                var user = context.UsersRepository.Where(m => m.Id == userId).FirstOrDefault();
                context.Add(context.PostsRepository, new PostContract()
                {
                    Id      = post.Id,
                    Content = post.Content,
                    Created = DateTime.Now,
                    User    = user
                });

                context.Save();
            }
        }
Ejemplo n.º 18
0
        public void AddPost(Post post, int studentId)
        {
            using (var context = contextFactory.GetContext())
            {
                var student = context.StudentsRepository.Where(m => m.Id == studentId).FirstOrDefault();
                context.Add(context.PostsRepository, new PostContract()
                {
                    Id      = post.Id,
                    Title   = post.Title,
                    Content = post.Content,
                    Created = DateTime.Now,
                    Author  = student
                });

                context.Save();
            }
        }
Ejemplo n.º 19
0
 public async Task <IEnumerable <BankTransaction> > GetBankTransactions(Guid userId)
 {
     using var context = contextFactory.GetContext();
     return(await context.BankTransactions
            .Where(t => t.User.Id == userId)
            .Include(c => c.BankTransactionType)
            .AsNoTracking()
            .ToListAsync());
 }
Ejemplo n.º 20
0
        public int CreateProduct(ProductModel productModel)
        {
            productModel.CategoryIds = productModel.CategoryIds ?? new List <int>();
            var product = productModel.ToEntity();

            using (var context = _factory.GetContext())
            {
                CheckIfAllCategoriesExist(productModel.CategoryIds, context);
                var result = context.Products.Add(product);
                context.SaveChanges();

                AddCategoriesToProduct(product.Id, productModel.CategoryIds, context);

                context.SaveChanges();

                return(product.Id);
            }
        }
Ejemplo n.º 21
0
        public bool Delete(IEnumerable <string> ids)
        {
            using (var context = _ContextFactory.GetContext())
            {
                foreach (var id in ids)
                {
                    if (!context.Products.Any(c => c.Id.Equals(id)))
                    {
                        return(false);
                    }

                    Product product = context.Products
                                      .Where(c => c.Id == id)
                                      .FirstOrDefault() ?? throw new NullReferenceException($"{nameof(product)} is null.");
                    context.Products.Remove(product);
                }
                context.SaveChanges();
                return(true);
            }
        }
Ejemplo n.º 22
0
        public async Task <string> GetExportedJson()
        {
            using var context = contextFactory.GetContext();
            var bankTransactionTypes = await context.BankTransactionTypes.ToListAsync();

            var rules = await context.Rules.ToListAsync();

            var groups = await context.Groups.ToListAsync();

            return("!BANKTRANSACTIONTYPES!" + "\r\n" + bankTransactionTypes.ToJson() + "\r\n" +
                   "!RULES!" + "\r\n" + rules.ToJson() + "\r\n" +
                   "!GROUPS!" + "\r\n" + groups.ToJson());
        }
Ejemplo n.º 23
0
        public bool Delete(IEnumerable <string> ids)
        {
            if (ids == null)
            {
                throw new ArgumentNullException(nameof(ids), $"{nameof(ids)} is null.");
            }

            using (var context = _ContextFactory.GetContext())
            {
                foreach (var id in ids)
                {
                    if (!context.Categories.Any(c => c.Id.Equals(id)))
                    {
                        return(false);
                    }

                    Category category = context.Categories.Where(c => c.Id == id).FirstOrDefault() ?? throw new NullReferenceException($"{nameof(category)} is null.");
                    context.Categories.Remove(category);
                }
                context.SaveChanges();
                return(true);
            }
        }
        public void ContextFactoryMock_OnGetContext_ShouldReturnContext()
        {
            //Arrange
            var ContextFactoryMock = new Moq.Mock <IContextFactory>();

            ContextFactoryMock.Setup(obj => obj.GetContext()).Returns <ApplicationContext>(null);

            IContextFactory factory = ContextFactoryMock.Object;

            //Act
            var context = factory.GetContext();

            //Assert
            Assert.IsNull(context);
        }
        public async Task Handle(AcceptConnectionCommand command)
        {
            using var context = contextFactory.GetContext();

            var connectionToAccept = await context.UsersConnections.SingleOrDefaultAsync(c =>
                                                                                         c.UserRequestedToConnectId == command.UserId &&
                                                                                         c.UserRequestingConnectionId == command.HostUserIdToAcceptConnection);

            if (connectionToAccept == null)
            {
                throw new ConnectionDoesNotExistsException(command.HostUserIdToAcceptConnection, command.UserId);
            }

            connectionToAccept.IsRequestApproved = true;

            await context.SaveChangesAsync();
        }
Ejemplo n.º 26
0
        public async Task Handle(SaveRuleCommand command)
        {
            using var context = contextFactory.GetContext();
            Rule rule;

            if (command.Id != default)
            {
                rule = await context.Rules.SingleOrDefaultAsync(r => r.Id == command.Id) ?? new Rule();
            }
            else
            {
                rule = new Rule();
            }

            var isNewRule = rule.Id == default;

            mapper.Map(command, rule);

            if (isNewRule)
            {
                rule.Id = Guid.NewGuid();
                await context.AddAsync(rule);
            }

            if (command.BankTransactionTypeId != null)
            {
                rule.BankTransactionType = await context.BankTransactionTypes.SingleAsync(b => b.Id == command.BankTransactionTypeId);
            }
            else
            {
                rule.BankTransactionType = null;
            }

            rule.User = await context.Users.FindAsync(command.UserId);

            using (var scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                await context.SaveChangesAsync();

                await eventsBus.Publish(new RuleSavedEvent(rule, command.UserId));

                scope.Complete();
            }

            await eventsBus.Publish(new CommandCompletedEvent(command));
        }
Ejemplo n.º 27
0
        public async Task Handle(RequestUserConnectionCommand command)
        {
            await using var context = contextFactory.GetContext();
            var requestedUser = await context.Users.SingleOrDefaultAsync(u => u.Username == command.RequestedUsername);

            await Validate(command, context, requestedUser);

            var connection = new UsersConnection()
            {
                UserRequestedToConnectId   = requestedUser.Id,
                UserRequestingConnectionId = command.UserId
            };

            await context.AddAsync(connection);

            await context.SaveChangesAsync();
        }
Ejemplo n.º 28
0
        public async Task Handle(DeleteRuleCommand command)
        {
            using var context = contextFactory.GetContext();
            var rule = await context.Rules.SingleOrDefaultAsync(r => r.Id == command.RuleId && r.User.Id == command.UserId);

            if (rule == null)
            {
                throw new BankAnalizerException($"Invalid rule id {command.RuleId}");
            }

            using (var scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                await commandsBus.SendAsync(new DeleteTransactionsAndGroupsAssignedToRuleCommand(rule));

                context.Rules.Remove(rule);

                await context.SaveChangesAsync();

                scope.Complete();
            }
        }
Ejemplo n.º 29
0
        public async Task <User> Authenticate(string username, string password)
        {
            if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password))
            {
                return(null);
            }

            using var context = contextFactory.GetContext();
            var user = await context.Users.SingleOrDefaultAsync(x => x.Username == username);

            if (user == null)
            {
                return(null);
            }

            if (!VerifyPasswordHash(password, user.PasswordHash, user.PasswordSalt))
            {
                return(null);
            }

            return(user);
        }
Ejemplo n.º 30
0
 public DepositRepository(IContextFactory factory) : base(factory.GetContext())
 {
 }