Ejemplo n.º 1
0
        private static void AssociateWorkItemWithWorkOrder(TSK task, ApplicationDataModel.ADM.ApplicationDataModel dataModel, WorkOrder workOrder)
        {
            var fieldId  = workOrder.FieldIds.FirstOrDefault();
            var workItem = new WorkItem
            {
                GrowerId = workOrder.GrowerId,
                FarmId   = workOrder.FarmIds.FirstOrDefault(),
                FieldId  = fieldId,
            };

            if (fieldId != 0)
            {
                var field = dataModel.Catalog.Fields.Single(f => f.Id.ReferenceId == fieldId);
                if (field.ActiveBoundaryId != 0)
                {
                    workItem.BoundaryId = field.ActiveBoundaryId;
                }
            }

            dataModel.Documents.WorkItems = dataModel.Documents.WorkItems.Concat(new[] { workItem });
            workOrder.WorkItemIds         = new List <int> {
                workItem.Id.ReferenceId
            };

            if (task.Items != null && task.Items.OfType <TZN>().Any())
            {
                AssociateRxWithWorkItem(task, dataModel, workItem);
            }
        }
Ejemplo n.º 2
0
        public static void Export(IPlugin plugin,
                                  ApplicationDataModel.ADM.ApplicationDataModel applicationDataModel,
                                  string initializeString,
                                  string exportPath,
                                  ApplicationDataModel.ADM.Properties properties)
        {
            InitializePlugin(plugin, initializeString);

            plugin.Export(applicationDataModel, exportPath, properties);
        }
Ejemplo n.º 3
0
        public void GivenPluginAndCardPathWhenExportThenAdmSerializerSerializeCalled()
        {
            var dataModel = new ApplicationDataModel.ADM.ApplicationDataModel();

            var plugin = new Plugin(_admSerializerMock.Object);

            plugin.Export(dataModel, _cardPath);

            _admSerializerMock.Verify(x => x.Serialize(dataModel, _cardPath));
        }
Ejemplo n.º 4
0
        public IEnumerable <TSK> Map(IEnumerable <WorkOrder> workOrders, ApplicationDataModel.ADM.ApplicationDataModel dataModel, int numberOfExistingTasks, TaskDocumentWriter writer)
        {
            if (workOrders == null)
            {
                yield break;
            }

            foreach (var workOrder in workOrders)
            {
                numberOfExistingTasks++;
                yield return(Map(workOrder, dataModel, numberOfExistingTasks, writer));
            }
        }
Ejemplo n.º 5
0
        public Documents Map(List <TSK> tsks, string dataPath, ApplicationDataModel.ADM.ApplicationDataModel dataModel, Dictionary <string, List <UniqueId> > linkedIds)
        {
            var tasksWithLoggedData = tsks.Where(task => task.Items != null && task.Items.OfType <TLG>().Any()).ToList();

            _loggedDataMapper.Map(tasksWithLoggedData, dataPath, dataModel, linkedIds);

            var tasksWithoutLogData = tsks.Where(task => task.Items == null || !task.Items.OfType <TLG>().Any()).ToList();
            var workOrders          = _workOrderMapper.Map(tasksWithoutLogData, dataModel);

            dataModel.Documents.WorkOrders = workOrders;

            return(dataModel.Documents);
        }
Ejemplo n.º 6
0
        public void GivenPluginAndDataModelWhenExportThenCatalogFileIsWritten()
        {
            var dataModel = new ApplicationDataModel.ADM.ApplicationDataModel
            {
                Catalog = new Catalog()
            };

            _plugin.Export(dataModel, _tempPath);

            var fileExists = File.Exists(Path.Combine(_tempPath, "adm", "Catalog.adm"));

            Assert.IsTrue(fileExists);
        }
Ejemplo n.º 7
0
        private static void AssociateRxWithWorkItem(TSK task, ApplicationDataModel.ADM.ApplicationDataModel dataModel, WorkItem workItem)
        {
            var matchingRx = dataModel.Catalog.Prescriptions.SingleOrDefault(p => p.Id.FindIsoId() == task.A);

            if (matchingRx != null)
            {
                var operation = new WorkItemOperation();
                operation.PrescriptionId = matchingRx.Id.ReferenceId;
                dataModel.Documents.WorkItemOperations = dataModel.Documents.WorkItemOperations.Concat(new[] { operation });
                workItem.WorkItemOperationIds          = new List <int> {
                    operation.Id.ReferenceId
                };
            }
        }
