Esempio n. 1
0
        private async void Map_Click(object sender, EventArgs e)
        {
            var mapView = MapView.Active;


            //string[,] input_rasters = new string[3, 1] { { @"G:\AdvancedRemoteSensing\LabData\Test\charleston12-8-90tm.img VALUE 0.5" }, { @"G:\AdvancedRemoteSensing\LabData\Test\cola_1-15-91tm.img VALUE 0.5" }, { @"G:\AdvancedRemoteSensing\LabData\Test\cola_10-7-97atlas.img VALUE 0.5" } };
            //node1.Tagb
            //myinputs.Add(RasterLayer(i) + " VALUE " + rowSum[i]);
            //Goal.TopNode.Nodes[i].Text.Split("-->") = x[0] + "-->" + Math.Round(rowSum[i], 3);

            System.Diagnostics.Debug.WriteLine(Goal.TopNode.Nodes[1].Tag.GetType());


            List <string> paths    = new List <string>();
            List <string> myinputs = new List <string>();
            TreeNode      test     = Goal.TopNode;
            //double[] rs = rowSum;

            Task t = QueuedTask.Run(() =>
            {
                for (int k = 0; k < test.Nodes.Count; k++)
                {
                    var rlyrs = MapView.Active.Map.Layers.OfType <RasterLayer>();  //All raster layers
                    //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);

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

            t.Wait();



            string output_raster = System.IO.Path.Combine(Project.Current.DefaultGeodatabasePath, "SuitedRaster");
            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);

            //Geoprocessing.OpenToolDialog("sa.WeightedSum", param_values);

            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" + "reclass0");
            var    kufli          = Geoprocessing.MakeValueArray(output_raster, "VALUE", remap, output_raster2);
            await Geoprocessing.ExecuteToolAsync("sa.Reclassify", kufli, env, null, null, GPExecuteToolFlags.AddOutputsToMap);

            //Geoprocessing.OpenToolDialog("sa.Reclassify", kufli);
        }
        private async void RunImplAsync(object param)
        {
            // Bring GP History tool forward
            var cmdShowHistory = FrameworkApplication.GetPlugInWrapper("esri_geoprocessing_showToolHistory") as ICommand;

            if (cmdShowHistory != null)
            {
                if (cmdShowHistory.CanExecute(null))
                {
                    cmdShowHistory.Execute(null);
                }
            }
            foreach (var oAoi in Names)
            {
                if (oAoi.AoiBatchIsSelected)
                {
                    // Currently only support AOI conversion but BASIN may be added in future
                    FolderType fType = await GeodatabaseTools.GetWeaselAoiFolderTypeAsync(oAoi.FilePath);

                    IList <string> lstExistingGdb = null;
                    if (fType == FolderType.AOI)
                    {
                        lstExistingGdb = CheckForBagisGdb(oAoi.FilePath);
                    }
                    else
                    {
                        lstExistingGdb = CheckForBasinGdb(oAoi.FilePath);
                    }

                    // Make directory for log if it doesn't exist
                    if (!Directory.Exists(oAoi.FilePath + "\\" + Constants.FOLDER_LOGS))
                    {
                        DirectoryInfo info = Directory.CreateDirectory(oAoi.FilePath + "\\" + Constants.FOLDER_LOGS);
                        if (info == null)
                        {
                            MessageBox.Show("Unable to create logs directory in Aoi folder!!", "BAGIS-PRO");
                        }
                    }
                    // Set logger to AOI directory
                    string logFolderName = oAoi.FilePath + "\\" + Constants.FOLDER_LOGS;
                    Module1.Current.ModuleLogManager.UpdateLogFileLocation(logFolderName);

                    // Delete old geodatabases if they exist
                    foreach (var geodatabasePath in lstExistingGdb)
                    {
                        IGPResult gpResult = await QueuedTask.Run(() =>
                        {
                            var parameters = Geoprocessing.MakeValueArray(geodatabasePath);
                            return(Geoprocessing.ExecuteToolAsync("Delete_management", parameters, null,
                                                                  CancelableProgressor.None, GPExecuteToolFlags.AddToHistory));
                        });

                        if (gpResult.IsFailed)
                        {
                            Module1.Current.ModuleLogManager.LogError(nameof(RunImplAsync),
                                                                      "Unable to delete geodatabase. Error code: " + gpResult.ErrorCode);
                            MessageBox.Show("Unable to delete geodatabase " + geodatabasePath + "!");
                        }
                    }

                    // Create new geodatabases
                    BA_ReturnCode success = await GeodatabaseTools.CreateGeodatabaseFoldersAsync(oAoi.FilePath, fType);

                    if (success == BA_ReturnCode.Success)
                    {
                        Module1.Current.ModuleLogManager.LogInfo(nameof(RunImplAsync),
                                                                 "Created geodatabases in " + oAoi.FilePath);
                    }
                    else
                    {
                        MessageBox.Show("Unable to create geodatabases in " + oAoi.FilePath + ". Check logs!");
                    }

                    // Assemble a dictionary with rasters we want to copy
                    IDictionary <string, string> rastersToCopy = GetDictOfReqRasters(oAoi.FilePath, fType);
                    // Accomodate two possible names for raster aoi boundary layer (aoibagis or aoi)
                    IList <string> lstTest = new List <string>
                    {
                        oAoi.FilePath + @"\aoibagis"
                    };
                    string         aoiGdb         = GeodatabaseTools.GetGeodatabasePath(oAoi.FilePath, GeodatabaseNames.Aoi, true);
                    IList <string> existingLayers = null;
                    if (fType == FolderType.AOI)
                    {
                        existingLayers = await GeneralTools.RasterDatasetsExistAsync(lstTest);

                        if (existingLayers.Count == 0)
                        {
                            lstTest.Clear();
                            string strLayer = oAoi.FilePath + @"\aoi";
                            lstTest.Add(strLayer);
                            existingLayers = await GeneralTools.RasterDatasetsExistAsync(lstTest);

                            if (existingLayers.Count > 0)
                            {
                                rastersToCopy[strLayer] = aoiGdb + Constants.FILE_AOI_RASTER;
                            }
                        }
                        else
                        {
                            rastersToCopy[oAoi.FilePath + @"\aoibagis"] = aoiGdb + Constants.FILE_AOI_RASTER;
                        }
                    }
                    // Check to see if optional layers are present
                    IDictionary <string, string> optRasterDict = GetDictOptWeaselRasters(oAoi.FilePath, fType);
                    existingLayers = await GeneralTools.RasterDatasetsExistAsync(optRasterDict.Keys);

                    foreach (var layerPath in existingLayers)
                    {
                        string gdbPath = optRasterDict[layerPath];
                        rastersToCopy[layerPath] = gdbPath;
                    }
                    // Raster layers with non-deterministic names in analysis and layers folders
                    string         strWeaselFolder = oAoi.FilePath + @"\layers";
                    string         strGdbPath      = GeodatabaseTools.GetGeodatabasePath(oAoi.FilePath, GeodatabaseNames.Layers, true);
                    IList <string> lstRasters      = await GeneralTools.GetLayersInFolderAsync(strWeaselFolder, "Raster Dataset");

                    foreach (var item in lstRasters)
                    {
                        rastersToCopy[strWeaselFolder + "\\" + item] = strGdbPath + item;
                    }
                    strWeaselFolder = oAoi.FilePath + @"\analysis";
                    strGdbPath      = GeodatabaseTools.GetGeodatabasePath(oAoi.FilePath, GeodatabaseNames.Analysis, true);
                    lstRasters      = await GeneralTools.GetLayersInFolderAsync(strWeaselFolder, "Raster Dataset");

                    foreach (var item in lstRasters)
                    {
                        rastersToCopy[strWeaselFolder + "\\" + item] = strGdbPath + item;
                    }

                    // Use Geoprocessor to copy the files
                    int errorCount = 0;
                    foreach (var key in rastersToCopy.Keys)
                    {
                        IGPResult gpResult = await QueuedTask.Run(() =>
                        {
                            var environments = Geoprocessing.MakeEnvironmentArray(workspace: oAoi.FilePath, cellSize: "MINOF");
                            var parameters   = Geoprocessing.MakeValueArray(key, rastersToCopy[key]);
                            return(Geoprocessing.ExecuteToolAsync("CopyRaster_management", parameters, null,
                                                                  CancelableProgressor.None, GPExecuteToolFlags.AddToHistory));
                        });

                        if (gpResult.IsFailed)
                        {
                            Module1.Current.ModuleLogManager.LogError(nameof(RunImplAsync),
                                                                      "Failed to copy raster " + key + "!");
                            errorCount++;
                        }
                    }
                    Module1.Current.ModuleLogManager.LogDebug(nameof(RunImplAsync),
                                                              "Raster copy completed with " + errorCount + " errors.");

                    // Assemble a dictionary with vectors we want to copy
                    IDictionary <string, string> vectorsToCopy = GetDictOfReqWeaselVectors(oAoi.FilePath, fType);
                    // Check for an optional vector
                    lstTest.Clear();
                    lstTest.Add(oAoi.FilePath + @"\unsnappedpp.shp");
                    existingLayers = await GeneralTools.ShapefilesExistAsync(lstTest);

                    if (existingLayers.Count > 0)
                    {
                        vectorsToCopy[oAoi.FilePath + @"\unsnappedpp.shp"] = aoiGdb + Constants.FILE_UNSNAPPED_POURPOINT;
                    }

                    // Vector layers with non-deterministic names in analysis and layers folders
                    strWeaselFolder = oAoi.FilePath + @"\layers";
                    strGdbPath      = GeodatabaseTools.GetGeodatabasePath(oAoi.FilePath, GeodatabaseNames.Layers, true);
                    IList <string> lstVectors = await GeneralTools.GetLayersInFolderAsync(strWeaselFolder, "Shapefile");

                    foreach (var item in lstVectors)
                    {
                        string noExtension = Path.GetFileNameWithoutExtension(item);
                        vectorsToCopy[strWeaselFolder + "\\" + item] = strGdbPath + noExtension;
                    }
                    strWeaselFolder = oAoi.FilePath + @"\analysis";
                    strGdbPath      = GeodatabaseTools.GetGeodatabasePath(oAoi.FilePath, GeodatabaseNames.Analysis, true);
                    lstVectors      = await GeneralTools.GetLayersInFolderAsync(strWeaselFolder, "Shapefile");

                    foreach (var item in lstVectors)
                    {
                        string noExtension = Path.GetFileNameWithoutExtension(item);
                        vectorsToCopy[strWeaselFolder + "\\" + item] = strGdbPath + noExtension;
                    }

                    // Use Geoprocessor to copy the files
                    errorCount = 0;
                    foreach (var entry in vectorsToCopy)
                    {
                        string strKey = entry.Key;
                    }
                    string strTempFile  = Path.GetFileName("tmpVector");
                    string strDirectory = "";
                    foreach (var entry in vectorsToCopy)
                    {
                        IGPResult gpResult = await QueuedTask.Run(() =>
                        {
                            var environments = Geoprocessing.MakeEnvironmentArray(workspace: oAoi.FilePath);
                            strDirectory     = Path.GetDirectoryName(entry.Value);
                            var parameters   = Geoprocessing.MakeValueArray(entry.Key, strDirectory, strTempFile);
                            return(Geoprocessing.ExecuteToolAsync("FeatureClassToFeatureClass_conversion", parameters, null,
                                                                  CancelableProgressor.None, GPExecuteToolFlags.AddToHistory));
                        });

                        if (gpResult.IsFailed)
                        {
                            Module1.Current.ModuleLogManager.LogError(nameof(RunImplAsync),
                                                                      "Failed to convert vector " + entry.Key + "!");
                            errorCount++;
                        }
                        else
                        {
                            //There is a bug with using converted shapefiles in Pro; We need to rename the converted file
                            //so that functions related to extent work
                            gpResult = await QueuedTask.Run(() =>
                            {
                                var environments = Geoprocessing.MakeEnvironmentArray(workspace: oAoi.FilePath);
                                strDirectory     = Path.GetDirectoryName(entry.Value);
                                var parameters   = Geoprocessing.MakeValueArray(strDirectory + "\\" + strTempFile, entry.Value);
                                return(Geoprocessing.ExecuteToolAsync("Rename_management", parameters, null,
                                                                      CancelableProgressor.None, GPExecuteToolFlags.AddToHistory));
                            });

                            if (gpResult.IsFailed)
                            {
                                Module1.Current.ModuleLogManager.LogError(nameof(RunImplAsync),
                                                                          "Failed to copy feature class " + entry.Key + "!");
                                errorCount++;
                            }
                        }
                    }
                    Module1.Current.ModuleLogManager.LogDebug(nameof(RunImplAsync),
                                                              "Vector copy completed with " + errorCount + " errors.");
                }
            }

            MessageBox.Show("Done!");
        }
        public void AddQAFieldToLayer()
        {
            try
            {
                QueuedTask.Run(async() =>
                {
                    if (QAFieldComboBox.Text == null)
                    {
                        return;
                    }
                    string QAfieldname = QAFieldComboBox.Text.ToString();
                    // search the layer for the field, if exists, then confirm use, if not, confirm addition
                    var LayerName = LayerComboBox.Text.ToString();
                    var QALayer   = MapView.Active.Map.FindLayers(LayerName).FirstOrDefault() as FeatureLayer;
                    if (QALayer == null)
                    {
                        return;
                    }
                    int qaFieldIndex = QALayer.GetTable().GetDefinition().FindField(QAfieldname);

                    if (qaFieldIndex == -1)                     // field not found
                    {
                        // Prompt for confirmation, and if answer is no, return.
                        var result = ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("Create new field: " + QAfieldname + "?", "CREATE QA FIELD", System.Windows.MessageBoxButton.OKCancel, System.Windows.MessageBoxImage.Asterisk);
                        // Return if cancel value is chosen
                        if (Convert.ToString(result) == "Cancel")
                        {
                            QAFieldComboBox.Text = "Choose...";
                            FrameworkApplication.State.Deactivate("active_state_3");
                            return;
                        }
                        else
                        {
                            // Check for edits, and if they exist prompt for saving - essential for attribute creation
                            if (Project.Current.HasEdits)
                            {
                                // Prompt for confirmation, and if answer is no, return.
                                result = MessageBox.Show("Edits must be saved before proceeding. Save edits?", "Save All Edits", System.Windows.MessageBoxButton.OKCancel, System.Windows.MessageBoxImage.Asterisk);
                                // Return if cancel value is chosen
                                if (Convert.ToString(result) == "OK")
                                {
                                    await Project.Current.SaveEditsAsync();
                                }
                                else                                 // operation cancelled
                                {
                                    MessageBox.Show("Add field cancelled.");
                                    QAFieldComboBox.Text = "Choose...";
                                    return;
                                }
                            }

                            // Add the field
                            // AddField_management(in_table, field_name, field_type, { field_precision}, { field_scale}, { field_length}, { field_alias}, { field_is_nullable}, { field_is_required}, { field_domain})
                            var parameters = Geoprocessing.MakeValueArray(QALayer.GetTable(), QAfieldname, "TEXT");
                            var gpResult   = await Geoprocessing.ExecuteToolAsync("Management.AddField", parameters);
                            //Geoprocessing.ShowMessageBox(gpResult.Messages, "GP Messages",
                            //gpResult.IsFailed ? GPMessageBoxStyle.Error : GPMessageBoxStyle.Default);
                            if (gpResult.IsFailed == true)
                            {
                                MessageBox.Show("New attribute operation failed.", "ERROR");
                            }

                            // Activate controls
                            FrameworkApplication.State.Activate("active_state_3");
                            if (EditNoteComboBox.ItemCollection.FirstOrDefault() == null || EditNoteComboBox.ItemCollection.FirstOrDefault().ToString() == "")
                            {
                                EditNoteComboBox.Text = "Load or add...";
                            }
                        }
                    }
                    else                      // field is found
                    {
                        // Prompt for confirmation, and if answer is no, return.
                        var result = MessageBox.Show("The QA Field, " + QAfieldname + " exists.  Use it?", "USE QA FIELD", System.Windows.MessageBoxButton.OKCancel, System.Windows.MessageBoxImage.Asterisk);
                        // Return if cancel value is chosen
                        if (Convert.ToString(result) == "Cancel")
                        {
                            QAFieldComboBox.Text = "Choose...";
                            return;
                        }
                        else
                        {
                            // Leave the field name in the box, and activate controls
                            FrameworkApplication.State.Activate("active_state_3");
                            EditNoteComboBox.Text = "Load or add...";
                        }
                    }
                });
            }

            catch (Exception ex)
            {
                MessageBox.Show("Error in AddQAFieldToLayer:  " + ex.ToString(), "Error");
            }
        }
Esempio n. 4
0
        protected override void OnClick()
        {
            ProgressDialog progDial = new ProgressDialog("I'm doing my thing.\nPlease be patient, Human.", false);

            QueuedTask.Run(() =>
            {
                try
                {
                    var map         = MapView.Active.Map;
                    var mhExists    = map.GetLayersAsFlattenedList().OfType <FeatureLayer>().Any(m => m.Name == "Manholes");
                    var sewerExists = map.GetLayersAsFlattenedList().OfType <FeatureLayer>().Any(s => s.Name == "Sewer Lines");

                    // Check for the SEWER LINES Layer and MANHOLES layers in the map.
                    if (mhExists == false && sewerExists == false)
                    {
                        MessageBox.Show("Manholes & Sewers are missing from map.", "Missing Layer(s)");
                    }
                    else if (mhExists == false && sewerExists)
                    {
                        MessageBox.Show("Sewer Lines layer is present. \n\nManholes layer is missing from map.", "Missing Layer(s)");
                    }
                    else if (mhExists && sewerExists == false)
                    {
                        MessageBox.Show("Manholes layer is present. \n\nSewers layer is missing from map.", "Missing Layer(s)");
                    }
                    else
                    {
                        var sewerLines  = map.GetLayersAsFlattenedList().OfType <FeatureLayer>().FirstOrDefault(s => s.Name == "Sewer Lines");
                        var manholes    = map.GetLayersAsFlattenedList().OfType <FeatureLayer>().FirstOrDefault(s => s.Name == "Manholes");
                        var selectCount = sewerLines.SelectionCount;

                        if (selectCount == 0)
                        {
                            MessageBox.Show("No sewer trace is in map! \n\nA sewer trace must be performed to add\nmanholes associate with trace.", "Sewer Trace Missing!");
                        }

                        else
                        {
                            progDial.Show();
                            string spatialRelate = "INTERSECT";
                            int distance         = 0;
                            string selectType    = "NEW_SELECTION";
                            string invertRelate  = "NOT_INVERT";

                            var parameters = Geoprocessing.MakeValueArray(manholes, spatialRelate, sewerLines, distance, selectType, invertRelate);

                            Geoprocessing.ExecuteToolAsync("management.SelectLayerByLocation", parameters);
                            progDial.Hide();
                        }
                    }
                }

                catch (Exception ex)
                {
                    SysModule.LogError(ex.Message, ex.StackTrace);

                    string caption = "Add Manholes to Trace Failed";
                    string message = "Failed to add manholes selection to trace. \n\nSave and restart ArcGIS Pro and try process again.\n" +
                                     "If problem persist, contact your local GIS nerd.";
                    progDial.Hide();


                    //Using the ArcGIS Pro SDK MessageBox class
                    MessageBox.Show(message, caption);
                }
            });
        }
        public async void SelectLayerBySLR()
        {
            // Get checkbox values for selection
            // checkBox.IsChecked.Value

            // Get the slider value for the current SLR Layer
            string strSLRLayerName = "FL_SLR_Study_" + Convert.ToString(_sliderValue) + "ft";

            // If SLR layer is set to Zero feet, or no layers are checked for selection, then exit.
            if (_sliderValue == 0)
            {
                ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("Set slider to an SLR height of 1 - 6 feet", "Set Slider Value");
                return;
            }
            if (_ckbLandUseChecked == false && _ckbParcelChecked == false && _ckbStreetChecked == false)
            {
                ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("Select checkbox of study layer(s) to review", "Select Study Layer(s)");
                return;
            }

            // Select Study Area Layers based on what is visible
            await QueuedTask.Run(async() =>
            {
                var activeMapView = MapView.Active;
                if (activeMapView == null)
                {
                    return;
                }

                // For sub-selection
                SpatialQueryFilter spatialFilter = new SpatialQueryFilter
                {
                    FilterGeometry      = new PolygonBuilder(MapView.Active.Extent).ToGeometry(),
                    SpatialRelationship = SpatialRelationship.Intersects
                };

                string luContentList     = "\r\n** LAND USE **\r\n";
                string parcelContentList = "\r\n\r\n** PARCELS **\r\n";
                string streetContentList = "\r\n\r\n** STREETS **\r\n";

                IList <KeyValueWithTooltip> luKv = new List <KeyValueWithTooltip>();
                IList <KeyValueWithTooltip> pKv  = new List <KeyValueWithTooltip>();
                IList <KeyValueWithTooltip> sKv  = new List <KeyValueWithTooltip>();

                // set titles & report configuration
                var paneConfiguration = _ckbLandUseChecked ? "Land Use" : string.Empty;
                if (_ckbParcelChecked)
                {
                    paneConfiguration += paneConfiguration.Length > 0 ?
                                         (_ckbStreetChecked ? " , Pacels, and Street" : " and Parcels") :
                                         (_ckbStreetChecked ? "Pacels and Street" : "Parcels");
                }
                else
                {
                    paneConfiguration += paneConfiguration.Length > 0 ?
                                         (_ckbStreetChecked ? " and Street" : string.Empty) :
                                         (_ckbStreetChecked ? " Street" : string.Empty);
                }
                paneConfiguration = "This report is showing effects on: " + paneConfiguration;
                var paneTitle     = $@"Sea Level Rise of {_sliderValue} Feet {Environment.NewLine}";

                // ** PARCELS
                //if (_ckbParcelChecked == true)
                {
                    var ParcelsLayer = MapView.Active.Map.FindLayers("Parcels_Study").FirstOrDefault() as BasicFeatureLayer;
                    ParcelsLayer.ClearSelection();

                    var args = Geoprocessing.MakeValueArray("Parcels_Study", "intersect", strSLRLayerName);
                    await Geoprocessing.ExecuteToolAsync("SelectLayerByLocation_management", args);

                    Selection ParcelsSelection = ParcelsLayer.Select(spatialFilter, SelectionCombinationMethod.And);
                    int parcelsSelectionCount;
                    parcelsSelectionCount = ParcelsSelection.GetCount();

                    // Format parcels report for Textbox output:
                    string parcelsSelectionCountstring = Convert.ToString(parcelsSelectionCount);
                    parcelContentList = parcelContentList + "* TOTAL:  " + parcelsSelectionCountstring + " Parcels affected.\r\n \r\n* Unique Codes in Affected Area: \r\n";

                    //  LOOP THROUGH THE PARCEL SELECTION AND GET THE UNIQUE LIST OF SUBCODES.
                    // Create list
                    List <string> ParcelCodeList = new List <string> {
                    };
                    // Populate list
                    using (RowCursor ParcelRowCursor = ParcelsSelection.Search(null, false))
                    {
                        while (ParcelRowCursor.MoveNext())
                        {
                            using (Row currentRow = ParcelRowCursor.Current)
                            {
                                ParcelCodeList.Add(Convert.ToString(currentRow["SUBCODE"]));
                            }
                        }
                    }
                    ParcelCodeList.Sort();
                    int count;

                    // Get unique values and counts in the list
                    foreach (var item in ParcelCodeList.Distinct())
                    {
                        count             = ParcelCodeList.Where(x => x.Equals(item)).Count();
                        parcelContentList = parcelContentList + Convert.ToString(count) + " instances of Code:  " + item + "\r\n";
                        pKv.Add(new KeyValueWithTooltip()
                        {
                            Code = $@"Sub Code: {item}", Key = item.ToString(), Value = count
                        });
                    }
                    // Dispose of data classes
                    ParcelsSelection.Dispose();
                }

                // ** STREETS
                //if (_ckbStreetChecked == true)
                {
                    var StreetsLayer = MapView.Active.Map.FindLayers("Streets_Study").FirstOrDefault() as BasicFeatureLayer;
                    StreetsLayer.ClearSelection();

                    var args = Geoprocessing.MakeValueArray("Streets_Study", "intersect", strSLRLayerName);
                    await Geoprocessing.ExecuteToolAsync("SelectLayerByLocation_management", args);

                    Selection StreetsSelection = StreetsLayer.Select(spatialFilter, SelectionCombinationMethod.And);
                    int streetsSelectionCount;
                    streetsSelectionCount = StreetsSelection.GetCount();
                    // Format streets report for Textbox output:
                    string streetSelectionCountstring = Convert.ToString(streetsSelectionCount);
                    streetContentList = streetContentList + "* TOTAL:  " + streetSelectionCountstring + " Streets affected.\r\n \r\n* Unique Codes in Affected Area: \r\n";

                    //  LOOP THROUGH THE STREET SELECTION AND GET THE UNIQUE LIST OF CODES.
                    // Create list
                    List <string> StreetCodeList = new List <string> {
                    };
                    // Populate list
                    using (RowCursor StreetRowCursor = StreetsSelection.Search(null, false))
                    {
                        while (StreetRowCursor.MoveNext())
                        {
                            using (Row currentRow = StreetRowCursor.Current)
                            {
                                StreetCodeList.Add(Convert.ToString(currentRow["CLASS"]));
                            }
                        }
                    }
                    StreetCodeList.Sort();
                    int count;
                    // Get unique values and counts in the list
                    foreach (var item in StreetCodeList.Distinct())
                    {
                        count             = StreetCodeList.Where(x => x.Equals(item)).Count();
                        streetContentList = streetContentList + Convert.ToString(count) + " instances of Code:  " + item + "\r\n";
                        sKv.Add(new KeyValueWithTooltip()
                        {
                            Code = $@"Class: {item}", Key = item, Value = count
                        });
                    }
                    // Dispose of data classes
                    StreetsSelection.Dispose();
                }

                // ** LAND USE
                //if (_ckbLandUseChecked == true)
                {
                    //  Get selection and make selection on map extent only if needed
                    var LandUseLayer = MapView.Active.Map.FindLayers("Land_Use_Study").FirstOrDefault() as BasicFeatureLayer;
                    LandUseLayer.ClearSelection();

                    var args = Geoprocessing.MakeValueArray("Land_Use_Study", "intersect", strSLRLayerName);
                    await Geoprocessing.ExecuteToolAsync("SelectLayerByLocation_management", args);

                    Selection LandUseSelection = LandUseLayer.Select(spatialFilter, SelectionCombinationMethod.And);
                    int luSelectionCount;
                    luSelectionCount = LandUseSelection.GetCount();
                    // Format land use report for Textbox output:
                    string luSelectionCountstring = Convert.ToString(luSelectionCount);
                    luContentList = luContentList + "* TOTAL:  " + luSelectionCountstring + " Land Use areas affected.\r\n \r\n* Unique Codes in Affected Area: \r\n";

                    //  LOOP THROUGH THE LANDUSE SELECTION AND GET THE UNIQUE LIST OF CODES.
                    // Create list
                    List <string> LandUseCodeList = new List <string> {
                    };
                    // Populate list
                    using (RowCursor LandUseRowCursor = LandUseSelection.Search(null, false))
                    {
                        while (LandUseRowCursor.MoveNext())
                        {
                            using (Row currentRow = LandUseRowCursor.Current)
                            {
                                LandUseCodeList.Add(Convert.ToString(currentRow["LU"]));
                            }
                        }
                    }
                    LandUseCodeList.Sort();
                    int count;
                    // Get unique values and counts in the list
                    foreach (var item in LandUseCodeList.Distinct())
                    {
                        count         = LandUseCodeList.Where(x => x.Equals(item)).Count();
                        luContentList = luContentList + Convert.ToString(count) + " instances of Code:  " + item + "\r\n";
                        luKv.Add(new KeyValueWithTooltip()
                        {
                            Code = $@"LU Code: {item}", Key = item.ToString(), Value = count
                        });
                    }
                    // Dispose of data classes
                    LandUseSelection.Dispose();
                }                 // End Parcel Routine

                string reportText = "SEA LEVEL RISE REPORT:  " + SliderValue + "-FEET LEVEL EFFECTS \r\n";
                if (_ckbLandUseChecked)
                {
                    reportText += luContentList;
                }
                if (_ckbParcelChecked)
                {
                    reportText += parcelContentList;
                }
                if (_ckbStreetChecked)
                {
                    reportText += streetContentList;
                }

                await System.Windows.Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal,
                                                                                new Action(() =>
                {
                    Module1.CreateNewSlrPane(paneTitle, paneConfiguration, reportText,
                                             _ckbLandUseChecked, _ckbParcelChecked, _ckbStreetChecked,
                                             luKv, pKv, sKv);
                }));
            });              // Close QueuedTask
        }
Esempio n. 6
0
        protected override async void OnClick()
        {
            SharedFunctions.Log("DamVolume Calculation started");
            DateTime startTime = DateTime.Now;
            await Project.Current.SaveEditsAsync();

            IncomingCandidates = 0;
            OutgoingCandidates = 0;
            List <CandidateDam> candidates        = new List <CandidateDam>();
            List <CandidateDam> candidates2Delete = new List <CandidateDam>();

            try
            {
                await QueuedTask.Run(async() =>
                {
                    if (!SharedFunctions.LayerExists("DamCandidates") || !SharedFunctions.LayerExists("Contours"))
                    {
                        return;
                    }
                    var _damCandidatesLayer = MapView.Active.Map.FindLayers("DamCandidates").FirstOrDefault();

                    BasicFeatureLayer damCandidatesLayer = _damCandidatesLayer as BasicFeatureLayer;
                    SharedFunctions.LoadDamCandidatesFromLayer(candidates, damCandidatesLayer);
                    IncomingCandidates = candidates.Count();
                    OutgoingCandidates = IncomingCandidates;

                    //create stacked profile
                    string inputDEM  = Parameter.DEMCombo.SelectedItem.ToString();
                    var valueArray   = Geoprocessing.MakeValueArray(damCandidatesLayer.Name, inputDEM, "DamProfile", null);
                    var environments = Geoprocessing.MakeEnvironmentArray(overwriteoutput: true);
                    var cts          = new CancellationTokenSource();
                    await Project.Current.SaveEditsAsync();
                    var res = await Geoprocessing.ExecuteToolAsync("StackProfile", valueArray, environments, cts.Token, null, GPExecuteToolFlags.Default);

                    //analyse profile and add data to line feature or delete line feature
                    //profile can be used to calculate frontal dam area and dam volume?!
                    var damProfileTable = MapView.Active.Map.FindStandaloneTables("DamProfile").FirstOrDefault();
                    if (damProfileTable == null)
                    {
                        SharedFunctions.Log("No DamProfile Table found!");
                    }

                    CandidateDam cand = null;
                    double prev_dist  = 0;
                    int prev_lineID   = -1;
                    using (var profileCursor = damProfileTable.Search())
                    {
                        while (profileCursor.MoveNext())
                        {
                            using (Row profileRow = profileCursor.Current)
                            {
                                var first_dist = (double)profileRow[1];
                                var first_z    = (double)profileRow[2];
                                var line_ID    = (int)profileRow[5];

                                if (prev_lineID != line_ID)
                                {
                                    prev_dist = 0;
                                    cand      = candidates.SingleOrDefault(c => c.ObjectID == line_ID);
                                    // set Volume and ZMin to the default values
                                    cand.DamVolume = 0;
                                    cand.ZMin      = cand.ContourHeight;
                                }
                                else if (candidates2Delete.Contains(cand))
                                {
                                    continue;
                                }
                                //set lowest point of dam to calculate max dam height later
                                if (cand.ZMin > (int)first_z)
                                {
                                    cand.ZMin = (int)first_z;
                                }

                                if ((int)first_z > (cand.ContourHeight + 5))
                                {
                                    candidates2Delete.Add(cand);
                                    continue;
                                }

                                //add volume of current block of dam... the assumption is a triangle dam shape (cross section) with alpha = 45°
                                //thus the area of the cross section is calculated by <height²> and the volume by <height² * length>
                                cand.DamVolume += (long)(Math.Pow((cand.ContourHeight - first_z), 2) * (first_dist - prev_dist));

                                prev_lineID = line_ID;
                                prev_dist   = first_dist;
                            }
                        }
                    }

                    await DeleteCandidates(candidates, damCandidatesLayer, candidates2Delete);
                    //remove candidates with dam heights outside of the limits
                    await DeleteCandidates(candidates, damCandidatesLayer, candidates.Where(c => (c.ContourHeight - c.ZMin) < 10 || (c.ContourHeight - c.ZMin) > 300).ToList());

                    //update the new attributes to the feature
                    foreach (var candidate in candidates)
                    {
                        var editOp2 = new EditOperation();
                        Dictionary <string, object> attributes = new Dictionary <string, object>();
                        attributes.Add("DamHeight", (short)(candidate.ContourHeight - candidate.ZMin));
                        attributes.Add("DamVolume", (long)(candidate.DamVolume));
                        editOp2.Modify(damCandidatesLayer, candidate.ObjectID, attributes);
                        var resu = await editOp2.ExecuteAsync();
                    }

                    await Project.Current.SaveEditsAsync();
                });
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
            finally
            {
                DateTime endTime = DateTime.Now;
                SharedFunctions.Log("Analysed in " + (endTime - startTime).TotalSeconds.ToString("N") + " seconds completed (" + OutgoingCandidates.ToString("N0") + " of " + IncomingCandidates.ToString("N0") + " candidates left)");
            }
        }
        /// <summary>
        /// The on comboBox selection change event. This creates a new table that lists the assignments for the specified category.  This table is added to the map, selected in the TOC, and opened.
        /// </summary>
        /// <param name="item">The newly selected combo box item</param>
        protected override async void OnSelectionChange(ComboBoxItem item)
        {
            if (item == null)
            {
                return;
            }

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

            if (myLayer == null)
            {
                return;
            }

            //Construct the name of our table for the category assignment report
            string baseCategoryReportTableName = "CategoryAssignments_" + item.Text;
            string categoryReportTableName     = baseCategoryReportTableName.Replace(" ", "_");

            bool needToCreateTable        = true;
            bool needToAddStandaloneTable = true;

            // Switch to the MCT to access the geodatabase
            await QueuedTask.Run(() =>
            {
                // Check if the table exists

                using (Geodatabase projectWorkspace = new Geodatabase(new FileGeodatabaseConnectionPath(new Uri(Project.Current.DefaultGeodatabasePath))))
                {
                    try
                    {
                        using (Table categoryReportTable = projectWorkspace.OpenDataset <Table>(categoryReportTableName))
                        {
                            // Table exists, we do not need to create it...
                            needToCreateTable = false;

                            // .. but we should delete the existing contents
                            categoryReportTable.DeleteRows(new QueryFilter());

                            // Check to see if a Standalone table exists in the map
                            bool standaloneTableFound = false;
                            ReadOnlyObservableCollection <StandaloneTable> initialStandaloneTables = MapView.Active.Map.StandaloneTables;
                            foreach (StandaloneTable standaloneTable in initialStandaloneTables)
                            {
                                if (standaloneTable.Name == categoryReportTableName)
                                {
                                    standaloneTableFound = true;
                                }
                            }

                            // Since there is already a StandaloneTable that references our category table in the map, we don't need to add it
                            needToAddStandaloneTable = !standaloneTableFound;
                        }
                    }
                    catch
                    {
                        //Table doesn't exist.  Not an error, but we will have to create it
                    }
                }
            });

            // Create the category report table

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

                if (result.IsFailed)
                {
                    MessageBox.Show("Unable to create category assignment table in project workspace", "Category Assignments");
                    return;
                }

                // Add field for feature class alias
                IReadOnlyList <string> addFieldParams = Geoprocessing.MakeValueArray(new object[] { categoryReportTableName, "FeatureClassAlias", "TEXT", null, null, 32, "Feature Class", "NULLABLE", "NON_REQUIRED", null });
                result = await Geoprocessing.ExecuteToolAsync("management.AddField", addFieldParams);

                if (result.IsFailed)
                {
                    MessageBox.Show("Unable to modify schema of category assignment table in project workspace", "Category Assignments");
                    return;
                }

                // Add field for Asset Group name
                addFieldParams = Geoprocessing.MakeValueArray(new object[] { categoryReportTableName, "AssetGroupName", "TEXT", null, null, 256, "Asset Group Name", "NULLABLE", "NON_REQUIRED", null });
                result         = await Geoprocessing.ExecuteToolAsync("management.AddField", addFieldParams);

                if (result.IsFailed)
                {
                    MessageBox.Show("Unable to modify schema of category assignment table in project workspace", "Category Assignments");
                    return;
                }

                // Add field for Asset Type name
                addFieldParams = Geoprocessing.MakeValueArray(new object[] { categoryReportTableName, "AssetTypeName", "TEXT", null, null, 256, "Asset Type Name", "NULLABLE", "NON_REQUIRED", null });
                result         = await Geoprocessing.ExecuteToolAsync("management.AddField", addFieldParams);

                if (result.IsFailed)
                {
                    MessageBox.Show("Unable to modify schema of category assignment table in project workspace", "Category Assignments");
                    return;
                }

                needToAddStandaloneTable = false; //creating a table automatically adds it to the map
            }


            // Populate table
            // Again, we need to switch to the MCT to execute geodatabase and utility network code
            await QueuedTask.Run(() =>
            {
                using (Geodatabase projectWorkspace = new Geodatabase(new FileGeodatabaseConnectionPath(new Uri(Project.Current.DefaultGeodatabasePath))))
                    using (Table categoryReportTable = projectWorkspace.OpenDataset <Table>(categoryReportTableName))
                        using (UtilityNetwork utilityNetwork = UtilityNetworkSamples.UtilityNetworkUtils.GetUtilityNetworkFromLayer(myLayer))
                            using (UtilityNetworkDefinition utilityNetworkDefinition = utilityNetwork.GetDefinition())
                            {
                                IReadOnlyList <NetworkSource> networkSources = utilityNetworkDefinition.GetNetworkSources();

                                // Step through each NetworkSource
                                foreach (NetworkSource networkSource in networkSources)
                                {
                                    IReadOnlyList <AssetGroup> assetGroups = networkSource.GetAssetGroups();

                                    // Step through each AssetGroup
                                    foreach (AssetGroup assetGroup in assetGroups)
                                    {
                                        IReadOnlyList <AssetType> assetTypes = assetGroup.GetAssetTypes();

                                        // Step through each AssetType
                                        foreach (AssetType assetType in assetTypes)
                                        {
                                            // Check to see if this AssetType is assigned the Category we are looking for
                                            IReadOnlyList <string> assignedCategoryList = assetType.CategoryList;
                                            foreach (string assignedCategory in assignedCategoryList)
                                            {
                                                if (assignedCategory == item.Text)
                                                {
                                                    // Our Category is assigned to this AssetType.  Create a row to store in the category report table
                                                    using (FeatureClass networkSourceFeatureClass = utilityNetwork.GetTable(networkSource) as FeatureClass)
                                                        using (FeatureClassDefinition networkSourceFeatureClassDefinition = networkSourceFeatureClass.GetDefinition())
                                                            using (RowBuffer rowBuffer = categoryReportTable.CreateRowBuffer())
                                                            {
                                                                rowBuffer["FeatureClassAlias"] = networkSourceFeatureClassDefinition.GetAliasName();
                                                                rowBuffer["AssetGroupName"]    = assetGroup.Name;
                                                                rowBuffer["AssetTypeName"]     = assetType.Name;
                                                                categoryReportTable.CreateRow(rowBuffer).Dispose();
                                                            }
                                                }
                                            }
                                        }
                                    }
                                }

                                // If necessary, add our category report table to the map as a standalone table
                                if (needToAddStandaloneTable)
                                {
                                    IStandaloneTableFactory tableFactory = StandaloneTableFactory.Instance;
                                    tableFactory.CreateStandaloneTable(categoryReportTable, MapView.Active.Map);
                                }
                            }
            });

            // Open category report stand alone table into a window
            ReadOnlyObservableCollection <StandaloneTable> standaloneTables = MapView.Active.Map.StandaloneTables;

            foreach (StandaloneTable standaloneTable in standaloneTables)
            {
                if (standaloneTable.Name == categoryReportTableName)
                {
                    FrameworkApplication.Panes.OpenTablePane(standaloneTable, TableViewMode.eAllRecords);
                }
            }
        }
        protected override void OnClick()
        {
            var args = Geoprocessing.MakeValueArray();

            AddIn.OpenCustomGPTool(AddIn.MTToolboxAlias, Constants.CreateReferenceSystemGRGFromArea, args);
        }
        protected override void OnClick()
        {
            var args = Geoprocessing.MakeValueArray();

            AddIn.OpenCustomGPTool(AddIn.MTToolboxAlias, Constants.LowestPoints, args);
        }
        protected override void OnClick()
        {
            var args = Geoprocessing.MakeValueArray();

            AddIn.OpenCustomGPTool(AddIn.MTToolboxAlias, Constants.TableToPolyline, args);
        }
        protected override void OnClick()
        {
            var args = Geoprocessing.MakeValueArray();

            AddIn.OpenCustomGPTool(AddIn.MTToolboxAlias, Constants.RangeRingsFromMinAndMaxTable, args);
        }
Esempio n. 12
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
        }
