Implementation of ISessionScope to provide transaction semantics
Inheritance: SessionScope
        public ActionResult Create(TaxpayerRecipient item)
        {
            if (!string.IsNullOrEmpty (item.Id)) {
                var entity = TaxpayerRecipient.TryFind (item.Id);

                if (entity != null) {
                    ModelState.AddModelError ("", Resources.TaxpayerRecipientAlreadyExists);
                }
            }

            if (!item.HasAddress) {
                ModelState.Where (x => x.Key.StartsWith ("Address.")).ToList ().ForEach (x => x.Value.Errors.Clear ());
                item.Address = null;
            }

            if (!ModelState.IsValid) {
                return PartialView ("_Create", item);
            }

            item.Id = item.Id.ToUpper ().Trim ();
            item.Name = item.Name.Trim ();
            item.Email = item.Email.Trim ();

            using (var scope = new TransactionScope ()) {
                if (item.HasAddress) {
                    item.Address.Create ();
                }

                item.CreateAndFlush ();
            }

            return PartialView ("_CreateSuccesful", item);
        }
        public ActionResult ApplyPayment(SalesOrderPayment item)
        {
            var entity = new SalesOrderPayment {
                SalesOrder = SalesOrder.TryFind (item.SalesOrder.Id),
                Payment = CustomerPayment.TryFind (item.PaymentId),
                Amount = item.Amount
            };
            var balance = entity.SalesOrder.Balance - GetRefunds (entity.SalesOrder.Id);

            if (entity.Amount > entity.Payment.Balance) {
                entity.Amount = entity.Payment.Balance;
            }

            balance -= entity.Amount;

            using (var scope = new TransactionScope ()) {
                if (balance <= 0) {
                    entity.SalesOrder.IsPaid = true;
                    entity.SalesOrder.Update ();
                }

                if (entity.Amount > 0) {
                    entity.Create ();
                }

                scope.Flush ();
            }

            return PartialView ("_ApplyPaymentSuccesful");
        }
Beispiel #3
0
        public JsonResult AddPurchaseDetail(int movement, int warehouse, int product)
        {
            var p = Product.Find (product);
            var cost = (from x in ProductPrice.Queryable
                    where x.Product.Id == product && x.List.Id == 0
                    select x.Value).SingleOrDefault ();

            var item = new PurchaseOrderDetail {
                Order = PurchaseOrder.Find (movement),
                Warehouse = Warehouse.Find (warehouse),
                Product = p,
                ProductCode = p.Code,
                ProductName = p.Name,
                Quantity = 1,
                TaxRate = p.TaxRate,
                IsTaxIncluded = p.IsTaxIncluded,
                Discount = 0,
                Price = cost,
                ExchangeRate = CashHelpers.GetTodayDefaultExchangeRate (),
                Currency = WebConfig.DefaultCurrency
            };

            using (var scope = new TransactionScope ()) {
                item.CreateAndFlush ();
            }

            return Json (new {
                id = item.Id
            });
        }
