/// <summary>
        /// Renders a Point feature layer using a single symbol.
        /// </summary>
        /// <remarks>
        /// ![Simple Renderer for Point features](http://Esri.github.io/arcgis-pro-sdk/images/Renderers/simple-point.png)
        /// </remarks>
        /// <returns>
        /// </returns>
        internal static Task SimpleRendererPoint()
        {
            //Check feature layer name
            //Code works with the USDemographics feature layer available with the ArcGIS Pro SDK Sample data
            var featureLayer = MapView.Active.Map.GetLayersAsFlattenedList().OfType <FeatureLayer>().FirstOrDefault(f => f.ShapeType == esriGeometryType.esriGeometryPoint);

            if (featureLayer == null)
            {
                MessageBox.Show("This renderer works with a point feature layer", "Data missing");
                return(Task.FromResult(0));
            }
            return(QueuedTask.Run(() =>
            {
                //Create a circle marker
                var pointSymbol = SymbolFactory.Instance.ConstructPointSymbol(ColorFactory.Instance.RedRGB, 8, SimpleMarkerStyle.Circle);

                //Get the layer's current renderer
                CIMSimpleRenderer renderer = featureLayer.GetRenderer() as CIMSimpleRenderer;

                //Update the symbol of the current simple renderer
                renderer.Symbol = pointSymbol.MakeSymbolReference();

                //Update the feature layer renderer
                featureLayer.SetRenderer(renderer);
            }));
        }
        /// <summary>
        /// Renders a Line feature layer using a single symbol.
        /// </summary>
        /// <remarks>
        /// ![Simple Renderer for Line features](http://Esri.github.io/arcgis-pro-sdk/images/Renderers/simple-line.png)
        /// </remarks>
        /// <returns>
        /// </returns>
        internal static Task SimpleRendererLine()
        {
            //Check feature layer name
            //Code works with the USDemographics feature layer available with the ArcGIS Pro SDK Sample data
            var featureLayer = MapView.Active.Map.GetLayersAsFlattenedList().OfType <FeatureLayer>().FirstOrDefault(f => f.Name == "U.S. National Transportation Atlas Interstate Highways");

            if (featureLayer == null)
            {
                MessageBox.Show("This renderer works with the U.S. National Transportation Atlas Interstate Highways feature layer available with the ArcGIS Pro SDK Sample data", "Data missing");
                return(Task.FromResult(0));
            }
            return(QueuedTask.Run(() =>
            {
                //Create a circle marker
                var lineSymbol = SymbolFactory.Instance.ConstructLineSymbol(ColorFactory.Instance.RedRGB, 2, SimpleLineStyle.DashDotDot);

                //Get the layer's current renderer
                CIMSimpleRenderer renderer = featureLayer.GetRenderer() as CIMSimpleRenderer;

                //Update the symbol of the current simple renderer
                renderer.Symbol = lineSymbol.MakeSymbolReference();

                //Update the feature layer renderer
                featureLayer.SetRenderer(renderer);
            }));
        }
        /// <summary>
        /// Renders a Polygon feature layer using a single symbol.
        /// </summary>
        /// <remarks>
        /// ![Simple Renderer for Polygon features](http://Esri.github.io/arcgis-pro-sdk/images/Renderers/simple-polygon.png)
        /// </remarks>
        /// <returns>
        /// </returns>
        internal static Task SimpleRendererPolygon()
        {
            //Check feature layer name
            //Code works with the USDemographics feature layer available with the ArcGIS Pro SDK Sample data
            var featureLayer = MapView.Active.Map.GetLayersAsFlattenedList().OfType <FeatureLayer>().FirstOrDefault(f => f.Name == "USDemographics");

            if (featureLayer == null)
            {
                MessageBox.Show("This renderer works with the USDemographics feature layer available with the ArcGIS Pro SDK Sample data", "Data missing");
                return(Task.FromResult(0));
            }
            return(QueuedTask.Run(() =>
            {
                //Creating a polygon with a red fill and blue outline.
                CIMStroke outline = SymbolFactory.Instance.ConstructStroke(
                    ColorFactory.Instance.BlueRGB, 2.0, SimpleLineStyle.Solid);
                CIMPolygonSymbol fillWithOutline = SymbolFactory.Instance.ConstructPolygonSymbol(
                    ColorFactory.Instance.CreateRGBColor(255, 190, 190), SimpleFillStyle.Solid, outline);
                //Get the layer's current renderer
                CIMSimpleRenderer renderer = featureLayer.GetRenderer() as CIMSimpleRenderer;

                //Update the symbol of the current simple renderer
                renderer.Symbol = fillWithOutline.MakeSymbolReference();

                //Update the feature layer renderer
                featureLayer.SetRenderer(renderer);
            }));
        }
        //Create a CIMSymbol from style item selected in the results gallery list box and
        //apply this newly created symbol to the feature layer currently selected in Contents pane
        private async void ApplyTheSelectedSymbol(StyleItem selectedStyleItemToApply)
        {
            if (selectedStyleItemToApply == null || string.IsNullOrEmpty(selectedStyleItemToApply.Key))
            {
                return;
            }

            await QueuedTask.Run(() =>
            {
                //Get the feature layer currently selected in the Contents pane
                FeatureLayer ftrLayer = MappingModule.ActiveTOC.MostRecentlySelectedLayer as FeatureLayer;

                if (ftrLayer == null)
                {
                    return;
                }

                //Create symbol from style item.
                CIMSymbol symbolFromStyleItem = selectedStyleItemToApply.GetObject() as CIMSymbol;

                //Set real world setting for created symbol = feature layer's setting
                //so that there isn't a mismatch between symbol and feature layer
                SymbolBuilder.SetRealWorldUnits(symbolFromStyleItem, ftrLayer.UsesRealWorldSymbolSizes);

                //Get simple renderer from feature layer
                CIMSimpleRenderer currentRenderer = ftrLayer.GetRenderer() as CIMSimpleRenderer;

                //Set current renderer's symbol reference = symbol reference of the newly created symbol
                currentRenderer.Symbol = SymbolBuilder.MakeSymbolReference(symbolFromStyleItem);

                //Update feature layer renderer with new symbol
                ftrLayer.SetRenderer(currentRenderer);
            });
        }
        // Map Authoring Snippet
        private Task ApplySymbolToFeatureLayerAsync(FeatureLayer featureLayer, string symbolName)
        {
            return(QueuedTask.Run(async() =>
            {
                //Get the ArcGIS 2D System style from the Project
                var arcGIS3DStyle = Project.Current.GetItems <StyleProjectItem>().FirstOrDefault(s => s.Name == "Sample 3D Models");

                //Search for the symbolName style items within the ArcGIS 2D style project item.
                var items = await QueuedTask.Run(() => arcGIS3DStyle.SearchSymbols(StyleItemType.PointSymbol, symbolName));

                //Gets the CIMSymbol
                CIMSymbol symbol = items.FirstOrDefault().Symbol;

                //Get the renderer of the point feature layer
                CIMSimpleRenderer renderer = featureLayer.GetRenderer() as CIMSimpleRenderer;

                //Set symbol's real world setting to be the same as that of the feature layer
                symbol.SetRealWorldUnits(featureLayer.UsesRealWorldSymbolSizes);

                //Apply the symbol to the feature layer's current renderer
                renderer.Symbol = symbol.MakeSymbolReference();
                try
                {
                    //Appy the renderer to the feature layer
                    featureLayer.SetRenderer(renderer);
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error in ApplySymbolToFeatureLayerAsync:  " + ex.ToString(), "Error");
                }
            }));
        }
        public Task SetFeatureLayerSymbolFromStyleItemAsync(FeatureLayer ftrLayer, SymbolStyleItem symbolItem)
        {
            if (ftrLayer == null || symbolItem == null)
            {
                throw new System.ArgumentNullException();
            }

            return(QueuedTask.Run(() =>
            {
                //Get simple renderer from the feature layer
                CIMSimpleRenderer currentRenderer = ftrLayer.GetRenderer() as CIMSimpleRenderer;
                if (currentRenderer == null)
                {
                    return;
                }
                //Get symbol from the SymbolStyleItem
                CIMSymbol symbol = symbolItem.Symbol;

                //Set symbol's real world setting to be the same as that of the feature layer
                symbol.SetRealWorldUnits(ftrLayer.UsesRealWorldSymbolSizes);

                //Update the symbol of the current simple renderer
                currentRenderer.Symbol = symbol.MakeSymbolReference();
                //Update the feature layer renderer
                ftrLayer.SetRenderer(currentRenderer);
            }));
        }
