protected override Task<bool> OnSketchCompleteAsync(ArcGIS.Core.Geometry.Geometry geometry)
        {
            //Check we only have one feature to extend to
            if (MapView.Active.Map.SelectionCount != 1)
            {
                MessageBox.Show("Please select one polyline or polygon feature to extend to", "Extend");
                return Task.FromResult(true);
            }

            //Run on MCT
            return QueuedTask.Run(() =>
            {
                //get selected feature geometry
                var selectedFeatures = MapView.Active.Map.GetSelection();
                var insp = new Inspector();
                insp.Load(selectedFeatures.Keys.First(), selectedFeatures.Values.First());
                var selGeom = insp.Shape;
                if (!(selGeom.GeometryType == GeometryType.Polygon
                    || selGeom.GeometryType == GeometryType.Polyline))
                {
                    MessageBox.Show("Please choose as the selected feature either a polyline or polygon feature to extend to");
                    return false;
                }

                //find feature at the click
                var clickFeatures = MapView.Active.GetFeatures(geometry);
                insp.Load(clickFeatures.First().Key, clickFeatures.First().Value);
                var clickGeom = insp.Shape as Polyline;
                if (clickGeom == null)
                {
                    MessageBox.Show("Please select a polyline feature to extend");
                    return false;
                }

                //extend the line to the poly?
                ArcGIS.Core.Geometry.Polyline extPolyline;
                extPolyline = GeometryEngine.Extend(clickGeom, (selGeom.GeometryType == GeometryType.Polygon ? GeometryEngine.Boundary(selGeom) as Polyline : selGeom as Polyline), ExtendFlags.Default);
                if (extPolyline == null)
                {
                    MessageBox.Show(string.Format("Unable to extend the clicked {0} to the selected {1}",
                        clickGeom.GeometryType, selGeom.GeometryType));
                    return false;
                }

                //set the new geometry back on the feature
                insp.Shape = extPolyline;

                //create and execute the edit operation
                var op = new EditOperation();
                op.Name = "Extend";
                op.SelectModifiedFeatures = false;
                op.SelectNewFeatures = false;
                op.Modify(insp);
                return op.Execute();
            });
        }
        /// <summary>
        /// The on comboBox selection change event. 
        /// </summary>
        /// <param name="item">The newly selected combo box item</param>
        protected async override void OnSelectionChange(ComboBoxItem item)
        {

            if (item == null)
                return;

            if (string.IsNullOrEmpty(item.Text))
                return;
            string error = String.Empty;
            bool result = false;
            await QueuedTask.Run(async () =>
            {
                var layer = MapView.Active.GetSelectedLayers()[0];
                if (layer is FeatureLayer)
                {
                    var featureLayer = layer as FeatureLayer;
                    if (featureLayer.GetTable().GetDatastore() is UnknownDatastore)
                        return;
                    using (var table = featureLayer.GetTable())
                    {
                        var subtypeField = table.GetDefinition().GetSubtypeField();
                        var code = table.GetDefinition().GetSubtypes().First(subtype => subtype.GetName().Equals(item.Text)).GetCode();
                        var queryFilter = new QueryFilter{WhereClause = string.Format("{0} = {1}", subtypeField, code)};
                        try
                        {
                            using (var rowCursor = table.Search(queryFilter, false))
                            {
                                var editOperation = new EditOperation();
                                editOperation.Callback(context =>
                                {
                                    while (rowCursor.MoveNext())
                                    {
                                        using (var row = rowCursor.Current)
                                        {
                                            context.Invalidate(row);
                                            row.Delete();
                                        }
                                    }
                                }, table);
                                if (table.GetRegistrationType().Equals(RegistrationType.Nonversioned) &&
                                    Project.Current.HasEdits)
                                {
                                    error =
                                        "The FeatureClass is Non-Versioned and there are Unsaved Edits in the Project. Please save or discard the edits before attempting Non-Versioned Edits";
                                }
                                else
                                    result = await editOperation.ExecuteAsync();
                                if (!result)
                                    error = editOperation.ErrorMessage;
                            }
                        }
                        catch (Exception e)
                        {
                            error = e.Message;
                        }                        
                    }
                }
            });
            if (!result)
                MessageBox.Show(String.Format("Could not delete features for subtype {0} : {1}",
                    item.Text, error));
        }
        protected override void OnClick()
        {
            var polyLayer = MapView.Active.Map.GetLayersAsFlattenedList().OfType<FeatureLayer>().First();

            QueuedTask.Run(() =>
            {

                var fc = polyLayer.GetTable() as FeatureClass;
                var fcDefinition = fc.GetDefinition();
                Polygon outerRings = null;

                var editOperation = new EditOperation();
                editOperation.Name = "Create outer ring";

                using (var cursor = fc.Search())
                {
                    while (cursor.MoveNext())
                    {
                        Feature feature = cursor.Current as Feature;

                        outerRings = Module1.Current.GetOutermostRings(feature.GetShape() as Polygon);

                        editOperation.Create(polyLayer, outerRings);
                    }
                }

                editOperation.Execute();
            });
        }
    protected override Task<bool> OnSketchCompleteAsync(ArcGIS.Core.Geometry.Geometry geometry)
    {
      //Simple check for selected layer
      if (MapView.Active.GetSelectedLayers().Count == 0)
      {
        MessageBox.Show("Please select a layer in the toc","Update attributes with sketch");
        return Task.FromResult(true);
      }

      //Run on MCT
      return QueuedTask.Run(() =>
      {
        //Get the selected layer in toc
        var featLayer = MapView.Active.GetSelectedLayers().First() as FeatureLayer;

        //find feature oids under the sketch for the selected layer
        var features = MapView.Active.GetFeatures(geometry);
        var featOids = features[featLayer];

        //update the attributes of those features
        var insp = new Inspector();
        insp.Load(featLayer, featOids);
        insp["PARCEL_ID"] = 42;

        //create and execute the edit operation
        var op = new EditOperation();
        op.Name = "Update parcel";
        op.SelectModifiedFeatures = true;
        op.SelectNewFeatures = false;
        op.Modify(insp);
        return op.Execute();
      });
    }
    protected override Task<bool> OnSketchCompleteAsync(ArcGIS.Core.Geometry.Geometry geometry)
    {
      //Simple check for selected layer
      if (MappingModule.ActiveTOC.SelectedLayers.Count == 0)
      {
        System.Windows.MessageBox.Show("Select a layer in the toc");
        return Task.FromResult(true);
      }

      //jump to CIM thread
      return QueuedTask.Run(async () =>
      {
        //Get the selected layer in toc
        var featLayer = MappingModule.ActiveTOC.SelectedLayers[0] as FeatureLayer;

        //find feature oids under the sketch for the selected layer
        var features = await MapView.Active.HitTestAsync(geometry, CancelableProgressor.None);
        var featOids = features.Where(x => x.Item1 == featLayer).Select(x => x.Item2).First();

        //update the attributes of those features
        var fi = new FeatureInspector(true);
        await fi.FillAsync(featLayer, featOids);
        await fi.Attributes.Where(a => a.FieldName == "PARCEL_ID").First().SetValueAsync(42);

        //create and execute the edit operation
        var op = new EditOperation();
        op.Name = "The ultimate answer";
        op.SelectModifiedFeatures = true;
        op.SelectNewFeatures = false;
        op.Modify(fi);
        return await op.ExecuteAsync();
      });
    }
        /// <summary>
        /// Create random sample points in the extent of the spatial reference
        /// </summary>
        /// <param name="pointFeatureLayer">Point geometry feature layer used to the generate the points.</param>
        /// <returns>Task{bool}</returns>
        private Task<bool> constructSamplePoints(FeatureLayer pointFeatureLayer)
        {
            // create a random number generator
            var randomGenerator = new Random();

            // the database and geometry interactions are considered fine-grained and must be executed on
            // the main CIM thread
            return QueuedTask.Run(() =>
            {
                // start an edit operation to create new (random) point features
                var createOperation = new EditOperation();
                createOperation.Name = "Generate points";
                createOperation.SelectNewFeatures = false;

                // get the feature class associated with the layer
                var featureClass = pointFeatureLayer.GetTable() as FeatureClass;

                // define an area of interest. Random points are generated in the allowed
                // confines of the allow extent range
                var areaOfInterest = MapView.Active.Extent;

                MapPoint newMapPoint = null;

                // retrieve the class definition of the point feature class
                var classDefinition = featureClass.GetDefinition() as FeatureClassDefinition;

                // store the spatial reference as its own variable
                var spatialReference = classDefinition.GetSpatialReference();

                // create 20 new point geometries and queue them for creation
                for (int i = 0; i < 20; i++)
                {
                    // generate either 2D or 3D geometries
                    if (classDefinition.HasZ())
                        newMapPoint = MapPointBuilder.CreateMapPoint(randomGenerator.NextCoordinate(areaOfInterest, true), spatialReference);
                    else
                        newMapPoint = MapPointBuilder.CreateMapPoint(randomGenerator.NextCoordinate(areaOfInterest, false), spatialReference);

                    // queue feature creation
                    createOperation.Create(pointFeatureLayer, newMapPoint);
                }

                // execute the edit (feature creation) operation
                return createOperation.ExecuteAsync();
            });

        }
        /// <summary>
        /// Create a single multi-point feature that is comprised of 20 points.
        /// </summary>
        /// <param name="multiPointLayer">Multi-point geometry feature layer used to add the multi-point feature.</param>
        /// <returns></returns>
        private Task constructSampleMultiPoints(FeatureLayer multiPointLayer)
        {
            // create a random number generator
            var randomGenerator = new Random();

            // the database and geometry interactions are considered fine-grained and need to be executed on
            // a separate thread
            return QueuedTask.Run(() =>
            {
                // get the feature class associated with the layer
                var featureClass =  multiPointLayer.GetTable() as FeatureClass;
                var featureClassDefinition = featureClass.GetDefinition() as FeatureClassDefinition;

                // store the spatial reference as its own variable
                var spatialReference = featureClassDefinition.GetSpatialReference();

                // define an area of interest. Random points are generated in the allowed
                // confines of the allow extent range
                var areaOfInterest = MapView.Active.Extent;

                // start an edit operation to create new (random) multi-point feature
                var createOperation = new EditOperation();
                createOperation.Name = "Generate multipoints";

                // retrieve the class definition of the point feature class
                var classDefinition = featureClass.GetDefinition() as FeatureClassDefinition;

                // create a list to hold the 20 coordinates of the multi-point feature
                IList<Coordinate> coordinateList = new List<Coordinate>(20);

                for (int i = 0; i < 20; i++)
                {
                    // generate either 2D or 3D geometries
                    if (classDefinition.HasZ())
                        coordinateList.Add(randomGenerator.NextCoordinate(areaOfInterest, true));
                    else
                        coordinateList.Add(randomGenerator.NextCoordinate(areaOfInterest, false));
                }

                var newPoints = MultipointBuilder.CreateMultipoint(coordinateList, classDefinition.GetSpatialReference());
                // create and execute the feature creation operation
                createOperation.Create(multiPointLayer, newPoints);

                return createOperation.ExecuteAsync();
            });
        }
Exemplo n.º 8
0
        /// <summary>
        /// Create sample polygon feature using the point geometries from the multi-point feature using the 
        /// ConvexHull method provided by the GeometryEngine.
        /// </summary>
        /// <param name="polygonLayer">Polygon geometry feature layer used to add the new feature.</param>
        /// <param name="lineLayer">The polyline feature layer containing the features used to construct the polygon.</param>
        /// <returns></returns>
        private Task<bool> constructSamplePolygon(FeatureLayer polygonLayer, FeatureLayer lineLayer)
        {

            // execute the fine grained API calls on the CIM main thread
            return QueuedTask.Run(() =>
            {
                // get the underlying feature class for each layer
                var polygonFeatureClass = polygonLayer.GetTable() as FeatureClass;
                var polygonDefinition = polygonFeatureClass.GetDefinition() as FeatureClassDefinition;
                var lineFeatureClass = lineLayer.GetTable() as FeatureClass;

                // construct a cursor to retrieve the line features
                var lineCursor = lineFeatureClass.Search(null, false);

                // set up the edit operation for the feature creation
                var createOperation = new EditOperation()
                {
                    Name = "Create polygons",
                    SelectNewFeatures = false
                };

                PolylineBuilder polylineBuilder = new PolylineBuilder(polygonDefinition.GetSpatialReference());

                while (lineCursor.MoveNext())
                {
                    // retrieve the first feature
                    var lineFeature = lineCursor.Current as Feature;

                    // add the coordinate collection of the current geometry into our overall list of collections
                    var polylineGeometry = lineFeature.GetShape() as Polyline;
                    polylineBuilder.AddParts(polylineGeometry.Parts);
                }

                // use the ConvexHull method from the GeometryEngine to construct the polygon geometry
                var newPolygon = GeometryEngine.ConvexHull(polylineBuilder.ToGeometry()) as Polygon;

                // queue the polygon creation
                createOperation.Create(polygonLayer, newPolygon);

                // execute the edit (polygon create) operation
                return createOperation.ExecuteAsync();
            });
        }
