예제 #1
0
        private async void OnDrop3D(DropInfo dropInfo)
        {
            string xlsName      = dropInfo.Items[0].Data.ToString();
            string xlsLayerName = Module1.GetUniqueLayerName(xlsName);
            string xlsSheetName = Module1.GetUniqueStandaloneTableName(xlsName);
            string xlsTableName = xlsName + "\\" + xlsSheetName;

            // set overwrite flag
            var environments = Geoprocessing.MakeEnvironmentArray(overwriteoutput: true);


            #region await Geoprocessing.ExecuteToolAsync(MakeXYEventLayer_management)

            var result = await Geoprocessing.ExecuteToolAsync("MakeXYEventLayer_management", new string[] {
                xlsTableName,
                "POINT_X",
                "POINT_Y",
                xlsLayerName,
                "WGS_1984"
            }, environments);

            #endregion

            #region await Geoprocessing.ExecuteToolAsync(ApplySymbologyFromLayer_management)

            result = await Geoprocessing.ExecuteToolAsync("ApplySymbologyFromLayer_management", new string[] {
                xlsLayerName,
                @"C:\Data\SDK\Default3DPointSymbols.lyrx"
            });

            #endregion
        }
예제 #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);
        }
예제 #3
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);
        }
예제 #4
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);
            }
        }
예제 #5
0
        private static async Task <string> CreateTheXYEventLayer(DropInfo dropInfo)
        {
            string xlsName      = dropInfo.Items[0].Data.ToString();
            string xlsLayerName = Module1.GetUniqueLayerName(xlsName);
            string xlsTableName = null;

            if (xlsName.ToUpper().EndsWith(".CSV"))
            {
                xlsTableName = xlsName;
            }
            else
            {
                string xlsSheetName = Module1.GetUniqueStandaloneTableName(xlsName);
                xlsTableName = xlsName + "\\" + xlsSheetName;
            }

            // set overwrite flag
            var environments = Geoprocessing.MakeEnvironmentArray(overwriteoutput: true);

            #region Geoprocessing.ExecuteToolAsync(MakeXYEventLayer_management)

            var result = await Geoprocessing.ExecuteToolAsync("MakeXYEventLayer_management", new string[] {
                xlsTableName,
                "X",
                "Y",
                xlsLayerName,
                "WGS_1984"
            }, environments);

            #endregion
            return(xlsLayerName);
        }
예제 #6
0
        private async Task <bool> ExecuteAddFieldTool(BasicFeatureLayer theLayer, KeyValuePair <string, string> field, string fieldType, int?fieldLength = null, bool isNullable = true)
        {
            try
            {
                return(await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
                {
                    var inTable = theLayer.Name;
                    var table = theLayer.GetTable();
                    var dataStore = table.GetDatastore();
                    var workspaceNameDef = dataStore.GetConnectionString();
                    var workspaceName = workspaceNameDef.Split('=')[1];

                    var fullSpec = System.IO.Path.Combine(workspaceName, inTable);
                    System.Diagnostics.Debug.WriteLine($@"Add {field.Key} from {fullSpec}");

                    var parameters = Geoprocessing.MakeValueArray(inTable, field.Key, fieldType.ToUpper(), null, null,
                                                                  fieldLength, field.Value, isNullable ? "NULABLE" : "NON_NULLABLE");
                    var env = Geoprocessing.MakeEnvironmentArray(workspace: workspaceName);
                    var cts = new CancellationTokenSource();
                    var results = Geoprocessing.ExecuteToolAsync("management.AddField", parameters, env, cts.Token,
                                                                 (eventName, o) =>
                    {
                        System.Diagnostics.Debug.WriteLine($@"GP event: {eventName}");
                    });
                    return true;
                }));
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
                return(false);
            }
        }
예제 #7
0
        public static async Task <BA_ReturnCode> CreateGeodatabaseFoldersAsync(string strAoiPath, FolderType fType)
        {
            BA_ReturnCode success = BA_ReturnCode.UnknownError;
            await QueuedTask.Run(() =>
            {
                var environments             = Geoprocessing.MakeEnvironmentArray(workspace: strAoiPath);
                string[] arrGeodatabaseNames = GeodatabaseNames.AllNames;
                if (fType == FolderType.BASIN)
                {
                    arrGeodatabaseNames = GeodatabaseNames.BasinNames;
                }
                {
                    foreach (var item in arrGeodatabaseNames)
                    {
                        var parameters = Geoprocessing.MakeValueArray(strAoiPath, item);
                        var gpResult   = Geoprocessing.ExecuteToolAsync("CreateFileGDB_management", parameters, environments,
                                                                        CancelableProgressor.None, GPExecuteToolFlags.AddToHistory);

                        if (gpResult.Result.IsFailed)
                        {
                            Module1.Current.ModuleLogManager.LogError(nameof(CreateGeodatabaseFoldersAsync),
                                                                      "Unable to create file geodatabase. Error code: " + gpResult.Result.ErrorCode);
                        }
                        else
                        {
                            success = BA_ReturnCode.Success;
                        }
                    }
                }
            });

            return(success);
        }
예제 #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);
        }
예제 #9
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);
        }
예제 #10
0
        private async void OpenEucDistance()
        {
            await CommonMethod.OpenMap(ConstDefintion.ConstMap_SpaceAnalyzeMap);

            string   projectDir   = System.IO.Path.GetDirectoryName(Project.Current.Path);
            string   path         = projectDir + "\\" + ConstDefintion.ConstRaster_RaderRangeDsName;
            Envelope env          = CommonMethod.GetRasterExtent(path).Result;
            var      environments = Geoprocessing.MakeEnvironmentArray(extent: env, mask: ConstDefintion.ConstLayer_RaderRangeLayerName);;

            Geoprocessing.OpenToolDialog("sa.EucDistance", null, environments, true, null);
        }
