private static void ResetLabels()
        {
            QueuedTask.Run(async() =>
            {
                //Get the line feature we want to clear labels for
                var featureLayer = MapView.Active.Map.GetLayersAsFlattenedList().Where(f => f.Name == "U.S. Rivers (Generalized)").FirstOrDefault() as FeatureLayer;
                if (featureLayer == null)
                {
                    return;
                }

                // create an instance of the inspector class
                var inspector = new ArcGIS.Desktop.Editing.Attributes.Inspector();

                //Clear the previous "Yes" values for the LabelOn field.
                //Create a QueryFilter to search for all features that have the LabelOn field value set at Yes.
                var qf = new QueryFilter
                {
                    WhereClause = "LabelOn = 'Yes'"
                };
                var selectionLabelOnYes = featureLayer.Select(qf);
                var featuresToClear     = selectionLabelOnYes.GetObjectIDs()?.ToList();
                if (featuresToClear.Count > 0)
                {
                    // load the features into the inspector using a list of object IDs
                    await inspector.LoadAsync(featureLayer, featuresToClear);

                    // assign the attribute value of "No" to the field "LabelOn"
                    // if more than one features are loaded, the change applies to all features
                    inspector["LabelOn"] = "No";
                    // apply the changes as an edit operation
                    await inspector.ApplyAsync();
                }
            });
        }
        /// <summary>
        /// Update the field with a given value (int)
        /// </summary>
        /// <param name="status"></param>
        /// <param name="editName"></param>
        public void Update(int status, string editName)
        {
            QueuedTask.Run(() => {
                try
                {
                    var basicfeaturelayer = _selectedLayer as BasicFeatureLayer;
                    var selection         = basicfeaturelayer.GetSelection();
                    var oidset            = selection.GetObjectIDs();

                    var insp = new ArcGIS.Desktop.Editing.Attributes.Inspector();
                    insp.Load(basicfeaturelayer, oidset);
                    insp[InpsectorFieldName] = 1;

                    var op  = new EditOperation();
                    op.Name = editName;
                    op.Modify(insp);
                    op.Execute();

                    basicfeaturelayer.ClearSelection();
                } catch (Exception ex)
                {
                    MessageBox.Show("Error: " + ex.Message);
                }
            });
        }
        /// <summary>
        /// Called when the sketch finishes. This is where we will create the sketch operation and then execute it.
        /// </summary>
        /// <param name="geometry">The geometry created by the sketch.</param>
        /// <returns>A Task returning a Boolean indicating if the sketch complete event was successfully handled.</returns>
        protected async override Task <bool> OnSketchCompleteAsync(Geometry geometry)
        {
            if (CurrentTemplate == null || geometry == null)
            {
                //return Task.FromResult(false);
                return(false);
            }

            await QueuedTask.Run(async() =>
            {
                // Create an EditOperation and make updates using Inspector
                var createOperation  = new EditOperation();
                createOperation.Name = string.Format("Create {0}", CurrentTemplate.Layer.Name);
                createOperation.SelectNewFeatures = true;
                createOperation.Create(CurrentTemplate, geometry);
                await createOperation.ExecuteAsync();
                var selectedFeatures = ArcGIS.Desktop.Mapping.MapView.Active.Map.GetSelection();
                var inspector        = new ArcGIS.Desktop.Editing.Attributes.Inspector();
                inspector.Load(selectedFeatures.ToDictionary().Keys.First(), selectedFeatures.ToDictionary().Values.First());
                var squarefeetValue = inspector["Shape_Area"];
                long squarefeetValueLong;
                squarefeetValueLong        = Convert.ToInt64(squarefeetValue);
                inspector["High"]          = (squarefeetValueLong / _dockpane.HighSetting);
                inspector["Medium"]        = (squarefeetValueLong / _dockpane.MediumSetting);
                inspector["Low"]           = (squarefeetValueLong / _dockpane.LowSetting);
                inspector["HighSetting"]   = _dockpane.HighSetting;
                inspector["MediumSetting"] = _dockpane.MediumSetting;
                inspector["LowSetting"]    = _dockpane.LowSetting;
                inspector["TargetSetting"] = _dockpane.TargetSetting;
                await inspector.ApplyAsync();
                _dockpane.GetTotalValues();
            });

            return(true);
        }
        public void saveDetails(object sender, EventArgs args)
        {
            string rtfValue = this.rtfBox.Rtf;

            ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
            {
                var disLayer = getLayer();
                var oidSet   = new List <long>();
                using (var rc = this.createRow())
                {
                    //Create list of oids to update
                    while (rc.MoveNext())
                    {
                        oidSet.Add(rc.Current.GetObjectID());
                    }
                }

                //Create edit operation
                var op  = new ArcGIS.Desktop.Editing.EditOperation();
                op.Name = "Update date";

                // load features into inspector and update field
                var insp = new ArcGIS.Desktop.Editing.Attributes.Inspector();
                insp.Load(disLayer, oidSet);
                insp[config.getConfig("Wydzielenia", "precintDetails")] = rtfValue;

                // modify and execute
                op.Modify(insp);
                op.Execute();
            });
        }
        // when the selection changes, obtain the first feature's geometry and assign to the GeometryControl
        private async void OnSelectionChanged(ArcGIS.Desktop.Mapping.Events.MapSelectionChangedEventArgs args)
        {
            if (args == null)
            {
                return;
            }

            var sel = args.Selection;

            // get the first BasicFeatureLayer
            var member = sel.Keys.FirstOrDefault(mm => mm is BasicFeatureLayer);

            if (member == null)
            {
                Clear();
                return;
            }

            // get the first oid
            var oids = sel[member];
            var oid  = oids[0];

            // get the geometry of that feature
            var geom = await QueuedTask.Run(() =>
            {
                var insp = new ArcGIS.Desktop.Editing.Attributes.Inspector();
                insp.Load(member, oid);
                return(insp.Shape);
            });

            // bind to the view
            Geometry = geom;
        }
        /// <summary>
        /// Applys the domain code to the currenly selected feature
        /// </summary>
        /// <param name="code"></param>
        internal async void ApplyDomain(DomainCode code)
        {
            if (await CheckRequirements())
            {
                await QueuedTask.Run(() =>
                {
                    try
                    {
                        Selection selection = _selectedLayer.GetSelection();
                        var oidset          = selection.GetObjectIDs();

                        var insp = new ArcGIS.Desktop.Editing.Attributes.Inspector();
                        insp.Load(_selectedLayer, oidset);
                        insp[_selectedField] = (int)code;

                        var op  = new EditOperation();
                        op.Name = "Set Domain to " + ((int)code).ToString();
                        op.Modify(insp);
                        op.Execute();
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("Error: " + ex.Message);
                    }
                });
            }
        }
