コード例 #1
0
ファイル: MnuMaps.cs プロジェクト: PSU-CSAR/bagis-pro
        protected async override void OnClick()
        {
            try
            {
                OpenItemDialog selectAoiDialog = new OpenItemDialog()
                {
                    Title       = "Select AOI Folder",
                    MultiSelect = false,
                    Filter      = ItemFilters.folders
                };
                if (selectAoiDialog.ShowDialog() == true)
                {
                    Module1.DeactivateState("Aoi_Selected_State");
                    IEnumerable <Item> selectedItems = selectAoiDialog.Items;
                    var            e    = selectedItems.FirstOrDefault();
                    BA_Objects.Aoi oAoi = await GeneralTools.SetAoiAsync(e.Path);

                    if (oAoi != null)
                    {
                        Module1.Current.CboCurrentAoi.SetAoiName(oAoi.Name);
                        MessageBox.Show("AOI is set to " + oAoi.Name + "!", "BAGIS PRO");
                    }
                }
            }
            catch (Exception e)
            {
                MessageBox.Show("An error occurred while trying to set the AOI!! " + e.Message, "BAGIS PRO");
            }
        }
コード例 #2
0
        /// <summary>
        /// Updates the combo box with all the items.
        /// </summary>

        public void UpdateCombo()  // Testing update combo. Changed to public method. JBK - 2020.07.17
        {
            // TODO – customize this method to populate the combobox with your desired items
            if (_isInitialized)
            {
                SelectedItem = ItemCollection.FirstOrDefault(); //set the default item in the comboBox
            }
            if (!_isInitialized)
            {
                //Clear();
                ClearLists();
                //Add items to the combobox
                string FILE_NAME = @"\\city.wdm.loc\gis\GISData\West Des Moines\Information Services\Work in Progress\lang\Pro_support\layerList.txt";
                //string FILE_NAME = @"C:\Work\GIS\data\shpList1.txt";

                if (File.Exists(FILE_NAME))
                {
                    readText(FILE_NAME);
                }
                else
                {
                    //var Result = MessageBox.Show(FILE_NAME + " cannot be found.", "Do you want to open another text file?", MessageBoxButton.YesNo, MessageBoxImage.Question, MessageBoxResult.Yes);
                    //MessageBox.Show(Result.ToString());
                    //if (Result == MessageBoxResult.Yes )

                    MessageBox.Show(FILE_NAME + " cannot be found. Please use OpenTextFile button to search for your text file");
                    return;
                    // OpenFile();
                }
                _isInitialized = true;
            }

            Enabled      = true;                            //enables the ComboBox
            SelectedItem = ItemCollection.FirstOrDefault(); //set the default item in the comboBox
        }
コード例 #3
0
        /// <summary>
        /// Called when the sketch finishes. This is where we will create the sketch operation and then execute it.
        /// </summary>
        /// <param name="geometry">The geometry created by the sketch.</param>
        /// <returns>A Task returning a Boolean indicating if the sketch complete event was successfully handled.</returns>
        protected override Task <bool> OnSketchCompleteAsync(Geometry geometry)
        {
            if (geometry.GeometryType == GeometryType.Polygon)
            {
                Polygon polygon = (Polygon)geometry;
                if (polygon.PointCount > 500)
                {
                    MessageBox.Show("Too many vertices. Please simplify your AOI. Max vertices: 500");
                    return(base.OnSketchCompleteAsync(geometry));
                }
            }
            if (_graphic != null)
            {
                _graphic.Dispose();
                _graphic = null;
            }

            addgraphic(geometry);
            DockPane pane = FrameworkApplication.DockPaneManager.Find("Planet_Data_DocPane");
            Data_DocPaneViewModel data_DocPaneViewModel = (Data_DocPaneViewModel)pane;

            data_DocPaneViewModel.AOIGeometry = geometry;
            data_DocPaneViewModel.Activate(true);
            //addwmts("asdasd");
            FrameworkApplication.SetCurrentToolAsync(null);
            return(base.OnSketchCompleteAsync(geometry));
        }
コード例 #4
0
        protected async override void OnClick()
        {
            string tempAoiPath = "C:\\Docs\\animas_AOI_prms";

            try
            {
                await MapTools.DisplayMaps(tempAoiPath);

                Module1.Current.DisplayedMap = Constants.FILE_EXPORT_MAP_ELEV_PDF;
                Module1.ToggleState("BtnMapLoad_State");
            }
            catch (Exception e)
            {
                MessageBox.Show("An error occurred while trying to load the maps!! " + e.Message, "BAGIS PRO");
            }
        }