Exemplo n.º 9
0
 private void IncreaseCounters(EditOperation operation)
 {
     if (operation.InputChar == CharConstants.Empty)
     {
         _deletions++;
     }
     else if (operation.ReferenceChar == CharConstants.Empty)
     {
         _insertions++;
     }
     else if (operation.InputChar == operation.ReferenceChar)
     {
         _matches++;
     }
     else
     {
         _nonMatches++;
     }
 }
        /// <summary>
        /// Fires once the user completes the onscreen sketch. In the context of a construction tool the sketch geometry 
        /// is used for the shape of the feature.
        /// </summary>
        /// <param name="geometry">The sketch geometry the user digitized on the screen.</param>
        /// <returns></returns>
        protected override Task<bool> OnSketchCompleteAsync(Geometry geometry)
        {
            if (geometry == null)
                return Task.FromResult(false);

            return QueuedTask.Run(() =>
                {
                    // create an edit operation
                    var editOperation = new EditOperation();
                    editOperation.Name = string.Format("Create point in '{0}'", CurrentTemplate.Layer.Name);
                    editOperation.ProgressMessage = "Working...";
                    editOperation.CancelMessage = "Operation canceled";
                    editOperation.ErrorMessage = "Error creating point";

                    // queue the edit operation using the sketch geometry as the shape of the feature and any attribute 
                    // configurations from the editing template
                    editOperation.Create(CurrentTemplate, geometry);                    

                    //execute the operation
                    return editOperation.ExecuteAsync();
                });
        }
Exemplo n.º 11
0
    protected override Task<bool> OnSketchCompleteAsync(Geometry geometry)
    {
      //Run on MCT
      return QueuedTask.Run(() =>
      {
        var op = new EditOperation();
        op.Name = "Create main-connector-manhole";
        op.SelectModifiedFeatures = false;
        op.SelectNewFeatures = false;

        //get the templates
        var map = MapView.Active.Map;
        var mainTemplate = map.FindLayers("main").First().GetTemplate("main");
        var mhTemplate = map.FindLayers("Manhole").First().GetTemplate("Manhole");
        var conTemplate = map.FindLayers("Connector").First().GetTemplate("Connector");

        //create the main geom
        var mainGeom = GeometryEngine.Move(geometry, 0, 0, -20);
        op.Create(mainTemplate, mainGeom);

        //create manhole points and connector
        foreach (var pnt in ((Polyline)geometry).Points)
        {
          //manhole point at sketch vertex
          op.Create(mhTemplate, pnt);

          //vertical connector between mahole and main
          var conPoints = new List<MapPoint>();
          conPoints.Add(pnt); //top of vertical connector
          conPoints.Add(GeometryEngine.Move(pnt, 0, 0, -20)); //bottom of vertical connector
          var conPolyLine = PolylineBuilder.CreatePolyline(conPoints);
          op.Create(conTemplate, conPolyLine);
        }
        return op.Execute();
      });
    }
Exemplo n.º 12
0
 public ConfusionMatrix(EditOperation operation)
 {
     EditOperation = operation;
 }
Exemplo n.º 13
0
        protected override async void OnClick()
        {
            #region Initialization
            // set up a set of TextureCoordinates - these determine how the texture is draped over a face
            //  In this scenario we will use the same textureCoordinates for each face
            var textureCoords = new List <Coordinate2D>()
            {
                new Coordinate2D(4.67909908294678, -2.89953231811523),
                new Coordinate2D(-3.7085223197937, -2.89953231811523),
                new Coordinate2D(-3.6790623664856, 1.89953279495239),
                new Coordinate2D(4.67909908294678, -2.89953231811523),
                new Coordinate2D(-3.6790623664856, 1.89953279495239),
                new Coordinate2D(4.7085223197937, 1.89953327178955)
            };

            TextureCompressionType compressionType = TextureCompressionType.CompressionJPEG;
            byte[] glassImageBuffer     = GetBufferImage("pack://application:,,,/MultipatchBuilder;component/Textures/Glass.jpg", compressionType);
            var    glassTextureResource = new TextureResource(new JPEGTexture(glassImageBuffer));
            byte[] roofImageBuffer      = GetBufferImage("pack://application:,,,/MultipatchBuilder;component/Textures/Roof.jpg", compressionType);
            var    roofTextureResource  = new TextureResource(new JPEGTexture(roofImageBuffer));

            var materialGray = new BasicMaterial
            {
                Color = System.Windows.Media.Colors.Gray
            };
            #endregion

            if (MapView.Active?.Map == null)
            {
                return;
            }

            // find footprint layer
            var footPrintLyr = MapView.Active.Map.GetLayersAsFlattenedList().FirstOrDefault(l => l.Name == "BuildingFootprints") as FeatureLayer;
            if (footPrintLyr == null)
            {
                MessageBox.Show("Can't find layer: BuildingFootprint");
                return;
            }

            var buildingLyr = MapView.Active.Map.GetLayersAsFlattenedList().FirstOrDefault(l => l.Name == "BuildingStructure") as FeatureLayer;
            if (buildingLyr == null)
            {
                MessageBox.Show("Can't find layer: BuildingStructure");
                return;
            }

            // create the multipatch
            var mpb = await QueuedTask.Run <MultipatchBuilderEx>(() =>
            {
                // get all selected lines and use them as the building footprint
                var footPrintSelection = footPrintLyr.GetSelection();
                Polygon footPrint      = null;
                int floorLevels        = 1;
                #region Get Footprint and Floor levels
                foreach (var footprintOid in footPrintSelection.GetObjectIDs())
                {
                    // get the multipatch shape using the Inspector
                    var insp = new Inspector();
                    insp.Load(footPrintLyr, footprintOid);
                    footPrint   = GeometryEngine.Instance.ReverseOrientation(insp.Shape as Multipart) as Polygon;
                    floorLevels = (int)insp["Floors"];
                }
                if (footPrint == null)
                {
                    MessageBox.Show("No selected building footprint found");
                    return(null);
                }
                #endregion
                // Create the MultipatchBuilder using the building footprints and the floorlevels as height
                return(MyMultipatchBuilder.CreateTriangleMultipatchBuilder(footPrint, floorLevels));
            });

            // apply texture or material
            // create a builder to work on the multipatch geometry
            switch (Module1.SelectedTexture)
            {
            case "Glass":
                // create the textures for walls and roof
                BasicMaterial glassMaterialTexture = new BasicMaterial
                {
                    TextureResource = glassTextureResource
                };
                BasicMaterial roofMaterialTexture = new BasicMaterial
                {
                    TextureResource = roofTextureResource
                };

                // apply the texture materials to the patches
                var patches = mpb.Patches;
                for (var iPatch = 0; iPatch < patches.Count; iPatch++)
                {
                    if (iPatch == patches.Count - 1)
                    {
                        // roof
                        patches[iPatch].Material        = roofMaterialTexture;
                        patches[iPatch].TextureCoords2D = textureCoords;
                    }
                    else
                    {
                        // walls
                        patches[iPatch].Material        = glassMaterialTexture;
                        patches[iPatch].TextureCoords2D = textureCoords;
                    }
                }
                break;

            case "Red-solid":
                // create some materials
                var materialRed = new BasicMaterial
                {
                    Color = System.Windows.Media.Colors.Brown
                };
                // apply the materials to the patches
                for (var iPatch = 0; iPatch < mpb.Patches.Count; iPatch++)
                {
                    if (iPatch == mpb.Patches.Count - 1)
                    {
                        // roof
                        mpb.Patches[iPatch].Material = materialGray;
                    }
                    else
                    {
                        // walls
                        mpb.Patches[iPatch].Material = materialRed;
                    }
                }
                break;

            case "Gray-solid":
                // create some materials
                var materialSilver = new BasicMaterial
                {
                    Color = System.Windows.Media.Colors.Silver
                };
                // apply the materials to the patches
                for (var iPatch = 0; iPatch < mpb.Patches.Count; iPatch++)
                {
                    if (iPatch == mpb.Patches.Count - 1)
                    {
                        // roof
                        mpb.Patches[iPatch].Material = materialGray;
                    }
                    else
                    {
                        // walls
                        mpb.Patches[iPatch].Material = materialSilver;
                    }
                }
                break;
            }

            // create a new feature using the multipatch
            bool result = await QueuedTask.Run(() =>
            {
                var op = new EditOperation
                {
                    Name = "Create multipatch feature",
                    SelectNewFeatures = false
                };
                Module1.NewMultipatch = mpb.ToGeometry() as Multipatch;
                var rowToken          = op.Create(buildingLyr, Module1.NewMultipatch);
                if (op.Execute())
                {
                    // track the newly created objectID
                    // save the oid in the module for other commands to use
                    Module1.NewMultipatchOID = rowToken.ObjectID.Value;
                    return(true);
                }
                var msg = op.ErrorMessage;
                return(false);
            });
        }
Exemplo n.º 14
0
 public void Prepend(EditOperation operation)
 {
     alignment.Insert(0, operation);
     IncreaseCounters(operation);
 }
Exemplo n.º 15
0
        public static ArcGIS.Core.Geometry.Geometry GetGeometry(int featureClassID, int OID, out bool isLine, FeatureLayer lineFeatureLayer, FeatureLayer pointFeatureLayer)
        {
            isLine = true;
            IFeatureClass fc = null;
            if(_fcIDToFeatureClass.ContainsKey(featureClassID) == false)
            {
                IFeatureWorkspaceManage2 fwsm2 = (IFeatureWorkspaceManage2)_fws;
                string className = fwsm2.GetObjectClassNameByID(featureClassID);
                _fcIDToFeatureClass.Add(featureClassID,_fws.OpenFeatureClass(className) );

            }
            fc = _fcIDToFeatureClass[featureClassID];
            var shape = fc.GetFeature(OID).Shape;
            if (shape.GeometryType == ESRI.ArcGIS.Geometry.esriGeometryType.esriGeometryPoint)
            {
                IPoint pnt = (IPoint)shape;
                //var coord = new Coordinate(xCoord, yCoord);
                //newMapPoint = MapPointBuilder.CreateMapPoint(coord, spatialReference);
                isLine = false;
            }
            else
            {
                isLine = true;
            }
            bool isLineForLambda = isLine;
            QueuedTask.Run(() =>
            {
                EnvelopeBuilder envBuilder = new EnvelopeBuilder();
                envBuilder.XMin = 0;
                envBuilder.XMax = 0;
                envBuilder.YMin = 0;
                envBuilder.YMax = 0;
                var env = envBuilder.ToGeometry().Extent;
                var pntFeatureClass = pointFeatureLayer.GetTable() as ArcGIS.Core.Data.FeatureClass;
                var pntClassDefinition = pntFeatureClass.GetDefinition() as FeatureClassDefinition;
                var spatialReference = pntClassDefinition.GetSpatialReference();
                var createOperation = new EditOperation();

                createOperation.Name = "Highlight Design Features";
                createOperation.SelectNewFeatures = false;
                if (isLineForLambda == false) //point
                {
                    IPoint pnt = (IPoint)shape;
                    var coord = new Coordinate(pnt.X,pnt.Y);
                    var newMapPoint = MapPointBuilder.CreateMapPoint(coord, spatialReference);
                    // queue feature creation
                    createOperation.Create(pointFeatureLayer, newMapPoint);
                    Common.UnionEnvelopes(envBuilder, newMapPoint);
                }
                else
                {
                    IPointCollection pc = (IPointCollection)shape;
                    var lineCoordinates = new List<Coordinate>(pc.PointCount);
                    for (int i = 0; i < pc.PointCount; i++)
                    {
                        var vertex = new Coordinate(pc.get_Point(i).X, pc.get_Point(i).Y);
                        lineCoordinates.Add(vertex);
                        var newPolyline = PolylineBuilder.CreatePolyline(lineCoordinates, spatialReference);
                        createOperation.Create(lineFeatureLayer, newPolyline);
                        Common.UnionEnvelopes(envBuilder, newPolyline);
                    }
                }

            });

            return null;
        }
        /// <summary>
        /// Create sample polyline feature using the geometries from the point feature layer.
        /// </summary>
        /// <param name="polylineLayer">Polyline geometry feature layer used to add the new features.</param>
        /// <param name="pointLayer">The geometries from the point layer are used as vertices for the new line features.</param>
        /// <returns></returns>
        private Task<bool> constructSamplePolylines(FeatureLayer polylineLayer, FeatureLayer pointLayer)
        {
            // execute the fine grained API calls on the CIM main thread
            return QueuedTask.Run(() =>
            {
                // get the underlying feature class for each layer
                var polylineFeatureClass = polylineLayer.GetTable() as FeatureClass;
                var pointFeatureClass = pointLayer.GetTable() as FeatureClass;

                // retrieve the feature class schema information for the feature classes
                var polylineDefinition = polylineFeatureClass.GetDefinition() as FeatureClassDefinition;
                var pointDefinition = pointFeatureClass.GetDefinition() as FeatureClassDefinition;

                // construct a cursor for all point features, since we want all feature there is no
                // QueryFilter required
                var pointCursor = pointFeatureClass.Search(null, false);

                // initialize a counter variable
                int pointCounter = 0;
                // initialize a list to hold 5 coordinates that are used as vertices for the polyline
                var lineCoordinates = new List<Coordinate>(5);

                // set up the edit operation for the feature creation
                var createOperation = new EditOperation();
                createOperation.Name = "Create polylines";
                createOperation.SelectNewFeatures = false;

                // loop through the point features
                while (pointCursor.MoveNext())
                {
                    pointCounter++;

                    var pointFeature = pointCursor.Current as Feature;
                    // add the feature point geometry as a coordinate into the vertex list of the line
                    // - ensure that the projection of the point geometry is converted to match the spatial reference of the line
                    lineCoordinates.Add(((MapPoint)GeometryEngine.Project(pointFeature.GetShape(), polylineDefinition.GetSpatialReference())).Coordinate);

                    // for every 5 geometries, construct a new polyline and queue a feature create
                    if (pointCounter % 5 == 0)
                    {
                        // construct a new polyline by using the 5 point coordinate in the current list
                        var newPolyline = PolylineBuilder.CreatePolyline(lineCoordinates, polylineDefinition.GetSpatialReference());
                        // queue the create operation as part of the edit operation
                        createOperation.Create(polylineLayer, newPolyline);
                        // reset the list of coordinates
                        lineCoordinates = new List<Coordinate>(5);
                    }
                }

                // execute the edit (create) operation
                return createOperation.ExecuteAsync();
            });
        }