Exemplo n.º 7
0
 private void Button_Click(object sender, RoutedEventArgs e)
 {
     Task t = QueuedTask.Run(() =>
     {
         try
         {
             var selectedFeatures  = ArcGIS.Desktop.Mapping.MapView.Active.Map.GetSelection();
             var firstSelectionSet = selectedFeatures.First();
             var inspector         = new ArcGIS.Desktop.Editing.Attributes.Inspector();
             inspector.Load(firstSelectionSet.Key, firstSelectionSet.Value);
             var currentResourceID = inspector["resourceinstanceid"];
             ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("The ResourceID of the selected feature is " + currentResourceID);
         }
         catch {
             ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("Make sure you selected only one feature!");
         }
     });
 }
        /// <summary>
        /// Called when the sketch finishes. This is where we will create the sketch operation and then execute it.
        /// </summary>
        /// <param name="geometry">The geometry created by the sketch.</param>
        /// <returns>A Task returning a Boolean indicating if the sketch complete event was successfully handled.</returns>
        protected async override Task <bool> OnSketchCompleteAsync(Geometry geometry)
        {
            if (CurrentTemplate == null || geometry == null)
            {
                //return Task.FromResult(false);
                return(false);
            }

            await QueuedTask.Run(async() =>
            {
                // Create an edit operation
                var createOperation  = new EditOperation();
                createOperation.Name = string.Format("Create {0}", CurrentTemplate.Layer.Name);
                createOperation.SelectNewFeatures = true;
                createOperation.Create(CurrentTemplate, geometry);
                await createOperation.ExecuteAsync();
                var selectedFeatures = ArcGIS.Desktop.Mapping.MapView.Active.Map.GetSelection();
                // get the first layer and its corresponding selected feature OIDs
                var firstSelectionSet = selectedFeatures.First();
                // create an instance of the inspector class
                var inspector = new ArcGIS.Desktop.Editing.Attributes.Inspector();
                // load the selected features into the inspector using a list of object IDs
                inspector.Load(firstSelectionSet.Key, firstSelectionSet.Value);
                var squarefeetValue = inspector["Shape_Area"];
                long squarefeetValueLong;
                squarefeetValueLong        = Convert.ToInt64(squarefeetValue);
                inspector["High"]          = (squarefeetValueLong / _dockpane.HighSetting);
                inspector["Medium"]        = (squarefeetValueLong / _dockpane.MediumSetting);
                inspector["Low"]           = (squarefeetValueLong / _dockpane.LowSetting);
                inspector["HighSetting"]   = _dockpane.HighSetting;
                inspector["MediumSetting"] = _dockpane.MediumSetting;
                inspector["LowSetting"]    = _dockpane.LowSetting;
                inspector["TargetSetting"] = _dockpane.TargetSetting;
                await inspector.ApplyAsync();
                _dockpane.GetTotalValues();
            });

            return(true);
        }