Ejemplo n.º 8
0
        void IPlugin.Export(ApplicationDataModel.ADM.ApplicationDataModel dataModel, string exportPath, Properties properties)
        {
            //Convert the ADAPT model into the ISO model
            string            outputPath     = exportPath.WithTaskDataPath();
            TaskDataMapper    taskDataMapper = new TaskDataMapper(outputPath, properties);
            ISO11783_TaskData taskData       = taskDataMapper.Export(dataModel);

            //Serialize the ISO model to XML
            TaskDocumentWriter writer = new TaskDocumentWriter();

            writer.WriteTaskData(exportPath, taskData);

            //Serialize the Link List
            writer.WriteLinkList(exportPath, taskData.LinkList);
        }
Ejemplo n.º 9
0
        public void Serialize(ApplicationDataModel.ADM.ApplicationDataModel dataModel, string path)
        {
            var dataPath = Path.Combine(path, DatacardConstants.DataFolder);

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

            _propriataryValuesSerializer.Serialize(GetPropriataryValuesBaseSerializer(_defaultSerializationVersion), dataModel.ProprietaryValues, dataPath);
            _documentsSerializer.Serialize(GetDocumentsBaseSerializer(_defaultSerializationVersion), dataModel.Documents, dataPath);
            _catalogSerializer.Serialize(GetCatalogBaseSerializer(_defaultSerializationVersion), dataModel.Catalog, dataPath);
            _referenceLayersSerializer.Serialize(GetReferenceLayersBaseSerializer(_defaultSerializationVersion), dataModel.ReferenceLayers, dataPath);
            _versionSerializer.Serialize(_defaultSerializationVersion, dataPath);
        }
Ejemplo n.º 10
0
        public IList <ApplicationDataModel.ADM.ApplicationDataModel> Import(string dataPath, Properties properties = null)
        {
            IList <ApplicationDataModel.ADM.ApplicationDataModel> models = new List <ApplicationDataModel.ADM.ApplicationDataModel>();

            List <IError> errors = new List <IError>();

            List <string> fileNames = GetInputFiles(dataPath);

            fileNames.Sort(); // required to ensure OS file system sorting differences are handled

            foreach (string fileName in fileNames)
            {
                try
                {
                    string jsonText = File.ReadAllText(fileName);

                    Model.Document document = JsonConvert.DeserializeObject <Model.Document>(jsonText);
                    if (document.ShippedItemInstances != null)
                    {
                        //Each document will import as individual ApplicationDataModel
                        ApplicationDataModel.ADM.ApplicationDataModel adm = new ApplicationDataModel.ADM.ApplicationDataModel();
                        adm.Catalog = new Catalog()
                        {
                            Description = fileName
                        };

                        //Map the document data into the Catalog
                        Mapper mapper = new Mapper(adm.Catalog);
                        errors.AddRange(mapper.MapDocument(document));

                        models.Add(adm);
                    }
                    else
                    {
                        errors.Add(new Error(null, $"Importing {fileName}", "Couldn't parse ShippedItemInstances", null));
                    }
                }
                catch (Exception ex)
                {
                    errors.Add(new Error(null, $"Exception Importing {fileName}", ex.Message, ex.StackTrace));
                }
            }

            //Read the Errors property after import to inspect any diagnostic messages.
            Errors = errors;

            return(models);
        }
Ejemplo n.º 11
0
        public void Setup()
        {
            _tempPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());

            _dataModel = new ApplicationDataModel.ADM.ApplicationDataModel();
            _dataModel.ProprietaryValues = new List <ProprietaryValue>();
            _dataModel.Catalog           = new Catalog();
            _dataModel.Documents         = new Documents();
            _dataModel.ReferenceLayers   = new List <ReferenceLayer>();

            _versionSerializerMock           = new Mock <IVersionInfoSerializer>();
            _propriataryValuesSerializerMock = new Mock <ISerializer <List <ProprietaryValue> > >();
            _catalogSearializerMock          = new Mock <ISerializer <Catalog> >();
            _documentsSerializerMock         = new Mock <ISerializer <Documents> >();
            _referenceLayersSerializerMock   = new Mock <ISerializer <IEnumerable <ReferenceLayer> > >();
        }
