Exemplo n.º 1
0
        public static void TransactionSupport()
        {
            Console.WriteLine("*** TransactionSupport Start ***");
            using (var context = new SchoolDBEntities())
            {
                using (System.Data.Entity.DbContextTransaction dbTran = context.Database.BeginTransaction( ))
                {
                    try
                    {
                        Student std1 = new Student()
                        {
                            StudentName = "newstudent"
                        };
                        context.Students.Add(std1);
                        context.Database.ExecuteSqlCommand(
                            @"UPDATE Student SET StudentName = 'Edited Student Name'" +
                            " WHERE StudentID =1"
                            );
                        context.Students.Remove(std1);

                        //saves all above operations within one transaction
                        context.SaveChanges();

                        //commit transaction
                        dbTran.Commit();
                    }
                    catch (Exception ex)
                    {
                        //Rollback transaction if exception occurs
                        dbTran.Rollback();
                    }
                }
            }
            Console.WriteLine("*** TransactionSupport Finished ***");
        }
        public static CommandResult ChangePassword(string userName, string oldPassword, string newPassword)
        {
            using (var context = new GST_MockProjectEntities())
            {
                using (System.Data.Entity.DbContextTransaction dbTran = context.Database.BeginTransaction())
                {
                    var user = context.USERs.FirstOrDefault(x => x.UserName == userName);
                    if (user == null)
                    {
                        return(new CommandResult(ResultCode.Fail, "User không tồn tại"));
                    }
                    else
                    {
                        var passMD5 = Encryptor.MD5Hash(oldPassword);
                        if (user.Password != passMD5)
                        {
                            return(new CommandResult(ResultCode.Fail, "Mật khẩu cũ không đúng"));
                        }
                        user.Password = Encryptor.MD5Hash(newPassword);
                        context.SaveChanges();
                    }



                    dbTran.Commit();

                    return(new CommandResult(ResultCode.Success, "Đổi mật khẩu thành công."));
                }
            }
        }
        public async Task <JsonResult> UpdateActiveService(string memberId, string Id, bool isActive)
        {
            initpage();////
            var db = new DBContext();

            using (System.Data.Entity.DbContextTransaction ContextTransaction = db.Database.BeginTransaction())
            {
                try
                {
                    string decrptMemId         = Decrypt.DecryptMe(memberId);
                    long   MembId              = long.Parse(decrptMemId);
                    string decrptSlID          = Decrypt.DecryptMe(Id);
                    long   SlId                = long.Parse(decrptSlID);
                    var    updateServiceStatus = await db.TBL_WHITELABLE_SERVICE.Where(x => x.SL_NO == SlId && x.MEMBER_ID == MembId).FirstOrDefaultAsync();

                    if (updateServiceStatus != null)
                    {
                        updateServiceStatus.ACTIVE_SERVICE  = isActive;
                        db.Entry(updateServiceStatus).State = System.Data.Entity.EntityState.Modified;
                        await db.SaveChangesAsync();

                        ContextTransaction.Commit();
                        return(Json(new { Result = "true" }));
                    }
                    return(Json(new { Result = "true" }));
                }
                catch (Exception ex)
                {
                    ContextTransaction.Rollback();
                    Logger.Error("Controller:-  SuperService(Super), method:- UpdateActiveService (POST) Line No:- 199", ex);
                    return(Json(new { Result = "false" }));
                }
            }
        }
Exemplo n.º 4
0
        public ActionResult CreateWithTransaction(Invoice invoice)
        {
            if (ModelState.IsValid)
            {
                using (System.Data.Entity.DbContextTransaction dbTran = db.Database.BeginTransaction())
                {
                    try
                    {
                        db.Invoices.Add(invoice);
                        db.SaveChanges();

                        //commit transaction
                        dbTran.Commit();
                    }
                    catch (Exception ex)
                    {
                        //Rollback transaction if exception occurs
                        dbTran.Rollback();
                    }
                }

                return(RedirectToAction("Index"));
            }

            ViewBag.ClienteId = new SelectList(db.Clientes, "Id", "RazonSocial", invoice.ClienteId);
            return(View(invoice));
        }
Exemplo n.º 5
0
        public async Task <JsonResult> DeactivateBankDetails(string id)
        {
            var db = new DBContext();

            using (System.Data.Entity.DbContextTransaction ContextTransaction = db.Database.BeginTransaction())
            {
                try
                {
                    long idval        = long.Parse(id);
                    var  bankdeactive = await db.TBL_SETTINGS_BANK_DETAILS.Where(x => x.SL_NO == idval).FirstOrDefaultAsync();

                    bankdeactive.ISDELETED       = 1;
                    bankdeactive.DELETED_DATE    = System.DateTime.Now;
                    bankdeactive.DELETED_BY      = 0;
                    db.Entry(bankdeactive).State = System.Data.Entity.EntityState.Modified;
                    await db.SaveChangesAsync();

                    ContextTransaction.Commit();
                    return(Json(new { Result = "true" }));
                }
                catch (Exception ex)
                {
                    ContextTransaction.Rollback();
                    return(Json(new { Result = "false" }));
                }
            }
        }