Exemplo n.º 9
0
        protected override Task HandleMouseDownAsync(MapViewMouseButtonEventArgs e)
        {
            return(QueuedTask.Run(() =>
            {
                var mapClickPnt = MapView.Active.ClientToMap(e.ClientPoint);
                double elevation = mapClickPnt.Z;

                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)
                {
                    MessageBox.Show("No features selected for layer, " + featLayer.Name + ". Elevation not applied. Exiting...", "Info");
                    return;
                }

                // Edit elevation for any/all selected polygons, and reset any existing calculated Volume and SArea values to null.
                var inspector = new ArcGIS.Desktop.Editing.Attributes.Inspector(true);
                inspector.Load(featLayer, featSelectionOIDs);
                inspector["PlaneHeight"] = elevation;
                inspector["Volume"] = null;
                inspector["SArea"] = null;
                inspector["EstWeightInTons"] = null;
                var editOp = new EditOperation
                {
                    Name = $@"Edit {featLayer.Name}, {featSelectionOIDs.Count} records."
                };
                editOp.Modify(inspector);
                editOp.ExecuteAsync();
                Project.Current.SaveEditsAsync();

                Module1.SceneCalcVM.ReferencePlaneElevation = elevation;
                // Refresh the selection
                Module1.Current.FeatureSelectionChanged();
            }));
        }
Exemplo n.º 10
0
        public async void CalculateVolume()
        {
            // Update the viewmodel with values
            await FrameworkApplication.SetCurrentToolAsync("esri_mapping_exploreTool");

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

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

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

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

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

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

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

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

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

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

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

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

                    // Get the path to the layer's feature class
                    string infc = featLayer.Name;
                    // Place parameters into an array
                    var parameters = Geoprocessing.MakeValueArray(surfaceLASDataset, infc, "PlaneHeight", refPlaneDirection);
                    // Place environment settings in an array, in this case, OK to over-write
                    var environments = Geoprocessing.MakeEnvironmentArray(overwriteoutput: true);
                    // Execute the GP tool with parameters
                    var gpResult = await Geoprocessing.ExecuteToolAsync("PolygonVolume_3d", parameters, environments);
                    // Save edits again
                    await Project.Current.SaveEditsAsync();

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

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

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

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

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

                    // Apply the values and refresh selection update
                    await Project.Current.SaveEditsAsync();
                    FeatureSelectionChanged();
                    // Close progress dialog
                    progDialog.Hide();
                    progDialog.Dispose();
                }));
            }
            catch (Exception exc)
            {
                // Catch any exception found and display a message box.
                ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("Exception caught while trying to perform update: " + exc.Message);
                return;
            }
        }
