Exemplo n.º 1
0
 /// <summary>
 /// Contstructor
 /// </summary>
 /// <param name="transaction"></param>
 public DataContextTransaction(DbContextTransaction transaction)
 {
     _transaction = transaction;
 }
Exemplo n.º 2
0
        public bool SaveQuanLy(QuanLy data, DMQuanLy dMQuanLy, int status)
        {
            #region chuẩn bị dữ liệu cho DMQLConnectQL
            //Khi insert Quan Lý thì Quản Lý sẽ thuộc một Danh mục quản lý được chọn trước đó.
            //Đảm bảo rằng khi thay đổi năm quyết toán của QuanLy thì dữ liệu quyết toán năm cũ không thay đổi.
            DMQLConnectQL dMQLConnectQL = new DMQLConnectQL
            {
                DMQuanLyID = dMQuanLy.DMQuanLyID,

                QLMa           = data.QLMa,
                QLTen          = data.QLTen,
                QLNamQT        = data.QLNamQT,
                QLNgayHopDong  = data.QLNgayHopDong,
                QLSoHopDong    = data.QLSoHopDong,
                QLSoLuongHD    = data.QLSoLuongHD,
                QLDoanhThu     = data.QLDoanhThu,
                QLVAT          = data.QLVAT,
                QLNgayKhoiCong = data.QLNgayKhoiCong,
                QLNgayKetThuc  = data.QLNgayKetThuc,
                QLHopDong      = data.QLHopDong,
                QLDuToan       = data.QLDuToan,
                QLQuyetToan    = data.QLQuyetToan,
                QLKLHoanThanh  = data.QLKLHoanThanh,
                QLBBNghiemThu  = data.QLBBNghiemThu,
                QLBBThanhLy    = data.QLBBThanhLy,
                QLHSChuan      = data.QLHSChuan,
                QLNhatKy       = data.QLNhatKy,
                QLYCBoSung     = data.QLYCBoSung,
                QLNo           = 1,
                QLStatus       = data.QLStatus,
                UserCreate     = UserInfo.UserID,
                CompanyID      = CommonInfo.CompanyInfo.CompanyID
            };
            #endregion chuẩn bị dữ liệu cho DMQLConnectQL

            using (DbContextTransaction transaction = Context.Database.BeginTransaction())
            {
                try
                {
                    long seq        = QuanLyDAO.GetQuanLySEQ();
                    long seqConnect = DMQLConnectQLDAO.GetDMQLConnectQLSEQ();
                    switch (data.Status)
                    {
                    // Add new
                    case ModifyMode.Insert:
                        seq++;
                        data.QLID = GenerateID.QuanLyID(seq);
                        this.QuanLyDAO.InsertQuanLy(data);
                        //after insert QuanLy was successfull then insert DMQuanLyConnectQuanLy
                        seqConnect++;
                        dMQLConnectQL.DMQLConnectQLID = GenerateID.DMQLConnectQLID(seqConnect);
                        dMQLConnectQL.QLID            = data.QLID;
                        this.DMQLConnectQLDAO.InsertDMQLConnectQL(dMQLConnectQL);
                        break;

                    // Update
                    case ModifyMode.Update:
                        this.QuanLyDAO.UpdateQuanLy(data, status);
                        break;

                    // Delete
                    case ModifyMode.Delete:
                        this.QuanLyDAO.DeleteQuanLy(data);
                        break;
                    }

                    transaction.Commit();
                    return(true);
                }
                catch (Exception e)
                {
                    transaction.Rollback();
                    Console.WriteLine("Update data fail.\r\n" + e.Message);
                    return(false);
                }
            }
        }
        public async Task <JsonResult> ProjectSettings(ProjectSettingsViewModel model)
        {
            if (model == null)
            {
                return(Json("Error"));
            }
            bool error = false;

            using (DbContextTransaction dbTran = db.Database.BeginTransaction())
            {
                try
                {
                    if (model.ProjectPriorities != null)
                    {
                        db.ProjectPriorityDetails.RemoveRange(db.ProjectPriorityDetails.Where(x => x.ProjectPriority.ProjectId == model.Id));
                        db.ProjectPriorities.RemoveRange(db.ProjectPriorities.Where(x => x.ProjectId == model.Id));

                        var projectPriorities = model.ProjectPriorities.Select(c => new ProjectPriority
                        {
                            ProjectId     = model.Id,
                            Field         = c.Field,
                            PriorityValue = c.PriorityValue,
                            CreationDate  = DateTime.Now,
                            LastUpdate    = DateTime.Now,
                        }).ToList();
                        var savedEntities = db.ProjectPriorities.AddRange(projectPriorities);

                        await db.SaveChangesAsync();

                        if (model.ProjectPriorityDetails != null)
                        {
                            db.ProjectPriorityDetails.AddRange(model.ProjectPriorityDetails.Select(c => new ProjectPriorityDetail
                            {
                                ProjectPriorityId  = savedEntities.Where(x => x.Field.Equals(c.Type)).FirstOrDefault().Id,
                                FieldValue         = c.FieldValue.Equals("Blank") ? string.Empty : c.FieldValue,
                                FieldPriorityValue = c.FieldPriorityValue,
                                CreationDate       = DateTime.Now,
                                LastUpdate         = DateTime.Now,
                            }).AsEnumerable());
                        }
                        await db.SaveChangesAsync();

                        dbTran.Commit();
                    }
                }
                catch (Exception ex)
                {
                    dbTran.Rollback();
                    error = true;
                }
            }

            if (error)
            {
                return(Json("Error"));
            }
            else
            {
                return(Json("Ok"));
            }
        }
Exemplo n.º 4
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="ids"></param>
        /// <param name="userID"></param>
        /// <param name="checkPermission"></param>
        /// <returns></returns>
        public CoreResult Delete(int[] ids, int?userID = null, bool checkPermission = false)
        {
            try
            {
                bool flag = false;
                if (userID == null && checkPermission)
                {
                    return(new CoreResult {
                        StatusCode = CoreStatusCode.Failed, Message = "\"UserID\" không được phép để trống."
                    });
                }
                else
                {
                    if (checkPermission)
                    {
                        var per = this.GetPermission(userID.Value, ActionType.Delete);
                        if (per.StatusCode == CoreStatusCode.OK)
                        {
                            ////action
                            flag = true;
                        }
                        else
                        {
                            return(per);
                        }
                    }
                    else
                    {
                        ////action
                        flag = true;
                    }
                }
                if (flag)
                {
                    CoreResult resultReturn = new CoreResult();
                    using (DbContextTransaction dbTransaction = this.context.Database.BeginTransaction())
                    {
                        foreach (int id in ids)
                        {
                            var dichvucls = this.GetByID(id);
                            if (dichvucls != null)
                            {
                                dichvucls.deleted = true;

                                this.context.Entry <DMDichVuCLSang>(dichvucls).State = EntityState.Modified;
                            }
                        }
                        try
                        {
                            this.context.SaveChanges();
                            dbTransaction.Commit();
                            resultReturn.StatusCode = CoreStatusCode.OK; resultReturn.Message = this.GetMessageByCoreStatusCode(CoreStatusCode.OK, ActionType.Delete);
                        }
                        catch (Exception ex)
                        {
                            dbTransaction.Rollback();
                            resultReturn.StatusCode = CoreStatusCode.Exception; resultReturn.Message = this.GetMessageByCoreStatusCode(CoreStatusCode.Exception, ActionType.Delete, ex);
                        }
                    }
                    if (resultReturn.StatusCode == CoreStatusCode.OK && this.GetUseCache())
                    {
                        this.RefreshCache();
                    }
                    return(resultReturn);
                }
                else
                {
                    return(new CoreResult {
                        StatusCode = CoreStatusCode.DontHavePermission, Message = this.GetMessageByCoreStatusCode(CoreStatusCode.DontHavePermission, ActionType.Delete)
                    });
                }
            }
            catch (Exception ex)
            {
                return(new CoreResult {
                    StatusCode = CoreStatusCode.Exception, Message = this.GetMessageByCoreStatusCode(CoreStatusCode.Exception, ActionType.Delete, ex)
                });
            }
        }
