/// <summary>
 /// OnClick method. Switch the tool on and off.
 /// </summary>
 protected override void OnClick()
 {
     // Check if the button is checked (tool is on).
     if (this.IsChecked)
     {
         // If button is checked, check off the button.
         this.IsChecked = false;
         // Set the mosaic rule back to what it was before the button was checked.
         ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
         {
             // Get the first selected layer.
             Layer firstSelectedLayer = null;
             try { firstSelectedLayer = MapView.Active.GetSelectedLayers().First(); } catch (Exception) { }
             // Check if there are any selected layers and if the first selected layer is a mosaic layer.
             if (firstSelectedLayer != null && firstSelectedLayer is MosaicLayer)
             {
                 MosaicLayer selectedMosaicLayer       = firstSelectedLayer as MosaicLayer;
                 ImageServiceLayer mosaicImageSublayer = selectedMosaicLayer.GetImageLayer() as ImageServiceLayer;
                 // Update the image service with the original mosaic rule.
                 mosaicImageSublayer.SetMosaicRule(mosaicRule);
                 // Reset the mosaic rule parameter
                 mosaicRule = null;
             }
         });
         // Unsubscribe from the MapSelectionChanged event.
         ArcGIS.Desktop.Mapping.Events.MapSelectionChangedEvent.Unsubscribe(MapSelectionChanged);
     }
     else
     {
         // If the button is checked off, check on the button.
         this.IsChecked = true;
         // Subscribe to the MapSelectionChanged event.
         ArcGIS.Desktop.Mapping.Events.MapSelectionChangedEvent.Subscribe(MapSelectionChanged);
     }
 }
        /// <summary>
        /// This function is used to apply a raster function template onto an image service layer.
        /// </summary>
        /// <param name="selectedLayer">The selected image service layer. </param>
        /// <param name="operation">An Enum type represents the user selected operation. </param>
        /// <param name="xmlFilePath">The XML file path.</param>
        /// <returns></returns>
        public static async Task ApplyRFTXmlFile(ImageServiceLayer selectedLayer, Enum operation, string xmlFilePath)
        {
            // Creates a new instance of XmlDocument class.
            XmlDocument xmlDoc = new XmlDocument();

            // Loads the RFT XML file from its file path.
            xmlDoc.Load(xmlFilePath);

            // Creates a new instance of the rendering rule.
            CIMRenderingRule setRenderingrule = new CIMRenderingRule();

            // Gets the markup containing all the nodes and their child nodes, passes to the rendering rule definition.
            setRenderingrule.Definition = xmlDoc.OuterXml;

            // Defines the rendering rule name as the operation name.
            setRenderingrule.Name = Convert.ToString(operation);

            await QueuedTask.Run(() =>
            {
                // Sets the new rendering rule to the selected layer.
                selectedLayer.SetRenderingRule(setRenderingrule);

                // Gets the current rendering rule from the layer.
                CIMRenderingRule renderingRule = selectedLayer.GetRenderingRule();

                //Verifies if the current rendering rule name is correct. Else, error message shows up.
                if (renderingRule.Name != Convert.ToString(operation))
                {
                    ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("The operation is not succeeded, please check...",
                                                                     "Operation unsucceeded:", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            });
        }
        /// <summary>
        /// Set the compression type and compression quality (if applicable) on the first selected image service layer in the first open 2D map.
        /// </summary>
        /// <param name="type">The compression type to set on the layer.</param>
        /// <param name="quality">The compression quality to set on the layer.</param>
        /// <returns></returns>
        public static async Task SetCompressionAsync(string type, int quality = 80)
        {
            try
            {
                // Get the first 2D map from the project that is called Map.
                Map _map = await GetMapFromProject(Project.Current, "Map");

                if (_map == null)
                {
                    ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("SetCompression: Failed to get map.");
                    return;
                }

                // Get the most recently selected layer of type ImageServiceLayer
                ImageServiceLayer imageServiceLayer = MapView.Active.GetSelectedLayers().OfType <ImageServiceLayer>().FirstOrDefault();
                if (imageServiceLayer != null)
                {
                    // Set the compression type and quality on the most recently selected layer.
                    // The compression has to be set on the Main CIM Thread (MCT).
                    await QueuedTask.Run(() =>
                    {
                        imageServiceLayer.SetCompression(type, quality);
                    });
                }
            }
            catch (Exception exc)
            {
                // Catch any exception found and display a message box.
                ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("Exception caught while trying to set compression: " + exc.Message);
            }
        }
 void SetMosaicRule(MosaicLayer mosaicLayer, FeatureLayer footprintLayer, List <long> selectedItems)
 {
     ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
     {
         // Check if overviews are supposed to be excluded from the selection.
         string objectIDs = null;
         if (excludeOverviews)
         {
             // Get the selected rows from the feature layer.
             RowCursor selectedRows = footprintLayer.GetSelection().Search();
             if (selectedRows.MoveNext())
             {
                 using (var selectedRow = selectedRows.Current)
                 {
                     // Get the value for the Category field.
                     int tag = Convert.ToInt32(selectedRow.GetOriginalValue(selectedRows.FindField("Category")));
                     // For each row, if Category is not 2 (2 = overview), then add the object id to the list of items to lock to.
                     if (tag != 2)
                     {
                         objectIDs = selectedRow.GetOriginalValue(selectedRows.FindField("OBJECTID")).ToString();
                     }
                     while (selectedRows.MoveNext())
                     {
                         tag = Convert.ToInt32(selectedRow.GetOriginalValue(selectedRows.FindField("Category")));
                         if (tag != 2)
                         {
                             objectIDs += "," + selectedRow.GetOriginalValue(selectedRows.FindField("OBJECTID")).ToString();
                         }
                     }
                 }
             }
         }
         // Get the mosaic rule of the image sub-layer of the mosaic layer.
         ImageServiceLayer imageLayer = mosaicLayer.GetImageLayer() as ImageServiceLayer;
         CIMMosaicRule newMosaicRule  = imageLayer.GetMosaicRule();
         // If there is no saved mosaic rule, then save the original mosaic rule of the mosaic layer.
         if (mosaicRule == null)
         {
             mosaicRule = newMosaicRule;
             // Then create a new mosaic rule.
             newMosaicRule = new CIMMosaicRule();
         }
         // Set the Mosaic Method to 'Lock Raster'
         newMosaicRule.MosaicMethod = RasterMosaicMethod.LockRaster;
         // Set the object id's to lock to.
         if (excludeOverviews)
         {
             newMosaicRule.LockRasterID = objectIDs;
         }
         else
         {
             newMosaicRule.LockRasterID = string.Join(",", selectedItems);
         }
         // Update the mosaic layer with the changed mosaic rule.
         imageLayer.SetMosaicRule(newMosaicRule);
     });
 }
        /// <summary>
        /// Called when the combo box item selection changed.
        /// </summary>
        /// <param name="item"> The selected combo box item. </param>
        protected override async void OnSelectionChange(ComboBoxItem item)
        {
            // Sets logic if selected combo box item is null, then return.
            if (item == null)
            {
                return;
            }

            // Passes the current selected combo box item to the selectedComboBoxItem.
            selectedComboBoxItem = item;

            // Adds validation here if the item text is emply then return.
            if (string.IsNullOrEmpty(item.Text))
            {
                return;
            }

            // Try and get the first selected layer.
            Layer firstSelectedLayer = null;

            try { firstSelectedLayer = MapView.Active.GetSelectedLayers().First(); } catch (Exception) { }
            // Check if there are any selected layers and if the first selected layer is a image service layer.
            if (!(firstSelectedLayer != null && firstSelectedLayer is ImageServiceLayer))
            {
                MessageBox.Show("Please select an image service layer.");
                return;
            }
            ImageServiceLayer selectedLayer = firstSelectedLayer as ImageServiceLayer;

            // Enters if the selected combo box item is not 'defult' or empty, else sets the original rendering rule to the selected layer.
            if (item.Text != "None" && item.Text != null)
            {
                // Gets the operation enum item from the its name.
                CellStatistics_Operations operation = (CellStatistics_Operations)Enum.Parse(typeof(CellStatistics_Operations), item.Text);
                try
                {
                    string rftFilePath = Project.Current.HomeFolderPath + fileRelativePath;
                    // Customizes the raster function template XML file using the user defined definition query and operation.
                    string xmlFilePath = Process.CustomRFTXmlFile(rftFilePath, operation, DefQueryEditBox.passingText);
                    // Applies the custom raster function template to the selected layer.
                    await Process.ApplyRFTXmlFile(selectedLayer, operation, xmlFilePath);
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Exception caught in OnSelectionChange:" + ex.Message, "Exception", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
            else
            {
                await QueuedTask.Run(() =>
                {
                    // Sets the defult rendering rule to the selected image service layer.
                    selectedLayer.SetRenderingRule(renderingRule_default);
                });
            }
        }
Example #6
0
        /// <summary>
        /// Create a raster layer and add it to a map.
        /// </summary>
        /// <returns>Task that contains a layer.</returns>
        private async Task AddRasterLayerToMap()
        {
            try
            {
                // Get the first map called "Map" from the current project.
                Map myMap = null;
                myMap = await GetMapFromProject(Project.Current, "Map");

                if (myMap == null)
                {
                    ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("Failed to get map.");
                    return;
                }


                // Create a url pointing to the source. In this case it is a url to an image service
                // which will result in an image service layer being created.
                string dataSoureUrl = @"https://environment.data.gov.uk/image/services/SURVEY/VegetationObjectModel/ImageServer";
                // Note: A url can also point to
                // 1.) An image on disk or an in a file geodatabase. e.g. string dataSoureUrl = @"C:\temp\a.tif"; This results in a raster layer.
                // 2.) A mosaic dataset in a file gdb e.g. string dataSoureUrl = @"c:\temp\mygdb.gdb\MyMosaicDataset"; This results in a mosaic layer.
                // 3.) A raster or mosaic dataset in an enterprise geodatabase.

                // Create an ImageServiceLayer object to hold the new layer.
                ImageServiceLayer rasterLayer = null;

                // The layer has to be created on the Main CIM Thread (MCT).
                await QueuedTask.Run(() =>
                {
                    // Create a layer based on the url. In this case the layer we are creating is an image service layer.
                    var layerParams = new LayerCreationParams(new Uri(dataSoureUrl));
                    rasterLayer     = LayerFactory.Instance.CreateLayer <ImageServiceLayer>(layerParams, myMap);

                    // Check if it is created.
                    if (rasterLayer == null)
                    {
                        ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("Failed to create layer for url:" + dataSoureUrl);
                        return;
                    }

                    // Validate the colorizer to see if the layer is colorized correctly.
                    if (!(rasterLayer.GetColorizer() is CIMRasterRGBColorizer))
                    {
                        ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("Colorizer does not match for layer created from url: " + dataSoureUrl);
                    }
                });
            }
            catch (Exception exc)
            {
                // Catch any exception found and display a message box.
                ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("Exception caught: " + exc.Message);
                return;
            }
        }
        // This method will be called when the lock button is clicked
        private async void LockScenes(object sender)
        {
            // Disable the AddToMap button
            IsAddToMapEnabled = false;
            NotifyPropertyChanged(() => IsAddToMapEnabled);

            if ((sender as ICollection <object>).Count == 0)
            {
                return;
            }

            _selectedList = sender as ICollection <object>;
            int _selectedListCount = _selectedList.Count;

            // This will be hit if only one scene has been selected
            if (_selectedListCount == 1)
            {
                if (SelectedLayer is ImageServiceLayer)
                {
                    await QueuedTask.Run(() =>
                    {
                        //Map _map = await GetMapFromProject(Project.Current, "Map");
                        Map _map = MapView.Active.Map;
                        ImageServiceLayer imageServiceLayer    = (ImageServiceLayer)SelectedLayer;
                        ImageServiceLayer originalServiceLayer = (ImageServiceLayer)LayerFactory.Instance.CopyLayer(imageServiceLayer, _map, 1);
                        originalServiceLayer.SetVisibility(false);
                        object obj  = _selectedList.First();
                        Scene scene = obj as Scene;
                        CIMMosaicRule mosaicRule = new CIMMosaicRule();
                        mosaicRule.MosaicMethod  = RasterMosaicMethod.LockRaster;
                        mosaicRule.LockRasterID  = scene.ObjectID;
                        imageServiceLayer.SetName(scene.Name);
                        ((ImageServiceLayer)imageServiceLayer).SetMosaicRule(mosaicRule);
                        imageServiceLayer.SetVisibility(true);
                        SelectedLayer = originalServiceLayer;
                    });
                }
            }
            else if (_selectedList.Count > 1)
            {
                // If more than one record has been selected, display the text box to accept GroupName
                GroupNameVisibility = true;
                NotifyPropertyChanged(() => GroupNameVisibility);
            }

            // Once the lock button has been clicked it should not be clickable again, the same goes for the DataGrid

            //IsLockButtonEnabled = false;
            //NotifyPropertyChanged(() => IsLockButtonEnabled);

            //DataGridEnabled = false;
            //NotifyPropertyChanged(() => DataGridEnabled);
        }
        // This method will be called when the AddToMap button is clicked, this button will be displayed only if more than one scene is selected in the Datagrid
        private async void AddToMap()
        {
            if (SelectedLayer is ImageServiceLayer)
            {
                await QueuedTask.Run(() =>
                {
                    ImageServiceLayer imageServiceLayer = (ImageServiceLayer)SelectedLayer;
                    // Store information of original service layer so that it can be displayed back again
                    CIMMosaicRule originalMosaicRule = imageServiceLayer.GetMosaicRule();
                    string originalLayerName         = imageServiceLayer.Name;
                    //Map _map = await GetMapFromProject(Project.Current, "Map");
                    Map _map = MapView.Active.Map;
                    // Create a Group Layer which will act as a cotainer where selected layers will be added
                    GroupLayer grplayer = (GroupLayer)LayerFactory.Instance.CreateGroupLayer(_map, 0, _groupLayerName);
                    int _sceneCount     = 0;
                    foreach (object obj in _selectedList.Reverse <object>())
                    {
                        Scene scene = obj as Scene;
                        CIMMosaicRule mosaicRule = new CIMMosaicRule();
                        mosaicRule.MosaicMethod  = RasterMosaicMethod.LockRaster;
                        mosaicRule.LockRasterID  = scene.ObjectID;
                        ((ImageServiceLayer)imageServiceLayer).SetMosaicRule(mosaicRule);
                        imageServiceLayer.SetName(scene.Name);
                        imageServiceLayer.SetVisibility(false);
                        int ListCount = _selectedList.Count - 1;
                        if (_sceneCount == ListCount)
                        {
                            imageServiceLayer.SetVisibility(true);
                        }
                        else
                        {
                            imageServiceLayer.SetVisibility(false);
                            _sceneCount = _sceneCount + 1;
                        }
                        LayerFactory.Instance.CopyLayer(imageServiceLayer, grplayer);
                    }
                    // Done to display original image service layer
                    imageServiceLayer.SetMosaicRule(originalMosaicRule);
                    imageServiceLayer.SetName(originalLayerName);
                    imageServiceLayer.SetVisibility(false);
                    SelectedLayer = imageServiceLayer;
                    // Set visibilty of Group Layer to be true by default
                    grplayer.SetVisibility(true);

                    // Once the user has entered Group Layer Name, reset the Stack Panel
                    GroupLayerName = "";
                    NotifyPropertyChanged(() => GroupLayerName);

                    GroupNameVisibility = false;
                    NotifyPropertyChanged(() => GroupNameVisibility);
                });
            }
        }
        /// <summary>
        /// Set the stretch type on the first selected image service layer in the first open 2D map.
        /// </summary>
        /// <param name="stretschType">The stretch type to set on the layer.</param>
        /// <param name="statsType">The stretch statistics type to set on the layer. This lets you pick between Dataset, Area of View (to enable DRA) or Custom statistics.</param>
        /// <returns></returns>
        public static async Task SetStretchTypeAsync(RasterStretchType stretschType, RasterStretchStatsType statsType = RasterStretchStatsType.Dataset)
        {
            try
            {
                // Get the first 2D map from the project that is called Map.
                Map _map = await GetMapFromProject(Project.Current, "Map");

                if (_map == null)
                {
                    ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("SetStretchType: Failed to get map.");
                    return;
                }

                // Get the most recently selected layer of type ImageServiceLayer
                ImageServiceLayer imageServiceLayer = MapView.Active.GetSelectedLayers().OfType <ImageServiceLayer>().FirstOrDefault();
                if (imageServiceLayer != null)
                {
                    // Set the colorizer on the most recently selected layer.
                    // The colorizer has to be set on the Main CIM Thread (MCT).
                    await QueuedTask.Run(() =>
                    {
                        // Get the colorizer from the selected layer.
                        CIMRasterColorizer newColorizer = imageServiceLayer.GetColorizer();
                        // Set the stretch type and stretch statistics type on the colorizer.
                        // Theese parameters only apply to the Stretch and RGB colorizers.
                        if (newColorizer is CIMRasterRGBColorizer)
                        {
                            ((CIMRasterRGBColorizer)newColorizer).StretchType      = stretschType;
                            ((CIMRasterRGBColorizer)newColorizer).StretchStatsType = statsType;
                        }
                        else if (newColorizer is CIMRasterStretchColorizer)
                        {
                            ((CIMRasterStretchColorizer)newColorizer).StretchType = stretschType;
                            ((CIMRasterStretchColorizer)newColorizer).StatsType   = statsType;
                        }
                        else
                        {
                            MessageBox.Show("Selected layer must be visualized using the RGB or Stretch colorizer");
                        }
                        // Update the image service with the new colorizer
                        imageServiceLayer.SetColorizer(newColorizer);
                    });
                }
            }
            catch (Exception exc)
            {
                // Catch any exception found and display a message box.
                ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("Exception caught while trying to set stretch type: " + exc.Message);
                return;
            }
        }
        /// <summary>
        /// Create a raster layer and add it to a map.
        /// </summary>
        /// <returns></returns>
        private async Task AddRasterLayerToMap()
        {
            try
            {
                // Get the first 2D map from the current project.
                Map myMap = null;
                myMap = await GetMapFromProject(Project.Current, "CIMPATH=map/map.xml");
                if (myMap == null)
                {
                    System.Windows.MessageBox.Show("Failed to get map.");
                    return;
                }

                // Create a url pointing to the source. In this case it is a url to an image service 
                // which will result in an image service layer being created.
                string serviceURL = @"http://imagery.arcgisonline.com/arcgis/services/LandsatGLS/GLS2010_Enhanced/ImageServer";
                // Note: A url can also point to  
                // 1.) An image on disk or an in a file geodatabase. e.g. string fileRasterURL = @"C:\temp\a.tif"; This results in a raster layer.
                // 2.) A mosaic dataset in a file gdb e.g. string mosaicURL = @"c:\temp\mygdb.gdb\MyMosaicDataset"; This results in a mosaic layer.
                // 3.) A raster or mosaic dataset in an enterprise geodatabase.

                // Create an ImageServiceLayer object to hold the new layer.
                ImageServiceLayer imageServiceLayer = null;

                // The layer has to be created on the Main CIM Thread (MCT).
                await QueuedTask.Run(() =>
                {
                    // Create a layer based on the url. In this case the layer we are creating is an image service layer.
                    imageServiceLayer = (ImageServiceLayer)Layer.Create(new Uri(serviceURL), myMap);
                    
                    // Check if it is created.
                    if (imageServiceLayer == null) 
                    {
                        System.Windows.MessageBox.Show("Failed to Create Image Service Layer for url:" + serviceURL);
                        return;
                    }
                    
                    // Validate the colorizer to see if the layer is colorized correctly.
                    if (!(imageServiceLayer.GetColorizer() is CIMRasterRGBColorizer)) 
                        System.Windows.MessageBox.Show("Colorizer does not match for layer created from url: " + serviceURL);
                });
            }
            catch (Exception exc)
            {
                // Catch any exception found and display a message box.
                System.Windows.MessageBox.Show("Exception caught: " + exc.Message);
                return;
            }
        }
        /// <summary>
        /// Create an image service layer and add it to the first 2D map.
        /// </summary>
        /// <returns>Task that contains a layer.</returns>
        public static async Task AddRasterLayerToMapAsync()
        {
            try
            {
                // Get the first 2D map from the project that is called Map.
                Map _map = await GetMapFromProject(Project.Current, "Map");

                if (_map == null)
                {
                    ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("AddRasterLayerToMap: Failed to get map.");
                    return;
                }

                // Create a url pointing to the source. In this case it is a url to an image service
                // which will result in an image service layer being created.
                string dataSoureUrl = @"https://landsat2.arcgis.com/arcgis/services/Landsat/MS/ImageServer";
                // Note: A url can also point to
                // 1.) An image on disk or an in a file geodatabase. e.g. string dataSoureUrl = @"C:\temp\a.tif"; This results in a raster layer.
                // 2.) A mosaic dataset in a file gdb e.g. string dataSoureUrl = @"c:\temp\mygdb.gdb\MyMosaicDataset"; This results in a mosaic layer.
                // 3.) A raster or mosaic dataset in an enterprise geodatabase.

                // Create an ImageServiceLayer object to hold the new layer.
                ImageServiceLayer imageServiceLayer = null;

                // The layer has to be created on the Main CIM Thread (MCT).
                string error = await QueuedTask.Run(() =>
                {
                    // Create a layer based on the url. In this case the layer we are creating is an image service layer.
                    imageServiceLayer = LayerFactory.Instance.CreateLayer(new Uri(dataSoureUrl), _map) as ImageServiceLayer;
                    if (imageServiceLayer == null)
                    {
                        return("Failed to create layer for url:" + dataSoureUrl);
                    }
                    return("");
                });

                if (!string.IsNullOrEmpty(error))
                {
                    ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show(error);
                }
            }
            catch (Exception exc)
            {
                // Catch any exception found and display a message box.
                ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("Exception caught while trying to add layer: " + exc.Message);
            }
        }
        /// <summary>
        /// Set the processing template on the first selected image service layer in the first open 2D map.
        /// </summary>
        /// <param name="templateName">The name of the processing template to set on the layer.</param>
        /// <returns></returns>
        public static async Task SetProcessingTemplateAsync(string templateName)
        {
            try
            {
                // Get the first 2D map from the project that is called Map.
                Map _map = await GetMapFromProject(Project.Current, "Map");

                if (_map == null)
                {
                    ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("SetResamplingType: Failed to get map.");
                    return;
                }

                // Get the most recently selected layer.
                Layer firstSelectedLayer = MapView.Active.GetSelectedLayers().First();
                // Check if the first selected layer is an image service layer.
                if (firstSelectedLayer is ImageServiceLayer)
                {
                    // Set the colorizer on the most recently selected layer.
                    // The colorizer has to be set on the Main CIM Thread (MCT).
                    ImageServiceLayer isLayer = (ImageServiceLayer)firstSelectedLayer;
                    await QueuedTask.Run(() =>
                    {
                        // Create a new Rendering rule
                        CIMRenderingRule setRenderingrule = new CIMRenderingRule()
                        {
                            // Set the name of the rendering rule.
                            Name = templateName
                        };
                        // Update the image service with the new mosaic rule.
                        isLayer.SetRenderingRule(setRenderingrule);
                    });
                }
            }
            catch (Exception exc)
            {
                // Catch any exception found and display a message box.
                ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("Exception caught while trying to set processing template: " + exc.Message);
                return;
            }
        }
        // Event Handler, gets name of selected RFT and changes the rendering rule of the Image Service to be displayed accordingly
        private async void RFT_SelectChanged(object sender)
        {
            try
            {
                //Map _map1 = await GetMapFromProject(Project.Current, "Map");
                Map _map = MapView.Active.Map;
                if (_map == null)
                {
                    ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("AddRasterLayerToMap: Failed to get map.");
                    return;
                }

                string            dataSoureUrl      = ServiceURL;
                ImageServiceLayer imageServiceLayer = null;
                await QueuedTask.Run(() =>
                {
                    imageServiceLayer = (ImageServiceLayer)LayerFactory.Instance.CreateLayer(new Uri(dataSoureUrl), _map);
                    if (imageServiceLayer == null)
                    {
                        ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("Failed to create layer for url:" + dataSoureUrl);
                        return;
                    }
                    ImageServiceLayer isLayer = imageServiceLayer;
                    // Create a new Rendering rule
                    CIMRenderingRule setRenderingrule = new CIMRenderingRule();
                    // Set the name of the rendering rule.
                    setRenderingrule.Name = sender.ToString();
                    // Update the image service with the new mosaic rule.
                    isLayer.SetRenderingRule(setRenderingrule);
                    string originalLayerName = isLayer.Name;
                    isLayer.SetName(originalLayerName + "_" + sender.ToString());
                });
            }
            catch (Exception ex)
            {
                System.Diagnostics.Trace.WriteLine(ex.Message);
            }
        }
        /// <summary>
        /// Set the resampling type on the first selected image service layer in the first open 2D map.
        /// </summary>
        /// <param name="resamplingType">The resampling type to set on the layer.</param>
        /// <returns></returns>
        public static async Task SetResamplingTypeAsync(RasterResamplingType resamplingType)
        {
            try
            {
                // Get the first 2D map from the project that is called Map.
                Map _map = await GetMapFromProject(Project.Current, "Map");

                if (_map == null)
                {
                    ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("SetResamplingType: Failed to get map.");
                    return;
                }

                // Get the most recently selected layer of type ImageServiceLayer
                ImageServiceLayer imageServiceLayer = MapView.Active.GetSelectedLayers().OfType <ImageServiceLayer>().FirstOrDefault();
                if (imageServiceLayer != null)
                {
                    // Set the colorizer on the most recently selected layer.
                    // The colorizer has to be get/set on the Main CIM Thread (MCT).
                    await QueuedTask.Run(() =>
                    {
                        // Get the colorizer from the selected layer.
                        CIMRasterColorizer newColorizer = imageServiceLayer.GetColorizer();
                        // Set the resampling type on the colorizer.
                        newColorizer.ResamplingType = resamplingType;
                        // Update the image service with the new colorizer
                        imageServiceLayer.SetColorizer(newColorizer);
                    });
                }
            }
            catch (Exception exc)
            {
                // Catch any exception found and display a message box.
                ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("Exception caught while trying to set resampling type: " + exc.Message);
            }
        }
        // Do a Query request on the selected point to get the list of overlapping scenes
        private Task ExtractInfoAsync(string X, string Y)
        {
            return(Application.Current.Dispatcher.Invoke(async() =>
            {
                try
                {
                    if (Scenes != null)
                    {
                        Scenes.Clear();
                        _selection.Clear();
                    }
                    // Get the image service URL from the current layer
                    SelectedLayer = MapView.Active.GetSelectedLayers().FirstOrDefault();
                    if (SelectedLayer is ImageServiceLayer)
                    {
                        string ImageServiceURL = null;
                        ImageServiceLayer imageServiceLayer = (ImageServiceLayer)SelectedLayer;
                        await QueuedTask.Run(() =>
                        {
                            CIMDataConnection DataConnection = imageServiceLayer.GetDataConnection();
                            string DataConnectionXMLString = DataConnection.ToXml();
                            var ParsedDataConnectionString = XElement.Parse(DataConnectionXMLString);
                            var URLNode = ParsedDataConnectionString.Elements("URL");
                            foreach (XElement nodeValue in URLNode)
                            {
                                ImageServiceURL = nodeValue.ToString();
                            }
                        });

                        // Send a request to the REST end point to get information
                        var point = "{x:" + X + ",y:" + Y + "}";
                        string[] URLSplit = Regex.Split(ImageServiceURL, "arcgis/");
                        //string ServiceURL = "https://landsat2.arcgis.com/";
                        string ServiceURL = URLSplit[0].Replace("<URL>", string.Empty);
                        string url = ServiceURL + "query";
                        var ubldr = new UriBuilder(ServiceURL);
                        string path = "arcgis/rest/" + URLSplit[1].Replace("</URL>", string.Empty) + "/query";
                        ubldr.Path = path;
                        //ubldr.Path = $"arcgis/rest/services/Landsat/MS/ImageServer/query";

                        // Allows to give parameters as dictionary key,pair values rather than manually constructing a json
                        var query = HttpUtility.ParseQueryString(ubldr.Query);
                        query["f"] = "json";
                        query["geometry"] = point;
                        query["geometryType"] = "esriGeometryPoint";
                        query["spatialRel"] = "esriSpatialRelIntersects";
                        query["outFields"] = "*";
                        query["pixelSize"] = "30";
                        query["returnGeometry"] = "false";
                        ubldr.Query = query.ToString();
                        var httpClient = new EsriHttpClient();
                        var response = httpClient?.Get(ubldr.Uri.ToString());
                        var respstr = await response?.Content?.ReadAsStringAsync();
                        var SceneList = JObject.Parse(respstr);
                        var SceneListInfo = (JArray)SceneList["features"];
                        foreach (JObject value in SceneListInfo)
                        {
                            foreach (var property in value.Properties())
                            {
                                if (property.Name == "attributes")
                                {
                                    {
                                        // Add obtained json response as a dictionary to a list of dictionaries
                                        var attribute = property.Value.ToString();
                                        var attributeValue = JObject.Parse(attribute);
                                        var category = Int32.Parse(attributeValue["Category"].ToString());
                                        var attributeValueDict = attributeValue.ToObject <Dictionary <string, string> >();
                                        if (category == 1)
                                        {
                                            _selection.Add(attributeValueDict);
                                        }
                                    }
                                }
                            }
                        }

                        foreach (var value in _selection)
                        {
                            // Extract and convert epoch time to dd/MM/yyyy format
                            double UnixTime = Convert.ToDouble(value["AcquisitionDate"].ToString());
                            var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
                            DateTime date = epoch.AddMilliseconds(UnixTime);
                            var AcqDate = date.ToString("dd / MM / yyyy");
                            var objID = value["OBJECTID"].ToString();
                            var ClCover = value["CloudCover"].ToString();
                            var SceneName = value["Name"].ToString();
                            Scenes.Add(new Scene {
                                AcqDate = AcqDate, Name = SceneName, CloudCover = ClCover, ObjectID = objID
                            });
                        }
                        // Add recieved information to an Observable Collection and notfy UI
                        NotifyPropertyChanged(() => Scenes);
                    }
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Trace.WriteLine(ex.Message);
                }
            }));
        }