internal async void CreatePackage()
        {
            if (_outputMap == null)
            {
                var maps = Project.Current.GetItems <MapProjectItem>();
                foreach (var mapProjectItem in maps)
                {
                    if (!mapProjectItem.Name.Contains("Map"))
                    {
                        continue;
                    }
                    await QueuedTask.Run(() =>
                    {
                        _outputMap = mapProjectItem.GetMap();
                    });

                    break;
                }
            }

            if (_outputMap == null)
            {
                return;
            }

            string[] values   = { "Map", @"c:\temp\MobileMapPackage.mmpk", "", "", "", "", "", "", "Description" };
            var      gpResult = await Geoprocessing.ExecuteToolAsync("CreateMobileMapPackage_management", values);

            Geoprocessing.ShowMessageBox(gpResult.Messages, "GP Messages",
                                         gpResult.IsFailed ? GPMessageBoxStyle.Error : GPMessageBoxStyle.Default);
            //  ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("Mobile map package created.","Geoprocessing Complete");
        }
Beispiel #2
0
        public async void ShowMessageBox()
        {
            #region message_box
            var gp_result = await Geoprocessing.ExecuteToolAsync("management.GetCount", Geoprocessing.MakeValueArray(@"C:\data\f.gdb\hello"));

            // this icon shows up left of content_header
            string icon_src = @"C:\data\Icons\ModifyLink32.png";
            Geoprocessing.ShowMessageBox(gp_result.Messages, "Content Header", GPMessageBoxStyle.Error, "Window Title", icon_src);
            #endregion
        }
Beispiel #3
0
        /// <summary>
        /// Constructs the point and drive time distances to be passed as parameter to ExecuteToolAsync
        /// Runs the DriveTime Analysis
        /// http://sampleserver1.arcgisonline.com/ArcGIS/rest/services/Network/ESRI_DriveTime_US/GPServer/CreateDriveTimePolygons
        /// </summary>
        /// <param name="geometry"></param>
        /// <returns>Geoprocessing result object as a Task</returns>
        protected override async Task <bool> OnSketchCompleteAsync(Geometry geometry)
        {
            var result = await QueuedTask.Run(() =>
            {
                string tool_path = string.Format(@"{0}\ArcGIS.ags\Network/ESRI_DriveTime_US\CreateDriveTimePolygons", Directory.GetCurrentDirectory());
                return(Geoprocessing.ExecuteToolAsync(tool_path, Geoprocessing.MakeValueArray(geometry, "1 2 3")));
            });

            Geoprocessing.ShowMessageBox(result.Messages, "GP Messages", result.IsFailed ? GPMessageBoxStyle.Error : GPMessageBoxStyle.Default);
            return(true);
        }
        protected override async void OnClick()
        {
            try
            {
                IGPResult toolResult = await Execute_ApplySymbologyFromFeatureLayer();

                Geoprocessing.ShowMessageBox(toolResult.Messages, "GP Messages", toolResult.IsFailed ? GPMessageBoxStyle.Error : GPMessageBoxStyle.Default);
            }
            catch (Exception ex)
            {
                MessageBox.Show($@"Exception thrown: {ex}");
            }
        }
        // Snap Environment
        // Snap a line to polygon EDGE, END of another line and to points VERTEX
        //
        protected override async void OnClick()
        {
            GPExecuteToolFlags executeFlags = GPExecuteToolFlags.AddOutputsToMap | GPExecuteToolFlags.GPThread | GPExecuteToolFlags.AddToHistory;

            string toolName = "edit.Snap";

            var environments = Geoprocessing.MakeEnvironmentArray(overwriteoutput: true);

            // make a copy of the input data - this data will be snapped to data specified in snap environment
            var inputFeatures = @"C:\\data\Snapping.gdb\otherline";

            // snapEnvironment parameter is of ValueTable type
            var snapEnvironments = @"C:\\data\Snapping.gdb\poly EDGE '15 Meters';C:\\data\Snapping.gdb\line END '15 Meters';C:\\data\Snapping.gdb\points VERTEX '18 Meters'";

            var parameters2 = Geoprocessing.MakeValueArray(inputFeatures, snapEnvironments);

            var gpResult = await Geoprocessing.ExecuteToolAsync(toolName, parameters2, environments, null, null, executeFlags);

            Geoprocessing.ShowMessageBox(gpResult.Messages, "GP Messages", gpResult.IsFailed ? GPMessageBoxStyle.Error : GPMessageBoxStyle.Default);
        }
