public HealthResult CheckHealth(BusState busState, string healthMessage) { var results = _endpoints.Values.Select(x => new { x.InputAddress, Result = x.HealthResult }).ToArray(); var unhealthy = results.Where(x => x.Result.Status == BusHealthStatus.Unhealthy).ToArray(); var degraded = results.Where(x => x.Result.Status == BusHealthStatus.Degraded).ToArray(); var unhappy = unhealthy.Union(degraded).ToArray(); var names = unhappy.Select(x => x.InputAddress.AbsolutePath.Split('/').LastOrDefault()).ToArray(); Dictionary <string, EndpointHealthResult> data = results.ToDictionary(x => x.InputAddress.ToString(), x => x.Result); var exception = results.Where(x => x.Result.Exception != null).Select(x => x.Result.Exception).FirstOrDefault(); if (busState != BusState.Started || unhealthy.Any() && unhappy.Length == results.Length) { return(HealthResult.Unhealthy($"Not ready: {healthMessage}", exception, data)); } if (unhappy.Any()) { return(HealthResult.Degraded($"Degraded Endpoints: {string.Join(",", names)}", exception, data)); } return(HealthResult.Healthy("Ready", data)); }
public void SetUp() { var hangingChecker = Substitute.For<ISystemChecker>(); hangingChecker.SystemName.Returns("Hanging checker"); hangingChecker.CheckSystem().Returns(x => { Thread.Sleep(TimeSpan.FromSeconds(10)); return (SystemCheckResult)null; }); var healthyChecker = Substitute.For<ISystemChecker>(); healthyChecker.CheckSystem().Returns(x => new SystemCheckResult { SystemName = "Healthy checker", Health = HealthState.Good }); var healthNetConfiguration = Substitute.For<IHealthNetConfiguration>(); healthNetConfiguration.DefaultSystemCheckTimeout.Returns(TimeSpan.FromSeconds(1)); var service = new HealthCheckService(healthNetConfiguration, Substitute.For<IVersionProvider>(), new[] { hangingChecker, healthyChecker }); var task = Task<HealthResult>.Factory.StartNew(() => service.CheckHealth()); if (Task.WaitAll(new Task[] {task}, TimeSpan.FromSeconds(5))) { result = task.Result; } else { throw new TimeoutException(); } }
private void ParseToHealthResult(List <string> values, ref HealthResult entity, List <ImportErrorColModel> errors) { if (errors.Count > 0) { entity = null; return; } entity.MainPositiveResult = values[8]; entity.Result = values[9]; entity.Deleted = false; entity.HealthCode = values[10]; entity.ImageCode = values[11]; entity.ReportCode = values[12]; //values[13] if (!string.IsNullOrEmpty(values[14])) { entity.HealthDate = DateTime.Parse(values[14]); } if (!string.IsNullOrEmpty(values[15])) { entity.HealthByCompany = values[15]; } if (!string.IsNullOrEmpty(values[16])) { entity.ReportDate = values[16]; } entity.HealthPerson = values[17]; }
public void SetUp() { var hangingChecker = Substitute.For <ISystemChecker>(); hangingChecker.SystemName.Returns("Hanging checker"); hangingChecker.CheckSystem().Returns(x => { Thread.Sleep(TimeSpan.FromSeconds(10)); return((SystemCheckResult)null); }); var healthyChecker = Substitute.For <ISystemChecker>(); healthyChecker.CheckSystem().Returns(x => new SystemCheckResult { SystemName = "Healthy checker", Health = HealthState.Good }); var healthNetConfiguration = Substitute.For <IHealthNetConfiguration>(); healthNetConfiguration.DefaultSystemCheckTimeout.Returns(TimeSpan.FromSeconds(1)); var service = new HealthCheckService(healthNetConfiguration, Substitute.For <IVersionProvider>(), new[] { hangingChecker, healthyChecker }); var task = Task <HealthResult> .Factory.StartNew(() => service.CheckHealth()); if (Task.WaitAll(new Task[] { task }, TimeSpan.FromSeconds(5))) { result = task.Result; } else { throw new TimeoutException(); } }
/// <summary> /// Gets the HealthResult analysis of this Sitecore instance /// </summary> /// <returns>The HealthResult analysis</returns> public HealthResult GetHealthResult() { result = new HealthResult(); db = Sitecore.Configuration.Factory.GetDatabase("master"); DoRenderings(); return(result); }
public void SetUp() { var versionProvider = Substitute.For<IVersionProvider>(); versionProvider.GetSystemVersion().Returns("1.2.3.4"); var healthNetConfiguration = Substitute.For<IHealthNetConfiguration>(); healthNetConfiguration.DefaultSystemCheckTimeout.Returns(TimeSpan.FromSeconds(5)); var service = new HealthCheckService(healthNetConfiguration, versionProvider, SystemStateCheckers()); Result = service.CheckHealth(PerformeIntrusive); }
public void SetUp() { var versionProvider = Substitute.For <IVersionProvider>(); versionProvider.GetSystemVersion().Returns("1.2.3.4"); var healthNetConfiguration = Substitute.For <IHealthNetConfiguration>(); healthNetConfiguration.DefaultSystemCheckTimeout.Returns(TimeSpan.FromSeconds(5)); var service = new HealthCheckService(healthNetConfiguration, versionProvider, SystemStateCheckers()); Result = service.CheckHealth(PerformeIntrusive); }
private void PrepareHealthResultViewModel(HealthResultViewModel model, HealthResult entity) { var companies = _companyService.GetAll(); foreach (var item in companies) { model.AvailableCompanies.Add(new SelectListItem { Text = item.CompanyName, Value = item.Id.ToString(), Selected = entity != null && entity.CompanyEmployee != null && entity.CompanyEmployee.Company != null && item.Id == entity.CompanyEmployee.Company.Id }); } }
public async Task<HealthResult> GetCurrent() { var result = new HealthResult(); result.ServicesVersion = AssemblyName .GetAssemblyName(HostingEnvironment.ApplicationPhysicalPath + "bin\\Resgrid.Web.Services.dll").Version.ToString(); result.ApiVersion = "v3"; result.SiteId = "0"; result.CacheOnline = _healthService.IsCacheProviderConnected(); var dbTime = await _healthService.GetDatabaseTimestamp(); if (!string.IsNullOrWhiteSpace(dbTime)) result.DatabaseOnline = true; else result.DatabaseOnline = false; return result; }
public async Task <IActionResult> GetCurrent() { var result = new HealthResult(); var path = System.IO.Path.GetDirectoryName(Assembly.GetEntryAssembly().Location) + "\\Resgrid.Web.Eventing.dll"; result.WebsiteVersion = AssemblyName.GetAssemblyName(path).Version.ToString(); result.SiteId = "0"; result.CacheOnline = false; //_healthService.IsCacheProviderConnected(); result.ServiceBusOnline = false; //_healthService.IsCacheProviderConnected(); //var dbTime = await _healthService.GetDatabaseTimestamp(); //if (!string.IsNullOrWhiteSpace(dbTime)) // result.DatabaseOnline = true; //else result.DatabaseOnline = false; return(Json(result)); }
private IRepository CreateRepository(HealthResult healthResult) { IRepository repository = null; try { var sessionManager = new SessionManager(); repository = new Repository(sessionManager); } catch (Exception e) { var exceptionMessage = e.InnerException != null ? e.InnerException.Message : e.Message; healthResult.Status = new HealthStatus(HealthStatus.Error); healthResult.Message = "Unable to create a database connection. " + exceptionMessage; healthResult.ErrorCode = "101"; return(repository); } return(repository); }
public void SetUp() { var hangingChecker = Substitute.For <ISystemChecker>(); hangingChecker.SystemName.Returns("Hanging checker"); hangingChecker.CheckSystem().Returns(x => { Thread.Sleep(TimeSpan.FromSeconds(10)); return((SystemCheckResult)null); }); var healthyChecker = Substitute.For <ISystemChecker>(); healthyChecker.SystemName.Returns("Healthy checker"); healthyChecker.CheckSystem() .Returns(x => new SystemCheckResult { SystemName = healthyChecker.SystemName, Health = HealthState.Good }); var healthNetConfiguration = Substitute.For <IHealthNetConfiguration>(); healthNetConfiguration.DefaultSystemCheckTimeout.Returns(TimeSpan.FromSeconds(4)); var service = new HealthCheckService(healthNetConfiguration, Substitute.For <IVersionProvider>(), new[] { hangingChecker, healthyChecker }); var task = Task <HealthResult> .Factory.StartNew(() => service.CheckHealth()); if (Task.WaitAll(new Task[] { task }, TimeSpan.FromSeconds(20))) { result = task.Result; TestContext.Progress.WriteLine($"Health check result:{Environment.NewLine}{JsonConvert.SerializeObject(result)}"); } else { TestContext.Progress.WriteLine("Healthcheck timed out"); throw new TimeoutException(); } }
public async Task <HealthResult> GetCurrent() { var result = new HealthResult(); var path = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location) + "\\Resgrid.Web.Services.dll"; result.ServicesVersion = AssemblyName.GetAssemblyName(path).Version.ToString(); result.ApiVersion = "v3"; result.SiteId = "0"; result.CacheOnline = _healthService.IsCacheProviderConnected(); var dbTime = await _healthService.GetDatabaseTimestamp(); if (!string.IsNullOrWhiteSpace(dbTime)) { result.DatabaseOnline = true; } else { result.DatabaseOnline = false; } return(result); }
public ActionResult CreateOrUpdate(HealthResultViewModel model, string command) { if (command == "searchEmployee") { ValidateHealthResultViewModelForSearch(model); if (ModelState.IsValid) { var entityEmplyee = _companyEmployeeService.GetEmployee(model.IDCard, model.CompanyId); if (entityEmplyee != null) { model.UserName = entityEmplyee.EmployeeBaseInfo.UserName; model.IDCard = entityEmplyee.EmployeeBaseInfo.IDCard; model.Sex = entityEmplyee.EmployeeBaseInfo.Sex; model.AdverseMonthes = entityEmplyee.AdverseMonthes; model.AdverseFactor = entityEmplyee.AdverseFactor; model.CompanyId = entityEmplyee.Company.Id; model.CompanyEmployeeId = entityEmplyee.Id; } else { ErrorNotification(new Exception("未找到员工")); model = new HealthResultViewModel(); } } else { ErrorNotification(new Exception("输入信息有误")); } } else if (command == "createOrUpdate") { ValidateHealthResultViewModelForCreateOrUpdate(model); if (ModelState.IsValid) { if (model.Id.ToString() == "00000000-0000-0000-0000-000000000000") { using (var unitOfWork = UnitOfWorkManager.NewUnitOfWork()) { var entity = new HealthResult() { Id = Guid.NewGuid(), MainPositiveResult = model.MainPositiveResult, Result = model.Result, HealthCode = model.HealthCode, ImageCode = model.ImageCode, ReportCode = model.ReportCode, HealthDate = model.HealthDate, ReportDate = model.ReportDate.HasValue ? model.ReportDate.Value.ToString("yyyy-MM-dd") : "", HealthPerson = model.HealthPerson, CompanyEmployee = _companyEmployeeService.GetById(model.CompanyEmployeeId), HealthByCompany = model.HealthByCompany, CreatedBy = _workContext.CurrentMembershipUser.Username, CreatedDate = DateTime.Now }; _healthResultService.Add(entity); unitOfWork.Commit(); SuccessNotification("添加成功"); model = new HealthResultViewModel(); PrepareHealthResultViewModel(model, entity); return(View(model)); } } else { var entity = _healthResultService.GetById(model.Id); if (entity != null) { using (var unitOfWork = UnitOfWorkManager.NewUnitOfWork()) { entity.MainPositiveResult = model.MainPositiveResult; entity.Result = model.Result; entity.HealthCode = model.HealthCode; entity.ImageCode = model.ImageCode; entity.ReportCode = model.ReportCode; entity.HealthDate = model.HealthDate; entity.ReportDate = model.ReportDate.HasValue ? model.ReportDate.Value.ToString("yyyy-MM-dd") : ""; entity.HealthPerson = model.HealthPerson; entity.CompanyEmployee = _companyEmployeeService.GetById(model.CompanyEmployeeId); entity.HealthByCompany = model.HealthByCompany; entity.UpdatedBy = _workContext.CurrentMembershipUser.Username; entity.UpdatedDate = DateTime.Now; unitOfWork.Commit(); SuccessNotification("编辑成功"); return(RedirectToAction("Index")); } } else { ErrorNotification(new Exception("编辑失败,未找到Id为" + model.Id.ToString() + "的体检信息")); return(RedirectToAction("Index")); } } } else { ErrorNotification(new Exception("编辑失败,输入信息有误")); PrepareHealthResultViewModel(model, null); return(View(model)); } } PrepareHealthResultViewModel(model, null); return(View(model)); }
public void Add(HealthResult entity) { _healthResultRepository.Add(entity); }
private async void GetPCHealth(string device_id) { if (comfun.isConnected()) { try { var clients = new HttpClient(); clients.BaseAddress = new Uri(App.api_url); var values = new Dictionary <string, string>(); values.Add("session_string", App.session_string); values.Add("data", "{\"table\": \"devices\"}"); values.Add("extra", "{\"id\": \"" + device_id + "\"}"); var content = new FormUrlEncodedContent(values); HttpResponseMessage response = await clients.PostAsync("/itcrm/getElements/", content); var result = await response.Content.ReadAsStringAsync(); HealthResult health_list = JsonConvert.DeserializeObject <HealthResult>(result); var detail = health_list.result[0]; dt.Add(new LvPcHealth() { title = "Device ID: ", value = detail.id }); dt.Add(new LvPcHealth() { title = "Name: ", value = detail.name }); pc_detail = pc_detail + "Device Name: " + detail.name + ", "; dt.Add(new LvPcHealth() { title = "Make: ", value = detail.make }); dt.Add(new LvPcHealth() { title = "HDD Status: ", value = detail.hdd_status }); pc_detail = pc_detail + "HDD Status: " + detail.hdd_status + ", "; dt.Add(new LvPcHealth() { title = "RAM: ", value = detail.ram }); pc_detail = pc_detail + "RAM: " + detail.ram + ", "; dt.Add(new LvPcHealth() { title = "Processor: ", value = detail.processor }); pc_detail = pc_detail + "Processor: " + detail.processor + ", "; dt.Add(new LvPcHealth() { title = "Temp: ", value = detail.temperature }); pc_detail = pc_detail + "Temprature: " + detail.temperature + ", "; dt.Add(new LvPcHealth() { title = "Antivirus: ", value = detail.antivirus }); pc_detail = pc_detail + "Antivirus: " + detail.antivirus + ", "; dt.Add(new LvPcHealth() { title = "OS Installed: ", value = detail.operating_system }); pc_detail = pc_detail + "OS Installed: " + detail.operating_system + ", "; dt.Add(new LvPcHealth() { title = "CPU Usage: ", value = detail.cpu_usage }); pc_detail = pc_detail + "CPU Usage: " + detail.cpu_usage; activityIndicator.IsRunning = false; } catch (Exception e) { // await DisplayAlert("Error!", e.Message, "ok"); } } else { await DisplayAlert("Connection", "Internet Connection Disabled", "Ok"); } }
public override HealthResult Execute() { var healthResult = new HealthResult { Status = new HealthStatus(HealthStatus.Success), Name = Name, Message = string.Empty, ExecutionTime = "0ms", Type = typeof(FailedEvaluationRequestHealthCheck) }; _repository = CreateRepository(healthResult); if (_repository == null) { return(healthResult); } var stopWatch = new Stopwatch(); stopWatch.Start(); var instanceName = Environment.MachineName; var testDate = DateTime.Now.AddMinutes(-TimeIntervalInMinutes); var evaluationRequests = _repository.GetAll <EvaluationRequest>().Where(x => x.DateModified != null && x.DateModified > testDate && x.InstanceName == instanceName).ToList(); if (evaluationRequests.Any()) { var failedRequestsCount = evaluationRequests.Count(x => x.RequestStatus == "Failed"); double percentage = failedRequestsCount * 100 / (double)evaluationRequests.Count; if (percentage > Threshold) { healthResult.Status = new HealthStatus(HealthStatus.Error); healthResult.ErrorCode = "100"; healthResult.Message += string.Format( "For the instance name {0}, the percentage of failed evaluation requests in the last {1} minutes has exceeded {2}%. Failed: {3}, In Progress: {4}, In Queue: {5}, Pending: {6}, Completed: {7}.", instanceName, TimeIntervalInMinutes, Threshold, failedRequestsCount, evaluationRequests.Count(x => x.RequestStatus == "In Progress"), evaluationRequests.Count(x => x.RequestStatus == "In Queue"), evaluationRequests.Count(x => x.RequestStatus == "Pending"), evaluationRequests.Count(x => x.RequestStatus == "Completed")); } else { healthResult.Message += string.Format( "For the instance name {0}, the percentage of failed evaluation requests in the last {1} minutes has NOT exceeded {2}%. Failed: {3}, In Progress: {4}, In Queue: {5}, Pending: {6}, Completed: {7}.", instanceName, TimeIntervalInMinutes, Threshold, failedRequestsCount, evaluationRequests.Count(x => x.RequestStatus == "In Progress"), evaluationRequests.Count(x => x.RequestStatus == "In Queue"), evaluationRequests.Count(x => x.RequestStatus == "Pending"), evaluationRequests.Count(x => x.RequestStatus == "Completed")); } } else { healthResult.Message += string.Format("No evaluation requests found for instance name {0} in the last {1} minutes.", instanceName, TimeIntervalInMinutes); } stopWatch.Stop(); healthResult.ExecutionTime = stopWatch.ElapsedMilliseconds + "ms"; return(healthResult); }
private void ParseToEntityMain(List <string> values, ref List <ImportErrorColModel> errors, bool isCoverData) { //判断源数据是否有身份证号 if (!string.IsNullOrEmpty(values[2])) { var company = _companyRepository.GetByName(values[13]); //判断是否有companyEmployee var companEmployee = _companyEmployeeRepository.GetEmployee(values[2], company.Id); if (companEmployee == null) { errors.Add(new ImportErrorColModel() { ColIndex = 2, Message = ERROR_USERNOTEXISTS }); } var entity = _healthResultRepository.GetByReportCode(values[12]); //创建新体检记录 if (entity == null) { entity = new HealthResult(); try { ParseToHealthResult(values, ref entity, errors); if (entity != null) { //是否覆盖 if (isCoverData) { _healthResultRepository.DeleteByReportCode(entity.ReportCode); } entity.CreatedBy = _workContext.CurrentMembershipUser.Username; entity.CreatedDate = DateTime.Now; entity.CompanyEmployee = companEmployee; _healthResultRepository.Add(entity); } } catch (Exception e) { throw e; } } else { try { ParseToHealthResult(values, ref entity, errors); if (entity != null) { entity.UpdatedBy = _workContext.CurrentMembershipUser.Username; entity.UpdatedDate = DateTime.Now; } } catch (Exception e) { throw e; } } } else { //没有身份证号 errors.Add(new ImportErrorColModel() { ColIndex = 2, Message = ERROR_IDCARD_EMPTY, }); } }
public void Add(HealthResult entity) { _context.HealthResult.Add(entity); }
private async void GetWarningDetails(string warning_id) { if (comfun.isConnected()) { var client = new HttpClient(); client.BaseAddress = new Uri(App.api_url); var values = new Dictionary <string, string>(); values.Add("operation", "query"); values.Add("session_string", App.session_string); values.Add("query", "select * from warnings where id = " + warning_id); var content = new FormUrlEncodedContent(values); HttpResponseMessage response = await client.PostAsync("/itcrm/webservices/", content); var result = await response.Content.ReadAsStringAsync(); //await DisplayAlert("Info!", result, "ok"); WarningsResult warningDetail = JsonConvert.DeserializeObject <WarningsResult>(result); var detail = warningDetail.result[0]; device_id = detail.warnings_device_id; // Device name try { var clientsID = new HttpClient(); clientsID.BaseAddress = new Uri(App.api_url); var valuesID = new Dictionary <string, string>(); valuesID.Add("session_string", App.session_string); valuesID.Add("data", "{\"table\": \"devices\"}"); valuesID.Add("extra", "{\"id\": \"" + device_id + "\"}"); var contentID = new FormUrlEncodedContent(valuesID); HttpResponseMessage responseID = await clientsID.PostAsync("/itcrm/getElements/", contentID); var resultID = await responseID.Content.ReadAsStringAsync(); // await DisplayAlert("Alert", "You have been alerted" + resultID, "OK"); HealthResult health_list = JsonConvert.DeserializeObject <HealthResult>(resultID); var detailID = health_list.result[0]; //lblWarningID.Text = detailID.name; dt.Add(new WarningDetailLv() { title = "Name: ", value = detailID.name }); } catch (Exception e) { // await DisplayAlert("Error!", e.Message, "ok"); } var lst = warningDetail.result[0]; var warning_list = lst.warnings_warnings; // OS try { var opSystem = warning_list.os; bool os_status = opSystem.status; if (os_status) { //lblWarningOS.Text = opSystem.warning; dt.Add(new WarningDetailLv() { title = "Operating System: ", value = opSystem.warning }); warning_detail = warning_detail + opSystem.warning + ", "; } else { //lblWarningOS.Text = "No errors found"; } } catch (Exception r) { //lblWarningOS.Text = "Something went wrong"; } // hard disk try { var hardDisk = warning_list.hdd_status; var hd_status = hardDisk.status; if (hd_status) { //lblWarningHDDStatus.Text = hardDisk.warning; dt.Add(new WarningDetailLv() { title = "HDD Status: ", value = hardDisk.warning }); warning_detail = warning_detail + hardDisk.warning + ", "; } else { //lblWarningHDDStatus.Text = "No errors found"; } } catch (Exception w) { //lblWarningHDDStatus.Text = "Something went wrong"; } // temp try { var temperature = warning_list.temperature; bool temp_status = temperature.status; if (temp_status) { //lblWarningTemperature.Text = temperature.warning; dt.Add(new WarningDetailLv() { title = "Temprature: ", value = temperature.warning }); warning_detail = warning_detail + temperature.warning + ", "; } else { //lblWarningTemperature.Text = "No errors found"; } } catch (Exception r) { //lblWarningTemperature.Text = "Something went wrong"; } // ram try { var memory = warning_list.ram; bool ram_status = memory.status; if (ram_status) { dt.Add(new WarningDetailLv() { title = "Momeory: ", value = memory.warning }); warning_detail = warning_detail + memory.warning + ", "; } else { //lblWarningRAM.Text = "No errors found"; } } catch (Exception r) { //lblWarningRAM.Text = "Something went wrong"; } // cpu try { var cpu_use = warning_list.cpu; bool cpu_status = cpu_use.status; if (cpu_status) { //lblWarningCPUUsage.Text = cpu_use.warning; dt.Add(new WarningDetailLv() { title = "CPU: ", value = cpu_use.warning }); warning_detail = warning_detail + cpu_use.warning + ", "; } else { //lblWarningCPUUsage.Text = "No errors found"; } } catch (Exception r) { //lblWarningCPUUsage.Text = "Something went wrong"; } // antivirus try { var antivirus = warning_list.antivirus; bool av_status = antivirus.status; if (av_status) { //lblWarningAntivirus.Text = antivirus.warning; dt.Add(new WarningDetailLv() { title = "Antivirus: ", value = antivirus.warning }); warning_detail = warning_detail + antivirus.warning + " "; } else { //lblWarningAntivirus.Text = "No errors found"; } } catch (Exception r) { //lblWarningAntivirus.Text = "Something went wrong"; } // created on dt.Add(new WarningDetailLv() { title = "Created on: ", value = detail.warnings_created }); activityIndicator.IsRunning = false; } else { await DisplayAlert("Connection", "Internet Connection Disabled", "Ok"); } }