Exemplo n.º 6
0
 /// <summary>
 /// Begin transaction
 /// </summary>
 /// <param name="commitOnDispose">Auto commit transaction on disposing</param>
 /// <returns>Disposable transaction</returns>
 public IDisposable BeginTransaction(bool commitOnDispose)
 {
     if (transaction != null)
         throw new Exception("Transaction already started. Use CommitTransaction() or RollbackTransaction() before");
     transaction = Database.BeginTransaction();
     return new DisposableHelper(() => { if (commitOnDispose) CommitTransaction(); else RollbackTransaction(); });
 }
        private void btnLinkDayAvailableToSchedule_Click(object sender, EventArgs e)
        {
            using (var Dbconnection = new MCDEntities())
            {
                using (System.Data.Entity.DbContextTransaction dbTran = Dbconnection.Database.BeginTransaction())
                {
                    try
                    {
                        //CRUD Operations

                        DateTime        dtStart            = new DateTime(2000, 01, 1, Convert.ToInt32(nudStartHours.Value), Convert.ToInt32(nudStartMin.Value), 0);
                        DateTime        dtEnd              = new DateTime(2000, 01, 1, Convert.ToInt32(nudEndHours.Value), Convert.ToInt32(nudEndMin.Value), 0);
                        LookupDayOfWeek newLookupDayOfWeek = (LookupDayOfWeek)availableCurriculumCourseDayCanBeScheduledBindingSource.Current;

                        CurriculumCourseDayCanBeScheduled newCurriculumCourseDayCanBeScheduled = new CurriculumCourseDayCanBeScheduled()
                        {
                            CurriculumCourseID = newCourseObj.CurriculumCourseID,
                            StartTime          = dtStart.TimeOfDay,
                            EndTime            = dtEnd.TimeOfDay,
                            DayOfWeekID        = newLookupDayOfWeek.DayOfWeekID,
                            ObjectState        = EntityObjectState.Added
                        };
                        Dbconnection.CurriculumCourseDayCanBeScheduleds.Add(newCurriculumCourseDayCanBeScheduled);
                        ////saves all above operations within one transaction
                        Dbconnection.SaveChanges();

                        //commit transaction
                        dbTran.Commit();
                        this.loadupStepThree();
                        this.nudStartHours.Value = 8;
                        this.nudStartMin.Value   = 0;
                        this.nudEndHours.Value   = 16;
                        this.nudEndMin.Value     = 0;
                        if (availableCurriculumCourseDayCanBeScheduledBindingSource.Count == 0)
                        {
                            btnLinkDayAvailableToSchedule.Enabled = false;
                        }
                    }
                    catch (Exception ex)
                    {
                        if (ex is DbEntityValidationException)
                        {
                            foreach (DbEntityValidationResult entityErr in ((DbEntityValidationException)ex).EntityValidationErrors)
                            {
                                foreach (DbValidationError error in entityErr.ValidationErrors)
                                {
                                    MessageBox.Show(error.ErrorMessage, "Error Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                }
                            }
                        }
                        else
                        {
                            MessageBox.Show(ex.Message, "Error Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                        //Rollback transaction if exception occurs
                        dbTran.Rollback();
                    }
                }
            };
        }
Exemplo n.º 8
0
        public async Task <JsonResult> RejectKYCDocument(string Id)
        {
            try
            {
                var db = new DBContext();
                using (System.Data.Entity.DbContextTransaction ContextTransaction = db.Database.BeginTransaction())
                {
                    long MemID      = long.Parse(Id);
                    var  getdocinfo = await db.TBL_MASTER_MEMBER.Where(x => x.MEM_ID == MemID).FirstOrDefaultAsync();

                    if (getdocinfo != null)
                    {
                        getdocinfo.KYC_VERIFIED      = false;
                        getdocinfo.KYC_VERIFIED_USER = long.Parse(Session["UserId"].ToString());
                        getdocinfo.VERIFICATION_DATE = System.DateTime.Now;
                        db.Entry(getdocinfo).State   = System.Data.Entity.EntityState.Modified;
                        await db.SaveChangesAsync();

                        ContextTransaction.Commit();
                        return(Json(new { Result = "true" }));
                    }
                    else
                    {
                        ContextTransaction.Rollback();
                        return(Json(new { Result = "false" }));
                    }
                }
                //string decrptMemId = Decrypt.DecryptMe(Id);
            }
            catch (Exception ex)
            {
                Logger.Error("Controller:-  MemberKYCVerification(Admin), method:- RejectKYCDocument (POST) Line No:- 212", ex);
                throw;
            }
        }
        public async Task <ActionResult> UpdateHostingDetails(TBL_WHITE_LEVEL_HOSTING_DETAILS value, HttpPostedFileBase MotoFile, HttpPostedFileBase LogoFile, HttpPostedFileBase BannerFile)
        {
            var db = new DBContext();

            using (System.Data.Entity.DbContextTransaction ContextTransaction = db.Database.BeginTransaction())
            {
                try
                {
                    long slno        = long.Parse(value.SLN.ToString());
                    var  hostinginfo = await db.TBL_WHITE_LEVEL_HOSTING_DETAILS.Where(x => x.SLN == slno).FirstOrDefaultAsync();

                    string Motofilename   = string.Empty;
                    string Logofilename   = string.Empty;
                    string Bannerfilename = string.Empty;
                    if (MotoFile != null)
                    {
                        var MotoFileName       = value.MEM_ID + "_" + value.LONG_CODE + "_" + System.DateTime.Now + "_" + Path.GetFileName(MotoFile.FileName);
                        var MotoServerSavePath = Path.Combine(Server.MapPath("~/MemberHostingFiles/") + MotoFileName);
                        Motofilename = "~/MemberHostingFiles/" + MotoFileName;
                        MotoFile.SaveAs(MotoServerSavePath);
                        //value.MOTO = Motofilename;
                        hostinginfo.MOTO = Motofilename;
                    }
                    if (LogoFile != null)
                    {
                        var LogoFileName       = value.MEM_ID + "_" + value.LONG_CODE + "_" + System.DateTime.Now + "_" + Path.GetFileName(LogoFile.FileName);
                        var LogoServerSavePath = Path.Combine(Server.MapPath("~/MemberHostingFiles/") + LogoFileName);
                        Logofilename = "~/MemberHostingFiles/" + LogoFileName;
                        LogoFile.SaveAs(LogoServerSavePath);
                        //value.LOGO = Logofilename;
                        hostinginfo.LOGO = Logofilename;
                    }
                    if (BannerFile != null)
                    {
                        var BannerFileName       = value.MEM_ID + "_" + value.LONG_CODE + "_" + System.DateTime.Now + "_" + Path.GetFileName(BannerFile.FileName);
                        var BannerServerSavePath = Path.Combine(Server.MapPath("~/MemberHostingFiles/") + BannerFileName);
                        Bannerfilename = "~/MemberHostingFiles/" + BannerFileName;
                        BannerFile.SaveAs(BannerServerSavePath);
                        //value.BANNER = Bannerfilename;
                        hostinginfo.BANNER = Bannerfilename;
                    }
                    hostinginfo.COMPANY_NAME    = value.COMPANY_NAME;
                    hostinginfo.DOMAIN          = value.DOMAIN;
                    hostinginfo.LONG_CODE       = value.LONG_CODE;
                    db.Entry(hostinginfo).State = System.Data.Entity.EntityState.Modified;
                    await db.SaveChangesAsync();

                    ContextTransaction.Commit();
                    return(RedirectToAction("Index"));
                }
                catch (Exception ex)
                {
                    ContextTransaction.Rollback();
                    Logger.Error("Controller:-  PowerAdminHostin(Distributor), method:- UpdateHostingDetails (POST) Line No:- 388", ex);
                    return(RedirectToAction("Exception", "ErrorHandler", new { area = "" }));

                    throw ex;
                }
            }
        }
Exemplo n.º 10
0
        //public JsonResult DeleteInformation(int id)
        public async Task <JsonResult> DeleteInformation(string id)
        {
            var context = new DBContext();

            using (System.Data.Entity.DbContextTransaction ContextTransaction = context.Database.BeginTransaction())
            {
                try
                {
                    string decrptSlId = Decrypt.DecryptMe(id);
                    long   Memid      = long.Parse(decrptSlId);
                    var    membinfo   = await context.TBL_MASTER_MEMBER.Where(x => x.MEM_ID == Memid).FirstOrDefaultAsync();

                    membinfo.IS_DELETED           = true;
                    context.Entry(membinfo).State = System.Data.Entity.EntityState.Modified;
                    await context.SaveChangesAsync();

                    ContextTransaction.Commit();
                    return(Json(new { Result = "true" }));
                }
                catch (Exception ex)
                {
                    Logger.Error("Controller:-  SuperMember(Super), method:- DeleteInformation (POST) Line No:- 374", ex);
                    ContextTransaction.Rollback();
                    return(Json(new { Result = "false" }));
                }
            }
        }
Exemplo n.º 11
0
        //public async Task<ActionResult> ChangePassword(MemberChangePasswordModel value)
        public async Task <JsonResult> ChangePassword(MemberChangePasswordModel value)
        {
            initpage();////
            var db = new DBContext();

            using (System.Data.Entity.DbContextTransaction ContextTransaction = db.Database.BeginTransaction())
            {
                try
                {
                    long mem_id     = MemberCurrentUser.MEM_ID;
                    var  changepass = db.TBL_MASTER_MEMBER.Where(x => x.MEM_ID == mem_id).FirstOrDefault();
                    if (changepass != null)
                    {
                        if (changepass.User_pwd == value.OldUser_pwd)
                        {
                            var userpass = value.User_pwd;
                            //userpass = userpass.GetPasswordHash();
                            changepass.User_pwd        = userpass;
                            db.Entry(changepass).State = System.Data.Entity.EntityState.Modified;
                            await db.SaveChangesAsync();

                            //throw new Exception();
                            var token            = TokenGenerator.GenerateToken();
                            var PasswordResetObj = new TBL_PASSWORD_RESET
                            {
                                ID      = token,
                                EmailID = changepass.EMAIL_ID,
                                Time    = DateTime.Now
                            };
                            db.TBL_PASSWORD_RESET.Add(PasswordResetObj);
                            db.SaveChanges();
                            ContextTransaction.Commit();
                            FormsAuthentication.SignOut();
                            FormsAuthentication.SignOut();
                            Session["WhiteLevelUserId"]   = null;
                            Session["WhiteLevelUserName"] = null;
                            Session.Clear();
                            Session.Remove("WhiteLevelUserId");
                            Session.Remove("WhiteLevelUserName");
                            //return RedirectToAction("Message");
                            return(Json("Password changed Successfully", JsonRequestBehavior.AllowGet));
                        }
                        else
                        {
                            return(Json("Please Enter Valid Old Password ", JsonRequestBehavior.AllowGet));
                        }
                    }
                    return(Json("OK", JsonRequestBehavior.AllowGet));
                }
                catch (Exception ex)
                {
                    ContextTransaction.Rollback();
                    Logger.Error("Controller:-  MemberChangePassword(Admin), method:- ChangePassword (POST) Line No:- 271", ex);

                    throw ex;
                    return(Json("Try Again After Sometime", JsonRequestBehavior.AllowGet));
                    //return View("Error", new HandleErrorInfo(ex, "APILabel", "CreateMember"));
                }
            }
        }
Exemplo n.º 12
0
 public void RollBack()
 {
     if (this.transaction != null)
     {
         this.transaction.Rollback();
         this.transaction = null;
     }
 }
Exemplo n.º 13
0
 //Represents a method that commits all changes in the database
 public void Commit()
 {
     if (this.trans != null)
     {
         this.trans.Commit();
         this.trans = null;
     }
 }
Exemplo n.º 14
0
        public CommerceDbTransaction(DbContextTransaction underlyingTransaction, CommerceDatabase database)
        {
            Require.NotNull(underlyingTransaction, "underlyingTransaction");
            Require.NotNull(database, "database");

            UnderlyingTransaction = underlyingTransaction;
            Database = database;
        }
Exemplo n.º 15
0
        public EfTransaction(DbContextTransaction transaction, TransactionCloseType closeType)
            : base(closeType)
        {
            if (transaction == null)
                throw new ArgumentNullException("transaction");

            _transaction = transaction;
        }
Exemplo n.º 16
0
 public void Commit()
 {
     if (transaction != null)
     {
         this.transaction.Commit();
         this.transaction = null;
     }
 }
Exemplo n.º 17
0
        public async Task <ActionResult> BankDetails(TBL_SETTINGS_BANK_DETAILS objval)
        {
            var db = new DBContext();

            using (System.Data.Entity.DbContextTransaction ContextTransaction = db.Database.BeginTransaction())
            {
                try
                {
                    var checkbankinfo = await db.TBL_SETTINGS_BANK_DETAILS.Where(x => x.SL_NO == objval.SL_NO).FirstOrDefaultAsync();

                    if (checkbankinfo == null)
                    {
                        objval.CREATED_DATE = DateTime.Now;
                        //objval.CREATED_BY = long.Parse(Session["UserId"].ToString());
                        objval.CREATED_BY = MemberCurrentUser.MEM_ID;
                        // For pawer admin created by vakue is 0 after that if admin logged in then  create bank then created by id values is goes to admin id
                        objval.CREATED_BY = 0;

                        //long memid = long.Parse(objval.UserName);

                        objval.MEM_ID     = MemberCurrentUser.MEM_ID;
                        objval.ISDELETED  = 0;
                        objval.CREATED_BY = MemberCurrentUser.MEM_ID;
                        db.TBL_SETTINGS_BANK_DETAILS.Add(objval);
                        await db.SaveChangesAsync();

                        //return RedirectToAction("Index");
                    }
                    else
                    {
                        checkbankinfo.MEM_ID          = MemberCurrentUser.MEM_ID;
                        checkbankinfo.BANK            = objval.BANK;
                        checkbankinfo.IFSC            = objval.IFSC;
                        checkbankinfo.MICR_CODE       = objval.MICR_CODE;
                        checkbankinfo.CITY            = objval.CITY;
                        checkbankinfo.BRANCH          = objval.BRANCH;
                        checkbankinfo.CONTACT         = objval.CONTACT;
                        checkbankinfo.STATE           = objval.STATE;
                        checkbankinfo.ADDRESS         = objval.ADDRESS;
                        checkbankinfo.DISTRICT        = objval.DISTRICT;
                        db.Entry(checkbankinfo).State = System.Data.Entity.EntityState.Modified;
                        await db.SaveChangesAsync();

                        //return RedirectToAction("Index");
                    }
                    ContextTransaction.Commit();
                    return(RedirectToAction("Index"));
                }
                catch (Exception ex)
                {
                    ContextTransaction.Rollback();
                    Logger.Error("Controller:-  MemberBankDetails(Admin), method:- BankDetails (POST) Line No:- 224", ex);
                    return(RedirectToAction("Exception", "ErrorHandler", new { area = "" }));

                    throw ex;
                }
            }
        }
 /// <summary>
 /// koniec transakcji 
 /// </summary>
 public void Commit()
 {
     if (_transaktion != null)
     {
         _sailingDbContext.SaveChanges();
         _transaktion.Commit();
         _transaktion = null;
     }
 }
Exemplo n.º 19
0
        /// <summary>
        ///     Инициализирует новый экземпляр класса <see cref="UnitOfWorkEf" />
        /// </summary>
        /// <param name="contextFactory">Фабрика контекста доступа к БД</param>
        /// <param name="isolationLevel">Уровень изоляции данных</param>
        public UnitOfWorkEf(
            IDbContextFactory contextFactory,
            IsolationLevel isolationLevel = IsolationLevel.ReadCommitted)
        {
            this._context = contextFactory.CreateDbContext<EntitiesContext>();

            // Если БД не была создана вызовет ошибку
            this._transaction = this._context.Database.BeginTransaction(isolationLevel);
        }
Exemplo n.º 20
0
        public async Task <ActionResult> BankDetails(TBL_SETTINGS_BANK_DETAILS objval)
        {
            var db = new DBContext();

            using (System.Data.Entity.DbContextTransaction ContextTransaction = db.Database.BeginTransaction())
            {
                try
                {
                    var checkbankinfo = await db.TBL_SETTINGS_BANK_DETAILS.Where(x => x.SL_NO == objval.SL_NO).FirstOrDefaultAsync();

                    if (checkbankinfo == null)
                    {
                        objval.CREATED_DATE = DateTime.Now;
                        objval.CREATED_BY   = CurrentUser.USER_ID;
                        objval.CREATED_BY   = 0;
                        objval.MEM_ID       = 0;
                        objval.ISDELETED    = 0;
                        //objval.STATE = objval.STATENAME;
                        db.TBL_SETTINGS_BANK_DETAILS.Add(objval);
                        await db.SaveChangesAsync();

                        //return RedirectToAction("Index");
                    }
                    else
                    {
                        checkbankinfo.MEM_ID             = 0;
                        checkbankinfo.BANK               = objval.BANK;
                        checkbankinfo.ACCOUNT_HOLDERNAME = objval.ACCOUNT_HOLDERNAME;
                        checkbankinfo.IFSC               = objval.IFSC;
                        checkbankinfo.MICR_CODE          = objval.MICR_CODE;
                        checkbankinfo.CITY               = objval.CITY;
                        checkbankinfo.BRANCH             = objval.BRANCH;
                        checkbankinfo.CONTACT            = objval.CONTACT;
                        checkbankinfo.STATE              = objval.STATE;
                        //checkbankinfo.STATE = objval.STATENAME;
                        checkbankinfo.ADDRESS         = objval.ADDRESS;
                        checkbankinfo.DISTRICT        = objval.DISTRICT;
                        checkbankinfo.ACCOUNT_NO      = objval.ACCOUNT_NO;
                        db.Entry(checkbankinfo).State = System.Data.Entity.EntityState.Modified;
                        await db.SaveChangesAsync();

                        //return RedirectToAction("Index");
                    }
                    ContextTransaction.Commit();
                    return(RedirectToAction("Index"));
                }
                catch (Exception ex)
                {
                    ContextTransaction.Rollback();
                    Logger.Error("Controller:-  PowerAdminBankDetails(PowerAdmin), method:- BankDetails (POST) Line No:- 212", ex);
                    return(RedirectToAction("Exception", "ErrorHandler", new { area = "" }));

                    throw ex;
                }
            }
        }
 public DbContextTransaction BeginTransaction()
 {
     if (this.Transaction != null)
     {
         this.Transaction.Dispose();
         this.Transaction = null;
     }
     this.Transaction = this.Database.BeginTransaction();
     return this.Transaction;
 }
 /// <summary>
 /// początek transakcji
 /// </summary>
 public void BeginTransaction()
 {
     if (_transaktion == null)
     {
         if (_sailingDbContext != null)
         {
             _transaktion = _sailingDbContext.Database.BeginTransaction();
         }
     }
 }
Exemplo n.º 23
0
 private void btnUpdateContact_Click(object sender, EventArgs e)
 {
     using (var Dbconnection = new MCDEntities())
     {
         using (System.Data.Entity.DbContextTransaction dbTran = Dbconnection.Database.BeginTransaction())
         {
             try
             {
                 //CRUD Operations
                 Data.Models.NextOfKin IndividualToUpdate = (from a in Dbconnection.NextOfKins
                                                             where a.IndividualID == IndividualID
                                                             select a).FirstOrDefault <Data.Models.NextOfKin>();
                 IndividualToUpdate.Individual.TitleID              = Convert.ToInt32(cboIndividualTitle.SelectedValue);
                 IndividualToUpdate.Individual.IndividualFirstName  = txtFirstName.Text.ToString();
                 IndividualToUpdate.Individual.IndividualSecondName = txtSecondName.Text.ToString();
                 IndividualToUpdate.Individual.IndividualLastname   = txtLastName.Text.ToString();
                 IndividualToUpdate.TypeOfRelationID = Convert.ToInt32(cboRelationType.SelectedValue);
                 Dbconnection.SaveChanges();
                 ////saves all above operations within one transaction
                 Dbconnection.SaveChanges();
                 if (CurrentNextOfKin != null)
                 {
                     CurrentNextOfKin.Individual.TitleID              = Convert.ToInt32(cboIndividualTitle.SelectedValue);
                     CurrentNextOfKin.Individual.IndividualFirstName  = txtFirstName.Text.ToString();
                     CurrentNextOfKin.Individual.IndividualSecondName = txtSecondName.Text.ToString();
                     CurrentNextOfKin.Individual.IndividualLastname   = txtLastName.Text.ToString();
                     CurrentNextOfKin.TypeOfRelationID = Convert.ToInt32(cboRelationType.SelectedValue);
                 }
                 //commit transaction
                 dbTran.Commit();
                 this.Close();
             }
             catch (Exception ex)
             {
                 if (ex is DbEntityValidationException)
                 {
                     foreach (DbEntityValidationResult entityErr in ((DbEntityValidationException)ex).EntityValidationErrors)
                     {
                         foreach (DbValidationError error in entityErr.ValidationErrors)
                         {
                             MessageBox.Show(error.ErrorMessage, "Error Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
                         }
                     }
                 }
                 else
                 {
                     MessageBox.Show(ex.Message, "Error Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
                 }
                 //Rollback transaction if exception occurs
                 dbTran.Rollback();
             }
         }
     };
 }
        //IEnumerable<HttpPostedFileBase> files
        //public async Task<JsonResult> POSTADDSUPERDistributor(TBL_MASTER_MEMBER objsupermem, HttpPostedFileBase AadhaarFile, HttpPostedFileBase PanFile)
        public async Task <JsonResult> PostUpdateMemberDetails(TBL_MASTER_MEMBER objsupermem)
        {
            initpage();////
            var db = new DBContext();

            using (System.Data.Entity.DbContextTransaction ContextTransaction = db.Database.BeginTransaction())
            {
                try
                {
                    long MemID            = 0;
                    var  GetMemberDetails = await db.TBL_MASTER_MEMBER.FirstOrDefaultAsync(x => x.MEM_ID == objsupermem.MEM_ID);

                    if (GetMemberDetails.MEMBER_ROLE == 3)
                    {
                        GetMemberDetails.SuperName = "SUPER";
                    }
                    else if (GetMemberDetails.MEMBER_ROLE == 4)
                    {
                        GetMemberDetails.SuperName = "DISTRIBUTOR";
                    }
                    else if (GetMemberDetails.MEMBER_ROLE == 5)
                    {
                        GetMemberDetails.SuperName = "MERCHANT";
                    }
                    GetMemberDetails.MEMBER_MOBILE    = objsupermem.MEMBER_MOBILE;
                    GetMemberDetails.MEMBER_NAME      = objsupermem.MEMBER_NAME;
                    GetMemberDetails.COMPANY          = objsupermem.COMPANY;
                    GetMemberDetails.ADDRESS          = objsupermem.ADDRESS;
                    GetMemberDetails.CITY             = objsupermem.CITY;
                    GetMemberDetails.PIN              = objsupermem.PIN;
                    GetMemberDetails.SECURITY_PIN_MD5 = objsupermem.SECURITY_PIN_MD5;
                    GetMemberDetails.COMPANY_GST_NO   = objsupermem.COMPANY_GST_NO;
                    GetMemberDetails.PIN              = objsupermem.PIN;
                    GetMemberDetails.BLOCKED_BALANCE  = objsupermem.BLOCKED_BALANCE;
                    GetMemberDetails.GST_FLAG         = objsupermem.GST_FLAG;
                    GetMemberDetails.TDS_FLAG         = objsupermem.TDS_FLAG;
                    db.Entry(GetMemberDetails).State  = System.Data.Entity.EntityState.Modified;
                    await db.SaveChangesAsync();

                    ContextTransaction.Commit();
                    //return View("Index");
                    return(Json("Information Update Successfully", JsonRequestBehavior.AllowGet));
                }
                catch (Exception ex)
                {
                    ContextTransaction.Rollback();
                    Logger.Error("Controller:-  MemberChannelRegistration(Admin), method:- ADDSUPERDISTRIBUTOR (POST) Line No:- 230", ex);
                    throw ex;
                    return(Json("Please Try After Sometime", JsonRequestBehavior.AllowGet));

                    //return View("Error", new HandleErrorInfo(ex, "APILabel", "CreateMember"));
                }
            }
        }
        public void Creating_DbContextTransaction_specifying_EntityTransaction_does_not_open_connection_if_already_open()
        {
            var mockEntityTransaction = new Mock<EntityTransaction>();
            var mockEntityConnection = new Mock<EntityConnection>();
            mockEntityConnection.SetupGet(m => m.State).Returns(ConnectionState.Open);
            mockEntityTransaction.SetupGet(m => m.Connection).Returns(mockEntityConnection.Object);

            var dbContextTransaction = new DbContextTransaction(mockEntityTransaction.Object);

            mockEntityConnection.Verify(m => m.Open(), Times.Never());
        }
        public void Creating_DbContextTransaction_specifying_IsolationLevel_does_not_open_connection_if_already_open()
        {
            var mockEntityTransaction = new Mock<EntityTransaction>();
            var mockEntityConnection = new Mock<EntityConnection>();
            mockEntityConnection.SetupGet(m => m.State).Returns(ConnectionState.Open);
            mockEntityConnection.Setup(m => m.BeginTransaction(It.IsAny<IsolationLevel>())).Returns(mockEntityTransaction.Object);

            var dbContextTransaction = new DbContextTransaction(mockEntityConnection.Object, IsolationLevel.Snapshot);

            mockEntityConnection.Verify(m => m.Open(), Times.Never());
        }
Exemplo n.º 27
0
        private void toolStripButton12_Click(object sender, EventArgs e)
        {
            if (companyContactsBindingSource.Count > 0)
            {
                using (var Dbconnection = new MCDEntities())
                {
                    using (System.Data.Entity.DbContextTransaction dbTran = Dbconnection.Database.BeginTransaction())
                    {
                        try
                        {
                            //CRUD Operations
                            CompanyContacts CC          = (CompanyContacts)companyContactsBindingSource.Current;
                            Individual      CCFromCache = CurrentlySelectedCompany.Individuals.Where(a => a.IndividualID == CC.IndividualID).First();

                            // return one instance each entity by primary key
                            var C = Dbconnection.Companies.FirstOrDefault(a => a.CompanyID == CurrentlySelectedCompany.CompanyID);
                            var I = Dbconnection.Individuals.FirstOrDefault(a => a.IndividualID == CC.IndividualID);

                            // call Remove method from navigation property for any instance
                            C.Individuals.Remove(I);

                            ////saves all above operations within one transaction
                            Dbconnection.SaveChanges();

                            //commit transaction
                            dbTran.Commit();
                            CurrentlySelectedCompany.Individuals.Remove(CCFromCache);
                            this.refreshCompanyContacts();
                        }
                        catch (Exception ex)
                        {
                            if (ex is DbEntityValidationException)
                            {
                                foreach (DbEntityValidationResult entityErr in ((DbEntityValidationException)ex).EntityValidationErrors)
                                {
                                    foreach (DbValidationError error in entityErr.ValidationErrors)
                                    {
                                        MessageBox.Show(error.ErrorMessage, "Error Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                    }
                                }
                            }
                            else
                            {
                                MessageBox.Show(ex.Message, "Error Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            }
                            //Rollback transaction if exception occurs
                            dbTran.Rollback();
                        }
                    }
                };
            }
        }
Exemplo n.º 28
0
        private void btnUpdateCompanyInfo_Click(object sender, EventArgs e)
        {
            using (var Dbconnection = new MCDEntities())
            {
                using (System.Data.Entity.DbContextTransaction dbTran = Dbconnection.Database.BeginTransaction())
                {
                    try
                    {
                        //CRUD Operations
                        Data.Models.Company UpdateCompany = (from a in Dbconnection.Companies

                                                             where a.CompanyID == CurrentlySelectedCompany.CompanyID
                                                             select a)

                                                            .FirstOrDefault <Data.Models.Company>();

                        UpdateCompany.CompanyName       = txtCompanyName.Text;
                        UpdateCompany.CompanySETANumber = txtSETANumber.Text;
                        UpdateCompany.CompanySicCode    = txtSiCode.Text;
                        UpdateCompany.CompanySARSLevyRegistrationNumber = txtSARSLevyReg.Text;
                        Dbconnection.Entry(UpdateCompany).State         = EntityState.Modified;



                        ////saves all above operations within one transaction
                        Dbconnection.SaveChanges();

                        //commit transaction
                        dbTran.Commit();
                    }
                    catch (Exception ex)
                    {
                        if (ex is DbEntityValidationException)
                        {
                            foreach (DbEntityValidationResult entityErr in ((DbEntityValidationException)ex).EntityValidationErrors)
                            {
                                foreach (DbValidationError error in entityErr.ValidationErrors)
                                {
                                    MessageBox.Show(error.ErrorMessage, "Error Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                }
                            }
                        }
                        else
                        {
                            MessageBox.Show(ex.Message, "Error Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                        //Rollback transaction if exception occurs
                        dbTran.Rollback();
                    }
                }
            };
        }
Exemplo n.º 29
0
        private void resetAdressDefaults(int AddressID = 0)
        {
            using (var Dbconnection = new MCDEntities())
            {
                using (System.Data.Entity.DbContextTransaction dbTran = Dbconnection.Database.BeginTransaction())
                {
                    try
                    {
                        //CRUD Operations
                        CompanyAddresses CurrentCompanyAddress = ((CompanyAddresses)companyAddressesBindingSource.Current);
                        Address          CurrentAddress        = (Address)CurrentlySelectedCompany.Addresses.Where(a => a.AddressID == CurrentCompanyAddress.AddressID).FirstOrDefault();
                        // Dbconnection.Companies.Attach(CurrentlySelectedCompany);
                        foreach (Address Add in CurrentlySelectedCompany.Addresses)
                        {
                            if (AddressID != Add.AddressID)
                            {
                                Add.AddressIsDefault = false;
                                var AddressToupdate = Dbconnection.Addresses.FirstOrDefault(s => s.AddressID == Add.AddressID);
                                AddressToupdate.AddressIsDefault = false;
                            }
                        }


                        ////saves all above operations within one transaction
                        Dbconnection.SaveChanges();

                        //commit transaction
                        dbTran.Commit();
                    }
                    catch (Exception ex)
                    {
                        if (ex is DbEntityValidationException)
                        {
                            foreach (DbEntityValidationResult entityErr in ((DbEntityValidationException)ex).EntityValidationErrors)
                            {
                                foreach (DbValidationError error in entityErr.ValidationErrors)
                                {
                                    MessageBox.Show(error.ErrorMessage, "Error Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                }
                            }
                        }
                        else
                        {
                            MessageBox.Show(ex.Message, "Error Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                        //Rollback transaction if exception occurs
                        dbTran.Rollback();
                    }
                }
            };
        }
        public async Task <JsonResult> PostMerchantCouponStockRequisition(TBL_COUPON_TRANSFER_LOGS objReq)
        {
            initpage();
            var db = new DBContext();

            using (System.Data.Entity.DbContextTransaction ContextTransaction = db.Database.BeginTransaction())
            {
                try
                {
                    var  getSuper = db.TBL_MASTER_MEMBER.FirstOrDefault(x => x.MEM_ID == CurrentMerchant.MEM_ID);
                    long SuperId  = 0;
                    long.TryParse(getSuper.INTRODUCER.ToString(), out SuperId);
                    var    GetCouponType = db.TBL_COUPON_MASTER.FirstOrDefault(x => x.couponType == objReq.COUPON_Name);
                    string GetRefNo      = GetUniqueKey(CurrentMerchant.MEM_ID.ToString());
                    TBL_COUPON_TRANSFER_LOGS objCoupon = new TBL_COUPON_TRANSFER_LOGS()
                    {
                        REFERENCE_NO           = GetRefNo,
                        TO_MEMBER              = 0,
                        FROM_MEMBER            = CurrentMerchant.MEM_ID,
                        REQUEST_DATE           = objReq.REQUEST_DATE,
                        REQUEST_TIME           = DateTime.Now,
                        QTY                    = objReq.QTY,
                        COUPON_TYPE            = GetCouponType.sln,
                        STATUS                 = "Pending",
                        APPROVED_BY            = "",
                        REMARKS                = objReq.REMARKS,
                        COMM_SLAB_ID           = 0,
                        SELL_VALUE_RATE        = 0,
                        GROSS_SELL_VALUE       = 0,
                        NET_SELL_VALUE         = 0,
                        GST_PERCENTAGE         = 0,
                        GST_VALUE              = 0,
                        TDS_PERCENTAGE         = 0,
                        TDS_VALUE              = 0,
                        GST_INPUT              = 0,
                        GST_OUTPUT             = 0,
                        IS_OVERRIDE_SELL_VALUE = false,
                        MEM_ROLE               = 5
                    };
                    db.TBL_COUPON_TRANSFER_LOGS.Add(objCoupon);
                    db.SaveChanges();
                    ContextTransaction.Commit();
                    return(Json("Requisition send to admin", JsonRequestBehavior.AllowGet));
                }
                catch (Exception ex)
                {
                    ContextTransaction.Rollback();
                    throw ex;
                }
            }
        }
Exemplo n.º 31
0
        //chỉnh sửa hóa đơn + ch tiết hóa đơn
        //public static CommandResult Edit1(HOADON c, int userId, int flag, long? warehousePlace, List<string> fileList, string[] listProductId, string[] listQuantity, string[] listQuantityApprove, string[] listPrice)
        public static CommandResult Edit1(BILL c, int userId, string[] listSanphamID, string[] listSoluong, string[] listGia)
        {
            using (var context = new GST_MockProjectEntities())
            {
                using (System.Data.Entity.DbContextTransaction dbTran = context.Database.BeginTransaction())
                {
                    decimal?Tongtien = 0;

                    var HoaDon =
                        context.BILLs.Include(x => x.BILL_DETAIL).First(x => x.ID == c.ID);



                    //xóa danh sách sản phẩm cũ
                    var listwtdOld = HoaDon.BILL_DETAIL;
                    context.BILL_DETAIL.RemoveRange(listwtdOld);

                    //thêm danh sách sản phẩm mới
                    var listwtd = new List <BILL_DETAIL>();
                    for (int i = 0; i < listSanphamID.Length; i++)
                    {
                        var     SanphamID = int.Parse(listSanphamID[i]);
                        var     Soluong   = int.Parse(listSoluong[i]);
                        decimal?Giaban    = null;
                        if (listGia[i] != "")
                        {
                            Giaban   = decimal.Parse(listGia[i]);
                            Tongtien = Tongtien + Giaban;
                        }
                        var cthd = new BILL_DETAIL()
                        {
                            Product_ID = SanphamID,
                            Quantity   = Soluong,
                            Bill_ID    = c.ID,
                            Amount     = Giaban
                        };
                        listwtd.Add(cthd);
                    }
                    context.BILL_DETAIL.AddRange(listwtd);
                    //Chỉnh sửa lại thông tin hóa đơn khi sửa
                    HoaDon.UpdateBy   = userId;
                    HoaDon.UpdateDate = DateTime.Now;
                    HoaDon.Amount     = Tongtien;

                    context.SaveChanges();
                    dbTran.Commit();

                    return(new CommandResult(ResultCode.Success, "Sửa thành công"));
                }
            }
        }
Exemplo n.º 32
0
        private void btnAddActivity_Click(object sender, EventArgs e)
        {

            using (var Dbconnection = new MCDEntities())
            {
                using (System.Data.Entity.DbContextTransaction dbTran = Dbconnection.Database.BeginTransaction())
                {
                    try
                    {
                        //CRUD Operations
                        int ActvityCategoryID = Convert.ToInt32(cboActivityCategory.SelectedValue);
                        Activity act = new Activity()
                        {
                            ActivityCode = txtActivityCode.Text,
                            ActivitiyDescription = txtActivityDescription.Text,
                            ActvityCategoryID = ActvityCategoryID
                        };
                        Dbconnection.Activities.Add(act);
                        ////saves all above operations within one transaction
                        Dbconnection.SaveChanges();

                        //commit transaction
                        dbTran.Commit();
                    }
                    catch (Exception ex)
                    {
                        if (ex is DbEntityValidationException)
                        {
                            foreach (DbEntityValidationResult entityErr in ((DbEntityValidationException)ex).EntityValidationErrors)
                            {
                                foreach (DbValidationError error in entityErr.ValidationErrors)
                                {
                                    MessageBox.Show(error.ErrorMessage, "Error Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                }
                            }
                        }
                        else
                        {
                            MessageBox.Show(ex.Message, "Error Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                        //Rollback transaction if exception occurs
                        dbTran.Rollback();
                    }
                }
            };


            this.populateAvailableModuleActivities();
            this.setAddRemoveControls();
        }
        private void btnUpdateVenueFromForm_Click(object sender, EventArgs e)
        {
            using (var Dbconnection = new MCDEntities())
            {
                using (System.Data.Entity.DbContextTransaction dbTran = Dbconnection.Database.BeginTransaction())
                {
                    try
                    {
                        //CRUD Operations
                        Venue CurrentVenue  = (Venue)venueBindingSource.Current;
                        Venue VenueToUpdate = Dbconnection.Venues.Where(a => a.VenueID == CurrentVenue.VenueID).FirstOrDefault();
                        VenueToUpdate.VenueName                 = this.txtVenueName.Text;
                        VenueToUpdate.VenueMaxCapacity          = (int)this.nudAddUpdateVenueCapacity.Value;
                        Dbconnection.Entry(VenueToUpdate).State = EntityState.Modified;

                        //CurrentVenue.VenueName = this.txtVenueName.Text;
                        //CurrentVenue.VenueMaxCapacity = (int)this.nudAddUpdateVenueCapacity.Value;
                        //Dbconnection.Entry(CurrentVenue).State = System.Data.Entity.EntityState.Modified;
                        ////saves all above operations within one transaction
                        Dbconnection.SaveChanges();

                        //commit transaction
                        dbTran.Commit();
                        this.hideAddEditVenues();
                    }
                    catch (Exception ex)
                    {
                        if (ex is DbEntityValidationException)
                        {
                            foreach (DbEntityValidationResult entityErr in ((DbEntityValidationException)ex).EntityValidationErrors)
                            {
                                foreach (DbValidationError error in entityErr.ValidationErrors)
                                {
                                    MessageBox.Show(error.ErrorMessage, "Error Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                }
                            }
                        }
                        else
                        {
                            MessageBox.Show(ex.Message, "Error Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                        //Rollback transaction if exception occurs
                        dbTran.Rollback();
                    }
                }
            };


            refreshVenues();
        }
Exemplo n.º 34
0
        private void button1_Click(object sender, EventArgs e)
        {
            using (var Dbconnection = new MCDEntities())
            {
                using (System.Data.Entity.DbContextTransaction dbTran = Dbconnection.Database.BeginTransaction())
                {
                    try
                    {
                        //CRUD Operations
                        Student newStudent = new Student()
                        {
                            StudentID       = 0,
                            StudentIDNumber = "",
                            Individual      = new Individual()
                            {
                                IndividualFirstName  = "sdafsadfdsa",
                                IndividualSecondName = "sdf",
                                IndividualLastname   = "4324"
                            }
                        };

                        Dbconnection.Students.Add(newStudent);
                        ////saves all above operations within one transaction
                        Dbconnection.SaveChanges();

                        //commit transaction
                        dbTran.Commit();
                    }
                    catch (Exception ex)
                    {
                        if (ex is DbEntityValidationException)
                        {
                            foreach (DbEntityValidationResult entityErr in ((DbEntityValidationException)ex).EntityValidationErrors)
                            {
                                foreach (DbValidationError error in entityErr.ValidationErrors)
                                {
                                    MessageBox.Show(error.ErrorMessage, "Error Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                }
                            }
                        }
                        else
                        {
                            MessageBox.Show(ex.Message, "Error Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                        //Rollback transaction if exception occurs
                        dbTran.Rollback();
                    }
                }
            };
        }
        public void Creating_DbContextTransaction_specifying_IsolationLevel_opens_connection_if_closed()
        {
            var connectionState = ConnectionState.Closed;
            var mockEntityTransaction = new Mock<EntityTransaction>();
            var mockEntityConnection = new Mock<EntityConnection>();
            mockEntityConnection.SetupGet(m => m.State).Returns(() => connectionState);
            mockEntityConnection.Setup(m => m.Open()).Callback(() => connectionState = ConnectionState.Open);
            mockEntityConnection.Setup(m => m.BeginTransaction(It.IsAny<IsolationLevel>())).Returns(mockEntityTransaction.Object);

            var dbContextTransaction = new DbContextTransaction(mockEntityConnection.Object, IsolationLevel.RepeatableRead);

            mockEntityConnection.Verify(m => m.Open(), Times.Once());
            Assert.Equal(ConnectionState.Open, connectionState);
        }
Exemplo n.º 36
0
        private void btnAddDisability_Click(object sender, EventArgs e)
        {
            using (var Dbconnection = new MCDEntities())
            {
                using (System.Data.Entity.DbContextTransaction dbTran = Dbconnection.Database.BeginTransaction())
                {
                    try
                    {
                        //CRUD Operations
                        CurrentStudentDisablity = new StudentDisability()
                        {
                            DisabilityID           = this.DisablityID,
                            StudentID              = this.StudentID,
                            StudentDisabilityNotes = this.txtStudentDisablityNotes.Text
                        };
                        Dbconnection.StudentDisabilities.Add(CurrentStudentDisablity);


                        ////saves all above operations within one transaction
                        Dbconnection.SaveChanges();

                        //commit transaction
                        dbTran.Commit();
                        Dbconnection.Entry(CurrentStudentDisablity).Reference(a => a.LookupDisability).Load();
                    }
                    catch (Exception ex)
                    {
                        if (ex is DbEntityValidationException)
                        {
                            foreach (DbEntityValidationResult entityErr in ((DbEntityValidationException)ex).EntityValidationErrors)
                            {
                                foreach (DbValidationError error in entityErr.ValidationErrors)
                                {
                                    MessageBox.Show(error.ErrorMessage, "Error Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                }
                            }
                        }
                        else
                        {
                            MessageBox.Show(ex.Message, "Error Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                        //Rollback transaction if exception occurs
                        dbTran.Rollback();
                    }
                    finally{
                        this.Close();
                    }
                }
            };
        }
Exemplo n.º 37
0
        //hàm tạo mới 1 hóa đơn sẽ tự tạo các chi tiết trong nhập xuất kho
        public static CommandResult Create1(WAREHOUSE_TRANSACTION c, int userId, string[] listSanphamID, string[] listSoluong, string[] listGia)

        {
            using (var context = new GST_MockProjectEntities())
            {
                using (System.Data.Entity.DbContextTransaction dbTran = context.Database.BeginTransaction())
                {
                    decimal?Tongtien = 0;
                    c.CreateBy   = userId;
                    c.CreateDate = DateTime.Now;
                    context.WAREHOUSE_TRANSACTION.Add(c);
                    context.SaveChanges();



                    //luu chi tiet san pham
                    var listwtd = new List <WAREHOUSETRANSACTION_DETAIL>();
                    for (var i = 0; i < listSanphamID.Length; i++)
                    {
                        var     SanphamID = int.Parse(listSanphamID[i]);
                        var     Soluong   = decimal.Parse(listSoluong[i]);
                        decimal?price     = null;
                        if (listGia[i] != "")
                        {
                            price    = decimal.Parse(listGia[i]);
                            Tongtien = Tongtien + price;
                        }
                        if (listSoluong[i] != "")
                        {
                            UpdateSoLuongSanPham(c.Warehouse_ID, SanphamID, Soluong);
                        }
                        var wtd = new WAREHOUSETRANSACTION_DETAIL()
                        {
                            WarehouseTransaction_ID = c.ID,
                            Product_ID = SanphamID,
                            Quantity   = Soluong,
                            Amount     = price
                        };
                        listwtd.Add(wtd);
                    }

                    context.WAREHOUSETRANSACTION_DETAIL.AddRange(listwtd);

                    context.SaveChanges();
                    dbTran.Commit();
                    return(new CommandResult());
                }
            }
        }
        public async Task <JsonResult> MemberStatusUpdate(string id, string statusval)
        {
            var db = new DBContext();

            using (System.Data.Entity.DbContextTransaction ContextTransaction = db.Database.BeginTransaction())
            {
                try
                {
                    long memid = long.Parse(id);

                    bool memberstatus = false;
                    if (statusval == "True")
                    {
                        memberstatus = false;
                    }
                    else
                    {
                        memberstatus = true;
                    }
                    var memberlist = db.TBL_MASTER_MEMBER.Where(x => x.MEM_ID == memid).FirstOrDefault();
                    if (statusval == "True")
                    {
                        memberlist.ACTIVE_MEMBER = false;
                    }
                    else
                    {
                        memberlist.ACTIVE_MEMBER = true;
                    }

                    memberlist.IS_DELETED = true;
                    //memberlist.UName = memberlist.UName;
                    //memberlist.PIN = memberlist.PIN;
                    //memberlist.User_pwd = memberlist.User_pwd;
                    //memberlist.BLOCKED_BALANCE = memberlist.BLOCKED_BALANCE;

                    db.Entry(memberlist).State = System.Data.Entity.EntityState.Modified;
                    await db.SaveChangesAsync();

                    ContextTransaction.Commit();
                    return(Json(new { Result = "true" }));
                }
                catch (Exception ex)
                {
                    Logger.Error("Controller:-  CreateMember(PowerAdmin), method:- MemberStatusUpdate (POST) Line No:- 438", ex);
                    ContextTransaction.Rollback();
                    return(Json(new { Result = "false" }));
                }
            }
        }
 public void RollbackTransaction()
 {
     if (this.Transaction != null)
     {
         try
         {
             this.Transaction.Rollback();
         }
         finally
         {
             this.Transaction.Dispose();
             this.Transaction = null;
         }
     }
 }
Exemplo n.º 40
0
        private void btnRemoveVenue_Click(object sender, EventArgs e)
        {
            DialogResult Rtn = MessageBox.Show("Are you sure as this will remove all information Associated with this Venue?", "Confirmation", MessageBoxButtons.YesNo, MessageBoxIcon.Question);

            if (Rtn == DialogResult.Yes)
            {
                using (var Dbconnection = new MCDEntities())
                {
                    using (System.Data.Entity.DbContextTransaction dbTran = Dbconnection.Database.BeginTransaction())
                    {
                        try
                        {
                            //CRUD Operations
                            Venue CurrentVenue = (Venue)venueBindingSource.Current;

                            Dbconnection.Entry(CurrentVenue).State = System.Data.Entity.EntityState.Deleted;

                            ////saves all above operations within one transaction
                            Dbconnection.SaveChanges();

                            //commit transaction
                            dbTran.Commit();
                        }
                        catch (Exception ex)
                        {
                            if (ex is DbEntityValidationException)
                            {
                                foreach (DbEntityValidationResult entityErr in ((DbEntityValidationException)ex).EntityValidationErrors)
                                {
                                    foreach (DbValidationError error in entityErr.ValidationErrors)
                                    {
                                        MessageBox.Show(error.ErrorMessage, "Error Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                    }
                                }
                            }
                            else
                            {
                                MessageBox.Show(ex.Message, "Error Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            }
                            //Rollback transaction if exception occurs
                            dbTran.Rollback();
                        }
                    }
                };

                refreshVenues();
            }
        }
Exemplo n.º 41
0
        public async Task <ActionResult> ChangePassword(MerchantChangePasswordModel value)
        {
            initpage();
            var db = new DBContext();

            using (System.Data.Entity.DbContextTransaction ContextTransaction = db.Database.BeginTransaction())
            {
                try
                {
                    long mem_id     = CurrentMerchant.MEM_ID;
                    var  changepass = db.TBL_MASTER_MEMBER.Where(x => x.MEM_ID == mem_id).FirstOrDefault();
                    if (changepass != null)
                    {
                        changepass.User_pwd        = value.User_pwd;
                        db.Entry(changepass).State = System.Data.Entity.EntityState.Modified;
                        await db.SaveChangesAsync();
                    }
                    var token            = TokenGenerator.GenerateToken();
                    var PasswordResetObj = new TBL_PASSWORD_RESET
                    {
                        ID      = token,
                        EmailID = changepass.EMAIL_ID,
                        Time    = DateTime.Now
                    };
                    db.TBL_PASSWORD_RESET.Add(PasswordResetObj);
                    db.SaveChanges();
                    //throw new Exception();
                    ContextTransaction.Commit();
                    FormsAuthentication.SignOut();
                    Session["MerchantUserId"]   = null;
                    Session["MerchantUserName"] = null;
                    Session.Clear();
                    Session.Remove("MerchantUserId");
                    Session.Remove("MerchantUserName");
                    //return RedirectToAction("Message");
                    return(RedirectToAction("Message", "MerchantLogin", new { area = "Merchant" }));
                }
                catch (Exception ex)
                {
                    ContextTransaction.Rollback();
                    Logger.Error("Controller:-  DistributorPasswordChange(Super), method:- ChangePassword (POST) Line No:- 124", ex);
                    return(RedirectToAction("Exception", "ErrorHandler", new { area = "" }));

                    throw ex;
                    //return View("Error", new HandleErrorInfo(ex, "APILabel", "CreateMember"));
                }
            }
        }
Exemplo n.º 42
0
        private void btnRemoveStudentClientInfo_Click(object sender, EventArgs e)
        {
            using (var Dbconnection = new MCDEntities())
            {
                using (System.Data.Entity.DbContextTransaction dbTran = Dbconnection.Database.BeginTransaction())
                {
                    try
                    {
                        //CRUD Operations
                        CompanyContacts CC          = (CompanyContacts)companyContactsBindingSource.Current;
                        Individual      CCFromCache = CurrentlySelectedCompany.Individuals.Where(a => a.IndividualID == CC.IndividualID).First();

                        CompanyContactDetails CD          = (CompanyContactDetails)companyContactsDetailsBindingSource.Current;
                        ContactDetail         CDFromCache = CCFromCache.ContactDetails.Where(a => a.ContactDetailID == CD.ContactDetailID).First();
                        Dbconnection.ContactDetails.Attach(CDFromCache);
                        Dbconnection.ContactDetails.Remove(CDFromCache);
                        ////saves all above operations within one transaction
                        Dbconnection.SaveChanges();

                        //commit transaction
                        dbTran.Commit();

                        CCFromCache.ContactDetails.Remove(CDFromCache);
                        this.refreshCompanyContactsDetails();
                    }
                    catch (Exception ex)
                    {
                        if (ex is DbEntityValidationException)
                        {
                            foreach (DbEntityValidationResult entityErr in ((DbEntityValidationException)ex).EntityValidationErrors)
                            {
                                foreach (DbValidationError error in entityErr.ValidationErrors)
                                {
                                    MessageBox.Show(error.ErrorMessage, "Error Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                }
                            }
                        }
                        else
                        {
                            MessageBox.Show(ex.Message, "Error Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                        //Rollback transaction if exception occurs
                        dbTran.Rollback();
                    }
                }
            };
        }
Exemplo n.º 43
0
        private void btnUpdateCurriculumCourse_Click(object sender, EventArgs e)
        {
            using (var Dbconnection = new MCDEntities())
            {
                using (System.Data.Entity.DbContextTransaction dbTran = Dbconnection.Database.BeginTransaction())
                {
                    try
                    {
                        //CRUD Operations
                        CurriculumCourse courseObj = (from a in Dbconnection.CurriculumCourses
                                                      where a.CurriculumCourseID == this.CurriculumCourseID
                                                      select a).FirstOrDefault <CurriculumCourse>();

                        courseObj.Cost     = Convert.ToDecimal(txtCourseCost.Text);
                        courseObj.Duration = Convert.ToInt32(nudCourseDuration.Value);
                        courseObj.CurriculumCourseMinimumMaximum.CurriculumCourseMaximum = Convert.ToInt32(nudCourseMaximumAllowed.Value);
                        courseObj.CurriculumCourseMinimumMaximum.CurriculumCourseMinimum = Convert.ToInt32(nudCourseMinimumAllowed.Value);
                        courseObj.CurricullumCourseCode.CurricullumCourseCodeValue       = txtCourseCourseCode.Text;
                        courseObj.CostCode = txtCurrentCostCode.Text;
                        ////saves all above operations within one transaction
                        Dbconnection.SaveChanges();

                        //commit transaction
                        dbTran.Commit();
                    }
                    catch (Exception ex)
                    {
                        if (ex is DbEntityValidationException)
                        {
                            foreach (DbEntityValidationResult entityErr in ((DbEntityValidationException)ex).EntityValidationErrors)
                            {
                                foreach (DbValidationError error in entityErr.ValidationErrors)
                                {
                                    MessageBox.Show(error.ErrorMessage, "Error Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                }
                            }
                        }
                        else
                        {
                            MessageBox.Show(ex.Message, "Error Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                        //Rollback transaction if exception occurs
                        dbTran.Rollback();
                    }
                }
            };
        }
Exemplo n.º 44
0
        //hàm tạo mới 1 hóa đơn sẽ tự tạo các chi tiết hóa đơn
        public static CommandResult Create1(BILL c, int userId, string[] listSanphamID, string[] listSoluong, string[] listGia)

        {
            using (var context = new GST_MockProjectEntities())
            {
                using (System.Data.Entity.DbContextTransaction dbTran = context.Database.BeginTransaction())
                {
                    decimal?Tongtien = 0;

                    c.CreateBy   = userId;
                    c.Amount     = 0;
                    c.CreateDate = DateTime.Now;

                    context.BILLs.Add(c);
                    context.SaveChanges();



                    //luu chi tiet san pham
                    var listwtd = new List <BILL_DETAIL>();
                    for (var i = 0; i < listSanphamID.Length; i++)
                    {
                        decimal?price = null;
                        if (listGia[i] != "")
                        {
                            price    = decimal.Parse(listGia[i]);
                            Tongtien = Tongtien + price;
                        }

                        var wtd = new BILL_DETAIL()
                        {
                            Bill_ID    = c.ID,
                            Product_ID = int.Parse(listSanphamID[i]),
                            Quantity   = int.Parse(listSoluong[i]),
                            Amount     = price
                        };
                        listwtd.Add(wtd);
                    }

                    context.BILL_DETAIL.AddRange(listwtd);
                    c.Amount = Tongtien;
                    context.SaveChanges();
                    dbTran.Commit();
                    return(new CommandResult());
                }
            }
        }
Exemplo n.º 45
0
        public void Commit()
        {
            if (_transaction == null )
            {
                return;
            }

            try
            {
                _transaction.Commit();
                _transaction.Dispose();
            }
            finally
            {
                _transaction = null;
            }
        }
Exemplo n.º 46
0
        public void BeginTransaction()
        {
            try
            {
                if (_currentTransaction != null)
                {
                    return;
                }

                _currentTransaction = Database.BeginTransaction(IsolationLevel.ReadCommitted);
            }
            catch (Exception)
            {
                // todo: log transaction exception
                throw;
            }
        }
Exemplo n.º 47
0
        public virtual void BeginTransaction()
        {
            try
            {
                if (currentTransaction != null)
                {
                    return;
                }

                currentTransaction = Database.BeginTransaction(IsolationLevel.ReadCommitted);
            }
            catch (Exception e)
            {
                if (Logger != null)
                    Logger.LogException(NLog.LogLevel.Error, "Unable to begin transaction.", e);
                throw;
            }
        }
Exemplo n.º 48
0
        public void GeneratesItemWithImageOk()
        {
            DbContextImpl context = new DbContextImpl();
            _transaction = context.Database.BeginTransaction();

            BuildItemWithImage(context);

            context.SaveChanges();

            IList<Image> images = context.Set<Image>().ToList();

            Assert.True(images.Any());

            UriType uriPath = images.First().UriPath;
            Uri uri = uriPath.GetUri();
            Assert.That(uri.ToString(), Is.EqualTo(Path));
            Assert.That(uriPath.Path, Is.EqualTo(Path));
        }
Exemplo n.º 49
0
        public async Task CommitAsync(Exception exception = null)
        {
            try
            {
                if (_dbTransaction != null && exception != null)
                {
                    _dbTransaction.Rollback();
                    Debug.WriteLine($"  Rollback with Skip Transaction {_dbContext.Identifier}");
                    return;
                }

                await _dbContext.SaveChangesAsync().ConfigureAwait(false);
                Debug.WriteLine($"  Commit Transaction {_dbContext.Identifier}");

                _dbTransaction?.Commit();
            }
            catch (Exception)
            {
                if (_dbTransaction?.UnderlyingTransaction.Connection != null)
                {
                    _dbTransaction?.Rollback();
                    Debug.WriteLine($"  Rollback Transaction {_dbContext.Identifier}");
                }

                throw;
            }
            finally
            {
                if (_dbTransaction != null)
                {
                    _dbTransaction.Dispose();
                    _dbTransaction = null;
                    Debug.WriteLine($"  Dispose Transaction {_dbContext.Identifier}");
                }
            }
        }
Exemplo n.º 50
0
        public virtual void CloseTransaction(Exception exception)
        {
            try
            {
                if (currentTransaction != null && exception != null)
                {
                    if (Logger != null)
                        Logger.LogException(NLog.LogLevel.Error, "Rolling back transaction.", exception);
                    currentTransaction.Rollback();
                    return;
                }

                SaveChanges();

                if (currentTransaction != null)
                {
                    currentTransaction.Commit();
                }
            }
            catch (Exception e)
            {
                if (Logger != null)
                    Logger.LogException(NLog.LogLevel.Error, "Unable to commit transaction.", e);

                if (currentTransaction != null && currentTransaction.UnderlyingTransaction.Connection != null)
                {
                    currentTransaction.Rollback();
                }

                throw;
            }
            finally
            {
                if (currentTransaction != null)
                {
                    currentTransaction.Dispose();
                    currentTransaction = null;
                }
            }
        }
Exemplo n.º 51
0
 public DbTransaction(DbContextTransaction transaction)
 {
     this.transaction = transaction;
 }
Exemplo n.º 52
0
 public void StartTransaction(IsolationLevel level)
 {
     _transaction = _dbContext.Database.BeginTransaction(level);
 }
Exemplo n.º 53
0
 private void CleanUpTransaction()
 {
     _transaction = null;
 }
Exemplo n.º 54
0
        /// <summary>
        /// Releases unmanaged and - optionally - managed resources.
        /// </summary>
        /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
        protected virtual void Dispose(bool disposing)
        {
            if (this.transaction != null)
            {
                this.transaction.Dispose();
                this.transaction = null;
            }

            if (this.Context != null)
            {
                this.Context.Database.Connection.Close();
                this.Context.Dispose();
                this.Context = null;
            }
        }
Exemplo n.º 55
0
 public Task StartAsync()
 {
     Debug.WriteLine($"  Start Transaction {_dbContext.Identifier}");
     _dbTransaction = _dbContext.Database.BeginTransaction(IsolationLevel.ReadCommitted);
     return Task.CompletedTask;
 }
 public void Setup()
 {
     DbContext = new AnApiOfIceAndFireContext(NameOrConnectionString);
     DbContext.Database.CreateIfNotExists();
     Transaction = DbContext.Database.BeginTransaction();
 }
Exemplo n.º 57
0
 public void SetUp()
 {
     _db = new HO2Context();
     _repository= new GenericRepository<Mate>(_db);
     _transaction = _db.BeginTransaction();
 }
Exemplo n.º 58
0
 /// <summary>
 /// Opens the transaction.
 /// </summary>
 /// <param name="transactionIsolationLevel">The isolation level.</param>
 public void OpenTransaction(IsolationLevel transactionIsolationLevel = IsolationLevel.ReadCommitted)
 {
     if (this.transaction == null)
     {
         this.transaction = this.Context.Database.BeginTransaction(transactionIsolationLevel);
     }
 }
Exemplo n.º 59
0
 public void BeginTransaction()
 {
     _transaction = _context.Database.BeginTransaction(_isolationLevel);
 }
Exemplo n.º 60
-1
 //Represents a method that rolls back the transaction and cancels all changes
 public void RollBack()
 {
     if (this.trans != null)
     {
         this.trans.Rollback();
         this.trans = null;
     }
 }