Пример #1
0
        /// <summary>
        /// Applies the Stretch colorizer to the basic raster layer.
        /// </summary>
        /// <param name="basicRasterLayer">The basic raster layer is either a raster or image service layer, or the image sub-layer of the mosaic layer.</param>
        /// <returns></returns>
        public static async Task SetToStretchColorizer(BasicRasterLayer basicRasterLayer)
        {
            // Defines parameters in colorizer definition.
            int bandIndex = 0;
            RasterStretchType stretchType    = RasterStretchType.MinimumMaximum;
            double            gamma          = 2.0;
            string            colorRampStyle = "ArcGIS Colors";
            string            colorRampName  = "Aspect";

            await QueuedTask.Run(async() =>
            {
                // Gets a color ramp from a style.
                IList <ColorRampStyleItem> rampList = GetColorRampsFromStyleAsync(Project.Current, colorRampStyle, colorRampName);
                CIMColorRamp colorRamp = rampList[0].ColorRamp;

                // Creates a new Stretch Colorizer Definition with defined parameters.
                StretchColorizerDefinition stretchColorizerDef = new StretchColorizerDefinition(bandIndex, stretchType, gamma, colorRamp);

                // Creates a new stretch colorizer using the colorizer definition created above.
                CIMRasterStretchColorizer newColorizer = await basicRasterLayer.CreateColorizerAsync(stretchColorizerDef) as CIMRasterStretchColorizer;

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


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

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

                //Iterates through the applicable colorizer collection to get the colorizer names, and add to the combo box.
                foreach (var rasterColorizerType in _applicableColorizerList)
                {
                    // Gets the colorizer name from the RasterColorizerType enum.
                    string ColorizerName = Enum.GetName(typeof(RasterColorizerType), rasterColorizerType);
                    Add(new ComboBoxItem(ColorizerName));
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Exception caught on Update combo box:" + ex.Message, "Exception", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
Пример #3
0
        /// <summary>
        /// Applies the Classify colorizer to the basic raster layer.
        /// </summary>
        /// <param name="basicRasterLayer">The basic raster layer is either a raster or image service layer, or the image sub-layer of the mosaic layer.</param>
        /// <returns></returns>
        public static async Task SetToClassifyColorizer(BasicRasterLayer basicRasterLayer)
        {
            // Defines values for parameters in colorizer definition.
            string fieldName = "Value";
            ClassificationMethod classificationMethod = ClassificationMethod.NaturalBreaks;
            int    numberofClasses = 7;
            string colorRampStyle  = "ArcGIS Colors";
            string colorRampName   = "Aspect";

            await QueuedTask.Run(async() =>
            {
                // Gets a color ramp from a style.
                IList <ColorRampStyleItem> rampList = GetColorRampsFromStyleAsync(Project.Current, colorRampStyle, colorRampName);
                CIMColorRamp colorRamp = rampList[0].ColorRamp;

                // Creates a new Classify Colorizer Definition using defined parameters.
                ClassifyColorizerDefinition classifyColorizerDef = new ClassifyColorizerDefinition(fieldName, numberofClasses, classificationMethod, colorRamp);

                // Creates a new Classify colorizer using the colorizer definition created above.
                CIMRasterClassifyColorizer newColorizer = await basicRasterLayer.CreateColorizerAsync(classifyColorizerDef) as CIMRasterClassifyColorizer;

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

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

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

                    default:
                        var style = Project.Current.GetItems <StyleProjectItem>().First(s => s.Name == "ArcGIS Colors");
                        SetRasterColorByAttributeField(basicRasterLayer as RasterLayer, item.Text, style);
                        break;
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Exception caught in OnSelectionChange:" + ex.Message, "Exception", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
Пример #5
0
        public static async void AddLayer(string targets, string name)
        {
            HttpClientHandler handler = new HttpClientHandler()
            {
                AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate
            };
            HttpClient client = new HttpClient(handler)
            {
                BaseAddress = new Uri("https://api.planet.com")
            };
            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "data/v1/layers");

            //request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));
            request.Headers.Host = "tiles2.planet.com";
            request.Headers.AcceptEncoding.Add(new StringWithQualityHeaderValue("gzip"));
            var nvc = new List <KeyValuePair <string, string> >();

            //nvc.Add(new KeyValuePair<string, string>("ids", "PSScene4Band:20190603_205042_1042,PSScene4Band:20190528_205949_43_1061,PSScene4Band:20190818_205116_1009"));
            nvc.Add(new KeyValuePair <string, string>("ids", targets));
            //var content = new StringContent(json, Encoding.UTF8, "application/json");
            var content = new FormUrlEncodedContent(nvc);

            request.Content = content;
            var byteArray = Encoding.ASCII.GetBytes("1fe575980e78467f9c28b552294ea410:hgvhgv");

            client.DefaultRequestHeaders.Host = "api.planet.com";
            //_client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));
            content.Headers.Remove("Content-Type");
            content.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
            client.DefaultRequestHeaders.Add("Connection", "keep-alive");
            client.DefaultRequestHeaders.Add("User-Agent", "ArcGISProC#");
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
            using (HttpResponseMessage httpResponse = client.SendAsync(request).Result)
            {
                using (HttpContent content2 = httpResponse.Content)
                {
                    var        json2      = content2.ReadAsStringAsync().Result;
                    customwmts customwmts = JsonConvert.DeserializeObject <customwmts>(json2);
                    customwmts.wmtsURL = new Uri("https://tiles.planet.com/data/v1/layers/wmts/" + customwmts.name + "?api_key=1fe575980e78467f9c28b552294ea410");
                    //Geometry geometry2 = GeometryEngine.Instance.ImportFromJSON(JSONImportFlags.jsonImportDefaults, JsonConvert.SerializeObject( quickSearchResult.features[5].geometry));
                    var serverConnection = new CIMProjectServerConnection {
                        URL = customwmts.wmtsURL.ToString()
                    };                                                                                            // "1fe575980e78467f9c28b552294ea410"
                    var connection = new CIMWMTSServiceConnection {
                        ServerConnection = serverConnection
                    };
                    await QueuedTask.Run(() =>
                    {
                        BasicRasterLayer layer2 = LayerFactory.Instance.CreateRasterLayer(connection, MapView.Active.Map, 0, name);
                    });
                }
            }
        }
Пример #6
0
        /// <summary>
        /// Applies the Unique Value colorizer to the basic raster layer.
        /// </summary>
        /// <param name="basicRasterLayer">The basic raster layer is either a raster or image service layer, or the image sub-layer of the mosaic layer.</param>
        /// <returns></returns>
        public static async Task SetToUniqueValueColorizer(BasicRasterLayer basicRasterLayer)
        {
            // Creates a new UV Colorizer Definition using the default constructor.
            UniqueValueColorizerDefinition UVColorizerDef = new UniqueValueColorizerDefinition();

            // Creates a new UV colorizer using the colorizer definition created above.
            CIMRasterUniqueValueColorizer newColorizer = await basicRasterLayer.CreateColorizerAsync(UVColorizerDef) as CIMRasterUniqueValueColorizer;

            // Sets the newly created colorizer on the layer.
            await QueuedTask.Run(() =>
            {
                basicRasterLayer.SetColorizer(newColorizer);
            });
        }
Пример #7
0
        public static async Task SetToClassifyColorizerFromLayerName(string layerName, int numberofClasses, string colorRampName)
        {
            try
            {
                // Gets the first 2D map from the project that is called Map.
                //Map _map = await GetMapFromProject(Project.Current, "Map");
                if (MapView.Active == null)
                {
                    ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("Failed to get map.");
                    return;
                }

                var _map = MapView.Active.Map;

                // Gets the selected layers from the current Map.
                IReadOnlyList <Layer> selectedLayers = _map.FindLayers(layerName);

                if (selectedLayers.Count == 1)
                {
                    // Gets the selected layer.
                    Layer firstSelectedLayer = selectedLayers.First();

                    if (firstSelectedLayer != null && (firstSelectedLayer is BasicRasterLayer || firstSelectedLayer is MosaicLayer))
                    {
                        // Gets the basic raster layer from the selected layer.

                        BasicRasterLayer basicRasterLayer = null;

                        if (firstSelectedLayer is BasicRasterLayer)
                        {
                            basicRasterLayer = (BasicRasterLayer)firstSelectedLayer;
                        }
                        else if (firstSelectedLayer is MosaicLayer)
                        {
                            basicRasterLayer = ((MosaicLayer)firstSelectedLayer).GetImageLayer() as BasicRasterLayer;
                        }

                        await SetToClassifyColorizerFromLayer(basicRasterLayer, numberofClasses, colorRampName);
                    }
                }
            }
            catch (Exception exc)
            {
                // Catch any exception found and display a message box.
                ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("Exception caught while trying to get layer: " + exc.Message);
                return;
            }
        }
        /// <summary>
        /// Event handler for layer selection changes.
        /// </summary>
        private async void SelectedLayersChanged(ArcGIS.Desktop.Mapping.Events.MapViewEventArgs mapViewArgs)
        {
            // Clears the combo box items when layer selection changes.
            Clear();

            // Checks the state of the active pane.
            // Returns the active pane state if the active pane is not null, else returns null.
            State state = (FrameworkApplication.Panes.ActivePane != null) ? FrameworkApplication.Panes.ActivePane.State : null;

            if (state != null && mapViewArgs.MapView != null)
            {
                // Gets the selected layers from the current Map.
                IReadOnlyList <Layer> selectedLayers = mapViewArgs.MapView.GetSelectedLayers();

                // The combo box will update only if one layer is selected.
                if (selectedLayers.Count == 1)
                {
                    // Gets the selected layer.
                    Layer firstSelectedLayer = selectedLayers.First();

                    // The combo box will update only if a raster layer is selected.
                    if (firstSelectedLayer != null && (firstSelectedLayer is BasicRasterLayer || firstSelectedLayer is MosaicLayer))
                    {
                        // Gets the basic raster layer from the selected layer.
                        if (firstSelectedLayer is BasicRasterLayer)
                        {
                            basicRasterLayer = (BasicRasterLayer)firstSelectedLayer;
                        }
                        else if (firstSelectedLayer is MosaicLayer)
                        {
                            basicRasterLayer = ((MosaicLayer)firstSelectedLayer).GetImageLayer() as BasicRasterLayer;
                        }

                        // Initiates the combox box selected item.
                        SelectedIndex = -1;

                        // Updates the combo box with the corresponding colorizers for the selected layer.
                        await UpdateCombo(basicRasterLayer);

                        // Sets the combo box to display the first combo box item.
                        SelectedIndex = 0;
                    }
                }
            }
        }
 private async void addwmts(string url)
 {
     if (MapView.Active == null)
     {
         ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("A map must be added the the project and be active");
         //FrameworkApplication.State.Deactivate("planet_state_connection");
     }
     Project project          = Project.Current;
     var     serverConnection = new CIMProjectServerConnection {
         URL = "https://tiles.planet.com/data/v1/layers/wmts/-7zefdf-UmCPwvBPaBJ0EmLRwx2M33-YL0Jdww?api_key=1fe575980e78467f9c28b552294ea410"
     };                                                                                                                                                                                             // "1fe575980e78467f9c28b552294ea410"
     var connection = new CIMWMTSServiceConnection {
         ServerConnection = serverConnection
     };
     await QueuedTask.Run(() =>
     {
         BasicRasterLayer layer2 = LayerFactory.Instance.CreateRasterLayer(connection, MapView.Active.Map, 0, "test");
     });
 }
        /// <summary>
        /// Create a map raster layer using the URL of the gallery item
        /// </summary>
        /// <param name="item"></param>
        private async void OpenWebMapAsync(object item)
        {
            if (item is Mosaic mosaic)
            {
                if (MapView.Active == null)
                {
                    ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("A map must be added the the project and be active");
                    //FrameworkApplication.State.Deactivate("planet_state_connection");
                    return;
                }
                Project project          = Project.Current;
                var     serverConnection = new CIMProjectServerConnection {
                    URL = mosaic._links._self.Substring(0, mosaic._links._self.IndexOf("?")) + "/wmts?REQUEST=GetCapabilities&api_key=" + Module1.Current.API_KEY.API_KEY_Value
                };
                var connection = new CIMWMTSServiceConnection {
                    ServerConnection = serverConnection
                };
                await QueuedTask.Run(() =>
                {
                    var extent            = MapView.Active.Extent;
                    string layerName      = "Planet Basemaps";
                    GroupLayer groupLayer = MapView.Active.Map.FindLayers(layerName).FirstOrDefault() as GroupLayer;
                    if (groupLayer == null)
                    {
                        int index  = MapView.Active.Map.Layers.Count;
                        groupLayer = LayerFactory.Instance.CreateGroupLayer(MapView.Active.Map, index, layerName);
                    }
                    BasicRasterLayer layer2 = LayerFactory.Instance.CreateRasterLayer(connection, groupLayer, 0, mosaic.name);
                    MapView.Active.ZoomTo(extent, TimeSpan.Zero);
                });
            }

            //Hardcoding trial to false so warning is never shown per Annies request 20190703
            Module1.Current.IsTrial = false;
            if (Module1.Current.IsTrial)
            {
                TrialWarning _trialwarning = new TrialWarning();
                _trialwarning.Owner   = FrameworkApplication.Current.MainWindow;
                _trialwarning.Closed += (o, e) => { _trialwarning = null; };
                _trialwarning.ShowDialog();
            }
        }
Пример #11
0
        /// <summary>
        /// Applies the Vector Field colorizer to the basic raster layer.
        /// </summary>
        /// <param name="basicRasterLayer">The basic raster layer is either a raster or image service layer, or the image sub-layer of the mosaic layer.</param>
        /// <returns></returns>
        public static async Task SetToVectorFieldColorizer(BasicRasterLayer basicRasterLayer)
        {
            // Defines values for parameters in colorizer definition.
            bool isUVComponents                 = false;
            int  magnitudeBandIndex             = 0;
            int  directionBandIndex             = 1;
            SymbolizationType symbolizationType = SymbolizationType.SingleArrow;

            await QueuedTask.Run(async() =>
            {
                // Creates a new Vector Field Colorizer Definition using defined parameters.
                VectorFieldColorizerDefinition vectorFieldColorizerDef = new VectorFieldColorizerDefinition(magnitudeBandIndex, directionBandIndex, isUVComponents, symbolizationType);

                // Creates a new Vector Field colorizer using the colorizer definition created above.
                CIMRasterVectorFieldColorizer newColorizer = await basicRasterLayer.CreateColorizerAsync(vectorFieldColorizerDef) as CIMRasterVectorFieldColorizer;

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

                bool hasRgb = _fieldList.Contains("red", StringComparer.OrdinalIgnoreCase) &&
                              _fieldList.Contains("green", StringComparer.OrdinalIgnoreCase) &&
                              _fieldList.Contains("blue", StringComparer.OrdinalIgnoreCase);
                if (_fieldList.Count == 0)
                {
                    Add(new ComboBoxItem("Msg: Raster has no Attribute table"));
                    return;
                }
                foreach (var fieldName in _fieldList)
                {
                    Add(new ComboBoxItem(fieldName));
                }
                if (hasRgb)
                {
                    Add(new ComboBoxItem(@"Attribute driven RGB"));
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($@"Exception caught on Update combo box: {ex.Message}", "Exception", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
Пример #13
0
        /// <summary>
        /// Applies the Discrete Color colorizer to the basic raster layer.
        /// </summary>
        /// <param name="basicRasterLayer">The basic raster layer is either a raster or image service layer, or the image sub-layer of the mosaic layer.</param>
        /// <returns></returns>
        public static async Task SetToDiscreteColorColorizer(BasicRasterLayer basicRasterLayer)
        {
            // Defines values for parameters in colorizer definition.
            int    numColors      = 50;
            string colorRampName  = "Aspect";
            string colorRampStyle = "ArcGIS Colors";

            await QueuedTask.Run(async() =>
            {
                //Get a color ramp from a style
                IList <ColorRampStyleItem> rampList = GetColorRampsFromStyleAsync(Project.Current, colorRampStyle, colorRampName);
                CIMColorRamp colorRamp = rampList[0].ColorRamp as CIMColorRamp;

                // Creates a new Discrete Colorizer Definition using the default constructor.
                DiscreteColorizerDefinition discreteColorizerDef = new DiscreteColorizerDefinition(numColors, colorRamp);

                // Creates a new Discrete colorizer using the colorizer definition created above.
                CIMRasterDiscreteColorColorizer newColorizer = await basicRasterLayer.CreateColorizerAsync(discreteColorizerDef) as CIMRasterDiscreteColorColorizer;

                // Sets the newly created colorizer on the layer.
                basicRasterLayer.SetColorizer(newColorizer);
            });
        }
Пример #14
0
        /// <summary>
        /// Applies the RGB colorizer to the basic raster layer.
        /// </summary>
        /// <param name="basicRasterLayer">The basic raster layer is either a raster or image service layer, or the image sub-layer of the mosaic layer.</param>
        /// <returns></returns>
        public static async Task SetToRGBColorizer(BasicRasterLayer basicRasterLayer)
        {
            // Defines parameters in colorizer definition.
            int bandIndexR = 2;
            int bandIndexG = 1;
            int bandIndexB = 0;
            RasterStretchType stretchType = RasterStretchType.MinimumMaximum;
            double            gammaR      = 2.0;
            double            gammaG      = 2.0;
            double            gammaB      = 2.0;

            await QueuedTask.Run(async() =>
            {
                // Creates a new RGB Colorizer Definition with defined parameters.
                RGBColorizerDefinition rgbColorizerDef = new RGBColorizerDefinition(bandIndexR, bandIndexG, bandIndexB, stretchType, gammaR, gammaG, gammaB);

                // Creates a new RGB colorizer using the colorizer definition created above.
                CIMRasterRGBColorizer newColorizer = await basicRasterLayer.CreateColorizerAsync(rgbColorizerDef) as CIMRasterRGBColorizer;

                // Sets the newly created colorizer on the layer.
                basicRasterLayer.SetColorizer(newColorizer);
            });
        }
Пример #15
0
        public static async void AddLayer(string targets, string name)
        {
            try
            {
                using (HttpClientHandler handler = new HttpClientHandler())
                {
                    handler.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
                    using (HttpClient client = new HttpClient(handler))
                    {
                        client.BaseAddress = new Uri("https://api.planet.com");
                        //HttpClientHandler handler = new HttpClientHandler()
                        //{
                        //    AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate
                        //};
                        //HttpClient client = new HttpClient(handler)
                        //{

                        //    BaseAddress = new Uri("https://api.planet.com")
                        //};
                        HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "data/v1/layers");
                        //request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));
                        request.Headers.Host = "tiles2.planet.com";
                        request.Headers.AcceptEncoding.Add(new StringWithQualityHeaderValue("gzip"));
                        var nvc = new List <KeyValuePair <string, string> >();
                        //nvc.Add(new KeyValuePair<string, string>("ids", "PSScene4Band:20190603_205042_1042,PSScene4Band:20190528_205949_43_1061,PSScene4Band:20190818_205116_1009"));
                        nvc.Add(new KeyValuePair <string, string>("ids", targets));
                        //var content = new StringContent(json, Encoding.UTF8, "application/json");
                        var content = new FormUrlEncodedContent(nvc);
                        request.Content = content;
                        var byteArray = Encoding.ASCII.GetBytes(Module1.Current.API_KEY.API_KEY_Value + ":hgvhgv");
                        client.DefaultRequestHeaders.Host = "api.planet.com";
                        //_client.DefaultRequestHeaders.Accept.Clear();
                        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));
                        content.Headers.Remove("Content-Type");
                        content.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
                        client.DefaultRequestHeaders.Add("Connection", "keep-alive");
                        client.DefaultRequestHeaders.Add("User-Agent", "ArcGISProC#");
                        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
                        using (HttpResponseMessage httpResponse = client.SendAsync(request).Result)
                        {
                            using (HttpContent content2 = httpResponse.Content)
                            {
                                var        json2      = content2.ReadAsStringAsync().Result;
                                customwmts customwmts = JsonConvert.DeserializeObject <customwmts>(json2);
                                customwmts.wmtsURL = new Uri("https://tiles.planet.com/data/v1/layers/wmts/" + customwmts.name + "?api_key=" + Module1.Current.API_KEY.API_KEY_Value);
                                //Geometry geometry2 = GeometryEngine.Instance.ImportFromJSON(JSONImportFlags.jsonImportDefaults, JsonConvert.SerializeObject( quickSearchResult.features[5].geometry));
                                var serverConnection = new CIMProjectServerConnection {
                                    URL = customwmts.wmtsURL.ToString()
                                };
                                var connection = new CIMWMTSServiceConnection {
                                    ServerConnection = serverConnection
                                };
                                await QueuedTask.Run(() =>
                                {
                                    Layer group           = MapView.Active.Map.FindLayer(Asset.RootGroup);
                                    GroupLayer groupLayer = null;
                                    if (group != null)
                                    {
                                        groupLayer = group as GroupLayer;
                                    }
                                    else
                                    {
                                        int index  = Asset.FindRootIndex();
                                        groupLayer = LayerFactory.Instance.CreateGroupLayer(MapView.Active.Map, index, Asset.RootGroup);
                                    }
                                    BasicRasterLayer layer2 = LayerFactory.Instance.CreateRasterLayer(connection, groupLayer, 0, name);
                                });
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                MessageBox.Show("Error adding to Map", "Add to Map");
            }
        }
        /// <summary>
        /// The on comboBox selection change event.
        /// </summary>
        /// <param name="item">The newly selected combo box item</param>
        protected override async void OnSelectionChange(ComboBoxItem item)
        {
            if (_applicableColorizerList == null)
            {
                MessageBox.Show("The applicable colorizer list is null.", "Colorizer Error:", MessageBoxButton.OK, MessageBoxImage.Error);
            }

            if (item == null)
            {
                MessageBox.Show("The combo box item is null.", "Combo box Error:", MessageBoxButton.OK, MessageBoxImage.Error);
            }

            if (string.IsNullOrEmpty(item.Text))
            {
                MessageBox.Show("The combo box item text is null or empty.", "Combo box Error:", MessageBoxButton.OK, MessageBoxImage.Error);
            }

            if (MapView.Active == null)
            {
                MessageBox.Show("There is no active MapView.", "Combo box Error:", MessageBoxButton.OK, MessageBoxImage.Error);
            }

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

                // Gets the BasicRasterLayer from the selected layer.
                if (firstSelectedLayer is BasicRasterLayer)
                {
                    basicRasterLayer = (BasicRasterLayer)firstSelectedLayer;
                }
                else if (firstSelectedLayer is MosaicLayer)
                {
                    basicRasterLayer = ((MosaicLayer)firstSelectedLayer).GetImageLayer() as BasicRasterLayer;
                }
                else
                {
                    MessageBox.Show("The selected layer is not a basic raster layer", "Select Layer Error:", MessageBoxButton.OK, MessageBoxImage.Error);
                }

                // Gets the colorizer type from the selected combo box item.
                RasterColorizerType ColorizerType = _applicableColorizerList.FirstOrDefault(cn => Enum.GetName(typeof(RasterColorizerType), cn) == item.Text);

                // Applies the selected colorizer to the layer.
                switch (ColorizerType)
                {
                case RasterColorizerType.RGBColorizer:
                {
                    // Sets the RGB colorizer to the selected layer.
                    await ColorizerDefinitionVM.SetToRGBColorizer(basicRasterLayer);

                    break;
                }

                case RasterColorizerType.StretchColorizer:
                {
                    // Sets the Stretch colorizer to the selected layer.
                    await ColorizerDefinitionVM.SetToStretchColorizer(basicRasterLayer);

                    break;
                }

                case RasterColorizerType.DiscreteColorColorizer:
                {
                    // Sets the Discrete Color colorizer to the selected layer.
                    await ColorizerDefinitionVM.SetToDiscreteColorColorizer(basicRasterLayer);

                    break;
                }

                case RasterColorizerType.ColormapColorizer:
                {
                    // Sets the ColorMap colorizer to the selected layer.
                    await ColorizerDefinitionVM.SetToColorMapColorizer(basicRasterLayer);

                    break;
                }

                case RasterColorizerType.ClassifyColorizer:
                {
                    // Sets the Classify colorizer to the selected layer.
                    await ColorizerDefinitionVM.SetToClassifyColorizer(basicRasterLayer);

                    break;
                }

                case RasterColorizerType.UniqueValueColorizer:
                {
                    // Sets the Unique Value colorizer to the selected layer
                    await ColorizerDefinitionVM.SetToUniqueValueColorizer(basicRasterLayer);

                    break;
                }

                case RasterColorizerType.VectorFieldColorizer:
                {
                    // Sets the Vector Field colorizer to the selected layer
                    await ColorizerDefinitionVM.SetToVectorFieldColorizer(basicRasterLayer);

                    break;
                }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Exception caught in OnSelectionChange:" + ex.Message, "Exception", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
        /// <summary>
        /// adds the sected  item to the map. uses the _mapLayerName prperty to know what scene to use
        /// </summary>
        public async void doAddToMap()
        {
            if (_permissions.Length == 0)
            {
                return;
            }
            //IsSelected = true;
            if (canToggleExisting())
            {
                return;
            }
            try
            {
                string            targets = properties.item_type + ":" + id.ToString();
                HttpClientHandler handler = new HttpClientHandler()
                {
                    AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate
                };
                using (HttpClient client = new HttpClient(handler))
                {
                    client.BaseAddress = new Uri("https://api.planet.com");
                    targets            = targets.TrimEnd(',');
                    HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "data/v1/layers");
                    //request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));
                    request.Headers.Host = "tiles2.planet.com";
                    request.Headers.AcceptEncoding.Add(new StringWithQualityHeaderValue("gzip"));
                    var nvc = new List <KeyValuePair <string, string> >();
                    //nvc.Add(new KeyValuePair<string, string>("ids", "PSScene4Band:20190603_205042_1042,PSScene4Band:20190528_205949_43_1061,PSScene4Band:20190818_205116_1009"));
                    nvc.Add(new KeyValuePair <string, string>("ids", targets));
                    //var content = new StringContent(json, Encoding.UTF8, "application/json");
                    var content = new FormUrlEncodedContent(nvc);
                    request.Content = content;
                    var byteArray = Encoding.ASCII.GetBytes(Module1.Current.API_KEY.API_KEY_Value + ":hgvhgv");
                    client.DefaultRequestHeaders.Host = "api.planet.com";
                    //_client.DefaultRequestHeaders.Accept.Clear();
                    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));
                    content.Headers.Remove("Content-Type");
                    content.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
                    client.DefaultRequestHeaders.Add("Connection", "keep-alive");
                    client.DefaultRequestHeaders.Add("User-Agent", "ArcGISProC#");
                    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
                    using (HttpResponseMessage httpResponse = client.SendAsync(request).Result)
                    {
                        if (httpResponse.IsSuccessStatusCode)
                        {
                            using (HttpContent content2 = httpResponse.Content)
                            {
                                var        json2      = content2.ReadAsStringAsync().Result;
                                customwmts customwmts = JsonConvert.DeserializeObject <customwmts>(json2);
                                customwmts.wmtsURL = new Uri("https://tiles.planet.com/data/v1/layers/wmts/" + customwmts.name + "?api_key=" + Module1.Current.API_KEY.API_KEY_Value);
                                //Geometry geometry2 = GeometryEngine.Instance.ImportFromJSON(JSONImportFlags.jsonImportDefaults, JsonConvert.SerializeObject( quickSearchResult.features[5].geometry));
                                var serverConnection = new CIMProjectServerConnection {
                                    URL = customwmts.wmtsURL.ToString()
                                };
                                var connection = new CIMWMTSServiceConnection {
                                    ServerConnection = serverConnection
                                };
                                string layerName = title + " (" + id + ")";
                                await QueuedTask.Run(() =>
                                {
                                    GroupLayer group        = GetGroupLayer();
                                    BasicRasterLayer layer2 = LayerFactory.Instance.CreateRasterLayer(connection, group as ILayerContainerEdit, 0, layerName);
                                });

                                mapLayerName = layerName;
                                CheckParents(true);
                                RemoveFootprints();
                            }
                        }
                        else
                        {
                            if (httpResponse.ReasonPhrase == "too many requests")
                            {
                                Thread.Sleep(1000);
                                doAddToMap();
                            }
                            else
                            {
                                MessageBox.Show("There was an problem adding the map, the server returned an error:" + Environment.NewLine + httpResponse.ReasonPhrase);
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("Error adding strip to Map", "Add to Map");
            }
        }
        /// <summary>
        /// Function to identify rendered and source dataset pixel values for one or more
        /// raster, mosaic and image service layers.
        /// </summary>
        /// <param name="mapPoint">Map point to identify pixel values.</param>
        public static async void CustomRasterIdentify(MapPoint mapPoint)
        {
            // Create a new list of popup pages.
            var popupContents = new List <PopupContent>();
            // Create an empty string that will represent what goes into a popup page.
            string identifiedVal = "";
            // Create the popup pages to show.
            await QueuedTask.Run(() =>
            {
                // Check if there is an active map view.
                if (MapView.Active != null)
                {
                    // Get the active map view.
                    var mapView = MapView.Active;
                    // Get the list of selected layers.
                    IReadOnlyList <Layer> selectedLayerList = MapView.Active.GetSelectedLayers();
                    if (selectedLayerList.Count == 0)
                    {
                        // If no layers are selected fill the popup page with the appropriate message.
                        // Note: you can use html tags to format the text.
                        identifiedVal += "<p>No Layers selected. Please select one or more Raster, Mosaic or Image Service layers.</p>";
                        // Add the popup page to the list of pages.
                        popupContents.Add(new PopupContent(identifiedVal, "Custom Raster Identify"));
                    }
                    else
                    {
                        // Iterate over the list of selected layers.
                        foreach (Layer currentSelectedLayer in selectedLayerList)
                        {
                            #region Get a basic raster layer from the selected layer.
                            BasicRasterLayer currentRasterLayer = null;
                            if (currentSelectedLayer is MosaicLayer)
                            {
                                // If the current selected layer is a mosaic layer,
                                MosaicLayer mosaicLayer = currentSelectedLayer as MosaicLayer;
                                // Get the image sub-layer from the mosaic layer. This is a basic raster layer.
                                currentRasterLayer = mosaicLayer.GetImageLayer() as BasicRasterLayer;
                            }
                            else if (currentSelectedLayer is BasicRasterLayer)
                            {
                                // If the current selected layer is a raster layer or image service layer,
                                // both are already basic raster layers.
                                currentRasterLayer = currentSelectedLayer as BasicRasterLayer;
                            }
                            else
                            {
                                // If the current selected layer is neither a mosaic nor a raster or image service layer,
                                // fill the popup page with the appropriate message.
                                identifiedVal += "<p>Selected layer is not a raster layer. Please select one or more Raster, Mosaic or Image Service layers.</p>";
                                // Add the popup page to the list of pages.
                                popupContents.Add(new PopupContent(identifiedVal, "Custom Raster Identify for: " + currentSelectedLayer.Name));
                                continue;
                            }
                            #endregion

                            #region Get the pixel value for the rendered raster.
                            // Add the label for the rendered pixel value.
                            identifiedVal += "<b>Rendered Pixel value: </b>";
                            // Get the raster from the current selected raster layer.
                            Raster raster = currentRasterLayer.GetRaster();
                            // If the map spatial reference is different from the spatial reference of the raster,
                            // set the map spatial reference on the raster. This will ensure the map points are
                            // correctly reprojected to image points.
                            if (mapView.Map.SpatialReference.Name != raster.GetSpatialReference().Name)
                            {
                                raster.SetSpatialReference(mapView.Map.SpatialReference);
                            }

                            // Convert the map point to be identified into an image point.
                            Tuple <int, int> imagePoint = raster.MapToPixel(mapPoint.X, mapPoint.Y);
                            if ((int)imagePoint.Item1 < 0 || (int)imagePoint.Item1 > raster.GetWidth() ||
                                (int)imagePoint.Item2 < 0 || (int)imagePoint.Item2 > raster.GetHeight())
                            {
                                // If the point is outside the image, fill the pixel value with the appropriate message.
                                identifiedVal += "Point is not within image. \n";
                            }
                            else
                            {
                                // If the point is within the image. Iterate over the bands in the raster.
                                for (int band = 0; band < raster.GetBandCount(); band++)
                                {
                                    // Get the pixel value based on the band, column and row and add the
                                    // formatted pixel value to the popup page.
                                    if (band == 0)
                                    {
                                        identifiedVal += raster.GetPixelValue(band, (int)imagePoint.Item1, (int)imagePoint.Item2).ToString();
                                    }
                                    else
                                    {
                                        identifiedVal += ", " + raster.GetPixelValue(band, (int)imagePoint.Item1, (int)imagePoint.Item2).ToString();
                                    }
                                }
                                identifiedVal += ".";
                            }
                            // Add the rendered pixel value to the popup page contents.
                            string htmlContent = "<p>" + identifiedVal + "</p>";
                            #endregion

                            #region Get the pixel value for the source raster dataset.
                            // Add the label for the source dataset pixel value.
                            identifiedVal = "<b>Dataset Pixel value: </b>";
                            // Get the basic raster dataset from the raster.
                            BasicRasterDataset basicRasterDataset = raster.GetRasterDataset();
                            if (!(basicRasterDataset is RasterDataset))
                            {
                                // If the dataset is not a raster dataset, fill the pixel value with the appropriate message.
                                identifiedVal += "Selected layer is not a Raster Layer. Please select one or more Raster, Mosaic or Image Service layers.";
                                htmlContent   += "<p>" + identifiedVal + "</p>";
                                popupContents.Add(new PopupContent(htmlContent, "Custom Raster Identify for " + currentSelectedLayer.Name));
                            }
                            // Get the raster dataset.
                            RasterDataset rasterDataset = basicRasterDataset as RasterDataset;
                            // Create a full raster from the raster dataset.
                            raster = rasterDataset.CreateFullRaster();
                            // If the map spatial reference is different from the spatial reference of the raster,
                            // Set the map spatial reference on the raster. This will ensure the map points are
                            // correctly reprojected to image points.
                            if (mapView.Map.SpatialReference.Name != raster.GetSpatialReference().Name)
                            {
                                raster.SetSpatialReference(mapView.Map.SpatialReference);
                            }

                            // Convert the map point to be identified to an image point.
                            imagePoint = raster.MapToPixel(mapPoint.X, mapPoint.Y);
                            if ((int)imagePoint.Item1 < 0 || (int)imagePoint.Item1 > raster.GetWidth() ||
                                (int)imagePoint.Item2 < 0 || (int)imagePoint.Item2 > raster.GetHeight())
                            {
                                // If the point is outside the image, fill the pixel value with the appropriate message.
                                identifiedVal += "Point is not within image. \n";
                            }
                            else
                            {
                                // If the point is within the image. Iterate over the bands in the raster.
                                for (int band = 0; band < raster.GetBandCount(); band++)
                                {
                                    // Get the pixel value based on the band, column and row and add the
                                    // formatted pixel value to the popup page.
                                    if (band == 0)
                                    {
                                        identifiedVal += raster.GetPixelValue(band, (int)imagePoint.Item1, (int)imagePoint.Item2).ToString();
                                    }
                                    else
                                    {
                                        identifiedVal += ", " + raster.GetPixelValue(band, (int)imagePoint.Item1, (int)imagePoint.Item2).ToString();
                                    }
                                }
                                identifiedVal += ".";
                            }
                            // Add the source dataset pixel value to the popup page contents.
                            htmlContent += "<p>" + identifiedVal + "</p>";
                            #endregion

                            // Add the popup page to the list of pages.
                            popupContents.Add(new PopupContent(htmlContent, "Custom Raster Identify for " + currentSelectedLayer.Name));
                            // Reset
                            identifiedVal = "";
                        }
                    }
                }
            });

            // Show custom popup with the list of popup pages created above.
            MapView.Active.ShowCustomPopup(popupContents);
        }
Пример #19
0
        /// <summary>
        /// Create a map raster layer using the URL of the gallery item
        /// </summary>
        /// <param name="item"></param>
        private async void OpenWebMapAsync(object item)
        {
            if (item is Mosaic mosaic)
            {
                if (MapView.Active == null)
                {
                    ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("A map must be added the the project and be active");
                    //FrameworkApplication.State.Deactivate("planet_state_connection");
                    return;
                }
                Project project          = Project.Current;
                var     serverConnection = new CIMProjectServerConnection {
                    URL = mosaic._links._self.Substring(0, mosaic._links._self.IndexOf("?")) + "/wmts?REQUEST=GetCapabilities&api_key=" + Module1.Current.API_KEY.API_KEY_Value
                };
                var connection = new CIMWMTSServiceConnection {
                    ServerConnection = serverConnection
                };
                await QueuedTask.Run(() =>
                {
                    var extent            = MapView.Active.Extent;
                    string layerName      = Model.Asset.BasemapsGroup;
                    GroupLayer groupLayer = MapView.Active.Map.FindLayers(layerName).FirstOrDefault() as GroupLayer;
                    if (groupLayer == null)
                    {
                        //add basemap group above any existing basemap-type layers, but below planet daily
                        //imagery group layer
                        IEnumerable <Layer> layers = MapView.Active.Map.Layers;
                        int targetIndex            = 0;
                        int lowestIndex            = MapView.Active.Map.Layers.Count;
                        if (lowestIndex > 0)
                        {
                            lowestIndex = lowestIndex - 1;
                            foreach (Layer layer in layers)
                            {
                                if (layer.Name == Model.Asset.RootGroup)
                                {
                                    targetIndex = MapView.Active.Map.Layers.IndexOf(layer) + 1;
                                    break;
                                }
                                if (layer is GroupLayer group)
                                {
                                    IEnumerable <Layer> children = group.GetLayersAsFlattenedList();
                                    foreach (Layer child in children)
                                    {
                                        string childType = child.GetType().Name;
                                        if (Model.Asset.ValidTypes.Contains(childType))
                                        {
                                            int layerIndex = MapView.Active.Map.Layers.IndexOf(group);
                                            if (layerIndex < lowestIndex)
                                            {
                                                lowestIndex = layerIndex;
                                                break;
                                            }
                                        }
                                    }
                                }
                                string type = layer.GetType().Name;
                                if (Model.Asset.ValidTypes.Contains(type))
                                {
                                    int layerIndex = MapView.Active.Map.Layers.IndexOf(layer);
                                    if (layerIndex < lowestIndex)
                                    {
                                        lowestIndex = layerIndex;
                                    }
                                }
                            }
                        }
                        if (targetIndex == 0)
                        {
                            targetIndex = lowestIndex == 0 ? lowestIndex : lowestIndex - 1;
                        }
                        groupLayer = LayerFactory.Instance.CreateGroupLayer(MapView.Active.Map, targetIndex, layerName);
                    }
                    try
                    {
                        BasicRasterLayer layer2 = LayerFactory.Instance.CreateRasterLayer(connection, groupLayer, 0, mosaic.name);
                        MapView.Active.ZoomTo(extent, TimeSpan.Zero);
                    }
                    catch (Exception)
                    {
                        ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("There is a problem loading the basemap. This is mostly likely due to a permissions issue.");
                    }
                });
            }

            //Hardcoding trial to false so warning is never shown per Annies request 20190703
            Module1.Current.IsTrial = false;
            if (Module1.Current.IsTrial)
            {
                TrialWarning _trialwarning = new TrialWarning();
                _trialwarning.Owner   = FrameworkApplication.Current.MainWindow;
                _trialwarning.Closed += (o, e) => { _trialwarning = null; };
                _trialwarning.ShowDialog();
            }
        }