Beispiel #4
0
        public ActionResult Create(Supplier item)
        {
            if (!ModelState.IsValid)
                return PartialView ("_Create", item);

            using (var scope = new TransactionScope ()) {
                item.CreateAndFlush ();
            }

            return PartialView ("_CreateSuccesful", item);

            //if (!ModelState.IsValid)
            //{
            //    if (Request.IsAjaxRequest())
            //        return PartialView("_Create", supplier);

            //    return View(supplier);
            //}

            //supplier.Create ();

            //if (Request.IsAjaxRequest())
            //{
            //    //FIXME: localize string
            //    return PartialView("_Success", "Operation successful!");
            //}

            //return View("Index");
        }
        public static void Registro()
        {
            foreach (var archivo in ActiveRecordBase<ConsumoDto>.FindAllByProperty("Procesado", false))
            {
                var documento = HelperPersona.GetPersona(
                    archivo.Cuit, archivo.TipoCliente,
                    archivo.RazonSocial, archivo.NombrePersona,
                    archivo.NroDocumento, archivo.Empresa);

                    var cliente = HelperCuenta.GetCuenta(
                        archivo.Cuit, archivo.NroDocumento, archivo.Empresa);

                    using (var transac = new TransactionScope())
                        try
                        {
                            var puntos = HelperPuntos.GetPuntos(archivo.Empresa, archivo.FechaHoraComprobante,
                                                            archivo.ImportePesosNetoImpuestos);

                            double acelerador = Double.Parse(archivo.Coeficiente) / 100;
                            puntos = acelerador > 0 ? acelerador * puntos : puntos;

                            var cuenta = new CuentaCorrienteDto
                            {
                                FechaCompra = archivo.FechaHoraComprobante.Date,
                                HoraCompra = DateTime.Now,
                                Key = new KeyCuenta
                                {
                                    CodEmpresa = archivo.Empresa,
                                    NumeroComprobante = archivo.NroComprobante
                                },
                                MontoCompra = archivo.ImportePesosNetoImpuestos,
                                Movimiento = puntos >= 0 ? HelperMovimiento.FindMovimiento("Suma De Puntos") : HelperMovimiento.FindMovimiento("Anulación Carga"),
                                NumeroDocumento = documento,
                                NumeroCuenta = cliente,
                                Puntos = puntos,
                                Sucursal = HelperSucursal.GetSucursal(),
                                Usuario = "web",
                                Programa = archivo.Programa,
                                Secretaria = archivo.Secretaria,
                                Coeficiente = archivo.Coeficiente
                            };
                            cuenta.Save();
                            transac.VoteCommit();
                        }
                        catch (Exception ex)
                        {
                            archivo.Error = ex.Message;
                            Log.Fatal(ex);
                            transac.VoteRollBack();
                        }
                    archivo.Procesado = true;
                    archivo.Save();
                } 
            }
		public void ActiveRecordUsingTransactionScopeWithRollback()
		{
			InitModel();
			using (TransactionScope scope = new TransactionScope())
			{
				new SSAFEntity("example").Save();
				//Assert.AreEqual(1, SSAFEntity.FindAll().Length);
				scope.VoteRollBack();
			}
			Assert.AreEqual(0, SSAFEntity.FindAll().Length);
		}
Beispiel #7
0
        public ActionResult Create(Employee item)
        {
            if (!ModelState.IsValid) {
                return PartialView ("_Create", item);
            }

            using (var scope = new TransactionScope ()) {
                item.CreateAndFlush ();
            }

            return PartialView ("_Refresh");
        }
        public ActionResult CancelReturn(int id)
        {
            var item = SupplierReturn.Find (id);

            item.IsCancelled = true;

            using (var scope = new TransactionScope ()) {
                item.UpdateAndFlush ();
            }

            return RedirectToAction ("Index");
        }
        public ActionResult Create(TechnicalServiceReceipt item)
        {
            if (!ModelState.IsValid) {
                return PartialView ("_Create", item);
            }

            using (var scope = new TransactionScope ()) {
                item.CreateAndFlush ();
            }

            return PartialView ("_CreateSuccesful", item);
        }
