Esempio n. 1
0
 public static void Import(IRepository destination,IDictionary source)
 {
     foreach(var key in source.Keys)
     {
         destination.Set(key.ToString(), source[key]);
     }
 }
Esempio n. 2
0
 public static void Import(IRepository destination,IReadOnlyRepository sourceRepository)
 {
     var getKeys = sourceRepository as IGetKeys;
     if(getKeys != null)
     {
         foreach(var key in getKeys.GetKeys())
         {
             destination.Set(key, sourceRepository.Get(key));
         }
     }
 }
Esempio n. 3
0
        public async Task Handle(Declaration_CreateCommand command)
        {
            Declaration declaration = new Declaration()
            {
                Id = command.Id, Description = command.Description, Title = command.Title
            };
            Declaration_CreateEvent declarationCreateEvent = new Declaration_CreateEvent()
            {
                Id = command.Id, Description = command.Description, Title = command.Title
            };
            await repository.Set(declaration);

            await eventRepository.Set(declarationCreateEvent);
        }
Esempio n. 4
0
        public void Load(string input)
        {
            var lines = input.Split(Environment.NewLine);

            for (var i = 0; i < lines.Length; ++i)
            {
                var route = ConvertLineFromFile(lines[i]);
                if (route != null)
                {
                    _routeRepository.Set(route);
                    break;
                }
            }
        }
Esempio n. 5
0
        public MovieRatingSource CreateSourceFromName(string code)
        {
            var source = _repository.Set <MovieSource>().FirstOrDefault(s => s.Code == code);

            if (source == null)
            {
                throw new InvalidDataException($"Could not find a MovieSource record with code {code}. Make sure that the MovieContext has a record in OnModelCreating.");
            }

            return(new MovieRatingSource()
            {
                Source = source
            });
        }
        public async Task <User> GetCurrentUserAsync()
        {
            if (currentUserCached is null)
            {
                string userId = httpContext.User.GetId();

                User foundUser = await userRepository.Set().Include(x => x.Wallet)
                                 .FirstOrDefaultAsync();

                currentUserCached = foundUser;
            }

            return(currentUserCached);
        }
Esempio n. 7
0
        public void Load(string input)
        {
            var lines = input.Split(Environment.NewLine);

            for (var i = 0; i < lines.Length; ++i)
            {
                var aircraft = ConvertLineFromFile(lines[i]);
                if (aircraft != null)
                {
                    _aircraftRepository.Set(aircraft);
                    break;
                }
            }
        }
Esempio n. 8
0
        public IFixedCostType SetFixedCostType(int?id, string name, int percent)
        {
            if ((percent < 0) || (percent > 100))
            {
                throw new InvalidOperationException($"Procento musi byt cele cislo 0 az 100");
            }

            return(m_costTypeRepository.Set(id,
                                            e =>
            {
                e.Name = name;
                e.PercentToDistributeAmongProducts = percent;
            }));
        }
Esempio n. 9
0
        public void SetValue(int typeId, int year, int month, decimal value)
        {
            var ett = m_costValueRepository.All()
                      .FirstOrDefault(e => (e.FixedCostTypeId == typeId) && (e.Year == year) && (e.Month == month));

            m_costValueRepository.Set(ett?.Id,
                                      e =>
            {
                e.FixedCostTypeId = typeId;
                e.Month           = month;
                e.Year            = year;
                e.Value           = value;
            });
        }
Esempio n. 10
0
        public static async Task RemoveAllChannels(this IRepository repository)
        {
            await repository.Clear <Channel>();

            var notifications = await repository.GetAll <Notification>();

            foreach (var notification in notifications)
            {
                if (!notification.Channel.IsEmpty())
                {
                    notification.Channel = null;
                    await repository.Set(notification.Id.ToString(), notification);
                }
            }
        }
