private async Task ImportWord(DbTranslatedWord word, Language language) { if (await TryUseExisting(word, language)) { return; } if (await TryAddTranslation(word, language)) { return; } word.Validate(); var newWord = new DbWord { Cefr = word.Cefr, PartOfSpeech = word.PartOfSpeech, PictureId = word.PictureId, Translations = new Dictionary <string, DbTranslation> { { language, word.Translation ! } } }; var importedWord = await _words.Add(newWord); word.Id = importedWord.Id; }
private async Task ImportExpression(DbTranslatedExpression expression, Language language) { if (await TryUseExisting(expression, language)) { return; } if (await TryAddTranslation(expression, language)) { return; } await Task.WhenAll(expression.Words.Select(word => ImportWord(word, language))); expression.Validate(); var wordIds = expression.Words.Select(word => word.Id).ToArray(); var newExpression = new DbExpression { Cefr = expression.Cefr, ExprType = expression.ExprType, Translations = new Dictionary <string, DbWords> { { language, new DbWords { WordIds = wordIds } } } }; var importedExpression = await _expressions.Add(newExpression); expression.ExpressionId = importedExpression.Id; }
public void Now() { int count = 0; foreach (Type t in repo.GetAvailableTypes()) { Console.WriteLine(" {0}\t{1}", (++count).ToString(), t.ToString()); } IStore <Customer> customers = repo.GetStoreOf <Customer>(); using (customers.ScopedChanges()) { customers.Add(new Customer { BusinessName = "Test", ContactName = "Test", Phone = "+X (XXX) XXX XXXX" }); customers.Add(new Customer { BusinessName = "Test2", ContactName = "Test", Phone = "+X (XXX) XXX XXXX" }); customers.Add(new Customer { BusinessName = "Test3", ContactName = "Test", Phone = "+X (XXX) XXX XXXX" }); customers.Add(new Customer { BusinessName = "Test", ContactName = "Test", Phone = "+X (XXX) XXX XXXX" }); } Console.WriteLine(""); foreach (Customer c in repo.GetStoreOf <Customer>()) { Console.WriteLine(c.BusinessName); } Console.Write("Press any key to continue."); Console.ReadKey(); Console.WriteLine(); Console.WriteLine("Rolling back changes..."); using (customers.ScopedChanges()) { foreach (var c in customers .AsEnumerable() .Where(x => x.ContactName.ToLower().Contains("test") || x.BusinessName.ToLower().Contains("test") || !x.Phone.Any(m => char.IsLetter(m)))) { customers.Remove(c); } } }
public virtual async Task AppendEvent <TStream>(Guid aggregateId, IEvent @event, int?expectedVersion = null, Func <StreamState, Task> action = null) { var version = 1; var events = await GetEvents(aggregateId); var versions = events.Select(e => e.Version).ToList(); if (expectedVersion.HasValue) { if (versions.Contains(expectedVersion.Value)) { throw new Exception($"Version '{expectedVersion.Value}' already exists for stream '{aggregateId}'"); } } else { version = versions.DefaultIfEmpty(0).Max() + 1; } var stream = new StreamState { AggregateId = aggregateId, Version = version, Type = MessageBrokersHelper.GetTypeName(@event.GetType()), Data = @event == null ? "{}" : JsonConvert.SerializeObject(@event, JSON_SERIALIZER_SETTINGS) }; await _store.Add(stream); if (action != null) { await action(stream); } }
public async Task <ActionResult <Store> > PostStore(Store store) { _IStore.Add(store); await _IStore.SaveAsync(); return(CreatedAtAction("GetStore", new { id = store.StoreId }, store)); }
public async Task <IActionResult> Register(RegisterViewModel model) { if (ModelState.IsValid) { var user = _userStore.Queryable.SingleOrDefault(p => p.Name == model.UserName); if (user.IsNotNull()) { ModelState.AddModelError(string.Empty, "用户已存在"); return(View(model)); } user = new User { Name = model.UserName, PasswordHash = _passwordHash.ComputeHash(model.Password), Gender = model.IsMale ? UserGender.Male : UserGender.Female, }; _userStore.Add(user); await _userStore.Accessor.SaveChangesAsync(); return(RedirectToAction(nameof(Login))); } return(View(model)); }
public async Task <Evaluation> Update(Evaluation evaluation, int pages) { var profileId = evaluation.Profile.Id; var chapterId = evaluation.Submit.ChapterId; var pageIndex = evaluation.Submit.PageIndex; var stats = await _database.QueryStats(chapterId, profileId) ?? await _stats.Add(DbStats.Create(profileId, chapterId, pages)); if (evaluation.Result == Result.Correct) { var completedBefore = stats.Completed; stats = stats .WithSubmit(pageIndex) .WithUpdatedCompleted(); await _stats.Replace(stats); if (completedBefore != stats.Completed) { await UpdateProfile(evaluation.Profile); } } else { await _stats.Replace(stats.WithFailure(pageIndex)); } return(evaluation); }
public Response AddOrder(Order order) { bool areOrderTestsValid = order.Tests != null && !order.Tests.Any(x => x.Id <= 0) && order.Tests.Any(); int testIds = order.Tests.Select(x => x.Id).Distinct().Count(); bool areTestsInOrderUnique = testIds == order.Tests.Count(); if (order != null && areOrderTestsValid && areTestsInOrderUnique) { if (!IsOrderAlreadyExists(order.Id)) { _store.Add(order); return(new Response() { ResponseType = ResponseType.Success, Description = "Order is added." }); } } return(new Response() { ResponseType = ResponseType.Failed, Description = "Order isn't added." }); }
public virtual void Manage() { int option; do { this.ShowStore(); option = this.ExecuteMenu(); if (option != 3) { int code = LimitedIntDialog.Instance().Read("Código? ", 100); int amount = LimitedIntDialog.Instance().Read("Cantidad? ", 100); switch (option) { case 1: store.Add(code, amount); break; case 2: if (store.Exist(code, amount)) { store.Remove(code, amount); } else { IO.Instance().Writeln("Error!!! No hay existencias"); } break; } } } while (option != 3); }
public virtual IActionResult AddDeviceData( [FromRoute][Required][RegularExpression(GuidRegex)][StringLength(36, MinimumLength = 36)] string deviceId, [FromQuery][Required][RegularExpression(GuidRegex)][StringLength(36, MinimumLength = 36)] string datapointId, [FromQuery][Required] DateTime?timestamp, [FromQuery][Required] float?value) { var key = $"{deviceId};{datapointId}"; if (!store.Exists(key) && value.HasValue) { store.Add(key, value.Value); logger.LogInformation($"Added {value.Value} for {key} to the store at {timestamp}."); } if (!value.HasValue) { logger.LogError($"No value found for {key}."); return(BadRequest($"No data value for device: {deviceId} and datapoint {datapointId}")); } var average = store.GetAll().Where(i => i.Key.StartsWith(deviceId)).Average(v => v.Value); logger.LogInformation($"Returning {average}."); return(Created("", average)); }
private async Task <Stats> LoadStats(Guid chapterId, Guid profileId, int pages) { var stats = await _database.QueryStats(chapterId, profileId) ?? await _stats.Add(DbStats.Create(profileId, chapterId, pages)); return(_convertStats.Convert(stats)); }
public void Add(IAdministrativeUnit unit) { if (!units.Contains(unit)) { units.Add(unit); store.Add(unit); } }
public IActionResult Post([FromBody] Customer customer) { if (_store.Add(customer)) { return(Ok()); } return(BadRequest()); }
public async Task CreateAsync(TUser user) { this.ThrowIfDisposed(); if (user == null) { throw new ArgumentNullException("user"); } userRepository.Add(user); await userRepository.SaveChangesAsync().ConfigureAwait(false); }
private void CreateUnit(string type, string name) { var unit = factory.CreateFromType(type, name); if (unit != null) { store.Add(unit); Console.WriteLine($"Create new unit of type {type} with name {name}\n"); return; } Console.WriteLine($"Cannot create unit of type {type}\n"); }
public void AddRange <T>(IReadOnlyCollection <T> entities) where T : class { _optimizer.Processed(entities); if (entities.Count > 1) { _store.AddRange(entities); } else if (entities.Count > 0) { _store.Add(entities.First()); } }
public void RentBook(User user, Book book) { var canRentBook = _userBooks .GetAll() .Count(x => x.UserId == user.Id) < 2; if (!canRentBook) { throw new InvalidOperationException(); } _userBooks.Add(new UserBook { BookId = book.Id, UserId = user.Id }); }
public void AddTask(DateTime Time, Sender Sender, IEnumerable <Recipient> Recipients, Server Server, Message Message) { Stop(); _TasksStore.Add(new SchedulerTask { Message = Message, Recipients = Recipients.ToArray(), Server = Server, Sender = Sender, Time = Time }); Start(); }
public void AddTask(DateTime time, Sender sender, IEnumerable <Recipient> recipients, Server server, Message message) { Stop(); _TaskStore.Add(new SchedulerTask { Message = message, Recipients = recipients.ToArray(), Server = server, Sender = sender, Time = time }); Start(); }
public void Run(IStore store) { // throw new NotImplementedException(); store.Add(sparqlQuadsPattern.Where(pattern => pattern.PatternType == SparqlGraphPatternType.SparqlTriple) .Cast <SparqlTriple>().Select(t => new TripleOV(t.Subject, t.Predicate, t.Object))); foreach (var sparqlGraph in sparqlQuadsPattern.Where(pattern => pattern.PatternType == SparqlGraphPatternType.Graph) .Cast <SparqlGraphGraph>() //.Where(graph => store.NamedGraphs.ContainsGraph(graph.Name)) ) { store.NamedGraphs.Add(sparqlGraph.Name, sparqlGraph.GetTriples().Select(t => new TripleOV(t.Subject, t.Predicate, t.Object))); } }
public async Task Update(Profile profile, Guid chapterId, int pageIndex) { var stats = await _database.QueryStats(chapterId, profile.Id); if (stats == default) { var chapter = await _chapters.Get(chapterId); if (chapter != null) { var pages = chapter.Pages?.Length ?? 0; stats = await _stats.Add(DbStats.Create(profile.Id, chapter.Id, pages)); } else { throw new ObjectNotFoundException(typeof(DbChapter), chapterId); } } await _stats.Replace(stats.WithTip(pageIndex)); }
public virtual Task AddClaimAsync(TUser user, Claim claim) { ThrowIfDisposed(); if (user == null) { throw new ArgumentNullException("user"); } if (claim == null) { throw new ArgumentNullException("claim"); } var forSave = new TClaim() { ClaimType = claim.Type, ClaimValue = claim.Value, User = user }; claimsRepository.Add(forSave); return(claimsRepository.SaveChangesAsync()); }
public JsonResult Add(string name) { try { if (string.IsNullOrEmpty(name)) { throw new HttpException((int)HttpStatusCode.BadRequest, "name cant be empty"); } var createdTodo = store.Add(new Todo(name)); return(new JsonResult { Data = createdTodo }); } catch (Exception ex) { log.Debug("Att lägga nya todos fungerar ej", ex); } return(null); }
public override void RunUnSilent(IStore store) { if ((this.From == null && this.To == null) || (this.From != null && this.From.Equals(this.To))) { return; } IGraph fromGraph; if (this.From == null) { fromGraph = store; } else { fromGraph = store.NamedGraphs.GetGraph(this.From); if (!fromGraph.Any()) { throw new Exception(this.From); } } if (this.To == null) { fromGraph.GetTriples( (s, p, o) => { store.Add(s, p, o); return(true); }); fromGraph.Clear(); } else // if (!store.NamedGraphs.ContainsGraph(To)) { store.NamedGraphs.AddGraph(this.To, fromGraph); } // else store.NamedGraphs.ReplaceGraph(To,fromGraph); }
public void RentBook(User user, Book book) { if (user == null) { throw new InvalidOperationException("Null user can not rent Book!"); } if (book == null) { throw new InvalidOperationException("Can not rent null Book!"); } var canRentBook = _userBooks.GetAll().Count(c => c.UserId == user.Id && !c.IsArchive) < 2; if (!canRentBook) { throw new InvalidOperationException("Can not rent more than two Books!"); } _userBooks.Add(new UserBook { BookId = book.Id, UserId = user.Id, RentDateStart = DateTime.Now }); }
public void SaveUserSettings(UserSettings userSettings) { var userId = userSettings.UserId; var selectedUserSettings = _store.Get(userId); if (selectedUserSettings != null) { _store.Update(new UserSettings { UserId = userId, Alias = userSettings.Alias, SendNewsletter = selectedUserSettings.SendNewsletter }); } else { _store.Add(new UserSettings { UserId = userId, Alias = userSettings.Alias, SendNewsletter = true }); } }
public void Add(UserSettings item) { item.Alias = _correcter.Correct(item.Alias); _store.Add(item); }
public static void Load(long orderId, DataConnection query, IStore store, out ResolvedOrderSummary orderSummary) { var checkOrderIds = new[] { orderId }; var order = query.GetTable <Order>() .Where(x => checkOrderIds.Contains(x.Id)) .Execute() .Single(); store.Add(order); LoadReleaseWithdrawals(query, order, store); var bargainIds = new[] { order.BargainId }; var dealIds = new[] { order.DealId }; var firmIds = new[] { order.FirmId }; var branchOfficeOrganizationUnitIds = new[] { order.BranchOfficeOrganizationUnitId }; var legalPersonIds = new[] { order.LegalPersonId }; var unlimitedOrder = query.GetTable <UnlimitedOrder>() .Where(x => checkOrderIds.Contains(x.OrderId)) .Execute(); store.AddRange(unlimitedOrder); var orderFiles = query.GetTable <OrderFile>() .Where(x => checkOrderIds.Contains(x.OrderId)) .Execute(); store.AddRange(orderFiles); var bills = query.GetTable <Bill>() .Where(x => checkOrderIds.Contains(x.OrderId)) .Execute(); store.AddRange(bills); var bargains = query.GetTable <Bargain>() .Where(x => bargainIds.Contains(x.Id)) .Execute(); store.AddRange(bargains); var bargainFiles = query.GetTable <BargainFile>() .Where(x => bargainIds.Contains(x.BargainId)) .Execute(); store.AddRange(bargainFiles); var deals = query.GetTable <Deal>() .Where(x => dealIds.Contains(x.Id)) .Execute(); store.AddRange(deals); // var branchOfficeOrganizationUnits = query.GetTable <BranchOfficeOrganizationUnit>() .Where(x => branchOfficeOrganizationUnitIds.Contains(x.Id)) .Execute(); store.AddRange(branchOfficeOrganizationUnits); var branchOfficeIds = branchOfficeOrganizationUnits.Select(x => x.BranchOfficeId).ToList(); var branchOffices = query.GetTable <BranchOffice>() .Where(x => branchOfficeIds.Contains(x.Id)) .Execute(); store.AddRange(branchOffices); var legalPersons = query.GetTable <LegalPerson>() .Where(x => legalPersonIds.Contains(x.Id)) .Execute(); store.AddRange(legalPersons); var legalPersonProfiles = query.GetTable <LegalPersonProfile>() .Where(x => legalPersonIds.Contains(x.LegalPersonId)) .Execute(); store.AddRange(legalPersonProfiles); // var orders = query.GetTable <Order>() .Where(op => op.IsActive && !op.IsDeleted) .Where(x => firmIds.Contains(x.FirmId)) .Where(x => new[] { 1, 2, 4, 5 }.Contains(x.WorkflowStepId)) .Where(x => x.BeginDistributionDate < order.EndDistributionDatePlan && order.BeginDistributionDate < x.EndDistributionDatePlan) .Execute(); store.AddRange(orders); var orderIds = orders.Select(x => x.Id).ToList(); var orderPositions = query.GetTable <OrderPosition>() .Where(op => op.IsActive && !op.IsDeleted) .Where(op => orderIds.Contains(op.OrderId)) .Execute(); store.AddRange(orderPositions); var orderPositionIds = orderPositions.Select(x => x.Id).ToList(); var usedPricePositionIds = orderPositions.Select(x => x.PricePositionId).Distinct().ToList(); var opas = query.GetTable <OrderPositionAdvertisement>() .Where(op => orderPositionIds.Contains(op.OrderPositionId)) .Execute(); store.AddRange(opas); var themeIds = opas.Where(x => x.ThemeId.HasValue).Select(x => x.ThemeId.Value).ToList(); var categoryIds = opas.Where(x => x.CategoryId.HasValue).Select(x => x.CategoryId.Value).ToList(); var firmAddressIds = opas.Where(x => x.FirmAddressId.HasValue).Select(x => x.FirmAddressId.Value).ToList(); // список привязанных адресов из-за ЗМК может превышать список адресов фирмы var costs = query.GetTable <OrderPositionCostPerClick>() .Where(x => orderPositionIds.Contains(x.OrderPositionId)) .Execute(); // Можно ужесточить: только проверямый заказ, только актуальные ставки store.AddRange(costs); // var themes = query.GetTable <Theme>() .Where(x => themeIds.Contains(x.Id)) .Execute(); store.AddRange(themes); var themeCategories = query.GetTable <ThemeCategory>() .Where(x => themeIds.Contains(x.ThemeId)) .Where(x => categoryIds.Contains(x.CategoryId)) .Execute(); store.AddRange(themeCategories); var themeOrganizationUnits = query.GetTable <ThemeOrganizationUnit>() .Where(x => x.OrganizationUnitId == order.DestOrganizationUnitId) .Where(x => themeIds.Contains(x.ThemeId)) .Execute(); store.AddRange(themeOrganizationUnits); var project = query.GetTable <Project>() .Where(x => x.OrganizationUnitId == order.DestOrganizationUnitId) .Take(1) .Execute() .Single(); store.Add(project); // var actualPrice = query.GetTable <Price>() .Where(x => !x.IsDeleted && x.IsPublished) .Where(x => x.ProjectId == project.Id && x.BeginDate <= order.BeginDistributionDate) .OrderByDescending(x => x.BeginDate) .Take(1) .Execute() .SingleOrDefault(); if (actualPrice != null) { store.Add(actualPrice); } var usedPricePositions = query.GetTable <PricePosition>() .Where(x => usedPricePositionIds.Contains(x.Id)) .Execute(); store.AddRange(usedPricePositions); var monthlyUsedPrices = query.GetTable <Price>() .Where(x => x.ProjectId == project.Id && x.BeginDate >= order.BeginDistributionDate && x.BeginDate <= order.EndDistributionDatePlan) .Execute(); store.AddRange(monthlyUsedPrices); var usedPriceIds = usedPricePositions.Select(x => x.PriceId).Union(actualPrice != null ? new[] { actualPrice.Id } : Array.Empty <long>()).Union(monthlyUsedPrices.Select(x => x.Id)).ToList(); var soldPackagesIds = usedPricePositions.Select(p => p.PositionId) .Distinct() .ToList(); var soldPackageElementsIds = opas.Select(y => y.PositionId) .Distinct() .ToList(); var usedPositionIds = soldPackagesIds.Union(soldPackageElementsIds).ToList(); var positions = query.GetTable <Position>() .Where(x => usedPositionIds.Contains(x.Id)) .Execute(); // Можно ограничиться проверямым заказов store.AddRange(positions); var positionChilds = query.GetTable <PositionChild>() .Where(x => usedPositionIds.Contains(x.MasterPositionId) || usedPositionIds.Contains(x.ChildPositionId)) .Execute(); store.AddRange(positionChilds); // Нужно ли ещё от PositionChild выбрать Position? var usedPrices = query.GetTable <Price>() .Where(x => usedPriceIds.Contains(x.Id)) .Execute(); store.AddRange(usedPrices); var releaseInfos = query.GetTable <ReleaseInfo>() .Where(x => x.OrganizationUnitId == order.DestOrganizationUnitId) .Where(x => x.IsActive && !x.IsDeleted && !x.IsBeta && x.Status == 2) .Execute(); // можно только последний? store.AddRange(releaseInfos); var categories = query.GetTable <Category>() .Where(x => categoryIds.Contains(x.Id)) .Execute(); store.AddRange(categories); var cat2Ids = categories.Select(x => x.ParentId); var categories2 = query.GetTable <Category>() .Where(x => cat2Ids.Contains(x.Id)) .Execute(); store.AddRange(categories2); var cat1Ids = categories2.Select(x => x.ParentId); var categories1 = query.GetTable <Category>() .Where(x => cat1Ids.Contains(x.Id)) .Execute(); store.AddRange(categories1); var categoryOrganizationUnit = query.GetTable <CategoryOrganizationUnit>() .Where(x => cat1Ids.Union(cat2Ids).Union(categoryIds).Contains(x.CategoryId)) .Where(x => x.OrganizationUnitId == order.DestOrganizationUnitId) .Execute(); store.AddRange(categoryOrganizationUnit); var costPerClickCategoryRestrictions = query.GetTable <CostPerClickCategoryRestriction>() .Where(x => x.ProjectId == project.Id) .Where(x => categoryIds.Contains(x.CategoryId)) .Execute(); // Можно ужесточить: рубрики из свзанных заказов нам на самом деле не нужны. store.AddRange(costPerClickCategoryRestrictions); if (costPerClickCategoryRestrictions.Any()) { var maxDate = costPerClickCategoryRestrictions.Max(x => x.BeginningDate); var nextCostPerClickCategoryRestrictions = query.GetTable <CostPerClickCategoryRestriction>() .Where(x => x.ProjectId == project.Id) .Where(x => x.BeginningDate > maxDate) .Take(1) .Execute(); // Нужно для того, чтобы понять, что имеющиеся ограчения не являются актуальными store.AddRange(nextCostPerClickCategoryRestrictions); } var salesModelCategoryRestrictions = query.GetTable <SalesModelCategoryRestriction>() .Where(x => x.ProjectId == project.Id) .Where(x => categoryIds.Contains(x.CategoryId)) .Execute(); // Можно ужесточить: рубрики из свзанных заказов нам на самом деле не нужны. store.AddRange(salesModelCategoryRestrictions); var nomenclatureCategories = query.GetTable <NomenclatureCategory>() .Execute(); store.AddRange(nomenclatureCategories); LoadAmountControlledSales(query, order, usedPriceIds, store); LoadFirm(query, order, firmAddressIds, store); LoadBuyHere(query, order, store); LoadPoi(query, order, store); orderSummary = new ResolvedOrderSummary { BeginDate = order.BeginDistributionDate, EndDate = order.EndDistributionDatePlan, ProjectId = project.Id, SoldPackagesIds = soldPackagesIds, SoldPackageElementsIds = soldPackageElementsIds }; }
public void Add(UserSettings item) { _store.Add(item); }
/// <summary> /// Records when the next call is scheduled to occur /// </summary> /// <param name="milliseconds"></param> public void CallWillHappenIn(double milliseconds) { _store.Add(ReferenceTime.UtcNow.AddMilliseconds(milliseconds)); }