Exemplo n.º 11
0
        /// <summary>
        /// The features are labeled using a Field in the feature layer. The field LabelOn has values Yes or No.
        /// If the value is "Yes", that feature will be labeled. If value is No, the feature will not be labeled.
        /// </summary>
        /// <param name="geometry"></param>
        /// <returns></returns>
        protected override Task <bool> OnSketchCompleteAsync(Geometry geometry)
        {
            QueuedTask.Run(async() =>
            {
                //select features that intersect the sketch geometry
                var selection = MapView.Active.SelectFeatures(geometry, SelectionCombinationMethod.New);
                //Get the line feature we want to label
                var featureLayer = selection.Where(f => f.Key.Name == "U.S. Rivers (Generalized)").FirstOrDefault().Key as FeatureLayer;
                if (featureLayer == null)
                {
                    return;
                }
                //Get the list of line features that are selected
                var oidsOfSelectedFeature = selection[featureLayer];
                if (oidsOfSelectedFeature.Count == 0)
                {
                    return;
                }

                //We want to only label the selected features. So..
                //Clear the previous "Yes" values for the LabelOn field.
                //Create a QueryFilter to search for all features that have the LabelOn field value set at Yes.
                // create an instance of the inspector class
                var inspector = new ArcGIS.Desktop.Editing.Attributes.Inspector();

                var qf = new QueryFilter
                {
                    WhereClause = "LabelOn = 'Yes'"
                };
                var selectionLabelOnYes = featureLayer.Select(qf);
                var featuresToClear     = selectionLabelOnYes.GetObjectIDs()?.ToList();
                if (featuresToClear.Count > 0)
                {
                    // load the features into the inspector using a list of object IDs
                    await inspector.LoadAsync(featureLayer, featuresToClear);

                    // assign the attribute value of "No" to the field "LabelOn"
                    // if more than one features are loaded, the change applies to all features
                    inspector["LabelOn"] = "No";
                    // apply the changes as an edit operation
                    await inspector.ApplyAsync();
                }

                //Now modify the features that are selected by the tool to have the value Yes
                await inspector.LoadAsync(featureLayer, oidsOfSelectedFeature);
                // assign the attribute value of "Yes" to the field "LabelOn" for the features selected
                // if more than one features are loaded, the change applies to all features
                inspector["LabelOn"] = "Yes";
                // apply the changes as an edit operation
                await inspector.ApplyAsync();
                //Get the layer's definition
                var lyrDefn = featureLayer.GetDefinition() as CIMFeatureLayer;
                //Get the label classes - and check if the correct label class we need to label the line features with exists
                var listLabelClasses = lyrDefn.LabelClasses.ToList();
                var theLabelClass    = listLabelClasses.Where(l => l.Name == "LabelSelectedManyFeaturesWithLength").FirstOrDefault();
                if (theLabelClass == null) //create label class and add to the collection
                {
                    theLabelClass = await CreateAndApplyLabelClassAsync(featureLayer);
                    listLabelClasses.Add(theLabelClass);
                }

                //Turn off all the label classes except this one
                foreach (var lc in listLabelClasses)
                {
                    lc.Visibility = lc.Name == "LabelSelectedManyFeaturesWithLength" ? true : false;
                }
                //Apply the label classes back to the layer definition
                lyrDefn.LabelClasses = listLabelClasses.ToArray();
                //Set the layer definition
                featureLayer.SetDefinition(lyrDefn);
                //set the label's visiblity
                featureLayer.SetLabelVisibility(true);
            });
            return(base.OnSketchCompleteAsync(geometry));
        }
