private void TreeViewAddLayerNode(TreeNode parentNode, LayerCollection collection)
 {
     foreach (var lyr in collection)
     {
         TreeViewAddLayerNode(parentNode, lyr);
     }
 }
Exemplo n.º 2
0
        public void Initialize(LayerCollection layers)
        {
            List <LayerListItem> toRemove = new List <LayerListItem>();

            foreach (var source in Items.Children)
            {
                if (source is LayerListItem x && x.Widget == null)
                {
                    toRemove.Add(x);
                }
            }

            foreach (var source in toRemove)
            {
                Items.Children.Remove(source);
            }

            foreach (var layer in layers)
            {
                var item = new LayerListItem {
                    LayerName = layer.Name
                };
                item.Enabled = layer.Enabled;
                //item.LayerOpacity = layer.Opacity;
                item.Layer = layer;
                Items.Children.Add(item);
            }
        }
Exemplo n.º 3
0
        public RelevantObjectLayer(LayerCollection parentCollection, RelevantObjectsGeneratorCollection generatorCollection)
        {
            ParentCollection    = parentCollection;
            GeneratorCollection = generatorCollection;

            Objects = new RelevantObjectCollection.RelevantObjectCollection();
        }
Exemplo n.º 4
0
        /// <summary>
        /// Converts a layer hierarchy that may include group layers into a flat collection of layers.
        /// </summary>
        private static IEnumerable <Layer> FlattenLayers(this IEnumerable <Layer> layers, GroupLayer parent = null)
        {
            LayerCollection flattenedLayers = new LayerCollection();

            foreach (Layer layer in layers)
            {
                if (layer is GroupLayer && !(layer is KmlLayer))
                {
                    // Flatten group layers
                    GroupLayer groupLayer = (GroupLayer)layer;
                    foreach (Layer child in groupLayer.ChildLayers.FlattenLayers(groupLayer))
                    {
                        flattenedLayers.Add(child);
                    }
                }
                else
                {
                    // If the layer was within a group layer, account for the group layer's visibility
                    // and opacity
                    if (parent != null)
                    {
                        layer.Visible     = !parent.Visible ? false : layer.Visible;
                        layer.Opacity     = parent.Opacity * layer.Opacity;
                        layer.DisplayName = parent.DisplayName;
                    }

                    flattenedLayers.Add(layer);
                }
            }

            return(flattenedLayers);
        }
Exemplo n.º 5
0
        private async void ViewButton_Click(object sender, RoutedEventArgs e)
        {
            originPoint = null;
            //Change button to 2D or 3D when button is clicked
            ViewButton.Content = FindResource(ViewButton.Content == FindResource("3D") ? "2D" : "3D");
            if (ViewButton.Content == FindResource("2D"))
            {
                threeD = true;
                if (myScene == null)
                {
                    //Create a new scene
                    myScene         = new Scene(Basemap.CreateNationalGeographic());
                    sceneView.Scene = myScene;
                    // create an elevation source
                    var elevationSource = new ArcGISTiledElevationSource(new System.Uri(ELEVATION_IMAGE_SERVICE));
                    // create a surface and add the elevation surface
                    var sceneSurface = new Surface();
                    sceneSurface.ElevationSources.Add(elevationSource);
                    // apply the surface to the scene
                    sceneView.Scene.BaseSurface = sceneSurface;

                    //Exercise 3: Open mobie map package (.mmpk) and add its operational layers to the scene
                    var mmpk = await MobileMapPackage.OpenAsync(MMPK_PATH);

                    if (mmpk.Maps.Count >= 0)
                    {
                        myMap = mmpk.Maps[0];
                        LayerCollection layerCollection = myMap.OperationalLayers;

                        for (int i = 0; i < layerCollection.Count(); i++)
                        {
                            var thelayer = layerCollection[i];
                            myMap.OperationalLayers.Clear();
                            myScene.OperationalLayers.Add(thelayer);
                            sceneView.SetViewpoint(myMap.InitialViewpoint);
                            //Rotate the camera
                            Viewpoint viewpoint = sceneView.GetCurrentViewpoint(ViewpointType.CenterAndScale);
                            Esri.ArcGISRuntime.Geometry.MapPoint targetPoint = (MapPoint)viewpoint.TargetGeometry;
                            Camera camera = sceneView.Camera.RotateAround(targetPoint, 45.0, 65.0, 0.0);
                            await sceneView.SetViewpointCameraAsync(camera);
                        }
                        sceneView.Scene = myScene;
                        bufferAndQuerySceneGraphics.SceneProperties.SurfacePlacement = SurfacePlacement.Draped;
                        sceneView.GraphicsOverlays.Add(bufferAndQuerySceneGraphics);
                        sceneRouteGraphics.SceneProperties.SurfacePlacement = SurfacePlacement.Draped;
                        sceneView.GraphicsOverlays.Add(sceneRouteGraphics);
                    }
                }

                //Exercise 1 Once the scene has been created hide the mapView and show the sceneView
                mapView.Visibility   = Visibility.Hidden;
                sceneView.Visibility = Visibility.Visible;
            }
            else
            {
                threeD = false;
                sceneView.Visibility = Visibility.Hidden;
                mapView.Visibility   = Visibility.Visible;
            }
        }
        void webMap_GetMapCompleted(object sender, GetMapCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                MyMap.Extent = e.Map.Extent;
                int i = 0;

                LayerCollection layerCollection = new LayerCollection();
                foreach (Layer layer in e.Map.Layers)
                {
                    layer.ID = i.ToString();
                    if (layer is FeatureLayer)
                    {
                        Border         maptip = (layer as FeatureLayer).MapTip as Border;
                        ContentControl scv    = maptip.Child as ContentControl;
                        scv.Foreground = new SolidColorBrush(Colors.Black);
                        mapTipsElements.Add(layer.ID, maptip);
                    }
                    layerCollection.Add(layer);
                    i++;
                }

                e.Map.Layers.Clear();
                MyMap.Layers = layerCollection;
            }
        }
Exemplo n.º 7
0
        // Initialize the xServer base map layers
        public void InsertXMapBaseLayers(LayerCollection layers, string url, string copyrightText, Size maxRequestSize, string user, string password)
        {
            var baseLayer = new TiledLayer("Background")
            {
                TiledProvider = new XMapTiledProvider(url, XMapMode.Background)
                {
                    User = user, Password = password, ContextKey = "in case of context key"
                },
                Copyright      = copyrightText,
                Caption        = MapLocalizer.GetString(MapStringId.Background),
                IsBaseMapLayer = true,
                Icon           = ResourceHelper.LoadBitmapFromResource("Ptv.XServer.Controls.Map;component/Resources/Background.png")
            };

            var labelLayer = new UntiledLayer("Labels")
            {
                UntiledProvider = new XMapTiledProvider(url, XMapMode.Town)
                {
                    User = user, Password = password, ContextKey = "in case of context key"
                },
                Copyright      = copyrightText,
                MaxRequestSize = maxRequestSize,
                Caption        = MapLocalizer.GetString(MapStringId.Labels),
                Icon           = ResourceHelper.LoadBitmapFromResource("Ptv.XServer.Controls.Map;component/Resources/Labels.png")
            };

            layers.Add(baseLayer);
            layers.Add(labelLayer);
        }
        void ReleaseDesignerOutlets()
        {
            if (PauseButton != null)
            {
                PauseButton.Dispose();
                PauseButton = null;
            }

            if (PlayButton != null)
            {
                PlayButton.Dispose();
                PlayButton = null;
            }

            if (StopButton != null)
            {
                StopButton.Dispose();
                StopButton = null;
            }

            if (TempoField != null)
            {
                TempoField.Dispose();
                TempoField = null;
            }

            if (LayerCollection != null)
            {
                LayerCollection.Dispose();
                LayerCollection = null;
            }
        }
        private void OnButton1Clicked(object sender, EventArgs e)
        {
            try
            {
                // Define the Uri to the WMTS service (NOTE: iOS applications require the use of Uri's to be https:// and not http://)
                var myUri = new Uri("https://sampleserver6.arcgisonline.com/arcgis/rest/services/WorldTimeZones/MapServer/WMTS");

                // Create a new instance of a WMTS layer using a Uri and provide an Id value
                WmtsLayer myWmtsLayer = new WmtsLayer(myUri, "WorldTimeZones");

                // Create a new map
                Map myMap = new Map();

                // Get the basemap from the map
                Basemap myBasemap = myMap.Basemap;

                // Get the layer collection for the base layers
                LayerCollection myLayerCollection = myBasemap.BaseLayers;

                // Add the WMTS layer to the layer collection of the map
                myLayerCollection.Add(myWmtsLayer);

                // Assign the map to the MapView
                _myMapView.Map = myMap;
            }
            catch (Exception ex)
            {
                // Report error
                UIAlertController alert = UIAlertController.Create("Error", ex.Message, UIAlertControllerStyle.Alert);
                alert.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null));
                PresentViewController(alert, true, null);
            }
        }
