Esempio n. 1
0
        // Initializes the Layer property
        private void initializeLayer()
        {
            Layer layer = null;

            // Create the layer based on the type of service encapsulated by the search result
            if (Service is MapService)
            {
                MapService mapService = (MapService)Service;
                if (mapService.IsTiled &&
                    mapService.SpatialReference.WKID == MapApplication.Current.Map.SpatialReference.WKID)
                {
                    layer = new ArcGISTiledMapServiceLayer()
                    {
                        Url = Service.Url, ProxyURL = ProxyUrl
                    }
                }
                ;
                else
                {
                    layer = new ArcGISDynamicMapServiceLayer()
                    {
                        Url = Service.Url, ProxyURL = ProxyUrl
                    }
                };
            }
            else if (Service is ImageService)
            {
                layer = new ArcGISImageServiceLayer()
                {
                    Url = Service.Url, ProxyURL = ProxyUrl
                };
            }
            else if (Service is FeatureLayerService || (Service is FeatureService && ((FeatureService)Service).Layers.Count() == 1))
            {
                string url = Service is FeatureService?string.Format("{0}/0", Service.Url) : Service.Url;

                layer = new FeatureLayer()
                {
                    Url       = url,
                    ProxyUrl  = ProxyUrl,
                    OutFields = new OutFields()
                    {
                        "*"
                    }
                };
            }

            // Initialize the layer's ID and display name
            if (layer != null)
            {
                string id   = Guid.NewGuid().ToString("N");
                string name = propertyExists("Title") ? Result.Title : id;

                layer.ID = id;
                MapApplication.SetLayerName(layer, name);
            }
            Layer = layer;
        }
Esempio n. 2
0
        }         // public string getAGSMapServiceUrl()

        /// <summary>
        /// Create and add to map a simple graphics layer, or return existed GL
        /// </summary>
        /// <returns>redline layer</returns>
        public static GraphicsLayer makeRLLayer(Map map, string layerID, string layerName)
        {
            if (map != null)
            {
                var graphicsLayer = map.Layers[layerID] as GraphicsLayer;
                if (graphicsLayer != null)
                {
                    string.Format("VLayer.makeRLLayer, layer already exists, id '{0}'", layerID).clog();
                    return(graphicsLayer);
                }
            }

            string.Format("VLayer.makeRLLayer, create new GraphicsLayer, id '{0}'", layerID).clog();
            // don't react on hover
            var symbPMS = new PictureMarkerSymbol()
            {
                Height  = 28,
                Width   = 28,
                OffsetX = 14,
                OffsetY = 28,
                Source  = new System.Windows.Media.Imaging.BitmapImage(
                    new Uri("/Images/MarkerSymbols/Basic/RedTag.png", UriKind.RelativeOrAbsolute))
            };
            // react on hover
            var symbIFS = new ESRI.ArcGIS.Mapping.Core.Symbols.ImageFillSymbol()
            {
                Source = "/Images/MarkerSymbols/Basic/RedTag.png",
                //OffsetX = 14, OffsetY = 28,
                Size    = 28,
                OriginX = 0.5, OriginY = 1
            };

            var gl = new GraphicsLayer()
            {
                ID       = layerID,
                Renderer = new SimpleRenderer()
                {
                    Symbol = symbIFS                     // new SimpleMarkerSymbol()
                },
                RendererTakesPrecedence = false
            };

            //ESRI.ArcGIS.Client.Extensibility.LayerProperties.SetIsPopupEnabled(gl, false);

            // Set layer name in Map Contents
            //gl.SetValue(MapApplication.LayerNameProperty, lyrName);
            //* Remove the line that says "wmsLayer.SetValue(MapApplication.LayerNameProperty, layerName);" and replace it with "MapApplication.SetLayerName(wmsLayer, layerName);"
            //* http://forums.arcgis.com/threads/51206-Adding-WMS-Service?p=178500&viewfull=1#post178500
            //MapApplication.SetLayerName(gl, lyrName);

            if (map != null)
            {
                gl.Initialize();
                map.Layers.Add(gl);
                MapApplication.SetLayerName(gl, layerName);
            }
            return(gl);
        } // public static GraphicsLayer makeRLLayer(Map map, string layerID, string layerName)
Esempio n. 3
0
        }                    // public void addSelectedLayer()

        public void addLayer(VLayer lyr)
        {
            log("addLayer " + lyr.lyrUrl);
            ESRI.ArcGIS.Client.Map             map  = MapApplication.Current.Map;
            ESRI.ArcGIS.Client.LayerCollection lyrs = map.Layers;
            lyr.lyr.InitializationFailed += new EventHandler <EventArgs>(lyr_InitializationFailed);
            lyrs.Add(lyr.lyr);
            MapApplication.SetLayerName(lyr.lyr, lyr.lyrName);
            // http://help.arcgis.com/en/webapps/silverlightviewer/help/index.html#//01770000001s000000
        }         // public void addLayer(VLayer lyr)