Exemplo n.º 5
0
        public IHttpActionResult PostInvoice([FromBody] InvoiceViewModel invoiceViewModel)
        {
            InvoiceTable Table = new InvoiceTable();

            using (DBEntities context = new DBEntities())
            {
                using (DbContextTransaction transaction = context.Database.BeginTransaction(System.Data.IsolationLevel.ReadCommitted))
                {
                    try
                    {
                        Table.Invoice_ID         = invoiceViewModel.Invoice_ID;
                        Table.CompanyId          = invoiceViewModel.CompanyId;
                        Table.UserId             = invoiceViewModel.UserId;
                        Table.ContactId          = invoiceViewModel.ContactId;
                        Table.RefNumber          = invoiceViewModel.RefNumber;
                        Table.InvoiceDate        = invoiceViewModel.InvoiceDate;
                        Table.InvoiceDueDate     = invoiceViewModel.InvoiceDueDate;
                        Table.SubTotal           = invoiceViewModel.SubTotal;
                        Table.DiscountAmount     = invoiceViewModel.DiscountAmount;
                        Table.TotalAmount        = invoiceViewModel.TotalAmount;
                        Table.CustomerNote       = invoiceViewModel.CustomerNote;
                        Table.TotalVat21         = invoiceViewModel.TotalVat21;
                        Table.TotalVat6          = invoiceViewModel.TotalVat6;
                        Table.Type               = StatusEnum.Goods.ToString();
                        Table.Status             = "accepted";
                        Table.InvoiceDescription = invoiceViewModel.InvoiceDescription;

                        if (Table.TotalVat6 != null)
                        {
                            double vat61 = Math.Round((double)Table.TotalVat6, 2, MidpointRounding.AwayFromZero);
                            Table.TotalVat6 = vat61;
                        }
                        if (Table.TotalVat21 != null)
                        {
                            double vat21 = Math.Round((double)Table.TotalVat21, 2, MidpointRounding.AwayFromZero);
                            Table.TotalVat21 = vat21;
                        }

                        Table = context.InvoiceTables.Add(Table);
                        context.SaveChanges();

                        if (invoiceViewModel.InvoiceDetailsTable != null)
                        {
                            foreach (InvoiceDetailsTable InvoiceDetailsList in invoiceViewModel.InvoiceDetailsTable)
                            {
                                InvoiceDetailsTable InvoiceDetails = new InvoiceDetailsTable();
                                InvoiceDetails.ItemId      = Convert.ToInt32(InvoiceDetailsList.ItemId);
                                InvoiceDetails.InvoiceId   = Table.InvoiceID;
                                InvoiceDetails.Description = InvoiceDetailsList.Description;
                                InvoiceDetails.Quantity    = InvoiceDetailsList.Quantity;
                                InvoiceDetails.Rate        = Convert.ToDouble(InvoiceDetailsList.Rate);
                                InvoiceDetails.Total       = Convert.ToDouble(InvoiceDetailsList.Total);
                                InvoiceDetails.ServiceDate = InvoiceDetailsList.ServiceDate;
                                InvoiceDetails.RowSubTotal = InvoiceDetailsList.RowSubTotal;
                                InvoiceDetails.Vat         = Convert.ToDouble(InvoiceDetailsList.Vat);
                                InvoiceDetails.Type        = InvoiceDetailsList.Type;

                                if (InvoiceDetails.InvoiceDetailId == 0)
                                {
                                    InvoiceDetails = context.InvoiceDetailsTables.Add(InvoiceDetails);
                                    context.SaveChanges();
                                }
                            }
                        }

                        AccountTransictionTable Account = new AccountTransictionTable();
                        Account.TransictionDate       = DateTime.Now;
                        Account.TransictionNumber     = base64Guid;
                        Account.TransictionType       = "Invoice";
                        Account.TransictionRefrenceId = Table.InvoiceID.ToString();
                        Account.CreationTime          = DateTime.Now.TimeOfDay;
                        Account.AddedBy       = 1;
                        Account.FK_CompanyId  = invoiceViewModel.CompanyId;
                        Account.FKPaymentTerm = 1;

                        //Cash Account Transaction
                        int CashtAccountId = AccountIdByName("Cash on hand", (int)invoiceViewModel.CompanyId);

                        if (CashtAccountId != 0)
                        {
                            Account.Dr           = invoiceViewModel.TotalAmount;
                            Account.Cr           = 0.00;
                            Account.FK_AccountID = CashtAccountId;
                            context.AccountTransictionTables.Add(Account);
                            context.SaveChanges();
                        }
                        // Sale Account Transaction
                        int SaleAccount = AccountIdByName("Seles", (int)invoiceViewModel.CompanyId);
                        if (SaleAccount != 0)
                        {
                            Account.Cr           = invoiceViewModel.SubTotal;
                            Account.Dr           = 0.00;
                            Account.FK_AccountID = SaleAccount;
                            context.AccountTransictionTables.Add(Account);
                            context.SaveChanges();
                        }
                        // vat Out Put Trnsaction
                        int VatAccountId = AccountIdByName("VAT Payable", (int)invoiceViewModel.CompanyId);
                        if (VatAccountId != 0)
                        {
                            Account.Cr           = invoiceViewModel.TotalVat6 + invoiceViewModel.TotalVat21;
                            Account.Dr           = 0.00;
                            Account.FK_AccountID = VatAccountId;
                            context.AccountTransictionTables.Add(Account);
                            int Id = context.SaveChanges();
                        }
                        InvoiceModel inc = new InvoiceModel();
                        inc.InvoiceID = Table.InvoiceID;
                        transaction.Commit();
                        return(Ok(inc));
                    }
                    catch (Exception)
                    {
                        transaction.Rollback();
                        return(BadRequest());
                    }
                }
            }
        }
Exemplo n.º 6
0
        public Mensaje InsertarDisgregacionValorDeclarado(string json, int IdValorDeclarado, string ListaArchivos, string ListaArchivosEliminados)
        {
            Mensaje mensaje = new Mensaje();

            try
            {
                using (DbContextTransaction Transaccion = context.Database.BeginTransaction())
                {
                    try
                    {
                        JavaScriptSerializer serializer = new JavaScriptSerializer();

                        dynamic jsonObject = serializer.Deserialize <dynamic>(json);
                        foreach (var registroList in jsonObject)
                        {
                            int     IdValorDeclaradoDetalle = int.Parse(registroList["IdValorDeclaradoDetalle"]);
                            short   IdRamoPoliza            = short.Parse(registroList["IdRamoPoliza"]);
                            short   IdTipoPoliza            = short.Parse(registroList["IdTipoPoliza"]);
                            decimal?ImporteValorDeclarado   = registroList["ImporteValorDeclarado"] != null?Decimal.Parse(registroList["ImporteValorDeclarado"]) : null;

                            short?IdUnidadMedida = registroList["IdUnidadMedida"] != null?short.Parse(registroList["IdUnidadMedida"]) : null;

                            decimal?Cantidad = registroList["Cantidad"] != null?Decimal.Parse(registroList["Cantidad"]) : null;

                            short IdMoneda = short.Parse(registroList["IdMoneda"]);

                            context.SP_I_ValorDeclaradoDetalleDisgregado(
                                IdValorDeclaradoDetalle,
                                IdRamoPoliza,
                                IdTipoPoliza,
                                IdUnidadMedida,
                                Cantidad,
                                IdMoneda,
                                ImporteValorDeclarado
                                );
                        }
                        ActualizacionArchivosValorDeclarado(IdValorDeclarado, ListaArchivos, ListaArchivosEliminados);
                        mensaje = valorDeclaradoBL.ActualizarEstadoValorDeclarado(IdValorDeclarado, "DISGREG");
                        if (!mensaje.esError)
                        {
                            context.SaveChanges();
                            Transaccion.Commit();
                            mensaje.mensaje = "La operación se realizó correctamente";
                            mensaje.esError = false;
                        }
                    }
                    catch (Exception ex)
                    {
                        Transaccion.Rollback();
                        throw ex;
                    }
                }
            }
            catch (Exception)
            {
                mensaje.mensaje = "Ocurrió un error al realizar la disgregación";
                mensaje.esError = true;
            }

            return(mensaje);
        }
Exemplo n.º 7
0
 public virtual void BeginTran()
 {
     _tranContext = DbContext.Database.BeginTransaction();
 }