Exemplo n.º 10
0
        /// <inheritdoc/>
        protected override void Initialize()
        {
            base.Initialize();

            if (!IsInDesignMode)
            {
                layers = Map.Layers;
                layers.CollectionChanged         += Layers_CollectionChanged;
                layers.LayerSelectabilityChanged += layers_LayerSelectabilityChanged;
                layers.LayerVisibilityChanged    += layers_LayerVisibilityChanged;

                UpdateLayerList();

                Tools.Reordering.GridReordering.apply(LayersStack, 1, null);

                Tools.Reordering.GridReordering.AddRowMovedHandler(LayersStack, (s, e) => layers.Move(layerIndices[e.SourceRow], layerIndices[e.TargetRow]));
                Tools.Reordering.GridReordering.AddAllowMoveRowHandler(LayersStack, (s, e) =>
                {
                    // only allow to move within the same primary category
                    int targetRow = Math.Min(layers.Count - 1, Math.Max(e.TargetRow, 0));

                    var sourceLayer = layers[layerIndices[e.SourceRow]];
                    var targetLayer = layers[layerIndices[targetRow]];

                    e.IsAllowed = sourceLayer != null && targetLayer != null &&
                                  sourceLayer.CanvasCategories != null && sourceLayer.CanvasCategories.Length != 0 &&
                                  targetLayer.CanvasCategories != null && targetLayer.CanvasCategories.Length != 0 &&
                                  sourceLayer.CanvasCategories[0] == targetLayer.CanvasCategories[0];
                });
            }

            // Adds this gadget to the gadget collection of the map as a layers gadget.
            Map.Gadgets.Add(GadgetType.Layers, this);
        }
Exemplo n.º 11
0
        public void InsertXMapBaseLayers(LayerCollection layers, XMapMetaInfo meta, string profile)
        {
            var baseLayer = new TiledLayer("Background")
            {
                TiledProvider = new ExtendedXMapTiledProvider(meta.Url, meta.User, meta.Password)
                {
                    ContextKey = "in case of context key",
                    CustomProfile = profile + "-bg",
                },
                Copyright = meta.CopyrightText,
                Caption = MapLocalizer.GetString(MapStringId.Background),
                IsBaseMapLayer = true,
                Icon = ResourceHelper.LoadBitmapFromResource("Ptv.XServer.Controls.Map;component/Resources/Background.png"),
            };

            var labelLayer = new UntiledLayer("Labels")
            {
                UntiledProvider = new XMapTiledProvider(
                    meta.Url, XMapMode.Town)
                {
                    User = meta.User, Password = meta.Password, ContextKey = "in case of context key",
                    CustomProfile = profile + "-fg",
                },
                Copyright = meta.CopyrightText,
                MaxRequestSize = meta.MaxRequestSize,
                Caption = MapLocalizer.GetString(MapStringId.Labels),
                Icon = ResourceHelper.LoadBitmapFromResource("Ptv.XServer.Controls.Map;component/Resources/Labels.png"),
            };

            layers.Add(baseLayer);
            layers.Add(labelLayer);
        }
Exemplo n.º 12
0
        private static void ExtendBoxForCollection(LayerCollection layersCollection, ref Envelope bbox)
        {
            foreach (var l in layersCollection)
            {
                //Tries to get bb. Fails on some specific shapes and Mercator projects (World.shp)
                Envelope bb;
                try
                {
                    bb = l.Envelope;
                }
                catch (Exception)
                {
                    bb = new Envelope(new Coordinate(-20037508.342789, -20037508.342789), new Coordinate(20037508.342789, 20037508.342789));
                }

                if (bbox == null)
                {
                    bbox = bb;
                }
                else
                {
                    //FB: bb can be null on empty layers (e.g. temporary working layers with no data objects)
                    if (bb != null)
                    {
                        bbox.ExpandToInclude(bb);
                    }
                }
            }
        }
        public static bool HasNonBasemapLayerBeforeAfterIndex(Layer layer, LayerCollection collection, bool before)
        {
            if (layer == null || collection == null)
                return false;

            int index = collection.IndexOf(layer);
            if (index < 0) //layer not found
                return false;

            if (before)
            {
                for(int i = index - 1; i >= 0; i--)
                {
                    if (!(bool)collection[i].GetValue(ESRI.ArcGIS.Client.WebMap.Document.IsBaseMapProperty))
                        return true;
                }
            }
            else
            {
                if (index < collection.Count - 1)
                {
                    for (int i = index + 1; i < collection.Count; i++)
                    {
                        if (!(bool)collection[i].GetValue(ESRI.ArcGIS.Client.WebMap.Document.IsBaseMapProperty))
                            return true;
                    }
                }

            }
            return false;
        }
Exemplo n.º 14
0
        /// <summary>
        /// Finalizes the network internal structure and locks it against further changes.
        /// </summary>
        /// <param name="outputActivation">Activation function of the output layer's neurons</param>
        public void FinalizeStructure(IActivationFunction outputActivation)
        {
            if (Finalized)
            {
                throw new InvalidOperationException($"Network structure has been already finalized.");
            }
            //Add output layer
            LayerCollection.Add(new Layer(NumOfOutputValues, outputActivation));
            //Finalize layers
            int numOfInputNodes     = NumOfInputValues;
            int neuronsFlatStartIdx = 0;
            int weightsFlatStartIdx = 0;

            _isAllowedNguyenWidrowRandomization = true;
            foreach (Layer layer in LayerCollection)
            {
                layer.FinalizeStructure(numOfInputNodes, neuronsFlatStartIdx, weightsFlatStartIdx);
                neuronsFlatStartIdx += layer.NumOfLayerNeurons;
                weightsFlatStartIdx += layer.NumOfLayerNeurons * layer.NumOfInputNodes + layer.NumOfLayerNeurons;
                numOfInputNodes      = layer.NumOfLayerNeurons;
                if (layer.Activation.GetType() != typeof(Elliot) &&
                    layer.Activation.GetType() != typeof(TanH)
                    )
                {
                    _isAllowedNguyenWidrowRandomization = false;
                }
            }
            if (LayerCollection.Count < 2)
            {
                _isAllowedNguyenWidrowRandomization = false;
            }
            NumOfNeurons = neuronsFlatStartIdx;
            _flatWeights = new double[weightsFlatStartIdx];
            return;
        }
Exemplo n.º 15
0
        /// <summary>
        /// Initializes a new map
        /// </summary>
        /// <param name="size">Size of map in pixels</param>
        public Map(Size size)
        {
            _mapViewportGuard = new MapViewPortGuard(size, 0d, double.MaxValue);

            if (LicenseManager.UsageMode != LicenseUsageMode.Designtime)
            {
                Factory = GeoAPI.GeometryServiceProvider.Instance.CreateGeometryFactory(_srid);
            }
            _layers = new LayerCollection();
            _layersPerGroup.Add(_layers, new List <ILayer>());
            _backgroundLayers = new LayerCollection();
            _layersPerGroup.Add(_backgroundLayers, new List <ILayer>());
            BackColor             = Color.Transparent;
            _mapTransform         = new Matrix();
            _mapTransformInverted = new Matrix();
            _center = new Point(0, 0);
            _zoom   = 1;

            WireEvents();

            if (_logger.IsDebugEnabled)
            {
                _logger.DebugFormat("Map initialized with size {0},{1}", size.Width, size.Height);
            }
        }
Exemplo n.º 16
0
        public void MoveAfterIndex()
        {
            // arrange
            var layerCollection = new LayerCollection();
            var layer1          = new MemoryLayer()
            {
                Name = "Layer1"
            };
            var layer2 = new MemoryLayer()
            {
                Name = "Layer2"
            };
            var layer3 = new MemoryLayer()
            {
                Name = "Layer3"
            };

            layerCollection.Add(layer1);
            layerCollection.Add(layer2);
            layerCollection.Add(layer3);

            // act
            layerCollection.Move(3, layer1);

            // assert
            var list = layerCollection.ToList();

            Assert.AreEqual(3, list.Count());
            Assert.NotNull(list[0]);
            Assert.AreEqual("Layer2", list[0].Name);
            Assert.NotNull(list[1]);
            Assert.AreEqual("Layer3", list[1].Name);
            Assert.NotNull(list[2]);
            Assert.AreEqual("Layer1", list[2].Name);
        }