Exemple #7
0
        private static async Task CreateFeatures(List <MapPoint> mapPointList)
        {
            RowBuffer rowBuffer = null;

            try
            {
                await QueuedTask.Run(() =>
                {
                    var layer = MapView.Active.GetSelectedLayers()[0];
                    if (layer is FeatureLayer)
                    {
                        var featureLayer = layer as FeatureLayer;

                        using (var table = featureLayer.GetTable())
                        {
                            TableDefinition definition = table.GetDefinition();
                            int shapeIndex             = definition.FindField("Shape");

                            foreach (var point in mapPointList)
                            {
                                rowBuffer = table.CreateRowBuffer();

                                rowBuffer[shapeIndex] = new MapPointBuilder(point).ToGeometry();

                                Row row = table.CreateRow(rowBuffer);
                            }
                        }

                        //Get simple renderer from feature layer
                        CIMSimpleRenderer currentRenderer = featureLayer.GetRenderer() as CIMSimpleRenderer;
                        CIMSymbolReference sybmol         = currentRenderer.Symbol;

                        //var outline = SymbolFactory.ConstructStroke(ColorFactory.RedRGB, 1.0, SimpleLineStyle.Solid);
                        //var s = SymbolFactory.ConstructPolygonSymbol(ColorFactory.RedRGB, SimpleFillStyle.Null, outline);
                        var s = SymbolFactory.ConstructPointSymbol(ColorFactory.RedRGB, 3.0);
                        CIMSymbolReference symbolRef = new CIMSymbolReference()
                        {
                            Symbol = s
                        };
                        currentRenderer.Symbol = symbolRef;

                        featureLayer.SetRenderer(currentRenderer);
                    }
                });
            }
            catch (GeodatabaseException exObj)
            {
                Console.WriteLine(exObj);
                throw;
            }
            finally
            {
                if (rowBuffer != null)
                {
                    rowBuffer.Dispose();
                }
            }
        }
Exemple #8
0
        public static void MakeLinesLayer(Map mapView)
        {
            try
            {
                // Create the "Sewer Lines" object.
                var lines = mapView.GetLayersAsFlattenedList().OfType <FeatureLayer>().FirstOrDefault(s => s.Name == "Sewer Lines");

                //Get the selected features from the map.
                var linesOIDList = lines.GetSelection().GetObjectIDs();                 // Gets a list of Object IDs
                var linesOID     = lines.GetTable().GetDefinition().GetObjectIDField(); // Gets the OBJECTID field name for the def query

                // Check to see if there are sewer lines features selected inthe map.
                if (linesOIDList.Count() == 0)
                {
                    MessageBox.Show("There are no sewer lines selected.");
                }

                else
                {
                    //Create the defenition query
                    string defQuery = $"{linesOID} in ({string.Join(",", linesOIDList)})";
                    string url      = @"O:\SHARE\405 - INFORMATION SERVICES\GIS_Layers\[email protected]\SDE.SEWERMAN.SEWERS_VIEW";

                    // Create the Uri object create the feature layer.
                    Uri uri            = new Uri(url);
                    var selectionLayer = LayerFactory.Instance.CreateFeatureLayer(uri, mapView, 0, "Sewer Lines SELECTION");

                    // Apply the definition query
                    selectionLayer.SetDefinitionQuery(defQuery);

                    // Create the line symbol renderer.
                    CIMLineSymbol lineSymbol = SymbolFactory.Instance.ConstructLineSymbol(
                        ColorFactory.Instance.RedRGB,
                        3.0,
                        SimpleLineStyle.Solid
                        );
                    CIMSimpleRenderer renderer = selectionLayer.GetRenderer() as CIMSimpleRenderer;

                    // Reference the existing renderer
                    renderer.Symbol = lineSymbol.MakeSymbolReference();
                    // Apply the new renderer
                    selectionLayer.SetRenderer(renderer);
                }
            }

            catch (Exception ex)
            {
                SysModule.LogError(ex.Message, ex.StackTrace);

                string caption = "Error Occurred";
                string message = "Process failed. \nSave and restart ArcGIS Pro and try process again.\n" +
                                 "If problem persist, contact your GIS Admin.";

                //Using the ArcGIS Pro SDK MessageBox class
                MessageBox.Show(message, caption);
            }
        }
Exemple #9
0
        public static void MakeManholesLayer(Map mapView)
        {
            try
            {
                // Create the "Manholes"  layer object.
                var mh = mapView.GetLayersAsFlattenedList().OfType <FeatureLayer>().FirstOrDefault(s => s.Name == "Manholes");

                //Get the selected features from the map.
                var mhOIDList = mh.GetSelection().GetObjectIDs();                 // Gets a list of Object IDs
                var mhOID     = mh.GetTable().GetDefinition().GetObjectIDField(); // Gets the OBJECTID field name for the def query

                // Check to see if there are manhole features selected in the map.
                if (mhOIDList.Count() == 0)
                {
                    MessageBox.Show("There are no manholes selected.", "Warning");
                }

                else
                {
                    // Create the defenition query
                    string defQuery = $"{mhOID} in ({string.Join(",", mhOIDList)})";
                    string url      = @"O:\SHARE\405 - INFORMATION SERVICES\GIS_Layers\[email protected]\SDE.SEWERMAN.MANHOLES_VIEW";

                    // Create the Uri object create the feature layer.
                    Uri uri            = new Uri(url);
                    var selectionLayer = LayerFactory.Instance.CreateFeatureLayer(uri, mapView, 0, "Manholes SELECTION");

                    // Apply the definition query
                    selectionLayer.SetDefinitionQuery(defQuery);

                    // Create the point symbol renderer.
                    CIMPointSymbol pointSymbol = SymbolFactory.Instance.ConstructPointSymbol(
                        ColorFactory.Instance.GreenRGB,
                        8.0,
                        SimpleMarkerStyle.Circle
                        );
                    CIMSimpleRenderer renderer = selectionLayer.GetRenderer() as CIMSimpleRenderer;
                    // Reference the existing renderer
                    renderer.Symbol = pointSymbol.MakeSymbolReference();
                    // Apply new renderer
                    selectionLayer.SetRenderer(renderer);
                }
            }

            catch (Exception ex)
            {
                string caption = "Module1.MakeManholesLayer method failed!";
                string message = "Process failed. \n\nSave and restart ArcGIS Pro and try process again.\n\n" +
                                 $"If problem persist, contact your local GIS nerd.\n\n{ex}";

                //Using the ArcGIS Pro SDK MessageBox class
                MessageBox.Show(message, caption);
            }
        }
Exemple #10
0
        internal async void ApplyRulePackage()
        {
            await DownloadRulePackage(SelectedRulePackage);  //Download the rule package selected.

            await QueuedTask.Run(async() =>
            {
                //Get the build footprint layer's current renderer.
                CIMSimpleRenderer renderer = (CIMSimpleRenderer)Module1.BuildingFootprintLayer.GetRenderer();

                if (renderer == null)
                {
                    return;
                }
                //Get the rule package attributes and mapping to Feature layer from the dictionary
                var attributeExpressionMapping =
                    SelectedRulePackage.RpkAttributeExpressionMapping[SelectedRulePackage.Title];

                //Create the array of CIMPrimitiveOverrides. This is where the field\attribute mapping for the rulepackage is done.
                var primitiveOverrides = attributeExpressionMapping.Select(kvp => new CIMPrimitiveOverride
                {
                    PrimitiveName = SelectedRulePackage.Title,
                    PropertyName  = kvp.Key,
                    Expression    = kvp.Value
                }).ToArray();

                //Full path of the rule package path
                var rulePkgPath = Path.Combine(_rulePkgPath, SelectedRulePackage.Name);

                //Creating a procedural symbol using the rulepackage
                var symbolReference = SymbolFactory.Instance.ConstructProceduralSymbol(rulePkgPath,
                                                                                       Module1.BuildingFootprintLayer, primitiveOverrides);

                //CIMPolygonSymbol needed to create a style item.
                CIMPolygonSymbol polygonSymbol = symbolReference.Symbol as CIMPolygonSymbol;

                //Set symbol's real world setting to be the same as that of the feature layer
                polygonSymbol.SetRealWorldUnits(Module1.BuildingFootprintLayer.UsesRealWorldSymbolSizes);

                //Set the current renderer to the new procedural symbol's CIMSymbolReference
                renderer.Symbol = polygonSymbol.MakeSymbolReference();

                //Set the Building footprint layer's render.
                Module1.BuildingFootprintLayer.SetRenderer(renderer);

                //Create a style project item.
                await CreateStyleItem();

                if (BuildingStyleProjectItem != null && !BuildingStyleProjectItem.IsReadOnly)
                {
                    await AddStyleItemToStyle(BuildingStyleProjectItem, polygonSymbol); //Building footprint's procedural symbol is added to the BuildingStyle
                }
            });
        }
