예제 #1
0
        public XmlWriter Export(ApplicationDataModel.ADM.ApplicationDataModel applicationDataModel, string taskDataPath, TaskDocumentWriter writer)
        {
            var isoTaskData = writer.Write(taskDataPath, applicationDataModel);

            if (applicationDataModel != null)
            {

                var numberOfExistingTasks = GetNumberOfExistingTasks(isoTaskData, writer);
                var tasks = applicationDataModel.Documents == null
                    ? null
                    : _taskMapper.Map(applicationDataModel.Documents.LoggedData, applicationDataModel.Catalog,
                        taskDataPath, numberOfExistingTasks, writer, false);
                if (tasks != null)
                {
                    var taskList = tasks.ToList();
                    taskList.ForEach(t => t.WriteXML(isoTaskData));
                }
            }

            //Close the root element with </ISO11783_TaskData>
            isoTaskData.WriteEndElement();
            isoTaskData.Close();
            return isoTaskData;
        }
예제 #2
0
        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);
        }
 public static IEnumerable <Field> GetFields(this ApplicationDataModel dataModel)
 {
     return(dataModel.Catalog?.Fields ?? Enumerable.Empty <Field>());
 }
 public static bool HasLoggedDataForField(this ApplicationDataModel dataModel, Field field)
 {
     return(dataModel.Documents.LoggedData
            .Any(l => l.FieldId == field.Id.ReferenceId));
 }
 public PrescriptionMapper(PluginProperties properties, ApplicationDataModel dataModel = null)
 {
     _properties = properties;
     _dataModel  = dataModel;
 }
예제 #6
0
 public void Export(ApplicationDataModel dataModel, string exportPath, Properties properties = null)
 {
     ExportArgs.Add(new ExportArgs(dataModel, exportPath, properties));
 }
 public FieldBoundaryMapper(PluginProperties properties, ApplicationDataModel dataModel = null)
 {
     _properties = properties;
     _dataModel  = dataModel;
 }
예제 #8
0
 /// <summary>
 /// The collection is based on a single ApplicationDataModel.  This is an important concept.  The reference
 /// ids used within the model to identify Grower, Farm, Field, Crop, CropZone etc. are valid only within the
 /// contect of the current ApplicationDataModel.  The same item added to another model would likely have a
 /// different value.  Therefore all values must be taken from the same ApplicationDataModel.
 /// </summary>
 /// <param name="model"></param>
 internal GrowerTree(ApplicationDataModel model)
     : base()
 {
     DataModel = model;
 }
예제 #9
0
 public static string GetUNRec20Code(ApplicationDataModel.Common.UnitOfMeasure uom)
 {
     return InternalUnitSystemManager.Instance.DomainIdToUnRec20Code[uom.Code];
 }
        private void AddDataModel(string pluginName = null, string pluginVersion = null, ApplicationDataModel dataModel = null)
        {
            var plugin = new PredicatePlugin
            {
                Name       = pluginName,
                Version    = pluginVersion,
                DataModels =
                {
                    dataModel ?? new ApplicationDataModel()
                }
            };
            var storageModel = new StorageDataModel(null, plugin);

            _dataModels.Add(storageModel);
        }
 public DrivenHeadlandMapper(PluginProperties properties, ApplicationDataModel dataModel)
 {
     this._properties = properties;
     this._dataModel  = dataModel;
 }
예제 #12
0
        public void SetData(ApplicationDataModel data)
        {
            SystemKeyId = data.ApplicationId;

            base.SetData(data);
        }
예제 #13
0
 private void ReBindEditableGrid()
 {
     var data          = new ApplicationDataModel();
     var dtApplication = Framework.Components.ApplicationUser.ApplicationDataManager.Search(data, SessionVariables.RequestProfile);
 }
예제 #14
0
        public XmlWriter Write(string taskDataPath, ApplicationDataModel.ADM.ApplicationDataModel dataModel)
        {
            BaseFolder = taskDataPath;
            DataModel = dataModel;

            CreateFolderStructure();

            XmlStream = new MemoryStream();
            RootWriter = CreateWriter("TASKDATA.XML", XmlStream);
            RootWriter.WriteStartDocument();

            IsoRootWriter.Write(this);
            RootWriter.Flush();

            return RootWriter;
        }