Exemplo n.º 17
0
        /// <summary>
        /// Initializes an instance with the specified size.
        /// </summary>
        /// <param name="grid">The grid.</param>
        /// <param name="settings">The settings.</param>
        /// <param name="layerCollection">The older layer collection.</param>
        public PictureSavingPreferencesWindow(Grid grid, Settings settings, LayerCollection layerCollection)
        {
            InitializeComponent();

            (_settings, _grid, _oldCollection) = (settings, grid, layerCollection);
            _textBoxSize.Text = _settings.SavingPictureSize.ToString();
        }
Exemplo n.º 18
0
        public void InsertXMapBaseLayers(LayerCollection layers, XMapMetaInfo meta, string profile)
        {
            var baseLayer = new TiledLayer("Background")
            {
                TiledProvider = new ExtendedXMapTiledProvider(meta.Url, meta.User, meta.Password)
                {
                    ContextKey    = "in case of context key",
                    CustomProfile = profile + "-bg"
                },
                Copyright      = meta.CopyrightText,
                Caption        = MapLocalizer.GetString(MapStringId.Background),
                IsBaseMapLayer = true,
                Icon           = ResourceHelper.LoadBitmapFromResource("Ptv.XServer.Controls.Map;component/Resources/Background.png")
            };

            var labelLayer = new UntiledLayer("Labels")
            {
                UntiledProvider = new XMapTiledProvider(
                    meta.Url, XMapMode.Town)
                {
                    User          = meta.User, Password = meta.Password, ContextKey = "in case of context key",
                    CustomProfile = profile + "-fg"
                },
                Copyright      = meta.CopyrightText,
                MaxRequestSize = meta.MaxRequestSize,
                Caption        = MapLocalizer.GetString(MapStringId.Labels),
                Icon           = ResourceHelper.LoadBitmapFromResource("Ptv.XServer.Controls.Map;component/Resources/Labels.png")
            };

            layers.Add(baseLayer);
            layers.Add(labelLayer);
        }
        private void LoadWebMapButton_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            if (!string.IsNullOrEmpty(WebMapTextBox.Text))
            {
                Document webMap = new Document();
                webMap.GetMapCompleted += (s, a) =>
                    {
                        if (a.Error != null)
                            MessageBox.Show(string.Format("Unable to load webmap. {0}", a.Error.Message));
                        else
                        {
                            MyMap.Extent = a.Map.Extent;

                            LayerCollection layerCollection = new LayerCollection();
                            foreach (Layer layer in a.Map.Layers)
                                layerCollection.Add(layer);

                            a.Map.Layers.Clear();
                            MyMap.Layers = layerCollection;
                            WebMapPropertiesTextBox.DataContext = a.ItemInfo;
                        }
                    };

                webMap.GetMapAsync(WebMapTextBox.Text);
            }
        }
Exemplo n.º 20
0
        private void OnCloneComplete()
        {
            if (_shutter != null)
            {
                base.Graphics.Remove(_shutter);
                _shutter.Dispose();
                _shutter = null;
            }

            if (_layers != null)
            {
                base.Graphics.Remove(_layers);
                _layers.Dispose();
                _layers = null;
            }

            _shutter = (ShutterCollection)base.Graphics.FirstOrDefault(IsType <ShutterCollection>);
            _layers  = (LayerCollection)base.Graphics.FirstOrDefault(IsType <LayerCollection>);

            FillOverlayCollections(_shutter);
            foreach (LayerGraphic layer in _layers)
            {
                FillOverlayCollections(layer.Graphics);
            }
        }
Exemplo n.º 21
0
        private void mapBox_GeometryDefined(IGeometry geometry)
        {
            if (showRouting)
            {
                if (!startPointChosen)
                {
                    startPointChosen = true;
                    routingPoints[0] = (NetTopologySuite.Geometries.Point)geometry;
                }
                else
                {
                    startPointChosen = false;
                    routingPoints[1] = (NetTopologySuite.Geometries.Point)geometry;

                    mapBox.Map.Layers.Add(dataManagement.createRoutingLayer(routingPoints));
                    mapBox.Refresh();
                }
            }
            else
            {
                LayerCollection geometryColl = dataManagement.GeometryFilter(mapBox.Map.Layers, geometry);

                mapBox.Map.Layers.Clear();

                mapBox.Map.Layers.AddCollection(geometryColl);
                mapBox.Refresh();
                mapBox.Invalidate();
            }
        }
Exemplo n.º 22
0
        public void InsertAfterRemoving()
        {
            // arrange
            var layerCollection = new LayerCollection();
            var layer1          = new MemoryLayer()
            {
                Name = "Layer1"
            };
            var layer2 = new MemoryLayer()
            {
                Name = "Layer2"
            };
            var layer3 = new MemoryLayer()
            {
                Name = "Layer3"
            };

            layerCollection.Add(layer1);
            layerCollection.Add(layer2);

            layerCollection.Remove(layer1);

            // act
            layerCollection.Insert(1, layer3);

            // assert
            var list = layerCollection.ToList();

            Assert.AreEqual(2, list.Count());
            Assert.NotNull(list[0]);
            Assert.AreEqual("Layer2", list[0].Name);
            Assert.NotNull(list[1]);
            Assert.AreEqual("Layer3", list[1].Name);
        }
Exemplo n.º 23
0
        public static async Task PerformNewTreeWorkflow(LayerCollection layers, Feature feature, MapPoint newFeatureGeometry)
        {
            // if the webmap used in the app is not the tree dataset map, this method will not work
            if (WebmapURL != TreeDatasetWebmapUrl)
            {
                return;
            }

            // Perform the following steps only if the trees sample dataset is present in the map
            var neighborhoodsTable = ((FeatureLayer)layers[Convert.ToInt32(NeighborhoodOperationalLayerId)])?.FeatureTable;

            if (neighborhoodsTable != null && neighborhoodsTable.GeometryType == GeometryType.Polygon &&
                feature.Attributes.ContainsKey(NeighborhoodAttribute))
            {
                // run custom app workflows to set neighborhood attribute
                feature.Attributes[NeighborhoodAttribute] = await GetNeighborhoodForAddedFeature(
                    neighborhoodsTable, newFeatureGeometry);
            }

            if (feature.Attributes.ContainsKey(AddressAttribute))
            {
                // run custom workflow to set address attribute
                feature.Attributes[AddressAttribute] = await GetAddressForAddedFeature(newFeatureGeometry);
            }
        }
Exemplo n.º 24
0
        public void CopyToAfterRemovingItem()
        {
            // arrange
            var layerCollection = new LayerCollection();
            var layer1          = new MemoryLayer();
            var layer2          = new MemoryLayer();

            layerCollection.Add(layer1);
            layerCollection.Add(layer2);

            var size  = layerCollection.Count();
            var array = new ILayer[size];

            layerCollection.Remove(layer1);

            // act
            layerCollection.CopyTo(array, 0);

            // assert
            Assert.AreEqual(2, array.Length);
            Assert.NotNull(array[0], "first element not null");
            // We have no crash but the seconds element is null.
            // This might have unpleasant consequences.
            Assert.Null(array[1], "second element IS null");
        }
Exemplo n.º 25
0
        private void Button1_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                // Define the Uri to the WMTS service
                var myUri = new Uri("http://sampleserver6.arcgisonline.com/arcgis/rest/services/WorldTimeZones/MapServer/WMTS");

                // Create a new instance of a WMTS layer using a Uri and provide an Id value
                WmtsLayer myWmtsLayer = new WmtsLayer(myUri, "WorldTimeZones");

                // Create a new map
                Map myMap = new Map();

                // Get the basemap from the map
                Basemap myBasemap = myMap.Basemap;

                // Get the layer collection for the base layers
                LayerCollection myLayerCollection = myBasemap.BaseLayers;

                // Add the WMTS layer to the layer collection of the map
                myLayerCollection.Add(myWmtsLayer);

                // Assign the map to the MapView
                MyMapView.Map = myMap;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
Exemplo n.º 26
0
        void webMap_GetMapCompleted(object sender, GetMapCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                MyMap.Extent = e.Map.Extent;
                int i = 0;

                LayerCollection layerCollection = new LayerCollection();
                foreach (Layer layer in e.Map.Layers)
                {
                    layer.ID = i.ToString();
                    layerCollection.Add(layer);
                    if (layer is GroupLayer) // the graphicslayer we are interested in is in a grouplayer
                    {
                        foreach (Layer childLayer in (layer as GroupLayer).ChildLayers)
                        {
                            if (childLayer is GraphicsLayer)
                            {
                                (childLayer as GraphicsLayer).MouseLeftButtonUp += WebMapMapNotesPopups_MouseLeftButtonUp;
                            }
                        }
                    }
                    i++;
                }

                e.Map.Layers.Clear();
                MyMap.Layers = layerCollection;
            }
        }
		private static IEnumerable<FeatureLayer> GetLayers(IEnumerable<string> ids, LayerCollection layers)
		{
			if (layers != null)
			{
				if (ids != null)
				{
					foreach (string item in ids)
					{
						FeatureLayer featureLayer = GetFeatureLayerWithID(item, layers);
						if (featureLayer != null)
							yield return featureLayer;
					}
				}
				else
				{
					foreach (Layer layer in layers)
					{
						if (layer is FeatureLayer && !string.IsNullOrEmpty(layer.ID))
						{
							yield return layer as FeatureLayer;
						}
					}
				}
				}
			}