Esempio n. 11
0
        public static async Task RemoveChannel(this IRepository repository, string channelId)
        {
            await repository.Remove <Channel>(channelId);

            var notifications = await repository.GetAll <Notification>();

            foreach (var notification in notifications)
            {
                if (notification.Channel?.Equals(channelId, StringComparison.InvariantCultureIgnoreCase) ?? false)
                {
                    notification.Channel = null;
                    await repository.Set(notification.Id.ToString(), notification);
                }
            }
        }
        protected override void OnValidEventReceived(ReceivedEventArgs <TPayload> args)
        {
            switch (args.Event.EventType)
            {
            case EventType.Set:
                _repository.Set(args.Event.Payload);
                break;

            case EventType.Remove:
                _repository.Remove(args.Event.Payload.Id);
                break;
            }

            base.OnValidEventReceived(args);
        }
Esempio n. 13
0
        public void LoadWorld(long worldId)
        {
            if (worldRepository.First() == null)
            {
                var newWorld = WorldFactory.Create();
                world = worldRepository.Set(newWorld);
                Trace.TraceInformation("New world detected, generating");
            }
            else
            {
                world = worldRepository.Get(worldId);
            }

            world.Load();
        }
        public void Handle(AddUserCommand command)
        {
            var users   = new List <User>(_repository.Get <User>());
            var newUser = new User
            {
                Id          = (users.Count + 1).ToString(),
                Name        = command.Name,
                Permissions = command.Permissions.Select(i => new Permission {
                    Name = i
                }).ToArray()
            };

            users.Add(newUser);
            _repository.Set(users.ToArray());
        }
Esempio n. 15
0
        private async Task CreateIfNotExists(YouTubeVideo video)
        {
            var seedExists = await _db.Contains(video.Id);

            if (!seedExists)
            {
                await _db.Set(video, video.Id);

                _logger.LogInformation($"Created video id {video.Id} in database.");
            }
            else
            {
                _logger.LogInformation($"Found video id {video.Id} in database. Not creating.");
            }
        }
        public async Task <AccountDTO[]> Handle(WalletStateRequest request, CancellationToken cancellationToken)
        {
            User currentUser = await currentUserService.GetCurrentUserAsync();

            var response = await accountRepository.Set()
                           .Where(x => x.WalletId == currentUser.Wallet.Id)
                           .Select(x => new AccountDTO()
            {
                CurrentBalance = x.Balance,
                Currency       = x.Currency.IsoAlfaCode,
                AccountId      = x.Id
            }).ToArrayAsync();


            return(response);
        }
Esempio n. 17
0
        public void Load(string input)
        {
            var passengers = new List <Passenger>();
            var lines      = input.Split(Environment.NewLine);

            for (var i = 0; i < lines.Length; ++i)
            {
                var passenger = ConvertLineFromFile(lines[i]);
                if (passenger != null)
                {
                    passengers.Add(passenger);
                }
            }

            _passengerRepository.Set(passengers);
        }
Esempio n. 18
0
        private TeamLocalization GetTeamLocalizationFromModel(Team team, TeamModel model)
        {
            var language = _languageRepository.Set().FirstOrDefault(l => l.Id == model.LanguageId);

            if (language == null)
            {
                throw new ArgumentException($"can\'t find language {model.LanguageId}", nameof(model));
            }

            return(new TeamLocalization
            {
                Team = team,
                Language = language,
                Name = model.Name,
                Description = model.Description
            });
        }
Esempio n. 19
0
        public void Import(int itemCount)
        {
            if (itemCount <= 0)
            {
                throw new ArgumentOutOfRangeException(nameof(itemCount));
            }

            var items = new List <TEntity>();

            for (var i = 0; i < itemCount; i++)
            {
                var entity = _service.Import(i);
                items.Add(entity);
            }

            _repository.Set(items);
        }