Ejemplo n.º 12
0
        public void Export(ApplicationDataModel.ADM.ApplicationDataModel dataModel, string exportPath, Properties properties = null)
        {
            using (var taskWriter = new TaskDocumentWriter())
            {
                var taskDataPath     = Path.Combine(exportPath, "TASKDATA");
                var iso11783TaskData = _exporter.Export(dataModel, taskDataPath, taskWriter);

                var filePath = Path.Combine(taskDataPath, FileName);
                if (iso11783TaskData != null)
                {
                    var xml = Encoding.UTF8.GetString(taskWriter.XmlStream.ToArray());
                    File.WriteAllText(filePath, xml);
                    LinkListWriter.Write(taskDataPath, taskWriter.Ids);
                }
            }
        }
Ejemplo n.º 13
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);
        }
Ejemplo n.º 14
0
        public void GivenPluginAndDataModelWhenExportThenVersionFileIsWritten()
        {
            var dataModel = new ApplicationDataModel.ADM.ApplicationDataModel
            {
                ReferenceLayers = new List <ReferenceLayer>
                {
                    new RasterReferenceLayer(),
                    new ShapeReferenceLayer()
                }
            };

            _plugin.Export(dataModel, _tempPath);

            var expectedFilename = Path.Combine(_tempPath, DatacardConstants.PluginFolderAndExtension, AdmVersionFilename);

            _admVersionInfoWriterMock.Verify(x => x.WriteVersionInfoFile(expectedFilename), Times.Once);
        }
Ejemplo n.º 15
0
        public void GivenPluginAndDataModelWhenExportThenReferenceLayersFileIsWritten()
        {
            var dataModel = new ApplicationDataModel.ADM.ApplicationDataModel
            {
                ReferenceLayers = new List <ReferenceLayer>
                {
                    new RasterReferenceLayer(),
                    new ShapeReferenceLayer()
                }
            };

            _plugin.Export(dataModel, _tempPath);
            var filepath = Path.Combine(_tempPath, "adm");
            var filename = "ReferenceLayers.adm";

            _protobufReferenceSerializerMock.Verify(x => x.Export(filepath, filename, dataModel.ReferenceLayers));
        }
Ejemplo n.º 16
0
        private void AssociatePersonWithWorkOrder(TSK task, ApplicationDataModel.ADM.ApplicationDataModel dataModel, WorkOrder workOrder)
        {
            var person = dataModel.Catalog.Persons.SingleOrDefault(p => p.Id.FindIsoId() == task.F);

            if (person != null)
            {
                var personRole = new PersonRole {
                    PersonId = person.Id.ReferenceId, Role = new EnumeratedValue {
                        Representation = RepresentationInstanceList.dtPersonRole.ToModelRepresentation(), Value = DefinedTypeEnumerationInstanceList.dtiPersonRoleOperator.ToModelEnumMember()
                    }
                };
                dataModel.Catalog.PersonRoles.Add(personRole);
                workOrder.PersonRoleIds = new List <int> {
                    personRole.Id.ReferenceId
                };
            }
        }
Ejemplo n.º 17
0
        public void Export(ApplicationDataModel.ADM.ApplicationDataModel dataModel, string exportPath, Properties properties = null)
        {
            var path = Path.Combine(exportPath, DatacardConstants.PluginFolderAndExtension);

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

            var versionFile = Path.Combine(path, AdmVersionFilename);

            _admVersionInfoWriter.WriteVersionInfoFile(versionFile);

            _documentsExporter.ExportDocuments(path, dataModel.Documents);
            ExportReferenceLayers(path, ReferencelayersAdm, dataModel.ReferenceLayers);
            ExportData(path, ProprietaryValuesAdm, dataModel.ProprietaryValues);
            ExportData(path, CatalogAdm, dataModel.Catalog);
        }
Ejemplo n.º 18
0
        public void GivenPluginAndDataModelWhenExportThenProprietaryValuesFileIsWritten()
        {
            var dataModel = new ApplicationDataModel.ADM.ApplicationDataModel
            {
                ProprietaryValues = new List <ProprietaryValue>
                {
                    new ProprietaryValue(),
                    new ProprietaryValue(),
                    new ProprietaryValue()
                }
            };

            _plugin.Export(dataModel, _tempPath);

            var fileExists = File.Exists(Path.Combine(_tempPath, "adm", "ProprietaryValues.adm"));

            Assert.IsTrue(fileExists);
        }