Beispiel #10
0
 public static void DisposeScope()
 {
     if (TransactionScope != null)
     {
         TransactionScope.Dispose();
         TransactionScope = null;
     }
     if (Scope != null)
     {
         Scope.Dispose();
         Scope = null;
     }
 }
        public void Can_execute_SQL()
        {
            using (var transaction = new TransactionScope())
            {
                var user = repository.Save(new User {Email = "*****@*****.**", Name = "User1"});
                transaction.Flush();

                repository.ExecuteSql(string.Format("UPDATE User SET Email=\"[email protected]\"", user.Id));
                transaction.Flush();

                repository.Refresh(user);
                Assert.AreEqual("*****@*****.**", user.Email);
            }
        }
        public ActionResult Create(Notarization item)
        {
            item.Requester = Employee.TryFind (item.RequesterId);

            if (!ModelState.IsValid) {
                return PartialView ("_Create", item);
            }

            using (var scope = new TransactionScope ()) {
                item.CreateAndFlush ();
            }

            return PartialView ("_CreateSuccesful", item);
        }
        public ActionResult Confirm(int id)
        {
            var item = SalesOrder.Find (id);

            item.Updater = CurrentUser.Employee;
            item.ModificationTime = DateTime.Now;
            item.IsDelivered = true;

            using (var scope = new TransactionScope ()) {
                item.UpdateAndFlush ();
            }

            return RedirectToAction ("Index");
        }
 public ActionResult Edit(int id, FormCollection form)
 {
     using (var transaction = new TransactionScope(TransactionMode.Inherits))
     {
         var original = Document.Find(id);
         if (TryUpdateModel(original))
         {
             original.Save();
             return RedirectToAction("Details", new { Id = id });
         }
         transaction.VoteRollBack();
         return View("Edit");
     }
 }
        public ActionResult Create(TechnicalServiceRequest item)
        {
            item.Customer = Customer.TryFind (item.CustomerId);

            if (!ModelState.IsValid) {
                return PartialView ("_Create", item);
            }

            using (var scope = new TransactionScope ()) {
                item.CreateAndFlush ();
            }

            return PartialView ("_CreateSuccesful", item);
        }
        /// <summary>
        /// evento disparado pelo botão salvar
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnSalvar_Click1(object sender, EventArgs e)
        {
            //bisca a lista de moradores selecionados
            List<int> lista = (List<int>)ViewState["moradores"];

            
            if (lista.Count > 0)
            {
                //abre a transação
                using (TransactionScope trans = new TransactionScope())
                {
                    try
                    {
                        //cria o template da mensagem
                        Domain.Model.Mensagem mensagem = new Domain.Model.Mensagem();
                        mensagem.Usuario = txtUsuario.Text;
                        mensagem.Detalhe = txtMensagem.Text;
                        mensagem.CreateAndFlush();


                        Usuario user = new Usuario();
                        MensagensDosUsuarios mensagemRelacionada;
                        //envia a mensagem para casa usuário selecionado
                        foreach (var item in lista)
                        {
                            user.Id = item;
                            mensagemRelacionada = new MensagensDosUsuarios();
                            mensagemRelacionada.Mensagem = mensagem;
                            mensagemRelacionada.Usuario = user;
                            mensagemRelacionada.CreateAndFlush();
                        }
                        //commit da transação
                        trans.VoteCommit();
                    }
                    catch (Exception ex)
                    {
                        //rollback da transação
                        trans.VoteRollBack();
                        //grava o erro em um log
                        Logger.Error(ex.Message);
                        base.ExibirMensagemErro();
                    }
                }
                base.ExibirMensagemSucesso(Funcionalidade.Mensagem, Operacao.Inclusao);
            }
            else
            {
                pnlMensagem.ExibirMensagem("Selecione os usuários para quem você vai enviar a mensagem");
            }
        }
        public ActionResult Cancel(int id)
        {
            var entity = CustomerRefund.Find (id);

            entity.Updater = CurrentUser.Employee;
            entity.ModificationTime = DateTime.Now;
            entity.Date = DateTime.Now;
            entity.IsCancelled = true;

            using (var scope = new TransactionScope ()) {
                entity.UpdateAndFlush ();
            }

            return RedirectToAction ("Index");
        }
        public ActionResult Confirm(int id)
        {
            var dt = DateTime.Now;
            bool changed = false;
            var entity = CustomerRefund.Find (id);

            using (var scope = new TransactionScope ()) {
                foreach (var item in entity.Details) {
                    var qty = GetRefundableQuantity (item.SalesOrderDetail.Id);

                    if (qty < item.Quantity) {
                        changed = true;

                        if (qty > 0) {
                            item.Quantity = qty;
                            item.Update ();
                        } else {
                            item.Delete ();
                        }
                    }
                }

                if (changed) {
                    entity.Updater = CurrentUser.Employee;
                    entity.ModificationTime = dt;
                    entity.UpdateAndFlush ();

                    return RedirectToAction ("Edit", new { id = entity.Id, notify = true });
                }
            }

            using (var scope = new TransactionScope ()) {

                foreach (var x in entity.Details) {
                    InventoryHelpers.ChangeNotification (TransactionType.CustomerRefund, entity.Id, dt,
                        x.SalesOrderDetail.Warehouse, null, x.Product, x.Quantity);
                }

                entity.Updater = CurrentUser.Employee;
                entity.ModificationTime = dt;
                entity.Date = dt;
                entity.IsCompleted = true;
                entity.UpdateAndFlush ();
            }

            return RedirectToAction ("View", new { id = entity.Id });
        }
        public ActionResult ConfirmReturn(int id)
        {
            var item = SupplierReturn.Find (id);

            var qry = from x in item.Details
                  where x.Order.Id == id
                  group x by x.Warehouse into g
                  select new { Warehouse = g.Key, Details = g.ToList () };

            var dt = DateTime.Now;
            var employee = CurrentUser.Employee;

            using (var scope = new TransactionScope ()) {
                foreach (var x in qry) {
                    var master = new InventoryIssue {
                        Return = item,
                        Warehouse = x.Warehouse,
                        CreationTime = dt,
                        ModificationTime = dt,
                        Creator = employee,
                        Updater = employee,
                        Comment = string.Format (Resources.Message_SupplierReturn, item.Supplier.Name, item.PurchaseOrder.Id, item.Id)
                    };

                    master.Create ();

                    foreach (var y in x.Details) {
                        var detail = new InventoryIssueDetail {
                            Issue = master,
                            Product = y.Product,
                            Quantity = y.Quantity,
                            ProductCode = y.ProductCode,
                            ProductName = y.ProductName
                        };

                        detail.Create ();
                    }
                }

                item.IsCompleted = true;
                item.UpdateAndFlush ();
            }

            return RedirectToAction ("Index");
        }
