Beispiel #1
0
        public static async Task <BA_ReturnCode> ClipRasterAsync(string strInputRaster, string strRectangle, string strOutputRaster,
                                                                 string strTemplateDataset, string strNoDataValue, bool bUseClippingGeometry,
                                                                 string strWorkspace, string strSnapRaster)
        {
            string strClippingGeometry = "NONE";

            if (bUseClippingGeometry == true)
            {
                strClippingGeometry = "ClippingGeometry";
            }
            IGPResult gpResult = await QueuedTask.Run(() =>
            {
                var environments = Geoprocessing.MakeEnvironmentArray(workspace: strWorkspace, snapRaster: strSnapRaster);
                var parameters   = Geoprocessing.MakeValueArray(strInputRaster, strRectangle, strOutputRaster, strTemplateDataset,
                                                                strNoDataValue, strClippingGeometry);
                return(Geoprocessing.ExecuteToolAsync("Clip_management", parameters, null,
                                                      CancelableProgressor.None, GPExecuteToolFlags.AddToHistory));
            });

            if (gpResult.IsFailed)
            {
                return(BA_ReturnCode.UnknownError);
            }
            else
            {
                return(BA_ReturnCode.Success);
            }
        }
Beispiel #2
0
        public async Task <bool> ExportKMLLayer(string layerName, string outputPath)
        {
            bool success = false;

            await QueuedTask.Run(async() =>
            {
                List <object> arguments = new List <object>();

                // TODO: if the user moves or renames this group, this layer name may no longer be valid
                arguments.Add("Distance And Direction" + @"\" + layerName);
                arguments.Add(outputPath);

                var parameters   = Geoprocessing.MakeValueArray(arguments.ToArray());
                var environments = Geoprocessing.MakeEnvironmentArray(overwriteoutput: true);

                string gpTool    = "LayerToKML_conversion";
                IGPResult result = await Geoprocessing.ExecuteToolAsync(
                    gpTool,
                    parameters,
                    environments,
                    null,
                    null,
                    GPExecuteToolFlags.Default);

                success = CheckResultAndReportMessages(result, gpTool, arguments);
            });

            return(success);
        }
Beispiel #3
0
        private async void OnGetJsonSelectionFinished(GetJsonSelectionFinishedEventArgs args)
        {
            //fill the textbox with info
            DockpaneGJViewModel.UpdateText("Processing...");
            //execute the geoprocessing tool for creating json
            Task <IGPResult> myTsk = QueuedTask.Run(() =>
            {
                BasicFeatureLayer bfl = args.BasicFL;
                var flist             = new List <object>()
                {
                    bfl,
                };
                Task <IGPResult> taskRes =
                    Geoprocessing.ExecuteToolAsync("conversion.FeaturesToJSON", Geoprocessing.MakeValueArray(flist, null, "FORMATTED"));
                return(taskRes);
            });
            IGPResult resultaat = await myTsk;

            if (!(resultaat.IsFailed || resultaat.IsCanceled))
            {
                ////filename
                string filename = myTsk.Result.ReturnValue;
                //read the file
                string contents = File.ReadAllText(@filename);
                //fill the textbox
                DockpaneGJViewModel.UpdateText(contents);
                //delete the file
                File.Delete(filename);
            }
            else
            {
                DockpaneGJViewModel.UpdateText("Sorry, but features can't be converted to JSON. " + Environment.NewLine + "Response: " + resultaat.ReturnValue);
            }
        }
Beispiel #4
0
        /// <summary>
        /// Create a feature class in the default geodatabase of the project.
        /// </summary>
        /// <param name="featureclassName">Name of the feature class to be created.</param>
        /// <param name="featureclassType">Type of feature class to be created. Options are:
        /// <list type="bullet">
        /// <item>POINT</item>
        /// <item>MULTIPOINT</item>
        /// <item>POLYLINE</item>
        /// <item>POLYGON</item></list></param>
        /// <returns></returns>
        private static async Task CreateLayer(string featureclassName, string featureclassType)
        {
            List <object> arguments = new List <object>
            {
                // store the results in the default geodatabase
                CoreModule.CurrentProject.DefaultGeodatabasePath,
                // name of the feature class
                featureclassName,
                // type of geometry
                featureclassType,
                // no template
                "",
                // no z values
                "DISABLED",
                // no m values
                "DISABLED"
            };
            await QueuedTask.Run(() =>
            {
                // spatial reference
                arguments.Add(SpatialReferenceBuilder.CreateSpatialReference(3857));
            });

            IGPResult result = await Geoprocessing.ExecuteToolAsync("CreateFeatureclass_management", Geoprocessing.MakeValueArray(arguments.ToArray()));
        }
Beispiel #5
0
        public static async Task <IList <double> > GetDemStatsAsync(string aoiPath, string maskPath, double adjustmentFactor)
        {
            IList <double> returnList = new List <double>();

            try
            {
                string    sDemPath     = GeodatabaseTools.GetGeodatabasePath(aoiPath, GeodatabaseNames.Surfaces, true) + Constants.FILE_DEM_FILLED;
                double    dblMin       = -1;
                var       parameters   = Geoprocessing.MakeValueArray(sDemPath, "MINIMUM");
                var       environments = Geoprocessing.MakeEnvironmentArray(workspace: aoiPath, mask: maskPath);
                IGPResult gpResult     = await Geoprocessing.ExecuteToolAsync("GetRasterProperties_management", parameters, environments,
                                                                              CancelableProgressor.None, GPExecuteToolFlags.AddToHistory);

                bool success = Double.TryParse(Convert.ToString(gpResult.ReturnValue), out dblMin);
                returnList.Add(dblMin - adjustmentFactor);
                double dblMax = -1;
                parameters = Geoprocessing.MakeValueArray(sDemPath, "MAXIMUM");
                gpResult   = await Geoprocessing.ExecuteToolAsync("GetRasterProperties_management", parameters, environments,
                                                                  CancelableProgressor.None, GPExecuteToolFlags.AddToHistory);

                success = Double.TryParse(Convert.ToString(gpResult.ReturnValue), out dblMax);
                returnList.Add(dblMax + adjustmentFactor);
            }
            catch (Exception e)
            {
                Module1.Current.ModuleLogManager.LogError(nameof(GetDemStatsAsync),
                                                          "Exception: " + e.Message);
            }
            return(returnList);
        }
Beispiel #6
0
        public static async Task <BA_ReturnCode> BufferLinesAsync(string strInputFeatures, string strOutputFeatures, string strDistance,
                                                                  string strLineSide, string strLineEndOption, string strDissolveOption)
        {
            if (String.IsNullOrEmpty(strLineSide))
            {
                strLineSide = "FULL";
            }
            if (String.IsNullOrEmpty(strLineEndOption))
            {
                strLineEndOption = "ROUND";
            }
            if (String.IsNullOrEmpty(strDissolveOption))
            {
                strDissolveOption = "ALL";
            }
            IGPResult gpResult = await QueuedTask.Run(() =>
            {
                var parameters = Geoprocessing.MakeValueArray(strInputFeatures, strOutputFeatures, strDistance, strLineSide,
                                                              strLineEndOption, strDissolveOption);
                return(Geoprocessing.ExecuteToolAsync("Buffer_analysis", parameters, null,
                                                      CancelableProgressor.None, GPExecuteToolFlags.AddToHistory));
            });

            if (gpResult.IsFailed)
            {
                Module1.Current.ModuleLogManager.LogError(nameof(BufferLinesAsync),
                                                          "Unable to buffer features. Error code: " + gpResult.ErrorCode);
                return(BA_ReturnCode.UnknownError);
            }
            else
            {
                Module1.Current.ModuleLogManager.LogDebug(nameof(BufferLinesAsync), "Lines buffered successfully");
                return(BA_ReturnCode.Success);
            }
        }
Beispiel #7
0
        protected async Task <string> AddSchema(string tableName, string[] fieldNames, string[] fieldTypes, string[] splitter, string csvFilePath)
        {
            // loop to create table schema

            /*  Note field properties are: tableName, fieldName, DataType: [Text, Short, Long, Float, Date, Blob, Raster Guid, Double],
             *  Domain, Default, fieldLength [number of characters ie, 32], AliasName, "NULLABLE", "NON_REQUIRED", null
             *  ref: https://community.esri.com/thread/246461-arcgis-pro-sdk-create-and-add-new-standalone-table
             */

            for (int i = 0; i < fieldNames.Length; i++)
            {
                IReadOnlyList <string> addFieldParams = Geoprocessing.MakeValueArray(new object[] { tableName, fieldNames[i], fieldTypes[i],
                                                                                                    null, null, 255, "", "NULLABLE", "NON_REQUIRED", null });
                IGPResult result = await Geoprocessing.ExecuteToolAsync("management.AddField", addFieldParams);

                if (result.IsFailed)
                {
                    ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("Unable to create Field");
                }
            }

            var dataLoad = LoadData(splitter, fieldTypes, csvFilePath);

            return("ok");
        }
Beispiel #8
0
        public static async Task <IList <double> > GetDemStatsAsync(string aoiPath, double adjustmentFactor)
        {
            IList <double> returnList = new List <double>();

            try
            {
                string    sMask        = GeodatabaseTools.GetGeodatabasePath(aoiPath, GeodatabaseNames.Aoi, true) + Constants.FILE_AOI_VECTOR;
                string    sDemPath     = GeodatabaseTools.GetGeodatabasePath(aoiPath, GeodatabaseNames.Surfaces, true) + Constants.FILE_DEM_FILLED;
                double    dblMin       = -1;
                var       parameters   = Geoprocessing.MakeValueArray(sDemPath, "MINIMUM");
                var       environments = Geoprocessing.MakeEnvironmentArray(workspace: aoiPath, mask: sMask);
                IGPResult gpResult     = await Geoprocessing.ExecuteToolAsync("GetRasterProperties_management", parameters, environments,
                                                                              ArcGIS.Desktop.Framework.Threading.Tasks.CancelableProgressor.None, GPExecuteToolFlags.AddToHistory);

                bool success = Double.TryParse(Convert.ToString(gpResult.ReturnValue), out dblMin);
                returnList.Add(dblMin - adjustmentFactor);
                double dblMax = -1;
                parameters = Geoprocessing.MakeValueArray(sDemPath, "MAXIMUM");
                gpResult   = await Geoprocessing.ExecuteToolAsync("GetRasterProperties_management", parameters, environments,
                                                                  ArcGIS.Desktop.Framework.Threading.Tasks.CancelableProgressor.None, GPExecuteToolFlags.AddToHistory);

                success = Double.TryParse(Convert.ToString(gpResult.ReturnValue), out dblMax);
                returnList.Add(dblMax + adjustmentFactor);
            }
            catch (Exception e)
            {
                Debug.WriteLine("GetDemStatsAsync: " + e.Message);
            }
            return(returnList);
        }
 private ProSuiteQAResponse FormatProSuiteResponse(IGPResult result)
 {
     // TODO return response data by Finished event or here?
     return(new ProSuiteQAResponse()
     {
         Error = ParseGPResultError(result),
         ErrorMessage = result.ErrorMessages.FirstOrDefault()?.Text,
         ResponseData = ParseGPResultValues(result)
     });
 }
        // TODO temporary extract results only from known QA XML GP Service
        // - first vales is path to zip
        // - second will be error counts (not implemented)
        private object ParseGPResultValues(IGPResult result)
        {
            if (result?.ReturnValue == null)
            {
                return(null);
            }

            // TODO - should set return data type
            return(result.Values.FirstOrDefault()?.ToString());
        }
Beispiel #11
0
        public static async Task RasterDomain(string input_raster)
        {
            string timestamp        = DateTime.Now.ToString("yyyyMMddHHmmss");
            string featureClassName = "AOI_Raster_Polygon_" + timestamp;

            string output = Path.Combine(Project.Current.DefaultGeodatabasePath, featureClassName);

            var parameters = Geoprocessing.MakeValueArray(input_raster, output, "POLYGON");

            IGPResult gpResult = await Geoprocessing.ExecuteToolAsync("ddd.RasterDomain", parameters);
        }
Beispiel #12
0
        public async Task <IGPResult> Execute_ApplySymbologyFromFeatureLayer()
        {
            var environments = Geoprocessing.MakeEnvironmentArray(overwriteoutput: true);

            var prj = Project.Current;
            var map = MapView.Active;

            var featLayers = map.Map.Layers.OfType <FeatureLayer>().Where(l => l.Name.StartsWith("Crimes", StringComparison.OrdinalIgnoreCase));

            if (featLayers.Count() < 1)
            {
                MessageBox.Show("Unable to find Crimes layer: the topmost Crime layer is the target layer for the symbology, the symbology source is a lyrx file");
                return(null);
            }

            // the first layer in TOC is without any symbology
            FeatureLayer targetLayer = featLayers.ElementAt(0);

            // the second layer has the symbology
            // symbology from the 2nd layer will be applied to the first layer
            //Create instance of BrowseProjectFilter using the id for Pro's Lyrx files filter
            BrowseProjectFilter bf = new BrowseProjectFilter("esri_browseDialogFilters_layers_lyrx");
            //Display the filter in an Open Item dialog
            OpenItemDialog lyrxOpenDlg = new OpenItemDialog
            {
                Title        = "Symbology Input Layer",
                MultiSelect  = false,
                BrowseFilter = bf
            };
            bool?ok = lyrxOpenDlg.ShowDialog();

            if (!ok.HasValue || !ok.Value)
            {
                return(null);
            }
            // Full path for the lyrx file
            var lryxItem = lyrxOpenDlg.Items.FirstOrDefault().Path;

            var    sourceField = "Major_Offense_Type";
            var    targetField = "Major_Offense_Type";
            var    fieldType   = "VALUE_FIELD";
            String fieldInfo   = String.Format("{0} {1} {2}", fieldType, sourceField, targetField);           // VALUE_FIELD NAME NAME")

            MessageBox.Show("Field Info for symbology: " + fieldInfo);

            var parameters = Geoprocessing.MakeValueArray(targetLayer, lryxItem, fieldInfo);             //, symbologyFields, updateSymbology);

            // Does not Add outputs to Map as GPExecuteToolFlags.AddOutputsToMap is not used
            GPExecuteToolFlags executeFlags = GPExecuteToolFlags.RefreshProjectItems | GPExecuteToolFlags.GPThread | GPExecuteToolFlags.AddToHistory;

            IGPResult result = await Geoprocessing.ExecuteToolAsync("ApplySymbologyFromLayer_management", parameters, null, null, null, executeFlags);

            return(result);
        }
Beispiel #13
0
        /// <summary>
        /// Create a feature class
        /// </summary>
        /// <param name="dataset">Name of the feature class to be created.</param>
        /// <param name="featureclassType">Type of feature class to be created. Options are:
        /// <list type="bullet">
        /// <item>POINT</item>
        /// <item>MULTIPOINT</item>
        /// <item>POLYLINE</item>
        /// <item>POLYGON</item></list></param>
        /// <param name="connection">connection path</param>
        /// <param name="spatialRef">SpatialReference</param>
        /// <param name="graphicsList">List of graphics</param>
        /// <param name="mapview">MapView object</param>
        /// <param name="isKML">Is this a kml output</param>
        /// <returns></returns>
        private static async Task CreateFeatureClass(string dataset, GeomType geomType, string connection, SpatialReference spatialRef, List <Graphic> graphicsList, MapView mapview, bool isKML = false)
        {
            try
            {
                string strGeomType = geomType == GeomType.PolyLine ? "POLYLINE" : "POLYGON";

                List <object> arguments = new List <object>();
                // store the results in the geodatabase
                arguments.Add(connection);
                // name of the feature class
                arguments.Add(dataset);
                // type of geometry
                arguments.Add(strGeomType);
                // no template
                arguments.Add("");
                // no z values
                arguments.Add("DISABLED");
                // no m values
                arguments.Add("DISABLED");
                arguments.Add(spatialRef);

                //IReadOnlyList<string> valueArray = null;
                //await QueuedTask.Run(async () =>
                //{
                //    valueArray = Geoprocessing.MakeValueArray(arguments.ToArray());
                //});

                //block the CIM for a second
                //Task.Delay(5000).Wait();
                var       valueArray = Geoprocessing.MakeValueArray(arguments.ToArray());
                IGPResult result     = await Geoprocessing.ExecuteToolAsync("CreateFeatureclass_management", valueArray);

                await CreateFeatures(graphicsList);

                if (isKML)
                {
                    await KMLUtils.ConvertLayerToKML(connection, dataset, MapView.Active);

                    // Delete temporary Shapefile
                    string[] extensionNames     = { ".cpg", ".dbf", ".prj", ".shx", ".shp" };
                    string   datasetNoExtension = Path.GetFileNameWithoutExtension(dataset);
                    foreach (string extension in extensionNames)
                    {
                        string shapeFile = Path.Combine(connection, datasetNoExtension + extension);
                        File.Delete(shapeFile);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
        internal static async void ExecuteBufferGP(CancelationSource cancelType)
        {
            string toolName = "Buffer_analysis";

            //input layer, output dataset, size of buffer
            string[] toolParams = new string[] { @"intrstat",
                                                 @"C:\Data\SDK\Test\ForTheUC_2014\usa_output.gdb\intrstat_Buffer1",
                                                 "30 Miles" };

            //environment parameters from http://resources.arcgis.com/en/help/main/10.2/index.html#//018z0000004s000000
            ForTheUcModule.Current.GPHelper.AddEnvironmentParameter(new Tuple <string, string>("OverwriteOutput", "True"));

            IGPResult result = null;

            if (cancelType == CancelationSource.withCancelationToken)
            {
                result = await ForTheUcModule.Current.GPHelper.ExecuteToolWithCancellationTokenSource(toolName, toolParams);
            }
            else
            {
                CancelableProgressorSource cps = new CancelableProgressorSource(string.Format("{0} running", toolName),
                                                                                string.Format("{0} canceled", toolName));
                result = await ForTheUcModule.Current.GPHelper.ExecuteToolWithCancelableProgressor(toolName, toolParams, cps);
            }

            //check the result
            StringBuilder sb = new StringBuilder();

            if (result.IsCanceled)
            {
                MessageBox.Show(Application.Current.MainWindow, string.Format("{0} was canceled", toolName), toolName);
            }
            else if (result.IsFailed)
            {
                //there was an error and execution was terminated
                foreach (var msg in result.Messages)
                {
                    sb.AppendLine(msg.Text);
                }
                string message = string.Format("{0} execution failed\r\n=======================\r\n{1}", toolName, sb.ToString());
                MessageBox.Show(Application.Current.MainWindow, message, toolName + " Error");
            }
            else
            {
                //success - access results
                foreach (var msg in result.Messages)
                {
                    sb.AppendLine(msg.Text);
                }
                string message = string.Format("{0} complete\r\n=======================\r\n{1}", toolName, sb.ToString());
                MessageBox.Show(Application.Current.MainWindow, message, toolName + " Success");
            }
        }
Beispiel #15
0
        public async Task IntersectTest()
        {
            IGPResult gpResult       = null;
            Geometry  lijnShape      = null;
            Geometry  buffer50Shape  = null;
            Geometry  buffer150Shape = null;

            FeatureLayer lineLayer = _map.Layers.First(layer => layer.Name.Equals("Lines")) as FeatureLayer;

            await QueuedTask.Run(async() =>
            {
                FeatureLayer pointLayer = _map.Layers.First(layer => layer.Name.Equals("Points")) as FeatureLayer;
                string FLPath           = pointLayer.GetFeatureClass().GetDatastore().GetPath().AbsolutePath;
                var FLPathCombine       = Path.GetFullPath(FLPath);
                string name             = pointLayer.GetFeatureClass().GetName();
                string infc             = Path.Combine(FLPathCombine, name);
                string outfc            = Path.Combine(FLPathCombine, $"Buffer_{pointLayer.Name}_50");
                // Place parameters into an array
                var parameters = Geoprocessing.MakeValueArray(infc, outfc, "50 Meter");
                // Place environment settings in an array, in this case, OK to over-write
                var environments = Geoprocessing.MakeEnvironmentArray(overwriteoutput: true);
                // Execute the GP tool with parameters
                gpResult = await Geoprocessing.ExecuteToolAsync("Buffer_analysis", parameters, environments);

                var gdb         = pointLayer.GetTable().GetDatastore() as Geodatabase;
                var fclBuffer50 = gdb.OpenDataset <FeatureClass>("Buffer_Points_50");

                outfc      = Path.Combine(FLPathCombine, $"Buffer_{pointLayer.Name}_150");
                parameters = Geoprocessing.MakeValueArray(infc, outfc, "150 Meter");
                gpResult   = await Geoprocessing.ExecuteToolAsync("Buffer_analysis", parameters, environments);

                var fclBuffer150 = gdb.OpenDataset <FeatureClass>("Buffer_Points_150");

                var temp = lineLayer.Search();
                temp.MoveNext();
                lijnShape = (temp.Current as Feature).GetShape();

                temp = fclBuffer50.Search();
                temp.MoveNext();
                buffer50Shape = (temp.Current as Feature).GetShape();

                temp = fclBuffer150.Search();
                temp.MoveNext();
                buffer150Shape = (temp.Current as Feature).GetShape();
            });

            Assert.IsNotNull(gpResult, "GPResult is null");
            Assert.AreEqual(0, gpResult.ErrorCode, "GP Tool failed or cancelled");

            Assert.IsTrue(GeometryEngine.Instance.Intersects(lijnShape, buffer150Shape), "De punten en lijnen intersecten niet op 150 meter");
            Assert.IsTrue(GeometryEngine.Instance.Intersects(lijnShape, buffer50Shape), "De punten en lijnen intersecten niet op 50 meter");
        }
        protected override async void OnClick()
        {
            try
            {
                IGPResult toolResult = await Execute_ApplySymbologyFromFeatureLayer();

                Geoprocessing.ShowMessageBox(toolResult.Messages, "GP Messages", toolResult.IsFailed ? GPMessageBoxStyle.Error : GPMessageBoxStyle.Default);
            }
            catch (Exception ex)
            {
                MessageBox.Show($@"Exception thrown: {ex}");
            }
        }
Beispiel #17
0
        private static async Task CreateFeatureClass(string dataset, string connection, SpatialReference spatialRef, List <MapPoint> mapPointList, MapView mapview, bool isKML = false)
        {
            try
            {
                List <object> arguments = new List <object>();
                // store the results in the geodatabase
                arguments.Add(connection);
                // name of the feature class
                arguments.Add(dataset);
                // type of geometry
                arguments.Add("POINT");
                // no template
                arguments.Add("");
                // m values
                arguments.Add("DISABLED");
                // no z values
                arguments.Add("DISABLED");
                arguments.Add(spatialRef);

                var env = Geoprocessing.MakeEnvironmentArray(overwriteoutput: true);

                var valueArray = Geoprocessing.MakeValueArray(arguments.ToArray());

                IGPResult result = await Geoprocessing.ExecuteToolAsync("CreateFeatureclass_management",
                                                                        valueArray,
                                                                        env,
                                                                        null,
                                                                        null,
                                                                        GPExecuteToolFlags.Default);

                await CreateFeatures(mapPointList);

                if (isKML)
                {
                    await KMLUtils.ConvertLayerToKML(connection, dataset, MapView.Active);

                    // Delete temporary Shapefile
                    string[] extensionNames     = { ".cpg", ".dbf", ".prj", ".shx", ".shp" };
                    string   datasetNoExtension = Path.GetFileNameWithoutExtension(dataset);
                    foreach (string extension in extensionNames)
                    {
                        string shapeFile = Path.Combine(connection, datasetNoExtension + extension);
                        File.Delete(shapeFile);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
Beispiel #18
0
        protected async void CreateTable(string tableName, string[] fieldNames, string[] fieldTypes)
        {
            //  Using the default geodatabase here. You can add a dialog and set yours if you want to.



            IReadOnlyList <string> createParams = Geoprocessing.MakeValueArray(new object[] { Project.Current.DefaultGeodatabasePath, tableName, null, null });
            IGPResult result = await Geoprocessing.ExecuteToolAsync("management.CreateTable", createParams);

            if (result.IsFailed)
            {
                ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("Unable to create table");
            }
        }
        /// <summary>
        /// Converts a layer to kml
        /// </summary>
        /// <param name="kmzOutputPath">Location of output file</param>
        /// <param name="datasetName">Name of output kmz file</param>
        /// <param name="mapview">MapView object</param>
        /// <returns></returns>
        public static async Task ConvertLayerToKML(string kmzOutputPath, string datasetName, MapView mapview)
        {
            try
            {
                string nameNoExtension = Path.GetFileNameWithoutExtension(datasetName);

                List <object> projArg     = new List <object>();
                var           srout       = SpatialReferenceBuilder.CreateSpatialReference(4326);
                string        outshp      = nameNoExtension + "_proj";
                string        projshpPath = Path.Combine(kmzOutputPath, outshp + ".shp");
                string        shppath     = Path.Combine(kmzOutputPath, nameNoExtension + ".shp");
                projArg.Add(shppath);
                projArg.Add(projshpPath);
                projArg.Add(srout);
                var       projvalueArray = Geoprocessing.MakeValueArray(projArg.ToArray());
                IGPResult projresult     = await Geoprocessing.ExecuteToolAsync("Project_management", projvalueArray);

                List <object> arguments2 = new List <object>();
                arguments2.Add(outshp);
                string fullPath = Path.Combine(kmzOutputPath, datasetName);
                arguments2.Add(fullPath);

                var       valueArray = Geoprocessing.MakeValueArray(arguments2.ToArray());
                IGPResult result     = await Geoprocessing.ExecuteToolAsync("LayerToKML_conversion", valueArray);

                // Remove the layer from the TOC
                Layer layer1 = null;
                Layer layer2 = null;
                ReadOnlyObservableCollection <Layer> layers = MapView.Active.Map.Layers;
                foreach (Layer layer in layers)
                {
                    if (layer.Name == outshp)
                    {
                        layer1 = layer;
                    }
                    else if (layer.Name == nameNoExtension)
                    {
                        layer2 = layer;
                    }
                }
                //var layer = MapView.Active.GetSelectedLayers()[0];
                MapView.Active.Map.RemoveLayer(layer1);
                MapView.Active.Map.RemoveLayer(layer2);
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message);
            }
        }
Beispiel #20
0
        public static async Task <BA_ReturnCode> DeleteDatasetAsync(string datasetPath)
        {
            var       parameters = Geoprocessing.MakeValueArray(datasetPath);
            IGPResult gpResult   = await Geoprocessing.ExecuteToolAsync("Delete_management", parameters, null,
                                                                        ArcGIS.Desktop.Framework.Threading.Tasks.CancelableProgressor.None, GPExecuteToolFlags.AddToHistory);

            if (gpResult.IsFailed)
            {
                return(BA_ReturnCode.UnknownError);
            }
            else
            {
                return(BA_ReturnCode.Success);
            }
        }
Beispiel #21
0
        public static async Task <BA_ReturnCode> DeleteFeatureClassFieldsAsync(string featureClassPath, string[] arrFieldsToDelete)
        {
            var       parameters = Geoprocessing.MakeValueArray(featureClassPath, arrFieldsToDelete);
            IGPResult gpResult   = await Geoprocessing.ExecuteToolAsync("DeleteField_management", parameters, null,
                                                                        CancelableProgressor.None, GPExecuteToolFlags.AddToHistory);

            if (gpResult.IsFailed)
            {
                return(BA_ReturnCode.UnknownError);
            }
            else
            {
                return(BA_ReturnCode.Success);
            }
        }
        public async static Task <BasicFeatureLayer> CreateDamFeatureClass(string name)
        {
            var existingLayer = MapView.Active.Map.FindLayers(name).FirstOrDefault();

            if (existingLayer != null)
            {
                return(existingLayer as BasicFeatureLayer);
            }

            SharedFunctions.Log("Creating DamCandidates layer");
            List <object> arguments = new List <object> {
                CoreModule.CurrentProject.DefaultGeodatabasePath, name, "POLYLINE", "", "DISABLED", "ENABLED"
            };

            arguments.Add(SpatialReference);
            IGPResult result = await Geoprocessing.ExecuteToolAsync("CreateFeatureclass_management", Geoprocessing.MakeValueArray(arguments.ToArray()));

            var layer = MapView.Active.Map.FindLayers(name).FirstOrDefault() as BasicFeatureLayer;
            await SharedFunctions.ExecuteAddFieldTool(layer, "ContourID", "LONG");

            await SharedFunctions.ExecuteAddFieldTool(layer, "StartPointID", "LONG");

            await SharedFunctions.ExecuteAddFieldTool(layer, "EndPointID", "LONG");

            await SharedFunctions.ExecuteAddFieldTool(layer, "ContourHeight", "SHORT");

            await SharedFunctions.ExecuteAddFieldTool(layer, "LengthRating", "FLOAT");

            await SharedFunctions.ExecuteAddFieldTool(layer, "DistanceOnLine", "LONG");

            await SharedFunctions.ExecuteAddFieldTool(layer, "Length", "SHORT");

            await SharedFunctions.ExecuteAddFieldTool(layer, "StartPointDistance", "LONG");

            await SharedFunctions.ExecuteAddFieldTool(layer, "EndPointDistance", "LONG");

            await SharedFunctions.ExecuteAddFieldTool(layer, "DamHeight", "SHORT");

            await SharedFunctions.ExecuteAddFieldTool(layer, "DamVolume", "LONG");

            await SharedFunctions.ExecuteAddFieldTool(layer, "ReservoirVolume", "LONG");

            await SharedFunctions.ExecuteAddFieldTool(layer, "VolumeRating", "FLOAT");

            await SharedFunctions.ExecuteAddFieldTool(layer, "DamSpansContourStart", "SHORT");

            return(layer);
        }
        private static async Task ConvertGeoJSONToFeatures(string in_geojsonfile)
        {
            string timestamp        = DateTime.Now.ToString("yyyyMMddHHmmss");
            string featureClassName = "AOI_GeoJSON_Polygon_" + timestamp;
            string output           = Path.Combine(Project.Current.DefaultGeodatabasePath, featureClassName);

            var parameters = Geoprocessing.MakeValueArray(in_geojsonfile, output, "POLYGON");

            IGPResult gpResult = await Geoprocessing.ExecuteToolAsync("conversion.JSONToFeatures", parameters);

            //return string.IsNullOrEmpty(gpResult.ReturnValue) ? $@"Error in gp tool: {gpResult.ErrorMessages}" : $@"Ok: {gpResult.ReturnValue}";
            if (string.IsNullOrEmpty(gpResult.ReturnValue))
            {
                ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show($@"Error in gp tool: {gpResult.ErrorMessages}");
            }
        }
Beispiel #24
0
        //The data referenced in this snippet can be downloaded from the arcgis-pro-sdk-community-samples repo
        //https://github.com/Esri/arcgis-pro-sdk-community-samples
        protected async Task <string> CreateRings(EditingTemplate currentTemplate)
        {
            var valueArray = await QueuedTask.Run(() =>
            {
                return(Geoprocessing.MakeValueArray(currentTemplate.MapMember.Name,
                                                    @"C:\Data\FeatureTest\FeatureTest.gdb\Points_MultipleRingBuffer",
                                                    new List <string> {
                    "1000", "2000"
                }, "Meters", "Distance",
                                                    "ALL", "FULL"));
            });

            IGPResult gpResult = await Geoprocessing.ExecuteToolAsync("Analysis.MultipleRingBuffer", valueArray);

            return(string.IsNullOrEmpty(gpResult.ReturnValue)
                ? $@"Error in gp tool: {gpResult.ErrorMessages}"
                : $@"Ok: {gpResult.ReturnValue}");
        }
Beispiel #25
0
        public static async Task <BA_ReturnCode> SetNullAsync(string strInputRaster, string strConstant, string strOutputRaster, string strWhere)
        {
            IGPResult gpResult = await QueuedTask.Run(() =>
            {
                var parameters = Geoprocessing.MakeValueArray(strInputRaster, strConstant, strOutputRaster, strWhere);
                return(Geoprocessing.ExecuteToolAsync("SetNull_sa", parameters, null,
                                                      CancelableProgressor.None, GPExecuteToolFlags.AddToHistory));
            });

            if (gpResult.IsFailed)
            {
                return(BA_ReturnCode.UnknownError);
            }
            else
            {
                return(BA_ReturnCode.Success);
            }
        }
Beispiel #26
0
        public static async Task <BA_ReturnCode> AddFieldAsync(string featureClassPath, string fieldName, string dataType)
        {
            IGPResult gpResult = await QueuedTask.Run(() =>
            {
                var parameters = Geoprocessing.MakeValueArray(featureClassPath, fieldName, dataType);
                return(Geoprocessing.ExecuteToolAsync("AddField_management", parameters, null,
                                                      CancelableProgressor.None, GPExecuteToolFlags.AddToHistory));
            });

            if (gpResult.IsFailed)
            {
                return(BA_ReturnCode.UnknownError);
            }
            else
            {
                return(BA_ReturnCode.Success);
            }
        }
Beispiel #27
0
        public static async Task <BA_ReturnCode> NearAsync(string strInputFeatures, string strNearFeatures)
        {
            IGPResult gpResult = await QueuedTask.Run(() =>
            {
                var parameters = Geoprocessing.MakeValueArray(strInputFeatures, strNearFeatures);
                return(Geoprocessing.ExecuteToolAsync("Near_analysis", parameters, null,
                                                      CancelableProgressor.None, GPExecuteToolFlags.AddToHistory));
            });

            if (gpResult.IsFailed)
            {
                return(BA_ReturnCode.UnknownError);
            }
            else
            {
                return(BA_ReturnCode.Success);
            }
        }
Beispiel #28
0
        public static async Task CreateFeatureClass(string geodatabasepath, SpatialReference spatialReference, string featureclassName, string featureclassType)
        {
            List <object> arguments = new List <object>
            {
                geodatabasepath,
                featureclassName,
                featureclassType,
                "",
                "DISABLED",
                "DISABLED"
            };
            await QueuedTask.Run(() =>
            {
                // spatial reference
                arguments.Add(spatialReference);
            });

            IGPResult result = await Geoprocessing.ExecuteToolAsync("CreateFeatureclass_management", Geoprocessing.MakeValueArray(arguments.ToArray()));
        }
        private async void CreateVectorTilePackage_Callback(string eventName, object o)
        {
            Debug.WriteLine("eventname:" + eventName);
            if (eventName == "OnEndExecute")
            {
                IGPResult res         = (IGPResult)o;
                string    packagePath = res.ReturnValue;

                if (!string.IsNullOrEmpty(packagePath) && File.Exists(packagePath))
                {
                    string summary = res.Parameters.Where(t => t.Item1 == "summary").First().Item3;
                    string tags    = res.Parameters.Where(t => t.Item1 == "tags").First().Item3;

                    await QueuedTask.Run(() => baseMapLayer.SetVisibility(true));
                    await UploadAndPublishPackage(packagePath, summary, tags);

                    ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("Uploaden en publiceren afgerond!", "Publiseren gereed.", System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Information);
                }
            }
        }
Beispiel #30
0
        public async static Task <BasicFeatureLayer> CreatePolygonFeatureClass(string name)
        {
            var existingLayer = MapView.Active.Map.FindLayers(name).FirstOrDefault();

            if (existingLayer != null)
            {
                return(existingLayer as BasicFeatureLayer);
            }
            List <object> arguments = new List <object> {
                CoreModule.CurrentProject.DefaultGeodatabasePath, name, "POLYGON", "", "DISABLED", "ENABLED"
            };

            arguments.Add(SpatialReference);
            IGPResult result = await Geoprocessing.ExecuteToolAsync("CreateFeatureclass_management", Geoprocessing.MakeValueArray(arguments.ToArray()));

            var layer = MapView.Active.Map.FindLayers(name).FirstOrDefault() as BasicFeatureLayer;
            await SharedFunctions.ExecuteAddFieldTool(layer, "DamID", "LONG");

            return(layer);
        }