Ejemplo n.º 19
0
        private WorkOrder Map(TSK task, ApplicationDataModel.ADM.ApplicationDataModel dataModel)
        {
            var workOrder = new WorkOrder();

            workOrder.Id.UniqueIds.Add(_uniqueIdMapper.Map(task.A));
            workOrder.Description   = task.B;
            workOrder.GrowerId      = GetGrower(dataModel.Catalog, task.C);
            workOrder.FarmIds       = GetFarms(dataModel.Catalog, task.D);
            workOrder.FieldIds      = GetFields(dataModel.Catalog, task.E);
            workOrder.StatusUpdates = new List <StatusUpdate>();
            workOrder.StatusUpdates.Add(_statusUpdateMapper.Map(task.G));

            if (!string.IsNullOrEmpty(task.F))
            {
                AssociatePersonWithWorkOrder(task, dataModel, workOrder);
            }
            AssociateWorkItemWithWorkOrder(task, dataModel, workOrder);

            return(workOrder);
        }
Ejemplo n.º 20
0
        public IList <ApplicationDataModel.ADM.ApplicationDataModel> Import(string dataPath, Properties properties = null)
        {
            var taskDataObjects = ReadDataCard(dataPath);

            if (taskDataObjects == null)
            {
                return(null);
            }

            var adms = new List <ApplicationDataModel.ADM.ApplicationDataModel>();

            foreach (var taskData in taskDataObjects)
            {
                //Convert the ISO model to ADAPT
                TaskDataMapper taskDataMapper = new TaskDataMapper(taskData.DataFolder, properties);
                ApplicationDataModel.ADM.ApplicationDataModel dataModel = taskDataMapper.Import(taskData);
                adms.Add(dataModel);
            }

            return(adms);
        }
Ejemplo n.º 21
0
        private void ProcessData(TreeNode treeNode)
        {
            var objectWithIndex = (ObjectWithIndex)treeNode.Tag;
            var element         = objectWithIndex.Element;

            workingDataComboBox.Visible = false;
            if (element is FieldBoundary)
            {
                _boundaryProcessor.ProcessBoundary(element as FieldBoundary);
                _tabControlViewer.SelectedTab = _tabPageSpatial;
            }
            else if (element is GuidanceGroup)
            {
                _guidanceProcessor.ProcessGuidance(element as GuidanceGroup, _model.ApplicationDataModels[objectWithIndex.ApplicationDataModelIndex].Catalog.GuidancePatterns);
                _tabControlViewer.SelectedTab = _tabPageSpatial;
            }
            else if (element is GuidancePattern)
            {
                _guidanceProcessor.ProccessGuidancePattern(element as GuidancePattern);
                _tabControlViewer.SelectedTab = _tabPageSpatial;
            }
            else if (element is OperationData)
            {
                OperationData        operation      = element as OperationData;
                List <SpatialRecord> spatialRecords = new List <SpatialRecord>();
                if (operation.GetSpatialRecords != null)
                {
                    spatialRecords = operation.GetSpatialRecords().ToList(); //Iterate the records once here for multiple consumers below
                }
                _dataGridViewRawData.DataSource = _operationDataProcessor.ProcessOperationData(operation, spatialRecords);
                ApplicationDataModel.ADM.ApplicationDataModel model = _model.ApplicationDataModels[objectWithIndex.ApplicationDataModelIndex];
                _spatialRecordProcessor.ProcessOperation(operation, spatialRecords, _model.ApplicationDataModels[objectWithIndex.ApplicationDataModelIndex].Catalog);
                workingDataComboBox.Visible    = true;
                workingDataComboBox.DataSource = _spatialRecordProcessor.WorkingDataList;
            }
            else if (element is Prescription)
            {
                _prescriptionProcessor.ProcessPrescription(element as Prescription);
            }
        }
Ejemplo n.º 22
0
        private TSK Map(WorkOrder workOrder, ApplicationDataModel.ADM.ApplicationDataModel dataModel, int taskNumber, TaskDocumentWriter taskDocumentWriter)
        {
            var taskId = "TSK" + taskNumber;

            taskDocumentWriter.Ids.Add(taskId, workOrder.Id);

            var task = new TSK
            {
                A = taskId,
                B = workOrder.Description,
                C = FindGrowerId(workOrder.GrowerId, dataModel.Catalog),
                G = TSKG.Item1 //TaskStatus.Planned
            };

            if (workOrder.WorkItemIds != null && workOrder.WorkItemIds.Any())
            {
                var workItem = dataModel.Documents.WorkItems.FirstOrDefault(item => item.Id.ReferenceId == workOrder.WorkItemIds.First());
                task.D = FindFarmId(workItem.FarmId, dataModel.Catalog);
                task.E = FindFieldId(workItem.FieldId, dataModel.Catalog);
                if (workItem.WorkItemOperationIds != null && workOrder.WorkItemIds.Any())
                {
                    var operation =
                        dataModel.Documents.WorkItemOperations.First(
                            item => item.Id.ReferenceId == workItem.WorkItemOperationIds.First());
                    if (operation.PrescriptionId != null && operation.PrescriptionId != 0)
                    {
                        var prescription =
                            dataModel.Catalog.Prescriptions.FirstOrDefault(
                                p => p.Id.ReferenceId == operation.PrescriptionId);
                        if (prescription != null)
                        {
                            PrescriptionWriter.WriteSingle(taskDocumentWriter, prescription);
                        }
                    }
                }
            }
            return(task);
        }