Beispiel #20
0
        public JsonResult AddIssueDetail(int movement, int product)
        {
            var p = Product.Find (product);

            var item = new InventoryIssueDetail {
                Issue = InventoryIssue.Find (movement),
                Product = p,
                ProductCode = p.Code,
                ProductName = p.Name,
                Quantity = 1
            };

            using (var scope = new TransactionScope ()) {
                item.CreateAndFlush ();
            }

            return Json (new {
                id = item.Id
            });
        }
        public static string GetPaymentUrl(Transaction idealPayer, string mollieClientNumber, bool testMode, string paymentName, string reportUrl, string landUrl)
        {
            if(idealPayer.Payed)
                throw new Exception("Er is al betaald");

            IdealFetch idealFetch = new IdealFetch(mollieClientNumber, testMode, paymentName, reportUrl, landUrl, idealPayer.BankId, idealPayer.Amount);

            if (idealFetch.Error)
            {
                throw new Exception(idealFetch.ErrorMessage);
            }

            idealPayer.TransactionId = idealFetch.TransactionId;
            using( TransactionScope transactionScope = new TransactionScope(TransactionMode.Inherits, OnDispose.Rollback))
            {
                idealPayer.Save();
                transactionScope.VoteCommit();
            }

            return idealFetch.Url;
        }
        public ActionResult Create(Document document)
        {
            using(var transaction = new TransactionScope(TransactionMode.New))
            {
                try
                {
                    var user = _user.UserName();
                    var author = Models.User.FindByUsername(user);
                    author.Documents.Add(document);
                    author.Save();
                    return RedirectToAction("Index");
                }
                catch (NotFoundException ex)
                {
                    transaction.VoteRollBack();
                    ViewBag.ErrorMessage = String.Format("{0}. Please add the user first.", ex.Message);

                }
            }
            return View("Create");
        }
Beispiel #23
0
        public ActionResult AddTaxpayer(int id, string value)
        {
            var item = Customer.TryFind (id);
            var taxpayer = TaxpayerRecipient.TryFind (value);

            if (item == null) {
                Response.StatusCode = 400;
                return Content (Resources.CustomerNotFound);
            }

            if (taxpayer == null) {
                Response.StatusCode = 400;
                return Content (Resources.TaxpayerRecipientNotFound);
            }

            using (var scope = new TransactionScope ()) {
                item.Taxpayers.Add (taxpayer);
                item.Update ();
            }

            return Json (new { id = id, result = true });
        }
        public ActionResult AddItem(int id, int product)
        {
            var p = Product.Find (product);
            var entity = DeliveryOrder.Find (id);

            if (entity.IsCompleted || entity.IsCancelled) {
                Response.StatusCode = 400;
                return Content (Resources.ItemAlreadyCompletedOrCancelled);
            }

            var item = new DeliveryOrderDetail {
                DeliveryOrder = DeliveryOrder.Find (id),
                Product = p,
                ProductCode = p.Code,
                ProductName = p.Name,
                Quantity = 1,
            };

            using (var scope = new TransactionScope ()) {
                item.CreateAndFlush ();
            }

            return Json (new { id = item.Id });
        }