예제 #11
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");
        }
예제 #12
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());
            }
        }
        //TODO: Fetch is required if <b>IsContainer</b> = <b>true</b>
        //public override void Fetch()
        //    {
        //TODO Retrieve your child items
        //TODO child items must also derive from CustomItemBase
        //this.AddRangeToChildren(children);
        //   }
        private async void CSVToPointFC(string path)
        {
            //Get the folder path
            string folderPath = System.IO.Path.GetDirectoryName(path);

            System.Diagnostics.Debug.WriteLine($"folderPath: {folderPath}");

            var fileNameWithoutExtension = System.IO.Path.GetFileNameWithoutExtension(path);

            System.Diagnostics.Debug.WriteLine($"fileNameWithoutExtension: {fileNameWithoutExtension}");

            //csv
            var csvFileName = $"{fileNameWithoutExtension}.csv";
            var csvFullPath = $@"{System.IO.Path.Combine(folderPath, csvFileName)}";

            //Delete the csv
            System.IO.File.Delete(csvFullPath);// C:\Users\uma2526\Documents\ArcGIS\Projects\CustomItemTest\AlaskaCitiesXY.csv");
            System.Diagnostics.Debug.WriteLine($"Delete: {csvFullPath}");

            //rename .uxh (custom item) to .csv. GP Tool only works with CSV files
            System.IO.File.Copy($@"{path}", csvFullPath, true);
            System.Diagnostics.Debug.WriteLine($"Rename: {csvFullPath}");

            //args for GP Tool
            string input_table = @"C:\Users\uma2526\Documents\ArcGIS\Projects\CustomItemTest\AlaskaCitiesXY.csv";
            var    gbd         = Project.Current.GetItems <GDBProjectItem>().FirstOrDefault().Path;
            string outputFC    = $@"{gbd}\AlaskaCitiesPointConv";
            string XField      = "POINT_X";
            string YField      = "POINT_Y";
            var    sr          = MapView.Active.Map.SpatialReference;

            var environments = Geoprocessing.MakeEnvironmentArray(overwriteoutput: true);
            var cts          = new CancellationTokenSource();

            //Make the GP Tool arg array
            var args = Geoprocessing.MakeValueArray(input_table, outputFC, XField, YField, "", sr);

            //Execute
            _ = await Geoprocessing.ExecuteToolAsync("XYTableToPoint_management", args, environments, cts.Token,
                                                     (eventName, o) =>
            {
                System.Diagnostics.Debug.WriteLine($@"GP event: {eventName}");
            }, GPExecuteToolFlags.None);             //No action is taken, so the new Feature class doesn't get added to the map
        }
예제 #14
0
        public static async Task <BA_ReturnCode> IntersectUnrankedAsync(string strWorkspace, string[] arrInputLayers, string outputLayerPath,
                                                                        string joinAttributes)
        {
            IGPResult gpResult = await QueuedTask.Run(() =>
            {
                var environments = Geoprocessing.MakeEnvironmentArray(workspace: strWorkspace);
                var parameters   = Geoprocessing.MakeValueArray(arrInputLayers, outputLayerPath, joinAttributes);
                return(Geoprocessing.ExecuteToolAsync("Intersect_analysis", parameters, null,
                                                      CancelableProgressor.None, GPExecuteToolFlags.AddToHistory));
            });

            if (gpResult.IsFailed)
            {
                return(BA_ReturnCode.UnknownError);
            }
            else
            {
                return(BA_ReturnCode.Success);
            }
        }
예제 #15
0
        public static async Task <BA_ReturnCode> CopyFeaturesAsync(string strWorkspace, string copyFeatures,
                                                                   string outputFeatures)
        {
            IGPResult gpResult = await QueuedTask.Run(() =>
            {
                var environments = Geoprocessing.MakeEnvironmentArray(workspace: strWorkspace);
                var parameters   = Geoprocessing.MakeValueArray(copyFeatures, outputFeatures);
                return(Geoprocessing.ExecuteToolAsync("CopyFeatures_management", parameters, environments,
                                                      CancelableProgressor.None, GPExecuteToolFlags.AddToHistory));
            });

            if (gpResult.IsFailed)
            {
                return(BA_ReturnCode.UnknownError);
            }
            else
            {
                return(BA_ReturnCode.Success);
            }
        }
        // Snap Environment
        // Snap a line to polygon EDGE, END of another line and to points VERTEX
        //
        protected override async void OnClick()
        {
            GPExecuteToolFlags executeFlags = GPExecuteToolFlags.AddOutputsToMap | GPExecuteToolFlags.GPThread | GPExecuteToolFlags.AddToHistory;

            string toolName = "edit.Snap";

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

            // make a copy of the input data - this data will be snapped to data specified in snap environment
            var inputFeatures = @"C:\\data\Snapping.gdb\otherline";

            // snapEnvironment parameter is of ValueTable type
            var snapEnvironments = @"C:\\data\Snapping.gdb\poly EDGE '15 Meters';C:\\data\Snapping.gdb\line END '15 Meters';C:\\data\Snapping.gdb\points VERTEX '18 Meters'";

            var parameters2 = Geoprocessing.MakeValueArray(inputFeatures, snapEnvironments);

            var gpResult = await Geoprocessing.ExecuteToolAsync(toolName, parameters2, environments, null, null, executeFlags);

            Geoprocessing.ShowMessageBox(gpResult.Messages, "GP Messages", gpResult.IsFailed ? GPMessageBoxStyle.Error : GPMessageBoxStyle.Default);
        }