Exemplo n.º 17
0
 public void Append(EditOperation operation)
 {
     alignment.Add(operation);
     IncreaseCounters(operation);
 }
        /// <summary>
        /// This function takes the selected features in the map view, finds the first field of type string in the each feature class
        /// and modifies the attribute value to a random string.
        /// </summary>
        /// <returns>Indicator if the edit operation was successful.</returns>
        private async Task<bool> PerformAttributeChange()
        {
            try
            {
                // retrieve the currently selected features in the map view            
                var currentSelectedFeatures = await QueuedTask.Run(() =>
                {
                    return MapView.Active.Map.GetSelection();
                });

                // for each of the map members in the selected layers
                foreach (var mapMember in currentSelectedFeatures)
                {
                    var featureLayer = mapMember.Key as BasicFeatureLayer;
                    // .. get the underlying table
                    var table = await QueuedTask.Run(() =>
                    {
                        return featureLayer.GetTable();
                    });

                    // retrieve the first field of type string
                    var stringField = table.GetFieldByTypeAsync(FieldType.String).Result;
                    var stringFieldName = stringField != null ? stringField.Name : String.Empty;

                    // check if the returned string of the field name actually contains something
                    // meaning if the current MapMember actually contains a field of type string
                    if (String.IsNullOrEmpty(stringFieldName))
                        continue;

                    #region Use edit operations for attribute changes
                    // create a new edit operation to encapsulate the string field modifications
                    var modifyStringsOperation = new EditOperation
                    {
                        Name = String.Format("Modify string field '{0}' in layer {1}.", stringFieldName, mapMember.Key.Name)
                    };
                    ICollection<long> oidSet = new List<long>();
                    var iCnt = 0;
                    // with each ObjectID of the selected feature
                    foreach (var oid in currentSelectedFeatures[mapMember.Key])
                    {
                        // set up a new dictionary with fields to modify
                        var modifiedAttributes = new Dictionary<string, object>
                        {
                            // add the name of the string field and the new attribute value to the dictionary
                            // in this example a random string is used
                            {stringFieldName, string.Format("Update {0} on: {1:s}", ++iCnt, DateTime.Now)}
                        };

                        // put the modify operation on the editor stack
                        modifyStringsOperation.Modify(mapMember.Key, oid, modifiedAttributes);
                        oidSet.Add(oid);
                    }

                    // execute the modify operation to apply the changes
                    await modifyStringsOperation.ExecuteAsync();
                    #endregion

                    #region Use the feature inspector for attribute changes
#if OrUseThis
                    // as an alternative approach
                    // use the feature inspector class
                    var featureInspector = new Inspector(true);

                    // fill the feature inspector with the oids from the feature layer               
                    await featureInspector.LoadAsync(mapMember.Key, currentSelectedFeatures[mapMember.Key]);

                    // change the attribute value for the string field
                    featureInspector[stringFieldName] = Path.GetRandomFileName().Replace(".", "");

                    // app. the new values
                    await featureInspector.ApplyAsync();
#endif
                    #endregion
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("An error occurred while updating attribute column data {0}", ex.ToString());
            }
            return true;
        }
        protected override Task <bool> OnSketchCompleteAsync(Geometry geometry)
        {
            // execute on the MCT
            return(QueuedTask.Run(() =>
            {
                // find features under the sketch
                var features = MapView.Active.GetFeatures(geometry);
                if (features.Count == 0)
                {
                    return false;
                }

                EditOperation op = null;
                foreach (var layerKey in features.Keys)
                {
                    // is it an anno layer?
                    if (!(layerKey is AnnotationLayer))
                    {
                        continue;
                    }

                    // are there features?
                    var featOids = features[layerKey];
                    if (featOids.Count == 0)
                    {
                        continue;
                    }

                    // use the inspector methodology - load multiple features at once
                    var insp = new Inspector();
                    insp.Load(layerKey, featOids);

                    // make sure tha attribute exists - remember TextString is not guaranteed in the schema
                    Attribute att = insp.FirstOrDefault(a => a.FieldName.ToUpper() == "TEXTSTRING");
                    if (att == null)
                    {
                        continue;
                    }
                    insp["TEXTSTRING"] = "Hello World";

                    // create the edit operation
                    if (op == null)
                    {
                        op = new EditOperation();
                        op.Name = "Update annotation text";
                        op.SelectModifiedFeatures = true;
                        op.SelectNewFeatures = false;
                    }

                    op.Modify(insp);

                    // OR
                    // rather than using the inspector you can use the Dictionary methodology - again TextString has to exist in the schema for the attributes to be applied.

                    //Dictionary<string, object> newAtts = new Dictionary<string, object>();
                    //newAtts.Add("TEXTSTRING", "Hello World");
                    //foreach (var oid in featOids)
                    //  op.Modify(layerKey, oid, newAtts);
                }

                // execute the operation
                if ((op != null) && !op.IsEmpty)
                {
                    return op.Execute();
                }
                return
                false;
            }));
        }
        private async void SaveEdits(object parameter)
        {
            string message = String.Empty;
            bool modificationResult = false;

            IEnumerable<GDBProjectItem> gdbProjectItems = Project.Current.GetItems<GDBProjectItem>();
            await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
            {
                try
                {
                    foreach (GDBProjectItem gdbProjectItem in gdbProjectItems)
                    {
                        using (Datastore datastore = gdbProjectItem.GetDatastore())
                        {
                            //Unsupported datastores (non File GDB and non Enterprise GDB) will be of type UnknownDatastore
                            if (datastore is UnknownDatastore)
                                continue;
                            Geodatabase geodatabase = datastore as Geodatabase;

                            //Find the correct gdb for the one with the complete schema
                            string geodatabasePath = geodatabase.GetPath();
                            if (geodatabasePath == ProSymbolEditorModule.Current.MilitaryOverlaySchema.DatabaseName)
                            {
                                EditOperation editOperation = new EditOperation();
                                editOperation.Callback(context =>
                                {
                                    string oidFieldName = _selectedSelectedFeature.FeatureLayer.GetTable().GetDefinition().GetObjectIDField();
                                    QueryFilter queryFilter = new QueryFilter();
                                    queryFilter.WhereClause = string.Format("{0} = {1}", oidFieldName, _selectedSelectedFeature.ObjectId);

                                    using (RowCursor cursor = _selectedSelectedFeature.FeatureLayer.GetTable().Search(queryFilter, false))
                                    {
                                        while (cursor.MoveNext())
                                        {
                                            Feature feature = (Feature)cursor.Current;

                                        // In order to update the Map and/or the attribute table.
                                        // Has to be called before any changes are made to the row
                                        context.Invalidate(feature);

                                            _symbolAttributeSet.PopulateFeatureWithAttributes(ref feature);

                                            feature.Store();

                                        // Has to be called after the store too
                                        context.Invalidate(feature);

                                        }
                                    }
                                }, _selectedSelectedFeature.FeatureLayer.GetTable());

                                var task = editOperation.ExecuteAsync();
                                modificationResult = task.Result;
                                if (!modificationResult)
                                    message = editOperation.ErrorMessage;
                            }
                        }

                    }
                }
                catch (Exception exception)
                {
                    System.Console.WriteLine(exception.Message);
                }
            });

            if (!modificationResult)
            {
                MessageBox.Show(message);
            }
        }
        public async void CreateNewFeatureAsync(object parameter)
        {
            string message = String.Empty;
            bool creationResult = false;

            //Generate geometry if polygon or polyline, if adding new feature is from using coordinates and not the map tool
            if (Convert.ToBoolean(parameter) == true)
            {
                if (GeometryType == GeometryType.Polyline || GeometryType == GeometryType.Polygon)
                {
                    GeneratePolyGeometry();
                }
            }

            IEnumerable<GDBProjectItem> gdbProjectItems = Project.Current.GetItems<GDBProjectItem>();
            await QueuedTask.Run(() =>
            {
                foreach (GDBProjectItem gdbProjectItem in gdbProjectItems)
                {
                    using (Datastore datastore = gdbProjectItem.GetDatastore())
                    {
                        //Unsupported datastores (non File GDB and non Enterprise GDB) will be of type UnknownDatastore
                        if (datastore is UnknownDatastore)
                            continue;
                        Geodatabase geodatabase = datastore as Geodatabase;
                        
                        //Find the correct gdb for the one with the complete schema
                        string geodatabasePath = geodatabase.GetPath();
                        if (geodatabasePath == ProSymbolEditorModule.Current.MilitaryOverlaySchema.DatabaseName)
                        {
                            //Correct GDB, open the current selected feature class
                            FeatureClass featureClass = geodatabase.OpenDataset<FeatureClass>(_currentFeatureClassName);
                            using (featureClass)
                            using (FeatureClassDefinition facilitySiteDefinition = featureClass.GetDefinition())
                            {
                                EditOperation editOperation = new EditOperation();
                                editOperation.Name = "Military Symbol Insert";
                                editOperation.Callback(context =>
                                {
                                    try
                                    {
                                        RowBuffer rowBuffer = featureClass.CreateRowBuffer();
                                        _symbolAttributeSet.PopulateRowBufferWithAttributes(ref rowBuffer);
                                        rowBuffer["Shape"] = GeometryEngine.Project(MapGeometry, facilitySiteDefinition.GetSpatialReference());

                                        Feature feature = featureClass.CreateRow(rowBuffer);
                                        feature.Store();

                                        //To Indicate that the attribute table has to be updated
                                        context.Invalidate(feature);
                                    }
                                    catch (GeodatabaseException geodatabaseException)
                                    {
                                        message = geodatabaseException.Message;
                                    }
                                }, featureClass);

                                var task = editOperation.ExecuteAsync();
                                creationResult = task.Result;
                                if (!creationResult)
                                {
                                    message = editOperation.ErrorMessage;
                                }

                                break;
                            }
                        }
                    }
                }
            });

            if (!creationResult)
            {
                MessageBox.Show(message);
            }
        }