Esempio n. 4
0
        }         // void pingsrv_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e) {

        /// <summary>
        /// If layers in config: clear map.layers; attach mapprogress event; add layers from config to map;
        /// set extent; set selected layer
        /// </summary>
        /// <param name="cfg"></param>
        /// <param name="map"></param>
        /// <param name="lyrInitFail"></param>
        /// <param name="mapProgress"></param>
        public static VLayer loadMapCfg(string cfg, ESRI.ArcGIS.Client.Map map,
                                        EventHandler <EventArgs> lyrInitFail, EventHandler <ProgressEventArgs> mapProgress)
        {
            // if LayersList: clean map; add layers from LayersList to map
            ESRI.ArcGIS.Client.Geometry.Envelope ext = VRestore.mapExtentFromConfig(cfg);
            var layersList = VRestore.lyrsListFromConfig(cfg);

            if (layersList.Count <= 0)
            {
                throw new Exception("VRestore.loadMapCfg: список слоев пуст, видимо была сохранена пустая карта");
            }

            ESRI.ArcGIS.Client.LayerCollection lyrs = map.Layers;
            // clear map
            lyrs.Clear();
            VLayer sl = null;

            if (mapProgress != null && layersList.Count > 0)
            {
                map.Progress -= mapProgress;
                map.Progress += mapProgress;
            }

            // add layers to map
            foreach (var x in layersList)
            {
                //string.Format("loadMapCfg, add layer {0}", x.lyrUrl).clog();
                string.Format("VRestore.loadMapCfg, add layer '{0}' '{1}' '{2}'", x.ID, x.lyrName, x.lyrType).clog();
                if (lyrInitFail != null)
                {
                    x.lyr.InitializationFailed += new EventHandler <EventArgs>(lyrInitFail);
                }
                //x.lyr.SetValue(MapApplication.LayerNameProperty, x.lyrName);
                //x.lyr.Initialize();
                lyrs.Add(x.lyr);
                MapApplication.SetLayerName(x.lyr, x.lyrName);
                if (x.selected)
                {
                    sl = x;
                }
            }
            if (ext != null)
            {
                map.Extent = ext;
            }

            // select selected layer
            if (sl != null)
            {
                string.Format("VRestore.loadMapCfg, selected layer '{0}' '{1}'", sl.ID, sl.lyrName).clog();
                MapApplication.Current.SelectedLayer = sl.lyr;
            }
            return(sl);
        }         // public static VLayer loadMapCfg(string cfg, ESRI.ArcGIS.Client.Map map)
Esempio n. 5
0
        }         // private static void OnDrawEnabledChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)

        /// <summary>
        /// Creates a simple graphics layer to show the location identified
        /// </summary>
        /// <returns></returns>
        private GraphicsLayer createResultsLayer()
        {
            log("VIdentify.createResultsLayer, create new GraphicsLayer");

            var gl = new GraphicsLayer()
            {
                ID       = "IdentifyResultsLayer",
                Renderer = new SimpleRenderer()
                {
                    //Symbol = identifyDialog.Resources["RedMarkerSymbol"] as Symbol
                    Symbol = identifyDialog.LayoutRoot.Resources["RedMarkerSymbol"] as Symbol
                }
            };

            // Set layer name in Map Contents
            // gl.SetValue(MapApplication.LayerNameProperty, "Выборка атрибутики"); // http://forums.arcgis.com/threads/51206-Adding-WMS-Service?p=178500&viewfull=1#post178500
            MapApplication.SetLayerName(gl, "Выборка атрибутики");
            return(gl);
        } // private GraphicsLayer createResultsLayer()
Esempio n. 6
0
        }         // public void userGiveKMLLayerParams(string url, string layers, string lyrname, string proxy)

        /// <summary>
        /// Call from form, add CSV layer to map
        /// </summary>
        /// <param name="url"></param>
        /// <param name="lyrname"></param>
        /// <param name="proxy"></param>
        public void userGiveCSVLayerParams(string url, string lyrname, string proxy)
        {
            log(string.Format("userGiveCSVLayerParams, name '{2}', url '{0}', proxy '{1}'", url, proxy, lyrname));
            MapApplication.Current.HideWindow(csvParamsForm);

            var lyr = new ESRI.ArcGIS.Client.Toolkit.DataSources.CsvLayer();

            lyr.Url      = url;
            lyr.ProxyUrl = proxy;
            lyr.Opacity  = 1;
            lyr.ID       = VExtClass.computeSHA1Hash(string.Format("{0}", url));

            lyr.Initialized += (osender, eargs) => {
                log(string.Format("userGiveCSVLayerParams.Initialized, {0}-{1}", lyrname, lyr.ID));
            };
            lyr.Initialize();

            MapApplication.SetLayerName(lyr, lyrname);
            ESRI.ArcGIS.Client.Extensibility.LayerProperties.SetIsVisibleInMapContents(lyr, true);
            MapApplication.Current.Map.Layers.Add(lyr);
            log(string.Format("userGiveCSVLayerParams, done for name '{2}', url '{0}', proxy '{1}'", url, proxy, lyrname));
        }         // public void userGiveCSVLayerParams(string url, string lyrname, string proxy)
