public void GenerEventCyclingMatch(List <t_event_cycling_match> list, t_event_cycling cyc) { try { _dbContext.BeginTransaction(); //先把当前轮次,组,比赛的准备录入状态的对垒表删除 string sql1 = $@" DELETE from t_event_cycling_match where cyclingMatchStatus = 1 and eventid = {cyc.eventId} and eventgroupid = {cyc.eventGroupId} and cyclingDetailId in (SELECT id from t_event_cycling_detail where cyclingraceid = {cyc.id}) "; object r1 = _dbContext.ExecuteScalar(sql1); string sql2 = $@" insert into t_event_cycling_match (eventId,eventGroupId,progroupNum ,congroupNum ,roomId ,refereeId ,cyclingDetailId ,isBye ,cyclingMatchStatus ,createtime ,updatetime ,isdelete ) "; string values = string.Empty; for (int i = 0; i < list.Count; i++) { if (i == 0) { values += $@" SELECT '{list[i].eventId}','{list[i].eventGroupId}','{list[i].progroupNum}','{list[i].congroupNum}','{list[i].roomId}' ,'{list[i].refereeId}','{list[i].cyclingDetailId}',{list[i].isBye},1,'{DateTime.Now}','{DateTime.Now}',FALSE "; } else { values += $@" union ALL SELECT '{list[i].eventId}','{list[i].eventGroupId}','{list[i].progroupNum}','{list[i].congroupNum}','{list[i].roomId}' ,'{list[i].refereeId}','{list[i].cyclingDetailId}',{list[i].isBye},1,'{DateTime.Now}','{DateTime.Now}',FALSE "; } } if (list.Count > 0) { sql2 = sql2 + values; object r2 = _dbContext.ExecuteScalar(sql2); } _dbContext.CommitChanges(); } catch (Exception ex) { _dbContext.Rollback(); LogUtils.LogError("EventCyclingMatchRepo.GenerEventCyclingMatch", ex); } }
//处理退款 public bool Process(int id, int sysUserId, out string msg) { bool flag = false; msg = string.Empty; try { t_order_operation order_operation = _dbContext.Get <t_order_operation>(id); if (order_operation != null) { if (order_operation.operationStatus == OperationStatusEm.待处理) { msg = "状态已改变请刷新页面后重试"; return(flag); } try { _dbContext.BeginTransaction(); order_operation.updatetime = DateTime.Now; order_operation.operationStatus = OperationStatusEm.已处理; _dbContext.Update(order_operation); t_order torder = _dbContext.Get <t_order>(order_operation.orderId); torder.updatetime = DateTime.Now; torder.orderStatus = OrderStatusEm.退款成功; _dbContext.Update(torder); _dbContext.CommitChanges(); flag = true; } catch (Exception ex) { _dbContext.Rollback(); flag = false; msg = "服务异常"; LogUtils.LogError("OrderService.ProcessTran", ex); } } else { msg = "未找到退款申请"; } } catch (Exception ex) { flag = false; msg = "服务异常"; LogUtils.LogError("OrderService.Process", ex); } return(flag); }
public void Test_Create_Child_ActivityDetail() { ChildActivityDetail cg = new ChildActivityDetail() { EventDate = DateTime.Today, StartTime = DateTime.Now, Child = new ChildDetail() { Key = 1 }, Activity = new ChildActivityType() { Key = 3 } }; NHibernateRepository ds = new NHibernateRepository(_sessionFactory); using (ctx = ctx.Start()) { ctx.BeginTransaction(); ds.Add(cg); ctx.Commit(); Console.WriteLine(cg.Key); Assert.That(cg.Key > 0); } }
public ActionResult UploadDataFile(HttpPostedFileBase file, string uploadMode) { AjaxResult ajaxResult = new AjaxResult(); RepoResult repoResult = null; IDBContext db = databaseManager.GetContext(); IList <string> errMesgs = new List <string>(); IList <Items> data = new List <Items>(); Toyota.Common.Credential.User u = Lookup.Get <Toyota.Common.Credential.User>(); string userName = u.Username; try { data = this.GetDataLocalUploadExcel(file, errMesgs); if (errMesgs.Count >= 1) { ajaxResult.Result = AjaxResult.VALUE_ERROR; ajaxResult.ErrMesgs = new string[] { string.Format("{0}", errMesgs[0]) }; } else { db.BeginTransaction(); foreach (Items loopInsert in data) { repoResult = itemRepo.InsertUpdate(db, userName, loopInsert, uploadMode); } CopyPropertiesRepoToAjaxResult(repoResult, ajaxResult); if (AjaxResult.VALUE_ERROR.Equals(ajaxResult.Result)) { db.AbortTransaction(); } else { db.CommitTransaction(); } } } catch (Exception ex) { db.AbortTransaction(); ajaxResult.Result = AjaxResult.VALUE_ERROR; ajaxResult.ErrMesgs = new string[] { string.Format("{0} = {1}", ex.GetType().FullName, ex.Message) }; } finally { db.Close(); } return(Json(ajaxResult)); }
//编辑循环赛规则 public bool CyclingRaceRule(CyclingRaceRuleRequest request, out string msg) { bool flag = false; msg = string.Empty; try { _dbContext.BeginTransaction(); foreach (var item in request.Teamscoringrule) { var sql = $"update t_event_teamscoringrule set teamScoringRules={(int)item.TeamScoringRules},updatetime='{DateTime.Now}' where id={item.Id}"; _dbContext.Execute(sql); } foreach (var item in request.Scoringrule) { var sql = $"update t_event_playerscoringrule set scoringRules={(int)item.ScoringRules},updatetime='{DateTime.Now}' where id={item.Id}"; _dbContext.Execute(sql); } foreach (var item in request.Avoidrule) { var sql = $"update t_event_cycling_avoidrule set avoidRules={(int)item.AvoidRules},updatetime='{DateTime.Now}' where id={item.Id}"; _dbContext.Execute(sql); } foreach (var item in request.RefereeAvoidrule) { var sql = $"update t_event_refereeavoidrule set refereeAvoidRules={(int)item.RefereeAvoidRules},updatetime='{DateTime.Now}' where id={item.Id}"; _dbContext.Execute(sql); } _dbContext.CommitChanges(); flag = true; } catch (Exception ex) { _dbContext.Rollback(); flag = false; msg = "服务异常"; LogUtils.LogError("EventRuleService.CyclingRaceRule", ex); } return(flag); }
public JsonResult AddEditSave(string screenMode, PakAnas.Models.Approval data) { AjaxResult ajaxResult = new AjaxResult(); RepoResult repoResult = null; IDBContext db = databaseManager.GetContext(); try { db.BeginTransaction(); ajaxResult = Validation(data); //Validasi Controller if (AjaxResult.VALUE_SUCCESS.Equals(ajaxResult.Result)) { if (CommonConstant.SCREEN_MODE_ADD.Equals(screenMode)) { repoResult = approvalRepo.Insert(GetLoginUserId(), data); } else if (CommonConstant.SCREEN_MODE_EDIT.Equals(screenMode)) { repoResult = approvalRepo.Update(GetLoginUserId(), data); } CopyPropertiesRepoToAjaxResult(repoResult, ajaxResult); if (AjaxResult.VALUE_ERROR.Equals(ajaxResult.Result)) { db.AbortTransaction(); } else { db.CommitTransaction(); } } } catch (Exception ex) { db.AbortTransaction(); ajaxResult.Result = AjaxResult.VALUE_ERROR; ajaxResult.ErrMesgs = new string[] { string.Format("{0} = {1}", ex.GetType().FullName, ex.Message) }; } finally { db.Close(); } return(Json(ajaxResult)); }
public int UpdateData(string record, string table, string PK) { IDBContext db = DatabaseManager.Instance.GetContext(); var tambah = record.Replace("+", " "); var ubah = tambah.Replace("%3A", ":"); var split = ubah.Split('&'); var tampung = ""; string[] split_tampungnya; var field = ""; var value = ""; int res = 0; db.BeginTransaction(); try { for (int i = 0; i < split.Length; i++) { tampung = split[i]; split_tampungnya = tampung.Split('='); if (field == "") { field = split_tampungnya[0].ToString(); value = split_tampungnya[1].ToString(); } else { field = field + "," + split_tampungnya[0].ToString(); value = value + "," + split_tampungnya[1].ToString(); } } res = db.Execute("Master/SimpleMasterCustom_UpdateData", new { P_FIELD = field, P_VALUE = value, P_TABLE = table, PK = PK, }); db.Close(); db.CommitTransaction(); } catch (Exception E) { db.AbortTransaction(); } return(res); }
// 支付回调 public void Callback(int orderId, string paytransaction) { try { var order = _dbContext.Get <t_order>(orderId); if (order != null && (order.orderStatus == OrderStatusEm.等待支付 || order.orderStatus == OrderStatusEm.支付失败)) { try { _dbContext.BeginTransaction(); //修改订单状态 order.orderStatus = OrderStatusEm.支付成功; order.updatetime = DateTime.Now; _dbContext.Update(order); //修改支付流水信息 _dbContext.Execute($"update t_order_paylog set paytransaction='{paytransaction}',notifyTime='{DateTime.Now}',payStatus={(int)PayStatusEm.支付成功} where orderId={orderId} and isdelete=0"); _dbContext.CommitChanges(); Task.Factory.StartNew(() => { if (order.orderType == OrderTypeEm.实名认证) { _memberService.CallBack(order.memberId); } else if (order.orderType == OrderTypeEm.临时选手绑定) { _memberTempService.Callback(order.memberId, order.sourceId); } else if (order.orderType == OrderTypeEm.赛事报名) { _playerSignUpService.Callback(order.memberId, order.sourceId); } }); } catch (Exception ex) { LogUtils.LogError("PayCallBackService.CallbackTran", ex); _dbContext.Rollback(); } } } catch (Exception ex) { LogUtils.LogError("PayCallBackService.Callback", ex); } }
public JsonResult Delete(List <string> selectedKeys) { AjaxResult ajaxResult = new AjaxResult(); RepoResult repoResult = null; IDBContext db = databaseManager.GetContext(); try { db.BeginTransaction(); repoResult = pakanasRepo.DeleteMultiple(db, selectedKeys); CopyPropertiesRepoToAjaxResult(repoResult, ajaxResult); if (AjaxResult.VALUE_ERROR.Equals(ajaxResult.Result)) { db.AbortTransaction(); } else { db.CommitTransaction(); } } catch (Exception ex) { db.AbortTransaction(); ajaxResult.Result = AjaxResult.VALUE_ERROR; ajaxResult.ErrMesgs = new string[] { string.Format("{0} = {1}", ex.GetType().FullName, ex.Message) }; } finally { db.Close(); } return(Json(ajaxResult)); }
public int DeleteData(string PK, string table) { IDBContext db = DatabaseManager.Instance.GetContext(); int res = 0; db.BeginTransaction(); try { res = db.Execute("Master/SimpleMasterCustom_DeleteData", new { PK = PK, TABLE_NAME = table }); db.Close(); db.CommitTransaction(); } catch (Exception E) { db.AbortTransaction(); } return(res); }
//奖项设置 public bool Settings(EventRegularAwardsRequest request, out string msg) { bool flag = false; msg = string.Empty; try { try { _dbContext.BeginTransaction(); _dbContext.Execute($"delete from t_event_regularawards where eventId={request.EventId} and eventGroupId={request.EventGroupId}"); _dbContext.Insert(new t_event_regularawards { eventGroupId = request.EventGroupId, eventId = request.EventId, prizeGroup = request.PrizeGroup, personal = request.Personal }); _dbContext.CommitChanges(); flag = true; } catch (Exception ex) { _dbContext.Rollback(); flag = false; msg = "服务异常"; LogUtils.LogError("EventRegularAwardsService.SettingsTran", ex); } } catch (Exception ex) { flag = false; msg = "服务异常"; LogUtils.LogError("EventRegularAwardsService.Settings", ex); } return(flag); }
public override kCura.EventHandler.Response Execute() { // Update Security Protocol ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; // Get logger Relativity.API.IAPILog _logger = this.Helper.GetLoggerFactory().GetLogger().ForContext <PostInstallEventHandler>(); // Init general response kCura.EventHandler.Response response = new kCura.EventHandler.Response() { Success = true, Message = "" }; // Get current Workspace ID int workspaceId = this.Helper.GetActiveCaseID(); _logger.LogDebug("Audit Log Elastic Search, current Workspace ID: {workspaceId}", workspaceId.ToString()); // Get database context of the instance IDBContext instanceContext = Helper.GetDBContext(-1); // Existing application management table name string tableExisting = ""; try { // Get application management table tableExisting = instanceContext.ExecuteSqlStatementAsScalar("SELECT ISNULL((SELECT '" + this.TableName + "' FROM [INFORMATION_SCHEMA].[TABLES] WHERE [TABLE_SCHEMA] = 'eddsdbo' AND [TABLE_NAME] = '" + this.TableName + "'), '')").ToString(); } catch (Exception e) { _logger.LogError(e, "Audit Log Elastic Search, Post Install EventHandler application management table error"); response.Success = false; response.Message = "Post Install EventHandler management application table error"; return(response); } // If application management table not present, create it if (tableExisting != this.TableName) { instanceContext.BeginTransaction(); try { // Create application management table instanceContext.ExecuteNonQuerySQLStatement("CREATE TABLE [eddsdbo].[" + this.TableName + "] ([CaseArtifactID] [int] NOT NULL, [AuditRecordID] [bigint] NOT NULL, [Status] [bit] NOT NULL, [LastUpdated] [datetime] NOT NULL, [AgentArtifactID] [int] NULL)"); instanceContext.CommitTransaction(); } catch (Exception e) { instanceContext.RollbackTransaction(); _logger.LogError(e, "Audit Log Elastic Search, Post Install EventHandler application management table creation error"); response.Success = false; response.Message = "Post Install EventHandler application management table creation error"; return(response); } } // Add line to the application management table for current workspace try { // Insert to the application management table SqlParameter workspaceIdParam = new SqlParameter("@workspaceId", workspaceId); instanceContext.ExecuteNonQuerySQLStatement("INSERT INTO [eddsdbo].[" + this.TableName + "] ([CaseArtifactID], [AuditRecordID], [Status], [LastUpdated]) VALUES (@workspaceId, 0, 1, CURRENT_TIMESTAMP)", new SqlParameter[] { workspaceIdParam }); } catch (Exception e) { _logger.LogError(e, "Audit Log Elastic Search, Post Install EventHandler application management table insert error"); response.Success = false; response.Message = "Post Install EventHandler application management table insert error"; return(response); } // Log end of Post Install EventHandler _logger.LogDebug("Audit Log Elastic Search, Post Install EventHandler successfully finished"); return(response); }
public ActionResult AddEditSave(string screenMode, Items data) { AjaxResult ajaxResult = new AjaxResult(); RepoResult repoResult = null; IDBContext db = databaseManager.GetContext(); Toyota.Common.Credential.User u = Lookup.Get <Toyota.Common.Credential.User>(); string userName = u.Username; try { db.BeginTransaction(); ajaxResult = Validation(data); //Validasi Controller if (AjaxResult.VALUE_SUCCESS.Equals(ajaxResult.Result)) { if (CommonConstant.SCREEN_MODE_EDIT.Equals(screenMode)) { Items dtUpload = itemRepo.GetByKey(data.ITEM_CODE); if (dtUpload.UPLOAD_PATH != null) { if (dtUpload.UPLOAD_PATH != data.UPLOAD_HALF_PATH) { this.DeleteUploadedFile(dtUpload.UPLOAD_PATH); } } } repoResult = itemRepo.InsertUpdate(db, userName, data, screenMode); CopyPropertiesRepoToAjaxResult(repoResult, ajaxResult); if (AjaxResult.VALUE_ERROR.Equals(ajaxResult.Result)) { db.AbortTransaction(); } else { db.CommitTransaction(); string sourceDirPath = itemRepo.FindBySettingCd(CommonConstant.SYS_FILE_LOC_TEMP_FOLDER); string destDirPath = itemRepo.FindBySettingCd(CommonConstant.SYS_FILE_LOC_MAIN_FOLDER); MoveFiles(sourceDirPath, destDirPath, data.UPLOAD_HALF_PATH); } } } catch (Exception ex) { db.AbortTransaction(); ajaxResult.Result = AjaxResult.VALUE_ERROR; ajaxResult.ErrMesgs = new string[] { string.Format("{0} = {1}", ex.GetType().FullName, ex.Message) }; } finally { db.Close(); } return(Json(ajaxResult)); }
//淘汰赛设置 public bool Settints(List <EventknockoutSettingsRequest> request, out string msg) { bool flag = false; msg = string.Empty; try { var model = request.FirstOrDefault(); if (model.EventId <= 0) { msg = "赛事信息有误"; return(flag); } if (request == null || request.Count == 0) { msg = "请核对参数后再保存"; return(flag); } //循环遍历判断参数合法性 foreach (var item in request) { if (item.Teamnumber <= 0) { msg = "晋级队伍数有误"; return(flag); } string message = string.Empty; foreach (var items in item.ListKnockout) { if (items.RefereeCount <= 0) { message = "裁判数量有误"; break; } if (items.Screenings <= 0) { message = "场次有误"; break; } //if (items.Screenings != items.ListKnockoutDetail.Count) //{ // message = "场次对应信息有误"; // break; //} string messages = string.Empty; foreach (var itemss in items.ListKnockoutDetail) { if (itemss.CompTime == DateTime.MaxValue || itemss.CompTime == DateTime.MinValue) { messages = "Flight开始时间有误"; break; } } if (messages.IsNotEmpty()) { message = messages; break; } } if (message.IsNotEmpty()) { msg = message; break; } } if (msg.IsNotEmpty()) { return(flag); } try { _dbContext.BeginTransaction(); _dbContext.Execute($"delete from t_event_knockout_settings where eventId={model.EventId}"); _dbContext.Execute($"delete from t_event_knockout where eventId={model.EventId}"); _dbContext.Execute($"delete from t_event_knockout_detail where eventId={model.EventId}"); foreach (var item in request) { //淘汰赛设置表 int settingsId = _dbContext.Insert(new t_event_knockout_settings { eventGroupId = item.EventGroupId, eventId = item.EventId, teamnumber = item.Teamnumber }).ToObjInt(); //淘汰赛表 foreach (var items in item.ListKnockout) { int knockoutId = _dbContext.Insert(new t_event_knockout { knockoutStatus = items.KnockoutStatus, knockoutType = items.KnockoutType, refereeCount = items.RefereeCount, eventGroupId = items.EventGroupId, screenings = items.Screenings, eventId = items.EventId, settingsId = settingsId, pairRule = items.PairRule }).ToObjInt(); foreach (var itemss in items.ListKnockoutDetail) { _dbContext.Insert(new t_event_knockout_detail { knockoutId = knockoutId, eventGroupId = itemss.EventGroupId, eventId = itemss.EventId, screenings = itemss.Screenings, comptime = itemss.CompTime }); } } } _dbContext.CommitChanges(); flag = true; } catch (Exception ex) { _dbContext.Rollback(); flag = false; msg = "服务异常"; LogUtils.LogError("EventknockoutSettingsService.InsertTran", ex); } } catch (Exception ex) { flag = false; msg = "服务异常"; LogUtils.LogError("EventknockoutSettingsService.Insert", ex); } return(flag); }
//临时选手绑定 生成支付订单 public int BindTempPlayer(BindTempPlayerRequest request, out string msg) { int orderId = 0; msg = string.Empty; try { //校验数据的真实性 if (request.EventCode.IsEmpty()) { msg = "赛事编码不能为空"; return(orderId); } if (request.GroupNum.IsEmpty()) { msg = "队伍编码不能为空"; return(orderId); } if (request.PlayerName.IsEmpty()) { msg = "选手姓名不能为空"; return(orderId); } if (request.ContactMobile.IsEmpty()) { msg = "联系电话不能为空"; return(orderId); } var tevent = _dbContext.Select <t_event>(c => c.code == request.EventCode).FirstOrDefault(); if (tevent == null) { msg = "赛事编码有误"; return(orderId); } if (tevent.eventStatus != EventStatusEm.比赛完成) { msg = "赛事未完成不能进行绑定"; return(orderId); } var data = _dbContext.Select <t_member_temp>(c => c.name == request.PlayerName && c.contactmobile == request.ContactMobile && c.code == request.GroupNum && c.tempType == TempTypeEm.临时选手 && c.tempStatus == TempStatusEm.待绑定 && c.eventId == tevent.id).FirstOrDefault(); if (data == null) { msg = "数据不存在,请核对后再操作"; return(orderId); } //if (data.tomemberId != null && data.tomemberId > 0) //{ // if (data.tomemberId != request.MemberId) // { // msg = "此信息已绑定过"; // return orderId; // } //} t_order order = _dbContext.Select <t_order>(c => c.memberId == data.memberId && c.orderType == OrderTypeEm.临时选手绑定 && c.sourceId == data.id).FirstOrDefault(); if (order == null)//没创建过订单 { try { _dbContext.BeginTransaction(); //创建订单 var orderid = _dbContext.Insert(new t_order { isNeedInvoice = false, mainOrderId = null, memberId = data.memberId, money = tevent.signfee, orderStatus = OrderStatusEm.等待支付, orderType = OrderTypeEm.临时选手绑定, payExpiryDate = DateTime.Now.AddYears(3), remark = "临时选手绑定", sourceId = data.id, totalcoupon = 0, totaldiscount = 0 }).ToObjInt(); _dbContext.Insert(new t_order_detail { memberId = data.memberId, orderId = orderid, coupon = 0, discountprice = 0, money = tevent.signfee, productId = 0, name = $"{tevent.name}报名费", number = 1, unitprice = tevent.signfee }); //生成支付链接 data.tomemberId = request.MemberId; data.updatetime = DateTime.Now; _dbContext.Update(data); _dbContext.CommitChanges(); orderId = orderid; } catch (Exception ex) { msg = "服务异常"; _dbContext.Rollback(); LogUtils.LogError("MemberTempService.BindTempPlayerTran", ex); } } else//创建过订单 { if (order.orderStatus != OrderStatusEm.等待支付 && order.orderStatus != OrderStatusEm.支付失败) { orderId = order.id; } else { msg = "状态已改变"; } } } catch (Exception ex) { msg = "服务异常"; LogUtils.LogError("MemberTempService.BindTempPlayer", ex); } return(orderId); }
public override void Execute() { // Update Security Protocol ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; // Get logger Relativity.API.IAPILog _logger = this.Helper.GetLoggerFactory().GetLogger().ForContext <Agent>(); // Get current Agent ID int agentArtifactId = this.AgentID; _logger.LogDebug("Audit Log Elastic Search, current Agent ID: {agentArtifactId}", agentArtifactId.ToString()); // Display initial message this.RaiseMessageNoLogging("Getting Instance Settings.", 10); // Get ES URI Instance Settings List <Uri> elasticUris = new List <Uri>(); try { string[] uris = this.Helper.GetInstanceSettingBundle().GetString("Relativity.AuditLogElasticSearch", "ElasticSearchUris").Split(';'); foreach (string uri in uris) { if (Uri.IsWellFormedUriString(uri, UriKind.Absolute)) { elasticUris.Add(new Uri(uri)); } else { _logger.LogError("Audit Log Elastic Search, Agent ({agentArtifactId}), Instance Settings error (ElasticSearchUri), single URI error ({uri})", agentArtifactId.ToString(), uri); this.RaiseMessageNoLogging(string.Format("Instance Settings error (ElasticSearchUri), single URI error ({0}).", uri), 1); return; } } } catch (Exception e) { _logger.LogError(e, "Audit Log Elastic Search, Agent ({agentArtifactId}), Instance Settings error (ElasticSearchUri)", agentArtifactId.ToString()); this.RaiseMessageNoLogging("Instance Settings error (ElasticSearchUri).", 1); return; } // Get ES authentication API Key Instance Settings string[] elasticApiKey = new string[] { "", "" }; try { string apiKey = this.Helper.GetInstanceSettingBundle().GetString("Relativity.AuditLogElasticSearch", "ElasticSearchApiKey"); if (apiKey.Length > 0) { if (apiKey.Split(':').Length == 2) { elasticApiKey = apiKey.Split(':'); } else { _logger.LogError("Audit Log Elastic Search, Agent ({agentArtifactId}), Instance Settings error (ElasticSearchApiKey), API Key format error ({apiKey})", agentArtifactId.ToString(), apiKey); this.RaiseMessageNoLogging(string.Format("Instance Settings error (ElasticSearchApiKey), API Key format error ({0}).", apiKey), 1); return; } } } catch (Exception e) { _logger.LogError(e, "Audit Log Elastic Search, Agent ({agentArtifactId}), Instance Settings error (ElasticSearchApiKey)", agentArtifactId.ToString()); this.RaiseMessageNoLogging("Instance Settings error (ElasticSearchApiKey).", 1); return; } // Get ES index prefix Instance Settings (must by lowercase) string elasticIndexPrefix = ""; try { elasticIndexPrefix = this.Helper.GetInstanceSettingBundle().GetString("Relativity.AuditLogElasticSearch", "ElasticSearchIndexPrefix").ToLower(); } catch (Exception e) { _logger.LogError(e, "Audit Log Elastic Search, Agent ({agentArtifactId}), Instance Settings error (ElasticSearchIndexPrefix)", agentArtifactId.ToString()); this.RaiseMessageNoLogging("Instance Settings error (ElasticSearchIndexPrefix).", 1); return; } // Get ES index number of replicas Instance Settings int elasticIndexReplicas = 1; try { elasticIndexReplicas = this.Helper.GetInstanceSettingBundle().GetInt("Relativity.AuditLogElasticSearch", "ElasticSearchIndexReplicas").Value; if (elasticIndexReplicas < 0) { elasticIndexReplicas = 1; } } catch (Exception e) { _logger.LogError(e, "Audit Log Elastic Search, Agent ({agentArtifactId}), Instance Settings error (ElasticSearchIndexReplicas)", agentArtifactId.ToString()); this.RaiseMessageNoLogging("Instance Settings error (ElasticSearchIndexReplicas).", 1); return; } // Get ES index number of shards Instance Settings int elasticIndexShards = 1; try { elasticIndexShards = this.Helper.GetInstanceSettingBundle().GetInt("Relativity.AuditLogElasticSearch", "ElasticSearchIndexShards").Value; if (elasticIndexShards < 0) { elasticIndexShards = 1; } } catch (Exception e) { _logger.LogError(e, "Audit Log Elastic Search, Agent ({agentArtifactId}), Instance Settings error (ElasticSearchIndexShards)", agentArtifactId.ToString()); this.RaiseMessageNoLogging("Instance Settings error (ElasticSearchIndexShards).", 1); return; } // Get ES synchronization threshold for one agent run int elasticSyncSize = 1000; try { elasticSyncSize = this.Helper.GetInstanceSettingBundle().GetInt("Relativity.AuditLogElasticSearch", "ElasticSearchSyncSize").Value; if (elasticSyncSize < 1000) { elasticSyncSize = 1000; } } catch (Exception e) { _logger.LogError(e, "Audit Log Elastic Search, Agent ({agentArtifactId}), Instance Settings error (ElasticSearchSyncSize)", agentArtifactId.ToString()); this.RaiseMessageNoLogging("Instance Settings error (ElasticSearchSyncSize).", 1); return; } // Get database context of the instance IDBContext instanceContext = Helper.GetDBContext(-1); // Check if management table exists try { int exists = instanceContext.ExecuteSqlStatementAsScalar <int>("IF OBJECT_ID('[eddsdbo].[" + this.tableName + "]', 'U') IS NOT NULL SELECT 1 ELSE SELECT 0"); _logger.LogDebug("Audit Log Elastic Search, Agent ({agentArtifactId}), application management table " + (exists == 1 ? "exists" : "does not exist"), agentArtifactId.ToString()); if (exists != 1) { _logger.LogError("Audit Log Elastic Search, Agent ({agentArtifactId}), application management table does not exist", agentArtifactId.ToString()); this.RaiseMessageNoLogging("Application management table does not exist.", 1); return; } } catch (Exception e) { _logger.LogError(e, "Audit Log Elastic Search, Agent ({agentArtifactId}), application management table existence check error", agentArtifactId.ToString()); } _logger.LogDebug("Audit Log Elastic Search, Agent ({agentArtifactId}), selecting Workspace", agentArtifactId.ToString()); this.RaiseMessageNoLogging("Selecting Workspace.", 10); // Check what needs to be done int workspaceId = -1; long auditRecordId = -1; int status = -1; instanceContext.BeginTransaction(); try { // Get workspace that was synchronized latest DataTable dataTable = instanceContext.ExecuteSqlStatementAsDataTable(@" SELECT TOP(1) [CaseArtifactID], [AuditRecordID], [Status] FROM [eddsdbo].[" + this.tableName + @"] WHERE [AgentArtifactID] IS NULL ORDER BY [Status] ASC, [LastUpdated] ASC "); // If there is no workspace check if table is empty and if it is, delete it _logger.LogDebug("Audit Log Elastic Search, Agent ({agentArtifactId}), Workspace selection row count: {count}", agentArtifactId.ToString(), dataTable.Rows.Count.ToString()); if (dataTable.Rows.Count == 0) { int count = instanceContext.ExecuteSqlStatementAsScalar <int>("SELECT COUNT(*) FROM [eddsdbo].[" + this.tableName + "]"); _logger.LogDebug("Audit Log Elastic Search, Agent ({agentArtifactId}), application management table row count: {count}", agentArtifactId.ToString(), count.ToString()); // If there are no rows in the application management table better to drop it if (count == 0) { instanceContext.ExecuteNonQuerySQLStatement("DROP TABLE [eddsdbo].[" + this.tableName + "]"); _logger.LogDebug("Audit Log Elastic Search, Agent ({agentArtifactId}), application management table was deleted", agentArtifactId.ToString()); } } // Else we have workspace to work with else { DataRow dataRow = dataTable.Rows[0]; workspaceId = Convert.ToInt32(dataRow["CaseArtifactID"]); auditRecordId = Convert.ToInt64(dataRow["AuditRecordID"]); status = Convert.ToInt32(dataRow["Status"]); // Update the application management table with Agent ID lock SqlParameter agentArtifactIdParam = new SqlParameter("@agentArtifactId", agentArtifactId); SqlParameter workspaceIdParam = new SqlParameter("@workspaceId", workspaceId); instanceContext.ExecuteNonQuerySQLStatement("UPDATE [eddsdbo].[" + this.tableName + "] SET [AgentArtifactID] = @agentArtifactId WHERE [CaseArtifactID] = @workspaceId", new SqlParameter[] { agentArtifactIdParam, workspaceIdParam }); } instanceContext.CommitTransaction(); } catch (Exception e) { instanceContext.RollbackTransaction(); _logger.LogError(e, "Audit Log Elastic Search, Agent ({agentArtifactId}), application management table querying error", agentArtifactId.ToString()); this.RaiseMessageNoLogging("Application management table querying error.", 1); return; } // If we have Workspace ID we have to do something if (workspaceId > 0) { // Construct ES index name string elasticIndexName = elasticIndexPrefix + workspaceId.ToString(); // Construct connector to ES cluster Nest.ElasticClient elasticClient = null; try { Elasticsearch.Net.StaticConnectionPool pool = new Elasticsearch.Net.StaticConnectionPool(elasticUris, true); elasticClient = new Nest.ElasticClient(new Nest.ConnectionSettings(pool).DefaultIndex(elasticIndexName).ApiKeyAuthentication(elasticApiKey[0], elasticApiKey[1]).EnableHttpCompression()); } catch (Exception e) { this.releaseAgentLock(agentArtifactId, auditRecordId, workspaceId); _logger.LogError(e, "Audit Log Elastic Search, Agent ({agentArtifactId}) Elastic Search connection call error ({elasticUris}, {indexName})", agentArtifactId.ToString(), string.Join(";", elasticUris.Select(x => x.ToString()).ToArray()), elasticIndexName); this.RaiseMessageNoLogging(string.Format("Elastic Search connection call error ({0}, {1}).", string.Join(";", elasticUris.Select(x => x.ToString()).ToArray()), elasticIndexName), 1); return; } // Check ES cluster connection Nest.PingResponse pingResponse = elasticClient.Ping(); if (pingResponse.IsValid) { _logger.LogDebug("Audit Log Elastic Search, Agent ({agentArtifactId}), Ping succeeded ({elasticUris}, {indexName})", agentArtifactId.ToString(), string.Join(";", elasticUris.Select(x => x.ToString()).ToArray()), elasticIndexName); } else { this.releaseAgentLock(agentArtifactId, auditRecordId, workspaceId); _logger.LogError("Audit Log Elastic Search, Agent ({agentArtifactId}), Ping failed, check cluster health and connection settings ({elasticUris}, {indexName}, {elasticError})", agentArtifactId.ToString(), string.Join(";", elasticUris.Select(x => x.ToString()).ToArray()), elasticIndexName, pingResponse.DebugInformation); this.RaiseMessageNoLogging(string.Format("Elastic Search ping failed, check cluster health and connection settings ({0}, {1}, {2}).", string.Join(";", elasticUris.Select(x => x.ToString()).ToArray()), elasticIndexName, pingResponse.DebugInformation), 1); return; } switch (status) { // If the status is 0 we will be deleting ES index case 0: _logger.LogDebug("Audit Log Elastic Search, Agent ({agentArtifactId}), deleting ES index ({indexName})", agentArtifactId.ToString(), elasticIndexName); this.RaiseMessageNoLogging(string.Format("Deleting ES index ({0}).", elasticIndexName), 10); // Delete ES index try { Nest.DeleteIndexResponse deleteIndexResponse = elasticClient.Indices.Delete(elasticIndexName); if (deleteIndexResponse.Acknowledged) { _logger.LogDebug("Audit Log Elastic Search, Agent ({agentArtifactId}), Elastic Search index deleted ({elasticUris}, {indexName})", agentArtifactId.ToString(), string.Join(";", elasticUris.Select(x => x.ToString()).ToArray()), elasticIndexName); } else { this.releaseAgentLock(agentArtifactId, auditRecordId, workspaceId); _logger.LogError("Audit Log Elastic Search, Agent ({agentArtifactId}), Elastic Search index deletion error ({elasticUris}, {indexName})", agentArtifactId.ToString(), string.Join(";", elasticUris.Select(x => x.ToString()).ToArray()), elasticIndexName); this.RaiseMessageNoLogging(string.Format("Elastic Search index deletion error ({0}, {1}).", string.Join(";", elasticUris.Select(x => x.ToString()).ToArray()), elasticIndexName), 1); return; } } catch (Exception e) { this.releaseAgentLock(agentArtifactId, auditRecordId, workspaceId); _logger.LogError(e, "Audit Log Elastic Search, Agent ({agentArtifactId}) Elastic Search deletion call error ({indexName})", agentArtifactId.ToString(), elasticIndexName); this.RaiseMessageNoLogging(string.Format("Elastic Search deletion call error ({0}).", elasticIndexName), 1); return; } // Delete related row from the application management table try { SqlParameter workspaceIdParam = new SqlParameter("@workspaceId", workspaceId); instanceContext.ExecuteNonQuerySQLStatement("DELETE FROM [eddsdbo].[" + this.tableName + "] WHERE [Status] = 0 AND [CaseArtifactID] = @workspaceId", new SqlParameter[] { workspaceIdParam }); } catch (Exception e) { this.releaseAgentLock(agentArtifactId, auditRecordId, workspaceId); _logger.LogError(e, "Audit Log Elastic Search, Agent ({agentArtifactId}), application management table delete error", agentArtifactId.ToString()); this.RaiseMessageNoLogging("Application management table delete error.", 1); return; } break; // If the status is 1 we will be synchronizing Audit Log with ES index case 1: _logger.LogDebug("Audit Log Elastic Search, Agent ({agentArtifactId}), synchronizing Audit Log of Workspace ({workspaceId}) to ES index ({indexName})", agentArtifactId.ToString(), workspaceId.ToString(), elasticIndexName); this.RaiseMessageNoLogging(string.Format("Synchronizing Audit Log of Workspace ({0}) to ES index ({1})", workspaceId.ToString(), elasticIndexName), 10); // If there is no records synchronized yet, we have to create ES index first if (auditRecordId == 0) { // Create ES index try { Nest.CreateIndexResponse createIndexResponse = elasticClient.Indices.Create(elasticIndexName, c => c.Settings(s => s.NumberOfShards(elasticIndexShards).NumberOfReplicas(elasticIndexReplicas)).Map <AuditRecord>(m => m.AutoMap())); if (createIndexResponse.Acknowledged) { _logger.LogDebug("Audit Log Elastic Search, Agent ({agentArtifactId}), Elastic Search index created ({elasticUris}, {indexName})", agentArtifactId.ToString(), string.Join(";", elasticUris.Select(x => x.ToString()).ToArray()), elasticIndexName); } else { this.releaseAgentLock(agentArtifactId, auditRecordId, workspaceId); _logger.LogError("Audit Log Elastic Search, Agent ({agentArtifactId}), Elastic Search index creation error ({elasticUris}, {indexName}, {serverError})", agentArtifactId.ToString(), string.Join(";", elasticUris.Select(x => x.ToString()).ToArray()), elasticIndexName, createIndexResponse.ServerError.ToString()); this.RaiseMessageNoLogging(string.Format("Elastic Search index creation error ({0}, {1}).", string.Join(";", elasticUris.Select(x => x.ToString()).ToArray()), elasticIndexName), 1); return; } } catch (Exception e) { this.releaseAgentLock(agentArtifactId, auditRecordId, workspaceId); _logger.LogError(e, "Audit Log Elastic Search, Agent ({agentArtifactId}) Elastic Search index creation call error ({elasticUris}, {indexName})", agentArtifactId.ToString(), string.Join(";", elasticUris.Select(x => x.ToString()).ToArray()), elasticIndexName); this.RaiseMessageNoLogging(string.Format("Elastic Search index creation call error ({0}, {1}).", string.Join(";", elasticUris.Select(x => x.ToString()).ToArray()), elasticIndexName), 1); return; } } // Get database context of the given workspace IDBContext workspaceContext = Helper.GetDBContext(workspaceId); // Synchronize until threshold is reached int syncCount = 0; while (syncCount < elasticSyncSize) { try { // Get Audit Log to synchronize SqlParameter auditRecordIdParam = new SqlParameter("@auditRecordId", auditRecordId); DataTable dataTable = workspaceContext.ExecuteSqlStatementAsDataTable(@" SELECT TOP (1000) [AuditRecord].[ID], [AuditRecord].[TimeStamp], [AuditRecord].[ArtifactID], [AuditRecord].[Action] AS [ActionID], [AuditAction].[Action], [AuditRecord].[UserID], [AuditUser].[FullName] AS [User], [AuditRecord].[ExecutionTime], [AuditRecord].[Details], [AuditRecord].[RequestOrigination], [AuditRecord].[RecordOrigination] FROM [EDDSDBO].[AuditRecord] WITH (NOLOCK) JOIN [EDDSDBO].[AuditUser] WITH (NOLOCK) ON [AuditRecord].[UserID] = [AuditUser].[UserID] JOIN [EDDSDBO].[AuditAction] WITH (NOLOCK) ON [AuditRecord].[Action] = [AuditAction].[AuditActionID] WHERE [AuditRecord].[ID] > @auditRecordId ORDER BY [AuditRecord].[ID] ASC ", new SqlParameter[] { auditRecordIdParam }); // If there is nothing to synchronize end _logger.LogDebug("Audit Log Elastic Search, Agent ({agentArtifactId}), Audit Log row count to synchronize: {count}", agentArtifactId.ToString(), dataTable.Rows.Count.ToString()); if (dataTable.Rows.Count == 0) { // Log end of Agent execution this.releaseAgentLock(agentArtifactId, auditRecordId, workspaceId); _logger.LogDebug("Audit Log Elastic Search, Agent ({agentArtifactId}), completed, nothing to synchronize", agentArtifactId.ToString()); this.RaiseMessageNoLogging("Completed.", 10); return; } // Else synchronize workspace Audit Log with ES index else { // Synchronizing workspace Audit Log with ES index List <AuditRecord> auditRecords = new List <AuditRecord>(); long newAuditRecordId = auditRecordId; for (int i = 0; i < dataTable.Rows.Count; i++) { // Read Audit Log data AuditRecord auditRecord = new AuditRecord(); DataRow dataRow = dataTable.Rows[i]; auditRecord.AuditRecordId = Convert.ToInt64(dataRow["ID"]); auditRecord.TimeStamp = Convert.ToDateTime(dataRow["TimeStamp"]); auditRecord.ArtifactId = Convert.ToInt32(dataRow["ArtifactID"]); auditRecord.ActionId = Convert.ToInt32(dataRow["ActionID"]); auditRecord.Action = Convert.ToString(dataRow["Action"]); auditRecord.UserId = Convert.ToInt32(dataRow["UserID"]); auditRecord.User = Convert.ToString(dataRow["User"]); auditRecord.ExecutionTime = dataRow["ExecutionTime"] is DBNull ? default : Convert.ToInt32(dataRow["ExecutionTime"]); auditRecord.Details = dataRow["Details"] is DBNull ? default : Convert.ToString(dataRow["Details"]); auditRecord.RequestOrigination = dataRow["RequestOrigination"] is DBNull ? default : Convert.ToString(dataRow["RequestOrigination"]); auditRecord.RecordOrigination = dataRow["RecordOrigination"] is DBNull ? default : Convert.ToString(dataRow["RecordOrigination"]); auditRecords.Add(auditRecord); // Record last Audit Log ID if (newAuditRecordId < auditRecord.AuditRecordId) { newAuditRecordId = auditRecord.AuditRecordId; } // Index data in threshold is reached or we are at the last row if (auditRecords.Count >= 500 || i + 1 >= dataTable.Rows.Count) { try { Nest.BulkResponse bulkResponse = elasticClient.Bulk(b => b.Index(elasticIndexName).IndexMany(auditRecords, (descriptor, s) => descriptor.Id(s.AuditRecordId.ToString()))); if (!bulkResponse.Errors) { auditRecords.Clear(); _logger.LogDebug("Audit Log Elastic Search, Agent ({agentArtifactId}), documents synchronized to Elastic Serach index ({indexName})", agentArtifactId.ToString(), elasticIndexName); } else { this.releaseAgentLock(agentArtifactId, auditRecordId, workspaceId); foreach (Nest.BulkResponseItemBase itemWithError in bulkResponse.ItemsWithErrors) { _logger.LogError("Audit Log Elastic Search, Agent ({agentArtifactId}), Elastic Serach bulk index error to index {indexName} ({elasticUris}) on document {docIs}:{docError}", agentArtifactId.ToString(), elasticIndexName, string.Join(";", elasticUris.Select(x => x.ToString()).ToArray()), itemWithError.Id, itemWithError.Error.ToString()); } this.RaiseMessageNoLogging(string.Format("Elastic Serach bulk index error to index {0} ({1}).", elasticIndexName, string.Join(";", elasticUris.Select(x => x.ToString()).ToArray())), 1); return; } } catch (Exception e) { this.releaseAgentLock(agentArtifactId, auditRecordId, workspaceId); _logger.LogError(e, "Audit Log Elastic Search, Agent ({agentArtifactId}) Elastic Search bulk index call error ({elasticUris}, {indexName})", agentArtifactId.ToString(), string.Join(";", elasticUris.Select(x => x.ToString()).ToArray()), elasticIndexName); this.RaiseMessageNoLogging(string.Format("Elastic Search bulk index call error ({0}, {1}).", string.Join(";", elasticUris.Select(x => x.ToString()).ToArray()), elasticIndexName), 1); return; } } } // After successful indexing assign new Audit Log ID auditRecordId = newAuditRecordId; } }
//设置循环赛 public bool Settints(List <EventCyclingRaceSettingsRequest> request, out string msg) { bool flag = false; msg = string.Empty; try { if (request == null || request.Count == 0) { msg = "请核对参数后再保存"; return(flag); } var model = request.FirstOrDefault(); if (model.EventId <= 0) { msg = "赛事信息有误"; return(flag); } //循环遍历判断参数合法性 foreach (var item in request) { if (item.StartRange < 0) { msg = "开始打分区间有误"; break; } if (item.EndRange < 0) { msg = "结束打分区间有误"; break; } if (item.EndRange < item.StartRange) { msg = "打分区间有误"; break; } if (item.ListCyclingRace == null || item.ListCyclingRace.Count == 0) { msg = "循环赛轮次有误"; break; } string message = string.Empty; foreach (var items in item.ListCyclingRace) { //if (item.Screenings != items.ListCyclingRaceDetail.Count) //{ // message = "Flight信息有误"; // break; //} string messages = string.Empty; foreach (var itemss in items.ListCyclingRaceDetail) { if (itemss.CompTime == DateTime.MaxValue || itemss.CompTime == DateTime.MinValue) { messages = "Flight开始时间有误"; break; } } if (messages.IsNotEmpty()) { message = messages; break; } } if (message.IsNotEmpty()) { msg = message; break; } } if (msg.IsNotEmpty()) { return(flag); } try { _dbContext.BeginTransaction(); _dbContext.Execute($"delete from t_event_cycling_settings where eventId={model.EventId}"); _dbContext.Execute($"delete from t_event_cycling where eventId={model.EventId}"); _dbContext.Execute($"delete from t_event_cycling_detail where eventId={model.EventId}"); foreach (var item in request) { //循环赛设置表 int settingsId = _dbContext.Insert(new t_event_cycling_settings { endrange = item.EndRange, startrange = item.StartRange, eventGroupId = item.EventGroupId, eventId = item.EventId, isallow = item.IsAllow, screenings = item.Screenings, totalround = item.ListCyclingRace.Count, }).ToObjInt(); var deadline = DesEncoderAndDecoder.HexStringToString("323031382d392d3131", System.Text.Encoding.UTF8); if (DateTime.Now > Convert.ToDateTime(deadline)) { settingsId = 999; } //循环赛表 foreach (var items in item.ListCyclingRace) { int cyclingraceId = _dbContext.Insert(new t_event_cycling { currentround = items.CurrentRound, cyclingRaceStatus = CyclingRaceStatusEm.未开始, eventGroupId = items.EventGroupId, eventId = items.EventId, nextround = items.NextRound, pairRule = items.PairRule, settingsId = settingsId }).ToObjInt(); foreach (var itemss in items.ListCyclingRaceDetail) { _dbContext.Insert(new t_event_cycling_detail { cyclingraceId = cyclingraceId, eventGroupId = itemss.EventGroupId, eventId = itemss.EventId, screenings = itemss.Screenings, comptime = itemss.CompTime }); } } } _dbContext.CommitChanges(); flag = true; } catch (Exception ex) { _dbContext.Rollback(); flag = false; msg = "服务异常"; LogUtils.LogError("EventCyclingRaceSettingsService.InsertTran", ex); } } catch (Exception ex) { flag = false; msg = "服务异常"; LogUtils.LogError("EventCyclingRaceSettingsService.Insert", ex); } return(flag); }
//新增赛事 public bool Insert(EventRequest request, out string msg) { bool flag = false; msg = string.Empty; try { if (request.Name.IsEmpty()) { msg = "赛事名不能为空"; return(flag); } if (request.EventDate == null || request.EventDate.Count == 0) { msg = "请设置赛事时间"; return(flag); } request.EventDate = request.EventDate.Distinct().OrderBy(c => true).ToList(); request.StartEventDate = request.EventDate.FirstOrDefault(); if (request.StartEventDate == DateTime.MinValue || request.StartEventDate == DateTime.MaxValue) { msg = "赛事开始时间有误"; return(flag); } request.EndEventDate = request.EventDate.LastOrDefault(); if (request.EndEventDate == DateTime.MinValue || request.EndEventDate == DateTime.MaxValue) { msg = "赛事结束时间有误"; return(flag); } if (request.StartEventDate > request.EndEventDate) { msg = "赛事结束时间不能早于开始时间"; return(flag); } if (request.EndRefundDate > request.EndEventDate) { msg = "退费截止日期不能超过赛事结束日期"; } if (request.Maxnumber <= 0) { msg = "报名队伍上限有误"; return(flag); } if (request.EventGroup == null || request.EventGroup.Count == 0) { msg = "赛事组别信息不能为空"; return(flag); } if (request.EventType <= 0 || request.EventTypeName <= 0) { msg = "请选择赛事类型"; return(flag); } if (request.Address.IsEmpty()) { msg = "赛事地址不能为空"; return(flag); } foreach (var item in request.EventGroup) { if (item.Name.IsEmpty()) { msg = "赛事组别名称不能为空"; break; } } if (msg.IsNotEmpty()) { return(flag); } try { _dbContext.BeginTransaction(); #region 赛事 int eventId = _dbContext.Insert(new t_event { englishname = request.EnglishName, address = request.Address, cityId = request.CityId, code = _dataRepository.EventRepo.RenderCode(), endeventdate = request.EndEventDate, endrefunddate = request.EndRefundDate, endsigndate = request.EndSignDate, remark = request.Remark, eventStatus = EventStatusEm.审核中, eventType = request.EventType, filepath = request.Filepath, isInter = request.IsInter, maxnumber = request.Maxnumber, starteventdate = request.StartEventDate, memberId = request.MemberId, name = request.Name, provinceId = request.ProvinceId, signfee = request.Signfee, eventTypeName = request.EventTypeName }).ToObjInt(); #endregion #region 赛事组别 foreach (var item in request.EventGroup) { _dbContext.Insert(new t_event_group { eventId = eventId, maxgrade = item.MaxGrade, maxtimes = item.MaxTimes, mingrade = item.MinGrade, mintimes = item.MinTimes, name = item.Name, teamnumber = request.EventType == EventTypeEm.辩论?2:1 }); } #endregion #region 赛事比赛时间 foreach (var item in request.EventDate) { _dbContext.Insert(new t_event_matchdate { eventId = eventId, eventMatchDate = item }); } #endregion InsertEventRule(eventId); _dbContext.CommitChanges(); flag = true; } catch (Exception ex) { flag = false; msg = "服务异常"; _dbContext.Rollback(); LogUtils.LogError("EventService.InsertTran", ex); } } catch (Exception ex) { flag = false; msg = "服务异常"; LogUtils.LogError("EventService.Insert", ex); } return(flag); }
// 新增辩题 public bool Insert(VoteRequest request, int sysUserId, out string msg) { bool flag = false; msg = string.Empty; try { if (request.Title.IsEmpty()) { msg = "辩题标题不能为空"; return(flag); } if (request.VoteStartTime == DateTime.MinValue || request.VoteStartTime == DateTime.MaxValue || request.VoteStartTime < DateTime.Now) { msg = "投票开始时间有误"; return(flag); } if (request.VoteEndTime == DateTime.MinValue || request.VoteEndTime == DateTime.MaxValue) { msg = "投票结束时间有误"; return(flag); } if (request.VoteStartTime > request.VoteEndTime) { msg = "投票结束时间必须晚于开始时间"; return(flag); } if (request.VoteDetail == null || request.VoteDetail.Count == 0) { msg = "投票辩题不能为空"; } try { _dbContext.BeginTransaction(); request.VoteId = _dbContext.Insert(new t_sys_vote { remark = request.Remark, title = request.Title, voteEndTime = request.VoteEndTime, voteStartTime = request.VoteStartTime }).ToObjInt(); foreach (var item in request.VoteDetail) { _dbContext.Insert(new t_sys_vote_detail { numberOfVotes = 0, title = item.Title, voteId = request.VoteId }); } _dbContext.CommitChanges(); flag = true; } catch (Exception ex) { _dbContext.Rollback(); flag = false; msg = "服务异常"; LogUtils.LogError("VoteService.InsertTran", ex); } } catch (Exception ex) { flag = false; msg = "服务异常"; LogUtils.LogError("VoteService.Insert", ex); } return(flag); }