示例#1
0
 public void SendData(BaseConnector from, string dat)
 {
     if (Connections.ContainsKey(from.Name))
     {
         Connections[from.Name].ForEach(r => RegisteredConnectors[r].SendData(dat));
     }
 }
        public async Task <List <HocPhanExtend> > getListUnRegistableAsync()
        {
            try
            {
                List <HocPhanExtend> listHocPhan = new List <HocPhanExtend>();
                BaseConnector        connector   = BaseConnector.getInstance();
                BaseResponse         res         = await connector.GetObject(DeployEnvironment.GetEnvironment().GetUnEnrolablePath());

                if (res.status)
                {
                    JsonAttributes jsonAttr = JsonAttributeGetter.GetJsonAttributes();
                    List <Object>  listO    = JsonGetter.getList(res.obj.ToString(), jsonAttr.RES_RESULT());
                    for (int i = 0; i < listO.Count; i++)
                    {
                        HocPhanExtend hocPhan = new HocPhanExtend()
                        {
                            hocPhan = HocPhan.Parse(JsonGetter.getObject(listO[i].ToString(), jsonAttr.RES_SUBJECT())),
                            lyDo    = JsonGetter.getString(listO[i].ToString(), jsonAttr.RES_REASON())
                        };
                        listHocPhan.Add(hocPhan);
                    }
                }
                return(listHocPhan);
            }
            catch (Exception ex)
            {
                LogHelper.Log("ERROR: " + ex);
                return(null);
            }
        }
示例#3
0
 public void Deregister(BaseConnector connector)
 {
     RegisteredConnectors.Where(c => c.Value == connector).
     ToList().
     ForEach(e =>
             RegisteredConnectors.Remove(e.Key)
             );
 }
示例#4
0
    public UserModel()
    {
        bc = new PGConnector(Global.DefaultConnectionString);

        //
        // TODO: Add constructor logic here
        //
    }
示例#5
0
 private void UpdateConnectionType()
 {
     _connector = (ConnectorType)Properties.Settings.Default.ConnectionType switch
     {
         ConnectorType.WebConnector => new WebConnector(),
         ConnectorType.ComConnector => new ComConnector(),
         _ => throw new System.NotImplementedException("Неизвестный тип подключения"),
     };
 }
        public async Task <bool> SetListEnrol(List <int> listMaMon)
        {
            BaseConnector        connector = BaseConnector.getInstance();
            RequestEnrolOrCancel req       = new RequestEnrolOrCancel();

            req.subject_ids = listMaMon.ToArray();
            BaseResponse res = await connector.PostObject(DeployEnvironment.GetEnvironment().GetEnrolPath(), req);

            return(res.status);
        }
示例#7
0
        public static async Task <bool> sendAuth(string un, string pw)
        {
            BaseConnector connector = BaseConnector.getInstance();
            BaseResponse  res       = await connector.PostObject(DeployEnvironment.GetEnvironment().GetLoginPath(), new AuthRequest()
            {
                mssv = un, password = pw
            });

            return(res.status);
        }
示例#8
0
 public void Register(BaseConnector c)
 {
     if (!RegisteredConnectors.ContainsKey(c.Name))
     {
         RegisteredConnectors.Add(c.Name, c);
     }
     else
     {
         RegisteredConnectors[c.Name] = c;
     }
 }
示例#9
0
 public async Task <SinhVien> GetSinhVienDetailAsync()
 {
     try
     {
         BaseConnector connector = BaseConnector.getInstance();
         sv.GetDataFromObject((await connector.GetObject(DeployEnvironment.GetEnvironment().GetStudentInfoPath(sv.mssv))).obj);
         return(sv);
     }
     catch (Exception ex)
     {
         LogHelper.Log("ERROR: " + ex);
         return(null);
     }
 }