Exemplo n.º 22
0
 public SpringboardStateEntry(EditOperation editOperation)
 {
     EditOperationId = editOperation.Id;
 }
Exemplo n.º 23
0
 internal override EditOperation UndoPrior(EditOperation hunk)
 {
     return UndoPrior<InsertOperation>(hunk);
 }
Exemplo n.º 24
0
 internal override EditOperation RedoPrior(EditOperation hunk)
 {
     return RedoPrior<CopyOperation>(hunk);
 }
Exemplo n.º 25
0
        public static async Task DeleteDxFeatures()
        {
            //Get the full list of features in the xpress design
            string[] commisioned = File.ReadAllLines(Common.GetConfiguration("CommisionedDesign"));
            //Turn the commissioned design list into a dictionary keyed by layer name
            Dictionary<string, List<int>> commissionedDesignLayerToOIDS = new Dictionary<string, List<int>>();
            string lastLayerName = "";
            foreach (string line in commisioned)
            {
                int oid = -1;
                if (int.TryParse(line, out oid) == false)
                {
                    commissionedDesignLayerToOIDS.Add(line, new List<int>());
                    lastLayerName = line;
                }
                else
                {
                    commissionedDesignLayerToOIDS[lastLayerName].Add(Convert.ToInt32(line));
                }
            }

            List<FeatureLayer> layerList = new List<FeatureLayer>();
            Map activeMap = MapView.Active.Map;
            var layers = activeMap.GetLayersAsFlattenedList().OfType<FeatureLayer>().Where(
                lyr => lyr.ShapeType == (ArcGIS.Core.CIM.esriGeometryType.esriGeometryPoint) || lyr.ShapeType == ArcGIS.Core.CIM.esriGeometryType.esriGeometryPolyline);

            QueuedTask.Run(() =>
            {
                foreach (FeatureLayer fl in layers)
                {
                    if (commissionedDesignLayerToOIDS.ContainsKey(fl.Name))
                    {
                        List<int> oidsToDelete = commissionedDesignLayerToOIDS[fl.Name];
                        string oidsCommaSep = "";
                        foreach (int oid in oidsToDelete)
                        {
                            if (oidsCommaSep.Length > 0)
                            {
                                oidsCommaSep += "," + oid;
                            }
                            else
                            {
                                oidsCommaSep = oid.ToString();
                            }
                        }

                        Table t = fl.GetTable();
                        var gdb = t.GetWorkspace();
                        EditOperation editOperation = new EditOperation();
                        editOperation.Callback(context =>
                        {
                            QueryFilter qf = new QueryFilter { WhereClause = "OBJECTID IN (" + oidsCommaSep + ")" };
                            using (RowCursor rowCursor = t.Search(qf, false))
                            {
                                while (rowCursor.MoveNext())
                                {
                                    using (Row row = rowCursor.Current)
                                    {
                                        row.Delete();
                                        context.invalidate(row);
                                    }
                                }
                            }
                        }, gdb);
                        bool editResult =  editOperation.ExecuteAsync().Result;
                        bool saveResult =  EditingModule.SaveEditsAsync().Result;
                    }
                }
            });
        }
    /// <summary>
    /// Divide the first selected feature into equal parts or by map unit distance.
    /// </summary>
    /// <param name="numberOfParts">Number of parts to create.</param>
    /// <param name="value">Value for number or parts or distance.</param>
    /// <returns></returns>
    private static Task DivideLinesAsync(bool numberOfParts, double value)
    {
      //Run on MCT
      return QueuedTask.Run(() =>
      {
        //get selected feature
        var selectedFeatures = MapView.Active.Map.GetSelection();

        //get the layer of the selected feature
        var featLayer = selectedFeatures.Keys.First() as FeatureLayer;
        var oid = selectedFeatures.Values.First().First();

        var feature = featLayer.Inspect(oid);

        //get geometry and length
        var origPolyLine = feature.Shape as Polyline;
        var origLength = GeometryEngine.Length(origPolyLine);

        //List of mappoint geometries for the split
        var splitPoints = new List<MapPoint>();

        var enteredValue = (numberOfParts) ? origLength / value : value;
        var splitAtDistance = 0 + enteredValue;

        while (splitAtDistance < origLength)
        {
          //create a mapPoint at splitDistance and add to splitpoint list
          splitPoints.Add(GeometryEngine.MovePointAlongLine(origPolyLine, splitAtDistance, false, 0));
          splitAtDistance += enteredValue;
        }
        
        //create and execute the edit operation
        var op = new EditOperation();
        op.Name = "Divide Lines";
        op.SelectModifiedFeatures = false;
        op.SelectNewFeatures = false;
        op.SplitAtPoints(featLayer, oid, splitPoints);
        op.Execute();

        //clear selection
        //MapView.Active.Map.SetSelection(null);
        featLayer.ClearSelection();
      });
    }
        /// <summary>
        /// Method to perform the cut operation on the geometry and change attributes
        /// </summary>
        /// <param name="geometry">Line geometry used to perform the cut against in the polygon features
        /// in the active map view.</param>
        /// <returns>If the cut operation was successful.</returns>
        protected Task<bool> ExecuteCut(Geometry geometry)
        {
            if (geometry == null)
                return Task.FromResult(false);

            // create an edit operation
            EditOperation cutOperation = new EditOperation();
            cutOperation.Name = "Cut Elements";
            cutOperation.ProgressMessage = "Working...";
            cutOperation.CancelMessage = "Operation canceled.";
            cutOperation.ErrorMessage = "Error cutting polygons";
            cutOperation.SelectModifiedFeatures = false;
            cutOperation.SelectNewFeatures = false;

            // create a collection of feature layers that can be edited
            var editableLayers = ActiveMapView.Map.GetLayersAsFlattenedList()
                .OfType<FeatureLayer>()
                .Where(lyr => lyr.CanEditData() == true).Where(lyr =>
                lyr.ShapeType == esriGeometryType.esriGeometryPolygon);

            // ensure that there are target layers
            if (editableLayers.Count() == 0)
                return Task.FromResult(false);

            // initialize a list of ObjectIDs that need to be cut
            var cutOIDs = new List<long>();

            // for each of the layers 
            foreach (FeatureLayer editableFeatureLayer in editableLayers)
            {
                // find the features crossed by the sketch geometry
                var rowCursor = editableFeatureLayer.Search(geometry, SpatialRelationship.Crosses);

                // get the feature class associated with the layer
                Table fc = editableFeatureLayer.GetTable();

                // find the field index for the 'Description' attribute
                int descriptionIndex = -1;
                descriptionIndex = fc.GetDefinition().FindField("Description");

                // add the feature IDs into our prepared list
                while (rowCursor.MoveNext())
                {
                    var feature = rowCursor.Current as Feature;
                    if (feature.GetShape() != null)
                    {
                        // we are looking for polygons are completely intersected by the cut line
                        if (GeometryEngine.Relate(geometry, feature.GetShape(), "TT*F*****"))
                        {
                            // add the current feature to the overall list of features to cut
                            cutOIDs.Add(rowCursor.Current.GetObjectID());

                            // adjust the attribute before the cut
                            if (descriptionIndex != -1)
                                cutOperation.Modify(rowCursor.Current, descriptionIndex, "Pro Sample");
                        }
                    }
                }
                // add the elements to cut into the edit operation
                cutOperation.Cut(editableFeatureLayer, cutOIDs, geometry);
            }

            //execute the operation
            var operationResult = cutOperation.Execute();

            return Task.FromResult(operationResult);
        }
Exemplo n.º 28
0
        public void MainMethodCode()
        {
            using (Geodatabase fileGeodatabase = new Geodatabase(new FileGeodatabaseConnectionPath(new Uri(@"C:\Data\LocalGovernment.gdb"))))
                using (FeatureClass featureClass = fileGeodatabase.OpenDataset <FeatureClass>("PollingPlace"))
                {
                    QueryFilter queryFilter = new QueryFilter {
                        WhereClause = "CITY = 'Plainfield'"
                    };
                    Selection selection = featureClass.Select(queryFilter, SelectionType.ObjectID, SelectionOption.Normal);

                    // The result is a mapping between those object ids which failed validation and the reason why the validation failed (a string message).
                    IReadOnlyDictionary <long, string> validationResult = featureClass.Validate(selection);

                    RowCursor      rowCursor = featureClass.Search(queryFilter, false);
                    List <Feature> features  = new List <Feature>();

                    try
                    {
                        while (rowCursor.MoveNext())
                        {
                            features.Add(rowCursor.Current as Feature);
                        }

                        // This is equivalent to the validation performed using the selection.
                        IReadOnlyDictionary <long, string> equivalentValidationResult = featureClass.Validate(features);

                        // Again this is equivalent to both the above results.
                        IReadOnlyDictionary <long, string> anotherEquivalentResult = featureClass.Validate(queryFilter);

                        SpatialQueryFilter spatialQueryFilter = new SpatialQueryFilter
                        {
                            FilterGeometry = new EnvelopeBuilder(
                                new MapPointBuilder(1052803, 1812751).ToGeometry(),
                                new MapPointBuilder(1034600, 1821320).ToGeometry()).ToGeometry(),

                            SpatialRelationship = SpatialRelationship.Within
                        };

                        IReadOnlyDictionary <long, string> spatialFilterBasedValidationResult = featureClass.Validate(spatialQueryFilter);
                    }
                    finally
                    {
                        rowCursor.Dispose();
                        Dispose(features);
                    }
                }

            // Opening a Non-Versioned SQL Server instance.

            DatabaseConnectionProperties connectionProperties = new DatabaseConnectionProperties(EnterpriseDatabaseType.SQLServer)
            {
                AuthenticationMode = AuthenticationMode.DBMS,

                // Where testMachine is the machine where the instance is running and testInstance is the name of the SqlServer instance.
                Instance = @"testMachine\testInstance",

                // Provided that a database called LocalGovernment has been created on the testInstance and geodatabase has been enabled on the database.
                Database = "LocalGovernment",

                // Provided that a login called gdb has been created and corresponding schema has been created with the required permissions.
                User     = "******",
                Password = "******",
                Version  = "dbo.DEFAULT"
            };

            using (Geodatabase geodatabase = new Geodatabase(connectionProperties))
                using (FeatureClass enterpriseFeatureClass = geodatabase.OpenDataset <FeatureClass>("LocalGovernment.GDB.FacilitySite"))
                {
                    QueryFilter parkFilter = new QueryFilter {
                        WhereClause = "FCODE = 'Park'"
                    };
                    Selection parkSelection = enterpriseFeatureClass.Select(parkFilter, SelectionType.ObjectID, SelectionOption.Normal);

                    // Remember that validation cost is directly proprtional to the number of Features validated. So, select the set of features to be
                    // validated judiciously.  This will be empty because all the Park Features are valid.
                    IReadOnlyDictionary <long, string> emptyDictionary = enterpriseFeatureClass.Validate(parkSelection);

                    // We are adding an invalid feature to illustrate a case where the validation result is not empty.

                    long invalidFeatureObjectID = -1;

                    EditOperation editOperation = new EditOperation();
                    editOperation.Callback(context =>
                    {
                        RowBuffer rowBuffer = null;
                        Feature feature     = null;

                        try
                        {
                            FeatureClassDefinition facilitySiteDefinition = enterpriseFeatureClass.GetDefinition();

                            rowBuffer = enterpriseFeatureClass.CreateRowBuffer();

                            rowBuffer["FACILITYID"] = "FAC-400";
                            rowBuffer["NAME"]       = "Griffith Park";
                            rowBuffer["OWNTYPE"]    = "Municipal";
                            rowBuffer["FCODE"]      = "Park";
                            // Note that this is an invalid subtype value.
                            rowBuffer[facilitySiteDefinition.GetSubtypeField()] = 890;
                            rowBuffer[facilitySiteDefinition.GetShapeField()]   = new PolygonBuilder(new List <Coordinate2D>
                            {
                                new Coordinate2D(1021570, 1880583),
                                new Coordinate2D(1028730, 1880994),
                                new Coordinate2D(1029718, 1875644),
                                new Coordinate2D(1021405, 1875397)
                            }).ToGeometry();

                            feature = enterpriseFeatureClass.CreateRow(rowBuffer);

                            invalidFeatureObjectID = feature.GetObjectID();
                        }
                        catch (GeodatabaseException exObj)
                        {
                            Console.WriteLine(exObj);
                        }
                        finally
                        {
                            if (rowBuffer != null)
                            {
                                rowBuffer.Dispose();
                            }

                            if (feature != null)
                            {
                                feature.Dispose();
                            }
                        }
                    }, enterpriseFeatureClass);

                    editOperation.Execute();

                    // This will have one keypair value for the invalid row that was added.
                    IReadOnlyDictionary <long, string> result = enterpriseFeatureClass.Validate(parkFilter);

                    // This will say "invalid subtype code".
                    string errorMessage = result[invalidFeatureObjectID];
                }
        }
