/// <summary> /// Called when the sketch finishes. This is where we will create the edit operation and then execute it. /// </summary> /// <param name="geometry">The geometry created by the sketch.</param> /// <returns>A Task returning a Boolean indicating if the sketch complete event was successfully handled.</returns> protected override async Task <bool> OnSketchCompleteAsync(Geometry geometry) { if (CurrentTemplate == null || geometry == null) { return(false); } bool result = await QueuedTask.Run(() => { // get the anno layer AnnotationLayer annoLayer = CurrentTemplate.Layer as AnnotationLayer; if (annoLayer == null) { return(false); } // get the anno feature class var fc = annoLayer.GetFeatureClass() as ArcGIS.Core.Data.Mapping.AnnotationFeatureClass; if (fc == null) { return(false); } // get the featureclass CIM definition which contains the labels, symbols var cimDefinition = fc.GetDefinition() as ArcGIS.Core.Data.Mapping.AnnotationFeatureClassDefinition; var labels = cimDefinition.GetLabelClassCollection(); var symbols = cimDefinition.GetSymbolCollection(); // make sure there are labels, symbols if ((labels.Count == 0) || (symbols.Count == 0)) { return(false); } // find the label class required // typically you would use a subtype name or some other characteristic // use the first label class var label = labels[0]; if (labels.Count > 1) { // find a label class based on template name foreach (var LabelClass in labels) { if (LabelClass.Name == CurrentTemplate.Name) { label = LabelClass; break; } } } // each label has a textSymbol // the symbolName *should* be the symbolID to be used var symbolName = label.TextSymbol.SymbolName; int symbolID = -1; if (!int.TryParse(symbolName, out symbolID)) { // int.TryParse fails - attempt to find the symbolName in the symbol collection foreach (var symbol in symbols) { if (symbol.Name == symbolName) { symbolID = symbol.ID; break; } } } // no symbol? if (symbolID == -1) { return(false); } // use the template's inspector object var inspector = CurrentTemplate.Inspector; // get the annotation properties var annoProperties = inspector.GetAnnotationProperties(); // AnnotationClassID, SymbolID and Shape are the bare minimum for an annotation feature // use the inspector[fieldName] to set the annotationClassid - this is allowed since annotationClassID is a guaranteed field in the annotation schema inspector["AnnotationClassID"] = label.ID; // set the symbolID too inspector["SymbolID"] = symbolID; // use the annotation properties to set the other attributes annoProperties.TextString = "My annotation feature"; annoProperties.Color = ColorFactory.Instance.GreenRGB; annoProperties.VerticalAlignment = ArcGIS.Core.CIM.VerticalAlignment.Top; annoProperties.Underline = true; // set the geometry to be the sketched line // when creating annotation features the shape to be passed in the create operation is the CIMTextGraphic shape annoProperties.Shape = geometry; // set the annotation properties back on the inspector inspector.SetAnnotationProperties(annoProperties); // Create an edit operation var createOperation = new EditOperation(); createOperation.Name = string.Format("Create {0}", CurrentTemplate.Layer.Name); createOperation.SelectNewFeatures = true; // create and execute using the inspector createOperation.Create(CurrentTemplate.Layer, inspector); return(createOperation.Execute()); }); return(result); }
public void snippets_elements() { #region Find an element on a layout // Reference a layoutitem in a project by name LayoutProjectItem layoutItem = Project.Current.GetItems <LayoutProjectItem>().FirstOrDefault(item => item.Name.Equals("MyLayout")); if (layoutItem != null) { QueuedTask.Run(() => { // Reference and load the layout associated with the layout item Layout layout = layoutItem.GetLayout(); if (layout != null) { //Find a single specific element Element rect = layout.FindElement("Rectangle") as Element; //Or use the Elements collection Element rect2 = layout.Elements.FirstOrDefault(item => item.Name.Equals("Rectangle")); } }); } #endregion Element element = null; #region Update element properties QueuedTask.Run(() => { // update an element's name element.SetName("New Name"); // update and element's visibility element.SetVisible(true); }); #endregion { #region Get element selection count //Count the number of selected elements on the active layout view LayoutView activeLayoutView = LayoutView.Active; if (activeLayoutView != null) { var selectedElements = activeLayoutView.GetSelectedElements(); ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show($@"Selected elements: {selectedElements.Count}"); } #endregion } { #region Set element selection //The the active layout view's selection to include 2 rectangle elements LayoutView activeLayoutView = LayoutView.Active; if (activeLayoutView != null) { QueuedTask.Run(() => { Layout lyt = activeLayoutView.Layout; Element rec = lyt.FindElement("Rectangle"); Element rec2 = lyt.FindElement("Rectangle 2"); List <Element> elmList = new List <Element> { rec, rec2 }; activeLayoutView.SelectElements(elmList); }); } #endregion } { #region Clear the layout selection //If the a layout view is active, the clear its selection LayoutView activeLayoutView = LayoutView.Active; if (activeLayoutView != null) { activeLayoutView.ClearElementSelection(); } #endregion } Layout aLayout = null; Element elm = null; #region Delete an element or elements on a layout QueuedTask.Run(() => { //Delete a specific element on a layout aLayout.DeleteElement(elm); //Or delete a group of elements using a filter aLayout.DeleteElements(item => item.Name.Contains("Clone")); //Or delete all elements on a layout aLayout.DeleteElements(item => true); }); #endregion #region Set Halo property of North Arrow //Assuming the selected item is a north arrow var northArrow = LayoutView.Active.GetSelectedElements().First(); QueuedTask.Run(() => { //Get definition of north arrow... var cim = northArrow.GetDefinition() as CIMMarkerNorthArrow; //this halo symbol is 50% transparent, no outline (i.e. 0 width) //First construct a polygon symbol to use in the Halo //Polygon symbol will need a fill and a stroke var polyFill = SymbolFactory.Instance.ConstructSolidFill(ColorFactory.Instance.CreateRGBColor(0, 0, 0, 50)); var polyStroke = SymbolFactory.Instance.ConstructStroke(ColorFactory.Instance.BlackRGB, 0); var haloPoly = SymbolFactory.Instance.ConstructPolygonSymbol(polyFill, polyStroke); //Set the north arrow defintion of HaloSymbol and HaloSize ((CIMPointSymbol)cim.PointSymbol.Symbol).HaloSymbol = haloPoly; ((CIMPointSymbol)cim.PointSymbol.Symbol).HaloSize = 3; //size of the halo //set it back northArrow.SetDefinition(cim); }); #endregion }
public void snippets_exportLayout() { #region Export a layout // Reference a layoutitem in a project by name LayoutProjectItem layoutItem = Project.Current.GetItems <LayoutProjectItem>().FirstOrDefault(item => item.Name.Equals("MyLayout")); if (layoutItem != null) { QueuedTask.Run(() => { Layout layout = layoutItem.GetLayout(); if (layout == null) { return; } // Create BMP format with appropriate settings BMPFormat BMP = new BMPFormat() { Resolution = 300, OutputFileName = @"C:\temp\Layout.bmp" }; if (BMP.ValidateOutputFilePath()) { layout.Export(BMP); } // Create EMF format with appropriate settings EMFFormat EMF = new EMFFormat() { Resolution = 300, OutputFileName = @"C:\temp\Layout.emf" }; if (EMF.ValidateOutputFilePath()) { layout.Export(EMF); } // create eps format with appropriate settings EPSFormat EPS = new EPSFormat() { Resolution = 300, OutputFileName = @"C:\temp\Layout.eps" }; if (EPS.ValidateOutputFilePath()) { layout.Export(EPS); } // Create GIF format with appropriate settings GIFFormat GIF = new GIFFormat() { Resolution = 300, OutputFileName = @"C:\temp\Layout.gif" }; if (GIF.ValidateOutputFilePath()) { layout.Export(GIF); } // Create JPEG format with appropriate settings JPEGFormat JPEG = new JPEGFormat() { Resolution = 300, OutputFileName = @"C:\temp\Layout.jpg" }; if (JPEG.ValidateOutputFilePath()) { layout.Export(JPEG); } // Create PDF format with appropriate settings PDFFormat PDF = new PDFFormat() { Resolution = 300, OutputFileName = @"C:\temp\Layout.pdf" }; if (PDF.ValidateOutputFilePath()) { layout.Export(PDF); } // Create PNG format with appropriate settings PNGFormat PNG = new PNGFormat() { Resolution = 300, OutputFileName = @"C:\temp\Layout.png" }; if (PNG.ValidateOutputFilePath()) { layout.Export(PNG); } // Create SVG format with appropriate settings SVGFormat SVG = new SVGFormat() { Resolution = 300, OutputFileName = @"C:\temp\Layout.svg" }; if (SVG.ValidateOutputFilePath()) { layout.Export(SVG); } // Create TGA format with appropriate settings TGAFormat TGA = new TGAFormat() { Resolution = 300, OutputFileName = @"C:\temp\Layout.tga" }; if (TGA.ValidateOutputFilePath()) { layout.Export(TGA); } // Create TIFF format with appropriate settings TIFFFormat TIFF = new TIFFFormat() { Resolution = 300, OutputFileName = @"C:\temp\Layout.tif" }; if (TIFF.ValidateOutputFilePath()) { layout.Export(TIFF); } }); } #endregion }
/// <summary> /// Function to identify rendered and source dataset pixel values for one or more /// raster, mosaic and image service layers. /// </summary> /// <param name="mapPoint">Map point to identify pixel values.</param> public static async void CustomRasterIdentify(MapPoint mapPoint) { // Create a new list of popup pages. var popupContents = new List <PopupContent>(); // Create an empty string that will represent what goes into a popup page. string identifiedVal = ""; // Create the popup pages to show. await QueuedTask.Run(() => { // Check if there is an active map view. if (MapView.Active != null) { // Get the active map view. var mapView = MapView.Active; // Get the list of selected layers. IReadOnlyList <Layer> selectedLayerList = MapView.Active.GetSelectedLayers(); if (selectedLayerList.Count == 0) { // If no layers are selected fill the popup page with the appropriate message. // Note: you can use html tags to format the text. identifiedVal += "<p>No Layers selected. Please select one or more Raster, Mosaic or Image Service layers.</p>"; // Add the popup page to the list of pages. popupContents.Add(new PopupContent(identifiedVal, "Custom Raster Identify")); } else { // Iterate over the list of selected layers. foreach (Layer currentSelectedLayer in selectedLayerList) { #region Get a basic raster layer from the selected layer. BasicRasterLayer currentRasterLayer = null; if (currentSelectedLayer is MosaicLayer) { // If the current selected layer is a mosaic layer, MosaicLayer mosaicLayer = currentSelectedLayer as MosaicLayer; // Get the image sub-layer from the mosaic layer. This is a basic raster layer. currentRasterLayer = mosaicLayer.GetImageLayer() as BasicRasterLayer; } else if (currentSelectedLayer is BasicRasterLayer) { // If the current selected layer is a raster layer or image service layer, // both are already basic raster layers. currentRasterLayer = currentSelectedLayer as BasicRasterLayer; } else { // If the current selected layer is neither a mosaic nor a raster or image service layer, // fill the popup page with the appropriate message. identifiedVal += "<p>Selected layer is not a raster layer. Please select one or more Raster, Mosaic or Image Service layers.</p>"; // Add the popup page to the list of pages. popupContents.Add(new PopupContent(identifiedVal, "Custom Raster Identify for: " + currentSelectedLayer.Name)); continue; } #endregion #region Get the pixel value for the rendered raster. // Add the label for the rendered pixel value. identifiedVal += "<b>Rendered Pixel value: </b>"; // Get the raster from the current selected raster layer. Raster raster = currentRasterLayer.GetRaster(); // If the map spatial reference is different from the spatial reference of the raster, // set the map spatial reference on the raster. This will ensure the map points are // correctly reprojected to image points. if (mapView.Map.SpatialReference.Name != raster.GetSpatialReference().Name) { raster.SetSpatialReference(mapView.Map.SpatialReference); } // Convert the map point to be identified into an image point. Tuple <int, int> imagePoint = raster.MapToPixel(mapPoint.X, mapPoint.Y); if ((int)imagePoint.Item1 < 0 || (int)imagePoint.Item1 > raster.GetWidth() || (int)imagePoint.Item2 < 0 || (int)imagePoint.Item2 > raster.GetHeight()) { // If the point is outside the image, fill the pixel value with the appropriate message. identifiedVal += "Point is not within image. \n"; } else { // If the point is within the image. Iterate over the bands in the raster. for (int band = 0; band < raster.GetBandCount(); band++) { // Get the pixel value based on the band, column and row and add the // formatted pixel value to the popup page. if (band == 0) { identifiedVal += raster.GetPixelValue(band, (int)imagePoint.Item1, (int)imagePoint.Item2).ToString(); } else { identifiedVal += ", " + raster.GetPixelValue(band, (int)imagePoint.Item1, (int)imagePoint.Item2).ToString(); } } identifiedVal += "."; } // Add the rendered pixel value to the popup page contents. string htmlContent = "<p>" + identifiedVal + "</p>"; #endregion #region Get the pixel value for the source raster dataset. // Add the label for the source dataset pixel value. identifiedVal = "<b>Dataset Pixel value: </b>"; // Get the basic raster dataset from the raster. BasicRasterDataset basicRasterDataset = raster.GetRasterDataset(); if (!(basicRasterDataset is RasterDataset)) { // If the dataset is not a raster dataset, fill the pixel value with the appropriate message. identifiedVal += "Selected layer is not a Raster Layer. Please select one or more Raster, Mosaic or Image Service layers."; htmlContent += "<p>" + identifiedVal + "</p>"; popupContents.Add(new PopupContent(htmlContent, "Custom Raster Identify for " + currentSelectedLayer.Name)); } // Get the raster dataset. RasterDataset rasterDataset = basicRasterDataset as RasterDataset; // Create a full raster from the raster dataset. raster = rasterDataset.CreateFullRaster(); // If the map spatial reference is different from the spatial reference of the raster, // Set the map spatial reference on the raster. This will ensure the map points are // correctly reprojected to image points. if (mapView.Map.SpatialReference.Name != raster.GetSpatialReference().Name) { raster.SetSpatialReference(mapView.Map.SpatialReference); } // Convert the map point to be identified to an image point. imagePoint = raster.MapToPixel(mapPoint.X, mapPoint.Y); if ((int)imagePoint.Item1 < 0 || (int)imagePoint.Item1 > raster.GetWidth() || (int)imagePoint.Item2 < 0 || (int)imagePoint.Item2 > raster.GetHeight()) { // If the point is outside the image, fill the pixel value with the appropriate message. identifiedVal += "Point is not within image. \n"; } else { // If the point is within the image. Iterate over the bands in the raster. for (int band = 0; band < raster.GetBandCount(); band++) { // Get the pixel value based on the band, column and row and add the // formatted pixel value to the popup page. if (band == 0) { identifiedVal += raster.GetPixelValue(band, (int)imagePoint.Item1, (int)imagePoint.Item2).ToString(); } else { identifiedVal += ", " + raster.GetPixelValue(band, (int)imagePoint.Item1, (int)imagePoint.Item2).ToString(); } } identifiedVal += "."; } // Add the source dataset pixel value to the popup page contents. htmlContent += "<p>" + identifiedVal + "</p>"; #endregion // Add the popup page to the list of pages. popupContents.Add(new PopupContent(htmlContent, "Custom Raster Identify for " + currentSelectedLayer.Name)); // Reset identifiedVal = ""; } } } }); // Show custom popup with the list of popup pages created above. MapView.Active.ShowCustomPopup(popupContents); }
public void snippets_CreateLayoutElements() { LayoutView layoutView = LayoutView.Active; Layout layout = layoutView.Layout; #region Create point graphic with symbology //Create a simple 2D point graphic and apply an existing point style item as the symbology. //An alternative simple symbol is also provided below. This would completely elminate the 4 lines of code that reference a style. QueuedTask.Run(() => { //Build 2D point geometry Coordinate2D coord2D = new Coordinate2D(2.0, 10.0); //Reference a point symbol in a style StyleProjectItem ptStylePrjItm = Project.Current.GetItems <StyleProjectItem>().FirstOrDefault(item => item.Name == "ArcGIS 2D"); SymbolStyleItem ptSymStyleItm = ptStylePrjItm.SearchSymbols(StyleItemType.PointSymbol, "City Hall")[0]; CIMPointSymbol pointSym = ptSymStyleItm.Symbol as CIMPointSymbol; pointSym.SetSize(50); //Set symbolology, create and add element to layout //CIMPointSymbol pointSym = SymbolFactory.Instance.ConstructPointSymbol(ColorFactory.Instance.RedRGB, 25.0, SimpleMarkerStyle.Star); //Alternative simple symbol GraphicElement ptElm = LayoutElementFactory.Instance.CreatePointGraphicElement(layout, coord2D, pointSym); ptElm.SetName("New Point"); }); #endregion #region Create line graphic with symbology //Create a simple 2D line graphic and apply an existing line style item as the symbology. //An alternative simple symbol is also provided below. This would completely elminate the 4 lines of code that reference a style. QueuedTask.Run(() => { //Build 2d line geometry List <Coordinate2D> plCoords = new List <Coordinate2D>(); plCoords.Add(new Coordinate2D(1, 8.5)); plCoords.Add(new Coordinate2D(1.66, 9)); plCoords.Add(new Coordinate2D(2.33, 8.1)); plCoords.Add(new Coordinate2D(3, 8.5)); Polyline linePl = PolylineBuilder.CreatePolyline(plCoords); //Reference a line symbol in a style StyleProjectItem lnStylePrjItm = Project.Current.GetItems <StyleProjectItem>().FirstOrDefault(item => item.Name == "ArcGIS 2D"); SymbolStyleItem lnSymStyleItm = lnStylePrjItm.SearchSymbols(StyleItemType.LineSymbol, "Line with 2 Markers")[0]; CIMLineSymbol lineSym = lnSymStyleItm.Symbol as CIMLineSymbol; lineSym.SetSize(20); //Set symbolology, create and add element to layout //CIMLineSymbol lineSym = SymbolFactory.Instance.ConstructLineSymbol(ColorFactory.Instance.BlueRGB, 4.0, SimpleLineStyle.Solid); //Alternative simple symbol GraphicElement lineElm = LayoutElementFactory.Instance.CreateLineGraphicElement(layout, linePl, lineSym); lineElm.SetName("New Line"); }); #endregion #region Create rectangle graphic with simple symbology //Create a simple 2D rectangle graphic and apply simple fill and outline symbols. QueuedTask.Run(() => { //Build 2D envelope geometry Coordinate2D rec_ll = new Coordinate2D(1.0, 4.75); Coordinate2D rec_ur = new Coordinate2D(3.0, 5.75); Envelope rec_env = EnvelopeBuilder.CreateEnvelope(rec_ll, rec_ur); //Set symbolology, create and add element to layout CIMStroke outline = SymbolFactory.Instance.ConstructStroke(ColorFactory.Instance.BlackRGB, 5.0, SimpleLineStyle.Solid); CIMPolygonSymbol polySym = SymbolFactory.Instance.ConstructPolygonSymbol(ColorFactory.Instance.GreenRGB, SimpleFillStyle.DiagonalCross, outline); GraphicElement recElm = LayoutElementFactory.Instance.CreateRectangleGraphicElement(layout, rec_env, polySym); recElm.SetName("New Rectangle"); }); #endregion #region Create text element with basic font properties //Create a simple point text element and assign basic symbology as well as basic text settings. QueuedTask.Run(() => { //Build 2D point geometry Coordinate2D coord2D = new Coordinate2D(3.5, 10); //Set symbolology, create and add element to layout CIMTextSymbol sym = SymbolFactory.Instance.ConstructTextSymbol(ColorFactory.Instance.RedRGB, 32, "Arial", "Regular"); string textString = "Point text"; GraphicElement ptTxtElm = LayoutElementFactory.Instance.CreatePointTextGraphicElement(layout, coord2D, textString, sym); ptTxtElm.SetName("New Point Text"); //Change additional text properties ptTxtElm.SetAnchor(Anchor.CenterPoint); ptTxtElm.SetX(4.5); ptTxtElm.SetY(9.5); ptTxtElm.SetRotation(45); }); #endregion #region Create rectangle text with more advanced symbol settings //Create rectangle text with background and border symbology. Also notice how formatting tags are using within the text string. QueuedTask.Run(() => { //Build 2D polygon geometry List <Coordinate2D> plyCoords = new List <Coordinate2D>(); plyCoords.Add(new Coordinate2D(3.5, 7)); plyCoords.Add(new Coordinate2D(4.5, 7)); plyCoords.Add(new Coordinate2D(4.5, 6.7)); plyCoords.Add(new Coordinate2D(5.5, 6.7)); plyCoords.Add(new Coordinate2D(5.5, 6.1)); plyCoords.Add(new Coordinate2D(3.5, 6.1)); Polygon poly = PolygonBuilder.CreatePolygon(plyCoords); //Set symbolology, create and add element to layout CIMTextSymbol sym = SymbolFactory.Instance.ConstructTextSymbol(ColorFactory.Instance.GreyRGB, 10, "Arial", "Regular"); string text = "Some Text String that is really long and is <BOL>forced to wrap to other lines</BOL> so that we can see the effects." as String; GraphicElement polyTxtElm = LayoutElementFactory.Instance.CreatePolygonParagraphGraphicElement(layout, poly, text, sym); polyTxtElm.SetName("New Polygon Text"); //(Optionally) Modify paragraph border CIMGraphic polyTxtGra = polyTxtElm.Graphic; CIMParagraphTextGraphic cimPolyTxtGra = polyTxtGra as CIMParagraphTextGraphic; cimPolyTxtGra.Frame.BorderSymbol = new CIMSymbolReference(); cimPolyTxtGra.Frame.BorderSymbol.Symbol = SymbolFactory.Instance.ConstructLineSymbol(ColorFactory.Instance.GreyRGB, 1.0, SimpleLineStyle.Solid); polyTxtElm.SetGraphic(polyTxtGra); }); #endregion #region Create a new picture element with advanced symbol settings //Create a picture element and also set background and border symbology. QueuedTask.Run(() => { //Build 2D envelope geometry Coordinate2D pic_ll = new Coordinate2D(6, 1); Coordinate2D pic_ur = new Coordinate2D(8, 2); Envelope env = EnvelopeBuilder.CreateEnvelope(pic_ll, pic_ur); //Create and add element to layout string picPath = @"C:\Temp\WhitePass.jpg"; GraphicElement picElm = LayoutElementFactory.Instance.CreatePictureGraphicElement(layout, env, picPath); picElm.SetName("New Picture"); //(Optionally) Modify the border and shadow CIMGraphic picGra = picElm.Graphic; CIMPictureGraphic cimPicGra = picGra as CIMPictureGraphic; cimPicGra.Frame.BorderSymbol = new CIMSymbolReference(); cimPicGra.Frame.BorderSymbol.Symbol = SymbolFactory.Instance.ConstructLineSymbol(ColorFactory.Instance.BlueRGB, 2.0, SimpleLineStyle.Solid); cimPicGra.Frame.ShadowSymbol = new CIMSymbolReference(); cimPicGra.Frame.ShadowSymbol.Symbol = SymbolFactory.Instance.ConstructPolygonSymbol(ColorFactory.Instance.BlackRGB, SimpleFillStyle.Solid); picElm.SetGraphic(picGra); }); #endregion #region Create a map frame and zoom to a bookmark //Create a map frame and also sets its extent by zooming the the extent of an existing bookmark. QueuedTask.Run(() => { //Build 2D envelope geometry Coordinate2D mf_ll = new Coordinate2D(6.0, 8.5); Coordinate2D mf_ur = new Coordinate2D(8.0, 10.5); Envelope mf_env = EnvelopeBuilder.CreateEnvelope(mf_ll, mf_ur); //Reference map, create MF and add to layout MapProjectItem mapPrjItem = Project.Current.GetItems <MapProjectItem>().FirstOrDefault(item => item.Name.Equals("Map")); Map mfMap = mapPrjItem.GetMap(); MapFrame mfElm = LayoutElementFactory.Instance.CreateMapFrame(layout, mf_env, mfMap); mfElm.SetName("New Map Frame"); //Zoom to bookmark Bookmark bookmark = mfElm.Map.GetBookmarks().FirstOrDefault(b => b.Name == "Great Lakes"); mfElm.SetCamera(bookmark); }); #endregion #region Create a legend for a specifc map frame //Create a legend for an associated map frame. QueuedTask.Run(() => { //Build 2D envelope geometry Coordinate2D leg_ll = new Coordinate2D(6, 2.5); Coordinate2D leg_ur = new Coordinate2D(8, 4.5); Envelope leg_env = EnvelopeBuilder.CreateEnvelope(leg_ll, leg_ur); //Reference MF, create legend and add to layout MapFrame mapFrame = layout.FindElement("New Map Frame") as MapFrame; if (mapFrame == null) { ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("Map frame not found", "WARNING"); return; } Legend legendElm = LayoutElementFactory.Instance.CreateLegend(layout, leg_env, mapFrame); legendElm.SetName("New Legend"); }); #endregion #region Creating group elements //Create an empty group element at the root level of the contents pane //Note: call within QueuedTask.Run() GroupElement grp1 = LayoutElementFactory.Instance.CreateGroupElement(layout); grp1.SetName("Group"); //Create a group element inside another group element //Note: call within QueuedTask.Run() GroupElement grp2 = LayoutElementFactory.Instance.CreateGroupElement(grp1); grp2.SetName("Group in Group"); #endregion Creating group elements { #region Create scale bar Coordinate2D llScalebar = new Coordinate2D(6, 2.5); MapFrame mapframe = layout.FindElement("New Map Frame") as MapFrame; //Note: call within QueuedTask.Run() LayoutElementFactory.Instance.CreateScaleBar(layout, llScalebar, mapframe); #endregion } #region How to search for scale bars in a style var arcgis_2d = Project.Current.GetItems <StyleProjectItem>().First(si => si.Name == "ArcGIS 2D"); QueuedTask.Run(() => { var scaleBarItems = arcgis_2d.SearchScaleBars("Double Alternating Scale Bar"); }); #endregion #region How to add a scale bar from a style to a layout var arcgis_2dStyle = Project.Current.GetItems <StyleProjectItem>().First(si => si.Name == "ArcGIS 2D"); QueuedTask.Run(() => { //Imperial Double Alternating Scale Bar //Metric Double Alternating Scale Bar //or just use empty string to list them all... var scaleBarItem = arcgis_2d.SearchScaleBars("Double Alternating Scale Bar").FirstOrDefault(); Coordinate2D coord2D = new Coordinate2D(10.0, 7.0); MapFrame myMapFrame = layout.FindElement("Map Frame") as MapFrame; LayoutElementFactory.Instance.CreateScaleBar(layout, coord2D, myMapFrame, scaleBarItem); }); #endregion #region Create NorthArrow Coordinate2D llNorthArrow = new Coordinate2D(6, 2.5); MapFrame mf = layout.FindElement("New Map Frame") as MapFrame; //Note: call within QueuedTask.Run() var northArrow = LayoutElementFactory.Instance.CreateNorthArrow(layout, llNorthArrow, mf); #endregion #region How to search for North Arrows in a style var arcgis_2dStyles = Project.Current.GetItems <StyleProjectItem>().First(si => si.Name == "ArcGIS 2D"); QueuedTask.Run(() => { var scaleBarItems = arcgis_2dStyles.SearchNorthArrows("ArcGIS North 13"); }); #endregion #region How to add a North Arrow from a style to a layout var arcgis2dStyles = Project.Current.GetItems <StyleProjectItem>().First(si => si.Name == "ArcGIS 2D"); QueuedTask.Run(() => { var northArrowStyleItem = arcgis2dStyles.SearchNorthArrows("ArcGIS North 13").FirstOrDefault(); Coordinate2D nArrow = new Coordinate2D(6, 2.5); MapFrame newFrame = layout.FindElement("New Map Frame") as MapFrame; //Note: call within QueuedTask.Run() var newNorthArrow = LayoutElementFactory.Instance.CreateNorthArrow(layout, nArrow, newFrame, northArrowStyleItem); }); #endregion #region Create dynamic text var title = @"<dyn type = ""page"" property = ""name"" />"; Coordinate2D llTitle = new Coordinate2D(6, 2.5); //Note: call within QueuedTask.Run() var titleGraphics = LayoutElementFactory.Instance.CreatePointTextGraphicElement(layout, llTitle, null) as TextElement; titleGraphics.SetTextProperties(new TextProperties(title, "Arial", 24, "Bold")); #endregion #region Create dynamic table QueuedTask.Run(() => { //Build 2D envelope geometry Coordinate2D tab_ll = new Coordinate2D(6, 2.5); Coordinate2D tab_ur = new Coordinate2D(12, 6.5); Envelope tab_env = EnvelopeBuilder.CreateEnvelope(tab_ll, tab_ur); MapFrame mapFrame = layout.FindElement("New Map Frame") as MapFrame; // get the layer MapProjectItem mapPrjItem = Project.Current.GetItems <MapProjectItem>().FirstOrDefault(item => item.Name.Equals("Map")); Map theMap = mapPrjItem?.GetMap(); var lyrs = theMap?.FindLayers("Inspection Point Layer", true); if (lyrs?.Count > 0) { Layer lyr = lyrs[0]; var table1 = LayoutElementFactory.Instance.CreateTableFrame(layout, tab_env, mapFrame, lyr, new string[] { "No", "Type", "Description" }); } }); #endregion }
public static Task <Layout> CloneAsync(this Layout layout) { return(QueuedTask.Run(() => { return Clone(layout); })); }
protected override async Task HandleMouseDownAsync(MapViewMouseButtonEventArgs e) { await QueuedTask.Run(() => { var mapPoint = MapPointBuilder.CreateMapPoint(e.ClientPoint.X, e.ClientPoint.Y); var result = ActiveMapView.GetFeatures(mapPoint); List <PopupContent> popups = new List <PopupContent>(); foreach (var kvp in result) { var layer = kvp.Key as BasicFeatureLayer; if (layer == null) { continue; } var fields = layer.GetFieldDescriptions().Where(f => f.Name == "DI_JI_HAO"); var tableDef = layer.GetTable().GetDefinition(); var oidField = tableDef.GetObjectIDField(); foreach (var id in kvp.Value) { //获取地级编号 //DI_JI_HAO var qf = new QueryFilter() { WhereClause = $"{oidField} = {id}", SubFields = string.Join(",", fields.Select(f => f.Name)) }; var rows = layer.Search(qf); if (!rows.MoveNext()) { continue; } using (var row = rows.Current) { foreach (var field in fields) { var val = row[field.Name]; if (field.Name == "DI_JI_HAO") { PopupContent pc = new PopupContent(new Uri("http://59.42.105.34:5001/client/?id=" + val), "林业"); popups.Add(pc); } } } } } //Flash the features that intersected the sketch geometry. MessageBox.Show(popups.ToString()); ActiveMapView.FlashFeature(result); var height = System.Windows.SystemParameters.WorkArea.Height / 2; var width = System.Windows.SystemParameters.WorkArea.Width / 2; var topLeftCornerPoint = new System.Windows.Point(0, 0); var popupDef = new PopupDefinition() { Append = true, // if true new record is appended to existing (if any) Dockable = true, // if true popup is dockable - if false Append is not applicable Position = topLeftCornerPoint, // Position of top left corner of the popup (in pixels) Size = new System.Windows.Size(width, height) // size of the popup (in pixels) }; //Show the custom pop-up with the custom commands and the default pop-up commands. try { ActiveMapView.ShowCustomPopup(popups, null, true, popupDef); } catch (System.Exception e1) { MessageBox.Show(string.Format("{0}", e1)); } //return the collection of pop-up content object. }); }
//public async void GetTotalValues() public async void GetTotalValues() { long TotalValueLow = 0; long TotalValueMedium = 0; long TotalValueHigh = 0; long targetSettingValue = 0; double lowSettingValue = 0; double mediumSettingValue = 0; double highSettingValue = 0; await QueuedTask.Run(() => { // FeatureLayer CrowdLayer = MapView.Active.Map.FindLayer("CrowdPlanning") as FeatureLayer; FeatureLayer CrowdLayer = MapView.Active.Map.Layers.First(layer => layer.Name.Equals("CrowdPlanning")) as FeatureLayer; if (CrowdLayer == null) { ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("Layer is not found"); return; } //CrowdLayer.Search(null) ArcGIS.Core.Data.Table CrowdTable = CrowdLayer.GetTable(); QueryFilter QF = new QueryFilter { WhereClause = "LOW > 0" }; RowCursor CrowdRow = CrowdTable.Search(QF, false); long lowValue; long mediumValue; long highValue; while (CrowdRow.MoveNext()) { lowValue = 0; mediumValue = 0; highValue = 0; using (Row currentRow = CrowdRow.Current) { lowValue = Convert.ToInt32(currentRow["Low"]); TotalValueLow = TotalValueLow + lowValue; mediumValue = Convert.ToInt32(currentRow["Medium"]); TotalValueMedium = TotalValueMedium + mediumValue; highValue = Convert.ToInt32(currentRow["High"]); TotalValueHigh = TotalValueHigh + highValue; targetSettingValue = Convert.ToInt32(currentRow["TargetSetting"]); lowSettingValue = Convert.ToDouble(currentRow["LowSetting"]); mediumSettingValue = Convert.ToDouble(currentRow["MediumSetting"]); highSettingValue = Convert.ToDouble(currentRow["HighSetting"]); } } }); // Assign values to properties TotalHigh = TotalValueHigh; TotalMedium = TotalValueMedium; TotalLow = TotalValueLow; // Assign setting values TargetSetting = targetSettingValue; LowSetting = lowSettingValue; MediumSetting = mediumSettingValue; HighSetting = highSettingValue; // UPDATE PIE CHARTS // Chart 1 - High Estimate KeyValuePair <string, int>[] myKeyValuePairHigh = new KeyValuePair <string, int>[] { new KeyValuePair <string, int>("High Estimate Allocated", Convert.ToInt32(TotalValueHigh)), new KeyValuePair <string, int>("Remaining to Estimate", Convert.ToInt32(TargetSetting)) }; PieChartResult = myKeyValuePairHigh; NotifyPropertyChanged(() => PieChartResult); // Chart 2 - Medium Estimate KeyValuePair <string, int>[] myKeyValuePairMedium = new KeyValuePair <string, int>[] { new KeyValuePair <string, int>("Medium Estimate Allocated", Convert.ToInt32(TotalValueMedium)), new KeyValuePair <string, int>("Remaining to Estimate", Convert.ToInt32(TargetSetting)) }; PieChartResultMedium = myKeyValuePairMedium; NotifyPropertyChanged(() => PieChartResultMedium); // Chart 3 - Low Estimate KeyValuePair <string, int>[] myKeyValuePairLow = new KeyValuePair <string, int>[] { new KeyValuePair <string, int>("Low Estimate Allocated", Convert.ToInt32(TotalValueLow)), new KeyValuePair <string, int>("Remaining to Estimate", Convert.ToInt32(TargetSetting)) }; PieChartResultLow = myKeyValuePairLow; NotifyPropertyChanged(() => PieChartResultLow); //end of GetTotalValues }
public static async Task <string> GetGeoJSONFromFeatureLayer(FeatureLayer polygonFeatureLayer) { return(await QueuedTask.Run(() => { QueryFilter filter = new QueryFilter { WhereClause = "1=1" }; //SpatialReference inSR = polygonFeatureLayer.GetSpatialReference(); SpatialReference outputSR = SpatialReferenceBuilder.CreateSpatialReference(4326); // wgs84 RowCursor rowCursor = polygonFeatureLayer.Search(filter); List <object> _features = new List <object>(); List <object> _coordinates = new List <object>(); while (rowCursor.MoveNext()) { var row = rowCursor.Current; Feature feature = row as Feature; Polygon inPolygon = feature.GetShape() as Polygon; Polygon outPolygon = GeometryEngine.Instance.Project(inPolygon, outputSR) as Polygon; IReadOnlyList <Coordinate2D> pts = outPolygon.Copy2DCoordinatesToList(); //List<object> _coordinates = new List<object>(); List <object> _main_coordinates = new List <object>(); //List<object> _hole_coordinates = new List<object>(); // ignore hole coordinates foreach (var pt in pts) { double[] _pt = { pt.X, pt.Y }; _main_coordinates.Add(_pt); } _coordinates.Add(_main_coordinates); } var _geometry = new { type = "Polygon", coordinates = _coordinates }; var _properties = new { //OBJECTID = }; var _feature = new { type = "Feature", geometry = _geometry, properties = _properties }; _features.Add(_feature); var geojson_object = new { type = "FeatureCollection", features = _features }; // API accept multipolygon's geojson string geojson_string = JsonConvert.SerializeObject(geojson_object.features[0]); return geojson_string; })); }
protected override void OnClick() { QueuedTask.Run(() => Module1.Current.ClearGraphics()); }
// Reset Settings Based on Current Settings public async void ResetValues(string settingsValue) { // *** Check to ensure the densitysettings are set. If not, show a warning and deactivate tool. if (HighSetting == 0 || MediumSetting == 0 || LowSetting == 0 || TargetSetting == 0) { ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("An empty setting value exists. All settings are required to use this tool.", "Warning!"); // ** End if there are not complete settings return; } // else proceed with confirming a reset is desired. else { if (settingsValue == "current") { // Prompt for confirmation, and if answer is no, return. var result = ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("Reset all values to CURRENT settings?", "RESET VALUES", MessageBoxButton.OKCancel, MessageBoxImage.Asterisk); // Return if cancel value is chosen if (Convert.ToString(result) == "Cancel") { return; } } else if (settingsValue == "default") { // Prompt for confirmation, and if answer is no, return. var result = ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("Reset all values to DEFAULT settings?", "RESET VALUES", MessageBoxButton.OKCancel, MessageBoxImage.Asterisk); // Return if cancel value is chosen if (Convert.ToString(result) == "Cancel") { return; } } } FeatureLayer CrowdLayer = MapView.Active.Map.Layers.First(layer => layer.Name.Equals("CrowdPlanning")) as FeatureLayer; if (CrowdLayer == null) { ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("CrowdPlanning Layer is not found"); return; } ArcGIS.Core.Data.Table CrowdTable = await QueuedTask.Run(() => CrowdLayer.GetTable()); var editOperation = new EditOperation(); editOperation.Callback(context => { QueryFilter QF = new QueryFilter { WhereClause = "LOW > 0" }; RowCursor CrowdRow = CrowdTable.Search(QF, false); while (CrowdRow.MoveNext()) { using (Row currentRow = CrowdRow.Current) { var squarefeetValue = currentRow["Shape_Area"]; long squarefeetValueLong; squarefeetValueLong = Convert.ToInt64(squarefeetValue); if (settingsValue == "current") { currentRow["High"] = (squarefeetValueLong / HighSetting); currentRow["Medium"] = (squarefeetValueLong / MediumSetting); currentRow["Low"] = (squarefeetValueLong / LowSetting); currentRow["TargetSetting"] = TargetSetting; currentRow["HighSetting"] = HighSetting; currentRow["MediumSetting"] = MediumSetting; currentRow["LowSetting"] = LowSetting; } else if (settingsValue == "default") { currentRow["High"] = squarefeetValueLong / 2.5; currentRow["Medium"] = squarefeetValueLong / 4.5; currentRow["Low"] = squarefeetValueLong / 10; currentRow["TargetSetting"] = TargetSetting; currentRow["HighSetting"] = 2.5; currentRow["MediumSetting"] = 4.5; currentRow["LowSetting"] = 10; } // Store the values currentRow.Store(); // Has to be called after the store too. context.Invalidate(currentRow); } } CrowdTable.Dispose(); // close the editOperation.Callback(context }, CrowdTable); await editOperation.ExecuteAsync(); GetTotalValues(); }
public async Task SubmitExecute() { ValidationSubmitError = null; List <string> validationSubmitErrors = new List <string>(); string aoi = null; if (_selectedAOILayer != null) { if (_selectedAOILayer is FeatureLayer) { FeatureLayer lyr = _selectedAOILayer as FeatureLayer; int featureCount = await QueuedTask.Run(() => { return(lyr.GetFeatureClass().GetCount()); }); if (featureCount == 0) { validationSubmitErrors.Add("AOI is empty."); } else { aoi = await Ag_Analytics_Module.GetGeoJSONFromFeatureLayer(lyr); } } else if (_selectedAOILayer is RasterLayer) { RasterLayer lyr = _selectedAOILayer as RasterLayer; string default_path = Path.GetDirectoryName(Project.Current.URI); string timestamp = DateTime.Now.ToString("yyyyMMddHHmmss"); string rasterFileName = "AOI_Raster_" + timestamp + ".tif"; string outputRaster = Path.Combine(default_path, rasterFileName); var parameters = Geoprocessing.MakeValueArray(lyr.Name, outputRaster, "", "", "", false, false, "", false, false, "TIFF"); IGPResult result = await Geoprocessing.ExecuteToolAsync("management.CopyRaster", parameters, null, null, null, GPExecuteToolFlags.None); aoi = outputRaster; } } else { validationSubmitErrors.Add("AOI parameter must be selected."); } string selectedBands = null; List <string> _selectedBands = new List <string>(); foreach (var band in _bands) { if (band.Check_Status == true) { _selectedBands.Add(band.Band_Name); } } if (_selectedBands.Count > 0) { selectedBands = JsonConvert.SerializeObject(_selectedBands); } else { validationSubmitErrors.Add("Bands must be selected"); } //satellite: _selectedSatellite int _showLatestValue = _showLatest ? 1 : 0; string startDate = String.Format("{0:M/d/yyyy}", _startDate); string endDate = String.Format("{0:M/d/yyyy}", _endDate); if (!_showLatest) { if (DateTime.Compare(_startDate, _endDate) >= 0) { validationSubmitErrors.Add("Start Date must be earlier than End Date."); } } if (_downloadPath == null || string.IsNullOrEmpty(_downloadPath)) { validationSubmitErrors.Add("Download path must be selected."); } else { if (!Directory.Exists(_downloadPath)) { validationSubmitErrors.Add("Download path doesn't exsist."); } } SpatialReference outputSpatialReference = null; if (selectedSpatialReference == null) { outputSpatialReference = await QueuedTask.Run(() => { return(_selectedAOILayer.GetSpatialReference()); }); } else { outputSpatialReference = selectedSpatialReference; } if (outputSpatialReference.IsGeographic && _cellSize > 1) { validationSubmitErrors.Add("Resolution must be < 1 in geographic coordinate system(ex:0.0001)"); } else if (outputSpatialReference.IsProjected && _cellSize < 1) { validationSubmitErrors.Add("Resolution must be > 1 in projected coordinate system(ex:10)"); } if (validationSubmitErrors.Count > 0) { ValidationSubmitError = string.Join("\n", validationSubmitErrors); return; } if (validationInputError != null) { return; } //ProgressDialog progressDialog = new ProgressDialog("Please wait for result response..."); //progressDialog.Show(); int byweekValue = _checkbyweek ? 1 : 0; int filterValue = _checkfilter ? 1 : 0; int qafilterValue = _checkqafilter ? 1 : 0; int flattendataValue = _checkflattendata ? 1 : 0; SubmitButtonEnabled = false; ResultBoxVisible = "Hidden"; ProgressVisible = "Visible"; ProgressMessage = "Request Calling..."; DateTime started_datetime = DateTime.Now; SubmitStartedTime = started_datetime.ToString(); ResultErrorMessage = ""; IRestResponse apiResponse = await BackgroundTask.Run <IRestResponse>(() => { var client = new RestClient("https://ag-analytics.azure-api.net/hls-service/"); client.Timeout = -1; var request = new RestRequest(Method.POST); //request.AlwaysMultipartFormData = true; //request.AddHeader("Content-Type", "application/x-www-form-urlencoded"); if (_selectedAOILayer is FeatureLayer) { request.AddParameter("aoi", aoi); } else if (_selectedAOILayer is RasterLayer) { request.AddFile("aoi", aoi); } request.AddParameter("Band", selectedBands); request.AddParameter("satellite", _selectedSatellite); request.AddParameter("showlatest", _showLatestValue); request.AddParameter("Startdate", startDate); request.AddParameter("Enddate", endDate); request.AddParameter("resolution", _cellSize); request.AddParameter("displaynormalvalues", _displaynormalvalues); request.AddParameter("qacloudperc", _qacloudperc); request.AddParameter("byweek", byweekValue); request.AddParameter("filter", filterValue); request.AddParameter("qafilter", qafilterValue); request.AddParameter("flatten_data", flattendataValue); request.AddParameter("projection", outputSpatialReference.Wkt); // these parameter options no need on ArcGIS pro request.AddParameter("legendtype", "Relative"); request.AddParameter("statistics", 0); // set always 0 request.AddParameter("return_tif", 1); // set always 1 SubmitAOI = aoi; SubmitBand = selectedBands; SubmitSatellite = _selectedSatellite; SubmitShowLatest = _showLatestValue.ToString(); SubmitStartDate = startDate; SubmitEndDate = endDate; SubmitResolution = _cellSize.ToString(); SubmitDisplayNormalValues = _displaynormalvalues.ToString(); SubmitQacloudperc = _qacloudperc.ToString(); SubmitByWeek = byweekValue.ToString(); SubmitFilter = filterValue.ToString(); SubmitQaFilter = qafilterValue.ToString(); SubmitFlattenData = flattendataValue.ToString(); SubmitProjection = outputSpatialReference.Wkt; SubmitDownloadFolder = _downloadPath; IRestResponse response = client.Execute(request); return(response); }, BackgroundProgressor.None); if (File.Exists(aoi)) { string default_path = Path.GetDirectoryName(Project.Current.URI); string filesToDelete = Path.GetFileNameWithoutExtension(aoi) + ".*"; string[] fileList = Directory.GetFiles(default_path, filesToDelete); foreach (string file in fileList) { File.Delete(file); } } if (!apiResponse.IsSuccessful) { //ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show(response.ErrorMessage); //ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("Failed Result. Please try again."); ResultErrorMessage += "Response Error\n"; ResultErrorMessage += apiResponse.ErrorMessage; DisplayFailed(started_datetime); return; } dynamic jsonData = JsonConvert.DeserializeObject <dynamic>(apiResponse.Content); ProgressMessage = "Downloading tif files..."; try { foreach (dynamic item in jsonData) { string filename = item.download_url; await ExportFile(_downloadPath, filename); } } catch (Exception e) { //ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("HLS API Error. Please try again."); ResultErrorMessage += "Download Error\n"; ResultErrorMessage += e.Message; DisplayFailed(started_datetime); return; } //progressDialog.Hide(); ProgressVisible = "Hidden"; ProgressMessage = ""; DateTime ended_datetime = DateTime.Now; CompletedTime = ended_datetime.ToString(); int seconds = (int)(ended_datetime.Subtract(started_datetime).TotalSeconds); ElapsedTime = seconds.ToString() + " Seconds"; ResultBoxBGColor = "#3a593a"; ResultBoxImage = "pack://application:,,,/ArcGIS.Desktop.Resources;component/Images/DataReviewerLifecycleVerified32.png"; ResultBoxMessage = "Completed"; ResultErrorMessage = "There are no errors or warnings."; ResultBoxVisible = "Visible"; SubmitButtonEnabled = true; }
public Task <ReadOnlyObservableCollection <Bookmark> > GetProjectBookmarksAsync() { //Get the collection of bookmarks for the project. return(QueuedTask.Run(() => Project.Current.GetBookmarks())); }
private async Task AddPointsAsync() { try { // this doesn't work in real time because the layers are added asynchronously late var pointsLayer = MapView.Active.Map.GetLayersAsFlattenedList().Where((l) => l.Name == Module1.PointFcName).FirstOrDefault(); if (pointsLayer == null) { throw new Exception($@"Unable to find {Module1.PointFcName} Layer"); } var polyLayer = MapView.Active.Map.GetLayersAsFlattenedList().Where((l) => l.Name == Module1.PolyFcName).FirstOrDefault(); if (polyLayer == null) { throw new Exception($@"Unable to find {Module1.PolyFcName} Layer"); } await QueuedTask.Run(() => { // make 5 points var centerPt = MapView.Active.Extent.Center; List <MapPoint> mapPoints = new List <MapPoint>(); for (int pnt = 0; pnt < 5; pnt++) { mapPoints.Add(GeometryEngine.Instance.Move(centerPt, pnt * 150.0, pnt * 150.0) as MapPoint); } var editOp = new EditOperation { Name = "1. edit operation" }; int iMap = 0; foreach (var mp in mapPoints) { var attributes = new Dictionary <string, object> { { "Shape", mp.Clone() }, { "Description", $@"Map point: {++iMap}" } }; editOp.Create(pointsLayer, attributes); } var result1 = editOp.Execute(); if (result1 != true || editOp.IsSucceeded != true) { throw new Exception($@"Edit 1 failed: {editOp.ErrorMessage}"); } MessageBox.Show("1. edit operation complete"); editOp = new EditOperation { Name = "2. edit operation" }; foreach (var mp in mapPoints) { var attributes = new Dictionary <string, object> { { "Shape", GeometryEngine.Instance.Buffer(mp, 50.0) }, { "Description", $@"Polygon: {iMap--}" } }; editOp.Create(polyLayer, attributes); } //Execute the operations var result2 = editOp.Execute(); if (result2 != true || editOp.IsSucceeded != true) { throw new Exception($@"Edit 2 failed: {editOp.ErrorMessage}"); } MessageBox.Show("2. edit operation complete"); }); } catch (Exception ex) { MessageBox.Show($@"Error: {ex.ToString()}"); } }
protected override async void OnClick() { // make sure there's an OID from a created feature if (Module1.MultipatchOID == -1) { return; } if (MapView.Active?.Map == null) { return; } // find layer var member = MapView.Active.Map.GetLayersAsFlattenedList().FirstOrDefault(l => l.Name == "MultipatchWithTextureSimple") as FeatureLayer; if (member == null) { return; } // create the textures esriTextureCompressionType compressionType = esriTextureCompressionType.CompressionJPEG; byte[] brickImageBuffer = GetBufferImage("pack://application:,,,/MultipatchBuilderEx;component/Textures/Brick.jpg", compressionType); var brickTextureResource = new TextureResource(new JPEGTexture(brickImageBuffer)); BasicMaterial brickMaterialTexture = new BasicMaterial(); brickMaterialTexture.TextureResource = brickTextureResource; byte[] blocksImageBuffer = GetBufferImage("pack://application:,,,/MultipatchBuilderEx;component/Textures/Retaining_Blocks.jpg", compressionType); var blocksTextureResource = new TextureResource(new JPEGTexture(blocksImageBuffer)); BasicMaterial blockskMaterialTexture = new BasicMaterial(); blockskMaterialTexture.TextureResource = blocksTextureResource; byte[] waterImageBuffer = GetBufferImage("pack://application:,,,/MultipatchBuilderEx;component/Textures/water.jpg", compressionType); var waterTextureResource = new TextureResource(new JPEGTexture(waterImageBuffer)); BasicMaterial waterMaterialTexture = new BasicMaterial(); waterMaterialTexture.TextureResource = waterTextureResource; // set up a set of TextureCoordinates - these determine how the texture is draped over a face // In this scenario we will use the same textureCoordinates for each face var textureCoords = new List <Coordinate2D>() { new Coordinate2D(0, 0), new Coordinate2D(1, 0), new Coordinate2D(1, -1), new Coordinate2D(0, 0), new Coordinate2D(1, -1), new Coordinate2D(0, -1), }; bool result = await QueuedTask.Run(() => { // get the multipatch shape using the Inspector var insp = new Inspector(); insp.Load(member, Module1.MultipatchOID); var origMultipatch = insp.Shape as Multipatch; // create a builder var mpb = new ArcGIS.Core.Geometry.MultipatchBuilderEx(origMultipatch); // apply the texture materials to the patches var patches = mpb.Patches; patches[0].Material = brickMaterialTexture; patches[0].TextureCoords2D = textureCoords; patches[1].Material = blockskMaterialTexture; patches[1].TextureCoords2D = textureCoords; patches[2].Material = brickMaterialTexture; patches[2].TextureCoords2D = textureCoords; patches[3].Material = waterMaterialTexture; patches[3].TextureCoords2D = textureCoords; patches[4].Material = blockskMaterialTexture; patches[4].TextureCoords2D = textureCoords; patches[5].Material = waterMaterialTexture; patches[5].TextureCoords2D = textureCoords; // use this method to determine patches which contain the specified texture //var texture = mpb.QueryPatchIndicesWithTexture(brickTextureResource); // get the modified multipatch geometry var newMultipatch = mpb.ToGeometry() as Multipatch; // modify operation var modifyOp = new EditOperation(); modifyOp.Name = "Apply textures to multipatch"; modifyOp.Modify(member, Module1.MultipatchOID, newMultipatch); if (modifyOp.Execute()) { return(true); } return(false); }); }
/// <summary> /// Run the rotate selected junctions /// </summary> /// <param name="rotation">Rotation Angle</param> private void RotateSelectedJunctions(double rotation) { if (MapView.Active != null) { // Get the Network Diagram Layer DiagramLayer diagramLayer = GetDiagramLayerFromMap(MapView.Active.Map); if (diagramLayer != null) { QueuedTask.Run(() => { // Get the Network Diagram NetworkDiagram diagram = diagramLayer.GetNetworkDiagram(); if (diagram != null) { try { List <long> junctionObjectIDs = new List <long>(); // get the selection by Layer SelectionSet selection = MapView.Active.Map.GetSelection(); // Get the selection only for junctions foreach (var v in selection.ToDictionary()) { FeatureLayer featureLayer = v.Key as FeatureLayer; if (featureLayer != null) { if (featureLayer.ShapeType != esriGeometryType.esriGeometryPoint) { continue; } junctionObjectIDs.AddRange(v.Value); } } // if no junction selected, work on all diagram junctions DiagramElementQueryResult result; if (junctionObjectIDs.Count == 0) { DiagramElementQueryByElementTypes query = new DiagramElementQueryByElementTypes { QueryDiagramContainerElement = false, QueryDiagramEdgeElement = false, QueryDiagramJunctionElement = true }; result = diagram.QueryDiagramElements(query); } else { DiagramElementQueryByObjectIDs query = new DiagramElementQueryByObjectIDs { AddConnected = false, AddContents = false, JunctionObjectIDs = junctionObjectIDs }; result = diagram.QueryDiagramElements(query); } List <DiagramJunctionElement> junctionsToSave = new List <DiagramJunctionElement>(); // Set the new Rotation Value foreach (var junction in result.DiagramJunctionElements) { if (_isRelative) { junction.Rotation += rotation; } else { junction.Rotation = rotation; } junctionsToSave.Add(junction); } // Save junctions if needed if (junctionsToSave.Count() > 0) { NetworkDiagramSubset nds = new NetworkDiagramSubset { DiagramEdgeElements = null, DiagramContainerElements = null, DiagramJunctionElements = junctionsToSave }; diagram.SaveLayout(nds, true); MapView.Active.Redraw(true); // re set the selection if (selection.Count > 0) { MapView.Active.Map.SetSelection(selection, SelectionCombinationMethod.New); } } } catch (GeodatabaseException e) { MessageBox.Show(e.Message, "Failed to Rotate Junctions "); } } }); } } }
/// <summary> /// Asynchrnously start the visual magnitude analysis. /// </summary> public async void StartAnalysis() { if (!ValidateInputLayers()) { return; } outputFolder = CreateOutputDirectory(outputFolderName); if (File.Exists(outputFolder + "/" + SettingsManager.Instance.CurrentSettings.OutputFilename)) { System.Windows.MessageBoxResult messageResult = MessageBox.Show("The output file already exists and will be overwritten. Continue?", "File exists!", System.Windows.MessageBoxButton.OKCancel, System.Windows.MessageBoxImage.Warning); if (messageResult == System.Windows.MessageBoxResult.OK) { GarbageHelper.Instance.AddGarbage(outputFolder + "/" + SettingsManager.Instance.CurrentSettings.OutputFilename); GarbageHelper.Instance.CleanUp(); } else { return; } } if (File.Exists(outputFolder + "/" + tmpRasterName)) { GarbageHelper.Instance.AddGarbage(outputFolder + "/" + tmpRasterName); GarbageHelper.Instance.CleanUp(); } ///most tasks have to run on MCT thread await QueuedTask.Run(async() => { outputFolder = CreateOutputDirectory(outputFolderName); FileSystemDatastore outputDataStore = CreateNewDatastore(); //get viewpoints Raster raster = SettingsManager.Instance.SelectedDemLayer.GetRaster(); Projection projection = new Projection(raster, outputFolder); //make the detection automatic try { if (await projection.CalculateViewpoints(SettingsManager.Instance.SelectedViewpointLayer) == false) { MessageBox.Show("Invalid viewpoint layer type.\nOnly points, lines and polylines are supported.", "Error", System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Error); return; } } catch (Exception) { if (!SettingsManager.Instance.CurrentSettings.OffsetGlobal) { MessageBox.Show("Invalid viewpoint data. Do the viewpoints have OFFSET column specified?", "Error", System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Error); } else if (SettingsManager.Instance.CurrentSettings.WeightedViewpoints) { MessageBox.Show("Invalid viewpoint data. Do the viewpoints have WEIGHT column specified?", "Error", System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Error); } else { MessageBox.Show("Invalid viewpoint data.", "Error", System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Error); } return; } GeoMap elevationMap = CreateElevationMap(raster); //initialize work manager WorkManager workManager = new WorkManager(SettingsManager.Instance.CurrentSettings.WorkerThreads); int invalidViewpointsCount = 0; foreach (SpatialUtils.ViewpointProps viewpoint in projection) { if (viewpoint.Y < 0 || viewpoint.X < 0) { invalidViewpointsCount++; } else { if (SettingsManager.Instance.CurrentSettings.OffsetGlobal) { viewpoint.ElevationOffset = SettingsManager.Instance.CurrentSettings.AltOffset; } workManager.AddWork(viewpoint); } } if (invalidViewpointsCount > 0) { string message = invalidViewpointsCount.ToString() + (invalidViewpointsCount == 1 ? " viewpoint was invalid or failed to process." : " viewpoints were invalid or failed to process."); MessageBox.Show(message, "Ignored viewpoints", System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Warning); } //wait for the calculation of the visual magnitude for all viewpoints to finish var watch = System.Diagnostics.Stopwatch.StartNew(); workManager.StartWorking(ref elevationMap); WorkManager.AutoEvent.WaitOne(); GeoMap result = workManager.GetResult(); MessageBox.Show("Computation finished\n------------\nTime: " + watch.ElapsedMilliseconds / 1000 + " seconds\nViewpoints: " + projection.GetViewpointsCount(), "Finished", System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Information); //save and display the result try { WriteToRaster(raster, outputDataStore, result); } catch (Exception) { MessageBox.Show("Cannot write data to raster.", "Error", System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Error); } LayerFactory.Instance.CreateLayer(new Uri(Path.Combine(outputFolder, SettingsManager.Instance.CurrentSettings.OutputFilename)), MapView.Active.Map); //clean up temporary files GarbageHelper.Instance.CleanUp(); }); }
public void RunApplyTextTool() { QueuedTask.Run(() => { // Take the currently selected text and update it as needed // get the first graphics layer in the map's collection of graphics layers var graphicsLayer = MapView.Active.Map.GetLayersAsFlattenedList() .OfType <ArcGIS.Desktop.Mapping.GraphicsLayer>().FirstOrDefault(); if (graphicsLayer == null) { return; } var selectedGraphicLayers = MapView.Active.GetSelectedLayers().OfType <GraphicsLayer>(); if (selectedGraphicLayers.Count() == 0) { //nothing selected. So clear the selected graphic layer. SelectedGraphicsLayerTOC = null; MessageBox.Show("No graphic layer selected.", "Select layer"); return; } SelectedGraphicsLayerTOC = selectedGraphicLayers.FirstOrDefault(); var selectedElements = graphicsLayer.GetSelectedElements(). OfType <GraphicElement>().Where(elem => elem.GetGraphic() is CIMTextGraphic || elem.GetGraphic() is CIMParagraphTextGraphic); if (selectedElements.Count() == 0) { //nothing selected. So clear the selected graphic layer. MessageBox.Show("No Text or Paragraph Text workflow graphics selected.", "Select graphics"); return; } // Get the editbox or the dockpane textbox value string txtBoxString = null; string queryTxtBoxString = null; if (Module1.Current.blnDockpaneOpenStatus == false) { // Use values in the edit boxes txtBoxString = Module1.Current.TextValueEditBox.Text; queryTxtBoxString = Module1.Current.QueryValueEditBox.Text; if (txtBoxString == null || txtBoxString == "") { txtBoxString = " Default Text"; } else { txtBoxString = " " + txtBoxString; } if (queryTxtBoxString != null && queryTxtBoxString != "") { txtBoxString = txtBoxString + "\r\n " + queryTxtBoxString; } } if (Module1.Current.blnDockpaneOpenStatus == true) { _dockpane = FrameworkApplication.DockPaneManager.Find("GraphicTools_TextPane") as TextPaneViewModel; txtBoxString = _dockpane.TxtBoxDoc; queryTxtBoxString = _dockpane.QueryTxtBoxDoc; if (txtBoxString == null || txtBoxString == "") { txtBoxString = " Default Text"; } else { txtBoxString = " " + txtBoxString; } if (queryTxtBoxString != null && queryTxtBoxString != "") { txtBoxString = txtBoxString + "\r\n " + queryTxtBoxString; } } foreach (var elem in selectedElements) { // Get the CIMTextGraphic of the current text graphic and update it with contents of text box if (elem.GetGraphic() is CIMTextGraphic) { var newCIMGraphic = elem.GetGraphic() as CIMTextGraphic; newCIMGraphic.Text = txtBoxString; elem.SetGraphic(newCIMGraphic); } // Get the CIMParagraphTextGraphic of the current text graphic and update it with contents of text box if (elem.GetGraphic() is CIMParagraphTextGraphic) { var newCIMGraphic = elem.GetGraphic() as CIMParagraphTextGraphic; newCIMGraphic.Text = txtBoxString; elem.SetGraphic(newCIMGraphic); } } SelectedGraphicsLayerTOC.ClearSelection(); }); }
/// <summary> /// Called when a sketch is completed. /// </summary> protected override async Task <bool> OnSketchCompleteAsync(ArcGIS.Core.Geometry.Geometry geometry) { List <PopupContent> popupContent = await QueuedTask.Run(() => { //Get the features that intersect the sketch geometry. var mapPoint = geometry as MapPoint; var sb = new StringBuilder(); sb.AppendLine(string.Format("OnSketchCompleteAsync X: {0}", mapPoint.X)); sb.Append(string.Format("Y: {0}", mapPoint.Y)); if (mapPoint.HasZ) { sb.AppendLine(); sb.Append(string.Format("Z: {0}", mapPoint.Z)); } MessageBox.Show(sb.ToString()); var result = ActiveMapView.GetFeatures(geometry); //For each feature in the result create a new instance of our custom pop-up content class. List <PopupContent> popups = new List <PopupContent>(); foreach (var kvp in result) { //kvp.Value.ForEach(id => popups.Add(new DynamicPopupContent(kvp.Key, id))); //kvp.Value.ForEach(id => popups.Add(new PopupContent(new Uri("https://www.google.com/webhp?ie=UTF-8&rct=j"), "xxxx"))); //popups.Add(new PopupContent("<b>This text is bold.</b>", "Custom tooltip from HTML string")); var layer = kvp.Key as BasicFeatureLayer; if (layer == null) { continue; } var fields = layer.GetFieldDescriptions().Where(f => f.Name == "DI_JI_HAO"); var tableDef = layer.GetTable().GetDefinition(); var oidField = tableDef.GetObjectIDField(); foreach (var id in kvp.Value) { //获取地级编号 //DI_JI_HAO var qf = new QueryFilter() { WhereClause = $"{oidField} = {id}", SubFields = string.Join(",", fields.Select(f => f.Name)) }; var rows = layer.Search(qf); if (!rows.MoveNext()) { continue; } using (var row = rows.Current) { foreach (var field in fields) { var val = row[field.Name]; if (field.Name == "DI_JI_HAO") { PopupContent pc = new PopupContent(new Uri("http://59.42.105.34:5001/client/?id=" + val), "林业"); popups.Add(pc); } } } } } //Flash the features that intersected the sketch geometry. ActiveMapView.FlashFeature(result); //return the collection of pop-up content object. return(popups); }); var height = System.Windows.SystemParameters.WorkArea.Height / 2; var width = System.Windows.SystemParameters.WorkArea.Width / 2; var topLeftCornerPoint = new System.Windows.Point(0, 0); var popupDef = new PopupDefinition() { Append = true, // if true new record is appended to existing (if any) Dockable = true, // if true popup is dockable - if false Append is not applicable Position = topLeftCornerPoint, // Position of top left corner of the popup (in pixels) Size = new System.Windows.Size(width, height) // size of the popup (in pixels) }; //Show the custom pop-up with the custom commands and the default pop-up commands. ActiveMapView.ShowCustomPopup(popupContent, null, true, popupDef); return(true); }
public void UpdateColor(string colorValue) { // Update Status Color for Selected Point and Polygon Graphics QueuedTask.Run(() => { // Take the currently selected text and update it as needed // get the first graphics layer in the map's collection of graphics layers var graphicsLayer = MapView.Active.Map.GetLayersAsFlattenedList() .OfType <ArcGIS.Desktop.Mapping.GraphicsLayer>().FirstOrDefault(); if (graphicsLayer == null) { return; } var selectedGraphicLayers = MapView.Active.GetSelectedLayers().OfType <GraphicsLayer>(); if (selectedGraphicLayers.Count() == 0) { //nothing selected. So clear the selected graphic layer. SelectedGraphicsLayerTOC = null; MessageBox.Show("No graphic layer selected.", "Select layer"); return; } SelectedGraphicsLayerTOC = selectedGraphicLayers.FirstOrDefault(); var selectedElements = graphicsLayer.GetSelectedElements(). OfType <GraphicElement>().Where(elem => elem.GetGraphic() is CIMPolygonGraphic || elem.GetGraphic() is CIMPointGraphic); if (selectedElements.Count() == 0) { //nothing selected. So clear the selected graphic layer. MessageBox.Show("No point or polygon workflow graphics selected.", "Select graphics"); return; } CIMColor myColor = null; switch (colorValue) { case "red": myColor = CIMColor.CreateRGBColor(255, 0, 0, 40); break; case "yellow": myColor = CIMColor.CreateRGBColor(255, 255, 0, 40); break; case "green": myColor = CIMColor.CreateRGBColor(0, 255, 0, 40); break; } foreach (var elem in selectedElements) { // Get the CIM Graphic and update it if (elem.GetGraphic() is CIMPolygonGraphic) { var newCIMGraphic = elem.GetGraphic() as CIMPolygonGraphic; CIMPolygonSymbol polySymbol = SymbolFactory.Instance.ConstructPolygonSymbol(myColor); // (CIMColor.CreateRGBColor(CreateRGBColor(0, 255, 0, 50)); newCIMGraphic.Symbol = polySymbol.MakeSymbolReference(); elem.SetGraphic(newCIMGraphic); } if (elem.GetGraphic() is CIMPointGraphic) { var newCIMGraphic = elem.GetGraphic() as CIMPointGraphic; CIMPointSymbol pointSymbol = SymbolFactory.Instance.ConstructPointSymbol(myColor); // (CIMColor.CreateRGBColor(CreateRGBColor(0, 255, 0, 50)); newCIMGraphic.Symbol = pointSymbol.MakeSymbolReference(); elem.SetGraphic(newCIMGraphic); } } }); }
private async Task ExecuteVisibilityRLOS() { try { var surfaceSR = await GetSpatialReferenceFromLayer(SelectedSurfaceName); if (surfaceSR == null || !surfaceSR.IsProjected) { MessageBox.Show(VisibilityLibrary.Properties.Resources.RLOSUserPrompt, VisibilityLibrary.Properties.Resources.RLOSUserPromptCaption); return; } await FeatureClassHelper.CreateLayer(ObserversLayerName, "POINT", true, true); // add fields for observer offset await FeatureClassHelper.AddFieldToLayer(ObserversLayerName, VisibilityLibrary.Properties.Resources.OffsetFieldName, "DOUBLE"); await FeatureClassHelper.AddFieldToLayer(ObserversLayerName, VisibilityLibrary.Properties.Resources.OffsetWithZFieldName, "DOUBLE"); // add observer points to feature layer await FeatureClassHelper.CreatingFeatures(ObserversLayerName, ObserverAddInPoints, GetAsMapZUnits(surfaceSR, ObserverOffset.Value)); // update with surface information await FeatureClassHelper.AddSurfaceInformation(ObserversLayerName, SelectedSurfaceName, VisibilityLibrary.Properties.Resources.ZFieldName); // Visibility var observerOffsetInMapZUnits = GetAsMapZUnits(surfaceSR, ObserverOffset.Value); var surfaceOffsetInMapZUnits = GetAsMapZUnits(surfaceSR, SurfaceOffset); var minDistanceInMapUnits = GetAsMapUnits(surfaceSR, MinDistance); var maxDistanceInMapUnits = GetAsMapUnits(surfaceSR, MaxDistance); var horizontalStartAngleInDegrees = GetAngularDistanceFromTo(AngularUnitType, AngularTypes.DEGREES, LeftHorizontalFOV); var horizontalEndAngleInDegrees = GetAngularDistanceFromTo(AngularUnitType, AngularTypes.DEGREES, RightHorizontalFOV); var verticalUpperAngleInDegrees = GetAngularDistanceFromTo(AngularUnitType, AngularTypes.DEGREES, TopVerticalFOV); var verticalLowerAngleInDegrees = GetAngularDistanceFromTo(AngularUnitType, AngularTypes.DEGREES, BottomVerticalFOV); await FeatureClassHelper.UpdateShapeWithZ(ObserversLayerName, VisibilityLibrary.Properties.Resources.ZFieldName, observerOffsetInMapZUnits); string maskFeatureClassName = CoreModule.CurrentProject.DefaultGeodatabasePath + "\\" + RLOSMaskLayerName; await CreateMask(RLOSMaskLayerName, maxDistanceInMapUnits, surfaceSR); var environments = Geoprocessing.MakeEnvironmentArray(mask: maskFeatureClassName, overwriteoutput: true); var rlosOutputLayer = CoreModule.CurrentProject.DefaultGeodatabasePath + "\\" + RLOSOutputLayerName; await FeatureClassHelper.CreateVisibility(SelectedSurfaceName, ObserversLayerName, rlosOutputLayer, observerOffsetInMapZUnits, surfaceOffsetInMapZUnits, minDistanceInMapUnits, maxDistanceInMapUnits, horizontalStartAngleInDegrees, horizontalEndAngleInDegrees, verticalUpperAngleInDegrees, verticalLowerAngleInDegrees, ShowNonVisibleData, environments, false); var rlosConvertedPolygonsLayer = CoreModule.CurrentProject.DefaultGeodatabasePath + "\\" + RLOSConvertedPolygonsLayerName; await FeatureClassHelper.IntersectOutput(rlosOutputLayer, rlosConvertedPolygonsLayer, false, "Value"); await FeatureClassHelper.CreateUniqueValueRenderer(GetLayerFromMapByName(RLOSConvertedPolygonsLayerName) as FeatureLayer, ShowNonVisibleData, RLOSConvertedPolygonsLayerName); // Eventually we will add the new layers to a new group layer for each run // Currently not working in current release of Pro. // From Roshan Herbert - I just spoke with the Dev who wrote the MoveLayer method. Apparently this a known issue. // We have bug to fix this and plan to fix it in the next release. List <Layer> layerList = new List <Layer>(); layerList.Add(GetLayerFromMapByName(ObserversLayerName)); //layerList.Add(GetLayerFromMapByName(RLOSConvertedPolygonsLayerName)); //string groupName = "RLOS Group"; //if (executionCounter > 0) // groupName = string.Format("{0}_{1}", groupName, executionCounter.ToString()); //await FeatureClassHelper.CreateGroupLayer(layerList, groupName); // for now we are not resetting after a run of the tool //await Reset(true); // Get the extent of the output layer and zoom to extent var layer = GetLayerFromMapByName(RLOSConvertedPolygonsLayerName); if (layer != null) { var envelope = await QueuedTask.Run(() => layer.QueryExtent()); await ZoomToExtent(envelope); } executionCounter++; } catch (Exception ex) { Debug.Print(ex.Message); } }
/// <summary> /// In order to illustrate that Geodatabase calls have to be made on the MCT /// </summary> /// <returns></returns> public async Task RowUpdateAttachmentAsync() { await QueuedTask.Run(() => MainMethodCode()); }
/// <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(); } } }
private void MakeDisplayUnitAsDefault() { MessageBox.Show("Make Default"); QueuedTask.Run(() => { DisplayUnitFormats.Instance.SetDefaultProjectUnitFormat(this._displayUnitFormat); }); }
async public void snippets_ProjectItems() { #region Reference layout project items //A layout project item is an item that appears in the Layouts folder in the Catalog pane //Reference all the layout project items IEnumerable <LayoutProjectItem> layouts = Project.Current.GetItems <LayoutProjectItem>(); //Or reference a specific layout project item by name LayoutProjectItem layoutItem = Project.Current.GetItems <LayoutProjectItem>().FirstOrDefault(item => item.Name.Equals("MyLayout")); #endregion #region Open a layout project item in a new view //A layout project item may be in a project but it may not be open in a view and/or active //First get the layout associated with the layout project item Layout layout = layoutItem.GetLayout(); //Open a new pane ILayoutPane iNewLayoutPane = await ProApp.Panes.CreateLayoutPaneAsync(layout); #endregion #region Activate an already open layout view //A layout view may exist but it may not be active //Iterate through each pane in the application and check to see if the layout is already open and if so, activate it foreach (var pane in ProApp.Panes) { var layoutPane = pane as ILayoutPane; if (layoutPane == null) //if not a layout view, continue to the next pane { continue; } if (layoutPane.LayoutView.Layout == layout) //if there is a match, activate the view { (layoutPane as Pane).Activate(); return; } } #endregion #region Reference the active layout view //First check to see if the current, active view is a layout view. If it is, use it LayoutView activeLayoutView = LayoutView.Active; if (activeLayoutView != null) { // use activeLayoutView } #endregion #region Create a new, basic layout and open it //Create a new layout project item layout in the project Layout newLayout = await QueuedTask.Run <Layout>(() => { newLayout = LayoutFactory.Instance.CreateLayout(8.5, 11, LinearUnit.Inches); newLayout.SetName("New 8.5x11 Layout"); return(newLayout); }); //Open new layout on the GUI thread await ProApp.Panes.CreateLayoutPaneAsync(newLayout); #endregion #region Create a new layout using a modified CIM and open it //Create a new layout project item layout in the project Layout newCIMLayout = await QueuedTask.Run <Layout>(() => { //Set up a CIM page CIMPage newPage = new CIMPage { //required parameters Width = 8.5, Height = 11, Units = LinearUnit.Inches, //optional rulers ShowRulers = true, SmallestRulerDivision = 0.5, //optional guides ShowGuides = true }; CIMGuide guide1 = new CIMGuide { Position = 1, Orientation = Orientation.Vertical }; CIMGuide guide2 = new CIMGuide { Position = 6.5, Orientation = Orientation.Vertical }; CIMGuide guide3 = new CIMGuide { Position = 1, Orientation = Orientation.Horizontal }; CIMGuide guide4 = new CIMGuide { Position = 10, Orientation = Orientation.Horizontal }; List <CIMGuide> guideList = new List <CIMGuide> { guide1, guide2, guide3, guide4 }; newPage.Guides = guideList.ToArray(); //Create a new page newCIMLayout = LayoutFactory.Instance.CreateLayout(newPage); newCIMLayout.SetName("New 8.5x11 Layout"); return(newCIMLayout); }); //Open new layout on the GUI thread await ProApp.Panes.CreateLayoutPaneAsync(newCIMLayout); #endregion #region Import a pagx into a project //Create a layout project item from importing a pagx file IProjectItem pagx = ItemFactory.Instance.Create(@"C:\Temp\Layout.pagx") as IProjectItem; Project.Current.AddItem(pagx); #endregion #region Remove a layout project item //Remove a layout from the project completely Project.Current.RemoveItem(layoutItem); #endregion }
public async Task MedataExamples() { string sourceXMLMetadataAsString = string.Empty; #region Item: Get its IMetadata interface Item gdbItem = ItemFactory.Instance.Create(@"C:\projectAlpha\GDBs\regionFive.gdb"); IMetadata gdbMetadataItem = gdbItem as IMetadata; #endregion #region Item: Get an item's metadata: GetXML string gdbXMLMetadataXmlAsString = string.Empty; gdbXMLMetadataXmlAsString = await QueuedTask.Run(() => gdbMetadataItem.GetXml()); //check metadata was returned if (!string.IsNullOrEmpty(gdbXMLMetadataXmlAsString)) { //use the metadata } #endregion IMetadata featureClassMetadataItem = null; #region Item: Set the metadata of an item: SetXML await QueuedTask.Run(() => { var xml = System.IO.File.ReadAllText(@"E:\Data\Metadata\MetadataForFeatClass.xml"); //Will throw InvalidOperationException if the metadata cannot be changed //so check "CanEdit" first if (featureClassMetadataItem.CanEdit()) { featureClassMetadataItem.SetXml(xml); } }); #endregion IMetadata metadataItemToCheck = null; #region Item: Check the metadata can be edited: CanEdit bool canEdit1; //Call CanEdit before calling SetXml await QueuedTask.Run(() => canEdit1 = metadataItemToCheck.CanEdit()); #endregion IMetadata metadataItemToSync = null; #region Item: Updates metadata with the current properties of the item: Synchronize string syncedMetadataXml = string.Empty; await QueuedTask.Run(() => syncedMetadataXml = metadataItemToSync.Synchronize()); #endregion IMetadata metadataCopyFrom = null; IMetadata metadataItemImport = null; #region Item: Copy metadata from the source item's metadata: CopyMetadataFromItem Item featureClassItem = ItemFactory.Instance.Create(@"C:\projectAlpha\GDBs\regionFive.gdb\SourceFeatureClass"); await QueuedTask.Run(() => metadataItemImport.CopyMetadataFromItem(featureClassItem)); #endregion //Item gdbItem = ItemFactory.Instance.Create(@"C:\projectAlpha\GDBs\regionFive.gdb"); #region Item: Updates metadata with the imported metadata - the input path can be the path to an item with metadata, or a URI to a XML file: ImportMetadata // the input path can be the path to an item with metadata, or a URI to an XML file IMetadata metadataItemImport1 = null; await QueuedTask.Run(() => metadataItemImport1.ImportMetadata(@"E:\YellowStone.gdb\MyDataset\MyFeatureClass", MDImportExportOption.esriCurrentMetadataStyle)); #endregion IMetadata metadataItemImport2 = null; #region Item: Updates metadata with the imported metadata: ImportMetadata // the input path can be the path to an item with metadata, or a URI to an XML file await QueuedTask.Run(() => metadataItemImport2.ImportMetadata(@"E:\YellowStone.gdb\MyDataset\MyFeatureClass", MDImportExportOption.esriCustomizedStyleSheet, @"E:\StyleSheets\Import\MyImportStyleSheet.xslt")); #endregion IMetadata metadataItemExport1 = null; #region Item: export the metadata of the currently selected item: ExportMetadata await QueuedTask.Run(() => metadataItemExport1.ExportMetadata(@"E:\Temp\OutputXML.xml", MDImportExportOption.esriCurrentMetadataStyle, MDExportRemovalOption.esriExportExactCopy)); #endregion IMetadata metadataItemExport2 = null; #region Item: export the metadata of the currently selected item: ExportMetadata await QueuedTask.Run(() => metadataItemExport2.ExportMetadata(@"E:\Temp\OutputXML.xml", MDImportExportOption.esriCustomizedStyleSheet, MDExportRemovalOption.esriExportExactCopy, @"E:\StyleSheets\Export\MyExportStyleSheet.xslt")); #endregion IMetadata metadataItemToSaveAsXML = null; #region Item: Save the metadata of the current item as XML: SaveMetadataAsXML await QueuedTask.Run(() => metadataItemToSaveAsXML.SaveMetadataAsXML(@"E:\Temp\OutputXML.xml", MDSaveAsXMLOption.esriExactCopy)); #endregion IMetadata metadataItemToSaveAsHTML = null; #region Item: Save the metadata of the current item as HTML: SaveMetadataAsHTML await QueuedTask.Run(() => metadataItemToSaveAsHTML.SaveMetadataAsHTML(@"E:\Temp\OutputHTML.htm", MDSaveAsHTMLOption.esriCurrentMetadataStyle)); #endregion IMetadata metadataItemToSaveAsUsingCustomXSLT = null; #region Item: Save the metadata of the current item using customized XSLT: SaveMetadataAsUsingCustomXSLT await QueuedTask.Run(() => metadataItemToSaveAsUsingCustomXSLT.SaveMetadataAsUsingCustomXSLT(@"E:\Data\Metadata\CustomXSLT.xsl", @"E:\Temp\OutputXMLCustom.xml")); #endregion #region Item: Upgrade the metadata of the current item: UpgradeMetadata var fgdcItem = ItemFactory.Instance.Create(@"C:\projectAlpha\GDBs\testData.gdb"); await QueuedTask.Run(() => fgdcItem.UpgradeMetadata(MDUpgradeOption.esriUpgradeFgdcCsdgm)); #endregion }
public void snippets_UpdateElements() { double x = 0; double y = 0; #region Update Text Element properties // Reference a layoutitem in a project by name LayoutProjectItem layoutItem = Project.Current.GetItems <LayoutProjectItem>().FirstOrDefault(item => item.Name.Equals("MyLayout")); if (layoutItem != null) { QueuedTask.Run(() => { // Reference and load the layout associated with the layout item Layout layout = layoutItem.GetLayout(); if (layout != null) { // Reference a text element by name TextElement txtElm = layout.FindElement("MyTextElement") as TextElement; if (txtElm != null) { // Change placement properties txtElm.SetAnchor(Anchor.CenterPoint); txtElm.SetX(x); txtElm.SetY(y); // Change TextProperties TextProperties txtProperties = new TextProperties("Hello world", "Times New Roman", 48, "Regular"); txtElm.SetTextProperties(txtProperties); } } }); } #endregion #region Update a picture element QueuedTask.Run(() => { // Reference and load the layout associated with the layout item Layout layout = layoutItem.GetLayout(); if (layout != null) { // Reference a picture element by name PictureElement picElm = layout.FindElement("MyPicture") as PictureElement; // Change the path to a new source if (picElm != null) { picElm.SetSourcePath(@"D:\MyData\Pics\somePic.jpg"); } } }); #endregion #region Update a map surround QueuedTask.Run(() => { // Reference and load the layout associated with the layout item Layout layout = layoutItem.GetLayout(); if (layout != null) { // Reference a scale bar element by name MapSurround scaleBar = layout.FindElement("MyScaleBar") as MapSurround; // Reference a map frame element by name MapFrame mf = layout.FindElement("MyMapFrame") as MapFrame; if ((scaleBar != null) && (mf != null)) { //Set the scale bar to the newly referenced map frame scaleBar.SetMapFrame(mf); } } }); #endregion #region Lock an element // The Locked property is displayed in the TOC as a lock symbol next to each element. // If locked the element can't be selected in the layout using the graphic // selection tools. QueuedTask.Run(() => { // Reference and load the layout associated with the layout item Layout layout = layoutItem.GetLayout(); if (layout != null) { //Reference an element by name Element element = layout.FindElement("MyElement"); if (element != null) { // Modify the Locked property via the CIM CIMElement CIMElement = element.GetDefinition() as CIMElement; CIMElement.Locked = true; element.SetDefinition(CIMElement); } } }); #endregion #region Update an elements transparency QueuedTask.Run(() => { // Reference and load the layout associated with the layout item Layout layout = layoutItem.GetLayout(); if (layout != null) { // Reference a element by name GraphicElement graphicElement = layout.FindElement("MyElement") as GraphicElement; if (graphicElement != null) { // Modify the Transparency property that exists only in the CIMGraphic class. CIMGraphic CIMGraphic = graphicElement.Graphic as CIMGraphic; CIMGraphic.Transparency = 50; // mark it 50% transparent graphicElement.SetGraphic(CIMGraphic); } } }); #endregion double xOffset = 0; double yOffset = 0; #region Clone an element QueuedTask.Run(() => { // Reference and load the layout associated with the layout item Layout layout = layoutItem.GetLayout(); if (layout != null) { // Reference a element by name GraphicElement graphicElement = layout.FindElement("MyElement") as GraphicElement; if (graphicElement != null) { // clone and set the new x,y GraphicElement cloneElement = graphicElement.Clone("Clone"); cloneElement.SetX(cloneElement.GetX() + xOffset); cloneElement.SetY(cloneElement.GetY() + yOffset); } } }); #endregion }
public async void ContentSnippets2() { #region Create new project using Pro's default settings //Get Pro's default project settings. var defaultProjectSettings = Project.GetDefaultProjectSettings(); //Create a new project using the default project settings await Project.CreateAsync(defaultProjectSettings); #endregion #region New project using a custom template file //Settings used to create a new project CreateProjectSettings projectSettings = new CreateProjectSettings() { //Sets the project's name Name = "New Project", //Path where new project will be stored in LocationPath = @"C:\Data\NewProject", //Sets the project template that will be used to create the new project TemplatePath = @"C:\Data\MyProject1\CustomTemplate.aptx" }; //Create the new project await Project.CreateAsync(projectSettings); #endregion #region Create project using template available with ArcGIS Pro //Settings used to create a new project CreateProjectSettings proTemplateSettings = new CreateProjectSettings() { //Sets the project's name Name = "New Project", //Path where new project will be stored in LocationPath = @"C:\Data\NewProject", //Select which Pro template you like to use TemplateType = TemplateType.Catalog //TemplateType = TemplateType.LocalScene //TemplateType = TemplateType.GlobalScene //TemplateType = TemplateType.Map }; //Create the new project await Project.CreateAsync(proTemplateSettings); #endregion #region Open project //Opens an existing project or project package await Project.OpenAsync(@"C:\Data\MyProject1\MyProject1.aprx"); #endregion #region Current project //Gets the current project var project = Project.Current; #endregion #region Get location of current project //Gets the location of the current project; that is, the path to the current project file (*.aprx) string projectPath = Project.Current.URI; #endregion #region Get the project's default gdb path var projGDBPath = Project.Current.DefaultGeodatabasePath; #endregion #region Save project //Saves the project await Project.Current.SaveAsync(); #endregion #region SaveAs project //Saves a copy of the current project file (*.aprx) to the specified location with the specified file name, //then opens the new project file await Project.Current.SaveAsAsync(@"C:\Data\MyProject1\MyNewProject1.aprx"); #endregion #region Close project //A project cannot be closed using the ArcGIS Pro API. //A project is only closed when another project is opened, a new one is created, or the application is shutdown. #endregion #region Adds item to the current project //Adding a folder connection string folderPath = "@C:\\myDataFolder"; var folder = await QueuedTask.Run(() => { //Create the folder connection project item var item = ItemFactory.Instance.Create(folderPath) as IProjectItem; //If it is succesfully added to the project, return it otherwise null return(Project.Current.AddItem(item) ? item as FolderConnectionProjectItem : null); }); //Adding a Geodatabase: string gdbPath = "@C:\\myDataFolder\\myData.gdb"; var newlyAddedGDB = await QueuedTask.Run(() => { //Create the File GDB project item var item = ItemFactory.Instance.Create(gdbPath) as IProjectItem; //If it is succesfully added to the project, return it otherwise null return(Project.Current.AddItem(item) ? item as GDBProjectItem : null); }); #endregion #region How to add a new map to a project await QueuedTask.Run(() => { //Note: see also MapFactory in ArcGIS.Desktop.Mapping var map = MapFactory.Instance.CreateMap("New Map", MapType.Map, MapViewingMode.Map, Basemap.Oceans); ProApp.Panes.CreateMapPaneAsync(map); }); #endregion #region Check if project needs to be saved //The project's dirty state indicates changes made to the project have not yet been saved. bool isProjectDirty = Project.Current.IsDirty; #endregion #region Get all the project items IEnumerable <Item> allProjectItems = Project.Current.GetItems <Item>(); foreach (var pi in allProjectItems) { //Do Something } #endregion #region Gets all the "MapProjectItems" IEnumerable <MapProjectItem> newMapItemsContainer = project.GetItems <MapProjectItem>(); await QueuedTask.Run(() => { foreach (var mp in newMapItemsContainer) { //Do Something with the map. For Example: Map myMap = mp.GetMap(); } }); #endregion #region Gets a specific "MapProjectItem" MapProjectItem mapProjItem = Project.Current.GetItems <MapProjectItem>().FirstOrDefault(item => item.Name.Equals("EuropeMap")); #endregion #region Gets all the "StyleProjectItems" IEnumerable <StyleProjectItem> newStyleItemsContainer = null; newStyleItemsContainer = Project.Current.GetItems <StyleProjectItem>(); foreach (var styleItem in newStyleItemsContainer) { //Do Something with the style. } #endregion #region Gets a specific "StyleProjectItem" var container = Project.Current.GetItems <StyleProjectItem>(); StyleProjectItem testStyle = container.FirstOrDefault(style => (style.Name == "ArcGIS 3D")); StyleItem cone = null; if (testStyle != null) { cone = testStyle.LookupItem(StyleItemType.PointSymbol, "Cone_Volume_3"); } #endregion #region Gets all the "GDBProjectItems" IEnumerable <GDBProjectItem> newGDBItemsContainer = null; newGDBItemsContainer = Project.Current.GetItems <GDBProjectItem>(); foreach (var GDBItem in newGDBItemsContainer) { //Do Something with the GDB. } #endregion #region Gets a specific "GDBProjectItem" GDBProjectItem GDBProjItem = Project.Current.GetItems <GDBProjectItem>().FirstOrDefault(item => item.Name.Equals("myGDB")); #endregion #region Gets all the "ServerConnectionProjectItem" IEnumerable <ServerConnectionProjectItem> newServerConnections = null; newServerConnections = project.GetItems <ServerConnectionProjectItem>(); foreach (var serverItem in newServerConnections) { //Do Something with the server connection. } #endregion #region Gets a specific "ServerConnectionProjectItem" ServerConnectionProjectItem serverProjItem = Project.Current.GetItems <ServerConnectionProjectItem>().FirstOrDefault(item => item.Name.Equals("myServer")); #endregion #region Gets all folder connections in a project //Gets all the folder connections in the current project var projectFolders = Project.Current.GetItems <FolderConnectionProjectItem>(); foreach (var FolderItem in projectFolders) { //Do Something with the Folder connection. } #endregion #region Gets a specific folder connection //Gets a specific folder connection in the current project FolderConnectionProjectItem myProjectFolder = Project.Current.GetItems <FolderConnectionProjectItem>().FirstOrDefault(folderPI => folderPI.Name.Equals("myDataFolder")); #endregion #region Remove a specific folder connection // Remove a folder connection from a project; the folder stored on the local disk or the network is not deleted FolderConnectionProjectItem folderToRemove = Project.Current.GetItems <FolderConnectionProjectItem>().FirstOrDefault(myfolder => myfolder.Name.Equals("PlantSpecies")); if (folderToRemove != null) { Project.Current.RemoveItem(folderToRemove as IProjectItem); } #endregion #region Gets a specific "LayoutProjectItem" LayoutProjectItem layoutProjItem = Project.Current.GetItems <LayoutProjectItem>().FirstOrDefault(item => item.Name.Equals("myLayout")); #endregion #region Gets all layouts in a project: //Gets all the layouts in the current project var projectLayouts = Project.Current.GetItems <LayoutProjectItem>(); foreach (var layoutItem in projectLayouts) { //Do Something with the layout } #endregion #region Gets a specific "GeoprocessingProjectItem" GeoprocessingProjectItem GPProjItem = Project.Current.GetItems <GeoprocessingProjectItem>().FirstOrDefault(item => item.Name.Equals("myToolbox")); #endregion #region Gets all GeoprocessingProjectItems in a project: //Gets all the GeoprocessingProjectItem in the current project var GPItems = Project.Current.GetItems <GeoprocessingProjectItem>(); foreach (var tbx in GPItems) { //Do Something with the toolbox } #endregion #region Search project for a specific item List <Item> _mxd = new List <Item>(); //Gets all the folder connections in the current project var allFoldersItem = Project.Current.GetItems <FolderConnectionProjectItem>(); if (allFoldersItem != null) { //iterate through all the FolderConnectionProjectItems found foreach (var folderItem in allFoldersItem) { //Search for mxd files in that folder connection and add it to the List<T> //Note:ArcGIS Pro automatically creates and dynamically updates a searchable index as you build and work with projects. //Items are indexed when they are added to a project. //The first time a folder or database is indexed, indexing may take a while if it contains a large number of items. //While the index is being created, searches will not return any results. _mxd.AddRange(folderItem.GetItems()); } } #endregion #region Get the Default Project Folder var defaultProjectPath = System.IO.Path.Combine( System.Environment.GetFolderPath( Environment.SpecialFolder.MyDocuments), @"ArcGIS\Projects"); #endregion }
public void snippets_Export() { #region Export a map frame // Reference a layoutitem in a project by name LayoutProjectItem layoutItem = Project.Current.GetItems <LayoutProjectItem>().FirstOrDefault(item => item.Name.Equals("MyLayout")); if (layoutItem != null) { QueuedTask.Run(() => { // get the layout Layout layout = layoutItem.GetLayout(); if (layout == null) { return; } // get the map frame MapFrame mf = layout.FindElement("MyMapFrame") as MapFrame; if (mf != null) { // Create BMP format with appropriate settings BMPFormat BMP = new BMPFormat() { HasWorldFile = true, Resolution = 300, OutputFileName = @"C:\temp\MapFrame.bmp" }; if (BMP.ValidateOutputFilePath()) { mf.Export(BMP); } // emf, eps, gif, jpeg, pdf, png, svg, tga, tiff formats are also available for export } }); } #endregion #region Export the active Mapview QueuedTask.Run(() => { MapView activeMapView = MapView.Active; if (activeMapView != null) { //Create BMP format with appropriate settings BMPFormat bmp = new BMPFormat() { Resolution = 300, Height = 500, Width = 800, HasWorldFile = true, OutputFileName = @"C:\temp\MapView.bmp" }; //Export active map view if (bmp.ValidateOutputFilePath()) { activeMapView.Export(bmp); } // emf, eps, gif, jpeg, pdf, png, svg, tga, tiff formats also available for export } }); #endregion }
private async void OnSelectionChanged(MapSelectionChangedEventArgs obj) { if (MapView.Active.Map != null && obj.Selection.Count == 1) { var fl = obj.Selection.FirstOrDefault().Key as FeatureLayer; if (fl == null || fl.SelectionCount != 1 || fl.ShapeType != esriGeometryType.esriGeometryPoint) { return; } var pointd = await QueuedTask.Run(() => { try { var SelectedOID = fl.GetSelection().GetObjectIDs().FirstOrDefault(); if (SelectedOID < 0) { return(string.Empty); } var SelectedLayer = fl as BasicFeatureLayer; var oidField = SelectedLayer.GetTable().GetDefinition().GetObjectIDField(); var qf = new ArcGIS.Core.Data.QueryFilter() { WhereClause = string.Format("{0} = {1}", oidField, SelectedOID) }; var cursor = SelectedLayer.Search(qf); Row row = null; if (cursor.MoveNext()) { row = cursor.Current; } if (row == null) { return(string.Empty); } var fields = row.GetFields(); lock (_lock) { foreach (ArcGIS.Core.Data.Field field in fields) { if (field.FieldType == FieldType.Geometry) { // have mappoint here var val = row[field.Name]; if (val is MapPoint) { var temp = val as MapPoint; // project to WGS1984 proCoordGetter.Point = temp; proCoordGetter.Project(4326); return(string.Format("{0:0.0####} {1:0.0####}", proCoordGetter.Point.Y, proCoordGetter.Point.X)); } break; } } } } catch (Exception ex) { } return(string.Empty); }); if (!string.IsNullOrWhiteSpace(pointd)) { InputCoordinate = pointd; } } }