Exemplo n.º 8
0
        public HttpResponseMessage Register()
        {
            DbContextTransaction transaction = entities.Database.BeginTransaction();

            string imageName  = null;
            string imageName1 = null;
            string imageName2 = null;

            var httpRequest = HttpContext.Current.Request;

            //Upload Image
            try
            {
                var postedFile  = httpRequest.Files["Image"];
                var postedFile1 = httpRequest.Files["Pan"];
                var postedFile2 = httpRequest.Files["TraderLicense"];

                //Create custom filename

                imageName = new String(Path.GetFileNameWithoutExtension(postedFile.FileName).Take(10).ToArray()).Replace(" ", "-");
                imageName = imageName + DateTime.Now.ToString("yymmssfff") + Path.GetExtension(postedFile.FileName);
                var filePath = HttpContext.Current.Server.MapPath("~/Image/" + imageName);
                postedFile.SaveAs(filePath);

                imageName1 = new String(Path.GetFileNameWithoutExtension(postedFile1.FileName).Take(10).ToArray()).Replace(" ", "-");
                imageName1 = imageName1 + DateTime.Now.ToString("yymmssfff") + Path.GetExtension(postedFile1.FileName);
                var filePath1 = HttpContext.Current.Server.MapPath("~/Image/" + imageName1);
                postedFile1.SaveAs(filePath1);

                imageName2 = new String(Path.GetFileNameWithoutExtension(postedFile2.FileName).Take(10).ToArray()).Replace(" ", "-");
                imageName2 = imageName2 + DateTime.Now.ToString("yymmssfff") + Path.GetExtension(postedFile2.FileName);
                var filePath2 = HttpContext.Current.Server.MapPath("~/Image/" + imageName2);
                postedFile2.SaveAs(filePath2);



                tblBidder br = new tblBidder();

                //Save to db
                using (dbFarmerScheme3Entities db = new dbFarmerScheme3Entities())
                {
                    string email = httpRequest["Email"];
                    var    e     = db.tblBidders.Where(x => x.bEmailId == email).FirstOrDefault();

                    if (e == null)
                    {
                        string acc = httpRequest["AccountNo"];
                        var    a   = db.tblBidders.Where(x => x.bAccountNo == acc).FirstOrDefault();
                        if (a == null)
                        {
                            try
                            {
                                br.bAadhar = filePath;

                                br.bUserName  = httpRequest["Username"];
                                br.bContactNo = httpRequest["Contact"];
                                br.bEmailId   = httpRequest["Email"];
                                br.bAddress   = httpRequest["Address"];
                                br.bCity      = httpRequest["City"];
                                br.bState     = httpRequest["State"];
                                br.bPincode   = httpRequest["Pincode"];
                                br.bAccountNo = httpRequest["AccountNo"];
                                br.bIFSCcode  = httpRequest["ifsccode"];

                                br.bPan           = filePath1;
                                br.bTraderLicense = filePath2;
                                br.bPassword      = httpRequest["Password"];

                                br.StatusOfBidderDocx = "pending";

                                entities.tblBidders.Add(br);
                                entities.SaveChanges();

                                transaction.Commit();
                            }
                            catch (Exception ex)
                            {
                                transaction.Rollback();
                                return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex.Message));
                            }
                        }
                        else
                        {
                            return(Request.CreateErrorResponse(HttpStatusCode.NotFound, "Account No already exist"));
                        }
                    }
                    else
                    {
                        return(Request.CreateErrorResponse(HttpStatusCode.NotFound, "Email already exist"));
                    }
                }
            }
            catch (Exception)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.NotAcceptable, "File size should be less than 2MB"));
            }

            return(Request.CreateResponse(HttpStatusCode.Created, "Successfully Registered"));
        }
Exemplo n.º 9
0
 public OfferRepository(ContextModel context, DbContextTransaction transaction)
     : base(context, transaction)
 {
 }
Exemplo n.º 10
0
        static void learnTransaction(Customer dataCustomer, Product dataProduct)
        {
            YTUEFEntities context = new YTUEFEntities();

            #region Transaction ile kullanımı
            using (DbContextTransaction trns = context.Database.BeginTransaction())
            {
                try
                {
                    context.CustomerProductLists.Add(new CustomerProductList()
                    {
                        Amount     = 1,
                        ListPrice  = dataProduct.ListPrice,
                        ProductId  = dataProduct.ProductID,
                        CustomerId = dataCustomer.CustomerID,
                        CreateDate = DateTime.Now
                    });
                    context.SaveChanges(); // SQL INSERT

                    //throw new Exception();

                    context.CustomerHistories.Add(new CustomerHistory()
                    {
                        productID  = dataProduct.ProductID,
                        amount     = 1,
                        stateCode  = 100,
                        createDate = DateTime.Now
                    });

                    context.SaveChanges();

                    trns.Commit(); // Onaylamak tüm işlemleri onaylıyorsunuz...
                }
                catch (Exception ex)
                {
                    trns.Rollback(); // Geri çağırma işlemi...
                }
            }
            #endregion

            #region Transaction olmadan kullanım

            context.CustomerProductLists.Add(new CustomerProductList()
            {
                Amount     = 1,
                ListPrice  = dataProduct.ListPrice,
                ProductId  = dataProduct.ProductID,
                CustomerId = dataCustomer.CustomerID,
                CreateDate = DateTime.Now
            });
            context.SaveChanges(); // SQL INSERT

            context.CustomerHistories.Add(new CustomerHistory()
            {
                productID  = dataProduct.ProductID,
                amount     = 1,
                stateCode  = 100,
                createDate = DateTime.Now
            });

            context.SaveChanges();
            #endregion
        }