Exemple #11
0
        /// <summary>
        /// Renders a Point feature layer using a single symbol.
        /// </summary>
        /// <remarks>
        /// ![Simple Renderer for Point features](http://Esri.github.io/arcgis-pro-sdk/images/Renderers/simple-point.png)
        /// </remarks>
        /// <param name="featureLayer"></param>
        /// <returns>
        /// </returns>
        internal async static Task SimpleRendererPoint(FeatureLayer featureLayer)
        {
            await QueuedTask.Run(() =>
            {
                //Create a circle marker
                var pointSymbol = SymbolFactory.Instance.ConstructPointSymbol(ColorFactory.Instance.RedRGB, 8, SimpleMarkerStyle.Circle);

                //Get the layer's current renderer
                CIMSimpleRenderer renderer = featureLayer.GetRenderer() as CIMSimpleRenderer;

                //Update the symbol of the current simple renderer
                renderer.Symbol = pointSymbol.MakeSymbolReference();

                //Update the feature layer renderer
                featureLayer.SetRenderer(renderer);
            });
        }
        /// <summary>
        /// Renders a Line feature layer using a single symbol.
        /// </summary>
        /// <remarks>
        /// ![Simple Renderer for Line features](http://Esri.github.io/arcgis-pro-sdk/images/Renderers/simple-line.png)
        /// </remarks>
        /// <param name="featureLayer"></param>
        /// <returns>
        /// </returns>
        internal static Task SimpleRendererLine(FeatureLayer featureLayer)
        {
            return(QueuedTask.Run(() =>
            {
                //Create a circle marker
                var lineSymbol = SymbolFactory.Instance.ConstructLineSymbol(ColorFactory.Instance.RedRGB, 2, SimpleLineStyle.DashDotDot);

                //Get the layer's current renderer
                CIMSimpleRenderer renderer = featureLayer.GetRenderer() as CIMSimpleRenderer;

                //Update the symbol of the current simple renderer
                renderer.Symbol = lineSymbol.MakeSymbolReference();

                //Update the feature layer renderer
                featureLayer.SetRenderer(renderer);
            }));
        }
Exemple #13
0
        /// <summary>
        /// Renders a Polygon feature layer using a single symbol.
        /// </summary>
        /// <remarks>
        /// ![Simple Renderer for Polygon features](http://Esri.github.io/arcgis-pro-sdk/images/Renderers/simple-polygon.png)
        /// </remarks>
        /// <param name="featureLayer"></param>
        /// <returns>
        /// </returns>
        internal async static Task SimpleRendererPolygon(FeatureLayer featureLayer)
        {
            await QueuedTask.Run(() =>
            {
                //Creating a polygon with a red fill and blue outline.
                CIMStroke outline = SymbolFactory.Instance.ConstructStroke(
                    ColorFactory.Instance.BlueRGB, 2.0, SimpleLineStyle.Solid);
                CIMPolygonSymbol fillWithOutline = SymbolFactory.Instance.ConstructPolygonSymbol(
                    ColorFactory.Instance.CreateRGBColor(255, 190, 190), SimpleFillStyle.Solid, outline);
                //Get the layer's current renderer
                CIMSimpleRenderer renderer = featureLayer.GetRenderer() as CIMSimpleRenderer;

                //Update the symbol of the current simple renderer
                renderer.Symbol = fillWithOutline.MakeSymbolReference();

                //Update the feature layer renderer
                featureLayer.SetRenderer(renderer);
            });
        }
Exemple #14
0
 internal static Task SimpleRendererLine(FeatureLayer featureLayer, String lineStyle)
 {
     return(QueuedTask.Run(() =>
     {
         //Create a circle marker
         if (lineStyle == "Dash")
         {
             var lineSymbol = SymbolFactory.Instance.ConstructLineSymbol(ColorFactory.Instance.BlueRGB, 3, SimpleLineStyle.Dash);
             CIMSimpleRenderer renderer = featureLayer.GetRenderer() as CIMSimpleRenderer;
             renderer.Symbol = lineSymbol.MakeSymbolReference();
             featureLayer.SetRenderer(renderer);
         }
         else if (lineStyle == "Dot")
         {
             var lineSymbol = SymbolFactory.Instance.ConstructLineSymbol(ColorFactory.Instance.BlueRGB, 3, SimpleLineStyle.Dot);
             CIMSimpleRenderer renderer = featureLayer.GetRenderer() as CIMSimpleRenderer;
             renderer.Symbol = lineSymbol.MakeSymbolReference();
             featureLayer.SetRenderer(renderer);
         }
         else if (lineStyle == "DashDot")
         {
             var lineSymbol = SymbolFactory.Instance.ConstructLineSymbol(ColorFactory.Instance.BlueRGB, 3, SimpleLineStyle.DashDot);
             CIMSimpleRenderer renderer = featureLayer.GetRenderer() as CIMSimpleRenderer;
             renderer.Symbol = lineSymbol.MakeSymbolReference();
             featureLayer.SetRenderer(renderer);
         }
         else if (lineStyle == "DashDotDot")
         {
             var lineSymbol = SymbolFactory.Instance.ConstructLineSymbol(ColorFactory.Instance.BlueRGB, 3, SimpleLineStyle.DashDotDot);
             CIMSimpleRenderer renderer = featureLayer.GetRenderer() as CIMSimpleRenderer;
             renderer.Symbol = lineSymbol.MakeSymbolReference();
             featureLayer.SetRenderer(renderer);
         }
         else if (lineStyle == "Solid")
         {
             var lineSymbol = SymbolFactory.Instance.ConstructLineSymbol(ColorFactory.Instance.BlueRGB, 3, SimpleLineStyle.Solid);
             CIMSimpleRenderer renderer = featureLayer.GetRenderer() as CIMSimpleRenderer;
             renderer.Symbol = lineSymbol.MakeSymbolReference();
             featureLayer.SetRenderer(renderer);
         }
     }));
 }