Exemplo n.º 12
0
        public void refreshLayers()
        {
            if (MapView.Active == null)
            {
                return;
            }

            QueuedTask.Run(() =>
            {
                //Combobox
                _allFeatureLayers = new ObservableCollection <string>();

                foreach (var f in MapView.Active.Map.GetLayersAsFlattenedList().OfType <FeatureLayer>())
                {
                    var okAdd     = true;
                    var inspector = new ArcGIS.Desktop.Editing.Attributes.Inspector(true);

                    var featSelectionOIDs = f.GetSelection().GetObjectIDs();

                    inspector.Load(f, featSelectionOIDs);

                    if (inspector.HasAttributes)
                    {
                        if (inspector.Count(a => a.FieldName.ToLower() == "type_couv1") == 0)
                        {
                            okAdd = false;
                        }
                        if (inspector.Count(a => a.FieldName.ToLower() == "type_couv2") == 0)
                        {
                            okAdd = false;
                        }
                        if (inspector.Count(a => a.FieldName.ToLower() == "part_str") == 0)
                        {
                            okAdd = false;
                        }
                        if (inspector.Count(a => a.FieldName.ToLower() == "et1_dens") == 0)
                        {
                            okAdd = false;
                        }
                        if (inspector.Count(a => a.FieldName.ToLower() == "et2_dens") == 0)
                        {
                            okAdd = false;
                        }
                        if (inspector.Count(a => a.FieldName.ToLower() == "et1_haut") == 0)
                        {
                            okAdd = false;
                        }
                        if (inspector.Count(a => a.FieldName.ToLower() == "et2_haut") == 0)
                        {
                            okAdd = false;
                        }
                        if (inspector.Count(a => a.FieldName.ToLower() == "couv_gaule") == 0)
                        {
                            okAdd = false;
                        }
                        if (inspector.Count(a => a.FieldName.ToLower() == "et_domi") == 0)
                        {
                            okAdd = false;
                        }
                        if (inspector.Count(a => a.FieldName.ToLower() == "origine") == 0)
                        {
                            okAdd = false;
                        }
                        if (inspector.Count(a => a.FieldName.ToLower() == "an_origine") == 0)
                        {
                            okAdd = false;
                        }
                        if (inspector.Count(a => a.FieldName.ToLower() == "reb_ess1") == 0)
                        {
                            okAdd = false;
                        }
                        if (inspector.Count(a => a.FieldName.ToLower() == "reb_ess2") == 0)
                        {
                            okAdd = false;
                        }
                        if (inspector.Count(a => a.FieldName.ToLower() == "reb_ess3") == 0)
                        {
                            okAdd = false;
                        }
                        if (inspector.Count(a => a.FieldName.ToLower() == "etagement") == 0)
                        {
                            okAdd = false;
                        }
                        if (inspector.Count(a => a.FieldName.ToLower() == "et1_age") == 0)
                        {
                            okAdd = false;
                        }
                        if (inspector.Count(a => a.FieldName.ToLower() == "et2_age") == 0)
                        {
                            okAdd = false;
                        }
                        if (inspector.Count(a => a.FieldName.ToLower() == "perturb") == 0)
                        {
                            okAdd = false;
                        }
                        if (inspector.Count(a => a.FieldName.ToLower() == "an_perturb") == 0)
                        {
                            okAdd = false;
                        }
                        if (inspector.Count(a => a.FieldName.ToLower() == "co_ter") == 0)
                        {
                            okAdd = false;
                        }

                        if (okAdd)
                        {
                            _allFeatureLayers.Add(f.Name);
                        }
                    }
                }

                this.AllFeatureLayers = new ReadOnlyObservableCollection <string>(_allFeatureLayers);
                NotifyPropertyChanged("AllFeatureLayers");
            });
        }
Exemplo n.º 13
0
        private void saveTableEdits()
        {
            if (MapView.Active == null)
            {
                return;
            }

            QueuedTask.Run(() =>
            {
                // Check to see if there is a selected feature layer
                var featLayer = MapView.Active.Map.GetLayersAsFlattenedList().FirstOrDefault(l => l.Name == SelectedFeatureLayer) as FeatureLayer;
                if (featLayer == null)
                {
                    return;
                }
                // Get the selected records, and check/exit if there are none:
                var featSelectionOIDs = featLayer.GetSelection().GetObjectIDs();
                if (featSelectionOIDs.Count == 0 || featSelectionOIDs.Count > 1)
                {
                    return;
                }

                try
                {
                    var inspector = new ArcGIS.Desktop.Editing.Attributes.Inspector(true);
                    inspector.Load(featLayer, featSelectionOIDs);

                    if (inspector.HasAttributes)
                    {
                        if (inspector.Count(a => a.FieldName.ToUpper() == "type_couv1") > 0)
                        {
                            inspector["type_couv1"] = _dataNaipf2019.TxtTbType1;
                        }

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

                        //MessageBox.Show("Update operation completed.", "Editing with Inspector");
                    }
                    else
                    {
                        //MessageBox.Show("The Attribute provided is not valid. " +
                        //    "\r\n Ensure your attribute name is correct.", "Invalid attribute");
                        // return;
                    }
                }
                catch (Exception exc)
                {
                    // Catch any exception found and display a message box.
                    MessageBox.Show("Exception caught: " + exc.Message);
                    return;
                }
                finally
                {
                    if (Project.Current.HasEdits)
                    {
                        Project.Current.SaveEditsAsync();
                    }
                }
            });
        }
