示例#1
0
        public void EditOperation2(FeatureLayer transformerBankLayer, Dictionary <string, object> transformerBankAttributes, FeatureLayer poleLayer, Dictionary <string, object> poleAttributes)
        {
            #region Create utility network features and associations in a single edit operation

            // Create an EditOperation
            EditOperation editOperation = new EditOperation();
            editOperation.Name = "Create pole; create transformer bank; attach transformer bank to pole";

            // Create the transformer bank
            RowToken transformerBankToken = editOperation.CreateEx(transformerBankLayer, transformerBankAttributes);

            // Create a pole
            RowToken poleToken = editOperation.CreateEx(poleLayer, poleAttributes);

            // Create a structural attachment association between the pole and the transformer bank
            RowHandle poleHandle            = new RowHandle(poleToken);
            RowHandle transformerBankHandle = new RowHandle(transformerBankToken);

            StructuralAttachmentAssociationDescription poleAttachment = new StructuralAttachmentAssociationDescription(poleHandle, transformerBankHandle);

            editOperation.Create(poleAttachment);

            // Execute the EditOperation
            editOperation.Execute();


            #endregion
        }
示例#2
0
        protected async void CreateNewRecord()
        {
            #region Create a new record
            await QueuedTask.Run(async() =>
            {
                Dictionary <string, object> RecordAttributes = new Dictionary <string, object>();
                var layers              = MapView.Active.Map.GetLayersAsFlattenedList();
                var recordsLayer        = layers.FirstOrDefault(l => l.Name == "Records" && l is FeatureLayer);
                var myParcelFabricLayer = layers.FirstOrDefault(l => l is ParcelLayer) as ParcelLayer;
                var spatRef             = recordsLayer.Map.SpatialReference;

                var editOper = new EditOperation()
                {
                    Name            = "Create Parcel Fabric Record",
                    ProgressMessage = "Create Parcel Fabric Record...",
                    ShowModalMessageAfterFailure = true,
                    SelectNewFeatures            = false,
                    SelectModifiedFeatures       = false
                };

                string sNewRecordName = "myNewRecord";
                Polygon newPolygon    = null;
                newPolygon            = PolygonBuilder.CreatePolygon(spatRef);
                if (newPolygon != null)
                {
                    RecordAttributes.Add("Name", sNewRecordName);
                    var editRowToken = editOper.CreateEx(recordsLayer, newPolygon, RecordAttributes);
                    RecordAttributes.Clear();
                    if (!await editOper.ExecuteAsync())
                    {
                        return;
                    }

                    //Default Guid
                    var defGuid = new Guid("dddddddd-dddd-dddd-dddd-dddddddddddd");
                    var defOID  = -1;
                    var guid    = editRowToken.GlobalID.HasValue ? editRowToken.GlobalID.Value : defGuid;
                    var lOid    = editRowToken.ObjectID.HasValue ? editRowToken.ObjectID.Value : defOID;

                    if (guid == defGuid | lOid == defOID)
                    {
                        return;
                    }

                    ParcelRecord parcelRecord = new ParcelRecord(myParcelFabricLayer.Map, sNewRecordName, guid, lOid);
                    await myParcelFabricLayer.SetActiveRecord(parcelRecord);
                }
            });

            #endregion
        }