Exemplo n.º 11
0
        /// <summary>
        /// Retorna TbContaCorrente_tbLoginAdquirenteEmpresa/TbContaCorrente_tbLoginAdquirenteEmpresa
        /// </summary>
        /// <returns></returns>
        public static Retorno Get(string token, int colecao = 0, int campo = 0, int orderBy = 0, int pageSize = 0, int pageNumber = 0, Dictionary <string, string> queryString = null, painel_taxservices_dbContext _dbContext = null)
        {
            painel_taxservices_dbContext _db;

            if (_dbContext == null)
            {
                _db = new painel_taxservices_dbContext();
            }
            else
            {
                _db = _dbContext;
            }
            DbContextTransaction transaction = _db.Database.BeginTransaction(IsolationLevel.ReadUncommitted);

            try
            {
                //DECLARAÇÕES
                List <dynamic> CollectionTbContaCorrente_tbLoginAdquirenteEmpresa = new List <dynamic>();
                Retorno        retorno = new Retorno();

                // Implementar o filtro por Grupo apartir do TOKEN do Usuário
                string outValue = null;
                Int32  IdGrupo  = 0;
                IdGrupo = Permissoes.GetIdGrupo(token, _db);
                if (IdGrupo != 0)
                {
                    if (queryString.TryGetValue("" + (int)CAMPOS.ID_GRUPO, out outValue))
                    {
                        queryString["" + (int)CAMPOS.ID_GRUPO] = IdGrupo.ToString();
                    }
                    else
                    {
                        queryString.Add("" + (int)CAMPOS.ID_GRUPO, IdGrupo.ToString());
                    }
                }
                string CnpjEmpresa = Permissoes.GetCNPJEmpresa(token, _db);
                if (!CnpjEmpresa.Equals(""))
                {
                    if (queryString.TryGetValue("" + (int)CAMPOS.NU_CNPJ, out outValue))
                    {
                        queryString["" + (int)CAMPOS.NU_CNPJ] = CnpjEmpresa;
                    }
                    else
                    {
                        queryString.Add("" + (int)CAMPOS.NU_CNPJ, CnpjEmpresa);
                    }
                }

                // GET QUERY
                var query = getQuery(_db, colecao, campo, orderBy, pageSize, pageNumber, queryString);

                // TOTAL DE REGISTROS
                retorno.TotalDeRegistros = query.Count();


                if (colecao != 5)
                {
                    // PAGINAÇÃO
                    int skipRows = (pageNumber - 1) * pageSize;
                    if (retorno.TotalDeRegistros > pageSize && pageNumber > 0 && pageSize > 0)
                    {
                        query = query.Skip(skipRows).Take(pageSize);
                    }
                    else
                    {
                        pageNumber = 1;
                    }

                    retorno.PaginaAtual    = pageNumber;
                    retorno.ItensPorPagina = pageSize;
                }



                // COLEÇÃO DE RETORNO
                if (colecao == 1)
                {
                    CollectionTbContaCorrente_tbLoginAdquirenteEmpresa = query.Select(e => new
                    {
                        cdContaCorrente          = e.cdContaCorrente,
                        cdLoginAdquirenteEmpresa = e.cdLoginAdquirenteEmpresa,
                        dtInicio = e.dtInicio,
                        dtFim    = e.dtFim,
                    }).ToList <dynamic>();
                }
                else if (colecao == 0)
                {
                    CollectionTbContaCorrente_tbLoginAdquirenteEmpresa = query.Select(e => new
                    {
                        cdContaCorrente          = e.cdContaCorrente,
                        cdLoginAdquirenteEmpresa = e.cdLoginAdquirenteEmpresa,
                        dtInicio = e.dtInicio,
                        dtFim    = e.dtFim,
                    }).ToList <dynamic>();
                }
                else if (colecao == 2) // [WEB] Vigência da Conta Corrente
                {
                    CollectionTbContaCorrente_tbLoginAdquirenteEmpresa = query.Select(e => new
                    {
                        dtInicio = e.dtInicio,
                        dtFim    = e.dtFim,
                        cdLoginAdquirenteEmpresa = e.tbLoginAdquirenteEmpresa.cdLoginAdquirenteEmpresa,
                        adquirente = new
                        {
                            cdAdquirente = e.tbLoginAdquirenteEmpresa.tbAdquirente.cdAdquirente,
                            nmAdquirente = e.tbLoginAdquirenteEmpresa.tbAdquirente.nmAdquirente,
                            dsAdquirente = e.tbLoginAdquirenteEmpresa.tbAdquirente.dsAdquirente,
                            stAdquirente = e.tbLoginAdquirenteEmpresa.tbAdquirente.stAdquirente,
                        },
                        empresa = new
                        {
                            nu_cnpj     = e.tbLoginAdquirenteEmpresa.empresa.nu_cnpj,
                            ds_fantasia = e.tbLoginAdquirenteEmpresa.empresa.ds_fantasia,
                            filial      = e.tbLoginAdquirenteEmpresa.empresa.filial
                        },
                        stLoginAdquirente = e.tbLoginAdquirenteEmpresa.stLoginAdquirente,
                        //stLoginAdquirenteEmpresa = l.tbLoginAdquirenteEmpresa.stLoginAdquirenteEmpresa // controle de bruno
                    }).ToList <dynamic>();
                }
                else if (colecao == 3) // [WEB] Filiais
                {
                    CollectionTbContaCorrente_tbLoginAdquirenteEmpresa = query
                                                                         .Where(e => e.tbLoginAdquirenteEmpresa.empresa.fl_ativo == 1)
                                                                         .GroupBy(e => e.tbLoginAdquirenteEmpresa.empresa.nu_cnpj)
                                                                         .Select(e => new
                    {
                        nu_cnpj     = e.Key,
                        ds_fantasia = e.Select(f => f.tbLoginAdquirenteEmpresa.empresa.ds_fantasia).FirstOrDefault(),
                        filial      = e.Select(f => f.tbLoginAdquirenteEmpresa.empresa.filial).FirstOrDefault(),
                        adquirentes = e.Select(f => new
                        {
                            cdAdquirente = f.tbLoginAdquirenteEmpresa.tbAdquirente.cdAdquirente,
                            nmAdquirente = f.tbLoginAdquirenteEmpresa.tbAdquirente.nmAdquirente,
                            stAdquirente = f.tbLoginAdquirenteEmpresa.tbAdquirente.stAdquirente,
                        }).OrderBy(f => f.nmAdquirente).ToList <dynamic>(),
                    }).OrderBy(e => e.ds_fantasia).ThenBy(e => e.filial).ToList <dynamic>();
                }
                else if (colecao == 4) // [WEB] Adquirentes
                {
                    CollectionTbContaCorrente_tbLoginAdquirenteEmpresa = query
                                                                         .Where(e => e.tbLoginAdquirenteEmpresa.tbAdquirente.stAdquirente == 1)
                                                                         .GroupBy(e => e.tbLoginAdquirenteEmpresa.tbAdquirente.cdAdquirente)
                                                                         .Select(e => new
                    {
                        cdAdquirente = e.Key,
                        nmAdquirente = e.Select(f => f.tbLoginAdquirenteEmpresa.tbAdquirente.nmAdquirente).FirstOrDefault(),
                        stAdquirente = e.Select(f => f.tbLoginAdquirenteEmpresa.tbAdquirente.stAdquirente).FirstOrDefault(),
                    }).OrderBy(e => e.nmAdquirente).ToList <dynamic>();
                }
                else if (colecao == 5) // [WEB] Relação adquirente-filial por conta
                {
                    List <dynamic> tbLoginAdquirenteEmpresas = query
                                                               .Where(e => e.tbLoginAdquirenteEmpresa.empresa.fl_ativo == 1)
                                                               .Select(e => new
                    {
                        tbContaCorrente = new
                        {
                            e.tbContaCorrente.cdContaCorrente,
                            //e.tbContaCorrente.cdBanco,
                            banco = new { Codigo = e.tbContaCorrente.cdBanco, NomeExtenso = "" },
                            e.tbContaCorrente.nrAgencia,
                            e.tbContaCorrente.nrConta
                        },
                        empresa = new
                        {
                            e.tbLoginAdquirenteEmpresa.empresa.nu_cnpj,
                            e.tbLoginAdquirenteEmpresa.empresa.ds_fantasia,
                            e.tbLoginAdquirenteEmpresa.empresa.filial
                        },
                        tbAdquirente = new
                        {
                            e.tbLoginAdquirenteEmpresa.tbAdquirente.cdAdquirente,
                            e.tbLoginAdquirenteEmpresa.tbAdquirente.nmAdquirente
                        },
                        cdEstabelecimento         = e.tbLoginAdquirenteEmpresa.cdEstabelecimento,
                        cdEstabelecimentoConsulta = e.tbLoginAdquirenteEmpresa.cdEstabelecimentoConsulta,
                        status   = e.tbLoginAdquirenteEmpresa.stLoginAdquirente,
                        dtInicio = e.dtInicio,
                        dtFim    = e.dtFim
                    })
                                                               .OrderBy(e => e.empresa.nu_cnpj)
                                                               .ThenBy(e => e.tbAdquirente.nmAdquirente)
                                                               .ThenBy(e => e.tbContaCorrente.banco.Codigo)
                                                               .ThenBy(e => e.tbContaCorrente.nrAgencia)
                                                               .ThenBy(e => e.tbContaCorrente.nrConta)
                                                               .ToList <dynamic>();

                    // PAGINAÇÃO
                    int skipRows = (pageNumber - 1) * pageSize;
                    if (tbLoginAdquirenteEmpresas.Count > pageSize && pageNumber > 0 && pageSize > 0)
                    {
                        tbLoginAdquirenteEmpresas = tbLoginAdquirenteEmpresas.Skip(skipRows).Take(pageSize).ToList <dynamic>();
                    }
                    else
                    {
                        pageNumber = 1;
                    }

                    retorno.PaginaAtual    = pageNumber;
                    retorno.ItensPorPagina = pageSize;

                    // Após transformar em lista (isto é, trazer para a memória), atualiza o valor do NomeExtenso associado ao banco
                    foreach (var tbLoginAdquirenteEmpresa in tbLoginAdquirenteEmpresas)
                    {
                        CollectionTbContaCorrente_tbLoginAdquirenteEmpresa.Add(new
                        {
                            tbContaCorrente = new {
                                cdContaCorrente = tbLoginAdquirenteEmpresa.tbContaCorrente.cdContaCorrente,
                                //e.tbContaCorrente.cdBanco,
                                banco     = new { Codigo = tbLoginAdquirenteEmpresa.tbContaCorrente.banco.Codigo, NomeExtenso = GatewayBancos.Get(tbLoginAdquirenteEmpresa.tbContaCorrente.banco.Codigo) },
                                nrAgencia = tbLoginAdquirenteEmpresa.tbContaCorrente.nrAgencia,
                                nrConta   = tbLoginAdquirenteEmpresa.tbContaCorrente.nrConta,
                            },
                            empresa                   = tbLoginAdquirenteEmpresa.empresa,
                            tbAdquirente              = tbLoginAdquirenteEmpresa.tbAdquirente,
                            cdEstabelecimento         = tbLoginAdquirenteEmpresa.cdEstabelecimento,
                            cdEstabelecimentoConsulta = tbLoginAdquirenteEmpresa.cdEstabelecimentoConsulta,
                            status   = tbLoginAdquirenteEmpresa.status,
                            dtInicio = tbLoginAdquirenteEmpresa.dtInicio,
                            dtFim    = tbLoginAdquirenteEmpresa.dtFim
                        });
                    }
                }

                transaction.Commit();

                retorno.Registros = CollectionTbContaCorrente_tbLoginAdquirenteEmpresa;

                return(retorno);
            }
            catch (Exception e)
            {
                transaction.Rollback();
                if (e is DbEntityValidationException)
                {
                    string erro = MensagemErro.getMensagemErro((DbEntityValidationException)e);
                    throw new Exception(erro.Equals("") ? "Falha ao listar adquirente empresa" : erro);
                }
                throw new Exception(e.InnerException == null ? e.Message : e.InnerException.InnerException == null ? e.InnerException.Message : e.InnerException.InnerException.Message);
            }
            finally
            {
                if (_dbContext == null)
                {
                    // Fecha conexão
                    _db.Database.Connection.Close();
                    _db.Dispose();
                }
            }
        }
 protected R GetDefaultRepository(DbContext context,
                                  DbContextTransaction transaction)
 {
     return((R)Activator.CreateInstance(typeof(R), context, transaction));
 }
 /// <summary>
 /// Devolve uma instância do repositório principal, utilizado pelo serviço
 /// </summary>
 /// <param name="context">Contexto do Entity Framework</param>
 /// <param name="transaction">Transação corrente do contexto</param>
 private void LoadDaoToSimpleOperation(DbContext context, DbContextTransaction transaction)
 {
     genericDaoEfContext = GetDefaultRepository(context, transaction);
 }