예제 #17
0
        private async void OnDrop2D(DropInfo dropInfo)
        {
            string xlsName      = dropInfo.Items[0].Data.ToString();
            string xlsLayerName = Module1.GetUniqueLayerName(xlsName);
            string xlsSheetName = Module1.GetUniqueStandaloneTableName(xlsName);
            string xlsTableName = xlsName + "\\" + xlsSheetName;

            // set overwrite flag
            var environments = Geoprocessing.MakeEnvironmentArray(overwriteoutput: true);

            //To use Excel files in Pro, you need Microsoft Access Database Engine 2016.
            //Refer to the Pro Help topic "Work with Microsoft Excel files" for more information on dowloading the required driver.
            //https://pro.arcgis.com/en/pro-app/help/data/excel/work-with-excel-in-arcgis-pro.htm

            #region Geoprocessing.ExecuteToolAsync(MakeXYEventLayer_management)
            var cts    = new CancellationTokenSource();
            var result = await Geoprocessing.ExecuteToolAsync("MakeXYEventLayer_management", new string[] {
                xlsTableName,
                "POINT_X",
                "POINT_Y",
                xlsLayerName,
                "WGS_1984"
            }, environments, cts.Token,
                                                              (eventName, o) =>
            {
                System.Diagnostics.Debug.WriteLine($@"GP event: {eventName}");
            });

            #endregion

            #region Assign Symbology (from Location layer)
            var featureLayer = MapView.Active.Map.GetLayersAsFlattenedList().OfType <FeatureLayer>().Where(fl => fl.Name.Contains(xlsLayerName)).FirstOrDefault();
            await ModifyLayerSymbologyFromLyrFileAsync(featureLayer, @"C:\Data\SDK\Default2DPointSymbols.lyrx");

            //  @"C:\Data\SDK\Default2DPointSymbols.lyrx"

            #endregion
        }
예제 #18
0
        protected override async void OnClick()
        {
            await QueuedTask.Run(async() =>
            {
                var pointLayer = (MapView.Active.Map.Layers.First(layer => layer.Name.Equals("Points")) as FeatureLayer);

                if (pointLayer == null)
                {
                    MessageBox.Show("Point layer can not be found...", "Error", System.Windows.MessageBoxButton.OK);
                    return;
                }

                try
                {
                    // Get the path to the layer's feature class and path to a new 200-foot buffer feature class
                    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);
                    // Place parameters into an array
                    var parameters = Geoprocessing.MakeValueArray(infc, outfc, "100 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
                    var gpResult = await Geoprocessing.ExecuteToolAsync("Buffer_analysis", parameters, environments);
                    // Show a messagebox with the results
                    Geoprocessing.ShowMessageBox(gpResult.Messages, "GP Meldingen", gpResult.IsFailed ? GPMessageBoxStyle.Error : GPMessageBoxStyle.Default);
                    MessageBox.Show("Lets Unit test here..");
                }
                catch (Exception exc)
                {
                    // Catch any exception found and display in a message box
                    MessageBox.Show("Exception caught while trying to run GP tool: " + exc.Message);
                    return;
                }
            });
        }
예제 #19
0
        public async Task BufferPointLayerTest()
        {
            IGPResult gpResult = null;

            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);
                // Place parameters into an array
                var parameters = Geoprocessing.MakeValueArray(infc, outfc, "100 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);
            });

            Assert.IsNotNull(gpResult, "GPResult is null");
            Assert.AreEqual(0, gpResult.ErrorCode, "GP Tool failed or cancelled");
        }
예제 #20
0
        public async Task <IGPResult> ExecuteSnap()
        {
            var environments = Geoprocessing.MakeEnvironmentArray(overwriteoutput: true);

            string toolName = @"Snap_edit";

            // Snap tool takes multiple inputs each of which has
            // Three (3) parts: a feature class or layer, a string value and a distance
            // Each part is separated by a semicolon - you can get example of sytax from the tool documentation page
            var snapEnv = @"'C:/SnapProject/fgdb.gdb/line_1' END '2 Meters';'C:/SnapProject/fgdb.gdb/points_1' VERTEX '1 Meters';'C:/SnapProject/fgdb.gdb/otherline_1' END '20 Meters'";

            var parameters = await QueuedTask.Run(() =>
            {
                var infc = @"C:/SnapProject/fgdb.gdb/poly_1";
                return(Geoprocessing.MakeValueArray(infc, snapEnv));
            });

            GPExecuteToolFlags tokens = GPExecuteToolFlags.RefreshProjectItems | GPExecuteToolFlags.GPThread | GPExecuteToolFlags.AddToHistory;

            var gpResult = await Geoprocessing.ExecuteToolAsync(toolName, parameters, environments, null, null, flags : tokens);

            return(gpResult);
        }