Beispiel #6
0
        protected override async void OnClick()
        {
            await QueuedTask.Run(async() =>
            {
                var pointLayer = (MapView.Active.Map.Layers.First(layer => layer.Name.Equals("Points")) as FeatureLayer);

                if (pointLayer == null)
                {
                    MessageBox.Show("Point layer can not be found...", "Error", System.Windows.MessageBoxButton.OK);
                    return;
                }

                try
                {
                    // Get the path to the layer's feature class and path to a new 200-foot buffer feature class
                    string FLPath     = pointLayer.GetFeatureClass().GetDatastore().GetPath().AbsolutePath;
                    var FLPathCombine = Path.GetFullPath(FLPath);
                    string name       = pointLayer.GetFeatureClass().GetName();
                    string infc       = Path.Combine(FLPathCombine, name);
                    string outfc      = Path.Combine(FLPathCombine, "Buffer_" + pointLayer.Name);
                    // Place parameters into an array
                    var parameters = Geoprocessing.MakeValueArray(infc, outfc, "100 Meter");
                    // Place environment settings in an array, in this case, OK to over-write
                    var environments = Geoprocessing.MakeEnvironmentArray(overwriteoutput: true);
                    // Execute the GP tool with parameters
                    var gpResult = await Geoprocessing.ExecuteToolAsync("Buffer_analysis", parameters, environments);
                    // Show a messagebox with the results
                    Geoprocessing.ShowMessageBox(gpResult.Messages, "GP Meldingen", gpResult.IsFailed ? GPMessageBoxStyle.Error : GPMessageBoxStyle.Default);
                    MessageBox.Show("Lets Unit test here..");
                }
                catch (Exception exc)
                {
                    // Catch any exception found and display in a message box
                    MessageBox.Show("Exception caught while trying to run GP tool: " + exc.Message);
                    return;
                }
            });
        }
Beispiel #7
0
        protected override async void OnClick()
        {
            // Toolbox adds a row to the table
            var tbxPath  = Project.Current.HomeFolderPath + @"\Toolbox.pyt\Tool";
            var gpResult = await QueuedTask.Run(() => Geoprocessing.ExecuteToolAsync(tbxPath, Geoprocessing.MakeValueArray()));

            // GP succeeds
            Geoprocessing.ShowMessageBox(gpResult.Messages, "GP Messages", gpResult.IsFailed ? GPMessageBoxStyle.Error : GPMessageBoxStyle.Default);

            // has no effect
            await Project.Current.SaveEditsAsync();

            // has also no effect
            await Project.Current.SaveAsync();

            // write to table
            var createRow = new EditOperation {
                Name = "Create Row in Table"
            };
            bool writeSucceeded = false;
            await QueuedTask.Run(() =>
            {
                using (var geodatabase = new Geodatabase(new FileGeodatabaseConnectionPath(new Uri(Project.Current.DefaultGeodatabasePath))))
                    using (var table = geodatabase.OpenDataset <Table>("TestTable"))
                    {
                        var attributes = new Dictionary <string, object> {
                            { "Something", "Something from Pro" }
                        };

                        createRow.Create(table, attributes);

                        // will fail
                        writeSucceeded = createRow.Execute();
                    }
            });

            MessageBox.Show("EditOperation() was " + (writeSucceeded ? "successful" : "has failed") + " \n" + createRow.ErrorMessage);
        }