Exemplo n.º 14
0
        public string InsertHolding(HOLDING holding, int numberOfCN, string recommendID, ref string composite)
        {
            if (String.IsNullOrEmpty(holding.CopyNumber))
            {
                return("Hãy tạo đăng ký cá biệt");
            }
            ITEM item = db.ITEMs.FirstOrDefault(i => i.ID == holding.ItemID);

            if (item == null)
            {
                return("Không tồn tại bản ghi");
            }

            List <HOLDING> holdings = new List <HOLDING>();

            //   ITEM item = db.ITEMs.Where(i => i.ID == holding.ItemID).FirstOrDefault();
            holding.Volume        = "";
            holding.UseCount      = 0;
            holding.InUsed        = false;
            holding.InCirculation = false;
            holding.ILLID         = 0;
            holding.DateLastUsed  = DateTime.Now;
            holding.CallNumber    = db.ITEMs.Where(i => i.ID == holding.ItemID).FirstOrDefault().CallNumber;
            holding.Acquired      = false;
            holding.Note          = "";
            holding.POID          = 0;
            if (holding.Price == null)
            {
                holding.Price = 0;
            }

            // check start holding tồn tại chưa

            if (!IsExistHolding(holding.CopyNumber, holding.LocationID, -1))
            {
                string symbol    = holding.CopyNumber.Substring(0, holding.CopyNumber.Length - 6);
                string strNumber = holding.CopyNumber.Substring(symbol.Length, 6);
                int    number    = Convert.ToInt32(strNumber);

                using (DbContextTransaction transaction = db.Database.BeginTransaction())
                {
                    for (int i = 0; i < numberOfCN; i++)
                    {
                        // tạo list ĐKCB
                        int    length     = 6 - number.ToString().Length;
                        string stringZero = "";
                        for (int j = 0; j < length; j++)
                        {
                            stringZero = stringZero + "0";
                        }
                        string copyNumber = symbol + stringZero + number;

                        if (IsExistHolding(copyNumber, holding.LocationID, -1))
                        {
                            transaction.Rollback();
                            return("Hãy sinh lại giá trị");
                        }
                        ;

                        number++;
                        // procedure đã + 1 giá trị MaxNumber trong HOLDING_LOCATION
                        db.SP_HOLDING_INS(
                            holding.ItemID,
                            holding.LocationID,
                            holding.LibID,
                            holding.UseCount,
                            holding.Volume,
                            // ngày bổ sung
                            holding.AcquiredDate.ToString(),
                            copyNumber,
                            holding.InUsed == true ? 1 : 0,
                            holding.InCirculation == true ? 1 : 0,
                            holding.ILLID,
                            holding.Price,
                            // giá sách
                            holding.Shelf,
                            holding.POID,
                            //ngày sử dụng cuối
                            holding.DateLastUsed.ToString(),
                            holding.CallNumber,
                            holding.Acquired == true ? 1 : 0,
                            holding.Note,
                            holding.LoanTypeID,
                            holding.AcquiredSourceID,
                            holding.Currency,
                            holding.Rate,
                            // số chứng từ
                            holding.RecordNumber,
                            // ngày chứng từ
                            holding.ReceiptedDate.ToString()

                            );
                        holding.CopyNumber = copyNumber;
                        holdings.Add(holding);
                    }
                    transaction.Commit();
                    if (!string.IsNullOrEmpty(recommendID))
                    {
                        InsertRecommend(recommendID, holding.ItemID);
                    }
                    composite = GenerateCompositeHoldings(holding.ItemID);
                }
            }
            else
            {
                return("ĐKCB đã tồn tại hãy sinh giá trị mới");
            }
            return("");
        }
        public object Update(List <FileModel> files, function item, Function_Extend itemExtend)
        {
            Message msg = new Message {
                Error = false
            };

            using (DbContextTransaction dbTran = _dbContext.Database.BeginTransaction())
            {
                try
                {
                    if (getNotExistsFunctionWhenInsert(item.Function1))
                    {
                        _dbContext.Entry(item).State = EntityState.Modified;
                        item.ModifiedBy   = ((account)Session["informationOfAccount"]).Account1;
                        item.ModifiedDate = DateTime.Now;
                        if (item.functionCategories != null)
                        {
                            item.functionCategoriesTitle = _dbContext.functionCategories.First(x => x.functionCategories == item.functionCategories).functionCategoriesTitle;
                        }
                        _dbContext.Entry(item).Property(x => x.History).IsModified     = false;
                        _dbContext.Entry(item).Property(x => x.CreatedBy).IsModified   = false;
                        _dbContext.Entry(item).Property(x => x.CreatedDate).IsModified = false;
                        _dbContext.SaveChanges();
                        msg.Title = Function_Message_InsertSuccess;
                        var RemoveFunctionBefore = _dbContext.childOfFunctions.Where(x => x.RemoveFunction.Contains("#" + itemExtend.Function1 + "#")).ToList();
                        if (RemoveFunctionBefore != null)
                        {
                            foreach (var itemChildRemove in RemoveFunctionBefore)
                            {
                                itemChildRemove.RemoveFunction = itemChildRemove.RemoveFunction.Replace("#" + itemExtend.Function1 + "#", "");
                                _dbContext.Entry(itemChildRemove).Property(x => x.Title).IsModified            = false;
                                _dbContext.Entry(itemChildRemove).Property(x => x.ChildOfFunction1).IsModified = false;
                                _dbContext.Entry(itemChildRemove).Property(x => x.Order).IsModified            = false;
                                _dbContext.SaveChanges();
                            }
                        }
                        var ChildFunction = _dbContext.childOfFunctions.ToList();
                        foreach (var itemChild in ChildFunction)
                        {
                            if (itemExtend.ArrayFunction != null)
                            {
                                if (itemExtend.ArrayFunction.Find(x => x == itemChild.ChildOfFunction1) == null)
                                {
                                    itemChild.RemoveFunction += "#" + itemExtend.Function1 + "#";
                                    _dbContext.Entry(itemChild).Property(x => x.ID).IsModified    = false;
                                    _dbContext.Entry(itemChild).Property(x => x.Title).IsModified = false;
                                    _dbContext.Entry(itemChild).Property(x => x.Order).IsModified = false;
                                    _dbContext.SaveChanges();
                                }
                            }
                        }
                        dbTran.Commit();
                    }
                    else
                    {
                        msg.Title = Function_Message_InsertErrror;
                        msg.Error = true;
                        dbTran.Rollback();
                    }
                }
                catch (Exception ex)
                {
                    msg.Title = Function_Message_InsertErrror;
                    msg.Error = true;
                    msg.Data  = ex.ToString();
                    dbTran.Rollback();
                }
            }
            return(Json(msg, JsonRequestBehavior.AllowGet));
        }