Exemple #15
0
        // Methods to create the selection layers.
        public static void MakeSewersLayers(Map mapView)
        {
            try
            {
                var mh    = mapView.GetLayersAsFlattenedList().OfType <FeatureLayer>().FirstOrDefault(s => s.Name == "Manholes");
                var lines = mapView.GetLayersAsFlattenedList().OfType <FeatureLayer>().FirstOrDefault(s => s.Name == "Sewer Lines");

                //Get the selected features from the map.
                var mhOIDList    = mh.GetSelection().GetObjectIDs();                 // Gets a list of Object IDs
                var mhOID        = mh.GetTable().GetDefinition().GetObjectIDField(); // Gets the OBJECTID field name for the def query
                var linesOIDList = lines.GetSelection().GetObjectIDs();
                var linesOID     = lines.GetTable().GetDefinition().GetObjectIDField();

                //Check to see if there are mmanhole or sewer line features selected in map.
                if (mhOIDList.Count() == 0 && linesOIDList.Count() == 0)
                {
                    MessageBox.Show("Manholes & Sewers contain no selected features.", "Warning");
                }

                else if (mhOIDList.Count() == 0 && linesOIDList.Count() > 0)
                {
                    MessageBox.Show("Manholes layer contains no selected features.", "Warning");
                }

                else if (mhOIDList.Count() > 0 && linesOIDList.Count() == 0)
                {
                    MessageBox.Show("Sewer Lines layer contains no selected features.", "Warning");
                }

                else
                {
                    // CREATE THE SEWER LINES SELECTION LAYER
                    // Create the defenition query
                    string linesDefQuery = $"{linesOID} in ({string.Join(",", linesOIDList)})";
                    string linesURL      = @"O:\SHARE\405 - INFORMATION SERVICES\GIS_Layers\[email protected]\SDE.SEWERMAN.SEWERS_VIEW";

                    // Create the Uri object create the feature layer.
                    Uri linesURI      = new Uri(linesURL);
                    var linesSelLayer = LayerFactory.Instance.CreateFeatureLayer(linesURI, mapView, 0, "Sewer Lines SELECTION");

                    // Apply the definition query
                    linesSelLayer.SetDefinitionQuery(linesDefQuery);

                    // Create the line symbol renderer.
                    CIMLineSymbol lineSymbol = SymbolFactory.Instance.ConstructLineSymbol(
                        ColorFactory.Instance.RedRGB,
                        3.0,
                        SimpleLineStyle.Solid
                        );
                    CIMSimpleRenderer lineRenderer = linesSelLayer.GetRenderer() as CIMSimpleRenderer;

                    // Renference the existing renderer
                    lineRenderer.Symbol = lineSymbol.MakeSymbolReference();
                    // Apply the new renderer
                    linesSelLayer.SetRenderer(lineRenderer);


                    // CREATE THE MANHOLES SELECTION LAYER
                    // Create the defenition query
                    string mhDefQuery = $"{mhOID} in ({string.Join(",", mhOIDList)})";
                    string mhURL      = @"O:\SHARE\405 - INFORMATION SERVICES\GIS_Layers\[email protected]\SDE.SEWERMAN.MANHOLES_VIEW";

                    // Create the Uri object create the feature layer.
                    Uri mhURI      = new Uri(mhURL);
                    var mhSelLayer = LayerFactory.Instance.CreateFeatureLayer(mhURI, mapView, 0, "Manholes SELECTION");

                    // Apply the definition query
                    mhSelLayer.SetDefinitionQuery(mhDefQuery);

                    // Create the point symbol renderer.
                    CIMPointSymbol pointSymbol = SymbolFactory.Instance.ConstructPointSymbol(
                        ColorFactory.Instance.GreenRGB,
                        8.0,
                        SimpleMarkerStyle.Circle
                        );
                    CIMSimpleRenderer pointRenderer = mhSelLayer.GetRenderer() as CIMSimpleRenderer;

                    // Renference the existing renderer
                    pointRenderer.Symbol = pointSymbol.MakeSymbolReference();
                    // Apply the new renderer
                    mhSelLayer.SetRenderer(pointRenderer);
                }
            }

            catch (Exception ex)
            {
                string caption = "Module1.MakeSewersLayers method failed!";
                string message = "Process failed. \n\nSave and restart ArcGIS Pro and try process again.\n\n" +
                                 $"If problem persist, contact your local GIS nerd.\n\n{ex}";

                //Using the ArcGIS Pro SDK MessageBox class
                MessageBox.Show(message, caption);
            }
        }
