### Create a New Layout with Custom Guides Source: https://github.com/esri/arcgis-pro-sdk/wiki/Features/Layouts/ProSnippet/ProSnippets-Layouts Creates a new layout with specified dimensions and adds custom guides. This code requires QueuedTask to run and is useful for programmatically generating layouts with predefined guide positions. ```csharp //Create a new layout using a modified CIM and open it. //The CIM exposes additional members that may not be //available through the managed API. //In this example, optional guides are added. //Create a new CIMLayout on the worker thread //Note: Needs QueuedTask to run //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 guideList = new List { guide1, guide2, guide3, guide4 }; newPage.Guides = guideList.ToArray(); //Construct the new layout using the customized cim definitions var layout_local = LayoutFactory.Instance.CreateLayout(newPage); layout_local.SetName("New 8.5x11 Layout"); //Open new layout on the GUI thread await ProApp.Panes.CreateLayoutPaneAsync(layout_local); ``` -------------------------------- ### Access and Modify Layout Options in C# Source: https://github.com/esri/arcgis-pro-sdk/wiki/Features/Layouts/ProConcepts-Layouts Demonstrates how to get and set various layout options, including keeping the last tool active, warning about associated surrounds, setting the layout template path, and managing guide colors. Note that `GetGuideColor` and `SetGuideColor` require `QueuedTask.Run`. ```csharp //Get current layout options var lastToolActive = ApplicationOptions.LayoutOptions.KeepLastToolActive; var warnOnSurrounds = ApplicationOptions.LayoutOptions.WarnAboutAssociatedSurrounds; //eg \Resources\LayoutTemplates\en-US var gallery_path = ApplicationOptions.LayoutOptions.LayoutTemplatePath; var defaultGuideColor = ApplicationOptions.LayoutOptions.DefaultGuideColor; //Set layout options //keep graphic element insert tool active ApplicationOptions.LayoutOptions.KeepLastToolActive = true; //no warning when deleting a map frame results in other elements being deleted ApplicationOptions.LayoutOptions.WarnAboutAssociatedSurrounds = false; //path to .pagx files used as templates ApplicationOptions.LayoutOptions.LayoutTemplatePath = @"D:\data\layout_templates"; QueuedTask.Run(() => { var guideColor = ApplicationOptions.LayoutOptions.GetGuideColor(); // set guide color ApplicationOptions.LayoutOptions.SetGuideColor(ColorFactory.Instance.RedRGB); }); ``` -------------------------------- ### Install Azure CLI using winget Source: https://github.com/esri/arcgis-pro-sdk/wiki/Features/Framework/ProGuide-Digitally-signed-add-ins-and-configurations Install the Azure CLI on Windows using the winget package manager. Ensure to close and reopen the command window after installation for the system to recognize the changes. ```bash winget install microsoft.azd winget install --exact --id Microsoft.AzureCLI ``` -------------------------------- ### Get Polyline Start Point Source: https://github.com/esri/arcgis-pro-sdk/wiki/Features/Geometry/ProSnippet/ProSnippets-Geometry Demonstrates two methods to obtain the starting point of a polyline: by accessing its point collection or by examining the start point of its first segment. ```csharp // Method 1: Get the start point of the polyline by converting the polyline // into a collection of points and getting the first point // sketchGeometry is a Polyline // get the sketch as a point collection Geometry sketchGeometry = polyline; // for example var pointCol = ((Multipart)sketchGeometry).Points; // Get the start point of the line var firstPoint = pointCol[0]; // Method 2: Convert polyline into a collection of line segments // and get the "StartPoint" of the first line segment. var polylineGeom = sketchGeometry as ArcGIS.Core.Geometry.Polyline; var polyLineParts = polylineGeom.Parts; ReadOnlySegmentCollection polylineSegments = polyLineParts.First(); //get the first segment as a LineSegment var firsLineSegment = polylineSegments.First() as LineSegment; //Now get the start Point var startPointOfSegment = firsLineSegment.StartPoint; ``` -------------------------------- ### Instantiate and Configure Layouts Source: https://github.com/esri/arcgis-pro-sdk/wiki/Features/Layouts/ProConcepts-Layouts Demonstrates creating layouts using both direct dimension specification and a CIMPage object, including setting custom guides and margins. ```C# QueuedTask.Run(()=> { //This is overload1, specifying a 17x11" page, show rulers is true and the minimum //dimension shown on the ruler is 1 inch var layout = LayoutFactory.Instance.CreateLayout(17, 11, LinearUnit.Inches, true, 1.0); layout.SetName("New Layout Name"); //This is overload2 using a CIMPage var newPage = new CIMPage(); newPage.Width = 17; newPage.Height = 11; newPage.Units = LinearUnit.Inches; newPage.ShowRulers = true; newPage.SmallestRulerDivision = 1.0; //To this point, the CIMPage simply duplicates the same settings we used on //overload 1 above...however, with a CIMPage, we can do more - such as defining //guides and margins var guides = new List() { new CIMGuide() { Orientation = Orientation.Vertical, Position = newPage.Width / 2}, new CIMGuide() { Orientation = Orientation.Horizontal, Position = newPage.Height / 2} }; newPage.Guides = guides.ToArray(); var margin = new CIMMargin(); margin.Left = margin.Right = margin.Top = margin.Bottom = 1.0; var layout2 = LayoutFactory.Instance.CreateLayout(newPage); layout2.SetName("New Layout Name2"); ``` -------------------------------- ### Access and Set General Application Options Source: https://github.com/esri/arcgis-pro-sdk/wiki/Features/Content/ProConcepts-Content-and-Items Demonstrates how to read and modify general application settings including startup project, default geodatabase, and default toolbox. Note the order of operations when setting custom paths and options. ```cs //access the current values var startMode = ApplicationOptions.GeneralOptions.StartupOption; var aprx_path = ApplicationOptions.GeneralOptions.StartupProjectPath; var gdb_option = ApplicationOptions.GeneralOptions.DefaultGeodatabaseOption; var def_gdb = ApplicationOptions.GeneralOptions.CustomDefaultGeodatabase;//can be null var tbx_option = ApplicationOptions.GeneralOptions.DefaultToolboxOption; var def_tbx = ApplicationOptions.GeneralOptions.CustomDefaultToolbox;//can be null //Set the application to use a custom project, gdb, and toolbox //In each case, the custom _path_ must be set _first_ before setting the "option" ApplicationOptions.GeneralOptions.StartupProjectPath = @"E:\data\usa.aprx";//custom project path first ApplicationOptions.GeneralOptions.StartupOption = StartProjectMode.WithDefaultProject;//option to use it second ApplicationOptions.GeneralOptions.CustomDefaultGeodatabase = @"E:\data\usa.gdb"; //custom gdb path first ApplicationOptions.GeneralOptions.DefaultGeodatabaseOption = OptionSetting.UseCustom;//option to use it second ApplicationOptions.GeneralOptions.CustomDefaultToolbox = @"E:\data\usa.tbx"; //custom toolbox path first ApplicationOptions.GeneralOptions.DefaultToolboxOption = OptionSetting.UseCustom;//option to use it second //To set the paths back to _null_ (the default), the options must be set _back_ to //their default value _first_ (i.e. reverse of the order used to set the custom path //in the first place) ApplicationOptions.GeneralOptions.StartupOption = StartProjectMode.ShowStartPage;//set default option first ApplicationOptions.GeneralOptions.StartupProjectPath = null;//path back to null second* ApplicationOptions.GeneralOptions.DefaultGeodatabaseOption = OptionSetting.UseDefault;//set default option first ApplicationOptions.GeneralOptions.CustomDefaultGeodatabase = null;//path back to null second* ApplicationOptions.GeneralOptions.DefaultToolboxOption = OptionSetting.UseDefault;//set default option first ApplicationOptions.GeneralOptions.CustomDefaultToolbox = null;//path back to null second* //nulling out the path isn't actually necessary to switch back to the default behavior. It is done really for //completeness. If the option setting is set to use "default", then any custom path that may (still) be stored //in the companion project, gdb, toolbox path property will be ignored. However, the path(s) will be visible on //the General options UI. ``` -------------------------------- ### Start Single Workspace Edit Session (Full Example) Source: https://github.com/esri/arcgis-pro-sdk/wiki/Features/Editing/ProSnippet/ProSnippets-Editing A comprehensive example demonstrating how to start a single workspace edit session. It includes checks for existing edits, prompts to save or discard, and then initiates the edit session for a specified layer. ```csharp // ApplicationOptions.EditingOptions.EnableEditingFromEditTab is true // ApplicationOptions.EditingOptions.IsSingleWorkspaceEditSession is true var project = Project.Current; // check if already editing if (project.IsEditingEnabled) { // save or discard any edits if (project.HasEdits) { var res = MessageBox.Show("Save edits?", "Save Edits?", System.Windows.MessageBoxButton.YesNoCancel); if (res == System.Windows.MessageBoxResult.Cancel) return; else if (res == System.Windows.MessageBoxResult.No) await project.DiscardEditsAsync(); else await project.SaveEditsAsync(); } // close the edit session await project.SetIsEditingEnabledAsync(false); } // find a layer var mm = MapView.Active.Map.GetLayersAsFlattenedList().FirstOrDefault(l => l.Name == "Roads"); if (mm == null) return; // start the edit session on the workspace attached to the layer var success = await project.SetSingleEditWorkspaceAsync(mm); // if success = true then an edit session was started // and project.IsEditingEnabled will be true ``` -------------------------------- ### Create and Configure Subcircuits Source: https://github.com/esri/arcgis-pro-sdk/wiki/Features/UtilityNetwork/ProConcepts-Telecom-Domain-Network Demonstrates how to create Subcircuit objects, set their names, assign a provider ID, and add them to a circuit. ```C# Subcircuit subcircuit1 = new Subcircuit(circuitManager); subcircuit1.SetName("Subcircuit1"); Subcircuit subcircuit2 = new Subcircuit(circuitManager); subcircuit2.SetName("Subcircuit2"); // Example GUID subcircuit2.SetProviderID(new Guid("9B587BB4-FA30-4AC8-ACAC-4CB1BB087111")); // Add subcircuits to the circuit object circuit.SetSubcircuits(new List { subcircuit1, subcircuit2 }); ``` -------------------------------- ### Get List of Installed Templates (Before 2.0) Source: https://github.com/esri/arcgis-pro-sdk/wiki/AddInFundamentals/Migration-2.0/Snippets/ProSnippets-2.0-Migration-Samples Retrieves a list of installed project template file names using the pre-2.0 SDK. ```csharp public static Task> GetDefaultTemplatesAsync() { return Task.Run(() => { string templatesDir = GetDefaultTemplateFolder(); return Directory.GetFiles(templatesDir, "*", SearchOption.TopDirectoryOnly) .Where(f => f.EndsWith(".ppkx") || f.EndsWith(".aptx")).ToList(); }); } ``` -------------------------------- ### Accessing and Setting Portal Project Options Source: https://github.com/esri/arcgis-pro-sdk/wiki/Features/Content/ProConcepts-Content-and-Items Demonstrates how to access and modify the general options for a portal project, including default home folder, geodatabase, toolbox, and local copy management. ```cs // access the current options var def_home = ApplicationOptions.GeneralOptions.PortalProjectCustomHomeFolder; var def_gdb = ApplicationOptions.GeneralOptions.PortalProjectCustomDefaultGeodatabase;//can be null var def_tbx = ApplicationOptions.GeneralOptions.PortalProjectCustomDefaultToolbox;//can be null var deleteOnClose = ApplicationOptions.GeneralOptions.PortalProjectDeleteLocalCopyOnClose; var def_location = ApplicationOptions.GeneralOptions.PortalProjectDownloadLocation; // set the options ApplicationOptions.GeneralOptions.PortalProjectCustomHomeFolder = @"E:\\data"; ApplicationOptions.GeneralOptions.PortalProjectCustomDefaultGeodatabase = @"E:\\data\\usa.gdb"; ApplicationOptions.GeneralOptions.PortalProjectCustomDefaultToolbox = @"E:\\data\\usa.tbx"; ApplicationOptions.GeneralOptions.PortalProjectDeleteLocalCopyOnClose = false; ApplicationOptions.GeneralOptions.PortalProjectDownloadLocation = @"E:\\data"; ``` -------------------------------- ### Get List of Installed Templates (After 2.0) Source: https://github.com/esri/arcgis-pro-sdk/wiki/AddInFundamentals/Migration-2.0/Snippets/ProSnippets-2.0-Migration-Samples Retrieves a list of installed project template file names using the updated SDK in version 2.0. ```csharp public static Task> GetDefaultTemplatesAsync() { return Task.Run(() => { string templatesDir = GetDefaultTemplateFolder(); return Directory.GetFiles(templatesDir, "*", SearchOption.TopDirectoryOnly) .Where(f => f.EndsWith(".ppkx") || f.EndsWith(".aptx")).ToList(); }); } ``` -------------------------------- ### Subscribe to Application Ready and Startup Events Source: https://github.com/esri/arcgis-pro-sdk/wiki/Features/Framework/ProConcepts-Configurations Subscribe to `ApplicationReadyEvent` and `ApplicationStartupEvent` within the `Initialize` method of a configuration module. Ensure `autoLoad` is set to 'true' in the DAML for the module. ```csharp internal class Module1 : Module { protected override bool Initialize() { //Immediately preceeds OnApplicationReady callback ArcGIS.Desktop.Framework.Events.ApplicationReadyEvent.Subscribe((a) => { Debug.WriteLine("ApplicationReadyEvent"); }); //Immediately follows OnApplicationReady callback ArcGIS.Desktop.Framework.Events.ApplicationStartupEvent.Subscribe((a) => { Debug.WriteLine("ApplicationStartupEvent"); }); return true; } } ``` -------------------------------- ### Get Sequenced Parcel Edge Information Source: https://github.com/esri/arcgis-pro-sdk/wiki/Features/ParcelFabric/ProConcepts-Parcel-Fabric Retrieves parcel edges in a clockwise sequence. Use a hint-point to specify the starting edge, or set it to null for an arbitrary start. ```C# ParcelEdgeCollection myEdgeCollection = await myParcelFabricLayer.GetSequencedParcelEdgeInfoAsync(MyPolygonLyr, myParceloid, pointOfBeginning); ``` -------------------------------- ### Get Traverse Associations Result from Downward Traversal Source: https://github.com/esri/arcgis-pro-sdk/wiki/Features/UtilityNetwork/ProSnippet/ProSnippets-UtilityNetwork Demonstrates how to get associations involved in a downward traversal from a set of starting elements. No specific depth limit is set, allowing traversal to the maximum depth. ```csharp static void GetTraverseAssociationsResultFromDownwardTraversal(UtilityNetwork utilityNetwork, IReadOnlyList startingElements) { // Set downward traversal with maximum depth TraverseAssociationsDescription traverseAssociationsDescription = new TraverseAssociationsDescription(TraversalDirection.Descending); // Get traverse associations result from the staring element up to maximum depth TraverseAssociationsResult traverseAssociationsResult = utilityNetwork.TraverseAssociations(startingElements, traverseAssociationsDescription); // Get associations participated in traversal IReadOnlyList associations = traverseAssociationsResult.Associations; } ``` -------------------------------- ### Open Topology and Process Definition (C#) Source: https://github.com/esri/arcgis-pro-sdk/wiki/Features/Geodatabase/ProSnippet/Topology/ProSnippets-Topology Demonstrates how to open a topology from both a file geodatabase and a feature service. It also shows how to retrieve and process the topology's definition, including cluster tolerances and participating feature classes. ```C# static void OpenTopologyAndProcessDefinition() { // Open a geodatabase topology from a file geodatabase and process the topology definition. using (Geodatabase geodatabase = new Geodatabase(new FileGeodatabaseConnectionPath(new Uri(@"C:\\TestData\\GrandTeton.gdb")))) using (ArcGIS.Core.Data.Topology.Topology topology = geodatabase.OpenDataset("Backcountry_Topology")) { ProcessDefinition(geodatabase, topology); } // Open a feature service topology and process the topology definition. const string TOPOLOGY_LAYER_ID = "0"; using (Geodatabase geodatabase = new Geodatabase(new ServiceConnectionProperties(new Uri("https://sdkexamples.esri.com/server/rest/services/GrandTeton/FeatureServer")))) using (ArcGIS.Core.Data.Topology.Topology topology = geodatabase.OpenDataset(TOPOLOGY_LAYER_ID)) { ProcessDefinition(geodatabase, topology); } static void ProcessDefinition(Geodatabase geodatabase, ArcGIS.Core.Data.Topology.Topology topology) { // Similar to the rest of the Definition objects in the Core.Data API, there are two ways to open a dataset's // definition -- via the Topology dataset itself or via the Geodatabase. using (TopologyDefinition definitionViaTopology = topology.GetDefinition()) { OutputDefinition(geodatabase, definitionViaTopology); } using (TopologyDefinition definitionViaGeodatabase = geodatabase.GetDefinition("Backcountry_Topology")) { OutputDefinition(geodatabase, definitionViaGeodatabase); } } static void OutputDefinition(Geodatabase geodatabase, TopologyDefinition topologyDefinition) { Console.WriteLine($"Topology cluster tolerance => {topologyDefinition.GetClusterTolerance()}"); Console.WriteLine($"Topology Z cluster tolerance => {topologyDefinition.GetZClusterTolerance()}"); IReadOnlyList featureClassNames = topologyDefinition.GetFeatureClassNames(); Console.WriteLine($"There are {featureClassNames.Count} feature classes that are participating in the topology:"); foreach (string name in featureClassNames) { // Open each feature class that participates in the topology. using (FeatureClass featureClass = geodatabase.OpenDataset(name)) using (FeatureClassDefinition featureClassDefinition = featureClass.GetDefinition()) { Console.WriteLine($"\t{featureClass.GetName()} ({featureClassDefinition.GetShapeType()})"); } } } } ``` -------------------------------- ### Configure and Execute a Connected Trace Source: https://github.com/esri/arcgis-pro-sdk/wiki/Features/UtilityNetwork/ProSnippet/ProSnippets-UtilityNetwork Demonstrates how to set up a TraceConfiguration, define result options, and execute an asynchronous connected trace. Ensure necessary network definitions and starting points are available. ```csharp // Set trace configuration TraceConfiguration traceConfiguration = new TraceConfiguration { AllowIndeterminateFlow = true, IgnoreBarriersAtStartingPoints = false, IncludeBarriersWithResults = true, IncludeContainers = true, IncludeContent = true, IncludeIsolatedFeatures = false, IncludeUpToFirstSpatialContainer = false }; traceConfiguration.Filter.Barriers = new And(statusNetworkAttributeComparison, networkAttributeComparison); traceConfiguration.DomainNetwork = domainNetwork; traceConfiguration.SourceTier = pipeDistributionSystemTier; // Attribute fields of a network source List deviceFields = distributionDeviceDefinition.GetFields().Select(f => f.Name).ToList(); // Network attributes List networkattributeNames = new List(); IReadOnlyList networkAttributes = utilityNetworkDefinition.GetNetworkAttributes(); foreach (NetworkAttribute networkAttribute in networkAttributes) { networkattributeNames.Add(networkAttribute.Name); } // Result Types List resultTypeList = new List() { ResultType.Feature }; // Resutl Options ResultOptions resultOptions = new ResultOptions() { IncludeGeometry = true, NetworkAttributes = networkattributeNames, ResultFields = new Dictionary>() { { deviceNetworkSource, deviceFields } } }; // Trace Arguments TraceArgument traceArgument = new TraceArgument(startingPoints) { Barriers = barriers, Configuration = traceConfiguration, ResultTypes = resultTypeList, ResultOptions = resultOptions }; // Tracer ConnectedTracer connectedTracer = traceManager.GetTracer(); // Async trace result IReadOnlyList traceResults = connectedTracer.Trace(traceArgument, ServiceSynchronizationType.Asynchronous); // Iterate trace results foreach (Result traceResult in traceResults) { if (traceResult is FeatureElementResult featureElementResult) { IReadOnlyList featureElements = featureElementResult.FeatureElements; } } ``` -------------------------------- ### Get Add-in Information Source: https://github.com/esri/arcgis-pro-sdk/wiki/Features/Framework/ProSnippet/ProSnippets-Framework Retrieves and displays detailed information about all installed add-ins. This is useful for debugging or inventory purposes. ```csharp var addin_infos = FrameworkApplication.GetAddInInfos(); StringBuilder sb = new(); foreach (var info in addin_infos) { if (info == null) break;//no add-ins probed sb.AppendLine($"Addin: {info.Name}"); sb.AppendLine($"Description {info.Description}"); sb.AppendLine($"ImagePath {info.ImagePath}"); sb.AppendLine($"Author {info.Author}"); sb.AppendLine($"Company {info.Company}"); sb.AppendLine($"Date {info.Date}"); sb.AppendLine($"Version {info.Version}"); sb.AppendLine($"FullPath {info.FullPath}"); sb.AppendLine($"DigitalSignature {info.DigitalSignature}"); sb.AppendLine($"IsCompatible {info.IsCompatible}"); sb.AppendLine($"IsDeleted {info.IsDeleted}"); sb.AppendLine($"TargetVersion {info.TargetVersion}"); sb.AppendLine($"ErrorMsg {info.ErrorMsg}"); sb.AppendLine($"ID {info.ID}"); sb.AppendLine(""); } System.Diagnostics.Debug.WriteLine(sb.ToString()); MessageBox.Show(sb.ToString(), "Addin Infos"); ``` -------------------------------- ### Get Project Items by Type Source: https://github.com/esri/arcgis-pro-sdk/wiki/Features/Content/ProConcepts-Content-and-Items Use the generic GetItems method on the Project.Current instance to retrieve specific types of items from the project. Constrain the type parameter T to filter results, for example, to get only maps, database connections, or layouts. ```cs //get just the maps - use MapProjectItem var maps = Project.Current.Getitems(); //Get a specific map var map = Project.Current.GetItems().FirstOrDefault( m => m.Name == "Map 1"); //get just the database connections - use GDBProjectItem var gdbs = Project.Current.Getitems(); //get just the layouts - use LayoutProjectItem var layouts = Project.Current.Getitems(); //etc. //Just get them all - no constraints var allItems = Project.Current.GetItems(); ``` -------------------------------- ### Managing Building Scene Layer Filters Source: https://github.com/esri/arcgis-pro-sdk/wiki/Features/MapAuthoring/ProConcepts-Scene-Layers This section provides examples of how to get, set, and remove filters from a Building Scene Layer. ```APIDOC ## Managing Building Scene Layer Filters ### Description This section provides examples of how to get, set, and remove filters from a Building Scene Layer. ### Methods #### Get All Filters ```cs // Get all the filters var filters = bsl.GetFilters(); ``` #### Get Filters with Wireframe Blocks ```cs // Get all the filters that contain wireframe blocks var wire_frame_filters = bsl.GetFilters().Where( f => f.FilterBlockDefinitions.Any( fb => fb.FilterBlockMode == Object3DRenderingMode.None)); ``` #### Get Active Filter ```cs // Get the active filter var activeFilter = bsl.GetActiveFilter(); if (activeFilter != null) { // TODO: something with the active filter } ``` #### Clear Active Filter ```cs // Clear the active filter bsl.ClearActiveFilter(); ``` #### Get Specific Filter ```cs // Get a specific filter by ID var id = ...; var filter = bsl.GetFilter(id); // or via Linq var filter = bsl.GetFilters().FirstOrDefault(f => f.ID == id); ``` #### Remove Specific Filter ```cs // Remove a specific filter by ID var id = ...; if (bsl.HasFilter(id)) bsl.RemoveFilter(id); ``` #### Remove All Filters ```cs // Clear all filters bsl.RemoveAllFilters(); ``` ``` -------------------------------- ### Create a Scene Layer Source: https://github.com/esri/arcgis-pro-sdk/wiki/Features/MapAuthoring/ProSnippet/Scene/ProSnippets-SceneLayers Demonstrates how to create a new scene layer with initial visibility settings. This code should be called within a QueuedTask.Run() context. ```csharp // Note: call within QueuedTask.Run() { //Create with initial visibility set to false. Add to current scene var createparams = new LayerCreationParams(new Uri(sceneLayerUrl, UriKind.Absolute)) { IsVisible = false }; //cast to specific type of scene layer being created - in this case FeatureSceneLayer var sceneLayer = LayerFactory.Instance.CreateLayer( createparams, MapView.Active.Map) as FeatureSceneLayer; //or...specify the cast directly var sceneLayer2 = LayerFactory.Instance.CreateLayer( createparams, MapView.Active.Map); //ditto for BuildingSceneLayer, PointCloudSceneLayer, IntegratedMeshSceneLayer //... } ``` -------------------------------- ### Get Traverse Associations Result from Upward Traversal with Depth Limit Source: https://github.com/esri/arcgis-pro-sdk/wiki/Features/UtilityNetwork/ProSnippet/ProSnippets-UtilityNetwork Demonstrates how to get associations involved in an upward traversal from a set of starting elements, up to a specified depth limit of 3. It also shows how to fetch additional fields for involved elements. ```csharp static void GetTraverseAssociationsResultFromUpwardTraversalWithDepthLimit(UtilityNetwork utilityNetwork, IReadOnlyList startingElements) { // List of fields whose values will be fetched as name-values pairs during association traversal operation List additionalFieldsToFetch = new List { "ObjectId", "AssetName", "AssetGroup", "AssetType" }; // Set downward traversal with maximum depth level of 3 TraverseAssociationsDescription traverseAssociationsDescription = new TraverseAssociationsDescription(TraversalDirection.Ascending, 3) { AdditionalFields = additionalFieldsToFetch }; // Get traverse associations result from the staring element up to depth level 3 TraverseAssociationsResult traverseAssociationsResult = utilityNetwork.TraverseAssociations(startingElements, traverseAssociationsDescription); // List of associations participated in traversal IReadOnlyList associations = traverseAssociationsResult.Associations; // KeyValue mapping between involved elements and their field name-values IReadOnlyDictionary> associationElementValuePairs = traverseAssociationsResult.AdditionalFieldValues; foreach (KeyValuePair> keyValuePair in associationElementValuePairs) { // Element Element element = keyValuePair.Key; // List of field names and their values IReadOnlyList elementFieldValues = keyValuePair.Value; } } ``` -------------------------------- ### Generate README.md for Add-in Source: https://github.com/esri/arcgis-pro-sdk/wiki/Features/Copilot/ProGuide-writing-an-addin-with-copilot Prompt GitHub Copilot to create a README.md file. Provide a detailed description of the add-in's functionality to be included in the README. ```text Create a README.md file to describe the add-in as follows: This ArcGIS Pro sample add-in uses a DockPane to guide the user through a GIS workflow. The DockPane allows the user to select a parcel lot feature from the map, displaying the selected parcel's ID, and has a drop-down option to select the final multi-patch polygon resolution (0 - rough, through 100 - fine in 10 increments), finally the dock-pane contains a button to initiate the 3D lot creation using the selected parcel lot as input. ``` -------------------------------- ### Full Simplify By Tangent Segments Example Source: https://github.com/esri/arcgis-pro-sdk/wiki/Features/ParcelFabric/ProConcepts-Parcel-Fabric A complete function demonstrating the use of ParcelUtilities.SimplifyShapeByTangentSegments, including setup, unit conversion, and layer iteration. ```C# protected override async void OnClick() { //loop through all layers and get their selections CancelableProgressorSource cps = new("Simplify By Tangent Segments", "Canceled"); string sReportResult = ""; double userAllowedOffsetInMeters = 1.0; double userAllowedOffsetConverted = 1.0; string errorMessage = await QueuedTask.Run(() => { try { var backstageDistanceUnit = DisplayUnitFormats.Instance.GetDefaultProjectUnitFormat(UnitFormatType.Distance); double metersPerBackstageUnit = backstageDistanceUnit.MeasurementUnit.ConversionFactor; var lstFeatLayers = MapView.Active?.Map?.GetLayersAsFlattenedList()?.OfType()?.Where(l => l != null).Where(l => (l as Layer).ConnectionStatus != ConnectionStatus.Broken).ToList(); ``` -------------------------------- ### Create and Configure a Basic Material Source: https://github.com/esri/arcgis-pro-sdk/wiki/Features/Geometry/ProConcepts-Multipatches Instantiate a BasicMaterial and set its properties such as color, shininess, transparency, and edge width. This material can then be assigned to multipatch features. ```csharp BasicMaterial faceMaterial = new BasicMaterial(); faceMaterial.Color = System.Windows.Media.Color.FromRgb(203, 65, 84); faceMaterial.Shininess = 150; faceMaterial.TransparencyPercent = 50; faceMaterial.EdgeWidth = 20; ``` -------------------------------- ### Get Ground to Grid Correction Object Source: https://github.com/esri/arcgis-pro-sdk/wiki/Features/Editing/ProConcepts-COGO Retrieves the GroundToGridCorrection object for the active map. This is the starting point for accessing ground to grid correction settings. ```C# //Get the active map view. var mapView = MapView.Active; if (mapView?.Map == null) return; var cimDefinition = mapView.Map?.GetDefinition(); if (cimDefinition == null) return; var cimG2G = cimDefinition.GroundToGridCorrection; ``` -------------------------------- ### Get General Application Options Source: https://github.com/esri/arcgis-pro-sdk/wiki/Features/Content/ProSnippet/ProSnippets-Content Retrieves various general application settings including startup mode, project path, home folder, default geodatabase, default toolbox, and project creation folder. ```csharp var startMode = ApplicationOptions.GeneralOptions.StartupOption; var aprx_path = ApplicationOptions.GeneralOptions.StartupProjectPath; var hf_option = ApplicationOptions.GeneralOptions.HomeFolderOption; var folder = ApplicationOptions.GeneralOptions.CustomHomeFolder; var gdb_option = ApplicationOptions.GeneralOptions.DefaultGeodatabaseOption; var def_gdb = ApplicationOptions.GeneralOptions.CustomDefaultGeodatabase; var tbx_option = ApplicationOptions.GeneralOptions.DefaultToolboxOption; var def_tbx = ApplicationOptions.GeneralOptions.CustomDefaultToolbox; var create_in_folder = ApplicationOptions.GeneralOptions.ProjectCreateInFolder; ``` -------------------------------- ### Get Workflow Manager Job Statistics Source: https://github.com/esri/arcgis-pro-sdk/wiki/Features/WorkflowManager/ProSnippet/ProSnippets-WorkflowManager Calculate statistics for jobs based on a query. This example retrieves statistics for open jobs assigned to users. ```csharp var query = new JobStatisticsQuery() { // Search for open jobs assigned to users Q = "\"assignedType='User' AND closed=0 \"" }; var jobManager = WorkflowClientModule.JobsManager; var results = jobManager.CalculateJobStatistics(query); var totalJobs = results.Total; ``` -------------------------------- ### Add Style to Project (Before 2.0 vs. After 2.0) Source: https://github.com/esri/arcgis-pro-sdk/wiki/AddInFundamentals/Migration-2.0/Snippets/ProSnippets-2.0-Migration-Samples Illustrates how to add styles to the current project, comparing the 'before' and 'after' SDK 2.0 approaches. Both system and custom styles are covered, with the updated version using `StyleHelper.AddStyle`. ```csharp //For ArcGIS Pro system styles, just pass in the name of the style to add to the project await Project.Current.AddStyleAsync("3D Vehicles"); //For custom styles, pass in the full path to the style file on disk string customStyleToAdd = @"C:\Temp\CustomStyle.stylx"; await Project.Current.AddStyleAsync(customStyleToAdd); ``` ```csharp //For ArcGIS Pro system styles, just pass in the name of the style to add to the project await QueuedTask.Run(() => StyleHelper.AddStyle(Project.Current, "3D Vehicles")); //For custom styles, pass in the full path to the style file on disk string customStyleToAdd = @"C:\Temp\CustomStyle.stylx"; await QueuedTask.Run(() => StyleHelper.AddStyle(Project.Current, customStyleToAdd)); ``` -------------------------------- ### Active Surface Constraints Source: https://github.com/esri/arcgis-pro-sdk/wiki/Features/MapAuthoring/ProSnippet/3DAnalyst/ProSnippets-3D-Analyst-Layers Code examples for getting and setting active surface constraints for a LAS dataset layer. This allows control over which surface constraints are applied. ```APIDOC ## LAS Dataset Layer Surface Constraints ### Active Surface Constraints This section demonstrates how to retrieve the currently active surface constraints and how to set them. #### Get Active Surface Constraints Retrieves a list of the currently active surface constraints. ```csharp // Note: Needs QueuedTask to run var activeSurfaceConstraints = lasDatasetLayer.GetActiveSurfaceConstraints(); ``` #### Set Active Surface Constraints Sets the active surface constraints for the LAS dataset layer. Passing `null` clears all active constraints. ##### Clearing Surface Constraints: ```csharp // Clear all surface constraints (i.e. none are active) lasDatasetLayer.SetActiveSurfaceConstraints(null); ``` ##### Setting Surface Constraints: This example shows how to set all available surface constraints to be active. ```csharp // Note: Needs QueuedTask to run using (lasDataset = lasDatasetLayer.GetLasDataset()) { var surfaceConstraints = lasDataset.GetSurfaceConstraints(); var names = surfaceConstraints.Select(sc => sc.DataSourceName).ToList(); lasDatasetLayer.SetActiveSurfaceConstraints(names); } ``` ``` -------------------------------- ### Create New Project Using a Template (Now) Source: https://github.com/esri/arcgis-pro-sdk/wiki/AddInFundamentals/Migration-2.0/Snippets/ProSnippets-2.0-Migration-Samples This snippet demonstrates the updated syntax for creating a new project using a specified template path with a C# object initializer. ```csharp CreateProjectSettings projectSettings = new CreateProjectSettings() { TemplatePath = @"C:\Data\MyProject1\CustomTemplate.aptx" }; await Project.CreateAsync(projectSettings); ``` -------------------------------- ### Basic QueuedTask.Run Syntax Source: https://github.com/esri/arcgis-pro-sdk/wiki/Features/Framework/ProConcepts-Asynchronous-Programming-in-ArcGIS-Pro Illustrates the fundamental syntax for invoking synchronous methods on the MCT using QueuedTask.Run. The returned task can be awaited for completion. ```csharp Task t = QueuedTask.Run(() => { //code goes here ... }); ``` ```csharp await QueuedTask.Run(() => { //code goes here ... }); ``` -------------------------------- ### Get Task Item Information Source: https://github.com/esri/arcgis-pro-sdk/wiki/Features/Tasks/ProConcepts-Tasks Retrieves and displays the Name, Description, and Guid of a task item, along with the count of tasks within it. Handles potential exceptions like OpenTaskException and TaskFileVersionException. ```csharp var taskItem = Project.Current.GetItems().FirstOrDefault(); if (taskItem == null) return; string message = await QueuedTask.Run(async () => { bool isOpen = taskItem.IsOpen; Guid taskGuid = taskItem.TaskItemGuid; string msg = ""; try { TaskItemInfo taskItemInfo = await taskItem.GetTaskItemInfoAsync(); msg = "Name : " + taskItemInfo.Name; msg += "\r\n" + "Description : " + taskItemInfo.Description; msg += "\r\n" + "Guid : " + taskItemInfo.Guid.ToString("B"); msg += "\r\n" + "Task Count : " + taskItemInfo.GetTasks().Count(); IEnumerable taskInfos = taskItemInfo.GetTasks(); foreach (TaskInfo taskInfo in taskInfos) { string name = taskInfo.Name; Guid guid = taskInfo.Guid; // do something } } catch (OpenTaskException e) { msg = e.Message; } catch (TaskFileVersionException e) { msg = e.Message; } return msg; }); ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show(message, "Task Information"); ``` -------------------------------- ### Open a Portal Project using Project.OpenAsync Source: https://github.com/esri/arcgis-pro-sdk/wiki/Features/Content/ProConcepts-Content-and-Items Use Project.OpenAsync to open a portal project. The projectUri must be a fully qualified URL to the portal project item. The portal must be the current active portal and the user must be signed in. ```cs var portalProjectUri = @"https://myportal.acme.com/portal/sharing/rest/content/items/10ba62fe50864339a8a3e0f18ca85506"; var proDocVer = string.Empty; //portalProjectUri must refer to the current active portal and the logged-on user must be signed in bool canOpen = Project.CanOpen(portalProjectUri, out proDocVer); if (canOpen) { var openedProject = await Project.OpenAsync(portalProjectUri); ... } ``` -------------------------------- ### CIMRowTemplate JSON Structure Example Source: https://github.com/esri/arcgis-pro-sdk/wiki/Features/Editing/ProGuide-Templates Illustrates the typical JSON structure of a CIMRowTemplate object, including properties like name, description, tags, default tool GUID, and default values. ```json { "type": "CIMRowTemplate", "description": "Template for Point_1", "name": "Point_1", "tags": "Point", "defaultToolGUID": "2a8b3331-5238-4025-972e-452a69535b06", "defaultValues": { "type": "PropertySet", "propertySetItems": [ "notes", "Some note" ] } } ``` -------------------------------- ### LAS Dataset Layer Display Filter Source: https://github.com/esri/arcgis-pro-sdk/wiki/Features/MapAuthoring/ProSnippet/3DAnalyst/ProSnippets-3D-Analyst-Layers Code examples for getting and setting the display filter for a LAS dataset layer. This includes filtering by classification codes, return types, and other point properties. ```APIDOC ## LAS Dataset Layer Display Filter ### Get and Set Display Filter This section demonstrates how to retrieve the current display filter and apply new filters to a LAS dataset layer. #### Get Display Filter ```csharp // Note: Needs QueuedTask to run LasPointDisplayFilter ptFilter = lasDatasetLayer.GetDisplayFilter(); ``` #### Set Display Filter Applies a display filter to the LAS dataset layer. This can be done using predefined types, lists of classification codes, or custom filter objects. ##### Using Predefined Types: ```csharp // Display only ground points lasDatasetLayer.SetDisplayFilter(LasPointDisplayFilterType.Ground); // Display first return points lasDatasetLayer.SetDisplayFilter(LasPointDisplayFilterType.FirstReturnPoints); ``` ##### Using Classification Codes: ```csharp // Set display filter to a set of classification codes List classifications = new List() { 4, 5, 7, 10 }; lasDatasetLayer.SetDisplayFilter(classifications); ``` ##### Using Return Types: ```csharp // Set display filter to a set of returns List returns = new List() { ArcGIS.Core.Data.Analyst3D.LasReturnType.ReturnFirstOfMany}; lasDatasetLayer.SetDisplayFilter(returns); ``` ##### Using a Custom Display Filter Object: ```csharp // Set up a display filter var newDisplayFilter = new LasPointDisplayFilter(); newDisplayFilter.Returns = new List() { ArcGIS.Core.Data.Analyst3D.LasReturnType.ReturnFirstOfMany, ArcGIS.Core.Data.Analyst3D.LasReturnType.ReturnLastOfMany}; newDisplayFilter.ClassCodes = new List() { 2, 4 }; newDisplayFilter.KeyPoints = true; newDisplayFilter.WithheldPoints = false; newDisplayFilter.SyntheticPoints = false; newDisplayFilter.NotFlagged = false; lasDatasetLayer.SetDisplayFilter(newDisplayFilter); ``` ``` -------------------------------- ### Get Specific Default Unit Format Source: https://github.com/esri/arcgis-pro-sdk/wiki/Features/Content/ProSnippet/ProSnippets-Content Fetches a specific default unit format for the current project, for example, the default distance unit. This code must be executed within a QueuedTask.Run() context. ```csharp // Note: Must be on the QueuedTask.Run() //UnitFormatType.Angular, UnitFormatType.Area, UnitFormatType.Distance, //UnitFormatType.Direction, UnitFormatType.Location, UnitFormatType.Page //UnitFormatType.Symbol2D, UnitFormatType.Symbol3D var default_unit = DisplayUnitFormats.Instance.GetDefaultProjectUnitFormat( UnitFormatType.Distance); // Use default_unit; ``` -------------------------------- ### Standard Numeric and Date/Time Formatting Examples Source: https://github.com/esri/arcgis-pro-sdk/wiki/AddInFundamentals/ProConcept-Localization Demonstrates standard formatting for currency and dates using CultureInfo. Use standard formats to ensure consistency across different cultures. Avoid custom formatting. ```csharp //Currency ā€˜C’ double amount = 123.456; amount.ToString("C", CultureInfo.CreateSpecificCulture("en-US")) ---> $123.46 amount.ToString("C", CultureInfo.CreateSpecificCulture("fr-FR")) ---> 123,46 € //Date "d" DateTime dt = new DateTime(2017, 3, 9, 16, 5, 7, 123); dt.ToString("{0:d}") //---> 3/9/2017 (en-US) dt.ToString("{0:d}") //---> 9/3/2017 (fr-FR) // date separator in german culture is "." (so "/" changes to ".") dt.ToString("{0:d}") //---> 9.3.2017 (de-DE) ... ``` -------------------------------- ### Get Layout Options Source: https://github.com/esri/arcgis-pro-sdk/wiki/Features/Layouts/ProSnippet/ProSnippets-Layouts Retrieve current layout settings such as keeping the last tool active, warning about associated surrounds, the layout template path, and default guide color. Note: Must be executed on a QueuedTask. ```csharp var lastToolActive = ApplicationOptions.LayoutOptions.KeepLastToolActive; var warnOnSurrounds = ApplicationOptions.LayoutOptions.WarnAboutAssociatedSurrounds; //eg \Resources\LayoutTemplates\en-US var gallery_path = ApplicationOptions.LayoutOptions.LayoutTemplatePath; var defaultGuideColor = ApplicationOptions.LayoutOptions.DefaultGuideColor; //Note: Must be on QueuedTask.Run. var guideColor = ApplicationOptions.LayoutOptions.GetGuideColor(); ``` -------------------------------- ### Create and Use a Join Source: https://github.com/esri/arcgis-pro-sdk/wiki/Features/Geodatabase/ProConcepts-Geodatabase Shows how to create a Join object using a JoinDescription, specifying join type and direction. It then demonstrates how to obtain the joined table. ```C# JoinDescription joinDescription = new JoinDescription(relationshipClass) { JoinType = JoinType.LeftOuterJoin, JoinDirection = JoinDirection.Backward }; using (Join join = new Join(joinDescription)) using (Table joinedTable = join.GetJoinedTable()) { // The joinedTable is an ArcGIS.Core.Data.Table reference that can be either an ArcGIS.Core.Data.Table or an // ArcGIS.Core.Data.FeatureClass (depending upon whether the join has a Shape column). } ``` -------------------------------- ### Create Terrain Layer with Creation Parameters Source: https://github.com/esri/arcgis-pro-sdk/wiki/Features/MapAuthoring/ProConcepts-3D-Analyst-Layers This approach allows for upfront configuration of the Terrain layer, such as setting its name and visibility. It requires a QueuedTask.Run() context. ```csharp //Must be on the QueuedTask.Run() string path = @"d:\Data\Terrain\filegdb_Containing_A_Terrain.gdb\nameOfTerrain"; var uri = new Uri(path); var createParams = new TerrainLayerCreationParams(uri); createParams.Name = "My Terrain Layer"; createParams.IsVisible = false; //Create the layer to the terrain var terrainLayer = LayerFactory.Instance.CreateLayer(createParams, map); ``` -------------------------------- ### Alter LineSegment Coordinates in C# Source: https://github.com/esri/arcgis-pro-sdk/wiki/Features/Geometry/ProSnippet/ProSnippets-Geometry Shows how to modify the start and end points of an existing LineSegment using LineBuilderEx. The operations involve querying current coordinates and setting new ones, with examples of using GeometryEngine.Instance.Move. ```csharp MapPoint startPt = MapPointBuilderEx.CreateMapPoint(1.0, 1.0); MapPoint endPt = MapPointBuilderEx.CreateMapPoint(2.0, 1.0); // builderEx constructors don't need to run on the MCT LineBuilderEx lbuilderEx = new LineBuilderEx(lineSegment); // find the existing coordinates lbuilderEx.QueryCoords(out startPt, out endPt); // or use //startPt = lbuilderEx.StartPoint; //endPt = lbuilderEx.EndPoint; // update the coordinates lbuilderEx.SetCoords(GeometryEngine.Instance.Move(startPt, 10, 10) as MapPoint, GeometryEngine.Instance.Move(endPt, -10, -10) as MapPoint); // or use //lbuilderEx.StartPoint = GeometryEngine.Instance.Move(startPt, 10, 10) as MapPoint; //lbuilderEx.EndPoint = GeometryEngine.Instance.Move(endPt, -10, -10) as MapPoint; LineSegment segment2 = lbuilderEx.ToSegment() as LineSegment; ``` -------------------------------- ### Get Sub-Curve Between M Values - GeometryEngine C# Source: https://github.com/esri/arcgis-pro-sdk/wiki/Features/Geometry/ProSnippet/GeometryEngine/ProSnippets-GeometryEngine Extracts a polyline representing the sub-curve between two specified M values. If the start M value is NaN, it extracts from the beginning of the geometry. Returns an empty polyline if no segment falls within the specified M range. ```csharp string json = "{\"hasM\":true,\"paths\":[[[-2000,0,1],[-1000,1000,2],[-1000,0,3],[1000,1000,4],[2000,1000,5],[2000,2000,6],[3000,2000,7],[4000,0,8]]],\"spatialReference\":{\"wkid\":3857}}"; polyline = PolylineBuilderEx.FromJson(json); Polyline subCurve = GeometryEngine.Instance.GetSubCurveBetweenMs(polyline, 2, 6); // subCurve.PointCount = 5 // subCurve.Points[0] X= --1000, Y= 1000 M= 2 // subCurve.Points[1] X= --1000, Y= 0 M= 3 // subCurve.Points[2] X= 1000, Y= 1000 M= 4 // subCurve.Points[3] X= 2000, Y= -1000 M= 5 // subCurve.Points[4] X= 2000, Y= -2000 M= 6 subCurve = GeometryEngine.Instance.GetSubCurveBetweenMs(polyline, double.NaN, 5); // subCurve.PointCount = 0 // subCurve.IsEmpty = true ``` -------------------------------- ### Start ArcGIS Pro from Command Line Source: https://github.com/esri/arcgis-pro-sdk/wiki/Features/Framework/ProSnippet/ProSnippets-Framework Demonstrates how to launch ArcGIS Pro using its executable path from the command line. ```batch C:\"C:\Program Files\ArcGIS Pro\bin\ArcGISPro.exe" ```