static void OnAttributesChange(DependencyObject o, DependencyPropertyChangedEventArgs args)
        {
            HoverResults hr = o as HoverResults;

            if (hr == null)
            {
                return;
            }
            hr.Graphic = hr.Layer.Graphics.FirstOrDefault(item => item.Attributes == hr.Attributes); //null or matching graphic
#if DEBUG
            if (hr.Attributes == null)
            {
                Debug.WriteLine(string.Format("@@Change, NULL, {0}", MapApplication.GetLayerName(hr.Layer)));
            }
            else if (hr.Attributes.ContainsKey("NAME"))
            {
                Debug.WriteLine(string.Format("@@Change, {0}, {1}", hr.Attributes["NAME"], MapApplication.GetLayerName(hr.Layer)));
            }
            else
            {
                Debug.WriteLine(string.Format("@@Change (no NAME field), {0}", MapApplication.GetLayerName(hr.Layer)));
            }
#endif
            PositionMapTip.rebuildMapTipContentsBasedOnFieldVisibility(hr);
        }
        private void attachApplicationMapTipToLayer(GraphicsLayer layer, Graphic g)
        {
#if DEBUG
            Debug.WriteLine(string.Format("@@Attaching map tip to layer: {0}", MapApplication.GetLayerName(layer)));
#endif
            // Create a new control each time a popup is to be displayed. This is to reset the controls to their
            // initial state. If this is not done, and you have controls like ToggleButtons, they may retain their
            // expanded or collapsed state even though binding is supposed to reset this. This way, you have a
            // consistent starting point for the display of a popup.
            HoverResults hoverResults = new HoverResults()
            {
                Style   = HoverLayoutStyleHelper.Instance.GetStyle("HoverPopupContainerStyle"),
                Layer   = layer,
                Graphic = g,
                Map     = AssociatedObject
            };

            // Associate map tip control with layer
            layer.MapTip = hoverResults;

            layer.MapTip.SizeChanged -= MapTip_SizeChanged;
            layer.MapTip.SizeChanged += MapTip_SizeChanged;

            // re-establish delay
            TimeSpan delay = (TimeSpan)AssociatedObject.GetValue(DelayMapTipHide.HideDelayProperty);
            layer.MapTip.SetValue(GraphicsLayer.MapTipHideDelayProperty, delay);
        }
        private void loadUI()
        {
            MapApplication.SetApplication(BuilderApplication.Instance);
            AppCoreHelper.SetService(new ApplicationServices());

            this.RootVisual = mainPage = new MainPage()
            {
                DataContext = BuilderApplication.Instance,
            };
            ESRI.ArcGIS.Mapping.Core.Utility.SetRTL(mainPage);
            ImageUrlResolver.RegisterImageUrlResolver(new BuilderImageUrlResolver());
            WebClientFactory.Initialize();

            NotificationPanel.Instance.Initialize();

            if (!NotificationPanel.Instance.OptedOutOfNotification)
            {
                EventHandler handler = null;
                handler = (o, e) =>
                {
                    if (NotificationPanel.Instance.OptedOutOfNotification)
                    {
                        NotificationPanel.Instance.NotificationsUpdated -= handler;
                        return;
                    }

                    showExtensionLoadFailedMessageOnStartup();
                };
                NotificationPanel.Instance.NotificationsUpdated += handler;
                if (hasStartupExtensionLoadFailedEvent)
                {
                    showExtensionLoadFailedMessageOnStartup();
                }
            }
        }