Exemplo n.º 14
0
        public async void UpdateValues()
        {
            //  This sample is intended for use with a featureclass with a default text field named "Description".
            //  You can replace "Description" with any field name that works for your dataset

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

            await QueuedTask.Run(async() =>
            {
                string nhdlayername = "NHDFlowline";
                string nhd_nd_name  = "NHDFlowline_ND";

                var featLayer = MapView.Active.Map.FindLayers(nhdlayername).First() as FeatureLayer;

                if (featLayer == null)
                {
                    MessageBox.Show("NHD Flowline layer not added to the Map. Exiting...", "Info");
                    return;
                }
                // Get the selected records, and check/exit if there are none:
                var featSelectionOIDs = featLayer.GetSelection().GetObjectIDs();
                if (featSelectionOIDs.Count == 0)
                {
                    MessageBox.Show("No records are selected for " + featLayer.Name + ". Exiting...", "Info");
                    return;
                }

                string strvalue = String.IsNullOrEmpty(Module1.Current.StreamVelValue.Text) ? "0.5" : Module1.Current.StreamVelValue.Text;
                double setvalue = double.Parse(strvalue);

                try
                {
                    // Now ready to do the actual editing:
                    // 1. Create a new edit operation and a new inspector for working with the attributes
                    // 2. Check to see if a valid field name was chosen for the feature layer
                    // 3. If so, apply the edit

                    //
                    var inspector = new ArcGIS.Desktop.Editing.Attributes.Inspector(true);
                    inspector.Load(featLayer, featSelectionOIDs);
                    //if (inspector.HasAttributes && inspector.Count(a => a.FieldName.ToUpper() == attributename.ToUpper()) > 0)
                    if (inspector.HasAttributes)
                    {
                        inspector["InNetwork"]     = 1;
                        inspector["FlowDir"]       = 1;
                        inspector["VelProvenance"] = "Manual Edit";
                        inspector["OneWay"]        = "FT";
                        inspector["CalculatedVel"] = setvalue * 3.2808; //fps
                        inspector["Stream_Vel"]    = setvalue;          //m/s
                        inspector["TravelTime"]    = 0.05;

                        var editOp  = new EditOperation();
                        editOp.Name = "Edit " + featLayer.Name + ", " + Convert.ToString(featSelectionOIDs.Count) + " records.";
                        editOp.Modify(inspector);
                        //editOp.ExecuteAsync();
                        if (editOp.IsEmpty)
                        {
                            editOp.Abort();
                        }
                        else
                        {
                            await editOp.ExecuteAsync();
                            //MessageBox.Show("Update operation completed.", "Editing with Inspector");

                            //Caliculate TtavelTime based on input stream velocity
                            var param_values1 = Geoprocessing.MakeValueArray(featLayer, "TravelTime", "!LengthKM! / (!CalculatedVel!*0.0003048*60)");
                            var gp_result1    = await Geoprocessing.ExecuteToolAsync("management.CalculateField", param_values1, null, null, null, GPExecuteToolFlags.AddToHistory);

                            string in_features = featLayer.GetPath().LocalPath.Replace(nhdlayername, nhd_nd_name);
                            var param_values   = Geoprocessing.MakeValueArray(in_features);
                            var gp_result      = await Geoprocessing.ExecuteToolAsync("na.BuildNetwork", param_values, null, null, null, GPExecuteToolFlags.AddToHistory);

                            if (!gp_result.IsFailed)
                            {
                                if (Project.Current.HasEdits)
                                {
                                    await Project.Current.SaveEditsAsync();

                                    //To Refresh the map
                                    MapView.Active.Redraw(true);
                                    // Display all the parameters for the update:
                                    MessageBox.Show("Here are update parameters details:  " +
                                                    "\r\n Layer: " + featLayer.Name +
                                                    "\r\n Number of records: " + Convert.ToString(featSelectionOIDs.Count) +
                                                    "\r\n\t InNetwork : 'Yes' " +
                                                    "\r\n\t FlowDir : 'WithDigitization' " +
                                                    "\r\n\t VelProvenance : 'Manual Edit' " +
                                                    "\r\n\t OneWay : 'FT' " +
                                                    "\r\n\t CalculatedVel : " + Convert.ToString(setvalue * 3.2808) + " fps" +
                                                    "\r\n\t Stream_Vel : " + Convert.ToString(setvalue) + " m/s" +
                                                    "\r\n\t TravelTime : Calculated value of length, Velocity"
                                                    );
                                }
                            }
                            //Geoprocessing.ShowMessageBox(gp_result.Messages, "Contents", GPMessageBoxStyle.Default, "Window Title");
                        }
                    }
                    else
                    {
                        MessageBox.Show("The Attribute provided is not valid. " +
                                        "\r\n Ensure your attribute name is correct.", "Invalid attribute");
                        // return;
                    }
                }
                catch (Exception exc)
                {
                    // Catch any exception found and display a message box.
                    MessageBox.Show("Exception caught while trying to perform update: " + exc.Message);
                    return;
                }
            });
        }