コード例 #5
0
        public void OpenFile()
        {
            string fileName = string.Empty;
            // System.Windows.Forms.OpenFileDialog OpenFileDialog = new System.Windows.Forms.OpenFileDialog();
            // OpenFileDialog.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*";
            OpenItemDialog oid = new OpenItemDialog
            {
                // oid.BrowseFilter = "Text files (*.txt)|*.txt|All files (*.*)|*.*";

                Title       = "Open a text file",
                Filter      = ItemFilters.textFiles,
                MultiSelect = true
            };
            bool?ok = oid.ShowDialog();

            //System.Threading.Thread.Sleep(300);


            if (ok == true)
            {
                IEnumerable <Item> selected = oid.Items;

                fileName = selected.First().Path;
                //MessageBox.Show("LayerList is updated using "+fileName);

                //pass the text file path to Button1, so it can read the file too.
                AddLayersToMap addLayersToMap = AddLayersToMap.Current;

                Button1 b1 = addLayersToMap.B1; //// get the instance of the current one, do not create a new Button1
                //Button1 b1 = new Button1();
                if (b1 != null)
                {
                    b1.FILE_NAME = fileName;
                    if (b1.Enabled == false)
                    {
                        b1.Enabled = true;
                    }
                }
                readText(fileName);
            }
            else
            {
                MessageBox.Show("No file selected");
                return;
            }
        }
コード例 #6
0
        public static string UpdateToolbar()
        {
            try
            {
                // Set source and local directories and get tbx and py files
                var sourceDir = @"T:\DATAMGT\MAPPING\Map Requests\_Toolbar\tool_and_scripts";
                //var localDir = Project.Current.HomeFolderPath;
                var localDir      = @"C:\TxDOT\MapRequestTools";
                var localPath     = localDir + @"\tools_and_scripts";
                var filteredFiles = Directory
                                    .EnumerateFiles(sourceDir)
                                    .Where(file => file.ToLower().EndsWith("tbx") || file.ToLower().EndsWith("py"))
                                    .ToList();

                // Get name of tbx file
                var tbxName = Path
                              .GetFileName(Directory.GetFiles(sourceDir, "*.tbx").ElementAt(0));

                // Copy scripts and toolbox locally
                if (!Directory.Exists(localPath))
                {
                    System.IO.Directory.CreateDirectory(localPath);
                    foreach (var i in filteredFiles)
                    {
                        var localFile = localPath + @"\" + Path.GetFileName(i);
                        File.Copy(i, localFile);
                    }
                }

                // Return path to toobox
                var tbxPath = localPath + @"\" + tbxName;
                return(tbxPath);
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
                return(null);
            }
        }
コード例 #7
0
        protected async override void OnClick()
        {
            try
            {
                OpenItemDialog selectAoiDialog = new OpenItemDialog()
                {
                    Title           = "Select AOI Folder",
                    InitialLocation = System.IO.Directory.GetCurrentDirectory(),
                    MultiSelect     = false,
                    Filter          = ItemFilters.folders
                };
                bool?boolOk = selectAoiDialog.ShowDialog();
                if (boolOk == true)
                {
                    IEnumerable <Item> selectedItems = selectAoiDialog.Items;
                    foreach (Item selectedItem in selectedItems)    // there will only be one
                    {
                        FolderType fType = await GeodatabaseTools.GetAoiFolderTypeAsync(selectedItem.Path);

                        if (fType != FolderType.AOI)
                        {
                            ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("!!The selected folder does not contain a valid AOI", "BAGIS Pro");
                        }
                        else
                        {
                            // Initialize AOI object
                            BA_Objects.Aoi oAoi = new BA_Objects.Aoi(System.IO.Path.GetFileName(selectedItem.Path), selectedItem.Path);
                            // Store current AOI in Module1
                            Module1.Current.Aoi = oAoi;
                            ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("AOI is set to " + oAoi.Name + "!", "BAGIS PRO");
                        }
                    }
                }
            }
            catch (Exception e)
            {
                MessageBox.Show("An error occurred while trying to set the AOI!! " + e.Message, "BAGIS PRO");
            }
        }
