public override TableTimeRuleConditionShift GetTableObject() { var obj = new TableTimeRuleConditionShift(); obj.time_rule_condition_shift_id = Id; obj.time_rule_condition_shift_guid = Guid; obj.time_series_id = TimeSeriesId; obj.time_rule_condition_date_type_id = (int)CommUtils.ParseEnum <TimeRuleDateType>(TimeRuleDateType); obj.time_interval = TimeInterval; obj.time_rule_unit_type_id = (int)CommUtils.ParseEnum <TimeRuleUnitType>(TimeRuleUnitType); obj.create_time = CreateTime; obj.create_user_name = CreateUserName; obj.last_modify_time = LastModifyTime; obj.last_modify_user_name = LastModifyUserName; obj.record_status_id = (int)RecordStatus; return(obj); }
/// <summary> /// Привязать соединение к КП, используя библиотеку КП /// </summary> protected void BindConnByDeviceLibrary(TcpConnection tcpConn, KPLogic kpLogic) { if (kpLogic != null) { WriteToLog(string.Format(Localization.UseRussian ? "{0} Клиент {1} привязан к {2}, используя библиотеку КП" : "{0} The client {1} is bound to the {2} using a device library", CommUtils.GetNowDT(), tcpConn.RemoteAddress, kpLogic.Caption)); SetConnection(kpLogic, tcpConn); } else { WriteToLog(string.Format(Localization.UseRussian ? "{0} Не удалось привязать клиента {1} к КП, используя библиотеку КП" : "{0} Unable to bind the client {1} to a device using a device library", CommUtils.GetNowDT(), tcpConn.RemoteAddress)); } }
private void LoadSubFolders(DMSFolderLogicModel parentFolderLogicModel, List <DMSFolder> allfolders, int folderDepth) { CommUtils.Assert(folderDepth < DMSLogicModel.MaxFolderDepth, "Load folder failed, folder depth > {0}", DMSLogicModel.MaxFolderDepth); var parentFolderId = parentFolderLogicModel.Instance.Id; var subFolders = allfolders.Where(x => x.ParentFolderId == parentFolderId); parentFolderLogicModel.SubFolders = new List <DMSFolderLogicModel>(); foreach (var subFolder in subFolders) { var subFolderLogicModel = new DMSFolderLogicModel(m_project); subFolderLogicModel.Instance = subFolder; subFolderLogicModel.ParentFolder = parentFolderLogicModel; LoadSubFolders(subFolderLogicModel, allfolders, folderDepth + 1); parentFolderLogicModel.SubFolders.Add(subFolderLogicModel); } }
/// <summary> /// 普通标 /// </summary> /// <returns></returns> private ShowModel GetModel() { var para = new Dapper.DynamicParameters(); string sql = string.Empty; //普通标 sql = @"select top 1 Id,0 AS IsWeFQB,InterestRate AS YearRate,Deadline,DeadType,Amount,CastedShares,LowerUnit,TotalShares,Type as TypeId from project with(nolock) where IsNewHand!=1 and type != 15 AND AddDate>dateadd(day,-15,getdate()) and Status =2 order by InterestRate desc"; ShowModel model = PublicConn.QuerySingle <ShowModel>(sql, ref para); if (model != null) { model.ProductName = invest_list.GetTypeName(model.TypeId, 1); model.DetailUrl = "/pages/invest/detail.aspx?id=" + model.Id; model.OrderCount = CommUtils.GetSubscribeUserCount(model.Id); } return(model); }
public void ModifyTaskGroup(string taskGroupGuid, string name, string description) { ValidateUtils.Name(name, "名称"); ValidateUtils.Description(description, "描述"); var hasTaskGroupGuid = TaskGroups.Any(x => x.Instance.Guid == taskGroupGuid); CommUtils.Assert(hasTaskGroupGuid, "此工作组不存在"); var taskGroupLogicModel = TaskGroups.Single(x => x.Instance.Guid == taskGroupGuid); var taskGroup = taskGroupLogicModel.Instance; taskGroup.Name = name; taskGroup.Description = description; m_dbAdapter.TaskGroup.UpdateTaskGroup(taskGroup); m_taskGroups = null; }
/// <summary> /// Остановить работу канала связи /// </summary> public override void Stop() { // очистка ссылки на соединение для всех КП на линии связи foreach (KPLogic kpLogic in kpList) { kpLogic.Connection = null; } // очистка словаря КП по позывным kpCallNumDict.Clear(); // закрытие соединения udpConn.Close(); WriteToLog(""); WriteToLog(string.Format(Localization.UseRussian ? "{0} Завершение приёма данных по UDP" : "{0} Stop receiving data via UDP", CommUtils.GetNowDT())); }
/// <summary> /// Остановить работу канала связи /// </summary> public override void Stop() { // отключение события приёма данных в режиме ведомого serialConn.SerialPort.DataReceived -= serialPort_DataReceived; // очистка ссылки на соединение для всех КП на линии связи foreach (KPLogic kpLogic in kpList) { kpLogic.Connection = null; } // закрытие последовательного порта serialConn.Close(); WriteToLog(""); WriteToLog(string.Format(Localization.UseRussian ? "{0} Последовательный порт '{1}' закрыт" : "{0} Serial port '{1}' is closed", CommUtils.GetNowDT(), serialConn.SerialPort.PortName)); }
public ActionResult AddUserGroup(string name) { return(ActionUtils.Json(() => { ValidateUtils.Name(name, "组名"); var userGroups = m_dbAdapter.UserGroup.GetByOwner(CurrentUserName); var userGroupNames = userGroups.Select(x => x.Name).ToList(); CommUtils.Assert(!userGroupNames.Contains(name), "[{0}]组名已存在,请重新输入", name); var userGroup = new UserGroup { Name = name, Owner = CurrentUserName }; var result = m_dbAdapter.UserGroup.New(userGroup); return ActionUtils.Success(result); })); }
public ActionResult GetProjects(string projectType) { return(ActionUtils.Json(() => { //TODO: CommUtils.AssertEquals(projectType, "存续期", "目前仅支持获取存续期产品列表"); var projectIds = m_dbAdapter.Authority.GetAuthorizedProjectIds(); var projects = m_dbAdapter.Project.GetProjects(projectIds); var result = projects.ConvertAll(x => new { name = x.Name, guid = x.ProjectGuid }); return ActionUtils.Success(result); })); }
private string GetCellValue(IWorkbook book, CellKeyword keyword) { var sheet = FindSheetByTitle(book, 2, 0, keyword.TitleName); if (sheet == null) { CommUtils.AssertNotNull(sheet, "找不到标题[{0}]", keyword.TitleName); } Tuple <int, int> findByRow = null; if (!keyword.RowName.Any(string.IsNullOrWhiteSpace)) { findByRow = FindCell(sheet, keyword.RowName); CommUtils.AssertNotNull(findByRow, "找不到关键字[{0}]", keyword.RowName); } Tuple <int, int> findByColumn = null; if (!keyword.ColumnName.Any(string.IsNullOrWhiteSpace)) { findByColumn = FindCell(sheet, keyword.ColumnName); CommUtils.AssertNotNull(findByColumn, "找不到关键字[{0}]", keyword.ColumnName); } CommUtils.Assert(!(findByRow == null && findByColumn == null), "行列关键字不能同时为空"); string cellValue = string.Empty; if (findByRow != null && findByColumn != null) { cellValue = GetCellValue(sheet, findByRow.Item1, findByColumn.Item2); } else if (findByRow != null && findByColumn == null) { cellValue = GetCellValue(sheet, findByRow.Item1, findByRow.Item2 + 1); } else if (findByRow == null && findByColumn != null) { cellValue = GetCellValue(sheet, findByColumn.Item1 + 1, findByColumn.Item2); } return(cellValue); }
public ActionResult GetProjectSeriesProcessInfo(string projectSeriesGuid) { return(ActionUtils.Json(() => { var projectSeriesLogicModel = new ProjectSeriesLogicModel(CurrentUserName, projectSeriesGuid); CheckPermission(PermissionObjectType.ProjectSeries, projectSeriesGuid, PermissionType.Read); var tasks = m_dbAdapter.Task.GetTasksByProjectId(projectSeriesLogicModel.CurrentProject.Instance.ProjectId); var finishedTaskCount = tasks.Count(x => x.TaskStatus == TaskStatus.Finished); var percentCompleted = CommUtils.Percent(finishedTaskCount, tasks.Count); var projectSeries = projectSeriesLogicModel.Instance; var personInChargeInfo = Platform.UserProfile.Get(projectSeries.PersonInCharge); var createUserInfo = Platform.UserProfile.Get(projectSeries.CreateUserName); var result = new { name = projectSeries.Name, personInCharge = new { userName = personInChargeInfo.UserName, realName = personInChargeInfo.RealName }, createUser = new { userName = createUserInfo.UserName, realName = createUserInfo.RealName }, createTimeStamp = projectSeries.CreateTime.ToString("yyyy-MM-dd"), estimatedFinishTime = Toolkit.DateToString(projectSeries.EstimatedFinishTime), remainingDayCount = projectSeries.EstimatedFinishTime.HasValue ? ((int)(projectSeries.EstimatedFinishTime.Value - DateTime.Today).TotalDays).ToString() : "-", stage = projectSeries.Stage.ToString(), taskCount = tasks.Count, finishedTaskCount = finishedTaskCount, percentCompleted = percentCompleted, projectType = projectSeries.Type.ToString(), email = string.IsNullOrWhiteSpace(projectSeries.Email)? null:projectSeries.Email, }; return ActionUtils.Success(result); })); }
/// <summary> /// Creates OPC server child nodes. /// </summary> private void CreateChildNodes(FolderState rootFolder) { foreach (ILineContext lineContext in commContext.GetCommLines()) { List <DeviceLogic> devices = new List <DeviceLogic>(); devices.AddRange(deviceFilter == null ? lineContext.SelectDevices() : lineContext.SelectDevices(d => deviceFilter.Contains(d.DeviceNum))); if (devices.Count > 0) { FolderState lineFolder = CreateFolder(rootFolder, CommUtils.GetLineLogFileName(lineContext.CommLineNum, ""), lineContext.Title); foreach (DeviceLogic deviceLogic in devices) { FolderState deviceFolder = CreateFolder(lineFolder, CommUtils.GetDeviceLogFileName(deviceLogic.DeviceNum, ""), deviceLogic.Title); DeviceVars deviceVars = new DeviceVars(); varByDevice[deviceLogic.DeviceNum] = deviceVars; if (deviceLogic.DeviceTags.FlattenGroups) { foreach (TagGroup tagGroup in deviceLogic.DeviceTags.TagGroups) { CreateDeviceTagNodes(deviceFolder, deviceLogic, tagGroup, deviceVars); } } else { int groupNum = 1; foreach (TagGroup tagGroup in deviceLogic.DeviceTags.TagGroups) { FolderState groupFolder = CreateFolder(deviceFolder, "group" + groupNum.ToString("D3"), tagGroup.Name); CreateDeviceTagNodes(groupFolder, deviceLogic, tagGroup, deviceVars); groupNum++; } } } } } }
public ActionResult CreateInvestment(string projectGuid, string name, double money, string yieldDue, string startTime, string endTime, string description) { return(ActionUtils.Json(() => { ValidateUtils.Name(name, "投资标的"); CommUtils.AssertHasContent(startTime, "[开始时间]不能为空"); CommUtils.AssertHasContent(endTime, "[到期时间]不能为空"); CommUtils.Assert(money <= 1000000000000, "[投资金额]不能大于10,000亿元"); CommUtils.Assert(money > 0, "[投资金额]必须大于0元"); var valStartTime = DateTime.Parse(startTime); var valEndTime = DateTime.Parse(endTime); CommUtils.Assert(DateTime.Compare(valEndTime, valStartTime) > 0, "[到期时间]必须大于[开始时间]"); var investment = new Investment(); var project = m_dbAdapter.Project.GetProjectByGuid(projectGuid); investment.ProjectId = project.ProjectId; investment.Name = name; investment.Money = money; investment.StartTime = valStartTime; investment.EndTime = valEndTime; investment.Description = description; investment.YieldDue = null; if (!string.IsNullOrWhiteSpace(yieldDue)) { var percentValue = 0.0; if (yieldDue.Contains('%')) { CommUtils.Assert(double.TryParse(yieldDue.Substring(0, yieldDue.Length - 1), out percentValue), "预计收益率必须为数字"); } else { CommUtils.Assert(double.TryParse(yieldDue, out percentValue), "预计收益率必须为数字"); } CommUtils.Assert(percentValue >= 365.00 * (-1) / (valEndTime - valStartTime).TotalDays, "预计收益率过低,请重新填写"); investment.YieldDue = percentValue / 100; } m_dbAdapter.Investment.NewInvestment(investment); return ActionUtils.Success(1); })); }
private List <string> GetTimeListByTimeRuleOrigin(TimeRuleViewModel timeRule, TimeOriginViewModel timeOrigin) { var timeOriginType = CommUtils.ParseEnum <TimeOriginType>(timeOrigin.TimeOriginType); TimeSeriesFactory timeSeriesFactory; var result = new List <string>(); if (timeOriginType == TimeOriginType.CustomInput) { var customTimeList = CommUtils.Split(timeOrigin.CustomInput.CustomTimeList).Select(x => DateTime.Parse(x)); timeSeriesFactory = new TimeSeriesFactory(customTimeList); result = CalculateTimeByTimeRule(timeRule, timeSeriesFactory); } if (timeOriginType == TimeOriginType.Loop) { var startTime = DateTime.Parse(timeOrigin.Loop.BeginTime); var endTime = DateTime.Parse(timeOrigin.Loop.EndTime); var ruleUnitType = CommUtils.ParseEnum <TimeUnit>(timeOrigin.Loop.RuleUnitType); timeSeriesFactory = new TimeSeriesFactory( new DateTime(startTime.Year, startTime.Month, startTime.Day), new TimeStep { Interval = timeOrigin.Loop.Interval, Unit = ruleUnitType }, new DateTime(endTime.Year, endTime.Month, endTime.Day)); result = CalculateTimeByTimeRule(timeRule, timeSeriesFactory); } if (timeOriginType == TimeOriginType.MetaTask) { result = GetTimeListByPrevMetaTask(timeRule, timeOrigin.PrevMetaTask.MetaTaskGuid, timeOrigin.PrevMetaTask.MetaTaskTimeType); } if (timeOriginType == TimeOriginType.TaskSelfTime) { var timeSeries = m_dbAdapter.TimeSeries.GetByGuid(timeOrigin.TaskSelfTime.TimeSeriesGuid); var CurrTimeRule = GetTimeRuleDetail(timeSeries.Id); var CurrTimeOrigin = GetTimeOriginDetail(timeSeries.Guid, timeSeries.Id); var timeList = GetTimeListByTimeRuleOrigin(CurrTimeRule, CurrTimeOrigin).Select(x => DateTime.Parse(x)); timeSeriesFactory = new TimeSeriesFactory(timeList); result = CalculateTimeByTimeRule(timeRule, timeSeriesFactory); } return(result); }
private NoteInfo GetNoteInfo() { var datasets = m_dbAdapter.Dataset.GetDatasetByProjectId(m_project.ProjectId); var findDatasets = datasets.Where(x => x.PaymentDate.HasValue && x.PaymentDate.Value == m_paymentDay).ToList(); findDatasets.Sort((l, r) => l.AsOfDate.CompareTo(r.AsOfDate)); CommUtils.Assert(findDatasets.Count >= 1, "Can' find any dataset of [" + m_paymentDay.ToString() + "]."); var dataset = findDatasets[0]; var notes = m_dbAdapter.Dataset.GetNotes(m_project.ProjectId); var noteDatas = m_dbAdapter.Dataset.GetNoteDatas(dataset.DatasetId); var cnabsNotes = new ProjectLogicModel(m_userName, m_project).Notes; Func <Note, bool> filterSecurityCode = (x) => m_docName.Contains("(" + x.SecurityCode + ")") || m_docName.Contains("(" + x.SecurityCode + ")"); Func <Note, bool> filterNoteShortName = (x) => m_docName.Contains("(" + x.ShortName + ")") || m_docName.Contains("(" + x.ShortName + ")"); var filters = new [] { filterSecurityCode, filterNoteShortName }; foreach (var filter in filters) { if (cnabsNotes.Any(filter)) { var cnabsNote = cnabsNotes.First(filter); CommUtils.Assert(notes.Any(x => x.NoteName == cnabsNote.NoteName), "找不到证券[{0}]相关信息", cnabsNote.NoteName); var note = notes.First(x => x.NoteName == cnabsNote.NoteName); m_usesAndComment = cnabsNote.SecurityCode + "兑付兑息款"; var noteData = noteDatas.Single(x => x.NoteId == note.NoteId); return(new NoteInfo { Note = note, NoteData = noteData, }); } } return(null); }
public ActionResult ModifyUserGroup(string userGroupGuid, string name) { return(ActionUtils.Json(() => { var userGroup = m_dbAdapter.UserGroup.GetByGuid(userGroupGuid); CommUtils.Assert(IsCurrentUser(userGroup.Owner), "当前用户[{0}]不是[{1}]的创建者", CurrentUserName, userGroup.Name); ValidateUtils.Name(name, "组名"); var userGroups = m_dbAdapter.UserGroup.GetByOwner(CurrentUserName); var userGroupNames = userGroups.Select(x => x.Name).ToList(); CommUtils.Assert(!userGroupNames.Contains(name), "[{0}]组名已存在,请重新输入", name); userGroup.Name = name; m_dbAdapter.UserGroup.Update(userGroup); return ActionUtils.Success(1); })); }
public ActionResult CreateMessageReminding(string uid, string userid, string remark, DateTime remindTime, string type) { return(ActionUtils.Json(() => { CommUtils.AssertHasContent(userid, "提醒人员不能为空"); CommUtils.AssertHasContent(remindTime.ToString(), "提醒时间不能为空"); CommUtils.Assert(remindTime > DateTime.Now, "提醒时间要大于现在时间"); var msgType = CommUtils.ParseEnum <MessageUidType>(type); CheckRemindingPermission(uid, msgType); userid.Split(',').ToList().ForEach(x => { if (x != "") { m_dbAdapter.MessageReminding.New(uid, x, remark, remindTime, msgType); } }); return ActionUtils.Success(1); })); }
public ActionResult SubscribeNews(string projectGuids) { return(ActionUtils.Json(() => { var projectGuidList = CommUtils.Split(projectGuids).ToList(); CommUtils.Assert(m_dbAdapter.NegativeNews.CheckProjectsPermission(projectGuidList), "当前用户没有操作该产品权限,请刷新重试"); projectGuidList.ForEach(x => { if (!string.IsNullOrWhiteSpace(x)) { var projectId = m_dbAdapter.Project.GetProjectByGuid(x).ProjectId; m_dbAdapter.NegativeNews.New(m_dbAdapter.Project.GetProjectByGuid(x).ProjectId, CurrentUserName); } }); return ActionUtils.Success(1); })); }
public CollateralAssetViewModel(AssetLogicModel asset) { AssetId = asset.AssetId; SecurityName = asset.SecurityData.SecurityName; PaymentMethod = asset.AmortizationType.ToString(); Currency = asset.SecurityData.Currency.ToString(); IsFloating = asset.SecurityData.IsFloating; AllInRate = asset.SecurityData.AllInRate; FloatingIndex = asset.SecurityData.FloatingIndex.ToString(); FloatingIndexCode = asset.SecurityData.FloatingIndexCode.ToString(); PaymentFrequency = asset.SecurityData.PaymentFrequency.ToString(); AccrualMethod = Toolkit.AccrualMethod(asset.SecurityData.AccrualMethod); LegalMaturityDate = DateUtils.IsNormalDate(asset.SecurityData.LegalMaturityDate) ? Toolkit.DateToString(asset.SecurityData.LegalMaturityDate) : "-"; PenultimateDate = DateUtils.IsNormalDate(asset.SecurityData.PenultimateDate) ? Toolkit.DateToString(asset.SecurityData.PenultimateDate) : "-"; Region = asset.SecurityData.Region; ChineseRating = CommUtils.FormatChineseRating(asset.SecurityData.ChineseRating); }
/// <summary> /// Adds the device to the communication line. /// </summary> private void AddDevice(DeviceLogic deviceLogic) { if (!deviceMap.ContainsKey(deviceLogic.DeviceNum)) { DeviceWrapper deviceWrapper = new DeviceWrapper(deviceLogic, Log) { InfoFileName = Path.Combine(coreLogic.AppDirs.LogDir, CommUtils.GetDeviceLogFileName(deviceLogic.DeviceNum, ".txt")) }; devices.Add(deviceWrapper); deviceMap.Add(deviceLogic.DeviceNum, deviceWrapper); if (maxDeviceTitleLength < deviceLogic.Title.Length) { maxDeviceTitleLength = deviceLogic.Title.Length; } } }
public override TableTimeOriginLoop GetTableObject() { var obj = new TableTimeOriginLoop(); obj.time_origin_loop_id = Id; obj.time_origin_loop_guid = Guid; obj.time_series_id = TimeSeriesId; obj.loop_begin = LoopBegin; obj.loop_end = LoopEnd; obj.loop_interval = LoopInterval; obj.time_rule_unit_type_id = (int)CommUtils.ParseEnum <TimeRuleUnitType>(TimeRuleUnitType); obj.create_time = CreateTime; obj.create_user_name = CreateUserName; obj.last_modify_time = LastModifyTime; obj.last_modify_user_name = LastModifyUserName; obj.record_status_id = (int)RecordStatus; return(obj); }
public ActionResult UploadTemplateFile(HttpPostedFileBase file) { return(ActionUtils.Json(() => { CommUtils.AssertNotNull(file, "文件不能为空,请选择文件"); CommUtils.Assert(file.ContentLength > 0, "文件内容不能为空"); CommUtils.Assert(file.FileName.EndsWith(".docx", StringComparison.CurrentCultureIgnoreCase), "文件[{0}]格式错误,请选择.docx格式的文件", file.FileName); CommUtils.Assert(!CommUtils.IsWPS(file.InputStream), "不支持wps编辑过的.docx格式文件,仅支持office编辑的.docx文件"); var path = DemoJianYuanUtils.GetTemplateFilePath(); file.SaveAs(path); return ActionUtils.Success(1); })); }
public ActionResult CheckPrevMetaTaskCount(string projectGuid, string endTimeSeriesGuid, string prevMetaTaskGuidText) { return(ActionUtils.Json(() => { var project = m_dbAdapter.Project.GetProjectByGuid(projectGuid); var prevMetaTaskGuids = CommUtils.Split(prevMetaTaskGuidText).ToList(); var prevMetaTasks = m_dbAdapter.MetaTask.GetMetaTaskByGuids(prevMetaTaskGuids); prevMetaTasks.ForEach(x => CommUtils.Assert(x.ProjectId == project.ProjectId, "前置工作的projectId[{0}]与当前产品的projectId[{1}]不一致", x.ProjectId, project.ProjectId)); var endTimeSeries = m_dbAdapter.TimeSeries.GetByGuid(endTimeSeriesGuid); var endTimeListCount = CheckStartAndEndTimeCount(null, endTimeSeries); CheckPrevMetaTaskGenerateCount(endTimeListCount, prevMetaTasks); return ActionUtils.Success(""); })); }
public ActionResult RemoveUsers(string userGroupGuid, string userNames) { return(ActionUtils.Json(() => { var userGroup = m_dbAdapter.UserGroup.GetByGuid(userGroupGuid); CommUtils.Assert(IsCurrentUser(userGroup.Owner), "当前用户[{0}]不是[{1}]的创建者", CurrentUserName, userGroup.Name); var userGroupMaps = m_dbAdapter.UserGroupMap.GetByUserGroupGuid(userGroupGuid); var userGroupMapDic = userGroupMaps.ToDictionary(x => x.UserName); var userNameList = CommUtils.Split(userNames); foreach (var userName in userNameList) { m_dbAdapter.UserGroupMap.Delete(userGroupMapDic[userName]); } return ActionUtils.Success(1); })); }
private List <AmortizationScheduleRecord> ParseDistributionDetail(int assetId, string distributionDetail) { var records = new List <AmortizationScheduleRecord>(); var items = distributionDetail.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries); foreach (var item in items) { var subStrs = item.Split('|'); CommUtils.AssertEquals(subStrs.Length, 2, "解析自定义偿付信息失败[" + distributionDetail + "]"); records.Add(new AmortizationScheduleRecord { AssetId = assetId, ReductionDate = DateUtils.ParseDigitDate(subStrs[0]), ReductionAmount = double.Parse(subStrs[1]) }); } return(records); }
private TimeOriginViewModel GetTimeOriginDetail(string timeSeriesGuid, int timeSeriesId) { var timeOriginViewModel = new TimeOriginViewModel(); var timeOrigin = m_dbAdapter.TimeOrigin.GetByTimeSeriesId(timeSeriesId); var timeOriginType = CommUtils.ParseEnum <TimeOriginType>(timeOrigin.TimeOriginType); timeOriginViewModel.TimeSeriesGuid = timeSeriesGuid; timeOriginViewModel.TimeOriginType = timeOrigin.TimeOriginType; switch (timeOriginType) { case TimeOriginType.CustomInput: var timeOriginCustomInput = m_dbAdapter.TimeOriginCustomInput.GetById(timeOrigin.TimeOriginInstanceId); timeOriginViewModel.CustomInput.CustomTimeList = timeOriginCustomInput.CustomTimeSeries; break; case TimeOriginType.Loop: var timeOriginLoop = m_dbAdapter.TimeOriginLoop.GetById(timeOrigin.TimeOriginInstanceId); timeOriginViewModel.Loop.Interval = timeOriginLoop.LoopInterval; timeOriginViewModel.Loop.BeginTime = timeOriginLoop.LoopBegin.ToString("yyyy-MM-dd"); timeOriginViewModel.Loop.EndTime = timeOriginLoop.LoopEnd.ToString("yyyy-MM-dd"); timeOriginViewModel.Loop.RuleUnitType = timeOriginLoop.TimeRuleUnitType; break; case TimeOriginType.MetaTask: var timeOriginMetaTask = m_dbAdapter.TimeOriginMetaTask.GetById(timeOrigin.TimeOriginInstanceId); var prevMetaTask = m_dbAdapter.MetaTask.GetById(timeOriginMetaTask.MetaTaskId); timeOriginViewModel.PrevMetaTask.MetaTaskGuid = prevMetaTask.Guid; timeOriginViewModel.PrevMetaTask.MetaTaskTimeType = timeOriginMetaTask.MetaTaskTimeType; break; case TimeOriginType.TaskSelfTime: var timeOriginTaskSelfTime = m_dbAdapter.TimeOriginTaskSelfTime.GetById(timeOrigin.TimeOriginInstanceId); timeOriginViewModel.TaskSelfTime.TimeSeriesGuid = timeOriginTaskSelfTime.TimeOriginTimeSeriesGuid; timeOriginViewModel.TaskSelfTime.TimeType = timeOriginTaskSelfTime.TimeType; break; default: break; } return(timeOriginViewModel); }
public ActionResult GetTeamAdminsOfUserGroup(string projectSeriesGuid, string userGroupGuid) { return(ActionUtils.Json(() => { var projectSeriesLogicModel = new ProjectSeriesLogicModel(CurrentUserName, projectSeriesGuid); var projectSeries = projectSeriesLogicModel.Instance; CommUtils.Assert(IsAdmin(projectSeriesLogicModel.Instance, CurrentUserName), "当前用户[{0}]不是项目[{1}]的创建者/负责人", Platform.UserProfile.GetDisplayRealNameAndUserName(CurrentUserName), projectSeriesLogicModel.Instance.Name); var userGroup = m_dbAdapter.UserGroup.GetByGuid(userGroupGuid); CommUtils.Assert(IsCurrentUser(userGroup.Owner), "当前用户[{0}]不是[{1}]的创建者", CurrentUserName, userGroup.Name); var projectId = projectSeriesLogicModel.CurrentProject.Instance.ProjectId; var teamAdmins = m_dbAdapter.TeamAdmin.GetByProjectId(projectId); var teamAdminUserNames = teamAdmins.Select(x => x.UserName).ToList(); var userGroupMaps = m_dbAdapter.UserGroupMap.GetByUserGroupGuid(userGroupGuid); var userGroupMapUserNames = userGroupMaps.Select(x => x.UserName).ToList(); var teamAdminsOfUserGroup = teamAdminUserNames.Intersect(userGroupMapUserNames).ToList(); Platform.UserProfile.Precache(userGroupMapUserNames); var result = new { UserGroupUsers = userGroupMapUserNames.ConvertAll(x => new { UserName = Platform.UserProfile.Get(x).UserName, RealName = Platform.UserProfile.Get(x).RealName, IsTeamAdminOfUserGroup = teamAdminsOfUserGroup.Contains(x) ? true : false, IsCreator = projectSeries.CreateUserName.Equals(x, StringComparison.CurrentCultureIgnoreCase) ? true : false, IsPersonInCharge = projectSeries.PersonInCharge.Equals(x, StringComparison.CurrentCultureIgnoreCase) ? true : false }).ToList(), StatisticInfo = new { TotalUserGroupUser = userGroupMapUserNames.Count(), TotalteamAdminOfUserGroup = teamAdminsOfUserGroup.Count() } }; return ActionUtils.Success(result); })); }
/// <summary> /// Выполнить действия перед сеансом опроса КП или отправкой команды /// </summary> public override void BeforeSession(KPLogic kpLogic) { // установка соединения при необходимости TcpConnection tcpConn = kpLogic.Connection as TcpConnection; if (tcpConn != null && !tcpConn.Connected) { try { // определение IP-адреса и TCP-порта IPAddress addr; int port; if (tcpConn == sharedTcpConn) { addr = IPAddress.Parse(settings.IpAddress); port = settings.TcpPort; } else { CommUtils.ExtractAddrAndPort(kpLogic.CallNum, settings.TcpPort, out addr, out port); } // установка соединения WriteToLog(""); WriteToLog(string.Format(Localization.UseRussian ? "{0} Установка TCP-соединения с {1}:{2}" : "{0} Establish a TCP connection with {1}:{2}", CommUtils.GetNowDT(), addr, port)); if (tcpConn.NetStream != null) // соединение уже было открыто, но разорвано { tcpConn.Renew(); } tcpConn.Open(addr, port); } catch (Exception ex) { WriteToLog(ex.Message); } } }
public ActionResult GetFileSeriesDetail(string projectGuid, string fileSeriesGuid) { return(ActionUtils.Json(() => { var dms = GetDMSAndCheckPermission(projectGuid, PermissionType.Read); var dmsFileSeries = m_dbAdapter.DMSFileSeries.GetByGuid(fileSeriesGuid); var dmsFolder = m_dbAdapter.DMSFolder.GetById(dmsFileSeries.DMSFolderId); CommUtils.AssertEquals(dmsFolder.DMSId, dms.Instance.Id, "文件[fileSeriesGuid={0}]不在DMS[{1}]中", fileSeriesGuid, dms.Instance.Guid); var allFiles = m_dbAdapter.DMSFile.GetFilesByFileSeriesId(dmsFileSeries.Id); allFiles = allFiles.OrderByDescending(x => x.Version).ToList(); Platform.UserProfile.Precache(allFiles.Select(x => x.CreateUserName)); Platform.UserProfile.Precache(allFiles.Select(x => x.LastModifyUserName)); var result = allFiles.Select(x => new { fileSeriesName = dmsFileSeries.Name, fileSeriesGuid = dmsFileSeries.Guid, fileGuid = x.Guid, fileName = x.Name, version = x.Version, description = x.Description, size = FileUtils.FormatSize(x.Size), createTime = Toolkit.DateTimeToString(x.CreateTime), createUser = Platform.UserProfile.Get(x.CreateUserName) == null? x.CreateUserName:Platform.UserProfile.Get(x.CreateUserName).RealName, lastModifyTime = Toolkit.DateTimeToString(x.LastModifyTime), lastModifyUser = Platform.UserProfile.Get(x.LastModifyUserName) == null?x.LastModifyUserName: Platform.UserProfile.Get(x.LastModifyUserName).RealName, } ); var fileSeriesTemplate = m_dbAdapter.DMSFileSeriesTemplate.GetByFileSeriesId(dmsFileSeries.Id); var templateType = fileSeriesTemplate == null ? "None" : fileSeriesTemplate.TemplateType.ToString(); return ActionUtils.Success(new { historicalFiles = result, templateType = templateType, }); })); }
private string GetCellValue(ISheet sheet, int findRowIndex, int findColumnIndex) { var rowIndex = 0; var rowEnumerator = sheet.GetRowEnumerator(); while (rowEnumerator.MoveNext()) { IRow row = rowEnumerator.Current as IRow; if (row != null) { var cellIndex = 0; var cellEnumerator = row.GetEnumerator(); while (cellEnumerator.MoveNext()) { ICell cell = cellEnumerator.Current as ICell; if (cell != null) { if (rowIndex == findRowIndex && cellIndex == findColumnIndex) { if (cell.CellType == NPOI.SS.UserModel.CellType.Formula) { if (cell.CachedFormulaResultType == CellType.Numeric) { return(cell.NumericCellValue.ToString(cell.CellStyle.GetDataFormatString())); } else { CommUtils.Assert(false, "cell.CachedFormulaResultType != CellType.Numeric"); } } return(cell.ToString()); } } ++cellIndex; } } ++rowIndex; } return(string.Empty); }
/// <summary> /// Сформировать текст считывания данных для вывода в журнал /// </summary> public static string BuildReadLogText(byte[] buffer, int offset, int readCnt, CommUtils.ProtocolLogFormats logFormat) { return CommPhrases.ReceiveNotation + " (" + readCnt + "): " + (logFormat == CommUtils.ProtocolLogFormats.Hex ? CommUtils.BytesToHex(buffer, offset, readCnt) : CommUtils.BytesToString(buffer, offset, readCnt)); }
/// <summary> /// Записать данные /// </summary> public override void Write(byte[] buffer, int offset, int count, CommUtils.ProtocolLogFormats logFormat, out string logText) { try { SerialPort.DiscardInBuffer(); SerialPort.DiscardOutBuffer(); try { SerialPort.Write(buffer, offset, count); logText = BuildWriteLogText(buffer, offset, count, logFormat); } catch (TimeoutException ex) { logText = CommPhrases.WriteDataError + ": " + ex.Message; } } catch (Exception ex) { throw new InvalidOperationException(CommPhrases.WriteDataError + ": " + ex.Message, ex); } }
/// <summary> /// Считать данные /// </summary> public override int Read(byte[] buffer, int offset, int count, int timeout, CommUtils.ProtocolLogFormats logFormat, out string logText) { try { int readCnt = 0; DateTime nowDT = DateTime.Now; DateTime startDT = nowDT; DateTime stopDT = startDT.AddMilliseconds(timeout); IPEndPoint endPoint = CreateIPEndPoint(); UdpClient.Client.ReceiveTimeout = DatagramReceiveTimeout; while (readCnt < count && startDT <= nowDT && nowDT <= stopDT) { // считывание данных int readPos; bool isNew; byte[] datagram = ReceiveDatagram(ref endPoint, out readPos, out isNew); // копирование полученных данных в заданный буфер if (datagram != null && datagram.Length > 0) { int requiredCnt = count - readCnt; int copyCnt = Math.Min(datagram.Length - readPos, requiredCnt); Array.Copy(datagram, readPos, buffer, readCnt, copyCnt); readCnt += copyCnt; readPos += copyCnt; } // накопление данных во внутреннем буфере соединения if (readCnt < count && isNew) Thread.Sleep(DataAccumThreadDelay); StoreDatagram(datagram, readPos); nowDT = DateTime.Now; } logText = BuildReadLogText(buffer, offset, count, readCnt, logFormat); return readCnt; } catch (SocketException ex) { logText = CommPhrases.ReadDataError + ": " + ex.Message; return 0; } catch (Exception ex) { throw new InvalidOperationException(CommPhrases.ReadDataError + ": " + ex.Message, ex); } }
/// <summary> /// Считать данные с условиями остановки чтения /// </summary> public abstract int Read(byte[] buffer, int offset, int maxCount, int timeout, BinStopCondition stopCond, out bool stopReceived, CommUtils.ProtocolLogFormats logFormat, out string logText);
/// <summary> /// Записать данные /// </summary> public override void Write(byte[] buffer, int offset, int count, CommUtils.ProtocolLogFormats logFormat, out string logText) { try { if (string.IsNullOrEmpty(RemoteAddress)) throw new InvalidOperationException("RemoteAddress is undefined."); if (RemotePort <= 0) throw new InvalidOperationException("RemotePort is undefined."); byte[] datagram; if (offset > 0) { datagram = new byte[count]; Array.Copy(buffer, offset, datagram, 0, count); } else { datagram = buffer; } try { int sentCnt = UdpClient.Send(datagram, count, RemoteAddress, RemotePort); logText = BuildWriteLogText(datagram, 0, count, logFormat); } catch (SocketException ex) { logText = CommPhrases.WriteDataError + ": " + ex.Message; } } catch (Exception ex) { throw new InvalidOperationException(CommPhrases.WriteDataError + ": " + ex.Message, ex); } }
/// <summary> /// Сформировать текст записи данных для вывода в журнал /// </summary> public static string BuildWriteLogText(byte[] buffer, int offset, int count, CommUtils.ProtocolLogFormats logFormat) { return CommPhrases.SendNotation + " (" + count + "): " + (logFormat == CommUtils.ProtocolLogFormats.Hex ? CommUtils.BytesToHex(buffer, offset, count) : CommUtils.BytesToString(buffer, offset, count)); }
/// <summary> /// Считать данные /// </summary> /// <returns>Количество считанных байт</returns> public abstract int Read(byte[] buffer, int offset, int count, int timeout, CommUtils.ProtocolLogFormats logFormat, out string logText);
/// <summary> /// Считать данные /// </summary> public override int Read(byte[] buffer, int offset, int count, int timeout, CommUtils.ProtocolLogFormats logFormat, out string logText) { try { int readCnt = 0; DateTime nowDT = DateTime.Now; DateTime startDT = nowDT; DateTime stopDT = startDT.AddMilliseconds(timeout); NetStream.ReadTimeout = timeout; // таймаут не выдерживается, если считаны все доступные данные while (readCnt < count && startDT <= nowDT && nowDT <= stopDT) { // считывание данных try { readCnt += NetStream.Read(buffer, readCnt + offset, count - readCnt); } catch (IOException) { } // накопление данных во внутреннем буфере соединения if (readCnt < count) Thread.Sleep(DataAccumThreadDelay); nowDT = DateTime.Now; } logText = BuildReadLogText(buffer, offset, count, readCnt, logFormat); if (readCnt > 0) UpdateActivityDT(); return readCnt; } catch (Exception ex) { throw new InvalidOperationException(CommPhrases.ReadDataError + ": " + ex.Message, ex); } }
/// <summary> /// Записать данные /// </summary> public abstract void Write(byte[] buffer, int offset, int count, CommUtils.ProtocolLogFormats logFormat, out string logText);
/// <summary> /// Считать данные с условием остановки чтения /// </summary> public override int Read(byte[] buffer, int offset, int maxCount, int timeout, BinStopCondition stopCond, out bool stopReceived, CommUtils.ProtocolLogFormats logFormat, out string logText) { try { int readCnt = 0; DateTime nowDT = DateTime.Now; DateTime startDT = nowDT; DateTime stopDT = startDT.AddMilliseconds(timeout); NetStream.ReadTimeout = OneByteReadTimeout; stopReceived = false; int curOffset = offset; byte stopCode = stopCond.StopCode; while (readCnt < maxCount && !stopReceived && startDT <= nowDT && nowDT <= stopDT) { // считывание одного байта данных bool readOk; try { readOk = NetStream.Read(buffer, curOffset, 1) > 0; } catch (IOException) { readOk = false; } if (readOk) { stopReceived = buffer[curOffset] == stopCode; curOffset++; readCnt++; } else { // накопление данных во внутреннем буфере соединения Thread.Sleep(DataAccumThreadDelay); } nowDT = DateTime.Now; } logText = BuildReadLogText(buffer, offset, readCnt, logFormat); if (readCnt > 0) UpdateActivityDT(); return readCnt; } catch (Exception ex) { throw new InvalidOperationException(CommPhrases.ReadDataWithStopCondError + ": " + ex.Message, ex); } }
/// <summary> /// Считать данные, доступные на текущий момент /// </summary> public int ReadAvailable(byte[] buffer, int offset, CommUtils.ProtocolLogFormats logFormat, out string logText) { try { int count = TcpClient.Available; int readCnt = NetStream.Read(buffer, offset, count); logText = BuildReadLogText(buffer, offset, count, readCnt, logFormat); if (readCnt > 0) UpdateActivityDT(); return readCnt; } catch (Exception ex) { throw new InvalidOperationException(CommPhrases.ReadAvailableError + ": " + ex.Message, ex); } }
/// <summary> /// Записать данные /// </summary> public override void Write(byte[] buffer, int offset, int count, CommUtils.ProtocolLogFormats logFormat, out string logText) { try { NetStream.Write(buffer, offset, count); logText = BuildWriteLogText(buffer, offset, count, logFormat); } catch (IOException ex) { logText = CommPhrases.WriteDataError + ": " + ex.Message; } catch (Exception ex) { throw new InvalidOperationException(CommPhrases.WriteDataError + ": " + ex.Message, ex); } }
/// <summary> /// Считать данные с условиями остановки чтения /// </summary> public override int Read(byte[] buffer, int offset, int maxCount, int timeout, Connection.BinStopCondition stopCond, out bool stopReceived, CommUtils.ProtocolLogFormats logFormat, out string logText) { try { int readCnt = 0; DateTime nowDT = DateTime.Now; DateTime startDT = nowDT; DateTime stopDT = startDT.AddMilliseconds(timeout); stopReceived = false; byte stopCode = stopCond.StopCode; int curInd = offset; SerialPort.ReadTimeout = 0; while (readCnt <= maxCount && !stopReceived && startDT <= nowDT && nowDT <= stopDT) { bool readOk; try { readOk = SerialPort.Read(buffer, curInd, 1) > 0; } catch (TimeoutException) { readOk = false; } if (readOk) { stopReceived = buffer[curInd] == stopCode; curInd++; readCnt++; } else { // накопление входных данных в буфере порта Thread.Sleep(DataAccumThreadDelay); } nowDT = DateTime.Now; } logText = BuildReadLogText(buffer, offset, readCnt, logFormat); return readCnt; } catch (Exception ex) { throw new InvalidOperationException(CommPhrases.ReadDataWithStopCondError + ": " + ex.Message, ex); } }
/// <summary> /// Считать данные из последовательного порта /// </summary> /// <param name="serialPort">Последовательный порт</param> /// <param name="buffer">Буфер принимаемых данных</param> /// <param name="index">Начальный индекс в буфере</param> /// <param name="count">Количество принимаемых байт</param> /// <param name="timeout">Таймаут чтения данных, мс</param> /// <param name="wait">Ожидать завершения таймаута после окончания чтения</param> /// <param name="logFormat">Формат вывода данных в журнал</param> /// <param name="logText">Строка для вывода в журнал</param> /// <returns>Количество считанных байт</returns> public static int ReadFromSerialPort(SerialPort serialPort, byte[] buffer, int index, int count, int timeout, bool wait /*игнорируется*/, CommUtils.ProtocolLogFormats logFormat, out string logText) { try { if (serialPort == null) { logText = ReadDataImpossible; return 0; } else { serialConn.SetSerialPort(serialPort); return serialConn.Read(buffer, index, count, timeout, logFormat, out logText); } } catch (Exception ex) { logText = ex.Message; return 0; } }
/// <summary> /// Считать данные /// </summary> public override int Read(byte[] buffer, int offset, int count, int timeout, CommUtils.ProtocolLogFormats logFormat, out string logText) { try { // данный способ чтения данных необходим для избежания исключения // System.ObjectDisposedException при прерывании потока линии связи int readCnt = 0; DateTime nowDT = DateTime.Now; DateTime startDT = nowDT; DateTime stopDT = startDT.AddMilliseconds(timeout); SerialPort.ReadTimeout = 0; while (readCnt < count && startDT <= nowDT && nowDT <= stopDT) { try { readCnt += SerialPort.Read(buffer, offset + readCnt, count - readCnt); } catch (TimeoutException) { } // накопление входных данных в буфере порта if (readCnt < count) Thread.Sleep(DataAccumThreadDelay); nowDT = DateTime.Now; } logText = BuildReadLogText(buffer, offset, count, readCnt, logFormat); return readCnt; } catch (Exception ex) { throw new InvalidOperationException(CommPhrases.ReadDataError + ": " + ex.Message, ex); } }
/// <summary> /// Считать данные с условиями остановки чтения /// </summary> public override int Read(byte[] buffer, int offset, int maxCount, int timeout, BinStopCondition stopCond, out bool stopReceived, CommUtils.ProtocolLogFormats logFormat, out string logText) { try { int readCnt = 0; DateTime nowDT = DateTime.Now; DateTime startDT = nowDT; DateTime stopDT = startDT.AddMilliseconds(timeout); IPEndPoint endPoint = CreateIPEndPoint(); stopReceived = false; byte stopCode = stopCond.StopCode; UdpClient.Client.ReceiveTimeout = DatagramReceiveTimeout; while (readCnt < maxCount && !stopReceived && startDT <= nowDT && nowDT <= stopDT) { // считывание данных int readPos; bool isNew; byte[] datagram = ReceiveDatagram(ref endPoint, out readPos, out isNew); if (datagram != null && datagram.Length > 0) { // поиск кода остановки в считанных данных int datagramLen = datagram.Length; int stopCodeInd = -1; for (int i = readPos; i < datagramLen && !stopReceived; i++) { if (datagram[i] == stopCode) { stopCodeInd = i; stopReceived = true; } } // копирование полученных данных в заданный буфер int requiredCnt = stopReceived ? stopCodeInd - readCnt + 1 : maxCount - readCnt; int copyCnt = Math.Min(datagram.Length - readPos, requiredCnt); Array.Copy(datagram, readPos, buffer, readCnt, copyCnt); readCnt += copyCnt; readPos += copyCnt; } // накопление данных во внутреннем буфере соединения if (readCnt < maxCount && !stopReceived && isNew) Thread.Sleep(DataAccumThreadDelay); StoreDatagram(datagram, readPos); nowDT = DateTime.Now; } logText = BuildReadLogText(buffer, offset, readCnt, logFormat); return readCnt; } catch (Exception ex) { throw new InvalidOperationException(CommPhrases.ReadDataWithStopCondError + ": " + ex.Message, ex); } }
/// <summary> /// Записать данные в последовательный порт /// </summary> /// <param name="serialPort">Последовательный порт</param> /// <param name="buffer">Буфер передаваемых данных</param> /// <param name="index">Начальный индекс в буфере</param> /// <param name="count">Количество передаваемых байт</param> /// <param name="logFormat">Формат вывода данных в журнал</param> /// <param name="logText">Строка для вывода в журнал</param> public static void WriteToSerialPort(SerialPort serialPort, byte[] buffer, int index, int count, CommUtils.ProtocolLogFormats logFormat, out string logText) { try { if (serialPort == null) { logText = WriteDataImpossible; } else { serialConn.SetSerialPort(serialPort); serialConn.Write(buffer, index, count, logFormat, out logText); } } catch (Exception ex) { logText = ex.Message; } }
/// <summary> /// Считать данные из последовательного порта /// </summary> /// <param name="serialPort">Последовательный порт</param> /// <param name="buffer">Буфер принимаемых данных</param> /// <param name="index">Начальный индекс в буфере</param> /// <param name="maxCount">Максимальное количество принимаемых байт</param> /// <param name="stopCode">Байт, означающий окончание считывания данных</param> /// <param name="timeout">Таймаут чтения данных, мс</param> /// <param name="wait">Ожидать завершения таймаута после окончания чтения</param> /// <param name="logFormat">Формат вывода данных в журнал</param> /// <param name="logText">Строка для вывода в журнал</param> /// <returns>Количество считанных байт</returns> public static int ReadFromSerialPort(SerialPort serialPort, byte[] buffer, int index, int maxCount, byte stopCode, int timeout, bool wait /*игнорируется*/, CommUtils.ProtocolLogFormats logFormat, out string logText) { try { if (serialPort == null) { logText = ReadDataImpossible; return 0; } else { serialConn.SetSerialPort(serialPort); bool stopReceived; return serialConn.Read(buffer, index, maxCount, timeout, new Connection.BinStopCondition(stopCode), out stopReceived, logFormat, out logText); } } catch (Exception ex) { logText = ex.Message; return 0; } }