public void ConfirmCredit(int userId) { var credit = _creditRepository.GetAll().SingleOrDefault(c => c.BankAccountId == userId && c.Confirmed == false && c.PaidInFull == false); if (credit == null) { return; } credit.Confirmed = true; credit.ConfirmationDate = DateTime.Now; credit.NextInstallmentDate = (DateTime.Now + TimeSpan.FromDays(1)).Date; var firstInstallment = new CreditInstallment() { CreditId = credit.Id, InstallmentAmount = credit.InstallmentAmount, PaymentDeadline = credit.NextInstallmentDate.Value }; _creditInstallmentsRepository.Create(firstInstallment); _creditRepository.Update(credit); _bankAccountService.GiveCash(credit.CreditAmount, userId); }
public EntityIdWithVersion <TEntityId, TEntityVersion> Update(TEntityId entityId, TEntity entityToUpdate, Func <TEntity, TEntity> entityModifier) { return(_inner.Create(newEntity => { _inner.Delete(entityId); return entityModifier(newEntity); })); }
public async Task <AccountModel> Update(AccountModel model) { var other = await _repository.FindByNameAsync <Account>(_currentSession.UserId, model.Name).ConfigureAwait(false); if (other != null) { if (other.Id != model.Id) { throw new ArgumentException("Счет с таким названием уже есть"); } else { _repository.Detach(other); } } var account = new Account { Name = model.Name, Balance = model.Balance, AvailBalance = model.AvailBalance, DateCreated = model.DateCreated, Number = model.Number, IsDeleted = false, OwnerId = _currentSession.UserId, IsDefault = model.IsDefault, AccountType = model.AccountType }; if (account.IsDefault) { var all = await _repository.GetQuery <Account>().ToListAsync().ConfigureAwait(false); all.ForEach(x => { x.IsDefault = false; _repository.Update(x); }); } if (model.Id < 0) { account.AvailBalance = model.Balance; _repository.Create(account); } else { account.Id = model.Id; _repository.Update(account); } await _repository.SaveChangesAsync().ConfigureAwait(false); model.Id = account.Id; return(model); }
public async Task <int> Create(ExpenseBillModel model, bool correction = false) { if (model == null) { throw new ArgumentNullException(nameof(model)); } model.Validate(); var bill = new ExpenseBill { ExpenseFlowId = model.ExpenseFlowId, AccountId = model.AccountId, DateTime = model.DateTime, SumPrice = model.Cost, OwnerId = _currentSession.UserId, IsCorrection = correction, }; model.IsCorection = correction; _repository.Create(bill); foreach (var item in model.Items) { _repository.Create(new ExpenseItem { Bill = bill, CategoryId = item.CategoryId, ProductId = item.ProductId, Price = item.Cost, Quantity = item.Quantity, Comment = item.Comment }); } Account account = null; if (model.AccountId != null) { account = await _repository.LoadAsync <Account>(model.AccountId.Value); } if (account != null) { var balancesUpdater = _balancesUpdaterFactory.Create(account.AccountType); await balancesUpdater.Create(account, bill).ConfigureAwait(false); _transactionBuilder.CreateExpense(bill, account.Balance); } await _repository.SaveChangesAsync().ConfigureAwait(false); model.Id = bill.Id; return(model.Id); }
public async Task <ExpenseFlowModel> Update(ExpenseFlowModel model) { var other = await _repository.FindByNameAsync <ExpenseFlow>(_currentSession.UserId, model.Name); if (other != null) { if (other.Id != model.Id) { throw new ArgumentException("Категория расходов с таким названием уже есть"); } else { _repository.Detach(other); } } var flow = new ExpenseFlow { Name = model.Name, Balance = model.Balance, DateCreated = model.DateCreated, Number = model.Number, IsDeleted = false, OwnerId = _currentSession.UserId }; if (model.Id < 0) { flow.Version = 1; _repository.Create(flow); } else { flow.Id = model.Id; flow.Version = model.Version + 1; _repository.Update(flow); if (model.Categories != null) { UpdateFlowCategories(flow.Id, model.Categories); } } await _repository.SaveChangesAsync().ConfigureAwait(false); model.Id = flow.Id; model.Version = flow.Version; return(model); }
public async Task <List <LocateBaseResponseModel> > City(string city) { var jsonString = await city.MakeCall(); var token = JToken.Parse(jsonString); var jsonList = token.SelectToken("predictions").ToString(); var parsed = JsonConvert.DeserializeObject <List <ParsingBaseModel> >(jsonList); var result = new List <LocateBaseResponseModel>(); foreach (var variable in parsed) { var cityName = variable.AddressModel.Address; var dbCity = await _repository.Filter <City>(x => x.Name.ToLower() == cityName.ToLower()).Include(c => c.Country).FirstOrDefaultAsync(); if (dbCity != null) { result.Add(new LocateBaseResponseModel { Id = dbCity.Id, Name = $"{dbCity.Name}, {dbCity.Country.Name}" }); } else { Country country = _repository.Filter <Country>(c => c.Name.ToLower() == variable.Terms[1].Value.ToLower()).FirstOrDefault(); if (country == null) { country = _repository.Create(new Country { Name = variable.Terms[1].Value }); _repository.SaveChanges(); } City c = _repository.Create(new City { Country = country, Name = cityName }); _repository.SaveChanges(); result.Add(new LocateBaseResponseModel { Id = c.Id, Name = $"{c.Name}, {c.Country.Name}" }); } } return(result); }
private EntityOperationResult UpdateInternal(EntityUpdate update) { if (!RunInspection(update)) { return(EntityOperationResult.FailResult(new EntityOperationError("Insufficient rights to perform this operation.", EntityOperationError.ACCESS_VIOLATION))); } EntityOperationContext ctx = new EntityOperationContext(); this.AppyLogicBefore(update, ctx); var entity = update.ToEntity(); EntityOperationResult result = null; bool created = false; try { if (update.Id.HasValue) { if (update.PropertyUpdates.Count > 0) { _repository.Update(entity); } } else { update.Id = _repository.Create(entity); created = true; } //Order by operation - process detach first foreach (var relUpdate in update.RelationUpdates.OrderByDescending(ru => ru.Operation)) { if (relUpdate.Operation == RelationOperation.Attach) { _repository.Attach(entity, relUpdate.ToRelation()); } else if (relUpdate.Operation == RelationOperation.Detach) { _repository.Detach(entity, relUpdate.ToRelation()); } else if (relUpdate.PropertyUpdates.Count > 0) { _repository.UpdateRelation(entity, relUpdate.ToRelation()); } } result = EntityOperationResult.SuccessResult(); if (created) { result.Data.Add("Created", update.Id.Value); } } catch (UniqueRuleViolationException rex) { result = EntityOperationResult.FailResult(new EntityOperationError(rex.Message, EntityOperationError.UNIQUE_RULE_VIOLATION)); } this.AppyLogicAfter(update, ctx, result); return(result); }
public async Task <IActionResult> AddAdvertisement(AdvertisementDTO adv, int id) { if (!ModelState.IsValid) { return(BadRequest("Fill all fields")); } Position pos = await _positionRepos.GetPositionByName(adv.PositionName); if (pos == null) { return(BadRequest("Such position is not in database")); } var advertisement = new Advertisement() { Title = adv.Title, Salary = adv.Salary.GetValueOrDefault(), Description = adv.Description, PositionName = adv.PositionName, PositionId = pos.PositionId, EmployerId = id }; if (await _repos.HasEntity(advertisement)) { return(BadRequest("Ads with this title already exists")); } logger.Info($"Adding new advertisement for employer with id = {id}"); if (await _repos.Create(advertisement)) { return(Ok("Added new ads")); } return(BadRequest("Failed to add ads")); }
private string InstallModulesPermissions(IModule module) { StringBuilder info = new StringBuilder(); info.Append("<ul>"); ModulePermission mp = new ModulePermission() { Available = module.Requirements.Permissions != null?module.Requirements.Permissions.ToArray() : new string[0], ModuleID = module.Id, ModuleName = module.Name }; var q = new EntityQuery2(ModulePermission.ENTITY); q.AddProperty("Available"); q.WhereIs("moduleId", module.Id); using (var dbContext = _dbService.GetDatabaseContext(true)) { var ex = _repository.Read(q); if (ex == null) { _repository.Create(mp.Entity); foreach (var p in mp.Available) { info.AppendFormat("<li>{0} - added.</li>", p); } } else if (ex.GetData <string>("Available") != mp.Entity.GetData <string>("Available")) { var oldRaw = ex.GetData <string>("Available"); string[] old = null; if (string.IsNullOrEmpty(oldRaw)) { old = new string[0]; } else { old = oldRaw.Split(";".ToCharArray(), StringSplitOptions.RemoveEmptyEntries); } ex.SetData <string>("Available", mp.Entity.GetData <string>("Available")); _repository.Update(ex); foreach (var p in mp.Available) { if (!old.Contains(p)) { info.AppendFormat("<li>{0} - added.</li>", p); } } foreach (var p in old) { if (!mp.Available.Contains(p)) { info.AppendFormat("<li>{0} - removed.</li>", p); } } } dbContext.Complete(); } info.Append("</ul>"); return(info.ToString()); }
public void Initialize() { try { var q = new EntityQuery2(User.ENTITY); q.WhereIs("Email", _systemUserEmail); using (var dbContext = _dbService.GetDatabaseContext(true)) { var e = _entityRepository.Search(q).SingleOrDefault(); if (e == null) { User admin = new User() { FirstName = "Build in", LastName = "Administrator", Email = _systemUserEmail, Password = _systemUserEmail, UserType = UserTypes.Admin, IsActive = true }; SHA1 sha1 = SHA1.Create(); admin.Password = Convert.ToBase64String(sha1.ComputeHash(Encoding.UTF8.GetBytes(admin.Password))); _entityRepository.Create(admin); dbContext.Complete(); } } } catch (Exception ex) { throw new Exception("Could not create build-in-administrator user.", ex); } }
public async Task <IActionResult> AddArticle(ArticleDTO art) { if (!ModelState.IsValid) { return(BadRequest("Fill all fields")); } Article article = new Article() { Title = art.Title, PublishDate = art.PublishDate, Description = art.Description, }; if (await _repos.HasEntity(article)) { return(BadRequest("This article already exists")); } if (await _repos.Create(article)) { return(Ok("Added new article")); } return(BadRequest("Failed to add article")); }
public StatusEnum.Status CreateEntity(EntityModel model) { StatusEnum.Status status = StatusEnum.Status.Success; try { _entity = new PASCore_Entity(); _entity.BankDetails = model.BankDetails; _entity.Code = model.Code; _entity.Description = model.Description; _entity.Email = model.Email; _entity.IsDeleted = false; _entity.Line1 = model.Line1; _entity.Line2 = model.Line2; _entity.Name = model.Name; _entity.PhoneNumber = model.PhoneNumber; _entity.CreatedDateTime = DateTime.UtcNow; _entityRepository.Create(_entity); _entityRepository.SaveChanges(); } catch (Exception) { status = StatusEnum.Status.Fail; throw; } return(status); }
private async Task UpdateMangaChaptersAsync(MangaInfo manga) { _log.LogInformation($"Started loading new chapters for '{manga.Name}' title"); try { var newManga = await _mangaLoader.LoadMangaInfoAsync(manga); var chapters = await _chaptersRep.GetByAsync(chapter => chapter.MangaId == manga.Id); var currentChapters = manga.Chapters; var newChapters = new List <MangaChapterInfo>(); newManga.Chapters.ForEach(chapter => { if (currentChapters.Any(c => c.Name == chapter.Name)) { return; } newChapters.Add(chapter); _chaptersRep.Create(chapter); }); _log.LogInformation($"Found {newChapters.Count} new chapters for '{newManga.Name}' title"); if (newChapters.IsNotEmpty()) { _chaptersRep.Save(); CreateNewMangaNotifications(newChapters); } } catch (Exception ex) { _log.LogError($"Error while loading new info for '{manga.Name}' title. Error info: \n{ex.Message}\n{ex.StackTrace}"); } }
public async Task Create(Address model) { if (model == null || string.IsNullOrEmpty(model.Country) || string.IsNullOrEmpty(model.County)) { throw new Exception("Model null"); } await _addressRepository.Create(model); }
public ActionResult Upload(string fileName) { // var cookie = Utils.ReadCookie(Request); if ((Session["IsValid2FA"] != null && (bool)Session["IsValid2FA"])) //if (cookie!=null && cookie.Value == "Logged") { if (fileName != null) { _filesRepository.Create(Utils.LoadCsvHeaderAndFillLoaderModel(fileName)); } List <FilesModel> models = _filesRepository.GetAllObjectsList(); return(View(models)); } return(RedirectToAction("Index", "Login")); }
public async Task Create(Writer model) { if (model == null) { throw new Exception("Model null"); } await _writerRepository.Create(model); }
public async Task Create(Book model) { if (model == null) { throw new Exception("Model null"); } await _bookRepository.Create(model); }
public bool Create(Domain.Entity entity, params string[] defaultAttributeNames) { if (_entityRepository.Exists(x => x.Name == entity.Name)) { throw new XmsException(_loc["name_already_exists"]); } var solutionid = entity.SolutionId; //当前解决方案 entity.SolutionId = SolutionDefaults.DefaultSolutionId; //组件属于默认解决方案 var result = true; if (defaultAttributeNames.IsEmpty()) { //默认添加主键字段 defaultAttributeNames = new string[] { entity.Name + "Id" }; } else if (!defaultAttributeNames.Contains(entity.Name + "Id", StringComparer.InvariantCultureIgnoreCase)) { var namesList = defaultAttributeNames.ToList(); namesList.Add(entity.Name + "Id"); defaultAttributeNames = namesList.ToArray(); } var parentEntity = entity.ParentEntityId.HasValue ? _entityRepository.FindById(entity.ParentEntityId.Value) : null; var defaultAttributes = _defaultAttributeProvider.GetSysAttributes(entity).Where(x => defaultAttributeNames.Contains(x.Name, StringComparer.InvariantCultureIgnoreCase)).Distinct().ToList(); using (UnitOfWork.Build(_entityRepository.DbContext)) { result = _entityRepository.Create(entity, defaultAttributes, _defaultAttributeProvider.GetSysAttributeRelationShips(entity, defaultAttributes)); //创建默认字段 _attributeCreater.CreateDefaultAttributes(entity, defaultAttributeNames); //如果是子实体,则创建引用字段 if (parentEntity != null) { _attributeCreater.Create(new Domain.Attribute { Name = parentEntity.Name + "Id" , AttributeTypeName = AttributeTypeIds.LOOKUP , EntityId = entity.EntityId , EntityName = entity.Name , IsRequired = true , LocalizedName = parentEntity.LocalizedName , ReferencedEntityId = parentEntity.EntityId }); } //事件发布 _eventPublisher.Publish(new ObjectCreatedEvent <Domain.Entity>(entity)); //solution component _solutionComponentService.Create(solutionid, entity.EntityId, EntityDefaults.ModuleName); //本地化标签 _localizedLabelService.Append(entity.SolutionId, entity.LocalizedName.IfEmpty(""), EntityDefaults.ModuleName, "LocalizedName", entity.EntityId) .Append(entity.SolutionId, entity.Description.IfEmpty(""), EntityDefaults.ModuleName, "Description", entity.EntityId) .Save(); //add to cache _cacheService.SetEntity(entity); } return(result); }
public void CreateExpense(ExpenseBill bill, decimal balance) { if (bill.AccountId == null) { return; } var transation = new Transaction { OwnerId = bill.OwnerId, DateTime = bill.DateTime, InitiatorId = bill.AccountId.Value, Bill = bill, Total = bill.SumPrice, Balance = balance }; _repository.Create(transation); }
public async Task <bool> Add(AddEmailRequestModel model) { _repository.Create <Email>(new Email { EmailText = model.Email }); await _repository.SaveChangesAsync(); return(true); }
public ActionResult Create(FoodOrder foodOrder) { if (ModelState.IsValid) { entityRepo.Create(foodOrder); return(RedirectToAction("Index")); } return(View("CreateFoodOrder", foodOrder)); }
public ActionResult AddItem(T item) { if (item == null) { return(BadRequest("Parameter object is null")); } EntityRepository.Create(item); EntityRepository.Save(); return(Ok()); }
public async Task <bool> Add(CityAddModel model) { _repository.Create(new City { Name = model.Name }); await _repository.SaveChangesAsync(); return(true); }
public async Task <bool> Add(AddFAQModel model) { _repository.Create(new FAQ { Title = model.Title, Description = model.Description }); await _repository.SaveChangesAsync(); return(true); }
public async Task <bool> Add(AddPhoneCodeModel model) { _repository.Create(new PhoneCode { Country = model.Country, Code = model.Code }); await _repository.SaveChangesAsync(); return(true); }
public async Task CreateAsync(T entity) { #region Guards if (entity == null) { throw new ArgumentNullException(nameof(entity)); } #endregion _repository.Create(entity); await Clients.All.SendAsync(nameof(Create), entity); }
public async Task <IResult <Tag> > Create(Tag tag) { if (tag == null || string.IsNullOrEmpty(tag.Name) || string.IsNullOrEmpty(tag.SeoUrl)) { return(new Result <Tag>(false, Message.ModelNotValid)); } tag.Id = Guid.NewGuid(); tag.CreatedDate = DateTime.Now; await _tagRepository.Create(tag); return(new Result <Tag>(true, tag)); }
/// <inheritdoc cref="IService{T}"/> public void Save(Entity entity) { try { repository.Create(entity); } catch (Exception e) { logger.Log($"Exception {e} occur during the execution of Save method: {e.Message}"); throw e; } }
private async Task CreateOrUpdateAcccountSettings(DistributionAccount distributionAccount) { var settings = await _repository.GetQuery <AccountFlowSettings>() .Where(x => x.AccountId == distributionAccount.Account.Id) .SingleOrDefaultAsync(); if (settings == null) { settings = new AccountFlowSettings { AccountId = distributionAccount.Account.Id, CanFlow = distributionAccount.UseInDistribution }; _repository.Create(settings); } else { settings.CanFlow = distributionAccount.UseInDistribution; _repository.Update(settings); } }
public void SaveFile(Domain.File file) { //TODO: fileservice is using repository (bypassing operation logic) if (file.Id > 0) { _repository.Update(file); } else { _repository.Create(file); } }