public async void ProgressDialogExample() { #region progress_dialog var progDlg = new ProgressDialog("Running Geoprocessing Tool", "Cancel", 100, true); progDlg.Show(); var progSrc = new CancelableProgressorSource(progDlg); // prepare input parameter values to CopyFeatures tool string input_data = @"C:\data\california.gdb\ca_highways"; string out_workspace = ArcGIS.Desktop.Core.Project.Current.DefaultGeodatabasePath; string out_data = System.IO.Path.Combine(out_workspace, "ca_highways2"); // make a value array of strings to be passed to ExecuteToolAsync var parameters = Geoprocessing.MakeValueArray(input_data, out_data); // execute the tool await Geoprocessing.ExecuteToolAsync("management.CopyFeatures", parameters, null, new CancelableProgressorSource(progDlg).Progressor, GPExecuteToolFlags.Default); // dialog hides itself once the execution is complete progDlg.Hide(); #endregion }
public static Task RunCancelableProgress(CancelableProgressorSource cps, int howLongInSeconds) { //simulate doing some work which can be canceled return QueuedTask.Run(() => { cps.Progressor.Max = (uint)howLongInSeconds; //check every second while (!cps.Progressor.CancellationToken.IsCancellationRequested) { cps.Progressor.Value += 1; cps.Progressor.Status = "Status " + cps.Progressor.Value; cps.Progressor.Message = "Message " + cps.Progressor.Value; if (System.Diagnostics.Debugger.IsAttached) { System.Diagnostics.Debug.WriteLine(string.Format("RunCancelableProgress Loop{0}", cps.Progressor.Value)); } //are we done? if (cps.Progressor.Value == cps.Progressor.Max) break; //block the CIM for a second Task.Delay(1000).Wait(); } System.Diagnostics.Debug.WriteLine(string.Format("RunCancelableProgress: Canceled {0}", cps.Progressor.CancellationToken.IsCancellationRequested)); }, cps.Progressor); }
public static Task RunCancelableProgress(CancelableProgressorSource cps, uint howLongInSeconds) { //simulate doing some work which can be canceled return(QueuedTask.Run(() => { cps.Progressor.Max = (uint)howLongInSeconds; //check every second while (!cps.Progressor.CancellationToken.IsCancellationRequested) { cps.Progressor.Value += 1; cps.Progressor.Status = (cps.Progressor.Value * 100 / cps.Progressor.Max) + @" % Completed"; cps.Progressor.Message = "Message " + cps.Progressor.Value; if (System.Diagnostics.Debugger.IsAttached) { System.Diagnostics.Debug.WriteLine(string.Format("RunCancelableProgress Loop{0}", cps.Progressor.Value)); } //block the CIM for a second Task.Delay(1000).Wait(); //are we done? if (cps.Progressor.Value == cps.Progressor.Max) { break; } } System.Diagnostics.Debug.WriteLine(string.Format("RunCancelableProgress: Canceled {0}", cps.Progressor.CancellationToken.IsCancellationRequested)); }, cps.Progressor)); }
private Task LoadToService(Element element, CancelableProgressorSource status, int chunksize) { return(QueuedTask.Run(() => { var featuresList = new List <Object>(); using (RowCursor rowCursor = element.Cursor) { while (rowCursor.MoveNext()) { using (Row row = rowCursor.Current) { Object feat; // Read attributes var _attributes = element.FormatAttributes(row); // Read and convert geometry if (element.Item.Type == "File Geodatabase Feature Class" || element.Item.Type == "Shapefile") { var feature = row as Feature; var shape = feature.GetShape(); var shape_prj = GeometryEngine.Instance.Project(shape, webMercator); var json_geom = GeometryEngine.Instance.ExportToJSON(JSONExportFlags.jsonExportSkipCRS, shape_prj); var geom = element.Serialize(json_geom); feat = new { attributes = _attributes, geometry = geom }; } else if (element.Item.Type == "File Geodatabase Table" || element.Item.Type == "Excel Table" || element.Item.Type == "Text File") { feat = new { attributes = _attributes } } ; else { feat = new { } }; // Maybe Throw a exception? // Add feature featuresList.Add(feat); // Evaluate size if (featuresList.Count == chunksize) { var _result = AddFeatures(featuresList, element); featuresList.Clear(); status.Progressor.Value += 1; status.Progressor.Status = String.Format("{0} de {1}", status.Progressor.Value * chunksize, element.Count); status.Progressor.Message = String.Format("Registros cargados {0}", status.Progressor.Value * chunksize); } } } } if (featuresList.Count > 0) { AddFeatures(featuresList, element); status.Progressor.Value += 1; status.Progressor.Message = String.Format("Registros cargados {0}", status.Progressor.Value * chunksize); } }, status.Progressor)); }
protected override CancelableProgressor GetSelectionProgressor() { var selectionCompleteProgressorSource = new CancelableProgressorSource( "Selecting features bla bla...", "cancelled", true); CancelableProgressor selectionProgressor = selectionCompleteProgressorSource.Progressor; return(selectionProgressor); }
public SfcTool(string clipExtentShapeFile, string outputDirectory, string postfix, string backupFolderName, OverwriteMode overwriteMode, CancelableProgressorSource cancelHandler) { this._clipExtentShapeFile = clipExtentShapeFile; this._outputDirectory = outputDirectory; this._postfix = postfix; this._backupFolderName = backupFolderName; this._overwriteMode = overwriteMode; this._cancelHandler = cancelHandler; }
protected CancelableProgressor GetOverlapsCalculationProgressor() { var overlapsCalculationProgressorSource = new CancelableProgressorSource( "Calculating overlaps...", "cancelled", true); CancelableProgressor selectionProgressor = overlapsCalculationProgressorSource.Progressor; return(selectionProgressor); }
private CancelableProgressorSource GetProgressorDialogSource(string msg, uint maxSteps) { var pd = new ProgressDialog(msg, $@"Canceled: {msg}", maxSteps, false); var cps = new CancelableProgressorSource(pd) { Max = maxSteps }; return(cps); }
private void saveGeoms(CancelableProgressorSource status) { foreach (var b in polutionGeoms) { if (status.Progressor.CancellationToken.IsCancellationRequested) { return; } createFeature(b); } }
// TODO: wrong place for business logic / method does to many things at once / refactoring needed private async void OnExecuteClicked(object sender, RoutedEventArgs e) { var progressDialog = new ProgressDialog("Running Shape File Clipper ...", "Cancel"); progressDialog.Show(); var ignoredShapeFiles = new HashSet <string>(); var clipExtentShapeFile = ClipExtentTextBox.Text; var outputDirectory = OutputDirectoryTextBox.Text; var postfix = PostfixTextBox.Text; var backupFolderName = DateTime.Now.ToString("yyyyMMddHHmmss"); var overwriteMode = ((ComboBoxValue <OverwriteMode>)OverwriteModeComboBox.SelectedItem).Value; var cancelHandler = new CancelableProgressorSource(progressDialog); string targetReferenceSystem = null; if (DoProjectCheckBox.IsChecked ?? false) { targetReferenceSystem = _selectedCoordinateSystem?.Wkid?.ToString(); } var clipController = new SfcTool(clipExtentShapeFile, outputDirectory, postfix, targetReferenceSystem, backupFolderName, overwriteMode, cancelHandler); var tempPath = Path.Combine(Path.GetTempPath(), $"ShapeFileClipper_{System.Guid.NewGuid()}"); Directory.CreateDirectory(tempPath); var layers = await QueuedTask.Run(() => GetLayers(_selectedShapeFiles, tempPath)); foreach (var layer in layers) { var hasFailed = !await clipController.Process(layer); if (hasFailed) { ignoredShapeFiles.Add(layer); } } Directory.Delete(tempPath, true); if (ignoredShapeFiles.Count > 0) { var message = string.Join("\n", ignoredShapeFiles); MessageBox.Show(this, message, "Finished with ignored shape files", MessageBoxButton.OK); } else { MessageBox.Show(this, "All shape files successfully clipped.", "Finished", MessageBoxButton.OK); } progressDialog.Hide(); }
internal static async void ExecuteBufferGP(CancelationSource cancelType) { string toolName = "Buffer_analysis"; //input layer, output dataset, size of buffer string[] toolParams = new string[] { @"intrstat", @"C:\Data\SDK\Test\ForTheUC_2014\usa_output.gdb\intrstat_Buffer1", "30 Miles" }; //environment parameters from http://resources.arcgis.com/en/help/main/10.2/index.html#//018z0000004s000000 ForTheUcModule.Current.GPHelper.AddEnvironmentParameter(new Tuple <string, string>("OverwriteOutput", "True")); IGPResult result = null; if (cancelType == CancelationSource.withCancelationToken) { result = await ForTheUcModule.Current.GPHelper.ExecuteToolWithCancellationTokenSource(toolName, toolParams); } else { CancelableProgressorSource cps = new CancelableProgressorSource(string.Format("{0} running", toolName), string.Format("{0} canceled", toolName)); result = await ForTheUcModule.Current.GPHelper.ExecuteToolWithCancelableProgressor(toolName, toolParams, cps); } //check the result StringBuilder sb = new StringBuilder(); if (result.IsCanceled) { MessageBox.Show(Application.Current.MainWindow, string.Format("{0} was canceled", toolName), toolName); } else if (result.IsFailed) { //there was an error and execution was terminated foreach (var msg in result.Messages) { sb.AppendLine(msg.Text); } string message = string.Format("{0} execution failed\r\n=======================\r\n{1}", toolName, sb.ToString()); MessageBox.Show(Application.Current.MainWindow, message, toolName + " Error"); } else { //success - access results foreach (var msg in result.Messages) { sb.AppendLine(msg.Text); } string message = string.Format("{0} complete\r\n=======================\r\n{1}", toolName, sb.ToString()); MessageBox.Show(Application.Current.MainWindow, message, toolName + " Success"); } }
private async void Button_Click(object sender, RoutedEventArgs e) { var a1 = mcb1.Items[mcb1.SelectedIndex] as ComboBoxItem; var a2 = mcb2.Items[mcb2.SelectedIndex] as ComboBoxItem; var a3 = mcb3.Items[mcb3.SelectedIndex] as ComboBoxItem; var routesLayer = MapView.Active.Map.GetLayersAsFlattenedList().OfType <FeatureLayer>().FirstOrDefault(f => f.ShapeType == esriGeometryType.esriGeometryPolyline && f.Name == a1.Content as String); var routesNewLayer = MapView.Active.Map.GetLayersAsFlattenedList().OfType <FeatureLayer>().FirstOrDefault(f => f.ShapeType == esriGeometryType.esriGeometryPolyline && f.Name == a2.Content as String); var dotsNewLayer = MapView.Active.Map.GetLayersAsFlattenedList().OfType <FeatureLayer>().FirstOrDefault(f => f.ShapeType == esriGeometryType.esriGeometryPoint && f.Name == a3.Content as String); if (routesLayer == null) { MessageBox.Show($@"To run this sample you need to have a polyline feature class layer."); return; } if (routesNewLayer == null) { MessageBox.Show($@"To run this sample you need to have a polyline feature class layer."); return; } if (dotsNewLayer == null) { MessageBox.Show($@"To run this sample you need to have a point feature class layer."); return; } using (var progress = new ProgressDialog("Обработка...", "Отменено", 10000, false)) { //progress.Show(); var status = new CancelableProgressorSource(progress); status.Max = 10000; status.Value = 0; await QueuedTask.Run(() => { // create an instance of the inspector class //var inspector = new ArcGIS.Desktop.Editing.Attributes.Inspector(); var fc = routesLayer.GetTable() as FeatureClass; if (fc == null) { return; } var fcDefinition = fc.GetDefinition(); var proccessor = new Module1.AppProccessor(fc, routesLayer, routesNewLayer, dotsNewLayer); proccessor.execute(status); }, status.Progressor); } Close(); }
public static async Task RunModel(IReadOnlyList <string> args, string ToolName) { Log("Tool " + ToolName + " started"); DateTime startTime = DateTime.Now; try { await QueuedTask.Run(async() => { var reservoirToolbox = CoreModule.CurrentProject.Items.OfType <GeoprocessingProjectItem>().SingleOrDefault(c => c.Name == "Reservoir.tbx"); if (reservoirToolbox == null) { MessageBox.Show("Please add the Reservoir.tbx Toolbox to the project first!"); return; } var rucTool = reservoirToolbox.GetItems().SingleOrDefault(c => c.Name == ToolName); if (rucTool == null) { MessageBox.Show("Please check the Reservoir.tbx Toolbox. Tool \"" + ToolName + "\" not found!"); return; } var progDlg = new ProgressDialog("Running Model " + ToolName, "Cancel", 100, true); progDlg.Show(); var progSrc = new CancelableProgressorSource(progDlg); var result = await Geoprocessing.ExecuteToolAsync(rucTool.Path, args , null, new CancelableProgressorSource(progDlg).Progressor, GPExecuteToolFlags.Default); progDlg.Hide(); if (result.IsFailed) { foreach (var item in result.Messages.Where(c => c.ErrorCode != 0)) { Log("ERROR:" + item.Text); } } }); } catch (Exception) { throw; } finally { DateTime endTime = DateTime.Now; Log("Tool " + ToolName + " finished in " + (endTime - startTime).TotalSeconds.ToString("N") + " seconds"); } }
public async Task ExecuteSqlCb() { try { await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() => { bool dpexists = FrameworkApplication.DockPaneManager.IsDockPaneCreated("QProSapAddIn_TableViewerPanel"); if (dpexists) { var cpd = new CancelableProgressorSource(); TableViewerPanelViewModel vm = FrameworkApplication.DockPaneManager.Find("QProSapAddIn_TableViewerPanel") as TableViewerPanelViewModel; Task r = vm.ExecuteSqlCallback(cpd); } }); } catch (Exception ex) { MessageBox.Show("Error : " + ex.Message.ToString() + " "); } }
private void ShowProgress(string message, string status, uint value) { if (_ps == null) { _pd = new ProgressDialog("Progress tracker"); _pd.Show(); _ps = new CancelableProgressorSource(_pd); _ps.Progressor.Max = 10; Debug.WriteLine("Progressorsources created"); } Debug.WriteLine(string.Format("Progress updated: {0} - {1} - {2}/{3}", message, status, value, _ps.Progressor.Max)); _ps.Progressor.Message = message; _ps.Progressor.Status = status; _ps.Progressor.Value = value; }
public async Task AddToMapCb2() { try { await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() => { bool dpexists = FrameworkApplication.DockPaneManager.IsDockPaneCreated("QProSapAddIn_SpatialTableFinder"); if (dpexists) { var cpd = new CancelableProgressorSource(); SpatialTableFinderViewModel vm = FrameworkApplication.DockPaneManager.Find("QProSapAddIn_SpatialTableFinder") as SpatialTableFinderViewModel; Task r = vm.AddToMapCallback2(cpd); } }); } catch (Exception ex) { MessageBox.Show("Error : " + ex.Message.ToString() + " "); } }
/// <summary> /// Attempts to copy each file the file list to the destination /// </summary> /// <returns></returns> private Task CloneFiles(CancelableProgressorSource CancelableProgressorSource, UInt32 TotalNumberOfFiles) { return(QueuedTask.Run(() => { bool itWorked = false; CancelableProgressorSource.Progressor.Max = TotalNumberOfFiles; foreach (KeyValuePair <string, Boolean> file in _fileList) { if (CancelableProgressorSource.Progressor.CancellationToken.IsCancellationRequested) { CancelableProgressorSource.Progressor.Message = "Cancelling"; CancelableProgressorSource.Progressor.Status = "I didn't finish..."; break; } if (file.Value) { if (!itWorked) { SaveFileExtensionsToDisk(_fileExtension); } itWorked = true; try { var sourceFile = file.Key; var destinationFile = _destinationWorkspace + @"\" + System.IO.Path.GetFileName(file.Key); System.IO.File.Copy(sourceFile, destinationFile); } catch (Exception yourBest) // But you don't succeed { yourBest.ToString(); // Just So We Get No Crashes ;) } } CancelableProgressorSource.Progressor.Value += 1; CancelableProgressorSource.Progressor.Status = string.Format("Copied {0} of {1} files", CancelableProgressorSource.Progressor.Value, TotalNumberOfFiles); CancelableProgressorSource.Progressor.Message = "Copying Files - " + Math.Round(((Convert.ToDouble(CancelableProgressorSource.Progressor.Value) / Convert.ToDouble(CancelableProgressorSource.Progressor.Max)) * 100.0), 0) + "% Complete"; } }, CancelableProgressorSource.Progressor)); }
internal static async void ExecuteBufferGP(CancelationSource cancelType) { string toolName = "Buffer_analysis"; //input layer, output dataset, size of buffer string[] toolParams = new string[] {@"intrstat", @"C:\Data\SDK\Test\ForTheUC_2014\usa_output.gdb\intrstat_Buffer1", "30 Miles" }; //environment parameters from http://resources.arcgis.com/en/help/main/10.2/index.html#//018z0000004s000000 ForTheUcModule.Current.GPHelper.AddEnvironmentParameter(new Tuple<string, string>("OverwriteOutput", "True")); IGPResult result = null; if (cancelType == CancelationSource.withCancelationToken) { result = await ForTheUcModule.Current.GPHelper.ExecuteToolWithCancellationTokenSource(toolName, toolParams); } else { CancelableProgressorSource cps = new CancelableProgressorSource(string.Format("{0} running", toolName), string.Format("{0} canceled", toolName)); result = await ForTheUcModule.Current.GPHelper.ExecuteToolWithCancelableProgressor(toolName, toolParams, cps); } //check the result StringBuilder sb = new StringBuilder(); if (result.IsCanceled) { MessageBox.Show(Application.Current.MainWindow, string.Format("{0} was canceled", toolName), toolName); } else if (result.IsFailed) { //there was an error and execution was terminated foreach (var msg in result.Messages) { sb.AppendLine(msg.Text); } string message = string.Format("{0} execution failed\r\n=======================\r\n{1}", toolName, sb.ToString()); MessageBox.Show(Application.Current.MainWindow, message, toolName + " Error"); } else { //success - access results foreach (var msg in result.Messages) { sb.AppendLine(msg.Text); } string message = string.Format("{0} complete\r\n=======================\r\n{1}", toolName, sb.ToString()); MessageBox.Show(Application.Current.MainWindow, message, toolName + " Success"); } }
public async Task AddToTOCCb() { try { await QueuedTask.Run(() => { bool dpexists = FrameworkApplication.DockPaneManager.IsDockPaneCreated("QProSapAddIn_TableViewerPanel"); if (dpexists) { TableViewerPanelViewModel vm = FrameworkApplication.DockPaneManager.Find("QProSapAddIn_TableViewerPanel") as TableViewerPanelViewModel; //var pd = new ProgressDialog("Adding data to map.", "Canceled", false); //pd.Show(); var cpd = new CancelableProgressorSource(); Task r = vm.AddToTOCCallback(cpd); } }); } catch (Exception ex) { MessageBox.Show("Error : " + ex.Message.ToString() + " "); } }
protected override void OnClick() { var result = editsResult(Project.Current.HasEdits); { QueuedTask.Run(async() => { try { if (result == MessageBoxResult.Yes) { var progDlg = new ProgressDialog("Saving Edits...", "Cancel", 100, true); var progSrc = new CancelableProgressorSource(progDlg); do { await Project.Current.SaveEditsAsync(); progDlg.Show(); }while (Project.Current.HasEdits); progDlg.Dispose(); var notify = new Notification() { Title = "ASYNC CAGE SAYS...", Message = "All Edits Saved Successfully!", ImageUrl = "pack://application:,,,/EditsHelper;component/Images/cage_toast.png" }; FrameworkApplication.AddNotification(notify); } } catch (Exception error) { ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show(String.Format("Save Edits Async Failed: {0}", error)); }; }); } }
private void createDotsGeoms(CancelableProgressorSource status) { List <PolutionGeom> dots = new List <PolutionGeom>(); foreach (var b in polutionGeoms) { if (status.Progressor.CancellationToken.IsCancellationRequested) { return; } Geometry gd = GeometryEngine.Instance.QueryPoint(b.geometry as Polyline, SegmentExtension.NoExtension, 0, AsRatioOrLength.AsLength); PolutionGeom d = new PolutionGeom(gd, b.objects.ToArray()); PolutionGeom d2 = dots.Find(dot => GeometryEngine.Instance.Intersects(dot.geometry, gd)); if (d2 != null) { if (d.objects.Sum(v => v.cityPolutionM3) > d2.objects.Sum(v => v.cityPolutionM3)) { dots.Remove(d2); dots.Add(d); } } else { dots.Add(d); } } foreach (var b in dots) { if (status.Progressor.CancellationToken.IsCancellationRequested) { return; } createDotsFeature(b); } }
//Option 1 - use a CancelableProgressor - uses can click on the cancel button when the tool is running internal virtual Task <IGPResult> ExecuteToolWithCancelableProgressor(string toolPath, string[] values, CancelableProgressorSource cps) { return(Geoprocessing.ExecuteTool(toolPath, values, _env.ToArray(), cps.Progressor)); }
//Click to create suitability map private async void Map_Click(object sender, EventArgs e) { var mapView = MapView.Active; List <string> paths = new List <string>(); List <string> myinputs = new List <string>(); TreeNode test = Goal.TopNode; //using await instead of .wait() for asynchronous execution (Wait for the results) await QueuedTask.Run(() => { for (int k = 0; k < test.Nodes.Count; k++) { var rlyrs = MapView.Active.Map.Layers.OfType <RasterLayer>(); //All raster layers for (int m = 0; m < rlyrs.Count(); m++) { RasterLayer rlyr = rlyrs.ElementAt(m); //raster layer at specific position Datastore dataStore = rlyr.GetRaster().GetRasterDataset().GetDatastore(); //getting datasource if (test.Nodes[k].Tag.ToString() == rlyr.Name) { paths.Add(dataStore.GetPath().AbsolutePath); myinputs.Add(paths.ElementAt(k) + "/" + rlyr.GetRaster().GetRasterDataset().GetName() + " VALUE " + Math.Round(rowSum[k], 2)); } } } }); //t.Wait(); //For Showing Progress Window (Optional) var progDlgWS = new ProgressDialog("Weighted Sum Progress", "Cancel", 100, true); progDlgWS.Show(); var progSrc = new CancelableProgressorSource(progDlgWS); string weightedSumRaster = System.IO.Path.Combine(Project.Current.DefaultGeodatabasePath, "SuitedRaster"); var param_values = Geoprocessing.MakeValueArray(myinputs, weightedSumRaster); //use toolBoxNameAlias.toolName.Alias string toolpath = "sa.WeightedSum"; var env = Geoprocessing.MakeEnvironmentArray(scratchWorkspace: Project.Current.DefaultGeodatabasePath); //Uncomment below line if you want GP tool to open in Pro //Geoprocessing.OpenToolDialog(toolpath, param_values); progressLabel.Text = "Performing Weighted Sum, please wait..."; //Not adding weighted sum result to map since its intermediate result await Geoprocessing.ExecuteToolAsync(toolpath, param_values, env, new CancelableProgressorSource(progDlgWS).Progressor, GPExecuteToolFlags.AddOutputsToMap); progressLabel.Text = "Weighted Sum processing complete. Reclassification started"; //Hide the progress once done. progDlgWS.Hide(); //----Use this if you want to see GP result messages---// //---The flow doesnt progress forward unless you close this box-----// //Geoprocessing.ShowMessageBox(wsresult.Messages, "GP Messages", //wsresult.IsFailed ? GPMessageBoxStyle.Error : GPMessageBoxStyle.Default); //Creating a list string to store reclass values List <string> remap = new List <string>(); //Classifying into 3 classes, values can be modified as per user needs. remap.Add("0 0.6 1"); //Least Suitable remap.Add("0.6 0.8 2"); //Moderately Suitable remap.Add("0.8 1 3"); //Highly Suitable string output_raster2 = System.IO.Path.Combine(Project.Current.DefaultGeodatabasePath, "SuitedRaster" + "reclass0"); var reclassedRaster = Geoprocessing.MakeValueArray(weightedSumRaster, "VALUE", remap, output_raster2); await Geoprocessing.ExecuteToolAsync("sa.Reclassify", reclassedRaster, env, null, null, GPExecuteToolFlags.AddOutputsToMap); progressLabel.Text = "Reclassification Completed. Check in TOC"; //Geoprocessing.OpenToolDialog("sa.Reclassify", reclassedRaster); }
protected override async void OnClick() { SharedFunctions.Log("Search for candidate dams started"); pointsIntervalOnContour = Convert.ToInt32(Parameter.PointIntervalBox.Text); DateTime startTime = DateTime.Now; chosenCandidates = new List <CandidateDam>(); PotentialCandidates = 0; var pd = new ProgressDialog("Search for candidate dams", "Canceled", 100, false); cps = new CancelableProgressorSource(pd); cps.Progressor.Max = 100; PointsAnalyzed = 0; TotalPointsCount = 0; try { await Project.Current.SaveEditsAsync(); BasicFeatureLayer layer = null; await QueuedTask.Run(async() => { if (!SharedFunctions.LayerExists("ContourPoints")) { return; } CancellationToken ctoken = new CancellationToken(); //create line feature layer if it does not exist BasicFeatureLayer damCandidatesLayer = await CreateDamFeatureClass("DamCandidates"); var contourPointsLayer = MapView.Active.Map.FindLayers("ContourPoints").FirstOrDefault(); layer = contourPointsLayer as BasicFeatureLayer; // store the spatial reference of the current layer SpatialReference = layer.GetSpatialReference(); //Cursor for selected points RowCursor cursor = layer.GetSelection().Search(); //If no selection was set, use full points layer if (layer.GetSelection().GetCount() == 0) { cursor = layer.Search(); } Dictionary <int, SortedDictionary <int, SortedDictionary <long, MapPoint> > > contourHeights = new Dictionary <int, SortedDictionary <int, SortedDictionary <long, MapPoint> > >(); cps.Progressor.Status = "Loading ContourPoints into memory"; SharedFunctions.Log("Loading all ContourPoints into memory"); while (cursor.MoveNext()) { if (ctoken.IsCancellationRequested) { SharedFunctions.Log("Canceled"); return; } using (Row row = cursor.Current) { var point = row[1] as MapPoint; var pointID = (int)row[0]; var contourHeight = (int)(double)row[4]; var contourID = (int)row[2]; if (!ContourLengths.ContainsKey(contourID)) { ContourLengths.Add(contourID, (double)row["Shape_Length"]); } if (!contourHeights.ContainsKey((int)contourHeight)) { contourHeights.Add((int)contourHeight, new SortedDictionary <int, SortedDictionary <long, MapPoint> >()); } if (!contourHeights[contourHeight].ContainsKey((int)contourID)) { contourHeights[contourHeight].Add((int)contourID, new SortedDictionary <long, MapPoint>()); } contourHeights[contourHeight][(int)contourID].Add(pointID, point); TotalPointsCount++; } } cps.Progressor.Status = "Analyze Contours"; SharedFunctions.Log("Analyze Contours"); bool multiThreading = (Parameter.MultiThreadingBox == null || !Parameter.MultiThreadingBox.IsChecked.HasValue || Parameter.MultiThreadingBox.IsChecked.Value); if (multiThreading) { HeightsToProcess = contourHeights.Keys.ToList(); int ThreadCount = Math.Min(HeightsToProcess.Count, Environment.ProcessorCount); SharedFunctions.Log("Divided work into " + ThreadCount + " threads..."); await Task.WhenAll(Enumerable.Range(1, ThreadCount).Select(c => Task.Run( () => { while (HeightsToProcess.Count > 0) // && !ctoken.IsCancellationRequested) { int height = -1; lock (HeightsToProcess) { height = HeightsToProcess.FirstOrDefault(); if (height != 0) { HeightsToProcess.Remove(height); } } if (height != -1) { var calc = new Dictionary <int, SortedDictionary <int, SortedDictionary <long, MapPoint> > >(); calc.Add(height, contourHeights[height]); AnalyseContourHeights(calc, ctoken); } } } , ctoken)) ); } else { //Single Thread: AnalyseContourHeights(contourHeights, ctoken); } cps.Progressor.Status = "Saving all " + chosenCandidates.Count + " candidates"; SharedFunctions.Log("Saving all " + chosenCandidates.Count + " candidates"); foreach (var candidate in chosenCandidates) { if (ctoken.IsCancellationRequested) { SharedFunctions.Log("Canceled"); return; } //Create coordinates for Polyline Feature with height ContourHeight + 5 Meters! List <Coordinate3D> coordinates = new List <Coordinate3D>() { new Coordinate3D(candidate.StartPoint.X, candidate.StartPoint.Y, candidate.ContourHeight + 5), new Coordinate3D(candidate.EndPoint.X, candidate.EndPoint.Y, candidate.ContourHeight + 5) }; //save all selected candidates into the db var attributes = new Dictionary <string, object> { { "Shape", PolylineBuilder.CreatePolyline(coordinates) }, { "ContourID", (long)candidate.ContourID }, { "StartPointID", (long)candidate.StartPointID }, { "EndPointID", (long)candidate.EndPointID }, { "ContourHeight", (short)candidate.ContourHeight }, { "LengthRating", (float)candidate.Rating }, { "DistanceOnLine", (long)candidate.DistanceOnLine }, { "Length", (short)candidate.Length }, { "StartPointDistance", (long)candidate.StartPointDistance }, { "EndPointDistance", (long)candidate.EndPointDistance }, { "DamSpansContourStart", (short)(candidate.DamSpansContourStart ? 1 : 0) } }; var editOp = new EditOperation() { Name = "Create dam candidate", SelectNewFeatures = false }; editOp.Create(damCandidatesLayer, attributes); ////Execute the operations editOp.Execute(); } }, cps.Progressor); //save all edits await Project.Current.SaveEditsAsync(); } catch (Exception ex) { MessageBox.Show(ex.ToString()); } finally { DateTime endTime = DateTime.Now; SharedFunctions.Log("Analysed " + PotentialCandidates.ToString("N0") + " candidates ( " + chosenCandidates.Count.ToString("N0") + " selected) in " + (endTime - startTime).TotalSeconds.ToString("N") + " seconds"); } }
protected override async void OnClick() => await ThreadService.RunOnBackground(async() => { Log.Debug("Running Authorization missing Action Validation"); var progressDialog = new ProgressDialog("🔍 Finding issues...", 100, false); var progressor = new CancelableProgressorSource(progressDialog).Progressor; progressDialog.Show(); const string layerName = "UICAuthorizationAction"; var layer = LayerService.GetStandaloneTable(layerName, MapView.Active.Map); if (layer == null) { NotificationService.NotifyOfMissingLayer(layerName); progressDialog.Hide(); return; } progressor.Value = 10; const string parentLayerName = "UICAuthorization"; var parentLayer = LayerService.GetStandaloneTable(parentLayerName, MapView.Active.Map); if (parentLayer == null) { NotificationService.NotifyOfMissingLayer(parentLayerName); progressDialog.Hide(); return; } progressor.Value = 20; var foreignKeys = new HashSet <string>(); var primaryKeys = new HashSet <string>(); using (var cursor = layer.Search(new QueryFilter { SubFields = "Authorization_FK" })) { while (cursor.MoveNext()) { var fk = Convert.ToString(cursor.Current["AUTHORIZATION_FK"]); foreignKeys.Add(fk); } } progressor.Value = 50; using (var cursor = parentLayer.Search(new QueryFilter { SubFields = "GUID" })) { while (cursor.MoveNext()) { var fk = Convert.ToString(cursor.Current["GUID"]); primaryKeys.Add(fk); } } progressor.Value = 80; primaryKeys.ExceptWith(foreignKeys); if (primaryKeys.Count == 0) { NotificationService.NotifyOfValidationSuccess(); progressDialog.Hide(); return; } var problems = new List <long>(primaryKeys.Count); using (var cursor = parentLayer.Search(new QueryFilter { SubFields = "OBJECTID", WhereClause = $"GUID IN ({string.Join(",", primaryKeys.Select(x => $"'{x}'"))})" })) { while (cursor.MoveNext()) { var id = cursor.Current.GetObjectID(); problems.Add(id); } } progressor.Value = 90; MapView.Active.Map.SetSelection(new Dictionary <MapMember, List <long> > { { parentLayer, problems } }); progressor.Value = 100; progressDialog.Hide(); NotificationService.NotifyOfValidationFailure(problems.Count); Log.Verbose("Zooming to selected"); await MapView.Active.ZoomToSelectedAsync(TimeSpan.FromSeconds(1.5)); Log.Debug("Finished Authorization Validation"); });
protected override async void OnClick() => await ThreadService.RunOnBackground(async() => { Log.Debug("running authorization missing action validation"); var progressDialog = new ProgressDialog("🔍 Finding issues...", "Cancel", 100, false); progressDialog.Show(); const string layerName = "UICAuthorization"; var layer = LayerService.GetStandaloneTable(layerName, MapView.Active.Map); if (layer == null) { NotificationService.NotifyOfMissingLayer(layerName); progressDialog.Hide(); return; } IGPResult result = null; var parameters = Geoprocessing.MakeValueArray(layer, "NEW_SELECTION", "Facility_FK IS NULL"); var progSrc = new CancelableProgressorSource(progressDialog); Log.Verbose("management.SelectLayerByAttribute on {layer} with {@params}", layerName, parameters); try { result = await Geoprocessing.ExecuteToolAsync( "management.SelectLayerByAttribute", parameters, null, new CancelableProgressorSource(progressDialog).Progressor, GPExecuteToolFlags.Default ); } catch (Exception ex) { NotificationService.NotifyOfGpCrash(ex, parameters); progressDialog.Hide(); return; } if (result.IsFailed || string.IsNullOrEmpty(result?.ReturnValue)) { NotificationService.NotifyOfGpFailure(result, parameters); progressDialog.Hide(); return; } var problems = Convert.ToInt32(result?.Values[1]); if (problems == 0) { NotificationService.NotifyOfValidationSuccess(); progressDialog.Hide(); return; } progressDialog.Hide(); NotificationService.NotifyOfValidationFailure(problems); Log.Verbose("Zooming to selected"); await MapView.Active.ZoomToSelectedAsync(TimeSpan.FromSeconds(1.5)); Log.Debug("finished authorization missing facility fk validation"); });
protected override async void OnClick() => await ThreadService.RunOnBackground(async() => { Log.Debug("running violation without return to compliance date"); var progressDialog = new ProgressDialog("🔍 Finding issues...", "Cancel", 100, false); progressDialog.Show(); var layerName = "UICViolation"; var table = LayerService.GetStandaloneTable(layerName, MapView.Active.Map); if (table == null) { NotificationService.NotifyOfMissingLayer(layerName); progressDialog.Hide(); return; } IGPResult result = null; var parameters = Geoprocessing.MakeValueArray(table, "NEW_SELECTION", "ReturnToComplianceDate IS NULL"); var progSrc = new CancelableProgressorSource(progressDialog); Log.Verbose("management.SelectLayerByAttribute on {layer} with {@params}", layerName, parameters); try { result = await Geoprocessing.ExecuteToolAsync( "management.SelectLayerByAttribute", parameters, null, new CancelableProgressorSource(progressDialog).Progressor, GPExecuteToolFlags.Default ); } catch (Exception ex) { NotificationService.NotifyOfGpCrash(ex, parameters); progressDialog.Hide(); return; } if (result.IsFailed || string.IsNullOrEmpty(result?.ReturnValue)) { NotificationService.NotifyOfGpFailure(result, parameters); progressDialog.Hide(); return; } var problems = Convert.ToInt32(result?.Values[1]); Log.Debug("found {problems} problems", problems); if (problems == 0) { NotificationService.NotifyOfValidationSuccess(); progressDialog.Hide(); return; } progressDialog.Hide(); NotificationService.NotifyOfValidationFailure(problems); Log.Debug("finished violation missing return to compliance date"); });
protected override void OnClick() => ThreadService.RunOnBackground(async() => { Log.Debug("running well missing operating status validation"); var progressDialog = new ProgressDialog("🔍 Finding issues...", 100, false); var progressor = new CancelableProgressorSource(progressDialog).Progressor; progressDialog.Show(); const string tableName = "UICWell"; const string relatedTableName = "UICWellOperatingStatus"; var layer = LayerService.GetLayer(tableName, MapView.Active.Map); progressor.Value = 10; if (layer == null) { NotificationService.NotifyOfMissingLayer(tableName); progressDialog.Hide(); return; } IGPResult result = null; var parameters = Geoprocessing.MakeValueArray(layer); Log.Verbose("management.GetCount on {layer}", tableName); var cts = new CancellationTokenSource(); try { result = await Geoprocessing.ExecuteToolAsync( "management.GetCount", parameters, null, cts.Token ); } catch (Exception ex) { NotificationService.NotifyOfGpCrash(ex, parameters); progressDialog.Hide(); return; } if (result.IsFailed || string.IsNullOrEmpty(result?.ReturnValue)) { NotificationService.NotifyOfGpFailure(result, parameters); progressDialog.Hide(); return; } progressor.Value = 20; var total = Convert.ToInt32(result?.Values[0]); Log.Verbose("found {records} well records", total); var perRecordTick = 60F / total; float startingPoint = 20; var idMap = new Dictionary <string, long>(total); var primaryKeys = new HashSet <string>(); var foreignKeys = new HashSet <string>(); using (var parentTable = LayerService.GetTableFromLayersOrTables(tableName, MapView.Active.Map)) using (var relatedTable = LayerService.GetTableFromLayersOrTables(relatedTableName, MapView.Active.Map)) { if (relatedTable == null) { NotificationService.NotifyOfMissingLayer(relatedTableName); progressDialog.Hide(); return; } var filter = new QueryFilter { SubFields = "OBJECTID,GUID" }; using (var cursor = parentTable.Search(filter, true)) { var guidIndex = cursor.FindField("GUID"); while (cursor.MoveNext()) { var id = cursor.Current.GetObjectID(); var guid = cursor.Current[guidIndex].ToString(); idMap[guid] = id; primaryKeys.Add(guid); startingPoint += perRecordTick; var tick = Convert.ToUInt32(startingPoint); if (tick - 5 > progressor.Value) { progressor.Value = tick; } } } Log.Verbose("built set of primary keys"); filter.SubFields = "WELL_FK"; using (var cursor = relatedTable.Search(filter, true)) { var guidIndex = cursor.FindField("WELL_FK"); while (cursor.MoveNext()) { var guid = cursor.Current[guidIndex].ToString(); foreignKeys.Add(guid); } } Log.Verbose("Built set of foreign keys"); progressor.Value = 90; } primaryKeys.ExceptWith(foreignKeys); Log.Information("Found {count} issues", primaryKeys.Count); if (primaryKeys.Count == 0) { NotificationService.NotifyOfValidationSuccess(); progressDialog.Hide(); return; } var problems = new List <long>(primaryKeys.Count); problems.AddRange(idMap.Where(x => primaryKeys.Contains(x.Key)).Select(x => x.Value)); Log.Debug("Problem records {items}", problems); progressor.Value = 100; Log.Verbose("Setting selection"); MapView.Active.Map.SetSelection(new Dictionary <MapMember, List <long> > { { layer, problems } }); progressDialog.Hide(); NotificationService.NotifyOfValidationFailure(problems.Count); Log.Verbose("Zooming to selected"); await MapView.Active.ZoomToSelectedAsync(TimeSpan.FromSeconds(1.5)); Log.Debug("Finished Well Operating Status Validation"); });
//Option 1 - use a CancelableProgressor - uses can click on the cancel button when the tool is running internal virtual Task<IGPResult> ExecuteToolWithCancelableProgressor(string toolPath, string[] values, CancelableProgressorSource cps) { return Geoprocessing.ExecuteTool(toolPath, values, _env.ToArray(), cps.Progressor); }
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> /// Generate a diagram and apply the EnclosureLayout custom telco layout on its content /// </summary> /// <param name="cps">Cancelable Progressor Source to show the progression</param> /// <returns>An error comment if needed, empty of no error</returns> private async Task <string> RunCancelableEnclosure(CancelableProgressorSource cps) { string status = ""; List <Guid> listIds = null; NetworkDiagram myDiagram = null; await QueuedTask.Run(() => { cps.Progressor.Max = 3; cps.Progressor.Value += 0; cps.Progressor.Status = (cps.Progressor.Value * 100 / cps.Progressor.Max) + @" % Completed"; cps.Progressor.Message = "Step 1 – Get Selected Guids"; try { if (m_DiagramManager == null) { UtilityNetwork un = GetUtilityNetworkFromActiveMap(); if (un == null) { return; } m_DiagramManager = un.GetDiagramManager(); if (m_DiagramManager == null) { return; } } if (m_Template == null) { m_Template = m_DiagramManager.GetDiagramTemplate(csTemplateName); if (m_Template == null) { return; } } listIds = GetSelectedGuidFromActiveMap(); if (listIds.Count == 0) { return; } } catch (Exception ex) { status = string.Format("Selected guids\n{0}", ExceptionFormat(ex)); } }, cps.Progressor); await QueuedTask.Run(() => { cps.Progressor.Value += 1; cps.Progressor.Status = (cps.Progressor.Value * 100 / cps.Progressor.Max) + @" % Completed"; cps.Progressor.Message = string.Format("Step 2 – Generate a diagram based on the '{0}' template", csTemplateName); try { // generate a diagram myDiagram = m_DiagramManager.CreateNetworkDiagram(diagramTemplate: m_Template, globalIDs: listIds); } catch (Exception ex) { if (string.IsNullOrEmpty(status)) { status = string.Format("Generate diagram\n{0}", ExceptionFormat(ex)); } else { status = string.Format("Generate diagram\n{0}", ExceptionFormat(ex)); } } }, cps.Progressor); await QueuedTask.Run(() => { cps.Progressor.Value += 1; cps.Progressor.Status = (cps.Progressor.Value * 100 / cps.Progressor.Max) + @" % Completed"; cps.Progressor.Message = "Step 3 – Apply the EnclosureLayout custom telco layout"; try { // apply the telco custom layout EnclosureLayout myLayout = new EnclosureLayout(); myLayout.Execute(myDiagram); ShowDiagram(myDiagram); } catch (Exception ex) { if (string.IsNullOrEmpty(status)) { status = string.Format("Apply layout\n{0}", ExceptionFormat(ex)); } else { status = string.Format("Apply layout\n{0}", ExceptionFormat(ex)); } } }); return(status); }
protected override void OnClick() => ThreadService.RunOnBackground(() => { Log.Debug("Running Area of Review Validation"); var progressDialog = new ProgressDialog("🔍 Finding issues...", "Cancel", 100, false); var progressor = new CancelableProgressorSource(progressDialog).Progressor; progressDialog.Show(); var authorizations = new Dictionary <string, List <long> >(); var noAreaOfReview = new HashSet <long>(); var tableName = "UICWell"; using (var table = LayerService.GetTableFromLayersOrTables("UICWell", MapView.Active.Map)) { progressor.Value = 10; if (table == null) { NotificationService.NotifyOfMissingLayer(tableName); progressDialog.Hide(); return; } var filter = new QueryFilter { SubFields = "OBJECTID,AUTHORIZATION_FK", WhereClause = "Authorization_FK is not null AND AOR_FK is null" }; Log.Verbose("Getting wells with an authorization but no area of review"); using (var cursor = table.Search(filter)) { while (cursor.MoveNext()) { var oid = Convert.ToInt64(cursor.Current["OBJECTID"]); var guid = Convert.ToString(cursor.Current["AUTHORIZATION_FK"]); if (authorizations.ContainsKey(guid)) { authorizations[guid].Add(oid); continue; } authorizations.Add(guid, new List <long> { oid }); } } } Log.Verbose("Got authorizations {dict}", authorizations); progressor.Value = 40; tableName = "UICAuthorization"; var table2 = LayerService.GetStandaloneTable(tableName, MapView.Active.Map); progressor.Value = 50; if (table2 == null) { NotificationService.NotifyOfMissingLayer(tableName); progressDialog.Hide(); return; } var filter2 = new QueryFilter { SubFields = "GUID", WhereClause = $"AuthorizationType IN ('IP', 'AP') AND GUID IN ({string.Join(",", authorizations.Keys.Select(x => $"'{x}'"))})" }; Log.Verbose("searching for well authorizations with type IP or AP"); using (var cursor = table2.Search(filter2)) { while (cursor.MoveNext()) { var guid = Convert.ToString(cursor.Current["GUID"]); authorizations[guid].ForEach(x => noAreaOfReview.Add(x)); } } Log.Verbose("got the guids {dict}", authorizations); progressor.Value = 90; if (noAreaOfReview.Count == 0) { NotificationService.NotifyOfValidationSuccess(); progressDialog.Hide(); return; } Log.Verbose("Found {count} wells with no AOR with an authorization of IP or AP", noAreaOfReview.Count); var layerName = "UICWell"; var layer = LayerService.GetLayer(layerName, MapView.Active.Map); if (layer == null) { NotificationService.NotifyOfMissingLayer(layerName); progressDialog.Hide(); return; } Log.Verbose("Selecting Wells"); progressor.Value = 95; MapView.Active.Map.SetSelection(new Dictionary <MapMember, List <long> > { { layer, noAreaOfReview.ToList() } }); progressor.Value = 100; progressDialog.Hide(); NotificationService.NotifyOfValidationFailure(noAreaOfReview.Count); Log.Verbose("Zooming to selected"); MapView.Active.ZoomToSelectedAsync(TimeSpan.FromSeconds(1.5)); Log.Debug("Finished Authorization Validation"); });