Ejemplo n.º 23
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);
        }
Ejemplo n.º 24
0
        public IList <ApplicationDataModel.ADM.ApplicationDataModel> Import(string dataPath, Properties properties = null)
        {
            var taskDataFiles = GetListOfTaskDataFiles(dataPath);

            if (!taskDataFiles.Any())
            {
                return(null);
            }

            var adms = new List <ApplicationDataModel.ADM.ApplicationDataModel>();

            foreach (var taskDataFile in taskDataFiles)
            {
                var dataModel = new ApplicationDataModel.ADM.ApplicationDataModel();

                var taskDataDocument = ConvertTaskDataFileToModel(taskDataFile, dataModel);

                var iso11783TaskData = _xmlReader.Read(taskDataFile);
                _importer.Import(iso11783TaskData, dataPath, dataModel, taskDataDocument.LinkedIds);
                adms.Add(dataModel);
            }

            return(adms);
        }
Ejemplo n.º 25
0
        private LoggedData Map(TSK tsk, string dataPath, ApplicationDataModel.ADM.ApplicationDataModel dataModel, Dictionary <string, List <UniqueId> > linkedIds)
        {
            if (tsk == null || dataModel.Documents.LoggedData == null)
            {
                return(null);
            }

            var existingLoggedData = dataModel.Documents.LoggedData.FirstOrDefault(x => x.Id.FindIsoId() == tsk.A);

            if (existingLoggedData == null)
            {
                return(null);
            }

            var taskId = null as int?;
            var grd    = tsk.Items != null?tsk.Items.FirstOrDefault(x => x.GetType() == typeof(GRD)) : null;

            if (grd != null)
            {
                taskId = dataModel.Catalog.Prescriptions.Single(x => x.Id.FindIsoId() == tsk.A).Id.ReferenceId;
            }
            existingLoggedData.OperationData = _operationDataMapper.Map(tsk.Items.GetItemsOfType <TLG>(), taskId, dataPath, existingLoggedData.Id.ReferenceId, linkedIds);
            return(existingLoggedData);
        }
Ejemplo n.º 26
0
        public IList <ApplicationDataModel.ADM.ApplicationDataModel> Import(string path, Properties properties = null)
        {
            if (!IsDataCardSupported(path, properties))
            {
                return(null);
            }
            var catalog           = ImportData <Catalog>(path, CatalogAdm);
            var documents         = _documentsImporter.ImportDocuments(path, DocumentAdm, catalog);
            var proprietaryValues = ImportData <List <ProprietaryValue> >(path, ProprietaryValuesAdm);
            var referenceLayers   = ImportReferenceLayers(path, ReferencelayersAdm);

            var applicationDataModel = new ApplicationDataModel.ADM.ApplicationDataModel
            {
                ProprietaryValues = proprietaryValues,
                Catalog           = catalog,
                Documents         = documents,
                ReferenceLayers   = referenceLayers
            };

            return(new List <ApplicationDataModel.ADM.ApplicationDataModel>
            {
                applicationDataModel
            });
        }
Ejemplo n.º 27
0
 public List <LoggedData> Map(List <TSK> tsks, string dataPath, ApplicationDataModel.ADM.ApplicationDataModel dataModel, Dictionary <string, List <UniqueId> > linkedIds)
 {
     return(tsks == null
         ? null
         : tsks.Select(tsk => Map(tsk, dataPath, dataModel, linkedIds)).ToList());
 }
Ejemplo n.º 28
0
        public IList<ApplicationDataModel.ADM.ApplicationDataModel> Import(string dataPath, Properties properties = null)
        {
            var taskDataFiles = GetListOfTaskDataFiles(dataPath);
            if (!taskDataFiles.Any())
                return null;

            var adms = new List<ApplicationDataModel.ADM.ApplicationDataModel>();

            foreach (var taskDataFile in taskDataFiles)
            {
                var dataModel = new ApplicationDataModel.ADM.ApplicationDataModel();

                var taskDataDocument = ConvertTaskDataFileToModel(taskDataFile, dataModel);

                var iso11783TaskData = _xmlReader.Read(taskDataFile);
                _importer.Import(iso11783TaskData, dataPath, dataModel, taskDataDocument.LinkedIds);
                adms.Add(dataModel);
            }

            return adms;
        }