示例#10
0
        /// <summary>
        ///     发送并接收数据,不进行协议扩展和收缩,用于特殊协议
        /// </summary>
        /// <param name="content">发送协议的内容</param>
        /// <returns>接收协议的内容</returns>
        public override async Task <OpcParamOut> SendReceiveWithoutExtAndDecAsync(OpcParamIn content)
        {
            //发送数据
            var receiveBytes = await BaseConnector.SendMsgAsync(content);

            //容错处理
            var checkRight = CheckRight(receiveBytes);

            return(checkRight == null
                ? new OpcParamOut {
                Success = false, Value = new byte[0]
            }
                : (!checkRight.Value ? null : receiveBytes));
            //返回字符
        }
示例#11
0
        public async Task <SinhVienInfo> getOveralInfo()
        {
            try
            {
                BaseConnector connector = BaseConnector.getInstance();
                SinhVienInfo  info      = new SinhVienInfo();
                info.nganh = sv.faculty;
                // Lấy năm hiện tại
                //BaseResponse res1 = await connector.GetObject("nam");
                //if(res1.status)
                //    info.nam = JsonGetter.getString(res1.obj.ToString(), "nam");
                //info.nam = "2019 - 2020";

                info.curCount = getCurCount(info.nam);
                return(info);
            }
            catch (Exception ex)
            {
                LogHelper.Log("ERROR: " + ex);
                return(null);
            }
        }
示例#12
0
    /// <summary>
    ///
    /// </summary>
    /// <param name="direction"></param>
    /// <param name="connector"></param>
    public void SetConnection(RoomConnection.DirectionType direction, BaseConnector connector)
    {
        RoomConnection connection;

        if (!m_connections.TryGetValue(direction, out connection))
        {
            Debug.LogError($"Failed to find a room connection for the direction '{direction}' within the room '{name}'.");
            return;
        }

        if (connection.transform.childCount > 0)
        {
            Debug.LogError($"The connection for direction '{direction}' within the room '{name}' already has a connector.");
            return;
        }

        var newConnection = Instantiate(connector.gameObject, connection.transform);

        newConnection.transform.localPosition = Vector3.zero;
        newConnection.transform.localRotation = Quaternion.identity;
        newConnection.transform.localScale    = Vector3.one;
        newConnection.name = $"{name} - {connector.name} [{direction}]";
    }