예제 #21
0
        private static async Task <bool> ExecuteAsync([NotNull] string tool,
                                                      [NotNull] IReadOnlyList <string> parameters)
        {
            Assert.ArgumentNotNullOrEmpty(tool, nameof(tool));
            Assert.ArgumentNotNull(parameters, nameof(parameters));
            Assert.ArgumentCondition(parameters.Count > 0, "no parameter");

            _msg.VerboseDebug($"{tool}, Parameters: {StringUtils.Concatenate(parameters, ", ")}");

            IReadOnlyList <KeyValuePair <string, string> > environments =
                Geoprocessing.MakeEnvironmentArray(overwriteoutput: true);

            IGPResult result = await Geoprocessing.ExecuteToolAsync(tool, parameters, environments);

            if (!result.IsFailed)
            {
                return(true);
            }

            _msg.Info(
                $"{tool} has failed: {StringUtils.Concatenate(Format(result.Messages), ", ")}, Parameters: {StringUtils.Concatenate(parameters, ", ")}");
            return(false);
        }
        public async Task <IGPResult> Execute_ApplySymbologyFromFeatureLayer()
        {
            var environments = Geoprocessing.MakeEnvironmentArray(overwriteoutput: true);

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

            if (map == null)
            {
                throw new Exception("No active map found!");
            }

            var featLayers = map.Map.Layers.OfType <FeatureLayer>();

            // 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
            FeatureLayer symbologyLayer = featLayers.ElementAt(1);

            // Make sure you have fields with the POP2000 name.
            var    sourceField = "POP2000";
            var    targetField = "POP2000";
            var    fieldType   = "VALUE_FIELD";
            String fieldInfo   = String.Format("{0} {1} {2}", fieldType, sourceField, targetField); // VALUE_FIELD NAME NAME")

            MessageBox.Show(fieldInfo);
            var parameters = Geoprocessing.MakeValueArray(targetLayer, symbologyLayer, 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);
        }
예제 #23
0
        // Setting environments, MakeEnvironmentArray
        public async void SetEnvironment()   // Task<IGPResult>
        {
            #region gp_environments
            // get the syntax of the tool from Python window or from tool help page
            string in_features  = @"C:\data\data.gdb\HighwaysWeb84";
            string out_features = @"C:\data\data.gdb\HighwaysUTM";
            var    param_values = Geoprocessing.MakeValueArray(in_features, out_features);

            // crate the spatial reference object to pass as an argument to management.CopyFeatures tool
            var sp_ref = await QueuedTask.Run(() => {
                return(SpatialReferenceBuilder.CreateSpatialReference(26911));    // UTM 83 11N: 26911
            });

            // set output coordinate system environment
            var environments = Geoprocessing.MakeEnvironmentArray(outputCoordinateSystem: sp_ref);
            // set environments in the 3rd parameter
            var gp_result = await Geoprocessing.ExecuteToolAsync("management.CopyFeatures", param_values, environments, null, null, GPExecuteToolFlags.AddOutputsToMap);

            Geoprocessing.ShowMessageBox(gp_result.Messages, "Contents", GPMessageBoxStyle.Default, "Window Title");

            //return gp_result;

            #endregion
        }
예제 #24
0
        public override async Task <Table> ConvertCSVToTable(string inputPath, string outPath, string outName)

        {
            //ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("Override for Biodiversidad has been done");
            var progressDlg = new ProgressDialog("Leyendo datos del archivo CSV seleccionado", "Cancelar", false);

            progressDlg.Show();

            var parameters_totable = Geoprocessing.MakeValueArray(inputPath, outPath, outName);
            var result_totable     = await Geoprocessing.ExecuteToolAsync("conversion.TableToTable", parameters_totable, null, new CancelableProgressorSource(progressDlg).Progressor, GPExecuteToolFlags.None);

            var parameters_toxylayer = Geoprocessing.MakeValueArray(inputPath, "longitud", "latitud", "bioxy" + outName);
            var environments_xy      = Geoprocessing.MakeEnvironmentArray(overwriteoutput: true, workspace: outPath);
            var result_toxylayer     = await Geoprocessing.ExecuteToolAsync("management.MakeXYEventLayer", parameters_toxylayer, environments_xy, new CancelableProgressorSource(progressDlg).Progressor, GPExecuteToolFlags.None);

            var layer = result_toxylayer.Values[0];

            var fc_name           = "bio" + outName;
            var parameters_tofc   = Geoprocessing.MakeValueArray(layer, outPath, fc_name);
            var environments_tofc = Geoprocessing.MakeEnvironmentArray(overwriteoutput: true, workspace: outPath);
            var result_tofc       = await Geoprocessing.ExecuteToolAsync("conversion.FeatureClassToFeatureClass", parameters_tofc, environments_tofc, new CancelableProgressorSource(progressDlg).Progressor, GPExecuteToolFlags.None);



            var table = await QueuedTask.Run(() =>
            {
                var geodatabase = new Geodatabase(new FileGeodatabaseConnectionPath(new Uri(outPath)));
                Table tbl       = geodatabase.OpenDataset <FeatureClass>(fc_name);
                return(tbl);
            });

            Type = "File Geodatabase Feature Class";

            progressDlg.Hide();
            return(table);
        }