Esempio n. 7
0
        }         // public void userGiveWMTSLayerParams(string url, string lyrname, string proxy, string sublyr)

        /// <summary>
        /// Call from form, add KML layer to map.
        /// </summary>
        /// <param name="url"></param>
        /// <param name="layers"></param>
        /// <param name="lyrname"></param>
        /// <param name="proxy"></param>
        public void userGiveKMLLayerParams(string url, string layers, string lyrname, string proxy)
        {
            log(string.Format("userGiveKMLLayerParams, name '{3}', url '{0}', layers '{1}', proxy '{2}'", url, layers, proxy, lyrname));
            MapApplication.Current.HideWindow(kmlParamsForm);

            var lyr = new ESRI.ArcGIS.Client.Toolkit.DataSources.KmlLayer();

            lyr.Url           = new System.Uri(url, UriKind.RelativeOrAbsolute);
            lyr.ProxyUrl      = proxy;
            lyr.VisibleLayers = string.IsNullOrEmpty(layers) ? null : layers.Split(',');
            lyr.Opacity       = 1;
            lyr.ID            = VExtClass.computeSHA1Hash(string.Format("{0}, {1}", url, layers));

            lyr.Initialized += (osender, eargs) => {
                log(string.Format("userGiveKMLLayerParams.Initialized, {0}-{1}", lyrname, lyr.ID));
            };
            lyr.Initialize();

            MapApplication.SetLayerName(lyr, lyrname);
            ESRI.ArcGIS.Client.Extensibility.LayerProperties.SetIsVisibleInMapContents(lyr, true);
            MapApplication.Current.Map.Layers.Add(lyr);
            log(string.Format("userGiveKMLLayerParams, done for {3}, url '{0}', layers '{1}', proxy '{2}'", url, layers, proxy, lyrname));
        }         // public void userGiveKMLLayerParams(string url, string layers, string lyrname, string proxy)
Esempio n. 8
0
        }         // private GraphicsLayer getRLLayer()

        /// <summary>
        /// Add RL layer to map or return already existing layer
        /// </summary>
        /// <param name="rl"></param>
        /// <returns></returns>
        private GraphicsLayer addRLL2Map(GraphicsLayer gl)
        {
            log(string.Format("VRedlineImpl.addRLL2Map, initialize and add to map RL layer"));
            var el = MapApplication.Current.Map.Layers[gl.ID] as GraphicsLayer;

            if (el != null)
            {
                log(string.Format("VRedlineImpl.addRLL2Map, layer already exist"));
                return(el);
            }

            //var lyr = MapApplication.Current.SelectedLayer;

            gl.MouseLeftButtonDown -= gl_MouseLeftButtonDown;
            gl.MouseLeftButtonDown += gl_MouseLeftButtonDown;
            gl.Initialize();
            MapApplication.Current.Map.Layers.Add(gl);
            MapApplication.SetLayerName(gl, layerName);

            //MapApplication.Current.SelectedLayer = lyr;
            //ESRI.ArcGIS.Client.Extensibility.LayerProperties.SetIsPopupEnabled(gl, false);
            return(gl);
        }         // private GraphicsLayer addRLL2Map(GraphicsLayer rl)
Esempio n. 9
0
        }         // public void userPickLayerType(string lyrtype)

        /// <summary>
        /// Call from form.
        /// Add WMS layer to map.
        /// </summary>
        /// <param name="url"></param>
        /// <param name="wmslayers"></param>
        /// <param name="version"></param>
        /// <param name="lyrname"></param>
        /// <param name="proxy"></param>
        public void userGiveWMSLayerParams(string url, string wmslayers, string version, string lyrname, string proxy)
        {
            log(string.Format("userGiveWMSLayerParams, {3}, url '{0}', layers '{1}', version '{2}'", url, wmslayers, version, lyrname));
            MapApplication.Current.HideWindow(wmsParamsForm);

            var lyr = new ESRI.ArcGIS.Client.Toolkit.DataSources.WmsLayer();

            lyr.Url = url;
            //lyr.ProxyUrl = "http://servicesbeta3.esri.com/SilverlightDemos/ProxyPage/proxy.ashx";
            //lyr.ProxyUrl = "http://vdesk.algis.com/agsproxy/proxy.ashx";
            //lyr.ProxyUrl = this.proxyUrl;
            lyr.ProxyUrl            = proxy;
            lyr.SkipGetCapabilities = false;
            lyr.Version             = string.IsNullOrEmpty(version) ? "1.1.1" : version;
            lyr.Opacity             = 1;
            lyr.Layers = string.IsNullOrEmpty(wmslayers) ? null : wmslayers.Split(',');
            lyr.ID     = VExtClass.computeSHA1Hash(string.Format("{0}, {1}, {2}", url, wmslayers, version));

            lyr.Initialized += (osender, eargs) => {
                log(string.Format("userGiveWMSLayerParams.Initialized, turn on all sublayers for {0}-{1}", lyrname, lyr.ID));
                List <string> layerNames = new List <string>();
                foreach (var layerInfo in lyr.LayerList)
                {
                    if (layerInfo.Name != null)
                    {
                        layerNames.Add(layerInfo.Name);
                    }
                }
                lyr.Layers = layerNames.ToArray();
            };
            lyr.Initialize();

            MapApplication.SetLayerName(lyr, lyrname);
            ESRI.ArcGIS.Client.Extensibility.LayerProperties.SetIsVisibleInMapContents(lyr, true);
            MapApplication.Current.Map.Layers.Add(lyr);
            log(string.Format("userGiveWMSLayerParams, done for {3}, url '{0}', layers '{1}', version '{2}'", url, wmslayers, version, lyrname));
        }         // public void userGiveWMSLayerParams(string url, string wmslayers, string version, string lyrname)
        // Initializes the available layers based on the parent service and clears the selected layers
        private void initializeLayers()
        {
            AvailableLayers.Clear();
            SelectedLayers.Clear();

            // Make sure the service is a type that contains sublayers
            if (!(Service is FeatureService) && !(Service is MapService))
            {
                return; // Other service types don't have sublayers
            }
            // Loop through each sublayer in the service
            dynamic serviceAsDynamic = Service;

            foreach (FeatureLayerDescription layer in serviceAsDynamic.Layers)
            {
                // Create a feature layer for the sublayer
                string       id     = Guid.NewGuid().ToString("N");
                FeatureLayer fLayer = new FeatureLayer()
                {
                    Url       = string.Format("{0}/{1}", Service.Url, layer.Id),
                    OutFields = new OutFields()
                    {
                        "*"
                    },
                    ProxyUrl = ProxyUrl,
                    ID       = id
                };

                // Initialize the layer's name
                string name = !string.IsNullOrEmpty(layer.Name) ? layer.Name : id;
                MapApplication.SetLayerName(fLayer, name);

                // Add the layer to the set of available layers
                AvailableLayers.Add(fLayer);
            }
        }
