static void RetrieveMoney(decimal amount, string cardNumber, string cardPin) { if (cardNumber == null) { throw new ArgumentNullException("cardNumber", "Provided card number cannot be null!"); } if (cardPin == null) { throw new ArgumentNullException("cardPIN", "Provided card PIN cannot be null!"); } if (cardNumber.Length != 10) { throw new ArgumentException( "Provided card number is invalid! Card number must consist of 10 digits!"); } if (cardPin.Length != 4) { throw new ArgumentException( "Provided card PIN is invalid! Card PIN must consist of 4 digits!"); } using (var scope = new TransactionScope(TransactionScopeOption.Required, new TransactionOptions() { IsolationLevel = IsolationLevel.RepeatableRead })) { using (var atmContext = new ATMEntities()) { var cardAccount = atmContext.CardAccounts.FirstOrDefault( ca => ca.CardNumber.CompareTo(cardNumber) == 0 && ca.CardPIN.CompareTo(cardPin) == 0); if (cardAccount == null) { scope.Dispose(); throw new TransactionException( "There is no card account with provided card number and PIN!"); } if (cardAccount.CardCash < amount) { scope.Dispose(); throw new TransactionException( "There is no enough money in the account to retrive the requested amount!"); } cardAccount.CardCash -= amount; atmContext.SaveChanges(); } scope.Complete(); } }
///<inheritdoc/> public void Complete() { if (innerScope != null) { this.pm.LogIfVerbose("Completing the TransactionScope"); innerScope.Complete(); innerScope.Dispose(); } CloseConnections(); innerScope = null; }
public static void RetrievesMoney(ATMContext db) { Console.WriteLine("Enter card number:"); string cNumber = Console.ReadLine(); Console.WriteLine("Enter PIN:"); string pin = Console.ReadLine(); Console.WriteLine("Enter money:"); decimal money = decimal.Parse(Console.ReadLine()); using (db) { using (var tran = new TransactionScope()) { var firstCheck = db.CardAccounts.Where(x => x.Number == cNumber).Where(x => x.PIN == pin); if (firstCheck.Count() != 1) { tran.Dispose(); Console.WriteLine("More"); } else { var a = db.CardAccounts.Where(x => x.Number == cNumber).First(); if (a.Cash >= money) { try { a.Cash -= money; db.SaveChanges(); tran.Complete(); Console.WriteLine("OK"); AddToHistory(cNumber, DateTime.Now, money, db); } catch (Exception ex) { Console.WriteLine(ex); tran.Dispose(); Console.WriteLine("No"); } } } } } }
/// <summary> /// Create new post /// </summary> /// <param name="id"></param> /// <param name="postTitle"></param> /// <param name="memberId"></param> /// <param name="fileName"></param> /// <param name="fileUpload"></param> /// <param name="fileType"></param> /// <param name="postStory"></param> /// <param name="postTags"></param> /// <param name="deviceInfo"></param> /// <param name="locationInfo"></param> /// <returns></returns> public int InsertNewPost(string postTitle, string memberId, string fileName, String fileUpload,string fileType, string postStory, string postTags, string deviceInfo, string locationInfo) { using (var tx = new TransactionScope()) { try { var upload = UploadFile(fileUpload, fileName, out fileName); if (!upload) { tx.Dispose(); return -1; // Upload image fail } // Insert new post var post = new Post { PostId = Guid.NewGuid(), PostTitle = postTitle, PostMemberId = new Guid(memberId), PostImage = fileName, PostStory = postStory, PostTags = postTags, DeviceInfo = deviceInfo, LocationInfo = locationInfo, PostCreated = DateTime.Now, PostImageType = fileType, Status = 1 }; DataContext.Posts.Add(post); var i = DataContext.SaveChanges(); tx.Complete(); return i; } catch (Exception) { tx.Dispose(); return -2; // Create post fail } } }
public void Save_on_new_UserNeed_creates_record_in_table() { using (TransactionScope scope = new TransactionScope()) { // Given: an existing Need Need existingNeed = GetExistingNeed(_churchID, CategoryEnum.Clothes, _userID, "I need clothes", "Because I am NAKED", "75240", new DateTime(2009, 5, 15), 1); // When: I create a UserNeed Model.DataContext = GetNewDataContext(); UserNeed userNeed = Model.New<UserNeed>(); userNeed.EntityState = EntityStateEnum.Added; userNeed.UserID = _userID; userNeed.NeedID = existingNeed.ID; userNeed.UserNeedStatusID = (int)UserNeedStatusEnum.Interested; userNeed.Save(); // Then: it should be present in the db Model.DataContext = GetNewDataContext(); UserNeed retrievedUserNeed = Model.New<UserNeed>().GetByKey(userNeed.UserID, userNeed.NeedID); Assert.AreEqual(userNeed.UserID, retrievedUserNeed.UserID); Assert.AreEqual(userNeed.NeedID, retrievedUserNeed.NeedID); Assert.AreEqual(userNeed.Created.ToString(), retrievedUserNeed.Created.ToString()); scope.Dispose(); } }
public void When_using_DTC_HiLo_knows_to_create_isolated_DTC_transaction() { object scalar1, scalar2; using (var session = sessions.OpenSession()) using (var command = session.Connection.CreateCommand()) { command.CommandText = "select next_hi from hibernate_unique_key with (updlock, rowlock)"; scalar1 = command.ExecuteScalar(); } using (var tx = new TransactionScope()) { var generator = sessions.GetIdentifierGenerator(typeof(Person).FullName); Assert.That(generator, Is.InstanceOf<TableHiLoGenerator>()); using(var session = sessions.OpenSession()) { var id = generator.Generate((ISessionImplementor) session, new Person()); } // intentionally dispose without committing tx.Dispose(); } using (var session = sessions.OpenSession()) using (var command = session.Connection.CreateCommand()) { command.CommandText = "select next_hi from hibernate_unique_key with (updlock, rowlock)"; scalar2 = command.ExecuteScalar(); } Assert.AreNotEqual(scalar1, scalar2,"HiLo must run with in its own transaction"); }
public void Explicit_rollback_can_be_used_to_rollback_a_transaction() { EnsureDatabaseInitialized(() => new SimpleModelContext()); using (var tx = new TransactionScope()) { using (var context = new SimpleModelContext()) { var product = new Product { Name = "BestTea" }; context.Products.Add(product); context.SaveChanges(); Assert.Equal(1, GetTransactionCount(context.Database.Connection)); Assert.True(context.Products.Where(p => p.Name == "BestTea").AsNoTracking().Any()); // Rollback System Transaction tx.Dispose(); Assert.False(context.Products.Where(p => p.Name == "BestTea").AsNoTracking().Any()); } } }
public ActionResult Alterar() { if (Session["ADMINISTRADOR"] != null) { using (TransactionScope transacao = new TransactionScope()) { try { using (CarOnlineEntities DB = new CarOnlineEntities()) { DB.SaveChanges(); transacao.Complete(); return View("Consulta"); } } catch (Exception ex) { transacao.Dispose(); return View("Cadastro"); } } } else return RedirectToAction("Index", "Login", new { area = "administrativo" }); }
public void ExpenseCzar_Should_Generate() { int staffid = BusinessUser.Current == null ? -1 : Convert.ToInt32(BusinessUser.Current.UserKey); staffid = BusinessUser.Current == null ? -1 : Convert.ToInt32(BusinessUser.Current.UserKey); //var isolation = IsolationLevel.ReadUncommitted; using (var transaction = new TransactionScope(TransactionScopeOption.Required, new TimeSpan(1, 1, 1))) { var generationDao = DataAccessFactory.Create<GenericDao>(); TestDao testDao = new TestDao(generationDao); int queueId = new ReportGenerationQueueBuilder() .WithGenerationDao(DataAccessFactory.CreateWithSameContext<GenerationDao>(generationDao)) .WithPeriod(201101) .WithReforecastQuarterName("Q0") .WithReportId(testDao.GetReportIdByName("Andre's Unit Test01")) .Build(); AbstractReportGenerator reportGenerator = ReportGeneratorFactory.GetReportGenerator(queueId); Assert.AreEqual(reportGenerator.GetType(), typeof(ExpenseCzarReportGenerator), "expected the report to use the expense czar generator"); reportGenerator.GenerateReport(); transaction.Dispose(); } }
static bool AddUserToGroup(string userName, string groupName) { using (UsersGroupsEntities context = new UsersGroupsEntities()) { using (TransactionScope scope = new TransactionScope()) { if (!context.Groups.Where(g => g.Name == groupName).Any()) { context.Groups.Add(new Group() { Name = groupName }); context.SaveChanges(); } Group groupToAddIn = context.Groups.Where(g => g.Name == groupName).First(); if (groupToAddIn.Users.Where(u => u.Name == userName).Any()) { scope.Dispose(); return false; } else { User newUser = new User() { Name = userName }; groupToAddIn.Users.Add(newUser); context.SaveChanges(); scope.Complete(); return true; } } } }
public void Distribute(Guid saleId) { using (var transaction = new TransactionScope()) { try { Sale sale = this.uow.SaleRepository.FindById(saleId); if (sale == null) throw new ArgumentException("Trying to distribute commissino on non-existing Sale"); IList<SalesPerson> salesPersonsToReceiveCommissions = this.uow .SalesPersonRepository .GetUplineHierarchy(sale.SalesPersonId); IList<SaleCommission> commissionsToDistribute = new List<SaleCommission>(); foreach (var salesPerson in salesPersonsToReceiveCommissions) { SaleCommission distributedCommission = commissionCalculator.ComputeCommission(sale, salesPerson); this.uow.SaleCommissionRepository.Add(distributedCommission); } this.uow.Commit(); transaction.Complete(); } catch (Exception ex) { transaction.Dispose(); throw ex; } } }
public int AddArticle(ArticleM article) { var tran = new TransactionScope(); try { //把文章数据写入数据库 var articleDa = new ArticleDA(); articleDa.AddArticle(article); //为新增加的文章生成静态页面 //文章作者增加积分 //写日志 //提交事务 tran.Complete(); } catch(Exception ex) { throw ex; } finally { tran.Dispose(); } return 1; }
public void DesvincularFormularioPerfil(List<long> listaIdFormulario, long perfilId) { using (var tran = new TransactionScope()) { try { var perfil = _uowSeguridad.PerfilRepositorio.ObtenerPorId(perfilId, "Formularios"); foreach (var id in listaIdFormulario) { var formulario = _uowSeguridad.FormularioRepositorio.ObtenerPorId(id); perfil.Formularios.Remove(formulario); } _uowSeguridad.Commit(); tran.Complete(); } catch (Exception) { tran.Dispose(); throw new Exception("Ocurrió un error al Desvincular un Formulario de un Perfil"); } } }
protected override void On_ActionDelete(object sender, EventArgs e) { TransactionScope ts = new TransactionScope( ); SharedDbConnectionScope ss = new SharedDbConnectionScope( ); try { int cashID = Utilities.ToInt(EVENTARGUMENT); string message; if (OrderBLL.DeleteMemberCash(cashID, AppContext.Context.Company, out message)) { OrderBLL.UpdateBalance( ); ts.Complete( ); } txtMessage.InnerHtml = message; } catch (Exception ex) { Logging.Log("FinanceList->On_ActionDelete", ex, true); txtMessage.InnerHtml = ex.Message; } finally { ss.Dispose( ); ts.Dispose( ); } On_ActionQuery(sender, e); }
public static List<SalesHistoryData> GetSalesHistory() { List<SalesHistoryData> result = new List<SalesHistoryData>(); try { // The encrypted list will timeout for slightly large lists (in the hundreds), so the list is // being grabbed in smaller chunks. Transaction logic is used to lock the list while the list is being // grabbed. TransactionOptions transactionOptions = new TransactionOptions(); transactionOptions.IsolationLevel = IsolationLevel.RepeatableRead; transactionOptions.Timeout = new TimeSpan(0, 2, 0); using (TransactionScope scope = new TransactionScope(TransactionScopeOption.RequiresNew, transactionOptions)) { Console.WriteLine("Test 1: List all Sales Orders"); int take = 5; int count = UserSession.Current.Client.GetSalesOrderListCount(); for (int skip = 0; skip < count; skip = skip + take) { List<SalesHistoryData> salesOrders = UserSession.Current.Client.GetSalesHistory(take, skip).ToList(); result = result.Union(salesOrders).ToList(); } result = result.OrderByDescending(so => so.SalesOrderNumber).ThenBy(so => so.SortOrder).ToList(); //No scope.Complete here as no write tasks are being scoped. scope.Dispose(); } } catch (Exception) { throw; } return result; }
public ActionResult AlterarParametroCargo(int idCargo, string ativo) { string mensagem = ""; using (TransactionScope transacao = new TransactionScope()) { tblCargo cargo = new tblCargo(); try { using (CarOnlineEntities DB = new CarOnlineEntities()) { cargo = DB.tblCargo.FirstOrDefault(c => c.idCargo.Equals(idCargo)); cargo.ativo = ativo; DB.SaveChanges(); transacao.Complete(); return Json(""); } } catch { transacao.Dispose(); mensagem = "Não foi possível salvar o parâmetro.Contate o administrador e tente mais tarde"; var data = new { mensagem }; return Json(data); } } }
public void ValidateUserByActiveDirectory() { using (TransactionScope scope = new TransactionScope()) { Assert.IsTrue(User.VerifyCredentials("*****@*****.**", "xrZ40uye")); scope.Dispose(); } }
public void disposeTransactionScope() { if (_transactionScope != null) { _transactionScope.Dispose(); _transactionScope = null; } }
public void When执行BindImei函数() { var db = new DormManageMvcContext(); var userInfoDao = new UserInfoDao(db); var scope = new TransactionScope(); _result = userInfoDao.BindImei(_userid, _imei); scope.Dispose(); }
public Boolean Facturar(Historicos Historicos, String Numero, Char Clase, DateTime Fecha) { Facturas F = new Facturas(); try { String Mes = Getmes(Fecha); F.concepto = " Comsion Mes " + Mes.ToString(); F.contrato_id = Historicos.contrato_id; F.fecha = DateTime.Now; F.importe = Historicos.importe; F.iva = Historicos.iva; F.neto = Historicos.neto; F.nro_factura = int.Parse(Numero); F.puntoventa_id = 9; F.tipo_factura = Clase; db.Facturas.InsertOnSubmit(F); db.SubmitChanges(); int id = F.factura_id; Historicos UpdateHistorico = (from com in db.GetTable<Historicos>() join o in db.GetTable<Contratos>() on com.contrato_id equals o.contrato_id join Iva in db.GetTable<Codigos_Iva>() on o.codigoiva_id equals Iva.codigoiva_id where ((com.historico_id == Historicos.historico_id)) select com).SingleOrDefault<Historicos>(); UpdateHistorico.factura_id = id; db.SubmitChanges(); transactionScope.Complete(); transactionScope.Dispose(); transactionScope = null; } catch (TransactionAbortedException ex) { transactionScope.Dispose(); transactionScope = null; return false; } catch (SystemException ex) { transactionScope.Dispose(); transactionScope = null; return false; } return true; }
public MemberEditResponseModel CreateAdmin(string username, string password, bool gender, DateTime? birthday, string address, string email, string apiKey) { if (AllowApi) if (!CheckApi(new Guid(apiKey))) return new MemberEditResponseModel() { Code = "-2", Message = "Not allow this function for this API key. Please check again" }; using (var tx = new TransactionScope()) { var adminId = Guid.NewGuid(); password = CommonLib.CreateShaHash(new[] { password, adminId.ToString() }); try { var admin = new AdministatorUser() { AdminAddress = address, AdminBirthday = birthday, AdminEmail = email, AdminGender = gender, AdminId = adminId, AdminPassword = password, AdminUserName = username, AdminJoinDate = DateTime.Now, AdminLocked = 1 }; DataContext.AdministatorUsers.Add(admin); var result = DataContext.SaveChanges(); tx.Complete(); return new MemberEditResponseModel { Code = "1", Message = result.ToString() }; } catch (Exception exception) { tx.Dispose(); return new MemberEditResponseModel() { Code = "-1", Message = exception.Message }; } } }
public void CleanupIsPerformedOnDispose() { bool cleanupCalled = false; var tx = new TransactionScope(); var ctx = new AmbientTransactionContext(); ctx.Cleanup += () => { cleanupCalled = true; }; tx.Dispose(); cleanupCalled.ShouldBe(true); }
public void CleanupIsPerformedEvenIfTransactionIsNotCommitted() { int cleanupCalled = 0; var tx = new TransactionScope(); var ctx = new AmbientTransactionContext(); ctx.Cleanup += () => { cleanupCalled++; }; tx.Dispose(); cleanupCalled.ShouldBe(1); }
public ProcessMsg CancleStored(List<string> trayIds) { using (TransactionScope trans = new TransactionScope()) { using (IUnitOfWork unit = MSSqlHelper.DataContext()) { ProcessMsg msg = new ProcessMsg() { result = true }; try { ITraysRep tr = new TraysRep(unit); List<Trays> tis = tr.GetByIds(trayIds); bool all_synced = true; foreach (Trays ts in tis) { bool synced = false; try { synced = new ApiService().SyncUnStoreContainer(ts.trayId, config.Get("WAREHOUSE")); } catch { all_synced = false; } if (synced == false) { all_synced = false; } ts.sync = synced; ts.status = (int)TrayStatus.Cancled; } unit.Submit(); trans.Complete(); if (all_synced) { msg.AddMessage(ReturnCode.OK, "入库取消成功!"); } else { msg.AddMessage(ReturnCode.OK, "入库取消成功!"); msg.AddMessage(ReturnCode.Warning, "入库取消成功,但WMS同步失败,请稍候重新同步!"); } msg.result = true; } catch (Exception e) { msg.result = false; msg.AddMessage(ReturnCode.Error, "错误:" + e.Message + "\n请联系程序管理员!"); } finally { trans.Dispose(); } return msg; } } }
public void CleanupIsPerformedOnce() { int cleanupCalled = 0; var tx = new TransactionScope(); var ctx = new AmbientTransactionContext(); ctx.Cleanup += () => { cleanupCalled++; }; tx.Complete(); cleanupCalled.ShouldBe(0); tx.Dispose(); cleanupCalled.ShouldBe(1); }
public static void GoAndRollback(Action action) { var transaction = new CommittableTransaction(new TransactionOptions { IsolationLevel = IsolationLevel.ReadCommitted }); using (var scope = new TransactionScope(transaction)) { action(); scope.Dispose(); } }
/// <summary> /// 添加--保存 /// </summary> /// <returns></returns> public MyResponseBase Sys_DictDetail_AddSave() { //return null; using (var scope = new TransactionScope()) { try { #region 重复验证 OperCode = "Sys_Dict.AddRep"; var rescheck = Execute(); if (resp.RespAttachInfo.bError) return resp; if (rescheck.Items.Count() != 0) { resp.RespAttachInfo.ValidationErrors.Add(new ValidationInfo { FieldName = "DText", Message = "该字典已存在" }); return resp; } #endregion #region 最大的DValue OperCode = "Sys_Dict.MaxDValueByCategory"; resp = Execute(); if (resp.RespAttachInfo.bError) return resp; #endregion Item.DValue =(Convert.ToInt32( resp.Obj.ToString()) + 2).ToString(); OperCode = "Sys_Dict.Add"; resp = Execute(); #region (3)事务提交 if (!resp.RespAttachInfo.bError)//判断是否存在错误 { scope.Complete();//提交事务 } #endregion } catch (Exception ex) { resp.RespAttachInfo.ValidationErrors.ErrorMessage = ex.Message; } finally { scope.Dispose();//结束事务 } } return resp; }
public void GuardarRetiro(Retiro retiro) { using (var transaction = new TransactionScope()) { ChequeService chequeService = new ChequeService(); chequeService.insert(retiro.cheque); RetiroRepository repo = new RetiroRepository(); repo.Insert(retiro); transaction.Complete(); transaction.Dispose(); } }
public SolicitudInsActDTO GrabarSolicitud(SolicitudInsActDTO entidad) { using (TransactionScope tran = new TransactionScope()) { try { var solicitud = Mapper.Map<SolicitudDTO, SAF_SOLICITUD>(entidad.Solicitud); if (entidad.Auditor != null) { var auditor = Mapper.Map<AuditorDTO, SAF_AUDITOR>(entidad.Auditor); var resultRegAuditor = this._safAuditorLogic.Registrar(auditor); solicitud.CODAUD = resultRegAuditor.CODAUD; entidad.Auditor.CODAUD = resultRegAuditor.CODAUD; } if (entidad.Soa != null) { var soa = Mapper.Map<SoaDTO, SAF_SOA>(entidad.Soa); var resultRegSoa = this._safSoaLogic.Registrar(soa); solicitud.CODSOA = resultRegSoa.CODSOA; entidad.Soa.CODSOA = resultRegSoa.CODSOA; } var resultRegSolicitud = this._safSolicitudLogic.Registrar(solicitud); tran.Complete(); return entidad; } catch (ExcepcionNegocio) { tran.Dispose(); throw; } catch (Exception) { tran.Dispose(); throw; } } }
public TransactionalUnitOfWorkWindsorScope(IWindsorContainer container) { _transactionScopeWeCreatedAndOwn = new TransactionScope(); try { _unitOfWork = new UnitOfWork(container.Resolve<ISingleContextUseGuard>()); _unitOfWork.AddParticipants(container.ResolveAll<IUnitOfWorkParticipant>()); Transaction.Current.EnlistVolatile(this, EnlistmentOptions.None); } catch(Exception) { _transactionScopeWeCreatedAndOwn.Dispose();//Under no circumstances leave transactions scopes hanging around unmanaged! throw; } }
public void ValidateUserByDefaultPassword() { using (TransactionScope scope = new TransactionScope()) { User.SaveUser(new User() { Password = "******", Email = "*****@*****.**", IsActive = true, CreatedAt = DateTime.Now }); Assert.IsTrue(User.VerifyCredentials("*****@*****.**", "test123")); scope.Dispose(); } }
public void RejectReport() { SupervisorController controller = new SupervisorController(); using (TransactionScope testTransaction = new TransactionScope()) { ViewResult result = controller.UpdateApprovalForTesting(46, "deny", 19) as ViewResult; BlueConsultingContext context = controller.Context(); IEnumerable<Report> reports = context.Reports.Where(x => x.ReportId == 15); foreach (var report in reports) Assert.AreEqual("REJECTED", report.SupervisorApproval); testTransaction.Dispose(); // rollback } }
static void Main() { Console.WriteLine("Sample begins."); using (System.Transactions.TransactionScope txScope = new System.Transactions.TransactionScope()) { Console.WriteLine("TransactionScope constructed."); //The local ID of the current transaction Console.WriteLine("Tx local ID: " + Transaction.Current.TransactionInformation.LocalIdentifier.ToString()); Console.WriteLine("\nLaunching WF using WorkflowInvoker."); //Launch my workflow. WorkflowInvoker is the only way to implicitly flow a current transaction into a new workflow new WorkflowInvoker(BuildWF()).BeginInvoke(null, null); txScope.Complete(); txScope.Dispose(); }; Console.WriteLine("\nSample complete. Press ENTER to exit"); Console.ReadLine(); }
private void ThreadWTSA() { // Implicit Transaction Boolean again = true; while (again) { using (var scope = new System.Transactions.TransactionScope()) { if (ThreadA() == 0) { again = false; scope.Complete(); } else { Console.WriteLine("ThreadWTSA fails and reties"); scope.Dispose(); } } } }
/// <summary> /// Pasa el alcance de transacción a disponibilidad y libera la referencia a este. /// </summary> /// <remarks> /// Al pasar a disponibilidad el ámbito, se aborta implícitamente la transacción. Para aceptar los cambios realizados, se debe ejecutar previamente <see cref="Complete"/>. /// </remarks> /// <date>2008-04-07T00:00:00</date> /// <author>moviedo</author> private void DisposeScope() { _TransactionScope.Dispose(); _TransactionScope = null; }
public void Cleanup() { tran.Dispose(); }
protected override void UnwindScope() { _inner.Dispose(); }
protected void btnUploadFile_Click(object sender, EventArgs e) { string path = Server.MapPath("~/TemporaryFile/"); try { if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } path += uploadFile.FileName; uploadFile.SaveAs(path); DataTable dtLOI = loiControllerr.initiateLOITable(); //dtLOI.Columns.Add("ErrorRemarks"); int successuploadedcount = 0; if (readLOIExcelFile(dtLOI, path)) { if (dtLOI.Rows.Count > 0) { using (System.Transactions.TransactionScope scope = new System.Transactions.TransactionScope()) { try { int errorcount = 0; int Subcon_Id = loiControllerr.Validate_SubconName(dtLOI.Rows[0]["Subcone_Name"].ToString()); int scope_type_id = loiControllerr.Validate_sowdetail(dtLOI.Rows[0]["ScopeOfWork"].ToString()); int RequestId = int.Parse(Request.QueryString["RequestId"]); if (loiControllerr.LOI_UploadRejected_by_FM(RequestId)) { foreach (DataRow dr in dtLOI.Rows) { int RegionId = 0; int ARA_ID = 0; DataTable dtRegion = loiControllerr.Validate_Region(dr["Region"].ToString()); if (dtRegion.Rows.Count > 0) { RegionId = Convert.ToInt32(dtRegion.Rows[0]["RGN_ID"]); ARA_ID = Convert.ToInt32(dtRegion.Rows[0]["ARA_ID"]); } string ErrorRemarks = ValidateLOIData(dr, RequestId, Subcon_Id, RegionId, scope_type_id); if (string.IsNullOrEmpty(ErrorRemarks)) { if (!loiControllerr.LOI_Detail_Upload_by_FM(dr, RequestId, RegionId, ARA_ID)) { errorcount += 1; dr["Remarks"] = "Failed when upload data to db"; } } else { errorcount += 1; dr["Remarks"] = ErrorRemarks; } } } else { errorcount += 1; } lblErrorUpload.Visible = false; Session["dtLOIError"] = null; if (errorcount == 0) { if (loiControllerr.update_loi_price_fromTemp(RequestId)) { try { SendEmail(RequestId); } catch (Exception ex) { } finally { scope.Complete(); ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('File completely uploaded');location.href = '../dashboard/frmDashboardFM.aspx';", true); } } else { scope.Dispose(); Session["dtLOIError"] = dtLOI; lblErrorUpload.Text = "Total Failed: " + errorcount.ToString(); lblErrorUpload.Visible = true; ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('upload data failed');", true); } } else { scope.Dispose(); Session["dtLOIError"] = dtLOI; lblErrorUpload.Text = "Total Failed: " + errorcount.ToString(); lblErrorUpload.Visible = true; ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('upload data failed');", true); } } catch { scope.Dispose(); ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('upload data failed');", true); } } } else { ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('There is no data to be uploaded');", true); } } else { ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('Failed to read excel file');", true); } } catch (Exception ex) { ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('Failed to upload data');", true); } finally { if (File.Exists(path)) { File.Delete(path); } } }
public void AfterTest(TestDetails testDetails) { _transactionScope.Dispose(); }