public SigmaResultType AddEquipment(TypeEquipment objEquipment) { TypeUserInfo userinfo = AuthMgr.GetUserInfo(); SigmaResultType result = new SigmaResultType(); TransactionScope scope = null; // Get connection string string connStr = ConnStrHelper.getDbConnString(); List<SqlParameter> paramList = new List<SqlParameter>(); paramList.Add(new SqlParameter("@EquipmentCodeMain", objEquipment.EquipmentCodeMain.Trim())); paramList.Add(new SqlParameter("@EquipmentCodeSub", objEquipment.EquipmentCodeSub.Trim())); paramList.Add(new SqlParameter("@Description", objEquipment.Description.Trim())); paramList.Add(new SqlParameter("@ThirdLevel", objEquipment.ThirdLevel.Trim())); paramList.Add(new SqlParameter("@Spec", objEquipment.Spec.Trim())); paramList.Add(new SqlParameter("@EquipmentType", objEquipment.EquipmentType.Trim())); paramList.Add(new SqlParameter("@CreatedBy", userinfo.SigmaUserId.Trim())); paramList.Add(new SqlParameter("@ModelNumber", objEquipment.ModelNumber.Trim())); SqlParameter outParam = new SqlParameter("@NewId", SqlDbType.Int); outParam.Direction = ParameterDirection.Output; paramList.Add(outParam); using (scope = new TransactionScope(TransactionScopeOption.Required)) { result.AffectedRow = SqlHelper.ExecuteNonQuery(connStr, CommandType.StoredProcedure, "usp_AddEquipment", paramList.ToArray()); result.IsSuccessful = true; result.ScalarValue = (int)outParam.Value; scope.Complete(); } return result; }
public SigmaResultType AddCWA(TypeCWA objCWA) { TypeUserInfo userinfo = AuthMgr.GetUserInfo(); TransactionScope scope = null; SigmaResultType result = new SigmaResultType(); // Get connection string string connStr = ConnStrHelper.getDbConnString(); List<SqlParameter> paramList = new List<SqlParameter>(); paramList.Add(new SqlParameter("@ProjectId", Utilities.ToInt32(userinfo.CurrentProjectId.ToString().Trim()))); paramList.Add(new SqlParameter("@Name", objCWA.Name.Trim())); paramList.Add(new SqlParameter("@Area", objCWA.Area)); paramList.Add(new SqlParameter("@Description", objCWA.Description.Trim())); paramList.Add(new SqlParameter("@CreatedBy", userinfo.SigmaUserId.Trim())); SqlParameter outParam = new SqlParameter("@NewId", SqlDbType.Int); outParam.Direction = ParameterDirection.Output; paramList.Add(outParam); using (scope = new TransactionScope(TransactionScopeOption.Required)) { result.AffectedRow = SqlHelper.ExecuteNonQuery(connStr, CommandType.StoredProcedure, "usp_AddCWA", paramList.ToArray()); result.IsSuccessful = true; result.ScalarValue = (int)outParam.Value; scope.Complete(); } return result; }
public void TransactionScopeCompleted3() { Assert.Throws<InvalidOperationException>(() => { using (TransactionScope scope = new TransactionScope()) { scope.Complete(); scope.Complete(); } }); }
protected virtual T ExecuteCommand <T>(Func <IDbConnection, IDbStatement, T> command) { ThrowWhenDisposed(); using (TransactionScope scope = OpenCommandScope()) using (IDbConnection connection = _connectionFactory.Open()) using (IDbTransaction transaction = _dialect.OpenTransaction(connection)) using (IDbStatement statement = _dialect.BuildStatement(scope, connection, transaction)) { try { if (Logger.IsVerboseEnabled) { Logger.Verbose(Messages.ExecutingCommand); } T rowsAffected = command(connection, statement); if (Logger.IsVerboseEnabled) { Logger.Verbose(Messages.CommandExecuted, rowsAffected); } transaction?.Commit(); scope?.Complete(); return(rowsAffected); } catch (Exception e) { if (Logger.IsDebugEnabled) { Logger.Debug(Messages.StorageThrewException, e.GetType()); } if (!RecoverableException(e)) { throw new StorageException(e.Message, e); } if (Logger.IsInfoEnabled) { Logger.Info(Messages.RecoverableExceptionCompletesScope); } scope?.Complete(); throw; } } }
public void CommitTransaction(bool startNewTransaction = false) { Trace.TraceWarning("!!!Commit {0} - {1}", typeof(T).Name, _index); if (_useTransaction) { switch (_transactionType) { case TransactionTypes.DbTransaction: if (_transaction?.Connection != null) { _transaction.Commit(); } break; case TransactionTypes.TransactionScope: _transactionScope?.Complete(); break; } if (startNewTransaction) { StartTransaction(); } } }
/// <summary> /// 创建报表文件格式 /// </summary> /// <param name="entity"></param> /// <param name="list"></param> /// <returns></returns> public int Create(ReportsEntity entity,List<ReportParamsEntity> list) { if (!entity.ReportNum.IsEmpty()) { return Update(entity,list); } int line = 0; using (TransactionScope ts = new TransactionScope()) { entity.ReportNum = entity.ReportNum.IsEmpty() ? SequenceProvider.GetSequence(typeof(ReportsEntity)) : entity.ReportNum; entity.IncludeAll(); line += this.Reports.Add(entity); if (!list.IsNullOrEmpty()) { foreach (ReportParamsEntity item in list) { item.ParamNum = item.ParamNum.IsEmpty() ? SequenceProvider.GetSequence(typeof(ReportParamsEntity)) : item.ParamNum; item.ReportNum = entity.ReportNum; item.IncludeAll(); } this.ReportParams.Add(list); } ts.Complete(); } return line; }
public static bool NoptienTamung(NoitruTamung objTamung) { try { using (var scope = new TransactionScope()) { using (var sh = new SharedDbConnectionScope()) { objTamung.Save(); KcbLuotkham objKcbLuotkham = Utility.getKcbLuotkham(objTamung.IdBenhnhan, objTamung.MaLuotkham); if (objKcbLuotkham != null) { objKcbLuotkham.IsNew = false; objKcbLuotkham.MarkOld(); if (Utility.ByteDbnull(objKcbLuotkham.TrangthaiNoitru, 0) == 1) { objKcbLuotkham.TrangthaiNoitru = 2; objKcbLuotkham.Save(); } } } scope.Complete(); } return true; } catch (Exception ex) { return false; } }
public SigmaResultType AddSigmaUserSigmaRole(TypeSigmaUserSigmaRole objSigmaUserSigmaRole) { TypeUserInfo userinfo = AuthMgr.GetUserInfo(); objSigmaUserSigmaRole.ProjectId = userinfo.CurrentProjectId; objSigmaUserSigmaRole.CreatedBy = userinfo.SigmaUserId; TransactionScope scope = null; SigmaResultType result = new SigmaResultType(); // Get connection string string connStr = ConnStrHelper.getDbConnString(); List<SqlParameter> paramList = new List<SqlParameter>(); paramList.Add(new SqlParameter("@SigmaRoleId", objSigmaUserSigmaRole.SigmaRoleId)); paramList.Add(new SqlParameter("@SigmaUserId", objSigmaUserSigmaRole.SigmaUserId)); paramList.Add(new SqlParameter("@ReportTo", objSigmaUserSigmaRole.ReportTo)); paramList.Add(new SqlParameter("@ReportToRole", objSigmaUserSigmaRole.ReportToRole)); paramList.Add(new SqlParameter("@IsDefault", objSigmaUserSigmaRole.IsDefault)); paramList.Add(new SqlParameter("@ProjectId", objSigmaUserSigmaRole.ProjectId)); paramList.Add(new SqlParameter("@CreatedBy", objSigmaUserSigmaRole.CreatedBy)); using (scope = new TransactionScope(TransactionScopeOption.Required)) { result.AffectedRow = SqlHelper.ExecuteNonQuery(connStr, CommandType.StoredProcedure, "usp_AddSigmaUserSigmaRole", paramList.ToArray()); result.IsSuccessful = true; scope.Complete(); } return result; }
public SigmaResultType AddProjectUserDiscipline(TypeProjectUserDiscipline objProjectUserDiscipline) { TypeUserInfo userinfo = AuthMgr.GetUserInfo(); objProjectUserDiscipline.ProjectId = userinfo.CurrentProjectId; TransactionScope scope = null; SigmaResultType result = new SigmaResultType(); // Get connection string string connStr = ConnStrHelper.getDbConnString(); List<SqlParameter> paramList = new List<SqlParameter>(); paramList.Add(new SqlParameter("@ProjectId", objProjectUserDiscipline.ProjectId)); paramList.Add(new SqlParameter("@SigmaUserId", objProjectUserDiscipline.SigmaUserId)); paramList.Add(new SqlParameter("@DisciplineCode", objProjectUserDiscipline.DisciplineCode)); SqlParameter outParam = new SqlParameter("@NewId", SqlDbType.Int); outParam.Direction = ParameterDirection.Output; paramList.Add(outParam); using (scope = new TransactionScope(TransactionScopeOption.Required)) { result.AffectedRow = SqlHelper.ExecuteNonQuery(connStr, CommandType.StoredProcedure, "usp_AddProjectUserDiscipline", paramList.ToArray()); result.IsSuccessful = true; scope.Complete(); } return result; }
public static Boolean AddTariffProperty(List<DAL.TariffInProperty> tariff) { Boolean flag = false; using (TransactionScope scope = new TransactionScope()) { using (var context = new SycousCon()) { try { foreach (DAL.TariffInProperty item in tariff) { context.TariffInProperties.AddObject(item); } context.SaveChanges(); context.AcceptAllChanges(); scope.Complete(); flag = true; } catch (Exception ex) { context.Dispose(); throw; } }// using return flag; }// trans }
/// <summary> /// 作者:Vincen /// 时间:2014.04.30 /// 描述:创建消息 /// </summary> /// <param name="model"></param> /// <param name="loginUserId"></param> /// <returns></returns> public static bool CreateMessage(MessageModel model, int loginUserId) { try { using (var tran = new TransactionScope()) { using (var edb = new EmeEntities()) { var msg = new Message() { MessageType = model.MessageType, Subject = model.Subject, MContent = model.MContent, Receivers = model.Receiver.Count, Openers = 0, Status = ConvertEnum.StatusTypeForActive, CreateBy = model.CreateBy, CreateTime = model.CreateTime }; edb.Entry(msg).State = EntityState.Added; edb.SaveChanges(); var receiver = from a in model.Receiver select new MessageReceiver() { MessageId = msg.Id, Receiver = a, IsRead = false, Status = ConvertEnum.StatusTypeForActive, CreateBy = model.CreateBy, CreateTime = model.CreateTime }; foreach (var messageReceiver in receiver) { edb.Entry(messageReceiver).State = EntityState.Added; } var result = edb.SaveChanges() > 0; tran.Complete(); return result; } } } catch (Exception e) { // 异常日志消息队列 Common.MSMQ.QueueManager.AddExceptionLog(new ExceptionLogs() { ExceptionType = CommonHelper.To<int>(ExceptionType.Function), Message = string.Format("EmeBLL-CreateMessage:{0};{1};{2}", e.Message, e.InnerException.Message, e.HelpLink), IsTreat = false, CreateBy = loginUserId, CreateTime = DateTime.Now }); return false; } }
public void InitialiseDatabase(Result result) { if (!result.Succeeded) return; SqlConnection conn = null; try { using (TransactionScope scope = new TransactionScope()) { conn = (SqlConnection)DatabaseManager.DatabaseEngine.GetConnection(); SqlServer2005Database db = (SqlServer2005Database)DatabaseManager.DatabaseEngine; Result r = db.ExecuteScript(conn, ResourceLoader.LoadTextResource("Sprocket.Web.FileManager.SqlServer2005.scripts.sql")); if (!r.Succeeded) { result.SetFailed(r.Message); return; } scope.Complete(); } } finally { DatabaseManager.DatabaseEngine.ReleaseConnection(conn); } return; }
public static Boolean DeletedDirectDebit(DirectDebit debit) { using (TransactionScope scope = new TransactionScope()) { Boolean bol = false; using (var context = new SycousCon()) { try { var Update = context.DirectDebits.Where(c => c.ID == debit.ID&& c.IsDeleted==0&&c.IsApproved==0); foreach (DirectDebit p in Update) { p.IsDeleted = 2; p.ModifyBy = debit.ModifyBy; p.ModifyDate = DateTime.Now; }// context.SaveChanges(); context.AcceptAllChanges(); scope.Complete(); context.Dispose(); bol = true; } catch (Exception ex) { context.Dispose(); throw; } }// using return bol; } //trans }
public string[] UpdateData(IEntityBase value) { EConfigHoraSet objE = (EConfigHoraSet)value; object[] objRet = null; try { using (TransactionScope tx = new TransactionScope()) { this.DeleteDetail(objE.ColConfigHora, true); //objRet = this.UpdateMaster(objE.EConfigHora); this.UpdateDetail(objE.ColConfigHora, objRet); tx.Complete(); } if (objRet == null) return null; return new String[] { objRet[0].ToString() }; } catch (Exception ex) { throw ex; } }
public int DeleteData(IEntityBase value) { EConfigHoraSet objE = (EConfigHoraSet)value; try { using (TransactionScope tx = new TransactionScope()) { this.DeleteDetail(objE.ColConfigHora, false); //this.DeleteMaster(objE.EConfigHora); tx.Complete(); } return 1; } catch (Exception ex) { throw ex; } }
public SigmaResultType AddCustomFieldWithEquipmentCustomField(TypeCustomField objCustomField) { TypeUserInfo userinfo = AuthMgr.GetUserInfo(); TransactionScope scope = null; SigmaResultType result = new SigmaResultType(); SigmaResultType customField = new SigmaResultType(); SigmaResultType EquipmentCustomField = new SigmaResultType(); TypeEquipmentCustomField typeEquipmentCustomField = new TypeEquipmentCustomField(); typeEquipmentCustomField.EquipmentId = objCustomField.Parentid; typeEquipmentCustomField.Value = objCustomField.Value; typeEquipmentCustomField.CreatedBy = userinfo.SigmaUserId; typeEquipmentCustomField.UpdatedBy = userinfo.SigmaUserId; using (scope = new TransactionScope(TransactionScopeOption.Required)) { CustomFieldMgr custom = new CustomFieldMgr(); customField = custom.AddCustomField(objCustomField); typeEquipmentCustomField.CustomFieldId = customField.ScalarValue; EquipmentCustomField = AddEquipmentCustomField(typeEquipmentCustomField); scope.Complete(); } return result; }
public void InsertAssignDetail(KcbChidinhcl objKcbChidinhcls, KcbLuotkham objLuotkham, KcbChidinhclsChitiet[] assignDetail) { using (var scope = new TransactionScope()) { if (objLuotkham == null) return; foreach (KcbChidinhclsChitiet objAssignDetail in assignDetail) { log.Info("Them moi thong tin cua phieu chi dinh chi tiet voi ma phieu Assign_ID=" + objKcbChidinhcls.IdChidinh); TinhCLS.TinhGiaChiDinhCLS(objLuotkham, objAssignDetail); objAssignDetail.IdDoituongKcb = Utility.Int16Dbnull(objLuotkham.IdDoituongKcb); objAssignDetail.IdChidinh = Utility.Int32Dbnull(objKcbChidinhcls.IdChidinh); objAssignDetail.IdKham = Utility.Int32Dbnull(objKcbChidinhcls.IdKham, -1); decimal PtramBHYT = Utility.DecimaltoDbnull(objLuotkham.PtramBhyt, 0); TinhCLS.GB_TinhPhtramBHYT(objAssignDetail, objLuotkham, PtramBHYT); objAssignDetail.MaLuotkham = objKcbChidinhcls.MaLuotkham; objAssignDetail.IdBenhnhan = objKcbChidinhcls.IdBenhnhan; if (Utility.Int32Dbnull(objAssignDetail.SoLuong) <= 0) objAssignDetail.SoLuong = 1; if (objAssignDetail.IdChitietchidinh <= 0) { objAssignDetail.IsNew = true; objAssignDetail.Save(); } else { objAssignDetail.MarkOld(); objAssignDetail.IsNew = false; objAssignDetail.Save(); } } scope.Complete(); } }
public static String AddProperty(Property prop) { String ReturnpropertyID = String.Empty; //if (!(IsExistingProperty(prop))) //{ using (TransactionScope scope = new TransactionScope()) { using (var context = new SycousCon()) { try { context.Properties.AddObject(prop); context.SaveChanges(); scope.Complete(); context.AcceptAllChanges(); ReturnpropertyID = prop.ID.ToString(); } catch (Exception ex) { context.Dispose(); throw; } }// }// using //}//if return ReturnpropertyID; }
public int DeleteData(IEntityBase value) { EProcPlani objE = (EProcPlani)value; try { using (TransactionScope tx = new TransactionScope()) { //this.DeleteDetail(objE.EProcPlani, false); this.DeleteMaster(objE); tx.Complete(); } return 1; } catch { return 0; } }
public ActionResult Disassociate(string provider, string providerUserId) { string ownerAccount = OAuthWebSecurity.GetUserName(provider, providerUserId); ManageMessageId? message = null; // Only disassociate the account if the currently logged in user is the owner if (ownerAccount == User.Identity.Name) { // Use a transaction to prevent the user from deleting their last login credential using ( var scope = new TransactionScope(TransactionScopeOption.Required, new TransactionOptions { IsolationLevel = IsolationLevel.Serializable })) { bool hasLocalAccount = OAuthWebSecurity.HasLocalAccount(WebSecurity.GetUserId(User.Identity.Name)); if (hasLocalAccount || OAuthWebSecurity.GetAccountsFromUserName(User.Identity.Name).Count > 1) { OAuthWebSecurity.DeleteAccount(provider, providerUserId); scope.Complete(); message = ManageMessageId.RemoveLoginSuccess; } } } return RedirectToAction("Manage", new { Message = message }); }
public ActionResult UpdateDynamicValues(List<DynamicValue> lstValues) { try { using (var scope = new TransactionScope()) { using (var sp = new SharedDbConnectionScope()) { foreach (DynamicValue _object in lstValues) { if (_object.Id > 0) { _object.MarkOld(); _object.IsNew = false; _object.Save(); } else//Insert { _object.IsNew = true; _object.Save(); } } } scope.Complete(); return ActionResult.Success; } } catch (Exception exception) { Utility.ShowMsg(exception.Message); return ActionResult.Error; } }
public void Editar(Partido item) { if (Eleicao.Iniciou) { throw new Exception("As eleições iniciaram não é possivel fazer essa operação"); } List<Partido> partidoEncontrado = FindByName(item.Nome); if (partidoEncontrado.FindAll(partido => partido.Nome == item.Nome).Count != 0 && partidoEncontrado.FindAll(partido => partido.Slogan == item.Slogan).Count != 0) { throw new Exception("Nome e slogan ja existentes."); } using (TransactionScope transacao = new TransactionScope()) using (IDbConnection connection = new SqlConnection(connectionString)) { IDbCommand comando = connection.CreateCommand(); comando.CommandText = "UPDATE Partido SET Nome = @paramNome, Slogan = @paramSlogan, Sigla = @paramSigla WHERE IDPartido = @paramIDPartido"; comando.AddParameter("paramNome", item.Nome); comando.AddParameter("paramSlogan", item.Slogan); comando.AddParameter("paramSigla", item.Sigla); comando.AddParameter("paramIDPartido", item.Id); connection.Open(); comando.ExecuteNonQuery(); transacao.Complete(); connection.Close(); } }
protected virtual void Dispose(bool disposing) { if (!disposing || _disposed) { return; } _disposed = true; _position = 0; _current = null; _reader?.Dispose(); _reader = null; _command?.Dispose(); // queries do not modify state and thus calling Complete() on a so-called 'failed' query only // allows any outer transaction scope to decide the fate of the transaction _scope?.Complete(); foreach (var dispose in _disposable) { dispose.Dispose(); } }
//删除区间 protected void Button2_Command(object sender, CommandEventArgs e) { int regionId = Convert.ToInt32(e.CommandArgument); bool success = false; using (TransactionScope ts = new TransactionScope()) { DataTable lists = item_bll.GetItemListByRegionId(userId, regionId); foreach (DataRow dr in lists.Rows) { int itemId = Convert.ToInt32(dr["ItemID"]); int itemAppId = Convert.ToInt32(dr["ItemAppID"]); success = item_bll.DeleteItem(userId, itemId, itemAppId); if (!success) { break; } } ts.Complete(); } if (success) { Utility.Alert(this, "删除成功。", "QuJianTongJi.aspx"); } else { Utility.Alert(this, "删除失败!"); } }
/// <summary> /// 添加选课 /// </summary> /// <param name="studentNo">学号</param> /// <param name="courseNo">课程编号</param> public void AddChooseCourse(string studentNo, string courseNo, string termTag, string ClassID) { try { string sql = "INSERT INTO [USTA].[dbo].[usta_CoursesStudentsCorrelation] ([studentNo],[courseNo],[Year],[ClassID]) VALUES(@studentNo ,@courseNo,@Year,@ClassID)"; SqlParameter[] parameters = { new SqlParameter("@courseNo", SqlDbType.NChar,20), new SqlParameter("@studentNo", SqlDbType.NChar,10), new SqlParameter("@Year", SqlDbType.NVarChar,50), new SqlParameter("@ClassID", SqlDbType.NVarChar,50) }; parameters[0].Value = courseNo; parameters[1].Value = studentNo; parameters[2].Value = termTag; parameters[3].Value = ClassID; using (TransactionScope scope = new TransactionScope()) { SqlHelper.ExecuteNonQuery(conn, CommandType.Text, sql, parameters); UpdateSchoolWordAndExperiment(studentNo, courseNo); scope.Complete(); } } catch (Exception ex) { MongoDBLog.LogRecord(ex); CommonUtility.RedirectUrl(); } finally { conn.Close(); } }
public static ActionResult Capnhatgia(long id, decimal don_gia, byte cachtinh_gia) { try { using (var scope = new TransactionScope()) { using (var sh = new SharedDbConnectionScope()) { new Update(NoitruPhanbuonggiuong.Schema) .Set(NoitruPhanbuonggiuong.Columns.DonGia).EqualTo(don_gia) .Set(NoitruPhanbuonggiuong.Columns.CachtinhGia).EqualTo(cachtinh_gia) .Where(NoitruPhanbuonggiuong.Columns.Id).IsEqualTo(id).Execute(); } scope.Complete(); return ActionResult.Success; } } catch (Exception exception) { Utility.CatchException(exception); return ActionResult.Error; } }
public int AddClient(Client client) { using (TransactionScope scope = new TransactionScope()) { DbParameter parameter = null; parameter = Db.CreateParameter("ClientId", DbType.Int32, 8); parameter.Direction = ParameterDirection.Output; Db.ExecuteNonQuery("usp_Client_InsertClientDetails", CommandType.StoredProcedure, new DbParameter[] { parameter, Db.CreateParameter("ClientName", client.ClientName), Db.CreateParameter("ContactName", client.ContactName), Db.CreateParameter("Phone", client.Phone), Db.CreateParameter("Email", client.Email), Db.CreateParameter("TIN", client.TIN), Db.CreateParameter("PrivateClientDetails", client.PrivateClientDetails), Db.CreateParameter("OtherClientDetails", client.OtherClientDetails), Db.CreateParameter("BillingAddress", client.BillingAddress), Db.CreateParameter("City", client.City), Db.CreateParameter("StateCode", client.StateCode), Db.CreateParameter("Zip", client.Zip), Db.CreateParameter("Country", client.Country), Db.CreateParameter("ShipToDifferentAddress", client.ShipToDifferentAddress), Db.CreateParameter("ShippingAddress", client.ShippingAddress), Db.CreateParameter("ShippingCity", client.ShippingCity), Db.CreateParameter("ShippingStateCode", client.ShippingStateCode), Db.CreateParameter("ShippingZip", client.ShippingZip), Db.CreateParameter("ShippingCountry", client.ShippingCountry), Db.CreateParameter("Status", client.Status) }); scope.Complete(); return (int)parameter.Value; } }
public static ActionResult CapnhatSoluong(long id, int soluongngay,byte cachtinhsoluong) { try { using (var scope = new TransactionScope()) { using (var sh = new SharedDbConnectionScope()) { new Update(NoitruPhanbuonggiuong.Schema) .Set(NoitruPhanbuonggiuong.Columns.SoLuong).EqualTo(soluongngay) .Set(NoitruPhanbuonggiuong.Columns.CachtinhSoluong).EqualTo(cachtinhsoluong) .Where(NoitruPhanbuonggiuong.Columns.Id).IsEqualTo(id).Execute(); } scope.Complete(); return ActionResult.Success; } } catch (Exception exception) { Utility.CatchException(exception); return ActionResult.Error; } }
/// <summary> /// データ登録 /// </summary> /// <param name="query">SQL文字列</param> /// <param name="args">パラメータ</param> /// <returns>True:正常終了 / False:エラー</returns> public static int Save(string query, params SQLiteParameter[] args) { using (var connector = new SqliteConnector()) using (var command = new SQLiteCommand(query, connector.Connection)) { SqliteCommander.SetParameters(command, args); connector.Open(); int result = 0; using (var tran = new TransactionScope()) { result = command.ExecuteNonQuery(); if (0 < result) { tran.Complete(); } } connector.Close(); return result; } }
public void Abandon(int masterSysNo, int userSysNo) { TransactionOptions options = new TransactionOptions(); options.IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted; options.Timeout = TransactionManager.DefaultTimeout; using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required, options)) { //�����dz�ʼ״̬ POInfo dbInfo = LoadPO(masterSysNo); if ( dbInfo == null ) throw new BizException("does not exist this po sysno"); if ( dbInfo.Status != (int)AppEnum.POStatus.Origin ) throw new BizException("status is not origin now, abandon failed"); //���� ���š�״̬������� Hashtable ht = new Hashtable(4); ht.Add("SysNo", masterSysNo); ht.Add("Status", (int)AppEnum.POStatus.Abandon); if ( 1!=new PODac().UpdateMaster(ht)) throw new BizException("expected one-row update failed, verify failed "); ProductIDManager.GetInstance().AbandonProductIDsByPO(masterSysNo); scope.Complete(); } }
public static Boolean CreateDirectDebit(DirectDebit mdirectdebit) { Boolean flag = false; using (TransactionScope scope = new TransactionScope()) { using (var context = new SycousCon()) { try { context.DirectDebits.AddObject(mdirectdebit); context.SaveChanges(); scope.Complete(); context.AcceptAllChanges(); flag = true; } catch (Exception ex) { context.Dispose(); throw; } } } return flag; }
public void Bug() { string connectionString = cfg.GetProperty("connection.connection_string"); int id = -1; using (TransactionScope ts = new TransactionScope()) { // Enlisting DummyEnlistment as a durable resource manager will start // a DTC transaction System.Transactions.Transaction.Current.EnlistDurable( DummyEnlistment.Id, new DummyEnlistment(), EnlistmentOptions.None); using (IDbConnection connection = new SqlConnection(connectionString)) { connection.Open(); using (ISession s = Sfi.OpenSession(connection)) { id = (int)s.Save(new MyTable() { String = "hello!" }); } connection.Close(); } // Prior to the patch, an InvalidOperationException exception would occur in the // TransactionCompleted delegate at this point with the message, "Disconnect cannot // be called while a transaction is in progress". Although the exception can be // seen reported in the IDE, NUnit fails to see it, and the test passes. The // TransactionCompleted event fires *after* the transaction is committed and so // it doesn't affect the success of the transaction ts.Complete(); } }
public static Boolean CreateEnergy(Energy energy) { Boolean flag = false; if (!(IsExistingEnergy(energy))) { using (TransactionScope scope = new TransactionScope()) { using (var context = new SycousCon()) { try { context.Energies.AddObject(energy); context.SaveChanges(); scope.Complete(); context.AcceptAllChanges(); flag = true; } catch (Exception ex) { context.Dispose(); throw; } }// }// using }//if return flag; }
public void HandleRequest(IRequest request) { // make sure the transaction scope is disposed of properly. using (TransactionScope scope = Db.CreateTransaction()) { try { if (TryGetRobotFromZone(request, out Robot robot)) { robot.EnlistTransaction(); } else { var robotEid = request.Data.GetOrDefault <long>(k.robotEID); robot = _robotHelper.LoadRobotForCharacter(robotEid, request.Session.Character); } if (robot == null) { throw new PerpetuumException(ErrorCodes.RobotNotFound); } if (!robot.IsSingleAndUnpacked) { throw new PerpetuumException(ErrorCodes.RobotMustbeSingleAndNonRepacked); } if (ForFitting) { robot.CheckOwnerOnlyCharacterAndThrowIfFailed(request.Session.Character); } else { robot.CheckOwnerCharacterAndCorporationAndThrowIfFailed(request.Session.Character); } switch (robot.GetOrLoadParentEntity()) { case DefaultSystemContainer _: case RobotInventory _ when ForFitting: case CorporateHangar _ when ForFitting: { throw new PerpetuumException(ErrorCodes.AccessDenied); } } var result = new Dictionary <string, object> { { k.robot, robot.ToDictionary() } }; Message.Builder.FromRequest(request).WithData(result).WrapToResult().WithEmpty().Send(); } finally { scope?.Complete(); } } }
public void TestDisposeFlagCloning962Test2( [DataSources(false)] string context, [Values] bool withScope) { if (withScope && ( TestProvName.AlliSeries.Contains(context) || context == ProviderName.DB2 || context == ProviderName.InformixDB2 || context == ProviderName.SapHanaOdbc || context == ProviderName.SqlCe || context == ProviderName.Sybase || #if !NET472 (context.Contains("Oracle") && context.Contains("Managed")) || context == ProviderName.SapHanaNative || #endif TestProvName.AllMySqlData.Contains(context) || context.StartsWith("Access") || context.Contains("SqlServer") || context.Contains("SqlAzure") || context.Contains("PostgreSQL") || context.Contains(ProviderName.SQLiteClassic) )) { // Access: The ITransactionLocal interface is not supported by the 'Microsoft.Jet.OLEDB.4.0' provider. Local transactions are unavailable with the current provider. // Access>ODBC: ERROR [HY092] [Microsoft][ODBC Microsoft Access Driver]Invalid attribute/option identifier // DB2: ERROR [58005] [IBM][DB2/NT64] SQL0998N Error occurred during transaction or heuristic processing. Reason Code = "16". Subcode = "2-8004D026". // Informix DB2: ERROR [2E000] [IBM] SQL1001N "<DBNAME>" is not a valid database name. SQLSTATE=2E000 // MySql.Data: Multiple simultaneous connections or connections with different connection strings inside the same transaction are not currently supported. // PostgreSQL: 55000: prepared transactions are disabled // SQLite.Classic: The operation is not valid for the state of the transaction. // SAP HANA ODBC: ERROR [HYC00] [SAP AG][LIBODBCHDB32 DLL] Optional feature not implemented // SQLCE: The connection object can not be enlisted in transaction scope. // Sybase native: Only One Local connection allowed in the TransactionScope // Oracle managed: Operation is not supported on this platform. // SAP.Native: Operation is not supported on this platform. // SqlServer: The operation is not valid for the state of the transaction. Assert.Inconclusive("Provider not configured or has issues with TransactionScope"); } TransactionScope?scope = withScope ? new TransactionScope() : null; try { using (new AllowMultipleQuery()) using (var db = new DataConnection(context)) { // test cloned data connection without LoadWith, as it doesn't use cloning in v3 db.Select(() => "test1"); using (var cdb = ((IDataContext)db).Clone(true)) { cdb.Select(() => "test2"); scope?.Complete(); } } } finally { scope?.Dispose(); } }
public void Commit() { if (m_rolledBack) { throw new InvalidOperationException("Cannot commit the transaction because some child transaction is uncommited"); } m_scope?.Complete(); }
public async Task <TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate <TResponse> next) { var response = default(TResponse); var typeName = request.GetGenericTypeName(); TransactionScope transaction = null; try { if (hasActiveTransaction) { return(await next()); } try { transaction = new TransactionScope(); unitOfWork.BeginTransaction(); hasActiveTransaction = true; logger.LogInformation("----- Begin transaction for {CommandName} ({@Command})", typeName, request); response = await next(); logger.LogInformation("----- Commit transaction for {CommandName}", typeName); unitOfWork.CommitTransaction(); transaction?.Complete(); } catch { unitOfWork.RollbackTransaction(); throw; } finally { transaction?.Dispose(); hasActiveTransaction = false; } await excecuteOnFinish?.Invoke(cancellationToken); return(response); } catch (Exception ex) { logger.LogError(ex, "ERROR Handling transaction for {CommandName} ({@Command})", typeName, request); throw; } }
public void CommitTransaction(bool startNewTransaction = false) { if (useTransaction) { switch (transactionType) { case TransactionTypes.DbTransaction: if (transaction?.Connection != null) { SaveChanges(); transaction.Commit(); } break; case TransactionTypes.TransactionScope: try { transactionScope?.Complete(); } catch (Exception error) { if (rethrowExceptions) { throw; } else { if (RepositoryBaseExceptionRaised != null) { RepositoryBaseExceptionRaised(error); } } } break; } if (startNewTransaction) { StartTransaction(); } } else { SaveChanges(); } }
/// <summary> /// Mothod for download document (PDF) and write history to download log /// </summary> /// <param name="strDocumentNo"></param> /// <param name="documentOCC"></param> /// <param name="strDocumentCode"></param> /// <param name="fileName"></param> /// <returns></returns> public ActionResult CMS030_DownloadPdfAndWriteLog(string strDocumentNo, string documentOCC, string strDocumentCode, string fileName) { ObjectResultData res = new ObjectResultData(); CMS030_ScreenParameter sParam = GetScreenObject <CMS030_ScreenParameter>(); //Add by Jutarat A. on 17082012 using (TransactionScope t = new TransactionScope()) { try { // doDocumentDownloadLog doDocumentDownloadLog cond = new doDocumentDownloadLog(); cond.DocumentNo = strDocumentNo; cond.DocumentCode = strDocumentCode; cond.DownloadDate = CommonUtil.dsTransData.dtOperationData.ProcessDateTime; cond.DownloadBy = CommonUtil.dsTransData.dtUserData.EmpNo; cond.DocumentOCC = documentOCC; ILogHandler handlerLog = ServiceContainer.GetService <ILogHandler>() as ILogHandler; int isOK = handlerLog.WriteDocumentDownloadLog(cond); //Update firstIssueFlag for invoice report if (cond.DocumentCode == ReportID.C_REPORT_ID_INVOICE) { IBillingHandler billingHandler = ServiceContainer.GetService <IBillingHandler>() as IBillingHandler; billingHandler.UpdateFirstIssue(cond.DocumentNo, cond.DocumentOCC, cond.DownloadDate.Value, CommonUtil.dsTransData.dtUserData.EmpNo); } IDocumentHandler handlerDoc = ServiceContainer.GetService <IDocumentHandler>() as IDocumentHandler; Stream reportStream = handlerDoc.GetDocumentReportFileStream(fileName); FileInfo fileinfo = new FileInfo(fileName); if (fileinfo.Extension.ToUpper().Equals(".CSV")) { //Modify by Jutarat A. on 17082012 //FileStreamResult result = File(reportStream, "text/csv"); //result.FileDownloadName = fileinfo.Name; //t.Complete(); //return result; sParam.FileName = fileinfo.Name; sParam.StreamReport = reportStream; res.ResultData = true; t.Complete(); return(Json(res)); //End Modify } else { t.Complete(); return(File(reportStream, "application/pdf")); } } catch (Exception ex) { t.Dispose(); res.AddErrorMessage(ex); return(Json(res)); } } }
public string AddEditAction(CustomerModel model) { //Variables ActionResultModel resultModel = new ActionResultModel(); crm_Customers customer = null; crm_Contacts contact = null; UserInfo usInfo = System.Web.HttpContext.Current.Session["UserInfo"] as UserInfo; bool isSaveImageSuccess = true; string pathFiles = "/Tenants/" + _userInfo.TenantAlias; long orgNumber = 0; try { //Check case add or edit if (model.CustomerId > 0) { customer = _customerService.GetCustomerByID(model.CustomerId); if (model.ContactId > 0) { contact = _contactService.GetContactDefaultByCusID(model.CustomerId); } } else { customer = new crm_Customers(); } #region Validate data //Check email vaild if (!GlobalFunctions.IsValidEmail(model.Email.Trim())) { resultModel.IsSuccess = 0; resultModel.Message = "Email is invalid!"; return(JsonConvert.SerializeObject(resultModel)); } if (_countryService.GetCountryById(model.CountryId) == null) { resultModel.IsSuccess = 0; resultModel.Message = "Country is not exist!"; return(JsonConvert.SerializeObject(resultModel)); } if (customer == null && model.CustomerId > 0) { resultModel.IsSuccess = 0; resultModel.Message = "Customer is not exist!"; return(JsonConvert.SerializeObject(resultModel)); } if (!long.TryParse(model.OrgNumber, out orgNumber)) { resultModel.IsSuccess = 0; resultModel.Message = "Org number must be numeric!"; return(JsonConvert.SerializeObject(resultModel)); } if (!_customerService.CheckOrgNumberExist(model.CustomerId, model.OrgNumber.Trim())) { resultModel.IsSuccess = 0; resultModel.Message = "Org number is exist!"; return(JsonConvert.SerializeObject(resultModel)); } #endregion #region Set value for customer entity customer.CustomerName = WebUtility.HtmlEncode(model.CustomerName.Trim()); customer.Email = model.Email.Trim(); customer.PostedAddress = WebUtility.HtmlEncode(model.PostedAddress.Trim()); customer.VisitingAddress = WebUtility.HtmlEncode(model.VisitingAddress.Trim()); customer.CountryId = model.CountryId; customer.Fax = WebUtility.HtmlEncode(model.Fax.Trim()); customer.OrgNumber = model.OrgNumber; customer.CreatedDate = DateTime.Now; customer.CreatedBy = usInfo.ID; customer.Description = WebUtility.HtmlEncode(model.Description.Trim()); customer.Website = WebUtility.HtmlEncode(model.Website); customer.LinkedURL = WebUtility.HtmlEncode(model.LinkedURL); customer.FacebookURL = WebUtility.HtmlEncode(model.FacebookURL); customer.TwitterURL = WebUtility.HtmlEncode(model.TwitterURL); customer.GoogleplusURL = WebUtility.HtmlEncode(model.GoogleplusURL); customer.CustomerLogo = _logoModel.FileName != null ? _logoModel.FileName : model.CustomerId > 0?customer.CustomerLogo:""; #endregion #region Set value for contact entity if (model.FirstName.Trim() != string.Empty || model.LastName.Trim() != string.Empty || model.Address.Trim() != string.Empty || model.ContactPhone.Trim() != string.Empty || model.MobilePhone.Trim() != string.Empty) { if (contact != null) { contact.FirstName = model.FirstName.Trim() != string.Empty ? WebUtility.HtmlEncode(model.FirstName.Trim()) : contact.FirstName; contact.LastName = model.LastName.Trim() != string.Empty ? WebUtility.HtmlEncode(model.LastName.Trim()) : contact.LastName; contact.ContactPhone = model.ContactPhone.Trim() != string.Empty ? WebUtility.HtmlEncode(model.ContactPhone.Trim()) : contact.ContactPhone; contact.MobilePhone = model.MobilePhone.Trim() != string.Empty ? WebUtility.HtmlEncode(model.MobilePhone.Trim()) : contact.MobilePhone; contact.Address = model.Address.Trim() != string.Empty ? WebUtility.HtmlEncode(model.Address.Trim()) : contact.Address; } else { contact = new crm_Contacts(); contact.FirstName = WebUtility.HtmlEncode(model.FirstName.Trim()); contact.LastName = WebUtility.HtmlEncode(model.LastName.Trim()); contact.ContactPhone = WebUtility.HtmlEncode(model.ContactPhone.Trim()); contact.MobilePhone = WebUtility.HtmlEncode(model.MobilePhone.Trim()); contact.Address = WebUtility.HtmlEncode(model.Address.Trim()); contact.IsDefault = true; } } #endregion #region Perform save data //Save image try { if (_logoModel != null && !string.IsNullOrEmpty(_logoModel.FileName)) { //move a file from temps file to tenant folder var _sourceFile = Path.Combine(Server.MapPath(_tempFiles), _logoModel.FileName); var _destinationFile = Path.Combine(Server.MapPath(pathFiles), _logoModel.FileName); if (System.IO.File.Exists(_destinationFile)) { System.IO.File.Delete(_destinationFile); } System.IO.File.Move(_sourceFile, _destinationFile); _logoModel = null; } } catch { isSaveImageSuccess = false; } if (isSaveImageSuccess) { //Add if (model.CustomerId <= 0) { using (TransactionScope scope = new TransactionScope()) { _customerService.Insert(customer); _unitOfWork.SaveChanges(); //_tenantUnitOfWork.SaveChanges(); if (contact != null) { contact.CustomerId = customer.CustomerId; _contactService.Insert(contact); _unitOfWork.SaveChanges(); //_tenantUnitOfWork.SaveChanges(); } scope.Complete(); } } else//Edit { using (TransactionScope scope = new TransactionScope()) { _customerService.Update(customer); _unitOfWork.SaveChanges(); //_tenantUnitOfWork.SaveChanges(); if (contact != null) { contact.CustomerId = customer.CustomerId; if (contact.ContactId > 0) { _contactService.Update(contact); } else { _contactService.Insert(contact); } _unitOfWork.SaveChanges(); //_tenantUnitOfWork.SaveChanges(); } scope.Complete(); } } resultModel.IsSuccess = 1; resultModel.Message = "Data were saved successfully!"; _helper.InsertLogActive(_logService, _unitOfWork, "Customers", model.CustomerId <= 0 ? "Insert new customer" : "Update customer", model.CustomerId <= 0 ? 1 : 2, true); } else { resultModel.IsSuccess = 0; resultModel.Message = "Save image unsuccessfully!"; _helper.InsertLogActive(_logService, _unitOfWork, "Customers", "Save avatar image.", 1, false); } #endregion } catch (TransactionAbortedException te) { _helper.InsertLogActive(_logService, _unitOfWork, "Customers", model.CustomerId <= 0? "Insert new customer":"Update customer", model.CustomerId <= 0?1:2, false); } catch (ApplicationException ex) { _helper.InsertLogActive(_logService, _unitOfWork, "Customers", model.CustomerId <= 0 ? "Insert new customer" : "Update customer", model.CustomerId <= 0 ? 1 : 2, false); resultModel.IsSuccess = 0; resultModel.Message = "Data were saved unsuccessfully!"; } return(JsonConvert.SerializeObject(resultModel)); }
private void SaveChanges() { _transaction?.Complete(); }
private void bindingNavigatorDeleteItem1_Click(object sender, EventArgs e) { if (null == this.ly_store_innum_purchaseDataGridView.CurrentRow) { return; } //if (this.formState != "View") return; if (SQLDatabase.nowUserName() != ly_store_innum_purchaseDataGridView.CurrentRow.Cells["收料人"].Value.ToString()) { MessageBox.Show("请收料人:" + ly_store_innum_purchaseDataGridView.CurrentRow.Cells["收料人"].Value.ToString() + " 删除"); return; } //int parentId = int.Parse(this.ly_material_plan_mainDataGridView.CurrentRow.Cells["id"].Value.ToString()); string innumber = this.ly_store_innum_purchaseDataGridView.CurrentRow.Cells["入库单号"].Value.ToString(); //string nowwarehouse = this.ly_store_outnumDataGridView.CurrentRow.Cells["warehouse"].Value.ToString(); if ("True" == ly_store_innum_purchaseDataGridView.CurrentRow.Cells["签证"].Value.ToString()) { MessageBox.Show("已经签证,入库单不能删除..."); return; } ////////////////////////////////// string message = "删除当前入库单:" + innumber + "吗?"; string caption = "提示..."; MessageBoxButtons buttons = MessageBoxButtons.YesNo; DialogResult result; result = MessageBox.Show(message, caption, buttons, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1); if (result == DialogResult.Yes) { //string delstr = " delete ly_store_out where out_number = '" + outnumber + "'"; string delstr = " delete ly_store_in from ly_store_in " + " where ly_store_in.in_number = '" + innumber + "'"; SqlConnection sqlConnection1 = new SqlConnection(SQLDatabase.Connectstring); SqlCommand cmd = new SqlCommand(); cmd.CommandText = delstr; cmd.CommandType = CommandType.Text; cmd.Connection = sqlConnection1; int temp = 0; using (TransactionScope scope = new TransactionScope()) { sqlConnection1.Open(); try { cmd.ExecuteNonQuery(); scope.Complete(); temp = 1; } catch (SqlException sqle) { MessageBox.Show(sqle.Message.Split('*')[0]); } finally { sqlConnection1.Close(); } } if (1 == temp) { //this.ly_material_plan_mainTableAdapter.Fill(this.lYPlanMange.ly_material_plan_main, "SCJH"); } RefreshInstore(); } }
public void Commit() { SaveChanges(); _transactionScope?.Complete(); }
public void TransactedRetiring() { if (enabled) { string testName = "TransactedRetiring"; path = "test." + testName; int nMsgs = 10; var ids = new List <string>(); Connection connection = new Connection(address); Session session = new Session(connection); SenderLink sender = new SenderLink(session, "sender-" + testName, path); // send one extra for validation for (int i = 0; i < nMsgs + 1; i++) { Message message = new Message("test"); message.Properties = new Properties() { MessageId = "msg" + i, GroupId = testName }; ids.Add(message.Properties.MessageId); sender.Send(message); } ReceiverLink receiver = new ReceiverLink(session, "receiver-" + testName, path); Message[] messages = new Message[nMsgs]; for (int i = 0; i < nMsgs; i++) { messages[i] = receiver.Receive(); Trace.WriteLine(TraceLevel.Information, "receive: {0}", messages[i].Properties.MessageId); } // commit half using (var ts = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled)) { for (int i = 0; i < nMsgs / 2; i++) { receiver.Accept(messages[i]); ids.Remove(messages[i].Properties.MessageId); } ts.Complete(); } // rollback using (var ts = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled)) { for (int i = nMsgs / 2; i < nMsgs; i++) { receiver.Accept(messages[i]); } } // after rollback, messages should be still acquired { Message message = receiver.Receive(); Assert.Contains(message.Properties.MessageId, ids); receiver.Release(message); } // commit using (var ts = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled)) { for (int i = nMsgs / 2; i < nMsgs; i++) { receiver.Accept(messages[i]); ids.Remove(messages[i].Properties.MessageId); } ts.Complete(); } // only the last message is left { Message message = receiver.Receive(); receiver.Accept(message); ids.Remove(message.Properties.MessageId); } // at this point, the queue should have zero messages. // If there are messages, it is a bug in the broker. Assert.Empty(ids); // shouldn't be any messages left Message empty = receiver.Receive(TimeSpan.Zero); Assert.Null(empty); connection.Close(); } }
public void TransactedRetiringAndPosting() { if (enabled) { string testName = "TransactedRetiringAndPosting"; path = "test." + testName; int nMsgs = 10; var ids = new List <string>(); Connection connection = new Connection(address); Session session = new Session(connection); SenderLink sender = new SenderLink(session, "sender-" + testName, path); for (int i = 0; i < nMsgs; i++) { Message message = new Message("test") { Properties = new Properties() { MessageId = "msg" + i, GroupId = testName } }; ids.Add(message.Properties.MessageId); sender.Send(message); } ReceiverLink receiver = new ReceiverLink(session, "receiver-" + testName, path); receiver.SetCredit(2, false); Message message1 = receiver.Receive(); Message message2 = receiver.Receive(); // ack message1 and send a new message in a txn using (var ts = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled)) { receiver.Accept(message1); ids.Remove(message1.Properties.MessageId); Message message = new Message("test"); message.Properties = new Properties() { MessageId = "msg" + nMsgs, GroupId = testName }; ids.Add(message.Properties.MessageId); sender.Send(message); ts.Complete(); } // ack message2 and send a new message in a txn but abort the txn using (var ts = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled)) { receiver.Accept(message2); Message message = new Message("test"); message.Properties = new Properties() { MessageId = "msg" + (nMsgs + 1), GroupId = testName }; sender.Send(message1); } // release the message, since it shouldn't have been accepted above receiver.Release(message2); // receive all messages. should see the effect of the first txn receiver.SetCredit(nMsgs, false); for (int i = 1; i <= nMsgs; i++) { Message message = receiver.Receive(); Trace.WriteLine(TraceLevel.Information, "receive: {0}", message.Properties.MessageId); receiver.Accept(message); Assert.Contains(message.Properties.MessageId, ids); ids.Remove(message.Properties.MessageId); } // at this point, the queue should have zero messages. // If there are messages, it is a bug in the broker. Assert.Empty(ids); // shouldn't be any messages left Message empty = receiver.Receive(TimeSpan.Zero); Assert.Null(empty); connection.Close(); } }
public string SaveBatch(CmnBatch objCmnBatch) { GenericFactory_EF_CmnCombo = new CmnCombo_EF(); string result = ""; using (ERP_Entities _ctxCmn = new ERP_Entities()) { if (objCmnBatch.BatchID > 0) { //using (TransactionScope transaction = new TransactionScope()) //{ // try // { // Int64 mrrID = mrrMaster.MrrID; // IEnumerable<InvMrrMaster> lstInvMrrMaster = (from qcm in _ctxCmn.InvMrrMasters.Where(m => m.MrrID == mrrID) select qcm).ToList(); // InvMrrMaster objInvMrrMaster = new InvMrrMaster(); // foreach (InvMrrMaster qcms in lstInvMrrMaster) // { // qcms.UpdateBy = mrrMaster.CreateBy; // qcms.UpdateOn = DateTime.Now; // qcms.UpdatePc = HostService.GetIP(); // qcms.ChallanNo = mrrMaster.ChallanNo; // qcms.CHID = mrrMaster.CHID; // qcms.CompanyID = mrrMaster.CompanyID; // qcms.GrrID = mrrMaster.GrrID; // qcms.CurrencyID = mrrMaster.CurrencyID; // qcms.MrrDate = mrrMaster.MrrDate; // qcms.DepartmentID = mrrMaster.DepartmentID; // qcms.Description = mrrMaster.Description; // qcms.IsDeleted = false; // qcms.MrrNo = mrrMaster.MrrNo; // qcms.MrrQcID = mrrMaster.MrrQcID; // qcms.MrrTypeID = mrrMaster.MrrTypeID; // qcms.PIID = mrrMaster.PIID; // qcms.POID = mrrMaster.POID; // qcms.PONo = mrrMaster.PONo; // qcms.Remarks = mrrMaster.Remarks; // qcms.ReqNo = mrrMaster.ReqNo; // qcms.RequisitionID = mrrMaster.RequisitionID; // //qcms.StatusBy = mrrMaster.StatusBy; // //qcms.StatusDate = mrrMaster.StatusDate; // //qcms.StatusID = mrrMaster.StatusID; // objInvMrrMaster = qcms; // } // List<InvMrrDetail> lstInvMrrDetail = new List<InvMrrDetail>(); // foreach (InvMrrDetail qcdt in mrrDetails) // { // InvMrrDetail objInvMrrDetail = (from qcdetl in _ctxCmn.InvMrrDetails.Where(m => m.MrrDetailID == qcdt.MrrDetailID) select qcdetl).FirstOrDefault(); // //start for exist passed n reject qty // // decimal? prePassedRejectQty = objInvMrrQcDetail.PassQty + objInvMrrQcDetail.RejectQty; // //end for exist passed n reject qty // objInvMrrDetail.Amount = qcdt.Amount; // objInvMrrDetail.BatchID = qcdt.BatchID; // objInvMrrDetail.IsDeleted = false; // objInvMrrDetail.GradeID = qcdt.GradeID; // objInvMrrDetail.UnitID = qcdt.UnitID; // objInvMrrDetail.UpdateBy = mrrMaster.CreateBy; // objInvMrrDetail.UpdateOn = DateTime.Now; // objInvMrrDetail.UpdatePc = HostService.GetIP(); // objInvMrrDetail.ItemID = qcdt.ItemID; // objInvMrrDetail.LotID = qcdt.LotID; // objInvMrrDetail.Qty = qcdt.Qty; // objInvMrrDetail.UnitPrice = qcdt.UnitPrice; // lstInvMrrDetail.Add(objInvMrrDetail); // //InvGrrDetail objInvGrrDetail = (from grrd in _ctxCmn.InvGrrDetails.Where(m => m.GrrID == qcMaster.GrrID && m.ItemID == qcdt.ItemID) select grrd).FirstOrDefault(); // //objInvGrrDetail.QcRemainingQty = (objInvGrrDetail.QcRemainingQty + prePassedRejectQty) - (qcdt.PassQty + qcdt.RejectQty); // } // _ctxCmn.SaveChanges(); // transaction.Complete(); // result = mrrMaster.MrrNo.ToString(); // } // catch (Exception e) // { // e.ToString(); // result = ""; // } //} } else { using (TransactionScope transaction = new TransactionScope()) { try { //...........START new maxId........// long NextId = Convert.ToInt64(GenericFactory_EF_CmnCombo.getMaxID("CmnBatch")); objCmnBatch.BatchID = NextId; objCmnBatch.CreateOn = DateTime.Now; objCmnBatch.CreatePc = HostService.GetIP(); objCmnBatch.BatchDate = DateTime.Now; objCmnBatch.IsDeleted = false; _ctxCmn.CmnBatches.Add(objCmnBatch); //............Update MaxID.................// GenericFactory_EF_CmnCombo.updateMaxID("CmnBatch", Convert.ToInt64(NextId)); _ctxCmn.SaveChanges(); transaction.Complete(); result = NextId.ToString(); } catch (Exception e) { result = ""; } } } } return(result); }
public string SaveUpdateMrrMasterNdetails(InvMrrMaster mrrMaster, List <InvMrrDetail> mrrDetails, int menuID) { GenericFactory_EF_CmnCombo = new CmnCombo_EF(); string result = ""; using (ERP_Entities _ctxCmn = new ERP_Entities()) { if (mrrMaster.MrrID > 0) { using (TransactionScope transaction = new TransactionScope()) { try { Int64 mrrID = mrrMaster.MrrID; IEnumerable <InvMrrMaster> lstInvMrrMaster = (from qcm in _ctxCmn.InvMrrMasters.Where(m => m.MrrID == mrrID && m.IsDeleted == false && m.CompanyID == mrrMaster.CompanyID) select qcm).ToList(); InvMrrMaster objInvMrrMaster = new InvMrrMaster(); foreach (InvMrrMaster qcms in lstInvMrrMaster) { qcms.UpdateBy = mrrMaster.CreateBy; qcms.UpdateOn = DateTime.Now; qcms.UpdatePc = HostService.GetIP(); qcms.ChallanNo = mrrMaster.ChallanNo; qcms.CHID = mrrMaster.CHID; qcms.CompanyID = mrrMaster.CompanyID; // qcms.MRRCertificateNo = mrrMaster.MRRCertificateNo; qcms.ManualMRRNo = mrrMaster.ManualMRRNo; qcms.GrrID = mrrMaster.GrrID; qcms.MrrTypeID = mrrMaster.MrrTypeID; qcms.CurrencyID = mrrMaster.CurrencyID; qcms.MrrDate = mrrMaster.MrrDate; qcms.DepartmentID = mrrMaster.DepartmentID; qcms.Description = mrrMaster.Description; qcms.IsDeleted = false; qcms.SupplierID = mrrMaster.SupplierID; qcms.MrrNo = mrrMaster.MrrNo; qcms.MrrQcID = mrrMaster.MrrQcID; qcms.MrrTypeID = mrrMaster.MrrTypeID; qcms.PIID = mrrMaster.PIID; qcms.POID = mrrMaster.POID; qcms.PONo = mrrMaster.PONo; qcms.Remarks = mrrMaster.Remarks; qcms.ReqNo = mrrMaster.ReqNo; qcms.RequisitionID = mrrMaster.RequisitionID; qcms.FromDepartmentID = mrrMaster.FromDepartmentID; qcms.IssueID = mrrMaster.IssueID; qcms.UserID = mrrMaster.UserID; //qcms.StatusBy = mrrMaster.StatusBy; //qcms.StatusDate = mrrMaster.StatusDate; //qcms.StatusID = mrrMaster.StatusID; qcms.IsAccountsCompleted = mrrMaster.IsAccountsCompleted; qcms.IsApproved = mrrMaster.IsApproved; qcms.IsStoreCompleted = mrrMaster.IsStoreCompleted; objInvMrrMaster = qcms; //if (mrrMaster.IsStoreCompleted == true) //{ // // for one save then grrcomplete // InvMrrQcMaster objInvMrrQcMaster = (from spr in _ctxCmn.InvMrrQcMasters.Where(m => m.MrrQcID == mrrMaster.MrrQcID && m.CompanyID == mrrMaster.CompanyID) select spr).FirstOrDefault(); // objInvMrrQcMaster.IsMrrCompleted = true; //} } List <InvMrrDetail> lstInvMrrDetail = new List <InvMrrDetail>(); foreach (InvMrrDetail qcdt in mrrDetails) { InvMrrDetail objInvMrrDetail = (from qcdetl in _ctxCmn.InvMrrDetails.Where(m => m.MrrDetailID == qcdt.MrrDetailID && m.IsDeleted == false) select qcdetl).FirstOrDefault(); objInvMrrDetail.AdditionalQty = qcdt.AdditionalQty; objInvMrrDetail.IsQcCompleted = false; objInvMrrDetail.Amount = qcdt.Amount; objInvMrrDetail.BatchID = qcdt.BatchID; objInvMrrDetail.IsDeleted = false; objInvMrrDetail.GradeID = qcdt.GradeID; objInvMrrDetail.UnitID = qcdt.UnitID; objInvMrrDetail.UpdateBy = mrrMaster.CreateBy; objInvMrrDetail.UpdateOn = DateTime.Now; objInvMrrDetail.UpdatePc = HostService.GetIP(); objInvMrrDetail.ItemID = qcdt.ItemID; objInvMrrDetail.LotID = qcdt.LotID; objInvMrrDetail.Qty = qcdt.Qty; objInvMrrDetail.UnitPrice = qcdt.UnitPrice; lstInvMrrDetail.Add(objInvMrrDetail); } _ctxCmn.SaveChanges(); transaction.Complete(); result = mrrMaster.MrrNo.ToString(); } catch (Exception e) { e.ToString(); result = ""; } } } else { using (TransactionScope transaction = new TransactionScope()) { try { //...........START new maxId........// long NextId = Convert.ToInt64(GenericFactory_EF_CmnCombo.getMaxID("InvMrrMaster")); long FirstDigit = 0; long OtherDigits = 0; long nextDetailId = Convert.ToInt64(GenericFactory_EF_CmnCombo.getMaxID("InvMrrDetail")); FirstDigit = Convert.ToInt64(nextDetailId.ToString().Substring(0, 1)); OtherDigits = Convert.ToInt64(nextDetailId.ToString().Substring(1, nextDetailId.ToString().Length - 1)); //..........END new maxId.........// //......... START for custom code........... // string customCode = ""; string CustomNo = GenericFactory_EF_CmnCombo.getCustomCode(menuID, DateTime.Now, mrrMaster.CompanyID, 1, 1); if (CustomNo != null) { customCode = CustomNo; } else { customCode = NextId.ToString(); } //.........END for custom code............ // string newMrrNo = customCode; mrrMaster.MrrID = NextId; mrrMaster.CreateOn = DateTime.Now; mrrMaster.CreatePc = HostService.GetIP(); mrrMaster.MrrNo = newMrrNo; mrrMaster.IsDeleted = false; //if (mrrMaster.IsStoreCompleted == true) //{ // // for one save then grrcomplete // InvMrrQcMaster objInvMrrQcMaster = (from spr in _ctxCmn.InvMrrQcMasters.Where(m => m.MrrQcID == mrrMaster.MrrQcID && m.CompanyID == mrrMaster.CompanyID) select spr).FirstOrDefault(); // objInvMrrQcMaster.IsMrrCompleted = true; //} List <InvMrrDetail> lstInvMrrDetail = new List <InvMrrDetail>(); foreach (InvMrrDetail sdtl in mrrDetails) { InvMrrDetail objInvMrrDetail = new InvMrrDetail(); objInvMrrDetail.MrrDetailID = Convert.ToInt64(FirstDigit + "" + OtherDigits); objInvMrrDetail.MrrID = NextId; objInvMrrDetail.ItemID = sdtl.ItemID; objInvMrrDetail.Amount = sdtl.Amount; objInvMrrDetail.UnitPrice = sdtl.UnitPrice; objInvMrrDetail.BatchID = sdtl.BatchID; objInvMrrDetail.IsDeleted = false; objInvMrrDetail.AdditionalQty = sdtl.AdditionalQty; // objInvMrrDetail.IsQcCompleted = mrrMaster.MrrQcID > 0 ? true : false; objInvMrrDetail.LotID = sdtl.LotID; objInvMrrDetail.Qty = sdtl.Qty; objInvMrrDetail.UnitID = sdtl.UnitID; objInvMrrDetail.CreateBy = mrrMaster.CreateBy;//sdtl.CreateBy; objInvMrrDetail.CreateOn = DateTime.Now; objInvMrrDetail.CreatePc = HostService.GetIP(); lstInvMrrDetail.Add(objInvMrrDetail); OtherDigits++; } _ctxCmn.InvMrrMasters.Add(mrrMaster); //............Update MaxID.................// GenericFactory_EF_CmnCombo.updateMaxID("InvMrrMaster", Convert.ToInt64(NextId)); //............Update CustomCode.............// GenericFactory_EF_CmnCombo.updateCustomCode(menuID, DateTime.Now, mrrMaster.CompanyID, 1, 1); _ctxCmn.InvMrrDetails.AddRange(lstInvMrrDetail); //............Update MaxID.................// GenericFactory_EF_CmnCombo.updateMaxID("InvMrrDetail", Convert.ToInt64(FirstDigit + "" + (OtherDigits - 1))); _ctxCmn.SaveChanges(); transaction.Complete(); result = newMrrNo; } catch (Exception e) { result = ""; } } } } return(result); }
public int SetupFranchisee(FranchiseeTenant franchiseeTenant, FranchiseeConfiguration franchiseeConfiguration) { using (var scope = new TransactionScope()) { //Add Franchise ValidateBusinessRules(franchiseeTenant); _franchiseeTenantRepository.Add(franchiseeTenant); _franchiseeTenantRepository.Commit(); int i = 0; var connectionString = PersistenceHelper.GenerateConnectionString(franchiseeTenant.Server, franchiseeTenant.Database, franchiseeTenant.UserName, franchiseeTenant.Password); var database = franchiseeTenant.Database; // Create franchisee configuaration // Check franchisee configuaration has exists #region _franchiseeConfigurationRepository.DeleteAllFranchiseeConfigurationBySqlString(database); var franchiseeId = PasswordHelper.HashString(franchiseeTenant.Id.ToString(), franchiseeTenant.Name); var licenseKey = franchiseeTenant.LicenseKey; var franchiseeContact = franchiseeConfiguration.FranchiseeContact; var primaryContactPhone = franchiseeConfiguration.PrimaryContactPhone; var primaryContactEmail = franchiseeConfiguration.PrimaryContactEmail; var primaryContactFax = franchiseeConfiguration.PrimaryContactFax; var primaryContactCellNumber = franchiseeConfiguration.PrimaryContactCellNumber; var name = franchiseeConfiguration.Name; var city = franchiseeConfiguration.City; var state = franchiseeConfiguration.State; var zip = franchiseeConfiguration.Zip; var address1 = franchiseeConfiguration.Address1; var address2 = franchiseeConfiguration.Address2; var officePhone = franchiseeConfiguration.OfficePhone; var faxNumber = franchiseeConfiguration.FaxNumber; var industryId = franchiseeConfiguration.IndustryId; var logo = franchiseeConfiguration.Logo; var franchiseeconfig = new FranchiseeConfiguration { FranchiseeId = franchiseeId, LicenseKey = licenseKey, FranchiseeContact = franchiseeContact, PrimaryContactPhone = primaryContactPhone, PrimaryContactEmail = primaryContactEmail, PrimaryContactFax = primaryContactFax, PrimaryContactCellNumber = primaryContactCellNumber, Name = name, City = city, State = state, Zip = zip, Address1 = address1, Address2 = address2, OfficePhone = officePhone, FaxNumber = faxNumber, Logo = logo, IndustryId = industryId }; _franchiseeConfigurationRepository.AddFranchiseeConfigurationBySqlString(franchiseeconfig, database); #endregion // Create a franchisee admin role #region _userRoleRepository.ChangeConnectionString(connectionString); var franchiseeAdminRole = _userRoleRepository.FirstOrDefault(o => o.AppRoleName == AppRole.GlobalAdmin.ToString()); var idFranchiseeAdminRole = 0; if (franchiseeAdminRole == null) { // Create franchisee admin role var franchiseeAdminRoleAdd = new UserRole { Name = "Franchisee Admin", AppRoleName = AppRole.GlobalAdmin.ToString(), UserRoleFunctions = new List <UserRoleFunction>() }; // Create list userRoleFunction for franchisee admin var objListDocumentType = _userRoleRepository.GetAllDocumentType(); foreach (var documentType in objListDocumentType) { var objViewAdd = new UserRoleFunction { DocumentTypeId = documentType.Id, SecurityOperationId = (int)OperationAction.View }; franchiseeAdminRoleAdd.UserRoleFunctions.Add(objViewAdd); //Implement View insert var objInsertAdd = new UserRoleFunction { DocumentTypeId = documentType.Id, SecurityOperationId = (int)OperationAction.Add, }; franchiseeAdminRoleAdd.UserRoleFunctions.Add(objInsertAdd); //Implement View update var objUpdateAdd = new UserRoleFunction { DocumentTypeId = documentType.Id, SecurityOperationId = (int)OperationAction.Update, }; franchiseeAdminRoleAdd.UserRoleFunctions.Add(objUpdateAdd); //Implement View delete var objDeleteAdd = new UserRoleFunction { DocumentTypeId = documentType.Id, SecurityOperationId = (int)OperationAction.Delete, }; franchiseeAdminRoleAdd.UserRoleFunctions.Add(objDeleteAdd); var objProcessAdd = new UserRoleFunction { DocumentTypeId = documentType.Id, SecurityOperationId = (int)OperationAction.Process, }; franchiseeAdminRoleAdd.UserRoleFunctions.Add(objProcessAdd); } _userRoleRepository.Add(franchiseeAdminRoleAdd); _userRoleRepository.Commit(); idFranchiseeAdminRole = franchiseeAdminRoleAdd.Id; } else { idFranchiseeAdminRole = franchiseeAdminRole.Id; } #endregion // Create franchisee admin user // Check user admin has exists #region _userRepository.ChangeConnectionString(connectionString); var isExistsUserFranchiseeAdmin = _userRepository.CheckExist(o => o.UserRoleId == idFranchiseeAdminRole); if (!isExistsUserFranchiseeAdmin) { var randomPassword = "******"; string username = franchiseeTenant.Name.Replace(" ", ""); var password = PasswordHelper.HashString(randomPassword, username); var phoneNumber = franchiseeConfiguration.PrimaryContactPhone; // "1111111111"; var email = franchiseeConfiguration.PrimaryContactEmail; // "*****@*****.**"; var cellPhone = franchiseeConfiguration.PrimaryContactCellNumber; // "1111111111"; // Create user franchisee admin var userFranchiseeAdmin = new User { UserName = username, Password = password, UserRoleId = idFranchiseeAdminRole, IsActive = true, FirstName = "Admin", LastName = "Franchisee", HomePhone = phoneNumber, MobilePhone = cellPhone, Email = email, }; _userRepository.AddUserBySqlString(userFranchiseeAdmin, database); } #endregion scope.Complete(); return(franchiseeTenant.Id); } }
public byte[] UpdateFranchisee(FranchiseeTenant franchiseeTenant, FranchiseeConfiguration franchiseeConfiguration) { using (var scope = new TransactionScope()) { ValidateBusinessRules(franchiseeTenant); _franchiseeTenantRepository.Update(franchiseeTenant); _franchiseeTenantRepository.Commit(); // change the connection var connectionString = PersistenceHelper.GenerateConnectionString(franchiseeTenant.Server, franchiseeTenant.Database, franchiseeTenant.UserName, franchiseeTenant.Password); var database = franchiseeTenant.Database; _franchiseeConfigurationRepository.ChangeConnectionString(connectionString); _franchiseeConfigurationRepository.DeleteAllFranchiseeConfigurationBySqlString(database); // Create franchisee configuaration //Add new Franchisee Configuration var franchiseeId = PasswordHelper.HashString(franchiseeTenant.Id.ToString(), franchiseeTenant.Name); var licenseKey = franchiseeTenant.LicenseKey; var franchiseeContact = franchiseeConfiguration.FranchiseeContact; var primaryContactPhone = franchiseeConfiguration.PrimaryContactPhone; var primaryContactEmail = franchiseeConfiguration.PrimaryContactEmail; var primaryContactFax = franchiseeConfiguration.PrimaryContactFax; var primaryContactCellNumber = franchiseeConfiguration.PrimaryContactCellNumber; var name = franchiseeConfiguration.Name; var city = franchiseeConfiguration.City; var state = franchiseeConfiguration.State; var zip = franchiseeConfiguration.Zip; var address1 = franchiseeConfiguration.Address1; var address2 = franchiseeConfiguration.Address2; var officePhone = franchiseeConfiguration.OfficePhone; var faxNumber = franchiseeConfiguration.FaxNumber; var logo = franchiseeConfiguration.Logo; var industryId = franchiseeConfiguration.IndustryId; var franchiseeconfig = new FranchiseeConfiguration { FranchiseeId = franchiseeId, LicenseKey = licenseKey, FranchiseeContact = franchiseeContact, PrimaryContactPhone = primaryContactPhone, PrimaryContactEmail = primaryContactEmail, PrimaryContactFax = primaryContactFax, PrimaryContactCellNumber = primaryContactCellNumber, Name = name, City = city, State = state, Zip = zip, Address1 = address1, Address2 = address2, OfficePhone = officePhone, FaxNumber = faxNumber, Logo = logo, IndustryId = industryId }; _franchiseeConfigurationRepository.AddFranchiseeConfigurationBySqlString(franchiseeconfig, database); scope.Complete(); return(franchiseeTenant.LastModified); } }
EventEntity AddEvent(EventsView entity, List <EventInviteEntity> inviteList) { #if !DEBUG using (TransactionScope tran = new TransactionScope()) #endif { if (entity.Repeat != RepeatType.None && entity.End == EndType.on_date && entity.Times <= 1) { var times = entity.Times > -1 ? entity.Times : 0; DateTime start = entity.FromDay; while (start < entity.EndDate) { times++; // calc next event date switch (entity.Repeat) { case RepeatType.Every_Day: start = start.AddDays(1); break; case RepeatType.Every_Week: start = start.AddDays(7); break; case RepeatType.Every_two_weeks: start = start.AddDays(2 * 7); break; case RepeatType.Every_Month: case RepeatType.Every_Month_First_Friday: start = start.AddMonths(1); break; case RepeatType.Every_Year: start = start.AddYears(1); break; } } entity.Times = times; } //entity.CreatedOn = DateTime.Now; entity.UpdatedOn = DateTime.Now; entity.Highlight = false; bool result = false; entity.ID = mgr.AddEvents(entity, entity.Times, entity.IsOff); if (entity.ID > 0) { result = mgr.AddEventInvites(entity, inviteList); } if (entity.IsOff)//如果选择了OFF的ticket,则添加TimeSheets { result = AddTimeSheetsWithEvent(entity); } #if !DEBUG if (result) { tran.Complete(); } #endif if (result) { return(entity); } else { return(null); } } }
public bool AddEvents(EventsView entity, List <EventInviteEntity> inviteList, out List <EventEntity> eventList) { eventList = new List <EventEntity>(); if (entity.Icon == 0) { entity.Icon = 1; } if (!entity.AllDay) { entity.FromDay = DateTime.Parse(string.Format("{0}/{1}/{2} {3} {4}" , entity.FromDay.Month, entity.FromDay.Day, entity.FromDay.Year, entity.FromTime, entity.FromTimeType == 1 ? "AM" : "PM")); } if (entity.Repeat == RepeatType.None) { EventEntity eventEntity = AddEvent(entity, inviteList); if (eventEntity != null) { eventList.Add(eventEntity); return(true); } else { return(false); } } else { bool result = false; if (entity.End == EndType.After_number_of_times) //重复次数 { #region DateTime tmpFromDay = entity.FromDay; string tmpToTime = entity.ToTime; int tmpToTimeType = entity.ToTimeType; bool isSameDay = entity.FromDay.Date == entity.ToDay.Date;//开始日期和结束日期是否为同一天 #if !DEBUG using (TransactionScope tran = new TransactionScope()) #endif { for (int i = 0; i < entity.Times; i++) { if (entity.Repeat == RepeatType.Every_Month_First_Friday) { entity.FromDay = GetNextDateForRepeat7(tmpFromDay); } else { entity.FromDay = tmpFromDay; } entity.ToDay = tmpFromDay; if (!isSameDay) //如果不是同一天,FromTime和ToTime要做处理 { //若选择的日期为04/14/2015 1:00 pm 到 04/15/2015 6:00 am, //则处理成 4.14号为 04/14/2015 1:00 pm 到 04/14/2015 11:59 pm, // 4.15号为 04/15/2015 12:00 am 到 04/15/2015 6:00 am if (i == entity.Times - 1) { entity.ToTime = tmpToTime; entity.ToTimeType = tmpToTimeType; } else { entity.ToTime = "11:59"; entity.ToTimeType = 2; } if (i > 0) { entity.FromTime = "12:00"; entity.FromTimeType = 1; } } EventEntity eventEntity = AddEvent(entity, inviteList); result = eventEntity != null; eventList.Add(new EventEntity() { Name = entity.Name, Where = entity.Where, Details = entity.Details, ProjectID = entity.ProjectID, FromDay = entity.FromDay, FromTime = entity.FromTime, FromTimeType = entity.FromTimeType, ToDay = entity.ToDay, ToTime = entity.ToTime, ToTimeType = entity.ToTimeType, AllDay = entity.AllDay }); // calc next event date switch (entity.Repeat) { case RepeatType.Every_Day: tmpFromDay = tmpFromDay.AddDays(1); break; case RepeatType.Every_Week: tmpFromDay = tmpFromDay.AddDays(7); break; case RepeatType.Every_two_weeks: tmpFromDay = tmpFromDay.AddDays(2 * 7); break; case RepeatType.Every_Month: case RepeatType.Every_Month_First_Friday: tmpFromDay = tmpFromDay.AddMonths(1); break; case RepeatType.Every_Year: tmpFromDay = tmpFromDay.AddYears(1); break; } if (!result) { return(false); } } #if !DEBUG if (result) { tran.Complete(); } #endif } #endregion } else { #region DateTime tmpFromDay = entity.FromDay; string tmpToTime = entity.ToTime; int tmpToTimeType = entity.ToTimeType; bool isSameDay = entity.FromDay.Date == entity.ToDay.Date;//开始日期和结束日期是否为同一天 int tmpIndex = 0; while (entity.FromDay < entity.EndDate.Date) //截止时间 { #if !DEBUG using (TransactionScope tran = new TransactionScope()) #endif { switch (entity.Repeat) { case RepeatType.Every_Day: entity.FromDay = tmpFromDay.AddDays(tmpIndex); entity.ToDay = entity.FromDay; break; case RepeatType.Every_Week: entity.FromDay = tmpFromDay.AddDays(tmpIndex * 7); entity.ToDay = entity.FromDay; break; case RepeatType.Every_two_weeks: entity.FromDay = tmpFromDay.AddDays(2 * 7 * tmpIndex); entity.ToDay = entity.FromDay; break; case RepeatType.Every_Month: entity.FromDay = tmpFromDay.AddMonths(1 * tmpIndex); entity.ToDay = entity.FromDay; break; case RepeatType.Every_Month_First_Friday: if (tmpIndex == 0) { entity.FromDay = GetNextDateForRepeat7(tmpFromDay); } else { entity.FromDay = GetNextDateForRepeat7(tmpFromDay.AddMonths(1 * tmpIndex)); if (entity.FromDay > entity.EndDate.Date) { continue; } } entity.ToDay = entity.FromDay; break; case RepeatType.Every_Year: entity.FromDay = tmpFromDay.AddYears(1 * tmpIndex); entity.ToDay = entity.FromDay; break; } if (!isSameDay) //如果不是同一天,FromTime和ToTime要做处理 { //若选择的日期为04/14/2015 1:00 pm 到 04/15/2015 6:00 am, //则处理成 4.14号为 04/14/2015 1:00 pm 到 04/14/2015 11:59 pm, // 4.15号为 04/15/2015 12:00 am 到 04/15/2015 6:00 am if (entity.FromDay.Date >= entity.EndDate.Date) { entity.ToTime = tmpToTime; entity.ToTimeType = tmpToTimeType; } else { entity.ToTime = "11:59"; entity.ToTimeType = 2; } if (tmpIndex > 0) { entity.FromTime = "12:00"; entity.FromTimeType = 1; } } EventEntity eventEntity = AddEvent(entity, inviteList); result = eventEntity != null; eventList.Add(eventEntity); if (result == false) { return(false); } tmpIndex++; #if !DEBUG if (result) { tran.Complete(); } #endif } } #endregion } return(result); } }
/// <summary> /// 修改Event时 /// </summary> public bool UpdateEvent(EventsView entity, EventEntity oldEvent, List <EventInviteEntity> inviteUserList) { bool result = false; entity.UpdatedOn = DateTime.Now; if (!entity.AllDay) { entity.FromDay = DateTime.Parse(string.Format("{0}/{1}/{2} {3} {4}" , entity.FromDay.Month, entity.FromDay.Day, entity.FromDay.Year, entity.FromTime, entity.FromTimeType == 1 ? "AM" : "PM")); } #if !DEBUG using (TransactionScope tran = new TransactionScope()) #endif { result = mgr.EditEvents(entity); if (entity.FromDay >= DateTime.Now.Date) //当天之前的TimeSheet不做修改 { if (entity.ProjectID.ToString() == Config.HRProjectID) //项目为HR时,需要处理TimeSheets { if (!(oldEvent.IsOff) && entity.IsOff) //如果之前没有选择OFF的ticket,修改后选择了,则添加TimeSheets { result = AddTimeSheetsWithEvent(entity); } if (oldEvent.IsOff && entity.IsOff)//如果两次都选择了OFF的ticket,则修改Timesheet时间 { TimeSheetsEntity timeSheetEntity = tsp.GetByEventId(entity.ID, entity.FromDay.Date); if (entity.AllDay) { timeSheetEntity.Hours = 8; } else { DateTime FromDay = DateTime.Parse(string.Format("{0}/{1}/{2} {3} {4}" , entity.FromDay.Month, entity.FromDay.Day, entity.FromDay.Year, entity.FromTime, entity.FromTimeType == 1 ? "AM" : "PM")); DateTime EndDay = DateTime.Parse(string.Format("{0}/{1}/{2} {3} {4}" , entity.ToDay.Month, entity.ToDay.Day, entity.ToDay.Year, entity.ToTime, entity.ToTimeType == 1 ? "AM" : "PM")); string Hours = EndDay.Subtract(FromDay).TotalHours.ToString(); timeSheetEntity.Hours = decimal.Parse(Hours); } timeSheetEntity.IsSubmitted = entity.AllDay ? true : false; timeSheetEntity.ModifiedOn = DateTime.Now; result = tsp.UpdateTimeSheet(timeSheetEntity); } if (oldEvent.IsOff && !(entity.IsOff))//如果之前选择了OFF的ticket,修改后没有选择,则删除TimeSheets { result = tsp.DeleteByEventId(entity.ID, entity.FromDay.Date); } } } if (result) { RemoveInviteUser(inviteUserList); inviteUserList.RemoveAll(r => (r.UserID > 0 && (r.OptionStatus == 1 || r.OptionStatus == 3)) || (r.UserID == 0 && r.OptionStatus == 3)); mgr.AddEventInvites(entity, inviteUserList); } #if !DEBUG if (result) { tran.Complete(); return(true); } #endif } return(result); }
public Model.Result AddRole(Model.UserInfo user, Model.RoleInfo role, List <int> menus) { using (TransactionScope ts = new TransactionScope()) { try { string sql = "select count(1) from RoleInfo where RoleName='" + role.RoleName + "'"; int count = (int)DbHelper.SqlHelper.ExecuteScalarByString(sql, new Dictionary <string, object>()); if (count > 0) { return(new Model.Result() { ReturnValue = false, Message = "已存在相同名称的角色,保存失败!" }); } sql = @"insert into RoleInfo(RoleName,Note)values(@name,@note) if (@@ROWCOUNT=1) begin select RoleID from RoleInfo where RoleName=@name end else begin select -1 end"; Dictionary <string, object> indic = new Dictionary <string, object>(); indic.Add("@name", role.RoleName); indic.Add("@note", role.Note); int roleID = (int)DbHelper.SqlHelper.ExecuteScalarByString(sql, indic); if (roleID == -1) { return(new Model.Result() { ReturnValue = false, Message = "保存失败!" }); } sql = "insert into RoleMenuInfo(RoleID,MenuID)"; int index = 1; foreach (var item in menus) { sql += "select " + roleID + "," + item; if (index < menus.Count) { sql += " union "; } index++; } count = DbHelper.SqlHelper.ExecuteNonQuery(sql, new Dictionary <string, object>()); if (count == menus.Count) { ts.Complete(); return(new Model.Result() { ReturnValue = true, Message = "保存成功!" }); } return(new Model.Result() { ReturnValue = false, Message = "保存失败!" }); } catch (Exception ex) { return(new Model.Result() { ReturnValue = false, Message = ex.Message }); } } }
private void btnSaveAll_Click(object sender, EventArgs e) { TransactionBLL transaction = new TransactionBLL(); transaction.type = lblTopPurcSale.Text; string deaCusName = txtPSDeaCusName.Text; DeaCusBLL dc = dcdal.GetDeaCusIDFromName(deaCusName); transaction.delr_cust_id = dc.id; transaction.grandTotal = Math.Round(decimal.Parse(txtPSCDGrandTotal.Text), 2); transaction.transaction_date = DateTime.Now; transaction.tax = decimal.Parse(txtPSCDVat.Text); transaction.discount = decimal.Parse(txtPSCDDiscount.Text); string loggeduser = frmLogin.loggedIn; UserBLL user = udal.GetIdFromUsername(loggeduser); transaction.added_by = user.id; transaction.transactionDetails = transactionDT; bool Success = false; using (TransactionScope scope = new TransactionScope()) { int transactionID = -1; bool X = tdal.Insert_Transaction(transaction, out transactionID); for (int i = 0; i < transactionDT.Rows.Count; i++) { TransactionDetailsBLL td = new TransactionDetailsBLL(); String ProductName = transactionDT.Rows[i][0].ToString(); ProductsBLL p = pdal.GetProductIDFromName(ProductName); td.product_id = p.id; td.rate = decimal.Parse(transactionDT.Rows[i][1].ToString()); td.qty = decimal.Parse(transactionDT.Rows[i][2].ToString()); td.total = Math.Round(decimal.Parse(transactionDT.Rows[i][3].ToString()), 2); td.delr_cust_id = dc.id; td.added_date = DateTime.Now; td.added_by = user.id; string transactionType = lblTopPurcSale.Text; bool Y = false; if (transactionType == "PURCHASE") { Y = pdal.IncreaseProduct(td.product_id, td.qty); } else if (transactionType == "SALES") { Y = pdal.DecreaseProduct(td.product_id, td.qty); } bool Z = tdDal.Insert_TransactionDetails(td); Success = X && Y && Z; } if (Success == true) { scope.Complete(); // CODE TO PRINT BILL DGVPrinter printer = new DGVPrinter(); printer.Title = "\r\n\r\nEVERYTHING PVT. LTD.\r\n"; printer.SubTitle = "\r\n MAIN ROAD NEAR RAILWAY STATION ,P.O:GHATSILA,\r\nDIST:EAST SINGHBHUM ,JHARKHAND\r\n Mob: 9583340426 \r\n\r\n "; printer.SubTitleFormatFlags = StringFormatFlags.LineLimit | StringFormatFlags.NoClip; printer.PageNumbers = true; printer.PageNumberInHeader = false; printer.PorportionalColumns = true; printer.HeaderCellAlignment = StringAlignment.Near; printer.Footer = "Discount:" + txtPSCDDiscount.Text + "%\r\n" + "TAX:" + txtPSCDVat.Text + "%\r\n" + "Grand-Total:RS" + txtPSCDGrandTotal.Text + "\r\n\r\n" + "THANK YOU FOR BUSINESS WITH US"; printer.FooterSpacing = 15; printer.PrintDataGridView(dgvPSAddedProduct); //---------------------------------------------------------------------------------------------------------------------------- MessageBox.Show("Transaction Successfully Done."); dgvPSAddedProduct.DataSource = null; dgvPSAddedProduct.Rows.Clear(); txtPSDeaCusSearch.Text = ""; txtPSDeaCusName.Text = ""; txtPSDeaCusEmail.Text = ""; txtPSDeaCusContact.Text = ""; txtPSDeaCusAddress.Text = ""; txtPSPDSearch.Text = ""; txtPSPDName.Text = ""; txtPSPDInventory.Text = "0"; txtPSPDRate.Text = "0"; txtPSPDQty.Text = ""; txtPSCDSubtotal.Text = "0"; txtPSCDDiscount.Text = "0"; txtPSCDVat.Text = "0"; txtPSCDGrandTotal.Text = "0"; txtPSCDpaidamount.Text = "0"; txtPSCDRetAmut.Text = "0"; } else { MessageBox.Show("Failed Transaction,Retry"); } } }
public string FillIn(IDictionary <string, string> SubmitFields, Template Template, FormCollection formCollection) { string result = null; IList <string> errors = Enumerable.Empty <string>().ToList(); var templateView = TemplateViewModel.CreateFromObject(Template, Constants.TemplateFieldMode.INPUT); templateView.AssignInputValues(formCollection); if (templateView.Fields.Any()) { IDictionary <int, string> submissionFields = new System.Collections.Generic.Dictionary <int, string>(); // first validate fields foreach (var field in templateView.Fields.OrderBy(f => f.TemplateFieldID)) { if (!field.SubmittedValueIsValid(formCollection)) { field.SetFieldErrors(); errors.Add(field.Errors); } var value = field.SubmittedValue(formCollection); if (field.IsRequired && value.IsNullOrEmpty()) { if (field.ConditionTemplateFieldID.HasValue) { if (isConditionalFieldRequired(field, submissionFields)) { field.Errors = "{0} is a required field".FormatWith(field.Label); errors.Add(field.Errors); } else { submissionFields.Add(field.TemplateFieldID.Value, value); } } else { field.Errors = "{0} is a required field".FormatWith(field.Label); errors.Add(field.Errors); } } else { submissionFields.Add(field.TemplateFieldID.Value, value); } } ; if (errors.Count == 0) { //then insert values var entryId = Guid.NewGuid(); using (TransactionScope scope = new TransactionScope()) { foreach (var field in templateView.Fields.OrderBy(f => f.TemplateFieldID)) { if (field.ConditionTemplateFieldID.HasValue) { if (isConditionalFieldRequired(field, submissionFields)) { var value = field.SubmittedValue(formCollection); HandleTemplateFieldValue(field, value, entryId); } } else { var value = field.SubmittedValue(formCollection); HandleTemplateFieldValue(field, value, entryId); } } HandleAdditionalInsert(templateView, Template, formCollection, entryId, submissionFields); UnitOfWork.Complete(); scope.Complete(); result = "success"; } } } if (errors.Count > 0) { result = errors.ToUnorderedList(); } return(result); }
public bool Insert(Product p) { bool InsertAttempt = false; System.IO.StringWriter writer = new System.IO.StringWriter(); try { // Create the TransactionScope to execute the commands, guaranteeing // that both commands can commit or roll back as a single unit of work. using (TransactionScope scope = new TransactionScope(TransactionScopeOption.RequiresNew, new TransactionOptions { IsolationLevel = IsolationLevel.ReadCommitted })) { using (SqlConnection _Sqlconnection = new SqlConnection(_Connection)) { // Opening the connection automatically enlists it in the // TransactionScope as a lightweight transaction. _Sqlconnection.Open(); // Create the SqlCommand object and execute the first command. using (SqlCommand cmd = _Sqlconnection.CreateCommand()) { cmd.CommandText = "INSERT INTO [dbo].[Products] " + "(Title, Description, Price)" + "VALUES(@Title, @Description, @Price)"; cmd.Parameters.AddWithValue("@Title", p.Title); cmd.Parameters.AddWithValue("@Description", p.Description); cmd.Parameters.AddWithValue("@Price", p.Price); int numberRowsAffected = cmd.ExecuteNonQuery(); writer.WriteLine("Rows to be affected by the insert command: {0}", numberRowsAffected); InsertAttempt = true; _TransactionsMade++; } // If you get here, this means that command1 succeeded. By nesting // the using block for connection2 inside that of connection1, you // conserve server and network resources as connection2 is opened // only when there is a chance that the transaction can commit. //using (SqlConnection connection2 = new SqlConnection(connectString2)) //{ // The transaction is escalated to a full distributed // transaction when connection2 is opened. // connection2.Open(); // Execute the second command in the second database. //} } // The Complete method commits the transaction. If an exception has been thrown, // Complete is not called and the transaction is rolled back. scope.Complete(); } } catch (TransactionAbortedException ex) { writer.WriteLine("TransactionAbortedException Message: {0}", ex.Message); } catch (SqlException ex) { if (ex.Number == 2627) { // Violation in unique constraint writer.WriteLine("Violation of Unique Constraint Message:\n {0}", ex.Message); } } // Display messages. Console.WriteLine(writer.ToString()); Console.WriteLine("Transactions made: " + _TransactionsMade); return(InsertAttempt); }
public void TransactedPosting() { if (enabled) { string testName = "TransactedPosting"; path = "test." + testName; int nMsgs = 5; Connection connection = new Connection(address); Session session = new Session(connection); SenderLink sender = new SenderLink(session, "sender-" + testName, path); // commit using (var ts = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled)) { for (int i = 0; i < nMsgs; i++) { Message message = new Message("test"); message.Properties = new Properties() { MessageId = "commit" + i, GroupId = testName }; sender.Send(message); } ts.Complete(); } // rollback using (var ts = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled)) { for (int i = nMsgs; i < nMsgs * 2; i++) { Message message = new Message("test"); message.Properties = new Properties() { MessageId = "rollback" + i, GroupId = testName }; sender.Send(message); } } // commit using (var ts = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled)) { for (int i = 0; i < nMsgs; i++) { Message message = new Message("test"); message.Properties = new Properties() { MessageId = "commit" + i, GroupId = testName }; sender.Send(message); } ts.Complete(); } Connection connection2 = new Connection(address); Session session2 = new Session(connection2); ReceiverLink receiver = new ReceiverLink(session2, "receiver-" + testName, path); for (int i = 0; i < nMsgs * 2; i++) { Message message = receiver.Receive(); Trace.WriteLine(TraceLevel.Information, "receive: {0}", message.Properties.MessageId); receiver.Accept(message); Assert.StartsWith("commit", message.Properties.MessageId); } // shouldn't be any messages left Message empty = receiver.Receive(TimeSpan.Zero); Assert.Null(empty); connection.Close(); connection2.Close(); } }
/// <summary> /// 内容相册上传 /// </summary> /// <param name="context"></param> private void OnUploadPictureContent(HttpContext context) { context.Response.ContentType = "text/plain"; string errorMsg = ""; try { HttpFileCollection files = context.Request.Files; if (files.Count == 0) { context.Response.Write("{\"success\": false,\"message\": \"未找到任何可上传的文件,请检查!\"}"); return; } object userId = WebCommon.GetUserId(); int effect = 0; UploadFilesHelper ufh = new UploadFilesHelper(); ImagesHelper ih = new ImagesHelper(); using (TransactionScope scope = new TransactionScope()) { foreach (string item in files.AllKeys) { HttpPostedFile file = files[item]; if (file == null || file.ContentLength == 0) { continue; } int fileSize = file.ContentLength; int uploadFileSize = int.Parse(WebConfigurationManager.AppSettings["UploadFileSize"]); if (fileSize > uploadFileSize) { throw new ArgumentException("文件【" + file.FileName + "】大小超出字节" + uploadFileSize + ",无法上传,请正确操作!"); } if (!UploadFilesHelper.IsFileValidated(file.InputStream, fileSize)) { throw new ArgumentException("文件【" + file.FileName + "】为受限制的文件,请正确操作!"); } string fileName = file.FileName; PictureContent bll = new PictureContent(); if (bll.IsExist(userId, file.FileName, fileSize)) { throw new ArgumentException("文件【" + file.FileName + "】已存在,请勿重复上传!"); } string originalUrl = UploadFilesHelper.UploadOriginalFile(file, "PictureContent"); //获取随机生成的文件名代码 string randomFolder = UploadFilesHelper.GetRandomFolder(originalUrl); PictureContentInfo model = new PictureContentInfo(); model.UserId = userId; model.FileName = VirtualPathUtility.GetFileName(originalUrl); model.FileSize = fileSize; model.FileExtension = VirtualPathUtility.GetExtension(originalUrl).ToLower(); model.FileDirectory = VirtualPathUtility.GetDirectory(originalUrl.Replace("~", "")); model.RandomFolder = randomFolder; model.LastUpdatedDate = DateTime.Now; bll.Insert(model); CreateThumbnailImage(context, ih, originalUrl, model.FileDirectory, model.RandomFolder, model.FileExtension); effect++; } scope.Complete(); } if (effect == 0) { context.Response.Write("{\"success\": false,\"message\": \"未找到任何可上传的文件,请检查!\"}"); return; } context.Response.Write("{\"success\": true,\"message\": \"已成功上传文件数:" + effect + "个\"}"); return; } catch (Exception ex) { errorMsg = ex.Message; } context.Response.Write("{\"success\": false,\"message\": \"" + errorMsg + "\"}"); }
private void NestedScopeInternalTest( TransactionScopeOption nestedOption, bool innerComplete, bool outerComplete, bool expectInnerChangesVisible, bool expectOuterChangesVisible) { executeSQL("CREATE TABLE T(str varchar(10))"); try { using (TransactionScope outer = new TransactionScope()) { string connStr = Connection.ConnectionString; using (MySqlConnection c1 = new MySqlConnection(connStr)) { c1.Open(); //MySqlCommand cmd1 = new MySqlCommand("LOCK TABLES T WRITE;", c1); //cmd1.ExecuteNonQuery(); MySqlCommand cmd1 = new MySqlCommand("INSERT INTO T VALUES ('outer')", c1); cmd1.ExecuteNonQuery(); //cmd1 = new MySqlCommand("UNLOCK TABLES", c1); //cmd1.ExecuteNonQuery(); using (TransactionScope inner = new TransactionScope(nestedOption)) { MySqlConnection c2; if (nestedOption == TransactionScopeOption.Required) { // inner scope joins already running ambient // transaction, we cannot use new connection here c2 = c1; } else { // when TransactionScopeOption.RequiresNew or // new TransactionScopeOption.Suppress is used, // we have to use a new transaction. We create a // new connection for it. c2 = new MySqlConnection(connStr); c2.Open(); } //MySqlCommand cmd2 = new MySqlCommand("LOCK TABLES T WRITE;", c2); //cmd2.ExecuteNonQuery(); MySqlCommand cmd2 = new MySqlCommand("INSERT INTO T VALUES ('inner')", c2); cmd2.ExecuteNonQuery(); //cmd2 = new MySqlCommand("UNLOCK TABLES", c2); //cmd2.ExecuteNonQuery(); if (innerComplete) { inner.Complete(); } // Dispose connection if it was created. if (c2 != c1) c2.Dispose(); } } if (outerComplete) outer.Complete(); } bool innerChangesVisible = ((long)MySqlHelper.ExecuteScalar(Connection, "select count(*) from T where str = 'inner'") == 1); bool outerChangesVisible = ((long)MySqlHelper.ExecuteScalar(Connection, "select count(*) from T where str = 'outer'") == 1); Assert.Equal(innerChangesVisible, expectInnerChangesVisible); Assert.Equal(outerChangesVisible, expectOuterChangesVisible); } finally { MySqlHelper.ExecuteNonQuery(Connection, "DROP TABLE T"); } }
public void TryGetRelationAddresses() { IContactAgent agent = ContactAgentFactory.CreateContactAgent(); List <DocumentItem> documentItemsSaved; List <AddressItem> addressItemsSaved; RelationItem relationItemSaved; List <RelationAddressItem> relationAddressItemsSaved; List <RelationDocumentItem> relationDocumentItemsSaved; List <CountryItem> countryItemsSaved; AddressItem[] addressItems; int count = 0; try { using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required)) { Debug.WriteLine("Creating all objects on " + DateTime.Now); List <AddressItem> addressItemsNew = GetAddressItems(2); List <CountryItem> countryItemsNew = GetCountryItems(2); List <DocumentItem> documentItemsNew = GetDocumentItems(2); RelationItem relationItemNew = GetRelationItem(); List <RelationAddressItem> relationAddressItemsNew = GetRelationAddressItems(2); List <RelationDocumentItem> relationDocumentItemsNew = GetRelationDocumentItems(2); Debug.WriteLine("All objects in memory on {0}", DateTime.Now); Debug.WriteLine("Saving all objects"); count = countryItemsNew.Count; countryItemsSaved = new List <CountryItem>(count); Debug.WriteLine("Saving countries objects"); for (int i = 0; i < count; i++) { CountryItem countryItemSaved = agent.SaveCountryItem(countryItemsNew[i]); Debug.WriteLine("CountryItem {0} / {1} saved {2}on {3}", (i + 1), count, (countryItemSaved.HasErrors ? "with errors " : ""), DateTime.Now); countryItemsSaved.Add(countryItemSaved); } count = documentItemsNew.Count; documentItemsSaved = new List <DocumentItem>(count); Debug.WriteLine("Saving documents objects"); for (int i = 0; i < count; i++) { DocumentItem documentItemSaved = agent.SaveDocumentItem(documentItemsNew[i]); Debug.WriteLine("DocumentItem {0} / {1} saved {2}on {3}", (i + 1), count, (documentItemSaved.HasErrors ? "with errors " : ""), DateTime.Now); documentItemsSaved.Add(documentItemSaved); } relationItemSaved = agent.SaveRelationItem(relationItemNew); Debug.WriteLine("AddressItem saved {0}on {1}", (relationItemSaved.HasErrors ? "with errors " : ""), DateTime.Now); count = addressItemsNew.Count; addressItemsSaved = new List <AddressItem>(count); Debug.WriteLine("Saving addresses objects"); for (int i = 0; i < count; i++) { AddressItem addressItemSaved = agent.SaveAddressItem(addressItemsNew[i]); Debug.WriteLine("CountryItem {0} / {1} saved {2}on {3}", (i + 1), count, (addressItemSaved.HasErrors ? "with errors " : ""), DateTime.Now); addressItemsSaved.Add(addressItemSaved); } count = relationAddressItemsNew.Count; relationAddressItemsSaved = new List <RelationAddressItem>(count); Debug.WriteLine("Saving RelationAddress objects"); for (int i = 0; i < count; i++) { RelationAddressItem relationAddressItemSaved = agent.SaveRelationAddressItem(relationAddressItemsNew[i]); Debug.WriteLine("RelationAddressItem {0} / {1} saved {2}on {3}", (i + 1), count, (relationAddressItemSaved.HasErrors ? "with errors " : ""), DateTime.Now); relationAddressItemsSaved.Add(relationAddressItemSaved); } count = relationDocumentItemsNew.Count; relationDocumentItemsSaved = new List <RelationDocumentItem>(count); Debug.WriteLine("Saving RelationDocument objects"); for (int i = 0; i < count; i++) { RelationDocumentItem relationDocumentItemSaved = agent.SaveRelationDocumentItem(relationDocumentItemsNew[i]); Debug.WriteLine("RelationDocumentItem {0} / {1} saved {2}on {3}", (i + 1), count, (relationDocumentItemSaved.HasErrors ? "with errors " : ""), DateTime.Now); relationDocumentItemsSaved.Add(relationDocumentItemSaved); } Debug.WriteLine("All objects saved"); Debug.WriteLine("Before commiting transaction"); scope.Complete(); Debug.WriteLine("Commit transaction completed"); } addressItems = agent.GetAddressItemsForRelation(ContactTestFixtureData.Keys.Relation[1]); } catch (Exception e) { Debug.WriteLine("Error(s) occured\n" + e.Message); } }