Exemplo n.º 29
0
 static EditOperation TransformForTargetState(EditOperation transformee, IEnumerable<int> sortedTargetState, Dictionary<int, EditOperation> transformedOperations, ICollection<EditOperation> allOperations)
 {
     EditOperation result;
     if (!transformedOperations.TryGetValue(transformee.Id, out result))
     {
         SpringboardState springBoardState = transformee.ChangeSubset.SpringboardState;
         List<int> sortedSpringBoard = new List<int>(springBoardState.Entries.Select(x => x.EditOperationId));
         sortedSpringBoard.Sort();
         List<UndoRedoEntry> undosRedos = new List<UndoRedoEntry>();
         ComputeStateDifferences(transformee.Id, sortedSpringBoard, sortedTargetState, undosRedos);
         result = transformee;
         foreach (UndoRedoEntry undoRedoEntry in undosRedos)
         {
             int transformerId = undoRedoEntry.OperationId;
             EditOperation transformer = TransformForTargetState(allOperations.First(x => (x.Id == transformerId)), sortedTargetState, transformedOperations, allOperations);
             if (undoRedoEntry.IsRedo)
                 result = result.RedoPrior(transformer);
             else
                 result = result.UndoPrior(transformer);
         }
         transformedOperations[transformee.Id] = result;
     }
     return result;
 }
Exemplo n.º 30
0
        private double CalculateProbability(EditOperation operation, char x, char y)
        {
            double output = 0;
            string fr;
            switch (operation)
            {
                case EditOperation.Insertion:
                    if (this.specialChars.Contains(y))
                    {
                        output = 1;
                    }
                    else
                    {
                        output = (double)dictionary.GetConfusionFrequency(x, y, EditOperation.Insertion) / dictionary.GetOneCharFrequency(x.ToString());
                    }
                    break;

                case EditOperation.Deletion:
                    fr = x.ToString() + y.ToString();
                    output = (double) dictionary.GetConfusionFrequency(x, y, EditOperation.Deletion) / dictionary.GetTwoCharFrequency(fr);
                    break;

                case EditOperation.Substitution:
                    output = (double) dictionary.GetConfusionFrequency(x, y, EditOperation.Substitution) / dictionary.GetOneCharFrequency(y.ToString());
                    break;

                case EditOperation.Transposition:
                    fr = x.ToString() + y.ToString();
                    output = (double) dictionary.GetConfusionFrequency(x, y, EditOperation.Transposition) / dictionary.GetTwoCharFrequency(fr);
                    break;

            }

            return output;
        }
Exemplo n.º 31
0
        private async Task <Tuple <string, int> > ImportPlatAsync(CancelableProgressorSource cps)
        {
            var result = await QueuedTask.Run <Tuple <string, int> >(async() =>
            {
                // first we  create a 'legal record' for the plat
                Dictionary <string, object> RecordAttributes = new Dictionary <string, object>();
                string sNewRecordName = $@"Plat {_selectedZone}-{_selectedSection}-{_selectedPlat}";
                int importedCount     = 0;
                try
                {
                    var editOper = new EditOperation()
                    {
                        Name            = $@"Create Parcel Fabric Record: {sNewRecordName}",
                        ProgressMessage = "Create Parcel Fabric Record...",
                        ShowModalMessageAfterFailure = false,
                        SelectNewFeatures            = false,
                        SelectModifiedFeatures       = false
                    };
                    cps.Progressor.Value += 1;
                    if (cps.Progressor.CancellationToken.IsCancellationRequested)
                    {
                        editOper.Abort();
                        return(new Tuple <string, int> ("Canceled", importedCount));
                    }
                    cps.Progressor.Status  = (cps.Progressor.Value * 100 / cps.Progressor.Max) + @" % Completed";
                    cps.Progressor.Message = editOper.ProgressMessage;
                    RecordAttributes.Add(FieldNameName, sNewRecordName);
                    RecordAttributes.Add(FieldNameZone, _selectedZone);
                    RecordAttributes.Add(FieldNameSect, _selectedSection);
                    RecordAttributes.Add(FieldNamePlat, _selectedPlat);
                    var editRowToken = editOper.Create(_recordLayer, RecordAttributes);
                    if (!editOper.Execute())
                    {
                        return(new Tuple <string, int>($@"Error [{editOper.Name}]: {editOper.ErrorMessage}", importedCount));
                    }

                    // now make the record the active record
                    var defOID = -1;
                    var lOid   = editRowToken.ObjectID ?? defOID;
                    await _parcelFabricLayer.SetActiveRecordAsync(lOid);
                }
                catch (Exception ex)
                {
                    return(new Tuple <string, int>($@"Error [Exception]: {ex.Message}", importedCount));
                }
                try
                {
                    // Copy the selected set of polygons into the Tax Parcels
                    // However, since we need to set the polygon attributes manually we need to add each
                    // parcel one at a time
                    var qry     = $@"{FieldNameZone} = {_selectedZone} and {FieldNameSect} = {_selectedSection} and {FieldNamePlat} = '{_selectedPlat}'";
                    var lstTmks = GetDistinctValues(_importParcelLineLayer, qry, FieldNameTmk);
                    lstTmks.Sort();
                    foreach (var selectedTmk in lstTmks)
                    {
                        importedCount++;
                        qry     = $@"{FieldNameTmk} = {selectedTmk}";
                        var cnt = SelectSet(_importParcelLineLayer, qry);
                        cps.Progressor.Value += cnt;
                        if (cps.Progressor.CancellationToken.IsCancellationRequested)
                        {
                            return(new Tuple <string, int>("Canceled", importedCount));
                        }
                        cps.Progressor.Status  = (cps.Progressor.Value * 100 / cps.Progressor.Max) + @" % Completed";
                        cps.Progressor.Message = $@"Process parcel no: {selectedTmk}";
                        var editOper           = new EditOperation()
                        {
                            Name            = $@"Copy new parcel lines for: {sNewRecordName}",
                            ProgressMessage = "Create Parcel lines ...",
                            ShowModalMessageAfterFailure = false,
                            SelectNewFeatures            = false,
                            SelectModifiedFeatures       = false
                        };
                        var ids = new List <long>(_importParcelLineLayer.GetSelection().GetObjectIDs());
                        if (ids.Count == 0)
                        {
                            return(new Tuple <string, int>($@"Error [{editOper.Name}]: No selected lines were found. Please select line features and try again.", importedCount));
                        }
                        var parcelEditTkn = editOper.CopyLineFeaturesToParcelType(_importParcelLineLayer, ids, _taxLayerLines, _taxLayerPolys);
                        if (!editOper.Execute())
                        {
                            return(new Tuple <string, int>($@"Error [{editOper.Name}]: {editOper.ErrorMessage}", importedCount));
                        }

                        // Update the names for all new parcel features
                        var createdParcelFeatures = parcelEditTkn.CreatedFeatures;
                        var editOperUpdate        = editOper.CreateChainedOperation();
                        // note: this only works for single parcels
                        Dictionary <string, object> ParcelAttributes = new Dictionary <string, object>();
                        // collect the attribute to be used for the polygon
                        // unfortunately the polygon attributes are not auto-populated so we have to do this here
                        foreach (KeyValuePair <MapMember, List <long> > kvp in createdParcelFeatures.ToDictionary())
                        {
                            if (cps.Progressor.CancellationToken.IsCancellationRequested)
                            {
                                editOperUpdate.Abort();
                                return(new Tuple <string, int>("Canceled", importedCount));
                            }
                            var mapMember = kvp.Key;
                            if (mapMember.Name.EndsWith("_Lines"))
                            {
                                var oids = kvp.Value;
                                foreach (long oid in oids)
                                {
                                    var insp = new Inspector();
                                    insp.Load(mapMember, oid);
                                    var tmk = insp[FieldNameTmk];
                                    if (tmk != null)
                                    {
                                        var sTmk = tmk.ToString();
                                        if (sTmk.Length > 6)
                                        {
                                            var selectedIsland  = sTmk.Substring(0, 1);
                                            var selectedZone    = sTmk.Substring(1, 1);
                                            var selectedSection = sTmk.Substring(2, 1);
                                            var selectedPlat    = sTmk.Substring(3, 3);
                                            ParcelAttributes.Add(FieldNameName, $@"{sTmk.Substring(0, 1)}-{sTmk.Substring(1, 1)}-{sTmk.Substring(2, 1)}-{sTmk.Substring(3, 3)}-{sTmk.Substring(6)}");
                                            ParcelAttributes.Add(FieldNameTmk, tmk);
                                            ParcelAttributes.Add(FieldNameIsland, selectedIsland);
                                            ParcelAttributes.Add(FieldNameZone, selectedZone);
                                            ParcelAttributes.Add(FieldNameSect, selectedSection);
                                            ParcelAttributes.Add(FieldNamePlat, selectedPlat);
                                            ParcelAttributes.Add(FieldNameParcel, insp[FieldNameParcel]);
                                            ParcelAttributes.Add(FieldNameLink, insp[FieldNameLink]);
                                            break;
                                        }
                                    }
                                }
                            }
                            if (ParcelAttributes.Count > 0)
                            {
                                break;
                            }
                        }
                        foreach (KeyValuePair <MapMember, List <long> > kvp in createdParcelFeatures.ToDictionary())
                        {
                            if (cps.Progressor.CancellationToken.IsCancellationRequested)
                            {
                                editOperUpdate.Abort();
                                return(new Tuple <string, int>("Canceled", importedCount));
                            }
                            var mapMember = kvp.Key;
                            if (!mapMember.Name.EndsWith("_Lines"))
                            {
                                var oids = kvp.Value;
                                foreach (long oid in oids)
                                {
                                    editOperUpdate.Modify(mapMember, oid, ParcelAttributes);
                                }
                            }
                        }
                        if (!editOperUpdate.Execute())
                        {
                            return(new Tuple <string, int>($@"Error [{editOperUpdate.Name}]: {editOperUpdate.ErrorMessage}", importedCount));
                        }
                    }
                }
                catch (Exception ex)
                {
                    return(new Tuple <string, int>($@"Error [Exception]: {ex.Message}", importedCount));
                }
                try
                {
                    // Build all Parcels for the Active record in the parcel fabric (set in step one)
                    var theActiveRecord = _parcelFabricLayer.GetActiveRecord();
                    var guid            = theActiveRecord.Guid;
                    var editOper        = new EditOperation()
                    {
                        Name            = "Build Parcels",
                        ProgressMessage = "Build Parcels...",
                        ShowModalMessageAfterFailure = true,
                        SelectNewFeatures            = true,
                        SelectModifiedFeatures       = true
                    };
                    cps.Progressor.Value += 1;
                    if (cps.Progressor.CancellationToken.IsCancellationRequested)
                    {
                        editOper.Abort();
                        return(new Tuple <string, int>("Canceled", importedCount));
                    }
                    cps.Progressor.Status  = (cps.Progressor.Value * 100 / cps.Progressor.Max) + @" % Completed";
                    cps.Progressor.Message = editOper.ProgressMessage;
                    editOper.BuildParcelsByRecord(_parcelFabricLayer, guid);
                    if (!editOper.Execute())
                    {
                        return(new Tuple <string, int>($@"Error [{editOper.Name}]: {editOper.ErrorMessage}", importedCount));
                    }
                }
                catch (Exception ex)
                {
                    return(new Tuple <string, int>($@"Error [Exception]: {ex.Message}", importedCount));
                }
                return(new Tuple <string, int>(string.Empty, importedCount));
            }, cps.Progressor);

            return(result);
        }