Esempio n. 13
0
        /// <summary>
        /// Downloads the quads from the Planet servers using a geometry,
        /// an array of DD coords, raster service name and raster serviceid.
        /// </summary>
        /// <param name="geometry"></param>
        /// <param name="ff"></param>
        /// <param name="rasterseriesname"></param>
        /// <param name="rasterseriesid"></param>
        /// <returns></returns>
        private async Task getQuadsAsync(Geometry geometry, string[] ff, string rasterseriesname, string rasterseriesid)
        {
            //Mosicing can only happen with a standard license, warn user
            var ll = ArcGIS.Core.Licensing.LicenseInformation.Level;

            if (ll == ArcGIS.Core.Licensing.LicenseLevels.Basic)
            {
                MessageBoxResult messageBoxResult = MessageBox.Show("ArcGIS Pro is currently using a Basic license. The data source tiles can still be downloaded but a Raster Mosaic will not created." + Environment.NewLine + "Would you like to continue?", "Basic License Detected", MessageBoxButton.YesNo, MessageBoxImage.Warning);
                if (messageBoxResult == MessageBoxResult.No)
                {
                    return;
                }
            }

            //should not use a using statement, need to fix
            //get a list of quads as GeoTiffs2 items by querying the rest endpoint of the selected layer
            //with the geometry and points
            using (HttpClient client = new HttpClient())
            {
                var response = client.GetAsync("https://api.planet.com/basemaps/v1/mosaics/" + rasterseriesid + "/quads?api_key=" + Module1.Current.API_KEY.API_KEY_Value + "&bbox=" + ff[1] + "," + ff[0] + "," + ff[3] + "," + ff[2]).Result;
                ObservableCollection <Data.GeoTiffs2> geotiffs = new ObservableCollection <Data.GeoTiffs2>();
                if (response.IsSuccessStatusCode)
                {
                    Task <string> responseContent = response.Content.ReadAsStringAsync();
                    Quads         quads           = JsonConvert.DeserializeObject <Quads>(responseContent.Result);
                    if (quads.items.Count() > 50)
                    {
                        MessageBox.Show("More than 50 quads selected, please download a smaller area.");
                        return;
                    }
                    foreach (Item item in quads.items)
                    {
                        geotiffs.Add(new Data.GeoTiffs2()
                        {
                            Name = item.id, DownloadURL = item._links.download
                        });
                    }
                    Console.WriteLine(responseContent.Result);
                }
                else
                {
                    MessageBox.Show("Extent not found");
                    return;
                }
                string area = "";
                if (geometry.GeometryType == GeometryType.Polygon)
                {
                    Polygon polygon = (Polygon)geometry;
                    if (geometry.SpatialReference.Unit.Name == "Foot_US")
                    {
                        double sqMeters = AreaUnit.SquareFeet.ConvertToSquareMeters(polygon.Area);
                        area = AreaUnit.SquareKilometers.ConvertFromSquareMeters(sqMeters).ToString();
                    }
                    else if (geometry.SpatialReference.Unit.Name == "Meter")
                    {
                        area = AreaUnit.SquareKilometers.ConvertFromSquareMeters(polygon.Area).ToString();
                    }

                    area = " Approx Sqkm: " + area.Substring(0, area.IndexOf("."));
                }

                //set up the Folderselector view with a list of the quads and area
                FolderSelector folderSelector = new FolderSelector();
                folderSelector.lbxGrids.ItemsSource = geotiffs;
                folderSelector.ShowNewFolderButton  = false;
                folderSelector.ShowActivated        = true;
                folderSelector.SizeToContent        = SizeToContent.Width;
                object da = folderSelector.txtGrids.DataContext;
                if (da is Data.BaseItem ba)
                {
                    ba.QuadCount = "Total basemap quads selected: " + geotiffs.Count.ToString() + area;
                }
                folderSelector.ShowDialog();

                //If the user clicked OK on the view start the download
                if ((bool)folderSelector.DialogResult)
                {
                    //Do the download
                    string        savelocation = folderSelector.SelectedPath;
                    List <string> tiffs        = new List <string>();
                    int           i            = 0;
                    int           total        = geotiffs.Count();

                    foreach (Data.GeoTiffs2 quad in geotiffs)
                    {
                        if (string.IsNullOrEmpty(quad.DownloadURL))
                        {
                            MessageBox.Show(String.Format("No download link provided for quad {0}", quad.Name));
                            continue;
                        }
                        await LoadImage(quad.DownloadURL, savelocation + "\\" + rasterseriesname + quad.Name + ".tif");

                        tiffs.Add(savelocation + "\\" + rasterseriesname + quad.Name + ".tif");
                        if (total % ++i == 0)
                        {
                            FrameworkApplication.AddNotification(new Notification()
                            {
                                Title    = "Downloading........",
                                Message  = String.Format("{0} of {1} files successfully dowloaded", i, total),
                                ImageUrl = @"Images/Planet_logo-dark.png"
                                           //ImageUrl = @"pack://*****:*****@"pack://application:,,,/Planet;component/Images/Planet_logo-dark.png"
                    });

                    //Create a raster Mosic in the default FGDB using Geoprocessing tools
                    string inpath = Project.Current.DefaultGeodatabasePath;
                    //inpath = @"C:\Users\Andrew\Documents\ArcGIS\Projects\MyProject22\MyProject22.gdb";
                    string in_mosaicdataset_name = rasterseriesname;
                    var    sr = await QueuedTask.Run(() => {
                        return(SpatialReferenceBuilder.CreateSpatialReference(3857));
                    });

                    var    parameters = Geoprocessing.MakeValueArray(inpath, in_mosaicdataset_name, sr, "3", "8_BIT_UNSIGNED", "NATURAL_COLOR_RGB");
                    string tool_path  = "management.CreateMosaicDataset";
                    System.Threading.CancellationTokenSource _cts = new System.Threading.CancellationTokenSource();
                    IGPResult result = await Geoprocessing.ExecuteToolAsync(tool_path, parameters, null, _cts.Token, (event_name, o) =>  // implement delegate and handle events, o is message object.
                    {
                        switch (event_name)
                        {
                        case "OnValidate":     // stop execute if any warnings
                            if ((o as IGPMessage[]).Any(it => it.Type == GPMessageType.Warning || it.Type == GPMessageType.Error))
                            {
                                System.Windows.MessageBox.Show(o.ToString());
                                _cts.Cancel();
                            }
                            break;
                            //case "OnProgressMessage":
                            //    string msg = string.Format("{0}: {1}", new object[] { event_name, (string)o });
                            //    //System.Windows.MessageBox.Show(msg);
                            //    //_cts.Cancel();
                            //    break;
                            //case "OnProgressPos":
                            //    string msg2 = string.Format("{0}: {1} %", new object[] { event_name, (int)o });
                            //    System.Windows.MessageBox.Show(msg2);
                            //    //_cts.Cancel();
                            //    break;
                        }
                    });

                    result     = null;
                    parameters = null;
                    _cts       = null;

                    //Load the downloaded .tifs into the Mosic
                    System.Threading.CancellationTokenSource _cts2 = new System.Threading.CancellationTokenSource();
                    tool_path  = "management.AddRastersToMosaicDataset";
                    parameters = Geoprocessing.MakeValueArray(inpath + "\\" + in_mosaicdataset_name, "Raster Dataset", String.Join(";", tiffs), "UPDATE_CELL_SIZES", "UPDATE_BOUNDARY", "UPDATE_OVERVIEWS", "-1");
                    //parameters = Geoprocessing.MakeValueArray(inpath + "\\" + in_mosaicdataset_name, "Raster Dataset", @"D:\Planet\global_monthly_2019_02_mosaic982-1377.tif;D:\Planet\global_monthly_2019_02_mosaic983-1377.tif");
                    try
                    {
                        IGPResult gPResult = await Geoprocessing.ExecuteToolAsync(tool_path, parameters, null, _cts2.Token, (event_name, o) =>  // implement delegate and handle events, o is message object.
                        {
                            switch (event_name)
                            {
                            case "OnValidate":     // stop execute if any warnings or errors
                                if ((o as IGPMessage[]).Any(it => it.Type == GPMessageType.Warning || it.Type == GPMessageType.Error))
                                {
                                    System.Windows.MessageBox.Show("Failed to add .tif files" + Environment.NewLine + o.ToString() + Environment.NewLine + "The files have been downloaded but not added to The raster Mosic", "Failed to add .tif files");
                                    _cts2.Cancel();
                                }
                                break;

                            case "OnProgressMessage":
                                //string msg = string.Format("{0}: {1}", new object[] { event_name, (string)o });
                                //System.Windows.MessageBox.Show(msg);
                                //_cts.Cancel();
                                break;

                            case "OnProgressPos":
                                //string msg2 = string.Format("{0}: {1} %", new object[] { event_name, (int)o });
                                //System.Windows.MessageBox.Show(msg2);
                                //_cts.Cancel();
                                break;
                            }
                        });

                        Geoprocessing.ShowMessageBox(gPResult.Messages, "GP Messages", gPResult.IsFailed ? GPMessageBoxStyle.Error : GPMessageBoxStyle.Default);
                        //Geoprocessing.OpenToolDialog(tool_path, parameters);
                    }
                    catch (Exception ex)
                    {
                        System.Windows.MessageBox.Show(ex.Message.ToString());
                        _cts2.Cancel();
                    }


                    //Everything downloaded and added to the mosic
                    FrameworkApplication.AddNotification(new Notification()
                    {
                        Title    = "Download successful",
                        Message  = "Successfully dowloaded the basemap source quads",
                        ImageUrl = @"pack://application:,,,/Planet;component/Images/Planet_logo-dark.png"
                    });
                }
            }
        }
Esempio n. 14
0
        private async void sensitivity_Click(object sender, EventArgs e)
        {
            //Creating a csv file
            //string main = @"D:\";
            //string filepath = main + "myfile.csv";
            //System.Diagnostics.Debug.WriteLine(filepath);

            //if (!File.Exists(filepath))
            //{
            // File.Create(filepath).Close();
            // }

            Stream         myStream;
            SaveFileDialog saveFileDialog1 = new SaveFileDialog();

            saveFileDialog1.Filter           = "csv files (*.csv)|*.csv|All files (*.*)|*.*";
            saveFileDialog1.FilterIndex      = 2;
            saveFileDialog1.RestoreDirectory = true;
            saveFileDialog1.OverwritePrompt  = true;
            saveFileDialog1.AddExtension     = true;
            saveFileDialog1.InitialDirectory = @"D:\";
            saveFileDialog1.Title            = "Save 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
                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);

                    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);
                    await Geoprocessing.ExecuteToolAsync("sa.Reclassify", kufli, env, null, null, GPExecuteToolFlags.AddOutputsToMap);

                    //Geoprocessing.OpenToolDialog("sa.Reclassify", kufli);
                }
                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);

                    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);
                    await Geoprocessing.ExecuteToolAsync("sa.Reclassify", kufli, env, null, null, GPExecuteToolFlags.AddOutputsToMap);

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


                //Geoprocessing.OpenToolDialog("sa.WeightedSum", param_values);



                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();
            }
        }
        public static async Task GenerateIDEKeyPointAsync(string fcName)
        {
            //1.
            await QueuedTask.Run(() =>
            {
                using (Geodatabase gdb = new Geodatabase(new FileGeodatabaseConnectionPath(new Uri(GeoDataTool.DefaultProject.DefaultGeodatabasePath))))
                {
                    gdb.ApplyEdits(() =>
                    {
                        using (FeatureClass fcStaticObstructPoint = gdb.OpenDataset <FeatureClass>(fcName))
                        {
                            FeatureClassDefinition fcdStaticObstructPoint = gdb.GetDefinition <FeatureClassDefinition>(fcName);
                            FeatureClass fcSOPBuffer    = gdb.OpenDataset <FeatureClass>(ConstDefintion.ConstFeatureClass_SOPBuffer);
                            FeatureClass fc_SOPIDEPoint = gdb.OpenDataset <FeatureClass>(ConstDefintion.ConstFeatureClass_SOPIDEPoint);
                            fc_SOPIDEPoint.DeleteRows(new QueryFilter()
                            {
                                WhereClause = "OBJECTID >= 1"
                            });
                            using (RowCursor rc = fcStaticObstructPoint.Search(null, false))
                            {
                                while (rc.MoveNext())
                                {
                                    using (Feature f = rc.Current as Feature)
                                    {
                                        int affectDis       = Convert.ToInt32(f[ConstDefintion.ConstFieldName_AffectDis]);
                                        double affectDegree = (double)f[ConstDefintion.ConstFieldName_AffectDegree];
                                        MapPoint p          = f[fcdStaticObstructPoint.GetShapeField()] as MapPoint;
                                        GeodesicEllipseParameter geodesic = new GeodesicEllipseParameter()
                                        {
                                            Center          = p.Coordinate2D,
                                            SemiAxis1Length = affectDis,
                                            SemiAxis2Length = affectDis,
                                            LinearUnit      = LinearUnit.Meters,
                                            OutGeometryType = GeometryType.Polygon,
                                            AxisDirection   = 0,
                                            VertexCount     = 800
                                        };
                                        Geometry circle = GeometryEngine.Instance.GeodesicEllipse(geodesic, SpatialReferenceBuilder.CreateSpatialReference(3857));
                                        using (RowBuffer rowBuffer = fcSOPBuffer.CreateRowBuffer())
                                        {
                                            // Either the field index or the field name can be used in the indexer.
                                            rowBuffer[ConstDefintion.ConstFieldName_AffectDegree] = 0;
                                            rowBuffer["Shape"] = circle;
                                            using (Feature feature = fcSOPBuffer.CreateRow(rowBuffer))
                                            {
                                                feature.Store();
                                            }
                                        }
                                        using (RowBuffer rowBuffer = fc_SOPIDEPoint.CreateRowBuffer())
                                        {
                                            // Either the field index or the field name can be used in the indexer.
                                            rowBuffer[ConstDefintion.ConstFieldName_AffectDegree] = affectDegree;
                                            rowBuffer["Shape"] = p;
                                            using (Feature feature = fc_SOPIDEPoint.CreateRow(rowBuffer))
                                            {
                                                feature.Store();
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    });
                }
            });

            //2.运行要素边缘转点
            string inpath = GeoDataTool.DefaultProject.DefaultGeodatabasePath + "\\" + ConstDefintion.ConstFeatureClass_SOPBufferPoint;
            var    args   = Geoprocessing.MakeValueArray(inpath);
            var    result = await Geoprocessing.ExecuteToolAsync("Delete_management", args, null, null, null);

            string inpath1 = GeoDataTool.DefaultProject.DefaultGeodatabasePath + "\\" + ConstDefintion.ConstFeatureClass_SOPBuffer;
            string outpath = GeoDataTool.DefaultProject.DefaultGeodatabasePath + "\\" + ConstDefintion.ConstFeatureClass_SOPBufferPoint;
            var    args1   = Geoprocessing.MakeValueArray(inpath1, outpath, "ALL");
            var    result1 = await Geoprocessing.ExecuteToolAsync("FeatureVerticesToPoints_management", args1, null, null, null);

            //3.
            await QueuedTask.Run(() =>
            {
                using (Geodatabase gdb = new Geodatabase(new FileGeodatabaseConnectionPath(new Uri(GeoDataTool.DefaultProject.DefaultGeodatabasePath))))
                {
                    gdb.ApplyEdits(() =>
                    {
                        FeatureClass SOPIDEPoint    = gdb.OpenDataset <FeatureClass>(ConstDefintion.ConstFeatureClass_SOPIDEPoint);
                        FeatureClass SOPBufferPoint = gdb.OpenDataset <FeatureClass>(ConstDefintion.ConstFeatureClass_SOPBufferPoint);
                        FeatureClassDefinition SOPIDEPointDefinition = gdb.GetDefinition <FeatureClassDefinition>(ConstDefintion.ConstFeatureClass_SOPIDEPoint);
                        using (RowCursor rowCursor = SOPBufferPoint.Search(null, false))
                        {
                            while (rowCursor.MoveNext())
                            {
                                using (Feature f = rowCursor.Current as Feature)
                                {
                                    using (RowBuffer rowBuffer = SOPIDEPoint.CreateRowBuffer())
                                    {
                                        rowBuffer[ConstDefintion.ConstFieldName_AffectDegree] = 0;
                                        rowBuffer[SOPIDEPointDefinition.GetShapeField()]      = f.GetShape();
                                        using (Feature feature = SOPIDEPoint.CreateRow(rowBuffer))
                                        {
                                            feature.Store();
                                        }
                                    }
                                }
                            }
                        }
                    });
                }
            });
        }
        protected override void OnClick()
        {
            var args = Geoprocessing.MakeValueArray();

            AddIn.OpenCustomGPTool(AddIn.MTToolboxAlias, Constants.RadialLineOfSightAndRange, args);
        }
Esempio n. 17
0
        internal async void UpdateCluster(bool isTolerance)
        {
            if (MapView.Active == null)
            {
                return;
            }
            // Get Layer Name
            string inputFC = SelectedLayer.Name;

            int  minPoints = 2;
            bool parsed    = Int32.TryParse(MinPoints, out minPoints);

            /// Set PYT path -This could be inserted as a resource file //
            string tool_path = "C:\\Dev_summit\\2018\\InteractiveAnalytics\\pyt\\UpdateCluster.pyt\\UpdateClusterTool";

            IReadOnlyList <string> args = null;

            if (isTolerance)
            {
                /// Arguments for executing process using Tolerance
                args = Geoprocessing.MakeValueArray(inputFC, minPoints, ValueSlider, -1);
            }
            else
            {
                /// Arguments for executing process using Threshold
                args = Geoprocessing.MakeValueArray(inputFC, minPoints, -1, ValueThreshold);
            }

            Task <IGPResult> task;

            /// Execute the Tool in the python toolbox
            task = Geoprocessing.ExecuteToolAsync(tool_path, args, flags: GPExecuteToolFlags.AddToHistory);


            StyleProjectItem style;
            CIMPointSymbol   pointSymbol = null;

            /// Get Pro Styles
            style = await QueuedTask.Run <StyleProjectItem>(() => Project.Current.GetItems <StyleProjectItem>().First(s => s.Name == "ArcGIS 2D"));


            await QueuedTask.Run(() =>
            {
                /// Search for a specific Symbol
                /// Other styles Arcgis/Resouces/Styles/Styles.stylx SQLite DB
                SymbolStyleItem symbolStyleItem = (SymbolStyleItem)style.LookupItem(StyleItemType.PointSymbol, "Circle 1_Shapes_3");
                pointSymbol = (CIMPointSymbol)symbolStyleItem.Symbol;

                /// Cluster Ids based in Color Schema
                int[] ids = new int[] { -1, 1, 2, 3, 4, 5, 6, 7, 8 };

                /// Set Colors
                string[] colors = new string[] { "156,156,156", "166,206,227", "31,120,180", "178,223,138",
                                                 "51,160,44", "251,154,153", "227,26,28", "253,191,111",
                                                 "255,127,0" };
                /// Color Field
                String[] fields = new string[] { "COLOR_ID" };

                /// Make a reference of the point symbol
                CIMSymbolReference symbolPointTemplate = pointSymbol.MakeSymbolReference();

                /// Get definition of type symbology unique values
                UniqueValueRendererDefinition uniqueValueRendererDef = new UniqueValueRendererDefinition(fields, symbolPointTemplate, null, symbolPointTemplate, false);

                /// Get Current renderer of the Selected Layer
                CIMUniqueValueRenderer renderer  = (CIMUniqueValueRenderer)SelectedLayer.CreateRenderer(uniqueValueRendererDef);
                CIMUniqueValueClass[] newClasses = new CIMUniqueValueClass[colors.Count()];

                /// Get Point Symbol as string for creating other point colors
                string point = pointSymbol.ToXml();

                /// Create Each Color
                for (int i = 0; i < ids.Length; i++)
                {
                    CIMPointSymbol npoint = CIMPointSymbol.FromXml(point);
                    if (ids[i] == -1)
                    {
                        npoint.SetSize(4);
                    }
                    else
                    {
                        npoint.SetSize(6);
                    }
                    CIMSymbolReference symbolPointTemplatei = npoint.MakeSymbolReference();
                    newClasses[i]                          = new CIMUniqueValueClass();
                    newClasses[i].Values                   = new CIMUniqueValue[1];
                    newClasses[i].Values[0]                = new CIMUniqueValue();
                    newClasses[i].Values[0].FieldValues    = new string[1];
                    newClasses[i].Values[0].FieldValues[0] = ids[i].ToString();
                    newClasses[i].Label                    = ids[i].ToString();
                    newClasses[i].Symbol                   = symbolPointTemplatei;
                    var color = colors[i].Split(',');
                    double r  = Convert.ToDouble(color[0]);
                    double g  = Convert.ToDouble(color[1]);
                    double b  = Convert.ToDouble(color[2]);
                    newClasses[i].Symbol.Symbol.SetColor(CIMColor.CreateRGBColor(r, g, b));
                }
                /// Add Colors into the renderer
                renderer.Groups[0].Classes = newClasses;

                /// Apply new renderer in the layer
                SelectedLayer.SetRenderer(renderer);

                //SelectedLayer.RecalculateRenderer();
            });
        }
Esempio n. 18
0
        public static async Task CreateFeatureClass(string geodatabasepath, SpatialReference spatialReference, string featureclassName, string featureclassType)
        {
            List <object> arguments = new List <object>
            {
                geodatabasepath,
                featureclassName,
                featureclassType,
                "",
                "DISABLED",
                "DISABLED"
            };
            await QueuedTask.Run(() =>
            {
                // spatial reference
                arguments.Add(spatialReference);
            });

            IGPResult result = await Geoprocessing.ExecuteToolAsync("CreateFeatureclass_management", Geoprocessing.MakeValueArray(arguments.ToArray()));
        }
 /// <summary>
 /// テキスト ボックスに格納される
 /// </summary>
 private async Task ExecuteGeoprocessingTool(string tool, IReadOnlyList <string> parameters)
 {
     await Geoprocessing.ExecuteToolAsync(tool, parameters);
 }
        public async void SubmitExecute()
        {
            ValidationSubmitError = null;

            List <string> validationSubmitErrors = new List <string>();

            string aoi = null;

            if (_selectedAOILayer != null)
            {
                if (_selectedAOILayer is FeatureLayer)
                {
                    FeatureLayer lyr = _selectedAOILayer as FeatureLayer;

                    int featureCount = await QueuedTask.Run(() => { return(lyr.GetFeatureClass().GetCount()); });

                    if (featureCount == 0)
                    {
                        validationSubmitErrors.Add("AOI is empty.");
                    }
                    else
                    {
                        aoi = await Ag_Analytics_Module.GetGeoJSONFromFeatureLayer(lyr);
                    }
                }
                else if (_selectedAOILayer is RasterLayer)
                {
                    RasterLayer lyr            = _selectedAOILayer as RasterLayer;
                    string      default_path   = Path.GetDirectoryName(Project.Current.URI);
                    string      timestamp      = DateTime.Now.ToString("yyyyMMddHHmmss");
                    string      rasterFileName = "AOI_Raster_" + timestamp + ".tif";
                    string      outputRaster   = Path.Combine(default_path, rasterFileName);
                    var         parameters     = Geoprocessing.MakeValueArray(lyr.Name, outputRaster, "", "", "", false, false, "", false, false, "TIFF");
                    IGPResult   result         = await Geoprocessing.ExecuteToolAsync("management.CopyRaster", parameters, null, null, null, GPExecuteToolFlags.None);

                    aoi = outputRaster;
                }
            }
            else
            {
                validationSubmitErrors.Add("AOI parameter must be selected.");
            }

            if (_downloadPath == null || string.IsNullOrEmpty(_downloadPath))
            {
                validationSubmitErrors.Add("Download path must be selected.");
            }
            else
            {
                if (!Directory.Exists(_downloadPath))
                {
                    validationSubmitErrors.Add("Download path doesn't exsist.");
                }
            }

            SpatialReference outputSpatialReference = null;

            if (selectedSpatialReference == null)
            {
                outputSpatialReference = await QueuedTask.Run(() => { return(_selectedAOILayer.GetSpatialReference()); });
            }
            else
            {
                outputSpatialReference = selectedSpatialReference;
            }

            if (outputSpatialReference.IsGeographic && _cellSize > 1)
            {
                validationSubmitErrors.Add("Resolution must be < 1 in geographic coordinate system(ex:0.0001)");
            }
            else if (outputSpatialReference.IsProjected && _cellSize < 1)
            {
                validationSubmitErrors.Add("Resolution must be > 1 in projected coordinate system(ex:10)");
            }

            if (validationSubmitErrors.Count > 0)
            {
                ValidationSubmitError = string.Join("\n", validationSubmitErrors);
                return;
            }
            if (validationInputError != null)
            {
                return;
            }

            SubmitButtonEnabled = false;
            ResultBoxVisible    = "Hidden";
            ProgressMessage     = "Request Calling...";
            ProgressVisible     = "Visible";
            DateTime started_datetime = DateTime.Now;

            SubmitStartedTime  = started_datetime.ToString();
            ResultErrorMessage = "";

            IRestResponse apiResponse = await BackgroundTask.Run <IRestResponse>(() => {
                var client     = new RestClient("https://ag-analytics.azure-api.net/dem-service/");
                client.Timeout = -1;
                var request    = new RestRequest(Method.POST);

                request.AlwaysMultipartFormData = true;
                //request.AddHeader("Content-Type", "application/x-www-form-urlencoded");

                if (_selectedAOILayer is FeatureLayer)
                {
                    request.AddParameter("aoi", aoi);
                }
                else if (_selectedAOILayer is RasterLayer)
                {
                    request.AddFile("aoi", aoi);
                }

                request.AddParameter("Resolution", _cellSize);
                request.AddParameter("Elevation_Index", _checkElevationIndex ? "True" : "False");


                request.AddParameter("Projection", string.Format("EPSG:{0}", outputSpatialReference.GcsWkid));

                // these parameter options no need on ArcGIS pro
                request.AddParameter("Legend_Ranges", 3);

                SubmitAOI            = aoi;
                SubmitResolution     = _cellSize.ToString();
                SubmitElevationIndex = _checkElevationIndex ? "True" : "False";
                SubmitProjection     = string.Format("EPSG:{0}", outputSpatialReference.GcsWkid);
                SubmitDownloadFolder = _downloadPath;

                IRestResponse response = client.Execute(request);

                return(response);
            }, BackgroundProgressor.None);

            if (File.Exists(aoi))
            {
                string   default_path  = Path.GetDirectoryName(Project.Current.URI);
                string   filesToDelete = Path.GetFileNameWithoutExtension(aoi) + ".*";
                string[] fileList      = Directory.GetFiles(default_path, filesToDelete);
                foreach (string file in fileList)
                {
                    File.Delete(file);
                }
            }

            if (!apiResponse.IsSuccessful)
            {
                //ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("Failed Result. Please try again.");
                ResultErrorMessage += "Response Error\n";
                ResultErrorMessage += apiResponse.ErrorMessage;
                DisplayFailed(started_datetime);

                return;
            }

            dynamic jsonData = JsonConvert.DeserializeObject <dynamic>(apiResponse.Content);

            // download elevation files
            ProgressMessage = "Downloading tif files...";
            try
            {
                string filename = jsonData.FileName;
                await ExportFile(_downloadPath, filename);
            }
            catch (Exception e)
            {
                //ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("API Error. Please try again.");
                ResultErrorMessage += "Download Error\n";
                ResultErrorMessage += e.Message;
                DisplayFailed(started_datetime);

                return;
            }

            // if return elevation index
            if (_checkElevationIndex)
            {
                try
                {
                    var Index_Files_list = jsonData.Index_Files;
                    for (int i = 0; i < Index_Files_list.Count; i++)
                    {
                        string index_filename = Index_Files_list[i];

                        await ExportFile(_downloadPath, index_filename);
                    }
                }
                catch (Exception e)
                {
                    //ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("No Elevation Index returned. Please try again.");
                    ResultErrorMessage += "Download Error\n";
                    ResultErrorMessage += e.Message;
                    DisplayFailed(started_datetime);

                    return;
                }
            }

            ProgressVisible = "Hidden";
            ProgressMessage = "";
            DateTime ended_datetime = DateTime.Now;

            CompletedTime = ended_datetime.ToString();
            int seconds = (int)(ended_datetime.Subtract(started_datetime).TotalSeconds);

            ElapsedTime = seconds.ToString() + "  Seconds";

            ResultBoxBGColor    = "#3a593a";
            ResultBoxImage      = "pack://application:,,,/ArcGIS.Desktop.Resources;component/Images/DataReviewerLifecycleVerified32.png";
            ResultBoxMessage    = "Completed";
            ResultErrorMessage  = "There are no errors or warnings.";
            ResultBoxVisible    = "Visible";
            SubmitButtonEnabled = true;
        }
        /// <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
            arguments.Add(CoreModule.CurrentProject.DefaultGeodatabasePath);
            // name of the feature class
            arguments.Add(featureclassName);
            // type of geometry
            arguments.Add(featureclassType);
            // no template
            arguments.Add("");
            // no z values
            arguments.Add("DISABLED");
            // no m values
            arguments.Add("DISABLED");

            await QueuedTask.Run(() =>
            {
                // spatial reference
                arguments.Add(SpatialReferenceBuilder.CreateSpatialReference(3857));
            });

            IGPResult result = await Geoprocessing.ExecuteToolAsync("CreateFeatureclass_management", Geoprocessing.MakeValueArray(arguments.ToArray()));
        }
        private async void GPToolRun()
        {
            try
            {
                //string toolboxPath = @"D:\RnD_Data\EsriTraining\PythonGP\Scripts\CreateFCAndFields.pyt\CreateFeatureClassAndFields";
                string toolboxPath = @"D:\RnD_Data\EsriTraining\PythonGP\ScriptTool\CreateFCAndFields.tbx\CreateFCAndFields";
                string gdbPath     = @"D:\RnD_Data\EsriTraining\PythonGP\Data\SanJuan.gdb";

                string fcName       = "TempFeature_" + DateTime.Now.ToString("yyyyMMddHHmmssf");
                string geometryType = "POINT";
                string hasZValue    = "DISABLED";
                //SpatialReference outSR = SpatialReferenceBuilder.CreateSpatialReference(4326);
                int outSR = 4326;
                List <FieldInfo> fieldInfoList = new List <FieldInfo>();
                fieldInfoList.Add(new FieldInfo()
                {
                    aliasName = "Home",
                    name      = "Home",
                    fieldType = (int)FieldType.String,
                    length    = 255
                });
                fieldInfoList.Add(new FieldInfo()
                {
                    aliasName = "Created By",
                    name      = "Created By",
                    fieldType = (int)FieldType.String,
                    length    = 255
                });
                fieldInfoList.Add(new FieldInfo()
                {
                    aliasName = "Age",
                    name      = "Age",
                    fieldType = (int)FieldType.Integer
                });
                fieldInfoList.Add(new FieldInfo()
                {
                    aliasName = "Updated Date",
                    name      = "Updated Date",
                    fieldType = (int)FieldType.Date
                });
                bool   result           = false;
                string message          = "";
                string strFieldInfoList = "[['school_name', 'TEXT', 'Name', 255, 'Hello world', '']," +
                                          "['street_number', 'LONG', 'Street Number', None, 35, 'StreetNumDomain']," +
                                          "['year_start', 'DATE', 'Year Start', None, '2017-08-09 16:05:07', '']]";
                List <List <string> > FieldInfoList = new List <List <string> >()
                {
                    new List <string>()
                    {
                        "school_name", "TEXT", "Name", "255", "Hello world", ""
                    },
                    new List <string>()
                    {
                        "year_start", "DATE", "Year Start", "None", "2017-08-09 16:05:07", ""
                    }
                };

                //Correct way of import
                List <string> strFieldList = new List <string>()
                {
                    "'school_name' 'TEXT' 'Name' 255 'Hello world' ''",
                    "'year_start' 'DATE' 'Year Start' None '2017-08-09 16:05:07' ''"
                };

                var arguments = Geoprocessing.MakeValueArray(gdbPath, fcName, geometryType, hasZValue, outSR, strFieldList, result, message);
                Geoprocessing.OpenToolDialog(toolboxPath, arguments);
                //var gpResult = Geoprocessing.ExecuteToolAsync(toolboxPath, arguments);
                //gpResult.Wait();
                //IGPResult ProcessingResult = gpResult.Result;
                //if (ProcessingResult.IsFailed)
                //{
                //    string errorMessage = "";
                //    foreach (IGPMessage gpMessage in ProcessingResult.Messages)
                //    {
                //        errorMessage += $"{{Error Code: {gpMessage.ErrorCode}, Text :  {gpMessage.Text} }}";
                //    }
                //    MessageBox.Show($"Geoprocessing fail {errorMessage}");
                //}
                //else
                //{
                //    MessageBox.Show("Process  success");

                //}
                //using (Geodatabase fileGeodatabase = new Geodatabase(new FileGeodatabaseConnectionPath(new Uri("dkfs"))))

                //using (FeatureClassDefinition featureClass = fileGeodatabase.GetDefinition<FeatureClassDefinition>("dkfs"))

                //{
                //    this.FieldListToAdd = featureClass.GetFields();
                //}
            }
            catch (Exception exce)
            {
                MessageBox.Show($"Exception occured {exce.Message}{Environment.NewLine}{exce.StackTrace}");
            }
        }
        public async void SubmitExecute()
        {
            ValidationSubmitError = null;
            List <string> validationSubmitErrors = new List <string>();

            if (_operationRasters.Count == 0)
            {
                validationSubmitErrors.Add("Operation Rasters must be added.");
            }

            if (_downloadPath == null || string.IsNullOrEmpty(_downloadPath))
            {
                validationSubmitErrors.Add("Download path must be selected.");
            }
            else
            {
                if (!Directory.Exists(_downloadPath))
                {
                    validationSubmitErrors.Add("Download path doesn't exsist.");
                }
            }
            if (validationSubmitErrors.Count > 0)
            {
                ValidationSubmitError = string.Join("\n", validationSubmitErrors);
                return;
            }

            if (validationInputError != null)
            {
                return;
            }

            SubmitButtonEnabled = false;
            ResultBoxVisible    = "Hidden";
            ProgressVisible     = "Visible";
            ProgressMessage     = "Iinitalizing...";
            DateTime started_datetime = DateTime.Now;

            SubmitStartedTime  = started_datetime.ToString();
            ResultErrorMessage = "";

            string default_path = Path.GetDirectoryName(Project.Current.URI);

            foreach (OperationRaster item in _operationRasters)
            {
                string    timestamp      = DateTime.Now.ToString("yyyyMMddHHmmss");
                string    rasterFileName = "Operation_Raster_" + timestamp + ".tif";
                string    outputRaster   = Path.Combine(default_path, rasterFileName);
                var       parameters     = Geoprocessing.MakeValueArray(_selectedOperationRasterLayer.Name, outputRaster, "", "", "", false, false, "", false, false, "TIFF");
                IGPResult result         = await Geoprocessing.ExecuteToolAsync("management.CopyRaster", parameters, null, null, null, GPExecuteToolFlags.None);

                item.Raster_Path = outputRaster;
            }

            string outputVarietyRasterPath = null;

            if (_checkVarietyRasterLayer && _selectedVarietyRasterLayer != null)
            {
                string timestamp      = DateTime.Now.ToString("yyyyMMddHHmmss");
                string rasterFileName = "Raster_" + timestamp + ".tif";
                outputVarietyRasterPath = Path.Combine(default_path, rasterFileName);
                var       parameters = Geoprocessing.MakeValueArray(_selectedVarietyRasterLayer.Name, outputVarietyRasterPath, "", "", "", false, false, "", false, false, "TIFF");
                IGPResult result     = await Geoprocessing.ExecuteToolAsync("management.CopyRaster", parameters, null, null, null, GPExecuteToolFlags.None);
            }

            string outputVarietyTablePath = null;

            if (_checkVarietyDBFTable && _selectedVarietyDBFTable != null)
            {
                string timestamp       = DateTime.Now.ToString("yyyyMMddHHmmss");
                string outputTableName = "Table_" + timestamp + ".dbf";
                outputVarietyTablePath = Path.Combine(default_path, outputTableName);
                var       parameters = Geoprocessing.MakeValueArray(_selectedVarietyDBFTable.Name, outputVarietyTablePath);
                IGPResult result     = await Geoprocessing.ExecuteToolAsync("management.CopyRows", parameters, null, null, null, GPExecuteToolFlags.None);
            }

            ProgressMessage = "Request Calling...";

            IRestResponse apiResponse = await BackgroundTask.Run <IRestResponse>(() =>
            {
                var client     = new RestClient("https://analytics.ag/api/ToolBoxProxy/ProfitLayer");
                client.Timeout = -1;
                var request    = new RestRequest(Method.POST);
                request.AlwaysMultipartFormData = true;

                List <string> raster_path_array = new List <string>();
                List <string> raster_cost_array = new List <string>();

                foreach (OperationRaster raster in _operationRasters)
                {
                    request.AddFile("rasters", raster.Raster_Path);
                    raster_path_array.Add(raster.Raster_Path.ToString());
                    raster_cost_array.Add(raster.Raster_Cost.ToString());
                }
                string constants_vector = string.Join(",", raster_cost_array);

                if (outputVarietyRasterPath != null)
                {
                    request.AddFile("category_raster", outputVarietyRasterPath);
                }

                if (outputVarietyTablePath != null)
                {
                    request.AddFile("dbf_file", outputVarietyTablePath);
                }

                request.AddParameter("constants_vector", constants_vector);
                request.AddParameter("constant_add", _constantAdd);
                request.AddParameter("cell_size", _cellSize);
                request.AddParameter("Token", "v4289wyrwIShfgIWQO4DFWawrzf");

                SubmitRasters         = string.Join(",", raster_path_array);
                SubmitConstantsVector = constants_vector;
                SubmitCategoryRaster  = outputVarietyRasterPath;
                SubmitDbfFile         = outputVarietyTablePath;
                SubmitConstantAdd     = _constantAdd.ToString();
                SubmitCellSize        = _cellSize.ToString();
                SubmitToken           = "v4289wyrwIShfgIWQO4DFWawrzf";
                SubmitDownloadFolder  = _downloadPath;

                IRestResponse response = client.Execute(request);

                return(response);
            }, BackgroundProgressor.None);

            // delect temporary files
            foreach (OperationRaster item in _operationRasters)
            {
                if (File.Exists(item.Raster_Path))
                {
                    string   filesToDelete = Path.GetFileNameWithoutExtension(item.Raster_Path) + ".*";
                    string[] fileList      = Directory.GetFiles(default_path, filesToDelete);
                    foreach (string file in fileList)
                    {
                        File.Delete(file);
                    }
                }
            }

            if (File.Exists(outputVarietyRasterPath))
            {
                string   filesToDelete = Path.GetFileNameWithoutExtension(outputVarietyRasterPath) + ".*";
                string[] fileList      = Directory.GetFiles(default_path, filesToDelete);
                foreach (string file in fileList)
                {
                    File.Delete(file);
                }
            }

            if (File.Exists(outputVarietyTablePath))
            {
                string   filesToDelete = Path.GetFileNameWithoutExtension(outputVarietyTablePath) + ".*";
                string[] fileList      = Directory.GetFiles(default_path, filesToDelete);
                foreach (string file in fileList)
                {
                    File.Delete(file);
                }
            }

            if (!apiResponse.IsSuccessful)
            {
                //ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show(response.ErrorMessage);
                //ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("Failed Result. Please try again");
                ResultErrorMessage += "Response Error\n";
                ResultErrorMessage += apiResponse.ErrorMessage;

                return;
            }

            string content             = apiResponse.Content;
            string unescapedJsonString = JsonConvert.DeserializeObject <dynamic>(content);

            dynamic jsonData = JsonConvert.DeserializeObject <dynamic>(unescapedJsonString);

            ProgressMessage = "Downloading file...";
            try
            {
                string filename = jsonData.file;
                await ExportFile(_downloadPath, filename);
            }
            catch (Exception e)
            {
                if (jsonData.GetType().GetProperty("msg") == null)
                {
                    //ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("No Result");
                    ResultErrorMessage += "Download Error\n";
                    ResultErrorMessage += e.Message;
                    DisplayFailed(started_datetime);
                    return;
                }
                else
                {
                    //ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show(jsonData.msg);
                    ResultErrorMessage += "Download Error\n";
                    ResultErrorMessage += jsonData.msg;
                    DisplayFailed(started_datetime);
                    return;
                }
            }

            ProgressVisible = "Hidden";
            DateTime ended_datetime = DateTime.Now;

            CompletedTime = ended_datetime.ToString();
            int seconds = (int)(ended_datetime.Subtract(started_datetime).TotalSeconds);

            ElapsedTime = seconds.ToString() + "  Seconds";

            ResultBoxBGColor    = "#3a593a";
            ResultBoxImage      = "pack://application:,,,/ArcGIS.Desktop.Resources;component/Images/DataReviewerLifecycleVerified32.png";
            ResultBoxMessage    = "Completed";
            ResultErrorMessage  = "There are no errors or warnings.";
            ResultBoxVisible    = "Visible";
            SubmitButtonEnabled = true;
        }
Esempio n. 24
0
        public async void CodeExamples()
        {
            #region How to execute a Model tool
            // get the model tool's parameter syntax from the model's help
            string input_roads      = @"C:\data\Input.gdb\PlanA_Roads";
            string buff_dist_field  = "Distance"; // use values from a field
            string input_vegetation = @"C:\data\Input.gdb\vegtype";
            string output_data      = @"C:\data\Output.gdb\ClippedFC2";

            // the model name is ExtractVegetation
            string tool_path = @"C:\data\MB\Models.tbx\ExtractVegetation";

            var args = Geoprocessing.MakeValueArray(input_roads, buff_dist_field, input_vegetation, output_data);

            var result = Geoprocessing.ExecuteToolAsync(tool_path, args);
            #endregion


            #region Set Geoprocessing extent environment

            var parameters = Geoprocessing.MakeValueArray(@"C:\data\data.gdb\HighwaysUTM11", @"C:\data\data.gdb\Highways_extent");
            var ext        = Geoprocessing.MakeEnvironmentArray(extent: "460532 3773964 525111 3827494");
            var gp_result  = await Geoprocessing.ExecuteToolAsync("management.CopyFeatures", parameters, ext);

            #endregion


            #region Open a script tool dialog in Geoprocessing pane
            string input_data = @"C:\data\data.gdb\Population";
            string out_pdf    = @"C:\temp\Reports.pdf";
            string field_name = "INCOME";
            // use defaults for other parameters - no need to pass any value
            var arguments = Geoprocessing.MakeValueArray(input_data, out_pdf, field_name);

            string toolpath = @"C:\data\WorkflowTools.tbx\MakeHistogram";

            Geoprocessing.OpenToolDialog(toolpath, args);
            #endregion


            #region Get Geoprocessing project items
            var gpItems = CoreModule.CurrentProject.Items.OfType <GeoprocessingProjectItem>();

            // go through all the available toolboxes
            foreach (var gpItem in gpItems)
            {
                var itemsInsideToolBox = gpItem.GetItems();

                // then for each toolbox list the tools inside
                foreach (var toolItem in itemsInsideToolBox)
                {
                    string newTool = String.Join(";", new string[] { toolItem.Path, toolItem.Name });
                    // do something with the newTool
                    // for example, add to a list to track or use them later
                }
            }
            #endregion

            #region Stop a featureclass created with GP from automatically adding to the map
            var GPresult = Geoprocessing.ExecuteToolAsync(tool_path, args, null, null, null, GPExecuteToolFlags.None);
            #endregion
        }
        internal async void SelectByLocation()
        {
            var mapView = MapView.Active;

            Layer towers = null;
            Layer roads = null;
            foreach (var layer in mapView.Map.Layers)
            {
                if (layer.Name == "Acme Transmission Structures")
                    towers = layer;
                if (layer.Name == "Acme Service Roads")
                    roads = layer;

                if (towers != null && roads != null)
                    break;
            }

            if (towers == null || roads == null)
            {
                MessageBox.Show("Could not find one or more input layers.");
                return;
            }

            // Show a progress dialog while GP operation is going
            var progressDialog = new ProgressDialog("Selecting structures > 50 meters from route.");
            progressDialog.Show();

            _featureLayer = towers as FeatureLayer;

            var list = new List<FeatureRepresentation>();

            //await QueuedTask.Run(() =>
            //{

            //var values = ArcGIS.Desktop.Core.Geoprocessing.Geoprocessing.MakeValueArray(towers, "WITHIN_A_DISTANCE", roads, 50, "NEW_SELECTION", "INVERT");
            string[] values = { "Acme Transmission Structures", "WITHIN_A_DISTANCE", "Acme Service Roads", "50", "NEW_SELECTION", "INVERT" };
            await Geoprocessing.ExecuteToolAsync("SelectLayerByLocation_management", values);

            await QueuedTask.Run(() =>
            {

                FeatureClass featureClass = _featureLayer.GetFeatureClass();

                IReadOnlyList<Field> fields = featureClass.GetDefinition().GetFields();
                if (fields == null)
                    return;

                // mapView.ZoomToSelected();

                var selectedFeatures = mapView.Map.GetSelection();

                var inspector = new Inspector();

                foreach (var kvEntry in selectedFeatures.ToDictionary())
                {
                    foreach (var id in kvEntry.Value)
                    {
                        var featureRep = new FeatureRepresentation { Id = id };

                        inspector.Load(kvEntry.Key, id);
                        var attr = inspector["Linename"];
                        if (attr != null)
                            featureRep.Value = attr.ToString();

                        list.Add(featureRep);
                    }
                }
            });

            // Back on UI thread
            foreach (var featureRep in list)
            {
                _features.Add(featureRep);
            }

            progressDialog.Hide();
        }
Esempio n. 26
0
        public static async Task CreateKeyPoints(string maskName, string unionMaskName, string keyPointName, double factor)
        {
            await QueuedTask.Run(() =>
            {
                StreamReader sr = new StreamReader(System.Environment.CurrentDirectory + ConstDefintion.ConstPath_TimeFilterConfig, Encoding.Default);
                String line;
                //读取状态
                line = sr.ReadLine();
                string filterStatus = line;
                line            = sr.ReadLine();
                int filterValue = Convert.ToInt32(line);
                sr.Close();
                using (Geodatabase gdb = new Geodatabase(new FileGeodatabaseConnectionPath(new Uri(GeoDataTool.DefaultProject.DefaultGeodatabasePath))))
                {
                    gdb.ApplyEdits(() =>
                    {
                        //置空原船舶领域图层
                        FeatureClass fc_targetShip = gdb.OpenDataset <FeatureClass>(ConstDefintion.ConstFeatureClass_TargetShip);
                        FeatureClass voyageMask    = gdb.OpenDataset <FeatureClass>(maskName);
                        FeatureClassDefinition voyageMaskDefinition = gdb.GetDefinition <FeatureClassDefinition>(maskName);
                        FeatureClass fc_ownShip             = gdb.OpenDataset <FeatureClass>(ConstDefintion.ConstFeatureClass_OwnShip);
                        FeatureClass TargetShipObstacleLine = gdb.OpenDataset <FeatureClass>(ConstDefintion.ConstFeatureClass_TargetShipObstacleLine);
                        TargetShipObstacleLine.DeleteRows(new QueryFilter()
                        {
                            WhereClause = "OBJECTID >= 1"
                        });
                        double own_x;
                        double own_y;
                        double own_cog;
                        using (RowCursor rowCursor = fc_ownShip.Search(null, false))
                        {
                            rowCursor.MoveNext();
                            using (Feature row = rowCursor.Current as Feature)
                            {
                                own_x   = (row.GetShape() as MapPoint).X;
                                own_y   = (row.GetShape() as MapPoint).Y;
                                own_cog = Convert.ToDouble(row[ConstDefintion.ConstFieldName_cog]);
                            }
                        }

                        voyageMask.DeleteRows(new QueryFilter()
                        {
                            WhereClause = "OBJECTID >= 1"
                        });
                        using (RowCursor rowCursor = fc_targetShip.Search(null, false))
                        {
                            while (rowCursor.MoveNext())
                            {
                                using (Row row = rowCursor.Current)
                                {
                                    Feature ship         = row as Feature;
                                    MapPoint p_ship      = ship.GetShape() as MapPoint;
                                    double CollisionRisk = Convert.ToDouble(ship[ConstDefintion.ConstFieldName_CollisionRisk]);
                                    double asemi         = Convert.ToDouble(ship[ConstDefintion.ConstFieldName_asemi]) * factor * 0.78;
                                    double bsemi         = Convert.ToDouble(ship[ConstDefintion.ConstFieldName_bsemi]) * factor * 0.78;
                                    double aoffset       = Convert.ToDouble(ship[ConstDefintion.ConstFieldName_aoffset]) * factor;
                                    double boffset       = Convert.ToDouble(ship[ConstDefintion.ConstFieldName_boffset]) * factor;
                                    double cog           = Convert.ToDouble(ship[ConstDefintion.ConstFieldName_cog]);
                                    double sog           = Convert.ToDouble(ship[ConstDefintion.ConstFieldName_sog]);
                                    double tdv1          = Convert.ToDouble(ship[ConstDefintion.ConstFieldName_tdv1]);
                                    double tdv2          = Convert.ToDouble(ship[ConstDefintion.ConstFieldName_tdv2]);
                                    double ddv           = Convert.ToDouble(ship[ConstDefintion.ConstFieldName_ddv]);
                                    double tcr           = Convert.ToDouble(ship[ConstDefintion.ConstFieldName_tcr]);
                                    double tmin          = Convert.ToDouble(ship[ConstDefintion.ConstFieldName_tmin]);
                                    long objectID        = Convert.ToInt64(ship[voyageMaskDefinition.GetObjectIDField()]);
                                    cog = CommonMethod.GIScoord2ShipCoord(cog);
                                    Coordinate2D ellipseCenter = new Coordinate2D()
                                    {
                                        X = p_ship.X,
                                        Y = p_ship.Y
                                    };
                                    if (!(CollisionRisk > 0))
                                    {
                                        continue;
                                    }
                                    //根据时间过滤器
                                    if (filterStatus != ConstDefintion.ConstStr_TimeFilterStatusOFF)
                                    {
                                        int time = filterValue * 60;
                                        if (tdv1 > time)
                                        {
                                            continue;
                                        }
                                        else
                                        {
                                            if (tdv2 > time)
                                            {
                                                tdv2 = time;
                                            }
                                        }
                                    }
                                    //if (CommonMethod.JungeLeft(own_x - ellipseCenter.X, own_y - ellipseCenter.Y, own_cog) && CollisionRisk != 1) continue;
                                    GeodesicEllipseParameter geodesic = new GeodesicEllipseParameter()
                                    {
                                        Center          = ellipseCenter,
                                        SemiAxis1Length = asemi,
                                        SemiAxis2Length = bsemi,
                                        LinearUnit      = LinearUnit.Meters,
                                        OutGeometryType = GeometryType.Polygon,
                                        AxisDirection   = AngularUnit.Degrees.ConvertToRadians(cog),
                                        VertexCount     = 800
                                    };
                                    //创建原始位置的椭圆
                                    Geometry ellipse          = GeometryEngine.Instance.GeodesicEllipse(geodesic, SpatialReferenceBuilder.CreateSpatialReference(3857));
                                    double moveX              = (aoffset *Math.Cos(AngularUnit.Degrees.ConvertToRadians(cog))) + boffset *Math.Sin(AngularUnit.Degrees.ConvertToRadians(cog));
                                    double moveY              = (aoffset *Math.Sin(AngularUnit.Degrees.ConvertToRadians(cog))) - boffset *Math.Cos(AngularUnit.Degrees.ConvertToRadians(cog));
                                    Geometry moved_ellipse    = GeometryEngine.Instance.Move(ellipse, moveX, moveY);
                                    Coordinate2D centerRevise = new Coordinate2D()
                                    {
                                        X = p_ship.X + moveX,
                                        Y = p_ship.Y + moveY
                                    };
                                    //基于TDV创建船舶领域与动界
                                    double moveXs = (tdv1 *sog *ConstDefintion.ConstDouble_mpersTOkn *Math.Cos(AngularUnit.Degrees.ConvertToRadians(cog)));
                                    double moveYs = (tdv1 *sog *ConstDefintion.ConstDouble_mpersTOkn *Math.Sin(AngularUnit.Degrees.ConvertToRadians(cog)));
                                    Geometry moved_start_ellipse = GeometryEngine.Instance.Move(moved_ellipse, moveXs, moveYs);
                                    Coordinate2D centerTs        = new Coordinate2D()
                                    {
                                        X = centerRevise.X + moveXs,
                                        Y = centerRevise.Y + moveYs
                                    };
                                    double moveXe = (tdv2 *sog *ConstDefintion.ConstDouble_mpersTOkn *Math.Cos(AngularUnit.Degrees.ConvertToRadians(cog)));
                                    double moveYe = (tdv2 *sog *ConstDefintion.ConstDouble_mpersTOkn *Math.Sin(AngularUnit.Degrees.ConvertToRadians(cog)));
                                    Geometry moved_end_ellipse = GeometryEngine.Instance.Move(moved_ellipse, moveXe, moveYe);
                                    Coordinate2D centerTe      = new Coordinate2D()
                                    {
                                        X = centerRevise.X + moveXe,
                                        Y = centerRevise.Y + moveYe
                                    };

                                    //最终图形由两个椭圆和连接椭圆的长方形组成
                                    Geometry e_s_start    = GeometryEngine.Instance.SimplifyAsFeature(moved_start_ellipse, false);
                                    Geometry e_s_end      = GeometryEngine.Instance.SimplifyAsFeature(moved_end_ellipse, false);
                                    MapPoint p_1          = MapPointBuilder.CreateMapPoint(centerTs.X - (bsemi *Math.Sin(AngularUnit.Degrees.ConvertToRadians(cog))) * 1.29, centerTs.Y + (bsemi *Math.Cos(AngularUnit.Degrees.ConvertToRadians(cog))) * 1.29);
                                    MapPoint p_2          = MapPointBuilder.CreateMapPoint(centerTs.X + (bsemi *Math.Sin(AngularUnit.Degrees.ConvertToRadians(cog))) * 1.29, centerTs.Y - (bsemi *Math.Cos(AngularUnit.Degrees.ConvertToRadians(cog))) * 1.29);
                                    MapPoint p_3          = MapPointBuilder.CreateMapPoint(centerTe.X + (bsemi *Math.Sin(AngularUnit.Degrees.ConvertToRadians(cog))) * 1.29, centerTe.Y - (bsemi *Math.Cos(AngularUnit.Degrees.ConvertToRadians(cog))) * 1.29);
                                    MapPoint p_4          = MapPointBuilder.CreateMapPoint(centerTe.X - (bsemi *Math.Sin(AngularUnit.Degrees.ConvertToRadians(cog))) * 1.29, centerTe.Y + (bsemi *Math.Cos(AngularUnit.Degrees.ConvertToRadians(cog))) * 1.29);
                                    IList <MapPoint> p1_4 = GetInternPoints(p_1, p_4);
                                    IList <MapPoint> p2_3 = GetInternPoints(p_2, p_3);
                                    p2_3 = p2_3.Reverse <MapPoint>().ToList();
                                    List <MapPoint> list2D = new List <MapPoint>();
                                    list2D.Add(p_1);
                                    foreach (MapPoint p in p1_4)
                                    {
                                        list2D.Add(p);
                                    }
                                    list2D.Add(p_4);
                                    list2D.Add(p_3);
                                    foreach (MapPoint p in p2_3)
                                    {
                                        list2D.Add(p);
                                    }
                                    list2D.Add(p_2);
                                    Polygon connect_R = PolygonBuilder.CreatePolygon(list2D, SpatialReferenceBuilder.CreateSpatialReference(3857));
                                    Geometry simple_r = GeometryEngine.Instance.SimplifyAsFeature(connect_R, false);
                                    //融合图形
                                    IList <Geometry> g_List = new List <Geometry>()
                                    {
                                        e_s_start, simple_r, e_s_end
                                    };
                                    Geometry ellInstance = GeometryEngine.Instance.Union(g_List);
                                    using (RowBuffer rowBuffer = voyageMask.CreateRowBuffer())
                                    {
                                        // Either the field index or the field name can be used in the indexer.
                                        rowBuffer[ConstDefintion.ConstFieldName_ddv]      = CollisionRisk;
                                        rowBuffer[ConstDefintion.ConstFieldName_tdv1]     = tdv1;
                                        rowBuffer[ConstDefintion.ConstFieldName_tdv2]     = tdv2;
                                        rowBuffer[ConstDefintion.ConstFieldName_asemi]    = asemi;
                                        rowBuffer[ConstDefintion.ConstFieldName_bsemi]    = bsemi;
                                        rowBuffer[ConstDefintion.ConstFieldName_cog]      = cog;
                                        rowBuffer[ConstDefintion.ConstFieldName_sog]      = sog;
                                        rowBuffer[ConstDefintion.ConstFieldName_centerX1] = centerTs.X;
                                        rowBuffer[ConstDefintion.ConstFieldName_centerY1] = centerTs.Y;
                                        rowBuffer[ConstDefintion.ConstFieldName_centerX2] = centerTe.X;
                                        rowBuffer[ConstDefintion.ConstFieldName_centerY2] = centerTe.Y;
                                        rowBuffer[voyageMaskDefinition.GetShapeField()]   = ellInstance;

                                        using (Feature feature = voyageMask.CreateRow(rowBuffer))
                                        {
                                            feature.Store();
                                        }
                                    }
                                    //创建本船与他船的冲突路径
                                    Coordinate2D ts_location = ellipseCenter;
                                    Coordinate2D ts_Ts       = new Coordinate2D()//目标船冲突起点
                                    {
                                        X = ts_location.X + moveXs,
                                        Y = ts_location.Y + moveYs
                                    };
                                    Coordinate2D ts_Te = new Coordinate2D()//目标船冲突终点
                                    {
                                        X = ts_location.X + moveXe,
                                        Y = ts_location.Y + moveYe
                                    };
                                    List <Coordinate2D> ts_obstaclePointList = new List <Coordinate2D>()
                                    {
                                        ts_Ts, ts_Te
                                    };
                                    Polyline ts_obstacleLine = PolylineBuilder.CreatePolyline(ts_obstaclePointList, SpatialReferenceBuilder.CreateSpatialReference(3857));
                                    double kj_risk           = 0;
                                    if (ddv > 1)
                                    {
                                        kj_risk = 0;
                                    }
                                    else if (ddv < 0.5)
                                    {
                                        kj_risk = 1;
                                    }
                                    else
                                    {
                                        kj_risk = Math.Pow(2 - 2 * ddv, 3.03);
                                    }
                                    using (RowBuffer rowBuffer = TargetShipObstacleLine.CreateRowBuffer())
                                    {
                                        // Either the field index or the field name can be used in the indexer.
                                        rowBuffer[ConstDefintion.ConstFieldName_dcr]   = kj_risk;
                                        rowBuffer[ConstDefintion.ConstFieldName_tcr]   = tcr;
                                        rowBuffer[ConstDefintion.ConstFieldName_risk]  = CollisionRisk;
                                        rowBuffer[ConstDefintion.ConstFieldName_tdv1]  = tdv1;
                                        rowBuffer[ConstDefintion.ConstFieldName_tdv2]  = tdv2;
                                        rowBuffer[ConstDefintion.ConstFieldName_tmin]  = tmin;
                                        rowBuffer[ConstDefintion.ConstFieldName_Shape] = ts_obstacleLine;

                                        using (Feature feature = TargetShipObstacleLine.CreateRow(rowBuffer))
                                        {
                                            feature.Store();
                                        }
                                    }
                                }
                            }
                        }
                    });
                }
            });

            //创建航行位置Mask

            await QueuedTask.Run(async() =>
            {
                //Mask边缘
                //合并要素
                using (Geodatabase gdb = new Geodatabase(new FileGeodatabaseConnectionPath(new Uri(GeoDataTool.DefaultProject.DefaultGeodatabasePath))))
                {
                    gdb.ApplyEdits(() =>
                    {
                        using (FeatureClass u_VoyageMask = gdb.OpenDataset <FeatureClass>(unionMaskName))
                        {
                            u_VoyageMask.DeleteRows(new QueryFilter()
                            {
                                WhereClause = "OBJECTID >= 1"
                            });
                            using (FeatureClass voyageMask = gdb.OpenDataset <FeatureClass>(maskName))
                            {
                                IList <Geometry> u_list = new List <Geometry>();
                                FeatureClassDefinition u_voyageMaskDefinition = gdb.GetDefinition <FeatureClassDefinition>(unionMaskName);
                                using (RowCursor rowCursor = voyageMask.Search(null, false))
                                {
                                    while (rowCursor.MoveNext())
                                    {
                                        using (Feature f = rowCursor.Current as Feature)
                                        {
                                            u_list.Add(f.GetShape());
                                        }
                                    }
                                    //赋值
                                    using (RowBuffer rowBuffer = u_VoyageMask.CreateRowBuffer())
                                    {
                                        Geometry geometry = GeometryEngine.Instance.Union(u_list);
                                        rowBuffer[u_voyageMaskDefinition.GetShapeField()] = geometry;
                                        using (Feature feature = u_VoyageMask.CreateRow(rowBuffer))
                                        {
                                            feature.Store();
                                        }
                                    }
                                }
                            }
                        }
                    });
                }
                //运行要素边缘转点
                string inpath = GeoDataTool.DefaultProject.DefaultGeodatabasePath + "\\" + keyPointName;
                var args      = Geoprocessing.MakeValueArray(inpath);
                var result    = await Geoprocessing.ExecuteToolAsync("Delete_management", args, null, null, null);

                string inpath1 = GeoDataTool.DefaultProject.DefaultGeodatabasePath + "\\" + unionMaskName;
                string outpath = GeoDataTool.DefaultProject.DefaultGeodatabasePath + "\\" + keyPointName;
                var args1      = Geoprocessing.MakeValueArray(inpath1, outpath, "ALL");
                var result1    = await Geoprocessing.ExecuteToolAsync("FeatureVerticesToPoints_management", args1, null, null, null);
            });
        }
        private static async Task CreateFeatureClass(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,  //POINT,POLYLINE,POLYGON...
                // no template
                "",
                // no z values
                "DISABLED",
                // no m values
                "DISABLED"
            };

            await QueuedTask.Run(() =>
            {
                // spatial reference
                arguments.Add(SpatialReferenceBuilder.CreateSpatialReference(4326)); //3857
            });

            IGPResult result = await Geoprocessing.ExecuteToolAsync("CreateFeatureclass_management", Geoprocessing.MakeValueArray(arguments.ToArray()));
        }
Esempio n. 28
0
        public async static Task <BasicFeatureLayer> CreateFeatureClass(string name)
        {
            var existingLayer = MapView.Active.Map.FindLayers(name).FirstOrDefault();

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

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

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

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

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

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

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

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

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

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

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

            return(layer);
        }
        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  += currentVolume;
                            totalAreaValue    += currentSArea;
                            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;
            }
        }
Esempio n. 30
0
 //Option 3 - open the Geoprocessing tool parameter dialog and interactively execute the tool
 internal virtual void ExecuteToolOpenToolDialog(string toolPath, string[] values)
 {
     Geoprocessing.OpenToolDialog(toolPath, values, _env.ToArray(), false, null);
 }