public void CreateServer(ServerDto server) { var entity = Mapper.Map <ServerDto, Server>(server); using (var dbScope = _dbScopeFactory.Create()) { var db = dbScope.DbContexts.Get <FireProjDbContext>(); entity.CreateDate = DateTime.Now; db.Servers.Add(entity); db.SaveChanges(); //保存域名信息 foreach (var item in server.IISData) { var domainEntity = new DomainResource() { Name = item.Name, SiteName = item.SiteName, ProjectId = item.ProjectId, ServerId = entity.Id, CreatorId = server.CreatorId.Value, CreatorName = server.CreatorName, CreateDate = DateTime.Now, }; db.DomainResource.Add(domainEntity); } db.SaveChanges(); } }
public ResponseHelper Insert(LessonsPerCourse model) { var rh = new ResponseHelper(); try { using (var ctx = _dbContextScopeFactory.Create()) { // New order var order = _lessonRepo.Find(x => x.CourseId == model.CourseId) .Select(x => x.Order) .DefaultIfEmpty(0).Max() + 1; model.Order = order; model.Content = string.Format("Contenido para la lección {0}", model.Name); _lessonRepo.Insert(model); ctx.SaveChanges(); rh.SetResponse(true); } } catch (DbEntityValidationException e) { logger.Error(e.Message); rh.SetResponse(false, e.Message); } catch (Exception e) { logger.Error(e.Message); rh.SetResponse(false, e.Message); } return(rh); }
public void CreateClient(Client client) { if (client == null) { throw new ArgumentNullException("When creating client, its object became null"); } // Probably a return needs to be made here if (!client.ConfirmClientPasswordsMatch()) { throw new Exception("The passwords do not match"); } using (var dbContextScope = _dbContextScopeFactory.Create()) { var foundClientObject = _clientRepository.GetClient(client.Email); if (foundClientObject != null) { throw new Exception("The username is already registered, sorry"); } client.InitializeClientPasswordEncryption(); client.IsBlocked = true; _clientRepository.CreateClient(client); dbContextScope.SaveChanges(); } }
public void Update(Blogpost value) { using (var scope = _dbContextScopeFactory.Create()) { var dbContext = scope.DbContexts .Get <ApplicationDbContext>(); var existed = dbContext.Set <Blogpost>().SingleOrDefault(c => c.ID == value.ID); existed.Content = value.Content; existed.IsPublished = value.IsPublished; existed.Keywords = value.Keywords; existed.Overview = value.Overview; existed.PublishedDate = value.PublishedDate; existed.Title = value.Title; existed.ServiceId = value.ServiceId; //existed.Author = value.Author; //existed.Service = value.Service; //existed.ViewsCount = value.ViewsCount; //HandleFile(existed.Image, value.Image); scope.SaveChanges(); } }
public ResponseHelper Review(ReviewPerCourse model) { var rh = new ResponseHelper(); try { // Registramos la valoración using (var ctx = _dbContextScopeFactory.Create()) { var hasReview = _reviewPerCourseRepo.Find(x => x.UserId == model.UserId && x.CourseId == model.CourseId ).Any(); if (!hasReview) { _reviewPerCourseRepo.Insert(model); ctx.SaveChanges(); rh.SetResponse(true); } else { rh.SetResponse(false, "Usted ya ha valorado este curso"); } } if (rh.Response) { // Calculamos el promedio de valoraciones using (var ctx = _dbContextScopeFactory.Create()) { var course = _courseRepo.Single(x => x.Id == model.CourseId ); course.Vote = _reviewPerCourseRepo.Find(x => x.CourseId == model.CourseId ).Average(x => x.Vote); _courseRepo.Update(course); ctx.SaveChanges(); rh.SetResponse(true); } } } catch (DbEntityValidationException e) { logger.Error(e.Message); rh.SetResponse(false, e.Message); } catch (Exception e) { logger.Error(e.Message); rh.SetResponse(false, e.Message); } return(rh); }
public async Task InitializeAsync() { using (var scope = dbContextScopeFactory.Create()) { try { var dbContext = scope.DbContexts.Get <TDbContext>(); if (!CheckTableExists <RawStreamEntry>(dbContext)) { var script = dbContext.ObjectContext.CreateDatabaseScript(); var steps = script.Split(new[] { "GO" }, StringSplitOptions.RemoveEmptyEntries); foreach (var step in steps) { await dbContext.Database.ExecuteSqlCommandAsync(step).ConfigureAwait(false); } } await scope.SaveChangesAsync().ConfigureAwait(false); } catch (Exception e) { Debug.WriteLine(e.ToString()); throw; } } }
/// <summary> /// 添加菜单 /// </summary> /// <param name="dto">菜单模型</param> /// <returns></returns> public async Task <string> Add(MenuDto dto) { using (var scope = _dbContextScopeFactory.Create()) { var entity = _mapper.Map <MenuDto, MenuEntity>(dto); entity.Create(); var db = scope.DbContexts.Get <JuCheapContext>(); var existsCode = await db.Menus.Where(item => item.ParentId == dto.ParentId) .Select(item => item.Code).ToListAsync(); var pathCode = await db.PathCodes.FirstOrDefaultAsync(item => !existsCode.Contains(item.Code)); entity.Code = pathCode.Code.Trim(); if (entity.ParentId.IsNotBlank()) { var parent = await db.Menus.FindAsync(entity.ParentId); entity.PathCode = string.Concat(parent.PathCode.Trim(), entity.Code.Trim()); entity.Type = parent.Type == 1 ? (byte)MenuType.Menu : (byte)MenuType.Button; } else { entity.PathCode = entity.Code.Trim(); entity.Type = (byte)MenuType.Module; } db.Menus.Add(entity); await scope.SaveChangesAsync(); return(entity.Id); } }
public void CreateCustomer(Customer customerToCreate) { if (customerToCreate == null) { throw new ArgumentNullException("userToCreate"); } if (!customerToCreate.IsConfirmPasswordCorrect()) { throw new Exception("Password doesn't match"); } using (var dbContextScope = _dbContextScopeFactory.Create()) { var foundCustomer = _customerRepository.FindByEmail(customerToCreate.Email); if (foundCustomer != null) { //TODO: UserAlreadyExistsException throw new Exception("User already exists"); } customerToCreate.HashPassword(); customerToCreate.IsActive = true; _customerRepository.Add(customerToCreate); dbContextScope.SaveChanges(); } }
/// <summary> /// Create a new game /// </summary> /// <param name="playerName"></param> /// <param name="numberOfPlayers"></param> /// <returns>Game info</returns> public Game Create(string playerName, int numberOfPlayers) { using (IDbContextScope contextScope = _dbContextFactory.Create()) { //create player var player = new Player() { Name = playerName }; //create game var game = new Game() { NumberOfPlayers = numberOfPlayers, Status = numberOfPlayers > 1 ? 0 : 1 }; //add player to game game.Players.Add(player); //add game and player to database _gameService.Add(game); contextScope.SaveChanges(); game.PlayerId = player.Id; return(game); } }
public async Task <List <PositionViewModel> > GetLastVehiclePositionAsync(string userName) { using (var contextFScope = _dbContextScopeFactory.Create()) { _objectContext = contextFScope.DbContexts.Get <SmartFleetObjectContext>(); var positions = new List <PositionViewModel>(); var query = await(from customer in _objectContext.Customers join account in _objectContext.UserAccounts on customer.Id equals account.CustomerId where account.UserName == userName join vcl in _objectContext.Vehicles on customer.Id equals vcl.CustomerId into vehicleJoin from vehicle in vehicleJoin join box in _objectContext.Boxes on vehicle.Id equals box.VehicleId into boxesJoin from box in boxesJoin join position in _objectContext.Positions on box.Id equals position.Box_Id group position by position.Box_Id into g select new { boxId = g.Key, Position = g.OrderByDescending(x => x.Timestamp).Select(x => new PositionViewModel { Address = x.Address, Latitude = x.Lat, Longitude = x.Long }).FirstOrDefault() }).ToArrayAsync().ConfigureAwait(false); foreach (var item in query) { var vehicle = await _objectContext.Boxes.Include(x => x.Vehicle).Where(x => x.Id == item.boxId).Select(x => new { x.Vehicle.VehicleType, x.Vehicle.VehicleName, x.Vehicle.CustomerId, x.VehicleId }).FirstOrDefaultAsync().ConfigureAwait(false); var pos = new PositionViewModel(vehicle?.VehicleName, vehicle?.CustomerId.ToString(), vehicle.VehicleType, vehicle?.VehicleId.ToString()); pos.Address = item.Position.Address; pos.Latitude = item.Position.Latitude; pos.Longitude = item.Position.Longitude; positions.Add(pos); } return(positions); } }
public ComplementoDeRespuesta InsertOrRemoveCourse(StudentPerCourse model) { var rh = new ComplementoDeRespuesta(); try { using (var ctx = _dbContextScopeFactory.Create()) { var courseByStudent = _studentPerCourseRepository.Find(x => x.StudentId == model.StudentId && x.CourseId == model.CourseId ).SingleOrDefault(); if (courseByStudent == null) { model.SuscribedAt = DateTime.Now; _studentPerCourseRepository.Insert(model); } else { _studentPerCourseRepository.Delete(courseByStudent); } ctx.SaveChanges(); rh.SetRespuesta(true); } } catch (Exception e) { logger.Error(e.Message); } return(rh); }
public PaymentInfo Pay(int customerId, Cart cart, string cvv) { using (var dbContextScope = _dbContextScopeFactory.Create()) { var customer = _customerRepository.FindById(customerId); if (customer == null) { //TODO: CustomerNotFoundException throw new Exception(); } customer.Card.CVV = cvv; var paymentInfo = _paymentService.Payment(customer.Card, cart.Cost); cart.Items.ToList().ForEach(x => x.Item = _itemQueryService.GetItem(x.Item.Id)); //TODO: remove hack var order = new Order { Cart = cart, DateTime = DateTime.Now, OrderStatus = paymentInfo.OrderStatus }; customer.Orders.Add(order); _customerRepository.Modify(customer); customer.Card.CVV = null; dbContextScope.SaveChanges(); return(paymentInfo); } }
public async Task UpdateUserDeviceAsync(UserDeviceDto userDeviceDto) { if (userDeviceDto == null) { return; } using (var dbContext = _dbContextScopeFactory.Create()) { var device = await _userDeviceRepository .FindAsync(w => w.UserId == userDeviceDto.UserId && w.IMEI == userDeviceDto.IMEI); if (device == null) { device = UserDevice.Create(userDeviceDto.UserId, userDeviceDto.Name, userDeviceDto.AppName, userDeviceDto.AppVersion, userDeviceDto.OSPlatform, userDeviceDto.OSVersion, userDeviceDto.SerialNumber, userDeviceDto.IMEI, userDeviceDto.FireBaseToken); _userDeviceRepository.Add(device); } else { device.Update( userDeviceDto.Name, userDeviceDto.AppName, userDeviceDto.AppVersion, userDeviceDto.OSPlatform, userDeviceDto.OSVersion, userDeviceDto.FireBaseToken); } await dbContext.SaveChangesAsync(); } }
public void CreateOrderRating(OrderRating orderRatingToCreate, Order order) { if (orderRatingToCreate == null) { throw new ArgumentNullException("orderRatingToCreate"); } using (var dbContextScope = _dbContextScopeFactory.Create()) { var foundOrderRating = _orderRatingRepository.FindByOrderId(orderRatingToCreate.Order.Id); if (foundOrderRating != null) { //TODO: OrderRatingAlreadyExistsException throw new Exception(); } //NO HACK var context = dbContextScope.DbContexts.Get <EShopDbContext>(); context.Orders.Attach(order); orderRatingToCreate.Order = order; _orderRatingRepository.Add(orderRatingToCreate); dbContextScope.SaveChanges(); } }
public async Task <bool> AddNewVehicleAsync(Vehicle vehicle) { try { using (var contextFScope = _dbContextScopeFactory.Create()) { _db = contextFScope.DbContexts.Get <SmartFleetObjectContext>(); vehicle.MileStoneUpdateUtc = DateTime.Now; if (vehicle.Box_Id.HasValue) { vehicle.VehicleStatus = VehicleStatus.Active; } var boxId = vehicle.Box_Id; var box = await _db.Boxes.FirstOrDefaultAsync(b => b.Id == boxId).ConfigureAwait(false); if (box != null) { box.VehicleId = vehicle.Id; box.BoxStatus = BoxStatus.Valid; _db.Entry(box).State = EntityState.Modified; } _db.Vehicles.Add(vehicle); await contextFScope.SaveChangesAsync().ConfigureAwait(false); return(true); } } catch (Exception e) { Debug.WriteLine(e.Message); return(false); } }
public void UpdateCreditScoreForAllUsers() { /* * Demo of DbContextScope + parallel programming. */ using (var dbContextScope = _dbContextScopeFactory.Create()) { //-- Get all users var dbContext = dbContextScope.DbContexts.Get <UserManagementDbContext>(); var userIds = dbContext.Users.Select(u => u.Id).ToList(); Console.WriteLine("Found {0} users in the database. Will calculate and store their credit scores in parallel.", userIds.Count); //-- Calculate and store the credit score of each user // We're going to imagine that calculating a credit score of a user takes some time. // So we'll do it in parallel. // You MUST call SuppressAmbientContext() when kicking off a parallel execution flow // within a DbContextScope. Otherwise, this DbContextScope will remain the ambient scope // in the parallel flows of execution, potentially leading to multiple threads // accessing the same DbContext instance. using (_dbContextScopeFactory.SuppressAmbientContext()) { Parallel.ForEach(userIds, UpdateCreditScore); } // Note: SaveChanges() isn't going to do anything in this instance since all the changes // were actually made and saved in separate DbContextScopes created in separate threads. dbContextScope.SaveChanges(); } }
public void CreateUser(UserCreationSpec userToCreate) { if (userToCreate == null) { throw new ArgumentNullException("userToCreate"); } userToCreate.Validate(); /* * Typical usage of DbContextScope for a read-write business transaction. * It's as simple as it looks. */ using (var dbContextScope = _dbContextScopeFactory.Create()) { //-- Build domain model var user = new User() { Id = userToCreate.Id, Name = userToCreate.Name, Email = userToCreate.Email, WelcomeEmailSent = false, CreatedOn = DateTime.UtcNow }; //-- Persist _userRepository.Add(user); dbContextScope.SaveChanges(); } }
public void Update(Entities.Vacancy value) { using (var scope = _dbContextScopeFactory.Create()) { var dbContext = scope.DbContexts .Get <ApplicationDbContext>(); var existed = dbContext.Set <Vacancy>().SingleOrDefault(s => s.ID == value.ID); existed.Title = value.Title; existed.ShortDescription = value.ShortDescription; existed.Bonuses = value.Bonuses; existed.Requirments = value.Requirments; existed.Responsibilities = value.Responsibilities; existed.WeOffer = value.WeOffer; existed.CreatedDate = value.CreatedDate; existed.IsPositionOpen = value.IsPositionOpen; existed.Technologies = HandleCollection <Technology, int>( existed.Technologies.ToList(), value.Technologies.ToList(), tech => tech.ID, dbContext); scope.SaveChanges(); } }
/// <inheritdoc /> public async Task SavePayment(Payment payment) { using (var dbContextScope = dbContextScopeFactory.Create()) { AddPaymentToChangeSet(payment); await dbContextScope.SaveChangesAsync(); } }
public void InsertColor(Domain.Nitaqat.Color color) { using (var dbContextScope = _dbContextScopeFactory.Create()) { _colorRepository.Add(color); dbContextScope.SaveChanges(); } }
private async Task <Box> Item(CreateTeltonikaGps context) { using (var contextFScope = _dbContextScopeFactory.Create()) { _db = contextFScope.DbContexts.Get <SmartFleetObjectContext>(); return(await _db.Boxes.SingleOrDefaultAsync(b => b.Imei == context.Imei)); } }
public void DeleteCity(Domain.Labor.City city) { using (var dbContextScope = _dbContextScopeFactory.Create()) { _cityRepository.Delete(city); dbContextScope.SaveChanges(); } }
public virtual ICollection <T> BaseGetAll() { using (var dbContextScope = _dbContextScopeFactory.Create()) { var context = GetDbContext(dbContextScope.DbContexts); return(context.Set <T>().ToList <T>()); } }
public ResponseHelper InsertOrUpdate(Category model) { var rh = new ResponseHelper(); var newRecord = false; try { using (var ctx = _dbContextScopeFactory.Create()) { if (model.Id > 0) { var originalCategory = _categoryRepo.Single(x => x.Id == model.Id); originalCategory.Name = model.Name; originalCategory.Icon = model.Icon; originalCategory.Slug = Slug.Category(model.Id, model.Name); _categoryRepo.Update(originalCategory); } else { newRecord = true; // Después de insertar el campo Id ya tiene ID _categoryRepo.Insert(model); } ctx.SaveChanges(); } if (newRecord) { using (var ctx = _dbContextScopeFactory.Create()) { // Obtenemos el registro insertado var originalCategory = _categoryRepo.Single(x => x.Id == model.Id); originalCategory.Slug = Slug.Category(model.Id, model.Name); // Actualizamos _categoryRepo.Update(originalCategory); ctx.SaveChanges(); } } Parameters.CategoryList = GetForMenu(); rh.SetResponse(true); } catch (Exception e) { logger.Error(e.Message); rh.SetResponse(false, e.Message); } return(rh); }
public async Task Consume(ConsumeContext <CreateTk103Gps> context) { using (var contextFScope = _dbContextScopeFactory.Create()) { var db = contextFScope.DbContexts.Get <SmartFleetObjectContext>(); Box box; using (DbContextTransaction scope = db.Database.BeginTransaction()) { box = await db.Boxes.FirstOrDefaultAsync(x => x.SerialNumber == context.Message.SerialNumber) .ConfigureAwait(false); scope.Commit(); } if (box == null) { box = new Box(); box.Id = Guid.NewGuid(); box.BoxStatus = BoxStatus.Prepared; box.CreationDate = DateTime.UtcNow; box.LastGpsInfoTime = context.Message.TimeStampUtc; box.Icci = String.Empty; box.PhoneNumber = String.Empty; box.Vehicle = null; box.Imei = context.Message.IMEI; box.SerialNumber = context.Message.SerialNumber; db.Boxes.Add(box); } if (box.BoxStatus == BoxStatus.WaitInstallation) { box.BoxStatus = BoxStatus.Prepared; } box.LastGpsInfoTime = context.Message.TimeStampUtc; var address = await _geoCodingService.ExecuteQueryAsync(context.Message.Latitude, context.Message.Longitude).ConfigureAwait(false); Position position = new Position { Box_Id = box.Id, Altitude = 0, Direction = 0, Lat = context.Message.Latitude, Long = context.Message.Longitude, Speed = context.Message.Speed, Id = Guid.NewGuid(), Priority = 0, Satellite = 0, Timestamp = context.Message.TimeStampUtc, Address = address.display_name, MotionStatus = (int)context.Message.Speed > 2 ? MotionStatus.Moving : MotionStatus.Stopped }; db.Positions.Add(position); await contextFScope.SaveChangesAsync().ConfigureAwait(false); } }
public ClientModel Add(ClientModel model) { using (var scope = _contextScopeFactory.Create()) { var entity = _mapper.Map <Client> (model); _repository.Add(entity); _repository.Save(); return(model); } }
public async Task Launch(Reference <Ship> ship, Reference <Player> player) { using var dbContextScope = dbContextScopeFactory.Create(); var s = Ship.Launch(ship, player); await shipRepository.Save(s); await dbContextScope.SaveChangesAsync(); }
public List <Testimonial> GetByIds(int[] ids) { using (var scope = _dbContextScopeFactory.Create()) { var dbContext = scope.DbContexts.Get <ApplicationDbContext>(); return(dbContext.Set <Testimonial>() .Where(t => ids.Contains(t.ID)) .ToList()); } }
public void Add(Comment item) { if (item != null) { using (var scope = _dbContextScopeFactory.Create()) { _commentRepository.Add(item); scope.SaveChanges(); } } }
public void CreatDictionary(DictionaryDto dto) { var entity = Mapper.Map <DictionaryDto, Dictionary>(dto); entity.CreateDate = DateTime.Now; using (var dbScope = _dbScopeFactory.Create()) { var db = dbScope.DbContexts.Get <FireProjDbContext>(); db.Dictionary.Add(entity); db.SaveChanges(); } }
public void Setup() { _dbContextScopeFactory = Substitute.For<IDbContextScopeFactory>(); _ambientDbContextLocator = Substitute.For<IAmbientDbContextLocator>(); _photographRepository = Substitute.For<IPhotographRepository>(); _dbContext = Substitute.For<IDbContextScope>(); _dbContextScopeFactory.Create().Returns(_dbContext); _photographService = new PhotographServices(_dbContextScopeFactory, _photographRepository); }