Exemple #16
0
        public void btnChangeRoomSymbology(object sender, EventArgs e)
        {
            var polygonSymbology = ((RadioButton)sender).Tag;

            QueuedTask.Run(() =>
            {
                //Get the active map's definition - CIMMap.

                if (polygonSymbology.ToString() == "None")
                {
                    var cimMap = MapView.Active.Map.GetDefinition();
                    //FeatureLayer a = MapView.Active.Map.Layers[1] as FeatureLayer;
                    var lyr = MapView.Active.Map.GetLayersAsFlattenedList().OfType <FeatureLayer>().FirstOrDefault(s => s.ShapeType == esriGeometryType.esriGeometryPolygon);
                    CIMSimpleRenderer renderer = lyr.GetRenderer() as CIMSimpleRenderer;
                    CIMStroke outline          = SymbolFactory.Instance.ConstructStroke(
                        ColorFactory.Instance.GreyRGB, 0.5, SimpleLineStyle.Solid);
                    CIMPolygonSymbol fillWithOutline = SymbolFactory.Instance.ConstructPolygonSymbol(
                        ColorFactory.Instance.CreateRGBColor(255, 255, 255), SimpleFillStyle.Solid, outline);
                    //Update the symbol of the current simple renderer
                    renderer.Symbol = fillWithOutline.MakeSymbolReference();
                    //Update the feature layer renderer
                    lyr.SetRenderer(renderer);
                }
                if (polygonSymbology.ToString() == "Multicolor1")
                {
                    Debug.WriteLine("Multicolor1");
                    var cimMap = MapView.Active.Map.GetDefinition();
                    //FeatureLayer a = MapView.Active.Map.Layers[1] as FeatureLayer;
                    var lyr = MapView.Active.Map.GetLayersAsFlattenedList().OfType <FeatureLayer>().FirstOrDefault(s => s.ShapeType == esriGeometryType.esriGeometryPolygon);
                    CIMUniqueValueRenderer renderer = lyr.GetRenderer() as CIMUniqueValueRenderer;

                    // color ramp
                    CIMICCColorSpace colorSpace = new CIMICCColorSpace()
                    {
                        URL = "Default RGB"
                    };

                    CIMRandomHSVColorRamp randomHSVColorRamp = new CIMRandomHSVColorRamp()
                    {
                        ColorSpace = colorSpace,
                        MinAlpha   = 100,
                        MaxAlpha   = 100,
                        MinH       = 0,
                        MaxH       = 360,
                        MinS       = 15,
                        MaxS       = 30,
                        MinV       = 99,
                        MaxV       = 100,
                        Seed       = 0
                    };

                    UniqueValueRendererDefinition uvr = new UniqueValueRendererDefinition()
                    {
                        ValueFields = new string[] { "RMAREA" }, //multiple fields in the array if needed.
                        ColorRamp   = randomHSVColorRamp         //Specify color ramp
                    };

                    var r = lyr.CreateRenderer(uvr);
                    lyr.SetRenderer(r);
                }
                if (polygonSymbology.ToString() == "Beige")
                {
                    var cimMap = MapView.Active.Map.GetDefinition();
                    //FeatureLayer a = MapView.Active.Map.Layers[1] as FeatureLayer;
                    var lyr = MapView.Active.Map.GetLayersAsFlattenedList().OfType <FeatureLayer>().FirstOrDefault(s => s.ShapeType == esriGeometryType.esriGeometryPolygon);
                    //CIMSimpleRenderer renderer = lyr.GetRenderer() as CIMSimpleRenderer;
                    CIMSimpleRenderer renderer = new CIMSimpleRenderer()
                    {
                    };
                    CIMStroke outline = SymbolFactory.Instance.ConstructStroke(
                        ColorFactory.Instance.GreyRGB, 0.5, SimpleLineStyle.Solid);
                    CIMPolygonSymbol fillWithOutline = SymbolFactory.Instance.ConstructPolygonSymbol(
                        ColorFactory.Instance.CreateRGBColor(255, 222, 173), SimpleFillStyle.Solid, outline);

                    //Update the symbol of the current simple renderer
                    renderer.Symbol = fillWithOutline.MakeSymbolReference();
                    //Update the feature layer renderer
                    lyr.SetRenderer(renderer);

                    /*
                     *
                     * unique value rendere
                     * internal static Task UniqueValueRenderer(FeatureLayer featureLayer)
                     * {
                     * return QueuedTask.Run(() =>
                     * {
                     * //construct unique value renderer definition
                     * UniqueValueRendererDefinition uvr = new
                     * UniqueValueRendererDefinition()
                     * {
                     * ValueFields = new string[] { SDKHelpers.GetDisplayField(featureLayer) }, //multiple fields in the array if needed.
                     * ColorRamp = SDKHelpers.GetColorRamp(), //Specify color ramp
                     * };
                     *
                     * //Creates a "Renderer"
                     * var cimRenderer = featureLayer.CreateRenderer(uvr);
                     *
                     * //Sets the renderer to the feature layer
                     * featureLayer.SetRenderer(cimRenderer);
                     * });
                     *
                     * }
                     *
                     *
                     * diagonal cross hatch example
                     * public static Task<CIMPolygonSymbol> CreateDiagonalCrossPolygonAsync()
                     * {
                     * return QueuedTask.Run<CIMPolygonSymbol>(() =>
                     * {
                     * var trans = 50.0;//semi transparent
                     * CIMStroke outline = SymbolFactory.Instance.ConstructStroke(CIMColor.CreateRGBColor(0, 0, 0, trans), 2.0, SimpleLineStyle.Solid);
                     *
                     * //Stroke for the fill
                     * var solid = SymbolFactory.Instance.ConstructStroke(CIMColor.CreateRGBColor(255, 0, 0, trans), 1.0, SimpleLineStyle.Solid);
                     *
                     * //Mimic cross hatch
                     * CIMFill[] diagonalCross =
                     * {
                     * new CIMHatchFill() {
                     * Enable = true,
                     * Rotation = 45.0,
                     * Separation = 5.0,
                     * LineSymbol = new CIMLineSymbol() { SymbolLayers = new CIMSymbolLayer[1] { solid } }
                     * },
                     * new CIMHatchFill() {
                     * Enable = true,
                     * Rotation = -45.0,
                     * Separation = 5.0,
                     * LineSymbol = new CIMLineSymbol() { SymbolLayers = new CIMSymbolLayer[1] { solid } }
                     * }
                     * };
                     * List<CIMSymbolLayer> symbolLayers = new List<CIMSymbolLayer>();
                     * symbolLayers.Add(outline);
                     * foreach (var fill in diagonalCross)
                     * symbolLayers.Add(fill);
                     * return new CIMPolygonSymbol() { SymbolLayers = symbolLayers.ToArray() };
                     * });
                     * }
                     */
                }
            });

            Debug.WriteLine(MapView.Active.Map.Layers[0].Name); // .SetLabelVisibility(true);
            Debug.WriteLine(MapView.Active.Map.Layers[1].Name); // .SetLabelVisibility(true);
            //Debug.WriteLine(MapView.Active.Map.SetLabelEngine
        }
        public async Task <string> GenerateGmlAsync()
        {
            MapView            mapView       = MapView.Active;
            Map                map           = mapView?.Map;
            SpatialReference   mapSpatRef    = map?.SpatialReference;
            MySpatialReference myCyclSpatRef = _settings.CycloramaViewerCoordinateSystem;

            SpatialReference cyclSpatRef = (myCyclSpatRef == null)
        ? mapSpatRef
        : (myCyclSpatRef.ArcGisSpatialReference ?? (await myCyclSpatRef.CreateArcGisSpatialReferenceAsync()));

            Unit   unit   = cyclSpatRef?.Unit;
            double factor = unit?.ConversionFactor ?? 1;
            Color  color  = Color.White;
            string result =
                "<wfs:FeatureCollection xmlns:xs=\"http://www.w3.org/2001/XMLSchema\" xmlns:wfs=\"http://www.opengis.net/wfs\" xmlns:gml=\"http://www.opengis.net/gml\">";

            await QueuedTask.Run(async() =>
            {
                SpatialReference layerSpatRef       = Layer.GetSpatialReference();
                IList <IList <Segment> > geometries = new List <IList <Segment> >();
                ICollection <Viewer> viewers        = _viewerList.Viewers;

                foreach (var viewer in viewers)
                {
                    double distance = viewer.OverlayDrawDistance;
                    RecordingLocation recordingLocation = viewer.Location;

                    if (recordingLocation != null)
                    {
                        if (cyclSpatRef?.IsGeographic ?? true)
                        {
                            distance = distance * factor;
                        }
                        else
                        {
                            distance = distance / factor;
                        }

                        double x    = recordingLocation.X;
                        double y    = recordingLocation.Y;
                        double xMin = x - distance;
                        double xMax = x + distance;
                        double yMin = y - distance;
                        double yMax = y + distance;

                        Envelope envelope     = EnvelopeBuilder.CreateEnvelope(xMin, yMin, xMax, yMax, cyclSpatRef);
                        Envelope copyEnvelope = envelope;

                        if (layerSpatRef.Wkid != 0)
                        {
                            ProjectionTransformation projection = ProjectionTransformation.Create(cyclSpatRef, layerSpatRef);
                            copyEnvelope = GeometryEngine.Instance.ProjectEx(envelope, projection) as Envelope;
                        }

                        Polygon copyPolygon = PolygonBuilder.CreatePolygon(copyEnvelope, layerSpatRef);
                        ReadOnlyPartCollection polygonParts = copyPolygon.Parts;
                        IEnumerator <ReadOnlySegmentCollection> polygonSegments = polygonParts.GetEnumerator();
                        IList <Segment> segments = new List <Segment>();

                        while (polygonSegments.MoveNext())
                        {
                            ReadOnlySegmentCollection polygonSegment = polygonSegments.Current;

                            foreach (Segment segment in polygonSegment)
                            {
                                segments.Add(segment);
                            }
                        }

                        geometries.Add(segments);
                    }
                }

                GC.Collect();
                Polygon polygon = PolygonBuilder.CreatePolygon(geometries, layerSpatRef);

                using (FeatureClass featureClass = Layer?.GetFeatureClass())
                {
                    string uri = Layer?.URI;

                    SpatialQueryFilter spatialFilter = new SpatialQueryFilter
                    {
                        FilterGeometry      = polygon,
                        SpatialRelationship = SpatialRelationship.Intersects,
                        SubFields           = "*"
                    };

                    using (RowCursor existsResult = featureClass?.Search(spatialFilter, false))
                    {
                        while (existsResult?.MoveNext() ?? false)
                        {
                            Row row       = existsResult.Current;
                            long objectId = row.GetObjectID();

                            if ((_selection == null) || (!_selection.Contains(objectId)))
                            {
                                Feature feature = row as Feature;
                                var fieldvalues = new Dictionary <string, string> {
                                    { FieldUri, uri }, { FieldObjectId, objectId.ToString() }
                                };

                                Geometry geometry         = feature?.GetShape();
                                GeometryType geometryType = geometry?.GeometryType ?? GeometryType.Unknown;
                                Geometry copyGeometry     = geometry;

                                if ((geometry != null) && (layerSpatRef.Wkid != 0))
                                {
                                    ProjectionTransformation projection = ProjectionTransformation.Create(layerSpatRef, cyclSpatRef);
                                    copyGeometry = GeometryEngine.Instance.ProjectEx(geometry, projection);
                                }

                                if (copyGeometry != null)
                                {
                                    string gml = string.Empty;

                                    switch (geometryType)
                                    {
                                    case GeometryType.Envelope:
                                        break;

                                    case GeometryType.Multipatch:
                                        break;

                                    case GeometryType.Multipoint:
                                        break;

                                    case GeometryType.Point:
                                        MapPoint point = copyGeometry as MapPoint;

                                        if (point != null)
                                        {
                                            gml =
                                                $"<gml:Point {GmlDimension(copyGeometry)}><gml:coordinates>{await GmlPointAsync(point)}</gml:coordinates></gml:Point>";
                                        }

                                        break;

                                    case GeometryType.Polygon:
                                        Polygon polygonGml = copyGeometry as Polygon;

                                        if (polygonGml != null)
                                        {
                                            ReadOnlyPartCollection polygonParts = polygonGml.Parts;
                                            IEnumerator <ReadOnlySegmentCollection> polygonSegments = polygonParts.GetEnumerator();

                                            while (polygonSegments.MoveNext())
                                            {
                                                ReadOnlySegmentCollection segments = polygonSegments.Current;

                                                gml =
                                                    $"{gml}<gml:MultiPolygon><gml:PolygonMember><gml:Polygon {GmlDimension(copyGeometry)}><gml:outerBoundaryIs><gml:LinearRing><gml:coordinates>";

                                                for (int i = 0; i < segments.Count; i++)
                                                {
                                                    if (segments[i].SegmentType == SegmentType.Line)
                                                    {
                                                        MapPoint polygonPoint = segments[i].StartPoint;
                                                        gml = $"{gml}{((i == 0) ? string.Empty : " ")}{await GmlPointAsync(polygonPoint)}";

                                                        if (i == (segments.Count - 1))
                                                        {
                                                            polygonPoint = segments[i].EndPoint;
                                                            gml          = $"{gml} {await GmlPointAsync(polygonPoint)}";
                                                        }
                                                    }
                                                }

                                                gml =
                                                    $"{gml}</gml:coordinates></gml:LinearRing></gml:outerBoundaryIs></gml:Polygon></gml:PolygonMember></gml:MultiPolygon>";
                                            }
                                        }
                                        break;

                                    case GeometryType.Polyline:
                                        Polyline polylineGml = copyGeometry as Polyline;

                                        if (polylineGml != null)
                                        {
                                            ReadOnlyPartCollection polylineParts = polylineGml.Parts;
                                            IEnumerator <ReadOnlySegmentCollection> polylineSegments = polylineParts.GetEnumerator();

                                            while (polylineSegments.MoveNext())
                                            {
                                                ReadOnlySegmentCollection segments = polylineSegments.Current;
                                                gml =
                                                    $"{gml}<gml:MultiLineString><gml:LineStringMember><gml:LineString {GmlDimension(copyGeometry)}><gml:coordinates>";

                                                for (int i = 0; i < segments.Count; i++)
                                                {
                                                    if (segments[i].SegmentType == SegmentType.Line)
                                                    {
                                                        MapPoint linePoint = segments[i].StartPoint;
                                                        gml = $"{gml}{((i == 0) ? string.Empty : " ")}{await GmlPointAsync(linePoint)}";

                                                        if (i == (segments.Count - 1))
                                                        {
                                                            linePoint = segments[i].EndPoint;
                                                            gml       = $"{gml} {await GmlPointAsync(linePoint)}";
                                                        }
                                                    }
                                                }

                                                gml = $"{gml}</gml:coordinates></gml:LineString></gml:LineStringMember></gml:MultiLineString>";
                                            }
                                        }

                                        break;

                                    case GeometryType.Unknown:
                                        break;
                                    }

                                    string fieldValueStr = fieldvalues.Aggregate(string.Empty,
                                                                                 (current, fieldvalue) =>
                                                                                 string.Format("{0}<{1}>{2}</{1}>", current, fieldvalue.Key, fieldvalue.Value));
                                    result =
                                        $"{result}<gml:featureMember><xs:Geometry>{fieldValueStr}{gml}</xs:Geometry></gml:featureMember>";
                                }
                            }
                        }
                    }
                }

                CIMRenderer renderer             = Layer.GetRenderer();
                CIMSimpleRenderer simpleRenderer = renderer as CIMSimpleRenderer;
                CIMUniqueValueRenderer uniqueValueRendererRenderer = renderer as CIMUniqueValueRenderer;
                CIMSymbolReference symbolRef = simpleRenderer?.Symbol ?? uniqueValueRendererRenderer?.DefaultSymbol;
                CIMSymbol symbol             = symbolRef?.Symbol;
                CIMColor cimColor            = symbol?.GetColor();
                double[] colorValues         = cimColor?.Values;

                int red   = ((colorValues != null) && (colorValues.Length >= 1)) ? ((int)colorValues[0]) : 255;
                int green = ((colorValues != null) && (colorValues.Length >= 2)) ? ((int)colorValues[1]) : 255;
                int blue  = ((colorValues != null) && (colorValues.Length >= 3)) ? ((int)colorValues[2]) : 255;
                int alpha = ((colorValues != null) && (colorValues.Length >= 4)) ? ((int)colorValues[3]) : 255;
                color     = Color.FromArgb(alpha, red, green, blue);
            });

            GmlChanged = (Color != color);
            Color      = color;
            string newGml = $"{result}</wfs:FeatureCollection>";

            GmlChanged = ((newGml != Gml) || GmlChanged);
            return(Gml = newGml);
        }
        /// <summary>
        /// Create polyline features from graphics and add to table
        /// </summary>
        /// <param name="graphicsList">List of graphics to add to table</param>
        /// <returns></returns>
        private static async Task CreateFeatures(List <Graphic> graphicsList, bool isKML)
        {
            RowBuffer rowBuffer = null;
            bool      isLine    = false;

            try
            {
                await QueuedTask.Run(() =>
                {
                    var layer = MapView.Active.GetSelectedLayers()[0];
                    if (layer is FeatureLayer)
                    {
                        var featureLayer = layer as FeatureLayer;

                        using (var table = featureLayer.GetTable())
                        {
                            TableDefinition definition = table.GetDefinition();
                            int shapeIndex             = definition.FindField("Shape");

                            string graphicsType;
                            foreach (Graphic graphic in graphicsList)
                            {
                                rowBuffer = table.CreateRowBuffer();

                                if (graphic.Geometry is Polyline)
                                {
                                    PolylineBuilder pb    = new PolylineBuilder(graphic.Geometry as Polyline);
                                    pb.HasZ               = false;
                                    rowBuffer[shapeIndex] = pb.ToGeometry();
                                    isLine = true;

                                    // Only add attributes for Esri format

                                    // Add attributes
                                    graphicsType = graphic.p.GetType().ToString().Replace("ProAppDistanceAndDirectionModule.", "");
                                    switch (graphicsType)
                                    {
                                    case "LineAttributes":
                                        {
                                            try
                                            {
                                                // Add attributes
                                                rowBuffer[definition.FindField("Distance")]  = ((LineAttributes)graphic.p)._distance;
                                                rowBuffer[definition.FindField("DistUnit")]  = ((LineAttributes)graphic.p).distanceunit;
                                                rowBuffer[definition.FindField("Angle")]     = ((LineAttributes)graphic.p).angle;
                                                rowBuffer[definition.FindField("AngleUnit")] = ((LineAttributes)graphic.p).angleunit;
                                                rowBuffer[definition.FindField("OriginX")]   = ((LineAttributes)graphic.p).originx;
                                                rowBuffer[definition.FindField("OriginY")]   = ((LineAttributes)graphic.p).originy;
                                                rowBuffer[definition.FindField("DestX")]     = ((LineAttributes)graphic.p).destinationx;
                                                rowBuffer[definition.FindField("DestY")]     = ((LineAttributes)graphic.p).destinationy;
                                                break;
                                            }
                                            // Catch exception likely due to missing fields
                                            // Just skip attempting to write to fields
                                            catch
                                            {
                                                break;
                                            }
                                        }

                                    case "RangeAttributes":
                                        {
                                            try
                                            {
                                                rowBuffer[definition.FindField("Rings")]    = ((RangeAttributes)graphic.p).numRings;
                                                rowBuffer[definition.FindField("Distance")] = ((RangeAttributes)graphic.p).distance;
                                                rowBuffer[definition.FindField("DistUnit")] = ((RangeAttributes)graphic.p).distanceunit;
                                                rowBuffer[definition.FindField("Radials")]  = ((RangeAttributes)graphic.p).numRadials;
                                                rowBuffer[definition.FindField("CenterX")]  = ((RangeAttributes)graphic.p).centerx;
                                                rowBuffer[definition.FindField("CenterY")]  = ((RangeAttributes)graphic.p).centery;
                                                break;
                                            }
                                            catch
                                            {
                                                break;
                                            }
                                        }
                                    }
                                }
                                else if (graphic.Geometry is Polygon)
                                {
                                    rowBuffer[shapeIndex] = new PolygonBuilder(graphic.Geometry as Polygon).ToGeometry();

                                    // Only add attributes for Esri format

                                    // Add attributes
                                    graphicsType = graphic.p.GetType().ToString().Replace("ProAppDistanceAndDirectionModule.", "");
                                    switch (graphicsType)
                                    {
                                    case "CircleAttributes":
                                        {
                                            try
                                            {
                                                rowBuffer[definition.FindField("Distance")] = ((CircleAttributes)graphic.p).distance;
                                                rowBuffer[definition.FindField("DistUnit")] = ((CircleAttributes)graphic.p).distanceunit;
                                                rowBuffer[definition.FindField("DistType")] = ((CircleAttributes)graphic.p).circletype;
                                                rowBuffer[definition.FindField("CenterX")]  = ((CircleAttributes)graphic.p).centerx;
                                                rowBuffer[definition.FindField("CenterY")]  = ((CircleAttributes)graphic.p).centery;
                                                break;
                                            }
                                            catch (Exception e)
                                            {
                                                break;
                                            }
                                        }

                                    case "EllipseAttributes":
                                        try
                                        {
                                            rowBuffer[definition.FindField("Minor")]     = ((EllipseAttributes)graphic.p).minorAxis;
                                            rowBuffer[definition.FindField("Major")]     = ((EllipseAttributes)graphic.p).majorAxis;
                                            rowBuffer[definition.FindField("DistUnit")]  = ((EllipseAttributes)graphic.p).distanceunit;
                                            rowBuffer[definition.FindField("CenterX")]   = ((EllipseAttributes)graphic.p).centerx;
                                            rowBuffer[definition.FindField("CenterY")]   = ((EllipseAttributes)graphic.p).centery;
                                            rowBuffer[definition.FindField("Angle")]     = ((EllipseAttributes)graphic.p).angle;
                                            rowBuffer[definition.FindField("AngleUnit")] = ((EllipseAttributes)graphic.p).angleunit;
                                            break;
                                        }
                                        catch
                                        {
                                            break;
                                        }
                                    }
                                }

                                Row row = table.CreateRow(rowBuffer);
                            }
                        }

                        //Get simple renderer from feature layer
                        CIMSimpleRenderer currentRenderer = featureLayer.GetRenderer() as CIMSimpleRenderer;
                        CIMSymbolReference sybmol         = currentRenderer.Symbol;

                        var outline = SymbolFactory.Instance.ConstructStroke(ColorFactory.Instance.RedRGB, 1.0, SimpleLineStyle.Solid);
                        CIMSymbol s;
                        if (isLine)
                        {
                            s = SymbolFactory.Instance.ConstructLineSymbol(outline);
                        }
                        else
                        {
                            s = SymbolFactory.Instance.ConstructPolygonSymbol(ColorFactory.Instance.RedRGB, SimpleFillStyle.Null, outline);
                        }
                        CIMSymbolReference symbolRef = new CIMSymbolReference()
                        {
                            Symbol = s
                        };
                        currentRenderer.Symbol = symbolRef;

                        featureLayer.SetRenderer(currentRenderer);
                    }
                });
            }
            catch (GeodatabaseException exObj)
            {
                Console.WriteLine(exObj);
                throw;
            }
            finally
            {
                if (rowBuffer != null)
                {
                    rowBuffer.Dispose();
                }
            }
        }
