public static void Import(IRepository destination,IDictionary source) { foreach(var key in source.Keys) { destination.Set(key.ToString(), source[key]); } }
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)); } } }
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); }
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; } } }
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); }
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; } } }
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; })); }
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; }); }
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); } } }
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); }
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()); }
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); }
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); }
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 }); }
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); }
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)); }
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); }
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(); } }
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 }); }
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 }); }
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); }
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; }
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(); }
public IQueryable <LanguageViewModel> GetAllAsNoTrackingMapped() { return(LanguageRepository.Set().AsNoTracking().To <LanguageViewModel>()); }
public IEnumerable <Language> GetAllLanguages() { return(_languageRepository.Set().ToList()); }
private async Task <bool> IsPromotionExists(string userId, PromotionEnum promotion) { return(await _promotionRepository.Set().AsNoTracking().AnyAsync(x => (x.UserId == userId) && (x.Type == promotion))); }