Ejemplo n.º 29
0
 public void Export(ApplicationDataModel.ADM.ApplicationDataModel dataModel, string exportPath, Properties properties = null)
 {
 }
Ejemplo n.º 30
0
        public ISO11783_TaskData Export(ApplicationDataModel.ADM.ApplicationDataModel adm)
        {
            AdaptDataModel = adm;

            //TaskData
            ISOTaskData = new ISO11783_TaskData();
            ISOTaskData.VersionMajor = 4;
            ISOTaskData.VersionMinor = 0;
            ISOTaskData.ManagementSoftwareManufacturer = "AgGateway";
            ISOTaskData.ManagementSoftwareVersion      = "1.0";
            ISOTaskData.DataTransferOrigin             = ISOEnumerations.ISOTaskDataTransferOrigin.FMIS;
            ISOTaskData.TaskControllerManufacturer     = "";
            ISOTaskData.TaskControllerVersion          = "";

            //LinkList
            ISOTaskData.LinkList = new ISO11783_LinkList();
            ISOTaskData.LinkList.VersionMajor = 4;
            ISOTaskData.LinkList.VersionMinor = 0;
            ISOTaskData.LinkList.ManagementSoftwareManufacturer = "AgGateway";
            ISOTaskData.LinkList.ManagementSoftwareVersion      = "1.0";
            ISOTaskData.LinkList.DataTransferOrigin             = ISOEnumerations.ISOTaskDataTransferOrigin.FMIS;
            ISOTaskData.LinkList.TaskControllerManufacturer     = "";
            ISOTaskData.LinkList.TaskControllerVersion          = "";
            ISOTaskData.LinkList.FileVersion = "";
            UniqueIDMapper = new UniqueIdMapper(ISOTaskData.LinkList);

            //Crops
            if (adm.Catalog.Crops != null)
            {
                CropTypeMapper            cropMapper = new CropTypeMapper(this, ProductGroupMapper);
                IEnumerable <ISOCropType> crops      = cropMapper.ExportCropTypes(adm.Catalog.Crops);
                ISOTaskData.ChildElements.AddRange(crops);
            }

            //Products
            if (adm.Catalog.Products != null)
            {
                IEnumerable <Product> products = AdaptDataModel.Catalog.Products;
                if (products.Any())
                {
                    ProductMapper            productMapper = new ProductMapper(this, ProductGroupMapper);
                    IEnumerable <ISOProduct> isoProducts   = productMapper.ExportProducts(products);
                    ISOTaskData.ChildElements.AddRange(isoProducts);
                }
            }

            //Growers
            if (adm.Catalog.Growers != null)
            {
                CustomerMapper            customerMapper = new CustomerMapper(this);
                IEnumerable <ISOCustomer> customers      = customerMapper.Export(adm.Catalog.Growers);
                ISOTaskData.ChildElements.AddRange(customers);
            }

            //Farms
            if (adm.Catalog.Farms != null)
            {
                FarmMapper            farmMapper = new FarmMapper(this);
                IEnumerable <ISOFarm> farms      = farmMapper.Export(adm.Catalog.Farms);
                ISOTaskData.ChildElements.AddRange(farms);
            }

            //Fields & Cropzones
            if (adm.Catalog.Fields != null)
            {
                PartfieldMapper fieldMapper = new PartfieldMapper(this);
                foreach (Field field in adm.Catalog.Fields)
                {
                    IEnumerable <CropZone> fieldCropZones = adm.Catalog.CropZones.Where(c => c.FieldId == field.Id.ReferenceId);
                    if (fieldCropZones.Count() == 0)
                    {
                        //Export Field
                        ISOPartfield isoField = fieldMapper.ExportField(field);
                        ISOTaskData.ChildElements.Add(isoField);
                    }
                    else if (fieldCropZones.Count() == 1)
                    {
                        //Export Cropzone to retain the crop reference
                        ISOPartfield isoField = fieldMapper.ExportCropZone(fieldCropZones.First());
                        ISOTaskData.ChildElements.Add(isoField);
                    }
                    else
                    {
                        //Export both
                        ISOPartfield isoField = fieldMapper.ExportField(field);
                        ISOTaskData.ChildElements.Add(isoField);
                        foreach (CropZone cropZone in fieldCropZones)
                        {
                            ISOPartfield isoCropField = fieldMapper.ExportCropZone(cropZone);
                            ISOTaskData.ChildElements.Add(isoCropField);
                        }
                    }
                }
            }

            //Workers
            if (adm.Catalog.Persons != null)
            {
                WorkerMapper            workerMapper = new WorkerMapper(this);
                IEnumerable <ISOWorker> workers      = workerMapper.Export(adm.Catalog.Persons);
                ISOTaskData.ChildElements.AddRange(workers);
            }

            //Devices
            if (adm.Catalog.DeviceModels.Any())
            {
                DeviceMapper            dvcMapper = new DeviceMapper(this);
                IEnumerable <ISODevice> devices   = dvcMapper.ExportDevices(adm.Catalog.DeviceModels);
                ISOTaskData.ChildElements.AddRange(devices);
            }

            //Tasks
            if (AdaptDataModel.Documents.WorkItems.Any() || AdaptDataModel.Documents.LoggedData.Any())
            {
                TaskMapper taskMapper = new TaskMapper(this);
                if (AdaptDataModel.Documents.WorkItems != null)
                {
                    //Prescriptions
                    int gridType = 1;
                    if (Properties != null)
                    {
                        Int32.TryParse(Properties.GetProperty(ISOGrid.GridTypeProperty), out gridType);
                    }
                    if (gridType == 1 || gridType == 2)
                    {
                        IEnumerable <ISOTask> plannedTasks = taskMapper.Export(AdaptDataModel.Documents.WorkItems, gridType);
                        ISOTaskData.ChildElements.AddRange(plannedTasks);
                    }
                    else
                    {
                        AddError($"Invalid Grid Type {gridType}.  WorkItems will not be exported", null, "TaskDataMapper");
                    }
                }

                if (AdaptDataModel.Documents.LoggedData != null)
                {
                    //LoggedData
                    IEnumerable <ISOTask> loggedTasks = taskMapper.Export(AdaptDataModel.Documents.LoggedData);
                    ISOTaskData.ChildElements.AddRange(loggedTasks.Where(t => !ISOTaskData.ChildElements.OfType <ISOTask>().Contains(t)));
                }
            }

            //Add Comments
            ISOTaskData.ChildElements.AddRange(CommentMapper.ExportedComments);

            //Add LinkList Attached File Reference
            if (ISOTaskData.LinkList.LinkGroups.Any())
            {
                ISOAttachedFile afe = new ISOAttachedFile();
                afe.FilenamewithExtension = "LINKLIST.XML";
                afe.Preserve        = ISOEnumerations.ISOAttachedFilePreserve.Preserve;
                afe.ManufacturerGLN = string.Empty;
                afe.FileType        = 1;
                ISOTaskData.ChildElements.Add(afe);
            }

            return(ISOTaskData);
        }