Esempio n. 11
0
        }         // public void userGiveWMSLayerParams(string url, string wmslayers, string version, string lyrname)

        /// <summary>
        /// Call from form, add WMTS layer to map
        /// </summary>
        /// <param name="url"></param>
        /// <param name="lyrname"></param>
        /// <param name="proxy"></param>
        /// <param name="sublyr"></param>
        public void userGiveWMTSLayerParams(string url, string lyrname, string proxy, string sublyr)
        {
            log(string.Format("userGiveWMTSLayerParams, url '{0}', proxy '{1}', name '{2}'", url, proxy, lyrname));
            MapApplication.Current.HideWindow(wmtsParamsForm);

            var lyr = new ESRI.ArcGIS.Client.Toolkit.DataSources.WmtsLayer();

            //lyr.ServiceMode = ESRI.ArcGIS.Client.Toolkit.DataSources.WmtsLayer.WmtsServiceMode.KVP;
            lyr.Url      = url;                                          // http://v2.suite.opengeo.org/geoserver/gwc/service/wmts?service=WMTS&request=GetCapabilities&version=1.0.0
            lyr.ProxyUrl = proxy;
            lyr.Layer    = string.IsNullOrEmpty(sublyr) ? null : sublyr; // "world:cities";
            lyr.Opacity  = 1;
            lyr.ID       = VExtClass.computeSHA1Hash(string.Format("{0}-{1}", url, sublyr));

            lyr.Initialized += (osender, eargs) => {
                log(string.Format("userGiveWMTSLayerParams.Initialized, turn on all sublayers for {0}-{1}", lyrname, lyr.ID));
            };
            lyr.Initialize();

            MapApplication.SetLayerName(lyr, lyrname);
            ESRI.ArcGIS.Client.Extensibility.LayerProperties.SetIsVisibleInMapContents(lyr, true);
            MapApplication.Current.Map.Layers.Add(lyr);
            log(string.Format("userGiveWMTSLayerParams, done for url '{0}', proxy '{1}', name '{2}'", url, proxy, lyrname));
        }         // public void userGiveWMTSLayerParams(string url, string lyrname, string proxy, string sublyr)