Exemplo n.º 28
0
        private void LoadWebMapButton_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            if (!string.IsNullOrEmpty(WebMapTextBox.Text))
            {
                Document webMap = new Document();
                webMap.GetMapCompleted += (s, a) =>
                {
                    if (a.Error != null)
                    {
                        MessageBox.Show(string.Format("Unable to load webmap. {0}", a.Error.Message));
                    }
                    else
                    {
                        MyMap.Extent = a.Map.Extent;

                        LayerCollection layerCollection = new LayerCollection();
                        foreach (Layer layer in a.Map.Layers)
                        {
                            layerCollection.Add(layer);
                        }

                        a.Map.Layers.Clear();
                        MyMap.Layers = layerCollection;
                        WebMapPropertiesTextBox.DataContext = a.ItemInfo;
                    }
                };

                webMap.GetMapAsync(WebMapTextBox.Text);
            }
        }
        private async void Button1_Click(object sender, EventArgs e)
        {
            try
            {
                // Define the Uri to the WMTS service (NOTE: iOS applications require the use of Uri's to be https:// and not http://)
                var myUri = new Uri("https://sampleserver6.arcgisonline.com/arcgis/rest/services/WorldTimeZones/MapServer/WMTS");

                // Create a new instance of a WMTS layer using a Uri and provide an Id value
                WmtsLayer myWmtsLayer = new WmtsLayer(myUri, "WorldTimeZones");

                // Create a new map
                Map myMap = new Map();

                // Get the basemap from the map
                Basemap myBasemap = myMap.Basemap;

                // Get the layer collection for the base layers
                LayerCollection myLayerCollection = myBasemap.BaseLayers;

                // Add the WMTS layer to the layer collection of the map
                myLayerCollection.Add(myWmtsLayer);

                // Assign the map to the MapView
                MyMapView.Map = myMap;
            }
            catch (Exception ex)
            {
                await DisplayAlert("Sample error", ex.ToString(), "OK");
            }
        }
Exemplo n.º 30
0
        private void Delete_Layer_Click(object sender, RoutedEventArgs e)
        {
            ObservableCollection <DxfLayerExtended> layers = new ObservableCollection <DxfLayerExtended>(LayerList.SelectedItems.OfType <DxfLayerExtended>());

            int index = LayerList.SelectedIndex;

            for (int i = 0; i < layers.Count; i++)
            {
                DxfLayerExtended layer = layers[i];

                if (layer.Name != "0")
                {
                    LayerList.SelectedItems.Remove(layer);
                    LayerCollection.Remove(layer);
                }
                else
                {
                    MessageBox.Show("Cannot Delete Default Layer \"0\"", "Warning");
                }
            }

            if (LayerList.Items.Count > index)
            {
                LayerList.SelectedIndex = index;
            }
            else
            {
                LayerList.SelectedIndex = LayerList.Items.Count - 1;
            }
        }
Exemplo n.º 31
0
        private void New_Layer_Click(object sender, RoutedEventArgs e)
        {
            string name = null;
            bool   found;

            for (int i = 0; (i < LayerCollection.Count + 1) && (name == null); i++)
            {
                found = false;
                for (int j = 0; (j < LayerCollection.Count) && !found; j++)
                {
                    if (LayerCollection[j].Name == "Layer" + (i + 1))
                    {
                        found = true;
                    }
                }
                if (!found)
                {
                    name = "Layer" + (i + 1);
                }
            }
            if (name != null)
            {
                LayerCollection.Add(new DxfLayerExtended(name));
            }
        }
Exemplo n.º 32
0
 /// <summary>
 /// Initializes a new map
 /// </summary>
 public Map()
 {
     BackColor = Color.White;
     layers = new LayerCollection();
     layers.LayerAdded += LayersLayerAdded;
     layers.LayerRemoved += LayersLayerRemoved;
 }
Exemplo n.º 33
0
        public static async Task <IDictionary <Layer, IEnumerable <IdentifyFeature> > > Identify(MapViewController controller, Point tapPoint, MapPoint mapPoint, IEnumerable <Layer> layers = null, double toleranceInPixels = 5)
        {
            if (controller == null)
            {
                throw new ArgumentNullException("controller");
            }
            if (layers == null)
            {
                throw new ArgumentNullException("layers");
            }

            var identifyLayers = LayerCollection.EnumerateLeaves(layers);
            var results        = await Task.WhenAll((from l in identifyLayers where l.IsVisible select IdentifyLayer(controller, l, tapPoint, mapPoint)).Where((l => l != null)).ToArray()).ConfigureAwait(false);

            IDictionary <Layer, IEnumerable <IdentifyFeature> > taskResults = null;

            foreach (var result in results)
            {
                if (taskResults == null)
                {
                    taskResults = new Dictionary <Layer, IEnumerable <IdentifyFeature> >();
                }
                if (!taskResults.ContainsKey(result.Key))
                {
                    taskResults.Add(result);
                }
            }

            return(taskResults);
        }
        private void Button1_Clicked(object sender, EventArgs e)
        {
            // Create dialog to display alert information
            var alert = new AlertDialog.Builder(this);

            try
            {
                // Define the Uri to the WMTS service
                var myUri = new Uri("http://sampleserver6.arcgisonline.com/arcgis/rest/services/WorldTimeZones/MapServer/WMTS");

                // Create a new instance of a WMTS layer using a Uri and provide an Id value
                WmtsLayer myWmtsLayer = new WmtsLayer(myUri, "WorldTimeZones");

                // Create a new map
                Map myMap = new Map();

                // Get the basemap from the map
                Basemap myBasemap = myMap.Basemap;

                // Get the layer collection for the base layers
                LayerCollection myLayerCollection = myBasemap.BaseLayers;

                // Add the WMTS layer to the layer collection of the map
                myLayerCollection.Add(myWmtsLayer);

                // Assign the map to the MapView
                _myMapView.Map = myMap;
            }
            catch (Exception ex)
            {
                alert.SetTitle("Sample Error");
                alert.SetMessage(ex.Message);
                alert.Show();
            }
        }
Exemplo n.º 35
0
        public void InsertWithNormalConditions()
        {
            // arrange
            var layerCollection = new LayerCollection();
            var layer1          = new MemoryLayer()
            {
                Name = "Layer1"
            };
            var layer2 = new MemoryLayer()
            {
                Name = "Layer2"
            };
            var layer3 = new MemoryLayer()
            {
                Name = "Layer3"
            };

            layerCollection.Add(layer1);
            layerCollection.Add(layer2);

            // act
            layerCollection.Insert(1, layer3);

            // assert
            var list = layerCollection.ToList();

            Assert.AreEqual(3, list.Count());
            Assert.NotNull(list[0]);
            Assert.AreEqual("Layer1", list[0].Name);
            Assert.NotNull(list[1]);
            Assert.AreEqual("Layer3", list[1].Name);
            Assert.NotNull(list[2]);
            Assert.AreEqual("Layer2", list[2].Name);
        }
Exemplo n.º 36
0
		public Canvas()
		{
			InitializeComponent();

			mLayers = new LayerCollection(this);

			SetStyle(ControlStyles.DoubleBuffer, true);
			SetStyle(ControlStyles.AllPaintingInWmPaint, true);
			SetStyle(ControlStyles.UserPaint, true);
		}
Exemplo n.º 37
0
        public void Initialize(LayerCollection layers)
        {
            items.Children.Clear();

            foreach (var layer in layers)
            {
                var item = new LayerListItem {LayerName = layer.LayerName};
                item.Enabled = layer.Enabled;
                item.LayerOpacity = layer.Opacity;
                item.Layer = layer;
                items.Children.Add(item);
            }
        }
        void webMap_GetMapCompleted(object sender, GetMapCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                MyMap.Extent = e.Map.Extent;
                int i = 0;

                LayerCollection layerCollection = new LayerCollection();
                foreach (Layer layer in e.Map.Layers)
                {
                    layer.ID = i.ToString();
                    layerCollection.Add(layer);
                    if (layer is FeatureLayer)
                        (layer as FeatureLayer).MouseLeftButtonUp += WebMapFeatureServicePopups_MouseLeftButtonUp;
                    i++;
                }

                e.Map.Layers.Clear();
                MyMap.Layers = layerCollection;
            }
        }
        public void CreateMapFromID(string webMapID)
        {
            if (!string.IsNullOrEmpty(webMapID))
            {
                Document webMap = new Document();
                webMap.GetMapCompleted += (s, e) =>
                {
                    MyMap.Extent = e.Map.Extent;

                    LayerCollection layerCollection = new LayerCollection();
                    foreach (Layer layer in e.Map.Layers)
                        layerCollection.Add(layer);

                    e.Map.Layers.Clear();
                    MyMap.Layers = layerCollection;
                    WebMapPropertiesTextBox.DataContext = e.ItemInfo;
                };

                webMap.GetMapAsync(webMapID);
            }
        }