Exemplo n.º 16
0
        /// <summary>
        /// SaveOrUpdate given Booking
        /// </summary>
        /// <param name="booking"></param>
        /// <returns>The saved booking, with its new id, if a new booking (which was never saved) is passed</returns>
        public async static Task <Booking> Save(Booking booking)
        {
            using (ResotelContext ctx = new ResotelContext())
            {
                Booking savedBooking = null;

                List <Room> rooms = await _getRoomRequest(ctx, true)
                                    .ToListAsync();

                List <Option> options = await _getOptionRequest(ctx)
                                        .ToListAsync();

                Client client = await _getClientRequest(ctx).FirstOrDefaultAsync(
                    cl => cl.Id == booking.Client.Id
                    );

                _assignCtxRooms(booking, rooms);
                _assignCtxOptions(booking, options);

                if (client != null)
                {
                    booking.Client = client;
                }

                if (booking.Id == 0)
                {
                    ctx.Entry(booking).State = EntityState.Added;
                }
                else
                {
                    Booking trackedBooking = await ctx.Bookings.FirstOrDefaultAsync(b => b.Id == booking.Id);

                    _updateTrackedBooking(trackedBooking, booking, ctx);
                    await _updateOptionChoices(trackedBooking.OptionChoices, booking.OptionChoices, ctx);
                    await _updateBookingRooms(trackedBooking, booking.Rooms, ctx);
                    await _updateRoomPacks(trackedBooking, trackedBooking.RoomPacks, booking.RoomPacks, ctx);

                    _updateTrackedBookingState(trackedBooking, booking.State, ctx);

                    DateRange trackedBookingDates = await _getTrackedBookingDates(booking.Dates, ctx);

                    trackedBooking.Dates = trackedBookingDates;
                }



                List <Room> unavailableRooms = new List <Room>();

                using (DbContextTransaction transaction = ctx.Database.BeginTransaction())
                {
                    try
                    {
                        await _fillUnavailableRooms(booking, ctx, unavailableRooms);

                        if (unavailableRooms.Count == 0)
                        {
                            savedBooking = await _saveBooking(booking, ctx, transaction);
                        }
                        else
                        {
                            List <Room> unavailableReplacementRooms = await _replaceRooms(booking, ctx, unavailableRooms);

                            if (unavailableReplacementRooms.Count > 0)
                            {
                                HashSet <RoomKind> unreplaceableRoomKinds = new HashSet <RoomKind>(unavailableReplacementRooms.ConvertAll(room => room.Kind));
                                transaction.Rollback();
                                throw new InvalidOperationException(
                                          $"Impossible de sauvegarder la réservation : nous n'avons plus assez de chambres des types {string.Join(",", unreplaceableRoomKinds)}");
                            }
                            else
                            {
                                savedBooking = await _saveBooking(booking, ctx, transaction);
                            }
                        }

                        return(savedBooking);
                    }
                    catch (Exception)
                    {
                        transaction.Rollback();
                        throw;
                    }
                }
            }
        }
Exemplo n.º 17
0
        public Mensaje ActualizarDisgregacionValorDeclarado(string jsonListaVista, int IdValorDeclarado,
                                                            string jsonListaEliminados, string jsonListaArchivos,
                                                            string jsonListaArchivosEliminados)
        {
            Mensaje mensaje = new Mensaje();

            try
            {
                using (DbContextTransaction Transaccion = context.Database.BeginTransaction())
                {
                    try
                    {
                        JavaScriptSerializer serializer = new JavaScriptSerializer();

                        dynamic jsonObject = serializer.Deserialize <dynamic>(jsonListaVista);
                        foreach (var registroList in jsonObject)
                        {
                            int IdValorDeclaradoDetalleDisgregado = registroList["IdValorDeclaradoDetalleDisgregado"];
                            if (IdValorDeclaradoDetalleDisgregado <= 0)
                            {
                                int     IdValorDeclaradoDetalle = int.Parse(registroList["IdValorDeclaradoDetalle"]);
                                short   IdRamoPoliza            = short.Parse(registroList["IdRamoPoliza"]);
                                short   IdTipoPoliza            = short.Parse(registroList["IdTipoPoliza"]);
                                decimal?ImporteValorDeclarado   = registroList["ImporteValorDeclarado"] != null?Decimal.Parse(registroList["ImporteValorDeclarado"]) : null;

                                short?IdUnidadMedida = registroList["IdUnidadMedida"] != null?short.Parse(registroList["IdUnidadMedida"]) : null;

                                decimal?Cantidad = registroList["Cantidad"] != null?Decimal.Parse(registroList["Cantidad"]) : null;

                                short IdMoneda = short.Parse(registroList["IdMoneda"]);

                                context.SP_I_ValorDeclaradoDetalleDisgregado(
                                    IdValorDeclaradoDetalle,
                                    IdRamoPoliza,
                                    IdTipoPoliza,
                                    IdUnidadMedida,
                                    Cantidad,
                                    IdMoneda,
                                    ImporteValorDeclarado
                                    );
                            }
                        }

                        dynamic jsonObjectEliminar = serializer.Deserialize <dynamic>(jsonListaEliminados);
                        foreach (var registroList in jsonObjectEliminar)
                        {
                            context.SP_D_ValorDeclaradoDetalleDisgregado(registroList["IdValorDeclaradoDetalleDisgregado"]);
                        }

                        ActualizacionArchivosValorDeclarado(IdValorDeclarado, jsonListaArchivos, jsonListaArchivosEliminados);
                        //--> Confirma los cambios y los almacena en mi ef y no lo envia al servidor-->
                        context.SaveChanges();
                        //--> confirma los cambios y lo envia al servidor
                        Transaccion.Commit();
                        mensaje.esError = false;
                    }
                    catch (Exception ex)
                    {
                        Transaccion.Rollback();
                        throw ex;
                    }
                }
            }
            catch (Exception ex)
            {
                mensaje.mensaje = ex.Message;
                mensaje.esError = true;
            }
            return(mensaje);
        }
Exemplo n.º 18
0
        private static async Task <Booking> _saveBooking(Booking booking, ResotelContext ctx, DbContextTransaction transaction)
        {
            await ctx.SaveChangesAsync();

            transaction.Commit();
            return(booking);
        }
Exemplo n.º 19
0
 public EntityFrameworkSessionScope(IDataContextFactory dbContextFactory)
 {
     Requires.NotNull(dbContextFactory, "dbContextFactory");
     _session     = dbContextFactory.CreateDataContext();
     _transaction = _session.BeginTransaction();
 }
Exemplo n.º 20
0
 public void BeginTransaction()
 {
     transaction = context.Database.BeginTransaction();
 }
Exemplo n.º 21
0
        public int Commit()
        {
            if (this._isDisposed)
            {
                throw new ObjectDisposedException("DbContextManager");
            }

            if (this._isCompleted)
            {
                throw new InvalidOperationException("You can't call Commit() or Rollback() more than once on a DbContextCollection. All the changes in the DbContext instances managed by this collection have already been saved or rollback and all database transactions have been completed and closed. If you wish to make more data changes, create a new DbContextCollection and make your changes there.");
            }

            // Best effort. You'll note that we're not actually implementing an atomic commit
            // here. It entirely possible that one DbContext instance will be committed successfully
            // and another will fail. Implementing an atomic commit would require us to wrap
            // all of this in a TransactionScope. The problem with TransactionScope is that
            // the database transaction it creates may be automatically promoted to a
            // distributed transaction if our DbContext instances happen to be using different
            // databases. And that would require the DTC service (Distributed Transaction Coordinator)
            // to be enabled on all of our live and dev servers as well as on all of our dev workstations.
            // Otherwise the whole thing would blow up at runtime.

            // In practice, if our services are implemented following a reasonably DDD approach,
            // a business transaction (i.e. a service method) should only modify entities in a single
            // DbContext. So we should never find ourselves in a situation where two DbContext instances
            // contain uncommitted changes here. We should therefore never be in a situation where the below
            // would result in a partial commit.

            ExceptionDispatchInfo lastError = null;

            var effort = 0;

            foreach (var dbContext in this._initializedDbContexts.Values)
            {
                try
                {
                    if (!this._isReadOnly)
                    {
                        effort += dbContext.SaveChanges();
                    }

                    // If we've started an explicit database transaction, time to commit it now.
                    DbContextTransaction transaction = null;
                    bool succeed = this._transactions.TryGetValue(dbContext, out transaction);
                    if (succeed)
                    {
                        transaction.Commit();
                        transaction.Dispose();
                    }
                }
                catch (Exception e)
                {
                    lastError = ExceptionDispatchInfo.Capture(e);
                }
            }

            this._transactions.Clear();
            this._isCompleted = true;

            if (lastError != null)
            {
                lastError.Throw(); // Re-throw while maintaining the exception's original stack track
            }

            return(effort);
        }