示例#4
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)
示例#5
0
        }         // private Layer createLayer(string id, bool vis)

        private void getLyrSignature(Map map, ESRI.ArcGIS.Client.Layer l)
        {
            // get all Layer parameters
            string typ = lyr.GetType().ToString();

            string[] parts = typ.Split(new string[] { "." }, StringSplitOptions.RemoveEmptyEntries);
            if (parts.Length > 0)
            {
                typ = parts[parts.Length - 1];
            }

            lyrType = typ;
            lyrName = MapApplication.GetLayerName(l);
            popupOn = ESRI.ArcGIS.Client.Extensibility.LayerProperties.GetIsPopupEnabled(l);

            // sublayers popups on/off http://forums.arcgis.com/threads/58106-Popup-for-visible-layers-only?highlight=popups
            var ids = ESRI.ArcGIS.Mapping.Core.LayerExtensions.GetIdentifyLayerIds(l);
            //var ids = new System.Collections.ObjectModel.Collection<int>();
            var xmlszn = new System.Xml.Serialization.XmlSerializer(typeof(System.Collections.ObjectModel.Collection <int>));
            var sw     = new StringWriter();

            xmlszn.Serialize(sw, ids);
            identifyLayerIds = string.Format("{0}", sw.ToString().Trim());

            if (typ == "ArcGISTiledMapServiceLayer")
            {
                var lr = (ArcGISTiledMapServiceLayer)lyr;
                lyrUrl = lr.Url;
                proxy  = lr.ProxyURL;
            }
            else if (typ == "OpenStreetMapLayer")
            {
                var lr = lyr as ESRI.ArcGIS.Client.Toolkit.DataSources.OpenStreetMapLayer;
                lyrUrl = "http://www.openstreetmap.org/";
            }
            else if (typ == "ArcGISDynamicMapServiceLayer")
            {
                var lr = (ArcGISDynamicMapServiceLayer)lyr;
                lyrUrl      = lr.Url;
                proxy       = lr.ProxyURL;
                imageFormat = lr.ImageFormat;
            }
            else if (typ == "FeatureLayer")
            {
                var lr = (FeatureLayer)lyr;
                lyrUrl   = lr.Url;
                renderer = getRenderer(lr);
                proxy    = lr.ProxyUrl;
            }
            else if (typ == "GraphicsLayer")
            {
                var lr = (GraphicsLayer)lyr;
                lyrUrl   = getContent(lr);
                renderer = getRenderer(lr);
                proxy    = "";
            }
            return;
        }         // private string getLyrSignature(Map map, ESRI.ArcGIS.Client.Layer lyr)
示例#6
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;
        }
        // Get mouse position
        void GraphicsLayer_MouseEnterOrMove(object sender, GraphicMouseEventArgs args)
        {
            _mousePos = args.GetPosition(AssociatedObject);
            GraphicsLayer graphicsLayer = sender as GraphicsLayer;

#if DEBUG
            if (args.Graphic != null)
            {
                if (args.Graphic.Symbol is ESRI.ArcGIS.Client.Clustering.FlareSymbol)
                {
                    Debug.WriteLine(string.Format("@@MouseEnter/Move, flare, {0}", MapApplication.GetLayerName(graphicsLayer)));
                }
                else if (args.Graphic.Attributes.ContainsKey("NAME"))
                {
                    Debug.WriteLine(string.Format("@@MouseEnter/Move, {0}, {1}", args.Graphic.Attributes["NAME"], MapApplication.GetLayerName(graphicsLayer)));
                }
                else
                {
                    Debug.WriteLine(string.Format("@@MouseEnter/Move, no NAME field, {0}", MapApplication.GetLayerName(graphicsLayer)));
                }
            }
#endif
            if (ESRI.ArcGIS.Client.Extensibility.LayerProperties.GetIsPopupEnabled(graphicsLayer))
            {
                if (!ESRI.ArcGIS.Mapping.Core.LayerExtensions.GetPopUpsOnClick(graphicsLayer))
                {
                    HoverResults hoverResults = graphicsLayer.MapTip as HoverResults;
                    if (graphicsLayer.MapTip == null) //if not a custom map tip
                    {
                        //if first time, attach map tip to layer
                        attachApplicationMapTipToLayer(graphicsLayer, args.Graphic);
                        hoverResults = graphicsLayer.MapTip as HoverResults;
                    }

                    //if map tip dirty, rebuild map tip
                    if (hoverResults != null)
                    {
                        if (ESRI.ArcGIS.Mapping.Core.LayerExtensions.GetIsMapTipDirty(graphicsLayer) &&
                            args.Graphic == hoverResults.Graphic)
                        {
                            rebuildMapTipContentsBasedOnFieldVisibility(hoverResults);
                        }
                        //clear map tip dirty flag
                        ESRI.ArcGIS.Mapping.Core.LayerExtensions.SetIsMapTipDirty(graphicsLayer, false);
                    }
                }
                else
                {
                    graphicsLayer.MapTip = null;
                }
            }
            else if (graphicsLayer.MapTip is HoverResults)
            {
                graphicsLayer.MapTip = null;
            }
        }
示例#8
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)
示例#9
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)
示例#10
0
 public void ShowWindow(MapApplication mapApplication, string windowTitle, FrameworkElement windowContents, bool isModal = false, EventHandler <CancelEventArgs> onHidingHandler = null, EventHandler onHideHandler = null)
 {
     if (!windowsBeingShown.Contains(windowContents))
     {
         mapApplication.ShowWindow(windowTitle, windowContents, isModal, onHidingHandler, (sender, args) =>
         {
             if (onHideHandler != null)
             {
                 onHideHandler(sender, args);
             }
             windowsBeingShown.Remove(windowContents);
         });
         windowsBeingShown.Add(windowContents);
     }
 }