Exemplo n.º 40
0
        /// <summary>
        /// Sets the collection of layers to be diplayed as items
        /// </summary>
        /// <param name="layers"></param>
        public void SetModifiedFiles(LayerCollection layers, ZoneCollection zones)
        {
            listView_Layers.BeginUpdate();
              listView_Layers.Items.Clear();

              foreach (Zone zone in zones)
              {
            ListViewItem item = listView_Layers.Items.Add(zone.ZoneName, IMAGE_NEW);
            item.SubItems.Add("New");
              }

              foreach (Layer layer in layers)
              {
            Layer.LayerFileStatus_e status = layer.FileStatus;
            int iImage = IMAGE_MODIFIED;
            string statusStr = "";
            switch (status)
            {
              case Layer.LayerFileStatus_e.Deleted:
            iImage = IMAGE_DELETED;
            statusStr = "Deleted";
            break;
              case Layer.LayerFileStatus_e.Modified:
            iImage = IMAGE_MODIFIED;
            statusStr = "Modified";
            break;
              case Layer.LayerFileStatus_e.NewLayer:
            iImage = IMAGE_NEW;
            statusStr = "New";
            break;
              default:
            System.Diagnostics.Debug.Assert(false,"Should never get here");
            break;
            }

            ListViewItem item = listView_Layers.Items.Add(layer.LayerName, iImage);
            item.SubItems.Add(statusStr);
              }
              listView_Layers.EndUpdate();
        }
        void webMap_GetMapCompleted(object sender, GetMapCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                MyMap.Extent = e.Map.Extent;
                int i = 0;

                LayerCollection layerCollection = new LayerCollection();
                foreach (Layer layer in e.Map.Layers)
                {
                    layer.ID = i.ToString();
                    layerCollection.Add(layer);
                    if (layer is GroupLayer) // the graphicslayer we are interested in is in a grouplayer
                        foreach (Layer childLayer in (layer as GroupLayer).ChildLayers)
                            if (childLayer is GraphicsLayer)
                                  (childLayer as GraphicsLayer).MouseLeftButtonUp += WebMapMapNotesPopups_MouseLeftButtonUp;
                    i++;
                }

                e.Map.Layers.Clear();
                MyMap.Layers = layerCollection;
            }
        }
        public Viewshed()
        {
            InitializeComponent();

            // Initialize the tap points graphics collection
            TapPoints = new ObservableCollection<Graphic>();

            // Initialize layers
            Layers = new LayerCollection();

            // Create the basemap layer and add it to the map
            Layers.Add(new ArcGISTiledMapServiceLayer() { ServiceUri =
                "http://services.arcgisonline.com/arcgis/rest/services/World_Topo_Map/MapServer" });

            // Symbol for tap points layer
            SimpleLineSymbol tapPointsOutline = new SimpleLineSymbol() { Color = Colors.Black };
            SimpleMarkerSymbol tapPointsSymbol = new SimpleMarkerSymbol() 
            { 
                Color = Colors.White, 
                Outline = tapPointsOutline 
            };

            // Tap points layer
            m_tapPointsLayer = new GraphicsLayer() { Renderer = new SimpleRenderer() { Symbol = tapPointsSymbol } };

            // Bind the TapPoints property to the GraphicsSource of the tap points layer
            Binding b = new Binding("TapPoints") { Source = this };
            BindingOperations.SetBinding(m_tapPointsLayer, GraphicsLayer.GraphicsSourceProperty, b);

            // Add the layer to the map
            Layers.Add(m_tapPointsLayer);

            // Set the data context to the page instance to allow for binding to the page's properties
            // in its XAML
            DataContext = this;
        }
Exemplo n.º 43
0
        /// <summary>
        /// Converts a layer hierarchy that may include group layers into a flat collection of layers.  
        /// </summary>
        private static IEnumerable<Layer> FlattenLayers(this IEnumerable<Layer> layers, GroupLayer parent = null)
        {
            LayerCollection flattenedLayers = new LayerCollection();
            foreach (Layer layer in layers)
            {
                if (layer is GroupLayer && !(layer is KmlLayer))
                {
                    // Flatten group layers
                    GroupLayer groupLayer = (GroupLayer)layer;
                    foreach (Layer child in groupLayer.ChildLayers.FlattenLayers(groupLayer))
                        flattenedLayers.Add(child);                    
                }
                else
                {
                    // If the layer was within a group layer, account for the group layer's visibility
                    // and opacity
                    if (parent != null)
                    {
                        layer.Visible = !parent.Visible ? false : layer.Visible;
                        layer.Opacity = parent.Opacity * layer.Opacity;
                        layer.DisplayName = parent.DisplayName;
                    }

                    flattenedLayers.Add(layer);
                }
            }

            return flattenedLayers;
        }
Exemplo n.º 44
0
 private void Configure()
 {
     Layers = new LayerCollection(MapFrame, this);
     _stateLocked = false;
     IsDragable = true;
     base.IsExpanded = true;
     ContextMenuItems = new List<MenuItem>();
     ContextMenuItems.Add(new MenuItem("Remove Group", Remove_Click));
     ContextMenuItems.Add(new MenuItem("Zoom to Group", ZoomToGroup_Click));
     ContextMenuItems.Add(new MenuItem("Create new Group", CreateGroup_Click));
     _selectionEnabled = true;
 }
Exemplo n.º 45
0
 private void OnLayersPropertyChanged(LayerCollection oldLayers, LayerCollection newLayers)
 {
     DetachLayersHandler(oldLayers);
     AttachLayersHandler(newLayers);
     UpdateAttributionItems();
 }
Exemplo n.º 46
0
 private void DetachLayersHandler(LayerCollection layers)
 {
     if (layers != null)
     {
         layers.LayersInitialized -= Layers_LayersInitialized;
         layers.CollectionChanged -= Layers_CollectionChanged;
         foreach (Layer layer in layers)
             DetachLayerHandler(layer);
     }
 }
Exemplo n.º 47
0
        private void AttachLayersHandler(LayerCollection layers)
        {
            if (layers != null)
            {
                layers.CollectionChanged += Layers_CollectionChanged;

                // if one layer is not initialized, subscribe to Layers_Initialize event in order to update attribution items
                // This update is only useful to avoid blank lines (for any reason, a TextBlock with a null string has a null height the first time and a non null height after setting again the text value to null)
                if (!layers.All(layer => layer.IsInitialized))
                    layers.LayersInitialized += Layers_LayersInitialized;
                foreach (Layer layer in layers)
                    AttachLayerHandler(layer);
            }
        }
Exemplo n.º 48
0
        public bool ImportLayerReferences(StringCollection externalLayers, StringCollection errorList)
        {
            _bSceneLoadingInProgress = true;
              bool bResult = true;
              if (errorList == null)
            errorList = new StringCollection();
              try
              {
            List<FileInfo> layerFiles = new List<FileInfo>();
            List<FileInfo> zoneFiles = new List<FileInfo>();
            LayerCollection newLayers = new LayerCollection();
            ZoneCollection newZones = new ZoneCollection();
            foreach (string name in externalLayers)
            {
              string absname = name;
              if (!FileHelper.IsAbsolute(absname))
            absname = Project.MakeAbsolute(name);
              string relname = Project.MakeRelative(absname);
              bool bIsLayer = relname.EndsWith(IScene.LayerFileExtension);
              bool bIsZone = relname.EndsWith(IScene.ZoneFileExtension);

              if (bIsLayer)
              {
            if (Layers.GetLayerByFilename(absname, null) != null)
            {
              errorList.Add(relname + " : Already exists in the scene");
              break;
            }
              }
              else if (bIsZone)
              {
            if (Zones.GetZoneByFilename(absname, null) != null)
            {
              errorList.Add(relname + " : Already exists in the scene");
              continue;
            }
              }

              if (File.Exists(absname))
              {
            if (bIsLayer)
              layerFiles.Add(new FileInfo(absname));
            if (bIsZone)
              zoneFiles.Add(new FileInfo(absname));
              }
              else
            errorList.Add(relname + " : File not found");
            }

            LoadLayers(newLayers, null, layerFiles.ToArray());
            // LoadZones(newZones, null, zoneFiles.ToArray()); // not supported yet

            // Add layers to the scene (do not lock them)
            foreach (Layer layer in newLayers)
            {
              if (layer is V3DLayer)
              {
            errorList.Add(layer.LayerFilename + " : External main layers cannot be added");
            continue;
              }

              EditorManager.Actions.Add(new AddLayerAction(layer, false));
            }

            foreach (Zone zone in newZones)
              EditorManager.Actions.Add(new AddZoneAction(zone, false));

              }
              catch (Exception ex)
              {
            EditorManager.DumpException(ex, true);
            bResult = false;
              }

              _bSceneLoadingInProgress = false;

              WriteReferenceFile();
              return bResult;
        }
		private static FeatureLayer GetFeatureLayerWithID(string layerID, LayerCollection layers)
		{
			if (layers != null && !string.IsNullOrEmpty(layerID) && layers[layerID] is FeatureLayer)
				return layers[layerID] as FeatureLayer;
			return null;
		}
