private bool AddToDB(string parentName, string topicName, string longTitle, string description) { try { using (var session = FactoryProvider.SessionFactory.OpenSession()) { MeasureService measureSvc = new MeasureService(session); if (topicName == string.Empty) { // Row is a topic category. measureSvc.AddTopicCategory(parentName, longTitle, description); } else { // Row is a topic. // Find the topic topic field. TopicCategory category = measureSvc.GetTopicCategory(parentName); // Check to make sure we found one. if (category == null) { // Create a new Topic topic. // longTitle and description are related to the topic, not the parent topic, so just reuse the name. measureSvc.AddTopicCategory(parentName, parentName, parentName); } Topic topic = measureSvc.AddTopic(category, topicName, longTitle, description); } } return(true); } catch (Exception ex) { Logger.Write(ex); return(false); } }
public static OpenProductionUnitsStatsViewModel GetNetworkStatistic(ApplicationDbContext db) { MeasureService measureService = new MeasureService(db); var rslt = db.ProductionUnits.Include(p => p.productionUnitStatus) .Where(p => p.productionUnitType.Id <= 5); var productionUnitNumber = rslt.Count(); var totalBalcony = rslt.Where(p => p.productionUnitType.Id == 1).Count(); var totalCity = rslt.Where(p => p.productionUnitType.Id == 2).Count(); var totalFamily14 = rslt.Where(p => p.productionUnitType.Id == 3).Count(); var totalFamily22 = rslt.Where(p => p.productionUnitType.Id == 4).Count(); var totalFarm = rslt.Where(p => p.productionUnitType.Id == 5).Count(); var totalMonthlyProduction = totalBalcony * monthlyAverageProductionAerospring + totalCity * monthlyAverageProductionCity + totalFamily14 * monthlyAverageProductionFamily14 + totalFamily22 * monthlyAverageProductionFamily22 + totalFarm * monthlyAverageProductionFarm; var totalMonthlySparedCO2 = Math.Round(totalMonthlyProduction * CO2SparedPerKilogramLocallyProduced); return(new OpenProductionUnitsStatsViewModel() { productionUnitNumber = productionUnitNumber, totalMonthlyProduction = totalMonthlyProduction, totalMonthlySparedCO2 = totalMonthlySparedCO2 }); }
public ActionResult GetNetworkStats() { ApplicationDbContext db = new ApplicationDbContext(); MeasureService measureService = new MeasureService(db); var rslt = db.ProductionUnits.Include(p => p.productionUnitStatus) .Where(p => p.productionUnitType.Id <= 5); var productionUnitNumber = rslt.Count(); var totalBalcony = rslt.Where(p => p.productionUnitType.Id == 1).Count(); var totalCity = rslt.Where(p => p.productionUnitType.Id == 2).Count(); var totalFamily14 = rslt.Where(p => p.productionUnitType.Id == 3).Count(); var totalFamily22 = rslt.Where(p => p.productionUnitType.Id == 4).Count(); var totalFarm = rslt.Where(p => p.productionUnitType.Id == 5).Count(); var totalMonthlyProduction = totalBalcony * 4 + totalCity * 7 + totalFamily14 * 10 + totalFamily22 * 15 + totalFarm * 25; var totalMonthlySparedCO2 = Math.Round(totalMonthlyProduction * 0.3); return(Json(new { ProductionUnitNumber = productionUnitNumber, TotalMonthlyProduction = totalMonthlyProduction, TotalMonthlySparedCO2 = totalMonthlySparedCO2, }, JsonRequestBehavior.AllowGet)); }
public ActionResult HumidityMeasure_Read([DataSourceRequest] DataSourceRequest request, int id, string range) { var db = new ApplicationDbContext(); var measureService = new MeasureService(db); var measuresList = new List <MeasureViewModel>(); measuresList.AddRange(measureService.Read(SensorTypeEnum.humidity, id, range)); measuresList.AddRange(measureService.Read(SensorTypeEnum.externalHumidity, id, range)); var groupedMesuresList = new List <GroupedMeasureViewModel>(); measuresList.GroupBy(m => m.captureDate).ToList().ForEach(m => { var groupedMeasures = new GroupedMeasureViewModel(); groupedMeasures.captureDate = m.Key; if (m.ToList().Where(i => i.sensorId == (int)SensorTypeEnum.humidity).FirstOrDefault() != null) { groupedMeasures.humidityValue = m.ToList().Where(i => i.sensorId == (int)SensorTypeEnum.humidity).FirstOrDefault().value; } if (m.ToList().Where(i => i.sensorId == (int)SensorTypeEnum.externalHumidity).FirstOrDefault() != null) { groupedMeasures.externalHumidityValue = m.ToList().Where(i => i.sensorId == (int)SensorTypeEnum.externalHumidity).FirstOrDefault().value; } groupedMesuresList.Add(groupedMeasures); }); return(Json(groupedMesuresList, JsonRequestBehavior.AllowGet)); }
private void ShowControls() { Console.WriteLine("Checking for data"); bool hasMeasures = MeasureService.HasMeasures(); Button addPredictorButton = FindViewById <Button> (Resource.Id.AddPredictorButton); Button addOutcomeButton = FindViewById <Button> (Resource.Id.AddOutcomeButton); TextView addPredictorInfo = FindViewById <TextView> (Resource.Id.AddPredictorInfo); TextView addOutcomeInfo = FindViewById <TextView> (Resource.Id.AddOutcomeInfo); ViewStates showControls; if (hasMeasures) { _getStartedButton.Text = "Edit Measures"; showControls = ViewStates.Visible; } else { _getStartedButton.Text = "Welcome! Get Started"; showControls = ViewStates.Gone; } addPredictorButton.Visibility = showControls; addOutcomeButton.Visibility = showControls; addPredictorInfo.Visibility = showControls; addOutcomeInfo.Visibility = showControls; }
public ActionResult ORPMeasure_Read([DataSourceRequest] DataSourceRequest request, int id) { var db = new ApplicationDbContext(); var measureService = new MeasureService(db); return(Json(measureService.Read(SensorTypeEnum.orp, id), JsonRequestBehavior.AllowGet)); }
public ActionResult Index() { ViewBag.Title = "Interactive Map Page"; var db = new ApplicationDbContext(); var measureService = new MeasureService(db); var listMarker = new List <Marker>(); db.ProductionUnits.Include(p => p.owner).ToList().ForEach(p => listMarker.Add(new Marker(p.locationLatitude, p.locationLongitude, String.Format("{0} </br> start since {1}", p.info, p.startDate.ToShortDateString())) { shape = "redMarker" })); var map = new Models.Map() { Name = "map", CenterLatitude = 46.094602, CenterLongitude = 10.998050, Zoom = 4, TileUrlTemplate = "http://#= subdomain #.tile.openstreetmap.org/#= zoom #/#= x #/#= y #.png", TileSubdomains = new string[] { "a", "b", "c" }, TileAttribution = "© <a href='http://osm.org/copyright'>OpenStreetMap contributors</a>", Markers = listMarker }; return(View(map)); }
public ActionResult WaterTempMeasure_Read([DataSourceRequest] DataSourceRequest request, int id, string range) { var db = new ApplicationDbContext(); var measureService = new MeasureService(db); var waterTemperature = measureService.Read(SensorTypeEnum.waterTemperature, id, range).ToList(); var filteredResult = FilterArrayForGraph(waterTemperature); if (db.ProductionUnitOwners.FirstOrDefault(o => o.user.UserName == this.User.Identity.Name).hasFahrenheitSetting == true) { filteredResult.ForEach(result => { result.value = Math.Round(result.value * 9 / 5, 1) + 32; }); } var json = new List <List <object> >(); foreach (var waterTempMeasure in filteredResult) { var list = new List <object>(); list.Add(waterTempMeasure.captureDate.ToString("R")); list.Add(waterTempMeasure.value); json.Add(list); } return(Json(json, JsonRequestBehavior.AllowGet)); }
/// <summary> /// Use this to perform whatever action is needed when committed /// </summary> /// <returns></returns> protected override Task <bool> OnCommitted() { //todo: crappy code alert. refactor try { if (TopicCategory != null) { Debug.Assert(MeasureService != null); //todo: add loging //todo: who is working on exception handling architecture //todo we need this (error handling procedure) documented MeasureService.SaveOrUpdateTopic(TopicCategory); _oldTopicCategoryName = TopicCategory.Name; } if (Entity != null) { MeasureService.SaveOrUpdateTopic(Entity.Owner); _oldSubtopicName = Entity.Name; } Events.GetEvent <TopicsUpdatedEvent>().Publish(1); return(Task.FromResult(true)); } catch (Exception ex) { Events.GetEvent <ErrorNotificationEvent>().Publish(ex); return(Task.FromResult(false)); } finally { Reset(false); // => invoke reset as non cancel action } }
public static OpenProductionUnitsStatsViewModel GetNetworkStatisticsAndIncidents(ApplicationDbContext db) { MeasureService measureService = new MeasureService(db); var productionUnits = db.ProductionUnits; var productionUnitNumber = 0; var totalMonthlyIncident = 0; var totalAnnuallyIncident = 0; productionUnitNumber = productionUnits.Where(p => p.productionUnitStatus.Id != 5).Count(); var lastMonth = DateTime.Now.AddMonths(-1); var lastYear = DateTime.Now.AddMonths(-1); totalMonthlyIncident = db.Events.Where(e => e.eventType.Id == 2 && e.date > lastMonth && e.createdBy != "Myfood Bot").Count(); totalAnnuallyIncident = db.Events.Where(e => e.eventType.Id == 2 && e.date > lastYear && e.createdBy != "Myfood Bot").Count(); return(new OpenProductionUnitsStatsViewModel() { productionUnitNumber = productionUnitNumber, totalMonthlyIncident = totalMonthlyIncident, totalAnnuallyIncident = totalAnnuallyIncident }); }
public ActionResult DissolvedOxyMeasure_Read([DataSourceRequest] DataSourceRequest request, int id, string range) { var db = new ApplicationDbContext(); var measureService = new MeasureService(db); return(Json(measureService.Read(SensorTypeEnum.dissolvedOxygen, id, range), JsonRequestBehavior.AllowGet)); }
public CamWindowViewModel(CamWindow camWindowView) { this.camWindowView = camWindowView; camService = new CamService(camWindowView); measureService = new MeasureService(camService); configService = MainWindow.ServiceContainer.Resolve <ConfigService>(); logger = MainWindow.ServiceContainer.Resolve <Logger>(); }
public ActionResult HydroponicTypes_Read([DataSourceRequest] DataSourceRequest request) { ApplicationDbContext db = new ApplicationDbContext(); MeasureService measureService = new MeasureService(db); var rslt = db.HydroponicTypes; return(Json(rslt, JsonRequestBehavior.AllowGet)); }
// GET: Measures public async Task <ActionResult> Index() { PopulateSensorsTypes(); PopulateProductionUnit(); var db = new ApplicationDbContext(); var measureService = new MeasureService(db); return(View(await db.Measures.ToListAsync())); }
/// <summary> /// Gets MeasureService /// </summary> public MeasureService GetMeasureService() { if (measureService == null) { measureService = new MeasureService(); measureService.ResourcePath = ResourcePath.MEASURE_RESOURCE_PATH; configureService(measureService); } return(measureService); }
public ActionResult GetClusterMapData() { var db = new ApplicationDbContext(); var measureService = new MeasureService(db); var listMarker = new List <Marker>(); db.ProductionUnits.Include(p => p.owner.preferedMoment).ToList().ForEach(p => { var phone = p.owner.phoneNumber == null ? "00 33 3 67 37 00 56" : p.owner.phoneNumber; var contactMail = p.owner.contactMail == null ? "*****@*****.**" : p.owner.contactMail; listMarker.Add(new Marker(p.locationLatitude, p.locationLongitude, String.Format(@"Click for view details")) { shape = "redMarker" }); }); var map = new Models.ClusterMap() { Name = "map", CenterLatitude = 44.0235561, CenterLongitude = 0.3640063, Zoom = 4, TileUrlTemplate = "http://#= subdomain #.tile.openstreetmap.org/#= zoom #/#= x #/#= y #.png", TileSubdomains = new string[] { "a", "b", "c" }, TileAttribution = "© <a href='http://osm.org/copyright'>OpenStreetMap contributors</a>" }; var result = new GeoClusterMapData { type = "FeatureCollection" }; var list = new List <GeoFeature>(); foreach (var marker in listMarker) { var feature = new GeoFeature { type = "Feature" }; feature.properties = new GeoProperties { scalerank = 2, name = marker.name, long_x = marker.latlng[0], lat_y = marker.latlng[1] }; feature.geometry = new Geometry { type = "Point", coordinates = new double[] { marker.latlng[1], marker.latlng[0] } }; list.Add(feature); } result.features = list.ToArray(); map.ClusterData = result; var data = new JavaScriptSerializer().Serialize(map); return(Json(new { data }, JsonRequestBehavior.AllowGet)); }
public void Init() { _cacheMock = new Mock <ICacheBase>(); _mdRepositoryMock = new Mock <IRepository <MeasureDimension> >(); _mwRepositoryMock = new Mock <IRepository <MeasureWeight> >(); _muRepositoryMock = new Mock <IRepository <MeasureUnit> >(); _settings = new MeasureSettings(); _mediatorMock = new Mock <IMediator>(); _measureService = new MeasureService(_cacheMock.Object, _mdRepositoryMock.Object, _mwRepositoryMock.Object, _muRepositoryMock.Object, _settings, _mediatorMock.Object); }
public IHttpActionResult EditMeasure(Measure measure) { var measureService = new MeasureService(); var editMeasure = measureService.EditMeasure(measure); var result = new { Count = editMeasure?"编辑成功":"编辑失败" }; return(Json(result)); }
/// <summary> /// 条件查询 /// </summary> /// <param name="byName"></param> /// <returns></returns> public IHttpActionResult GetList(string byName) { var masureService = new MeasureService(); var mesureList = masureService.GetMeasureList(byName); var result = new { list = mesureList }; return(Json(result)); }
public IHttpActionResult DeleteMeasure(int ID) { var measureService = new MeasureService(); var delMeasure = measureService.DeleteMeasure(ID); var result = new { Count = delMeasure?"删除成功":"删除失败" }; return(Json(result)); }
/// <summary> /// Use this to perform whatever action is needed when committed /// </summary> /// <returns></returns> protected async override Task <bool> OnCommitted() { ReconcileTopicsBeforeSave(); Measure.IsLibEdit = true; var errorOccurred = false; var progressService = new ProgressService(); progressService.SetProgress("Saving measure", 0, false, true); // await Task.Delay(500); var operationComplete = await progressService.Execute(() => { MeasureService.SaveMeasure(Measure, (o, e) => { if (e != null) { progressService.SetProgress("Failed", 100, true, false); throw e; } }); }, opResult => { if (!opResult.Status || opResult.Exception != null) { SynchronizationContext.Current.Post(x => { errorOccurred = true; var ex = opResult.Exception; Events.GetEvent <ErrorNotificationEvent>().Publish(ex); }, null); } progressService.SetProgress("Completed", 100, true, false); }, new CancellationToken()); if (operationComplete && !errorOccurred) { Events.GetEvent <TopicsUpdatedEvent>().Publish(Measure.Id); var msg = string.Format("Measure \"{0}\" was successfully save and/or updated.", ClinicalTitle); Events.GetEvent <GenericNotificationEvent>().Publish(msg); Reset(); return(true); } if (errorOccurred) { return(false); } return(true); }
public ActionResult Editing_Read([DataSourceRequest] DataSourceRequest request) { var db = new ApplicationDbContext(); var measureService = new MeasureService(db); JsonResult result = Json(measureService.Read().ToDataSourceResult(request), JsonRequestBehavior.AllowGet); result.MaxJsonLength = Int32.MaxValue; return(result); }
private void UserInit() { this.TypeCombobox.SelectionChanged += OnTypeSelected; this.TypeCombobox.ItemsSource = new WriteOffFieldValueType[] { WriteOffFieldValueType.LEFT_SIDE, WriteOffFieldValueType.RIGHT_SIDE, WriteOffFieldValueType.CUSTOM }; this.TypeCombobox.SelectedItem = WriteOffFieldValueType.LEFT_SIDE; MeasureService service = ApplicationManager.Instance.ControllerFactory.ServiceFactory.GetMeasureService(); this.MeasureCombobox.ItemsSource = service.getAllLeafts(); }
public ActionResult Option_Read([DataSourceRequest] DataSourceRequest request, int id) { ApplicationDbContext db = new ApplicationDbContext(); MeasureService measureService = new MeasureService(db); var rslt = db.OptionLists.Include(o => o.productionUnit) .Include(o => o.option) .Where(p => p.productionUnit.Id == id) .Select(p => p.option); return(Json(rslt.ToDataSourceResult(request))); }
/// <inheritdoc /> public override void HandleAddMeasure(AddMeasureIntent intent, Action <AddMeasureIntentResponse> completion) { try { if (intent == null) { completion(new AddMeasureIntentResponse(AddMeasureIntentResponseCode.Failure, null)); return; } var level = intent.Level; var shortInsulin = intent.Shortinsulin; var breadUnits = intent.Breadunits; var hasLevel = level.DoubleValue > 0; var hasShortInsulin = shortInsulin.Int32Value > 0; var hasBreadUnits = breadUnits.DoubleValue > 0; var hasSomeValues = hasLevel || hasBreadUnits || hasShortInsulin; if (!hasSomeValues) { completion(new AddMeasureIntentResponse(AddMeasureIntentResponseCode.Failure, null)); return; } var measureService = new MeasureService(new SharedDatabaseConnectionStringHolder()); var measure = new Measure { Date = DateTime.UtcNow, Level = hasLevel ? (int?)(level.DoubleValue * 10) : null, LongInsulin = 0, ShortInsulin = shortInsulin.Int32Value }; measureService.AddAsync(measure).GetAwaiter().GetResult(); completion(new AddMeasureIntentResponse(AddMeasureIntentResponseCode.Success, null)); } catch (Exception e) { var logger = Mvx.IoCProvider .Resolve <IMvxLogProvider>() .GetLogFor <AddMeasureIntentHandler>(); logger.ErrorException("While handling add measure intent", e); completion(new AddMeasureIntentResponse(AddMeasureIntentResponseCode.Failure, null)); } }
public ActionResult GetClusterMapData() { var db = new ApplicationDbContext(); var measureService = new MeasureService(db); var listMarker = new List <Marker>(); db.ProductionUnits.ToList().ForEach(p => listMarker.Add(new Marker(p.locationLatitude, p.locationLongitude, String.Format("{0} </br> start since {1}", p.info, p.startDate.ToShortDateString())) { shape = "redMarker" })); var map = new Models.ClusterMap() { Name = "map", CenterLatitude = 44.0235561, CenterLongitude = -10.3640063, Zoom = 4, TileUrlTemplate = "http://#= subdomain #.tile.openstreetmap.org/#= zoom #/#= x #/#= y #.png", TileSubdomains = new string[] { "a", "b", "c" }, TileAttribution = "© <a href='http://osm.org/copyright'>OpenStreetMap contributors</a>" }; var result = new GeoClusterMapData { type = "FeatureCollection" }; var list = new List <GeoFeature>(); foreach (var marker in listMarker) { var feature = new GeoFeature { type = "Feature" }; feature.properties = new GeoProperties { scalerank = 2, name = marker.name, long_x = marker.latlng[0], lat_y = marker.latlng[1] }; feature.geometry = new Geometry { type = "Point", coordinates = new double[] { marker.latlng[1], marker.latlng[0] } }; list.Add(feature); } result.features = list.ToArray(); map.ClusterData = result; var data = new JavaScriptSerializer().Serialize(map); return(Json(new { data }, JsonRequestBehavior.AllowGet)); }
public ActionResult Editing_Destroy([DataSourceRequest] DataSourceRequest request, [Bind(Prefix = "models")] IEnumerable <MeasureViewModel> measures) { var db = new ApplicationDbContext(); var measureService = new MeasureService(db); if (measures.Any()) { foreach (var measure in measures) { measureService.Destroy(measure); } } return(Json(measures.ToDataSourceResult(request, ModelState))); }
public ActionResult Editing_Update([DataSourceRequest] DataSourceRequest request, [Bind(Prefix = "models")] IEnumerable <MeasureViewModel> messages) { var db = new ApplicationDbContext(); var measureService = new MeasureService(db); if (messages != null && ModelState.IsValid) { foreach (var measure in messages) { measureService.Update(measure); } } return(Json(messages.ToDataSourceResult(request, ModelState))); }
public ActionResult TempMeasure_Read([DataSourceRequest] DataSourceRequest request, int id, string range) { var db = new ApplicationDbContext(); var measureService = new MeasureService(db); var airTemperature = measureService.Read(SensorTypeEnum.airTemperature, id, range).ToList(); var filteredResult = FilterArrayForGraph(airTemperature); var air = new List <List <object> >(); var hasFahrenheitSetting = db.ProductionUnitOwners.FirstOrDefault(o => o.user.UserName == this.User.Identity.Name).hasFahrenheitSetting; foreach (var airtemp in filteredResult) { airtemp.value = hasFahrenheitSetting == true?Math.Round(airtemp.value * 9 / 5, 1) + 32 : airtemp.value; var list = new List <object>(); list.Add(airtemp.captureDate.ToString("R")); list.Add(airtemp.value); air.Add(list); } var airExternalTemperature = measureService.Read(SensorTypeEnum.externalAirTemperature, id, range).ToList(); var airExternalTemperatureFiltered = FilterArrayForGraph(airExternalTemperature); var externalAir = new List <List <object> >(); foreach (var externalAirTemperature in airExternalTemperatureFiltered) { externalAirTemperature.value = hasFahrenheitSetting == true?Math.Round(externalAirTemperature.value * 9 / 5, 1) + 32 : externalAirTemperature.value; var list = new List <object>(); list.Add(externalAirTemperature.captureDate.ToString("R")); list.Add(externalAirTemperature.value); externalAir.Add(list); } var obj = new object(); obj = new { air = air, externalAir = externalAir, }; return(Json(obj, JsonRequestBehavior.AllowGet)); }
//todo move out hard refernece of the service //crappy code alert /// <summary> /// Rollbacks this measure. /// </summary> public void Rollback() { if (MeasureService == null) { MeasureService = ServiceLocator.Current.GetInstance <IMeasureServiceSync>(); } // var service = ServiceLocator.Current.GetInstance<IMeasureServiceSync>(); var updatedMeasure = MeasureService.Refresh(Measure); //.GetById<Measure>(Measure.Id); //bug possible MEF might create multiple versions /ensure only one import is create or better fix the architecture var parentViewModel = ServiceLocator.Current.GetInstance <MeasureDetailsViewModel>(); //todo: null reference exception FIX this InitMeasure(updatedMeasure); parentViewModel.UpdateCurrentMeasure(this); }