Exemplo n.º 22
0
        public ActionResult ImportStudents([Bind(Include = "ID,SchoolID,SchoolName,TeacherName,RoomNumber,Students")] ClassRoomImport classRoom)
        {
            ActionResult         result = View(classRoom);
            DbContextTransaction xactn  = null;

            try
            {
                if (ModelState.IsValid)
                {
                    xactn = db.Database.BeginTransaction();

                    foreach (StudentImport s in classRoom.Students)
                    {
                        db.Students.Add(new Student()
                        {
                            SchoolID           = classRoom.SchoolID,
                            ClassRoomID        = classRoom.ID,
                            FullName           = s.FullName,
                            StudentNumber      = s.StudentNumber,
                            Guardian1TempEmail = s.Guardian1TempEmail,
                            Guardian2TempEmail = s.Guardian2TempEmail
                        });
                    }

                    ClassRoom c = db.ClassRooms.Find(classRoom.ID);
                    c.SetModified();
                    if (db.Entry(c).State != EntityState.Modified)
                    {
                        db.Entry(c).State = EntityState.Modified;
                    }

                    db.SaveChanges();

                    //////////////////////////////////////////////////////
                    ///	Send Emails to each of the registered guardians
                    //////////////////////////////////////////////////////
                    foreach (StudentImport s in classRoom.Students)
                    {
                        try
                        {
                            if (s.Guardian1TempEmail != null)
                            {
                                SendGuardianRegistrationEmail(classRoom.ID, s.ID, s.Guardian1TempEmail);
                            }
                            if (s.Guardian2TempEmail != null)
                            {
                                SendGuardianRegistrationEmail(classRoom.ID, s.ID, s.Guardian2TempEmail);
                            }
                        }
                        catch (Exception innerEx) { throw new Exception("Unable to send Guardian Emails", innerEx); }
                    }

                    xactn.Commit();
                    xactn.Dispose();
                    xactn = null;

                    result = RedirectToAction("Edit", "ClassRooms", new { id = classRoom.ID });
                }
            }
            catch (Exception ex)
            {
                string    Message      = "Error Saving Changes";
                string    InnerMessage = "";
                Exception inner        = ex.InnerException;
                while (inner != null)
                {
                    InnerMessage = " :: " + inner.Message;
                    inner        = inner.InnerException;
                }
                Message += InnerMessage;

                ModelState.AddModelError("", Message);
                if (xactn != null)
                {
                    xactn.Rollback();
                    xactn.Dispose();
                    xactn = null;
                }
            }
            return(result);
        }
 /// <summary>
 ///
 /// </summary>
 /// <returns></returns>
 public DbContextTransaction BeginTransaction()
 {
     _transaction = _context.Database.BeginTransaction();
     return(_transaction);
 }
Exemplo n.º 24
0
 private void SaveData()
 {
     try
     {
         string createBy     = Helper.GetLocalIPAddress();
         string stockNo      = string.Empty;
         int    stockItem    = 0;
         int    locationCode = cboLocation.SelectedValue.ToString().ToInt16();
         using (var db = new SlaughterhouseEntities())
         {
             long barcodeNo = txtBarcodeNo.Text.ToLong();
             var  barcode   = db.barcodes.Find(barcodeNo);
             if (barcode == null)
             {
                 throw new Exception("ไม่พบข้อมูลบาร์โค็ดนี้!");
             }
             //if (barcode.active == false)
             //{
             //    throw new Exception("ข้อมูลบาร์โค็ด จ่ายออกแล้ว!");
             //}
             if (barcode.location_code != null)
             {
                 throw new Exception("รหัสบาร์โค็ดนี้ รับเข้าคลังแล้ว!");
             }
             var stocks = db.stocks.Where(p => p.stock_date == productionDate &&
                                          p.product_code == barcode.product_code &&
                                          p.lot_no == barcode.lot_no &&
                                          p.transaction_type == 1).ToList();
             if (stocks.Count == 0)
             {
                 var stockGenerate = db.document_generate.Find(Constants.STK);
                 stockNo                       = Constants.STK + stockGenerate.running.ToString().PadLeft(10 - Constants.STK.Length, '0');
                 stockItem                     = 1;
                 stockGenerate.running        += 1;
                 db.Entry(stockGenerate).State = System.Data.Entity.EntityState.Modified;
                 db.SaveChanges();
             }
             else
             {
                 stockNo   = stocks[0].stock_no;
                 stockItem = stocks.Count + 1;
             }
             using (DbContextTransaction transaction = db.Database.BeginTransaction())
             {
                 try
                 {
                     //insert stock
                     var stock = new stock
                     {
                         stock_date   = productionDate,
                         stock_no     = stockNo,
                         stock_item   = stockItem,
                         product_code = barcode.product_code,
                         stock_qty    = barcode.qty,
                         stock_wgh    = barcode.wgh,
                         //ref_document_no = receive.receive_no,
                         //ref_document_type = Constants.REV,
                         lot_no           = barcode.lot_no,
                         location_code    = locationCode,
                         barcode_no       = barcode.barcode_no,
                         transaction_type = 1,
                         create_by        = createBy
                     };
                     db.stocks.Add(stock);
                     //update stock location
                     //stock.location_code =locationCode;
                     //db.Entry(stock).State = System.Data.Entity.EntityState.Modified;
                     //update barcode location
                     barcode.location_code   = locationCode;
                     barcode.modified_at     = DateTime.Now;
                     barcode.modified_by     = modifiedBy;
                     db.Entry(barcode).State = System.Data.Entity.EntityState.Modified;
                     db.SaveChanges();
                     transaction.Commit();
                 }
                 catch (Exception)
                 {
                     transaction.Rollback();
                     throw;
                 }
             }
             //foreach (int locationCode in _locations)
             //{
             //    if (barcode.location_code == locationCode)
             //        throw new Exception("รหัสบาร์โค็ดนี้ รับเข้าคลังแล้ว!");
             //}
             //lblWeight.Text = barcode.wgh.ToFormat2Decimal();
             //lblProduct.Text = barcode.product.product_name;
             //lblLotNo.Text = barcode.lot_no;
             //Get Location เดิม
             //var stocks = db.stocks.Where(p => p.stock_date == productionDate
             //    && p.product_code == barcode.product_code
             //    && p.location_code == barcode.location_code
             //    && p.barcode_no == barcode.barcode_no).ToList();
             //if (stocks.Count == 1)
             //{
             //    //var stock = db.stocks.Where(p => p.stock_date == productionDate
             //    //&& p.stock_no == stocks[0].stock_no
             //    //&& p.stock_item == stocks[0].stock_item
             //    //&& p.product_code == stocks[0].product_code).SingleOrDefault();
             //    //var stock = db.stocks.Find(productionDate, stocks[0].stock_no, stocks[0].stock_item, stocks[0].product_code);
             //}
         }
     }
     catch (Exception)
     {
         throw;
     }
 }