Exemplo n.º 50
0
        /// <summary>
        /// Opens a dialog to confirm all the layer changes
        /// </summary>
        public void UpdateLayers()
        {
            LayerCollection modifiedLayers = new LayerCollection();
              ZoneCollection modifiedZones = new ZoneCollection();

              // gather new and modified layers
              GatherZones(modifiedZones);
              GatherLayers(modifiedLayers, null);

              // gather deleted layers
              foreach (Layer layer in Layers)
              {
            if (layer.OwnsLock) // cannot be deleted or modified
              continue;

            if (File.Exists(layer.AbsoluteLayerFilename))
              continue;

            layer.FileStatus = Layer.LayerFileStatus_e.Deleted;
            modifiedLayers.Add(layer);
              }

              if (modifiedLayers.Count == 0 && modifiedZones.Count == 0)
              {
            EditorManager.ShowMessageBox("No updated, new or deleted layers/zones have been detected", "Update Layers", MessageBoxButtons.OK, MessageBoxIcon.Information);
            return;
              }

              LayerUpdateDlg dlg = new LayerUpdateDlg();
              dlg.SetModifiedFiles(modifiedLayers, modifiedZones);
              if (dlg.ShowDialog() != DialogResult.OK)
            return;

              EditorManager.Actions.StartGroup("Update Layers");

              // add new zones
              foreach (Zone zone in modifiedZones)
              {
            zone.ParentScene = this;
            Zones.Add(zone);
              }

              // now merge the layers into the scene
              foreach (Layer layer in modifiedLayers)
              {
            Layer.LayerFileStatus_e status = layer.FileStatus;

            if (status == Layer.LayerFileStatus_e.Deleted)
            {
              EditorManager.Actions.Add(new RemoveLayerAction(layer));
              continue;
            }
            if (status == Layer.LayerFileStatus_e.NewLayer)
            {
              EditorManager.Actions.Add(new AddLayerAction(layer, false)); // no unique filenames, use as-is
              continue;
            }
            if (status == Layer.LayerFileStatus_e.Modified)
            {
              Layer oldLayer = Layers.GetLayerByFilename(layer.LayerFilename);
              EditorManager.Actions.Add(new UpdateLayerAction(oldLayer, layer));
              continue;
            }
              }

              EditorManager.Actions.EndGroup();

              modifiedZones.MatchupLayerNames(Layers, null); // only call this for new zones!

              IScene.SendZoneChangedEvent(new ZoneChangedArgs(null, ZoneChangedArgs.Action.RebuildList));
        }
		private void Layers_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
		{
			bool featureLayerUpdated = (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Reset);
			if (e.OldItems != null)
			{
				var featureLayers = new List<FeatureLayer>();
				foreach (object layer in e.OldItems)
				{
					if (layer is FeatureLayer && !string.IsNullOrEmpty((layer as FeatureLayer).ID))
						featureLayers.Add(layer as FeatureLayer);
				}
				featureLayerUpdated = featureLayers.Count > 0;
				DetachLayerEventHandler(featureLayers);
			}
			if (e.NewItems != null)
			{
				var hookToInitialized = new LayerCollection();
				var hookToPropertyChangedOnly = new LayerCollection();
				foreach (object layer in e.NewItems)
				{
					if (layer is FeatureLayer && !string.IsNullOrEmpty((layer as FeatureLayer).ID))
						{
						if (mapLayersInitialized && !(layer as FeatureLayer).IsInitialized)
							hookToInitialized.Add(layer as FeatureLayer);
							else
							hookToPropertyChangedOnly.Add(layer as FeatureLayer);
					}
				}
				featureLayerUpdated = hookToPropertyChangedOnly.Count > 0;
				AttachLayerEventHandler(GetLayers(LayerIDs, hookToInitialized), true);
				AttachLayerEventHandler(GetLayers(LayerIDs, hookToPropertyChangedOnly), false);
			}
			if (this.mapLayersInitialized && featureLayerUpdated)
				this.setTemplates();
		}
		private void AttachMapLayerCollection(LayerCollection layers)
		{
			if (layers == null) return;
			layerCollection = layers;
			layers.LayersInitialized += MapView_LayersInitialized;
			layers.CollectionChanged += Layers_CollectionChanged;
			AttachLayerEventHandler(GetLayers(LayerIDs, layers));
			var initializedLayers = layers.Where(l => l is FeatureLayer && l.IsInitialized);
			if (initializedLayers.Count() > 0)
				setTemplates();
		}
		private void DetachMapLayerCollection(LayerCollection layers)
		{
			layers.LayersInitialized -= MapView_LayersInitialized;
			layers.CollectionChanged -= Layers_CollectionChanged;
			DetachLayerEventHandler(GetLayers(LayerIDs, layers));
		}
