예제 #1
0
        /// <summary>
        /// Execute a tool in A
        /// </summary>
        /// <param name="toolName"></param>
        /// <param name="args"></param>
        /// <returns></returns>
        private static async Task <IGPResult> ExecuteTool(String toolName, params object[] args)
        {
            var toolArgs            = Geoprocessing.MakeValueArray(args);
            Task <IGPResult> result = Geoprocessing.ExecuteToolAsync(toolName, toolArgs, null, null, null);

            return(await result);
        }
예제 #2
0
        /// <summary>
        /// The MakeQueryLayer Geoprocessing tool is used to create a Query Layer consisting of
        /// all the datasets which reference the selected domain
        /// </summary>
        /// <param name="item">The newly selected combo box item</param>
        protected override void OnSelectionChange(ComboBoxItem item)
        {
            if (item == null)
            {
                return;
            }

            if (string.IsNullOrEmpty(item.Text))
            {
                return;
            }

            if (String.IsNullOrEmpty(gdbItemsOwner))
            {
                return;
            }
            // HACK: Currently the API does not have any Getters for obtaining the Connection Properties or any other info. This will be fixed soon.
            // Until then we are getting the first enterprise connection to make the GP call.
            string physicalPath = Project.Current.GetItems <GDBProjectItem>().First(projectItem => projectItem.Path != null && projectItem.Path.Contains(".sde")).Path;

            string QueryLayerName             = String.Format("RelatedDomains{0}", item.Text);
            string Query                      = String.Format("SELECT ClassItems.Name, ClassItems.Path FROM (SELECT Relationships.OriginID AS ClassID, Relationships.DestID AS DomainID FROM {1}.GDB_ITEMRELATIONSHIPS AS Relationships INNER JOIN {1}.GDB_ITEMRELATIONSHIPTYPES AS RelationshipTypes ON Relationships.Type = RelationshipTypes.UUID WHERE RelationshipTypes.Name = 'DomainInDataset') AS DomainRelationships INNER JOIN {1}.GDB_ITEMS AS DomainItems ON DomainRelationships.DomainID = DomainItems.UUID INNER JOIN {1}.GDB_ITEMS AS ClassItems ON DomainRelationships.ClassID = ClassItems.UUID WHERE DomainItems.Name = '{0}'", item.Text, gdbItemsOwner);
            IReadOnlyList <string> valueArray = Geoprocessing.MakeValueArray(new object[] { physicalPath, QueryLayerName, Query, "Name" });

            Geoprocessing.ExecuteToolAsync("management.MakeQueryLayer", valueArray);
        }
예제 #3
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);
        }
        private async void SelectCourse()
        {
            string fieldName = string.Empty;
            var    oidField  = QueuedTask.Run(() =>
            {
                string name;
                using (Geodatabase geodatabase = new Geodatabase(new FileGeodatabaseConnectionPath(new Uri(GeoDataTool.DefaultProject.DefaultGeodatabasePath))))
                {
                    FeatureClassDefinition fcd = geodatabase.GetDefinition <FeatureClassDefinition>(ConstDefintion.ConstFeatureClass_Course);
                    name = fcd.GetObjectIDField();
                }
                return(name);
            }).Result;
            string path        = ConstDefintion.ConstFeatureClass_Course;
            string whereClause = $"{oidField} = {CourseListSelectedItem}";

            ProgressDialog progressDialogDomain = new ProgressDialog($"切换选择中", ConstDefintion.ConstStr_GeoprocessCancling, false);
            var            arg  = Geoprocessing.MakeValueArray(path, "NEW_SELECTION", whereClause);
            var            task = await Geoprocessing.ExecuteToolAsync("SelectLayerByAttribute_management", arg, null, new CancelableProgressorSource(progressDialogDomain).Progressor);

            if (!task.IsFailed)
            {
                if (!(MapView.Active == null))
                {
                    await MapView.Active.ZoomToSelectedAsync();
                }
            }
        }
예제 #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
        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");
        }
        internal async void CreatePackage()
        {
            if (_outputMap == null)
            {
                var maps = Project.Current.GetItems <MapProjectItem>();
                foreach (var mapProjectItem in maps)
                {
                    if (!mapProjectItem.Name.Contains("Map"))
                    {
                        continue;
                    }
                    await QueuedTask.Run(() =>
                    {
                        _outputMap = mapProjectItem.GetMap();
                    });

                    break;
                }
            }

            if (_outputMap == null)
            {
                return;
            }

            string[] values   = { "Map", @"c:\temp\MobileMapPackage.mmpk", "", "", "", "", "", "", "Description" };
            var      gpResult = await Geoprocessing.ExecuteToolAsync("CreateMobileMapPackage_management", values);

            Geoprocessing.ShowMessageBox(gpResult.Messages, "GP Messages",
                                         gpResult.IsFailed ? GPMessageBoxStyle.Error : GPMessageBoxStyle.Default);
            //  ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("Mobile map package created.","Geoprocessing Complete");
        }