コード例 #8
0
        public static string UpdateToolbar()
        {
            try
            {
                // Set source and local directories and get tbx file
                var sourceDir = @"T:\DATAMGT\MAPPING\Map Requests\_Toolbar\tool_and_scripts";
                var localDir  = @"C:\TxDOT\MapRequestTools";
                var localPath = localDir + @"\tools_and_scripts";

                // Get name of tbx file
                var tbxName = Path
                              .GetFileName(Directory.GetFiles(sourceDir, "*.tbx").ElementAt(0));

                // Set local tbx path
                var tbxPath = localPath + @"\" + tbxName;

                // Copy tbx locally
                if (!Directory.Exists(localPath))
                {
                    System.IO.Directory.CreateDirectory(localPath);
                    File.Copy(sourceDir + @"\" + tbxName, tbxPath);
                }
                else
                {
                    File.Delete(tbxPath);
                    File.Copy(sourceDir + @"\" + tbxName, tbxPath);
                }
                // Return path to toobox
                return(tbxPath);
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
                return(null);
            }
        }
コード例 #9
0
        public void readText(string FILE_NAME)
        {
            //this.Clear();
            ClearLists();
            if (FILE_NAME != "")
            {
                string[] lines = File.ReadAllLines(FILE_NAME);
                if (lines.ToList().Count == 0)
                {
                    MessageBox.Show(FILE_NAME + " is empty!");
                    return;
                }
                foreach (string line in lines)
                {
                    if (line != "")
                    {
                        if (line.Contains(","))
                        {
                            string[] content   = line.Split(',');
                            string   layerName = content[0].Trim();
                            //MessageBox.Show(layerName);
                            //Add(new ComboBoxItem(layerName));
                            layerNameAndPath[layerName] = content[1].Trim();
                        }
                        else
                        {
                            string FName = Path.GetFileName(line.Trim());
                            if (Path.HasExtension(line.Trim()))
                            {
                                FName = Path.GetFileNameWithoutExtension(FName);
                                //Add(new ComboBoxItem(FName));
                                layerNameAndPath[FName] = line.Trim();
                            }
                            else
                            {
                                if (FName.ToUpper().Contains("SERVER"))
                                {
                                    string[] folders     = line.Trim().Split('/'); //(Path.DirectorySeparatorChar);
                                    string   serviceName = folders[folders.Length - 2];
                                    //Add(new ComboBoxItem(serviceName));
                                    layerNameAndPath[serviceName + " - " + FName] = line.Trim();
                                }
                                else
                                {
                                    MessageBox.Show(FName + " is not a map service, please verify.");
                                    return;
                                }
                            }
                        }
                    }
                }

                var list = layerNameAndPath.Keys.ToList();
                list.Sort();
                foreach (var key in list)
                {
                    if (key.ToUpper() == "LAYERNAME")
                    {
                        Insert(0, new ComboBoxItem(key));
                    }
                    else
                    {
                        Add(new ComboBoxItem(key));
                    }
                }
                // MessageBox.Show(this.ItemCollection.Count() + " layers added to layer list from "+FILE_NAME);
                _isInitialized = true;
            }
            else
            {
                MessageBox.Show("No file to read");
                return;
            }
        }
コード例 #10
0
ファイル: MnuMaps.cs プロジェクト: PSU-CSAR/bagis-pro
        protected async override void OnClick()
        {
            string tempAoiPath = "C:\\Docs\\animas_AOI_prms";

            try
            {
                Layout layout = await MapTools.GetDefaultLayoutAsync(Constants.MAPS_DEFAULT_LAYOUT_NAME);

                BA_ReturnCode success = await MapTools.DisplayMaps(tempAoiPath, layout, true);

                if (success == BA_ReturnCode.Success && layout != null)
                {
                    bool bFoundIt = false;
                    //A layout view may exist but it may not be active
                    //Iterate through each pane in the application and check to see if the layout is already open and if so, activate it
                    foreach (var pane in FrameworkApplication.Panes)
                    {
                        if (!(pane is ILayoutPane layoutPane))  //if not a layout view, continue to the next pane
                        {
                            continue;
                        }
                        if (layoutPane.LayoutView != null &&
                            layoutPane.LayoutView.Layout == layout) //if there is a match, activate the view
                        {
                            (layoutPane as Pane).Activate();
                            bFoundIt = true;
                        }
                        else
                        {
                            continue;
                        }
                    }
                    if (!bFoundIt)
                    {
                        ILayoutPane iNewLayoutPane = await FrameworkApplication.Panes.CreateLayoutPaneAsync(layout); //GUI thread
                    }
                }

                // Legend
                success = await MapTools.DisplayLegendAsync(Constants.MAPS_DEFAULT_MAP_FRAME_NAME, layout, "ArcGIS Colors",
                                                            "1.5 Point", true);

                // update map elements for default map (elevation)
                if (FrameworkApplication.State.Contains("MapButtonPalette_BtnElevation_State"))
                {
                    BA_Objects.MapDefinition defaultMap = MapTools.LoadMapDefinition(BagisMapType.ELEVATION);
                    await MapTools.UpdateMapElementsAsync(Module1.Current.Aoi.NwccName.ToUpper(), defaultMap);

                    success = await MapTools.UpdateLegendAsync(layout, defaultMap.LegendLayerList);
                }
                else
                {
                    MessageBox.Show("The default Elevation Zones map could not be loaded. Use " +
                                    "the Display Maps buttons to display other maps!!", "BAGIS-PRO");
                }
                Module1.Current.DisplayedMap = Constants.FILE_EXPORT_MAP_ELEV_PDF;
                Module1.ActivateState("BtnMapLoad_State");
                MessageBox.Show("The maps are loaded. Use the Toggle Maps buttons to view the maps.", "BAGIS-PRO");
            }
            catch (Exception e)
            {
                MessageBox.Show("An error occurred while trying to load the maps!! " + e.Message, "BAGIS PRO");
            }
        }
コード例 #11
0
        /// <summary>
        /// Called when the sketch finishes. This is where we will create the sketch operation and then execute it.
        /// The sketch geometry will be turned into an envelope and used to query the Planet api for the relevant quads
        /// The FolderSelector view and various models will then be presented allowing the user to choose a save location
        /// Finally, after the .tif files have been downloaded a raster mosic will be created in the project default FGDB and
        /// the downloaded .tif files added.
        /// </summary>
        /// <param name="geometry">The geometry created by the sketch.</param>
        /// <returns>A Task returning a Boolean indicating if the sketch complete event was successfully handled.</returns>
        protected override Task <bool> OnSketchCompleteAsync(Geometry geometry)
        {
            string rasterseriesname = "";
            string rasterseriesid   = "";
            bool   _isPlanetRaster  = false;

            if (geometry == null)
            {
                return(Task.FromResult(false));
            }


            //Make sure a valid Planet layer is selected.
            IReadOnlyList <Layer> ts = MapView.Active.GetSelectedLayers();

            if (ts.Count > 1)
            {
                ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("More than one layer selected \n Please only choose a single Planet Imagery layer", "More than one layer selected", MessageBoxButton.OK, MessageBoxImage.Warning);
                return(Task.FromResult(false));
            }

            foreach (Layer item in ts)
            {
                if (item is TiledServiceLayer tiledService)
                {
                    if (!tiledService.URL.Contains("https://api.planet.com/basemaps/v1/mosaics"))
                    {
                        ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("The selected layer is not a Planet Image layer", "Wrong Layer type", MessageBoxButton.OK, MessageBoxImage.Warning);
                        return(Task.FromResult(false));
                    }
                    else
                    {
                        rasterseriesname = tiledService.Name;
                        rasterseriesid   = tiledService.URL.Substring(tiledService.URL.IndexOf("mosaics") + 8, 36);
                        _isPlanetRaster  = true;
                    }
                }
            }
            if (!_isPlanetRaster)
            {
                ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("The selected layer is not a Planet Image layer", "Wrong Layer type", MessageBoxButton.OK, MessageBoxImage.Warning);
                return(Task.FromResult(false));
            }

            //Create min max points from the envelope and get the coords in Decimal Degrees
            MapPoint point0 = MapPointBuilder.CreateMapPoint(geometry.Extent.XMin, geometry.Extent.YMin, MapView.Active.Extent.SpatialReference);
            MapPoint point1 = MapPointBuilder.CreateMapPoint(geometry.Extent.XMax, geometry.Extent.YMax, MapView.Active.Extent.SpatialReference);
            ToGeoCoordinateParameter ddParam = new ToGeoCoordinateParameter(GeoCoordinateType.DD);

            string geoCoordString = geometry.Extent.Center.ToGeoCoordinateString(ddParam);

            string[] lowP  = point0.ToGeoCoordinateString(ddParam).Split(' ');
            string[] highP = point1.ToGeoCoordinateString(ddParam).Split(' ');

            IEnumerable <string> union = lowP.Union(highP);
            string quadparm            = "";

            //need to change the formatting of the coords.
            for (int i = 0; i < union.Count(); i++)
            {
                string crr = union.ElementAt(i);
                if (crr.Contains("W") || crr.Contains("S"))
                {
                    crr = "-" + crr.Substring(0, crr.Length - 1);
                }
                else
                {
                    crr = crr.Substring(0, crr.Length - 1);
                }
                quadparm = quadparm + "," + crr;
            }
            string[] ff     = quadparm.Trim(',').Split(',');
            var      result = getQuadsAsync(geometry, ff, rasterseriesname, rasterseriesid);

            //result.Wait();
            if (result.IsFaulted)
            {
                MessageBox.Show(result.Exception.Message, "An error Occured", MessageBoxButton.OK, MessageBoxImage.Error);
                return(Task.FromResult(false));
            }
            //result.Wait();
            return(Task.FromResult(true));
        }
コード例 #12
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"
                    });
                }
            }
        }