示例#13
0
        async static Task Main(string[] args)
        {
            var cfg        = Config.FromFile();
            var connectors = new BaseConnector[] { new TGConnector() };
            var modules    = new BaseModule[] { new ClockModule(), new GuthibModule() };

            foreach (var connector in connectors)
            {
                await connector.Initialize(cfg);
            }
            foreach (var module in modules)
            {
                await module.Initialize(cfg, connectors);
            }
            Console.WriteLine("Online.");
            while (true)
            {
                foreach (var connector in connectors)
                {
                    try {
                        var msgs = await connector.FetchMessages();

                        foreach (var msg in msgs)
                        {
                            foreach (var module in modules)
                            {
                                await module.HandleMessage(msg);
                            }
                            Console.WriteLine("Handled: " + LitJson.JsonMapper.ToJson(msg));
                        }
                    } catch (Exception e) {
                        Console.WriteLine("Error: " + e.Message);
                    }
                }
                await Task.Delay(1000);
            }
        }
        /// <summary>
        /// 处理告警队列
        /// </summary>
        private void StartAlarmEventProcessor()
        {
            Version = MGroup.Instance.Version;
            logger.Polling.Info("Current Management Server version is: " + Version.ToString());

            RateLimitQueueSize = this.pluginConfig.RateLimitQueueSize;
            RateLimitTimeSpan  = TimeSpan.FromSeconds(this.pluginConfig.RateLimitTimeSpan);

            if (AlarmProcessor == null)
            {
                AlarmProcessor = new Thread(delegate()
                {
                    while (this.IsRunning) // TODO(turnbig) 假如Queue里面还有未处理的数据,直接丢弃?
                    {
                        logger.Polling.Info($"Current Alarm Processing Queue amount: {AlarmQueue.Count}.");

                        if (AlarmQueue.Count > 0 || ReceiveAlarmEvent.WaitOne())
                        {
                            AlarmData alarm = null;
                            lock (this.locker)
                            {
                                if (AlarmQueue.Count > 0)
                                {
                                    alarm = AlarmQueue.Dequeue();
                                }
                            }

                            if (alarm != null)
                            {
                                EventData eventObject = new EventData(alarm, this.FusionDirectorIp);
                                logger.Polling.Info($"[{alarm.Sn}] Start processing alarm:: Source:{alarm.DeviceId}, Category:{alarm.EventCategory}, Status: {alarm.Status}.");

                                var objectId                            = eventObject.UnionId;
                                string mpClazzName                      = EventCategory.BMC.Equals(alarm.EventCategory) ? EntityTypeConst.Server.MainName : EntityTypeConst.Enclosure.MainName;
                                ManagementPackClass mpClazz             = MGroup.Instance.GetManagementPackClass(mpClazzName);
                                MonitoringDeviceObject monitoringObject = BaseConnector.GetDeviceByObjectId(mpClazz, objectId);
                                if (monitoringObject == null)
                                {
                                    // TODO(turnbig.net) should we trigger an update server task, and retry later?
                                    logger.Polling.Warn($"[{alarm.Sn}] No MonitoringObject({objectId}) exists, alarm will be ignored.");
                                    continue;
                                }

                                // waiting for monitoring-object ready.
                                WaitForDeviceMonitored(monitoringObject);


                                var now = DateTime.Now;
                                ProcessedOn previewNProcessedOn = null;
                                FixedSizedQueue <ProcessedOn> processedOnQueue = GetProcessedOnQueue(eventObject);
                                if (EventStatus.Cleared.Equals(alarm.Status))
                                {
                                    // Close SCOM alert
                                    CloseSCOMAlert(eventObject, monitoringObject);
                                }
                                else if (ShouldProcessedAlarmLevels.Contains(eventObject.LevelId))
                                {
                                    // Create New EventLog for new alarms, and generate SCOM alert through associated rule
                                    CreateNewEventLogForAlarm(eventObject);
                                    // use a seperated process on tracker
                                    previewNProcessedOn = processedOnQueue.Enqueue(new ProcessedOn(now));
                                }

                                if (previewNProcessedOn != null)
                                {
                                    TimeSpan timeSpan = now - previewNProcessedOn.Timestamp;
                                    // do not know why system time was changed to yestoday.
                                    if (now >= previewNProcessedOn.Timestamp && timeSpan < RateLimitTimeSpan)
                                    {
                                        TimeSpan timeout = RateLimitTimeSpan - timeSpan;
                                        logger.Polling.Info($"Alarm processing reach rate limit, {processedOnQueue.Size} alarms have been processed during time span {timeSpan}, will sleep {timeout} now.");
                                        Thread.Sleep(timeout);
                                    }
                                }
                            }
                        }
                    }
                });
            }

            this.AlarmProcessor.Start();
            logger.Polling.Info("Alarm processor starts successfully.");
        }
示例#15
0
 public UserModel(BaseConnector _connector)
 {
     bc = _connector;
 }