예제 #8
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()));
        }
예제 #9
0
        public static async Task <bool> ExecuteAddFieldTool(BasicFeatureLayer layer, string field, string fieldType, int?fieldLength = null, bool isNullable = true)
        {
            try
            {
                return(await QueuedTask.Run(() =>
                {
                    var layerName = layer.Name;
                    var table = layer.GetTable();
                    var dataStore = table.GetDatastore();
                    var workspaceNameDef = dataStore.GetConnectionString();
                    var workspaceName = workspaceNameDef.Split('=')[1];

                    var fullSpec = System.IO.Path.Combine(workspaceName, layerName);
                    Log($@"{field} added -> {fullSpec}");

                    var parameters = Geoprocessing.MakeValueArray(fullSpec, field, fieldType.ToUpper(), null, null, fieldLength, null, isNullable ? "NULLABLE" : "NON_NULLABLE");
                    var results = Geoprocessing.ExecuteToolAsync("management.AddField", parameters, null, new CancellationTokenSource().Token,
                                                                 (eventName, o) =>
                    {
                        //OnProgressPos
                    });
                    return true;
                }));
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
                return(false);
            }
        }
        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 cts = new CancellationTokenSource();
                    var results = Geoprocessing.ExecuteToolAsync("management.DeleteField", parameters, null, 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);
            }
        }
예제 #11
0
        /// <summary>
        /// This method calls Geoprocessing to create a new version for the Workspace corresponding to the table
        /// </summary>
        /// <param name="table"></param>
        /// <returns></returns>
        private async Task <string> CreateVersion(Table table)
        {
            try
            {
                Version defaultVersion = (table.GetDatastore() as Geodatabase).GetVersionManager().GetVersions().FirstOrDefault(version =>
                {
                    string name = version.GetName();
                    return(name.ToLowerInvariant().Equals("dbo.default") || name.ToLowerInvariant().Equals("sde.default"));
                });
                if (defaultVersion == null)
                {
                    return(null);
                }
                using (defaultVersion)
                {
                    IReadOnlyList <string> valueArray = Geoprocessing.MakeValueArray(new object[] { table, defaultVersion.GetName(), string.Format("NewVersion{0}", random.Next()), "private" });
                    List <string>          values     = new List <String>
                    {
                        valueArray[0].Remove(valueArray[0].LastIndexOf("\\", StringComparison.Ordinal)),
                        valueArray[1],
                        valueArray[2],
                        valueArray[3]
                    };
                    await Geoprocessing.ExecuteToolAsync("management.CreateVersion", values);

                    return(valueArray[2]);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
            return(null);
        }
예제 #12
0
        public async void ProgressDialogExample()
        {
            #region progress_dialog

            var progDlg = new ProgressDialog("Running Geoprocessing Tool", "Cancel", 100, true);
            progDlg.Show();

            var progSrc = new CancelableProgressorSource(progDlg);

            // prepare input parameter values to CopyFeatures tool
            string input_data    = @"C:\data\california.gdb\ca_highways";
            string out_workspace = ArcGIS.Desktop.Core.Project.Current.DefaultGeodatabasePath;
            string out_data      = System.IO.Path.Combine(out_workspace, "ca_highways2");

            // make a value array of strings to be passed to ExecuteToolAsync
            var parameters = Geoprocessing.MakeValueArray(input_data, out_data);

            // execute the tool
            await Geoprocessing.ExecuteToolAsync("management.CopyFeatures", parameters,
                                                 null, new CancelableProgressorSource(progDlg).Progressor, GPExecuteToolFlags.Default);

            // dialog hides itself once the execution is complete
            progDlg.Hide();

            #endregion
        }
예제 #13
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);
        }
예제 #14
0
파일: GetPro.cs 프로젝트: GisSense/GetJSON
        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);
            }
        }
예제 #15
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(fullSpec, field.Key, fieldType.ToUpper(), null, null,
                                                                  fieldLength, field.Value, isNullable ? "NULABLE" : "NON_NULLABLE");
                    var cts = new CancellationTokenSource();
                    var results = Geoprocessing.ExecuteToolAsync("management.AddField", parameters, null, cts.Token,
                                                                 (eventName, o) =>
                    {
                        System.Diagnostics.Debug.WriteLine($@"GP event: {eventName}");
                    });
                    return true;
                }));
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
                return(false);
            }
        }