Exemplo n.º 54
0
        /// <summary>
        /// Actually load the scene
        /// </summary>
        /// <param name="relFileName"></param>
        /// <returns></returns>
        public bool Load(string relFileName)
        {
            _bSceneLoadingInProgress = true;
              EditorManager.Progress.StatusString = "Load manifest file";
              FileName = relFileName;
              string absFileName = AbsoluteFileName;

              // Check for old scene file format, and refuse to load it.
              try
              {
            using (FileStream fs = new FileStream(absFileName, FileMode.Open, FileAccess.Read))
            {
              long iLen = fs.Length;

              if (iLen > 0) // this is an old file
              {
            String error = String.Format("Loading aborted.\nThe file format of this scene is not supported by recent versions of vForge.\nTo migrate it, please open and then re-save this file in vForge prior to version 2012.3.");
            EditorManager.ShowMessageBox(error, "Scene loading error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            return false;
              }
            }
              }
              catch (Exception ex)
              {
            EditorManager.DumpException(ex);
            EditorManager.ShowMessageBox("An exception occurred while loading scene file '" + relFileName + "'.\nPlease check whether the file is there and it is not write protected.\n\nDetailed Message:\n" + ex.Message,
              "Scene loading error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            _bSceneLoadingInProgress = false;
            return false; // the file isn't there at all or write protected?
              }
              EditorManager.Progress.Percentage = 15.0f; // loaded manifest
              EditorManager.Progress.StatusString = "Load layer and zone files";

              // Load export profile. If the return value is null, CurrentExportProfile creates a new instance
              _currentProfile = SceneExportProfile.LoadProfile(this, null, false);
              if (_currentProfile == null)
            EditorSceneSettings.PATCH_PROFILE = CurrentExportProfile; // patch into profile if no dedicated file has been loaded

              // Load user specific data
              string directoryName = LayerDirectoryName;
              string userFilename = Path.Combine(directoryName, EditorManager.UserSettingsFilename);

              // first try user specific file:
              if (!LoadUserSettingsFile(userFilename))
              {
            // alternatively try default.user file
            userFilename = Path.Combine(directoryName, "default.user");
            LoadUserSettingsFile(userFilename);
              }
              EditorSceneSettings.PATCH_PROFILE = null;

              if (!string.IsNullOrEmpty(Settings.ExportProfileName))
              {
            SceneExportProfile profile = SceneExportProfile.LoadProfile(this, Settings.ExportProfileName, false);
            if (profile != null)
              _currentProfile = profile;
              }

              EditorManager.Progress.SetRange(15.0f, 20.0f); // remap GatherLayers to range 15..20
              Zones.Clear();
              if (!GatherZones(Zones))
              {
            _bSceneLoadingInProgress = false;
            return false;
              }

              Layers.Clear();

              // load the layer files...
              LayerCollection newLayers = new LayerCollection();
              if (!GatherLayers(newLayers, EditorManager.Progress))
              {
            _bSceneLoadingInProgress = false;
            Layers.Clear();
            return false;
              }

              // Take the SortingOrder value
              newLayers.Sort();

              // create a dictionary for fast name lookup
              Dictionary<string, Layer> layerNameDict = new Dictionary<string, Layer>(newLayers.Count);
              foreach (Layer layer in newLayers)
            layerNameDict.Add(layer.LayerFilename, layer);

              if (!Zones.MatchupLayerNames(newLayers, layerNameDict))
              {
            _bSceneLoadingInProgress = false;
            return false;
              }

              // Add layers to the scene (do not lock them)
              foreach (Layer layer in newLayers)
            AddLayer(layer, false, false, false);

              // If project setting is to lock all layers on scene load open the layer lock dialog.
              // Otherwise all layers will be locked automatically (when not locked already by any other user).
              if (!TestManager.IsRunning && !EditorManager.SilentMode && Project.LayerLocking == EditorProject.LayerLocking_e.AskOnSceneOpen)
              {
            // user lock selection is not obeyed if a layer backup was detected, then the layer restore selection was responsible for locking the layers
            if (_useLayersBackupRestore)
            {
              foreach (Layer layer in _layersBackupRestoreSelection)
              {
            layer.TryLock(this, false);
              }
            }
            else
            {
              // Open layer lock dialog where user can select the layers to lock
              LayerLockDlg dlg = new LayerLockDlg();
              dlg.Scene = this;

              // Dialog has only an OK button as canceling the operation doesn't make much sense
              dlg.ShowDialog();
            }
              }
              else
              {
            foreach (Layer layer in Layers)
              layer.TryLock(this, false);
              }

              if (!newLayers.CheckLayerUniqueIDs())
              {
            EditorManager.ShowMessageBox("Layer IDs in this scene are not unique. Please contact support", "Layer ID conflict", MessageBoxButtons.OK, MessageBoxIcon.Warning);
              }

              // fixup exported layer names and put the Export flag into the layers own flag
              SceneExportProfile exportprofile = CurrentExportProfile;
              exportprofile.FixupLayerNames();
              if (exportprofile.LoadedFromFile) // preserve the flags loaded from Layer files otherwise
            exportprofile.ExportedLayersToScene();

              _iSceneversion = SCENE_VERSION_CURRENT; // however, scene version does not make much sense anymore

              // Mark all layers that have been restored from a backup as dirty
              foreach (Layer layer in _layersBackupRestoreSelection)
              {
            layer.Dirty = true;
              }

              // The scene is dirty if any layer was restored from a backup
              m_bDirty = (_useLayersBackupRestore && _layersBackupRestoreSelection.Count > 0);

              // Layers with backup have been dealt with, clean list for potential next selection
              _layersBackupRestoreSelection.Clear();

              EditorManager.Progress.SetRange(0.0f, 100.0f); // set back sub-range
              EditorManager.Progress.Percentage = 20.0f; // loaded layer files
              _bSceneLoadingInProgress = false;

              return true;
        }
Exemplo n.º 55
0
        private void Configure()
        {
            Layers = new LayerCollection(this);
            base.LegendText = SymbologyMessageStrings.LayerFrame_Map_Layers;
            ContextMenuItems = new List<SymbologyMenuItem>();
            ContextMenuItems.Add(new SymbologyMenuItem(SymbologyMessageStrings.LayerFrame_RemoveMapFrame, Remove_Click));
            ContextMenuItems.Add(new SymbologyMenuItem(SymbologyMessageStrings.LayerFrame_ZoomToMapFrame, ZoomToMapFrame_Click));
            ContextMenuItems.Add(new SymbologyMenuItem(SymbologyMessageStrings.LayerFrame_CreateGroup, CreateGroup_Click));

            base.LegendSymbolMode = SymbolMode.GroupSymbol;
            LegendType = LegendType.Group;
            MapFrame = this;
            ParentGroup = this;
            _drawingLayers = new List<ILayer>();
        }
Exemplo n.º 56
0
        public bool LoadLayersFromXML(LayerCollection newLayers, ProgressStatus progress, FileInfo[] files)
        {
            bool bOK = true;
              float fPercentage = 0.0f;
              foreach (FileInfo fileInfo in files)
              {
            fPercentage += 100.0f / (float)files.Length;
            if (fileInfo == null || (fileInfo.Attributes & FileAttributes.Directory) != 0) // file info can be null
              continue;
            if (string.Compare(fileInfo.Extension, IScene.LayerFileExtensionXML, true) != 0)
              continue;
            try
            {
              string absfilename = fileInfo.FullName;
              string filename = fileInfo.Name;
              using (XmlTextReader xmlReader = new XmlTextReader(absfilename))
              {
              XmlDocument doc = new XmlDocument();
              doc.Load(xmlReader);
              if (doc.DocumentElement == null)
            throw new Exception("XML does not contain root node");
              IEnumerator nodes = doc.DocumentElement.GetEnumerator();
              while (nodes.MoveNext())
              {
            XmlElement node = nodes.Current as XmlElement;
            if (node == null || node.Name != "layer")
              continue;

            string classname = node.GetAttribute("class");
            string name = node.GetAttribute("name");
            string uid = node.GetAttribute("uid");

            if (string.IsNullOrEmpty(name))
              name = Path.GetFileNameWithoutExtension(filename);

            Type t = EditorManager.ShapeFactory.GetTypeByName(classname, typeof(Layer), false);
            if (t == null)
              t = typeof(Layer);
            Layer layer = Activator.CreateInstance(t, new object[1] { name }) as Layer;
            if (layer == null)
              throw new Exception("Could not instantiate Layer");
            layer.SetLayerFileNameInternal(filename); // same filename but will replace extension

            if (!string.IsNullOrEmpty(uid))
            {
              layer.SetLayerIDInternal(Convert.ToUInt32(uid));
            }

            newLayers.Add(layer);

            // apply property/value pairs to layer
            SerializationHelper.ApplyXMLProperties(node, layer, false);

            // parse for shapes
            IEnumerator propNodes = node.GetEnumerator();
            while (propNodes.MoveNext())
            {
              XmlElement propNode = propNodes.Current as XmlElement;
              if (propNode == null)
                continue;
              if (propNode.Name == "shapes")
              {
                // use prefab functionality to parse it
                PrefabDesc dummyPrefab = new PrefabDesc(null);
                ShapeCollection shapes = dummyPrefab.CreateInstances(propNode, true, true);
                if (shapes != null)
                {
                  layer.Root.SetChildCollectionInternal(shapes);
                  foreach (ShapeBase shape in shapes)
                  {
                    shape.SetParentInternal(layer.Root);
                    shape.SetParentLayerInternal(layer);
                  }
                }
                if (!string.IsNullOrEmpty(dummyPrefab.LastError))
                {
                  string msg = "An error occurred while parsing file: \n\n" + filename + "\n\nThe layer won't contain any shapes.\nDetailed message:\n" + dummyPrefab.LastError;
                  EditorManager.ShowMessageBox(msg, "Error parsing layer file", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                continue;
              }
              }
            }
              }
            }
            catch (Exception ex)
            {
              EditorManager.DumpException(ex, false);
              return false;
            }

              }
              return bOK;
        }
Exemplo n.º 57
0
        public override bool LoadLayers(LayerCollection newLayers, ProgressStatus progress, FileInfo[] files)
        {
            bool bOK = true;
              float fPercentage = 0.0f;
              string layerDir = LayerDirectoryName;
              foreach (FileInfo fileInfo in files)
              {
            fPercentage += 100.0f / (float)files.Length;
            if (fileInfo == null || (fileInfo.Attributes & FileAttributes.Directory) != 0) // file info can be null
              continue;
            if (string.Compare(fileInfo.Extension, IScene.LayerFileExtension, true) != 0)
              continue;

            string layerFile = fileInfo.Name;
            if (!fileInfo.FullName.StartsWith(LayerDirectoryName)) // assume it is a layer reference
              layerFile = this.Project.MakeRelative(fileInfo.FullName);

            Layer layer = Layers.GetLayerByFilename(layerFile);
            Layer.LayerFileStatus_e newState = Layer.LayerFileStatus_e.NewLayer;
            if (layer != null) // already there
            {
              bool bModified = layer.LastModified != fileInfo.LastWriteTime;
              System.Diagnostics.Debug.Assert(!layer.OwnsLock || !bModified);
              if (bModified && !layer.OwnsLock)
              {
            newState = Layer.LayerFileStatus_e.Modified;
              }
              else
              {
            // don't add the non-modified layer to the list
            layer.FileStatus = Layer.LayerFileStatus_e.NotModified;
            continue;
              }
            }

            BinaryFormatter fmt = SerializationHelper.BINARY_FORMATTER;
            try
            {
              // open the layer in read-only mode
              FileStream fs = new FileStream(fileInfo.FullName, FileMode.Open, FileAccess.Read);
              layer = (Layer)fmt.Deserialize(fs);
              fs.Close();

              // make sure there is only one layer of type V3DLayer [#18824]
              if (layer is V3DLayer)
              {
            foreach (Layer other in newLayers)
              if (other is V3DLayer)
                throw new Exception("The Layer directory contains more than one Layer of type 'Main Layer'. E.g. '" + layer.LayerFilename + "' and '" + other.LayerFilename + "'.\n\nIgnoring '" + layer.LayerFilename + "'");
              }
            }
            catch (Exception ex)
            {
              EditorManager.DumpException(ex);
              EditorManager.ShowMessageBox("An exception occurred while loading layer '" + fileInfo.Name + "'\n\nDetailed Message:\n" + ex.ToString(),
            "Layer loading error", MessageBoxButtons.OK, MessageBoxIcon.Error);
              continue;
            }

            if (fileInfo.FullName.StartsWith(layerDir))
              layer.SetLayerFileNameInternal(fileInfo.Name);
            else
            {
              // this layer is a reference
              string name = Project.MakeRelative(fileInfo.FullName);
              layer.SetLayerFileNameInternal(name);
              layer.IsReference = true;
            }

            layer.UpdateLastModified(fileInfo);
            layer.FileStatus = newState;
            layer.UpdateReadOnlyState(fileInfo);
            newLayers.Add(layer);
            if (progress != null)
              progress.Percentage = fPercentage;
              }

              return bOK;
        }
Exemplo n.º 58
0
        public override bool LoadLayers(LayerCollection newLayers, ProgressStatus progress, FileInfo[] files)
        {
            bool bOK = true;
              float fPercentage = 0.0f;
              string layerDir = LayerDirectoryName;

              Dictionary<FileInfo, bool> layersToLoad = new Dictionary<FileInfo, bool>();
              foreach (FileInfo file in files)
              {
            // Key is FileInfo, Value bool says if a layer backup should be loaded instead of the original layer file.
            // The layer may have been filtered if it belongs to a zone that isn't currently loaded.
            if (file != null)
            {
              layersToLoad.Add(file, false);
            }
              }

              // Check if there's any layers with backup files and mark their value with true.
              _layersBackupRestoreSelection.Clear();
              if (CheckLayersInterimBackup(layersToLoad, layerDir))
              {
            // Open layer lock dialog where user can select the layers to restore from the backup file.
            LayerRestoreDlg dlg = new LayerRestoreDlg();
            dlg.RestoreLayerList = layersToLoad;
            dlg.ShowDialog();

            // If the user chooses the layers to restore, the layers to restore will be locked, all others won't.
            _useLayersBackupRestore = true;
              }
              else
              {
            _useLayersBackupRestore = false;
              }

              foreach (var fileInfoEntry in layersToLoad)
              {
            FileInfo fileInfo = fileInfoEntry.Key;

            fPercentage += 100.0f / (float)files.Length;
            if (fileInfo == null || (fileInfo.Attributes & FileAttributes.Directory) != 0) // file info can be null
              continue;
            if (string.Compare(fileInfo.Extension, IScene.LayerFileExtension, true) != 0)
              continue;

            string layerFile = fileInfo.Name;
            if (!fileInfo.FullName.StartsWith(LayerDirectoryName)) // assume it is a layer reference
              layerFile = this.Project.MakeRelative(fileInfo.FullName);

            Layer layer = Layers.GetLayerByFilename(layerFile);
            Layer.LayerFileStatus_e newState = Layer.LayerFileStatus_e.NewLayer;
            if (layer != null) // already there
            {
              bool bModified = layer.LastModified != fileInfo.LastWriteTime;
              System.Diagnostics.Debug.Assert(!layer.OwnsLock || !bModified);
              if (bModified && !layer.OwnsLock)
              {
            newState = Layer.LayerFileStatus_e.Modified;
              }
              else
              {
            // don't add the non-modified layer to the list
            layer.FileStatus = Layer.LayerFileStatus_e.NotModified;
            continue;
              }
            }

            // If the layer is loaded from the backup, it will load the content from the backup file
            // and lock the layer right away
            bool useBackupRestore = fileInfoEntry.Value == true;

            IFormatter fmt = SerializationHelper.AUTO_FORMATTER;
            try
            {
              string layerToLoad = fileInfo.FullName;

              // If the layer was marked to load the backup file, add this here
              if (useBackupRestore)
              {
            layerToLoad += IScene.InterimBackupFileExtension;
              }

              // open the layer in read-only mode
              using (FileStream fs = new FileStream(layerToLoad, FileMode.Open, FileAccess.Read))
              {
            layer = (Layer)fmt.Deserialize(fs);
              }

              // make sure there is only one layer of type V3DLayer [#18824]
              if (layer is V3DLayer)
              {
            foreach (Layer other in newLayers)
              if (other is V3DLayer)
                throw new Exception("The Layer directory contains more than one Layer of type 'Main Layer'. E.g. '" + layer.LayerFilename + "' and '" + other.LayerFilename + "'.\n\nIgnoring '" + layer.LayerFilename + "'");
              }
            }
            catch (Exception ex)
            {
              EditorManager.DumpException(ex);
              EditorManager.ShowMessageBox("An exception occurred while loading layer '" + fileInfo.Name + "'\n\nDetailed Message:\n" + ex.Message,
            "Layer loading error", MessageBoxButtons.OK, MessageBoxIcon.Error);
              continue;
            }

            if (fileInfo.FullName.StartsWith(layerDir))
              layer.SetLayerFileNameInternal(fileInfo.Name);
            else
            {
              // this layer is a reference
              string name = Project.MakeRelative(fileInfo.FullName);
              layer.SetLayerFileNameInternal(name);
              layer.IsReference = true;
            }

            layer.UpdateLastModified(fileInfo);
            layer.FileStatus = newState;
            layer.UpdateReadOnlyState(fileInfo);
            newLayers.Add(layer);
            if (progress != null)
              progress.Percentage = fPercentage;

            // If we restore a backup, we will always try to lock the layer and bypass a potential user choice for locking layers
            if (useBackupRestore)
            {
              _layersBackupRestoreSelection.Add(layer);
            }
              }

              return bOK;
        }
        void webMap_GetMapCompleted(object sender, GetMapCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                MyMap.Extent = e.Map.Extent;

                LayerCollection layerCollection = new LayerCollection();
                foreach (Layer layer in e.Map.Layers)
                    layerCollection.Add(layer);

                GraphicsLayer selectedGraphics = new GraphicsLayer()
                {
                    RendererTakesPrecedence = false,
                    ID = "MySelectionGraphicsLayer"
                };
                layerCollection.Add(selectedGraphics);

                e.Map.Layers.Clear();
                MyMap.Layers = layerCollection;
            }
        }
Exemplo n.º 60
0
        /// <summary>
        /// Update the list of layers. Ignores filenames that exist as layers
        /// </summary>
        /// <param name="newLayers"></param>
        /// <param name="progress"></param>
        /// <returns></returns>
        public bool GatherLayers(LayerCollection newLayers, ProgressStatus progress)
        {
            bool bOK = true;
              string directoryName = LayerDirectoryName;
              DirectoryInfo layerFolder = new DirectoryInfo(directoryName);

              if (!layerFolder.Exists)
            return bOK;

              FileInfo[] files = layerFolder.GetFiles("*" + IScene.LayerFileExtension); // filter out *.Layer
              FileInfo[] filesXML = layerFolder.GetFiles("*" + IScene.LayerFileExtensionXML); // filter out *.LayerXML

              // add layer references:
              string refFile = LayerReferenceFile;
              if (File.Exists(refFile))
              {
            List<FileInfo> allFiles = new List<FileInfo>(files); ;
            TextReader txt = new StreamReader(refFile);
            while (true)
            {
              string line = txt.ReadLine();
              if (line == null)
            break;
              if (line.StartsWith("//") || !line.EndsWith(IScene.LayerFileExtension)) // commented out or not .Layer?
            continue;
              string externalname = this.Project.MakeAbsolute(line);
              if (File.Exists(externalname))
            allFiles.Add(new FileInfo(externalname));
            }
            txt.Close();
            files = allFiles.ToArray();
              }

              FilterLayerFiles(files, null);
              FilterLayerFiles(filesXML, files);

              bOK = LoadLayers(newLayers, progress, files);
              bOK &= LoadLayersFromXML(newLayers, progress, filesXML);

              return bOK;
        }