public PedidosComprasModel GenerarPedidoCompraDeLineasPedidos(string fkserie, string fecha, string fkproveedor, IEnumerable <StLineasAsistentePedidos> lineas) { if (!lineas.Any()) { throw new Exception("No existen lineas para generar un pedido de compra"); } using (var tran = TransactionScopeBuilder.CreateTransactionObject()) { var result = Helper.fModel.GetModel <PedidosComprasModel>(_context); using (var pedidosService = FService.Instance.GetService(typeof(PedidosModel), _context) as PedidosService) { ImportarCabecera(fkserie, fkproveedor, fecha, result); GenerarLineas(pedidosService, result, result.Lineas, lineas); result.Totales = Recalculartotales(result.Lineas, result.Porcentajedescuentoprontopago ?? 0, result.Porcentajedescuentocomercial ?? 0, result.Importeportes ?? 0, result.Decimalesmonedas).ToList(); result.Importetotaldoc = Math.Round(result.Totales.Sum(f => f.Subtotal) ?? 0.0, result.Decimalesmonedas); create(result); tran.Complete(); return(result); } } }
public override void create(IModelView obj) { using (var tran = TransactionScopeBuilder.CreateTransactionObject()) { var model = obj as AcabadosModel; //Hemos puesto a check el bruto if (model.Bruto) { var posibleAcabado = _db.Acabados.Where(f => f.empresa == Empresa && f.bruto == true).Select(f => f.id).SingleOrDefault(); if (!String.IsNullOrEmpty(posibleAcabado)) { var acabadoEnBruto = this.get(posibleAcabado); this.delete(acabadoEnBruto); } } //Llamamos al base base.create(obj); //Guardamos los cambios _db.SaveChanges(); tran.Complete(); } }
public override void create(IModelView obj) { using (var tran = TransactionScopeBuilder.CreateTransactionObject()) { var model = obj as TransformacioneslotesModel; // Calcular costesadicionales costexm2 o costexm3 //DocumentosHelpers.GenerarCarpetaAsociada(model, TipoDocumentos.TransformacionesAcabados, _context, _db); CalcularCosteTotalMetros(model.Lineas, model.Costes); var validation = _validationService as TransformacioneslotesValidation; validation.EjercicioId = EjercicioId; RepartirCostesLineas(model.Lineas, model.Costes); //Calculo ID var contador = ServiceHelper.GetNextId <Transformacioneslotes>(_db, Empresa, model.Fkseries); var identificadorsegmento = ""; model.Referencia = ServiceHelper.GetReference <Transformacioneslotes>(_db, model.Empresa, model.Fkseries, contador, model.Fechadocumento.Value, out identificadorsegmento); model.Identificadorsegmento = identificadorsegmento; //CalcularPrecioPiezas(model.Lineas, model.Lineas.Sum(f => f.Precio * f.Metros) ?? 0); foreach (var item in model.Lineas) { item.Precio = Math.Round((double)(item.Precio * item.Metros), 2); } base.create(obj); var trobj = _db.Transformacioneslotes.Single(f => f.empresa == model.Empresa && f.referencia == model.Referencia); model.Id = trobj.id; ModificarArticuloLote(model); _db.SaveChanges(); tran.Complete(); } }
public async Task <IActionResult> UpdateProfile(long userId, [FromBody] UserProfileDto userProfileDto) { if (!ModelState.IsValid) { return(new BadRequestObjectResult(ModelState)); } using (var tx = TransactionScopeBuilder.New()) { // NOTE: no need for transaction *** although due the def. TX level the DbContext has (serializabe) *** we should add to have repeatable read or read committed var user = dbContext .Set <User>() .Include(u => u.Profile) .First(u => u.Id == userId); user.Profile = user.Profile ?? new UserProfile(); user.Profile.AllowedCalories = userProfileDto.AllowedCalories; await dbContext.SaveChangesAsync(); tx.Complete(); } return(Ok()); }
public override void create(IModelView obj) { using (var tran = TransactionScopeBuilder.CreateTransactionObject()) { var model = obj as CampañasModel; var validation = _validationService as CampañasValidation; model.Id = NextId(); var appService = new ApplicationHelper(_context); if (model.Fechadocumento == null) { model.Fechadocumento = DateTime.Now; } var contador = ServiceHelper.GetNextId <Campañas>(_db, Empresa, model.Fkseries); var identificadorsegmento = ""; model.Referencia = ServiceHelper.GetReference <Campañas>(_db, model.Empresa, model.Fkseries, contador, model.Fechadocumento.Value, out identificadorsegmento); model.Identificadorsegmento = identificadorsegmento; foreach (var linea in model.Campañas) { linea.Empresa = model.Empresa; linea.Context = model.Context; linea.Fkcampañas = model.Id; } base.create(obj); _db.SaveChanges(); tran.Complete(); } }
public async Task ExecuteAsync(PostId postId, DateTime now, Func <Task> potentialRemovalOperation) { postId.AssertNotNull("postId"); now.AssertUtc("now"); potentialRemovalOperation.AssertNotNull("potentialRemovalOperation"); var queuedCollectionId = await this.tryGetPostQueueId.ExecuteAsync(postId, now); if (queuedCollectionId == null) { await potentialRemovalOperation(); } else { var weeklyReleaseSchedule = await this.getWeeklyReleaseSchedule.ExecuteAsync(queuedCollectionId); using (var transaction = TransactionScopeBuilder.CreateAsync()) { await potentialRemovalOperation(); await this.defragmentQueue.ExecuteAsync(queuedCollectionId, weeklyReleaseSchedule, now); transaction.Complete(); } } }
//public void ModificarCostes(TransformacioneslotesModel model) //{ // var currentValidationService = _validationService as TransformacioneslotesValidation; // currentValidationService.ModificarCostes = true; // edit(model); // currentValidationService.ModificarCostes = false; //} public void ModificarCostes(TransformacioneslotesModel model)//, List<TransformacioneslotesModel> costesOriginal = null) { var currentValidationService = _validationService as TransformacioneslotesValidation; currentValidationService.ModificarCostes = true; //jmm using (var tran = TransactionScopeBuilder.CreateTransactionObject()) { var original = get(Funciones.Qnull(model.get("id"))) as TransformacioneslotesModel; foreach (var item in model.Lineas) { item.Nueva = false; } CalcularCosteTotalMetros(model.Lineas, model.Costes); RepartirCostesLineas(model.Lineas, model.Costes); //edit(model); base.edit(model); var trabajosService = FService.Instance.GetService(typeof(TrabajosModel), _context) as TrabajosService; var trabajosObj = trabajosService.get(model.Fktrabajos) as TrabajosModel; GenerarMovimientosLineasCostes(original.Lineas, original, TipoOperacionService.EliminarCostes, trabajosObj); GenerarMovimientosLineasCostes(model.Lineas, model, TipoOperacionService.InsertarCostes, trabajosObj); _db.SaveChanges(); tran.Complete(); } currentValidationService.ModificarCostes = false; }
public override void edit(IModelView obj) { using (var tran = TransactionScopeBuilder.CreateTransactionObject()) { var model = obj as IncidenciasCRMModel; var currentValidationService = _validationService as IncidenciasCRMValidation; var etapaAnterior = _db.IncidenciasCRM.Where(f => f.empresa == model.Empresa && f.id == model.Id).Select(f => f.fketapa).SingleOrDefault(); var s = etapaAnterior.Split('-'); var documento = Funciones.Qint(s[0]); var id = s[1]; var estadoAnterior = _db.Estados.Where(f => f.documento == documento && f.id == id).Select(f => f.tipoestado).SingleOrDefault(); if (model.Cerrado && (estadoAnterior != (int)TipoEstado.Finalizado && estadoAnterior != (int)TipoEstado.Caducado && estadoAnterior != (int)TipoEstado.Anulado)) { var estadoFinalizado = _db.Estados.Where(f => f.documento == (int)DocumentoEstado.Incidencias && f.tipoestado == (int)TipoEstado.Finalizado).SingleOrDefault() ?? _db.Estados.Where(f => f.documento == (int)DocumentoEstado.Todos && f.tipoestado == (int)TipoEstado.Finalizado).SingleOrDefault(); model.Fketapa = estadoFinalizado.documento + "-" + estadoFinalizado.id; currentValidationService.CambiarEstado = true; } base.edit(obj); _db.SaveChanges(); tran.Complete(); } }
public async Task <IActionResult> UpdateMeal(long userId, long mealId, [FromBody] MealDto mealDto) { if (!ModelState.IsValid) { return(new BadRequestObjectResult(ModelState)); } using (var tx = TransactionScopeBuilder.New()) { var meal = ( from u in dbContext.Set <User>() from m in u.Meals where u.Id == userId && m.Id == mealId select m ).First(); meal.Date = mealDto.Date; meal.Calories = mealDto.Calories; meal.Description = mealDto.Description; await dbContext.SaveChangesAsync(); tx.Complete(); } return(Ok()); }
public async Task SchedulePostAsync(Post post, IReadOnlyList <PostFile> postFiles, DateTime?scheduledPostDate, DateTime now) { post.AssertNotNull("post"); if (post.QueueId.HasValue) { throw new ArgumentException("Queue ID should not exist", "post"); } if (scheduledPostDate.HasValue) { now.AssertUtc("scheduledPostDate"); } now.AssertUtc("now"); post.LiveDate = this.scheduledDateClipping.Apply(now, scheduledPostDate); using (var transaction = TransactionScopeBuilder.CreateAsync()) { // The order we access tables should match RevisePostDbStatement. using (var connection = this.connectionFactory.CreateConnection()) { await connection.InsertAsync(post); await connection.InsertAsync(postFiles); } transaction.Complete(); } }
private async Task CreateChannelAsync(UserId userId, CreateChannelCommand command) { var now = DateTime.UtcNow; var channel = new Channel( command.NewChannelId.Value, command.BlogId.Value, null, command.Name.Value, command.Price.Value, command.IsVisibleToNonSubscribers, now, now, false); using (var transaction = TransactionScopeBuilder.CreateAsync()) { using (var connection = this.connectionFactory.CreateConnection()) { await connection.InsertAsync(channel); } await this.requestSnapshot.ExecuteAsync(userId, SnapshotType.CreatorChannels); transaction.Complete(); } }
public async Task <IActionResult> CreateMeal(long userId, [FromBody] MealDto mealDto) { if (!ModelState.IsValid) { return(new BadRequestObjectResult(ModelState)); } long?mealId = null; using (var tx = TransactionScopeBuilder.New()) { var user = dbContext .Set <User>() .First(u => u.Id == userId); // NOTE: with DDD it would be a user.AddMeal(date, calories, desc) where inside I'd set the back-ref to User as well (always valid object graph)! var meal = new UserMeal() { Date = mealDto.Date, Calories = mealDto.Calories, Description = mealDto.Description }; user.Meals.Add(meal); // it's not NH, so to get the ID we need to save await dbContext.SaveChangesAsync(); mealId = meal.Id; tx.Complete(); } return(this.Created(mealId)); }
public async Task ExecuteAsync( UserId userId, ChannelId channelId, ValidChannelName name, ValidChannelPrice price, bool isVisibleToNonSubscribers, DateTime now) { using (var transaction = TransactionScopeBuilder.CreateAsync()) { using (var connection = this.connectionFactory.CreateConnection()) { await connection.ExecuteAsync( UpdateStatement, new { Id = channelId.Value, IsVisibleToNonSubscribers = isVisibleToNonSubscribers, Name = name.Value, Price = price.Value, PriceLastSetDate = now }); } await this.requestSnapshot.ExecuteAsync(userId, SnapshotType.CreatorChannels); transaction.Complete(); } }
public void CreateAdmin(string password) { using (var tran = TransactionScopeBuilder.CreateTransactionObject()) { if (!_db.Administrador.Any()) { if (string.IsNullOrEmpty(password)) { throw new ValidationException("El password no puede estar vacío"); } var item = _db.Administrador.Create(); item.password = password; _db.Administrador.Add(item); var usuarioAministrador = _db.Usuarios.Create(); usuarioAministrador.id = Guid.Empty; usuarioAministrador.usuario = ApplicationHelper.UsuariosAdministrador; usuarioAministrador.password = password; usuarioAministrador.nombre = ApplicationHelper.UsuariosAdministrador; _db.Usuarios.Add(usuarioAministrador); _db.SaveChanges(); tran.Complete(); } } }
public async Task ExecuteAsync(QueueId queueId, WeeklyReleaseSchedule weeklyReleaseSchedule) { queueId.AssertNotNull("queueId"); weeklyReleaseSchedule.AssertNotNull("weeklyReleaseSchedule"); var newWeeklyReleaseTimes = weeklyReleaseSchedule.Value.Select( _ => new WeeklyReleaseTime(queueId.Value, null, (byte)_.Value)); var deletionParameters = new { QueueId = queueId.Value }; // Transaction required on the following, as database must always contain at least one weekly release time per // collection. The absence of weekly release times would cause a breaking inconsistency. using (var transaction = TransactionScopeBuilder.CreateAsync()) { using (var connection = this.connectionFactory.CreateConnection()) { await connection.ExecuteAsync(DeleteWeeklyReleaseTimesSql, deletionParameters); await connection.InsertAsync(newWeeklyReleaseTimes); } transaction.Complete(); } }
private async Task CreateQueueAsync(CreateQueueCommand command) { var queue = new Queue( command.NewQueueId.Value, command.BlogId.Value, null, command.Name.Value, DateTime.UtcNow); var releaseDate = new WeeklyReleaseTime( command.NewQueueId.Value, null, (byte)command.InitialWeeklyReleaseTime.Value); // Assuming no lock escalation, this transaction will hold X locks on the new rows and IX locks further up the hierarchy, // so no deadlocks are to be expected. using (var transaction = TransactionScopeBuilder.CreateAsync()) { using (var connection = this.connectionFactory.CreateConnection()) { await connection.InsertAsync(queue); await connection.InsertAsync(releaseDate); } transaction.Complete(); } }
public override void delete(IModelView obj) { using (var tran = TransactionScopeBuilder.CreateTransactionObject()) { base.delete(obj); EliminarPreferencias(obj as ConfiguraciongraficasModel); tran.Complete(); } }
public async Task ExecuteAsync( UserId userId, Username username, Email email, string exampleWork, Password password, DateTime timeStamp) { userId.AssertNotNull("userId"); username.AssertNotNull("username"); email.AssertNotNull("email"); password.AssertNotNull("password"); var passwordHash = this.userManager.PasswordHasher.HashPassword(password.Value); var user = new FifthweekUser { Id = userId.Value, UserName = username.Value, Email = email.Value, ExampleWork = exampleWork, RegistrationDate = timeStamp, LastSignInDate = SqlDateTime.MinValue.Value, LastAccessTokenDate = SqlDateTime.MinValue.Value, SecurityStamp = Guid.NewGuid().ToString(), PasswordHash = passwordHash, }; var parameters = new SqlGenerationParameters <FifthweekUser, FifthweekUser.Fields>(user) { Conditions = new[] { WhereUsernameNotTaken, WhereEmailNotTaken } }; using (var transaction = TransactionScopeBuilder.CreateAsync()) { using (var connection = this.connectionFactory.CreateConnection()) { var result = await connection.InsertAsync(parameters); switch (result) { case 0: throw new RecoverableException("The username '" + username.Value + "' is already taken."); case 1: throw new RecoverableException("The email address '" + email.Value + "' is already taken."); } } await this.requestSnapshot.ExecuteAsync(userId, SnapshotType.Subscriber); transaction.Complete(); } }
public override void edit(IModelView obj) { using (var tran = TransactionScopeBuilder.CreateTransactionObject()) { var editado = obj as FamiliasproductosModel; base.edit(editado); _db.SaveChanges(); tran.Complete(); } }
public async Task <int> UpdateAsync(SampleTable t, CancellationToken token) { using var tran = TransactionScopeBuilder.Create(); // if transaction needed. using var session = sessionManager.OpenSession(); var updResult = await session.Db.UpdateAsync(t, token : token); tran.Complete(); return(updResult); }
public void SaldarPedidos(OperacionSaldarPedidosModel model, AlbaranesModel entrega) { using (var tran = TransactionScopeBuilder.CreateTransactionObject()) { entrega.Pedidosaldado = true; SaldarLineaPedidos(model); edit(entrega); _db.SaveChanges(); tran.Complete(); } }
public override void edit(IModelView obj) { using (var tran = TransactionScopeBuilder.CreateTransactionObject()) { //var original = get(Funciones.Qnull(obj.get("id"))) as GrupoMaterialesModel; //var editado = obj as GrupoMaterialesModel; base.edit(obj); _db.SaveChanges(); tran.Complete(); } }
public override void create(IModelView obj) { using (var tran = TransactionScopeBuilder.CreateTransactionObject()) { var model = obj as CircuitoTesoreriaCobrosModel; //Llamamos al base base.create(obj); //Guardamos los cambios _db.SaveChanges(); tran.Complete(); } }
protected async Task DatabaseTestAsync(Func <TestDatabaseContext, Task <ExpectedSideEffects> > databaseTest) { var database = await TestDatabase.CreateNewAsync(); var databaseSnapshot = new TestDatabaseSnapshot(database); var databaseContext = new TestDatabaseContext(database, databaseSnapshot); using (TransactionScopeBuilder.CreateAsync()) { var sideEffects = await databaseTest(databaseContext); await databaseSnapshot.AssertSideEffectsAsync(sideEffects); } }
public override void create(IModelView obj) { using (var tran = TransactionScopeBuilder.CreateTransactionObject()) { var model = obj as ImputacionCostesModel; var validation = _validationService as ImputacionCostesValidation; validation.EjercicioId = EjercicioId; model.Id = NextId(); var appService = new ApplicationHelper(_context); if (model.Fechadocumento == null) { model.Fechadocumento = DateTime.Now; } var contador = ServiceHelper.GetNextId <ImputacionCostes>(_db, Empresa, model.Fkseries); var identificadorsegmento = ""; model.Referencia = ServiceHelper.GetReference <ImputacionCostes>(_db, model.Empresa, model.Fkseries, contador, model.Fechadocumento.Value, out identificadorsegmento); model.Identificadorsegmento = identificadorsegmento; //Calculo id entradas int index = 1; foreach (var lin in model.LineasLotes) { lin.Empresa = model.Empresa; lin.Fkimputacioncostes = model.Id.Value; lin.Id = index; lin.Empresa = Empresa; index++; } ////Calculo id salidas //index = 1; //foreach (var lin in model.LineasCostes) //{ // lin.Empresa = model.Empresa; // lin.Fkimputacioncostes = model.Id.Value; // lin.Id = index; // lin.Empresa = Empresa; // index++; //} //Llamamos al base base.create(model); //Guardamos los cambios _db.SaveChanges(); tran.Complete(); } }
public async Task ExecuteAsync( UserId subscriberId, UserId creatorId, IReadOnlyList <AppendOnlyLedgerRecord> ledgerRecords, UncommittedSubscriptionPayment uncommittedRecord) { subscriberId.AssertNotNull("subscriberId"); creatorId.AssertNotNull("creatorId"); ledgerRecords.AssertNotNull("ledgerRecords"); using (PaymentsPerformanceLogger.Instance.Log(typeof(PersistCommittedAndUncommittedRecordsDbStatement))) using (var transaction = TransactionScopeBuilder.CreateAsync()) { using (var connection = this.connectionFactory.CreateConnection()) { if (ledgerRecords.Any()) { await connection.InsertAsync(ledgerRecords, false); } if (uncommittedRecord != null) { var uncommittedFields = UncommittedSubscriptionPayment.Fields.StartTimestampInclusive | UncommittedSubscriptionPayment.Fields.EndTimestampExclusive | UncommittedSubscriptionPayment.Fields.Amount | UncommittedSubscriptionPayment.Fields.InputDataReference; await connection.UpsertAsync(uncommittedRecord, uncommittedFields); } else { // Remove the existing uncommitted record. await connection.ExecuteAsync( string.Format( @"DELETE FROM {0} WHERE {1}=@SubscriberId AND {2}=@CreatorId", UncommittedSubscriptionPayment.Table, UncommittedSubscriptionPayment.Fields.SubscriberId, UncommittedSubscriptionPayment.Fields.CreatorId), new { SubscriberId = subscriberId.Value, CreatorId = creatorId.Value }); } } transaction.Complete(); } }
public async Task ExecuteAsync(UserId userId, BlogId blogId, IReadOnlyList <AcceptedChannelSubscription> channels, DateTime now) { userId.AssertNotNull("userId"); blogId.AssertNotNull("blogId"); if (channels == null || channels.Count == 0) { channels = new List <AcceptedChannelSubscription>(); } using (var transaction = TransactionScopeBuilder.CreateAsync()) { using (var connection = this.connectionFactory.CreateConnection()) { await connection.ExecuteAsync( DeleteStatement, new { BlogId = blogId.Value, SubscriberId = userId.Value, KeepChannelIds = channels.Select(v => v.ChannelId.Value).ToList() }); foreach (var item in channels) { var channelSubscription = new ChannelSubscription( item.ChannelId.Value, null, userId.Value, null, item.AcceptedPrice.Value, now, now); const ChannelSubscription.Fields UpdateFields = ChannelSubscription.Fields.AcceptedPrice | ChannelSubscription.Fields.PriceLastAcceptedDate; await connection.UpsertAsync( channelSubscription, UpdateFields); } } await this.requestSnapshot.ExecuteAsync(userId, SnapshotType.SubscriberChannels); transaction.Complete(); } }
public async Task ExecuteAsync(QueueId queueId, WeeklyReleaseSchedule weeklyReleaseSchedule, DateTime now) { queueId.AssertNotNull("queueId"); weeklyReleaseSchedule.AssertNotNull("weeklyReleaseSchedule"); now.AssertUtc("now"); // Transaction required on the following, as we don't want user to see a queue that does not match the collection's release times. using (var transaction = TransactionScopeBuilder.CreateAsync()) { await this.replaceWeeklyReleaseTimes.ExecuteAsync(queueId, weeklyReleaseSchedule); await this.defragmentQueue.ExecuteAsync(queueId, weeklyReleaseSchedule, now); transaction.Complete(); } }
public override void delete(IModelView obj) { using (var tran = TransactionScopeBuilder.CreateTransactionObject()) { var objPersistance = _converterModel.EditPersitance(obj); ((CuentasValidation)_validationService).FlagDeleteFromThird = FlagDeleteFromThird; if (_validationService.ValidarBorrar(objPersistance)) { BorrarCuentasAsociadas(obj as CuentasModel); _db.Set <Cuentas>().Remove(objPersistance); _db.SaveChanges(); } tran.Complete(); } }
public override void create(IModelView obj) { using (var tran = TransactionScopeBuilder.CreateTransactionObject()) { var model = obj as CarteraVencimientosModel; if (_db.CarteraVencimientos.Any()) { model.Id = _db.CarteraVencimientos.Where(f => f.empresa == Empresa).Select(f => f.id).Max() + 1; } else { model.Id = 0; } if (!model.Tiponumerofactura.HasValue) { model.Tiponumerofactura = 0; } if (!model.Monedabase.HasValue) { model.Monedabase = 0; } if (!model.Monedagiro.HasValue) { model.Monedagiro = 0; } model.Fecha = DateTime.Now; Conversion c = new Conversion(); model.Importeletra = c.enletras(model.Importegiro.ToString()); //Calculo ID var contador = ServiceHelper.GetNextIdContable <CarteraVencimientos>(_db, Empresa, model.Fkseriescontables); var identificadorsegmento = ""; model.Referencia = ServiceHelper.GetReferenceContable <CarteraVencimientos>(_db, model.Empresa, model.Fkseriescontables, contador, model.Fecha.Value, out identificadorsegmento); model.Identificadorsegmento = identificadorsegmento; //Llamamos al base base.create(model); //Guardamos los cambios _db.SaveChanges(); tran.Complete(); } }