예제 #25
0
        protected override async void OnClick()
        {
            await QueuedTask.Run(async() =>
            {
                // Check to see if the selected layer is a feature layer, if not, then prompt and exit.
                if (!(MapView.Active.GetSelectedLayers().First() is FeatureLayer featLayer))
                {
                    MessageBox.Show("Selecteer een feature layer in de Contents pane.", "Info");
                    return;
                }

                try
                {
                    // Get the path to the layer's feature class and path to a new 200-foot buffer feature class
                    string FLPath     = featLayer.GetFeatureClass().GetDatastore().GetPath().AbsolutePath;
                    var FLPathCombine = Path.GetFullPath(FLPath);
                    string name       = featLayer.GetFeatureClass().GetName();
                    string infc       = Path.Combine(FLPathCombine, name);
                    string outfc      = Path.Combine(FLPathCombine, "Buffer_" + featLayer.Name);
                    // Place parameters into an array
                    var parameters = Geoprocessing.MakeValueArray(infc, outfc, "100 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
                    var gpResult = await Geoprocessing.ExecuteToolAsync("Buffer_analysis", parameters, environments);
                    // Show a messagebox with the results
                    Geoprocessing.ShowMessageBox(gpResult.Messages, "GP Meldingen", gpResult.IsFailed ? GPMessageBoxStyle.Error : GPMessageBoxStyle.Default);
                }
                catch (Exception exc)
                {
                    // Catch any exception found and display in a message box
                    MessageBox.Show("Exception caught while trying to run GP tool: " + exc.Message);
                    return;
                }
            });
        }
예제 #26
0
        protected override async void OnClick()
        {
            string databasePath = @"E:\GISTech\2021\ProProjects\GPSTracks\GPSTracks.gdb";
            string gpxFile      = @"E:\GISTech\2021\ProScripts\clubrit.gpx";
            string outfc        = Path.Combine(databasePath, "GPSTracks");

            await QueuedTask.Run(async() =>
            {
                try
                {
                    // Place parameters into an array
                    var parameters = Geoprocessing.MakeValueArray(gpxFile, outfc);
                    // 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
                    var gpResult = await Geoprocessing.ExecuteToolAsync("GPXtoFeatures_conversion", parameters, environments);

                    if (gpResult.IsFailed == false)
                    {
                        parameters = Geoprocessing.MakeValueArray(outfc, "NEW_SELECTION", "\"Type\" = 'TRKPT'");
                        gpResult   = await Geoprocessing.ExecuteToolAsync("SelectLayerByAttribute_management", parameters, environments, null, null, GPExecuteToolFlags.None);
                        if (gpResult.IsFailed != true)
                        {
                            parameters = Geoprocessing.MakeValueArray(outfc, Path.Combine(databasePath, "MyRide"), "Name");
                            gpResult   = await Geoprocessing.ExecuteToolAsync("PointsToLine_management", parameters, environments);
                        }
                    }
                }
                catch (Exception exc)
                {
                    // Catch any exception found and display in a message box
                    MessageBox.Show("Exception caught while trying to run GP tool: " + exc.Message);
                    return;
                }
            });
        }
예제 #27
0
        private async Task <bool> ExecuteDeleteFieldTool(BasicFeatureLayer theLayer, string fieldName)
        {
            try
            {
                return(await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
                {
                    var inTable = theLayer.Name;
                    var table = theLayer.GetTable();
                    var dataStore = table.GetDatastore();
                    var workspaceNameDef = dataStore.GetConnectionString();
                    var workspaceName = workspaceNameDef.Split('=')[1];

                    var fullSpec = System.IO.Path.Combine(workspaceName, inTable);
                    System.Diagnostics.Debug.WriteLine($@"Delete {fieldName} from {fullSpec}");

                    var parameters = Geoprocessing.MakeValueArray(fullSpec, fieldName);
                    var env = Geoprocessing.MakeEnvironmentArray(workspace: workspaceName);
                    var cts = new CancellationTokenSource();
                    var results = Geoprocessing.ExecuteToolAsync("management.DeleteField", parameters, env, cts.Token,
                                                                 (eventName, o) =>
                    {
                        System.Diagnostics.Debug.WriteLine($@"GP event: {eventName}");
                        if (eventName == "OnMessage")
                        {
                            System.Diagnostics.Debug.WriteLine($@"Msg: {o}");
                        }
                    });
                    return true;
                }));
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
                return(false);
            }
        }