예제 #16
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);
        }
        protected override async void OnClick()
        {
            var rasterLayer =
                MapView.Active.Map.GetLayersAsFlattenedList().OfType <ImageServiceLayer>().FirstOrDefault();

            if (rasterLayer == null)
            {
                MessageBox.Show("Please add a raster as layer 0", "Cannot find layer");
                return;
            }

            await QueuedTask.Run(async() =>
            {
                var renderer = rasterLayer.GetColorizer();

                var parametersMin = Geoprocessing.MakeValueArray(rasterLayer, "MINIMUM");
                var parametersMax = Geoprocessing.MakeValueArray(rasterLayer, "MAXIMUM");
                var minRes        = await Geoprocessing.ExecuteToolAsync("GetRasterProperties_management", parametersMin);
                var maxRes        = await Geoprocessing.ExecuteToolAsync("GetRasterProperties_management", parametersMax);

                var min = Convert.ToDouble(minRes.Values[0]);
                var max = Convert.ToDouble(maxRes.Values[0]);

                var layerCimRenderer = CreateStretchRendererFromScratch(min, max);

                //For examination in the debugger..
                string xmlDef  = renderer.ToXml();
                string xmlDef2 = layerCimRenderer.ToXml();

                rasterLayer.SetColorizer(layerCimRenderer);
            });
        }
        internal async void BuildNetwork()
        {
            var mapView = MapView.Active;

            if (_networkDatasetLayer == null)
            {
                var layers = mapView.Map.GetLayersAsFlattenedList();
                foreach (var layer in layers)
                {
                    if (!(layer is NetworkDatasetLayer))
                    {
                        continue;
                    }
                    _networkDatasetLayer = layer as NetworkDatasetLayer;
                    break;
                }
            }

            if (_networkDatasetLayer == null)
            {
                return;
            }

            var values = Geoprocessing.MakeValueArray(_networkDatasetLayer);

            await Geoprocessing.ExecuteToolAsync("BuildNetwork_na", values);
        }
예제 #19
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);
            }
        }
예제 #20
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);
            }
        }
예제 #21
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
        }
