public void GivenIsoSpatialRowAndMeterWhenMapThenSpatialRecordContainsMeterValue() { var spatialValue = new SpatialValue { Id = 0, Value = 12.3 }; _isoSpatialRow.SpatialValues = new List <SpatialValue> { spatialValue }; _isoSpatialRows.Add(_isoSpatialRow); WorkingData meter = new NumericWorkingData { Representation = RepresentationInstanceList.vrAvgHarvestMoisture.ToModelRepresentation(), DeviceElementUseId = 1, UnitOfMeasure = UnitSystemManager.GetUnitOfMeasure("prcnt") }; var uniqueId = new UniqueId { IdType = IdTypeEnum.String, Id = "DLV0", Source = UniqueIdMapper.IsoSource }; meter.Id.UniqueIds.Add(uniqueId); _meters.Add(meter); var result = Map(); var meterValue = result.First().GetMeterValue(meter) as NumericRepresentationValue; Assert.AreEqual(12.3, meterValue.Value.Value); }
private static IEnumerable <WorkingData> GetWorkingDatas() { return(new List <WorkingData> { new NumericWorkingData { Representation = RepresentationInstanceList.vrHarvestMoisture.ToModelRepresentation(), UnitOfMeasure = UnitSystemManager.GetUnitOfMeasure("prcnt"), Values = new List <double> { 0 } }, new NumericWorkingData { Representation = RepresentationInstanceList.vrYieldMass.ToModelRepresentation(), UnitOfMeasure = UnitSystemManager.GetUnitOfMeasure("kg"), Values = new List <double> { 123 } }, new NumericWorkingData { Representation = RepresentationInstanceList.vrEngineSpeed.ToModelRepresentation(), UnitOfMeasure = UnitSystemManager.GetUnitOfMeasure("RPM"), Values = new List <double> { 453 } } }); }
public void Setup() { _interpolator = new RepresentationValueInterpolator(); _numericMeter = new NumericWorkingData { Representation = RepresentationInstanceList.vrAvgHarvestMoisture.ToModelRepresentation(), DeviceElementUseId = 1, UnitOfMeasure = UnitSystemManager.GetUnitOfMeasure("prcnt") }; _enumeratedMeter = new ISOEnumeratedMeter { Representation = RepresentationInstanceList.dtSectionControlMasterState.ToModelRepresentation(), ValueCodes = new List <int> { 1, 2, 3 }, DeviceElementUseId = 1, GetEnumeratedValue = (sv, im) => new EnumeratedValue { Value = new AgGateway.ADAPT.ApplicationDataModel.Representations.EnumerationMember { Code = 3 } } }; }
public void GivenIsoUomLookupThenAdaptUomMillimetersIsMapped() { var uom = UnitSystemManager.GetUnitOfMeasure("mm"); var isoMapping = IsoUnitOfMeasureList.Mappings.Single(x => x.Unit == "mm"); Assert.AreEqual(uom.Code, isoMapping.AdaptCode); }
public void Setup() { _dataPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); Directory.CreateDirectory(_dataPath); _fileName = "test.bin"; _meters = new List <WorkingData>(); _spatialRecord = new SpatialRecord { Geometry = new Point { X = 93.6208, Y = 41.5908 } }; _spatialRecords = new List <SpatialRecord> { _spatialRecord }; _numericMeter = new NumericWorkingData { Representation = RepresentationInstanceList.vrAvgHarvestMoisture.ToModelRepresentation(), UnitOfMeasure = UnitSystemManager.GetUnitOfMeasure("prcnt"), DeviceElementUseId = 1 }; _enumeratedMeter = new ISOEnumeratedMeter { Representation = RepresentationInstanceList.dtSkyCondition.ToModelRepresentation(), DeviceElementUseId = 1, ValueCodes = new List <int> { 0, 1, 2 } }; _numericValueMapperMock = new Mock <INumericValueMapper>(); _enumeratedMeterMapperMock = new Mock <IEnumeratedValueMapper>(); _binaryWriter = new BinaryWriter(_enumeratedMeterMapperMock.Object, _numericValueMapperMock.Object); }
public void GivenAdaptUomWhenGetIsoMappingThenIsoUomExists() { var uom = UnitSystemManager.GetUnitOfMeasure("l1ha-1"); var isoUom = IsoUnitOfMeasureList.Mappings.SingleOrDefault(x => x.AdaptCode == "l1ha-1"); Assert.IsNotNull(uom); Assert.IsNotNull(isoUom); Assert.AreEqual("l/ha", isoUom.Unit.ToLower()); }
public void GivenIsoUomLookupThenAdaptUomKgHaIsMapped() { var uom = UnitSystemManager.GetUnitOfMeasure("kg1ha-1"); var isoUom = IsoUnitOfMeasureList.Mappings.SingleOrDefault(x => x.AdaptCode == "kg1ha-1"); Assert.IsNotNull(uom); Assert.IsNotNull(isoUom); Assert.AreEqual("kg/ha", isoUom.Unit.ToLower()); }
private NumericWorkingData CreateProductIndexWorkingData(int deviceElementUseId) { var meter = new NumericWorkingData { UnitOfMeasure = UnitSystemManager.GetUnitOfMeasure("count"), DeviceElementUseId = deviceElementUseId, Representation = RepresentationMapper.GetRepresentation("vrProductIndex") }; return(meter); }
public static AgGateway.ADAPT.ApplicationDataModel.Common.UnitOfMeasure GetModelUom(string unit) { AgGateway.ADAPT.ApplicationDataModel.Common.UnitOfMeasure uom = UnitSystemManager.GetUnitOfMeasure(unit); if (uom == null) { UnitOfMeasure incompatibleUnit = new CompositeUnitOfMeasure(unit); uom = incompatibleUnit.ToModelUom(); } return(uom); }
private NumericWorkingData AddWorkingData(NumericRepresentation representation, string uom, double value) { var numericWorkingData = new NumericWorkingData { Representation = representation.ToModelRepresentation(), UnitOfMeasure = UnitSystemManager.GetUnitOfMeasure(uom), Values = new List <double> { value } }; _workingData.Add(numericWorkingData); return(numericWorkingData); }
private static NumericRepresentationValue GetShiftValue(string inputValue) { long shift; if (!inputValue.ParseValue(out shift)) { return(null); } var shiftUnitOfMeasure = UnitSystemManager.GetUnitOfMeasure("mm"); var numericValue = new NumericValue(shiftUnitOfMeasure, shift); return(new NumericRepresentationValue(null, numericValue.UnitOfMeasure, numericValue)); }
public UnitOfMeasure GetUnitForDdi(int ddi) { if (!_ddis.ContainsKey(ddi)) { return(null); } var matchingDdi = _ddis[ddi]; if (matchingDdi != null) { var uom = IsoUnitOfMeasureList.Mappings.Single(x => x.Unit == matchingDdi.Unit); return(UnitSystemManager.GetUnitOfMeasure(uom.AdaptCode)); } return(null); }
public void GivenTimHeaderWithDlvWhenMapThenUnitOfMeasureIsMapped() { var dlv = new DLV { A = "1" }; _tim.Items = new List <DLV> { dlv }.ToArray(); _representationMapperMock.Setup(r => r.GetUnitForDdi(1)).Returns(UnitSystemManager.GetUnitOfMeasure("m")); var result = (NumericWorkingData)MapSingle(); Assert.AreEqual("m", result.UnitOfMeasure.Code); }
public void GivenIsoSpatialRowsWithoutNumericMeterOnSecondWhenMapThenSecondValueIsInterpolator() { var spatialValue = new SpatialValue { Id = 0, Value = 12.3 }; _isoSpatialRow.SpatialValues = new List <SpatialValue> { spatialValue }; var isoSpatialRow2 = new ISOSpatialRow { SpatialValues = new List <SpatialValue>() }; _isoSpatialRows = new List <ISOSpatialRow> { _isoSpatialRow, isoSpatialRow2 }; var meter = new NumericWorkingData { Representation = RepresentationInstanceList.vrAvgHarvestMoisture.ToModelRepresentation(), DeviceElementUseId = 1, UnitOfMeasure = UnitSystemManager.GetUnitOfMeasure("prcnt") }; var uniqueId = new UniqueId { IdType = IdTypeEnum.String, Id = "DLV0" }; meter.Id.UniqueIds.Add(uniqueId); _meters.Add(meter); var numericRepresentation = new NumericRepresentationValue(meter.Representation as NumericRepresentation, meter.UnitOfMeasure, new NumericValue(meter.UnitOfMeasure, 2.3)); _spatialValueInterpolator.Setup(s => s.Interpolate(meter)).Returns(numericRepresentation); var result = Map().ToList(); Assert.AreEqual(numericRepresentation, result[1].GetMeterValue(meter) as NumericRepresentationValue); }
private static NumericRepresentationValue GetAccuracy(decimal?accuracyValue) { if (!accuracyValue.HasValue || accuracyValue < 0m || accuracyValue > 65m) { return(null); } double accuracy = Convert.ToDouble(accuracyValue.Value); var accuracyUnitOfMeasure = UnitSystemManager.GetUnitOfMeasure("m"); var numericValue = new NumericValue(accuracyUnitOfMeasure, accuracy); var numericRepresentation = new NumericRepresentation { DecimalDigits = 1, MaxValue = new NumericValue(accuracyUnitOfMeasure, 65), MinValue = new NumericValue(accuracyUnitOfMeasure, 0), }; return(new NumericRepresentationValue(numericRepresentation, numericValue.UnitOfMeasure, numericValue)); }
private static NumericRepresentationValue GetAccuracy(string accuracyValue) { double accuracy; if (accuracyValue.ParseValue(out accuracy) == false || accuracy < 0 || accuracy > 65) { return(null); } var accuracyUnitOfMeasure = UnitSystemManager.GetUnitOfMeasure("m"); var numericValue = new NumericValue(accuracyUnitOfMeasure, accuracy); var numericRepresentation = new NumericRepresentation { DecimalDigits = 1, MaxValue = new NumericValue(accuracyUnitOfMeasure, 65), MinValue = new NumericValue(accuracyUnitOfMeasure, 0), }; return(new NumericRepresentationValue(numericRepresentation, numericValue.UnitOfMeasure, numericValue)); }
public void GivenIsoSpatialRowWithoutMeterWhenMapThenInterpolatorIsCalled() { var spatialValue = new SpatialValue { Id = 0, Value = 12.3 }; _isoSpatialRow.SpatialValues = new List <SpatialValue> { spatialValue }; var isoSpatialRow2 = new ISOSpatialRow { SpatialValues = new List <SpatialValue>() }; _isoSpatialRows = new List <ISOSpatialRow> { _isoSpatialRow, isoSpatialRow2 }; var meter = new NumericWorkingData { Representation = RepresentationInstanceList.vrAvgHarvestMoisture.ToModelRepresentation(), DeviceElementUseId = 1, UnitOfMeasure = UnitSystemManager.GetUnitOfMeasure("prcnt") }; var uniqueId = new UniqueId { IdType = IdTypeEnum.String, Id = "DLV0" }; meter.Id.UniqueIds.Add(uniqueId); _meters.Add(meter); Map().ToList(); _spatialValueInterpolator.Verify(s => s.Interpolate(It.IsAny <WorkingData>())); }
public void GivenOperationDataFileWhenReadSpatialRecordsThenSpatialRecordsAreReturned() { var meter = new NumericWorkingData(); _meters.Add(meter); var numericRepValue = new NumericRepresentationValue(RepresentationInstanceList.vrABLineHeading.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("m"), 21.2)); var spatialRecord1 = new SpatialRecord { Timestamp = DateTime.Now, Geometry = new Point { X = 45.123456, Y = -65.456789 } }; spatialRecord1.SetMeterValue(meter, numericRepValue); spatialRecord1.SetAppliedLatency(meter, 2); _spatialRecords.Add(spatialRecord1); var spatialRecord2 = new SpatialRecord { Timestamp = DateTime.Now, Geometry = new Point { X = 85.654875, Y = -65.3456212 } }; spatialRecord2.SetMeterValue(meter, numericRepValue); spatialRecord2.SetAppliedLatency(meter, 2); _spatialRecords.Add(spatialRecord2); var filePath = Path.Combine(_testCardPath, "OperationData-1.adm"); _protobufSerializer.WriteSpatialRecords(filePath, _spatialRecords); var spatialRecords = _protobufSerializer.ReadSpatialRecords(filePath).ToList(); Assert.AreEqual(spatialRecord1.Timestamp, spatialRecords[0].Timestamp); Assert.AreEqual(spatialRecord1.Geometry.Id, spatialRecords[0].Geometry.Id); Assert.AreEqual(numericRepValue.Value.Value, ((NumericRepresentationValue)spatialRecords[0].GetMeterValue(meter)).Value.Value); Assert.AreEqual(numericRepValue.Representation.Code, ((NumericRepresentationValue)spatialRecords[0].GetMeterValue(meter)).Representation.Code); Assert.AreEqual(numericRepValue.Value.UnitOfMeasure.Code, ((NumericRepresentationValue)spatialRecords[0].GetMeterValue(meter)).Value.UnitOfMeasure.Code); Assert.AreEqual(spatialRecord2.Timestamp, spatialRecords[1].Timestamp); Assert.AreEqual(spatialRecord2.Geometry.Id, spatialRecords[1].Geometry.Id); Assert.AreEqual(numericRepValue.Value.Value, ((NumericRepresentationValue)spatialRecords[1].GetMeterValue(meter)).Value.Value); Assert.AreEqual(numericRepValue.Representation.Code, ((NumericRepresentationValue)spatialRecords[1].GetMeterValue(meter)).Representation.Code); Assert.AreEqual(numericRepValue.Value.UnitOfMeasure.Code, ((NumericRepresentationValue)spatialRecords[1].GetMeterValue(meter)).Value.UnitOfMeasure.Code); }
public void GivenNumericRepresentationValueOfRateTypeWhenInterpolateThenRepresentationValueIsSameAsPrevious() { var previousRepresentationValue = new NumericRepresentationValue(RepresentationInstanceList.vrYieldMass.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("m2"), 1.0)); _interpolator.SetMostRecentMeterValue(_numericMeter, previousRepresentationValue); var result = _interpolator.Interpolate(_numericMeter); var numericRepresentationValue = result as NumericRepresentationValue; Assert.AreEqual(previousRepresentationValue.Value.Value, numericRepresentationValue.Value.Value); }
private IEnumerable <WorkingData> Map(ISODataLogValue dlv, IEnumerable <ISOSpatialRow> isoSpatialRows, DeviceElementUse deviceElementUse, int order, List <DeviceElementUse> pendingDeviceElementUses, DeviceElementHierarchy isoDeviceElementHierarchy) { var workingDatas = new List <WorkingData>(); if (_ddis.ContainsKey(dlv.ProcessDataDDI.AsInt32DDI())) { //Numeric Representations NumericWorkingData numericMeter = MapNumericMeter(dlv, deviceElementUse.Id.ReferenceId); DataLogValuesByWorkingDataID.Add(numericMeter.Id.ReferenceId, dlv); ISODeviceElementIDsByWorkingDataID.Add(numericMeter.Id.ReferenceId, dlv.DeviceElementIdRef); workingDatas.Add(numericMeter); return(workingDatas); } var meterCreator = _enumeratedMeterCreatorFactory.GetMeterCreator(dlv.ProcessDataDDI.AsInt32DDI()); if (meterCreator != null) { //Enumerated Representations var isoEnumeratedMeters = meterCreator.CreateMeters(isoSpatialRows, dlv); foreach (ISOEnumeratedMeter enumeratedMeter in isoEnumeratedMeters) { DataLogValuesByWorkingDataID.Add(enumeratedMeter.Id.ReferenceId, dlv); ISODeviceElementIDsByWorkingDataID.Add(enumeratedMeter.Id.ReferenceId, dlv.DeviceElementIdRef); enumeratedMeter.DeviceElementUseId = deviceElementUse.Id.ReferenceId; } workingDatas.AddRange(isoEnumeratedMeters); if (meterCreator is CondensedStateMeterCreator) { UpdateCondensedWorkingDatas(workingDatas, dlv, deviceElementUse, pendingDeviceElementUses, isoDeviceElementHierarchy); } } else { //Proprietary DDIs - report out as numeric value NumericWorkingData proprietaryWorkingData = new NumericWorkingData(); proprietaryWorkingData.Representation = new ApplicationDataModel.Representations.NumericRepresentation { Code = dlv.ProcessDataDDI, CodeSource = RepresentationCodeSourceEnum.ISO11783_DDI }; proprietaryWorkingData.DeviceElementUseId = deviceElementUse.Id.ReferenceId; //Always set unit as count. In SpatialRecordMapper, we will place the DVP unit on the NumericRepresentationValue.UserProvidedUnitOfMeasure //so that consumers can apply any offset/scaling to get to the desired display unit. proprietaryWorkingData.UnitOfMeasure = UnitSystemManager.GetUnitOfMeasure("count"); //Take any information from DPD ISODeviceElement det = isoDeviceElementHierarchy.DeviceElement; if (det != null) { ISODeviceProcessData dpd = det.DeviceProcessDatas.FirstOrDefault(d => d.DDI == dlv.ProcessDataDDI); if (dpd != null) { proprietaryWorkingData.Representation.Description = dpd.Designator; //Update the representation with a name since we have one here. } } DataLogValuesByWorkingDataID.Add(proprietaryWorkingData.Id.ReferenceId, dlv); ISODeviceElementIDsByWorkingDataID.Add(proprietaryWorkingData.Id.ReferenceId, dlv.DeviceElementIdRef); workingDatas.Add(proprietaryWorkingData); } return(workingDatas); }
public void GivenOperationDataWithSpatialRecordDataWithNumericRepValueWhenProcessOperationDAtaThenRowsAreAdded() { var harvestMoistureMeter = new NumericWorkingData { Representation = RepresentationInstanceList.vrHarvestMoisture.ToModelRepresentation() }; _workingDatas.Add(harvestMoistureMeter); _deviceElementUses.Add(0, new List <DeviceElementUse> { new DeviceElementUse { Depth = 0, GetWorkingDatas = () => _workingDatas, } }); var spatialRecord = new SpatialRecord(); var numericRepresentation = new NumericRepresentationValue(RepresentationInstanceList.vrHarvestMoisture.ToModelRepresentation(), UnitSystemManager.GetUnitOfMeasure("prcnt"), new NumericValue(UnitSystemManager.GetUnitOfMeasure("prcnt"), 3.0)); spatialRecord.SetMeterValue(harvestMoistureMeter, numericRepresentation); _spatialRecords.Add(spatialRecord); var dataTable = _operationDataProcessor.ProcessOperationData(_operationData, _spatialRecords); Assert.AreEqual(1, dataTable.Rows.Count); Assert.AreEqual(numericRepresentation.Value.Value.ToString(), dataTable.Rows[0][4]); }
private static NumericRepresentationValue CreateHarvestMoisture(double value) { return(new NumericRepresentationValue(RepresentationInstanceList.vrHarvestMoisture.ToModelRepresentation(), UnitSystemManager.GetUnitOfMeasure("prcnt"), new NumericValue(UnitSystemManager.GetUnitOfMeasure("prcnt"), value))); }
public void GivenOperationDataWithSpatialRecordDataWithNumericRepValueWhenProcessOperationDataThenColumnNamesContainUom() { var harvestMoistureMeter = new NumericWorkingData { Representation = RepresentationInstanceList.vrHarvestMoisture.ToModelRepresentation() }; _workingDatas.Add(harvestMoistureMeter); _deviceElementUses.Add(0, new List <DeviceElementUse> { new DeviceElementUse { Depth = 0, GetWorkingDatas = () => _workingDatas, } }); var spatialRecord = new SpatialRecord(); var numericRepresentation = new NumericRepresentationValue(RepresentationInstanceList.vrHarvestMoisture.ToModelRepresentation(), UnitSystemManager.GetUnitOfMeasure("prcnt"), new NumericValue(UnitSystemManager.GetUnitOfMeasure("prcnt"), 3.0)); spatialRecord.SetMeterValue(harvestMoistureMeter, numericRepresentation); _spatialRecords.Add(spatialRecord); var dataTable = _operationDataProcessor.ProcessOperationData(_operationData, _spatialRecords); var expectedColumnName = _workingDatas.First().Representation.Code + "-" + _workingDatas.First().Id.ReferenceId + "-0-" + numericRepresentation.Value.UnitOfMeasure.Code; Assert.AreEqual(expectedColumnName, dataTable.Columns[4].ColumnName); }
private IEnumerable <WorkingData> Map(ISODataLogValue dlv, IEnumerable <ISOSpatialRow> isoSpatialRows, DeviceElementUse deviceElementUse, int order, List <DeviceElementUse> pendingDeviceElementUses, DeviceElementHierarchy isoDeviceElementHierarchy) { var workingDatas = new List <WorkingData>(); if (_ddis.ContainsKey(dlv.ProcessDataDDI.AsInt32DDI())) { //Numeric Representations NumericWorkingData numericMeter = MapNumericMeter(dlv, deviceElementUse.Id.ReferenceId); DataLogValuesByWorkingDataID.Add(numericMeter.Id.ReferenceId, dlv); ISODeviceElementIDsByWorkingDataID.Add(numericMeter.Id.ReferenceId, dlv.DeviceElementIdRef); workingDatas.Add(numericMeter); return(workingDatas); } var meterCreator = _enumeratedMeterCreatorFactory.GetMeterCreator(dlv.ProcessDataDDI.AsInt32DDI()); if (meterCreator != null) { //Enumerated Representations var isoEnumeratedMeters = meterCreator.CreateMeters(isoSpatialRows); foreach (ISOEnumeratedMeter enumeratedMeter in isoEnumeratedMeters) { DataLogValuesByWorkingDataID.Add(enumeratedMeter.Id.ReferenceId, dlv); ISODeviceElementIDsByWorkingDataID.Add(enumeratedMeter.Id.ReferenceId, dlv.DeviceElementIdRef); enumeratedMeter.DeviceElementUseId = deviceElementUse.Id.ReferenceId; } workingDatas.AddRange(isoEnumeratedMeters); if (meterCreator is CondensedStateMeterCreator) { UpdateCondensedWorkingDatas(workingDatas, dlv, deviceElementUse, pendingDeviceElementUses, isoDeviceElementHierarchy); } } else { //Proprietary DDIs - report out as numeric value NumericWorkingData proprietaryWorkingData = new NumericWorkingData(); proprietaryWorkingData.Representation = new ApplicationDataModel.Representations.NumericRepresentation { Code = dlv.ProcessDataDDI, CodeSource = RepresentationCodeSourceEnum.ISO11783_DDI }; proprietaryWorkingData.DeviceElementUseId = deviceElementUse.Id.ReferenceId; //Take any information from DPDs/DVPs ApplicationDataModel.Common.UnitOfMeasure uom = null; ISODeviceElement det = isoDeviceElementHierarchy.DeviceElement; if (det != null) { ISODeviceProcessData dpd = det.DeviceProcessDatas.FirstOrDefault(d => d.DDI == dlv.ProcessDataDDI); if (dpd != null) { proprietaryWorkingData.Representation.Description = dpd.Designator; //Update the representation with a name since we have one here. ISODeviceValuePresentation dvp = det.Device.DeviceValuePresentations.FirstOrDefault(d => d.ObjectID == dpd.DeviceValuePresentationObjectId); if (dvp != null && dvp.UnitDesignator != null) { if (AgGateway.ADAPT.Representation.UnitSystem.InternalUnitSystemManager.Instance.UnitOfMeasures.Contains(dvp.UnitDesignator)) { //The unit designator used by the OEM will need to match ADAPT for this to work, otherwise we'll need to default to 'count' below //It will likely work for many simple units and will not for work compound units uom = UnitSystemManager.GetUnitOfMeasure(dvp.UnitDesignator); } } } } proprietaryWorkingData.UnitOfMeasure = uom ?? UnitSystemManager.GetUnitOfMeasure("count"); //Best we can do DataLogValuesByWorkingDataID.Add(proprietaryWorkingData.Id.ReferenceId, dlv); ISODeviceElementIDsByWorkingDataID.Add(proprietaryWorkingData.Id.ReferenceId, dlv.DeviceElementIdRef); workingDatas.Add(proprietaryWorkingData); } return(workingDatas); }
private static void LoadDefinition(GridDescriptor gridDescriptor, RasterGridPrescription prescription) { prescription.BoundingBox = new BoundingBox(); prescription.BoundingBox.MinY = new NumericRepresentationValue(RepresentationInstanceList.vrLatitude.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("arcdeg"), gridDescriptor.Origin.Y)); prescription.BoundingBox.MinX = new NumericRepresentationValue(RepresentationInstanceList.vrLongitude.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("arcdeg"), gridDescriptor.Origin.X)); var maxYValue = prescription.BoundingBox.MinY.Value.Value + gridDescriptor.CellHeight.Value.Value * gridDescriptor.RowCount; var maxXValue = prescription.BoundingBox.MinX.Value.Value + gridDescriptor.CellWidth.Value.Value * gridDescriptor.ColumnCount; prescription.BoundingBox.MaxY = new NumericRepresentationValue(RepresentationInstanceList.vrLatitude.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("arcdeg"), maxYValue)); prescription.BoundingBox.MaxX = new NumericRepresentationValue(RepresentationInstanceList.vrLongitude.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("arcdeg"), maxXValue)); prescription.Origin = gridDescriptor.Origin; prescription.CellHeight = gridDescriptor.CellHeight; prescription.CellWidth = gridDescriptor.CellWidth; prescription.ColumnCount = gridDescriptor.ColumnCount; prescription.RowCount = gridDescriptor.RowCount; }
public RasterGridPrescription Import(ISOTask task, WorkItem workItem) { RasterGridPrescription rasterPrescription = new RasterGridPrescription(); _prescriptionMapper.ImportSharedPrescriptionProperties(task, workItem, rasterPrescription); GridDescriptor gridDescriptor = LoadGridDescriptor(task, TaskDataPath); if (gridDescriptor != null) { rasterPrescription.BoundingBox = new BoundingBox(); rasterPrescription.BoundingBox.MinY = new NumericRepresentationValue(RepresentationInstanceList.vrLatitude.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("arcdeg"), gridDescriptor.Origin.Y)); rasterPrescription.BoundingBox.MinX = new NumericRepresentationValue(RepresentationInstanceList.vrLongitude.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("arcdeg"), gridDescriptor.Origin.X)); var maxYValue = rasterPrescription.BoundingBox.MinY.Value.Value + gridDescriptor.CellHeight.Value.Value * gridDescriptor.RowCount; var maxXValue = rasterPrescription.BoundingBox.MinX.Value.Value + gridDescriptor.CellWidth.Value.Value * gridDescriptor.ColumnCount; rasterPrescription.BoundingBox.MaxY = new NumericRepresentationValue(RepresentationInstanceList.vrLatitude.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("arcdeg"), maxYValue)); rasterPrescription.BoundingBox.MaxX = new NumericRepresentationValue(RepresentationInstanceList.vrLongitude.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("arcdeg"), maxXValue)); rasterPrescription.Origin = gridDescriptor.Origin; rasterPrescription.CellHeight = gridDescriptor.CellHeight; rasterPrescription.CellWidth = gridDescriptor.CellWidth; rasterPrescription.ColumnCount = gridDescriptor.ColumnCount; rasterPrescription.RowCount = gridDescriptor.RowCount; ImportRates(task, gridDescriptor, rasterPrescription); } return(rasterPrescription); }
static void Main(string[] args) { var testData = JArray.Parse(File.ReadAllText("data.json")); string applicationPath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location); var pluginFactory = new PluginFactory(applicationPath); var admPlugin = pluginFactory.GetPlugin("ADMPlugin"); admPlugin.Initialize(); ApplicationDataModel export = new ApplicationDataModel(); export.Catalog = new Catalog(); export.Documents = new Documents(); List <WorkRecord> workRecords = new List <WorkRecord>(); List <Summary> summaries = new List <Summary>(); // All of these records are for the same Grower/Farm/Field/CropZone/CropYear so I'm just // pulling the common info from the first record. #region Create a "crop year" TimeScope to tag each of the WorkRecords with. TimeScope cropYear = new TimeScope(); UniqueId ourId = new UniqueId(); ourId.Id = testData[0]["CropYear"].ToString(); ourId.IdType = IdTypeEnum.String; ourId.Source = "www.somecompany.com"; ourId.SourceType = IdSourceTypeEnum.URI; cropYear.Id.UniqueIds.Add(ourId); cropYear.Description = testData[0]["CropYear"].ToString(); cropYear.DateContext = DateContextEnum.CropSeason; export.Catalog.TimeScopes.Add(cropYear); #endregion #region Create the Grower/Farm/Field/CropZone objects for this group of applications Grower grower = new Grower(); ourId = new UniqueId(); ourId.Id = testData[0]["ApplicationId"]["DataSourceId"].ToString(); ourId.IdType = IdTypeEnum.UUID; ourId.Source = "www.somecompany.com"; ourId.SourceType = IdSourceTypeEnum.URI; grower.Id.UniqueIds.Add(ourId); grower.Name = testData[0]["GrowerName"].ToString(); export.Catalog.Growers.Add(grower); Farm farm = new Farm(); ourId = new UniqueId(); ourId.Id = testData[0]["FarmId"]["Id"].ToString(); ourId.IdType = IdTypeEnum.UUID; ourId.Source = "www.somecompany.com"; ourId.SourceType = IdSourceTypeEnum.URI; farm.Id.UniqueIds.Add(ourId); farm.Description = testData[0]["FarmName"].ToString(); farm.GrowerId = grower.Id.ReferenceId; export.Catalog.Farms.Add(farm); Field field = new Field(); ourId = new UniqueId(); ourId.Id = testData[0]["FieldId"].ToString(); ourId.IdType = IdTypeEnum.UUID; ourId.Source = "www.somecompany.com"; ourId.SourceType = IdSourceTypeEnum.URI; field.Id.UniqueIds.Add(ourId); field.Description = testData[0]["FieldName"].ToString(); field.FarmId = farm.Id.ReferenceId; export.Catalog.Fields.Add(field); Crop crop = new Crop(); ourId = new UniqueId(); ourId.Id = testData[0]["CropId"]["Id"].ToString(); ourId.IdType = IdTypeEnum.UUID; ourId.Source = "www.somecompany.com"; ourId.SourceType = IdSourceTypeEnum.URI; crop.Id.UniqueIds.Add(ourId); crop.Name = testData[0]["Crop"].ToString(); // Add EPPO code as ContextItem at some point in the future export.Catalog.Crops.Add(crop); CropZone cropZone = new CropZone(); ourId = new UniqueId(); ourId.Id = testData[0]["CropZoneId"].ToString(); ourId.IdType = IdTypeEnum.UUID; ourId.Source = "www.somecompany.com"; ourId.SourceType = IdSourceTypeEnum.URI; cropZone.Id.UniqueIds.Add(ourId); cropZone.Description = testData[0]["CropZoneName"].ToString(); cropZone.FieldId = field.Id.ReferenceId; cropZone.CropId = crop.Id.ReferenceId; cropZone.TimeScopes.Add(cropYear); string areaString = testData[0]["AreaApplied"].ToString(); double area = Convert.ToDouble(areaString); cropZone.Area = new NumericRepresentationValue(RepresentationInstanceList.vrReportedFieldArea.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("ac1"), area)); export.Catalog.CropZones.Add(cropZone); #endregion // Foreach Application var applicationIds = ((from c in testData select c["ApplicationId"]["Id"]).Distinct()).ToList(); foreach (var applicationId in applicationIds) { var appliedProducts = (from c in testData where (string)c["ApplicationId"]["Id"] == applicationId.ToString() select c).ToList(); // Create a WorkRecord and Summary (ADAPT's version of an Application) WorkRecord workRecord = new WorkRecord(); ourId = new UniqueId(); ourId.Id = appliedProducts[0]["ApplicationId"]["Id"].ToString(); ourId.IdType = IdTypeEnum.UUID; ourId.Source = "www.somecompany.com"; ourId.SourceType = IdSourceTypeEnum.URI; workRecord.Id.UniqueIds.Add(ourId); workRecord.Description = appliedProducts[0]["ApplicationName"].ToString(); workRecord.TimeScopes.Add(cropYear); TimeScope timingEvent = new TimeScope(); timingEvent.DateContext = DateContextEnum.TimingEvent; timingEvent.Description = appliedProducts[0]["TimingEvent"].ToString(); workRecord.TimeScopes.Add(timingEvent); TimeScope startDate = new TimeScope(); startDate.DateContext = DateContextEnum.ActualStart; startDate.TimeStamp1 = DateTime.Parse(appliedProducts[0]["StartDate"].ToString()); workRecord.TimeScopes.Add(startDate); TimeScope endDate = new TimeScope(); endDate.DateContext = DateContextEnum.ActualEnd; endDate.TimeStamp1 = DateTime.Parse(appliedProducts[0]["EndDate"].ToString()); workRecord.TimeScopes.Add(endDate); Summary summary = new Summary(); // This property linking the Summary to its parent WorkRecord doesn't exist in ADAPT 1.1.0.8. // Slated to be added in next release. // summary.WorkRecordId = workRecord.Id.ReferenceId; // This property linking the Summary to its Grower doesn't exist in ADAPT 1.1.0.8. // Slated to be added in next release. // summary.GrowerId = grower.Id.ReferenceId; summary.FarmId = farm.Id.ReferenceId; summary.FieldId = field.Id.ReferenceId; summary.CropZoneId = cropZone.Id.ReferenceId; // Foreach Product foreach (var appliedProduct in appliedProducts) { //Note that Manufacturer is not a required property for a given product. Manufacturer manufacturer = null; var manufacturers = export.Catalog.Manufacturers.Where(x => (x.Description == appliedProduct["Manufacturer"].ToString())).ToList(); if (manufacturers.Count > 0) { manufacturer = manufacturers[0]; } else { manufacturer = new Manufacturer(); ourId = new UniqueId(); // Couldn't find Manufacturer id in your data ourId.Id = "00000000-0000-0000-0000-000000000000"; ourId.IdType = IdTypeEnum.UUID; ourId.Source = "www.somecompany.com"; ourId.SourceType = IdSourceTypeEnum.URI; manufacturer.Id.UniqueIds.Add(ourId); manufacturer.Description = appliedProduct["Manufacturer"].ToString(); export.Catalog.Manufacturers.Add(manufacturer); } // This is sub-optimal, but it is what we have to work with at the moment. // We're creating the use of each product as its own "operation" OperationSummary operation = new OperationSummary(); operation.Data = new List <StampedMeteredValues>(); if (appliedProduct["Type"].ToString() == "Seed") { #region Handle Seed CropVariety cropVariety = null; var products = export.Catalog.Products.Where(x => (x.Description == appliedProduct["Product"].ToString())).ToList(); if (products.Count > 0) { cropVariety = products[0] as CropVariety; } else { cropVariety = new CropVariety(); ourId = new UniqueId(); ourId.Id = appliedProduct["ProductId"]["Id"].ToString(); ourId.IdType = IdTypeEnum.UUID; ourId.Source = "www.somecompany.com"; ourId.SourceType = IdSourceTypeEnum.URI; cropVariety.Id.UniqueIds.Add(ourId); cropVariety.Description = appliedProduct["Product"].ToString(); cropVariety.CropId = crop.Id.ReferenceId; if (manufacturer != null) { cropVariety.ManufacturerId = manufacturer.Id.ReferenceId; } export.Catalog.Products.Add(cropVariety); } operation.ProductId = cropVariety.Id.ReferenceId; operation.OperationType = OperationTypeEnum.SowingAndPlanting; #endregion } else if (appliedProduct["Type"].ToString() == "CropProtection") { #region Handle CropProtection CropProtectionProduct cropProtection = null; var products = export.Catalog.Products.Where(x => (x.Description == appliedProduct["Product"].ToString())).ToList(); if (products.Count > 0) { cropProtection = products[0] as CropProtectionProduct; } else { cropProtection = new CropProtectionProduct(); ourId = new UniqueId(); ourId.Id = appliedProduct["ProductId"]["Id"].ToString(); ourId.IdType = IdTypeEnum.UUID; ourId.Source = "www.somecompany.com"; ourId.SourceType = IdSourceTypeEnum.URI; cropProtection.Id.UniqueIds.Add(ourId); cropProtection.Description = appliedProduct["Product"].ToString(); if (manufacturer != null) { cropProtection.ManufacturerId = manufacturer.Id.ReferenceId; } if (!string.IsNullOrEmpty(appliedProduct["RegNo"].ToString())) { ContextItem epaNumber = new ContextItem(); epaNumber.Code = "US-EPA-N"; epaNumber.Value = ConditionEPA(appliedProduct["RegNo"].ToString(), true, true); cropProtection.ContextItems.Add(epaNumber); } export.Catalog.Products.Add(cropProtection); } operation.ProductId = cropProtection.Id.ReferenceId; operation.OperationType = OperationTypeEnum.CropProtection; #endregion } else if (appliedProduct["Type"].ToString() == "Fertilizer") { #region Handle Fertilizer FertilizerProduct cropNutrition = null; var products = export.Catalog.Products.Where(x => (x.Description == appliedProduct["Product"].ToString())).ToList(); if (products.Count > 0) { cropNutrition = products[0] as FertilizerProduct; } else { cropNutrition = new FertilizerProduct(); ourId = new UniqueId(); ourId.Id = appliedProduct["ProductId"]["Id"].ToString(); ourId.IdType = IdTypeEnum.UUID; ourId.Source = "www.somecompany.com"; ourId.SourceType = IdSourceTypeEnum.URI; cropNutrition.Id.UniqueIds.Add(ourId); cropNutrition.Description = appliedProduct["Product"].ToString(); if (manufacturer != null) { cropNutrition.ManufacturerId = manufacturer.Id.ReferenceId; } export.Catalog.Products.Add(cropNutrition); } operation.ProductId = cropNutrition.Id.ReferenceId; operation.OperationType = OperationTypeEnum.Fertilizing; #endregion } StampedMeteredValues smv = new StampedMeteredValues(); MeteredValue mv = null; NumericRepresentationValue rateValue = null; #region Set the product rate (currently hardcoded to be per acre) switch (appliedProduct["RateUnit"].ToString()) { case ("seed"): rateValue = new NumericRepresentationValue(RepresentationInstanceList.vrSeedRateSeedsActual.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("seeds1ac-1"), Convert.ToDouble(appliedProduct["RateValue"].ToString()))); break; case ("kernel"): rateValue = new NumericRepresentationValue(RepresentationInstanceList.vrSeedRateSeedsActual.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("seeds1ac-1"), Convert.ToDouble(appliedProduct["RateValue"].ToString()))); break; case ("short ton"): rateValue = new NumericRepresentationValue(RepresentationInstanceList.vrAppRateMassActual.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("ton1ac-1"), Convert.ToDouble(appliedProduct["RateValue"].ToString()))); break; case ("metric ton"): rateValue = new NumericRepresentationValue(RepresentationInstanceList.vrAppRateMassActual.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("t1ac-1"), Convert.ToDouble(appliedProduct["RateValue"].ToString()))); break; case ("pound"): if (appliedProduct["Type"].ToString() == "Seed") { rateValue = new NumericRepresentationValue(RepresentationInstanceList.vrSeedRateMassActual.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("lb1ac-1"), Convert.ToDouble(appliedProduct["RateValue"].ToString()))); } else { rateValue = new NumericRepresentationValue(RepresentationInstanceList.vrAppRateMassActual.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("lb1ac-1"), Convert.ToDouble(appliedProduct["RateValue"].ToString()))); } break; case ("ounce"): rateValue = new NumericRepresentationValue(RepresentationInstanceList.vrAppRateMassActual.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("oz1ac-1"), Convert.ToDouble(appliedProduct["RateValue"].ToString()))); break; case ("kilogram"): if (appliedProduct["Type"].ToString() == "Seed") { rateValue = new NumericRepresentationValue(RepresentationInstanceList.vrSeedRateMassActual.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("kg1ac-1"), Convert.ToDouble(appliedProduct["RateValue"].ToString()))); } else { rateValue = new NumericRepresentationValue(RepresentationInstanceList.vrAppRateMassActual.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("kg1ac-1"), Convert.ToDouble(appliedProduct["RateValue"].ToString()))); } break; case ("gram"): rateValue = new NumericRepresentationValue(RepresentationInstanceList.vrAppRateMassActual.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("g1ac-1"), Convert.ToDouble(appliedProduct["RateValue"].ToString()))); break; case ("fluid ounce"): rateValue = new NumericRepresentationValue(RepresentationInstanceList.vrAppRateVolumeActual.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("floz1ac-1"), Convert.ToDouble(appliedProduct["RateValue"].ToString()))); break; case ("quart"): rateValue = new NumericRepresentationValue(RepresentationInstanceList.vrAppRateVolumeActual.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("qt1ac-1"), Convert.ToDouble(appliedProduct["RateValue"].ToString()))); break; case ("pint"): rateValue = new NumericRepresentationValue(RepresentationInstanceList.vrAppRateVolumeActual.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("pt1ac-1"), Convert.ToDouble(appliedProduct["RateValue"].ToString()))); break; case ("milliliter"): rateValue = new NumericRepresentationValue(RepresentationInstanceList.vrAppRateVolumeActual.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("ml1ac-1"), Convert.ToDouble(appliedProduct["RateValue"].ToString()))); break; case ("liter"): rateValue = new NumericRepresentationValue(RepresentationInstanceList.vrAppRateVolumeActual.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("l1ac-1"), Convert.ToDouble(appliedProduct["RateValue"].ToString()))); break; case ("gallon"): rateValue = new NumericRepresentationValue(RepresentationInstanceList.vrAppRateVolumeActual.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("gal1ac-1"), Convert.ToDouble(appliedProduct["RateValue"].ToString()))); break; case ("centiliter"): rateValue = new NumericRepresentationValue(RepresentationInstanceList.vrAppRateVolumeActual.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("cl1ac-1"), Convert.ToDouble(appliedProduct["RateValue"].ToString()))); break; case ("acre"): break; default: break; } if (rateValue != null) { mv = new MeteredValue(); mv.Value = rateValue; smv.Values.Add(mv); } #endregion // Set the "applied area" for this use of the product (currently hardcoded to be in acres) NumericRepresentationValue areaValue = new NumericRepresentationValue(RepresentationInstanceList.vrTotalAreaCovered.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("ac1"), Convert.ToDouble(appliedProduct["AreaApplied"].ToString()))); mv = new MeteredValue(); mv.Value = areaValue; smv.Values.Add(mv); if (!string.IsNullOrEmpty(appliedProduct["ApplicationMethod"].ToString())) { EnumeratedValue applicationMethod = null; #region Set the product application method switch (appliedProduct["ApplicationMethod"].ToString()) { case ("Aerial"): applicationMethod = new EnumeratedValue { Value = DefinedTypeEnumerationInstanceList.dtiAerial.ToModelEnumMember() }; applicationMethod.Representation = RepresentationInstanceList.dtApplicationMethod.ToModelRepresentation(); break; case ("Air Blast"): applicationMethod = new EnumeratedValue { Value = DefinedTypeEnumerationInstanceList.dtiAirBlast.ToModelEnumMember() }; applicationMethod.Representation = RepresentationInstanceList.dtApplicationMethod.ToModelRepresentation(); break; case ("Chemigation"): applicationMethod = new EnumeratedValue { Value = DefinedTypeEnumerationInstanceList.dtiChemigation.ToModelEnumMember() }; applicationMethod.Representation = RepresentationInstanceList.dtApplicationMethod.ToModelRepresentation(); break; case ("Fertigation"): applicationMethod = new EnumeratedValue { Value = DefinedTypeEnumerationInstanceList.dtiFertigation.ToModelEnumMember() }; applicationMethod.Representation = RepresentationInstanceList.dtApplicationMethod.ToModelRepresentation(); break; case ("Ground - Banded"): applicationMethod = new EnumeratedValue { Value = DefinedTypeEnumerationInstanceList.dtiBand.ToModelEnumMember() }; applicationMethod.Representation = RepresentationInstanceList.dtApplicationMethod.ToModelRepresentation(); break; case ("Ground - Broadcast"): applicationMethod = new EnumeratedValue { Value = DefinedTypeEnumerationInstanceList.dtiBroadcast.ToModelEnumMember() }; applicationMethod.Representation = RepresentationInstanceList.dtApplicationMethod.ToModelRepresentation(); break; case ("Ground - Hooded"): applicationMethod = new EnumeratedValue { Value = DefinedTypeEnumerationInstanceList.dtiHoodedSprayer.ToModelEnumMember() }; applicationMethod.Representation = RepresentationInstanceList.dtApplicationMethod.ToModelRepresentation(); break; case ("Ground - In Furrow"): applicationMethod = new EnumeratedValue { Value = DefinedTypeEnumerationInstanceList.dtiInFurrow.ToModelEnumMember() }; applicationMethod.Representation = RepresentationInstanceList.dtApplicationMethod.ToModelRepresentation(); break; case ("Ground Application"): applicationMethod = new EnumeratedValue { Value = DefinedTypeEnumerationInstanceList.dtiInGround.ToModelEnumMember() }; applicationMethod.Representation = RepresentationInstanceList.dtApplicationMethod.ToModelRepresentation(); break; case ("Planting"): applicationMethod = new EnumeratedValue { Value = DefinedTypeEnumerationInstanceList.dtiPlanter.ToModelEnumMember() }; applicationMethod.Representation = RepresentationInstanceList.dtApplicationMethod.ToModelRepresentation(); break; case ("Re-Planting"): applicationMethod = new EnumeratedValue { Value = DefinedTypeEnumerationInstanceList.dtiPlanter.ToModelEnumMember() }; applicationMethod.Representation = RepresentationInstanceList.dtApplicationMethod.ToModelRepresentation(); break; case ("Sidedress"): applicationMethod = new EnumeratedValue { Value = DefinedTypeEnumerationInstanceList.dtiSideDress.ToModelEnumMember() }; applicationMethod.Representation = RepresentationInstanceList.dtApplicationMethod.ToModelRepresentation(); break; case ("Fumigation"): case ("Ground - Incorporated"): case ("Ground - Seed Treatment"): case ("Ground - Variable Rate"): case ("Storage"): case ("Topdress"): case ("Tree Injection"): case ("Water Run"): default: applicationMethod = new EnumeratedValue { Value = DefinedTypeEnumerationInstanceList.dtiInGround.ToModelEnumMember() }; applicationMethod.Representation = RepresentationInstanceList.dtApplicationMethod.ToModelRepresentation(); break; } if (applicationMethod != null) { mv = new MeteredValue(); mv.Value = applicationMethod; smv.Values.Add(mv); } #endregion } // There is a problem here handling seed totals by bag....will have to come back to this at some point NumericRepresentationValue totalProductValue = null; #region Set the total product switch (appliedProduct["TotalProductUnit"].ToString()) { case ("seed"): totalProductValue = new NumericRepresentationValue(RepresentationInstanceList.vrTotalSeedQuantityAppliedSeed.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("seeds"), Convert.ToDouble(appliedProduct["TotalProductQty"].ToString()))); break; case ("kernel"): totalProductValue = new NumericRepresentationValue(RepresentationInstanceList.vrTotalSeedQuantityAppliedSeed.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("seeds"), Convert.ToDouble(appliedProduct["TotalProductQty"].ToString()))); break; case ("short ton"): totalProductValue = new NumericRepresentationValue(RepresentationInstanceList.vrTotalQuantityAppliedMass.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("ton"), Convert.ToDouble(appliedProduct["TotalProductQty"].ToString()))); break; case ("metric ton"): totalProductValue = new NumericRepresentationValue(RepresentationInstanceList.vrTotalQuantityAppliedMass.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("t"), Convert.ToDouble(appliedProduct["TotalProductQty"].ToString()))); break; case ("pound"): if (appliedProduct["Type"].ToString() == "Seed") { totalProductValue = new NumericRepresentationValue(RepresentationInstanceList.vrTotalSeedQuantityAppliedMass.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("lb"), Convert.ToDouble(appliedProduct["TotalProductQty"].ToString()))); } else { totalProductValue = new NumericRepresentationValue(RepresentationInstanceList.vrTotalQuantityAppliedMass.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("lb"), Convert.ToDouble(appliedProduct["TotalProductQty"].ToString()))); } break; case ("ounce"): totalProductValue = new NumericRepresentationValue(RepresentationInstanceList.vrTotalQuantityAppliedMass.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("oz"), Convert.ToDouble(appliedProduct["TotalProductQty"].ToString()))); break; case ("kilogram"): if (appliedProduct["Type"].ToString() == "Seed") { totalProductValue = new NumericRepresentationValue(RepresentationInstanceList.vrTotalSeedQuantityAppliedMass.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("kg"), Convert.ToDouble(appliedProduct["TotalProductQty"].ToString()))); } else { totalProductValue = new NumericRepresentationValue(RepresentationInstanceList.vrTotalQuantityAppliedMass.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("kg"), Convert.ToDouble(appliedProduct["TotalProductQty"].ToString()))); } break; case ("gram"): totalProductValue = new NumericRepresentationValue(RepresentationInstanceList.vrTotalQuantityAppliedMass.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("g1ac-1"), Convert.ToDouble(appliedProduct["TotalProductQty"].ToString()))); break; case ("fluid ounce"): totalProductValue = new NumericRepresentationValue(RepresentationInstanceList.vrTotalQuantityAppliedVolume.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("floz"), Convert.ToDouble(appliedProduct["TotalProductQty"].ToString()))); break; case ("quart"): totalProductValue = new NumericRepresentationValue(RepresentationInstanceList.vrTotalQuantityAppliedVolume.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("qt"), Convert.ToDouble(appliedProduct["TotalProductQty"].ToString()))); break; case ("pint"): totalProductValue = new NumericRepresentationValue(RepresentationInstanceList.vrTotalQuantityAppliedVolume.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("pt"), Convert.ToDouble(appliedProduct["TotalProductQty"].ToString()))); break; case ("milliliter"): totalProductValue = new NumericRepresentationValue(RepresentationInstanceList.vrTotalQuantityAppliedVolume.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("ml"), Convert.ToDouble(appliedProduct["TotalProductQty"].ToString()))); break; case ("liter"): totalProductValue = new NumericRepresentationValue(RepresentationInstanceList.vrTotalQuantityAppliedVolume.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("l"), Convert.ToDouble(appliedProduct["TotalProductQty"].ToString()))); break; case ("gallon"): totalProductValue = new NumericRepresentationValue(RepresentationInstanceList.vrTotalQuantityAppliedVolume.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("gal"), Convert.ToDouble(appliedProduct["TotalProductQty"].ToString()))); break; case ("centiliter"): totalProductValue = new NumericRepresentationValue(RepresentationInstanceList.vrTotalQuantityAppliedVolume.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("cl"), Convert.ToDouble(appliedProduct["TotalProductQty"].ToString()))); break; case ("acre"): break; default: break; } if (totalProductValue != null) { mv = new MeteredValue(); mv.Value = totalProductValue; smv.Values.Add(mv); } #endregion operation.Data.Add(smv); // Add the OperationSummary to the collection in Summary summary.OperationSummaries.Add(operation); // End - Foreach Product } // Add this Summary to the list summaries.Add(summary); // Add the WorkRecord to the list workRecords.Add(workRecord); // End - Foreach Application } // This property is an IEnumerable so we had to build up the collection in a local list then assign it export.Documents.Summaries = summaries; // This property is an IEnumerable so we had to build up the collection in a local list then assign it export.Documents.WorkRecords = workRecords; // Make sure the target directory exits string outputPath = applicationPath + @"\Output"; if (Directory.Exists(outputPath)) { Directory.Delete(outputPath, true); } if (!Directory.Exists(outputPath)) { Directory.CreateDirectory(outputPath); } admPlugin.Export(export, outputPath); // NOTE: There is a fundamental problem with this version of ADAPT 1.1.0.8 and the ADMPlugin that prevents // the Summary and WorkRecord objects from serializing correctly. This sample will be updated after the MVP // process is complete. }
static void Main(string[] args) { // Load up the sample farm/field/cropzone information var treeData = (JArray)(JObject.Parse(File.ReadAllText("tree.json"))["Results"]); // Load up the field/cropzone boundaries var boundaryData = (JArray)(JObject.Parse(File.ReadAllText("boundaries.json"))["Results"]); // Initialize a Well-Known-Text (WKT) reader for handling the sample boundary data GeometryFactory geometryFactory = new GeometryFactory(); NetTopologySuite.IO.WKTReader wktReader = new NetTopologySuite.IO.WKTReader(geometryFactory); // In this console app the ADMPlugin is included as a NuGet package so the ADMPlugin.dll is always // copied directly in to the executable directory. That's why we tell the PluginFactory to look there // for the ADMPlugin. string applicationPath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location); // The PluginFactory looks at all the DLLs in the target directory to find any that implement the IPlugin interface. var pluginFactory = new PluginFactory(applicationPath); // We're only interested in the ADMPlugin here, so I address it directly instead of looking through all the // available plugins that the PluginFactory found. var admPlugin = pluginFactory.GetPlugin("ADMPlugin"); // The ADMPlugin doesn't require any initialization parameters. admPlugin.Initialize(); // The ApplicationDataModel is the root object in ADAPT ApplicationDataModel export = new ApplicationDataModel(); // The Catalog object (inside the ApplicationDataModel) holds all the items you would expect to find in a "pick list". // Alternatively, you could think of it as the place you put everything used "by reference" in any of the Documents // you are trying to send. export.Catalog = new Catalog(); // The Documents object (inside the ApplicationDataModel) holds all the Plans, Recommendations, WorkOrders, and // WorkRecords (and their component parts). We won't be using this in this example. export.Documents = new Documents(); // Create a "crop year" TimeScope to tag objects with. TimeScope cropYear = new TimeScope(); cropYear.Description = "2017"; cropYear.DateContext = DateContextEnum.CropSeason; export.Catalog.TimeScopes.Add(cropYear); // Create the Grower object. The constructor will automatically create the Id property and assign the // next available ReferenceId integer. Grower adaptGrower = new Grower(); // Associate your internal, unique identifier to the Grower object by creating a UniqueId object // and adding it to the Grower object's CompoundIdentifier. UniqueId ourId = new UniqueId(); ourId.Id = "7d2253f0-fce6-4740-b3c3-f9c8ab92bfaa"; // Notice the available IdTypeEnum choices. Not everybody uses the same way of identifying things in their // system. As a result, we must support a number of identification schemes. ourId.IdType = IdTypeEnum.UUID; // Almost as important as the identifier is knowing who created it (or where it came from). ourId.Source = "www.agconnections.com"; ourId.SourceType = IdSourceTypeEnum.URI; // Each CompoundIdentifier that is used in ADAPT can have multiple unique identifiers associated with it. // Consider the possibilites here, not only can your identifier for something be peristed but also the // identifiers that your trading partner assigns to the same object. PLEASE CONSIDER PERSISTING AND RETURNING // IDENTIFIERS PASSED TO YOU IN THIS FASHION. This has the potential to result in a "frictionless" conversation // once the initial mapping is done, buy this benefit will only emerge if we all are "good neighbors". adaptGrower.Id.UniqueIds.Add(ourId); // You may notice that many of the objects in ADAPT have a minimal number of properties. Don't panic if you // can't find a place to put all your data. It may be in an associated object or intended to be expressed // as a ContextItem. adaptGrower.Name = "Ponderosa Farms"; // Add the Grower object to the Catalog. export.Catalog.Growers.Add(adaptGrower); // Pull the farm objects out of the sample JSON test data var farms = (from c in treeData where ((string)c["type"] == "farm") select c).ToList(); // Iterate over each farm foreach (var farm in farms) { // Create the Farm object. The constructor will automatically create the Id property and assign the // next available ReferenceId integer. Farm adaptFarm = new Farm(); ourId = new UniqueId(); ourId.Id = (string)farm["id"]; ourId.IdType = IdTypeEnum.UUID; ourId.Source = "www.agconnections.com"; ourId.SourceType = IdSourceTypeEnum.URI; adaptFarm.Id.UniqueIds.Add(ourId); adaptFarm.Description = (string)farm["text"]; // Here we link this farm object to the grower. Note that this is the integer (ReferenceId) in the // Grower's CompountIdentifier object. adaptFarm.GrowerId = adaptGrower.Id.ReferenceId; // Add the Farm object to the Catalog. export.Catalog.Farms.Add(adaptFarm); // Pull the field objects out of the sample JSON test data that are part of this iteration's farm var fields = (from c in treeData where (((string)c["type"] == "field") && ((string)c["parent"] == (string)farm["id"])) select c).ToList(); // Iterate over each field foreach (var field in fields) { // Create the Field object. The constructor will automatically create the Id property and assign the // next available ReferenceId integer. Field adaptField = new Field(); ourId = new UniqueId(); ourId.Id = (string)field["id"]; ourId.IdType = IdTypeEnum.UUID; ourId.Source = "www.agconnections.com"; ourId.SourceType = IdSourceTypeEnum.URI; adaptField.Id.UniqueIds.Add(ourId); adaptField.Description = (string)field["text"]; // Here we link this field object to the farm. Note that this is the integer (ReferenceId) in the // Farm's CompountIdentifier object. adaptField.FarmId = adaptFarm.Id.ReferenceId; // Pull the boundary object out of the sample JSON test data (if it exists) var fieldBoundary = (from c in boundaryData where (((string)c["FieldId"] == (string)field["id"]) && ((string)c["CropZoneId"] == null)) select c).FirstOrDefault(); if (fieldBoundary != null) { // This sample data has boundaries expressed as MultiPolygons in WKT so we need to transform that into the correlary ADAPT objects. // Your data may use a different geometry (instead of MultiPolygon) to describe your boundaries so your code may differ at this point. var boundary = wktReader.Read((string)fieldBoundary["MapData"]) as NetTopologySuite.Geometries.MultiPolygon; AgGateway.ADAPT.ApplicationDataModel.Shapes.MultiPolygon adaptMultiPolygon = new AgGateway.ADAPT.ApplicationDataModel.Shapes.MultiPolygon(); adaptMultiPolygon.Polygons = new List <AgGateway.ADAPT.ApplicationDataModel.Shapes.Polygon>(); foreach (var geometry in boundary.Geometries) { var polygon = geometry as NetTopologySuite.Geometries.Polygon; AgGateway.ADAPT.ApplicationDataModel.Shapes.Polygon adaptPolygon = new AgGateway.ADAPT.ApplicationDataModel.Shapes.Polygon(); adaptPolygon.ExteriorRing = new AgGateway.ADAPT.ApplicationDataModel.Shapes.LinearRing(); adaptPolygon.InteriorRings = new List <AgGateway.ADAPT.ApplicationDataModel.Shapes.LinearRing>(); foreach (var coordinate in polygon.ExteriorRing.Coordinates) { var adaptPoint = new AgGateway.ADAPT.ApplicationDataModel.Shapes.Point(); adaptPoint.X = coordinate.X; adaptPoint.Y = coordinate.Y; adaptPolygon.ExteriorRing.Points.Add(adaptPoint); } foreach (var ring in polygon.InteriorRings) { var adaptRing = new AgGateway.ADAPT.ApplicationDataModel.Shapes.LinearRing(); adaptRing.Points = new List <AgGateway.ADAPT.ApplicationDataModel.Shapes.Point>(); foreach (var coordinate in ring.Coordinates) { var adaptPoint = new AgGateway.ADAPT.ApplicationDataModel.Shapes.Point(); adaptPoint.X = coordinate.X; adaptPoint.Y = coordinate.Y; adaptRing.Points.Add(adaptPoint); } adaptPolygon.InteriorRings.Add(adaptRing); } adaptMultiPolygon.Polygons.Add(adaptPolygon); } // Unlike the CropZone object (which holds its geomertry internally) a Field's boundary is held in a separate FieldBoundary object. // Create the FieldBoundary object. The constructor will automatically create the Id property and assign the // next available ReferenceId integer. FieldBoundary adaptBoundary = new FieldBoundary(); // The FieldBoundary.SpatialData property is an ADAPT Shape object (which is an abastract class). What you actually attach here // is one of the child classes of Shape (Polygon, MultiPolygon, etc.). adaptBoundary.SpatialData = adaptMultiPolygon; // Here we link this field boundary object to the field. Note that this is the integer (ReferenceId) in the // Field's CompountIdentifier object. adaptBoundary.FieldId = adaptField.Id.ReferenceId; // Add the FieldBoundary object to the Catalog. export.Catalog.FieldBoundaries.Add(adaptBoundary); // It is possible for a given Field to have multiple FieldBounday objects associated with it, but we need to be able // to indicate which one should be used by "default". adaptField.ActiveBoundaryId = adaptBoundary.Id.ReferenceId; } // Add the Field object to the Catalog. *Note: We are adding this to the Catalog here so that we don't have to go // back and fetch the object to set the ActiveBoundaryId property. Not required, just convenient. export.Catalog.Fields.Add(adaptField); // We're defining a CropZone as a spatial area within a field grown to a crop during a specific window of time. // This is fundamentally different from the concept of a management zone (that might vary by plant population or soil type). // Pull the cropzone objects out of the sample JSON test data that are part of this iteration's field var cropzones = (from c in treeData where (((string)c["type"] == "cropzone") && ((string)c["parent"] == (string)field["id"])) select c).ToList(); // Iterate over each cropzone foreach (var cropzone in cropzones) { // It's entirely possible that we have already added this Crop to the Catalog during a previous iteration. We need to check // the Crop list in Catalog first and reuse that object if it exists. Crop adaptCrop = null; var crops = export.Catalog.Crops.Where(x => (x.Name == (string)cropzone["li_attr"]["CropName"])).ToList(); if (crops.Count > 0) { adaptCrop = crops[0]; } else { // Create the Crop object. The constructor will automatically create the Id property and assign the // next available ReferenceId integer. adaptCrop = new Crop(); ourId = new UniqueId(); ourId.Id = (string)cropzone["li_attr"]["CropId"]; ourId.IdType = IdTypeEnum.UUID; ourId.Source = "www.agconnections.com"; ourId.SourceType = IdSourceTypeEnum.URI; adaptCrop.Id.UniqueIds.Add(ourId); adaptCrop.Name = (string)cropzone["li_attr"]["CropName"]; // Add EPPO code as ContextItem at some point in the future // Add the Crop object to the Catalog. export.Catalog.Crops.Add(adaptCrop); } // Create the CropZone object. The constructor will automatically create the Id property and assign the // next available ReferenceId integer. CropZone adaptCropZone = new CropZone(); ourId = new UniqueId(); ourId.Id = (string)cropzone["id"]; ourId.IdType = IdTypeEnum.UUID; ourId.Source = "www.agconnections.com"; ourId.SourceType = IdSourceTypeEnum.URI; adaptCropZone.Id.UniqueIds.Add(ourId); adaptCropZone.Description = (string)cropzone["text"]; // Here we link this cropzone object to the field. Note that this is the integer (ReferenceId) in the // Field's CompountIdentifier object. adaptCropZone.FieldId = adaptField.Id.ReferenceId; // Here we link this cropzone object to the crop. Note that this is the integer (ReferenceId) in the // Crop's CompountIdentifier object. adaptCropZone.CropId = adaptCrop.Id.ReferenceId; // Here we link this cropzone object to the crop year TimeScope. Note that the TimeScope is used BY VALUE // instead of BY REFERENCE (like the field and crop above). adaptCropZone.TimeScopes.Add(cropYear); string areaString = (string)cropzone["li_attr"]["AreaValue"]; if (!string.IsNullOrEmpty(areaString)) { double area = Convert.ToDouble(areaString); adaptCropZone.Area = new NumericRepresentationValue(RepresentationInstanceList.vrReportedFieldArea.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("ac1"), area)); } // As mentioned before, the CropZone (unlike Field) holds its boundary internally. Also unlike field, a CropZone is only expected // to have a single boundary due to its scope in crop & time. var czBoundary = (from c in boundaryData where ((string)c["CropZoneId"] == (string)cropzone["id"]) select c).FirstOrDefault(); if (czBoundary != null) { var boundary = wktReader.Read((string)czBoundary["MapData"]) as NetTopologySuite.Geometries.MultiPolygon; AgGateway.ADAPT.ApplicationDataModel.Shapes.MultiPolygon adaptMultiPolygon = new AgGateway.ADAPT.ApplicationDataModel.Shapes.MultiPolygon(); adaptMultiPolygon.Polygons = new List <AgGateway.ADAPT.ApplicationDataModel.Shapes.Polygon>(); foreach (var geometry in boundary.Geometries) { var polygon = geometry as NetTopologySuite.Geometries.Polygon; AgGateway.ADAPT.ApplicationDataModel.Shapes.Polygon adaptPolygon = new AgGateway.ADAPT.ApplicationDataModel.Shapes.Polygon(); adaptPolygon.ExteriorRing = new AgGateway.ADAPT.ApplicationDataModel.Shapes.LinearRing(); adaptPolygon.InteriorRings = new List <AgGateway.ADAPT.ApplicationDataModel.Shapes.LinearRing>(); foreach (var coordinate in polygon.ExteriorRing.Coordinates) { var adaptPoint = new AgGateway.ADAPT.ApplicationDataModel.Shapes.Point(); adaptPoint.X = coordinate.X; adaptPoint.Y = coordinate.Y; adaptPolygon.ExteriorRing.Points.Add(adaptPoint); } foreach (var ring in polygon.InteriorRings) { var adaptRing = new AgGateway.ADAPT.ApplicationDataModel.Shapes.LinearRing(); adaptRing.Points = new List <AgGateway.ADAPT.ApplicationDataModel.Shapes.Point>(); foreach (var coordinate in ring.Coordinates) { var adaptPoint = new AgGateway.ADAPT.ApplicationDataModel.Shapes.Point(); adaptPoint.X = coordinate.X; adaptPoint.Y = coordinate.Y; adaptRing.Points.Add(adaptPoint); } adaptPolygon.InteriorRings.Add(adaptRing); } adaptMultiPolygon.Polygons.Add(adaptPolygon); } adaptCropZone.BoundingRegion = adaptMultiPolygon; } // Add the CropZone object to the Catalog. export.Catalog.CropZones.Add(adaptCropZone); } } } // At this point we have added all the Grower/Farm/Field objects to the Catalog and are ready to export. // Create an output path string outputPath = applicationPath + @"\Output"; if (Directory.Exists(outputPath)) { Directory.Delete(outputPath, true); } if (!Directory.Exists(outputPath)) { Directory.CreateDirectory(outputPath); } // Export to a local directory using the ADMPlugin admPlugin.Export(export, outputPath); // The ADMPlugin creates an "adm" subdirectory in the indicated local directory that contains the following items: // An additional "documents" subdirectory that contains the protobuf-encoded document files. // An AdmVersion.info file that contains version information. // A ProprietaryValues.adm file // A Catalog.adm file that contains the zipped JSON serialization of the ApplicationDataModel.Catalog object. // We've added logic here to zip that "adm" subdirectory into a single file, in case you want to email it to someone. string zipPath = applicationPath + @"\Zip"; if (Directory.Exists(zipPath)) { Directory.Delete(zipPath, true); } if (!Directory.Exists(zipPath)) { Directory.CreateDirectory(zipPath); } // Delete the file if it already exists string zipFile = zipPath + @"\tree.zip"; if (File.Exists(zipFile)) { File.Delete(zipFile); } ZipFile.CreateFromDirectory(outputPath, zipFile); // This is logic to import the same data from the "adm" subdirectory we just created so you can compare it // in the debugger if you want. var pluginFactory2 = new PluginFactory(applicationPath); var admPlugin2 = pluginFactory.GetPlugin("ADMPlugin"); admPlugin2.Initialize(); // Note that when a plugin imports, the returned object is a list of ApplicationDataModel objects. var imports = admPlugin2.Import(outputPath); }
private List <Feature> MapMultiple(RasterGridPrescription prescription) { List <Feature> features = new List <Feature>(); // Based on Open.Topology.TestRunner.Functions/CreateShapeFunctions.Grid var grid = new List <BoundingBox>(); int nCellsOnSideX = (int)prescription.ColumnCount; int nCellsOnSideY = (int)prescription.RowCount; double cellSizeX = prescription.CellWidth.Value.Value; double cellSizeY = prescription.CellHeight.Value.Value; double dMinX, dMinY; if (prescription.BoundingBox != null) { dMinX = prescription.BoundingBox.MinX.Value.Value; dMinY = prescription.BoundingBox.MinY.Value.Value; } else { dMinX = prescription.Origin.X; dMinY = prescription.Origin.Y; } for (int j = 0; j < nCellsOnSideY; j++) { for (int i = 0; i < nCellsOnSideX; i++) { double x1 = dMinX + i * cellSizeX; double y1 = dMinY + j * cellSizeY; double x2 = dMinX + (i + 1) * cellSizeX; double y2 = dMinY + (j + 1) * cellSizeY; var bbox = new BoundingBox(); bbox.MinY = new NumericRepresentationValue(RepresentationInstanceList.vrLatitude.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("arcdeg"), y1)); bbox.MinX = new NumericRepresentationValue(RepresentationInstanceList.vrLongitude.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("arcdeg"), x1)); bbox.MaxY = new NumericRepresentationValue(RepresentationInstanceList.vrLatitude.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("arcdeg"), y2)); bbox.MaxX = new NumericRepresentationValue(RepresentationInstanceList.vrLongitude.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("arcdeg"), x2)); grid.Add(bbox); } } int index = 0; double outOfFieldRate = -1.0; // something save to compare with if (prescription.OutOfFieldRate != null) { outOfFieldRate = prescription.OutOfFieldRate.Value.Value; } Console.WriteLine($"PrescriptionMapper outOfFieldRate: {outOfFieldRate}, grids {grid.Count}"); // @ToDo merge adjacent grid boxes with same property values? foreach (var bbox in grid) { // skip outOfField grids if (prescription.Rates[index].RxRates[0].Rate != outOfFieldRate) { GeoJSON.Net.Geometry.IGeometryObject geometry = PolygonMapper.MapBoundingBox(bbox, _properties.AffineTransformation); Dictionary <string, object> properties = new Dictionary <string, object>(); RxProductLookup product = prescription.RxProductLookups.Where(r => r.Id.ReferenceId == prescription.Rates[index].RxRates[0].RxProductLookupId).FirstOrDefault(); if (product != null) { properties.Add("productId", product.ProductId); Product adaptProduct = _dataModel.Catalog.Products.Where(p => p.Id.ReferenceId == product.ProductId).FirstOrDefault(); if (adaptProduct != null) { properties.Add("productDescription", adaptProduct.Description); properties.Add("productType", adaptProduct.ProductType.ToString()); // or via GetName? } properties.Add("productCode", product.Representation.Code); properties.Add("productUom", product.UnitOfMeasure.Code); } else { properties.Add("productId", prescription.Rates[index].RxRates[0].RxProductLookupId); } properties.Add("rate", prescription.Rates[index].RxRates[0].Rate); features.Add(new Feature(geometry, properties)); } index++; } return(features); }
public void GivenSpatialRecordWhenMapThenValueIsReturned() { var numericRepresentationValue = new NumericRepresentationValue(RepresentationInstanceList.vrLongitude.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("arcdeg"), 85)); _spatialRecord.SetMeterValue(_meter, numericRepresentationValue); _representationMapperMock.Setup(x => x.Map(numericRepresentationValue.Representation)).Returns(1); var result = _mapper.Map(_meter, _spatialRecord); var expectedValue = (uint)numericRepresentationValue.Value.Value / .01; Assert.AreEqual(expectedValue, result); }