예제 #28
0
        public async void CalculateVolume()
        {
            // Update the viewmodel with values
            await FrameworkApplication.SetCurrentToolAsync("esri_mapping_exploreTool");

            // Check for an active mapview
            if (MapView.Active == null)
            {
                ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("No MapView currently active. Exiting...", "Info");
                return;
            }

            // Prompt before proceeding with calculation work
            var response = ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("Save edits and calculate volume on selected features?", "Calculate Volume", System.Windows.MessageBoxButton.YesNo, System.Windows.MessageBoxImage.Question);

            if (response == MessageBoxResult.No)
            {
                return;
            }

            // Save edits for reading by GP Tool
            await Project.Current.SaveEditsAsync();

            try
            {
                await QueuedTask.Run((Func <Task>)(async() =>
                {
                    var featLayer = MapView.Active.Map.FindLayers("Clip_Polygon_Asphalt").FirstOrDefault() as FeatureLayer;

                    // Get the selected records, and check/exit if there are none:
                    var featSelectionOIDs = featLayer.GetSelection().GetObjectIDs();
                    if (featSelectionOIDs.Count == 0)
                    {
                        ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("No records selected for layer, " + featLayer.Name + ". Exiting...", "Info");
                        return;
                    }

                    // Ensure value for reference plane direction combobox
                    else if (SceneCalcVM.ReferencePlaneDirection == string.Empty)
                    {
                        ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("Choose the reference plane direction for volume calculation. Exiting...", "Value Needed");
                        return;
                    }

                    // Ensure there is a valid reference plane height/elevation value for all selected records
                    RowCursor cursorPolygons = featLayer.GetSelection().Search(null);
                    while (cursorPolygons.MoveNext())
                    {
                        using (Row currentRow = cursorPolygons.Current)
                        {
                            // Get values for dockpane
                            if (currentRow["PlaneHeight"] == null || Convert.ToDouble(currentRow["PlaneHeight"]) == 0)
                            {
                                string currentObjectID = Convert.ToString(currentRow["ObjectID"]);
                                ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("Empty or invalid Plane Height value for polygon ObjectID: " + currentObjectID + ". Exiting...", "Value Needed");
                                return;
                            }
                        }
                    }

                    // Get the name of the attribute to update, and the value to set:
                    double refPlaneElevation = SceneCalcVM.ReferencePlaneElevation;
                    string refPlaneDirection = SceneCalcVM.ReferencePlaneDirection;

                    // Start progress dialog
                    var progDialog = new ProgressDialog("Calculating Volume");
                    var progSource = new ProgressorSource(progDialog);
                    progDialog.Show();

                    // Prepare for run of GP tool -- Get the path to the LAS point layer
                    string surfaceLASDataset = "Asphalt3D_132_point_cloud.las";
                    var inspector            = new ArcGIS.Desktop.Editing.Attributes.Inspector(true);
                    inspector.Load(featLayer, featSelectionOIDs);
                    inspector["PlaneDirection"]    = refPlaneDirection;
                    inspector["DateOfCapture"]     = DateTime.Today;
                    inspector["ElevationMeshFile"] = "Asphalt3D_132_3d_mesh.slpk";
                    inspector["PointCloudFile"]    = surfaceLASDataset;

                    var editOp  = new EditOperation();
                    editOp.Name = "Edit " + featLayer.Name + ", " + Convert.ToString(featSelectionOIDs.Count) + " records.";
                    editOp.Modify(inspector);
                    await editOp.ExecuteAsync();
                    await Project.Current.SaveEditsAsync();

                    // Get the path to the layer's feature class
                    string infc = featLayer.Name;
                    // Place parameters into an array
                    var parameters = Geoprocessing.MakeValueArray(surfaceLASDataset, infc, "PlaneHeight", refPlaneDirection);
                    // 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
                    var gpResult = await Geoprocessing.ExecuteToolAsync("PolygonVolume_3d", parameters, environments);
                    // Save edits again
                    await Project.Current.SaveEditsAsync();

                    // var selFeatures = featLayer.GetSelection().GetCount();
                    RowCursor cursorPolygons2 = featLayer.GetSelection().Search(null);

                    double totalVolumeValue  = 0;
                    double totalAreaValue    = 0;
                    double totalWeightInTons = 0;
                    double currentVolume;
                    double currentSArea;
                    double currentWeightInTons;
                    long currentOID;

                    while (cursorPolygons2.MoveNext())
                    {
                        using (Row currentRow = cursorPolygons2.Current)
                        {
                            // Get values for dockpane
                            currentOID = currentRow.GetObjectID();
                            // Convert volume in cubic meters from source data to cubic feet:
                            currentVolume = Convert.ToDouble(currentRow["Volume"]) * 35.3147;
                            // Convert surface area value from square meters from source data to square feet:
                            currentSArea = Convert.ToDouble(currentRow["SArea"]) * 10.7639;
                            // Calculate estimated weight in tons = (volume in square foot * 103.7 pounds per square foot) / 2000 pounds per ton
                            currentWeightInTons = (currentVolume * 103.7) / 2000;

                            // Update the new cubic feet and square feet values for the feature:
                            inspector.Load(featLayer, currentOID);
                            inspector["Volume"]          = currentVolume;
                            inspector["SArea"]           = currentSArea;
                            inspector["EstWeightInTons"] = currentWeightInTons;
                            await inspector.ApplyAsync();

                            // Combine values for display of total volume and surface area values in the dockpane:
                            totalVolumeValue  = totalVolumeValue + currentVolume;
                            totalAreaValue    = totalAreaValue + currentSArea;
                            totalWeightInTons = totalWeightInTons + currentWeightInTons;
                        }
                    }

                    // Apply the values and refresh selection update
                    await Project.Current.SaveEditsAsync();
                    FeatureSelectionChanged();
                    // Close progress dialog
                    progDialog.Hide();
                    progDialog.Dispose();
                }));
            }
            catch (Exception exc)
            {
                // Catch any exception found and display a message box.
                ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("Exception caught while trying to perform update: " + exc.Message);
                return;
            }
        }