示例#3
0
        protected async void CreateNewRecord()
        {
            #region Create a new record
            string errorMessage = await QueuedTask.Run(async() =>
            {
                Dictionary <string, object> RecordAttributes = new Dictionary <string, object>();
                string sNewRecord = "MyRecordName";
                try
                {
                    var myParcelFabricLayer = MapView.Active.Map.GetLayersAsFlattenedList().OfType <ParcelLayer>().FirstOrDefault();
                    //if there is no fabric in the map then bail
                    if (myParcelFabricLayer == null)
                    {
                        return("There is no fabric in the map.");
                    }
                    var recordsLayer = await myParcelFabricLayer.GetRecordsLayerAsync();
                    var editOper     = new EditOperation()
                    {
                        Name            = "Create Parcel Fabric Record",
                        ProgressMessage = "Create Parcel Fabric Record...",
                        ShowModalMessageAfterFailure = true,
                        SelectNewFeatures            = false,
                        SelectModifiedFeatures       = false
                    };
                    RecordAttributes.Add("Name", sNewRecord);
                    var editRowToken = editOper.CreateEx(recordsLayer.FirstOrDefault(), RecordAttributes);
                    if (!editOper.Execute())
                    {
                        return(editOper.ErrorMessage);
                    }

                    var defOID = -1;
                    var lOid   = editRowToken.ObjectID.HasValue ? editRowToken.ObjectID.Value : defOID;
                    await myParcelFabricLayer.SetActiveRecordAsync(lOid);
                }
                catch (Exception ex)
                {
                    return(ex.Message);
                }
                return("");
            });

            if (!string.IsNullOrEmpty(errorMessage))
            {
                MessageBox.Show(errorMessage, "Create New Record.");
            }
            #endregion
        }
        protected async void CreateNewRecord()
        {
            #region Create a new record
            await QueuedTask.Run(async() =>
            {
                var myParcelFabricLayer = MapView.Active.Map.GetLayersAsFlattenedList().OfType <ParcelLayer>().FirstOrDefault();

                string sNewRecordName = "myNewRecord";
                Dictionary <string, object> RecordAttributes = new Dictionary <string, object>();

                var recordsLayer = await myParcelFabricLayer.GetParcelSubLayerAsync(ParcelSubLayerType.Records);

                var editOper = new EditOperation()
                {
                    Name            = "Create Parcel Fabric Record",
                    ProgressMessage = "Create Parcel Fabric Record...",
                    ShowModalMessageAfterFailure = true,
                    SelectNewFeatures            = false,
                    SelectModifiedFeatures       = false
                };

                RecordAttributes.Add("Name", sNewRecordName);
                var editRowToken    = editOper.CreateEx(recordsLayer, RecordAttributes);
                RowHandle rowHandle = new RowHandle(editRowToken);

                if (!editOper.Execute())
                {
                    return;
                }

                long lOid = rowHandle.ObjectID.Value;
                Guid guid = rowHandle.GlobalID.Value;
                await myParcelFabricLayer.SetActiveRecordAsync(guid);
            });

            #endregion
        }