Exemplo n.º 32
0
        /// <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 override async Task <bool> OnSketchCompleteAsync(Geometry geometry)
        {
            if (geometry == null)
            {
                return(false);
            }

            // Create an edit operation
            var createOperation = new EditOperation()
            {
                Name = "Create Transformer Bank",
                SelectNewFeatures = true
            };

            bool   success      = false;
            string errorMessage = "";

            await QueuedTask.Run(() =>
            {
                Map map = GetMap();

                using (UtilityNetwork utilityNetwork = GetUtilityNetwork())
                {
                    if (utilityNetwork == null)
                    {
                        errorMessage = "Please select a layer that participates in a utility network.";
                    }
                    else
                    {
                        if (!ValidateDataModel(utilityNetwork))
                        {
                            errorMessage = "This sample is designed for a different utility network data model";
                        }
                        else
                        {
                            using (UtilityNetworkDefinition utilityNetworkDefinition = utilityNetwork.GetDefinition())
                                // Get the NetworkSource, FeatureClass, AssetGroup, and AssetTypes for all of the features we want to create
                                // The existence of these values has already been confirmed in the ValidateDataModel() routine

                                // TransformerBank
                                using (NetworkSource transformerBankNetworkSource = GetNetworkSource(utilityNetworkDefinition, AssemblyNetworkSourceName))
                                    using (FeatureClass transformerBankFeatureClass = utilityNetwork.GetTable(transformerBankNetworkSource) as FeatureClass)
                                        using (AssetGroup transformerBankAssetGroup = transformerBankNetworkSource.GetAssetGroup(TransformerBankAssetGroupName))
                                            using (AssetType transformerBankAssetType = transformerBankAssetGroup.GetAssetType(TransformerBankAssetTypeName))

                                                // Transformer
                                                using (NetworkSource deviceNetworkSource = GetNetworkSource(utilityNetworkDefinition, DeviceNetworkSourceName))
                                                    using (FeatureClass deviceFeatureClass = utilityNetwork.GetTable(deviceNetworkSource) as FeatureClass)
                                                        using (AssetGroup transformerAssetGroup = deviceNetworkSource.GetAssetGroup(TransformerAssetGroupName))
                                                            using (AssetType transformerAssetType = transformerAssetGroup.GetAssetType(TransformerAssetTypeName))

                                                                // Arrester
                                                                using (AssetGroup arresterAssetGroup = deviceNetworkSource.GetAssetGroup(ArresterAssetGroupName))
                                                                    using (AssetType arresterAssetType = arresterAssetGroup.GetAssetType(ArresterAssetTypeName))

                                                                        // Fuse
                                                                        using (AssetGroup fuseAssetGroup = deviceNetworkSource.GetAssetGroup(FuseAssetGroupName))
                                                                            using (AssetType fuseAssetType = fuseAssetGroup.GetAssetType(FuseAssetTypeName))
                                                                            {
                                                                                MapPoint clickPoint = geometry as MapPoint;

                                                                                // Create a transformer bank

                                                                                RowToken token = createOperation.Create(transformerBankFeatureClass, CreateAttributes(transformerBankAssetGroup, transformerBankAssetType, clickPoint));
                                                                                RowHandle transformerBankHandle = new RowHandle(token);

                                                                                // Create three transformers, one for each phase

                                                                                MapPoint transformerPointA = CreateOffsetMapPoint(clickPoint, -1 * XOffset, YOffset);
                                                                                token = createOperation.Create(deviceFeatureClass, CreateDeviceAttributes(transformerAssetGroup, transformerAssetType, transformerPointA, APhase));
                                                                                RowHandle transformerHandleA = new RowHandle(token);

                                                                                MapPoint transformerPointB = CreateOffsetMapPoint(clickPoint, 0, YOffset);
                                                                                token = createOperation.Create(deviceFeatureClass, CreateDeviceAttributes(transformerAssetGroup, transformerAssetType, transformerPointB, BPhase));
                                                                                RowHandle transformerHandleB = new RowHandle(token);

                                                                                MapPoint transformerPointC = CreateOffsetMapPoint(clickPoint, XOffset, YOffset);
                                                                                token = createOperation.Create(deviceFeatureClass, CreateDeviceAttributes(transformerAssetGroup, transformerAssetType, transformerPointC, CPhase));
                                                                                RowHandle transformerHandleC = new RowHandle(token);

                                                                                // Create containment associations between the bank and the transformers
                                                                                AssociationDescription containmentAssociationDescription = new AssociationDescription(AssociationType.Containment, transformerBankHandle, transformerHandleA, false);
                                                                                createOperation.Create(containmentAssociationDescription);

                                                                                containmentAssociationDescription = new AssociationDescription(AssociationType.Containment, transformerBankHandle, transformerHandleB, false);
                                                                                createOperation.Create(containmentAssociationDescription);

                                                                                containmentAssociationDescription = new AssociationDescription(AssociationType.Containment, transformerBankHandle, transformerHandleC, false);
                                                                                createOperation.Create(containmentAssociationDescription);

                                                                                // Find the high-side terminal for transformers
                                                                                TerminalConfiguration transformerTerminalConfiguration = transformerAssetType.GetTerminalConfiguration();
                                                                                IReadOnlyList <Terminal> terminals = transformerTerminalConfiguration.Terminals;
                                                                                Terminal highSideTerminal          = terminals.First(x => x.IsUpstreamTerminal == true);
                                                                                long highSideTerminalID            = highSideTerminal.ID;

                                                                                // Create three fuses, one for each phase

                                                                                MapPoint fusePointA = CreateOffsetMapPoint(clickPoint, -1 * XOffset, 2 * YOffset);
                                                                                token = createOperation.Create(deviceFeatureClass, CreateDeviceAttributes(fuseAssetGroup, fuseAssetType, fusePointA, APhase));
                                                                                RowHandle fuseHandleA = new RowHandle(token);

                                                                                MapPoint fusePointB = CreateOffsetMapPoint(clickPoint, 0, 2 * YOffset);
                                                                                token = createOperation.Create(deviceFeatureClass, CreateDeviceAttributes(fuseAssetGroup, fuseAssetType, fusePointB, BPhase));
                                                                                RowHandle fuseHandleB = new RowHandle(token);

                                                                                MapPoint fusePointC = CreateOffsetMapPoint(clickPoint, XOffset, 2 * YOffset);
                                                                                token = createOperation.Create(deviceFeatureClass, CreateDeviceAttributes(fuseAssetGroup, fuseAssetType, fusePointC, CPhase));
                                                                                RowHandle fuseHandleC = new RowHandle(token);

                                                                                // Create containment associations between the bank and the fuses
                                                                                containmentAssociationDescription = new AssociationDescription(AssociationType.Containment, transformerBankHandle, fuseHandleA, false);
                                                                                createOperation.Create(containmentAssociationDescription);

                                                                                containmentAssociationDescription = new AssociationDescription(AssociationType.Containment, transformerBankHandle, fuseHandleB, false);
                                                                                createOperation.Create(containmentAssociationDescription);

                                                                                containmentAssociationDescription = new AssociationDescription(AssociationType.Containment, transformerBankHandle, fuseHandleC, false);
                                                                                createOperation.Create(containmentAssociationDescription);

                                                                                // Connect the high-side transformer terminals to the fuses (connect the A-phase transformer to the A-phase fuse, and so on)
                                                                                AssociationDescription connectivityAssociationDescription = new AssociationDescription(AssociationType.JunctionJunctionConnectivity, transformerHandleA, highSideTerminalID, fuseHandleA);
                                                                                createOperation.Create(connectivityAssociationDescription);

                                                                                connectivityAssociationDescription = new AssociationDescription(AssociationType.JunctionJunctionConnectivity, transformerHandleB, highSideTerminalID, fuseHandleB);
                                                                                createOperation.Create(connectivityAssociationDescription);

                                                                                connectivityAssociationDescription = new AssociationDescription(AssociationType.JunctionJunctionConnectivity, transformerHandleC, highSideTerminalID, fuseHandleC);
                                                                                createOperation.Create(connectivityAssociationDescription);

                                                                                // Create three arresters, one for each phase

                                                                                MapPoint arresterPointA = CreateOffsetMapPoint(clickPoint, -1 * XOffset, 3 * YOffset);
                                                                                token = createOperation.Create(deviceFeatureClass, CreateDeviceAttributes(arresterAssetGroup, arresterAssetType, arresterPointA, APhase));
                                                                                RowHandle arresterHandleA = new RowHandle(token);

                                                                                MapPoint arresterPointB = CreateOffsetMapPoint(clickPoint, 0, 3 * YOffset);
                                                                                token = createOperation.Create(deviceFeatureClass, CreateDeviceAttributes(arresterAssetGroup, arresterAssetType, arresterPointB, BPhase));
                                                                                RowHandle arresterHandleB = new RowHandle(token);

                                                                                MapPoint arresterPointC = CreateOffsetMapPoint(clickPoint, XOffset, 3 * YOffset);
                                                                                token = createOperation.Create(deviceFeatureClass, CreateDeviceAttributes(arresterAssetGroup, arresterAssetType, arresterPointC, CPhase));
                                                                                RowHandle arresterHandleC = new RowHandle(token);

                                                                                // Create containment associations between the bank and the arresters
                                                                                containmentAssociationDescription = new AssociationDescription(AssociationType.Containment, transformerBankHandle, arresterHandleA, false);
                                                                                createOperation.Create(containmentAssociationDescription);

                                                                                containmentAssociationDescription = new AssociationDescription(AssociationType.Containment, transformerBankHandle, arresterHandleB, false);
                                                                                createOperation.Create(containmentAssociationDescription);

                                                                                containmentAssociationDescription = new AssociationDescription(AssociationType.Containment, transformerBankHandle, arresterHandleC, false);
                                                                                createOperation.Create(containmentAssociationDescription);

                                                                                // Create connectivity associations between the fuses and the arresters (connect the A-phase fuse the A-phase arrester, and so on)
                                                                                connectivityAssociationDescription = new AssociationDescription(AssociationType.JunctionJunctionConnectivity, fuseHandleA, arresterHandleA);
                                                                                createOperation.Create(connectivityAssociationDescription);

                                                                                connectivityAssociationDescription = new AssociationDescription(AssociationType.JunctionJunctionConnectivity, fuseHandleB, arresterHandleB);
                                                                                createOperation.Create(connectivityAssociationDescription);

                                                                                connectivityAssociationDescription = new AssociationDescription(AssociationType.JunctionJunctionConnectivity, fuseHandleC, arresterHandleC);
                                                                                createOperation.Create(connectivityAssociationDescription);

                                                                                // Execute the edit operation, which creates all of the rows and associations
                                                                                success = createOperation.Execute();

                                                                                if (!success)
                                                                                {
                                                                                    errorMessage = createOperation.ErrorMessage;
                                                                                }
                                                                            }
                        }
                    }
                }
            });

            if (!success)
            {
                MessageBox.Show(errorMessage, "Create Transformer Bank Tool");
            }
            return(success);
        }
    /// <summary>
    /// Separate a selected multipart feature into individual features.
    /// </summary>
    protected override void OnClick()
    {
      //check for one selected feature
      if (MapView.Active.Map.SelectionCount != 1)
      {
        MessageBox.Show("Please select one multipart feature to explode", "Explode Multipart Feature");
        return;
      }

      //run on MCT
      QueuedTask.Run(() =>
      {
        //get selected feature geometry
        var selectedFeatures = MapView.Active.Map.GetSelection();
        var insp = new Inspector();
        insp.Load(selectedFeatures.Keys.First(), selectedFeatures.Values.First());
        var selGeom = insp.Shape;
        var selGeomType = selGeom.GeometryType;

        //early checks for geometry type and single point in a multipoint
        if ( !(selGeomType == GeometryType.Multipoint || selGeomType == GeometryType.Polygon || selGeomType == GeometryType.Polyline) || selGeom.PointCount == 1)
        {
          MessageBox.Show("Please select a multipart feature to explode", "Explode Multipart Feature");
          return;
        }

        //check if selected feature has multiple parts
        var mpGeom = selGeom as Multipart;
        if (mpGeom != null)
          if (mpGeom.PartCount < 2)
          {
            MessageBox.Show("Please select a multipart feature to explode","Explode Multipart Feature");
            return;
          }

        //setup the edit operation
        var op = new EditOperation();
        op.Name = "Explode Multipart Feature";

        //handle geometry types
        switch(selGeomType)
        {
          case GeometryType.Multipoint:
            //create a new feature for each pointcount
            var mpoint = selGeom as Multipoint;
            for (var i = 0; i < mpoint.PointCount; i++)
            {
              //copy the original feature into a dictionary and update the shape.
              var newFeature = insp.ToDictionary(a => a.FieldName, a => a.CurrentValue);
              newFeature[insp.GeometryAttribute.FieldName] = new MultipointBuilder(mpoint.Points[i]).ToGeometry();
              op.Create(insp.MapMember, newFeature);
            }
            break;

          case GeometryType.Polyline:
            //create a new feature for each polyline part
            for (var i = 0; i < mpGeom.PartCount; i++)
            {
              //copy the original feature into a dictionary and update the shape.
              var newFeature = insp.ToDictionary(a => a.FieldName, a => a.CurrentValue);
              newFeature[insp.GeometryAttribute.FieldName] = new PolylineBuilder(mpGeom.Parts[i]).ToGeometry();
              op.Create(insp.MapMember, newFeature);
            }
          break;

          case GeometryType.Polygon:
            //ignore donut features for now
            //check if any part area is negative
            for (var i = 0; i < mpGeom.PartCount; i++)
            {
              if ((new PolygonBuilder(mpGeom.Parts[i]).ToGeometry()).Area < 0)
              {
                MessageBox.Show("Please select a non-donut polygon to explode", "Explode Mutltpart Feature");
                return;
              }
            }

            //create a new feature for each polygon part
            for (var i = 0; i < mpGeom.PartCount; i++)
            {
              //copy the original feature into a dictionary and update the shape.
              var newFeature = insp.ToDictionary(a => a.FieldName, a => a.CurrentValue);
              newFeature[insp.GeometryAttribute.FieldName] = new PolygonBuilder(mpGeom.Parts[i]).ToGeometry();
              op.Create(insp.MapMember, newFeature);
            }
            break;
        } //switch

        //delete the original feature and execute the creates
        //op.Delete(insp.MapMember, insp.ObjectID);
        //double cast to workaround 1.1 bug
        op.Delete(insp.MapMember, (long)(int)insp.ObjectIDAttribute.CurrentValue);
        op.Execute();
      });
    }
        protected override Task <bool> OnSketchCompleteAsync(Geometry geometry)
        {
            // execute on the MCT
            return(QueuedTask.Run(() =>
            {
                // find features under the sketch
                var features = MapView.Active.GetFeatures(geometry);
                if (features.Count == 0)
                {
                    return false;
                }

                EditOperation op = null;
                foreach (var annoLayer in features.Keys)
                {
                    // is it an anno layer?
                    if (!(annoLayer is AnnotationLayer))
                    {
                        continue;
                    }

                    // are there features?
                    var featOids = features[annoLayer];
                    if (featOids.Count == 0)
                    {
                        continue;
                    }

                    // for each feature
                    foreach (var oid in featOids)
                    {
                        // create the edit operation
                        if (op == null)
                        {
                            op = new EditOperation();
                            op.Name = "Update annotation symbol";
                            op.SelectModifiedFeatures = true;
                            op.SelectNewFeatures = false;
                        }

                        // use the callback method
                        op.Callback(context =>
                        {
                            // find the feature
                            QueryFilter qf = new QueryFilter();
                            qf.WhereClause = "OBJECTID = " + oid.ToString();

                            // use the table
                            using (var table = annoLayer.GetTable())
                            {
                                // make sure you use a non-recycling cursor
                                using (var rowCursor = table.Search(qf, false))
                                {
                                    rowCursor.MoveNext();
                                    if (rowCursor.Current != null)
                                    {
                                        ArcGIS.Core.Data.Mapping.AnnotationFeature annoFeature = rowCursor.Current as ArcGIS.Core.Data.Mapping.AnnotationFeature;
                                        if (annoFeature != null)
                                        {
                                            // get the CIMTextGraphic
                                            var textGraphic = annoFeature.GetGraphic() as CIMTextGraphic;
                                            if (textGraphic != null)
                                            {
                                                // change the text
                                                textGraphic.Text = "Hello World";

                                                // get the symbol reference
                                                var cimSymbolReference = textGraphic.Symbol;
                                                string symbolName = cimSymbolReference.SymbolName;
                                                // get the symbol
                                                var cimSymbol = cimSymbolReference.Symbol;

                                                // change the color to red
                                                cimSymbol.SetColor(ColorFactory.Instance.RedRGB);

                                                //// change the horizontal alignment
                                                //var cimTextSymbol = cimSymbol as CIMTextSymbol;
                                                //cimTextSymbol.HorizontalAlignment = HorizontalAlignment.Center;

                                                try
                                                {
                                                    // update the graphic
                                                    annoFeature.SetGraphic(textGraphic);
                                                    // store
                                                    annoFeature.Store();

                                                    // refresh the cache
                                                    context.Invalidate(annoFeature);
                                                }

                                                // SetGraphic can throw a GeodatabaseException if the AnnotationFeatureClassDefinition AreSymbolOverridesAllowed = false
                                                //  or if IsSymbolIDRequired = true and the symbol edit you're making causes the symbol to be disconnected from the symbol collection.
                                                //   see http://pro.arcgis.com/en/pro-app/sdk/api-reference/#topic17424.html
                                                //   and http://pro.arcgis.com/en/pro-app/sdk/api-reference/#topic17432.html
                                                catch (GeodatabaseException ex)
                                                {
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }, annoLayer.GetTable());
                    }
                }

                // execute the operation
                if ((op != null) && !op.IsEmpty)
                {
                    return op.Execute();
                }
                return
                false;
            }));
        }
Exemplo n.º 35
0
 public void Insert(int index, EditOperation operation)
 {
     alignment.Insert(index, operation);
     IncreaseCounters(operation);
 }
        /// <summary>
        /// This method will
        /// 1. Make sure if a Feature Layer is selected.
        /// 2. The Workspace is not null
        /// 3. Make sure that the workspace is an Enterprise SQL Server Geodatabase Workspace
        ///
        /// and then create a new version (In a Queued Task)
        /// and Connect to the newly created version and delete all the features for the selected subtype (In a separate QueuedTask)
        /// </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;
            }

            Layer        layer        = MapView.Active.GetSelectedLayers()[0];
            FeatureLayer featureLayer = null;

            if (layer is FeatureLayer)
            {
                featureLayer = layer as FeatureLayer;
                Geodatabase geodatabase = null;
                await QueuedTask.Run(() => geodatabase = (featureLayer.GetTable().GetDatastore() as Geodatabase));

                using (geodatabase)
                {
                    if (geodatabase == null)
                    {
                        return;
                    }
                }
            }
            else
            {
                return;
            }

            EnterpriseDatabaseType enterpriseDatabaseType = EnterpriseDatabaseType.Unknown;
            await QueuedTask.Run(() =>
            {
                using (Table table = (MapView.Active.GetSelectedLayers()[0] as FeatureLayer).GetTable())
                {
                    try
                    {
                        var geodatabase        = table.GetDatastore() as Geodatabase;
                        enterpriseDatabaseType = (geodatabase.GetConnector() as DatabaseConnectionProperties).DBMS;
                    }
                    catch (InvalidOperationException)
                    {
                    }
                }
            });

            if (enterpriseDatabaseType != EnterpriseDatabaseType.SQLServer)
            {
                Enabled = false;
                return;
            }

            string versionName = String.Empty;
            await QueuedTask.Run(async() =>
            {
                using (Table table = featureLayer.GetTable())
                {
                    versionName = await CreateVersion(table);
                }
            });

            if (versionName == null)
            {
                return;
            }

            await QueuedTask.Run(() =>
            {
                using (Table table = featureLayer.GetTable())
                {
                    if (table.GetRegistrationType().Equals(RegistrationType.Nonversioned))
                    {
                        return;
                    }
                }
            });


            await QueuedTask.Run(async() =>
            {
                using (Table table = featureLayer.GetTable())
                {
                    string subtypeField     = table.GetDefinition().GetSubtypeField();
                    int code                = table.GetDefinition().GetSubtypes().First(subtype => subtype.GetName().Equals(item.Text)).GetCode();
                    QueryFilter queryFilter = new QueryFilter {
                        WhereClause = string.Format("{0} = {1}", subtypeField, code)
                    };
                    try
                    {
                        VersionManager versionManager     = (table.GetDatastore() as Geodatabase).GetVersionManager();
                        Version newVersion                = versionManager.GetVersions().First(version => version.GetName().Contains(versionName));
                        Geodatabase newVersionGeodatabase = newVersion.Connect();
                        using (Table newVersionTable = newVersionGeodatabase.OpenDataset <Table>(table.GetName()))
                        {
                            using (var rowCursor = newVersionTable.Search(queryFilter, false))
                            {
                                EditOperation editOperation = new EditOperation
                                {
                                    EditOperationType = EditOperationType.Long,
                                    Name = "Delete Based On Subtype"
                                };

                                editOperation.Callback(context =>
                                {
                                    while (rowCursor.MoveNext())
                                    {
                                        using (Row row = rowCursor.Current)
                                        {
                                            context.Invalidate(row);
                                            row.Delete();
                                        }
                                    }
                                }, newVersionTable);
                                bool result = await editOperation.ExecuteAsync();
                                if (!result)
                                {
                                    MessageBox.Show(String.Format("Could not delete features for subtype {0} : {1}",
                                                                  item.Text, editOperation.ErrorMessage));
                                }
                                await Project.Current.SaveEditsAsync();
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e);
                    }
                }
            });
        }
Exemplo n.º 37
0
        /// <summary>
        /// Internal execution fonction to toggle switches
        /// </summary>
        /// <returns>An error comment if needed, empty of no error</returns>
        private static string ToggleSwitchesExecute()
        {
            bool canUpdate = false;

            // Load all Diagram Element and selection
            if (!IsDiagramUsable(GetAllElements: false, GetSelection: true))
            {
                return("");
            }

            if (GlobalSelectedJunctionIDs.Count == 0)
            {
                return("There are no junction selected");
            }

            Dictionary <long, List <Guid> > guidBySourceId = new Dictionary <long, List <Guid> >();

            // retrieve the junctions GlobalId
            foreach (long oid in GlobalSelectedJunctionIDs)
            {
                DiagramJunctionElement junctionElement = GlobalDiagramJunctionElements.FirstOrDefault(a => a.ObjectID == oid);
                if (junctionElement != null)
                {
                    if (!guidBySourceId.TryGetValue(junctionElement.AssociatedSourceID, out List <Guid> guidList))
                    {
                        guidList = new List <Guid>();
                        guidBySourceId.Add(junctionElement.AssociatedSourceID, guidList);
                    }

                    if (!guidList.Contains(junctionElement.AssociatedGlobalID))
                    {
                        guidList.Add(junctionElement.AssociatedGlobalID);
                    }
                }
            }

            IReadOnlyList <NetworkSource> theSources = GlobalUtilityNetwork.GetDefinition().GetNetworkSources();

            List <string> searchFields = new List <string> {
                cDeviceStatusFieldName, "ObjectId", "AssetGroup"
            };

            foreach (NetworkSource source in theSources)
            {
                if (guidBySourceId.TryGetValue(source.ID, out List <Guid> guidList))
                {
                    // Get a cursor of guid list, get the qualified fields name
                    using (RowCursor sel = GetRowCursorFromSourceNameAndGuidList(SourceName: source.Name.Replace(" ", ""), SearchGuid: guidList, ListSearchFields: searchFields, WhereField: "GlobalId", FieldsName: out List <Tuple <string, string> > FieldsName))
                    {
                        int deviceStatusIndex = -1;
                        int assetGroupIndex   = -1;
                        // retrieved the fields indexes
                        foreach (Tuple <string, string> findTuple in FieldsName)
                        {
                            if (findTuple.Item1 == cDeviceStatusFieldName)
                            {
                                deviceStatusIndex = sel.FindField(findTuple.Item2);
                            }
                            else if (findTuple.Item1 == "AssetGroup")
                            {
                                assetGroupIndex = sel.FindField(findTuple.Item2);
                            }
                        }

                        if (deviceStatusIndex >= 0) // run only if there is a device status
                        {
                            var modifyStringsOperation = new EditOperation
                            {
                                Name = String.Format("Modify string field '{0}' in source {1}.", cDeviceStatusFieldName, source.Name)
                            };

                            ICollection <long> oidSet = new List <long>();
                            while (sel.MoveNext())
                            {
                                string AssetGroupValue = sel.Current[assetGroupIndex].ToString();
                                // verify if the Asset Group is correct
                                if (!String.IsNullOrEmpty(AssetGroupValue) && AssetGroupValue == cAssetGroupFieldValue)
                                {
                                    string deviceStatus  = sel.Current[deviceStatusIndex]?.ToString();
                                    Guid   globalIdValue = sel.Current.GetGlobalID();
                                    long   oid           = sel.Current.GetObjectID();

                                    // set up a new dictionary with fields to modify
                                    var modifiedAttributes = new Dictionary <string, object>
                                    {
                                        // add the name of the string field and the new attribute value to the dictionary
                                        { cDeviceStatusFieldName, deviceStatus == "2" ? 1 : 2 }
                                    };

                                    // put the modify operation on the editor stack
                                    modifyStringsOperation.Modify(sel.Current, modifiedAttributes);
                                    oidSet.Add(oid);
                                }
                            }

                            if (oidSet.Count > 0)
                            { // execute the modify operation to apply the changes
                                modifyStringsOperation.Execute();
                                canUpdate = true;
                            }
                            else
                            {
                                modifyStringsOperation.Abort();
                            }
                        }
                    }
                }
            }

            return(canUpdate ? "" : "This command only applies to medium voltage switches. Please make sure there is at least one selected medium voltage switch in the active diagram before its execution.");
        }
Exemplo n.º 38
0
        private async Task <string> CopyParcelsToLotAsync(CancelableProgressorSource cps)
        {
            var error = await QueuedTask.Run <string>(() =>
            {
                // copy tax parcels to lot
                try
                {
                    if (_parcelFabricLayer == null)
                    {
                        return("There is no parcel fabric in the map.");
                    }
                    var theActiveRecord = _parcelFabricLayer.GetActiveRecord();
                    if (theActiveRecord == null)
                    {
                        return("There is no Active Record for the Parcel Fabric");
                    }
                }
                catch (Exception ex)
                {
                    return($@"Error [Exception]: {ex.Message}");
                }
                try
                {
                    // use CopyParcelLinesToParcelType to copy the tax parcels to the lot parcel type
                    var editOper = new EditOperation()
                    {
                        Name            = "Copy Lines To Lot Parcel Type",
                        ProgressMessage = "Copy Lines To Lot Parcel Type ...",
                        ShowModalMessageAfterFailure = false,
                        SelectNewFeatures            = false,
                        SelectModifiedFeatures       = false
                    };
                    var qry = $@"{FieldNameZone} = {_selectedZone} and {FieldNameSect} = {_selectedSection} and {FieldNamePlat} = '{_selectedPlat}'";
                    SelectSetAndZoomAsync(_taxLayerPolys, qry);
                    var ids = new List <long>(_taxLayerPolys.GetSelection().GetObjectIDs());
                    if (ids.Count == 0)
                    {
                        return("No selected parcels found. Please select parcels and try again.");
                    }
                    //add the standard feature line layers source, and their feature ids to a new KeyValuePair
                    //var kvp = new KeyValuePair<MapMember, List<long>>(_taxLayerPolys, ids);
                    //var sourceParcelFeatures = new List<KeyValuePair<MapMember, List<long>>> { kvp };

                    var selectionDictionary = new Dictionary <MapMember, List <long> >();
                    selectionDictionary.Add(_taxLayerPolys, ids);

                    editOper.CopyParcelLinesToParcelType(_parcelFabricLayer, SelectionSet.FromDictionary(selectionDictionary), _lotLayerLines, _lotLayerPolys, false, true, true);
                    if (!editOper.Execute())
                    {
                        return(editOper.ErrorMessage);
                    }
                }
                catch (Exception ex)
                {
                    return($@"Error [Exception]: {ex.Message}");
                }
                try
                {
                    // Build all Parcels for the Active record in the parcel fabric (set in step one)
                    var theActiveRecord = _parcelFabricLayer.GetActiveRecord();
                    var guid            = theActiveRecord.Guid;
                    var editOper        = new EditOperation()
                    {
                        Name            = "Build Parcels",
                        ProgressMessage = "Build Parcels...",
                        ShowModalMessageAfterFailure = true,
                        SelectNewFeatures            = true,
                        SelectModifiedFeatures       = true
                    };
                    cps.Progressor.Value += 1;
                    if (cps.Progressor.CancellationToken.IsCancellationRequested)
                    {
                        editOper.Abort();
                        return("Canceled");
                    }
                    cps.Progressor.Status  = (cps.Progressor.Value * 100 / cps.Progressor.Max) + @" % Completed";
                    cps.Progressor.Message = editOper.ProgressMessage;
                    editOper.BuildParcelsByRecord(_parcelFabricLayer, guid);
                    if (!editOper.Execute())
                    {
                        return($@"Error [{editOper.Name}]: {editOper.ErrorMessage}");
                    }
                }
                catch (Exception ex)
                {
                    return($@"Error [Exception]: {ex.Message}");
                }
                return(string.Empty);
            }, cps.Progressor);

            return(error);
        }
Exemplo n.º 39
0
    public void LoadData()
    {
        string id = string.Format("Id: {0} Uri: {1}", Guid.NewGuid(), HttpContext.Current.Request.Url);

        using (Utils utility = new Utils())
        {
            utility.MethodStart(id, System.Reflection.MethodBase.GetCurrentMethod());
        }
        try
        {
            EditOperation _objEdit = new EditOperation();
            _objEdit.Primary_Value = TXT_I_EVENT.Text;
            _objEdit.WebPage       = this.Page;
            _objEdit.Xml_File      = "Patient_Intake3.xml";
            _objEdit.LoadData();

            if (txtrdblstTREATED_PREVIOUSLY.Text != "")
            {
                rdblstTREATED_PREVIOUSLY.SelectedValue = txtrdblstTREATED_PREVIOUSLY.Text;
            }

            if (txtrdblstDO_YOU_WORK.Text != "")
            {
                rdblstDO_YOU_WORK.SelectedValue = txtrdblstDO_YOU_WORK.Text;
            }
            if (txtrdblstTAKING_MEDICATION.Text != "")
            {
                rdblstTAKING_MEDICATION.SelectedValue = txtrdblstTAKING_MEDICATION.Text;
            }

            if (txtrdblstALLERGIC_TO_DRUGS.Text != "")
            {
                rdblstALLERGIC_TO_DRUGS.SelectedValue = txtrdblstALLERGIC_TO_DRUGS.Text;
            }

            if (txtrdblstDO_YOU_SMOKE.Text != "")
            {
                rdblstDO_YOU_SMOKE.SelectedValue = txtrdblstDO_YOU_SMOKE.Text;
            }
            if (txtrdblstSUFFER_ALLERGIES.Text != "")
            {
                rdblstSUFFER_ALLERGIES.SelectedValue = txtrdblstSUFFER_ALLERGIES.Text;
            }
            if (txtrdblstHAD_SURGERY.Text != "")
            {
                rdblstHAD_SURGERY.SelectedValue = txtrdblstHAD_SURGERY.Text;
            }
            if (txtrdblstARE_YOU_PREGNANT.Text != "")
            {
                rdblstARE_YOU_PREGNANT.SelectedValue = txtrdblstARE_YOU_PREGNANT.Text;
            }
        }
        catch (Exception ex)
        {
            Elmah.ErrorSignal.FromCurrentContext().Raise(ex);
            using (Utils utility = new Utils())
            {
                utility.MethodEnd(id, System.Reflection.MethodBase.GetCurrentMethod());
            }
            string str2 = "Error Request=" + id + ".Please share with Technical support.";
            base.Response.Redirect("Bill_Sys_ErrorPage.aspx?ErrMsg=" + str2);
        }
        //Method End
        using (Utils utility = new Utils())
        {
            utility.MethodEnd(id, System.Reflection.MethodBase.GetCurrentMethod());
        }
    }
Exemplo n.º 40
0
 private static EditOperation CreateOperationAndBuildInitialEnvelope(ref EnvelopeBuilder envBuilder, ref ArcGIS.Core.Geometry.Envelope env)
 {
     var createOperation = new EditOperation();
     createOperation.Name = "Highlight Design Features";
     createOperation.SelectNewFeatures = false;
     if (envBuilder == null)
     {
         envBuilder = new EnvelopeBuilder();
         envBuilder.XMin = 0;
         envBuilder.XMax = 0;
         envBuilder.YMin = 0;
         envBuilder.YMax = 0;
         env = envBuilder.ToGeometry().Extent;
     }
     return createOperation;
 }
        /// <summary>
        /// Method to perform the cut operation on the geometry and change attributes
        /// </summary>
        /// <param name="geometry">Line geometry used to perform the cut against in the polygon features
        /// in the active map view.</param>
        /// <returns>If the cut operation was successful.</returns>
        protected Task <bool> ExecuteCut(Geometry geometry)
        {
            if (geometry == null)
            {
                return(Task.FromResult(false));
            }

            // create a collection of feature layers that can be edited
            var editableLayers = ActiveMapView.Map.GetLayersAsFlattenedList()
                                 .OfType <FeatureLayer>()
                                 .Where(lyr => lyr.CanEditData() == true).Where(lyr =>
                                                                                lyr.ShapeType == esriGeometryType.esriGeometryPolygon);

            // ensure that there are target layers
            if (editableLayers.Count() == 0)
            {
                return(Task.FromResult(false));
            }

            // create an edit operation
            EditOperation cutOperation = new EditOperation();

            cutOperation.Name                   = "Cut Elements";
            cutOperation.ProgressMessage        = "Working...";
            cutOperation.CancelMessage          = "Operation canceled.";
            cutOperation.ErrorMessage           = "Error cutting polygons";
            cutOperation.SelectModifiedFeatures = false;
            cutOperation.SelectNewFeatures      = false;

            // initialize a list of ObjectIDs that need to be cut
            var cutOIDs = new List <long>();

            // for each of the layers
            foreach (FeatureLayer editableFeatureLayer in editableLayers)
            {
                // find the features crossed by the sketch geometry
                var rowCursor = editableFeatureLayer.Search(geometry, SpatialRelationship.Crosses);

                // get the feature class associated with the layer
                Table fc = editableFeatureLayer.GetTable();

                // find the field index for the 'Description' attribute
                int descriptionIndex = -1;
                descriptionIndex = fc.GetDefinition().FindField("Description");

                // add the feature IDs into our prepared list
                while (rowCursor.MoveNext())
                {
                    var feature = rowCursor.Current as Feature;
                    if (feature.GetShape() != null)
                    {
                        // we are looking for polygons are completely intersected by the cut line
                        if (GeometryEngine.Relate(geometry, feature.GetShape(), "TT*F*****"))
                        {
                            // add the current feature to the overall list of features to cut
                            cutOIDs.Add(rowCursor.Current.GetObjectID());

                            // adjust the attribute before the cut
                            if (descriptionIndex != -1)
                            {
                                cutOperation.Modify(rowCursor.Current, descriptionIndex, "Pro Sample");
                            }
                        }
                    }
                }
                // add the elements to cut into the edit operation
                cutOperation.Cut(editableFeatureLayer, cutOIDs, geometry);
            }

            //execute the operation
            var operationResult = cutOperation.Execute();

            return(Task.FromResult(operationResult));
        }
Exemplo n.º 42
0
        /// <summary>
        /// Divide the first selected feature into equal parts or by map unit distance.
        /// </summary>
        /// <param name="numberOfParts">Number of parts to create.</param>
        /// <param name="value">Value for number or parts or distance.</param>
        /// <returns></returns>
        private static Task DivideLinesAsync(bool numberOfParts, double value)
        {
            //Run on MCT
            return(QueuedTask.Run(() =>
            {
                //get selected feature
                var selectedFeatures = MapView.Active.Map.GetSelection();

                //get the layer of the selected feature
                var featLayer = selectedFeatures.Keys.First() as FeatureLayer;
                var oid = selectedFeatures.Values.First().First();

                var feature = featLayer.Inspect(oid);

                //get geometry and length
                var origPolyLine = feature.Shape as Polyline;
                var origLength = GeometryEngine.Instance.Length(origPolyLine);

                string xml = origPolyLine.ToXML();

                //List of mappoint geometries for the split
                var splitPoints = new List <MapPoint>();

                var enteredValue = (numberOfParts) ? origLength / value : value;
                var splitAtDistance = 0 + enteredValue;

                while (splitAtDistance < origLength)
                {
                    //create a mapPoint at splitDistance and add to splitpoint list
                    MapPoint pt = null;
                    try
                    {
                        pt = GeometryEngine.Instance.MovePointAlongLine(origPolyLine, splitAtDistance, false, 0, SegmentExtension.NoExtension);
                    }
                    catch (GeometryObjectException)
                    {
                        // line is an arc?
                    }

                    if (pt != null)
                    {
                        splitPoints.Add(pt);
                    }
                    splitAtDistance += enteredValue;
                }

                if (splitPoints.Count == 0)
                {
                    ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("Divide lines was unable to process your selected line. Please select another.", "Divide Lines");
                    return;
                }
                //create and execute the edit operation
                var op = new EditOperation()
                {
                    Name = "Divide Lines",
                    SelectModifiedFeatures = false,
                    SelectNewFeatures = false
                };
                op.Split(featLayer, oid, splitPoints);
                op.Execute();

                //clear selection
                featLayer.ClearSelection();
            }));
        }