Ejemplo n.º 31
0
        public ApplicationDataModel.ADM.ApplicationDataModel Import(ISO11783_TaskData taskData)
        {
            ISOTaskData    = taskData;
            UniqueIDMapper = new UniqueIdMapper(ISOTaskData.LinkList);

            AdaptDataModel         = new ApplicationDataModel.ADM.ApplicationDataModel();
            AdaptDataModel.Catalog = new Catalog()
            {
                Description = taskData.FilePath
            };
            AdaptDataModel.Documents = new Documents();

            //Comments
            CodedCommentListMapper commentListMapper = new CodedCommentListMapper(this);
            CodedCommentMapper     commentMapper     = new CodedCommentMapper(this, commentListMapper);

            //Crops - several dependencies require import prior to Products
            IEnumerable <ISOCropType> crops = taskData.ChildElements.OfType <ISOCropType>();

            if (crops.Any())
            {
                CropTypeMapper cropMapper = new CropTypeMapper(this, ProductGroupMapper);
                AdaptDataModel.Catalog.Crops.AddRange(cropMapper.ImportCropTypes(crops));
            }

            //Products
            IEnumerable <ISOProduct> products = taskData.ChildElements.OfType <ISOProduct>();

            if (products.Any())
            {
                ProductMapper         productMapper = new ProductMapper(this, ProductGroupMapper);
                IEnumerable <Product> adaptProducts = productMapper.ImportProducts(products);
                AdaptDataModel.Catalog.Products.AddRange(adaptProducts.Where(p => !AdaptDataModel.Catalog.Products.Contains(p)));
            }

            //Growers
            IEnumerable <ISOCustomer> customers = taskData.ChildElements.OfType <ISOCustomer>();

            if (customers.Any())
            {
                CustomerMapper customerMapper = new CustomerMapper(this);
                AdaptDataModel.Catalog.Growers.AddRange(customerMapper.Import(customers));
            }

            //Farms
            IEnumerable <ISOFarm> farms = taskData.ChildElements.OfType <ISOFarm>();

            if (farms.Any())
            {
                FarmMapper farmMapper = new FarmMapper(this);
                AdaptDataModel.Catalog.Farms.AddRange(farmMapper.Import(farms));
            }

            //Fields & Cropzones
            IEnumerable <ISOPartfield> partFields = taskData.ChildElements.OfType <ISOPartfield>();

            if (partFields.Any())
            {
                PartfieldMapper partFieldMapper = new PartfieldMapper(this);
                AdaptDataModel.Catalog.Fields.AddRange(partFieldMapper.ImportFields(partFields));
                AdaptDataModel.Catalog.CropZones.AddRange(partFieldMapper.ImportCropZones(partFields));
            }

            //Devices
            IEnumerable <ISODevice> devices = taskData.ChildElements.OfType <ISODevice>();

            if (devices.Any())
            {
                DeviceElementHierarchies = new DeviceElementHierarchies(devices, RepresentationMapper);

                DeviceMapper deviceMapper = new DeviceMapper(this);
                AdaptDataModel.Catalog.DeviceModels.AddRange(deviceMapper.ImportDevices(devices));
            }

            //Workers
            IEnumerable <ISOWorker> workers = taskData.ChildElements.OfType <ISOWorker>();

            if (workers.Any())
            {
                WorkerMapper workerMapper = new WorkerMapper(this);
                AdaptDataModel.Catalog.Persons.AddRange(workerMapper.Import(workers));
            }


            //Cultural Practices
            IEnumerable <ISOCulturalPractice> practices = taskData.ChildElements.OfType <ISOCulturalPractice>();

            if (practices.Any())
            {
                foreach (ISOCulturalPractice cpc in practices)
                {
                    (AdaptDataModel.Documents.WorkOrders as List <WorkOrder>).Add(new WorkOrder()
                    {
                        Description = cpc.CulturalPracticeDesignator
                    });
                }
            }

            //OperationTechniques
            IEnumerable <ISOOperationTechnique> techniques = taskData.ChildElements.OfType <ISOOperationTechnique>();

            if (techniques.Any())
            {
                foreach (ISOOperationTechnique otq in techniques)
                {
                    (AdaptDataModel.Documents.WorkOrders as List <WorkOrder>).Add(new WorkOrder()
                    {
                        Description = otq.OperationTechniqueDesignator
                    });
                }
            }

            IEnumerable <ISOTask> prescribedTasks = taskData.ChildElements.OfType <ISOTask>().Where(t => t.IsWorkItemTask);
            IEnumerable <ISOTask> loggedTasks     = taskData.ChildElements.OfType <ISOTask>().Where(t => t.IsLoggedDataTask || t.TimeLogs.Any());

            if (prescribedTasks.Any() || loggedTasks.Any())
            {
                TaskMapper taskMapper = new TaskMapper(this);
                if (prescribedTasks.Any())
                {
                    //Prescribed Tasks
                    IEnumerable <WorkItem> workItems = taskMapper.ImportWorkItems(prescribedTasks);
                    AdaptDataModel.Documents.WorkItems = workItems;
                }

                if (loggedTasks.Any())
                {
                    //Logged Tasks
                    IEnumerable <LoggedData> loggedDatas = taskMapper.ImportLoggedDatas(loggedTasks);
                    AdaptDataModel.Documents.LoggedData = loggedDatas;

                    //Create Work Records for Logged Tasks
                    List <WorkRecord> workRecords = new List <WorkRecord>();
                    foreach (LoggedData data in loggedDatas)
                    {
                        WorkRecord record = new WorkRecord();
                        record.LoggedDataIds.Add(data.Id.ReferenceId);
                        if (data.SummaryId.HasValue)
                        {
                            record.SummariesIds.Add(data.SummaryId.Value);
                            Summary summary = AdaptDataModel.Documents.Summaries.FirstOrDefault(s => s.Id.ReferenceId == data.SummaryId);
                            if (summary != null)
                            {
                                summary.WorkRecordId = record.Id.ReferenceId;
                            }
                        }
                        workRecords.Add(record);
                    }
                    AdaptDataModel.Documents.WorkRecords = workRecords;
                }
            }

            return(AdaptDataModel);
        }