示例#5
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> ("Cancelled", 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.CreateEx(_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>("Cancelled", 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 autopopulated so we have to do this here
                        foreach (KeyValuePair <MapMember, List <long> > kvp in createdParcelFeatures)
                        {
                            if (cps.Progressor.CancellationToken.IsCancellationRequested)
                            {
                                editOperUpdate.Abort();
                                return(new Tuple <string, int>("Cancelled", 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)
                        {
                            if (cps.Progressor.CancellationToken.IsCancellationRequested)
                            {
                                editOperUpdate.Abort();
                                return(new Tuple <string, int>("Cancelled", 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>("Cancelled", 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);
        }
        public void EditOperations()
        {
            var featureLayer = MapView.Active.Map.GetLayersAsFlattenedList()[0] as FeatureLayer;
            var polygon      = new PolygonBuilder().ToGeometry();
            var clipPoly     = new PolygonBuilder().ToGeometry();
            var cutLine      = new PolylineBuilder().ToGeometry();
            var modifyLine   = cutLine;
            var oid          = 1;
            var layer        = featureLayer;

            #region Edit Operation Create Features

            var createFeatures = new EditOperation();
            createFeatures.Name = "Create Features";
            //Create a feature with a polygon
            createFeatures.Create(featureLayer, polygon);

            //with a callback
            createFeatures.Create(featureLayer, polygon, (object_id) => {
                //TODO - use the oid of the created feature
                //in your callback
            });

            //Do a create features and set attributes
            var attributes = new Dictionary <string, object>();
            attributes.Add("SHAPE", polygon);
            attributes.Add("NAME", "Corner Market");
            attributes.Add("SIZE", 1200.5);
            attributes.Add("DESCRIPTION", "Corner Market");

            createFeatures.Create(featureLayer, attributes);

            //Create features using the current template
            //Must be within a MapTool
            createFeatures.Create(this.CurrentTemplate, polygon);

            //Execute to execute the operation
            //Must be called within QueuedTask.Run
            createFeatures.Execute();

            //or use async flavor
            //await createFeatures.ExecuteAsync();

            #endregion

            #region Create a feature using the current template
            var myTemplate = ArcGIS.Desktop.Editing.Templates.EditingTemplate.Current;
            var myGeometry = _geometry;

            //Create edit operation and execute
            var op = new ArcGIS.Desktop.Editing.EditOperation();
            op.Name = "Create my feature";
            op.Create(myTemplate, myGeometry);
            op.Execute();
            #endregion

            #region Create feature from a modified inspector

            var insp = new ArcGIS.Desktop.Editing.Attributes.Inspector();
            insp.Load(layer, 86);

            ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
            {
                // modify attributes if necessary
                // insp["Field1"] = newValue;

                //Create new feature from an existing inspector (copying the feature)
                var createOp  = new ArcGIS.Desktop.Editing.EditOperation();
                createOp.Name = "Create from insp";
                createOp.Create(insp.MapMember, insp.ToDictionary(a => a.FieldName, a => a.CurrentValue));
                createOp.Execute();
            });
            #endregion

            var csvData = new List <CSVData>();

            #region Create features from a CSV file
            //Run on MCT
            ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
            {
                //Create the edit operation
                var createOperation  = new ArcGIS.Desktop.Editing.EditOperation();
                createOperation.Name = "Generate points";
                createOperation.SelectNewFeatures = false;

                // determine the shape field name - it may not be 'Shape'
                string shapeField = layer.GetFeatureClass().GetDefinition().GetShapeField();

                //Loop through csv data
                foreach (var item in csvData)
                {
                    //Create the point geometry
                    ArcGIS.Core.Geometry.MapPoint newMapPoint = ArcGIS.Core.Geometry.MapPointBuilder.CreateMapPoint(item.X, item.Y);

                    // include the attributes via a dictionary
                    var atts = new Dictionary <string, object>();
                    atts.Add("StopOrder", item.StopOrder);
                    atts.Add("FacilityID", item.FacilityID);
                    atts.Add(shapeField, newMapPoint);

                    // queue feature creation
                    createOperation.Create(layer, atts);
                }

                // execute the edit (feature creation) operation
                return(createOperation.Execute());
            });
            #endregion

            #region Edit Operation Clip Features

            var clipFeatures = new EditOperation();
            clipFeatures.Name = "Clip Features";
            clipFeatures.Clip(featureLayer, oid, clipPoly, ClipMode.PreserveArea);
            //Execute to execute the operation
            //Must be called within QueuedTask.Run
            clipFeatures.Execute();

            //or use async flavor
            //await clipFeatures.ExecuteAsync();

            #endregion

            #region Edit Operation Cut Features

            var select = MapView.Active.SelectFeatures(clipPoly);

            var cutFeatures = new EditOperation();
            cutFeatures.Name = "Cut Features";
            cutFeatures.Split(featureLayer, oid, cutLine);

            //Cut all the selected features in the active view
            //Select using a polygon (for example)
            var kvps = MapView.Active.SelectFeatures(polygon).Select(
                k => new KeyValuePair <MapMember, List <long> >(k.Key as MapMember, k.Value));
            cutFeatures.Split(kvps, cutLine);

            //Execute to execute the operation
            //Must be called within QueuedTask.Run
            cutFeatures.Execute();

            //or use async flavor
            //await cutFeatures.ExecuteAsync();

            #endregion

            #region Edit Operation Delete Features

            var deleteFeatures = new EditOperation();
            deleteFeatures.Name = "Delete Features";
            var table = MapView.Active.Map.StandaloneTables[0];
            //Delete a row in a standalone table
            deleteFeatures.Delete(table, oid);

            //Delete all the selected features in the active view
            //Select using a polygon (for example)
            var selection = MapView.Active.SelectFeatures(polygon).Select(
                k => new KeyValuePair <MapMember, List <long> >(k.Key as MapMember, k.Value));

            deleteFeatures.Delete(selection);

            //Execute to execute the operation
            //Must be called within QueuedTask.Run
            deleteFeatures.Execute();

            //or use async flavor
            //await deleteFeatures.ExecuteAsync();

            #endregion

            #region Edit Operation Duplicate Features

            var duplicateFeatures = new EditOperation();
            duplicateFeatures.Name = "Duplicate Features";

            //Duplicate with an X and Y offset of 500 map units
            duplicateFeatures.Duplicate(featureLayer, oid, 500.0, 500.0, 0.0);

            //Execute to execute the operation
            //Must be called within QueuedTask.Run
            duplicateFeatures.Execute();

            //or use async flavor
            //await duplicateFeatures.ExecuteAsync();

            #endregion

            #region Edit Operation Explode Features

            var explodeFeatures = new EditOperation();
            explodeFeatures.Name = "Explode Features";

            //Take a multipart and convert it into one feature per part
            //Provide a list of ids to convert multiple
            explodeFeatures.Explode(featureLayer, new List <long>()
            {
                oid
            }, true);

            //Execute to execute the operation
            //Must be called within QueuedTask.Run
            explodeFeatures.Execute();

            //or use async flavor
            //await explodeFeatures.ExecuteAsync();

            #endregion

            var destinationLayer = featureLayer;

            #region Edit Operation Merge Features

            var mergeFeatures = new EditOperation();
            mergeFeatures.Name = "Merge Features";

            //Merge three features into a new feature using defaults
            //defined in the current template
            mergeFeatures.Merge(this.CurrentTemplate as EditingFeatureTemplate, featureLayer, new List <long>()
            {
                10, 96, 12
            });

            //Merge three features into a new feature in the destination layer
            mergeFeatures.Merge(destinationLayer, featureLayer, new List <long>()
            {
                10, 96, 12
            });

            //Use an inspector to set the new attributes of the merged feature
            var inspector = new Inspector();
            inspector.Load(featureLayer, oid);//base attributes on an existing feature
            //change attributes for the new feature
            inspector["NAME"]        = "New name";
            inspector["DESCRIPTION"] = "New description";

            //Merge features into a new feature in the same layer using the
            //defaults set in the inspector
            mergeFeatures.Merge(featureLayer, new List <long>()
            {
                10, 96, 12
            }, inspector);

            //Execute to execute the operation
            //Must be called within QueuedTask.Run
            mergeFeatures.Execute();

            //or use async flavor
            //await mergeFeatures.ExecuteAsync();

            #endregion

            #region Edit Operation Modify single feature

            var modifyFeature = new EditOperation();
            modifyFeature.Name = "Modify a feature";

            //use an inspector
            var modifyInspector = new Inspector();
            modifyInspector.Load(featureLayer, oid);//base attributes on an existing feature

            //change attributes for the new feature
            modifyInspector["SHAPE"] = polygon;        //Update the geometry
            modifyInspector["NAME"]  = "Updated name"; //Update attribute(s)

            modifyFeature.Modify(modifyInspector);

            //update geometry and attributes using overload
            var featureAttributes = new Dictionary <string, object>();
            featureAttributes["NAME"] = "Updated name";//Update attribute(s)
            modifyFeature.Modify(featureLayer, oid, polygon, featureAttributes);

            //Execute to execute the operation
            //Must be called within QueuedTask.Run
            modifyFeature.Execute();

            //or use async flavor
            //await modifyFeatures.ExecuteAsync();

            #endregion

            #region Edit Operation Modify multiple features

            //Search by attribute
            var queryFilter = new QueryFilter();
            queryFilter.WhereClause = "OBJECTID < 1000000";
            //Create list of oids to update
            var oidSet = new List <long>();
            using (var rc = featureLayer.Search(queryFilter))
            {
                while (rc.MoveNext())
                {
                    using (var record = rc.Current)
                    {
                        oidSet.Add(record.GetObjectID());
                    }
                }
            }

            //create and execute the edit operation
            var modifyFeatures = new EditOperation();
            modifyFeatures.Name           = "Modify features";
            modifyFeatures.ShowProgressor = true;

            var muultipleFeaturesInsp = new Inspector();
            muultipleFeaturesInsp.Load(featureLayer, oidSet);
            muultipleFeaturesInsp["MOMC"] = 24;
            modifyFeatures.Modify(muultipleFeaturesInsp);
            modifyFeatures.ExecuteAsync();
            #endregion

            #region Search for layer features and update a field
            ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
            {
                //find layer
                var disLayer = ArcGIS.Desktop.Mapping.MapView.Active.Map.FindLayers("Distribution mains").FirstOrDefault() as BasicFeatureLayer;

                //Search by attribute
                var filter         = new ArcGIS.Core.Data.QueryFilter();
                filter.WhereClause = "CONTRACTOR = 'KCGM'";

                var oids = new List <long>();
                using (var rc = disLayer.Search(filter))
                {
                    //Create list of oids to update
                    while (rc.MoveNext())
                    {
                        using (var record = rc.Current)
                        {
                            oidSet.Add(record.GetObjectID());
                        }
                    }
                }

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

                // load features into inspector and update field
                var dateInsp = new ArcGIS.Desktop.Editing.Attributes.Inspector();
                dateInsp.Load(disLayer, oids);
                dateInsp["InspDate"] = "9/21/2013";

                // modify and execute
                modifyOp.Modify(insp);
                modifyOp.Execute();
            });
            #endregion

            #region Move features

            //Get all of the selected ObjectIDs from the layer.
            var firstLayer       = MapView.Active.Map.GetLayersAsFlattenedList().OfType <FeatureLayer>().FirstOrDefault();
            var selectionfromMap = firstLayer.GetSelection();

            // set up a dictionary to store the layer and the object IDs of the selected features
            var selectionDictionary = new Dictionary <MapMember, List <long> >();
            selectionDictionary.Add(firstLayer as MapMember, selectionfromMap.GetObjectIDs().ToList());

            var moveFeature = new EditOperation();
            moveFeature.Name = "Move features";
            moveFeature.Move(selectionDictionary, 10, 10); //specify your units along axis to move the geometry

            moveFeature.Execute();
            #endregion

            #region Move feature to a specific coordinate

            //Get all of the selected ObjectIDs from the layer.
            var abLayer     = MapView.Active.Map.GetLayersAsFlattenedList().OfType <FeatureLayer>().FirstOrDefault();
            var mySelection = abLayer.GetSelection();
            var selOid      = mySelection.GetObjectIDs().FirstOrDefault();

            var moveToPoint = new MapPointBuilder(1.0, 2.0, 3.0, 4.0, MapView.Active.Map.SpatialReference); //can pass in coordinates.

            var modifyFeatureCoord = new EditOperation();
            modifyFeatureCoord.Name = "Move features";
            modifyFeatureCoord.Modify(abLayer, selOid, moveToPoint.ToGeometry()); //Modify the feature to the new geometry
            modifyFeatureCoord.Execute();

            #endregion

            #region Edit Operation Planarize Features

            var planarizeFeatures = new EditOperation();
            planarizeFeatures.Name = "Planarize Features";

            //Planarize one or more features
            planarizeFeatures.Planarize(featureLayer, new List <long>()
            {
                oid
            });

            //Execute to execute the operation
            //Must be called within QueuedTask.Run
            planarizeFeatures.Execute();

            //or use async flavor
            //await planarizeFeatures.ExecuteAsync();

            #endregion

            #region Edit Operation Reshape Features

            var reshapeFeatures = new EditOperation();
            reshapeFeatures.Name = "Reshape Features";

            reshapeFeatures.Reshape(featureLayer, oid, modifyLine);

            //Reshape a set of features that intersect some geometry....
            var selFeatures = MapView.Active.GetFeatures(modifyLine).Select(
                k => new KeyValuePair <MapMember, List <long> >(k.Key as MapMember, k.Value));

            reshapeFeatures.Reshape(selFeatures, modifyLine);

            //Execute to execute the operation
            //Must be called within QueuedTask.Run
            reshapeFeatures.Execute();

            //or use async flavor
            //await reshapeFeatures.ExecuteAsync();

            #endregion

            var origin = MapPointBuilder.CreateMapPoint(0, 0, null);

            #region Edit Operation Rotate Features

            var rotateFeatures = new EditOperation();
            rotateFeatures.Name = "Rotate Features";

            //Rotate works on a selected set of features
            //Get all features that intersect a polygon
            var rotateSelection = MapView.Active.GetFeatures(polygon).Select(
                k => new KeyValuePair <MapMember, List <long> >(k.Key as MapMember, k.Value));

            //Rotate selected features 90 deg about "origin"
            rotateFeatures.Rotate(rotateSelection, origin, Math.PI / 2);

            //Execute to execute the operation
            //Must be called within QueuedTask.Run
            rotateFeatures.Execute();

            //or use async flavor
            //await rotateFeatures.ExecuteAsync();

            #endregion

            #region Edit Operation Scale Features

            var scaleFeatures = new EditOperation();
            scaleFeatures.Name = "Scale Features";

            //Rotate works on a selected set of features
            var scaleSelection = MapView.Active.GetFeatures(polygon).Select(
                k => new KeyValuePair <MapMember, List <long> >(k.Key as MapMember, k.Value));

            //Scale the selected features by 2.0 in the X and Y direction
            scaleFeatures.Scale(scaleSelection, origin, 2.0, 2.0, 0.0);

            //Execute to execute the operation
            //Must be called within QueuedTask.Run
            scaleFeatures.Execute();

            //or use async flavor
            //await scaleFeatures.ExecuteAsync();

            #endregion

            var mp1 = MapPointBuilder.CreateMapPoint(0, 0, null);
            var mp2 = mp1;
            var mp3 = mp1;

            #region Edit Operation Split Features

            var splitFeatures = new EditOperation();
            splitFeatures.Name = "Split Features";

            var splitPoints = new List <MapPoint>()
            {
                mp1, mp2, mp3
            };

            //Split the feature at 3 points
            splitFeatures.Split(featureLayer, oid, splitPoints);

            // split using percentage
            var splitByPercentage = new SplitByPercentage()
            {
                Percentage = 33, SplitFromStartPoint = true
            };
            splitFeatures.Split(featureLayer, oid, splitByPercentage);

            // split using equal parts
            var splitByEqualParts = new SplitByEqualParts()
            {
                NumParts = 3
            };
            splitFeatures.Split(featureLayer, oid, splitByEqualParts);

            // split using single distance
            var splitByDistance = new SplitByDistance()
            {
                Distance = 27.3, SplitFromStartPoint = false
            };
            splitFeatures.Split(featureLayer, oid, splitByDistance);

            // split using varying distance
            var distances = new List <double>()
            {
                12.5, 38.2, 89.99
            };
            var splitByVaryingDistance = new SplitByVaryingDistance()
            {
                Distances = distances, SplitFromStartPoint = true, ProportionRemainder = true
            };
            splitFeatures.Split(featureLayer, oid, splitByVaryingDistance);

            //Execute to execute the operation
            //Must be called within QueuedTask.Run
            splitFeatures.Execute();

            //or use async flavor
            //await splitAtPointsFeatures.ExecuteAsync();

            #endregion

            var linkLayer = featureLayer;

            #region Edit Operation Transform Features

            var transformFeatures = new EditOperation();
            transformFeatures.Name = "Transform Features";

            //Transform a selected set of features
            var transformSelection = MapView.Active.GetFeatures(polygon).Select(
                k => new KeyValuePair <MapMember, List <long> >(k.Key as MapMember, k.Value));

            transformFeatures.Transform(transformSelection, linkLayer);

            //Transform just a layer
            transformFeatures.Transform(featureLayer, linkLayer);

            //Perform an affine transformation
            transformFeatures.TransformAffine(featureLayer, linkLayer);

            //Execute to execute the operation
            //Must be called within QueuedTask.Run
            transformFeatures.Execute();

            //or use async flavor
            //await transformFeatures.ExecuteAsync();

            #endregion

            #region Edit Operation Perform a Clip, Cut, and Planarize

            //Multiple operations can be performed by a single
            //edit operation.
            var clipCutPlanarizeFeatures = new EditOperation();
            clipCutPlanarizeFeatures.Name = "Clip, Cut, and Planarize Features";
            clipCutPlanarizeFeatures.Clip(featureLayer, oid, clipPoly);
            clipCutPlanarizeFeatures.Split(featureLayer, oid, cutLine);
            clipCutPlanarizeFeatures.Planarize(featureLayer, new List <long>()
            {
                oid
            });

            //Note: An edit operation is a single transaction.
            //Execute the operations (in the order they were declared)
            clipCutPlanarizeFeatures.Execute();

            //or use async flavor
            //await clipCutPlanarizeFeatures.ExecuteAsync();

            #endregion

            #region Edit Operation Chain Edit Operations

            //Chaining operations is a special case. Use "Chained Operations" when you require multiple transactions
            //to be undo-able with a single "Undo".

            //The most common use case for operation chaining is creating a feature with an attachement.
            //Adding an attachment requires the object id (of a new feature) has already been created.
            var editOperation1 = new EditOperation();
            editOperation1.Name = string.Format("Create point in '{0}'", CurrentTemplate.Layer.Name);

            long newFeatureID = -1;
            //The Create operation has to execute so we can get an object_id
            editOperation1.Create(this.CurrentTemplate, polygon, (object_id) => newFeatureID = object_id);
            //Must be within a QueuedTask
            editOperation1.Execute();

            //or use async flavor
            //await editOperation1.ExecuteAsync();

            //Now, because we have the object id, we can add the attachment.  As we are chaining it, adding the attachment
            //can be undone as part of the "Undo Create" operation. In other words, only one undo operation will show on the
            //Pro UI and not two.
            var editOperation2 = editOperation1.CreateChainedOperation();
            //Add the attachement using the new feature id
            editOperation2.AddAttachment(this.CurrentTemplate.Layer, newFeatureID, @"C:\data\images\Hydrant.jpg");

            //editOperation1 and editOperation2 show up as a single Undo operation on the UI even though
            //we had two transactions
            //Must be within a QueuedTask
            editOperation2.Execute();

            //or use async flavor
            //await editOperation2.ExecuteAsync();

            #endregion

            #region Edit Operation add attachment via RowToken

            //ArcGIS Pro 2.5 extends the EditOperation.AddAttachment method to take a RowToken as a paramter.
            //This allows you to create a feature, using EditOperation.CreateEx, and add an attachment in one transaction.

            var editOpAttach = new EditOperation();
            editOperation1.Name = string.Format("Create point in '{0}'", CurrentTemplate.Layer.Name);

            var attachRowToken = editOpAttach.CreateEx(this.CurrentTemplate, polygon);
            editOpAttach.AddAttachment(attachRowToken, @"c:\temp\image.jpg");

            //Must be within a QueuedTask
            editOpAttach.Execute();
            #endregion

            #region SetOnUndone, SetOnRedone, SetOnComitted

            // SetOnUndone, SetOnRedone and SetOnComittedManage can be used to manage
            // external actions(such as writing to a log table) that are associated with
            // each edit operation.

            //get selected feature and update attribute
            var selectedFeatures = MapView.Active.Map.GetSelection();
            var testInspector    = new Inspector();
            testInspector.Load(selectedFeatures.Keys.First(), selectedFeatures.Values.First());
            testInspector["Name"] = "test";

            //create and execute the edit operation
            var updateTestField = new EditOperation();
            updateTestField.Name = "Update test field";
            updateTestField.Modify(insp);

            //actions for SetOn...
            updateTestField.SetOnUndone(() =>
            {
                //Sets an action that will be called when this operation is undone.
                Debug.WriteLine("Operation is undone");
            });

            updateTestField.SetOnRedone(() =>
            {
                //Sets an action that will be called when this editoperation is redone.
                Debug.WriteLine("Operation is redone");
            });

            updateTestField.SetOnComitted((bool b) => //called on edit session save(true)/discard(false).
            {
                // Sets an action that will be called when this editoperation is committed.
                Debug.WriteLine("Operation is committed");
            });

            updateTestField.Execute();
        }
示例#7
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();

            createOperation.Name = "Create Transformer Bank";
            createOperation.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
                    {
                        using (UtilityNetworkDefinition utilityNetworkDefinition = utilityNetwork.GetDefinition())

                            // Get the NetworkSource, AssetGroup, and AssetTypes for all of the features we want to create
                            // If this was production code, you would want to check the return values to make sure that these asset groups and asset types existed.

                            // TransformerBank
                            using (NetworkSource transformerBankNetworkSource = utilityNetworkDefinition.GetNetworkSource(AssemblyNetworkSourceName))
                                using (AssetGroup transformerBankAssetGroup = transformerBankNetworkSource.GetAssetGroup(TransformerBankAssetGroupName))
                                    using (AssetType transformerBankAssetType = transformerBankAssetGroup.GetAssetType(TransformerBankAssetTypeName))

                                        // Transformer
                                        using (NetworkSource deviceNetworkSource = utilityNetworkDefinition.GetNetworkSource(DeviceNetworkSourceName))
                                            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
                                                                    Layer transformerBankLayer      = GetLayerForEdit(map, AssemblyNetworkSourceName, TransformerBankAssetGroupName);
                                                                    RowToken token                  = createOperation.CreateEx(transformerBankLayer, CreateAttributes(transformerBankAssetGroup, transformerBankAssetType, clickPoint));
                                                                    RowHandle transformerBankHandle = new RowHandle(token);

                                                                    // Create three transformers, one for each phase
                                                                    Layer transformerLayer = GetLayerForEdit(map, DeviceNetworkSourceName, TransformerAssetGroupName);

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

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

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

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

                                                                    containmentAssociationDescription = new ContainmentAssociationDescription(transformerBankHandle, transformerHandleB, false);
                                                                    createOperation.Create(containmentAssociationDescription);

                                                                    containmentAssociationDescription = new ContainmentAssociationDescription(transformerBankHandle, transformerHandleC, false);
                                                                    createOperation.Create(containmentAssociationDescription);

                                                                    // Create three arresters, one for each phase
                                                                    Layer arresterLayer = GetLayerForEdit(map, DeviceNetworkSourceName, ArresterAssetGroupName);

                                                                    MapPoint arresterPointA = CreateOffsetMapPoint(clickPoint, -1 * XOffset, 2 * YOffset);
                                                                    token = createOperation.CreateEx(arresterLayer, CreateDeviceAttributes(arresterAssetGroup, arresterAssetType, arresterPointA, APhase));
                                                                    RowHandle arresterHandlA = new RowHandle(token);

                                                                    MapPoint arresterPointB = CreateOffsetMapPoint(clickPoint, 0, 2 * YOffset);
                                                                    token = createOperation.CreateEx(arresterLayer, CreateDeviceAttributes(arresterAssetGroup, arresterAssetType, arresterPointB, BPhase));
                                                                    RowHandle arresterHandleB = new RowHandle(token);

                                                                    MapPoint arresterPointC = CreateOffsetMapPoint(clickPoint, XOffset, 2 * YOffset);
                                                                    token = createOperation.CreateEx(arresterLayer, CreateDeviceAttributes(arresterAssetGroup, arresterAssetType, arresterPointC, CPhase));
                                                                    RowHandle arresterHandleC = new RowHandle(token);

                                                                    // Create containment associations between the bank and the arresters
                                                                    containmentAssociationDescription = new ContainmentAssociationDescription(transformerBankHandle, arresterHandlA, false);
                                                                    createOperation.Create(containmentAssociationDescription);

                                                                    containmentAssociationDescription = new ContainmentAssociationDescription(transformerBankHandle, arresterHandleB, false);
                                                                    createOperation.Create(containmentAssociationDescription);

                                                                    containmentAssociationDescription = new ContainmentAssociationDescription(transformerBankHandle, arresterHandleC, 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;

                                                                    // Connect the high-side transformer terminals to the arresters (connect the A-phase transformer to the A-phase arrester, and so on)
                                                                    ConnectivityAssociationDescription connectivityAssociationDescription = new ConnectivityAssociationDescription(transformerHandleA, highSideTerminalID, arresterHandlA);
                                                                    createOperation.Create(connectivityAssociationDescription);

                                                                    connectivityAssociationDescription = new ConnectivityAssociationDescription(transformerHandleB, highSideTerminalID, arresterHandleB);
                                                                    createOperation.Create(connectivityAssociationDescription);

                                                                    connectivityAssociationDescription = new ConnectivityAssociationDescription(transformerHandleC, highSideTerminalID, arresterHandleC);
                                                                    createOperation.Create(connectivityAssociationDescription);

                                                                    // Create three fuses, one for each phase
                                                                    Layer fuseLayer = GetLayerForEdit(map, DeviceNetworkSourceName, FuseAssetGroupName);

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

                                                                    MapPoint fusePointB = CreateOffsetMapPoint(clickPoint, 0, 3 * YOffset);
                                                                    token = createOperation.CreateEx(fuseLayer, CreateDeviceAttributes(fuseAssetGroup, fuseAssetType, fusePointB, BPhase));
                                                                    RowHandle fuseHandleB = new RowHandle(token);

                                                                    MapPoint fusePointC = CreateOffsetMapPoint(clickPoint, XOffset, 3 * YOffset);
                                                                    token = createOperation.CreateEx(fuseLayer, CreateDeviceAttributes(fuseAssetGroup, fuseAssetType, fusePointC, CPhase));
                                                                    RowHandle fuseHandleC = new RowHandle(token);

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

                                                                    containmentAssociationDescription = new ContainmentAssociationDescription(transformerBankHandle, fuseHandleB, false);
                                                                    createOperation.Create(containmentAssociationDescription);

                                                                    containmentAssociationDescription = new ContainmentAssociationDescription(transformerBankHandle, fuseHandleC, 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 ConnectivityAssociationDescription(fuseHandleA, arresterHandlA);
                                                                    createOperation.Create(connectivityAssociationDescription);

                                                                    connectivityAssociationDescription = new ConnectivityAssociationDescription(fuseHandleB, arresterHandleB);
                                                                    createOperation.Create(connectivityAssociationDescription);

                                                                    connectivityAssociationDescription = new ConnectivityAssociationDescription(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);
        }
示例#8
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.CreateEx(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.CreateEx(deviceFeatureClass, CreateDeviceAttributes(transformerAssetGroup, transformerAssetType, transformerPointA, APhase));
                                                                                RowHandle transformerHandleA = new RowHandle(token);

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

                                                                                MapPoint transformerPointC = CreateOffsetMapPoint(clickPoint, XOffset, YOffset);
                                                                                token = createOperation.CreateEx(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.CreateEx(deviceFeatureClass, CreateDeviceAttributes(fuseAssetGroup, fuseAssetType, fusePointA, APhase));
                                                                                RowHandle fuseHandleA = new RowHandle(token);

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

                                                                                MapPoint fusePointC = CreateOffsetMapPoint(clickPoint, XOffset, 2 * YOffset);
                                                                                token = createOperation.CreateEx(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.CreateEx(deviceFeatureClass, CreateDeviceAttributes(arresterAssetGroup, arresterAssetType, arresterPointA, APhase));
                                                                                RowHandle arresterHandleA = new RowHandle(token);

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

                                                                                MapPoint arresterPointC = CreateOffsetMapPoint(clickPoint, XOffset, 3 * YOffset);
                                                                                token = createOperation.CreateEx(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);
        }