Exemplo n.º 25
0
        /// <summary>
        /// Thêm invoice kèm product
        /// </summary>
        /// <param name="invoiceObj"></param>
        /// <param name="lstProductObj"></param>
        /// <returns></returns>
        public int insertInvoiceProduct(PVOILInvoice invoiceObj, List <ProductInv> lstProductObj, String originKey)
        {
            ProductInvDA   cPro        = new ProductInvDA();
            PVOILInvoiceDA ctlPvoil    = new PVOILInvoiceDA();
            AdjustInvDH    cAdj        = new AdjustInvDH();
            AdjustInv      objAdj      = new AdjustInv();
            int            idInvoice   = 0;
            Boolean        draftCancel = invoiceObj.DraftCancel ?? false;
            PVOILInvoice   objInv      = ctlPvoil.checkExistInvoice(originKey, invoiceObj.ComTaxCode);
            PVOILInvoice   objAdjInv   = ctlPvoil.checkExistInvoice(invoiceObj.Fkey, invoiceObj.ComTaxCode);
            int            adjustInvId = objAdjInv != null ? objAdjInv.id : 0;

            //Set status cho table AdjustInv
            if (draftCancel)
            {
                if (invoiceObj.Type == InvoiceType.Nomal || invoiceObj.Type == InvoiceType.ForReplace || invoiceObj.Type == InvoiceType.ForAdjustAccrete ||
                    invoiceObj.Type == InvoiceType.ForAdjustReduce ||
                    invoiceObj.Type == InvoiceType.ForAdjustInfo)
                {
                    objAdj.Status = StatusAdj.Du_Thao_Huy;
                }
            }
            else
            {
                if (invoiceObj.Type == InvoiceType.ForReplace)
                {
                    objAdj.Status = StatusAdj.Du_Thao_Thay_The;
                }

                else if (invoiceObj.Type == InvoiceType.ForAdjustAccrete ||
                         invoiceObj.Type == InvoiceType.ForAdjustReduce ||
                         invoiceObj.Type == InvoiceType.ForAdjustInfo)
                {
                    objAdj.Status = StatusAdj.Du_Thao_Dieu_Chinh;
                }
                else
                {
                    objAdj.Status = 0;
                }
            }

            using (DbContextTransaction transaction = dbInvoice.db.Database.BeginTransaction())
            {
                try
                {
                    if (draftCancel && ((invoiceObj.Type == InvoiceType.Nomal ||
                                         invoiceObj.Type == InvoiceType.ForReplace || invoiceObj.Type == InvoiceType.ForAdjustAccrete ||
                                         invoiceObj.Type == InvoiceType.ForAdjustReduce ||
                                         invoiceObj.Type == InvoiceType.ForAdjustInfo)))
                    {
                        objAdjInv.Type        = invoiceObj.Type;
                        objAdjInv.Status      = invoiceObj.Status;
                        objAdjInv.DraftCancel = invoiceObj.DraftCancel;
                        updateInvoices(objAdjInv);
                        objAdj.AdjustInvId = adjustInvId;
                        if (objInv == null)
                        {
                            invoiceObj   = objAdjInv;
                            objAdj.InvId = invoiceObj.id;
                        }
                        else
                        {
                            objAdj.InvId = objInv.id;
                        }
                        objAdj.Description = invoiceObj.Name;
                        objAdj.Pattern     = invoiceObj.Pattern;
                        objAdj.ProcessDate = DateTime.Now;
                        objAdj.ComID       = invoiceObj.ComID;
                    }
                    else
                    {
                        idInvoice   = insertInvoices(invoiceObj);
                        adjustInvId = objAdjInv != null ? objAdjInv.id : idInvoice;
                        int invID = objInv != null ? objInv.id : 0;
                        objAdj.InvId       = invID;
                        objAdj.AdjustInvId = adjustInvId;
                        objAdj.Description = invoiceObj.Name;
                        objAdj.Pattern     = invoiceObj.Pattern;
                        objAdj.ProcessDate = DateTime.Now;
                        objAdj.ComID       = invoiceObj.ComID;

                        //Type =4 khoong nhan product
                        if (invoiceObj.Type != InvoiceType.ForAdjustInfo)
                        {
                            foreach (ProductInv item in lstProductObj)
                            {
                                item.id    = Guid.NewGuid();
                                item.InvID = idInvoice;
                            }

                            cPro.insertProduct(lstProductObj);
                        }
                    }
                    //check insert table AdjustInv type=0 and status=0 and daftcancel=0  thì ko insert
                    if (invoiceObj.Type == InvoiceType.Nomal)
                    {
                        if (draftCancel)
                        {
                            cAdj.insertAdjustInv(objAdj);
                        }
                    }
                    else
                    {
                        cAdj.insertAdjustInv(objAdj);
                    }

                    transaction.Commit();
                    return(idInvoice);
                }
                catch (Exception ex)
                {
                    transaction.Rollback();
                    throw ex;
                }
            }
        }
Exemplo n.º 26
0
        public async Task <int> SaveBeverageAsync(List <Rms.Classes.MenuItem> MenuItems)
        {
            using (DbContextTransaction transaction = Context.Database.BeginTransaction())
            {
                try
                {
                    var catlist = await Context.BeverageCategories.ToListAsync();

                    var items = await Context.Beverages.ToListAsync();

                    foreach (var bevcat in MenuItems.GroupBy(a => a.MenuCategoryName))
                    {
                        var cat = bevcat.Key;

                        BeverageCategory flag = catlist.Where(a => a.BeverageCategoryName == cat).FirstOrDefault();

                        if (flag == null)
                        {
                            flag = new BeverageCategory();
                            flag.BeverageCategoryName = cat;
                            Context.BeverageCategories.Add(flag);
                        }
                        else
                        {
                            Context.Entry(flag).State = EntityState.Modified;
                        }
                        await Context.SaveChangesAsync();

                        foreach (var i in bevcat)
                        {
                            var      beverage = i.beverage;
                            var      price    = i.Price;
                            Beverage flag1    = items.Where(a => a.Name.Trim().ToUpper() == beverage.Trim().ToUpper()).FirstOrDefault();
                            if (flag1 == null)
                            {
                                flag1             = new Beverage();
                                flag1.Name        = beverage;
                                flag1.Price       = price;
                                flag1.IsPopular   = i.IsPopular;
                                flag1.ShowInChart = i.ShowInChart;
                                int volume = 0;
                                int.TryParse(i.Volume, out volume);
                                flag1.Volume             = volume;
                                flag1.Image              = i.Image;
                                flag1.DrinkType          = Drinktype.Whisky;
                                flag1.BeverageCategoryId = flag.BeverageCategoryId;
                                Context.Beverages.Add(flag1);
                            }
                            else
                            {
                                Context.Entry(flag1).State = EntityState.Modified;
                            }
                            await Context.SaveChangesAsync();
                        }
                    }
                    transaction.Commit();
                    return(0);
                }
                catch (Exception ex)
                {
                    transaction.Rollback();
                    throw ex;
                }
            }
        }
Exemplo n.º 27
0
 /// <summary>
 /// This method is to begin a new transaction.
 /// </summary>
 public void BeginTransaction()
 {
     _transaction = _dbContext.Database.BeginTransaction();
 }
Exemplo n.º 28
0
        public void UpdateOrder(Order model)
        {
            if (model == null)
            {
                throw new OrderNotFoundException();
            }
            var editmodel = GetOrderByID(model.OrderId, false);

            if (editmodel == null)
            {
                throw new OrderNotFoundException();
            }
            var items = model.OrderItems.ToList();
            var i     = 0;

            if (items.Count() > 0)
            {
                using (DbContextTransaction transaction = unitOfWork.DbContext.Database.BeginTransaction())
                {
                    foreach (var orderItem in editmodel.OrderItems)
                    {
                        if (orderItem.OrderItemIsDeleted == false)
                        {
                            if (orderItem.OrderItemProductId != items[i].OrderItemProductId)
                            {
                                try
                                {
                                    _productService.UpdateProductQuantity(orderItem.OrderItemProductId, orderItem.OrderItemQuantity, true);
                                    _productService.UpdateProductQuantity(items[i].OrderItemProductId, items[i].OrderItemQuantity, false);
                                }
                                catch (Exception exp)
                                {
                                    transaction.Rollback();
                                    throw exp;
                                }
                                orderItem.OrderItemProductId = items[i].OrderItemProductId;
                            }
                            //order Total limit exception
                            if (items[i].OrderItemQuantity > 10)
                            {
                                transaction.Rollback();
                                throw new ProductMaxQuantityExceededException();
                            }
                            else
                            {
                                orderItem.OrderItemQuantity = items[i].OrderItemQuantity;
                            }
                            orderItem.OrderItemTotalPrice = items[i].OrderItemTotalPrice;
                            if (items[i].OrderItemIsDeleted)
                            {
                                orderItem.OrderItemIsDeleted = items[i].OrderItemIsDeleted;
                                try
                                {
                                    _productService.UpdateProductQuantity(orderItem.OrderItemProductId, orderItem.OrderItemQuantity, true);
                                }
                                catch (Exception ex)
                                {
                                    transaction.Rollback();
                                    throw ex;
                                }
                            }
                            i++;
                        }
                    }
                    if (model.OrderTotal > 5000)
                    {
                        transaction.Rollback();
                        throw new OrderExceededMaxTotalException();
                    }
                    else
                    {
                        editmodel.OrderTotal = model.OrderTotal;
                    }
                    try
                    {
                        unitOfWork.OrderRepository.Update(editmodel);
                        unitOfWork.Save();
                        transaction.Commit();
                    }
                    catch (DbUpdateException ex)
                    {
                        transaction.Rollback();
                        var sqlException = ex.GetBaseException() as SqlException;
                        if (sqlException != null && sqlException.Number == 547)
                        {
                            throw new MyPosDbException("Oops A Database Error Occured While Updating The Order", ex);
                        }
                        throw ex;
                    }
                }
            }
        }
Exemplo n.º 29
0
 public ApplicationFixture()
 {
     Db           = new ApplicationDbContext(ConfigurationManager.ConnectionStrings["DefaultConnectionString"].ConnectionString);
     Factory      = new DbFactory(Db);
     _transaction = Db.Database.BeginTransaction();
 }
Exemplo n.º 30
0
 public void BeginTransaction()
 {
     DbTransaction = Context.Database.BeginTransaction();
 }