示例#16
0
        internal static async Task UpdateReportAsync(string projectName, string version, IConfiguration configuration)
        {
            var genericRepo        = new BaseConnector(null, null, AuthenticationType.None);
            var reportStatus       = new List <ReportExecutionStatus>();
            var projectDescription = string.Empty;

            try
            {
                var timeoutInMinutes = 10;
                var url = configuration["Fortify:Url"];
                var key = Convert.ToBase64String(Encoding.UTF8.GetBytes($"{configuration["Fortify:User"]}:{configuration["Fortify:Password"]}"));

                _fortifyConnector = new FortifyConnector(url, key, AuthenticationType.Basic)
                {
                    Timeout = TimeSpan.FromMinutes(timeoutInMinutes)
                };

                var unifiedLoginToken = await _fortifyConnector.GetUnifiedLoginTokenAsync();

                _fortifyConnector = new FortifyConnector(url, unifiedLoginToken, AuthenticationType.FortifyToken)
                {
                    Timeout = TimeSpan.FromMinutes(timeoutInMinutes)
                };

                var projects = await _fortifyConnector.GetProjectsAsync();

                var project = projects.FirstOrDefault(p => p.Name.Equals(projectName));

                if (project != null)
                {
                    var projectVersions = await _fortifyConnector.GetProjectVersionsAsync(project.Id);

                    var projectVersion = projectVersions.FirstOrDefault(v => version.Equals(v.Name, StringComparison.InvariantCultureIgnoreCase));
                    projectDescription = project.Description;

                    if (projectVersion != null)
                    {
                        Console.WriteLine($"{project.Name} {project.Description} {projectVersion.Name} started");
                        var appSecItems = new List <AppSecItem>();

                        var issues = await _fortifyConnector.GetIssuesAsync(projectVersion.Id);

                        if (issues != null)
                        {
                            foreach (var issue in issues)
                            {
                                var issueDetails = await GetIssueDetailsAsync(project.Name, projectVersion.Name, issue.IssueInstanceId);

                                var appSecItem = new AppSecItem()
                                {
                                    Id            = issue.IssueInstanceId,
                                    UploadDate    = DateTime.Now.Date.ToString("yyyy-MM-dd"),
                                    UAID          = $"{project.Name} {project.Description}",
                                    Version       = projectVersion.Name,
                                    Status        = issue.IssueStatus,
                                    Category      = issue.IssueName,
                                    Severity      = issue.friority,
                                    Source        = issue.EngineType,
                                    Tag           = issue.PrimaryTag,
                                    IsRedBall     = IsRedBall(issue) || issueDetails.IsOWASPTopTen,
                                    OWASPCategory = issueDetails.OWASPCategory,
                                    File          = issue.PrimaryLocation,
                                    LineNumber    = issue.LineNumber,
                                    ScanStatus    = issue.ScanStatus
                                };

                                appSecItems.Add(appSecItem);
                            }
                        }

                        var jsonBody = JsonSerializer.Serialize(appSecItems);

                        //Save file for further analysis
                        File.WriteAllText($@"C:\Temp\UVMS\{DateTime.Now.Date.ToString("yyyy-MM-dd")} {projectVersion.Name} {project.Name} {project.Description}.json", jsonBody);

                        await genericRepo.PostWithJsonAsync(configuration["PowerBI:UVMSDashboardUrl"], jsonBody);

                        Console.WriteLine($"{project.Name} {project.Description} {projectVersion.Name} finished");

                        var executionStatus = new ReportExecutionStatus()
                        {
                            ReportDate = DateTime.Now.Date.ToString("yyyy-MM-dd"),
                            UAID       = $"{projectName} {projectDescription}",
                            Version    = version,
                            Status     = "Successful"
                        };

                        reportStatus.Add(executionStatus);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"{ex.Message}");

                var executionStatus = new ReportExecutionStatus()
                {
                    ReportDate = DateTime.Now.Date.ToString("yyyy-MM-dd"),
                    UAID       = $"{projectName} {projectDescription}",
                    Version    = version,
                    Status     = "Failed"
                };

                reportStatus.Add(executionStatus);
            }

            await genericRepo.PostWithJsonAsync(configuration["PowerBI:ReportExecutionDashboardUrl"], JsonSerializer.Serialize(reportStatus));
        }
示例#17
0
 public BasicInformation(BaseConnector connector)
 {
     this.Connector = connector;
     this.PortName  = Connector.PortName;
 }