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 }; editOper.CopyParcelLinesToParcelType(_parcelFabricLayer, sourceParcelFeatures, _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("Cancelled"); } 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); }
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); }
/// <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."); }
public async void UpdateValues() { // This sample is intended for use with a featureclass with a default text field named "Description". // You can replace "Description" with any field name that works for your dataset // Check for an active mapview if (MapView.Active == null) { MessageBox.Show("No MapView currently active. Exiting...", "Info"); return; } await QueuedTask.Run(async() => { string nhdlayername = "NHDFlowline"; string nhd_nd_name = "NHDFlowline_ND"; var featLayer = MapView.Active.Map.FindLayers(nhdlayername).First() as FeatureLayer; if (featLayer == null) { MessageBox.Show("NHD Flowline layer not added to the Map. Exiting...", "Info"); return; } // Get the selected records, and check/exit if there are none: var featSelectionOIDs = featLayer.GetSelection().GetObjectIDs(); if (featSelectionOIDs.Count == 0) { MessageBox.Show("No records are selected for " + featLayer.Name + ". Exiting...", "Info"); return; } string strvalue = String.IsNullOrEmpty(Module1.Current.StreamVelValue.Text) ? "0.5" : Module1.Current.StreamVelValue.Text; double setvalue = double.Parse(strvalue); try { // Now ready to do the actual editing: // 1. Create a new edit operation and a new inspector for working with the attributes // 2. Check to see if a valid field name was chosen for the feature layer // 3. If so, apply the edit // var inspector = new ArcGIS.Desktop.Editing.Attributes.Inspector(true); inspector.Load(featLayer, featSelectionOIDs); //if (inspector.HasAttributes && inspector.Count(a => a.FieldName.ToUpper() == attributename.ToUpper()) > 0) if (inspector.HasAttributes) { inspector["InNetwork"] = 1; inspector["FlowDir"] = 1; inspector["VelProvenance"] = "Manual Edit"; inspector["OneWay"] = "FT"; inspector["CalculatedVel"] = setvalue * 3.2808; //fps inspector["Stream_Vel"] = setvalue; //m/s inspector["TravelTime"] = 0.05; var editOp = new EditOperation(); editOp.Name = "Edit " + featLayer.Name + ", " + Convert.ToString(featSelectionOIDs.Count) + " records."; editOp.Modify(inspector); //editOp.ExecuteAsync(); if (editOp.IsEmpty) { editOp.Abort(); } else { await editOp.ExecuteAsync(); //MessageBox.Show("Update operation completed.", "Editing with Inspector"); //Caliculate TtavelTime based on input stream velocity var param_values1 = Geoprocessing.MakeValueArray(featLayer, "TravelTime", "!LengthKM! / (!CalculatedVel!*0.0003048*60)"); var gp_result1 = await Geoprocessing.ExecuteToolAsync("management.CalculateField", param_values1, null, null, null, GPExecuteToolFlags.AddToHistory); string in_features = featLayer.GetPath().LocalPath.Replace(nhdlayername, nhd_nd_name); var param_values = Geoprocessing.MakeValueArray(in_features); var gp_result = await Geoprocessing.ExecuteToolAsync("na.BuildNetwork", param_values, null, null, null, GPExecuteToolFlags.AddToHistory); if (!gp_result.IsFailed) { if (Project.Current.HasEdits) { await Project.Current.SaveEditsAsync(); //To Refresh the map MapView.Active.Redraw(true); // Display all the parameters for the update: MessageBox.Show("Here are update parameters details: " + "\r\n Layer: " + featLayer.Name + "\r\n Number of records: " + Convert.ToString(featSelectionOIDs.Count) + "\r\n\t InNetwork : 'Yes' " + "\r\n\t FlowDir : 'WithDigitization' " + "\r\n\t VelProvenance : 'Manual Edit' " + "\r\n\t OneWay : 'FT' " + "\r\n\t CalculatedVel : " + Convert.ToString(setvalue * 3.2808) + " fps" + "\r\n\t Stream_Vel : " + Convert.ToString(setvalue) + " m/s" + "\r\n\t TravelTime : Calculated value of length, Velocity" ); } } //Geoprocessing.ShowMessageBox(gp_result.Messages, "Contents", GPMessageBoxStyle.Default, "Window Title"); } } else { MessageBox.Show("The Attribute provided is not valid. " + "\r\n Ensure your attribute name is correct.", "Invalid attribute"); // return; } } catch (Exception exc) { // Catch any exception found and display a message box. MessageBox.Show("Exception caught while trying to perform update: " + exc.Message); return; } }); }
protected override void OnClick() { // Check for an active mapview if (MapView.Active == null) { MessageBox.Show("No MapView currently active. Exiting...", "Info"); return; } QueuedTask.Run(async() => { string nhdlayername = "NHDFlowline"; var featLayer = MapView.Active.Map.FindLayers(nhdlayername).First() as FeatureLayer; if (featLayer == null) { MessageBox.Show("A feature layer must be selected. Exiting...", "Info"); return; } // Get the selected records, and check/exit if there are none: var featSelectionOIDs = featLayer.GetSelection().GetObjectIDs(); if (featSelectionOIDs.Count == 0) { MessageBox.Show("No records selected for layer, " + featLayer.Name + ". Exiting...", "Info"); return; } try { foreach (var fid in featSelectionOIDs) { var inspector = new Inspector(true); inspector.Load(featLayer, fid); //GeometryBag g_bag = inspector.Shape as GeometryBag; if (inspector.HasAttributes) { Geometry geo = GeometryEngine.Instance.ReverseOrientation(inspector.Shape as Multipart); inspector["VelProvenance"] = "Manual Shape Reverse"; inspector["SHAPE"] = geo; var editOp = new EditOperation(); editOp.Name = "EditReverse " + featLayer.Name + ", " + Convert.ToString(featSelectionOIDs.Count) + " records."; editOp.Modify(inspector); //editOp.ExecuteAsync(); if (editOp.IsEmpty) { editOp.Abort(); } else { await editOp.ExecuteAsync(); await Project.Current.SaveEditsAsync(); } } } } catch (Exception exc) { // Catch any exception found and display a message box. MessageBox.Show("Exception caught while trying to perform reverse: " + exc.Message); return; } }); }