Beispiel #8
0
        protected override async void OnClick()
        {
            await QueuedTask.Run(async() =>
            {
                // Check to see if the selected layer is a feature layer, if not, then prompt and exit.
                if (!(MapView.Active.GetSelectedLayers().First() is FeatureLayer featLayer))
                {
                    MessageBox.Show("Selecteer een feature layer in de Contents pane.", "Info");
                    return;
                }

                try
                {
                    // Get the path to the layer's feature class and path to a new 200-foot buffer feature class
                    string FLPath     = featLayer.GetFeatureClass().GetDatastore().GetPath().AbsolutePath;
                    var FLPathCombine = Path.GetFullPath(FLPath);
                    string name       = featLayer.GetFeatureClass().GetName();
                    string infc       = Path.Combine(FLPathCombine, name);
                    string outfc      = Path.Combine(FLPathCombine, "Buffer_" + featLayer.Name);
                    // Place parameters into an array
                    var parameters = Geoprocessing.MakeValueArray(infc, outfc, "100 Meter");
                    // Place environment settings in an array, in this case, OK to over-write
                    var environments = Geoprocessing.MakeEnvironmentArray(overwriteoutput: true);
                    // Execute the GP tool with parameters
                    var gpResult = await Geoprocessing.ExecuteToolAsync("Buffer_analysis", parameters, environments);
                    // Show a messagebox with the results
                    Geoprocessing.ShowMessageBox(gpResult.Messages, "GP Meldingen", gpResult.IsFailed ? GPMessageBoxStyle.Error : GPMessageBoxStyle.Default);
                }
                catch (Exception exc)
                {
                    // Catch any exception found and display in a message box
                    MessageBox.Show("Exception caught while trying to run GP tool: " + exc.Message);
                    return;
                }
            });
        }
        protected override async void OnClick()
        {
            var result = await Geoprocessing.ExecuteToolAsync("analysis.Near", new string[] {
                @"Campings_FGDB", "Hydrographie\\Cours d'eau", "50 Meters", "false", "false", "PLANAR"
            });

            if (result.IsFailed)
            {
                Geoprocessing.ShowMessageBox(result.Messages, "GP Messages", result.IsFailed ? GPMessageBoxStyle.Error : GPMessageBoxStyle.Default);
                return;
            }

            #region Assign Symbology to selected features
            if (!result.IsFailed)
            {
                var campingsLayer = MapView.Active.Map.FindLayers("Campings_FGDB").FirstOrDefault() as BasicFeatureLayer;
                if (campingsLayer != null)
                {
                    await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
                                                                                  campingsLayer.SetDefinitionQuery("NEAR_DIST > -1"));
                }
            }
            #endregion
        }
Beispiel #10
0
        // Setting environments, MakeEnvironmentArray
        public async void SetEnvironment()   // Task<IGPResult>
        {
            #region gp_environments
            // get the syntax of the tool from Python window or from tool help page
            string in_features  = @"C:\data\data.gdb\HighwaysWeb84";
            string out_features = @"C:\data\data.gdb\HighwaysUTM";
            var    param_values = Geoprocessing.MakeValueArray(in_features, out_features);

            // crate the spatial reference object to pass as an argument to management.CopyFeatures tool
            var sp_ref = await QueuedTask.Run(() => {
                return(SpatialReferenceBuilder.CreateSpatialReference(26911));    // UTM 83 11N: 26911
            });

            // set output coordinate system environment
            var environments = Geoprocessing.MakeEnvironmentArray(outputCoordinateSystem: sp_ref);
            // set environments in the 3rd parameter
            var gp_result = await Geoprocessing.ExecuteToolAsync("management.CopyFeatures", param_values, environments, null, null, GPExecuteToolFlags.AddOutputsToMap);

            Geoprocessing.ShowMessageBox(gp_result.Messages, "Contents", GPMessageBoxStyle.Default, "Window Title");

            //return gp_result;

            #endregion
        }
