/// <summary>
        /// Updates the combo box with the colorizers that can be applied to the selected layer.
        /// </summary>
        /// <param name="basicRasterLayer">the selected layer.</param>
        private async Task UpdateCombo(BasicRasterLayer basicRasterLayer)
        {
            try
            {
                await QueuedTask.Run(() =>
                {
                    // Gets a list of raster colorizers that can be applied to the selected layer.
                    _applicableColorizerList = basicRasterLayer.GetApplicableColorizers();
                });


                if (_applicableColorizerList == null)
                {
                    Add(new ComboBoxItem("No colorizers found"));
                    return;
                }

                // Adds new combox box item for how many colorizers found.
                Add(new ComboBoxItem($@"{_applicableColorizerList.Count()} Colorizer{(_applicableColorizerList.Count() > 1 ? "s" : "")} found"));

                //Iterates through the applicable colorizer collection to get the colorizer names, and add to the combo box.
                foreach (var rasterColorizerType in _applicableColorizerList)
                {
                    // Gets the colorizer name from the RasterColorizerType enum.
                    string ColorizerName = Enum.GetName(typeof(RasterColorizerType), rasterColorizerType);
                    Add(new ComboBoxItem(ColorizerName));
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Exception caught on Update combo box:" + ex.Message, "Exception", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
        protected override void OnClick()
        {
            if (this.IsChecked)
            {
                MapViewCameraChangedEvent.Unsubscribe(MapViewCameraCanged);
                this.IsChecked = false;
                this.Caption   = "Activate";

                try
                {
                    string currentViewFile = Path.Combine(_saveDirectory, _currentViewFileName);

                    if (File.Exists(currentViewFile))
                    {
                        File.Delete(currentViewFile);
                    }
                } catch (Exception ex)
                {
                    MessageBox.Show("Deactivation Failed...\n" + ex.Message);
                }
            }
            else
            {
                MapViewCameraChangedEvent.Subscribe(MapViewCameraCanged, false);
                WriteCurrentView();
                WriteNetworkLink();
                this.IsChecked = true;
                this.Caption   = "Deactivate";
            }
        }
Example #3
0
        /// <summary>
        /// Zoom to selection
        /// </summary>
        private async void Zoom2Select()
        {
            var mapView = MapView.Active;

            if (mapView == null)
            {
                return;
            }
            await QueuedTask.Run(() =>
            {
                //select features that intersect the sketch geometry
                var selection = mapView.Map.GetSelection()
                                .Where(kvp => kvp.Key is BasicFeatureLayer)
                                .ToDictionary(kvp => (BasicFeatureLayer)kvp.Key, kvp => kvp.Value);

                //zoom to selection
                MapView.Active.ZoomToAsync(selection.Select(kvp => kvp.Key), true);
            }).ContinueWith(t =>
            {
                if (t.Exception != null)
                {
                    var aggException = t.Exception.Flatten();
                    var sb           = new StringBuilder();
                    foreach (var exception in aggException.InnerExceptions)
                    {
                        sb.AppendLine(exception.Message);
                    }
                    MessageBox.Show(sb.ToString(), "Error in Zoom2Select", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            });
        }
        /// <summary>
        /// Update the field with a given value (int)
        /// </summary>
        /// <param name="status"></param>
        /// <param name="editName"></param>
        public void Update(int status, string editName)
        {
            QueuedTask.Run(() => {
                try
                {
                    var basicfeaturelayer = _selectedLayer as BasicFeatureLayer;
                    var selection         = basicfeaturelayer.GetSelection();
                    var oidset            = selection.GetObjectIDs();

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

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

                    basicfeaturelayer.ClearSelection();
                } catch (Exception ex)
                {
                    MessageBox.Show("Error: " + ex.Message);
                }
            });
        }
        /// <summary>
        /// Applys the domain code to the currenly selected feature
        /// </summary>
        /// <param name="code"></param>
        internal async void ApplyDomain(DomainCode code)
        {
            if (await CheckRequirements())
            {
                await QueuedTask.Run(() =>
                {
                    try
                    {
                        Selection selection = _selectedLayer.GetSelection();
                        var oidset          = selection.GetObjectIDs();

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

                        var op  = new EditOperation();
                        op.Name = "Set Domain to " + ((int)code).ToString();
                        op.Modify(insp);
                        op.Execute();
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("Error: " + ex.Message);
                    }
                });
            }
        }
        protected async override void OnClick()
        {
            // TODO: Step 5: Fine Grained - select features using where clause and then zoom to selection
            // TODO: Step 6: Fine Grained - correct the layer name and where clause
            var featureLayerName    = "Crimes";
            var featureSelectClause = "Major_Offense_Type <> 'Larceny' And Neighborhood = 'CATHEDRAL PARK'";

            await Module1.SelectByAttributeAsync(featureLayerName, featureSelectClause)
            .ContinueWith(t =>
            {
                if (t.Exception != null)
                {
                    // if an exception was thrown in the async task we can process the result here:
                    var aggException = t.Exception.Flatten();
                    var sb           = new StringBuilder();
                    foreach (var exception in aggException.InnerExceptions)
                    {
                        sb.AppendLine(exception.Message);
                    }
                    MessageBox.Show(sb.ToString(), "Error in SelectByAttributeAsync", MessageBoxButton.OK, MessageBoxImage.Error);
                }
                else
                {
                    MessageBox.Show(string.Format("{0} features selected", t.Result), "Feature Selection");
                }
            });;
        }
Example #7
0
        private async void GetSelectedFeatures(FeatureLayer selectedFeatureLayer)
        {
            System.Diagnostics.Debug.WriteLine("GetSelectedFeatures");
            //Get the active map view.
            var theMapView = MapView.Active;

            if (theMapView == null || selectedFeatureLayer == null)
            {
                System.Diagnostics.Debug.WriteLine("theMapView is null -> can't load selected features");
                return;
            }
            await QueuedTask.Run(() =>
            {
                // Get all selected features for selectedFeatureLayer
                // and populate a datatable with data and column headers
                var resultTable = new DataTable();
                using (var rowCursor = selectedFeatureLayer.GetSelection().Search(null))
                {
                    bool bDefineColumns = true;
                    while (rowCursor.MoveNext())
                    {
                        var anyRow = rowCursor.Current;
                        if (bDefineColumns)
                        {
                            foreach (var fld in anyRow.GetFields().Where(fld => fld.FieldType != FieldType.Geometry))
                            {
                                resultTable.Columns.Add(new DataColumn(fld.Name, typeof(string))
                                {
                                    Caption = fld.AliasName
                                });
                            }
                        }
                        var addRow = resultTable.NewRow();
                        foreach (var fld in anyRow.GetFields().Where(fld => fld.FieldType != FieldType.Geometry))
                        {
                            addRow[fld.Name] = (anyRow[fld.Name] == null) ? string.Empty : anyRow[fld.Name].ToString();
                        }
                        resultTable.Rows.Add(addRow);
                        bDefineColumns = false;
                    }
                }
                lock (_lockSelectedFeaturesDataTable) _selectedFeaturesDataTable = resultTable;
            }).ContinueWith(t =>
            {
                if (t.Exception != null)
                {
                    var aggException = t.Exception.Flatten();
                    var sb           = new StringBuilder();
                    foreach (var exception in aggException.InnerExceptions)
                    {
                        sb.AppendLine(exception.Message);
                    }
                    MessageBox.Show(sb.ToString(), "Error in GetSelectedFeatures", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            });

            NotifyPropertyChanged(() => SelectedFeatureDataTable);
        }
        /// <summary>
        /// Check to make sure the enviornment is set up correctly before processing the users request
        ///
        /// </summary>
        /// <returns></returns>
        private async Task <bool> CheckRequirements()
        {
            if (_selectedMap == null)
            {
                MessageBox.Show("Select A Map In Domain Appointer Settings");
                return(false);
            }

            if (_selectedLayer == null)
            {
                MessageBox.Show("Select A Layer in Domain Appointer Settings");
                return(false);
            }

            if (_selectedField == null)
            {
                MessageBox.Show("Select a Field in Domain Appointer Settings");
            }

            bool canEditData = false;

            await QueuedTask.Run(() =>
            {
                canEditData = _selectedLayer.CanEditData();
            });

            if (!canEditData)
            {
                MessageBox.Show("Feature Layer '" + _selectedLayer.Name + "' Is not Editable");
                return(false);
            }

            IEnumerable <Field> fields = null;

            await QueuedTask.Run(() =>
            {
                Table table = _selectedLayer.GetTable();
                if (table is FeatureClass)
                {
                    FeatureClass featureclass = table as FeatureClass;
                    using (FeatureClassDefinition def = featureclass.GetDefinition())
                    {
                        fields = def.GetFields();
                    }
                }
            });

            var match = fields.FirstOrDefault(field => field.Name.ToLower().Contains(_selectedField.ToLower()));

            if (match == null)
            {
                MessageBox.Show("The field '" + _selectedField + "' is Missing From '" + _selectedLayer.Name + "' Feature Layer");
                return(false);
            }


            return(true);
        }
        /// <summary>
        /// The on comboBox selection change event.
        /// </summary>
        /// <param name="item">The newly selected combo box item</param>
        protected override void OnSelectionChange(ComboBoxItem item)
        {
            if (item == null)
            {
                MessageBox.Show("The combo box item is null.", "Combo box Error:", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            if (item.Text.StartsWith("Msg: "))
            {
                return;
            }
            if (string.IsNullOrEmpty(item.Text))
            {
                MessageBox.Show("The combo box item text is null or empty.", "Combo box Error:", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            if (MapView.Active == null)
            {
                MessageBox.Show("There is no active MapView.", "Combo box Error:", MessageBoxButton.OK, MessageBoxImage.Error);
            }

            try
            {
                // Gets the first selected layer in the active MapView.
                Layer firstSelectedLayer = MapView.Active.GetSelectedLayers().First();

                // Gets the BasicRasterLayer from the selected layer.
                if (firstSelectedLayer is BasicRasterLayer)
                {
                    basicRasterLayer = (BasicRasterLayer)firstSelectedLayer;
                }
                else if (firstSelectedLayer is MosaicLayer)
                {
                    basicRasterLayer = ((MosaicLayer)firstSelectedLayer).GetImageLayer() as BasicRasterLayer;
                }
                else
                {
                    MessageBox.Show("The selected layer is not a basic raster layer", "Select Layer Error:", MessageBoxButton.OK, MessageBoxImage.Error);
                }
                if (basicRasterLayer != null)
                {
                    switch (item.Text)
                    {
                    case @"Attribute driven RGB":
                        SetRasterColorByRGBAttributeFields(basicRasterLayer as RasterLayer, _fieldList);
                        break;

                    default:
                        var style = Project.Current.GetItems <StyleProjectItem>().First(s => s.Name == "ArcGIS Colors");
                        SetRasterColorByAttributeField(basicRasterLayer as RasterLayer, item.Text, style);
                        break;
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Exception caught in OnSelectionChange:" + ex.Message, "Exception", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
        private async Task <Boolean> CheckRequirements()
        {
            if (_selectedMap == null)
            {
                MessageBox.Show("Select A Map In File Tile Opener Settings");
                return(false);
            }

            if (_selectedFeatureLayer == null)
            {
                MessageBox.Show("Select A Layer in File Tile Opener Settings");
                return(false);
            }

            if (_selectedField == null)
            {
                MessageBox.Show("Select a Field in File Tile Opener Settings");
            }

            IEnumerable <Field> fields = null;

            await QueuedTask.Run(() =>
            {
                Table table = _selectedFeatureLayer.GetTable();
                if (table is FeatureClass)
                {
                    FeatureClass featureclass = table as FeatureClass;
                    using (FeatureClassDefinition def = featureclass.GetDefinition())
                    {
                        fields = def.GetFields();
                    }
                }
            });

            var match = fields.FirstOrDefault(field => field.Name.ToLower().Contains(_selectedField.ToLower()));

            if (match == null)
            {
                MessageBox.Show("This field '" + _selectedField + "' is Missing From '" + _selectedFeatureLayer.Name + "' Feature Layer", "Oops");
                return(false);
            }

            // No need to check for whitespace. I disallow this in the 'view'.
            if (String.IsNullOrEmpty(_fileExtension))
            {
                MessageBox.Show("Type or Choose a File Extension in File Tile Opener Settings");
                return(false);
            }

            if (String.IsNullOrWhiteSpace(_fileWorkspace))
            {
                MessageBox.Show("Type or Choose a File Workspace in File Tile Opener Settings");
                return(false);
            }

            return(true);
        }
        public bool ShowErrorDialog(string jobId)
        {
            var result =
                MessageBox.Show(
                    $"An error has occured while executing the job {jobId}. Would you like to open the error report now?",
                    "Unexpected error", MessageBoxButton.YesNo, MessageBoxImage.Error);

            return(result == MessageBoxResult.Yes);
        }
Example #12
0
        /// <summary>
        /// utility function to open and activate a map given the map url.
        /// </summary>
        /// <param name="url">unique map identifier</param>
        internal static async void OpenAndActivateMap(string url)
        {
            try
            {
                // if active map is the correct one, we're done
                if (MapView.Active != null && MapView.Active.Map != null && MapView.Active.Map.URI == url)
                {
                    return;
                }

                // get the map from the project item
                Map map = null;
                await QueuedTask.Run(() =>
                {
                    var mapItem = Project.Current.GetItems <MapProjectItem>().FirstOrDefault(i => i.Path == url);
                    if (mapItem != null)
                    {
                        map = mapItem.GetMap();
                    }
                });

                // url is not a project item - oops
                if (map == null)
                {
                    return;
                }

                // check the open panes to see if it's open but just needs activating
                var mapPanes = FrameworkApplication.Panes.OfType <IMapPane>();
                foreach (var mapPane in mapPanes)
                {
                    if (mapPane.MapView?.Map?.URI == null)
                    {
                        continue;
                    }

                    if (mapPane.MapView.Map.URI != url)
                    {
                        continue;
                    }

                    var pane = mapPane as Pane;
                    pane?.Activate();

                    return;
                }

                // it's not currently open... so open it
                await FrameworkApplication.Panes.CreateMapPaneAsync(map);
            }
            catch (Exception ex)
            {
                MessageBox.Show($@"Error in OpenAndActivateMap: {ex.Message}");
            }
        }
        /// <summary>
        /// Goes to the next feature if applicable. A bool can be set if you want to keep the current scale or not
        /// </summary>
        /// <param name="featureLayer"></param>
        /// <param name="KeepScale"></param>
        public async void GoToNext(Layer featureLayer, bool KeepScale)
        {
            var basicfeaturelayer = _selectedLayer as BasicFeatureLayer;

            QueryFilter queryfilter = new QueryFilter();

            queryfilter.WhereClause = InpsectorFieldName + " IS NULL";
            try
            {
                await QueuedTask.Run(() =>
                {
                    basicfeaturelayer.ClearSelection();
                    FeatureClass featureclass = Utilities.ProUtilities.LayerToFeatureClass(_selectedLayer);
                    using (RowCursor cursor = featureclass.Search(queryfilter, false))
                    {
                        while (cursor.MoveNext())
                        {
                            using (Feature feature = (Feature)cursor.Current)
                            {
                                var shape         = feature.GetShape() as Geometry;
                                Envelope envelope = shape.Extent;
                                envelope.Expand(5, 5, true);

                                if (!KeepScale)
                                {
                                    MapView.Active.ZoomTo(envelope, null, false);
                                }
                                else
                                {
                                    MapView.Active.PanTo(shape);  // Okay, Scale implementation
                                }
                                // Get The Next Feature
                                IReadOnlyDictionary <MapMember, List <long> > NextFeature = new Dictionary <MapMember, List <long> >
                                {
                                    { _selectedLayer, new List <long> {
                                          feature.GetObjectID()
                                      } }
                                };

                                _selectedMap.SetSelection(NextFeature, SelectionCombinationMethod.New);

                                //queryfilter.WhereClause = "= " + feature.GetObjectID().ToString();
                                // _selectedLayer.Select(queryfilter, SelectionCombinationMethod.New);

                                return;
                            }
                        }
                    }
                });
            } catch (Exception ex)
            {
                MessageBox.Show("Error: " + ex.Message);
            }
        }
        // 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();
        }
        protected override Task <bool> OnSketchCompleteAsync(Geometry geometry)
        {
            if (reference != null && (geometry as MapPoint) != null)
            {
                reference.LoadFile(geometry as MapPoint);
            }
            else
            {
                MessageBox.Show("Is that you davy???? Davvvyyyyyyyy....", "Error");
            }


            return(base.OnSketchCompleteAsync(geometry));
        }
        protected void CheckUpdatedVersion(string pathProExe)
        {
            try
            {
                //Fetch the conda path, Which is required to invoke and run Conda packages
                var condafilepath = System.IO.Path.Combine(pathProExe.Substring(0, pathProExe.LastIndexOf("envs") - 1), @"scripts\conda");

                this.CheckUpdatedVersionAync(condafilepath);
            }
            catch (Exception e)
            {
                MessageBox.Show("Error in checking latest version " + e.Message, "   Error ");
            }
        }
Example #17
0
        protected void HandleError(string message, Exception e, bool noMessageBox = false)
        {
            _msg.Error(message, e);

            if (!noMessageBox)
            {
                Application.Current.Dispatcher.Invoke(
                    () =>
                {
                    MessageBox.Show(message, "Error", MessageBoxButton.OK,
                                    MessageBoxImage.Error);
                });
            }
        }
        protected override void OnClick()
        {
            if (Dockpane1ViewModel.token != "")
            {
                //Dockpane1View.ReinitializeComponent();
                //Module1.Reinitialice();
                Dockpane1ViewModel.Show();
            }

            else
            {
                MessageBox.Show("Debe iniciar sesiĆ³n en ArcGIS Pro para acceder al administrador");
            }
        }
        /// <summary>
        /// Validates Conditions for user before attempting to edit the data
        /// </summary>
        /// <returns></returns>
        private async Task <bool> PrepStatus()
        {
            if (_selectedMap == null)
            {
                MessageBox.Show("Select A Map In Inspector Settings");
                return(false);
            }

            if (_selectedLayer == null)
            {
                MessageBox.Show("Select A Layer in Inspector Settings");
                return(false);
            }

            IEnumerable <Field> fields       = null;
            FeatureClass        featureclass = null;

            await QueuedTask.Run(() =>
            {
                // Get the fields
                Table table = (_selectedLayer as FeatureLayer).GetTable();

                if (table is FeatureClass)
                {
                    featureclass = table as FeatureClass;
                    using (FeatureClassDefinition def = featureclass.GetDefinition())
                    {
                        fields = def.GetFields();
                    }
                }
            });


            var match = fields.FirstOrDefault(field => field.Name.ToLower().Contains(InpsectorFieldName.ToLower()));

            if (match == null)
            {
                MessageBox.Show("Add field named '" + InpsectorFieldName + "' to '" + _selectedLayer.Name + "' layer of type Integer");
                return(false);
            }
            match = fields.FirstOrDefault(field => (field.FieldType == FieldType.SmallInteger || field.FieldType == FieldType.Integer));
            if (match == null)
            {
                MessageBox.Show("Add field named '" + InpsectorFieldName + "' to '" + _selectedLayer.Name + "' layer of type Integer");
                return(false);
            }


            return(true);
        }
        /// <summary>
        /// Generates File List and Attempts To Load it
        /// </summary>
        private async void LoadFiles()
        {
            if (await CheckRequirements())
            {
                await GenerateFileList();

                if (ValidateFileList())
                {
                    await LoadFileList();
                }
                else
                {
                    MessageBox.Show("Current Configuration Could Not Match Any Files in the File Workspace", "Something Went Wrong ...");
                }
            }
        }
        private async void CheckUpdatedVersionAync(string condafilepath)
        {
            try
            {
                string _condaPackageVersion = "0";
                string _localPackageVersion = "0";
                // Process to fetch Conda package details
                using (var process = new Process
                {
                    StartInfo =
                    {
                        FileName               = condafilepath, Arguments             = " search -c " + _channelName + "  " + _packageName,
                        UseShellExecute        = false,         CreateNoWindow        = true,
                        RedirectStandardOutput = true,          RedirectStandardError = true
                    },
                    EnableRaisingEvents = true
                })
                {
                    //Run package search from conda to fetch the current package version from Conda
                    var outputsearchresult = await FetchCondaPackageVersionAsync(process).ConfigureAwait(false);

                    //Run package list from local to fetch the current linstalled package version
                    _localPackageVersion = FetchLocalPackageVersion(condafilepath, _packageName);

                    _condaPackageVersion = outputsearchresult.Split(new string[] { "liquidshca" }, StringSplitOptions.None)[1].Split('p')[0].Trim();

                    //Check the both version or diffrent, then invoke update button.
                    if (!_condaPackageVersion.Contains(_localPackageVersion))
                    {
                        System.Windows.Application.Current.Dispatcher.Invoke(
                            System.Windows.Threading.DispatcherPriority.Normal, (Action) delegate
                        {
                            // Update UI component here
                            Caption        = "Update Liquids HCA Tool";
                            TooltipHeading = "Updates Liquids HCA Tool";
                            Tooltip        = "Updates the G2-IS Liquids HCA Tool from version " + _localPackageVersion + " to version '" + _condaPackageVersion;
                            LargeImage     = new System.Windows.Media.Imaging.BitmapImage(new Uri(
                                                                                              @"pack://application:,,,/ArcGIS.Desktop.Resources;component/Images/GeoprocessingToolboxPythonNew32.png"));
                        });
                    }
                }
            }
            catch (Exception e)
            {
                MessageBox.Show("Error in latest version checking " + e.Message, "  Error");
            }
        }
        /// <summary>
        /// Attempts to load in each File file into the selected map
        /// </summary>
        /// <returns></returns>
        private async Task LoadFileList()
        {
            int        couldNotLoadCount = 0;
            bool       itWorked          = false;
            GroupLayer group             = null;

            await QueuedTask.Run(() =>
            {
                group = LayerFactory.Instance.CreateGroupLayer(_selectedMap, 0, "Files");
            });

            foreach (KeyValuePair <String, Boolean> File in _FileList)
            {
                if (File.Value)
                {
                    if (!itWorked)
                    {
                        SaveFileExtensionsToDisk(_fileExtension);
                    }

                    itWorked = true;

                    try
                    {
                        Uri uri = new Uri(File.Key);
                        await QueuedTask.Run(() =>
                        {
                            LayerFactory.Instance.CreateLayer(uri, group).SetExpanded(false);
                        });
                    }
                    catch (Exception yourBest) // But you don't succeed
                    {
                        yourBest.ToString();
                        // Just So We Get No Crashes ;)
                    }
                }
                else
                {
                    couldNotLoadCount += 1;
                }
            }

            if (couldNotLoadCount > 0)
            {
                MessageBox.Show("There were " + Convert.ToString(couldNotLoadCount) + " File that could not be loaded..", "Notice");
            }
        }
Example #23
0
        public async override void OnDrop(DropInfo dropInfo)
        {
            var mapView = MapView.Active;

            if (mapView == null)
            {
                MessageBox.Show("Drop Into A Map", "Woah", MessageBoxButton.OK, MessageBoxImage.Stop);
                dropInfo.Handled = true;
                return;
            }

            IList <String> Files = dropInfo.Items.Select(item => item.Data.ToString()).ToList();

            // If there is more than on file promt the user to see if they would like to put the files into a group or not
            if (Files.Count > 1)
            {
                var result = MessageBox.Show(string.Format("Add {0} SID Files to a group?", Files.Count), "Quick", MessageBoxButton.YesNoCancel);

                switch (result)
                {
                case MessageBoxResult.Cancel:
                    return;

                case MessageBoxResult.No:
                    Utilities.ProUtilities.AddFilesToMap(Files, mapView.Map);
                    break;

                case MessageBoxResult.Yes:

                    GroupLayer group = null;
                    await QueuedTask.Run(() =>
                    {
                        group = LayerFactory.Instance.CreateGroupLayer(mapView.Map, 0, "SID Group");
                    });

                    Utilities.ProUtilities.AddFilesToMap(Files, group);
                    break;
                }
            }
            else
            {
                Utilities.ProUtilities.AddFilesToMap(Files, mapView.Map);
            }

            dropInfo.Handled = true;
        }
Example #24
0
 /// <summary>
 /// utility function to enable an action to run on the UI thread (if not already)
 /// </summary>
 /// <param name="action">the action to execute</param>
 /// <returns></returns>
 internal static void RunOnUiThread(Action action)
 {
     try
     {
         if (IsOnUiThread)
         {
             action();
         }
         else
         {
             Application.Current.Dispatcher.Invoke(action);
         }
     }
     catch (Exception ex)
     {
         MessageBox.Show($@"Error in OpenAndActivateMap: {ex.Message}");
     }
 }
        protected async override void OnClick()
        {
            // TODO: Step 2: Coarse Grained - select features using where clause and then zoom to selection
            // TODO: Step 3: Coarse Grained - correct the layer name and where clause
            await Geoprocessing.ExecuteToolAsync(
                "SelectLayerByAttribute_management", new string[] {
                "Crimes", "NEW_SELECTION", "Major_Offense_Type = 'Larceny' And Neighborhood = 'CATHEDRAL PARK'"
            }).ContinueWith(t =>
            {
                if (t.Exception != null)
                {
                    // if an exception was thrown in the async task we can process the result here:
                    var aggException = t.Exception.Flatten();
                    var sb           = new StringBuilder();
                    foreach (var exception in aggException.InnerExceptions)
                    {
                        sb.AppendLine(exception.Message);
                    }
                    MessageBox.Show(sb.ToString(), "Error in ExecuteToolAsync", MessageBoxButton.OK, MessageBoxImage.Error);
                }
                else
                {
                    // Examime the results of the GP task
                    if (t.Result.ErrorCode != 0)
                    {
                        var sb = new StringBuilder();
                        foreach (var msg in t.Result.Messages)
                        {
                            sb.AppendLine(msg.Text);
                        }
                        MessageBox.Show(sb.ToString(), "Error in ExecuteToolAsync", MessageBoxButton.OK, MessageBoxImage.Error);
                    }
                    else
                    {
                        System.Diagnostics.Debug.WriteLine(string.Format("GP tool status: {0}", t.Status));
                    }
                }
            });

            // TODO: Step 4: Coarse Grained - Zoom to the selection
            await MapView.Active.ZoomToSelectedAsync(new TimeSpan(0, 0, 3), true);

            MessageBox.Show("CoarseGrained calls completed!");
        }
Example #26
0
        /// <summary>
        /// Generates File List and Attempts To Load it
        /// </summary>
        private async void LoadFiles()
        {
            if (await CheckRequirements())
            {
                await GenerateFileList();

                if (ValidateFileList())
                {
                    var maxCount = Convert.ToUInt32(_fileList.Count());
                    var pd       = new ArcGIS.Desktop.Framework.Threading.Tasks.ProgressDialog("Copying Files", "Canceled", maxCount, false);

                    await CloneFiles(new CancelableProgressorSource(pd), maxCount);
                }
                else
                {
                    MessageBox.Show("Current Configuration Could Not Match Any Files in the File Workspace", "Something Went Wrong ...");
                }
            }
        }
 /// <summary>
 /// Adds the projects maps to the '_maps' Collection
 /// </summary>
 private async void GetMaps()
 {
     _maps.Clear();
     if (Project.Current != null)
     {
         await QueuedTask.Run(() =>
         {
             // GetMap needs to be on the MCT
             foreach (var map in Project.Current.GetItems <MapProjectItem>())
             {
                 _maps.Add(map.GetMap());
             }
         });
     }
     if (_maps.Count <= 0)
     {
         MessageBox.Show("No Maps Exist");
     }
 }
        /// <summary>
        /// Deletes Currently Selected Features and zooms to next feature if applicable
        /// </summary>
        public async void Delete()
        {
            bool proceed = false;

            proceed = await PrepStatus();

            if (!proceed)
            {
                return;
            }

            if (!FeaturesSelected())
            {
                return;
            }

            await QueuedTask.Run(() =>
            {
                try
                {
                    var basicfeaturelayer = _selectedLayer as BasicFeatureLayer;
                    var selection         = basicfeaturelayer.GetSelection();
                    var oidset            = selection.GetObjectIDs();

                    var op  = new EditOperation();
                    op.Name = "Delete Next";

                    foreach (var oid in oidset)
                    {
                        op.Delete(basicfeaturelayer, oid);
                    }

                    op.Execute();
                } catch (Exception ex)
                {
                    MessageBox.Show("Error: " + ex.Message);
                }
            });


            GoToNext(_selectedLayer, false);
        }
        /// <summary>
        /// Updates the combo box with the raster's attribute table field names.
        /// </summary>
        /// <param name="basicRasterLayer">the selected layer.</param>
        private async Task UpdateCombo(BasicRasterLayer basicRasterLayer)
        {
            try
            {
                _fieldList.Clear();
                await QueuedTask.Run(() =>
                {
                    var rasterTbl = basicRasterLayer.GetRaster().GetAttributeTable();
                    if (rasterTbl == null)
                    {
                        return;
                    }
                    var fields = rasterTbl.GetDefinition().GetFields();
                    foreach (var field in fields)
                    {
                        _fieldList.Add(field.Name);
                    }
                });

                bool hasRgb = _fieldList.Contains("red", StringComparer.OrdinalIgnoreCase) &&
                              _fieldList.Contains("green", StringComparer.OrdinalIgnoreCase) &&
                              _fieldList.Contains("blue", StringComparer.OrdinalIgnoreCase);
                if (_fieldList.Count == 0)
                {
                    Add(new ComboBoxItem("Msg: Raster has no Attribute table"));
                    return;
                }
                foreach (var fieldName in _fieldList)
                {
                    Add(new ComboBoxItem(fieldName));
                }
                if (hasRgb)
                {
                    Add(new ComboBoxItem(@"Attribute driven RGB"));
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($@"Exception caught on Update combo box: {ex.Message}", "Exception", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
Example #30
0
        private async void GetFeatureLayers(MapView theMapView)
        {
            System.Diagnostics.Debug.WriteLine("GetFeatureLayers");
            if (theMapView == null)
            {
                System.Diagnostics.Debug.WriteLine("theMapView is null -> can't load any feature layers");
                return;
            }

            // get new feature layer list
            SelectedFeatureDataTable = null;
            FeatureLayers.Clear();
            await QueuedTask.Run(() =>
            {
                var featureLayers = theMapView.Map.Layers.OfType <FeatureLayer>();
                lock (_lockFeaturelayers)
                {
                    _featureLayers.Clear();
                    foreach (var featureLayer in featureLayers)
                    {
                        _featureLayers.Add(featureLayer);
                    }
                }
            }).ContinueWith(t =>
            {
                if (t.Exception != null)
                {
                    var aggException = t.Exception.Flatten();
                    var sb           = new StringBuilder();
                    foreach (var exception in aggException.InnerExceptions)
                    {
                        sb.AppendLine(exception.Message);
                    }
                    MessageBox.Show(sb.ToString(), "Error in GetFeatureLayers", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            });

            NotifyPropertyChanged(() => FeatureLayers);
            //var firstFeatureLayer = FeatureLayers.FirstOrDefault();
            //if (firstFeatureLayer != null) SelectedFeatureLayer = firstFeatureLayer;
        }