예제 #29
0
        private async void sensitivity_Click(object sender, EventArgs e)
        {
            if ((combo1.SelectedIndex == -1) || (combo2.SelectedIndex == -1))
            {
                MessageBox.Show("Cannot Perform SA unless criteria and simulations are selected");
                return;
            }

            Stream         myStream;
            SaveFileDialog saveFileDialog1 = new SaveFileDialog();

            saveFileDialog1.Filter           = "csv file (*.csv)|*.csv|txt file (*.txt)|*.txt|All files (*.*)|*.*";
            saveFileDialog1.FilterIndex      = 2;
            saveFileDialog1.RestoreDirectory = true;
            saveFileDialog1.OverwritePrompt  = true;
            saveFileDialog1.AddExtension     = true;
            saveFileDialog1.InitialDirectory = @"D:\";
            saveFileDialog1.Title            = "Save your Weights";

            if (saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
                if ((myStream = saveFileDialog1.OpenFile()) != null)
                {
                    myStream.Close();
                }
            }
            else if (saveFileDialog1.ShowDialog() == DialogResult.Cancel)
            {
                MessageBox.Show("Save your csv file");
            }
            string fp = saveFileDialog1.FileName;

            // Defining new array rowSum1 with length as rowSum
            double[] rowSum1 = new double[rowSum.Length];

            for (int i = -Convert.ToInt16(combo2.SelectedItem) / 2; i <= Convert.ToInt16(combo2.SelectedItem) / 2; i++)
            {
                //Copy contents of rowSum to rowSum1 starting from 0
                rowSum.CopyTo(rowSum1, 0);
                if (i == 0)
                {
                    continue;
                }

                for (int j = 0; j < combo1.Items.Count; j++)
                {
                    //Positive Increment
                    if (i > 0)
                    {
                        rowSum1[combo1.SelectedIndex] = rowSum1[combo1.SelectedIndex] * (1 + 0.01 * i);
                        if (j != combo1.SelectedIndex)
                        {
                            System.Diagnostics.Debug.WriteLine(i);
                            rowSum1[j] = rowSum1[j] * (1 - 0.01 * i);
                        }
                    }
                    //Negative increment
                    else
                    {
                        rowSum1[combo1.SelectedIndex] = rowSum1[combo1.SelectedIndex] * (1 + 0.01 * i);
                        if (j != combo1.SelectedIndex)
                        {
                            System.Diagnostics.Debug.WriteLine(i);
                            rowSum1[j] = rowSum1[j] * (1 - 0.01 * i);
                        }
                    }
                    //Skip iteration when i=0
                }
                // Writing to a csv file
                string delimiter = ",";
                int    length    = rowSum1.Length;
                //using (TextWriter writer = File.CreateText(filepath))

                using (TextWriter writer = File.AppendText(fp))
                //StringBuilder csv = new StringBuilder();
                {
                    if (i == -Convert.ToInt16(combo2.SelectedItem) / 2)
                    {
                        writer.Write(string.Join(delimiter, "% Change", "\t"));
                        for (int a = 0; a < combo1.Items.Count; a++)
                        {
                            writer.Write(string.Join(delimiter, combo1.Items[a], "\t"));
                        }
                    }


                    writer.Write("\n");
                    writer.Write(string.Join(delimiter, i, "\t"));


                    for (int index = 0; index < length; index++)
                    {
                        writer.Write(string.Join(delimiter, Math.Round(rowSum1[index], 3), "\t"));
                    }
                }

                List <string> paths    = new List <string>();
                List <string> myinputs = new List <string>();
                TreeNode      test     = Goal.TopNode;

                //Geoprocessing starts here
                await QueuedTask.Run(() =>
                                     // Task t = QueuedTask.Run(() =>
                {
                    for (int k = 0; k < test.Nodes.Count; k++)
                    {
                        var rlyrs = MapView.Active.Map.Layers.OfType <RasterLayer>();  //All raster layers in Map View
                        //System.Diagnostics.Debug.WriteLine(test.Nodes[k].Tag.ToString());
                        for (int m = 0; m < rlyrs.Count(); m++)
                        {
                            RasterLayer rlyr    = rlyrs.ElementAt(m);                                 //raster layer at specific position
                            Datastore dataStore = rlyr.GetRaster().GetRasterDataset().GetDatastore(); //getting datasource
                            if (test.Nodes[k].Tag.ToString() == rlyr.Name)
                            {
                                paths.Add(dataStore.GetPath().AbsolutePath);//getting path

                                System.Diagnostics.Debug.WriteLine(rlyr.Name);
                                System.Diagnostics.Debug.WriteLine(paths);

                                // adding paths to input array, value and weights
                                myinputs.Add(paths.ElementAt(k) + "/" + rlyr.GetRaster().GetRasterDataset().GetName() + " VALUE " + Math.Round(rowSum1[k], 3));
                                System.Diagnostics.Debug.WriteLine(rowSum1);
                            }
                        }
                    }
                });

                //t.Wait();

                System.Diagnostics.Debug.WriteLine(i);
                if (i < 0)
                {
                    string output_raster = System.IO.Path.Combine(Project.Current.DefaultGeodatabasePath, "SuitedRaster" + Math.Abs(i) + "down");
                    System.Diagnostics.Debug.WriteLine(output_raster);
                    var    param_values = Geoprocessing.MakeValueArray(myinputs, output_raster);
                    string toolpath     = "sa.WeightedSum";
                    var    env          = Geoprocessing.MakeEnvironmentArray(scratchWorkspace: Project.Current.DefaultGeodatabasePath);
                    await Geoprocessing.ExecuteToolAsync(toolpath, param_values, env, null, null, GPExecuteToolFlags.None);

                    progressLabel.Text = "Reclassification Started for " + Math.Abs(i).ToString() + " % decrease";

                    List <string> remap = new List <string>();
                    remap.Add("0 0.6 1");
                    remap.Add("0.6 0.8 2");
                    remap.Add("0.8 1 3");
                    string output_raster2 = System.IO.Path.Combine(Project.Current.DefaultGeodatabasePath, "SuitedRaster" + Math.Abs(i) + "downreclass");
                    var    kufli          = Geoprocessing.MakeValueArray(output_raster, "VALUE", remap, output_raster2);
                    //Geoprocessing.OpenToolDialog("sa.Reclassify", kufli);
                    await Geoprocessing.ExecuteToolAsync("sa.Reclassify", kufli, env, null, null, GPExecuteToolFlags.AddOutputsToMap);

                    progressLabel.Text = "Reclassification Finished for " + Math.Abs(i).ToString() + " % decrease. Check in TOC";
                }
                else
                {
                    string output_raster = System.IO.Path.Combine(Project.Current.DefaultGeodatabasePath, "SuitedRaster" + i + "up");
                    System.Diagnostics.Debug.WriteLine(output_raster);
                    var    param_values = Geoprocessing.MakeValueArray(myinputs, output_raster);
                    string toolpath     = "sa.WeightedSum";
                    var    env          = Geoprocessing.MakeEnvironmentArray(scratchWorkspace: Project.Current.DefaultGeodatabasePath);
                    await Geoprocessing.ExecuteToolAsync(toolpath, param_values, env, null, null, GPExecuteToolFlags.None);

                    progressLabel.Text = "Reclassification Started for " + Math.Abs(i).ToString() + " % increase";

                    List <string> remap = new List <string>();
                    remap.Add("0 0.6 1");
                    remap.Add("0.6 0.8 2");
                    remap.Add("0.8 1 3");
                    string output_raster2 = System.IO.Path.Combine(Project.Current.DefaultGeodatabasePath, "SuitedRaster" + Math.Abs(i) + "upreclass");
                    var    kufli          = Geoprocessing.MakeValueArray(output_raster, "VALUE", remap, output_raster2);

                    //Geoprocessing.OpenToolDialog("sa.Reclassify", kufli);

                    await Geoprocessing.ExecuteToolAsync("sa.Reclassify", kufli, env, null, null, GPExecuteToolFlags.AddOutputsToMap);

                    progressLabel.Text = "Reclassification Finished for " + Math.Abs(i).ToString() + " % increase. Check in TOC";
                }

                foreach (var Item in rowSum1)
                {
                    System.Diagnostics.Debug.WriteLine(Item.ToString());
                }


                // Clear the array so that new values will be populated based on original
                Array.Clear(rowSum1, 0, rowSum1.Length);

                //Clear inputs
                myinputs.Clear();
            }
        }