Exemple #19
0
        private static async Task CreateFeatures(List <CCProGraphic> mapPointList, string layerName, bool isKML)
        {
            ArcGIS.Core.Data.RowBuffer rowBuffer = null;
            try
            {
                var layer = MapView.Active.Map.GetLayersAsFlattenedList().Where(x => x.Name == Path.GetFileNameWithoutExtension(layerName)).FirstOrDefault();
                if (layer == null)
                {
                    MessageBox.Show("Something went wrong");
                }
                else
                {
                    await QueuedTask.Run(() =>
                    {
                        if (layer is FeatureLayer)
                        {
                            var featureLayer = (FeatureLayer)layer;

                            using (var table = featureLayer.GetTable())
                            {
                                TableDefinition definition = table.GetDefinition();
                                int shapeIndex             = definition.FindField("Shape");

                                foreach (var point in mapPointList)
                                {
                                    rowBuffer = table.CreateRowBuffer();

                                    var geom = !point.MapPoint.HasZ ?
                                               new MapPointBuilder(point.MapPoint).ToGeometry() :
                                               MapPointBuilder.CreateMapPoint(point.MapPoint.X, point.MapPoint.Y, point.MapPoint.SpatialReference);
                                    rowBuffer[shapeIndex] = geom;
                                    foreach (var item in point.Attributes)
                                    {
                                        int idx = definition.FindField(item.Key);
                                        if (idx > -1)
                                        {
                                            rowBuffer[idx] = item.Value == null ? "" : item.Value;
                                        }
                                    }
                                    ArcGIS.Core.Data.Row row = table.CreateRow(rowBuffer);
                                }
                            }

                            //Set header text
                            var cimFeatureDefinition     = featureLayer.GetDefinition() as ArcGIS.Core.CIM.CIMFeatureLayer;
                            var cimDisplayTable          = cimFeatureDefinition.FeatureTable;
                            var displayField             = cimDisplayTable.DisplayField;
                            cimDisplayTable.DisplayField = TabBaseViewModel.CoordinateFieldName;
                            featureLayer.SetDefinition(cimFeatureDefinition);

                            //set label property
                            var lc = featureLayer.LabelClasses.FirstOrDefault();
                            lc.SetExpression(string.Format("[{0}]", TabBaseViewModel.CoordinateFieldName));
                            lc.SetExpressionEngine(LabelExpressionEngine.VBScript);

                            //Get simple renderer from feature layer
                            CIMSimpleRenderer currentRenderer = featureLayer.GetRenderer() as CIMSimpleRenderer;
                            if (currentRenderer != null)
                            {
                                CIMSymbolReference sybmol = currentRenderer.Symbol;
                                //var outline = SymbolFactory.ConstructStroke(ColorFactory.RedRGB, 1.0, SimpleLineStyle.Solid);
                                //var s = SymbolFactory.ConstructPolygonSymbol(ColorFactory.RedRGB, SimpleFillStyle.Null, outline);
                                var s = SymbolFactory.Instance.ConstructPointSymbol(ColorFactory.Instance.RedRGB, 3.0);
                                if (isKML)
                                {
                                    s.SetSize(CoordinateConversionLibrary.Constants.SymbolSize);
                                }
                                CIMSymbolReference symbolRef = new CIMSymbolReference()
                                {
                                    Symbol = s
                                };
                                currentRenderer.Symbol = symbolRef;

                                featureLayer.SetRenderer(currentRenderer);
                            }
                        }
                    });
                }
            }
            catch (GeodatabaseException exObj)
            {
                System.Diagnostics.Debug.WriteLine(exObj);
                throw;
            }
            finally
            {
                if (rowBuffer != null)
                {
                    rowBuffer.Dispose();
                }
            }
        }