Beispiel #11
0
        /// <summary>
        /// Downloads the quads from the Planet servers using a geometry,
        /// an array of DD coords, raster service name and raster serviceid.
        /// </summary>
        /// <param name="geometry"></param>
        /// <param name="ff"></param>
        /// <param name="rasterseriesname"></param>
        /// <param name="rasterseriesid"></param>
        /// <returns></returns>
        private async Task getQuadsAsync(Geometry geometry, string[] ff, string rasterseriesname, string rasterseriesid)
        {
            //Mosicing can only happen with a standard license, warn user
            var ll = ArcGIS.Core.Licensing.LicenseInformation.Level;

            if (ll == ArcGIS.Core.Licensing.LicenseLevels.Basic)
            {
                MessageBoxResult messageBoxResult = MessageBox.Show("ArcGIS Pro is currently using a Basic license. The data source tiles can still be downloaded but a Raster Mosaic will not created." + Environment.NewLine + "Would you like to continue?", "Basic License Detected", MessageBoxButton.YesNo, MessageBoxImage.Warning);
                if (messageBoxResult == MessageBoxResult.No)
                {
                    return;
                }
            }

            //should not use a using statement, need to fix
            //get a list of quads as GeoTiffs2 items by querying the rest endpoint of the selected layer
            //with the geometry and points
            using (HttpClient client = new HttpClient())
            {
                var response = client.GetAsync("https://api.planet.com/basemaps/v1/mosaics/" + rasterseriesid + "/quads?api_key=" + Module1.Current.API_KEY.API_KEY_Value + "&bbox=" + ff[1] + "," + ff[0] + "," + ff[3] + "," + ff[2]).Result;
                ObservableCollection <Data.GeoTiffs2> geotiffs = new ObservableCollection <Data.GeoTiffs2>();
                if (response.IsSuccessStatusCode)
                {
                    Task <string> responseContent = response.Content.ReadAsStringAsync();
                    Quads         quads           = JsonConvert.DeserializeObject <Quads>(responseContent.Result);
                    if (quads.items.Count() > 50)
                    {
                        MessageBox.Show("More than 50 quads selected, please download a smaller area.");
                        return;
                    }
                    foreach (Item item in quads.items)
                    {
                        geotiffs.Add(new Data.GeoTiffs2()
                        {
                            Name = item.id, DownloadURL = item._links.download
                        });
                    }
                    Console.WriteLine(responseContent.Result);
                }
                else
                {
                    MessageBox.Show("Extent not found");
                    return;
                }
                string area = "";
                if (geometry.GeometryType == GeometryType.Polygon)
                {
                    Polygon polygon = (Polygon)geometry;
                    if (geometry.SpatialReference.Unit.Name == "Foot_US")
                    {
                        double sqMeters = AreaUnit.SquareFeet.ConvertToSquareMeters(polygon.Area);
                        area = AreaUnit.SquareKilometers.ConvertFromSquareMeters(sqMeters).ToString();
                    }
                    else if (geometry.SpatialReference.Unit.Name == "Meter")
                    {
                        area = AreaUnit.SquareKilometers.ConvertFromSquareMeters(polygon.Area).ToString();
                    }

                    area = " Approx Sqkm: " + area.Substring(0, area.IndexOf("."));
                }

                //set up the Folderselector view with a list of the quads and area
                FolderSelector folderSelector = new FolderSelector();
                folderSelector.lbxGrids.ItemsSource = geotiffs;
                folderSelector.ShowNewFolderButton  = false;
                folderSelector.ShowActivated        = true;
                folderSelector.SizeToContent        = SizeToContent.Width;
                object da = folderSelector.txtGrids.DataContext;
                if (da is Data.BaseItem ba)
                {
                    ba.QuadCount = "Total basemap quads selected: " + geotiffs.Count.ToString() + area;
                }
                folderSelector.ShowDialog();

                //If the user clicked OK on the view start the download
                if ((bool)folderSelector.DialogResult)
                {
                    //Do the download
                    string        savelocation = folderSelector.SelectedPath;
                    List <string> tiffs        = new List <string>();
                    int           i            = 0;
                    int           total        = geotiffs.Count();

                    foreach (Data.GeoTiffs2 quad in geotiffs)
                    {
                        if (string.IsNullOrEmpty(quad.DownloadURL))
                        {
                            MessageBox.Show(String.Format("No download link provided for quad {0}", quad.Name));
                            continue;
                        }
                        await LoadImage(quad.DownloadURL, savelocation + "\\" + rasterseriesname + quad.Name + ".tif");

                        tiffs.Add(savelocation + "\\" + rasterseriesname + quad.Name + ".tif");
                        if (total % ++i == 0)
                        {
                            FrameworkApplication.AddNotification(new Notification()
                            {
                                Title    = "Downloading........",
                                Message  = String.Format("{0} of {1} files successfully dowloaded", i, total),
                                ImageUrl = @"Images/Planet_logo-dark.png"
                                           //ImageUrl = @"pack://*****:*****@"pack://application:,,,/Planet;component/Images/Planet_logo-dark.png"
                    });

                    //Create a raster Mosic in the default FGDB using Geoprocessing tools
                    string inpath = Project.Current.DefaultGeodatabasePath;
                    //inpath = @"C:\Users\Andrew\Documents\ArcGIS\Projects\MyProject22\MyProject22.gdb";
                    string in_mosaicdataset_name = rasterseriesname;
                    var    sr = await QueuedTask.Run(() => {
                        return(SpatialReferenceBuilder.CreateSpatialReference(3857));
                    });

                    var    parameters = Geoprocessing.MakeValueArray(inpath, in_mosaicdataset_name, sr, "3", "8_BIT_UNSIGNED", "NATURAL_COLOR_RGB");
                    string tool_path  = "management.CreateMosaicDataset";
                    System.Threading.CancellationTokenSource _cts = new System.Threading.CancellationTokenSource();
                    IGPResult result = await Geoprocessing.ExecuteToolAsync(tool_path, parameters, null, _cts.Token, (event_name, o) =>  // implement delegate and handle events, o is message object.
                    {
                        switch (event_name)
                        {
                        case "OnValidate":     // stop execute if any warnings
                            if ((o as IGPMessage[]).Any(it => it.Type == GPMessageType.Warning || it.Type == GPMessageType.Error))
                            {
                                System.Windows.MessageBox.Show(o.ToString());
                                _cts.Cancel();
                            }
                            break;
                            //case "OnProgressMessage":
                            //    string msg = string.Format("{0}: {1}", new object[] { event_name, (string)o });
                            //    //System.Windows.MessageBox.Show(msg);
                            //    //_cts.Cancel();
                            //    break;
                            //case "OnProgressPos":
                            //    string msg2 = string.Format("{0}: {1} %", new object[] { event_name, (int)o });
                            //    System.Windows.MessageBox.Show(msg2);
                            //    //_cts.Cancel();
                            //    break;
                        }
                    });

                    result     = null;
                    parameters = null;
                    _cts       = null;

                    //Load the downloaded .tifs into the Mosic
                    System.Threading.CancellationTokenSource _cts2 = new System.Threading.CancellationTokenSource();
                    tool_path  = "management.AddRastersToMosaicDataset";
                    parameters = Geoprocessing.MakeValueArray(inpath + "\\" + in_mosaicdataset_name, "Raster Dataset", String.Join(";", tiffs), "UPDATE_CELL_SIZES", "UPDATE_BOUNDARY", "UPDATE_OVERVIEWS", "-1");
                    //parameters = Geoprocessing.MakeValueArray(inpath + "\\" + in_mosaicdataset_name, "Raster Dataset", @"D:\Planet\global_monthly_2019_02_mosaic982-1377.tif;D:\Planet\global_monthly_2019_02_mosaic983-1377.tif");
                    try
                    {
                        IGPResult gPResult = await Geoprocessing.ExecuteToolAsync(tool_path, parameters, null, _cts2.Token, (event_name, o) =>  // implement delegate and handle events, o is message object.
                        {
                            switch (event_name)
                            {
                            case "OnValidate":     // stop execute if any warnings or errors
                                if ((o as IGPMessage[]).Any(it => it.Type == GPMessageType.Warning || it.Type == GPMessageType.Error))
                                {
                                    System.Windows.MessageBox.Show("Failed to add .tif files" + Environment.NewLine + o.ToString() + Environment.NewLine + "The files have been downloaded but not added to The raster Mosic", "Failed to add .tif files");
                                    _cts2.Cancel();
                                }
                                break;

                            case "OnProgressMessage":
                                //string msg = string.Format("{0}: {1}", new object[] { event_name, (string)o });
                                //System.Windows.MessageBox.Show(msg);
                                //_cts.Cancel();
                                break;

                            case "OnProgressPos":
                                //string msg2 = string.Format("{0}: {1} %", new object[] { event_name, (int)o });
                                //System.Windows.MessageBox.Show(msg2);
                                //_cts.Cancel();
                                break;
                            }
                        });

                        Geoprocessing.ShowMessageBox(gPResult.Messages, "GP Messages", gPResult.IsFailed ? GPMessageBoxStyle.Error : GPMessageBoxStyle.Default);
                        //Geoprocessing.OpenToolDialog(tool_path, parameters);
                    }
                    catch (Exception ex)
                    {
                        System.Windows.MessageBox.Show(ex.Message.ToString());
                        _cts2.Cancel();
                    }


                    //Everything downloaded and added to the mosic
                    FrameworkApplication.AddNotification(new Notification()
                    {
                        Title    = "Download successful",
                        Message  = "Successfully dowloaded the basemap source quads",
                        ImageUrl = @"pack://application:,,,/Planet;component/Images/Planet_logo-dark.png"
                    });
                }
            }
        }