예제 #22
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 async Task <IGPResult> ExtraObstacle(double distance)
        {
            string fieldName = string.Empty;
            var    oidField  = QueuedTask.Run(() =>
            {
                string name;
                using (Geodatabase geodatabase = new Geodatabase(new FileGeodatabaseConnectionPath(new Uri(GeoDataTool.DefaultProject.DefaultGeodatabasePath))))
                {
                    FeatureClassDefinition fcd = geodatabase.GetDefinition <FeatureClassDefinition>(ConstDefintion.ConstFeatureClass_Course);
                    name = fcd.GetObjectIDField();
                }
                return(name);
            }).Result;
            string         path                 = GeoDataTool.DefaultProject.DefaultGeodatabasePath + "\\" + ConstDefintion.ConstFeatureClass_Course;
            string         outpath              = GeoDataTool.DefaultProject.DefaultGeodatabasePath + "\\" + ConstDefintion.ConstFeatureClass_SelectedCourse;
            string         whereClause          = $"{oidField} = {CourseListSelectedItem}";
            ProgressDialog progressDialogDomain = new ProgressDialog($"正在创建被选择航线图层", ConstDefintion.ConstStr_GeoprocessCancling, false);
            var            arg = Geoprocessing.MakeValueArray(path, outpath, whereClause);
            var            gp  = await Geoprocessing.ExecuteToolAsync("Select_analysis", arg, null, new CancelableProgressorSource(progressDialogDomain).Progressor);

            if (!gp.IsFailed)
            {
                ProgressDialog progressDialog1 = new ProgressDialog($"正在构造缓冲区", ConstDefintion.ConstStr_GeoprocessCancling, false);
                string         outBufferpath   = GeoDataTool.DefaultProject.DefaultGeodatabasePath + "\\" + ConstDefintion.ConstFeatureClass_CourseBuffer;
                string         str_distance    = $"{distance} NauticalMiles";
                var            arg1            = Geoprocessing.MakeValueArray(outpath, outBufferpath, str_distance);
                var            gp1             = await Geoprocessing.ExecuteToolAsync("Buffer_analysis", arg1, null, new CancelableProgressorSource(progressDialog1).Progressor);

                if (!gp1.IsFailed)
                {
                    ProgressDialog progressDialog2   = new ProgressDialog($"正在提取碍航物", ConstDefintion.ConstStr_GeoprocessCancling, false);
                    string         insArgs           = $"{ObstaclePath} 1;{outBufferpath} 2";
                    string         outcourseObstacle = GeoDataTool.DefaultProject.DefaultGeodatabasePath + "\\" + ConstDefintion.ConstFeatureClass_CourseObstacle;
                    var            arg2 = Geoprocessing.MakeValueArray(insArgs, outcourseObstacle);
                    var            gp2  = await Geoprocessing.ExecuteToolAsync("Intersect_analysis", arg2, null, new CancelableProgressorSource(progressDialog2).Progressor);

                    if (!gp2.IsFailed)
                    {
                        ProgressDialog progressDialog3            = new ProgressDialog($"正在创建泰森多边形", ConstDefintion.ConstStr_GeoprocessCancling, false);
                        string         outCourseObstacle_Thiessen = GeoDataTool.DefaultProject.DefaultGeodatabasePath + "\\" + ConstDefintion.ConstFeatureClass_CourseObstacleThiessen;
                        var            arg3 = Geoprocessing.MakeValueArray(outcourseObstacle, outCourseObstacle_Thiessen);
                        var            gp3  = await Geoprocessing.ExecuteToolAsync("CreateThiessenPolygons_analysis", arg3, null, new CancelableProgressorSource(progressDialog3).Progressor);

                        if (!gp3.IsFailed)
                        {
                            ProgressDialog progressDialog4           = new ProgressDialog($"正在裁剪", ConstDefintion.ConstStr_GeoprocessCancling, false);
                            string         inCourseObstacle_Thiessen = outCourseObstacle_Thiessen;
                            string         inBuffer        = outBufferpath;
                            string         outClipThiessen = GeoDataTool.DefaultProject.DefaultGeodatabasePath + "\\" + ConstDefintion.ConstFeatureClass_CourseObstacleThiessenClip;
                            var            arg4            = Geoprocessing.MakeValueArray(inCourseObstacle_Thiessen, inBuffer, outClipThiessen);
                            var            gp4             = await Geoprocessing.ExecuteToolAsync("Clip_analysis", arg4, null, new CancelableProgressorSource(progressDialog4).Progressor);

                            return(gp4);
                        }
                    }
                }
            }
            return(null);
        }
 protected async Task DefineProjectionAsync(string CadFileName, SpatialReference SpatialRef, CancelableProgressorSource cps)
 {
     //GP Define Projection
     GPExecuteToolFlags flags = GPExecuteToolFlags.Default; // | GPExecuteToolFlags.GPThread;
     var parameters           = Geoprocessing.MakeValueArray(CadFileName, SpatialRef.Wkt);
     await Geoprocessing.ExecuteToolAsync("management.DefineProjection", parameters,
                                          null, cps.Progressor, flags);
 }
        protected override async void OnClick()
        {
            MessageBox.Show("truncate 3");
            string output_polys = System.IO.Path.Combine(System.IO.Path.Combine(ArcGIS.Desktop.Core.Project.Current.HomeFolderPath, "bufferOutPuts.gdb"), "buffer_100miles"); // @"C:\data\ca_ozone.gdb\ozone_buff";
            var    param_values = Geoprocessing.MakeValueArray(output_polys);

            //Geoprocessing.OpenToolDialog("TruncateTable_management", param_values);
            var result = await Geoprocessing.ExecuteToolAsync("TruncateTable_management", param_values);
        }
        private async Task <bool> Project(string shapeFile, string outputPath)
        {
            var projectToolParams
                = await QueuedTask.Run(() => Geoprocessing.MakeValueArray(shapeFile, outputPath, _targetReferenceSystem));

            var result = await Geoprocessing.ExecuteToolAsync("management.Project", projectToolParams, null,
                                                              _cancelHandler.Progressor, GPExecuteToolFlags.None | GPExecuteToolFlags.GPThread);

            return(!result.IsFailed);
        }
        private async Task <bool> Clip(string shapeFile, string outputPath)
        {
            var clipToolParams
                = await QueuedTask.Run(() => Geoprocessing.MakeValueArray(shapeFile, _clipExtentShapeFile, outputPath));

            var result = await Geoprocessing.ExecuteToolAsync("analysis.Clip", clipToolParams, null,
                                                              _cancelHandler.Progressor, GPExecuteToolFlags.None | GPExecuteToolFlags.GPThread);

            return(!result.IsFailed);
        }
        private async Task <bool> CopyShapeFile(string shapeFile, string targetPath)
        {
            var copyToolParams
                = await QueuedTask.Run(() => Geoprocessing.MakeValueArray(shapeFile, targetPath));

            var result = await Geoprocessing.ExecuteToolAsync("management.CopyFeatures", copyToolParams, null,
                                                              _cancelHandler.Progressor, GPExecuteToolFlags.None | GPExecuteToolFlags.GPThread);

            return(!result.IsFailed);
        }
예제 #29
0
        public async void ShowMessageBox()
        {
            #region message_box
            var gp_result = await Geoprocessing.ExecuteToolAsync("management.GetCount", Geoprocessing.MakeValueArray(@"C:\data\f.gdb\hello"));

            // this icon shows up left of content_header
            string icon_src = @"C:\data\Icons\ModifyLink32.png";
            Geoprocessing.ShowMessageBox(gp_result.Messages, "Content Header", GPMessageBoxStyle.Error, "Window Title", icon_src);
            #endregion
        }
예제 #30
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);
        }