예제 #15
0
        public void Export(ApplicationDataModel dataModel, string exportPath, Properties properties = null)
        {
            ParseExportProperties(properties);

            if (!Directory.Exists(exportPath))
            {
                Directory.CreateDirectory(exportPath);
            }

            // Path of exportfolder: "PluginFolder - [Name of Catalog]"
            var newPath = Path.Combine(exportPath, InfoFileConstants.PluginFolderPrefix + "-" + ZipUtils.GetSafeName(dataModel.Catalog.Description));

            // ToDo: add more meta data of this export
            _JsonExporter.WriteInfoFile(newPath, Name, Version, dataModel.Catalog.Description, CustomProperties);

            switch (CustomProperties.ApplyingAnonymiseValuesPer)
            {
            case ApplyingAnonymiseValuesEnum.PerField:
                foreach (var fieldId in dataModel.Catalog.Fields.Select(f => f.Id.ReferenceId))
                {
                    List <int> workRecordIds =
                        dataModel.Documents.WorkRecords
                        .Where(wr => wr.FieldIds.Contains(fieldId))
                        .Select(wr => wr.Id.ReferenceId)
                        .ToList();

                    if (CustomProperties.Anonymise)
                    {
                        // Randomize the Anonymization values
                        AnonymizeUtils.GenerateRandomAffineTransformation(CustomProperties);
                    }
                    ;

                    // OperationDataMapper
                    // ToDo: replace with OperationDataMapper
                    //var workRecordDtos = workRecordsMapper.MapAll(workRecordIds);
                    //_JsonExporter.WriteWorkRecordDtos(newPath, workRecordDtos);

                    // FieldBoundaryMapper
                    // ToDo: FieldBoundaryMapper.MapAsSingleFeature([fieldId])

                    // GuidanceGroupMapper
                    // ToDo: GuidanceGroupMapper.MapAs...([all GuidanceGroups for fieldId])

                    // WorkItemOperationMapper
                    // ToDo: WorkItemOperationMapper.MapAs...([all WorkItemOperations for fieldId])
                }
                break;

            case ApplyingAnonymiseValuesEnum.PerWorkRecord:
                foreach (var workRecord in dataModel.Documents.WorkRecords)
                {
                    if (CustomProperties.Anonymise)
                    {
                        // Randomize the Anonymization values
                        AnonymizeUtils.GenerateRandomAffineTransformation(CustomProperties);
                    }
                    ;

                    // OperationDataMapper
                    // ToDo: replace with OperationDataMapper
                    //WorkRecordDto workRecordDto_mapped = workRecordsMapper.MapSingle(workRecord);
                    //_JsonExporter.WriteWorkRecordDto(newPath, workRecordDto_mapped);

                    // FieldBoundaryMapper
                    // ToDo: FieldBoundaryMapper.MapAsMultipleFeatures([all FieldBoundaries for workRecord.Id])

                    // GuidanceGroupMapper
                    // ToDo: GuidanceGroupMapper.MapAs...([all GuidanceGroups for workRecord.Id])

                    // WorkItemOperationMapper
                    // ToDo: GuidanceGroupMapper.MapAs...([all WorkItemOperations for workRecord.Id])
                }
                break;

            default:
                if (CustomProperties.Anonymise)
                {
                    // Randomize the Anonymization values
                    AnonymizeUtils.GenerateRandomAffineTransformation(CustomProperties);
                }
                ;
                foreach (var workRecord in dataModel.Documents.WorkRecords)
                {
                    // OperationDataMapper
                    // ToDo: OperationDataMapper.MapAsFeatureCollection([workRecord])
                }
                FieldBoundaryMapper fieldBoundaryMapper = new FieldBoundaryMapper(CustomProperties, dataModel);
                foreach (var fieldBoundary in dataModel.Catalog.FieldBoundaries)
                {
                    // FieldBoundaryMapper
                    Feature fieldBoundaryFeature  = fieldBoundaryMapper.MapAsSingleFeature(fieldBoundary);
                    string  fileNamePrescriptions = FieldBoundaryMapper.GetFieldBoundaryPrefix();
                    if (fieldBoundaryFeature.Properties.ContainsKey("FieldId"))
                    {
                        fileNamePrescriptions = fileNamePrescriptions + "_for_field_" + fieldBoundaryFeature.Properties["FieldId"];
                    }
                    else if (fieldBoundaryFeature.Properties.ContainsKey("Guid"))
                    {
                        fileNamePrescriptions = fileNamePrescriptions + "_" + fieldBoundaryFeature.Properties["Guid"];
                    }
                    else
                    {
                        fileNamePrescriptions = fileNamePrescriptions + "_" + Guid.NewGuid();
                    }

                    _JsonExporter.WriteAsGeoJson(newPath, new List <Feature>()
                    {
                        fieldBoundaryFeature
                    }, fileNamePrescriptions);


                    // DrivenHeadlandMapper
                    foreach (Headland headland in fieldBoundary.Headlands)
                    {
                        if (headland is DrivenHeadland)
                        {
                            DrivenHeadlandMapper drivenHeadlandMapper = new DrivenHeadlandMapper(CustomProperties, dataModel);
                            Feature drivenHeadlandFeature             = drivenHeadlandMapper.MapAsSingleFeature(headland as DrivenHeadland, fieldBoundaryFeature);
                            if (drivenHeadlandFeature == null)
                            {
                                drivenHeadlandMapper = null;
                            }
                            else
                            {
                                string drivenHeadlandFileName = DrivenHeadlandMapper.GetPrefix();
                                if (drivenHeadlandFeature.Properties.ContainsKey("FieldId"))
                                {
                                    drivenHeadlandFileName += "_for_field_" + drivenHeadlandFeature.Properties["FieldId"];
                                }
                                _JsonExporter.WriteAsGeoJson(newPath, new List <Feature>()
                                {
                                    drivenHeadlandFeature
                                }, drivenHeadlandFileName);
                            }
                        }
                    }
                }
                GuidanceGroupMapper guidanceGroupMapper = new GuidanceGroupMapper(CustomProperties, dataModel);
                foreach (var guidanceGroup in dataModel.Catalog.GuidanceGroups)
                {
                    // GuidanceGroupMapper
                    List <Feature> guidanceGroupFeatures = guidanceGroupMapper.MapAsMultipleFeatures(guidanceGroup);
                    string         fileNameGuidanceGroup = GuidanceGroupMapper.GetPrefix();
                    if (guidanceGroupFeatures[0] != null)
                    {
                        if (guidanceGroupFeatures[0].Properties.ContainsKey("GuidancePatternType"))
                        {
                            fileNameGuidanceGroup = fileNameGuidanceGroup + "_type_" + guidanceGroupFeatures[0].Properties["GuidancePatternType"];
                        }
                        if (guidanceGroupFeatures[0].Properties.ContainsKey("FieldId"))
                        {
                            fileNameGuidanceGroup = fileNameGuidanceGroup + "_for_field_" + guidanceGroupFeatures[0].Properties["FieldId"];
                        }
                        else if (guidanceGroupFeatures[0].Properties.ContainsKey("Guid"))
                        {
                            fileNameGuidanceGroup = fileNameGuidanceGroup + "_" + guidanceGroupFeatures[0].Properties["Guid"];
                        }
                        else
                        {
                            fileNameGuidanceGroup = fileNameGuidanceGroup + "_" + Guid.NewGuid();
                        }
                    }

                    _JsonExporter.WriteAsGeoJson(newPath, guidanceGroupFeatures, fileNameGuidanceGroup);
                }

                //Prescriptions (without gridType)
                List <Feature>     prescriptionFeatures       = new List <Feature>();
                List <Feature>     prescriptionFeaturesSingle = new List <Feature>();
                PrescriptionMapper prescriptionMapper         = new PrescriptionMapper(CustomProperties, dataModel);
                foreach (var workItemOperation in dataModel.Documents.WorkItemOperations)
                {
                    Console.WriteLine("WorkItemOperation: " + workItemOperation.Description + " OperationType " + workItemOperation.OperationType);

                    Prescription adaptPrescription = dataModel.Catalog.Prescriptions.Where(f => f.Id.ReferenceId == workItemOperation.PrescriptionId).FirstOrDefault();
                    if (adaptPrescription != null)
                    {
                        // single
                        var prescriptionFeature = prescriptionMapper.MapAsSingleFeature(adaptPrescription);
                        if (prescriptionFeature != null)
                        {
                            prescriptionFeature.Properties.Add("OperationType", Enum.GetName(typeof(OperationTypeEnum), workItemOperation.OperationType));                                      // Enum:
                            //workItemOperationFeature.Properties.Add("Description", workItemOperation.Description);
                            //workItemOperationFeature.Properties.Add("ID", workItemOperation.Id);
                            prescriptionFeaturesSingle.Add(prescriptionFeature);
                        }
                        else
                        {
                            Console.WriteLine("prescriptionFeature single null for: " + workItemOperation.PrescriptionId);
                        }

                        // multiple
                        var features = prescriptionMapper.MapAsMultipleFeatures(adaptPrescription);
                        if (features != null && features.Count > 0)
                        {
                            prescriptionFeatures.AddRange(features);
                        }
                        else
                        {
                            Console.WriteLine("prescriptionFeatures null or empty for: " + workItemOperation.PrescriptionId);
                        }
                    }
                    else
                    {
                        Console.WriteLine("adaptPrescription not found : " + workItemOperation.PrescriptionId);
                    }
                }

                // Todo: [Check] if all dataModel.Catalog.Prescriptions has been mapped
                if (dataModel.Catalog.Prescriptions.Count() != dataModel.Documents.WorkItemOperations.Count())
                {
                    Console.WriteLine("Count prescriptions and WorkItemOperations differ: " + dataModel.Catalog.Prescriptions.Count() + " " + dataModel.Documents.WorkItemOperations.Count());
                }
                //else
                //	Console.WriteLine("Count prescriptions and WorkItemOperations same: " + dataModel.Catalog.Prescriptions.Count() + " " + dataModel.Documents.WorkItemOperations.Count());

                string fileNamePs;
                // @ToDo only when count > 0?
                fileNamePs = PrescriptionMapper.GetWorkItemOperationPrefix();
                fileNamePs = fileNamePs + "_single_" + Guid.NewGuid();
                _JsonExporter.WriteAsGeoJson(newPath, prescriptionFeaturesSingle, fileNamePs);

                string fileNamePm;
                fileNamePm = PrescriptionMapper.GetWorkItemOperationPrefix();
                fileNamePm = fileNamePm + "_" + Guid.NewGuid();
                _JsonExporter.WriteAsGeoJson(newPath, prescriptionFeatures, fileNamePm);

                // LoggedData
                OperationTimelogMapper operationTimelogMapper = new OperationTimelogMapper(CustomProperties, dataModel);

                // starting from workRecords --> Not doing this as some loggedData may have not been referenced in a workrecord; we want to catch all logged data in the adm
                // starting from LoggedData
                foreach (var loggedData in dataModel.Documents.LoggedData)
                {
                    foreach (OperationData operation in loggedData.OperationData)
                    {
                        Console.WriteLine("OperationTimelog - operationData: " + operation.Id.ReferenceId + " " + operation.OperationType + " maxDepth " + operation.MaxDepth);

                        IEnumerable <SpatialRecord> spatialRecords = operation.GetSpatialRecords != null?operation.GetSpatialRecords() : null;

                        if (spatialRecords != null && spatialRecords.Any())                                 //No need to export a timelog if no data
                        {
                            var operationTimelogFeatures = operationTimelogMapper.MapMultiple(operation, spatialRecords);



                            string fileNameL = OperationTimelogMapper.GetPrefix() + "_" + operation.OperationType + "_" + Guid.NewGuid();
                            _JsonExporter.WriteAsGeoJson(newPath, operationTimelogFeatures, fileNameL);
                        }
                    }
                }

                break;                         // Default ApplyingAnonymiseValuesPer switch
            }
        }
        public static void Export(string path)
        {
            ApplicationDataModel adm = new ApplicationDataModel();

            adm.Catalog   = new Catalog();
            adm.Documents = new Documents();

            //--------------------------
            //Setup information
            //--------------------------
            //Add a crop
            Crop corn = new Crop()
            {
                Name = "Corn"
            };

            adm.Catalog.Crops.Add(corn);

            //Add some seed varieties
            CropVarietyProduct seedVariety1 = new CropVarietyProduct()
            {
                CropId = corn.Id.ReferenceId, Description = "Variety 1"
            };
            CropVarietyProduct seedVariety2 = new CropVarietyProduct()
            {
                CropId = corn.Id.ReferenceId, Description = "Variety 2"
            };

            adm.Catalog.Products.Add(seedVariety1);
            adm.Catalog.Products.Add(seedVariety2);

            //Add a liquid product
            CropNutritionProduct fertilizer = new CropNutritionProduct()
            {
                Description = "Starter", Form = ProductFormEnum.Liquid
            };

            fertilizer.ProductType = ProductTypeEnum.Fertilizer;
            adm.Catalog.Products.Add(fertilizer);

            //Add a granular product
            CropProtectionProduct insecticide = new CropProtectionProduct()
            {
                Description = "Insecticide", Form = ProductFormEnum.Solid
            };

            insecticide.ProductType = ProductTypeEnum.Chemical;
            adm.Catalog.Products.Add(insecticide);

            //GFF
            Grower grower = new Grower()
            {
                Name = "Example Grower"
            };

            adm.Catalog.Growers.Add(grower);

            Farm farm = new Farm()
            {
                Description = "Example Farm", GrowerId = grower.Id.ReferenceId
            };

            adm.Catalog.Farms.Add(farm);

            Field field = new Field()
            {
                Description = "Example Field", FarmId = farm.Id.ReferenceId, GrowerId = grower.Id.ReferenceId
            };

            field.Area = GetNumericRepresentationValue(23d, "ha", "vrReportedFieldArea");
            adm.Catalog.Fields.Add(field);

            //Crop zone
            TimeScope season = new TimeScope()
            {
                DateContext = DateContextEnum.CropSeason, TimeStamp1 = new DateTime(2021, 1, 1)
            };
            CropZone cropZone = new CropZone()
            {
                CropId = corn.Id.ReferenceId, FieldId = field.Id.ReferenceId, TimeScopes = new List <TimeScope>()
                {
                    season
                }
            };

            adm.Catalog.CropZones.Add(cropZone);

            //Field boundary
            FieldBoundary boundary = new FieldBoundary()
            {
                SpatialData = new MultiPolygon()
                {
                    Polygons = new List <Polygon>()
                    {
                        new Polygon()
                        {
                            ExteriorRing = new LinearRing()
                            {
                                Points = new List <Point>()
                                {
                                    new Point()
                                    {
                                        X = -89.488565, Y = 40.478304
                                    },
                                    new Point()
                                    {
                                        X = -89.485439, Y = 40.478304
                                    },
                                    new Point()
                                    {
                                        X = -89.485439, Y = 40.475010
                                    },
                                    new Point()
                                    {
                                        X = -89.488565, Y = 40.475010
                                    }
                                }
                            },
                            InteriorRings = new List <LinearRing>()
                            {
                                new LinearRing()
                                {
                                    Points = new List <Point>()
                                    {
                                        new Point()
                                        {
                                            X = -89.487719, Y = 40.478091
                                        },
                                        new Point()
                                        {
                                            X = -89.487536, Y = 40.478091
                                        },
                                        new Point()
                                        {
                                            X = -89.487536, Y = 40.477960
                                        },
                                        new Point()
                                        {
                                            X = -89.487719, Y = 40.477960
                                        },
                                        new Point()
                                        {
                                            X = -89.487719, Y = 40.478091
                                        }
                                    }
                                },
                                new LinearRing()
                                {
                                    Points = new List <Point>()
                                    {
                                        new Point()
                                        {
                                            X = -89.486732, Y = 40.478172
                                        },
                                        new Point()
                                        {
                                            X = -89.486453, Y = 40.478172
                                        },
                                        new Point()
                                        {
                                            X = -89.486453, Y = 40.478082
                                        },
                                        new Point()
                                        {
                                            X = -89.486732, Y = 40.478082
                                        },
                                        new Point()
                                        {
                                            X = -89.486732, Y = 40.478172
                                        }
                                    }
                                }
                            }
                        }
                    }
                },
                FieldId = field.Id.ReferenceId
            };

            adm.Catalog.FieldBoundaries.Add(boundary);
            field.ActiveBoundaryId = boundary.Id.ReferenceId;

            //--------------------------
            //Prescription
            //--------------------------

            //Prescription setup data
            //Setup the representation and units for seed rate & seed depth prescriptions
            NumericRepresentation seedRate = GetNumericRepresentation("vrSeedRateSeedsTarget");
            UnitOfMeasure         seedUOM  = UnitInstance.UnitSystemManager.GetUnitOfMeasure("seeds1ac-1");
            RxProductLookup       seedVariety1RateLookup = new RxProductLookup()
            {
                ProductId = seedVariety1.Id.ReferenceId, Representation = seedRate, UnitOfMeasure = seedUOM
            };
            RxProductLookup seedVariety2RateLookup = new RxProductLookup()
            {
                ProductId = seedVariety2.Id.ReferenceId, Representation = seedRate, UnitOfMeasure = seedUOM
            };

            NumericRepresentation seedDepth = GetNumericRepresentation("vrSeedDepthTarget");
            UnitOfMeasure         depthUOM  = UnitInstance.UnitSystemManager.GetUnitOfMeasure("cm");
            RxProductLookup       seedVariety1DepthLookup = new RxProductLookup()
            {
                ProductId = seedVariety1.Id.ReferenceId, Representation = seedDepth, UnitOfMeasure = depthUOM
            };
            RxProductLookup seedVariety2DepthLookup = new RxProductLookup()
            {
                ProductId = seedVariety2.Id.ReferenceId, Representation = seedDepth, UnitOfMeasure = depthUOM
            };

            //Setup liquid rx representation/units
            NumericRepresentation fertilizerRate       = GetNumericRepresentation("vrAppRateVolumeTarget");
            UnitOfMeasure         fertilizerUOM        = UnitInstance.UnitSystemManager.GetUnitOfMeasure("gal1ac-1");
            RxProductLookup       fertilizerRateLookup = new RxProductLookup()
            {
                ProductId = fertilizer.Id.ReferenceId, Representation = fertilizerRate, UnitOfMeasure = fertilizerUOM
            };

            //Setup granular rx representation/units
            NumericRepresentation insecticideRate       = GetNumericRepresentation("vrAppRateMassTarget");
            UnitOfMeasure         insecticideUOM        = UnitInstance.UnitSystemManager.GetUnitOfMeasure("lb1ac-1");
            RxProductLookup       insecticideRateLookup = new RxProductLookup()
            {
                ProductId = insecticide.Id.ReferenceId, Representation = insecticideRate, UnitOfMeasure = insecticideUOM
            };


            //Prescription zones
            //Zone 1 - Variety 1 at 32000 seeds/acre, 4 cm depth target; Starter at 7 gal/ac; Insecticide at 5 lb/ac
            RxShapeLookup zone1 = new RxShapeLookup()
            {
                Rates = new List <RxRate>()
                {
                    new RxRate()
                    {
                        Rate = 32000d,
                        RxProductLookupId = seedVariety1RateLookup.Id.ReferenceId
                    },
                    new RxRate()
                    {
                        Rate = 4d,
                        RxProductLookupId = seedVariety1DepthLookup.Id.ReferenceId
                    },
                    new RxRate()
                    {
                        Rate = 7d,
                        RxProductLookupId = fertilizerRateLookup.Id.ReferenceId
                    },
                    new RxRate()
                    {
                        Rate = 5d,
                        RxProductLookupId = insecticideRateLookup.Id.ReferenceId
                    }
                },
                Shape = new MultiPolygon()
                {
                    Polygons = new List <Polygon>()
                    {
                        new Polygon()
                        {
                            ExteriorRing = new LinearRing()
                            {
                                Points = new List <Point>()
                                {
                                    new Point()
                                    {
                                        X = -89.488565, Y = 40.478304
                                    },
                                    new Point()
                                    {
                                        X = -89.485439, Y = 40.478304
                                    },
                                    new Point()
                                    {
                                        X = -89.485439, Y = 40.477404
                                    },
                                    new Point()
                                    {
                                        X = -89.488565, Y = 40.477756
                                    },
                                    new Point()
                                    {
                                        X = -89.488565, Y = 40.478304
                                    }
                                }
                            },
                            InteriorRings = new List <LinearRing>()
                            {
                                new LinearRing()
                                {
                                    Points = new List <Point>()
                                    {
                                        new Point()
                                        {
                                            X = -89.487719, Y = 40.478091
                                        },
                                        new Point()
                                        {
                                            X = -89.487536, Y = 40.478091
                                        },
                                        new Point()
                                        {
                                            X = -89.487536, Y = 40.477960
                                        },
                                        new Point()
                                        {
                                            X = -89.487719, Y = 40.477960
                                        },
                                        new Point()
                                        {
                                            X = -89.487719, Y = 40.478091
                                        }
                                    }
                                },
                                new LinearRing()
                                {
                                    Points = new List <Point>()
                                    {
                                        new Point()
                                        {
                                            X = -89.486732, Y = 40.478172
                                        },
                                        new Point()
                                        {
                                            X = -89.486453, Y = 40.478172
                                        },
                                        new Point()
                                        {
                                            X = -89.486453, Y = 40.478082
                                        },
                                        new Point()
                                        {
                                            X = -89.486732, Y = 40.478082
                                        },
                                        new Point()
                                        {
                                            X = -89.486732, Y = 40.478172
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            };

            //Zone 2 - Variety 1 at 34000 seeds/acre, depth target 5cm; Starter at 4 gal/ac; Insecticide at 2.5 lb/ac
            RxShapeLookup zone2 = new RxShapeLookup()
            {
                Rates = new List <RxRate>()
                {
                    new RxRate()
                    {
                        Rate = 34000d,
                        RxProductLookupId = seedVariety1RateLookup.Id.ReferenceId
                    },
                    new RxRate()
                    {
                        Rate = 5d,
                        RxProductLookupId = seedVariety1DepthLookup.Id.ReferenceId
                    },
                    new RxRate()
                    {
                        Rate = 4d,
                        RxProductLookupId = fertilizerRateLookup.Id.ReferenceId
                    },
                    new RxRate()
                    {
                        Rate = 2.5,
                        RxProductLookupId = insecticideRateLookup.Id.ReferenceId
                    }
                },
                Shape = new MultiPolygon()
                {
                    Polygons = new List <Polygon>()
                    {
                        new Polygon()
                        {
                            ExteriorRing = new LinearRing()
                            {
                                Points = new List <Point>()
                                {
                                    new Point()
                                    {
                                        X = -89.488565, Y = 40.477756
                                    },
                                    new Point()
                                    {
                                        X = -89.485439, Y = 40.477404
                                    },
                                    new Point()
                                    {
                                        X = -89.485439, Y = 40.476688
                                    },
                                    new Point()
                                    {
                                        X = -89.488565, Y = 40.476688
                                    },
                                    new Point()
                                    {
                                        X = -89.488565, Y = 40.477756
                                    }
                                }
                            }
                        }
                    }
                }
            };

            //Zone 3 - Variety 2 at 29000 seeds/acre, depth target 6 cm; Starter at 6 gal/ac ; Insecticide at 2.75 lb/ac
            RxShapeLookup zone3 = new RxShapeLookup()
            {
                Rates = new List <RxRate>()
                {
                    new RxRate()
                    {
                        Rate = 29000d,
                        RxProductLookupId = seedVariety2RateLookup.Id.ReferenceId
                    },
                    new RxRate()
                    {
                        Rate = 6d,
                        RxProductLookupId = seedVariety2DepthLookup.Id.ReferenceId
                    },
                    new RxRate()
                    {
                        Rate = 6d,
                        RxProductLookupId = fertilizerRateLookup.Id.ReferenceId
                    },
                    new RxRate()
                    {
                        Rate = 2.75,
                        RxProductLookupId = insecticideRateLookup.Id.ReferenceId
                    }
                },
                Shape = new MultiPolygon()
                {
                    Polygons = new List <Polygon>()
                    {
                        new Polygon()
                        {
                            ExteriorRing = new LinearRing()
                            {
                                Points = new List <Point>()
                                {
                                    new Point()
                                    {
                                        X = -89.488565, Y = 40.476688
                                    },
                                    new Point()
                                    {
                                        X = -89.485439, Y = 40.476688
                                    },
                                    new Point()
                                    {
                                        X = -89.485439, Y = 40.475010
                                    },
                                    new Point()
                                    {
                                        X = -89.488565, Y = 40.475010
                                    },
                                    new Point()
                                    {
                                        X = -89.488565, Y = 40.476688
                                    }
                                }
                            }
                        }
                    }
                }
            };

            //Assembled Rx
            VectorPrescription vectorPrescription = new VectorPrescription()
            {
                Description      = "Test Prescription",
                RxProductLookups = new List <RxProductLookup>()
                {
                    seedVariety1RateLookup,
                    seedVariety2RateLookup,
                    fertilizerRateLookup,
                    seedVariety1DepthLookup,
                    seedVariety2DepthLookup,
                    insecticideRateLookup
                },
                RxShapeLookups = new List <RxShapeLookup>()
                {
                    zone1, zone2, zone3
                },
                CropZoneId = cropZone.Id.ReferenceId,
                FieldId    = field.Id.ReferenceId
            };

            (adm.Catalog.Prescriptions as List <Prescription>).Add(vectorPrescription);

            //--------------------------
            //Export data to file via the Plugin
            //--------------------------
            PrecisionPlanting.ADAPT._2020.Plugin plugin = new Plugin();
            plugin.Export(adm, path);
        }
예제 #17
0
        //For a graphical user interface, clone https://github.com/ADAPT/ADAPT-Visualizer and follow the usage instructions in http://2020.ag/developers.html
        //This example code provides examples specific to data populated into the ADAPT model by the 2020 Plugin.

        static void Main()
        {
            Console.WriteLine();

            // set arguments below
            //Arg 0 - path to data
            //-5: 5hz data frequency
            //-1: 1hz data frequency (default)
            //-all: include all optional data (default is none)
            string[] args       = new string[] { @".\consoleApp\sampleData", "-5", "-all" }; //Console.ReadLine().Split(' ');
            string   dirToWrite = @"XXX file_path where to write csv files";

            Console.WriteLine($"The arguments are {string.Join(" ", args)}. Change in Program.cs line 27 if needed");
            Console.WriteLine($"Data will be written to {dirToWrite}");
            string dataPath = args.Any() ? args[0] : null;

            while (!Directory.Exists(dataPath))
            {
                Console.WriteLine("Input is not a valid directory path.   Try again.");
                dataPath = Console.ReadLine();
            }

            Console.WriteLine("Looking for data...");

            //Instantiate the 2020 plugin
            PrecisionPlanting.ADAPT._2020.Plugin _2020Plugin = new PrecisionPlanting.ADAPT._2020.Plugin();

            //Load any properties to customize the data import
            Properties pluginProperties = GetPluginProperties(args);

            //Import data from the given path.
            IList <ApplicationDataModel> admObjects = _2020Plugin.Import(dataPath, pluginProperties);

            if (admObjects != null && admObjects.Any())
            {
                //A 2020 Plugin import will always contain 1 ApplicationDataModel (ADM) object.    All data in the import path is included within this object.
                //The ADAPT Framework Plugin Import method returns a list of ADM objects to support other industry data types (e.g., ISOXML)
                //where there is a concept of multiple wholly-contained datasets in a given file path.
                ApplicationDataModel adm = admObjects.Single();

                //The Catalog contains definition data for this import
                Catalog catalog = adm.Catalog;

                //The LoggedDataobject corresponds to a single 2020 file and defines one or more operations on a particular field.
                int loggedDataCount = adm.Documents.LoggedData.Count();
                if (loggedDataCount > 0)
                {
                    //loop through files of the input data folder
                    foreach (LoggedData loggedata in adm.Documents.LoggedData)
                    {
                        string CSVfilename = SetupData.DescribeLogisticsData(catalog, loggedata);

                        //loop through 20|20 file and create one csv per opdata
                        foreach (OperationData opdata in loggedata.OperationData)
                        {
                            //Make a dictionary of product names
                            // Dictionary<int, string> productNames = new Dictionary<int, string>();
                            // foreach (int productID in opdata.ProductIds)
                            // {

                            //     List<DeviceElementUse> productDeviceElementUses = new List<DeviceElementUse>();
                            //     Product product = catalog.Products.First(p => p.Id.ReferenceId == productID);
                            //     Console.WriteLine(productID);
                            //     productNames.Add(productID, product.Description);
                            // }
                            // Console.WriteLine($"The following varieties are planted at various points in the field: {string.Join(", ", productNames.Values)}");

                            List <SpatialRecord> spatialRecords = new List <SpatialRecord>();
                            if (opdata.GetSpatialRecords != null)
                            {
                                spatialRecords = opdata.GetSpatialRecords().ToList(); //Iterate the records once here for multiple consumers below
                            }

                            DataTable         data     = new DataTable();
                            ExportSpatialData exporter = new ExportSpatialData();
                            data = exporter.ProcessOperationData(opdata, spatialRecords);

                            string filepath = $"{dirToWrite}{CSVfilename}.csv";

                            int c = 1;
                            while (File.Exists(filepath))
                            {
                                filepath = $"{dirToWrite}{CSVfilename}_{c}.csv";
                                c++;
                            }
                            Console.WriteLine(filepath);
                            data.ToCsv(filepath);
                        }
                    }
                }

                Console.WriteLine("Done");

                Console.ReadLine();
            }
            else
            {
                Console.WriteLine("No data found");
                Console.ReadLine();
            }
        }
        //For a graphical user interface, clone https://github.com/ADAPT/ADAPT-Visualizer and follow the usage instructions in http://2020.ag/developers.html
        //This example code provides examples specific to data populated into the ADAPT model by the 2020 Plugin.

        //Import 20|20 data arguments:
        //Arg 0 - "-import"
        //Arg 1 - path to data for import
        //Optional args
        //-5: 5hz data frequency
        //-1: 1hz data frequency (default)
        //-all: include all optional data (default is none)

        //Export 20|20 data arguments
        //Arg 0 - "-export"
        //Arg 1 - path to export sample prescriptions/setup data
        static void Main(string[] args)
        {
            Console.WriteLine("Precision Planting 20|20 ADAPT Plugin Example Code");
            if (!args.Any() || args.Count() < 2)
            {
                Console.WriteLine();
                Console.WriteLine("Import Usage: -import {path to 20|20 data} optional args");
                Console.WriteLine("Export Usage: -export {export path}");
                Console.WriteLine();
                Console.WriteLine("Please enter required arguments");
                args = Console.ReadLine().Split(' ');
            }


            //Instantiate the 2020 plugin
            PrecisionPlanting.ADAPT._2020.Plugin _2020Plugin = new Plugin();
            string dataPath = args[1];

            if (args.Contains("-import"))
            {
                //Load any properties to customize the data import
                Properties pluginProperties = GetPluginProperties(args);

                //Import data from the given path.
                IList <ApplicationDataModel> admObjects = _2020Plugin.Import(dataPath, pluginProperties);

                if (admObjects != null && admObjects.Any())
                {
                    //A 2020 Plugin import will always contain 1 ApplicationDataModel (ADM) object.    All data in the import path is included within this object.
                    //The ADAPT Framework Plugin Import method returns a list of ADM objects to support other industry data types (e.g., ISOXML)
                    //where there is a concept of multiple wholly-contained datasets in a given file path.
                    ApplicationDataModel adm = admObjects.Single();

                    //The Catalog contains definition data for this import
                    Catalog catalog = adm.Catalog;

                    //The LoggedDataobject corresponds to a single 2020 file and defines one or more operations on a particular field.
                    int loggedDataCount = adm.Documents.LoggedData.Count();
                    if (loggedDataCount > 0)
                    {
                        LoggedData exampleLoggedData = adm.Documents.LoggedData.First();
                        if (loggedDataCount > 1)
                        {
                            Console.WriteLine("This dataset contains multiple 2020 files.   Illustrating data from the first file only.");
                            Console.WriteLine();
                        }

                        //Grower, Farm, Field, and Crop illustration.
                        SetupData.DescribeLogisticsData(catalog, exampleLoggedData);

                        //Operation Types, Regions and Product illustration
                        OperationTypeData.DescribeTypeRegionProduct(catalog, exampleLoggedData);

                        //Task Summary illustration
                        SummaryData.DescribeSummaryData(adm, exampleLoggedData);

                        //Implement illustration
                        ImplementData.DescribeImplement(catalog, exampleLoggedData);

                        //Spatial Data illustration, including discussion of multivariety, ADAPT representations and Units of Measure
                        SpatialData.DescribeSpatialData(catalog, exampleLoggedData);
                    }

                    Console.WriteLine("Done");

                    Console.ReadLine();
                }
                else
                {
                    Console.WriteLine("No data found");
                    Console.ReadLine();
                }
            }
            else if (args.Contains("-export"))
            {
                //Export the sample 2020 file
                ExportData.Export(dataPath);
                Directory.CreateDirectory(dataPath);
                Console.WriteLine($"File written to {dataPath}");
            }
        }
예제 #19
0
 public static void AreEqual(XmlNode taskData, ApplicationDataModel applicationDataModel, string currentPath, Dictionary <string, List <UniqueId> > linkList)
 {
     CatalogAssert.AreEqual(taskData, applicationDataModel.Catalog, linkList);
     DocumentsAssert.AreEqual(taskData, applicationDataModel.Documents, applicationDataModel.Catalog, currentPath);
 }
예제 #20
0
        public void SetData(ApplicationDataModel item)
        {
            SystemKeyId = item.ApplicationId;

            base.SetData(item);
        }
예제 #21
0
 public GuidanceGroupMapper(PluginProperties properties, ApplicationDataModel dataModel)
 {
     this._properties = properties;
     this._dataModel  = dataModel;
 }
예제 #22
0
 public OperationTimelogMapper(PluginProperties properties, ApplicationDataModel dataModel = null)
 {
     _dataModel  = dataModel;
     _properties = properties;
 }
예제 #23
0
        private async Task <FieldTotals> CalculateFieldTotals(Field catalogField, ApplicationDataModel dataModel)
        {
            var operationTotals = await _operationTotalsCalculator.Calculate(catalogField, dataModel);

            return(new FieldTotals(catalogField.Description, operationTotals));
        }
예제 #24
0
 public void Put(int id, ApplicationDataModel obj)
 {
     Shared.WebCommon.UI.Web.ApplicationCommon.ResetApplicationCache(obj.Code);
 }
예제 #25
0
        public void LoadData(int fieldConfigurationId, bool showId)
        {
            // clear UI
            Clear();

            // set up parameters
            var data = new FieldConfigurationDataModel();

            data.FieldConfigurationId = fieldConfigurationId;

            // get data
            var items = FieldConfigurationDataManager.GetEntityDetails(data, SessionVariables.RequestProfile, ApplicationCommon.ReturnAuditInfo);

            // should only have single match
            if (items.Count != 1)
            {
                return;
            }

            var item = items[0];

            txtFieldConfigurationId.Text = item.FieldConfigurationId.ToString();
            txtName.Text        = item.Name;
            txtApplication.Text = item.ApplicationId.ToString();

            txtSystemEntityTypeId.Text            = item.SystemEntityTypeId.ToString();
            drpSystemEntityTypeList.SelectedValue = item.SystemEntityTypeId.ToString();
            txtDisplayName.Text                     = item.FieldConfigurationDisplayName;
            txtName.Text                            = item.Name;
            txtValue.InnerText                      = item.Value;
            txtWidth.Text                           = item.Width.ToString();
            txtFormatting.Text                      = item.Formatting;
            txtControlType.Text                     = item.ControlType;
            txtHorizontalAlignment.Text             = item.HorizontalAlignment;
            txtGridViewPriority.Text                = item.GridViewPriority.ToString();
            txtDetailsViewPriority.Text             = item.DetailsViewPriority.ToString();
            ddlFieldConfigurationMode.SelectedValue = item.FieldConfigurationModeId.ToString();
            txtFieldConfigurationMode.Text          = item.FieldConfigurationModeId.ToString();
            txtDisplayColumn.Text                   = item.DisplayColumn.ToString();
            txtCellCount.Text                       = item.CellCount.ToString();

            var applicationData = new ApplicationDataModel();

            applicationData.ApplicationId = item.ApplicationId;
            var appDatas = ApplicationDataManager.GetDetails(applicationData, SessionVariables.RequestProfile);

            //drpApplicationList.SelectedValue = appDatas.Rows[0][ApplicationDataModel.DataColumns.Name].ToString();
            if (!showId)
            {
                txtFieldConfigurationId.Text = item.FieldConfigurationId.ToString();

                txtDisplayName.Enabled = false;

                //PlaceHolderAuditHistory.Visible = true;
                // only show Audit History in case of Update page, not for Clone.
                oHistoryList.Setup(PrimaryEntity, fieldConfigurationId, PrimaryEntityKey);
            }
            else
            {
                txtFieldConfigurationId.Text = String.Empty;
            }

            //oUpdateInfo.LoadText(item.UpdatedDate, item.UpdatedBy, item.LastAction);
        }
 public static IEnumerable <LoggedData> GetLoggedData(this ApplicationDataModel dataModel)
 {
     return(dataModel.Documents == null
         ? Enumerable.Empty <LoggedData>()
         : dataModel.Documents.LoggedData);
 }
예제 #27
0
 public ExportArgs(ApplicationDataModel dataModel, string exportPath, Properties properties)
 {
     DataModel  = dataModel;
     ExportPath = exportPath;
     Properties = properties;
 }
 public static IEnumerable <FieldBoundary> GetFieldBoundaries(this ApplicationDataModel dataModel, Field field)
 {
     return(dataModel.Catalog?.FieldBoundaries != null
         ? dataModel.Catalog.FieldBoundaries.Where(b => b.FieldId == field.Id.ReferenceId)
         : Enumerable.Empty <FieldBoundary>());
 }
예제 #29
0
        public static void Update(ApplicationDataModel data, RequestProfile requestProfile)
        {
            var sql = CreateOrUpdate(data, requestProfile, "Update");

            DataAccess.DBDML.RunSQL("Application.Update", sql, DataStoreKey);
        }
예제 #30
0
 public CenterPivotMapper(PluginProperties properties, ApplicationDataModel dataModel, Dictionary <string, object> featProps)
 {
     this._properties = properties;
     this._dataModel  = dataModel;
     this._featProps  = featProps;
 }
예제 #31
0
        //public static List<ApplicationDataModel> GetApplicationList(RequestProfile requestProfile)
        //{
        //	var sql = "EXEC dbo.ApplicationSearch " +
        //	   " " + ToSQLParameter(BaseDataModel.BaseDataColumns.AuditId, requestProfile.AuditId);

        //	var result = new List<ApplicationDataModel>();

        //	using (var reader = new DBDataReader("Get List", sql, DataStoreKey))
        //	{
        //		var dbReader = reader.DBReader;

        //		while (dbReader.Read())
        //		{
        //			var dataItem = new ApplicationDataModel();

        //			dataItem.ApplicationId = (int)dbReader[ApplicationDataModel.DataColumns.ApplicationId];

        //			SetStandardInfo(dataItem, dbReader);

        //			result.Add(dataItem);
        //		}
        //	}

        //	return result;
        //}

        #endregion

        #region GetDetails

        public static ApplicationDataModel GetDetails(ApplicationDataModel data, RequestProfile requestProfile)
        {
            var list = GetEntityDetails(data, requestProfile, 1);

            return(list.FirstOrDefault());
        }
예제 #32
0
파일: MainForm.cs 프로젝트: ranec/ADAPT
        private void ImportDataCard(IPlugin plugin, string datacardPath)
        {
            _treeViewMetadata.Nodes.Clear();

            _applicationDataModel = plugin.Import(datacardPath);

            var parentNode = _treeViewMetadata.Nodes.Add("ApplicationDataModel");
            AddNode(_applicationDataModel, parentNode);
        }
예제 #33
0
 public PluginDataModel(string pluginName, string pluginVersion, ApplicationDataModel dataModel)
 {
     PluginName    = pluginName;
     PluginVersion = pluginVersion;
     DataModel     = dataModel;
 }