示例#11
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()
示例#12
0
        /// <summary>
        /// Clears the AutoCAD Map Error Stack
        /// </summary>
        /// <returns></returns>
        public static bool ClearErrorStack()
        {
            bool retVal = false;

            //_logger.Debug("Start ClearErrorStack");
            try
            {
                MapApplication AcMap = HostMapApplicationServices.Application;
                AcMap.ErrorStack.Clear();
                retVal = true;
            }
            catch (System.Exception ex)
            {
                //_logger.Error("Error in ClearErrorStack", ex);
                throw;
            }
            //_logger.Debug("End ClearErrorStack");
            return(retVal);
        }
示例#13
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)
示例#14
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)
示例#15
0
        /// <summary>
        /// Checks whether a layer is in a measurable state
        /// </summary>
        /// <param name="layer">The layer to check</param>
        /// <param name="map">The map containing the layer</param>
        /// <returns></returns>
        internal static bool IsMeasurable(this Layer layer, Map map)
        {
            // Check whether the layer is visible, of a measurable type, has a defined layer name, and is not
            // hidden due to scale dependency
            bool measurable = layer.Visible &&
                              ((layer is ArcGISDynamicMapServiceLayer) ||
                               (layer is GraphicsLayer &&
                                ((GraphicsLayer)layer).GeometryType() != null &&
                                ((GraphicsLayer)layer).GeometryType() != ESRI.ArcGIS.Client.Tasks.GeometryType.MultiPoint)) &&
                              !string.IsNullOrEmpty(MapApplication.GetLayerName(layer)) &&
                              layer.IsInVisibleRange(map);

            // For map service layers, make sure at least one sub-layer is visible
            if (measurable && layer is ArcGISDynamicMapServiceLayer)
            {
                ArcGISDynamicMapServiceLayer dynLayer = (ArcGISDynamicMapServiceLayer)layer;
                // Check sub-layer visibility directly and as defined by the sub-layer's scale dependency
                measurable = dynLayer.Layers.Any(subLayer => dynLayer.GetLayerVisibility(subLayer.ID) &&
                                                 subLayer.IsInVisibleRange(map));
            }

            return(measurable);
        }
示例#16
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)
示例#17
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)
示例#18
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)
        // 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);
            }
        }
示例#20
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)
        } // 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)
示例#22
0
 /// <summary>
 /// Initializes a new instance of the <see cref="QueryManager"/> class.
 /// </summary>
 /// <param name="db">The db.</param>
 public QueryManager(Database db)
 {
     _mapApp       = Autodesk.Gis.Map.HostMapApplicationServices.Application;
     _projectModel = _mapApp.GetProjectForDB(db);
 }
