public void GetPluginShouldInitializePlugin() { var plugin = _pluginFactory.GetPlugin(_pluginMetadata.Name); _pluginLoader.Verify(x => x.CreateInstance(_pluginMetadata)); Assert.AreSame(_pluginMetadata.AssemblyInstance, plugin); }
private void _buttonLoadDatacard_Click(object sender, EventArgs e) { var textBox = _textBoxDatacardPath; if (_pluginFactory == null) { MessageBox.Show(@"Select a valid plugin path and load them before importing a datacard."); _textBoxPluginPath.Focus(); return; } if (IsValid(textBox, "Datacard")) { foreach (var availablePlugin in _pluginFactory.AvailablePlugins) { var plugin = _pluginFactory.GetPlugin(availablePlugin); plugin.Initialize(_textBoxApplicationId.Text); if (plugin.IsDataCardSupported(_textBoxDatacardPath.Text)) { ImportDataCard(plugin, textBox.Text); return; } } MessageBox.Show(@"Not supported data format."); } }
/// <summary> /// 生成原始记录证书 不 签名 /// </summary> /// <param name="ipt"></param> /// <returns></returns> public async Task <string[]> MakeXlsCert(CertDto ipt) //public async Task<string[]> MakeCert(JDJLFM jdjlfm, RawTemplate rawTemplate, int[] Signer) { if (string.IsNullOrWhiteSpace(ipt.rawTemplate.MBMC)) { return(null); } //PerformanceCounterTest test = new PerformanceCounterTest(); //test.Go(); var plugin = await PluginFactory.GetPlugin(_cache, _options, ipt.rawTemplate.MBMC); if (plugin != null) { var zsbh = GetZSBH(ipt.rawTemplate.MBMC, ipt.jdjlfm.ID); ipt.jdjlfm.ZSBH = zsbh; //string[] ret = plugin.Handle(ipt.rawTemplate, ipt.jdjlfm, ipt.Signer); string[] ret = plugin.Handle(ipt.rawTemplate, ipt.jdjlfm); string resData = JsonConvert.SerializeObject(ret); AddtoZshData(ipt.jdjlfm.ID, resData); //test.Go(); return(ret); } return(null); }
private IPluginConfigurationControl CreatePluginControl() { PluginAssembly assembly = null; try { assembly = PluginFactory.GetPlugin(_metadata.MetadataType); } catch (InvalidOperationException) { // Assembly stays null; error is thrown below } if (assembly?.Implements <IPluginConfigurationControl>() == true) { IPluginConfigurationControl configurationControl = assembly.Create <IPluginConfigurationControl>(); configurationControl.ConfigurationChanged += PluginControl_ConfigurationChanged; InitializePluginControl(configurationControl); return(configurationControl); } else { string errorMessage = Resource.PluginLoadErrorMessage.FormatWith(_metadata.MetadataType); TraceFactory.Logger.Error(errorMessage); throw new PluginLoadException(errorMessage); } }
/// <summary> /// Loads plugin, register it as a service and add its own services /// </summary> /// <param name="container"></param> /// <param name="pluginAssembly"></param> /// <returns></returns> private static IServiceCollection AddPluginServices(this IServiceCollection container, Assembly pluginAssembly) { try { IPlugin plugin = PluginFactory.GetPlugin <IPlugin>(pluginAssembly); PluginServices pluginServices = plugin.GetPluginServices(); foreach ((Type serviceType, Type implementationType) in pluginServices.ScopedServices) { container.AddScoped(serviceType, implementationType); } foreach ((Type serviceType, Type implementationType) in pluginServices.TransientServices) { container.AddTransient(serviceType, implementationType); } foreach ((Type serviceType, Type implementationType) in pluginServices.SingletonServices) { container.AddSingleton(serviceType, implementationType); } } catch (ApplicationException) { return(container); } return(container); }
public static void GetPlugin_NullXmlNode_ArgumentNullException() { Assert.Throws <ArgumentNullException>(() => { PluginFactory.GetPlugin(null, "NullPlugin.dll"); }, "{0}.{1}() should throw a {2} when a null XmlNode is passed in!", nameof(PluginFactory), nameof(PluginFactory.GetPlugin), nameof(ArgumentNullException)); }
public static void LoadPlugin() { PluginFactory factory = new PluginFactory(ConfigurationManager.AppSettings["pluginDirectory"]); plugin = factory.GetPlugin(ConfigurationManager.AppSettings["pluginName"]); plugin.Initialize(); }
private async Task <string> SignerCert(CertDto2 ipt) { var plugin = await PluginFactory.GetPlugin(_cache, _options, ipt.MBMC); if (plugin != null) { plugin.Handle(ipt.QJMCBM, ipt.ID, ipt.Signer); return("OK"); } return(null); }
public void Config() { //use the below to test locally //string path = Path.Combine(Environment.CurrentDirectory, @"AdaptPlugin\"); //PluginFactory factory = new PluginFactory(path); PluginFactory factory = new PluginFactory("/app/AdaptPlugin/"); plugin = factory.GetPlugin("ClimateADAPT"); plugin.Initialize(); tempDir = CreateTempDir(); }
public static void GetPlugin_InvalidXmlConfig_XmlException(string xmlConfig) { XmlDocument doc = new XmlDocument(); doc.LoadXml(xmlConfig); XmlNode node = doc.FirstChild; Assert.Throws <XmlException>(() => { PluginFactory.GetPlugin(node, xmlConfig); }, "{0}.{1}() should throw a {2} when the NTestController.xml file contains an invalid plugin node!", nameof(PluginFactory), nameof(PluginFactory.GetPlugin), nameof(XmlException)); }
public static void GetPlugin_InvalidPluginTypeInXmlConfig_ArgumentException(string xmlConfig) { XmlDocument doc = new XmlDocument(); doc.LoadXml(StringUtils.FormatInvariant("<plugin type=\"{0}\" path=\"NullPlugin.dll\" />", xmlConfig)); XmlNode node = doc.FirstChild; Assert.Throws <ArgumentException>(() => { PluginFactory.GetPlugin(node, xmlConfig); }, "{0}.{1}() should throw a {2} when the NTestController.xml file contains an invalid plugin type!", nameof(PluginFactory), nameof(PluginFactory.GetPlugin), nameof(ArgumentException)); }
public static void GetPlugin_NullOrWhiteSpaceXmlConfig_ArgumentNullException(string xmlConfig) { XmlDocument doc = new XmlDocument(); doc.LoadXml("<plugin type=\"TestReader\" path=\"NullPlugin.dll\" />"); XmlNode node = doc.FirstChild; Assert.Throws <ArgumentNullException>(() => { PluginFactory.GetPlugin(node, xmlConfig); }, "{0}.{1}() should throw a {2} when a null or white space NTestController.xml file is passed in!", nameof(PluginFactory), nameof(PluginFactory.GetPlugin), nameof(ArgumentNullException)); }
private void CreatePlugin() { TraceFactory.Logger.Debug("Loading plugin instance for {0} activity '{1}'".FormatWith(ActivityType, Name)); try { _plugin = PluginFactory.GetPlugin(ActivityType).Create <IPluginExecutionEngine>(); } catch (PluginLoadException ex) { TraceFactory.Logger.Error($"Unable to load plugin for Activity Type: {ActivityType}", ex); throw; } }
public static void GetPlugin_WrongPluginType_TypeLoadException() { XmlDocument doc = new XmlDocument(); doc.LoadXml("<plugin type=\"TestReporter\" path=\"NUnit-Reader.dll\" />"); XmlNode node = doc.FirstChild; string xmlConfig = XML_CONFIG.Replace("NullPlugin", "NUnit-Reader.dll"); Assert.Throws <TypeLoadException>(() => { PluginFactory.GetPlugin(node, xmlConfig); }, "{0}.{1}() should throw a {2} when the DLL doesn't contain the type of plugin specified in the NTestController.xml file!", nameof(PluginFactory), nameof(PluginFactory.GetPlugin), nameof(TypeLoadException)); }
// ToDo: in seperated class? private bool ExportData(ApplicationDataModel applicationDataModel, ConsoleParameters consoleParameters) { if (PluginFactory.AvailablePlugins.Count == 0) { Console.WriteLine("PluginFactory: no plugins available"); return(false); } // To Do (check if possible/needed): Task.Run(() => {}); Console.WriteLine("Starting ADAPT export"); DateTime startTime = DateTime.Now; // Get Plugin // ToDo: [Check] version of plugin var exportPlugin = PluginFactory.GetPlugin(consoleParameters.ExportPluginName); if (exportPlugin == null) { Console.WriteLine($"Could not find ExportPlugin {consoleParameters.ImportPluginName}"); return(false); } // Initialise Plugin if (ExportSettings != null) { if (!string.IsNullOrEmpty(ExportSettings.InitialiseString)) { exportPlugin.Initialize(ExportSettings.InitialiseString); } } // Check if Plugin supports the data if (ExportSettings != null) { if (ExportSettings.GetProperties() != null) { exportPlugin.Export(applicationDataModel, consoleParameters.ExportDataPath, ExportSettings.GetProperties()); } } else { exportPlugin.Export(applicationDataModel, consoleParameters.ExportDataPath); } TimeSpan conversionTime = DateTime.Now.Subtract(startTime); Console.WriteLine($"Completed ADAPT export in {conversionTime}, exported 1 ApplicationDataModels"); return(true); }
/// <summary> /// This demo uses the ADMPlugin to manage the contents of the ADAPT Application Data Model. This method will /// initialize the plugin. /// </summary> private static IPlugin InitializeAdaptPlugin() { IPlugin iPlugin = null; try { var appPath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location); var pluginFactory = new PluginFactory(appPath); iPlugin = pluginFactory.GetPlugin("ADMPlugin"); iPlugin.Initialize(); } catch (Exception exp) { throw exp; } return(iPlugin); }
private static void CreateSetupFile(PluginFactory pluginManager) { var setupDataModel = new SetupDataCreator().PopulateDataModel(); //You can export setup data through any plugin other than the Deere Gen4 plugin. //Currently the Gen4 displays use a 2630 setup model - use the 2630 plugin to send setup data to a Gen4 display. var plugin = pluginManager.GetPlugin(PluginNames.Deere2630); if (plugin == null) { //In this case, the desired plugin failed to load. //If you have not yet licensed and received a copy of the Deere plugins, that could be why - they are not distributed with this sample code. } else { var exportDirectory = Path.Combine("C:", "temp", "ADAPT_Export_Directory"); plugin.Export(setupDataModel, exportDirectory.ToString()); } }
public static void GetPlugin_ValidArgs_ReturnsIPlugin() { IPlugin plugin = null; string xmlConfigPath = "GetPlugin_ValidArgs_ReturnsIPlugin.xml"; // If the XML file was left over from a previous run, delete it. if (File.Exists(xmlConfigPath)) { File.Delete(xmlConfigPath); } try { // Create the XML file. using (StreamWriter writer = File.CreateText(xmlConfigPath)) { writer.Write(XML_CONFIG); } XmlDocument doc = new XmlDocument(); doc.LoadXml("<plugin type=\"TestReader\" path=\"NullPlugin.dll\" />"); XmlNode node = doc.FirstChild; Assert.DoesNotThrow(() => { plugin = PluginFactory.GetPlugin(node, xmlConfigPath); }, "{0}.{1}() should not throw an exception when passed a valid DLL & XML Config file!", nameof(PluginFactory), nameof(PluginFactory.GetPlugin)); Assert.NotNull(plugin, "{0}.{1}() returned null when passed a valid DLL & XML Config file!", nameof(PluginFactory), nameof(PluginFactory.GetPlugin)); } finally { // Delete the XML file. if (File.Exists(xmlConfigPath)) { File.Delete(xmlConfigPath); } } }
public static void Main(string[] args) { //This returns the \bin directory. //ADAPT plugins do not need to be located in the application directory. //If you place the plugins in a separate folder, this variable should contain the path to that folder. var pluginLocation = AppDomain.CurrentDomain.BaseDirectory; var pluginManager = new PluginFactory(pluginLocation); //When you license the John Deere ADAPT plugins, you will receive a license file and an application id. //Initializing the plugin with your application id activates the license. //Keep the application id in a secure place. It is associated with your company. foreach (var pluginName in pluginManager.AvailablePlugins) { var plugin = pluginManager.GetPlugin(pluginName); plugin.Initialize(_applicationId.ToString()); } //If you want to process documentation data (ie, sensor data that was collected by a machine in the field): LoadDocumentationDataFromSomeDatacard(pluginManager); //If you want to create a setup file that can be sent to a machine: CreateSetupFile(pluginManager); }
static void Main(string[] args) { var testData = JArray.Parse(File.ReadAllText("data.json")); string applicationPath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location); var pluginFactory = new PluginFactory(applicationPath); var admPlugin = pluginFactory.GetPlugin("ADMPlugin"); admPlugin.Initialize(); ApplicationDataModel export = new ApplicationDataModel(); export.Catalog = new Catalog(); export.Documents = new Documents(); List <WorkRecord> workRecords = new List <WorkRecord>(); List <Summary> summaries = new List <Summary>(); // All of these records are for the same Grower/Farm/Field/CropZone/CropYear so I'm just // pulling the common info from the first record. #region Create a "crop year" TimeScope to tag each of the WorkRecords with. TimeScope cropYear = new TimeScope(); UniqueId ourId = new UniqueId(); ourId.Id = testData[0]["CropYear"].ToString(); ourId.IdType = IdTypeEnum.String; ourId.Source = "www.somecompany.com"; ourId.SourceType = IdSourceTypeEnum.URI; cropYear.Id.UniqueIds.Add(ourId); cropYear.Description = testData[0]["CropYear"].ToString(); cropYear.DateContext = DateContextEnum.CropSeason; export.Catalog.TimeScopes.Add(cropYear); #endregion #region Create the Grower/Farm/Field/CropZone objects for this group of applications Grower grower = new Grower(); ourId = new UniqueId(); ourId.Id = testData[0]["ApplicationId"]["DataSourceId"].ToString(); ourId.IdType = IdTypeEnum.UUID; ourId.Source = "www.somecompany.com"; ourId.SourceType = IdSourceTypeEnum.URI; grower.Id.UniqueIds.Add(ourId); grower.Name = testData[0]["GrowerName"].ToString(); export.Catalog.Growers.Add(grower); Farm farm = new Farm(); ourId = new UniqueId(); ourId.Id = testData[0]["FarmId"]["Id"].ToString(); ourId.IdType = IdTypeEnum.UUID; ourId.Source = "www.somecompany.com"; ourId.SourceType = IdSourceTypeEnum.URI; farm.Id.UniqueIds.Add(ourId); farm.Description = testData[0]["FarmName"].ToString(); farm.GrowerId = grower.Id.ReferenceId; export.Catalog.Farms.Add(farm); Field field = new Field(); ourId = new UniqueId(); ourId.Id = testData[0]["FieldId"].ToString(); ourId.IdType = IdTypeEnum.UUID; ourId.Source = "www.somecompany.com"; ourId.SourceType = IdSourceTypeEnum.URI; field.Id.UniqueIds.Add(ourId); field.Description = testData[0]["FieldName"].ToString(); field.FarmId = farm.Id.ReferenceId; export.Catalog.Fields.Add(field); Crop crop = new Crop(); ourId = new UniqueId(); ourId.Id = testData[0]["CropId"]["Id"].ToString(); ourId.IdType = IdTypeEnum.UUID; ourId.Source = "www.somecompany.com"; ourId.SourceType = IdSourceTypeEnum.URI; crop.Id.UniqueIds.Add(ourId); crop.Name = testData[0]["Crop"].ToString(); // Add EPPO code as ContextItem at some point in the future export.Catalog.Crops.Add(crop); CropZone cropZone = new CropZone(); ourId = new UniqueId(); ourId.Id = testData[0]["CropZoneId"].ToString(); ourId.IdType = IdTypeEnum.UUID; ourId.Source = "www.somecompany.com"; ourId.SourceType = IdSourceTypeEnum.URI; cropZone.Id.UniqueIds.Add(ourId); cropZone.Description = testData[0]["CropZoneName"].ToString(); cropZone.FieldId = field.Id.ReferenceId; cropZone.CropId = crop.Id.ReferenceId; cropZone.TimeScopes.Add(cropYear); string areaString = testData[0]["AreaApplied"].ToString(); double area = Convert.ToDouble(areaString); cropZone.Area = new NumericRepresentationValue(RepresentationInstanceList.vrReportedFieldArea.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("ac1"), area)); export.Catalog.CropZones.Add(cropZone); #endregion // Foreach Application var applicationIds = ((from c in testData select c["ApplicationId"]["Id"]).Distinct()).ToList(); foreach (var applicationId in applicationIds) { var appliedProducts = (from c in testData where (string)c["ApplicationId"]["Id"] == applicationId.ToString() select c).ToList(); // Create a WorkRecord and Summary (ADAPT's version of an Application) WorkRecord workRecord = new WorkRecord(); ourId = new UniqueId(); ourId.Id = appliedProducts[0]["ApplicationId"]["Id"].ToString(); ourId.IdType = IdTypeEnum.UUID; ourId.Source = "www.somecompany.com"; ourId.SourceType = IdSourceTypeEnum.URI; workRecord.Id.UniqueIds.Add(ourId); workRecord.Description = appliedProducts[0]["ApplicationName"].ToString(); workRecord.TimeScopes.Add(cropYear); TimeScope timingEvent = new TimeScope(); timingEvent.DateContext = DateContextEnum.TimingEvent; timingEvent.Description = appliedProducts[0]["TimingEvent"].ToString(); workRecord.TimeScopes.Add(timingEvent); TimeScope startDate = new TimeScope(); startDate.DateContext = DateContextEnum.ActualStart; startDate.TimeStamp1 = DateTime.Parse(appliedProducts[0]["StartDate"].ToString()); workRecord.TimeScopes.Add(startDate); TimeScope endDate = new TimeScope(); endDate.DateContext = DateContextEnum.ActualEnd; endDate.TimeStamp1 = DateTime.Parse(appliedProducts[0]["EndDate"].ToString()); workRecord.TimeScopes.Add(endDate); Summary summary = new Summary(); // This property linking the Summary to its parent WorkRecord doesn't exist in ADAPT 1.1.0.8. // Slated to be added in next release. // summary.WorkRecordId = workRecord.Id.ReferenceId; // This property linking the Summary to its Grower doesn't exist in ADAPT 1.1.0.8. // Slated to be added in next release. // summary.GrowerId = grower.Id.ReferenceId; summary.FarmId = farm.Id.ReferenceId; summary.FieldId = field.Id.ReferenceId; summary.CropZoneId = cropZone.Id.ReferenceId; // Foreach Product foreach (var appliedProduct in appliedProducts) { //Note that Manufacturer is not a required property for a given product. Manufacturer manufacturer = null; var manufacturers = export.Catalog.Manufacturers.Where(x => (x.Description == appliedProduct["Manufacturer"].ToString())).ToList(); if (manufacturers.Count > 0) { manufacturer = manufacturers[0]; } else { manufacturer = new Manufacturer(); ourId = new UniqueId(); // Couldn't find Manufacturer id in your data ourId.Id = "00000000-0000-0000-0000-000000000000"; ourId.IdType = IdTypeEnum.UUID; ourId.Source = "www.somecompany.com"; ourId.SourceType = IdSourceTypeEnum.URI; manufacturer.Id.UniqueIds.Add(ourId); manufacturer.Description = appliedProduct["Manufacturer"].ToString(); export.Catalog.Manufacturers.Add(manufacturer); } // This is sub-optimal, but it is what we have to work with at the moment. // We're creating the use of each product as its own "operation" OperationSummary operation = new OperationSummary(); operation.Data = new List <StampedMeteredValues>(); if (appliedProduct["Type"].ToString() == "Seed") { #region Handle Seed CropVariety cropVariety = null; var products = export.Catalog.Products.Where(x => (x.Description == appliedProduct["Product"].ToString())).ToList(); if (products.Count > 0) { cropVariety = products[0] as CropVariety; } else { cropVariety = new CropVariety(); ourId = new UniqueId(); ourId.Id = appliedProduct["ProductId"]["Id"].ToString(); ourId.IdType = IdTypeEnum.UUID; ourId.Source = "www.somecompany.com"; ourId.SourceType = IdSourceTypeEnum.URI; cropVariety.Id.UniqueIds.Add(ourId); cropVariety.Description = appliedProduct["Product"].ToString(); cropVariety.CropId = crop.Id.ReferenceId; if (manufacturer != null) { cropVariety.ManufacturerId = manufacturer.Id.ReferenceId; } export.Catalog.Products.Add(cropVariety); } operation.ProductId = cropVariety.Id.ReferenceId; operation.OperationType = OperationTypeEnum.SowingAndPlanting; #endregion } else if (appliedProduct["Type"].ToString() == "CropProtection") { #region Handle CropProtection CropProtectionProduct cropProtection = null; var products = export.Catalog.Products.Where(x => (x.Description == appliedProduct["Product"].ToString())).ToList(); if (products.Count > 0) { cropProtection = products[0] as CropProtectionProduct; } else { cropProtection = new CropProtectionProduct(); ourId = new UniqueId(); ourId.Id = appliedProduct["ProductId"]["Id"].ToString(); ourId.IdType = IdTypeEnum.UUID; ourId.Source = "www.somecompany.com"; ourId.SourceType = IdSourceTypeEnum.URI; cropProtection.Id.UniqueIds.Add(ourId); cropProtection.Description = appliedProduct["Product"].ToString(); if (manufacturer != null) { cropProtection.ManufacturerId = manufacturer.Id.ReferenceId; } if (!string.IsNullOrEmpty(appliedProduct["RegNo"].ToString())) { ContextItem epaNumber = new ContextItem(); epaNumber.Code = "US-EPA-N"; epaNumber.Value = ConditionEPA(appliedProduct["RegNo"].ToString(), true, true); cropProtection.ContextItems.Add(epaNumber); } export.Catalog.Products.Add(cropProtection); } operation.ProductId = cropProtection.Id.ReferenceId; operation.OperationType = OperationTypeEnum.CropProtection; #endregion } else if (appliedProduct["Type"].ToString() == "Fertilizer") { #region Handle Fertilizer FertilizerProduct cropNutrition = null; var products = export.Catalog.Products.Where(x => (x.Description == appliedProduct["Product"].ToString())).ToList(); if (products.Count > 0) { cropNutrition = products[0] as FertilizerProduct; } else { cropNutrition = new FertilizerProduct(); ourId = new UniqueId(); ourId.Id = appliedProduct["ProductId"]["Id"].ToString(); ourId.IdType = IdTypeEnum.UUID; ourId.Source = "www.somecompany.com"; ourId.SourceType = IdSourceTypeEnum.URI; cropNutrition.Id.UniqueIds.Add(ourId); cropNutrition.Description = appliedProduct["Product"].ToString(); if (manufacturer != null) { cropNutrition.ManufacturerId = manufacturer.Id.ReferenceId; } export.Catalog.Products.Add(cropNutrition); } operation.ProductId = cropNutrition.Id.ReferenceId; operation.OperationType = OperationTypeEnum.Fertilizing; #endregion } StampedMeteredValues smv = new StampedMeteredValues(); MeteredValue mv = null; NumericRepresentationValue rateValue = null; #region Set the product rate (currently hardcoded to be per acre) switch (appliedProduct["RateUnit"].ToString()) { case ("seed"): rateValue = new NumericRepresentationValue(RepresentationInstanceList.vrSeedRateSeedsActual.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("seeds1ac-1"), Convert.ToDouble(appliedProduct["RateValue"].ToString()))); break; case ("kernel"): rateValue = new NumericRepresentationValue(RepresentationInstanceList.vrSeedRateSeedsActual.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("seeds1ac-1"), Convert.ToDouble(appliedProduct["RateValue"].ToString()))); break; case ("short ton"): rateValue = new NumericRepresentationValue(RepresentationInstanceList.vrAppRateMassActual.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("ton1ac-1"), Convert.ToDouble(appliedProduct["RateValue"].ToString()))); break; case ("metric ton"): rateValue = new NumericRepresentationValue(RepresentationInstanceList.vrAppRateMassActual.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("t1ac-1"), Convert.ToDouble(appliedProduct["RateValue"].ToString()))); break; case ("pound"): if (appliedProduct["Type"].ToString() == "Seed") { rateValue = new NumericRepresentationValue(RepresentationInstanceList.vrSeedRateMassActual.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("lb1ac-1"), Convert.ToDouble(appliedProduct["RateValue"].ToString()))); } else { rateValue = new NumericRepresentationValue(RepresentationInstanceList.vrAppRateMassActual.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("lb1ac-1"), Convert.ToDouble(appliedProduct["RateValue"].ToString()))); } break; case ("ounce"): rateValue = new NumericRepresentationValue(RepresentationInstanceList.vrAppRateMassActual.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("oz1ac-1"), Convert.ToDouble(appliedProduct["RateValue"].ToString()))); break; case ("kilogram"): if (appliedProduct["Type"].ToString() == "Seed") { rateValue = new NumericRepresentationValue(RepresentationInstanceList.vrSeedRateMassActual.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("kg1ac-1"), Convert.ToDouble(appliedProduct["RateValue"].ToString()))); } else { rateValue = new NumericRepresentationValue(RepresentationInstanceList.vrAppRateMassActual.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("kg1ac-1"), Convert.ToDouble(appliedProduct["RateValue"].ToString()))); } break; case ("gram"): rateValue = new NumericRepresentationValue(RepresentationInstanceList.vrAppRateMassActual.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("g1ac-1"), Convert.ToDouble(appliedProduct["RateValue"].ToString()))); break; case ("fluid ounce"): rateValue = new NumericRepresentationValue(RepresentationInstanceList.vrAppRateVolumeActual.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("floz1ac-1"), Convert.ToDouble(appliedProduct["RateValue"].ToString()))); break; case ("quart"): rateValue = new NumericRepresentationValue(RepresentationInstanceList.vrAppRateVolumeActual.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("qt1ac-1"), Convert.ToDouble(appliedProduct["RateValue"].ToString()))); break; case ("pint"): rateValue = new NumericRepresentationValue(RepresentationInstanceList.vrAppRateVolumeActual.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("pt1ac-1"), Convert.ToDouble(appliedProduct["RateValue"].ToString()))); break; case ("milliliter"): rateValue = new NumericRepresentationValue(RepresentationInstanceList.vrAppRateVolumeActual.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("ml1ac-1"), Convert.ToDouble(appliedProduct["RateValue"].ToString()))); break; case ("liter"): rateValue = new NumericRepresentationValue(RepresentationInstanceList.vrAppRateVolumeActual.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("l1ac-1"), Convert.ToDouble(appliedProduct["RateValue"].ToString()))); break; case ("gallon"): rateValue = new NumericRepresentationValue(RepresentationInstanceList.vrAppRateVolumeActual.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("gal1ac-1"), Convert.ToDouble(appliedProduct["RateValue"].ToString()))); break; case ("centiliter"): rateValue = new NumericRepresentationValue(RepresentationInstanceList.vrAppRateVolumeActual.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("cl1ac-1"), Convert.ToDouble(appliedProduct["RateValue"].ToString()))); break; case ("acre"): break; default: break; } if (rateValue != null) { mv = new MeteredValue(); mv.Value = rateValue; smv.Values.Add(mv); } #endregion // Set the "applied area" for this use of the product (currently hardcoded to be in acres) NumericRepresentationValue areaValue = new NumericRepresentationValue(RepresentationInstanceList.vrTotalAreaCovered.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("ac1"), Convert.ToDouble(appliedProduct["AreaApplied"].ToString()))); mv = new MeteredValue(); mv.Value = areaValue; smv.Values.Add(mv); if (!string.IsNullOrEmpty(appliedProduct["ApplicationMethod"].ToString())) { EnumeratedValue applicationMethod = null; #region Set the product application method switch (appliedProduct["ApplicationMethod"].ToString()) { case ("Aerial"): applicationMethod = new EnumeratedValue { Value = DefinedTypeEnumerationInstanceList.dtiAerial.ToModelEnumMember() }; applicationMethod.Representation = RepresentationInstanceList.dtApplicationMethod.ToModelRepresentation(); break; case ("Air Blast"): applicationMethod = new EnumeratedValue { Value = DefinedTypeEnumerationInstanceList.dtiAirBlast.ToModelEnumMember() }; applicationMethod.Representation = RepresentationInstanceList.dtApplicationMethod.ToModelRepresentation(); break; case ("Chemigation"): applicationMethod = new EnumeratedValue { Value = DefinedTypeEnumerationInstanceList.dtiChemigation.ToModelEnumMember() }; applicationMethod.Representation = RepresentationInstanceList.dtApplicationMethod.ToModelRepresentation(); break; case ("Fertigation"): applicationMethod = new EnumeratedValue { Value = DefinedTypeEnumerationInstanceList.dtiFertigation.ToModelEnumMember() }; applicationMethod.Representation = RepresentationInstanceList.dtApplicationMethod.ToModelRepresentation(); break; case ("Ground - Banded"): applicationMethod = new EnumeratedValue { Value = DefinedTypeEnumerationInstanceList.dtiBand.ToModelEnumMember() }; applicationMethod.Representation = RepresentationInstanceList.dtApplicationMethod.ToModelRepresentation(); break; case ("Ground - Broadcast"): applicationMethod = new EnumeratedValue { Value = DefinedTypeEnumerationInstanceList.dtiBroadcast.ToModelEnumMember() }; applicationMethod.Representation = RepresentationInstanceList.dtApplicationMethod.ToModelRepresentation(); break; case ("Ground - Hooded"): applicationMethod = new EnumeratedValue { Value = DefinedTypeEnumerationInstanceList.dtiHoodedSprayer.ToModelEnumMember() }; applicationMethod.Representation = RepresentationInstanceList.dtApplicationMethod.ToModelRepresentation(); break; case ("Ground - In Furrow"): applicationMethod = new EnumeratedValue { Value = DefinedTypeEnumerationInstanceList.dtiInFurrow.ToModelEnumMember() }; applicationMethod.Representation = RepresentationInstanceList.dtApplicationMethod.ToModelRepresentation(); break; case ("Ground Application"): applicationMethod = new EnumeratedValue { Value = DefinedTypeEnumerationInstanceList.dtiInGround.ToModelEnumMember() }; applicationMethod.Representation = RepresentationInstanceList.dtApplicationMethod.ToModelRepresentation(); break; case ("Planting"): applicationMethod = new EnumeratedValue { Value = DefinedTypeEnumerationInstanceList.dtiPlanter.ToModelEnumMember() }; applicationMethod.Representation = RepresentationInstanceList.dtApplicationMethod.ToModelRepresentation(); break; case ("Re-Planting"): applicationMethod = new EnumeratedValue { Value = DefinedTypeEnumerationInstanceList.dtiPlanter.ToModelEnumMember() }; applicationMethod.Representation = RepresentationInstanceList.dtApplicationMethod.ToModelRepresentation(); break; case ("Sidedress"): applicationMethod = new EnumeratedValue { Value = DefinedTypeEnumerationInstanceList.dtiSideDress.ToModelEnumMember() }; applicationMethod.Representation = RepresentationInstanceList.dtApplicationMethod.ToModelRepresentation(); break; case ("Fumigation"): case ("Ground - Incorporated"): case ("Ground - Seed Treatment"): case ("Ground - Variable Rate"): case ("Storage"): case ("Topdress"): case ("Tree Injection"): case ("Water Run"): default: applicationMethod = new EnumeratedValue { Value = DefinedTypeEnumerationInstanceList.dtiInGround.ToModelEnumMember() }; applicationMethod.Representation = RepresentationInstanceList.dtApplicationMethod.ToModelRepresentation(); break; } if (applicationMethod != null) { mv = new MeteredValue(); mv.Value = applicationMethod; smv.Values.Add(mv); } #endregion } // There is a problem here handling seed totals by bag....will have to come back to this at some point NumericRepresentationValue totalProductValue = null; #region Set the total product switch (appliedProduct["TotalProductUnit"].ToString()) { case ("seed"): totalProductValue = new NumericRepresentationValue(RepresentationInstanceList.vrTotalSeedQuantityAppliedSeed.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("seeds"), Convert.ToDouble(appliedProduct["TotalProductQty"].ToString()))); break; case ("kernel"): totalProductValue = new NumericRepresentationValue(RepresentationInstanceList.vrTotalSeedQuantityAppliedSeed.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("seeds"), Convert.ToDouble(appliedProduct["TotalProductQty"].ToString()))); break; case ("short ton"): totalProductValue = new NumericRepresentationValue(RepresentationInstanceList.vrTotalQuantityAppliedMass.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("ton"), Convert.ToDouble(appliedProduct["TotalProductQty"].ToString()))); break; case ("metric ton"): totalProductValue = new NumericRepresentationValue(RepresentationInstanceList.vrTotalQuantityAppliedMass.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("t"), Convert.ToDouble(appliedProduct["TotalProductQty"].ToString()))); break; case ("pound"): if (appliedProduct["Type"].ToString() == "Seed") { totalProductValue = new NumericRepresentationValue(RepresentationInstanceList.vrTotalSeedQuantityAppliedMass.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("lb"), Convert.ToDouble(appliedProduct["TotalProductQty"].ToString()))); } else { totalProductValue = new NumericRepresentationValue(RepresentationInstanceList.vrTotalQuantityAppliedMass.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("lb"), Convert.ToDouble(appliedProduct["TotalProductQty"].ToString()))); } break; case ("ounce"): totalProductValue = new NumericRepresentationValue(RepresentationInstanceList.vrTotalQuantityAppliedMass.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("oz"), Convert.ToDouble(appliedProduct["TotalProductQty"].ToString()))); break; case ("kilogram"): if (appliedProduct["Type"].ToString() == "Seed") { totalProductValue = new NumericRepresentationValue(RepresentationInstanceList.vrTotalSeedQuantityAppliedMass.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("kg"), Convert.ToDouble(appliedProduct["TotalProductQty"].ToString()))); } else { totalProductValue = new NumericRepresentationValue(RepresentationInstanceList.vrTotalQuantityAppliedMass.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("kg"), Convert.ToDouble(appliedProduct["TotalProductQty"].ToString()))); } break; case ("gram"): totalProductValue = new NumericRepresentationValue(RepresentationInstanceList.vrTotalQuantityAppliedMass.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("g1ac-1"), Convert.ToDouble(appliedProduct["TotalProductQty"].ToString()))); break; case ("fluid ounce"): totalProductValue = new NumericRepresentationValue(RepresentationInstanceList.vrTotalQuantityAppliedVolume.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("floz"), Convert.ToDouble(appliedProduct["TotalProductQty"].ToString()))); break; case ("quart"): totalProductValue = new NumericRepresentationValue(RepresentationInstanceList.vrTotalQuantityAppliedVolume.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("qt"), Convert.ToDouble(appliedProduct["TotalProductQty"].ToString()))); break; case ("pint"): totalProductValue = new NumericRepresentationValue(RepresentationInstanceList.vrTotalQuantityAppliedVolume.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("pt"), Convert.ToDouble(appliedProduct["TotalProductQty"].ToString()))); break; case ("milliliter"): totalProductValue = new NumericRepresentationValue(RepresentationInstanceList.vrTotalQuantityAppliedVolume.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("ml"), Convert.ToDouble(appliedProduct["TotalProductQty"].ToString()))); break; case ("liter"): totalProductValue = new NumericRepresentationValue(RepresentationInstanceList.vrTotalQuantityAppliedVolume.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("l"), Convert.ToDouble(appliedProduct["TotalProductQty"].ToString()))); break; case ("gallon"): totalProductValue = new NumericRepresentationValue(RepresentationInstanceList.vrTotalQuantityAppliedVolume.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("gal"), Convert.ToDouble(appliedProduct["TotalProductQty"].ToString()))); break; case ("centiliter"): totalProductValue = new NumericRepresentationValue(RepresentationInstanceList.vrTotalQuantityAppliedVolume.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("cl"), Convert.ToDouble(appliedProduct["TotalProductQty"].ToString()))); break; case ("acre"): break; default: break; } if (totalProductValue != null) { mv = new MeteredValue(); mv.Value = totalProductValue; smv.Values.Add(mv); } #endregion operation.Data.Add(smv); // Add the OperationSummary to the collection in Summary summary.OperationSummaries.Add(operation); // End - Foreach Product } // Add this Summary to the list summaries.Add(summary); // Add the WorkRecord to the list workRecords.Add(workRecord); // End - Foreach Application } // This property is an IEnumerable so we had to build up the collection in a local list then assign it export.Documents.Summaries = summaries; // This property is an IEnumerable so we had to build up the collection in a local list then assign it export.Documents.WorkRecords = workRecords; // Make sure the target directory exits string outputPath = applicationPath + @"\Output"; if (Directory.Exists(outputPath)) { Directory.Delete(outputPath, true); } if (!Directory.Exists(outputPath)) { Directory.CreateDirectory(outputPath); } admPlugin.Export(export, outputPath); // NOTE: There is a fundamental problem with this version of ADAPT 1.1.0.8 and the ADMPlugin that prevents // the Summary and WorkRecord objects from serializing correctly. This sample will be updated after the MVP // process is complete. }
private void Deserialize(object p) { var dialog = new OpenFileDialog(); dialog.Filter = "Any file(xml,bin,txt or their encoded versions)|*.*"; var result = dialog.ShowDialog(); if (result == null || result == false) { return; } var extension = Path.GetExtension(dialog.SafeFileName); var serializer = serializersFactory.NewSerializer(dialog.FileName); if (serializer == null) { MessageBox.Show("Cannot load this file."); return; } try { Object jewelries; if (SerializationHelper.IsPluginUsed(extension)) { var plugin = PluginFactory.GetPlugin(SerializationHelper.GetPluginExtension(Path.GetExtension(dialog.SafeFileName)), Plugins); if (plugin == null) { MessageBox.Show("Some plugins are missing!"); return; } //get decoded file name var decodedFileName = plugin.Decode(new FileStream(dialog.FileName, FileMode.Open), dialog.FileName); jewelries = serializer.Deserialize(typeof(JewelrySerialized), new FileStream(decodedFileName, FileMode.Open)); //delete decoded file File.Delete(decodedFileName); } else // no plugins were used { jewelries = serializer.Deserialize(typeof(JewelrySerialized), new FileStream(dialog.FileName, FileMode.Open)); } JewelryList = null; JewelryListUI = null; JewelryList = ((JewelrySerialized)jewelries).jewelries; JewelryListUI = new ObservableCollection <Jewelry>(JewelryList); } catch (Exception ex) { MessageBox.Show($"Could not load this file. Either its contents are incorrect or was not generated by this program. Detailed message : {ex.Message}"); } }
private List <ApplicationDataModel> ImportData(string importPluginName, string importDataPath) { if (PluginFactory.AvailablePlugins.Count == 0) { Console.WriteLine("PluginFactory: no plugins available"); return(null); } // Get ImportPlugin // ToDo: [Check] version of plugin // ToDo: Read importDataPath with all available plugins var importPlugin = PluginFactory.GetPlugin(importPluginName); if (importPlugin == null) { Console.WriteLine($"Could not find ImportPlugin {importPluginName}"); return(null); } // Initialise Plugin if (ImportSettings != null) { if (!string.IsNullOrEmpty(ImportSettings.InitialiseString)) { importPlugin.Initialize(ImportSettings.InitialiseString); } } // [Check] if data path is correct if (!Directory.Exists(importDataPath)) { Console.WriteLine($"Incorrect importDataPath {importDataPath}"); return(null); } List <ApplicationDataModel> adms = new List <ApplicationDataModel>(); // To Do (check if possible/needed): Task.Run(() => {}); Console.WriteLine("Starting ADAPT import"); DateTime startTime = DateTime.Now; // Check if Plugin supports the data if (importPlugin.IsDataCardSupported(importDataPath)) { if (ImportSettings != null) { if (ImportSettings.GetProperties() != null) { adms.AddRange(importPlugin.Import(importDataPath, ImportSettings.GetProperties())); } } else { adms.AddRange(importPlugin.Import(importDataPath)); } TimeSpan conversionTime = DateTime.Now.Subtract(startTime); Console.WriteLine($"Completed ADAPT import in {conversionTime}, imported {adms.Count} ApplicationDataModels"); return(adms); } else { Console.WriteLine($"ImportPlugin cannot read the data, not imported!"); return(null); } }
public IPlugin GetPlugin(string pluginName) { return(_pluginFactory.GetPlugin(pluginName)); }
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); }