Esempio n. 12
0
        }         // public void userGiveCSVLayerParams(string url, string lyrname, string proxy)

        /// <summary>
        /// Call from form, add to map graphicslayer from json
        /// </summary>
        /// <param name="url"></param>
        /// <param name="lyrname"></param>
        /// <param name="proxy"></param>
        public void userGiveJSONLayerParams(string url, string lyrname, string proxy)
        {
            log(string.Format("userGiveJSONLayerParams, name '{2}', url '{0}', proxy '{1}'", url, proxy, lyrname));
            MapApplication.Current.HideWindow(jsonParamsForm);

            var requrl = string.IsNullOrEmpty(proxy) ? url : string.Format("{0}?{1}", proxy, url);

            // get json text
            WebClient wc  = new WebClient();
            Uri       uri = new Uri(requrl, UriKind.RelativeOrAbsolute);

            wc.OpenReadCompleted += (sender, args) => {
                if (args.Error != null)
                {
                    log(String.Format("userGiveJSONLayerParams wc_OpenReadCompleted, error in reading answer, msg [{0}], trace [{1}]",
                                      args.Error.Message, args.Error.StackTrace));
                }
                else
                {
                    try {
                        StreamReader reader = new StreamReader(args.Result);
                        string       text   = reader.ReadToEnd();
                        log(string.Format("userGiveJSONLayerParams wc_OpenReadCompleted, resp '{0}'", text));

                        // got layer content, make layer
                        var featureSet    = FeatureSet.FromJson(text);
                        var graphicsLayer = new GraphicsLayer()
                        {
                            Graphics = new GraphicCollection(featureSet)
                        };
                        // set layer params
                        graphicsLayer.Opacity      = 1;
                        graphicsLayer.ID           = VExtClass.computeSHA1Hash(string.Format("{0}", text));
                        graphicsLayer.Initialized += (osender, eargs) => {
                            log(string.Format("userGiveJSONLayerParams.Initialized, {0}-{1}", lyrname, graphicsLayer.ID));
                        };

                        // projection
                        var MyMap    = MapApplication.Current.Map;
                        var mercator = new ESRI.ArcGIS.Client.Projection.WebMercator();
                        if (!featureSet.SpatialReference.Equals(MyMap.SpatialReference))
                        {
                            if (MyMap.SpatialReference.Equals(new SpatialReference(102100)) &&
                                featureSet.SpatialReference.Equals(new SpatialReference(4326)))
                            {
                                foreach (Graphic g in graphicsLayer.Graphics)
                                {
                                    g.Geometry = mercator.FromGeographic(g.Geometry);
                                }
                            }

                            else if (MyMap.SpatialReference.Equals(new SpatialReference(4326)) &&
                                     featureSet.SpatialReference.Equals(new SpatialReference(102100)))
                            {
                                foreach (Graphic g in graphicsLayer.Graphics)
                                {
                                    g.Geometry = mercator.ToGeographic(g.Geometry);
                                }
                            }

                            else
                            {
                                var geometryService = new GeometryService(
                                    "http://tasks.arcgisonline.com/ArcGIS/rest/services/Geometry/GeometryServer");

                                geometryService.ProjectCompleted += (s, a) => {
                                    for (int i = 0; i < a.Results.Count; i++)
                                    {
                                        graphicsLayer.Graphics[i].Geometry = a.Results[i].Geometry;
                                    }
                                };

                                geometryService.Failed += (s, a) => {
                                    MessageBox.Show("Ошибка проецирования: " + a.Error.Message);
                                };

                                geometryService.ProjectAsync(graphicsLayer.Graphics, MyMap.SpatialReference);
                            }
                        }                         // if map.SR != featureset.SR

                        // add layer to map
                        graphicsLayer.Initialize();
                        MapApplication.SetLayerName(graphicsLayer, lyrname);
                        ESRI.ArcGIS.Client.Extensibility.LayerProperties.SetIsVisibleInMapContents(graphicsLayer, true);
                        MapApplication.Current.Map.Layers.Add(graphicsLayer);
                    }                     // got json text
                    catch (Exception ex) {
                        log(String.Format("userGiveJSONLayerParams wc_OpenReadCompleted, make layer failed {0}, {1}", ex.Message, ex.StackTrace));
                    }
                }
            };             // wc.OpenReadCompleted
            wc.OpenReadAsync(uri);

            log(string.Format("userGiveJSONLayerParams, done for name '{2}', url '{0}', proxy '{1}'", url, proxy, lyrname));
        }         // public void userGiveJSONLayerParams(string url, string lyrname, string proxy)
        /// <summary>
        /// Creates the permanent layer from the results of the Query
        /// </summary>
        /// <returns>Permanent <see cref="ESRI.ArcGIS.Client.FeatureLayer"/></returns>
        /// <remarks>The permanent layer uses the default renderer of the layer.
        /// The permanent layer is visible in the Map Contents panel.</remarks>
        private FeatureLayer CreatePermanentLayer()
        {
            // Check that the results layer is not null and use the results layer to create the permanent layer
            if (resultsLayer != null)
            {
                permanentLayer = resultsLayer;

                // Create a layer ID for displaying the layer in the map contents and attribute table
                string permanentLayerID = string.Format(Strings.RelatedTo, permanentLayer.LayerInfo.Name, PopupInfo.PopupItem.Title);

                // If there is more than one layer with the same name, add a number to the end of the name
                int layerCountSuffix = 0;

                string layerName;
                // Verify the next number in the sequence hasn't been used. If layers are renamed after the name is generated, a scenario may occur where
                // the last number used in the name is actually greater than the number of existing layers with the same name. We don't want a number to
                // repeat, so we check the last number used.
                foreach (Layer layer in map.Layers)
                {
                    layerName = MapApplication.GetLayerName(layer);
                    if (layerName != null && layerName.StartsWith(permanentLayerID))
                    {
                        if (layerName.EndsWith(")"))
                        {
                            // Split the layer name at the end to get the last number used (number contained within the parentheses)
                            string[] splitLayerName     = layerName.Split('(');
                            int      lastNumberAppended = Convert.ToInt32(splitLayerName.Last <string>().TrimEnd(')'));
                            // If the last number used is greater than the count of number of existing layers with the same name,
                            // set the count to the last number used.
                            if (lastNumberAppended > layerCountSuffix)
                            {
                                layerCountSuffix = lastNumberAppended;
                            }
                        }
                        else // Found a layer with the same name, but no (#) suffix.  This is the first layer added with this name.
                        {
                            // Only set the suffix based on this layer if the suffix has not yet been set (i.e. is still zero)
                            if (layerCountSuffix == 0)
                            {
                                layerCountSuffix = 1;
                            }
                        }
                    }
                }

                if (layerCountSuffix != 0)
                {
                    permanentLayerID += string.Format(" ({0})", layerCountSuffix + 1);
                }


                MapApplication.SetLayerName(permanentLayer, permanentLayerID);

                // Create a unique ID for the layer.
                permanentLayer.ID = Guid.NewGuid().ToString();

                // If the results layer is a table, don't show it in the map contents.
                if (resultsLayer.LayerInfo.Type == "Table")
                {
                    LayerProperties.SetIsVisibleInMapContents(permanentLayer, false);
                }
                else
                {
                    LayerProperties.SetIsVisibleInMapContents(permanentLayer, true);
                }

                // Set the layer renderer to the renderer of the original layer
                permanentLayer.Renderer = resultsLayer.LayerInfo.Renderer;
            }

            return(permanentLayer);
        }
        /// <summary>
        /// Create the temporary layer from the results of the Query
        /// </summary>
        /// <returns>Temporary <see cref="ESRI.ArcGIS.Client.FeatureLayer"/></returns>
        /// <remarks>Uses "temporary" symbols to render the points, lines, or polygons. The temporary
        /// layer is not displayed in the Map Contents panel, but the attribute grid opens to show the feature attributes.</remarks>
        private FeatureLayer CreateTempLayer()
        {
            // Check that the results layer is not null and use the results layer to create the temporary layer
            if (resultsLayer != null)
            {
                temporaryLayer = resultsLayer;

                // ControlTemplate to create ellipse for temporary point symbol
                var template = (ControlTemplate)System.Windows.Markup.XamlReader.Load("<ControlTemplate " +
                                                                                      "xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" " +
                                                                                      "xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\">" +
                                                                                      "<Grid RenderTransformOrigin=\"{Binding Symbol.RenderTransformPoint}\">" +
                                                                                      "<Ellipse " +
                                                                                      "Fill=\"#99FFFFFF\" " +
                                                                                      "Width=\"21\" " +
                                                                                      "Height=\"21\" " +
                                                                                      "Stroke=\"Red\" " +
                                                                                      "StrokeThickness=\"2\">" +
                                                                                      "</Ellipse>" +
                                                                                      "<Ellipse Fill=\"#99FFFFFF\" " +
                                                                                      "Width=\"3\" " +
                                                                                      "Height=\"3\" " +
                                                                                      "Stroke=\"Red\" " +
                                                                                      "StrokeThickness=\"2\">" +
                                                                                      "</Ellipse>" +
                                                                                      "</Grid> " +
                                                                                      "</ControlTemplate>");

                Symbol test = new SimpleMarkerSymbol();

                // Set the renderers to a "temporary" look for the temp Layer
                if (temporaryLayer.LayerInfo.GeometryType == GeometryType.Point || temporaryLayer.LayerInfo.GeometryType == GeometryType.MultiPoint)
                {
                    temporaryLayer.Renderer = new SimpleRenderer()
                    {
                        Symbol = new MarkerSymbol()
                        {
                            ControlTemplate = template as ControlTemplate, OffsetX = 10, OffsetY = 10
                        }
                    }
                }
                ;
                else if (temporaryLayer.LayerInfo.GeometryType == GeometryType.Polyline)
                {
                    temporaryLayer.Renderer = new SimpleRenderer()
                    {
                        Symbol = new SimpleLineSymbol()
                        {
                            Color = new SolidColorBrush(Color.FromArgb(255, 255, 0, 0)),
                            Width = 3
                        }
                    }
                }
                ;
                else if (temporaryLayer.LayerInfo.GeometryType == GeometryType.Polygon)
                {
                    temporaryLayer.Renderer = new SimpleRenderer()
                    {
                        Symbol = new SimpleFillSymbol()
                        {
                            Fill            = new SolidColorBrush(Color.FromArgb(80, 255, 255, 255)),
                            BorderBrush     = new SolidColorBrush(Color.FromArgb(255, 255, 0, 0)),
                            BorderThickness = 3
                        }
                    }
                }
                ;

                // Specify a name to set the ID property on the Layer. This name is associated with the layer but does not display in the map contents panel
                string tempLayerID = string.Format(Strings.RelatedTo, temporaryLayer.LayerInfo.Name, PopupInfo.PopupItem.Title);

                MapApplication.SetLayerName(temporaryLayer, tempLayerID);

                LayerProperties.SetIsVisibleInMapContents(temporaryLayer, false);
            }

            return(temporaryLayer);
        }
        /// <summary>
        /// Toggles the query UI on or off
        /// </summary>
        public void Execute(object parameter)
        {
            ToolExecuting = true;

            // Updates tool DataContext with savedConfiguration.
            var toolViewModel = toolView.DataContext as QueryViewModel;

            if (toolViewModel == null)
            {
                toolViewModel        = savedConfiguration != null ? new QueryViewModel(savedConfiguration) : new QueryViewModel();
                toolView.DataContext = toolViewModel;
            }
            else if (savedConfiguration != null)
            {
                toolViewModel.ApplyChanges(savedConfiguration);
            }

            // Sets map and proxy url based on application settings.
            if (MapApplication.Current != null)
            {
                toolViewModel.Map = MapApplication.Current.Map;
                if (MapApplication.Current.Urls != null)
                {
                    toolViewModel.ProxyUrl = MapApplication.Current.Urls.ProxyUrl;
                }
            }

            // Updates default/selection on each query expression.
            toolViewModel.ResetExpressions();

            // Sets the result layer name.
            toolViewModel.SetLayerNameAction = (layer, title) =>
            {
                if (layer != null && !string.IsNullOrEmpty(title))
                {
                    var    index     = 1;
                    string layerName = title;
                    if (MapApplication.Current != null && MapApplication.Current.Map != null && MapApplication.Current.Map.Layers != null)
                    {
                        LayerCollection layers = MapApplication.Current.Map.Layers;
                        while (layers.Any(l => MapApplication.GetLayerName(l) == layerName))
                        {
                            index++;
                            layerName = string.Format("{0} ({1})", title, index);
                        }
                    }

                    MapApplication.SetLayerName(layer, layerName);
                }
            };

            // Adds result layer to map.
            toolViewModel.AddLayerAction = (layer) =>
            {
                if (layer != null)
                {
                    if (MapApplication.Current.Map != null && MapApplication.Current.Map.Layers != null)
                    {
                        if (!MapApplication.Current.Map.Layers.Contains(layer))
                        {
                            MapApplication.Current.Map.Layers.Add(layer);
                        }
                    }
                }
            };

            // Removes result layer from map.
            toolViewModel.RemoveLayerAction = (layer) =>
            {
                if (layer != null)
                {
                    if (MapApplication.Current.Map != null && MapApplication.Current.Map.Layers != null)
                    {
                        if (MapApplication.Current.Map.Layers.Contains(layer))
                        {
                            MapApplication.Current.Map.Layers.Remove(layer);
                        }
                    }
                }
            };

            // Updates layer selection on map after query is executed.
            toolViewModel.SelectLayerAction = (layer) =>
            {
                if (layer != null)
                {
                    MapApplication.Current.SelectedLayer = layer;
                }
            };

            // Zooms to result layer.
            toolViewModel.ZoomToExtentAction = (geometry) =>
            {
                if (geometry != null)
                {
                    var env = geometry.Extent;
                    if (env.Width > 0 || env.Height > 0)
                    {
                        env = new Envelope(env.XMin - env.Width * EXPAND_EXTENT_RATIO, env.YMin - env.Height * EXPAND_EXTENT_RATIO,
                                           env.XMax + env.Width * EXPAND_EXTENT_RATIO, env.YMax + env.Height * EXPAND_EXTENT_RATIO);
                        if (MapApplication.Current.Map != null)
                        {
                            MapApplication.Current.Map.ZoomTo(env);
                        }
                    }
                    else
                    {
                        if (MapApplication.Current.Map != null)
                        {
                            MapApplication.Current.Map.PanTo(env);
                        }
                    }
                }
            };

            // Updates visibility of data grid after query is expecuted.
            toolViewModel.UpdateDataGridVisibility = (visibility) =>
            {
                UpdateFeatureDataGridVisibility(visibility);
            };

            // Displays QueryToolView.
            MapApplication.Current.ShowWindow(toolViewModel.QueryTitle, toolView, false,
                                              null,
                                              (s, e) =>
            {
                ToolExecuting = false;
                // Clears map of query results when done.
                toolViewModel.ClearResults();

                foreach (ExpressionViewModel exp in toolViewModel.QueryExpressions)
                {
                    exp.ClearValidationExceptions();
                }
            },
                                              WindowType.Floating);

            // Executes query on click when there are no visible expression.
            if (!toolViewModel.HasVisibleExpression)
            {
                if (toolViewModel.Execute.CanExecute(null))
                {
                    toolViewModel.Execute.Execute(null);
                }
            }
        }
        } // private void resultsLayer_Initialized(object sender, EventArgs e)

        /// <summary>
        /// Get related records ID's from query result, add filtered by ID's layer to map
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void doResultsLayer_Initialized(object sender, EventArgs e)
        {
            // Get the FeatureLayer's OID field off the LayerInfo
            string oidField      = resultsLayer.LayerInfo.ObjectIdField;
            var    reslyr        = new VUtils.ArcGIS.SLViewer.VLayer(resultsLayer);
            string oidFieldAlias = reslyr.getFieldAlias(oidField);

            log(string.Format(
                    "doResultsLayer_Initialized, resultsLayer.oidfield='{0}', alias='{1}'",
                    oidField, oidFieldAlias));
            if (oidFieldAlias != "")
            {
                oidField = oidFieldAlias;
            }

            // Create a List to hold the ObjectIds
            List <int>            list = new List <int>();
            IEnumerable <Graphic> RelatedRecords;

            //Go through the RelatedRecordsGroup and add the Graphic to the IEnumerable<Graphic>
            foreach (var records in queryResult.RelatedRecordsGroup)
            {
                RelatedRecords = records.Value;
                foreach (Graphic graphic in RelatedRecords)
                {
                    list.Add((int)graphic.Attributes[oidField]);
                }
            }
            log(string.Format("doResultsLayer_Initialized, relatedRecords.oidList.Count='{0}'", list.Count));
            if (list.Count <= 0)
            {
                throw new Exception("Haven't related records for that object");
            }

            int[] objectIDs = list.ToArray();
            resultsLayer.ObjectIDs = objectIDs;
            log(string.Format("doResultsLayer_Initialized, ID's set"));

            // Specify renderers for Point, Polyline, and Polygon features if the related features have geometry.
            if (resultsLayer.LayerInfo.GeometryType == GeometryType.Point)
            {
                log(string.Format("doResultsLayer_Initialized, MapPoint"));
                resultsLayer.Renderer = new SimpleRenderer()
                {
                    Symbol = new SimpleMarkerSymbol()
                    {
                        Style = SimpleMarkerSymbol.SimpleMarkerStyle.Circle
                    }
                };
            }
            else if (resultsLayer.LayerInfo.GeometryType == GeometryType.Polyline)
            {
                log(string.Format("doResultsLayer_Initialized, Polyline"));
                resultsLayer.Renderer = new SimpleRenderer()
                {
                    Symbol = new SimpleLineSymbol()
                    {
                        Color = new SolidColorBrush(Colors.Red),
                        Width = 2
                    }
                };
            }
            else if (resultsLayer.LayerInfo.GeometryType == GeometryType.Polygon)
            {
                log(string.Format("doResultsLayer_Initialized, Polygon"));
                resultsLayer.Renderer = new SimpleRenderer()
                {
                    Symbol = new SimpleFillSymbol()
                    {
                        Fill        = new SolidColorBrush(Color.FromArgb(125, 255, 0, 0)),
                        BorderBrush = new SolidColorBrush(Colors.Red)
                    }
                };
            }
            log(string.Format("doResultsLayer_Initialized, resultsLayer.Geometry is '{0}'", resultsLayer.LayerInfo.GeometryType));

            // Specify a layer name so that it displays on the Attribute table,
            // but do not display the layer in the Map Contents.
            string mapLayerName = resultsLayer.LayerInfo.Name +
                                  ", related records '" +
                                  relationInfo.name +
                                  "' for OID " +
                                  inputFeature.Attributes[objectID].ToString();

            MapApplication.SetLayerName(resultsLayer, mapLayerName);
            LayerProperties.SetIsVisibleInMapContents(resultsLayer, true);
            log(string.Format("doResultsLayer_Initialized, SetLayerName '{0}'", mapLayerName));

            // Add the layer to the map and set it as the selected layer so the attributes appear in the Attribute table.
            resultsLayer.UpdateCompleted += resultsLayer_UpdateCompleted;
            MapApplication.Current.Map.Layers.Add(resultsLayer);
        } // private void doResultsLayer_Initialized(object sender, EventArgs e)