示例#23
0
 /// <summary>
 /// Initializes a new instance of the <see cref="QueryManager"/> class.
 /// </summary>
 public QueryManager()
 {
     _mapApp       = Autodesk.Gis.Map.HostMapApplicationServices.Application;
     _projectModel = _mapApp.ActiveProject;
 }
        /// <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);
        }
        public void exportshapefiles()
        {
            DocumentCollection docCol   = Application.DocumentManager;
            Database           localDb  = docCol.MdiActiveDocument.Database;
            Editor             editor   = docCol.MdiActiveDocument.Editor;
            Document           doc      = docCol.MdiActiveDocument;
            CivilDocument      civilDoc = Autodesk.Civil.ApplicationServices.CivilApplication.ActiveDocument;
            MapApplication     mapApp   = HostMapApplicationServices.Application;

            Autodesk.Gis.Map.ImportExport.Exporter exporter = mapApp.Exporter;

            using (Transaction tx = localDb.TransactionManager.StartTransaction())
            {
                string logFileName = @"C:\1\DRI\0371-1158 - Gentofte Fase 4 - Dokumenter\02 Ekstern\" +
                                     @"01 Gældende tegninger\01 GIS input\02 Trace shape\export.log";

                try
                {
                    string fileName    = localDb.OriginalFileName;
                    string phaseNumber = "";

                    Regex regex = new Regex(@"(?<number>\d.\d)(?<extension>\.[^.]*$)");

                    if (regex.IsMatch(fileName))
                    {
                        Match match = regex.Match(fileName);
                        phaseNumber = match.Groups["number"].Value;
                        phaseNumber = phaseNumber.Replace(".", "");
                        File.AppendAllLines(logFileName, new string[] { $"{DateTime.Now}: Phase number detected: <{phaseNumber}>." });
                    }
                    else
                    {
                        File.AppendAllLines(logFileName, new string[] { $"{DateTime.Now}: " +
                                                                        $"Detection of phase from filename failed! Aborting export for current file." });
                        tx.Abort();
                        return;
                    }

                    string finalExportFileNameBase = @"C:\1\DRI\0371-1158 - Gentofte Fase 4 - Dokumenter\02 Ekstern\" +
                                                     @"01 Gældende tegninger\01 GIS input\02 Trace shape";
                    string finalExportFileNamePipes  = finalExportFileNameBase + "\\" + phaseNumber + ".shp";
                    string finalExportFileNameBlocks = finalExportFileNameBase + "\\" + phaseNumber + "-komponenter.shp";

                    #region Create GIS Data
                    GisData.creategisdata();
                    #endregion

                    #region Export af rør
                    File.AppendAllLines(logFileName, new string[] { $"{DateTime.Now}: Exporting pipes to {finalExportFileNamePipes}." });

                    HashSet <Polyline> pls  = localDb.HashSetOfType <Polyline>(tx, true);
                    HashSet <Line>     ls   = localDb.HashSetOfType <Line>(tx, true);
                    HashSet <Arc>      arcs = localDb.HashSetOfType <Arc>(tx, true);
                    HashSet <Entity>   ents = new HashSet <Entity>();
                    ents.UnionWith(pls);
                    ents.UnionWith(ls);
                    ents.UnionWith(arcs);
                    //Filter ents for forbidden values
                    ents = ents.Where(x => !DataQa.Gis.ContainsForbiddenValues(x.Layer)).ToHashSet();

                    ObjectIdCollection ids         = new ObjectIdCollection();
                    ObjectIdCollection rejectedIds = new ObjectIdCollection();
                    foreach (Entity ent in ents)
                    {
                        if (ent.Layer.Contains("FJV-TWIN") ||
                            ent.Layer.Contains("FJV-FREM") ||
                            ent.Layer.Contains("FJV-RETUR"))
                        {
                            ids.Add(ent.Id);
                        }
                        else
                        {
                            rejectedIds.Add(ent.Id);
                        }
                    }

                    foreach (ObjectId id in rejectedIds)
                    {
                        File.AppendAllLines(logFileName, new string[]
                                            { $"{DateTime.Now}: PIPEERROR!!! Pipe {id.Handle} has wrong layer: {id.Layer()}" });
                    }

                    File.AppendAllLines(logFileName, new string[] { $"{DateTime.Now}: {ids.Count} pipe(s) found for export." });

                    exporter.Init("SHP", finalExportFileNamePipes);
                    exporter.SetStorageOptions(
                        Autodesk.Gis.Map.ImportExport.StorageType.FileOneEntityType,
                        Autodesk.Gis.Map.ImportExport.GeometryType.Line, null);
                    exporter.SetSelectionSet(ids);
                    Autodesk.Gis.Map.ImportExport.ExpressionTargetCollection mappings =
                        exporter.GetExportDataMappings();
                    mappings.Add(":Serie@Pipes", "Serie");
                    mappings.Add(":System@Pipes", "System");
                    mappings.Add(":DN@Pipes", "DN");
                    exporter.SetExportDataMappings(mappings);

                    File.AppendAllLines(logFileName, new string[] { $"{DateTime.Now}: Starting pipes export." });
                    exporter.Export(true);
                    File.AppendAllLines(logFileName, new string[] { $"{DateTime.Now}: Exporting of pipes completed!" });
                    #endregion

                    #region Export af komponenter
                    File.AppendAllLines(logFileName, new string[] { $"{DateTime.Now}: Exporting components to {finalExportFileNameBlocks}." });
                    System.Data.DataTable fjvKomponenter = CsvReader.ReadCsvToDataTable(
                        @"C:\1\DRI\AutoCAD DRI - 01 Civil 3D\FJV Komponenter.csv", "FjvKomponenter");
                    System.Data.DataTable fjvKompDyn = CsvReader.ReadCsvToDataTable(
                        @"C:\1\DRI\AutoCAD DRI - 01 Civil 3D\FJV Dynamiske Komponenter.csv", "FjvKomponenter");
                    ObjectIdCollection allBlockIds = new ObjectIdCollection();

                    #region Gather ordinary blocks
                    BlockTable bt = tx.GetObject(localDb.BlockTableId, OpenMode.ForRead) as BlockTable;
                    foreach (ObjectId oid in bt)
                    {
                        BlockTableRecord btr = tx.GetObject(oid, OpenMode.ForRead) as BlockTableRecord;
                        if (btr.GetBlockReferenceIds(true, true).Count == 0)
                        {
                            continue;
                        }

                        if (ReadStringParameterFromDataTable(btr.Name, fjvKomponenter, "Navn", 0) != null)
                        {
                            ObjectIdCollection blkIds = btr.GetBlockReferenceIds(true, true);
                            foreach (ObjectId blkId in blkIds)
                            {
                                allBlockIds.Add(blkId);
                            }
                        }
                    }
                    #endregion

                    #region Gather dynamic blocks
                    HashSet <BlockReference> brSet = localDb.HashSetOfType <BlockReference>(tx);
                    foreach (BlockReference br in brSet)
                    {
                        if (br.IsDynamicBlock)
                        {
                            string realName = ((BlockTableRecord)tx.GetObject(br.DynamicBlockTableRecord, OpenMode.ForRead)).Name;
                            if (ReadStringParameterFromDataTable(realName, fjvKompDyn, "Navn", 0) != null)
                            {
                                allBlockIds.Add(br.ObjectId);
                            }
                        }
                    }
                    #endregion
                    File.AppendAllLines(logFileName, new string[] { $"{DateTime.Now}: {allBlockIds.Count} block(s) found for export." });

                    #region QA block export
                    HashSet <string> blockNamesInModel = new HashSet <string>();
                    foreach (BlockReference br in brSet)
                    {
                        if (br.IsDynamicBlock)
                        {
                            blockNamesInModel.Add(((BlockTableRecord)tx.GetObject(br.DynamicBlockTableRecord, OpenMode.ForRead)).Name);
                        }
                        else
                        {
                            blockNamesInModel.Add(br.Name);
                        }
                    }

                    HashSet <string> blockNamesGathered = new HashSet <string>();
                    foreach (ObjectId oid in allBlockIds)
                    {
                        BlockReference br = oid.Go <BlockReference>(tx);
                        if (br.IsDynamicBlock)
                        {
                            blockNamesGathered.Add(((BlockTableRecord)tx.GetObject(br.DynamicBlockTableRecord, OpenMode.ForRead)).Name);
                        }
                        else
                        {
                            blockNamesGathered.Add(br.Name);
                        }
                    }

                    var query = blockNamesInModel.Where(x => !blockNamesGathered.Contains(x));
                    foreach (string name in query)
                    {
                        File.AppendAllLines(logFileName, new string[] { $"{DateTime.Now}: BLOCKERROR!!!: Block named {name} not included in export!" });
                    }
                    #endregion

                    #region Export components
                    int i = 1;
                    exporter.Init("SHP", finalExportFileNameBlocks);
                    exporter.SetStorageOptions(
                        Autodesk.Gis.Map.ImportExport.StorageType.FileOneEntityType,
                        Autodesk.Gis.Map.ImportExport.GeometryType.Point, null);
                    exporter.SetSelectionSet(allBlockIds);
                    Autodesk.Gis.Map.ImportExport.ExpressionTargetCollection mappingsForBlocks =
                        exporter.GetExportDataMappings();
                    mappings.Add(":BlockName@Components", "BlockName");
                    mappings.Add(":Type@Components", "Type");
                    mappings.Add(":Rotation@Components", "Rotation");
                    // mappings.Add(":System@Components", "System");
                    mappings.Add(":DN1@Components", "DN1");
                    mappings.Add(":DN2@Components", "DN2");
                    //mappings.Add(":Serie@Components", "Serie");
                    exporter.SetExportDataMappings(mappings);


                    File.AppendAllLines(logFileName, new string[] { $"{DateTime.Now}: Starting blocks export." });
                    exporter.Export(true);
                    File.AppendAllLines(logFileName, new string[] { $"{DateTime.Now}: Exporting of blocks complete." });
                    #endregion

                    #endregion
                }
                catch (MapImportExportException mex)
                {
                    tx.Abort();
                    File.AppendAllLines(logFileName, new string[] { $"{DateTime.Now}: EXCEPTION!!! Message: {mex.Message}. Aborting export of current file!" });
                    editor.WriteMessage("\n" + mex.Message);
                    return;
                }
                catch (System.Exception ex)
                {
                    tx.Abort();
                    File.AppendAllLines(logFileName, new string[] { $"{DateTime.Now}: EXCEPTION!!! Message: {ex.Message}. Aborting export of current file!" });
                    editor.WriteMessage("\n" + ex.Message);
                    return;
                }
                tx.Abort();
            }
        }
        /// <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);
                }
            }
        }
示例#28
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)