Exemple #20
0
        /// <summary>
        /// Create polyline features from graphics and add to table
        /// </summary>
        /// <param name="graphicsList">List of graphics to add to table</param>
        /// <returns></returns>
        private static async Task CreateFeatures(List <ProGraphic> graphicsList, string layerName)
        {
            ArcGIS.Core.Data.RowBuffer rowBuffer = null;

            try
            {
                var layer = MapView.Active.Map.GetLayersAsFlattenedList().Where(x => x.Name == Path.GetFileNameWithoutExtension(layerName)).FirstOrDefault();
                if (layer == null)
                {
                    ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("Something went wrong");
                }
                else
                {
                    await QueuedTask.Run(() =>
                    {
                        if (layer is FeatureLayer)
                        {
                            var featureLayer = (FeatureLayer)layer;

                            using (var table = featureLayer.GetTable())
                            {
                                TableDefinition definition = table.GetDefinition();
                                int shapeIndex             = definition.FindField("Shape");

                                foreach (ProGraphic graphic in graphicsList)
                                {
                                    rowBuffer = table.CreateRowBuffer();

                                    if (graphic.Geometry is Polyline)
                                    {
                                        Polyline poly         = new PolylineBuilder(graphic.Geometry as Polyline).ToGeometry();
                                        rowBuffer[shapeIndex] = poly;
                                    }
                                    else if (graphic.Geometry is Polygon)
                                    {
                                        rowBuffer[shapeIndex] = new PolygonBuilder(graphic.Geometry as Polygon).ToGeometry();
                                    }

                                    ArcGIS.Core.Data.Row row = table.CreateRow(rowBuffer);
                                }
                            }

                            //Get simple renderer from feature layer
                            CIMSimpleRenderer currentRenderer = featureLayer.GetRenderer() as CIMSimpleRenderer;
                            if (currentRenderer != null)
                            {
                                CIMSymbolReference sybmol = currentRenderer.Symbol;

                                var outline = SymbolFactory.Instance.ConstructStroke(ColorFactory.Instance.RedRGB, 1.0, SimpleLineStyle.Solid);
                                var s       = SymbolFactory.Instance.ConstructPolygonSymbol(ColorFactory.Instance.RedRGB, SimpleFillStyle.Null, outline);
                                CIMSymbolReference symbolRef = new CIMSymbolReference()
                                {
                                    Symbol = s
                                };
                                currentRenderer.Symbol = symbolRef;

                                featureLayer.SetRenderer(currentRenderer);
                            }
                        }
                    });
                }
            }
            catch (GeodatabaseException exObj)
            {
                System.Diagnostics.Debug.WriteLine(exObj);
                throw;
            }
            finally
            {
                if (rowBuffer != null)
                {
                    rowBuffer.Dispose();
                }
            }
        }
        //Create a CIMSymbol from style item selected in the results gallery list box and
        //apply this newly created symbol to the feature layer currently selected in Contents pane
        private async void ApplyTheSelectedSymbol(SymbolStyleItem selectedStyleItemToApply)
        {
            if (selectedStyleItemToApply == null || string.IsNullOrEmpty(selectedStyleItemToApply.Key))
            {
                return;
            }

            await QueuedTask.Run(() =>
            {
                //Get the feature layer currently selected in the Contents pane
                var selectedLayers = MapView.Active.GetSelectedLayers();

                //Only one feature layer should be selected in the Contents pane
                if (selectedLayers.Count != 1)
                {
                    ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("Select the feature layer to which you want to apply the selected symbol. Only one feature layer should be selected.");
                    //Clear the current selection in gallery
                    _selectedStyleItem = null;
                    NotifyPropertyChanged(() => SelectedStyleItem);
                    return;
                }

                FeatureLayer ftrLayer = selectedLayers[0] as FeatureLayer;

                //The selected layer should be a feature layer
                if (ftrLayer == null)
                {
                    return;
                }

                //Get symbol from symbol style item.
                CIMSymbol symbolFromStyleItem = selectedStyleItemToApply.Symbol;

                //Make sure there isn't a mismatch between the type of selected symbol in gallery and feature layer geometry type
                if ((symbolFromStyleItem is CIMPointSymbol && ftrLayer.ShapeType != esriGeometryType.esriGeometryPoint) ||
                    (symbolFromStyleItem is CIMLineSymbol && ftrLayer.ShapeType != esriGeometryType.esriGeometryPolyline) ||
                    (symbolFromStyleItem is CIMPolygonSymbol && ftrLayer.ShapeType != esriGeometryType.esriGeometryPolygon && ftrLayer.ShapeType != esriGeometryType.esriGeometryMultiPatch))
                {
                    ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("There is a mismatch between symbol type and feature layer geometry type.");
                    //Clear the current selection in gallery
                    _selectedStyleItem = null;
                    NotifyPropertyChanged(() => SelectedStyleItem);
                    return;
                }


                //Get simple renderer from feature layer
                CIMSimpleRenderer currentRenderer = ftrLayer.GetRenderer() as CIMSimpleRenderer;

                if (currentRenderer == null)
                {
                    ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("Select a feature layer symbolized with a simple renderer.");
                    //Clear the current selection in gallery
                    _selectedStyleItem = null;
                    NotifyPropertyChanged(() => SelectedStyleItem);
                    return;
                }

                //Set real world setting for created symbol = feature layer's setting
                //so that there isn't a mismatch between symbol and feature layer
                SymbolFactory.SetRealWorldUnits(symbolFromStyleItem, ftrLayer.UsesRealWorldSymbolSizes);

                //Set current renderer's symbol reference = symbol reference of the newly created symbol
                currentRenderer.Symbol = SymbolFactory.MakeSymbolReference(symbolFromStyleItem);

                //Update feature layer renderer with new symbol
                ftrLayer.SetRenderer(currentRenderer);
            });
        }