Esempio n. 20
0
        public Task <List <SearchResult> > Query(string text)
        {
            var result = new List <SearchResult>();

            if (string.IsNullOrWhiteSpace(text))
            {
                return(Task.FromResult(result));
            }

            var keys = new[] { text };

            if (text.Contains(" "))
            {
                keys = text.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
            }

            var words = _wordRepository.Set <Word>();

            foreach (var key in keys)
            {
                var _key = key;
                words = words.Where(x => x.Key.Contains(_key) ||
                                    (x.Translation_TR != null && x.Translation_TR.Contains(_key)) ||
                                    (x.Translation_EN != null && x.Translation_EN.Contains(_key)));
            }

            var wordResults = words.OrderByDescending(x => x.Id).Skip(0).Take(10).ToList();

            foreach (var item in wordResults)
            {
                var exp = string.Format("{0}", item.Translation_EN ?? item.Translation_TR);
                if (exp.Length > 15)
                {
                    exp = exp.Substring(0, 15);
                }
                result.Add(new SearchResult
                {
                    Url    = string.Format("/word/detail/{0}", item.Key),
                    Name   = string.Format("{0}, {1} ...", item.Key, exp),
                    ImgUrl = "/public/img/word.png"
                });
            }

            return(Task.FromResult(result));
        }
Esempio n. 21
0
        public ImageModel UpdateImageById(int id, string uri)
        {
            if (uri == null)
            {
                throw new Exception("File was null");
            }
            var image = _imageRepository.Set().FirstOrDefault(a => a.Id == id);

            if (image == null)
            {
                throw new Exception("Image with such id does not exist");
            }

            image.Uri = "https://sporthubblob.blob.core.windows.net/imagecontainer/" + uri;
            _imageRepository.Update(image);

            return(GetModel(image));
        }
        public async Task <OperationDTO[]> Handle(AccountOperationHistoryRequest request, CancellationToken cancellationToken)
        {
            User currentUser = await currentUserService.GetCurrentUserAsync();

            var response = await operationRepository.Set().Where(x => x.Account.Wallet.Id == currentUser.Wallet.Id)
                           .OrderBy(x => x.Date)
                           .Select(x => new OperationDTO()
            {
                Amount        = x.Amount,
                Currency      = x.Account.Currency.IsoAlfaCode,
                Direction     = x.Direction.ToString(),
                OperationDate = x.Date,
                Id            = x.Id
            })
                           .ToArrayAsync();

            return(response);
        }
Esempio n. 23
0
        public void Invite(string userName, string groupName)
        {
            UserIdentity user  = m_UserRepository.Set().Where(p => p.UserName == userName).FirstOrDefault();
            Group        group = m_GroupRepository.Set().Where(p => p.Name == groupName).FirstOrDefault();

            if (user != null && group != null)
            {
                UserInvitation target = new UserInvitation
                {
                    Date  = DateTime.Now,
                    User  = user,
                    Group = group
                };

                m_UserInvitationRepository.Set().Add(target);
                m_UserInvitationRepository.SaveChanges();
            }
        }
Esempio n. 24
0
        private SportArticle GetSportArticleFromModel(SportArticleModel model)
        {
            if (model == null)
            {
                throw new ArgumentNullException(nameof(model));
            }

            var article = _articleService.GetArticleById(model.ArticleId) ?? _articleModelService.GetArticleFromModel(model);

            var team = _teamRepository.Set()
                       .FirstOrDefault(t => t.Id == model.TeamId) ??
                       throw new Exception($"team {model.TeamId} doesn\'t exist");

            return(new SportArticle
            {
                ArticleId = model.ArticleId,
                Article = article,
                Team = team,
                TeamId = team.Id
            });
        }
Esempio n. 25
0
        private Conference GetConferenceFromModel(ConferenceModel model)
        {
            if (model == null)
            {
                throw new ArgumentNullException(nameof(model));
            }
            if (_conferenceRepository.Set().Any(a => a.Id == model.ConferenceId))
            {
                throw new ArgumentException($"Conference id {model.ConferenceId} is already taken", nameof(model));
            }
            var category = _categoryRepository.Set().FirstOrDefault(c => c.Id == model.CategoryId);

            if (category == null)
            {
                throw new ArgumentException($"Category {model.CategoryId} not found", nameof(model));
            }
            return(new Conference
            {
                Category = category,
                Show = (bool)model.Show
            });
        }