Esempio n. 17
0
        }         // private void resultsLayer_Initialized(object sender, EventArgs e)

        /// <summary>
        /// Get related records ID's from query result, add filtered by ID's layer to map
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void doResultsLayer_Initialized(object sender, EventArgs e)
        {
            // Get the FeatureLayer's OID field off the LayerInfo
            string oidField      = resultsLayer.getFL().LayerInfo.ObjectIdField;
            var    reslyr        = resultsLayer;
            string oidFieldAlias = reslyr.getFieldAlias(oidField);

            log(string.Format("doResultsLayer_Initialized, resultsLayer.oidfield='{0}', alias='{1}'", oidField, oidFieldAlias));
            oidField = "";

            // Create a List to hold the ObjectIds
            List <int>            list = new List <int>();
            IEnumerable <Graphic> RelatedRecords;

            //Go through the RelatedRecordsGroup and add the Graphic to the IEnumerable<Graphic>
            foreach (var records in queryResult.RelatedRecordsGroup)
            {
                RelatedRecords = records.Value;
                foreach (Graphic graphic in RelatedRecords)
                {
                    if (oidField == "")
                    {
                        var oid = resultsLayer.getOID(graphic);
                        oidField = resultsLayer.getOIDFieldnameOrAlias();
                        log(string.Format("doResultsLayer_Initialized, real resultsLayer.oidfield='{0}', alias='{1}'", oidField, oidFieldAlias));
                    }
                    list.Add((int)graphic.Attributes[oidField]);
                }
            }
            log(string.Format("doResultsLayer_Initialized, relatedRecords.oidList.Count='{0}'", list.Count));
            if (list.Count <= 0)
            {
                throw new Exception("Для указанного обьекта связанные записи отсутствуют");
            }

            resultsLayer.getFL().UpdateCompleted += resultsLayer_UpdateCompleted;
            int[] objectIDs = list.ToArray();
            resultsLayer.getFL().ObjectIDs = objectIDs;
            log(string.Format("doResultsLayer_Initialized, ID's set"));

            // Specify renderers for Point, Polyline, and Polygon features if the related features have geometry.
            if (resultsLayer.getFL().LayerInfo.GeometryType == GeometryType.Point)
            {
                log(string.Format("doResultsLayer_Initialized, MapPoint"));
                resultsLayer.getFL().Renderer = new SimpleRenderer()
                {
                    Symbol = new SimpleMarkerSymbol()
                    {
                        Style = SimpleMarkerSymbol.SimpleMarkerStyle.Circle
                    }
                };
            }
            else if (resultsLayer.getFL().LayerInfo.GeometryType == GeometryType.Polyline)
            {
                log(string.Format("doResultsLayer_Initialized, Polyline"));
                resultsLayer.getFL().Renderer = new SimpleRenderer()
                {
                    Symbol = new SimpleLineSymbol()
                    {
                        Color = new SolidColorBrush(Colors.Red),
                        Width = 2
                    }
                };
            }
            else if (resultsLayer.getFL().LayerInfo.GeometryType == GeometryType.Polygon)
            {
                log(string.Format("doResultsLayer_Initialized, Polygon"));
                resultsLayer.getFL().Renderer = new SimpleRenderer()
                {
                    Symbol = new SimpleFillSymbol()
                    {
                        Fill        = new SolidColorBrush(Color.FromArgb(125, 255, 0, 0)),
                        BorderBrush = new SolidColorBrush(Colors.Red)
                    }
                };
            }
            log(string.Format("doResultsLayer_Initialized, resultsLayer.Geometry is '{0}'", resultsLayer.getFL().LayerInfo.GeometryType));

            // Specify a layer name so that it displays on the Attribute table, but do not display the layer in the Map Contents.
            // old style
            string mapLayerName = resultsLayer.getFL().LayerInfo.Name + ", related records '" + relationInfo.name +
                                  "' for OID " + relatesLayer.getOID(inputFeature).ToString();

            try {             // Parilov style
                mapLayerName = string.Format("{0}, {1}", resultsLayer.getFL().LayerInfo.Name,
                                             inputFeature.Attributes[relatesLayer.getFL().LayerInfo.DisplayField]);
            }
            catch (Exception ex) {
                log(string.Format("doResultsLayer_Initialized, Parilov style layer name failed. SetLayerName '{0}'", mapLayerName));
            }
            MapApplication.SetLayerName(resultsLayer.lyr, mapLayerName);
            LayerProperties.SetIsVisibleInMapContents(resultsLayer.lyr, true);
            log(string.Format("doResultsLayer_Initialized, SetLayerName '{0}'", mapLayerName));
            // Add the layer to the map and set it as the selected layer so the attributes appear in the Attribute table.
            MapApplication.Current.Map.Layers.Add(resultsLayer.lyr);
        }         // private void doResultsLayer_Initialized(object sender, EventArgs e)