Exemple #22
0
        //Exporting logic
        public static async Task Export3DMarkerSymbols()
        {
            var activeMapView = ArcGIS.Desktop.Mapping.MapView.Active;

            if (activeMapView == null)
            {
                return;
            }

            CIMObjectMarker3D mrkr3D = null;
            var selectedLayers       = activeMapView.GetSelectedLayers();

            if (selectedLayers.Count == 0)
            {
                ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("Select at least one point feature layer in the Contents pane.");
                return;
            }

            string outputFolder = SetOutputFolder();

            if (outputFolder == "")
            {
                return;
            }

            await QueuedTask.Run(() =>
            {
                foreach (Layer layer in selectedLayers)
                {
                    if (layer is FeatureLayer)
                    {
                        FeatureLayer ftrLayer       = layer as FeatureLayer;
                        CIMRenderer currentRenderer = ftrLayer.GetRenderer();

                        if (currentRenderer is CIMSimpleRenderer)
                        {
                            //Get simple renderer from feature layer
                            CIMSimpleRenderer simpleRenderer = currentRenderer as CIMSimpleRenderer;
                            CIMPointSymbol ptSymbol          = simpleRenderer.Symbol.Symbol as CIMPointSymbol;
                            if (ptSymbol != null)
                            {
                                var symbolLayers = ptSymbol.SymbolLayers;
                                int count        = 0;
                                foreach (CIMSymbolLayer s in symbolLayers)
                                {
                                    mrkr3D = s as CIMObjectMarker3D;
                                    if (mrkr3D != null)
                                    {
                                        string output = outputFolder + "\\" + ftrLayer.Name + "_" + count.ToString() + ".json";
                                        if (File.Exists(output))
                                        {
                                            ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("Following file already exists: " + output);
                                        }
                                        else
                                        {
                                            bool success = mrkr3D.ExportWeb3DObjectResource(output);
                                            if (!success)
                                            {
                                                //Export will fail if the 3D marker symbol being exported is a restricted symbol
                                                ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("Export failed for: " + output);
                                            }
                                        }
                                        count++;
                                    }
                                }
                            }
                        }

                        else if (currentRenderer is CIMUniqueValueRenderer)
                        {
                            //Get unique value renderer from feature layer
                            CIMUniqueValueRenderer uniqueRenderer = currentRenderer as CIMUniqueValueRenderer;
                            CIMUniqueValueGroup[] uv_group        = uniqueRenderer.Groups;
                            foreach (CIMUniqueValueGroup v in uv_group)
                            {
                                CIMUniqueValueClass[] uv_classes = v.Classes;
                                foreach (CIMUniqueValueClass uv_class in uv_classes)
                                {
                                    CIMPointSymbol ptSymbol = uv_class.Symbol.Symbol as CIMPointSymbol;
                                    if (ptSymbol != null)
                                    {
                                        var symbolLayers = ptSymbol.SymbolLayers;
                                        int count        = 0;
                                        foreach (CIMSymbolLayer s in symbolLayers)
                                        {
                                            mrkr3D = s as CIMObjectMarker3D;
                                            if (mrkr3D != null)
                                            {
                                                string output = outputFolder + "\\" + ftrLayer.Name + "_" + uv_class.Label + "_" + count.ToString() + ".json";
                                                if (File.Exists(output))
                                                {
                                                    ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("Following file already exists: " + output);
                                                }
                                                else
                                                {
                                                    bool success = mrkr3D.ExportWeb3DObjectResource(output);
                                                    if (!success)
                                                    {
                                                        //Export will fail if the 3D marker symbol being exported is a restricted symbol
                                                        ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("Export failed for: " + output);
                                                    }
                                                }
                                                count++;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            });
        }
        /// <summary>
        /// Create polyline features from graphics and add to table
        /// </summary>
        /// <param name="graphicsList">List of graphics to add to table</param>
        /// <returns></returns>
        private static async Task CreateFeatures(List <Graphic> graphicsList)
        {
            RowBuffer rowBuffer = null;
            bool      isLine    = false;

            try
            {
                await QueuedTask.Run(() =>
                {
                    var layer = MapView.Active.GetSelectedLayers()[0];
                    if (layer is FeatureLayer)
                    {
                        var featureLayer = layer as FeatureLayer;

                        using (var table = featureLayer.GetTable())
                        {
                            TableDefinition definition = table.GetDefinition();
                            int shapeIndex             = definition.FindField("Shape");

                            foreach (Graphic graphic in graphicsList)
                            {
                                rowBuffer = table.CreateRowBuffer();

                                if (graphic.Geometry is Polyline)
                                {
                                    PolylineBuilder pb    = new PolylineBuilder(graphic.Geometry as Polyline);
                                    pb.HasZ               = false;
                                    rowBuffer[shapeIndex] = pb.ToGeometry();
                                    isLine = true;
                                }
                                else if (graphic.Geometry is Polygon)
                                {
                                    rowBuffer[shapeIndex] = new PolygonBuilder(graphic.Geometry as Polygon).ToGeometry();
                                }

                                Row row = table.CreateRow(rowBuffer);
                            }
                        }

                        //Get simple renderer from feature layer
                        CIMSimpleRenderer currentRenderer = featureLayer.GetRenderer() as CIMSimpleRenderer;
                        CIMSymbolReference sybmol         = currentRenderer.Symbol;

                        var outline = SymbolFactory.ConstructStroke(ColorFactory.RedRGB, 1.0, SimpleLineStyle.Solid);
                        CIMSymbol s;
                        if (isLine)
                        {
                            s = SymbolFactory.ConstructLineSymbol(outline);
                        }
                        else
                        {
                            s = SymbolFactory.ConstructPolygonSymbol(ColorFactory.RedRGB, SimpleFillStyle.Null, outline);
                        }
                        CIMSymbolReference symbolRef = new CIMSymbolReference()
                        {
                            Symbol = s
                        };
                        currentRenderer.Symbol = symbolRef;

                        featureLayer.SetRenderer(currentRenderer);
                    }
                });
            }
            catch (GeodatabaseException exObj)
            {
                Console.WriteLine(exObj);
                throw;
            }
            finally
            {
                if (rowBuffer != null)
                {
                    rowBuffer.Dispose();
                }
            }
        }