Esempio n. 26
0
        public async ValueTask <OperationResult> Approve(int Id, PostType postType, int type)
        {
            switch (postType)
            {
            case PostType.Company:
            {
                var item = await _companiesRepository.Set().FirstOrDefaultAsync(j => j.Id == Id);

                item.isApproved = type;

                var success = await _companiesRepository.SaveChangesAsync();

                return(success);
            }

            case PostType.Contestant:
            {
                var item = await _contestantRepository.Set().FirstOrDefaultAsync(j => j.Id == Id);

                item.isApproved = type;

                var success = await _contestantRepository.SaveChangesAsync();

                return(success);
            }

            case PostType.Job:
            {
                var item = await _jobsRepository.Set().FirstOrDefaultAsync(j => j.Id == Id);

                item.isApproved = type;

                var success = await _jobsRepository.SaveChangesAsync();

                return(success);
            }
            }
            return(null);
        }
Esempio n. 27
0
        public UserAuthTokenRequestValidator(IRepository <User> userRepo)
        {
            RuleFor(model => model.Email).NotEmpty();

            RuleFor(model => model.Email).EmailAddress();

            RuleFor(model => model.Password).NotEmpty()
            .MinimumLength(6);

            RuleSet("EmailIsRegistered", () =>
            {
                RuleFor(model => model.Email)
                .MustAsync(async(email, token) =>
                {
                    bool userExist = await userRepo.Set().AnyAsync(x => x.Email == email);
                    return(userExist);
                })
                .WithMessage("User with thie Email not registered");
            });

            CascadeMode = CascadeMode.Continue;
        }
Esempio n. 28
0
        private IEnumerable <Event> Process <T>(T cmd) where T : Command
        {
            var evnts = new List <Event>();

            var cmdType = cmd.GetType();

            if (!_commandHandlers.ContainsKey(cmdType))
            {
                return(evnts);
            }

            var aggregateType = _commandHandlers[cmdType];
            var aggregate     = _repository.Get(aggregateType, cmd.AggregateId);

            foreach (var evnt in ((dynamic)aggregate).Handle((dynamic)cmd))
            {
                evnts.Add(evnt);
            }

            _repository.Set(cmd.AggregateId, aggregate, evnts);
            return(evnts);
        }
        /// <summary>
        /// Adds missing movie sources from raw result that aren't already stored
        /// </summary>
        /// <param name="rawResults">List of deserialized models</param>
        public void AddMissingMovieSources(IEnumerable <MovieEntities.Serialization.MovieRating> rawResults)
        {
            var uniqueCodes  = rawResults.SelectMany(r => r.Sources).Distinct();
            var missingCodes = uniqueCodes.Where(u => !_repository
                                                 .Set <MovieSource>()
                                                 .Select(s => s.Code)
                                                 .Contains(u))
                               .ToList();

            // Just exit if we already have all the sources saved
            if (!missingCodes.Any())
            {
                return;
            }

            Console.WriteLine($"Adding ${missingCodes.Count} missing codes");

            _repository.AddRange(missingCodes.Select(code => new MovieSource {
                Name = code, Code = code
            }));
            _repository.Save();
        }
Esempio n. 30
0
 public IQueryable <LanguageViewModel> GetAllAsNoTrackingMapped()
 {
     return(LanguageRepository.Set().AsNoTracking().To <LanguageViewModel>());
 }
Esempio n. 31
0
 public IEnumerable <Language> GetAllLanguages()
 {
     return(_languageRepository.Set().ToList());
 }
Esempio n. 32
0
 private async Task <bool> IsPromotionExists(string userId, PromotionEnum promotion)
 {
     return(await _promotionRepository.Set().AsNoTracking().AnyAsync(x => (x.UserId == userId) && (x.Type == promotion)));
 }