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" })); } } }
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 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" })); } } }
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; } } }
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<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")); } } }
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" })); } } }
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(); } } }; }
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)); }
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> 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; } } }
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; } } }
//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")); } } }
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(); } } }; }
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(); } } }; }
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(); } } }; } }
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; } } }
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(); } } }; }
//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")); } } }
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(); }
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(); } } }; }
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 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 async Task <JsonResult> PostAddVenderMaster(TBL_VENDOR_MASTER objVend) { initpage(); var db = new DBContext(); using (System.Data.Entity.DbContextTransaction ContextTransaction = db.Database.BeginTransaction()) { try { var Vender_Info = db.TBL_VENDOR_MASTER.FirstOrDefault(x => x.ID == objVend.ID); if (Vender_Info != null) { Vender_Info.VENDOR_NAME = objVend.VENDOR_NAME; Vender_Info.VENDOR_TYPE = objVend.VENDOR_TYPE; Vender_Info.STATUS = objVend.STATUS; Vender_Info.CREATED_DATE = DateTime.Now; db.Entry(Vender_Info).State = System.Data.Entity.EntityState.Modified; db.SaveChanges(); ContextTransaction.Commit(); return(Json("Vender Information Updated", JsonRequestBehavior.AllowGet)); } else { objVend.CREATED_DATE = DateTime.Now; db.TBL_VENDOR_MASTER.Add(objVend); db.SaveChanges(); ContextTransaction.Commit(); return(Json("Vendor Information Add", JsonRequestBehavior.AllowGet)); } } catch (Exception ex) { ContextTransaction.Rollback(); throw ex; } } }
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" })); } } }
//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()); } } }
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(); } }
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")); } } }
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(); } } }; }
//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()); } } }
private static async Task<Booking> _saveBooking(Booking booking, ResotelContext ctx, DbContextTransaction transaction) { await ctx.SaveChangesAsync(); transaction.Commit(); return booking; }
/// <summary> /// Copies the folderId to this Folder /// </summary> /// <param name="destination"></param> /// <param name="folderId"></param> /// <param name="destinationName"></param> /// <param name="user"></param> /// <param name="context"></param> /// <param name="recursive"></param> /// <param name="dbcxtransaction"></param> public static void CopyFolderHere(this Folder destination, Guid folderId, string destinationName, Principal user, OnlineFilesEntities context = null, bool recursive = true, DbContextTransaction dbcxtransaction = null) { bool createdContext = false; bool createdTransaction = false; bool didRollback = false; if (context == null) { createdContext = true; context = new OnlineFilesEntities(); } if (dbcxtransaction == null) { dbcxtransaction = context.Database.BeginTransaction(); createdTransaction = true; } try { var destSecurity = context.FolderSecurities.Where(d => d.fk_FolderId == destination.pk_FolderId); //Can the user create folders at the destination location? if (destSecurity.Any(d => d.canCreateFolders && user.UserProfile.mySecurityGroups.Contains(d.SecurityObjectId))) { Folder folderToMove = context.Folders.Include(d => d.FolderSecurities).FirstOrDefault(d => d.pk_FolderId == folderId); if (folderToMove == null) throw new Exception("Cannot move a non existant folder"); Folder parentToFolderToMove = context.Folders.Include(x => x.FolderSecurities).FirstOrDefault(d => d.pk_FolderId == folderToMove.fk_ParentFolderId); if (parentToFolderToMove == null) throw new Exception("No parent to folder being moved."); //Does the user have read permission in the folder the item is comming from? if (parentToFolderToMove.FolderSecurities.Any(d => user.UserProfile.mySecurityGroups.Contains(d.SecurityObjectId) && d.canListObjects)) { Folder newFolder = Folder.Create(destinationName, destination.pk_FolderId, user.UserProfile, true); context.SaveChanges(); if (recursive) { //Get all the files that are in the folder being copied. var files = context.Files.Where(d => d.fk_FolderId == folderToMove.pk_FolderId); foreach (File file in files) newFolder.CopyFileHere(file.pk_FileId, file.Name, user, context, dbcxtransaction); //Get all the folders inside the folder we are moving. var folders = context.Folders.Where(d => d.fk_ParentFolderId == folderToMove.pk_FolderId); //Copy the folders to the new location foreach (var folder in folders) newFolder.CopyFolderHere(folder.pk_FolderId, folder.Name, user, context, recursive, dbcxtransaction); } context.SaveChanges(); } else { throw new SecurityException("Not Authorized."); } } else { throw new SecurityException("Not Authorized."); } } catch (Exception) { if (createdTransaction) { didRollback = true; dbcxtransaction.Rollback(); } throw; } finally { if (createdTransaction) { if (!didRollback) dbcxtransaction.Commit(); dbcxtransaction.Dispose(); } if (createdContext) context.Dispose(); } }
/// <summary> /// Copies the fileId to this Folder. /// </summary> /// <param name="destination"></param> /// <param name="fileId"></param> /// <param name="destinationName"></param> /// <param name="user"></param> /// <param name="context"></param> /// <param name="dbcxtransaction"></param> public static void CopyFileHere(this Folder destination, Guid fileId, string destinationName, Principal user, OnlineFilesEntities context = null, DbContextTransaction dbcxtransaction = null) { bool createdContext = false; bool createdTransaction = false; bool didRollback = false; if (context == null) { createdContext = true; context = new OnlineFilesEntities(); } if (dbcxtransaction == null) { dbcxtransaction = context.Database.BeginTransaction(); createdTransaction = true; } try { var destSecurity = context.FolderSecurities.Where(d => d.fk_FolderId == destination.pk_FolderId); //Can the user create files at the destination location? if (destSecurity.Any(d => d.canCreateFiles && user.UserProfile.mySecurityGroups.Contains(d.SecurityObjectId))) { var file = context.Files .Include(x => x.FileSecurities) .Include(x => x.FileDatas) .FirstOrDefault(d => d.pk_FileId == fileId); //Can the user Read the file to be copied? if (file.FileSecurities.Any(f => user.UserProfile.mySecurityGroups.Contains(f.SecurityObjectId) && f.canRead)) { File newFile = File.Create(destination.pk_FolderId, file.Name, user.UserProfile, true); context.SaveChanges(); //Copy the file data using (Stream s = file.OpenReadStream(user)) using (Stream d = newFile.OpenWriteStream(user)) s.CopyTo(d); //Copy the file Security foreach (FileSecurity security in file.FileSecurities) { FileSecurity nsec = context.FileSecurities.FirstOrDefault(d => d.fk_FileId == newFile.pk_FileId && d.SecurityObjectId == security.SecurityObjectId); if (nsec == null) { nsec = new FileSecurity() { canRead = security.canRead, canWrite = security.canWrite, CanDelete = security.CanDelete, fk_FileId = newFile.pk_FileId, SecurityObjectId = security.SecurityObjectId }; context.FileSecurities.Add(nsec); } else { nsec.canRead = nsec.canRead || security.canRead; nsec.CanDelete = nsec.CanDelete || security.CanDelete; nsec.canWrite = nsec.canWrite || security.canWrite; } } context.SaveChanges(); } else { throw new SecurityException("Not Authorized."); } } else { throw new SecurityException("Not Authorized."); } } catch (Exception) { //If we got an error and we created the transaction, roll it back. if (createdTransaction) { dbcxtransaction.Rollback(); didRollback = true; } throw; } finally { if (createdTransaction) { //If we didn't roll back the transaction, commit it. if (!didRollback) dbcxtransaction.Commit(); dbcxtransaction.Dispose(); } if (createdContext) context.Dispose(); } }
/// <summary> /// Will set the permissions for the targetUser, use recursive if you want it to propagate to child file and folders. /// context & dbcxtransaction should be null. /// </summary> /// <param name="FolderId"></param> /// <param name="user"></param> /// <param name="targetUser"></param> /// <param name="canListObjects"></param> /// <param name="canCreateFiles"></param> /// <param name="canCreateFolders"></param> /// <param name="canDelete"></param> /// <param name="canChangePermissions"></param> /// <param name="recursive"></param> /// <param name="context"></param> /// <param name="dbcxtransaction"></param> public static void SetPermissions(Guid FolderId, Principal user, Principal targetUser, bool canListObjects, bool canCreateFiles, bool canCreateFolders, bool canDelete, bool canChangePermissions, bool recursive = false, OnlineFilesEntities context = null, DbContextTransaction dbcxtransaction = null) { bool createdContext = false; bool createdTransaction = false; bool didRollback = false; if (context == null) { createdContext = true; context = new OnlineFilesEntities(); } if (dbcxtransaction == null) { dbcxtransaction = context.Database.BeginTransaction(); createdTransaction = true; } try { Folder target = context.Folders .Include(d => d.FolderSecurities) .FirstOrDefault(d => d.pk_FolderId == FolderId); //Can the user Change Permissions if (target.FolderSecurities.Any(d => d.canChangePermissions && user.UserProfile.mySecurityGroups.Contains(d.SecurityObjectId))) { var secRecord = target.FolderSecurities.FirstOrDefault(d => d.SecurityObjectId == targetUser.UserProfile.SecurityObjectId); if (secRecord == null) { secRecord = new FolderSecurity() { SecurityObjectId = targetUser.UserProfile.SecurityObjectId, canChangePermissions = canChangePermissions, canListObjects = canListObjects, canCreateFolders = canCreateFolders, canCreateFiles = canCreateFiles, canDelete = canDelete, fk_FolderId = target.pk_FolderId }; target.FolderSecurities.Add(secRecord); } else { secRecord.canListObjects = canListObjects; secRecord.canChangePermissions = canChangePermissions; secRecord.canCreateFiles = canCreateFiles; secRecord.canCreateFolders = canCreateFolders; secRecord.canDelete = canDelete; } foreach (File source in context.Files.Where(d => d.fk_FolderId == target.pk_FolderId)) File.SetPermissions(source.pk_FileId, user, targetUser, canListObjects, canCreateFiles, canDelete, context, dbcxtransaction); context.SaveChanges(); if (recursive) foreach (Folder folder in context.Folders.Where(d => d.fk_ParentFolderId == target.pk_FolderId)) SetPermissions(folder.pk_FolderId, user, targetUser, canListObjects, canCreateFiles, canCreateFolders, canDelete, canChangePermissions, recursive, context, dbcxtransaction); } else { throw new SecurityException("Not Authorized."); } } catch (Exception) { if (createdTransaction) { didRollback = true; dbcxtransaction.Rollback(); } throw; } finally { if (createdTransaction) { if (!didRollback) dbcxtransaction.Commit(); dbcxtransaction.Dispose(); } if (createdContext) context.Dispose(); } }
public void Calling_Commit_on_an_already_disposed_DbContextTransaction_still_calls_Commit_on_underlying_EntityTransaction() { var mockEntityTransaction = new Mock<EntityTransaction>(); var mockEntityConnection = new Mock<EntityConnection>(); mockEntityConnection.SetupGet(m => m.State).Returns(ConnectionState.Open); mockEntityConnection.Setup(m => m.BeginTransaction()).Returns(mockEntityTransaction.Object); var dbContextTransaction = new DbContextTransaction(mockEntityConnection.Object); dbContextTransaction.Dispose(); dbContextTransaction.Commit(); mockEntityTransaction.Verify(m => m.Commit(), Times.Once()); }
public void Calling_Commit_twice_on_a_DbContextTransaction_calls_Commit_twice_on_underlying_EntityTransaction() { var mockEntityTransaction = new Mock<EntityTransaction>(); var mockEntityConnection = new Mock<EntityConnection>(); mockEntityConnection.SetupGet(m => m.State).Returns(ConnectionState.Open); mockEntityConnection.Setup(m => m.BeginTransaction()).Returns(mockEntityTransaction.Object); var dbContextTransaction = new DbContextTransaction(mockEntityConnection.Object); dbContextTransaction.Commit(); dbContextTransaction.Commit(); mockEntityTransaction.Verify(m => m.Commit(), Times.Exactly(2)); }
/// <summary> /// Set the permission on a file for the target User. /// </summary> /// <param name="fileId"></param> /// <param name="user"></param> /// <param name="targetUser"></param> /// <param name="canRead"></param> /// <param name="canWrite"></param> /// <param name="canDelete"></param> /// <param name="context"></param> /// <param name="dbcxtransaction"></param> public static void SetPermissions(Guid fileId, Principal user, Principal targetUser, bool canRead, bool canWrite, bool canDelete, OnlineFilesEntities context = null, DbContextTransaction dbcxtransaction = null) { bool createdContext = false; bool createdTransaction = false; bool didRollback = false; if (context == null) { createdContext = true; context = new OnlineFilesEntities(); } if (dbcxtransaction == null) { dbcxtransaction = context.Database.BeginTransaction(); createdTransaction = true; } try { File targetfile = context.Files .Include(d => d.FileSecurities) .FirstOrDefault(d => d.pk_FileId == fileId); if (targetfile == null) throw new Exception("File does not exist."); Folder target = context.Folders.Include(d => d.FolderSecurities).FirstOrDefault(d => d.pk_FolderId == targetfile.fk_FolderId); if (target == null) throw new Exception("Parent Folder does not exist."); //Can the user Change Permissions if (target.FolderSecurities.Any(d => d.canChangePermissions && user.UserProfile.mySecurityGroups.Contains(d.SecurityObjectId))) { var secRecord = targetfile.FileSecurities.FirstOrDefault(d => d.SecurityObjectId == targetUser.UserProfile.SecurityObjectId); if (secRecord == null) { secRecord = new FileSecurity { fk_FileId = targetfile.pk_FileId, CanDelete = canDelete, canRead = canRead, canWrite = canWrite, SecurityObjectId = targetUser.UserProfile.SecurityObjectId }; targetfile.FileSecurities.Add(secRecord); } else { secRecord.canRead = canRead; secRecord.CanDelete = canDelete; secRecord.canWrite = canWrite; } context.SaveChanges(); } else { throw new SecurityException("Not Authorized."); } } catch (Exception) { if (!createdTransaction) throw; didRollback = true; dbcxtransaction.Rollback(); throw; } finally { if (createdTransaction) { if (!didRollback) dbcxtransaction.Commit(); dbcxtransaction.Dispose(); } if (createdContext) context.Dispose(); } }