Beispiel #25
0
        bool CreateUser(string username, string password, string email)
        {
            username = username.ToLower ();

            if (Model.User.Queryable.Count (x => x.UserName == username) > 0) {
                throw new Exception (Mictlanix.BE.Resources.Message_UserNameAlreadyExists);
            }

            var item = new User {
                UserName = username,
                Password = SecurityHelpers.SHA1 (password),
                Email = email.ToLower ()
            };

            using (var scope = new TransactionScope ()) {
                item.CreateAndFlush ();
            }

            return true;
        }
Beispiel #26
0
        bool ChangePassword(string username, string oldPassword, string newPassword)
        {
            User item = Model.User.Find (username);
            string pwd = SecurityHelpers.SHA1 (oldPassword);

            if (item == null || item.Password != pwd)
                return false;

            item.Password = SecurityHelpers.SHA1 (newPassword);

            using (var scope = new TransactionScope ()) {
                item.UpdateAndFlush ();
            }

            return true;
        }
        public ActionResult AddItems(int id, string value)
        {
            var entity = DeliveryOrder.Find (id);
            SalesOrder sales_order = null;
            int sales_order_id = 0;
            int count = 0;

            if (entity.IsCompleted || entity.IsCancelled) {
                Response.StatusCode = 400;
                return Content (Resources.ItemAlreadyCompletedOrCancelled);
            }

            if (int.TryParse (value, out sales_order_id)) {
                sales_order = SalesOrder.TryFind (sales_order_id);
            }

            if (sales_order == null) {
                Response.StatusCode = 400;
                return Content (Resources.SalesOrderNotFound);
            }

            using (var scope = new TransactionScope ()) {
                foreach (var x in sales_order.Details) {
                    var item = new DeliveryOrderDetail {
                        DeliveryOrder = entity,
                        Product = x.Product,
                        OrderDetail = x,
                        ProductCode = x.ProductCode,
                        ProductName = x.ProductName,
                        Quantity = x.Quantity
                    };

                    item.Create ();
                    count++;
                }
            }

            if (count == 0) {
                Response.StatusCode = 400;
                return Content (Resources.InvoiceableItemsNotFound);
            }

            return Json (new { id = id, value = string.Empty, itemsChanged = count });
        }
        public ActionResult SetShipTo(int id, int value)
        {
            var entity = DeliveryOrder.Find (id);
            var item = Address.TryFind (value);

            if (entity.IsCompleted || entity.IsCancelled) {
                Response.StatusCode = 400;
                return Content (Resources.ItemAlreadyCompletedOrCancelled);
            }

            if (item != null) {
                entity.ShipTo = item;
                entity.Updater = CurrentUser.Employee;
                entity.ModificationTime = DateTime.Now;

                using (var scope = new TransactionScope ()) {
                    entity.UpdateAndFlush ();
                }
            }

            return Json (new { id = id, value = entity.ShipTo.ToString () });
        }
        public ActionResult SetItemQuantity(int id, decimal value)
        {
            var entity = DeliveryOrderDetail.Find (id);

            if (entity.DeliveryOrder.IsCompleted || entity.DeliveryOrder.IsCancelled) {
                Response.StatusCode = 400;
                return Content (Resources.ItemAlreadyCompletedOrCancelled);
            }

            if (value > 0) {
                entity.Quantity = value;

                using (var scope = new TransactionScope ()) {
                    entity.UpdateAndFlush ();
                }
            }

            return Json (new {
                id = entity.Id,
                value = entity.FormattedValueFor (x => x.Quantity)
            });
        }
        public ActionResult SetItemProductName(int id, string value)
        {
            var entity = DeliveryOrderDetail.Find (id);
            string val = (value ?? string.Empty).Trim ();

            if (entity.DeliveryOrder.IsCompleted || entity.DeliveryOrder.IsCancelled) {
                Response.StatusCode = 400;
                return Content (Resources.ItemAlreadyCompletedOrCancelled);
            }

            if (val.Length == 0) {
                entity.ProductName = entity.Product.Name;
            } else {
                entity.ProductName = val;
            }

            using (var scope = new TransactionScope ()) {
                entity.UpdateAndFlush ();
            }

            return Json (new { id = entity.Id, value = entity.ProductName });
        }