예제 #30
0
        //Click to create suitability map
        private async void Map_Click(object sender, EventArgs e)
        {
            var           mapView  = MapView.Active;
            List <string> paths    = new List <string>();
            List <string> myinputs = new List <string>();
            TreeNode      test     = Goal.TopNode;


            //using await instead of .wait() for asynchronous execution (Wait for the results)
            await QueuedTask.Run(() =>
            {
                for (int k = 0; k < test.Nodes.Count; k++)
                {
                    var rlyrs = MapView.Active.Map.Layers.OfType <RasterLayer>();  //All raster layers
                    for (int m = 0; m < rlyrs.Count(); m++)
                    {
                        RasterLayer rlyr    = rlyrs.ElementAt(m);                                 //raster layer at specific position
                        Datastore dataStore = rlyr.GetRaster().GetRasterDataset().GetDatastore(); //getting datasource

                        if (test.Nodes[k].Tag.ToString() == rlyr.Name)
                        {
                            paths.Add(dataStore.GetPath().AbsolutePath);

                            myinputs.Add(paths.ElementAt(k) + "/" + rlyr.GetRaster().GetRasterDataset().GetName() + " VALUE " + Math.Round(rowSum[k], 2));
                        }
                    }
                }
            });

            //t.Wait();


            //For Showing Progress Window (Optional)
            var progDlgWS = new ProgressDialog("Weighted Sum Progress", "Cancel", 100, true);

            progDlgWS.Show();

            var progSrc = new CancelableProgressorSource(progDlgWS);

            string weightedSumRaster = System.IO.Path.Combine(Project.Current.DefaultGeodatabasePath, "SuitedRaster");
            var    param_values      = Geoprocessing.MakeValueArray(myinputs, weightedSumRaster);

            //use toolBoxNameAlias.toolName.Alias
            string toolpath = "sa.WeightedSum";

            var env = Geoprocessing.MakeEnvironmentArray(scratchWorkspace: Project.Current.DefaultGeodatabasePath);

            //Uncomment below line if you want GP tool to open in Pro
            //Geoprocessing.OpenToolDialog(toolpath, param_values);

            progressLabel.Text = "Performing Weighted Sum, please wait...";

            //Not adding weighted sum result to map since its intermediate result
            await Geoprocessing.ExecuteToolAsync(toolpath, param_values, env, new CancelableProgressorSource(progDlgWS).Progressor, GPExecuteToolFlags.AddOutputsToMap);

            progressLabel.Text = "Weighted Sum processing complete. Reclassification started";

            //Hide the progress once done.
            progDlgWS.Hide();


            //----Use this if you want to see GP result messages---//
            //---The flow doesnt progress forward unless you close this box-----//
            //Geoprocessing.ShowMessageBox(wsresult.Messages, "GP Messages",
            //wsresult.IsFailed ? GPMessageBoxStyle.Error : GPMessageBoxStyle.Default);


            //Creating a list string to store reclass values
            List <string> remap = new List <string>();

            //Classifying into 3 classes, values can be modified as per user needs.

            remap.Add("0 0.6 1");   //Least Suitable
            remap.Add("0.6 0.8 2"); //Moderately Suitable
            remap.Add("0.8 1 3");   //Highly Suitable

            string output_raster2  = System.IO.Path.Combine(Project.Current.DefaultGeodatabasePath, "SuitedRaster" + "reclass0");
            var    reclassedRaster = Geoprocessing.MakeValueArray(weightedSumRaster, "VALUE", remap, output_raster2);
            await Geoprocessing.ExecuteToolAsync("sa.Reclassify", reclassedRaster, env, null, null, GPExecuteToolFlags.AddOutputsToMap);

            progressLabel.Text = "Reclassification Completed. Check in TOC";
            //Geoprocessing.OpenToolDialog("sa.Reclassify", reclassedRaster);
        }