ProSnippets 2.0 Migration Samples - Esri/arcgis-pro-sdk GitHub Wiki

Language:      c#
Subject:       Framework
Contributor:   ArcGIS Pro SDK Team <[email protected]>
Organization:  esri, http://www.esri.com
Date:          9/28/2021  
ArcGIS Pro:    2.9 
Visual Studio: 2017, 2019

The upgrade from ArcGIS Pro SDK 1.4 to ArcGIS Pro SDK 2.0 is a 'code breaking' change. This means that you have to change, recompile, rebuild, and redistribute any 1.x (SDK 1.4 and earlier) add-ins and configurations so that they work with ArcGIS Pro 2.0.
This document lists all 1.4 ProSnippets that required modification in order to work with ArcGIS Pro 2.0. The 1.4 code snippet is shown as the before code snippet and the equivalent 2.0 code snippet is shown as the now: code snippet.
With 2.0 the ItemFactory pattern changed notably as documented in ProConcepts Content and Items.


The following ProSnippet Migrations samples are available:

ProSnippet Migration by topic

Content

New project with specified name

    before:

//Settings used to create a new project
CreateProjectSettings projectSettings = new CreateProjectSettings();
//Sets the name of the project that will be created
projectSettings.Name = @"C:\Data\MyProject1\MyProject1.aprx";
//Create the new project
await Project.CreateAsync(projectSettings);

    now:

//Settings used to create a new project
CreateProjectSettings projectSettings = new CreateProjectSettings()
{
  //Sets the name of the project that will be created
  Name = @"C:\Data\MyProject1\MyProject1.aprx"
};
//Create the new project
await Project.CreateAsync(projectSettings);

New project using a particular template

    before:

//Settings used to create a new project
CreateProjectSettings projectSettings = new CreateProjectSettings();
//Sets the project template that will be used to create the new project
projectSettings.TemplatePath = @"C:\Data\MyProject1\CustomTemplate.aptx";
//Create the new project
await Project.CreateAsync(projectSettings);

    now:

//Settings used to create a new project
CreateProjectSettings projectSettings = new CreateProjectSettings()
{
  //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);

Adds item to the current project

    before:

//Adding a folder connection
string folderPath = "@C:\\myDataFolder";
var folder = await Project.Current.AddAsync(ItemFactory.Create(folderPath));

//Adding a Geodatabase:
string gdbPath = "@C:\\myDataFolder\\myData.gdb";
var newlyAddedGDB = await Project.Current.AddAsync(ItemFactory.Create(gdbPath));            

    now:

//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;
});

How to add a new map to a project

    before:

await QueuedTask.Run(() =>
  {
    var map = MapFactory.CreateMap("New Map", ArcGIS.Core.CIM.MapType.Map, ArcGIS.Core.CIM.MapViewingMode.Map, Basemap.Oceans);
    ProApp.Panes.CreateMapPaneAsync(map);
  });

    now:

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);
});

Get all the project items

    before:

IEnumerable<ProjectItem> allProjectItems = Project.Current.GetItems<ProjectItem>();
foreach (var pi in allProjectItems)
{
    //Do Something 
}

    now:

IEnumerable<Item> allProjectItems = Project.Current.GetItems<Item>();
foreach (var pi in allProjectItems)
{
  //Do Something 
}

Gets a specific folder connection

    before:

//Gets a specific folder connection in the current project
ProjectItem myProjectFolder = Project.Current.GetItems<FolderConnectionProjectItem>().FirstOrDefault(folderPI => folderPI.Name.Equals("myDataFolder"));

    now:

//Gets a specific folder connection in the current project
FolderConnectionProjectItem myProjectFolder = Project.Current.GetItems<FolderConnectionProjectItem>().FirstOrDefault(folderPI => folderPI.Name.Equals("myDataFolder"));

Remove a specific folder connection

    before:

// 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)
    await Project.Current.RemoveAsync(folderToRemove);

    now:

// 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);

Search project for a specific item

    before:

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(await folderItem.SearchAsync(".mxd"));
    }
}

    now:

{
  List<Item> _mxd = new List<Item>();
  //Gets all the folder connections in the current project
  var allFolderItems = Project.Current.GetItems<FolderConnectionProjectItem>();
  if (allFolderItems != null)
  {
    await QueuedTask.Run(() =>
     {
       _mxd = GetItemsFromFolderItem(allFolderItems, ".mxd");
     });
  }
  MessageBox.Show($@"Count: {_mxd.Count}");
}

private List<Item> GetItemsFromFolderItem (IEnumerable<FolderConnectionProjectItem> allFolderItems, string fileExtension)
{
  List<Item> foundItems = new List<Item>();
  List<FolderConnectionProjectItem> childFolders = new List<FolderConnectionProjectItem>();
  //iterate recursively through all the FolderConnectionProjectItems found
  foreach (var folderItem in allFolderItems)
  {
    //Search for mxd files in that folder connection and add it to the List<T>
    //Note:ArcGIS Pro automatically creates and dynamically updates a search-able 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.
    childFolders.AddRange(folderItem.GetItems()
                          .Where(f => (f is FolderConnectionProjectItem))
                          .Select(f => f as FolderConnectionProjectItem));
    foundItems.AddRange(folderItem.GetItems()
                          .Where(f => f.Name.EndsWith(fileExtension, StringComparison.CurrentCultureIgnoreCase)));
  }
  if (childFolders.Count > 0)
  {
    foundItems.AddRange(GetItemsFromFolderItem(childFolders, fileExtension));
  }
  return foundItems;
}

Get Item Categories

    before:

// Get the ItemCategories with which an item is associated
Item gdb = ItemFactory.Create(@"E:\CurrentProject\RegionalPolling\polldata.gdb");
List<ItemCategory> gdbItemCategories = gdb.ItemCategories;

    now:

// Get the ItemCategories with which an item is associated
Item gdb = ItemFactory.Instance.Create(@"E:\CurrentProject\RegionalPolling\polldata.gdb");
List<ItemCategory> gdbItemCategories = gdb.ItemCategories;

Using Item Categories

    before:

// Browse items using an ItemCategory as a filter
IEnumerable<Item> gdbContents = await gdb.GetItemsAsync();
IEnumerable<Item> filteredGDBContents1 = gdbContents.Where(item => item.ItemCategories.OfType<ItemCategoryDataSet>().Any());
IEnumerable<Item> filteredGDBContents2 = new ItemCategoryDataSet().Items(gdbContents);

    now:

// Browse items using an ItemCategory as a filter
IEnumerable<Item> gdbContents = gdb.GetItems();
IEnumerable<Item> filteredGDBContents1 = gdbContents.Where(item => item.ItemCategories.OfType<ItemCategoryDataSet>().Any());
IEnumerable<Item> filteredGDBContents2 = new ItemCategoryDataSet().Items(gdbContents);

Method to Return The Default Template Folder

    before:

public static string GetDefaultTemplateFolder() {
    string dir = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location);
    string root = dir.Split(new string[] { @"\bin" }, StringSplitOptions.RemoveEmptyEntries)[0];
    return System.IO.Path.Combine(root, @"Resources\ProjectTemplates");
}

    now:

public static string GetDefaultTemplateFolder()
{
  string dir = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location);
  string root = dir.Split(new string[] { @"\bin" }, StringSplitOptions.RemoveEmptyEntries)[0];
  return System.IO.Path.Combine(root, @"Resources\ProjectTemplates");
}

Get The List of Installed Templates

    before:

public static Task<List<string>> GetDefaultTemplatesAsync() {
    return Task.Run(() => {
        string templatesDir = GetDefaultTemplateFolder();
        return
            Directory.GetFiles(templatesDir, "*", SearchOption.TopDirectoryOnly)
                .Where(f => f.EndsWith(".ppkx") || f.EndsWith(".aptx")).ToList();
    });
}

    now:

public static Task<List<string>> GetDefaultTemplatesAsync()
{
  return Task.Run(() =>
  {
    string templatesDir = GetDefaultTemplateFolder();
    return
        Directory.GetFiles(templatesDir, "*", SearchOption.TopDirectoryOnly)
            .Where(f => f.EndsWith(".ppkx") || f.EndsWith(".aptx")).ToList();
  });
}

Create Project With Template

    before:

var templates = await GetDefaultTemplatesAsync();
var projectFolder = System.IO.Path.Combine(
    System.Environment.GetFolderPath(
        Environment.SpecialFolder.MyDocuments),
    @"ArcGIS\Projects");

CreateProjectSettings ps = new CreateProjectSettings() {
    Name = "MyProject",
    LocationPath = projectFolder,
    TemplatePath = templates[2]//2D "Map" template
};

var project = await Project.CreateAsync(ps);

    now:

var templates = await GetDefaultTemplatesAsync();
var projectFolder = System.IO.Path.Combine(
    System.Environment.GetFolderPath(
        Environment.SpecialFolder.MyDocuments),
    @"ArcGIS\Projects");

CreateProjectSettings ps = new CreateProjectSettings()
{
  Name = "MyProject",
  LocationPath = projectFolder,
  TemplatePath = templates[2]//2D "Map" template
};

var project = await Project.CreateAsync(ps);

Geodatabase

Obtaining related Feature Classes from a Relationship Class

    before:

public async Task GetFeatureClassesInRelationshipClassAsync()
{
    await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
    {
        using (Geodatabase geodatabase = new Geodatabase(@"C:\Data\LocalGovernment.gdb"))
        {
            IReadOnlyList<RelationshipClassDefinition> relationshipClassDefinitions = geodatabase.GetDefinitions<RelationshipClassDefinition>();
            foreach (var relationshipClassDefintion in relationshipClassDefinitions)
            {
                IReadOnlyList<Definition> definitions = geodatabase.GetRelatedDefinitions(relationshipClassDefintion,
                    DefinitionRelationshipType.DatasetsRelatedThrough);
                foreach (var definition in definitions)
                {
                    MessageBox.Show($"Feature class in the RelationshipClass is:{definition.GetName()}");
                }
            }
        }
    });
}

    now:

public async Task GetFeatureClassesInRelationshipClassAsync()
{
    await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
    {
        using (Geodatabase geodatabase = new Geodatabase(new FileGeodatabaseConnectionPath(new Uri(@"C:\Data\LocalGovernment.gdb"))))
        {
            IReadOnlyList<RelationshipClassDefinition> relationshipClassDefinitions = geodatabase.GetDefinitions<RelationshipClassDefinition>();
            foreach (var relationshipClassDefintion in relationshipClassDefinitions)
            {
                IReadOnlyList<Definition> definitions = geodatabase.GetRelatedDefinitions(relationshipClassDefintion,
                    DefinitionRelationshipType.DatasetsRelatedThrough);
                foreach (var definition in definitions)
                {
                    MessageBox.Show($"Feature class in the RelationshipClass is:{definition.GetName()}");
                }
            }
        }
    });
}

Opening a File Geodatabase given the path

    before:

public async Task OpenFileGDB()
{
  await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
  {
    try
    {
      // Opens a file geodatabase. This will open the geodatabase if the folder exists and contains a valid geodatabase.
      using (Geodatabase geodatabase = new Geodatabase(new FileGeodatabaseConnectionPath(new Uri(@"C:\Data\LocalGovernment.gdb"))))
      {
        // Use the geodatabase.
      }
    }
    catch (GeodatabaseNotFoundOrOpenedException exception)
    {
      // Handle Exception.
    }
  });
}

    now:

public async Task OpenFileGDB()
{
  try {
    await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() => {
      // Opens a file geodatabase. This will open the geodatabase if the folder exists and contains a valid geodatabase.
      using (
        Geodatabase geodatabase =
          new Geodatabase(new FileGeodatabaseConnectionPath(new Uri(@"C:\Data\LocalGovernment.gdb")))) {
        // Use the geodatabase.
      }
    });
  }
  catch (GeodatabaseNotFoundOrOpenedException exception) {
    // Handle Exception.
  }

}

Opening an Enterprise Geodatabase using connection properties

    before:

public async Task OpenEnterpriseGeodatabase()
{
  await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
  {
    // Opening a Non-Versioned SQL Server instance.
    DatabaseConnectionProperties connectionProperties = new DatabaseConnectionProperties(EnterpriseDatabaseType.SQLServer)
    {
      AuthenticationMode = AuthenticationMode.DBMS,

      // Where testMachine is the machine where the instance is running and testInstance is the name of the SqlServer instance.
      Instance = @"testMachine\testInstance",

      // Provided that a database called LocalGovernment has been created on the testInstance and geodatabase has been enabled on the database.
      Database = "LocalGovernment",

      // Provided that a login called gdb has been created and corresponding schema has been created with the required permissions.
      User     = "gdb",
      Password = "password",
      Version  = "dbo.DEFAULT"
    };

    using (Geodatabase geodatabase = new Geodatabase(connectionProperties))
    {
      // Use the geodatabase
    }
  });
}

    now:

public async Task OpenEnterpriseGeodatabase()
{
  await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() => {
    // Opening a Non-Versioned SQL Server instance.
    DatabaseConnectionProperties connectionProperties = new DatabaseConnectionProperties(EnterpriseDatabaseType.SQLServer) {
      AuthenticationMode = AuthenticationMode.DBMS,

      // Where testMachine is the machine where the instance is running and testInstance is the name of the SqlServer instance.
      Instance = @"testMachine\testInstance",

      // Provided that a database called LocalGovernment has been created on the testInstance and geodatabase has been enabled on the database.
      Database = "LocalGovernment",

      // Provided that a login called gdb has been created and corresponding schema has been created with the required permissions.
      User = "gdb",
      Password = "password",
      Version = "dbo.DEFAULT"
    };

    using (Geodatabase geodatabase = new Geodatabase(connectionProperties)) {
      // Use the geodatabase
    }
  });
}

Opening an Enterprise Geodatabase using sde file path

    before:

public async Task OpenEnterpriseGeodatabaseUsingSDEFilePath()
{
  await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
  {
    using (Geodatabase geodatabase = new Geodatabase(new DatabaseConnectionFile(new Uri("path\\to\\sde\\file\\sdefile.sde"))))
    {
      // Use the geodatabase.
    }
  });
}

    now:

public async Task OpenEnterpriseGeodatabaseUsingSDEFilePath()
{
  await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() => {
    using (Geodatabase geodatabase = new Geodatabase(new DatabaseConnectionFile(new Uri("path\\to\\sde\\file\\sdefile.sde")))) {
      // Use the geodatabase.
    }
  });
}

Obtaining Geodatabase from Project Item

    before:

public async Task ObtainingGeodatabaseFromProjectItem()
{
  IEnumerable<GDBProjectItem> gdbProjectItems = Project.Current.GetItems<GDBProjectItem>();

  await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
  {
    foreach (GDBProjectItem gdbProjectItem in gdbProjectItems)
    {
      using (Datastore datastore = gdbProjectItem.GetDatastore())
      {
        //Unsupported datastores (non File GDB and non Enterprise GDB) will be of type UnknownDatastore
        if (datastore is UnknownDatastore)
          continue;

        Geodatabase geodatabase = datastore as Geodatabase;
        // Use the geodatabase.
      }
    }
  });
}

    now:

public async Task ObtainingGeodatabaseFromProjectItem()
{
  IEnumerable<GDBProjectItem> gdbProjectItems = Project.Current.GetItems<GDBProjectItem>();

  await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() => {
    foreach (GDBProjectItem gdbProjectItem in gdbProjectItems) {
      using (Datastore datastore = gdbProjectItem.GetDatastore()) {
        //Unsupported datastores (non File GDB and non Enterprise GDB) will be of type UnknownDatastore
        if (datastore is UnknownDatastore)
          continue;

        Geodatabase geodatabase = datastore as Geodatabase;
        // Use the geodatabase.
      }
    }
  });
}

Obtaining Geodatabase from FeatureLayer

    before:

public async Task ObtainingGeodatabaseFromFeatureLayer()
{
  IEnumerable<Layer> layers = MapView.Active.Map.Layers.Where(layer => layer is FeatureLayer);

  await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
  {
    foreach (FeatureLayer featureLayer in layers)
    {
      using (Table table = featureLayer.GetTable())
      using (Datastore datastore = table.GetDatastore())
      {
        if (datastore is UnknownDatastore)
          continue;

        Geodatabase geodatabase = datastore as Geodatabase;
      }
    }
  });
}

    now:

public async Task ObtainingGeodatabaseFromFeatureLayer()
{
  IEnumerable<Layer> layers = MapView.Active.Map.Layers.Where(layer => layer is FeatureLayer);

  await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() => {
    foreach (FeatureLayer featureLayer in layers) {
      using (Table table = featureLayer.GetTable())
      using (Datastore datastore = table.GetDatastore()) {
        if (datastore is UnknownDatastore)
          continue;

        Geodatabase geodatabase = datastore as Geodatabase;
      }
    }
  });
}

Opening datasets from Geodatabase

    before:

public async Task OpeningDatasetsFromGeodatabase()
{
  await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
  {
    using (Geodatabase geodatabase = new Geodatabase(new DatabaseConnectionFile(new Uri("path\\to\\sde\\file\\sdefile.sde"))))
    {
      using (Table table = geodatabase.OpenDataset<Table>("LocalGovernment.GDB.EmployeeInfo"))
      {
      }

      // Open a featureClass (within a feature dataset or outside a feature dataset).
      using (FeatureClass featureClass = geodatabase.OpenDataset<FeatureClass>("LocalGovernment.GDB.AddressPoint"))
      {
      }

      // You can open a FeatureClass as a Table which will give you a Table Reference.
      using (Table featureClassAsTable = geodatabase.OpenDataset<Table>("LocalGovernment.GDB.AddressPoint"))
      {
        // But it is really a FeatureClass object.
        FeatureClass featureClassOpenedAsTable = featureClassAsTable as FeatureClass;
      }

      // Open a FeatureDataset.
      using (FeatureDataset featureDataset = geodatabase.OpenDataset<FeatureDataset>("LocalGovernment.GDB.Address"))
      {
      }
      
      // Open a RelationsipClass.  Just as you can open a FeatureClass as a Table, you can also open an AttributedRelationshipClass as a RelationshipClass.
      using (RelationshipClass relationshipClass = geodatabase.OpenDataset<RelationshipClass>("LocalGovernment.GDB.AddressPointHasSiteAddresses"))
      {
      }
    }
  });
}

    now:

public async Task OpeningDatasetsFromGeodatabase()
{
  await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() => {
    using (Geodatabase geodatabase = new Geodatabase(new DatabaseConnectionFile(new Uri("path\\to\\sde\\file\\sdefile.sde")))) {
      using (Table table = geodatabase.OpenDataset<Table>("LocalGovernment.GDB.EmployeeInfo")) {
      }

      // Open a featureClass (within a feature dataset or outside a feature dataset).
      using (FeatureClass featureClass = geodatabase.OpenDataset<FeatureClass>("LocalGovernment.GDB.AddressPoint")) {
      }

      // You can open a FeatureClass as a Table which will give you a Table Reference.
      using (Table featureClassAsTable = geodatabase.OpenDataset<Table>("LocalGovernment.GDB.AddressPoint")) {
        // But it is really a FeatureClass object.
        FeatureClass featureClassOpenedAsTable = featureClassAsTable as FeatureClass;
      }

      // Open a FeatureDataset.
      using (FeatureDataset featureDataset = geodatabase.OpenDataset<FeatureDataset>("LocalGovernment.GDB.Address")) {
      }

      // Open a RelationsipClass.  Just as you can open a FeatureClass as a Table, you can also open an AttributedRelationshipClass as a RelationshipClass.
      using (RelationshipClass relationshipClass = geodatabase.OpenDataset<RelationshipClass>("LocalGovernment.GDB.AddressPointHasSiteAddresses")) {
      }
    }
  });
}

Obtaining Definition from Geodatabase

    before:

public async Task ObtainingDefinitionFromGeodatabase()
{
  await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
  {
    using (Geodatabase geodatabase = new Geodatabase(new DatabaseConnectionFile(new Uri("path\\to\\sde\\file\\sdefile.sde"))))
    {
      // Remember that for Enterprise databases you have to qualify your dataset names with the DatabaseName and UserName.
      TableDefinition enterpriseTableDefinition = geodatabase.GetDefinition<TableDefinition>("LocalGovernment.GDB.CitizenContactInfo");

      // It does not matter if the dataset is within a FeatureDataset or not.
      FeatureClassDefinition featureClassDefinition = geodatabase.GetDefinition<FeatureClassDefinition>("LocalGovernment.GDB.FireStation");

      // GetDefinition For a RelationshipClass.
      RelationshipClassDefinition relationshipClassDefinition = geodatabase.GetDefinition<RelationshipClassDefinition>("LocalGovernment.GDB.AddressPointHasSiteAddresses");

      // GetDefinition For a FeatureDataset.
      FeatureDatasetDefinition featureDatasetDefinition = geodatabase.GetDefinition<FeatureDatasetDefinition>("LocalGovernment.GDB.Address");
    }
  });
}

    now:

public async Task ObtainingDefinitionFromGeodatabase()
{
  await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() => {
    using (Geodatabase geodatabase = new Geodatabase(new DatabaseConnectionFile(new Uri("path\\to\\sde\\file\\sdefile.sde")))) {
      // Remember that for Enterprise databases you have to qualify your dataset names with the DatabaseName and UserName.
      TableDefinition enterpriseTableDefinition = geodatabase.GetDefinition<TableDefinition>("LocalGovernment.GDB.CitizenContactInfo");

      // It does not matter if the dataset is within a FeatureDataset or not.
      FeatureClassDefinition featureClassDefinition = geodatabase.GetDefinition<FeatureClassDefinition>("LocalGovernment.GDB.FireStation");

      // GetDefinition For a RelationshipClass.
      RelationshipClassDefinition relationshipClassDefinition = geodatabase.GetDefinition<RelationshipClassDefinition>("LocalGovernment.GDB.AddressPointHasSiteAddresses");

      // GetDefinition For a FeatureDataset.
      FeatureDatasetDefinition featureDatasetDefinition = geodatabase.GetDefinition<FeatureDatasetDefinition>("LocalGovernment.GDB.Address");
    }
  });
}

Obtaining List of Defintions from Geodatabase

    before:

public async Task ObtainingDefinitionsFromGeodatabase()
{
  await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
  {
    using (Geodatabase geodatabase = new Geodatabase(new DatabaseConnectionFile(new Uri("path\\to\\sde\\file\\sdefile.sde"))))
    {
      IReadOnlyList<FeatureClassDefinition> enterpriseDefinitions = geodatabase.GetDefinitions<FeatureClassDefinition>();
      IEnumerable<Definition> featureClassesHavingGlobalID = enterpriseDefinitions.Where(definition => definition.HasGlobalID());

      IReadOnlyList<FeatureDatasetDefinition> featureDatasetDefinitions = geodatabase.GetDefinitions<FeatureDatasetDefinition>();
      bool electionRelatedFeatureDatasets = featureDatasetDefinitions.Any(definition => definition.GetName().Contains("Election"));

      IReadOnlyList<AttributedRelationshipClassDefinition> attributedRelationshipClassDefinitions = geodatabase.GetDefinitions<AttributedRelationshipClassDefinition>();

      IReadOnlyList<RelationshipClassDefinition> relationshipClassDefinitions = geodatabase.GetDefinitions<RelationshipClassDefinition>();
    }
  });
}

    now:

public async Task ObtainingDefinitionsFromGeodatabase()
{
  await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() => {
    using (Geodatabase geodatabase = new Geodatabase(new DatabaseConnectionFile(new Uri("path\\to\\sde\\file\\sdefile.sde")))) {
      IReadOnlyList<FeatureClassDefinition> enterpriseDefinitions = geodatabase.GetDefinitions<FeatureClassDefinition>();
      IEnumerable<Definition> featureClassesHavingGlobalID = enterpriseDefinitions.Where(definition => definition.HasGlobalID());

      IReadOnlyList<FeatureDatasetDefinition> featureDatasetDefinitions = geodatabase.GetDefinitions<FeatureDatasetDefinition>();
      bool electionRelatedFeatureDatasets = featureDatasetDefinitions.Any(definition => definition.GetName().Contains("Election"));

      IReadOnlyList<AttributedRelationshipClassDefinition> attributedRelationshipClassDefinitions = geodatabase.GetDefinitions<AttributedRelationshipClassDefinition>();

      IReadOnlyList<RelationshipClassDefinition> relationshipClassDefinitions = geodatabase.GetDefinitions<RelationshipClassDefinition>();
    }
  });
}

Obtaining Related Defintions from Geodatabase

    before:

public async Task ObtainingRelatedDefinitionsFromGeodatabase()
{
  await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
  {
    using (Geodatabase geodatabase = new Geodatabase(new DatabaseConnectionFile(new Uri("path\\to\\sde\\file\\sdefile.sde"))))
    {
      // Remember the qualification of DatabaseName. for the RelationshipClass.

      RelationshipClassDefinition enterpriseDefinition = geodatabase.GetDefinition<RelationshipClassDefinition>("LocalGovernment.GDB.AddressPointHasSiteAddresses");
      IReadOnlyList<Definition> enterpriseDefinitions = geodatabase.GetRelatedDefinitions(enterpriseDefinition, DefinitionRelationshipType.DatasetsRelatedThrough);
      FeatureClassDefinition enterpriseAddressPointDefinition = enterpriseDefinitions.First(
              defn => defn.GetName().Equals("LocalGovernment.GDB.AddressPoint")) as FeatureClassDefinition;

      FeatureDatasetDefinition featureDatasetDefinition = geodatabase.GetDefinition<FeatureDatasetDefinition>("LocalGovernment.GDB.Address");
      IReadOnlyList<Definition> datasetsInAddressDataset = geodatabase.GetRelatedDefinitions(featureDatasetDefinition, DefinitionRelationshipType.DatasetInFeatureDataset);
      FeatureClassDefinition addressPointInAddressDataset = datasetsInAddressDataset.First(
              defn => defn.GetName().Equals("LocalGovernment.GDB.AddressPoint")) as FeatureClassDefinition;

      RelationshipClassDefinition addressPointHasSiteAddressInAddressDataset = datasetsInAddressDataset.First(
              defn => defn.GetName().Equals("LocalGovernment.GDB.AddressPointHasSiteAddresses")) as RelationshipClassDefinition;
    }
  });
}

    now:

public async Task ObtainingRelatedDefinitionsFromGeodatabase()
{
  await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() => {
    using (Geodatabase geodatabase = new Geodatabase(new DatabaseConnectionFile(new Uri("path\\to\\sde\\file\\sdefile.sde")))) {
      // Remember the qualification of DatabaseName. for the RelationshipClass.

      RelationshipClassDefinition enterpriseDefinition = geodatabase.GetDefinition<RelationshipClassDefinition>("LocalGovernment.GDB.AddressPointHasSiteAddresses");
      IReadOnlyList<Definition> enterpriseDefinitions = geodatabase.GetRelatedDefinitions(enterpriseDefinition, DefinitionRelationshipType.DatasetsRelatedThrough);
      FeatureClassDefinition enterpriseAddressPointDefinition = enterpriseDefinitions.First(
              defn => defn.GetName().Equals("LocalGovernment.GDB.AddressPoint")) as FeatureClassDefinition;

      FeatureDatasetDefinition featureDatasetDefinition = geodatabase.GetDefinition<FeatureDatasetDefinition>("LocalGovernment.GDB.Address");
      IReadOnlyList<Definition> datasetsInAddressDataset = geodatabase.GetRelatedDefinitions(featureDatasetDefinition, DefinitionRelationshipType.DatasetInFeatureDataset);
      FeatureClassDefinition addressPointInAddressDataset = datasetsInAddressDataset.First(
              defn => defn.GetName().Equals("LocalGovernment.GDB.AddressPoint")) as FeatureClassDefinition;

      RelationshipClassDefinition addressPointHasSiteAddressInAddressDataset = datasetsInAddressDataset.First(
              defn => defn.GetName().Equals("LocalGovernment.GDB.AddressPointHasSiteAddresses")) as RelationshipClassDefinition;
    }
  });
}

Searching a Table using QueryFilter

    before:

public async Task SearchingATable()
{
  await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
  {
    using (Geodatabase geodatabase = new Geodatabase(new DatabaseConnectionFile(new Uri("path\\to\\sde\\file\\sdefile.sde"))))
    using (Table table             = geodatabase.OpenDataset<Table>("EmployeeInfo"))
    {
      try
      {
        QueryFilter queryFilter = new QueryFilter
        {
          WhereClause   = "COSTCTRN = 'Information Technology'",
          SubFields     = "KNOWNAS, OFFICE, LOCATION",
          PostfixClause = "ORDER BY OFFICE"
        };

        using (RowCursor rowCursor = table.Search(queryFilter, false))
        {
          while (rowCursor.MoveNext())
          {
            using (Row row = rowCursor.Current)
            {
              string location = Convert.ToString(row["LOCATION"]);
              string knownAs = Convert.ToString(row["KNOWNAS"]);
            }
          }
        }
      }
      catch (GeodatabaseFieldException fieldException)
      {
        // One of the fields in the where clause might not exist. There are multiple ways this can be handled:
        // Handle error appropriately
      }
      catch (Exception exception)
      {
        // logger.Error(exception.Message);
      }
    }
  });
}

    now:

public async Task SearchingATable()
{
  try {
    await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() => {
      using (Geodatabase geodatabase = new Geodatabase(new DatabaseConnectionFile(new Uri("path\\to\\sde\\file\\sdefile.sde"))))
      using (Table table = geodatabase.OpenDataset<Table>("EmployeeInfo")) {

        QueryFilter queryFilter = new QueryFilter {
          WhereClause = "COSTCTRN = 'Information Technology'",
          SubFields = "KNOWNAS, OFFICE, LOCATION",
          PostfixClause = "ORDER BY OFFICE"
        };

        using (RowCursor rowCursor = table.Search(queryFilter, false)) {
          while (rowCursor.MoveNext()) {
            using (Row row = rowCursor.Current) {
              string location = Convert.ToString(row["LOCATION"]);
              string knownAs = Convert.ToString(row["KNOWNAS"]);
            }
          }
        }
      }
    });
  }
  catch (GeodatabaseFieldException fieldException) {
    // One of the fields in the where clause might not exist. There are multiple ways this can be handled:
    // Handle error appropriately
  }
  catch (Exception exception) {
    // logger.Error(exception.Message);
  }
}

Searching a FeatureClass using SpatialQueryFilter

    before:

public async Task SearchingAFeatureClass()
{
  await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
  {
    using (Geodatabase geodatabase                 = new Geodatabase(new DatabaseConnectionFile(new Uri("path\\to\\sde\\file\\sdefile.sde"))))
    using (FeatureClass schoolBoundaryFeatureClass = geodatabase.OpenDataset<FeatureClass>("LocalGovernment.GDB.SchoolBoundary"))
    {
      // Using a spatial query filter to find all features which have a certain district name and lying within a given Polygon.
      SpatialQueryFilter spatialQueryFilter = new SpatialQueryFilter
      {
        WhereClause    = "DISTRCTNAME = 'Indian Prairie School District 204'",
        FilterGeometry = new PolygonBuilder(new List<Coordinate>
        {
          new Coordinate(1021880, 1867396),
          new Coordinate(1028223, 1870705),
          new Coordinate(1031165, 1866844),
          new Coordinate(1025373, 1860501),
          new Coordinate(1021788, 1863810)
        }).ToGeometry(),

        SpatialRelationship = SpatialRelationship.Within
      };

      using (RowCursor indianPrairieCursor = schoolBoundaryFeatureClass.Search(spatialQueryFilter, false))
      {
        while (indianPrairieCursor.MoveNext())
        {
          using (Feature feature = (Feature)indianPrairieCursor.Current)
          {
            // Process the feature. For example...
            Console.WriteLine(feature.GetObjectID());
          }
        }
      }
    }
  });
}

    now:

public async Task SearchingAFeatureClass()
{
  await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() => {
    using (Geodatabase geodatabase = new Geodatabase(new DatabaseConnectionFile(new Uri("path\\to\\sde\\file\\sdefile.sde"))))
    using (FeatureClass schoolBoundaryFeatureClass = geodatabase.OpenDataset<FeatureClass>("LocalGovernment.GDB.SchoolBoundary")) {
      // Using a spatial query filter to find all features which have a certain district name and lying within a given Polygon.
      SpatialQueryFilter spatialQueryFilter = new SpatialQueryFilter {
        WhereClause = "DISTRCTNAME = 'Indian Prairie School District 204'",
        FilterGeometry = new PolygonBuilder(new List<Coordinate2D>
        {
          new Coordinate2D(1021880, 1867396),
          new Coordinate2D(1028223, 1870705),
          new Coordinate2D(1031165, 1866844),
          new Coordinate2D(1025373, 1860501),
          new Coordinate2D(1021788, 1863810)
        }).ToGeometry(),

        SpatialRelationship = SpatialRelationship.Within
      };

      using (RowCursor indianPrairieCursor = schoolBoundaryFeatureClass.Search(spatialQueryFilter, false)) {
        while (indianPrairieCursor.MoveNext()) {
          using (Feature feature = (Feature)indianPrairieCursor.Current) {
            // Process the feature. For example...
            Console.WriteLine(feature.GetObjectID());
          }
        }
      }
    }
  });
}

Selecting Rows from a Table

    before:

public async Task SelectingRowsFromATable()
{
  await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
  {
    using (Geodatabase geodatabase = new Geodatabase(new DatabaseConnectionFile(new Uri("path\\to\\sde\\file\\sdefile.sde"))))
    using (Table enterpriseTable   = geodatabase.OpenDataset<Table>("LocalGovernment.GDB.piCIPCost"))
    {
      QueryFilter anotherQueryFilter = new QueryFilter { WhereClause = "FLOOR = 1 AND WING = 'E'" };

      // For Selecting all matching entries.
      Selection anotherSelection = enterpriseTable.Select(anotherQueryFilter, SelectionType.ObjectID, SelectionOption.Normal);

      // This can be used to get one record which matches the criteria. No assumptions can be made about which record satisfying the criteria is selected.
      Selection onlyOneSelection = enterpriseTable.Select(anotherQueryFilter, SelectionType.ObjectID, SelectionOption.OnlyOne);

      // This can be used to obtain a empty selction which can be used as a container to combine results from different selections.
      Selection emptySelection = enterpriseTable.Select(anotherQueryFilter, SelectionType.ObjectID, SelectionOption.Empty);

      // If you want to select all the records in a table.
      Selection allRecordSelection = enterpriseTable.Select(null, SelectionType.ObjectID, SelectionOption.Normal);
    }
  });
}

    now:

public async Task SelectingRowsFromATable()
{
  await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() => {
    using (Geodatabase geodatabase = new Geodatabase(new DatabaseConnectionFile(new Uri("path\\to\\sde\\file\\sdefile.sde"))))
    using (Table enterpriseTable = geodatabase.OpenDataset<Table>("LocalGovernment.GDB.piCIPCost")) {
      QueryFilter anotherQueryFilter = new QueryFilter { WhereClause = "FLOOR = 1 AND WING = 'E'" };

      // For Selecting all matching entries.
      using (Selection anotherSelection = enterpriseTable.Select(anotherQueryFilter, SelectionType.ObjectID, SelectionOption.Normal)) {
      }

      // This can be used to get one record which matches the criteria. No assumptions can be made about which record satisfying the criteria is selected.
      using (Selection onlyOneSelection = enterpriseTable.Select(anotherQueryFilter, SelectionType.ObjectID, SelectionOption.OnlyOne)) {
      }

      // This can be used to obtain a empty selction which can be used as a container to combine results from different selections.
      using (Selection emptySelection = enterpriseTable.Select(anotherQueryFilter, SelectionType.ObjectID, SelectionOption.Empty)) {
      }

      // If you want to select all the records in a table.
      using (Selection allRecordSelection = enterpriseTable.Select(null, SelectionType.ObjectID, SelectionOption.Normal)) {
      }
    }
  });
}

Selecting Features from a FeatureClass

    before:

public async Task SelectingFeaturesFromAFeatureClass()
{
  await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
  {
    using (Geodatabase geodatabase             = new Geodatabase(new DatabaseConnectionFile(new Uri("path\\to\\sde\\file\\sdefile.sde"))))
    using (FeatureClass enterpriseFeatureClass = geodatabase.OpenDataset<FeatureClass>("LocalGovernment.GDB.FacilitySite"))
    {
      List<Coordinate> newCoordinates = new List<Coordinate>
      {
        new Coordinate(1021570, 1880583),
        new Coordinate(1028730, 1880994),
        new Coordinate(1029718, 1875644),
        new Coordinate(1021405, 1875397)
      };

      SpatialQueryFilter spatialFilter = new SpatialQueryFilter
      {
        WhereClause         = "FCODE = 'Park'",
        FilterGeometry      = new PolygonBuilder(newCoordinates).ToGeometry(),
        SpatialRelationship = SpatialRelationship.Crosses
      };

      // For Selecting all matching entries.
      Selection anotherSelection = enterpriseFeatureClass.Select(spatialFilter, SelectionType.ObjectID, SelectionOption.Normal);

      // This can be used to get one record which matches the criteria. No assumptions can be made about which record satisfying the 
      // criteria is selected.
      Selection onlyOneSelection = enterpriseFeatureClass.Select(spatialFilter, SelectionType.ObjectID, SelectionOption.OnlyOne);

      // This can be used to obtain a empty selction which can be used as a container to combine results from different selections.
      Selection emptySelection = enterpriseFeatureClass.Select(spatialFilter, SelectionType.ObjectID, SelectionOption.Empty);

      // If you want to select all the records in a table.
      Selection allRecordSelection = enterpriseFeatureClass.Select(null, SelectionType.ObjectID, SelectionOption.Normal);
    }
  });
}

    now:

public async Task SelectingFeaturesFromAFeatureClass()
{
  await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() => {
    using (Geodatabase geodatabase = new Geodatabase(new DatabaseConnectionFile(new Uri("path\\to\\sde\\file\\sdefile.sde"))))
    using (FeatureClass enterpriseFeatureClass = geodatabase.OpenDataset<FeatureClass>("LocalGovernment.GDB.FacilitySite")) {
      List<Coordinate2D> newCoordinates = new List<Coordinate2D>
      {
        new Coordinate2D(1021570, 1880583),
        new Coordinate2D(1028730, 1880994),
        new Coordinate2D(1029718, 1875644),
        new Coordinate2D(1021405, 1875397)
      };

      SpatialQueryFilter spatialFilter = new SpatialQueryFilter {
        WhereClause = "FCODE = 'Park'",
        FilterGeometry = new PolygonBuilder(newCoordinates).ToGeometry(),
        SpatialRelationship = SpatialRelationship.Crosses
      };

      // For Selecting all matching entries.
      using (Selection anotherSelection = enterpriseFeatureClass.Select(spatialFilter, SelectionType.ObjectID, SelectionOption.Normal)) {
      }

      // This can be used to get one record which matches the criteria. No assumptions can be made about which record satisfying the 
      // criteria is selected.
      using (Selection onlyOneSelection = enterpriseFeatureClass.Select(spatialFilter, SelectionType.ObjectID, SelectionOption.OnlyOne)) {
      }

      // This can be used to obtain a empty selction which can be used as a container to combine results from different selections.
      using (Selection emptySelection = enterpriseFeatureClass.Select(spatialFilter, SelectionType.ObjectID, SelectionOption.Empty)) {
      }

      // If you want to select all the records in a table.
      using (Selection allRecordSelection = enterpriseFeatureClass.Select(null, SelectionType.ObjectID, SelectionOption.Normal)) {
      }
    }
  });
}

Creating a Row

    before:

public async Task CreatingARow()
{
  string message      = String.Empty;
  bool creationResult = false;

  await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
  {
    using (Geodatabase geodatabase = new Geodatabase(new DatabaseConnectionFile(new Uri("path\\to\\sde\\file\\sdefile.sde"))))
    using (Table enterpriseTable   = geodatabase.OpenDataset<Table>("LocalGovernment.GDB.piCIPCost"))
    {
      EditOperation editOperation = new EditOperation();
      editOperation.Callback(context =>      
      {
        try
        {
          TableDefinition tableDefinition = enterpriseTable.GetDefinition();
          int assetNameIndex= tableDefinition.FindField("ASSETNA");

          using (RowBuffer rowBuffer = enterpriseTable.CreateRowBuffer())
          {
            // Either the field index or the field name can be used in the indexer.
            rowBuffer[assetNameIndex] = "wMain";
            rowBuffer["COST"]         = 700;
            rowBuffer["ACTION"]       = "Open Cut";

            // subtype value for "Abandon".
            rowBuffer[tableDefinition.GetSubtypeField()] = 3;

            using (Row row = enterpriseTable.CreateRow(rowBuffer))
            {
              // To Indicate that the attribute table has to be updated.
              context.Invalidate(row);
            }
          }
        }
        catch (GeodatabaseException exObj)
        {
          message = exObj.Message;
        }
      }, enterpriseTable);

      var task = editOperation.ExecuteAsync();
      creationResult = task.Result;
      if (!creationResult)
        message = editOperation.ErrorMessage;
    }
  });

  if (!creationResult)
    MessageBox.Show(message);
}

    now:

public async Task CreatingARow()
{
  string message = String.Empty;
  bool creationResult = false;
  EditOperation editOperation = new EditOperation();

  await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() => {

    using (Geodatabase geodatabase = new Geodatabase(new DatabaseConnectionFile(new Uri("path\\to\\sde\\file\\sdefile.sde"))))
    using (Table enterpriseTable = geodatabase.OpenDataset<Table>("LocalGovernment.GDB.piCIPCost")) {

      //var geodatabase = new Geodatabase(new FileGeodatabaseConnectionPath(uri)) for a File GDB
      //
      //var shapeFileConnPath = new FileSystemConnectionPath(uri, FileSystemDatastoreType.Shapefile);
      //var shapefile = new FileSystemDatastore(shapeFileConnPath);
      //var table = shapefile.OpenDataset<Table>(strShapeFileName); for a Shape file

      //declare the callback here. We are not executing it ~yet~
      editOperation.Callback(context => {
        TableDefinition tableDefinition = enterpriseTable.GetDefinition();
        int assetNameIndex = tableDefinition.FindField("ASSETNA");

        using (RowBuffer rowBuffer = enterpriseTable.CreateRowBuffer()) {
          // Either the field index or the field name can be used in the indexer.
          rowBuffer[assetNameIndex] = "wMain";
          rowBuffer["COST"] = 700;
          rowBuffer["ACTION"] = "Open Cut";

          // subtype value for "Abandon".
          rowBuffer[tableDefinition.GetSubtypeField()] = 3;

          using (Row row = enterpriseTable.CreateRow(rowBuffer)) {
            // To Indicate that the attribute table has to be updated.
            context.Invalidate(row);
          }
        }
      }, enterpriseTable);

      try {
        creationResult = editOperation.Execute();
        if (!creationResult) message = editOperation.ErrorMessage;
      }
      catch (GeodatabaseException exObj) {
        message = exObj.Message;
      }
    }
  });

  if (!string.IsNullOrEmpty(message))
    MessageBox.Show(message);

}

Creating a Feature

    before:

public async Task CreatingAFeature()
{
  string message      = String.Empty;
  bool creationResult = false;

  await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
  {
    using (Geodatabase geodatabase             = new Geodatabase(new DatabaseConnectionFile(new Uri("path\\to\\sde\\file\\sdefile.sde"))))
    using (FeatureClass enterpriseFeatureClass = geodatabase.OpenDataset<FeatureClass>("LocalGovernment.GDB.FacilitySite"))
    {
      EditOperation editOperation = new EditOperation();
      editOperation.Callback(context =>        
      {
        try
        {
          FeatureClassDefinition facilitySiteDefinition = enterpriseFeatureClass.GetDefinition();
          int facilityIdIndex = facilitySiteDefinition.FindField("FACILITYID");

          using (RowBuffer rowBuffer = enterpriseFeatureClass.CreateRowBuffer())
          {
            // Either the field index or the field name can be used in the indexer.
            rowBuffer[facilityIdIndex] = "wMain";
            rowBuffer["NAME"]          = "Griffith Park";
            rowBuffer["OWNTYPE"]       = "Municipal";
            rowBuffer["FCODE"]         = "Park";
            // Add it to Public Attractions Subtype.
            rowBuffer[facilitySiteDefinition.GetSubtypeField()] = 820;
            
            List<Coordinate> newCoordinates = new List<Coordinate>
            {
              new Coordinate(1021570, 1880583),
              new Coordinate(1028730, 1880994),
              new Coordinate(1029718, 1875644),
              new Coordinate(1021405, 1875397)
            };
            
            rowBuffer[facilitySiteDefinition.GetShapeField()] = new PolygonBuilder(newCoordinates).ToGeometry();
            
            using (Feature feature = enterpriseFeatureClass.CreateRow(rowBuffer))
            {
              //To Indicate that the attribute table has to be updated
              context.Invalidate(feature);
            }
          }
        }
        catch (GeodatabaseException exObj)
        {
          message = exObj.Message;
        }
      }, enterpriseFeatureClass);

      var task = editOperation.ExecuteAsync();
      creationResult = task.Result;

      if (!creationResult)
        message = editOperation.ErrorMessage;
    }
  });

  if (!creationResult)
    MessageBox.Show(message);
}

    now:

public async Task CreatingAFeature()
{
  string message = String.Empty;
  bool creationResult = false;

  await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() => {
    using (Geodatabase geodatabase = new Geodatabase(new DatabaseConnectionFile(new Uri("path\\to\\sde\\file\\sdefile.sde"))))
    using (FeatureClass enterpriseFeatureClass = geodatabase.OpenDataset<FeatureClass>("LocalGovernment.GDB.FacilitySite")) {
      //var geodatabase = new Geodatabase(new FileGeodatabaseConnectionPath(uri)) for a File GDB
      //
      //var shapeFileConnPath = new FileSystemConnectionPath(uri, FileSystemDatastoreType.Shapefile);
      //var shapefile = new FileSystemDatastore(shapeFileConnPath);
      //var table = shapefile.OpenDataset<Table>(strShapeFileName); for a Shape file

      //declare the callback here. We are not executing it ~yet~
      EditOperation editOperation = new EditOperation();
      editOperation.Callback(context => {
        FeatureClassDefinition facilitySiteDefinition = enterpriseFeatureClass.GetDefinition();
        int facilityIdIndex = facilitySiteDefinition.FindField("FACILITYID");

        using (RowBuffer rowBuffer = enterpriseFeatureClass.CreateRowBuffer()) {
          // Either the field index or the field name can be used in the indexer.
          rowBuffer[facilityIdIndex] = "wMain";
          rowBuffer["NAME"] = "Griffith Park";
          rowBuffer["OWNTYPE"] = "Municipal";
          rowBuffer["FCODE"] = "Park";
          // Add it to Public Attractions Subtype.
          rowBuffer[facilitySiteDefinition.GetSubtypeField()] = 820;

          List<Coordinate2D> newCoordinates = new List<Coordinate2D>
          {
              new Coordinate2D(1021570, 1880583),
              new Coordinate2D(1028730, 1880994),
              new Coordinate2D(1029718, 1875644),
              new Coordinate2D(1021405, 1875397)
            };

          rowBuffer[facilitySiteDefinition.GetShapeField()] = new PolygonBuilder(newCoordinates).ToGeometry();

          using (Feature feature = enterpriseFeatureClass.CreateRow(rowBuffer)) {
            //To Indicate that the attribute table has to be updated
            context.Invalidate(feature);
          }
        }

      }, enterpriseFeatureClass);

      try {
        creationResult = editOperation.Execute();
        if (!creationResult) message = editOperation.ErrorMessage;
      }
      catch (GeodatabaseException exObj) {
        message = exObj.Message;
      }
    }
  });

  if (!string.IsNullOrEmpty(message))
    MessageBox.Show(message);
}

Modifying a Row

    before:

public async Task ModifyingARow()
{
  string message          = String.Empty;
  bool modificationResult = false;

  await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
  {
    using (Geodatabase geodatabase = new Geodatabase(new DatabaseConnectionFile(new Uri("path\\to\\sde\\file\\sdefile.sde"))))
    using (Table enterpriseTable   = geodatabase.OpenDataset<Table>("LocalGovernment.GDB.piCIPCost"))
    {
      EditOperation editOperation = new EditOperation();
      editOperation.Callback(context =>  
      {
        QueryFilter openCutFilter = new QueryFilter { WhereClause = "ACTION = 'Open Cut'" };

        using (RowCursor rowCursor = enterpriseTable.Search(openCutFilter, false))
        {
          TableDefinition tableDefinition = enterpriseTable.GetDefinition();
          int subtypeFieldIndex = tableDefinition.FindField(tableDefinition.GetSubtypeField());
          
          while (rowCursor.MoveNext())
          {
            using (Row row = rowCursor.Current)
            {
              // In order to update the Map and/or the attribute table.
              // Has to be called before any changes are made to the row.
              context.Invalidate(row);
              
              row["ASSETNA"] = "wMainOpenCut";
              
              if (Convert.ToDouble(row["COST"]) > 700)
              {
                // Abandon asset if cost is higher than 700 (if that is what you want to do).
                row["ACTION"]          = "Open Cut Abandon";
                row[subtypeFieldIndex] = 3; //subtype value for "Abandon"   
              }

              //After all the changes are done, persist it.
              row.Store();

              // Has to be called after the store too.
              context.Invalidate(row);
            }
          }
        }
      }, enterpriseTable);

      var task = editOperation.ExecuteAsync();
      modificationResult = task.Result;
      if (!modificationResult)
        message = editOperation.ErrorMessage;
    }
  });

  if (!modificationResult)
    MessageBox.Show(message);
}

    now:

public async Task ModifyingARow()
{
  string message = String.Empty;
  bool modificationResult = false;

  await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() => {
    using (Geodatabase geodatabase = new Geodatabase(new DatabaseConnectionFile(new Uri("path\\to\\sde\\file\\sdefile.sde"))))
    using (Table enterpriseTable = geodatabase.OpenDataset<Table>("LocalGovernment.GDB.piCIPCost")) {
      //var geodatabase = new Geodatabase(new FileGeodatabaseConnectionPath(uri)) for a File GDB
      //
      //var shapeFileConnPath = new FileSystemConnectionPath(uri, FileSystemDatastoreType.Shapefile);
      //var shapefile = new FileSystemDatastore(shapeFileConnPath);
      //var table = shapefile.OpenDataset<Table>(strShapeFileName); for a Shape file

      EditOperation editOperation = new EditOperation();
      editOperation.Callback(context => {
        QueryFilter openCutFilter = new QueryFilter { WhereClause = "ACTION = 'Open Cut'" };

        using (RowCursor rowCursor = enterpriseTable.Search(openCutFilter, false)) {
          TableDefinition tableDefinition = enterpriseTable.GetDefinition();
          int subtypeFieldIndex = tableDefinition.FindField(tableDefinition.GetSubtypeField());

          while (rowCursor.MoveNext()) {
            using (Row row = rowCursor.Current) {
              // In order to update the Map and/or the attribute table.
              // Has to be called before any changes are made to the row.
              context.Invalidate(row);

              row["ASSETNA"] = "wMainOpenCut";

              if (Convert.ToDouble(row["COST"]) > 700) {
                // Abandon asset if cost is higher than 700 (if that is what you want to do).
                row["ACTION"] = "Open Cut Abandon";
                row[subtypeFieldIndex] = 3; //subtype value for "Abandon"   
              }

              //After all the changes are done, persist it.
              row.Store();

              // Has to be called after the store too.
              context.Invalidate(row);
            }
          }
        }
      }, enterpriseTable);

      try {
        modificationResult = editOperation.Execute();
        if (!modificationResult) message = editOperation.ErrorMessage;
      }
      catch (GeodatabaseException exObj) {
        message = exObj.Message;
      }
    }
  });

  if (!string.IsNullOrEmpty(message))
    MessageBox.Show(message);
}

Modifying a Feature

    before:

public async Task ModifyingAFeature()
{
  string message          = String.Empty;
  bool modificationResult = false;

  await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
  {
    using (Geodatabase geodatabase             = new Geodatabase(new DatabaseConnectionFile(new Uri("path\\to\\sde\\file\\sdefile.sde"))))
    using (FeatureClass enterpriseFeatureClass = geodatabase.OpenDataset<FeatureClass>("LocalGovernment.GDB.FacilitySite"))
    {
      FeatureClassDefinition facilitySiteDefinition = enterpriseFeatureClass.GetDefinition();

      int ownTypeIndex = facilitySiteDefinition.FindField("OWNTYPE");
      int areaIndex    = facilitySiteDefinition.FindField(facilitySiteDefinition.GetAreaField());

      EditOperation editOperation = new EditOperation();
      editOperation.Callback(context =>
      {
        QueryFilter queryFilter = new QueryFilter { WhereClause = "FCODE = 'Hazardous Materials Facility' AND OWNTYPE = 'Private'" };
        
        using (RowCursor rowCursor = enterpriseFeatureClass.Search(queryFilter, false))
        {
          while (rowCursor.MoveNext())
          {
            using (Feature feature = (Feature)rowCursor.Current)
            {
              // In order to update the Map and/or the attribute table.
              // Has to be called before any changes are made to the row
              context.Invalidate(feature);

              // Transfer all Hazardous Material Facilities to the City.
              feature[ownTypeIndex] = "Municipal";
              
              if (Convert.ToDouble(feature[areaIndex]) > 50000)
              {
                // Set the Shape of the feature to whatever you need.
                List<Coordinate> newCoordinates = new List<Coordinate>
                {
                  new Coordinate(1021570, 1880583),
                  new Coordinate(1028730, 1880994),
                  new Coordinate(1029718, 1875644),
                  new Coordinate(1021405, 1875397)
                };
                
                feature.SetShape(new PolygonBuilder(newCoordinates).ToGeometry());
              }

              feature.Store();

              // Has to be called after the store too
              context.Invalidate(feature);
            }
          }
        }
      }, enterpriseFeatureClass);

      var task = editOperation.ExecuteAsync();
      modificationResult = task.Result;

      if (!modificationResult)
        message = editOperation.ErrorMessage;
    }
  });

  if (!modificationResult)
    MessageBox.Show(message);
}

    now:

public async Task ModifyingAFeature()
{
  string message = String.Empty;
  bool modificationResult = false;

  await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() => {
    using (Geodatabase geodatabase = new Geodatabase(new DatabaseConnectionFile(new Uri("path\\to\\sde\\file\\sdefile.sde"))))
    using (FeatureClass enterpriseFeatureClass = geodatabase.OpenDataset<FeatureClass>("LocalGovernment.GDB.FacilitySite")) {

      //var geodatabase = new Geodatabase(new FileGeodatabaseConnectionPath(uri)) for a File GDB
      //
      //var shapeFileConnPath = new FileSystemConnectionPath(uri, FileSystemDatastoreType.Shapefile);
      //var shapefile = new FileSystemDatastore(shapeFileConnPath);
      //var table = shapefile.OpenDataset<Table>(strShapeFileName); for a Shape file

      FeatureClassDefinition facilitySiteDefinition = enterpriseFeatureClass.GetDefinition();

      int ownTypeIndex = facilitySiteDefinition.FindField("OWNTYPE");
      int areaIndex = facilitySiteDefinition.FindField(facilitySiteDefinition.GetAreaField());

      EditOperation editOperation = new EditOperation();
      editOperation.Callback(context => {
        QueryFilter queryFilter = new QueryFilter { WhereClause = "FCODE = 'Hazardous Materials Facility' AND OWNTYPE = 'Private'" };

        using (RowCursor rowCursor = enterpriseFeatureClass.Search(queryFilter, false)) {
          while (rowCursor.MoveNext()) {
            using (Feature feature = (Feature)rowCursor.Current) {
              // In order to update the Map and/or the attribute table.
              // Has to be called before any changes are made to the row
              context.Invalidate(feature);

              // Transfer all Hazardous Material Facilities to the City.
              feature[ownTypeIndex] = "Municipal";

              if (Convert.ToDouble(feature[areaIndex]) > 50000) {
                // Set the Shape of the feature to whatever you need.
                List<Coordinate2D> newCoordinates = new List<Coordinate2D>
                {
                  new Coordinate2D(1021570, 1880583),
                  new Coordinate2D(1028730, 1880994),
                  new Coordinate2D(1029718, 1875644),
                  new Coordinate2D(1021405, 1875397)
                };

                feature.SetShape(new PolygonBuilder(newCoordinates).ToGeometry());
              }

              feature.Store();

              // Has to be called after the store too
              context.Invalidate(feature);
            }
          }
        }
      }, enterpriseFeatureClass);

      try {
        modificationResult = editOperation.Execute();
        if (!modificationResult) message = editOperation.ErrorMessage;
      }
      catch (GeodatabaseException exObj) {
        message = exObj.Message;
      }
    }
  });

  if (!string.IsNullOrEmpty(message))
    MessageBox.Show(message);
}

Deleting a Row/Feature

    before:

public async Task DeletingARowOrFeature()
{
  string message      = String.Empty;
  bool deletionResult = false;

  await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
  {
    using (Geodatabase geodatabase = new Geodatabase(new DatabaseConnectionFile(new Uri("path\\to\\sde\\file\\sdefile.sde"))))
    using (Table enterpriseTable   = geodatabase.OpenDataset<Table>("LocalGovernment.GDB.piCIPCost"))
    {
      EditOperation editOperation = new EditOperation();
      editOperation.Callback(context =>
      {
        QueryFilter openCutFilter = new QueryFilter { WhereClause = "ACTION = 'Open Cut'" };

        using (RowCursor rowCursor = enterpriseTable.Search(openCutFilter, false))
        {
          while (rowCursor.MoveNext())
          {
            using (Row row = rowCursor.Current)
            {
              // In order to update the Map and/or the attribute table. Has to be called before the delete.
              context.Invalidate(row);
              
              row.Delete();
            }
          }
        }
      }, enterpriseTable);

      var task = editOperation.ExecuteAsync();
      deletionResult = task.Result;

      if (!deletionResult)
        message = editOperation.ErrorMessage;
    }
  });

  if (!deletionResult)
    MessageBox.Show(message);
}

    now:

public async Task DeletingARowOrFeature()
{
  string message = String.Empty;
  bool deletionResult = false;

  await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() => {
    using (Geodatabase geodatabase = new Geodatabase(new DatabaseConnectionFile(new Uri("path\\to\\sde\\file\\sdefile.sde"))))
    using (Table enterpriseTable = geodatabase.OpenDataset<Table>("LocalGovernment.GDB.piCIPCost")) {

      //var geodatabase = new Geodatabase(new FileGeodatabaseConnectionPath(uri)) for a File GDB
      //
      //var shapeFileConnPath = new FileSystemConnectionPath(uri, FileSystemDatastoreType.Shapefile);
      //var shapefile = new FileSystemDatastore(shapeFileConnPath);
      //var table = shapefile.OpenDataset<Table>(strShapeFileName); for a Shape file

      EditOperation editOperation = new EditOperation();
      editOperation.Callback(context => {
        QueryFilter openCutFilter = new QueryFilter { WhereClause = "ACTION = 'Open Cut'" };

        using (RowCursor rowCursor = enterpriseTable.Search(openCutFilter, false)) {
          while (rowCursor.MoveNext()) {
            using (Row row = rowCursor.Current) {
              // In order to update the Map and/or the attribute table. Has to be called before the delete.
              context.Invalidate(row);

              row.Delete();
            }
          }
        }
      }, enterpriseTable);

      try {
        deletionResult = editOperation.Execute();
        if (!deletionResult) message = editOperation.ErrorMessage;
      }
      catch (GeodatabaseException exObj) {
        message = exObj.Message;
      }
    }
  });

  if (!string.IsNullOrEmpty(message))
    MessageBox.Show(message);
}

Obtaining a memory stream to modify or create Attachment data

    before:

private MemoryStream CreateMemoryStreamFromContentsOf(String fileNameWithPath)
{
  MemoryStream memoryStream = new MemoryStream();

  using (FileStream file = new FileStream(fileNameWithPath, FileMode.Open, FileAccess.Read))
  {
    byte[] bytes = new byte[file.Length];
    file.Read(bytes, 0, (int)file.Length);
    memoryStream.Write(bytes, 0, (int)file.Length);
  }

  return memoryStream;
}

    now:

private MemoryStream CreateMemoryStreamFromContentsOf(String fileNameWithPath)
{
  MemoryStream memoryStream = new MemoryStream();

  using (FileStream file = new FileStream(fileNameWithPath, FileMode.Open, FileAccess.Read)) {
    byte[] bytes = new byte[file.Length];
    file.Read(bytes, 0, (int)file.Length);
    memoryStream.Write(bytes, 0, (int)file.Length);
  }

  return memoryStream;
}

Adding Attachments

    before:

public async Task AddingAttachments()
{
  await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
  {
    using (Geodatabase geodatabase       = new Geodatabase(new DatabaseConnectionFile(new Uri("path\\to\\sde\\file\\sdefile.sde"))))
    using (FeatureClass parkFeatureClass = geodatabase.OpenDataset<FeatureClass>("LocalGovernment.GDB.Park"))
    {
      QueryFilter filter = new QueryFilter { WhereClause = "NUMPARKING > 0" };

      using (RowCursor parkingCursor = parkFeatureClass.Search(filter, false))
      {
        while (parkingCursor.MoveNext())
        {
          using (MemoryStream stream = CreateMemoryStreamFromContentsOf("Sample.xml"))
          {
            Attachment attachment = new Attachment("Sample.xml", "text/xml", stream);

            using (Row row = parkingCursor.Current)
            {
              long attachmentId = row.AddAttachment(attachment);
            }
          }
        }
      }
    }
  });
}

    now:

public async Task AddingAttachments()
{
  await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() => {
    using (Geodatabase geodatabase = new Geodatabase(new DatabaseConnectionFile(new Uri("path\\to\\sde\\file\\sdefile.sde"))))
    using (FeatureClass parkFeatureClass = geodatabase.OpenDataset<FeatureClass>("LocalGovernment.GDB.Park")) {
      QueryFilter filter = new QueryFilter { WhereClause = "NUMPARKING > 0" };

      using (RowCursor parkingCursor = parkFeatureClass.Search(filter, false)) {
        while (parkingCursor.MoveNext()) {
          using (MemoryStream stream = CreateMemoryStreamFromContentsOf("Sample.xml")) {
            Attachment attachment = new Attachment("Sample.xml", "text/xml", stream);

            using (Row row = parkingCursor.Current) {
              long attachmentId = row.AddAttachment(attachment);
            }
          }
        }
      }
    }
  });
}

Updating Attachments

    before:

public async Task UpdatingAttachments()
{
  await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
  {
    using (Geodatabase geodatabase = new Geodatabase(new DatabaseConnectionFile(new Uri("path\\to\\sde\\file\\sdefile.sde"))))
    using (FeatureClass landUseCaseFeatureClass = geodatabase.OpenDataset<FeatureClass>("LocalGovernment.GDB.LandUseCase"))
    {
      QueryFilter filter = new QueryFilter { WhereClause = "CASETYPE = 'Rezoning'" };

      using (RowCursor landUseCursor = landUseCaseFeatureClass.Search(filter, false))
      {
        while (landUseCursor.MoveNext())
        {
          Feature rezoningUseCase = (Feature)landUseCursor.Current;

          IReadOnlyList<Attachment> rezoningAttachments = rezoningUseCase.GetAttachments();
          IEnumerable<Attachment> filteredAttachments = rezoningAttachments.Where(attachment => !attachment.GetName().Contains("rezoning"));

          foreach (Attachment attachmentToUpdate in filteredAttachments)
          {
            attachmentToUpdate.SetName(attachmentToUpdate.GetName().Replace(".pdf", "Rezoning.pdf"));
            rezoningUseCase.UpdateAttachment(attachmentToUpdate);
          }
        }
      }
    }
  });
}

    now:

public async Task UpdatingAttachments()
{
  await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() => {
    using (Geodatabase geodatabase = new Geodatabase(new DatabaseConnectionFile(new Uri("path\\to\\sde\\file\\sdefile.sde"))))
    using (FeatureClass landUseCaseFeatureClass = geodatabase.OpenDataset<FeatureClass>("LocalGovernment.GDB.LandUseCase")) {
      QueryFilter filter = new QueryFilter { WhereClause = "CASETYPE = 'Rezoning'" };

      using (RowCursor landUseCursor = landUseCaseFeatureClass.Search(filter, false)) {
        while (landUseCursor.MoveNext()) {
          Feature rezoningUseCase = (Feature)landUseCursor.Current;

          IReadOnlyList<Attachment> rezoningAttachments = rezoningUseCase.GetAttachments();
          IEnumerable<Attachment> filteredAttachments = rezoningAttachments.Where(attachment => !attachment.GetName().Contains("rezoning"));

          foreach (Attachment attachmentToUpdate in filteredAttachments) {
            attachmentToUpdate.SetName(attachmentToUpdate.GetName().Replace(".pdf", "Rezoning.pdf"));
            rezoningUseCase.UpdateAttachment(attachmentToUpdate);
          }
        }
      }
    }
  });
}

Deleting Attachments

    before:

public async Task DeletingAttachments()
{
  await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
  {
    using (Geodatabase geodatabase = new Geodatabase(new DatabaseConnectionFile(new Uri("path\\to\\sde\\file\\sdefile.sde"))))
    using (Table inspectionTable   = geodatabase.OpenDataset<Table>("luCodeInspection"))
    {
      QueryFilter queryFilter = new QueryFilter { WhereClause = "ACTION = '1st Notice'" };

      using (RowCursor cursor = inspectionTable.Search(queryFilter, false))
      {
        while (cursor.MoveNext())
        {
          using (Row currentRow = cursor.Current)
          {
            IReadOnlyList<Attachment> rowAttachments = currentRow.GetAttachments(null, true);
            IEnumerable<Attachment> attachments      = rowAttachments.Where(attachment => attachment.GetContentType().Equals("application/pdf"));

            var attachmentIDs = attachments.Select(attachment => attachment.GetAttachmentID()) as IReadOnlyList<long>;
            IReadOnlyDictionary<long, Exception> failures = currentRow.DeleteAttachments(attachmentIDs);

            if (failures.Count > 0)
            {
              //process errors
            }
          }
        }
      }
    }
  });
}

    now:

public async Task DeletingAttachments()
{
  await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() => {
    using (Geodatabase geodatabase = new Geodatabase(new DatabaseConnectionFile(new Uri("path\\to\\sde\\file\\sdefile.sde"))))
    using (Table inspectionTable = geodatabase.OpenDataset<Table>("luCodeInspection")) {
      QueryFilter queryFilter = new QueryFilter { WhereClause = "ACTION = '1st Notice'" };

      using (RowCursor cursor = inspectionTable.Search(queryFilter, false)) {
        while (cursor.MoveNext()) {
          using (Row currentRow = cursor.Current) {
            IReadOnlyList<Attachment> rowAttachments = currentRow.GetAttachments(null, true);
            IEnumerable<Attachment> attachments = rowAttachments.Where(attachment => attachment.GetContentType().Equals("application/pdf"));

            var attachmentIDs = attachments.Select(attachment => attachment.GetAttachmentID()) as IReadOnlyList<long>;
            IReadOnlyDictionary<long, Exception> failures = currentRow.DeleteAttachments(attachmentIDs);

            if (failures.Count > 0) {
              //process errors
            }
          }
        }
      }
    }
  });
}

Working with Versions

    before:

public async Task WorkingWithVersions()
{
  await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
  {
    using (Geodatabase geodatabase       = new Geodatabase(new DatabaseConnectionFile(new Uri("path\\to\\sde\\file"))))
    using (VersionManager versionManager = geodatabase.GetVersionManager())
    {
      IReadOnlyList<Version> versionList = versionManager.GetVersions();

      //The default version will have a null Parent
      Version defaultVersion = versionList.First(version => version.GetParent() == null);

      IEnumerable<Version> publicVersions = versionList.Where(version => version.GetAccessType() == VersionAccessType.Public);
      Version qaVersion = defaultVersion.GetChildren().First(version => version.GetName().Contains("QA"));

      Geodatabase qaVersionGeodatabase = qaVersion.Connect();

      FeatureClass currentFeatureClass = geodatabase.OpenDataset<FeatureClass>("featureClassName");
      FeatureClass qaFeatureClass = qaVersionGeodatabase.OpenDataset<FeatureClass>("featureClassName");
    }
  });
}

    now:

public async Task WorkingWithVersions()
{
  await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() => {
    using (Geodatabase geodatabase = new Geodatabase(new DatabaseConnectionFile(new Uri("path\\to\\sde\\file"))))
    using (VersionManager versionManager = geodatabase.GetVersionManager()) {
      IReadOnlyList<Version> versionList = versionManager.GetVersions();

      //The default version will have a null Parent
      Version defaultVersion = versionList.First(version => version.GetParent() == null);

      IEnumerable<Version> publicVersions = versionList.Where(version => version.GetAccessType() == VersionAccessType.Public);
      Version qaVersion = defaultVersion.GetChildren().First(version => version.GetName().Contains("QA"));

      Geodatabase qaVersionGeodatabase = qaVersion.Connect();

      FeatureClass currentFeatureClass = geodatabase.OpenDataset<FeatureClass>("featureClassName");
      FeatureClass qaFeatureClass = qaVersionGeodatabase.OpenDataset<FeatureClass>("featureClassName");
    }
  });
}

Getting Rows related by RelationshipClass

    before:

public async Task GettingRowsRelatedByRelationshipClass()
{
  await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
  {
    using (Geodatabase geodatabase             = new Geodatabase(new DatabaseConnectionFile(new Uri("path\\to\\sde\\file"))))
    using (RelationshipClass relationshipClass = geodatabase.OpenDataset<RelationshipClass>("LocalGovernment.GDB.luCodeViolationHasInspections"))
    using (FeatureClass violationsFeatureClass = geodatabase.OpenDataset<FeatureClass>("LocalGovernment.GDB.luCodeViolation"))
    using (Table inspectionTable               = geodatabase.OpenDataset<Table>("LocalGovernment.GDB.luCodeInspection"))
    {
      List<Row> jeffersonAveViolations = new List<Row>();
      QueryFilter queryFilter = new QueryFilter { WhereClause = "LOCDESC LIKE '///%Jefferson///%'" };

      using (RowCursor rowCursor = violationsFeatureClass.Search(queryFilter, false))
      {
        while (rowCursor.MoveNext())
        {
          jeffersonAveViolations.Add(rowCursor.Current);
        }
      }

      IReadOnlyList<Row> relatedOriginRows = null;
      IReadOnlyList<Row> relatedDestinationRows = null;

      try
      {
        QueryFilter filter = new QueryFilter { WhereClause = "ACTION = '1st Notice'" };
        Selection selection = inspectionTable.Select(filter, SelectionType.ObjectID, SelectionOption.Normal);

        relatedOriginRows = relationshipClass.GetRowsRelatedToDestinationRows(selection.GetObjectIDs());
        bool containsJeffersonAve = relatedOriginRows.Any(row => Convert.ToString(row["LOCDESC"]).Contains("Jefferson"));

        List<long> jeffersonAveViolationObjectIds = jeffersonAveViolations.Select(row => row.GetObjectID()).ToList();

        relatedDestinationRows = relationshipClass.GetRowsRelatedToOriginRows(jeffersonAveViolationObjectIds);
        bool hasFirstNoticeInspections = relatedDestinationRows.Any(row => Convert.ToString(row["ACTION"]).Contains("1st Notice"));
      }
      finally
      {
        Dispose(jeffersonAveViolations);
        Dispose(relatedOriginRows);
        Dispose(relatedDestinationRows);
      }
    }
  });
}

private static void Dispose(IEnumerable<Row> rows)
{
  foreach (Row row in rows)
    row.Dispose();
}

    now:

public async Task GettingRowsRelatedByRelationshipClass()
{
  await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() => {
    using (Geodatabase geodatabase = new Geodatabase(new DatabaseConnectionFile(new Uri("path\\to\\sde\\file"))))
    using (RelationshipClass relationshipClass = geodatabase.OpenDataset<RelationshipClass>("LocalGovernment.GDB.luCodeViolationHasInspections"))
    using (FeatureClass violationsFeatureClass = geodatabase.OpenDataset<FeatureClass>("LocalGovernment.GDB.luCodeViolation"))
    using (Table inspectionTable = geodatabase.OpenDataset<Table>("LocalGovernment.GDB.luCodeInspection")) {
      List<Row> jeffersonAveViolations = new List<Row>();
      QueryFilter queryFilter = new QueryFilter { WhereClause = "LOCDESC LIKE '///%Jefferson///%'" };

      using (RowCursor rowCursor = violationsFeatureClass.Search(queryFilter, false)) {
        while (rowCursor.MoveNext()) {
          jeffersonAveViolations.Add(rowCursor.Current);
        }
      }

      IReadOnlyList<Row> relatedOriginRows = null;
      IReadOnlyList<Row> relatedDestinationRows = null;

      try {
        QueryFilter filter = new QueryFilter { WhereClause = "ACTION = '1st Notice'" };

        using (Selection selection = inspectionTable.Select(filter, SelectionType.ObjectID, SelectionOption.Normal)) {
          relatedOriginRows = relationshipClass.GetRowsRelatedToDestinationRows(selection.GetObjectIDs());
        }

        bool containsJeffersonAve = relatedOriginRows.Any(row => Convert.ToString(row["LOCDESC"]).Contains("Jefferson"));

        List<long> jeffersonAveViolationObjectIds = jeffersonAveViolations.Select(row => row.GetObjectID()).ToList();

        relatedDestinationRows = relationshipClass.GetRowsRelatedToOriginRows(jeffersonAveViolationObjectIds);
        bool hasFirstNoticeInspections = relatedDestinationRows.Any(row => Convert.ToString(row["ACTION"]).Contains("1st Notice"));
      }
      finally {
        Dispose(jeffersonAveViolations);
        Dispose(relatedOriginRows);
        Dispose(relatedDestinationRows);
      }
    }
  });
}

private static void Dispose(IEnumerable<Row> rows)
{
  foreach (Row row in rows)
    row.Dispose();
}

Creating a Relationship

    before:

public async Task CreatingARelationship()
{
  await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
  {
    using (Geodatabase geodatabase             = new Geodatabase(new DatabaseConnectionFile(new Uri("path\\to\\sde\\file"))))
    using (RelationshipClass relationshipClass = geodatabase.OpenDataset<RelationshipClass>("LocalGovernment.GDB.OverviewToProject"))
    using (FeatureClass projectsFeatureClass   = geodatabase.OpenDataset<FeatureClass>("LocalGovernment.GDB.CIPProjects"))
    using (FeatureClass overviewFeatureClass   = geodatabase.OpenDataset<FeatureClass>("LocalGovernment.GDB.CIPProjectsOverview"))
    {
      // This will be PROJNAME. This can be used to get the field index or used directly as the field name.
      string originKeyField = relationshipClass.GetDefinition().GetOriginKeyField();

      EditOperation editOperation = new EditOperation();
      editOperation.Callback(context => 
      {
        // The rows are being added to illustrate adding relationships. If one has existing rows, those can be used to add a relationship.
        using (RowBuffer projectsRowBuffer = projectsFeatureClass.CreateRowBuffer())
        using (RowBuffer overviewRowBuffer = overviewFeatureClass.CreateRowBuffer())
        {
          projectsRowBuffer["TOTCOST"] = 500000;
          
          overviewRowBuffer[originKeyField] = "LibraryConstruction";
          overviewRowBuffer["PROJECTMAN"]   = "John Doe";
          overviewRowBuffer["FUNDSOUR"]     = "Public";

          using (Row projectsRow = projectsFeatureClass.CreateRow(projectsRowBuffer))
          using (Row overviewRow = overviewFeatureClass.CreateRow(overviewRowBuffer))
          {
            Relationship relationship = relationshipClass.CreateRelationship(overviewRow, projectsRow);

            //To Indicate that the Map has to draw this feature/row and/or the attribute table has to be updated
            context.Invalidate(projectsRow);
            context.Invalidate(overviewRow);
            context.Invalidate(relationshipClass);
          }
        }
      }, projectsFeatureClass, overviewFeatureClass);

      bool editResult = editOperation.Execute();
    }
  });
}

    now:

public async Task CreatingARelationship()
{
  await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() => {
    using (Geodatabase geodatabase = new Geodatabase(new DatabaseConnectionFile(new Uri("path\\to\\sde\\file"))))
    using (RelationshipClass relationshipClass = geodatabase.OpenDataset<RelationshipClass>("LocalGovernment.GDB.OverviewToProject"))
    using (FeatureClass projectsFeatureClass = geodatabase.OpenDataset<FeatureClass>("LocalGovernment.GDB.CIPProjects"))
    using (FeatureClass overviewFeatureClass = geodatabase.OpenDataset<FeatureClass>("LocalGovernment.GDB.CIPProjectsOverview")) {
      // This will be PROJNAME. This can be used to get the field index or used directly as the field name.
      string originKeyField = relationshipClass.GetDefinition().GetOriginKeyField();

      EditOperation editOperation = new EditOperation();
      editOperation.Callback(context => {
        // The rows are being added to illustrate adding relationships. If one has existing rows, those can be used to add a relationship.
        using (RowBuffer projectsRowBuffer = projectsFeatureClass.CreateRowBuffer())
        using (RowBuffer overviewRowBuffer = overviewFeatureClass.CreateRowBuffer()) {
          projectsRowBuffer["TOTCOST"] = 500000;

          overviewRowBuffer[originKeyField] = "LibraryConstruction";
          overviewRowBuffer["PROJECTMAN"] = "John Doe";
          overviewRowBuffer["FUNDSOUR"] = "Public";

          using (Row projectsRow = projectsFeatureClass.CreateRow(projectsRowBuffer))
          using (Row overviewRow = overviewFeatureClass.CreateRow(overviewRowBuffer)) {
            Relationship relationship = relationshipClass.CreateRelationship(overviewRow, projectsRow);

            //To Indicate that the Map has to draw this feature/row and/or the attribute table has to be updated
            context.Invalidate(projectsRow);
            context.Invalidate(overviewRow);
            context.Invalidate(relationshipClass);
          }
        }
      }, projectsFeatureClass, overviewFeatureClass);

      bool editResult = editOperation.Execute();
    }
  });
}

Deleting a Relationship

    before:

public async Task DeletingARelationship()
{
  await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
  {
    using (Geodatabase geodatabase             = new Geodatabase(new DatabaseConnectionFile(new Uri("path\\to\\sde\\file"))))
    using (RelationshipClass relationshipClass = geodatabase.OpenDataset<RelationshipClass>("LocalGovernment.GDB.luCodeViolationHasInspections"))
    using (FeatureClass violationsFeatureClass = geodatabase.OpenDataset<FeatureClass>("LocalGovernment.GDB.luCodeViolation"))
    {
      QueryFilter queryFilter = new QueryFilter { WhereClause = "LOCDESC LIKE '///%Jefferson///%'" };

      using (RowCursor rowCursor = violationsFeatureClass.Search(queryFilter, false))
      {
        if (!rowCursor.MoveNext())
          return;

        using (Row jeffersonAveViolation = rowCursor.Current)
        {
          IReadOnlyList<Row> relatedDestinationRows = relationshipClass.GetRowsRelatedToOriginRows(new List<long> { jeffersonAveViolation.GetObjectID() });

          try
          {
            EditOperation editOperation = new EditOperation();
            editOperation.Callback(context =>
            {
              foreach (Row relatedDestinationRow in relatedDestinationRows)
              {
                try
                {
                  relationshipClass.DeleteRelationship(jeffersonAveViolation, relatedDestinationRow);
                }
                catch (GeodatabaseRelationshipClassException exception)
                {
                  Console.WriteLine(exception);
                }
              }
            }, relationshipClass);

            bool editResult = editOperation.Execute();
          }
          finally
          {
            foreach (Row row in relatedDestinationRows)
              row.Dispose();
          }
        }
      }
    }
  });
}

    now:

public async Task DeletingARelationship()
{
  await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() => {
    using (Geodatabase geodatabase = new Geodatabase(new DatabaseConnectionFile(new Uri("path\\to\\sde\\file"))))
    using (RelationshipClass relationshipClass = geodatabase.OpenDataset<RelationshipClass>("LocalGovernment.GDB.luCodeViolationHasInspections"))
    using (FeatureClass violationsFeatureClass = geodatabase.OpenDataset<FeatureClass>("LocalGovernment.GDB.luCodeViolation")) {
      QueryFilter queryFilter = new QueryFilter { WhereClause = "LOCDESC LIKE '///%Jefferson///%'" };

      using (RowCursor rowCursor = violationsFeatureClass.Search(queryFilter, false)) {
        if (!rowCursor.MoveNext())
          return;

        using (Row jeffersonAveViolation = rowCursor.Current) {
          IReadOnlyList<Row> relatedDestinationRows = relationshipClass.GetRowsRelatedToOriginRows(new List<long> { jeffersonAveViolation.GetObjectID() });

          try {
            EditOperation editOperation = new EditOperation();
            editOperation.Callback(context => {
              foreach (Row relatedDestinationRow in relatedDestinationRows) {
                try {
                  relationshipClass.DeleteRelationship(jeffersonAveViolation, relatedDestinationRow);
                }
                catch (GeodatabaseRelationshipClassException exception) {
                  Console.WriteLine(exception);
                }
              }
            }, relationshipClass);

            bool editResult = editOperation.Execute();
          }
          finally {
            foreach (Row row in relatedDestinationRows)
              row.Dispose();
          }
        }
      }
    }
  });
}

Evaluating a QueryDef on a single table

    before:

public async Task SimpleQueryDef()
{
  await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
  {
    using (Geodatabase geodatabase = new Geodatabase(new DatabaseConnectionFile(new Uri("path\\to\\sde\\file"))))
    {
      QueryDef adaCompilantParksQueryDef = new QueryDef
      {
        Tables      = "Park",
        WhereClause = "ADACOMPLY = 'Yes'",
      };

      using (RowCursor rowCursor = geodatabase.Evaluate(adaCompilantParksQueryDef, false))
      {
        while (rowCursor.MoveNext())
        {
          using (Row row = rowCursor.Current)
          {
            Feature feature = row as Feature;
            Geometry shape = feature.GetShape();

            String type = Convert.ToString(row["ADACOMPLY"]); // will be "Yes" for each row.

            try
            {
              Table table = row.GetTable(); // Will always throw exception.
            }
            catch (NotSupportedException exception)
            {
              // Handle not supported exception.
            }
          }
        }
      }
    }
  });
}

    now:

public async Task SimpleQueryDef()
{
  await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() => {
    using (Geodatabase geodatabase = new Geodatabase(new DatabaseConnectionFile(new Uri("path\\to\\sde\\file")))) {
      QueryDef adaCompilantParksQueryDef = new QueryDef {
        Tables = "Park",
        WhereClause = "ADACOMPLY = 'Yes'",
      };

      using (RowCursor rowCursor = geodatabase.Evaluate(adaCompilantParksQueryDef, false)) {
        while (rowCursor.MoveNext()) {
          using (Row row = rowCursor.Current) {
            Feature feature = row as Feature;
            Geometry shape = feature.GetShape();

            String type = Convert.ToString(row["ADACOMPLY"]); // will be "Yes" for each row.

            try {
              Table table = row.GetTable(); // Will always throw exception.
            }
            catch (NotSupportedException exception) {
              // Handle not supported exception.
            }
          }
        }
      }
    }
  });
}

Evaluating a QueryDef on a Join using WHERE Clause

    before:

public async Task JoiningWithWhereQueryDef()
{
  await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
  {
    using (Geodatabase geodatabase = new Geodatabase(new DatabaseConnectionFile(new Uri("path\\to\\sde\\file"))))
    {
      QueryDef municipalEmergencyFacilitiesQueryDef = new QueryDef
      {
        SubFields   = "EmergencyFacility.OBJECTID, EmergencyFacility.Shape, EmergencyFacility.FACILITYID, FacilitySite.FACILITYID, FacilitySite.FCODE",
        Tables      = "EmergencyFacility, FacilitySite",
        WhereClause = "EmergencyFacility.FACNAME = FacilitySite.NAME AND EmergencyFacility.JURISDICT = 'Municipal'",
      };

      using (RowCursor rowCursor = geodatabase.Evaluate(municipalEmergencyFacilitiesQueryDef, false))
      {
        while (rowCursor.MoveNext())
        {
          using (Row row = rowCursor.Current)
          {
            Feature feature = row as Feature;
            Geometry shape = feature.GetShape();

            long objectID = Convert.ToInt64(row["EmergencyFacility.OBJECTID"]);
            String featureCode = Convert.ToString(row["FacilitySite.FCODE"]);

            IReadOnlyList<Field> fields = feature.GetFields(); //Contains one ArcGIS.Core.Data.Field objects for every subfield
          }
        }
      }
    }
  });
}

    now:

public async Task JoiningWithWhereQueryDef()
{
  await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() => {
    using (Geodatabase geodatabase = new Geodatabase(new DatabaseConnectionFile(new Uri("path\\to\\sde\\file")))) {
      QueryDef municipalEmergencyFacilitiesQueryDef = new QueryDef {
        SubFields = "EmergencyFacility.OBJECTID, EmergencyFacility.Shape, EmergencyFacility.FACILITYID, FacilitySite.FACILITYID, FacilitySite.FCODE",
        Tables = "EmergencyFacility, FacilitySite",
        WhereClause = "EmergencyFacility.FACNAME = FacilitySite.NAME AND EmergencyFacility.JURISDICT = 'Municipal'",
      };

      using (RowCursor rowCursor = geodatabase.Evaluate(municipalEmergencyFacilitiesQueryDef, false)) {
        while (rowCursor.MoveNext()) {
          using (Row row = rowCursor.Current) {
            Feature feature = row as Feature;
            Geometry shape = feature.GetShape();

            long objectID = Convert.ToInt64(row["EmergencyFacility.OBJECTID"]);
            String featureCode = Convert.ToString(row["FacilitySite.FCODE"]);

            IReadOnlyList<Field> fields = feature.GetFields(); //Contains one ArcGIS.Core.Data.Field objects for every subfield
          }
        }
      }
    }
  });
}

Evaluating a QueryDef on a OUTER JOIN

    before:

public async Task EvaluatingQueryDefWithOuterJoin()
{
  await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
  {
    using (Geodatabase geodatabase = new Geodatabase(new DatabaseConnectionFile(new Uri("path\\to\\sde\\file"))))
    {
      QueryDef queryDefWithLeftOuterJoin = new QueryDef
      {
        Tables    = "CommunityAddress LEFT OUTER JOIN MunicipalBoundary on CommunityAddress.Municipality = MunicipalBoundary.Name",
        SubFields = "CommunityAddress.OBJECTID, CommunityAddress.Shape, CommunityAddress.SITEADDID, CommunityAddress.ADDRNUM, CommunityAddress.FULLNAME, CommunityAddress.FULLADDR, CommunityAddress.MUNICIPALITY, MunicipalBoundary.Name, MunicipalBoundary.MUNITYP, MunicipalBoundary.LOCALFIPS",
      };

      using (RowCursor rowCursor = geodatabase.Evaluate(queryDefWithLeftOuterJoin, false))
      {
        while (rowCursor.MoveNext())
        {
          using (Row row = rowCursor.Current)
          {
            Feature feature = row as Feature;
            Geometry shape = feature.GetShape();

            int siteAddressId = Convert.ToInt32(row["CommunityAddress.SITEADDID"]);
            String stateName = Convert.ToString(row["MunicipalBoundary.name"]);
          }
        }
      }
    }
  });
}

    now:

public async Task EvaluatingQueryDefWithOuterJoin()
{
  await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() => {
    using (Geodatabase geodatabase = new Geodatabase(new DatabaseConnectionFile(new Uri("path\\to\\sde\\file")))) {
      QueryDef queryDefWithLeftOuterJoin = new QueryDef {
        Tables = "CommunityAddress LEFT OUTER JOIN MunicipalBoundary on CommunityAddress.Municipality = MunicipalBoundary.Name",
        SubFields = "CommunityAddress.OBJECTID, CommunityAddress.Shape, CommunityAddress.SITEADDID, CommunityAddress.ADDRNUM, CommunityAddress.FULLNAME, CommunityAddress.FULLADDR, CommunityAddress.MUNICIPALITY, MunicipalBoundary.Name, MunicipalBoundary.MUNITYP, MunicipalBoundary.LOCALFIPS",
      };

      using (RowCursor rowCursor = geodatabase.Evaluate(queryDefWithLeftOuterJoin, false)) {
        while (rowCursor.MoveNext()) {
          using (Row row = rowCursor.Current) {
            Feature feature = row as Feature;
            Geometry shape = feature.GetShape();

            int siteAddressId = Convert.ToInt32(row["CommunityAddress.SITEADDID"]);
            String stateName = Convert.ToString(row["MunicipalBoundary.name"]);
          }
        }
      }
    }
  });
}

Opening a FeatureClass from a ShapeFile Datastore

    before:

public async Task OpenShapefileFeatureClass()
{
  await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
  {
    using (Shapefile shapefile = new Shapefile(new ShapefileConnectionPath(new Uri("path\\to\\folder\\containing\\shapefiles"))))
    {
      FeatureClass taxLotsFeatureClass      = shapefile.OpenTable("TaxLots") as FeatureClass;
      FeatureClass manHolesFeatureClass     = shapefile.OpenTable("ManHoles.shp") as FeatureClass; // Can use the .shp extension, but its not needed.
      Table taxDetailsTableWithoutExtension = shapefile.OpenTable("TaxDetails");
      Table taxDetailsTable                 = shapefile.OpenTable("TaxDetails.dbf");
    }
  });
}

    now:

public async Task OpenShapefileFeatureClass()
{
  await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() => {
    var fileConnection = new FileSystemConnectionPath(new Uri("path\\to\\folder\\containing\\shapefiles"), FileSystemDatastoreType.Shapefile);
    using (FileSystemDatastore shapefile = new FileSystemDatastore(fileConnection)) {
      FeatureClass taxLotsFeatureClass = shapefile.OpenDataset<FeatureClass>("TaxLots");
      FeatureClass manHolesFeatureClass = shapefile.OpenDataset<FeatureClass>("ManHoles.shp"); // Can use the .shp extension, but its not needed.
      Table taxDetailsTableWithoutExtension = shapefile.OpenDataset<Table>("TaxDetails");
      Table taxDetailsTable = shapefile.OpenDataset<Table>("TaxDetails.dbf");
    }
  });
}

Create Default QueryDescription for a Database table and obtain the ArcGIS.Core.Data.Table for the QueryDescription

    before:

public async Task DefaultQueryDescription()
{
  await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
  {
    DatabaseConnectionProperties databaseConnectionProperties = new DatabaseConnectionProperties(EnterpriseDatabaseType.SQLServer)
    {
      AuthenticationMode = AuthenticationMode.DBMS,
      Instance           = "instance",
      Database           = "database",
      User               = "user",
      Password           = "password"
    };

    using (Database database = new Database(databaseConnectionProperties))
    {
      QueryDescription queryDescription = database.GetQueryDescription("CUSTOMERS");

      using (Table table = database.OpenTable(queryDescription))
      {
        //use table
      }
    }
  });
}

    now:

public async Task DefaultQueryDescription()
{
  await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() => {
    DatabaseConnectionProperties databaseConnectionProperties = new DatabaseConnectionProperties(EnterpriseDatabaseType.SQLServer) {
      AuthenticationMode = AuthenticationMode.DBMS,
      Instance = "instance",
      Database = "database",
      User = "user",
      Password = "password"
    };

    using (Database database = new Database(databaseConnectionProperties)) {
      QueryDescription queryDescription = database.GetQueryDescription("CUSTOMERS");

      using (Table table = database.OpenTable(queryDescription)) {
        //use table
      }
    }
  });
}

Create QueryDescription from a custom query for a Database table

    before:

public async Task CustomQueryDescription()
{
  await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
  {
    DatabaseConnectionProperties databaseConnectionProperties = new DatabaseConnectionProperties(EnterpriseDatabaseType.SQLServer)
    {
      AuthenticationMode = AuthenticationMode.DBMS,
      Instance           = "instance",
      Database           = "database",
      User               = "user",
      Password           = "password"
    };

    using (Database database = new Database(databaseConnectionProperties))
    {
      QueryDescription queryDescription = database.GetQueryDescription("SELECT OBJECTID, Shape, FACILITYID FROM EmergencyFacility WHERE JURISDICT = 'Municipal'", "MunicipalEmergencyFacilities");

      using (Table table = database.OpenTable(queryDescription))
      {
        // Use the table.
      }
    }
  });
}

    now:

public async Task CustomQueryDescription()
{
  await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() => {
    DatabaseConnectionProperties databaseConnectionProperties = new DatabaseConnectionProperties(EnterpriseDatabaseType.SQLServer) {
      AuthenticationMode = AuthenticationMode.DBMS,
      Instance = "instance",
      Database = "database",
      User = "user",
      Password = "password"
    };

    using (Database database = new Database(databaseConnectionProperties)) {
      QueryDescription queryDescription = database.GetQueryDescription("SELECT OBJECTID, Shape, FACILITYID FROM EmergencyFacility WHERE JURISDICT = 'Municipal'", "MunicipalEmergencyFacilities");

      using (Table table = database.OpenTable(queryDescription)) {
        // Use the table.
      }
    }
  });
}

Create QueryDescription from a join query where there is no non-nullable unique id column

    before:

public async Task JoinQueryDescription()
{
  await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
  {
    DatabaseConnectionProperties databaseConnectionProperties = new DatabaseConnectionProperties(EnterpriseDatabaseType.SQLServer)
    {
      AuthenticationMode = AuthenticationMode.DBMS,
      Instance           = "instance",
      Database           = "database",
      User               = "user",
      Password           = "password"
    };

    using (Database database = new Database(databaseConnectionProperties))
    {
      QueryDescription queryDescription = database.GetQueryDescription("SELECT BUSLINES.ID as BUSLINESID, BUSSTOPS.ID as BUSSTOPSID, BUSLINES.RTE_DESC, BUSLINES.DIR, BUSSTOPS.JURISDIC, BUSSTOPS.LOCATION, BUSSTOPS.ROUTE,BUSSTOPS.SHAPE from demosql.dbo.BUSSTOPS JOIN demosql.dbo.BUSLINES ON BUSSTOPS.ROUTE = BUSLINES.ROUTE", "BusInfo");

      queryDescription.SetObjectIDFields("BUSLINESID,BUSSTOPSID");

      using (Table table = database.OpenTable(queryDescription))
      {
        // Use the table.
      }
    }
  });
}

    now:

public async Task JoinQueryDescription()
{
  await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() => {
    DatabaseConnectionProperties databaseConnectionProperties = new DatabaseConnectionProperties(EnterpriseDatabaseType.SQLServer) {
      AuthenticationMode = AuthenticationMode.DBMS,
      Instance = "instance",
      Database = "database",
      User = "user",
      Password = "password"
    };

    using (Database database = new Database(databaseConnectionProperties)) {
      QueryDescription queryDescription = database.GetQueryDescription("SELECT BUSLINES.ID as BUSLINESID, BUSSTOPS.ID as BUSSTOPSID, BUSLINES.RTE_DESC, BUSLINES.DIR, BUSSTOPS.JURISDIC, BUSSTOPS.LOCATION, BUSSTOPS.ROUTE,BUSSTOPS.SHAPE from demosql.dbo.BUSSTOPS JOIN demosql.dbo.BUSLINES ON BUSSTOPS.ROUTE = BUSLINES.ROUTE", "BusInfo");

      queryDescription.SetObjectIDFields("BUSLINESID,BUSSTOPSID");

      using (Table table = database.OpenTable(queryDescription)) {
        // Use the table.
      }
    }
  });
}

Create QueryDescription from a query for a Database table which has more than one shape type

    before:

public async Task MultiGeometryQueryDescription()
{
  await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
  {
    DatabaseConnectionProperties databaseConnectionProperties = new DatabaseConnectionProperties(EnterpriseDatabaseType.SQLServer)
    {
      AuthenticationMode = AuthenticationMode.DBMS,
      Instance           = "instance",
      Database           = "database",
      User               = "user",
      Password           = "password"
    };

    using (Database database = new Database(databaseConnectionProperties))
    {
      QueryDescription pointQueryDescription = database.GetQueryDescription("select Description, SHAPE, UniqueID from MULTIGEOMETRYTEST", "MultiGeometryPoint");
      pointQueryDescription.SetShapeType(GeometryType.Point);
      using (Table pointTable = database.OpenTable(pointQueryDescription))
      {
        //use pointTable
      }

      QueryDescription polygonQueryDescription = database.GetQueryDescription("select Description, SHAPE, UniqueID from MULTIGEOMETRYTEST", "MultiGeometryPolygon");
      polygonQueryDescription.SetShapeType(GeometryType.Polygon);
      using (Table polygonTable = database.OpenTable(polygonQueryDescription))
      {
        //use polygonTable
      }
    }
  });
}

    now:

public async Task MultiGeometryQueryDescription()
{
  await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() => {
    DatabaseConnectionProperties databaseConnectionProperties = new DatabaseConnectionProperties(EnterpriseDatabaseType.SQLServer) {
      AuthenticationMode = AuthenticationMode.DBMS,
      Instance = "instance",
      Database = "database",
      User = "user",
      Password = "password"
    };

    using (Database database = new Database(databaseConnectionProperties)) {
      QueryDescription pointQueryDescription = database.GetQueryDescription("select Description, SHAPE, UniqueID from MULTIGEOMETRYTEST", "MultiGeometryPoint");
      pointQueryDescription.SetShapeType(GeometryType.Point);
      using (Table pointTable = database.OpenTable(pointQueryDescription)) {
        //use pointTable
      }

      QueryDescription polygonQueryDescription = database.GetQueryDescription("select Description, SHAPE, UniqueID from MULTIGEOMETRYTEST", "MultiGeometryPolygon");
      polygonQueryDescription.SetShapeType(GeometryType.Polygon);
      using (Table polygonTable = database.OpenTable(polygonQueryDescription)) {
        //use polygonTable
      }
    }
  });
}

Create QueryDescription from a query for a SQLite Database table

    before:

public async Task SqliteQueryDescription()
{
  await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
  {
    using (Database database = new Database(new SQLiteConnectionPath(new Uri("Path\\To\\Sqlite\\Database\\USA.sqlite"))))
    {
      QueryDescription washingtonCitiesQueryDescription = database.GetQueryDescription("select OBJECTID, Shape, CITY_FIPS, CITY_NAME, STATE_FIPS, STATE_CITY, TYPE, CAPITAL from main.cities where STATE_NAME='Washington'", "WashingtonCities");

      using (Table washingtonTable = database.OpenTable(washingtonCitiesQueryDescription))
      {
        // Use washingtonTable.
      }
    }
  });
}

    now:

public async Task SqliteQueryDescription()
{
  await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() => {
    using (Database database = new Database(new SQLiteConnectionPath(new Uri("Path\\To\\Sqlite\\Database\\USA.sqlite")))) {
      QueryDescription washingtonCitiesQueryDescription = database.GetQueryDescription("select OBJECTID, Shape, CITY_FIPS, CITY_NAME, STATE_FIPS, STATE_CITY, TYPE, CAPITAL from main.cities where STATE_NAME='Washington'", "WashingtonCities");

      using (Table washingtonTable = database.OpenTable(washingtonCitiesQueryDescription)) {
        // Use washingtonTable.
      }
    }
  });
}

Using SQLSyntax to form platform agnostic queries

    before:

public async Task UsingSqlSyntaxToFormPlatformAgnosticQueries()
{
  await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
  {
    using (Geodatabase geodatabase   = new Geodatabase(new FileGeodatabaseConnectionPath(new Uri("C:\\Data\\LocalGovernment.gdb"))))
    using (FeatureClass featureClass = geodatabase.OpenDataset<FeatureClass>("FacilitySite"))
    {
      SQLSyntax sqlSyntax          = geodatabase.GetSQLSyntax();
      string substringFunctionName = sqlSyntax.GetFunctionName(SQLFunction.Substring);
      string upperFunctionName     = sqlSyntax.GetFunctionName(SQLFunction.Upper);
      string substringfunction     = string.Format("{0}({1}(FCODE, 1, 6)) = 'SCHOOL'", upperFunctionName, substringFunctionName);

      QueryFilter queryFilter = new QueryFilter
      {
        WhereClause = substringfunction
      };
      using (Selection selection = featureClass.Select(queryFilter, SelectionType.ObjectID, SelectionOption.Normal))
      {
        // work with the selection.
      }
    }
  });
}

    now:

public async Task UsingSqlSyntaxToFormPlatformAgnosticQueries()
{
  await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() => {
    using (Geodatabase geodatabase = new Geodatabase(new FileGeodatabaseConnectionPath(new Uri("C:\\Data\\LocalGovernment.gdb"))))
    using (FeatureClass featureClass = geodatabase.OpenDataset<FeatureClass>("FacilitySite")) {
      SQLSyntax sqlSyntax = geodatabase.GetSQLSyntax();
      string substringFunctionName = sqlSyntax.GetFunctionName(SQLFunction.Substring);
      string upperFunctionName = sqlSyntax.GetFunctionName(SQLFunction.Upper);
      string substringfunction = string.Format("{0}({1}(FCODE, 1, 6)) = 'SCHOOL'", upperFunctionName, substringFunctionName);

      QueryFilter queryFilter = new QueryFilter {
        WhereClause = substringfunction
      };
      using (Selection selection = featureClass.Select(queryFilter, SelectionType.ObjectID, SelectionOption.Normal)) {
        // work with the selection.
      }
    }
  });
}

Joining a file geodatabase feature class to an Oracle database query layer feature class with a virtual relationship class

    before:

public async Task JoiningFileGeodatabaseFeatureClassToOracleQueryLayer()
{
  await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
  {
    using (Geodatabase geodatabase = new Geodatabase(new FileGeodatabaseConnectionPath(new Uri("C:\\Data\\LocalGovernment.gdb"))))
    using (Database database       = new Database(new DatabaseConnectionProperties(EnterpriseDatabaseType.Oracle)
    {
      AuthenticationMode = AuthenticationMode.DBMS,
      Instance           = "instance",
      User               = "user",
      Password           = "password",
      Database           = "database"
    }))

    using (FeatureClass leftFeatureClass = geodatabase.OpenDataset<FeatureClass>("Hospital"))
    using (Table rightTable              = database.OpenTable(database.GetQueryDescription("FacilitySite")))
    {
      Field originPrimaryKey      = leftFeatureClass.GetDefinition().GetFields().FirstOrDefault(field => field.Name.Equals("facilityId"));
      Field destinationForeignKey = rightTable.GetDefinition().GetFields().FirstOrDefault(field => field.Name.Equals("hospitalID"));

      VirtualRelationshipClassDescription description = new VirtualRelationshipClassDescription(originPrimaryKey, destinationForeignKey, RelationshipCardinality.OneToOne);

      using (RelationshipClass relationshipClass = leftFeatureClass.RelateTo(rightTable, description))
      {
        JoinDescription joinDescription = new JoinDescription(relationshipClass)
        {
          JoinDirection = JoinDirection.Forward,
          JoinType      = JoinType.LeftOuterJoin
        };

        Join join = new Join(joinDescription);

        using (Table joinedTable = join.GetJoinedTable())
        {
          // Perform operation on joined table.
        }
      }
    }
  });
}

    now:

public async Task JoiningFileGeodatabaseFeatureClassToOracleQueryLayer()
{
  await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() => {
    using (Geodatabase geodatabase = new Geodatabase(new FileGeodatabaseConnectionPath(new Uri("C:\\Data\\LocalGovernment.gdb"))))
    using (Database database = new Database(new DatabaseConnectionProperties(EnterpriseDatabaseType.Oracle) {
      AuthenticationMode = AuthenticationMode.DBMS,
      Instance = "instance",
      User = "user",
      Password = "password",
      Database = "database"
    }))

    using (FeatureClass leftFeatureClass = geodatabase.OpenDataset<FeatureClass>("Hospital"))
    using (Table rightTable = database.OpenTable(database.GetQueryDescription("FacilitySite"))) {
      Field originPrimaryKey = leftFeatureClass.GetDefinition().GetFields().FirstOrDefault(field => field.Name.Equals("facilityId"));
      Field destinationForeignKey = rightTable.GetDefinition().GetFields().FirstOrDefault(field => field.Name.Equals("hospitalID"));

      VirtualRelationshipClassDescription description = new VirtualRelationshipClassDescription(originPrimaryKey, destinationForeignKey, RelationshipCardinality.OneToOne);

      using (RelationshipClass relationshipClass = leftFeatureClass.RelateTo(rightTable, description)) {
        JoinDescription joinDescription = new JoinDescription(relationshipClass) {
          JoinDirection = JoinDirection.Forward,
          JoinType = JoinType.LeftOuterJoin
        };

        Join join = new Join(joinDescription);

        using (Table joinedTable = join.GetJoinedTable()) {
          // Perform operation on joined table.
        }
      }
    }
  });
}

Creating a QueryTable using a query which joins two versioned tables in a geodatabase

    before:

public async Task QueryTableJoinWithVersionedData()
{
  await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
  {
    QueryDef queryDef = new QueryDef
    {
      Tables    = "CommunityAddress JOIN MunicipalBoundary on CommunityAddress.Municipality = MunicipalBoundary.Name",
      SubFields = "CommunityAddress.OBJECTID, CommunityAddress.Shape, CommunityAddress.SITEADDID, CommunityAddress.ADDRNUM, CommunityAddress.FULLNAME, CommunityAddress.FULLADDR, CommunityAddress.MUNICIPALITY, MunicipalBoundary.Name, MunicipalBoundary.MUNITYP, MunicipalBoundary.LOCALFIPS",
    };

    using (Geodatabase testVersion1Geodatabase = new Geodatabase(new DatabaseConnectionProperties(EnterpriseDatabaseType.Oracle)
    {
      AuthenticationMode = AuthenticationMode.DBMS,
      Instance           = "instance",
      User               = "user",
      Password           = "password",
      Database           = "database",
      Version            = "user.testVersion1"
    }))
    {
      QueryTableDescription queryTableDescription = new QueryTableDescription(queryDef)
      {
        Name        = "CommunityAddrJounMunicipalBoundr",
        PrimaryKeys = testVersion1Geodatabase.GetSQLSyntax().QualifyColumnName("CommunityAddress", "OBJECTID")
      };

      // Will be based on testVersion1.
      using (Table queryTable = testVersion1Geodatabase.OpenQueryTable(queryTableDescription))
      {
        // Use queryTable.
      }
    }

    using (Geodatabase testVersion2Geodatabase = new Geodatabase(new DatabaseConnectionProperties(EnterpriseDatabaseType.Oracle)
    {
      AuthenticationMode = AuthenticationMode.DBMS,
      Instance           = "instance",
      User               = "user",
      Password           = "password",
      Database           = "database",
      Version            = "user.testVersion2"
    }))
    {
      QueryTableDescription queryTableDescription = new QueryTableDescription(queryDef)
      {
        Name = "CommunityAddrJounMunicipalBoundr",
        PrimaryKeys = testVersion2Geodatabase.GetSQLSyntax().QualifyColumnName("CommunityAddress", "OBJECTID")
      };

      // Will be based on testVersion2.
      using (Table queryTable = testVersion2Geodatabase.OpenQueryTable(queryTableDescription))
      {
        // Use queryTable.
      }
    }
  });
}

    now:

public async Task QueryTableJoinWithVersionedData()
{
  await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() => {
    QueryDef queryDef = new QueryDef {
      Tables = "CommunityAddress JOIN MunicipalBoundary on CommunityAddress.Municipality = MunicipalBoundary.Name",
      SubFields = "CommunityAddress.OBJECTID, CommunityAddress.Shape, CommunityAddress.SITEADDID, CommunityAddress.ADDRNUM, CommunityAddress.FULLNAME, CommunityAddress.FULLADDR, CommunityAddress.MUNICIPALITY, MunicipalBoundary.Name, MunicipalBoundary.MUNITYP, MunicipalBoundary.LOCALFIPS",
    };

    using (Geodatabase testVersion1Geodatabase = new Geodatabase(new DatabaseConnectionProperties(EnterpriseDatabaseType.Oracle) {
      AuthenticationMode = AuthenticationMode.DBMS,
      Instance = "instance",
      User = "user",
      Password = "password",
      Database = "database",
      Version = "user.testVersion1"
    })) {
      QueryTableDescription queryTableDescription = new QueryTableDescription(queryDef) {
        Name = "CommunityAddrJounMunicipalBoundr",
        PrimaryKeys = testVersion1Geodatabase.GetSQLSyntax().QualifyColumnName("CommunityAddress", "OBJECTID")
      };

      // Will be based on testVersion1.
      using (Table queryTable = testVersion1Geodatabase.OpenQueryTable(queryTableDescription)) {
        // Use queryTable.
      }
    }

    using (Geodatabase testVersion2Geodatabase = new Geodatabase(new DatabaseConnectionProperties(EnterpriseDatabaseType.Oracle) {
      AuthenticationMode = AuthenticationMode.DBMS,
      Instance = "instance",
      User = "user",
      Password = "password",
      Database = "database",
      Version = "user.testVersion2"
    })) {
      QueryTableDescription queryTableDescription = new QueryTableDescription(queryDef) {
        Name = "CommunityAddrJounMunicipalBoundr",
        PrimaryKeys = testVersion2Geodatabase.GetSQLSyntax().QualifyColumnName("CommunityAddress", "OBJECTID")
      };

      // Will be based on testVersion2.
      using (Table queryTable = testVersion2Geodatabase.OpenQueryTable(queryTableDescription)) {
        // Use queryTable.
      }
    }
  });
}

Geometry

Construct a SpatialReference - from a Well Known ID

    before:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  // use the builder constructor
  SpatialReferenceBuilder srBuilder = new SpatialReferenceBuilder(3857);
  SpatialReference sr3857 = srBuilder.ToSpatialReference();

  // or use the convenience method
  SpatialReference sr_3857 = SpatialReferenceBuilder.CreateSpatialReference(3857);
});

    now:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  // use the builder constructor
  SpatialReference sr3857 = null;
  using (SpatialReferenceBuilder srBuilder = new SpatialReferenceBuilder(3857))
    sr3857 = srBuilder.ToSpatialReference();

  // or use the convenience method
  SpatialReference sr_3857 = SpatialReferenceBuilder.CreateSpatialReference(3857);
});

Construct a SpatialReference - from a string

    before:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  string wkt = "GEOGCS[\"MyGCS84\",DATUM[\"D_WGS_1984\",SPHEROID[\"WGS_1984\",6378137.0,298.257223563]],PRIMEM[\"Greenwich\",0.0],UNIT[\"Radian\",1.0]]";

  // use the builder constructor
  SpatialReferenceBuilder builder = new SpatialReferenceBuilder(wkt);
  SpatialReference sr = builder.ToSpatialReference();

  // or use the convenience method
  SpatialReference anotherSR = SpatialReferenceBuilder.CreateSpatialReference(wkt);
});

    now:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  string wkt = "GEOGCS[\"MyGCS84\",DATUM[\"D_WGS_1984\",SPHEROID[\"WGS_1984\",6378137.0,298.257223563]],PRIMEM[\"Greenwich\",0.0],UNIT[\"Radian\",1.0]]";

  // use the builder constructor
  using (SpatialReferenceBuilder builder = new SpatialReferenceBuilder(wkt))
  {
    SpatialReference sr = builder.ToSpatialReference();
  }

  // or use the convenience method
  SpatialReference anotherSR = SpatialReferenceBuilder.CreateSpatialReference(wkt);
});

Construct a SpatialReference with a vertical coordinate system - from Well Known IDs

    before:

// see a list of vertical coordinate systems at http://resources.arcgis.com/en/help/arcgis-rest-api/index.html#/Vertical_coordinate_systems/02r3000000rn000000/

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  // use the builder constructor
  // 4326 = GCS_WGS_1984
  // 115700 = vertical WGS_1984
  SpatialReferenceBuilder sb = new SpatialReferenceBuilder(4326, 115700);
  SpatialReference sr = sb.ToSpatialReference();

  // or use the convenience method
  SpatialReference sr_4326 = SpatialReferenceBuilder.CreateSpatialReference(4326, 115700);
});

// test creation with wkid, vwkid

    now:

// see a list of vertical coordinate systems at http://resources.arcgis.com/en/help/arcgis-rest-api/index.html#/Vertical_coordinate_systems/02r3000000rn000000/

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  // use the builder constructor
  // 4326 = GCS_WGS_1984
  // 115700 = vertical WGS_1984
  using (SpatialReferenceBuilder sb = new SpatialReferenceBuilder(4326, 115700))
  {
    SpatialReference sr = sb.ToSpatialReference();

    // spatialReferenceBuilder properties
    int wkid = sb.Wkid;
    string wkt = sb.Wkt;
    string name = sb.Name;
    int vcsWkid = sb.VcsWkid;
    string vcsWkt = sb.VcsWkt;
  }

  // or use the convenience method
  SpatialReference sr_4326 = SpatialReferenceBuilder.CreateSpatialReference(4326, 115700);
});

Construct a SpatialReference with a verical coordinate system - from a string

    before:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  // custom VCS - use vertical shift of -1.23 instead of 0
  string custom_vWkt = @"VERTCS[""SHD_height"",VDATUM[""Singapore_Height_Datum""],PARAMETER[""Vertical_Shift"",-1.23],PARAMETER[""Direction"",-1.0],UNIT[""Meter"",1.0]]";

  SpatialReferenceBuilder sb = new SpatialReferenceBuilder(4326, custom_vWkt);
  SpatialReference sr = sb.ToSpatialReference();

  int wkid = sr.Wkid;             // wkid = 4326
  int vert_wkid = sr.VcsWkid;     // vert_wkid = 0
  string vert_wkt = sr.VcsWkt;    // vert_wkt = custom_vWkt

  // or use the convenience method
  SpatialReference sr_4326 = SpatialReferenceBuilder.CreateSpatialReference(4326, custom_vWkt);
});

    now:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  // custom VCS - use vertical shift of -1.23 instead of 0
  string custom_vWkt = @"VERTCS[""SHD_height"",VDATUM[""Singapore_Height_Datum""],PARAMETER[""Vertical_Shift"",-1.23],PARAMETER[""Direction"",-1.0],UNIT[""Meter"",1.0]]";

  using (SpatialReferenceBuilder sb = new SpatialReferenceBuilder(4326, custom_vWkt))
  {
    SpatialReference sr = sb.ToSpatialReference();

    int wkid = sr.Wkid;             // wkid = 4326
    int vert_wkid = sr.VcsWkid;     // vert_wkid = 0
    string vert_wkt = sr.VcsWkt;    // vert_wkt = custom_vWkt

    bool hasVcs = sr.HasVcs;
  }

  // or use the convenience method
  SpatialReference sr_4326 = SpatialReferenceBuilder.CreateSpatialReference(4326, custom_vWkt);
});

SpatialReference Properties

    before:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  // use the builder constructor
  SpatialReferenceBuilder srBuilder = new SpatialReferenceBuilder(3857);

  // spatialReferenceBuilder properties
  int wkid = srBuilder.Wkid;
  string wkt = srBuilder.Wkt;
  string name = srBuilder.Name;

  double xyScale = srBuilder.XYScale;
  double xyTolerance = srBuilder.XYTolerance;
  double xyResolution = srBuilder.XYResolution;
  Unit unit = srBuilder.Unit;

  double zScale = srBuilder.ZScale;
  double zTolerance = srBuilder.ZTolerance;
  Unit zUnit = srBuilder.ZUnit;

  double mScale = srBuilder.MScale;
  double mTolerance = srBuilder.MTolerance;

  double falseX = srBuilder.FalseX;
  double falseY = srBuilder.FalseY;
  double falseZ = srBuilder.FalseZ;
  double falseM = srBuilder.FalseM;

  // get the spatial reference
  SpatialReference sr3857 = srBuilder.ToSpatialReference();

  // spatial reference properties
  wkid = sr3857.Wkid;
  wkt = sr3857.Wkt;
  name = sr3857.Name;

  xyScale = sr3857.XYScale;
  xyTolerance = sr3857.XYTolerance;
  xyResolution = sr3857.XYResolution;
  unit = sr3857.Unit;

  zScale = sr3857.ZScale;
  zTolerance = sr3857.ZTolerance;
  zUnit = sr3857.ZUnit;

  mScale = sr3857.MScale;
  mTolerance = sr3857.MTolerance;

  falseX = sr3857.FalseX;
  falseY = sr3857.FalseY;
  falseZ = sr3857.FalseZ;
  falseM = sr3857.FalseM;
});

    now:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  // use the builder constructor
  using (SpatialReferenceBuilder srBuilder = new SpatialReferenceBuilder(3857))
  {
    // spatialReferenceBuilder properties
    int wkid = srBuilder.Wkid;
    string wkt = srBuilder.Wkt;
    string name = srBuilder.Name;

    double xyScale = srBuilder.XYScale;
    double xyTolerance = srBuilder.XYTolerance;
    double xyResolution = srBuilder.XYResolution;
    Unit unit = srBuilder.Unit;

    double zScale = srBuilder.ZScale;
    double zTolerance = srBuilder.ZTolerance;
    Unit zUnit = srBuilder.ZUnit;

    double mScale = srBuilder.MScale;
    double mTolerance = srBuilder.MTolerance;

    double falseX = srBuilder.FalseX;
    double falseY = srBuilder.FalseY;
    double falseZ = srBuilder.FalseZ;
    double falseM = srBuilder.FalseM;

    // get the spatial reference
    SpatialReference sr3857 = srBuilder.ToSpatialReference();

    // spatial reference properties
    wkid = sr3857.Wkid;
    wkt = sr3857.Wkt;
    name = sr3857.Name;

    xyScale = sr3857.XYScale;
    xyTolerance = sr3857.XYTolerance;
    xyResolution = sr3857.XYResolution;
    unit = sr3857.Unit;

    zScale = sr3857.ZScale;
    zTolerance = sr3857.ZTolerance;
    zUnit = sr3857.ZUnit;

    mScale = sr3857.MScale;
    mTolerance = sr3857.MTolerance;

    falseX = sr3857.FalseX;
    falseY = sr3857.FalseY;
    falseZ = sr3857.FalseZ;
    falseM = sr3857.FalseM;

    bool hasVcs = sr3857.HasVcs;
  }
});

Builder Properties

    before:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  // list of points
  List<MapPoint> points = new List<MapPoint> 
  { 
    MapPointBuilder.CreateMapPoint(0, 0, 2, 3, 1), 
    MapPointBuilder.CreateMapPoint(1, 1, 5, 6),
    MapPointBuilder.CreateMapPoint(2, 1, 6),
    MapPointBuilder.CreateMapPoint(0, 0)
  };

  // will have attributes because it is created with convenience method
  Polyline polylineWithAttrs = PolylineBuilder.CreatePolyline(points);

  bool hasZ = polylineWithAttrs.HasZ;          // hasZ = true
  bool hasM = polylineWithAttrs.HasM;          // hasM = true
  bool hasID = polylineWithAttrs.HasID;        // hasID = true

  // will not have attributes because it is passed something other than an attributed polyline
  PolylineBuilder polylineB = new PolylineBuilder(points);
  hasZ = polylineB.HasZ;                      // hasZ = false
  hasM = polylineB.HasM;                      // hasM = false
  hasID = polylineB.HasID;                    // hasID = false

  // will have attributes because it is passed an attributed polyline
  polylineB = new PolylineBuilder(polylineWithAttrs);
  hasZ = polylineB.HasZ;                      // hasZ = true
  hasM = polylineB.HasM;                      // hasM = true
  hasID = polylineB.HasID;                    // hasID = true


  // will have attributes because it is created with convenience method
  Polygon polygonWithAttrs = PolygonBuilder.CreatePolygon(points);
  hasZ = polygonWithAttrs.HasZ;               // hasZ = true
  hasM = polygonWithAttrs.HasM;               // hasM = true
  hasID = polygonWithAttrs.HasID;             // hasID = true

  // will not have attributes because it is passed something other than an attributed polygon
  PolygonBuilder polygonB = new PolygonBuilder(points);
  hasZ = polygonB.HasZ;                       // hasZ = false
  hasM = polygonB.HasM;                       // hasM = false
  hasID = polygonB.HasID;                     // hasID = false

  // will have attributes because it is passed an attributed polygon
  polygonB = new PolygonBuilder(polygonWithAttrs);
  hasZ = polygonB.HasZ;                       // hasZ = true
  hasM = polygonB.HasM;                       // hasM = true
  hasID = polygonB.HasID;                     // hasID = true
});

    now:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  // list of points
  List<MapPoint> points = new List<MapPoint> 
  { 
    MapPointBuilder.CreateMapPoint(0, 0, 2, 3, 1), 
    MapPointBuilder.CreateMapPoint(1, 1, 5, 6),
    MapPointBuilder.CreateMapPoint(2, 1, 6),
    MapPointBuilder.CreateMapPoint(0, 0)
  };

  // will have attributes because it is created with convenience method
  Polyline polylineWithAttrs = PolylineBuilder.CreatePolyline(points);

  bool hasZ = polylineWithAttrs.HasZ;          // hasZ = true
  bool hasM = polylineWithAttrs.HasM;          // hasM = true
  bool hasID = polylineWithAttrs.HasID;        // hasID = true

  // will not have attributes because it is passed something other than an attributed polyline
  using (PolylineBuilder polylineB = new PolylineBuilder(points))
  {
    hasZ = polylineB.HasZ;                      // hasZ = false
    hasM = polylineB.HasM;                      // hasM = false
    hasID = polylineB.HasID;                    // hasID = false
  }

  // will have attributes because it is passed an attributed polyline
  using (PolylineBuilder polylineB = new PolylineBuilder(polylineWithAttrs))
  {
    hasZ = polylineB.HasZ;                      // hasZ = true
    hasM = polylineB.HasM;                      // hasM = true
    hasID = polylineB.HasID;                    // hasID = true
  }

  // will have attributes because it is created with convenience method
  Polygon polygonWithAttrs = PolygonBuilder.CreatePolygon(points);
  hasZ = polygonWithAttrs.HasZ;               // hasZ = true
  hasM = polygonWithAttrs.HasM;               // hasM = true
  hasID = polygonWithAttrs.HasID;             // hasID = true

  // will not have attributes because it is passed something other than an attributed polygon
  using (PolygonBuilder polygonB = new PolygonBuilder(points))
  {
    hasZ = polygonB.HasZ;                       // hasZ = false
    hasM = polygonB.HasM;                       // hasM = false
    hasID = polygonB.HasID;                     // hasID = false
  }

  // will have attributes because it is passed an attributed polygon
  using (PolygonBuilder polygonB = new PolygonBuilder(polygonWithAttrs))
  {
    hasZ = polygonB.HasZ;                       // hasZ = true
    hasM = polygonB.HasM;                       // hasM = true
    hasID = polygonB.HasID;                     // hasID = true
  }
});

Construct a MapPoint

    before:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  // create a 3d point with M
  // use the builder constructor
  MapPointBuilder mb = new MapPointBuilder(1.0, 2.0, 3.0, 4.0);
  MapPoint ptWithM = mb.ToGeometry();

  MapPoint clone = ptWithM.Clone() as MapPoint;

  // or use the convenience methods
  MapPoint anotherPt = MapPointBuilder.CreateMapPoint(1.0, 2.0, 3.0, 4.0);

  MapPoint anotherM = MapPointBuilder.CreateMapPoint(ptWithM);
});

    now:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  // create a 3d point with M
  // use the builder constructor
  using (MapPointBuilder mb = new MapPointBuilder(1.0, 2.0, 3.0, 4.0))
  {
    MapPoint ptWithM = mb.ToGeometry();

    MapPoint clone = ptWithM.Clone() as MapPoint;

    // or use the convenience methods
    MapPoint anotherPt = MapPointBuilder.CreateMapPoint(1.0, 2.0, 3.0, 4.0);

    MapPoint anotherM = MapPointBuilder.CreateMapPoint(ptWithM);
  }
});

MapPoint Builder Properties

    before:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  MapPointBuilder mb = new MapPointBuilder(1.0, 2.0, 3.0);
  bool hasZ = mb.HasZ;          // hasZ = true
  bool hasM = mb.HasM;          // hasM = false
  bool hasID = mb.HasID;        // hasID = false

  MapPoint pt = mb.ToGeometry();
  double x = pt.X;                  // x = 1.0
  double y = pt.Y;                  // y = 2.0
  double z = pt.Z;                  // z = 3.0
  double m = pt.M;                  // m = Nan
  int ID = pt.ID;                   // ID = 0
  hasZ = pt.HasZ;                   // hasZ = true
  hasM = pt.HasM;                   // hasM = false
  hasID = pt.HasID;                 // hasID = false
  bool isEmpty = pt.IsEmpty;        // isEmpty = false

  MapPoint pt2 = MapPointBuilder.CreateMapPoint(pt);
  x = pt.X;                   // x = 1.0
  y = pt.Y;                   // y = 2.0
  z = pt.Z;                   // z = 3.0
  m = pt.M;                   // m = Nan
  hasZ = pt2.HasZ;            // hasZ = true
  hasM = pt2.HasM;            // hasM = false
  hasID = pt2.HasID;          // hasID = false
});

    now:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  using (MapPointBuilder mb = new MapPointBuilder(1.0, 2.0, 3.0))
  {
    bool hasZ = mb.HasZ;          // hasZ = true
    bool hasM = mb.HasM;          // hasM = false
    bool hasID = mb.HasID;        // hasID = false

    MapPoint pt = mb.ToGeometry();
    double x = pt.X;                  // x = 1.0
    double y = pt.Y;                  // y = 2.0
    double z = pt.Z;                  // z = 3.0
    double m = pt.M;                  // m = Nan
    int ID = pt.ID;                   // ID = 0
    hasZ = pt.HasZ;                   // hasZ = true
    hasM = pt.HasM;                   // hasM = false
    hasID = pt.HasID;                 // hasID = false
    bool isEmpty = pt.IsEmpty;        // isEmpty = false

    MapPoint pt2 = MapPointBuilder.CreateMapPoint(pt);
    x = pt.X;                   // x = 1.0
    y = pt.Y;                   // y = 2.0
    z = pt.Z;                   // z = 3.0
    m = pt.M;                   // m = Nan
    hasZ = pt2.HasZ;            // hasZ = true
    hasM = pt2.HasM;            // hasM = false
    hasID = pt2.HasID;          // hasID = false
  }
});

Construct a Polyline - from an enumeration of MapPoints

    before:

// methods need to run on MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  MapPoint startPt = MapPointBuilder.CreateMapPoint(1.0, 1.0);
  MapPoint endPt = MapPointBuilder.CreateMapPoint(2.0, 1.0);

  List<MapPoint> list = new List<MapPoint>();
  list.Add(startPt);
  list.Add(endPt);

  // use the builder constructor
  PolylineBuilder pb = new PolylineBuilder(list);
  pb.SpatialReference = SpatialReferences.WGS84;
  Polyline polyline1 = pb.ToGeometry();

  // or use the convenience method
  Polyline polyline2 = PolylineBuilder.CreatePolyline(list, SpatialReferences.WGS84);
});

    now:

// methods need to run on MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  MapPoint startPt = MapPointBuilder.CreateMapPoint(1.0, 1.0);
  MapPoint endPt = MapPointBuilder.CreateMapPoint(2.0, 1.0);

  List<MapPoint> list = new List<MapPoint>();
  list.Add(startPt);
  list.Add(endPt);

  // use the builder constructor
  using (PolylineBuilder pb = new PolylineBuilder(list))
  {
    pb.SpatialReference = SpatialReferences.WGS84;
    Polyline polyline1 = pb.ToGeometry();
  }

  // or use the convenience method
  Polyline polyline2 = PolylineBuilder.CreatePolyline(list, SpatialReferences.WGS84);
});

Get the points of a Polyline

    before:

// get the points as a readonly Collection
ReadOnlyPointCollection pts = polyline.Points;
int numPts = polyline.PointCount;

// get an enumeration of the points
IEnumerator<MapPoint> enumPts = polyline.Points.GetEnumerator();

// get the point coordinates as a readonly list
IReadOnlyList<Coordinate> coordinates = polyline.CopyCoordinatesToList();

    now:

// get the points as a readonly Collection
ReadOnlyPointCollection pts = polyline.Points;
int numPts = polyline.PointCount;

// get an enumeration of the points
IEnumerator<MapPoint> enumPts = polyline.Points.GetEnumerator();

// get the point coordinates as a readonly list
IReadOnlyList<Coordinate2D> coordinates = polyline.Copy2DCoordinatesToList();

Reverse the order of points in a Polyline

    before:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  PolylineBuilder polylineBuilder = new PolylineBuilder(polyline);
  polylineBuilder.ReverseOrientation();
  Polyline reversedPolyline = polylineBuilder.ToGeometry();
});

    now:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  using (PolylineBuilder polylineBuilder = new PolylineBuilder(polyline))
  {
    polylineBuilder.ReverseOrientation();
    Polyline reversedPolyline = polylineBuilder.ToGeometry();
  }
});

Build a multi-part Polyline

    before:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  List<MapPoint> firstPoints = new List<MapPoint>();
  firstPoints.Add(MapPointBuilder.CreateMapPoint(1.0, 1.0));
  firstPoints.Add(MapPointBuilder.CreateMapPoint(1.0, 2.0));
  firstPoints.Add(MapPointBuilder.CreateMapPoint(2.0, 2.0));
  firstPoints.Add(MapPointBuilder.CreateMapPoint(2.0, 1.0));

  List<MapPoint> nextPoints = new List<MapPoint>();
  nextPoints.Add(MapPointBuilder.CreateMapPoint(11.0, 1.0));
  nextPoints.Add(MapPointBuilder.CreateMapPoint(11.0, 2.0));
  nextPoints.Add(MapPointBuilder.CreateMapPoint(12.0, 2.0));
  nextPoints.Add(MapPointBuilder.CreateMapPoint(12.0, 1.0));

  PolylineBuilder pBuilder = new PolylineBuilder(firstPoints);
  pBuilder.AddPart(nextPoints);

  Polyline p = pBuilder.ToGeometry();
  // polyline p has 2 parts

  pBuilder.RemovePart(0);
  p = pBuilder.ToGeometry();
  // polyline p has 1 part
});

    now:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  List<MapPoint> firstPoints = new List<MapPoint>();
  firstPoints.Add(MapPointBuilder.CreateMapPoint(1.0, 1.0));
  firstPoints.Add(MapPointBuilder.CreateMapPoint(1.0, 2.0));
  firstPoints.Add(MapPointBuilder.CreateMapPoint(2.0, 2.0));
  firstPoints.Add(MapPointBuilder.CreateMapPoint(2.0, 1.0));

  List<MapPoint> nextPoints = new List<MapPoint>();
  nextPoints.Add(MapPointBuilder.CreateMapPoint(11.0, 1.0));
  nextPoints.Add(MapPointBuilder.CreateMapPoint(11.0, 2.0));
  nextPoints.Add(MapPointBuilder.CreateMapPoint(12.0, 2.0));
  nextPoints.Add(MapPointBuilder.CreateMapPoint(12.0, 1.0));

  using (PolylineBuilder pBuilder = new PolylineBuilder(firstPoints))
  {
    pBuilder.AddPart(nextPoints);

    Polyline p = pBuilder.ToGeometry();
    // polyline p has 2 parts

    pBuilder.RemovePart(0);
    p = pBuilder.ToGeometry();
    // polyline p has 1 part
  }
});

Split Polyline at distance

    before:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  // create list of points
  MapPoint startPt = MapPointBuilder.CreateMapPoint(1.0, 1.0);
  MapPoint endPt = MapPointBuilder.CreateMapPoint(2.0, 1.0);

  List<MapPoint> list = new List<MapPoint>();
  list.Add(startPt);
  list.Add(endPt);

  // use the PolylineBuilder as we wish to manipulate the geometry
  PolylineBuilder polylineBuilder = new PolylineBuilder(list);
  // split at a distance 0.75
  polylineBuilder.SplitAtDistance(0.75, false);
  // get the polyline
  Polyline p = polylineBuilder.ToGeometry();

  // polyline p should have 3 points  (1,1), (1.75, 1), (2,1)

  // add another path
  MapPoint p1 = MapPointBuilder.CreateMapPoint(4.0, 1.0);
  MapPoint p2 = MapPointBuilder.CreateMapPoint(6.0, 1.0);
  MapPoint p3 = MapPointBuilder.CreateMapPoint(7.0, 1.0);
  List<MapPoint> pts = new List<MapPoint>();
  pts.Add(p1);
  pts.Add(p2);
  pts.Add(p3);

  polylineBuilder.AddPart(pts);
  p = polylineBuilder.ToGeometry();

  // polyline p has 2 parts.  Each part has 3 points

  // split the 2nd path half way - dont create a new path
  polylineBuilder.SplitPartAtDistance(1, 0.5, true, false);

  p = polylineBuilder.ToGeometry();

  // polyline p still has 2 parts; but now has 7 points 
});

    now:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  // create list of points
  MapPoint startPt = MapPointBuilder.CreateMapPoint(1.0, 1.0);
  MapPoint endPt = MapPointBuilder.CreateMapPoint(2.0, 1.0);

  List<MapPoint> list = new List<MapPoint>();
  list.Add(startPt);
  list.Add(endPt);

  // use the PolylineBuilder as we wish to manipulate the geometry
  using (PolylineBuilder polylineBuilder = new PolylineBuilder(list))
  {
    // split at a distance 0.75
    polylineBuilder.SplitAtDistance(0.75, false);
    // get the polyline
    Polyline p = polylineBuilder.ToGeometry();
    // polyline p should have 3 points  (1,1), (1.75, 1), (2,1)

    // add another path
    MapPoint p1 = MapPointBuilder.CreateMapPoint(4.0, 1.0);
    MapPoint p2 = MapPointBuilder.CreateMapPoint(6.0, 1.0);
    MapPoint p3 = MapPointBuilder.CreateMapPoint(7.0, 1.0);
    List<MapPoint> pts = new List<MapPoint>();
    pts.Add(p1);
    pts.Add(p2);
    pts.Add(p3);

    polylineBuilder.AddPart(pts);
    p = polylineBuilder.ToGeometry();

    // polyline p has 2 parts.  Each part has 3 points

    // split the 2nd path half way - dont create a new path
    polylineBuilder.SplitPartAtDistance(1, 0.5, true, false);

    p = polylineBuilder.ToGeometry();

    // polyline p still has 2 parts; but now has 7 points 
  }
});

Construct a Polygon - from an enumeration of MapPoints

    before:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  MapPoint pt1 = MapPointBuilder.CreateMapPoint(1.0, 1.0);
  MapPoint pt2 = MapPointBuilder.CreateMapPoint(1.0, 2.0);
  MapPoint pt3 = MapPointBuilder.CreateMapPoint(2.0, 2.0);
  MapPoint pt4 = MapPointBuilder.CreateMapPoint(2.0, 1.0);

  List<MapPoint> list = new List<MapPoint>();
  list.Add(pt1);
  list.Add(pt2);
  list.Add(pt3);
  list.Add(pt4);

  // use the builder constructor
  PolygonBuilder pb = new PolygonBuilder(list);
  pb.SpatialReference = SpatialReferences.WGS84;
  Polygon polygon = pb.ToGeometry();

  // or use the convenience method
  Polygon anotherPolygon = PolygonBuilder.CreatePolygon(list, SpatialReferences.WGS84);
});

    now:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  MapPoint pt1 = MapPointBuilder.CreateMapPoint(1.0, 1.0);
  MapPoint pt2 = MapPointBuilder.CreateMapPoint(1.0, 2.0);
  MapPoint pt3 = MapPointBuilder.CreateMapPoint(2.0, 2.0);
  MapPoint pt4 = MapPointBuilder.CreateMapPoint(2.0, 1.0);

  List<MapPoint> list = new List<MapPoint>();
  list.Add(pt1);
  list.Add(pt2);
  list.Add(pt3);
  list.Add(pt4);

  // use the builder constructor
  using (PolygonBuilder pb = new PolygonBuilder(list))
  {
    pb.SpatialReference = SpatialReferences.WGS84;
    Polygon polygon = pb.ToGeometry();
  }

  // or use the convenience method
  Polygon anotherPolygon = PolygonBuilder.CreatePolygon(list, SpatialReferences.WGS84);
});

Get the points of a Polygon

    before:

// get the points as a readonly Collection
ReadOnlyPointCollection pts = poly.Points;

// get an enumeration of the points
IEnumerator<MapPoint> enumPts = poly.Points.GetEnumerator();

// get the point coordinates as a readonly list
IReadOnlyList<Coordinate> coordinates = poly.CopyCoordinatesToList();

    now:

// get the points as a readonly Collection
ReadOnlyPointCollection pts = poly.Points;

// get an enumeration of the points
IEnumerator<MapPoint> enumPts = poly.Points.GetEnumerator();

// get the point coordinates as a readonly list
IReadOnlyList<Coordinate3D> coordinates = poly.Copy3DCoordinatesToList();

Build a donut polygon

    before:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  List<Coordinate2D> outerCoordinates = new List<Coordinate2D>();
  outerCoordinates.Add(new Coordinate2D(10.0, 10.0));
  outerCoordinates.Add(new Coordinate2D(10.0, 20.0));
  outerCoordinates.Add(new Coordinate2D(20.0, 20.0));
  outerCoordinates.Add(new Coordinate2D(20.0, 10.0));

  // use the PolygonBuilder as we wish to manipulate the parts
  PolygonBuilder pb = new PolygonBuilder(outerCoordinates);
  Polygon donut = pb.ToGeometry();
  double area = donut.Area;       // area = 100

  // define the inner polygon as anti-clockwise
  List<Coordinate2D> innerCoordinates = new List<Coordinate2D>();
  innerCoordinates.Add(new Coordinate2D(13.0, 13.0));
  innerCoordinates.Add(new Coordinate2D(17.0, 13.0));
  innerCoordinates.Add(new Coordinate2D(17.0, 17.0));
  innerCoordinates.Add(new Coordinate2D(13.0, 17.0));

  pb.AddPart(innerCoordinates);
  donut = pb.ToGeometry();

  area = donut.Area;    // area = 84.0

  area = GeometryEngine.Area(donut);    // area = 84.0
});

    now:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  List<Coordinate2D> outerCoordinates = new List<Coordinate2D>();
  outerCoordinates.Add(new Coordinate2D(10.0, 10.0));
  outerCoordinates.Add(new Coordinate2D(10.0, 20.0));
  outerCoordinates.Add(new Coordinate2D(20.0, 20.0));
  outerCoordinates.Add(new Coordinate2D(20.0, 10.0));

  // use the PolygonBuilder as we wish to manipulate the parts
  using (PolygonBuilder pb = new PolygonBuilder(outerCoordinates))
  {
    Polygon donut = pb.ToGeometry();
    double area = donut.Area;       // area = 100

    // define the inner polygon as anti-clockwise
    List<Coordinate2D> innerCoordinates = new List<Coordinate2D>();
    innerCoordinates.Add(new Coordinate2D(13.0, 13.0));
    innerCoordinates.Add(new Coordinate2D(17.0, 13.0));
    innerCoordinates.Add(new Coordinate2D(17.0, 17.0));
    innerCoordinates.Add(new Coordinate2D(13.0, 17.0));

    pb.AddPart(innerCoordinates);
    donut = pb.ToGeometry();

    area = donut.Area;    // area = 84.0

    area = GeometryEngine.Instance.Area(donut);    // area = 84.0
  }
});

Construct an Envelope

    before:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  MapPoint minPt = MapPointBuilder.CreateMapPoint(1.0, 1.0);
  MapPoint maxPt = MapPointBuilder.CreateMapPoint(2.0, 2.0);

  EnvelopeBuilder ev = new EnvelopeBuilder(minPt, maxPt);
  Envelope env = ev.ToGeometry();
});

    now:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  MapPoint minPt = MapPointBuilder.CreateMapPoint(1.0, 1.0);
  MapPoint maxPt = MapPointBuilder.CreateMapPoint(2.0, 2.0);

  using (EnvelopeBuilder ev = new EnvelopeBuilder(minPt, maxPt))
  {
    Envelope env = ev.ToGeometry();
  }
});

Expand an Envelope

    before:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  Envelope envelope = EnvelopeBuilder.CreateEnvelope(100.0, 100.0, 500.0, 500.0);

  // shrink the envelope by 50%
  Envelope result = envelope.Expand(0.5, 0.5, true);
});

    now:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  Envelope envelope = EnvelopeBuilder.CreateEnvelope(100.0, 100.0, 500.0, 500.0);

  // shrink the envelope by 50%
  Envelope result = envelope.Expand(0.5, 0.5, true);

  // or use the builder
  using (EnvelopeBuilder eBuilder = new EnvelopeBuilder(100.0, 100.0, 500.0, 500.0))
  {
    // shrink by 50%
    eBuilder.Expand(0.5, 0.5, true);

    result = eBuilder.ToGeometry();
  }
});

Construct a Multipoint - from an enumeration of MapPoints

    before:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  List<MapPoint> list = new List<MapPoint>();
  list.Add(MapPointBuilder.CreateMapPoint(1.0, 1.0));
  list.Add(MapPointBuilder.CreateMapPoint(1.0, 2.0));
  list.Add(MapPointBuilder.CreateMapPoint(2.0, 2.0));
  list.Add(MapPointBuilder.CreateMapPoint(2.0, 1.0));

  // use the builder constructor
  MultipointBuilder mpb = new MultipointBuilder(list);
  Multipoint mPt = mpb.ToGeometry();

  // or use the convenience method
  Multipoint multiPoint = MultipointBuilder.CreateMultipoint(list);
});

    now:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  List<MapPoint> list = new List<MapPoint>();
  list.Add(MapPointBuilder.CreateMapPoint(1.0, 1.0));
  list.Add(MapPointBuilder.CreateMapPoint(1.0, 2.0));
  list.Add(MapPointBuilder.CreateMapPoint(2.0, 2.0));
  list.Add(MapPointBuilder.CreateMapPoint(2.0, 1.0));

  // use the builder constructor
  using (MultipointBuilder mpb = new MultipointBuilder(list))
  {
    Multipoint mPt = mpb.ToGeometry();
  }

  // or use the convenience method
  Multipoint multiPoint = MultipointBuilder.CreateMultipoint(list);
});

Modify the points of a Multipoint

    before:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  // assume a multiPoint has been built from 4 points
  // the modified multiPoint will have the first point removed and the last point moved

  MultipointBuilder mpb = new MultipointBuilder(multiPt);

  // remove the first point
  mpb.RemovePoint(0);

  // modify the coordinates of the last point
  MapPoint pt = mpb.GetMapPoint(mpb.PointCount-1);
  mpb.RemovePoint(mpb.PointCount - 1);

  MapPoint newPt = MapPointBuilder.CreateMapPoint(pt.X + 1.0, pt.Y + 2.0);
  mpb.Add(newPt);

  Multipoint modifiedMultiPoint = mpb.ToGeometry();
});

    now:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  // assume a multiPoint has been built from 4 points
  // the modified multiPoint will have the first point removed and the last point moved

  using (MultipointBuilder mpb = new MultipointBuilder(multiPt))
  {
    // remove the first point
    mpb.RemovePoint(0);

    // modify the coordinates of the last point
    MapPoint pt = mpb.GetMapPoint(mpb.PointCount - 1);
    mpb.RemovePoint(mpb.PointCount - 1);

    MapPoint newPt = MapPointBuilder.CreateMapPoint(pt.X + 1.0, pt.Y + 2.0);
    mpb.Add(newPt);

    Multipoint modifiedMultiPoint = mpb.ToGeometry();
  }
});

Construct a LineSegment using two MapPoints

    before:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  MapPoint startPt = MapPointBuilder.CreateMapPoint(1.0, 1.0);
  MapPoint endPt = MapPointBuilder.CreateMapPoint(2.0, 1.0);

  // use the builder constructor
  LineBuilder lb = new LineBuilder(startPt, endPt);
  LineSegment line = lb.ToSegment();

  // or use the convenience method
  LineSegment anotherLine = LineBuilder.CreateLineSegment(startPt, endPt);
});

    now:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  MapPoint startPt = MapPointBuilder.CreateMapPoint(1.0, 1.0);
  MapPoint endPt = MapPointBuilder.CreateMapPoint(2.0, 1.0);

  // use the builder constructor
  using (LineBuilder lb = new LineBuilder(startPt, endPt))
  {
    LineSegment line = lb.ToSegment();
  }

  // or use the convenience method
  LineSegment anotherLine = LineBuilder.CreateLineSegment(startPt, endPt);
});

Construct a Cubic Bezier - from Coordinates

    before:

// builders need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  Coordinate startPt = new Coordinate(1.0, 1.0, 3.0);
  Coordinate endPt = new Coordinate(2.0, 2.0, 3.0);

  Coordinate2D ctrl1Pt = new Coordinate2D(1.0, 2.0);
  Coordinate2D ctrl2Pt = new Coordinate2D(2.0, 1.0);

  // use the builder constructor 
  CubicBezierBuilder cbb = new CubicBezierBuilder(startPt, ctrl1Pt, ctrl2Pt, endPt, SpatialReferences.WGS84);
  CubicBezierSegment bezier = cbb.ToSegment();

  // or use the convenience method
  CubicBezierSegment anotherBezier = CubicBezierBuilder.CreateCubicBezierSegment(startPt, ctrl1Pt, ctrl2Pt, endPt, SpatialReferences.WGS84);

});

    now:

// builders need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  MapPoint startPt = MapPointBuilder.CreateMapPoint(1.0, 1.0, 3.0);
  MapPoint endPt = MapPointBuilder.CreateMapPoint(2.0, 2.0, 3.0);

  Coordinate2D ctrl1Pt = new Coordinate2D(1.0, 2.0);
  Coordinate2D ctrl2Pt = new Coordinate2D(2.0, 1.0);

  // use the builder constructor 
  using (CubicBezierBuilder cbb = new CubicBezierBuilder(startPt, ctrl1Pt, ctrl2Pt, endPt))
  {
    CubicBezierSegment bezier = cbb.ToSegment();
  }

  // or use the convenience method
  CubicBezierSegment anotherBezier = CubicBezierBuilder.CreateCubicBezierSegment(startPt, ctrl1Pt, ctrl2Pt, endPt, SpatialReferences.WGS84);

});

Construct a Cubic Bezier - from MapPoints

    before:

// builders need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  MapPoint startPt = MapPointBuilder.CreateMapPoint(1.0, 1.0, SpatialReferences.WGS84);
  MapPoint endPt = MapPointBuilder.CreateMapPoint(2.0, 2.0, SpatialReferences.WGS84);

  MapPoint ctrl1Pt = MapPointBuilder.CreateMapPoint(1.0, 2.0, SpatialReferences.WGS84);
  MapPoint ctrl2Pt = MapPointBuilder.CreateMapPoint(2.0, 1.0, SpatialReferences.WGS84);

  // use the builder constructor
  CubicBezierBuilder cbb = new CubicBezierBuilder(startPt, ctrl1Pt, ctrl2Pt, endPt);
  CubicBezierSegment bezier = cbb.ToSegment();

  // or use the convenience method
  CubicBezierSegment anotherBezier = CubicBezierBuilder.CreateCubicBezierSegment(startPt, ctrl1Pt, ctrl2Pt, endPt);
});

    now:

// builders need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  MapPoint startPt = MapPointBuilder.CreateMapPoint(1.0, 1.0, SpatialReferences.WGS84);
  MapPoint endPt = MapPointBuilder.CreateMapPoint(2.0, 2.0, SpatialReferences.WGS84);

  MapPoint ctrl1Pt = MapPointBuilder.CreateMapPoint(1.0, 2.0, SpatialReferences.WGS84);
  MapPoint ctrl2Pt = MapPointBuilder.CreateMapPoint(2.0, 1.0, SpatialReferences.WGS84);

  // use the builder constructor
  using (CubicBezierBuilder cbb = new CubicBezierBuilder(startPt, ctrl1Pt, ctrl2Pt, endPt))
  {
    CubicBezierSegment bezier = cbb.ToSegment();
  }

  // or use the convenience method
  CubicBezierSegment anotherBezier = CubicBezierBuilder.CreateCubicBezierSegment(startPt, ctrl1Pt, ctrl2Pt, endPt);
});

Construct a Cubic Bezier - from an enumeration of MapPoints

    before:

// builders need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  MapPoint startPt = MapPointBuilder.CreateMapPoint(1.0, 1.0, SpatialReferences.WGS84);
  MapPoint endPt = MapPointBuilder.CreateMapPoint(2.0, 2.0, SpatialReferences.WGS84);

  MapPoint ctrl1Pt = MapPointBuilder.CreateMapPoint(1.0, 2.0, SpatialReferences.WGS84);
  MapPoint ctrl2Pt = MapPointBuilder.CreateMapPoint(2.0, 1.0, SpatialReferences.WGS84);

  List<MapPoint> listMapPoints = new List<MapPoint>();
  listMapPoints.Add(startPt);
  listMapPoints.Add(ctrl1Pt);
  listMapPoints.Add(ctrl2Pt);
  listMapPoints.Add(endPt);

  // use the builder constructor
  CubicBezierBuilder cbb = new CubicBezierBuilder(listMapPoints);
  CubicBezierSegment bezier = cbb.ToSegment();

  // or use the convenience method
  CubicBezierSegment anotherBezier = CubicBezierBuilder.CreateCubicBezierSegment(listMapPoints);
});

    now:

// builders need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  MapPoint startPt = MapPointBuilder.CreateMapPoint(1.0, 1.0, SpatialReferences.WGS84);
  MapPoint endPt = MapPointBuilder.CreateMapPoint(2.0, 2.0, SpatialReferences.WGS84);

  MapPoint ctrl1Pt = MapPointBuilder.CreateMapPoint(1.0, 2.0, SpatialReferences.WGS84);
  MapPoint ctrl2Pt = MapPointBuilder.CreateMapPoint(2.0, 1.0, SpatialReferences.WGS84);

  List<MapPoint> listMapPoints = new List<MapPoint>();
  listMapPoints.Add(startPt);
  listMapPoints.Add(ctrl1Pt);
  listMapPoints.Add(ctrl2Pt);
  listMapPoints.Add(endPt);

  // use the builder constructor
  using (CubicBezierBuilder cbb = new CubicBezierBuilder(listMapPoints))
  {
    CubicBezierSegment bezier = cbb.ToSegment();
  }

  // or use the convenience method
  CubicBezierSegment anotherBezier = CubicBezierBuilder.CreateCubicBezierSegment(listMapPoints);
});

Cubic Bezier Builder Properties

    before:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  // retrieve the bezier curve's control points
  CubicBezierBuilder cbb = new CubicBezierBuilder(bezierSegment);
  MapPoint startPt = cbb.StartPoint;
  Coordinate2D ctrlPt1 = cbb.ControlPoint1;
  Coordinate2D ctrlPt2 = cbb.ControlPoint2;
  MapPoint endPt = cbb.EndPoint;

  // or use the QueryCoords method
  cbb.QueryCoords(out startPt, out ctrlPt1, out ctrlPt2, out endPt);
});

    now:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  // retrieve the bezier curve's control points
  using (CubicBezierBuilder cbb = new CubicBezierBuilder(bezierSegment))
  {
    MapPoint startPt = cbb.StartPoint;
    Coordinate2D ctrlPt1 = cbb.ControlPoint1;
    Coordinate2D ctrlPt2 = cbb.ControlPoint2;
    MapPoint endPt = cbb.EndPoint;

    // or use the QueryCoords method
    cbb.QueryCoords(out startPt, out ctrlPt1, out ctrlPt2, out endPt);
  }
});

Construct a Circular Arc - using an interior point

    before:

//  methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  // Construct a circular arc from (2, 1) to (1, 2) with interior pt (1 + sqrt(2)/2, 1 + sqrt(2)/2).

  Coordinate fromPt = new Coordinate(2, 1);
  Coordinate toPt = new Coordinate(1, 2);
  Coordinate2D interiorPt = new Coordinate2D(1 + Math.Sqrt(2) / 2, 1 + Math.Sqrt(2) / 2);

  // use the builder constructor
  EllipticArcBuilder cab = new EllipticArcBuilder(fromPt.ToMapPoint(), toPt.ToMapPoint(), interiorPt);
  EllipticArcSegment circularArc = cab.ToSegment();

  // or use the convenience method
  EllipticArcSegment anotherCircularArc = EllipticArcBuilder.CreateEllipticArcSegment(fromPt.ToMapPoint(), toPt.ToMapPoint(), interiorPt);
});

    now:

//  methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  // Construct a circular arc from (2, 1) to (1, 2) with interior pt (1 + sqrt(2)/2, 1 + sqrt(2)/2).

  MapPoint fromPt = MapPointBuilder.CreateMapPoint(2, 1);
  MapPoint toPt = MapPointBuilder.CreateMapPoint(1, 2);
  Coordinate2D interiorPt = new Coordinate2D(1 + Math.Sqrt(2) / 2, 1 + Math.Sqrt(2) / 2);

  // use the builder constructor
  using (EllipticArcBuilder cab = new EllipticArcBuilder(fromPt, toPt, interiorPt))
  {
    EllipticArcSegment circularArc = cab.ToSegment();
  }

  // or use the convenience method
  EllipticArcSegment anotherCircularArc = EllipticArcBuilder.CreateEllipticArcSegment(fromPt, toPt, interiorPt);
});

Construct a Circular Arc - using a chord length and bearing

    before:

//  methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  // Construct a circular arc counterclockwise from (2, 1) to (1, 2) such that the embedded 
  // circle has center point at (1, 1) and radius = 1

  MapPoint fromPt = MapPointBuilder.CreateMapPoint(2, 1, SpatialReferences.WGS84);
  double chordLength = Math.Sqrt(2);
  double chordBearing = 3 * Math.PI / 4;
  double radius = 1;
  esriArcOrientation orientation = esriArcOrientation.esriArcCounterClockwise;
  MinorOrMajor minorOrMajor = MinorOrMajor.Minor;

  // use the builder constructor
  EllipticArcBuilder cab = new EllipticArcBuilder(fromPt, chordLength, chordBearing, radius, orientation, minorOrMajor);
  EllipticArcSegment circularArc = cab.ToSegment();

  // or use the convenience method
  EllipticArcSegment anotherCircularArc = EllipticArcBuilder.CreateEllipticArcSegment(fromPt, chordLength, chordBearing, radius, orientation, minorOrMajor);
});

    now:

//  methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  // Construct a circular arc counterclockwise from (2, 1) to (1, 2) such that the embedded 
  // circle has center point at (1, 1) and radius = 1

  MapPoint fromPt = MapPointBuilder.CreateMapPoint(2, 1, SpatialReferences.WGS84);
  double chordLength = Math.Sqrt(2);
  double chordBearing = 3 * Math.PI / 4;
  double radius = 1;
  esriArcOrientation orientation = esriArcOrientation.esriArcCounterClockwise;
  MinorOrMajor minorOrMajor = MinorOrMajor.Minor;

  // use the builder constructor
  using (EllipticArcBuilder cab = new EllipticArcBuilder(fromPt, chordLength, chordBearing, radius, orientation, minorOrMajor))
  {
    EllipticArcSegment circularArc = cab.ToSegment();
  }

  // or use the convenience method
  EllipticArcSegment anotherCircularArc = EllipticArcBuilder.CreateEllipticArcSegment(fromPt, chordLength, chordBearing, radius, orientation, minorOrMajor);
});

Construct a Circular Arc - using a center point and orientation

    before:

//  methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{

  // Construct a circular arc from (2, 1) to (1, 2) 
  // with center point at (1, 1) and orientation counterclockwise.

  Coordinate fromPt = new Coordinate(2, 1);
  Coordinate toPt = new Coordinate(1, 2);
  Coordinate2D centerPtCoord = new Coordinate2D(1, 1);

  // use the builder constructor
  EllipticArcBuilder cab = new EllipticArcBuilder(fromPt.ToMapPoint(), toPt.ToMapPoint(), centerPtCoord, esriArcOrientation.esriArcCounterClockwise);
  EllipticArcSegment circularArc = cab.ToSegment();

  // or use the convenience method
  EllipticArcSegment anotherCircularArc = EllipticArcBuilder.CreateEllipticArcSegment(fromPt.ToMapPoint(), toPt.ToMapPoint(), centerPtCoord, esriArcOrientation.esriArcCounterClockwise);
});

    now:

//  methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
  {

    // Construct a circular arc from (2, 1) to (1, 2) 
    // with center point at (1, 1) and orientation counterclockwise.

    MapPoint fromPt = MapPointBuilder.CreateMapPoint(2, 1);
    MapPoint toPt = MapPointBuilder.CreateMapPoint(1, 2);
    Coordinate2D centerPtCoord = new Coordinate2D(1, 1);

    // use the builder constructor
    using (EllipticArcBuilder cab = new EllipticArcBuilder(fromPt, toPt, centerPtCoord, esriArcOrientation.esriArcCounterClockwise))
    {
      EllipticArcSegment circularArc = cab.ToSegment();
    }

    // or use the convenience method
    EllipticArcSegment anotherCircularArc = EllipticArcBuilder.CreateEllipticArcSegment(fromPt, toPt, centerPtCoord, esriArcOrientation.esriArcCounterClockwise);
  });

Construct a Circle

    before:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  // Construct a circle with center at (-1,-1), radius = 2, and oriented clockwise.

  Coordinate2D centerPtCoord = new Coordinate2D(-1, -1);

  // use the builder constructor
  EllipticArcBuilder builder = new EllipticArcBuilder(centerPtCoord, 2, esriArcOrientation.esriArcClockwise);
  EllipticArcSegment circle = builder.ToSegment();

  // or use the convenience method
  EllipticArcSegment anotherCircle = EllipticArcBuilder.CreateEllipticArcSegment(centerPtCoord, 2, esriArcOrientation.esriArcClockwise);
});

    now:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  // Construct a circle with center at (-1,-1), radius = 2, and oriented clockwise.

  Coordinate2D centerPtCoord = new Coordinate2D(-1, -1);

  // use the builder constructor
  using (EllipticArcBuilder builder = new EllipticArcBuilder(centerPtCoord, 2, esriArcOrientation.esriArcClockwise))
  {
    EllipticArcSegment circle = builder.ToSegment();
    // circle.IsCircular = true
    // circle.IsCounterClockwise = false
    // circle.IsMinor = false

    double startAngle, centralAngle, rotationAngle;
    double semiMajor, semiMinor;
    Coordinate2D actualCenterPt;
    circle.QueryCoords(out actualCenterPt, out startAngle, out centralAngle, out rotationAngle, out semiMajor, out semiMinor);

    // semiMajor = 2.0
    // semiMinor = 2.0
    // startAngle = PI/2
    // centralAngle = -2*PI
    // rotationAngle = 0
    // endAngle = PI/2
  }

  // or use the convenience method
  EllipticArcSegment anotherCircle = EllipticArcBuilder.CreateEllipticArcSegment(centerPtCoord, 2, esriArcOrientation.esriArcClockwise);
});

Construct an Ellipse

    before:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  // Construct an ellipse centered at (1, 2) with rotationAngle = -pi/6,  
  // semiMajorAxis = 5, minorMajorRatio = 0.2, oriented clockwise

  Coordinate2D centerPt = new Coordinate2D(1, 2);

  // use the builder constructor
  EllipticArcBuilder builder = new EllipticArcBuilder(centerPt, -1 * Math.PI / 6, 5, 0.2, esriArcOrientation.esriArcClockwise);
  EllipticArcSegment ellipse = builder.ToSegment();

  // or use the convenience method
  EllipticArcSegment anotherEllipse = EllipticArcBuilder.CreateEllipticArcSegment(centerPt, -1 * Math.PI / 6, 5, 0.2, esriArcOrientation.esriArcClockwise);
});

    now:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  // Construct an ellipse centered at (1, 2) with rotationAngle = -pi/6,  
  // semiMajorAxis = 5, minorMajorRatio = 0.2, oriented clockwise

  Coordinate2D centerPt = new Coordinate2D(1, 2);

  // use the builder constructor
  using (EllipticArcBuilder builder = new EllipticArcBuilder(centerPt, -1 * Math.PI / 6, 5, 0.2, esriArcOrientation.esriArcClockwise))
  {
    EllipticArcSegment ellipse = builder.ToSegment();
  }

  // or use the convenience method
  EllipticArcSegment anotherEllipse = EllipticArcBuilder.CreateEllipticArcSegment(centerPt, -1 * Math.PI / 6, 5, 0.2, esriArcOrientation.esriArcClockwise);
});

Elliptic Arc Builder Properties

    before:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  // retrieve the curve's control points
  EllipticArcBuilder builder = new EllipticArcBuilder(arcSegment);
  MapPoint startPt = builder.StartPoint;
  MapPoint endPt = builder.EndPoint;
  Coordinate2D centerPt = builder.CenterPoint;
  bool isCircular = builder.IsCircular;
  bool isMinor = builder.IsMinor;
   
});

    now:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  // retrieve the curve's control points
  using (EllipticArcBuilder builder = new EllipticArcBuilder(arcSegment))
  {
    MapPoint startPt = builder.StartPoint;
    MapPoint endPt = builder.EndPoint;
    Coordinate2D centerPt = builder.CenterPoint;
    bool isCircular = builder.IsCircular;
    bool isMinor = builder.IsMinor;
    double startAngle = builder.StartAngle;
    double endAngle = builder.EndAngle;
    double centralAngle = builder.CentralAngle;
    double rotationAngle = builder.RotationAngle;
  }
});

Get the outermost rings of a polygon

    before:

public Polygon GetOutermostRings(Polygon inputPolygon)
{
  if (inputPolygon == null || inputPolygon.IsEmpty)
    return null;

  PolygonBuilder outerRings = new PolygonBuilder();
  List<Polygon> internalRings = new List<Polygon>();

  // explode the parts of the polygon into a list of individual geometries
  // see the "Get the individual parts of a multipart feature" snippet for MultipartToSinglePart method defintion
  var parts = MultipartToSinglePart(inputPolygon);

  // get an enumeration of clockwise geometries (area > 0) ordered by the area
  var clockwiseParts = parts.Where(geom => ((Polygon)geom).Area > 0).OrderByDescending(geom => ((Polygon)geom).Area);

  // for each of the exterior rings
  foreach (var part in clockwiseParts)
  {
    // add the first (the largest) ring into the internal collection
    if (internalRings.Count == 0)
      internalRings.Add(part as Polygon);

    // use flag to indicate if current part is within the already selection polygons
    bool isWithin = false;

    foreach (var item in internalRings)
    {
      if (GeometryEngine.Within(part, item))
        isWithin = true;
    }

    // if the current polygon is not within any polygon of the internal collection
    // then it is disjoint and needs to be added to 
    if (isWithin == false)
      internalRings.Add(part as Polygon);
  }

  // now assemble a new polygon geometry based on the internal polygon collection
  foreach (var ring in internalRings)
  {
    outerRings.AddParts(ring.Parts);
  }

  // return the final geometry of the outer rings
  return outerRings.ToGeometry();
}

    now:

public Polygon GetOutermostRings(Polygon inputPolygon)
{
  if (inputPolygon == null || inputPolygon.IsEmpty)
    return null;

  List<Polygon> internalRings = new List<Polygon>();

  // explode the parts of the polygon into a list of individual geometries
  // see the "Get the individual parts of a multipart feature" snippet for MultipartToSinglePart method defintion
  var parts = MultipartToSinglePart(inputPolygon);

  // get an enumeration of clockwise geometries (area > 0) ordered by the area
  var clockwiseParts = parts.Where(geom => ((Polygon)geom).Area > 0).OrderByDescending(geom => ((Polygon)geom).Area);

  // for each of the exterior rings
  foreach (var part in clockwiseParts)
  {
    // add the first (the largest) ring into the internal collection
    if (internalRings.Count == 0)
      internalRings.Add(part as Polygon);

    // use flag to indicate if current part is within the already selection polygons
    bool isWithin = false;

    foreach (var item in internalRings)
    {
      if (GeometryEngine.Instance.Within(part, item))
        isWithin = true;
    }

    // if the current polygon is not within any polygon of the internal collection
    // then it is disjoint and needs to be added to 
    if (isWithin == false)
      internalRings.Add(part as Polygon);
  }

  using (PolygonBuilder outerRings = new PolygonBuilder())
  {
    // now assemble a new polygon geometry based on the internal polygon collection
    foreach (var ring in internalRings)
    {
      outerRings.AddParts(ring.Parts);
    }

    // return the final geometry of the outer rings
    return outerRings.ToGeometry();
}
    }

Retrieve Geometry from Geodatabase

    before:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{

  try
  {
    // open a gdb
    ArcGIS.Core.Data.Geodatabase gdb = new ArcGIS.Core.Data.Geodatabase(new FileGeodatabaseConnectionPath(new Uri(@"c:\Temp\MyDatabase.gdb")));

    //Open a featureClass 
    ArcGIS.Core.Data.FeatureClass featureClass = gdb.OpenDataset<ArcGIS.Core.Data.FeatureClass>("Polygon");

    // find a field 
    ArcGIS.Core.Data.FeatureClassDefinition featureClassDefinition = featureClass.GetDefinition();
    int fldIndex = featureClassDefinition.FindField("SomeField");
    if (fldIndex == -1)
    {
      return;
    }

    ArcGIS.Core.Data.QueryFilter filter = new ArcGIS.Core.Data.QueryFilter
    {
      WhereClause = "OBJECTID = 6"
    };

    // get the row
    ArcGIS.Core.Data.RowCursor rowCursor = featureClass.Search(filter, false);
    while (rowCursor.MoveNext())
    {
      long oid = rowCursor.Current.GetObjectID();

      // get the shape from the row
      ArcGIS.Core.Data.Feature feature = rowCursor.Current as ArcGIS.Core.Data.Feature;
      Polygon polygon = feature.GetShape() as Polygon;

      // get the attribute from the row (assume it's a double field)
      double value = (double)rowCursor.Current.GetOriginalValue(fldIndex);

      // do something here
    }
  }
  catch (Exception ex)
  {
    // error - handle appropriately
  }
});

    now:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{

  try
  {
    // open a gdb
    using (ArcGIS.Core.Data.Geodatabase gdb = new ArcGIS.Core.Data.Geodatabase(new FileGeodatabaseConnectionPath(new Uri(@"c:\Temp\MyDatabase.gdb"))))
    {
      //Open a featureClass 
      using (ArcGIS.Core.Data.FeatureClass featureClass = gdb.OpenDataset<ArcGIS.Core.Data.FeatureClass>("Polygon"))
      {
        // find a field 
        ArcGIS.Core.Data.FeatureClassDefinition featureClassDefinition = featureClass.GetDefinition();
        int fldIndex = featureClassDefinition.FindField("SomeField");
        if (fldIndex == -1)
        {
          return;
        }

        ArcGIS.Core.Data.QueryFilter filter = new ArcGIS.Core.Data.QueryFilter
        {
          WhereClause = "OBJECTID = 6"
        };

        // get the row
        using (ArcGIS.Core.Data.RowCursor rowCursor = featureClass.Search(filter, false))
        {
          while (rowCursor.MoveNext())
          {
            long oid = rowCursor.Current.GetObjectID();

            // get the shape from the row
            ArcGIS.Core.Data.Feature feature = rowCursor.Current as ArcGIS.Core.Data.Feature;
            Polygon polygon = feature.GetShape() as Polygon;

            // get the attribute from the row (assume it's a double field)
            double value = (double)rowCursor.Current.GetOriginalValue(fldIndex);

            // do something here
          }
        }
      }
    }
  }
  catch (Exception ex)
  {
    // error - handle appropriately
  }
});

Import and Export Geometries to Well Known Text

    before:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  // create a point with z, m
  MapPoint point = MapPointBuilder.CreateMapPoint(100, 200, 300, 400, SpatialReferences.WebMercator);

  // set the flags
  WKTExportFlags exportFlags = WKTExportFlags.wktExportDefaults;
  WKTImportFlags importFlags = WKTImportFlags.wktImportDefaults;

  // export and import
  string wktString = GeometryEngine.ExportToWKT(exportFlags, point);
  MapPoint importPoint = GeometryEngine.ImportFromWKT(importFlags, wktString, SpatialReferences.WebMercator) as MapPoint;

  double x = importPoint.X;       // x = 100
  double y = importPoint.Y;       // y = 200
  bool hasZ = importPoint.HasZ;   // hasZ = true
  double z = importPoint.Z;       // z = 300
  bool hasM = importPoint.HasM;   // hasM = true
  double m = importPoint.M;       // m = 400

  // export without z
  WKTExportFlags exportFlagsNoZ = WKTExportFlags.wktExportStripZs;
  wktString = GeometryEngine.ExportToWKT(exportFlags, point);
  importPoint = GeometryEngine.ImportFromWKT(importFlags, wktString, SpatialReferences.WebMercator) as MapPoint;

  x = importPoint.X;        // x = 100
  y = importPoint.Y;        // y = 200
  hasZ = importPoint.HasZ;  // hasZ = false
  z = importPoint.Z;        // z = Nan
  hasM = importPoint.HasM;  // hasM = true
  m = importPoint.M;        // m = 400

  // export without m
  WKTExportFlags exportFlagsNoM = WKTExportFlags.wktExportStripMs;
  wktString = GeometryEngine.ExportToWKT(exportFlags, point);
  importPoint = GeometryEngine.ImportFromWKT(importFlags, wktString, SpatialReferences.WebMercator) as MapPoint;

  x = importPoint.X;        // x = 100
  y = importPoint.Y;        // y = 200
  hasZ = importPoint.HasZ;  // hasZ = true
  z = importPoint.Z;        // z = 300
  hasM = importPoint.HasM;  // hasM = false
  m = importPoint.M;        // m = Nan

  // export without z, m
  wktString = GeometryEngine.ExportToWKT(exportFlagsNoZ | exportFlagsNoM, point);
  importPoint = GeometryEngine.ImportFromWKT(importFlags, wktString, SpatialReferences.WebMercator) as MapPoint;

  x = importPoint.X;        // x = 100
  y = importPoint.Y;        // y = 200
  hasZ = importPoint.HasZ;  // hasZ = false
  z = importPoint.Z;        // z = Nan
  hasM = importPoint.HasM;  // hasM = false
  m = importPoint.M;        // m = Nan

});

    now:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  // create a point with z, m
  MapPoint point = MapPointBuilder.CreateMapPoint(100, 200, 300, 400, SpatialReferences.WebMercator);

  // set the flags
  WKTExportFlags exportFlags = WKTExportFlags.wktExportDefaults;
  WKTImportFlags importFlags = WKTImportFlags.wktImportDefaults;

  // export and import
  string wktString = GeometryEngine.Instance.ExportToWKT(exportFlags, point);
  MapPoint importPoint = GeometryEngine.Instance.ImportFromWKT(importFlags, wktString, SpatialReferences.WebMercator) as MapPoint;

  double x = importPoint.X;       // x = 100
  double y = importPoint.Y;       // y = 200
  bool hasZ = importPoint.HasZ;   // hasZ = true
  double z = importPoint.Z;       // z = 300
  bool hasM = importPoint.HasM;   // hasM = true
  double m = importPoint.M;       // m = 400

  // export without z
  WKTExportFlags exportFlagsNoZ = WKTExportFlags.wktExportStripZs;
  wktString = GeometryEngine.Instance.ExportToWKT(exportFlagsNoZ, point);
  importPoint = GeometryEngine.Instance.ImportFromWKT(importFlags, wktString, SpatialReferences.WebMercator) as MapPoint;

  x = importPoint.X;        // x = 100
  y = importPoint.Y;        // y = 200
  hasZ = importPoint.HasZ;  // hasZ = false
  z = importPoint.Z;        // z = 0
  hasM = importPoint.HasM;  // hasM = true
  m = importPoint.M;        // m = 400

  // export without m
  WKTExportFlags exportFlagsNoM = WKTExportFlags.wktExportStripMs;
  wktString = GeometryEngine.Instance.ExportToWKT(exportFlagsNoM, point);
  importPoint = GeometryEngine.Instance.ImportFromWKT(importFlags, wktString, SpatialReferences.WebMercator) as MapPoint;

  x = importPoint.X;        // x = 100
  y = importPoint.Y;        // y = 200
  hasZ = importPoint.HasZ;  // hasZ = true
  z = importPoint.Z;        // z = 300
  hasM = importPoint.HasM;  // hasM = false
  m = importPoint.M;        // m = Nan

  // export without z, m
  wktString = GeometryEngine.Instance.ExportToWKT(exportFlagsNoZ | exportFlagsNoM, point);
  importPoint = GeometryEngine.Instance.ImportFromWKT(importFlags, wktString, SpatialReferences.WebMercator) as MapPoint;

  x = importPoint.X;        // x = 100
  y = importPoint.Y;        // y = 200
  hasZ = importPoint.HasZ;  // hasZ = false
  z = importPoint.Z;        // z = 0
  hasM = importPoint.HasM;  // hasM = false
  m = importPoint.M;        // m = Nan

});

Import and Export Geometries to Well Known Binary

    before:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  // create a polyline
  List<Coordinate2D> coords = new List<Coordinate2D> 
  {
    new Coordinate2D(0, 0), 
    new Coordinate2D(0, 1),
    new Coordinate2D(1, 1),
    new Coordinate2D(1, 0)
  };

  Polyline polyline = PolylineBuilder.CreatePolyline(coords, SpatialReferences.WGS84);

  WKBExportFlags exportFlags = WKBExportFlags.wkbExportDefaults;
  WKBImportFlags importFlags = WKBImportFlags.wkbImportDefaults;

  // export and import
  byte[] buffer = GeometryEngine.ExportToWKB(exportFlags, polyline);
  Geometry geometry = GeometryEngine.ImportFromWKB(importFlags, buffer, SpatialReferences.WGS84);
  Polyline importPolyline = geometry as Polyline;


  // alternatively, determine the size for the buffer
  int bufferSize = GeometryEngine.GetWKBSize(exportFlags, polyline);
  buffer = new byte[bufferSize];
  // export
  bufferSize = GeometryEngine.ExportToWKB(exportFlags, polyline, ref buffer);
  // import
  importPolyline = GeometryEngine.ImportFromWKB(importFlags, buffer, SpatialReferences.WGS84) as Polyline;

});

    now:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  // create a polyline
  List<Coordinate2D> coords = new List<Coordinate2D> 
  {
    new Coordinate2D(0, 0), 
    new Coordinate2D(0, 1),
    new Coordinate2D(1, 1),
    new Coordinate2D(1, 0)
  };

  Polyline polyline = PolylineBuilder.CreatePolyline(coords, SpatialReferences.WGS84);

  WKBExportFlags exportFlags = WKBExportFlags.wkbExportDefaults;
  WKBImportFlags importFlags = WKBImportFlags.wkbImportDefaults;

  // export and import
  byte[] buffer = GeometryEngine.Instance.ExportToWKB(exportFlags, polyline);
  Geometry geometry = GeometryEngine.Instance.ImportFromWKB(importFlags, buffer, SpatialReferences.WGS84);
  Polyline importPolyline = geometry as Polyline;


  // alternatively, determine the size for the buffer
  int bufferSize = GeometryEngine.Instance.GetWKBSize(exportFlags, polyline);
  buffer = new byte[bufferSize];
  // export
  bufferSize = GeometryEngine.Instance.ExportToWKB(exportFlags, polyline, ref buffer);
  // import
  importPolyline = GeometryEngine.Instance.ImportFromWKB(importFlags, buffer, SpatialReferences.WGS84) as Polyline;

});

Import and Export Geometries to EsriShape

    before:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  // create an envelope
  List<Coordinate> coordsZM = new List<Coordinate> 
  {
    new Coordinate(1001, 1002, 1003, 1004), 
    new Coordinate(2001, 2002, Double.NaN, 2004),
    new Coordinate(3001, -3002, 3003, 3004),
    new Coordinate(1001, -4002, 4003, 4004)
  };

  Envelope envelope = EnvelopeBuilder.CreateEnvelope(coordsZM[0], coordsZM[2], SpatialReferences.WGS84);


  // export and import
  EsriShapeExportFlags exportFlags = EsriShapeExportFlags.esriShapeExportDefaults;
  EsriShapeImportFlags importFlags = EsriShapeImportFlags.esriShapeImportDefaults;
  byte[] buffer = GeometryEngine.ExportToEsriShape(exportFlags, envelope);
  Polygon importedPolygon = GeometryEngine.ImportFromEsriShape(importFlags, buffer, envelope.SpatialReference) as Polygon;
  Envelope importedEnvelope = importedPolygon.Extent;

  // export without z,m
  buffer = GeometryEngine.ExportToEsriShape(EsriShapeExportFlags.esriShapeExportStripZs | EsriShapeExportFlags.esriShapeExportStripMs, envelope);
  importedPolygon = GeometryEngine.ImportFromEsriShape(importFlags, buffer, SpatialReferences.WGS84) as Polygon;
  importedEnvelope = importedPolygon.Extent;

  bool hasZ = importedEnvelope.HasZ;      // hasZ = false
  bool hasM = importedEnvelope.HasM;      // hasM = false

  // export with shapeSize
  int bufferSize = GeometryEngine.GetEsriShapeSize(exportFlags, envelope);
  buffer = new byte[bufferSize];

  bufferSize = GeometryEngine.ExportToEsriShape(exportFlags, envelope, ref buffer);
  importedPolygon = GeometryEngine.ImportFromEsriShape(importFlags, buffer, envelope.SpatialReference) as Polygon;
  importedEnvelope = importedPolygon.Extent;
});

    now:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  // create an envelope
  List<MapPoint> coordsZM = new List<MapPoint> 
  {
    MapPointBuilder.CreateMapPoint(1001, 1002, 1003, 1004), 
    MapPointBuilder.CreateMapPoint(2001, 2002, Double.NaN, 2004),
    MapPointBuilder.CreateMapPoint(3001, -3002, 3003, 3004),
    MapPointBuilder.CreateMapPoint(1001, -4002, 4003, 4004)
  };

  Envelope envelope = EnvelopeBuilder.CreateEnvelope(coordsZM[0], coordsZM[2], SpatialReferences.WGS84);


  // export and import
  EsriShapeExportFlags exportFlags = EsriShapeExportFlags.esriShapeExportDefaults;
  EsriShapeImportFlags importFlags = EsriShapeImportFlags.esriShapeImportDefaults;
  byte[] buffer = GeometryEngine.Instance.ExportToEsriShape(exportFlags, envelope);
  Polygon importedPolygon = GeometryEngine.Instance.ImportFromEsriShape(importFlags, buffer, envelope.SpatialReference) as Polygon;
  Envelope importedEnvelope = importedPolygon.Extent;

  // export without z,m
  buffer = GeometryEngine.Instance.ExportToEsriShape(EsriShapeExportFlags.esriShapeExportStripZs | EsriShapeExportFlags.esriShapeExportStripMs, envelope);
  importedPolygon = GeometryEngine.Instance.ImportFromEsriShape(importFlags, buffer, SpatialReferences.WGS84) as Polygon;
  importedEnvelope = importedPolygon.Extent;

  bool hasZ = importedEnvelope.HasZ;      // hasZ = false
  bool hasM = importedEnvelope.HasM;      // hasM = false

  // export with shapeSize
  int bufferSize = GeometryEngine.Instance.GetEsriShapeSize(exportFlags, envelope);
  buffer = new byte[bufferSize];

  bufferSize = GeometryEngine.Instance.ExportToEsriShape(exportFlags, envelope, ref buffer);
  importedPolygon = GeometryEngine.Instance.ImportFromEsriShape(importFlags, buffer, envelope.SpatialReference) as Polygon;
  importedEnvelope = importedPolygon.Extent;


  // or use the envelope and envelopeBuilder classes
  buffer = envelope.ToEsriShape();
  // buffer represents a polygon as there is not an envelope Esri shape buffer
  // EnvelopeBuilder.FromEsriShape takes a polygon Esri shape buffer and returns the extent of the polygon.
  importedEnvelope = EnvelopeBuilder.FromEsriShape(buffer);
});

Import and Export Geometries to JSON

    before:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  // MapPoint
  MapPoint point = MapPointBuilder.CreateMapPoint(1, 2, SpatialReferences.WGS84);
  string inputString = "{\"x\":1,\"y\":2,\"spatialReference\":{\"wkid\":4326,\"latestWkid\":4326}}";
  Geometry geometry = GeometryEngine.ImportFromJSON(JSONImportFlags.jsonImportDefaults, inputString);

  MapPoint importPoint = geometry as MapPoint;
  // importPoint = 1, 2
  // importPoint.SpatialReference.WKid = 4326

  string outputString = GeometryEngine.ExportToJSON(JSONExportFlags.jsonExportDefaults, point);
  // outputString =  "{\"x\":1,\"y\":2,\"spatialReference\":{\"wkid\":4326,\"latestWkid\":4326}}"

  inputString = "{\"spatialReference\":{\"wkid\":4326},\"z\":3,\"m\":4,\"x\":1,\"y\":2}";
  point = GeometryEngine.ImportFromJSON(JSONImportFlags.jsonImportDefaults, inputString) as MapPoint;
  // point.HasM = true
  // point.HasZ = true
  // point.M = 4
  // point.Z = 3

  // skip spatial reference
  outputString = GeometryEngine.ExportToJSON(JSONExportFlags.jsonExportSkipCRS, point);
  // outputString = "{\"x\":1,\"y\":2,\"z\":3,\"m\":4}"

  //
  // Multipoint
  //
  List<Coordinate2D> coords = new List<Coordinate2D>
  {
    new Coordinate2D(100, 200),
    new Coordinate2D(201, 300),
    new Coordinate2D(301, 400),
    new Coordinate2D(401, 500)
  };

  Multipoint multipoint = MultipointBuilder.CreateMultipoint(coords, SpatialReferences.WebMercator);

  inputString = "{\"points\":[[100,200],[201,300],[301,400],[401,500]],\"spatialReference\":{\"wkid\":3857}}";
  Multipoint importMultipoint = GeometryEngine.ImportFromJSON(JSONImportFlags.jsonImportDefaults, inputString) as Multipoint;
  // importMultipoint.IsEqual(multipoint) = true

  outputString = GeometryEngine.ExportToJSON(JSONExportFlags.jsonExportDefaults, multipoint);
  // outputString = inputString

  ReadOnlyPointCollection points = importMultipoint.Points;
  // points.Count = 4
  // points[0] = 100, 200
  // points[1] = 201, 300
  // points[2] = 301, 400
  // points[3] = 401, 500

  //
  // Polyline
  //
  Polyline polyline = PolylineBuilder.CreatePolyline(coords, SpatialReferences.WebMercator);

  outputString = GeometryEngine.ExportToJSON(JSONExportFlags.jsonExportSkipCRS, polyline);
  geometry = GeometryEngine.ImportFromJSON(JSONImportFlags.jsonImportDefaults, outputString);
  Polyline importPolyline = geometry as Polyline;
  // importPolyline.SpatialReference = null

  points = importPolyline.Points;
  // points.Count = 4
  // points[0] = 100, 200
  // points[1] = 201, 300
  // points[2] = 301, 400
  // points[3] = 401, 500

  //
  // Polygon
  //
  Polygon polygon = PolygonBuilder.CreatePolygon(coords, SpatialReferences.WebMercator);

  outputString = GeometryEngine.ExportToJSON(JSONExportFlags.jsonExportSkipCRS, polygon);
  geometry = GeometryEngine.ImportFromJSON(JSONImportFlags.jsonImportDefaults, outputString);

  Polygon importPolygon = geometry as Polygon;
  points = importPolygon.Points;
  // points.Count = 5


  // Empty polygon
  polygon = PolygonBuilder.CreatePolygon(SpatialReferences.WebMercator);
  outputString = GeometryEngine.ExportToJSON(JSONExportFlags.jsonExportDefaults, polygon);
  importPolygon = GeometryEngine.ImportFromJSON(JSONImportFlags.jsonImportDefaults, outputString) as Polygon;

  // importPolygon.IsEmpty = true
  // importPolygon.SpatialReference.Wkid = 3857
});

    now:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  // MapPoint
  string inputString = "{\"x\":1,\"y\":2,\"spatialReference\":{\"wkid\":4326,\"latestWkid\":4326}}";
  Geometry geometry = GeometryEngine.Instance.ImportFromJSON(JSONImportFlags.jsonImportDefaults, inputString);

  MapPoint importPoint = geometry as MapPoint;
  // importPoint = 1, 2
  // importPoint.SpatialReference.WKid = 4326

  // use the MapPointBuilder convenience method
  MapPoint importPoint2 = MapPointBuilder.FromJson(inputString);
  // importPoint2 = 1, 2
  // impointPoint2.SpatialReference.Wkid = 4326

  string outputString = GeometryEngine.Instance.ExportToJSON(JSONExportFlags.jsonExportDefaults, importPoint);
  // outputString =  "{\"x\":1,\"y\":2,\"spatialReference\":{\"wkid\":4326,\"latestWkid\":4326}}"

  string outputString2 = importPoint.ToJson();


  inputString = "{\"spatialReference\":{\"wkid\":4326},\"z\":3,\"m\":4,\"x\":1,\"y\":2}";
  importPoint = GeometryEngine.Instance.ImportFromJSON(JSONImportFlags.jsonImportDefaults, inputString) as MapPoint;
  // importPoint.HasM = true
  // importPoint.HasZ = true
  // importPoint.X = 1
  // importPoint.Y = 2
  // importPoint.M = 4
  // importPoint.Z = 3

  importPoint2 = MapPointBuilder.FromJson(inputString);

  // export to json - skip spatial reference
  outputString = GeometryEngine.Instance.ExportToJSON(JSONExportFlags.jsonExportSkipCRS, importPoint);
  // outputString = "{\"x\":1,\"y\":2,\"z\":3,\"m\":4}"

  // export from mappoint, skipping the sr - same as GeometryEngine.Instance.ExportToJSON w JSONExportFlags.jsonExportSkipCRS
  outputString2 = importPoint.ToJson(true);


  //
  // Multipoint
  //
  List<Coordinate2D> coords = new List<Coordinate2D>
  {
    new Coordinate2D(100, 200),
    new Coordinate2D(201, 300),
    new Coordinate2D(301, 400),
    new Coordinate2D(401, 500)
  };

  Multipoint multipoint = MultipointBuilder.CreateMultipoint(coords, SpatialReferences.WebMercator);

  inputString = "{\"points\":[[100,200],[201,300],[301,400],[401,500]],\"spatialReference\":{\"wkid\":3857}}";
  Multipoint importMultipoint = GeometryEngine.Instance.ImportFromJSON(JSONImportFlags.jsonImportDefaults, inputString) as Multipoint;
  // importMultipoint.IsEqual(multipoint) = true

  ReadOnlyPointCollection points = importMultipoint.Points;
  // points.Count = 4
  // points[0] = 100, 200
  // points[1] = 201, 300
  // points[2] = 301, 400
  // points[3] = 401, 500

  // use the Multipointbuilder convenience method
  Multipoint importMultipoint2 = MultipointBuilder.FromJson(inputString);
  // importMultipoint2.IsEqual(multipoint) = true

  // export to json
  outputString = GeometryEngine.Instance.ExportToJSON(JSONExportFlags.jsonExportDefaults, multipoint);
  // outputString = inputString

  // or use the multipoint itself
  outputString2 = multipoint.ToJson();


  //
  // Polyline
  //
  Polyline polyline = PolylineBuilder.CreatePolyline(coords, SpatialReferences.WebMercator);

  // export without the spatial reference
  outputString = GeometryEngine.Instance.ExportToJSON(JSONExportFlags.jsonExportSkipCRS, polyline);
  // import
  geometry = GeometryEngine.Instance.ImportFromJSON(JSONImportFlags.jsonImportDefaults, outputString);
  Polyline importPolyline = geometry as Polyline;
  // importPolyline.SpatialReference = null


  points = importPolyline.Points;
  // points.Count = 4
  // points[0] = 100, 200
  // points[1] = 201, 300
  // points[2] = 301, 400
  // points[3] = 401, 500

  // use the polylineBuilder convenience method 
  Polyline importPolyline2 = PolylineBuilder.FromJson(outputString);
  // importPolyline2 = importPolyline

  outputString2 = importPolyline2.ToJson();
  // outputString2 = outputString


  //
  // Polygon
  //
  Polygon polygon = PolygonBuilder.CreatePolygon(coords, SpatialReferences.WebMercator);

  // export without the spatial reference
  outputString = GeometryEngine.Instance.ExportToJSON(JSONExportFlags.jsonExportSkipCRS, polygon);
  // import
  geometry = GeometryEngine.Instance.ImportFromJSON(JSONImportFlags.jsonImportDefaults, outputString);

  Polygon importPolygon = geometry as Polygon;
  // importPolygon.SpatialReference = null
  points = importPolygon.Points;
  // points.Count = 5

  // polygonBuilder convenience method
  Polygon importPolyon2 = PolygonBuilder.FromJson(outputString);
  // importPolygon2 = importPolygon

  // export from the polygon
  outputString2 = importPolyon2.ToJson(true);


  // Empty polygon
  polygon = PolygonBuilder.CreatePolygon(SpatialReferences.WebMercator);
  outputString = GeometryEngine.Instance.ExportToJSON(JSONExportFlags.jsonExportDefaults, polygon);
  importPolygon = GeometryEngine.Instance.ImportFromJSON(JSONImportFlags.jsonImportDefaults, outputString) as Polygon;

  // importPolygon.IsEmpty = true
  // importPolygon.SpatialReference.Wkid = 3857
});

Determine area of a polygon

    before:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  var g1 = PolygonBuilder.FromJson("{\"rings\": [ [ [0, 0], [10, 0], [10, 10], [0, 10] ] ] }");
  double d = GeometryEngine.Area(g1);
  // d = -100.0         //negative due to wrong ring orientation
  d = GeometryEngine.Area(GeometryEngine.SimplifyAsFeature(g1));
  // d = 100.0        // feature has been simplifed; ring orientation is correct
});

    now:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  var g1 = PolygonBuilder.FromJson("{\"rings\": [ [ [0, 0], [10, 0], [10, 10], [0, 10] ] ] }");
  double d = GeometryEngine.Instance.Area(g1);
  // d = -100.0         //negative due to wrong ring orientation
  d = GeometryEngine.Instance.Area(GeometryEngine.Instance.SimplifyAsFeature(g1));
  // d = 100.0        // feature has been simplifed; ring orientation is correct
});

Determine the boundary of a multi-part Polygon

    before:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  // create a donut polygon.  Must use the PolygonBuilder object

  List<Coordinate2D> outerPts = new List<Coordinate2D>();
  outerPts.Add(new Coordinate2D(10.0, 10.0));
  outerPts.Add(new Coordinate2D(10.0, 20.0));
  outerPts.Add(new Coordinate2D(20.0, 20.0));
  outerPts.Add(new Coordinate2D(20.0, 10.0));

  List<Coordinate2D> innerPts = new List<Coordinate2D>();
  innerPts.Add(new Coordinate2D(13.0, 13.0));
  innerPts.Add(new Coordinate2D(17.0, 13.0));
  innerPts.Add(new Coordinate2D(17.0, 17.0));
  innerPts.Add(new Coordinate2D(13.0, 17.0));

  // add the outer points
  PolygonBuilder pb = new PolygonBuilder(outerPts);
  // add the inner points (note they are defined anticlockwise)
  pb.AddPart(innerPts);
  // get the polygon
  Polygon donut = pb.ToGeometry();

  // get the boundary 
  Geometry g = GeometryEngine.Boundary(donut);
  Polyline boundary = g as Polyline;
});

    now:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  // create a donut polygon.  Must use the PolygonBuilder object

  List<Coordinate2D> outerPts = new List<Coordinate2D>();
  outerPts.Add(new Coordinate2D(10.0, 10.0));
  outerPts.Add(new Coordinate2D(10.0, 20.0));
  outerPts.Add(new Coordinate2D(20.0, 20.0));
  outerPts.Add(new Coordinate2D(20.0, 10.0));

  List<Coordinate2D> innerPts = new List<Coordinate2D>();
  innerPts.Add(new Coordinate2D(13.0, 13.0));
  innerPts.Add(new Coordinate2D(17.0, 13.0));
  innerPts.Add(new Coordinate2D(17.0, 17.0));
  innerPts.Add(new Coordinate2D(13.0, 17.0));

  // add the outer points
  using (PolygonBuilder pb = new PolygonBuilder(outerPts))
  {
    // add the inner points (note they are defined anticlockwise)
    pb.AddPart(innerPts);
    // get the polygon
    Polygon donut = pb.ToGeometry();

    // get the boundary 
    Geometry g = GeometryEngine.Instance.Boundary(donut);
    Polyline boundary = g as Polyline;
  }
});

Buffer a MapPoint

    before:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  // buffer a point
  MapPoint pt = MapPointBuilder.CreateMapPoint(1.0, 1.0, SpatialReferences.WGS84);
  Geometry ptBuffer = GeometryEngine.Buffer(pt, 5.0);
  Polygon buffer = ptBuffer as Polygon;
});

    now:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  // buffer a point
  MapPoint pt = MapPointBuilder.CreateMapPoint(1.0, 1.0, SpatialReferences.WGS84);
  Geometry ptBuffer = GeometryEngine.Instance.Buffer(pt, 5.0);
  Polygon buffer = ptBuffer as Polygon;
});

Buffer a Circular Arc

    before:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  // create the circular arc
  Coordinate fromPt = new Coordinate(2, 1);
  Coordinate toPt = new Coordinate(1, 2);
  Coordinate2D interiorPt = new Coordinate2D(1 + Math.Sqrt(2) / 2, 1 + Math.Sqrt(2) / 2);

  EllipticArcSegment circularArc = EllipticArcBuilder.CreateEllipticArcSegment(fromPt.ToMapPoint(), toPt.ToMapPoint(), interiorPt);

  // buffer the arc
  Polyline polyline = PolylineBuilder.CreatePolyline(circularArc);
  Geometry lineBuffer = GeometryEngine.Buffer(polyline, 10);
});

    now:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  // create the circular arc
  MapPoint fromPt = MapPointBuilder.CreateMapPoint(2, 1);
  MapPoint toPt = MapPointBuilder.CreateMapPoint(1, 2);
  Coordinate2D interiorPt = new Coordinate2D(1 + Math.Sqrt(2) / 2, 1 + Math.Sqrt(2) / 2);

  EllipticArcSegment circularArc = EllipticArcBuilder.CreateEllipticArcSegment(fromPt, toPt, interiorPt);

  // buffer the arc
  Polyline polyline = PolylineBuilder.CreatePolyline(circularArc);
  Geometry lineBuffer = GeometryEngine.Instance.Buffer(polyline, 10);
});

Buffer multiple MapPoints

    before:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  // creates a buffer around each MapPoint

  List<MapPoint> pts = new List<MapPoint>();
  pts.Add(MapPointBuilder.CreateMapPoint(1.0, 1.0));
  pts.Add(MapPointBuilder.CreateMapPoint(1.0, 2.0));
  pts.Add(MapPointBuilder.CreateMapPoint(2.0, 2.0));
  pts.Add(MapPointBuilder.CreateMapPoint(2.0, 1.0));

  Geometry ptsBuffer = GeometryEngine.Buffer(pts, 0.25);
  Polygon bufferResult = ptsBuffer as Polygon;      // bufferResult will have 4 parts
});

    now:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  // creates a buffer around each MapPoint

  List<MapPoint> pts = new List<MapPoint>();
  pts.Add(MapPointBuilder.CreateMapPoint(1.0, 1.0));
  pts.Add(MapPointBuilder.CreateMapPoint(1.0, 2.0));
  pts.Add(MapPointBuilder.CreateMapPoint(2.0, 2.0));
  pts.Add(MapPointBuilder.CreateMapPoint(2.0, 1.0));

  Geometry ptsBuffer = GeometryEngine.Instance.Buffer(pts, 0.25);
  Polygon bufferResult = ptsBuffer as Polygon;      // bufferResult will have 4 parts
});

Buffer many different Geometry Types

    before:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  List<Coordinate2D> coords = new List<Coordinate2D>()
  {
    new Coordinate2D(1, 2), new Coordinate2D(3, 4), new Coordinate2D(4, 2),
    new Coordinate2D(5, 6), new Coordinate2D(7, 8), new Coordinate2D(8, 4),
    new Coordinate2D(9, 10), new Coordinate2D(11, 12), new Coordinate2D(12, 8),
    new Coordinate2D(10, 8), new Coordinate2D(12, 12), new Coordinate2D(14, 10)
  };

  List<Geometry> manyGeometries = new List<Geometry>
  {
    MapPointBuilder.CreateMapPoint(coords[9]),
    PolylineBuilder.CreatePolyline(new List<Coordinate2D>(){coords[0], coords[1], coords[2]}, SpatialReferences.WGS84),
    PolylineBuilder.CreatePolyline(new List<Coordinate2D>(){coords[3], coords[4], coords[5]}),
    PolygonBuilder.CreatePolygon(new List<Coordinate2D>(){coords[6], coords[7], coords[8]})
  };

  Geometry manyGeomBuffer = GeometryEngine.Buffer(manyGeometries, 0.25);
});

    now:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  List<Coordinate2D> coords = new List<Coordinate2D>()
  {
    new Coordinate2D(1, 2), new Coordinate2D(3, 4), new Coordinate2D(4, 2),
    new Coordinate2D(5, 6), new Coordinate2D(7, 8), new Coordinate2D(8, 4),
    new Coordinate2D(9, 10), new Coordinate2D(11, 12), new Coordinate2D(12, 8),
    new Coordinate2D(10, 8), new Coordinate2D(12, 12), new Coordinate2D(14, 10)
  };

  List<Geometry> manyGeometries = new List<Geometry>
  {
    MapPointBuilder.CreateMapPoint(coords[9]),
    PolylineBuilder.CreatePolyline(new List<Coordinate2D>(){coords[0], coords[1], coords[2]}, SpatialReferences.WGS84),
    PolylineBuilder.CreatePolyline(new List<Coordinate2D>(){coords[3], coords[4], coords[5]}),
    PolygonBuilder.CreatePolygon(new List<Coordinate2D>(){coords[6], coords[7], coords[8]})
  };

  Geometry manyGeomBuffer = GeometryEngine.Instance.Buffer(manyGeometries, 0.25);
});

Interpolate Z values on a polyline

    before:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  List<Coordinate> coords2 = new List<Coordinate>()
  {
    new Coordinate(0, 0, 0),
    new Coordinate(0, 1000),
    new Coordinate(1000, 1000, 50),
    new Coordinate(1000, 1000, 76),
    new Coordinate(0, 1000),
    new Coordinate(0, 0, 0)
  };

  SpatialReference sr = SpatialReferences.WebMercator;

  Polyline polyline = PolylineBuilder.CreatePolyline(coords2, sr);

  // polyline.HasZ = true
  // polyline.Points[1].HasZ = true
  // polyline.Points[1].Z  = NaN   
  // polyline.Points[4].HasZ = true
  // polyline.Points[4].Z  = NaN   

  Polyline polylineNoNaNZs = GeometryEngine.CalculateNonSimpleZs(polyline, 0) as Polyline;

  // polylineNoNaNZs.Points[1].HasZ = true
  // polylineNoNaNZs.Points[1].Z = 25  (halfway between 0 and 50)
  // polylineNoNaNZs.Points[4].HasZ = true
  // polylineNoNaNZs.Points[4].Z = 38  (halfway between 76 and 0)
});

    now:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  List<Coordinate3D> coords2 = new List<Coordinate3D>()
  {
    new Coordinate3D(0, 0, 0),
    new Coordinate3D(0, 1000, double.NaN),
    new Coordinate3D(1000, 1000, 50),
    new Coordinate3D(1000, 1000, 76),
    new Coordinate3D(0, 1000, double.NaN),
    new Coordinate3D(0, 0, 0)
  };

  SpatialReference sr = SpatialReferences.WebMercator;

  Polyline polyline = PolylineBuilder.CreatePolyline(coords2, sr);

  // polyline.HasZ = true
  // polyline.Points[1].HasZ = true
  // polyline.Points[1].Z  = NaN   
  // polyline.Points[4].HasZ = true
  // polyline.Points[4].Z  = NaN   

  Polyline polylineNoNaNZs = GeometryEngine.Instance.CalculateNonSimpleZs(polyline, 0) as Polyline;

  // polylineNoNaNZs.Points[1].HasZ = true
  // polylineNoNaNZs.Points[1].Z = 25  (halfway between 0 and 50)
  // polylineNoNaNZs.Points[4].HasZ = true
  // polylineNoNaNZs.Points[4].Z = 38  (halfway between 76 and 0)
});

Interpolate M values on a polygon

    before:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  List<Coordinate> coords = new List<Coordinate>()
  {
    new Coordinate(0, 0, 0, 0),
    new Coordinate(0, 1000),
    new Coordinate(1000, 1000, 10, 50)
  };

  SpatialReference sr2 = SpatialReferences.WebMercator;

  Polygon polygon = PolygonBuilder.CreatePolygon(coords, sr2);

  // polygon.HasM = true
  // polygon.Points[1].HasM = true
  // polygon.Points[1].M = NaN

  Polygon polygonNoNaNMs = GeometryEngine.CalculateNonSimpleMs(polygon, 0) as Polygon;

  // polygonNoNaNMs.Points[1].HasM = true
  // polygonNoNaNMs.Points[1].M = 25  (halfway between 0 and 50)

});

    now:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  List<MapPoint> coords = new List<MapPoint>()
  {
    MapPointBuilder.CreateMapPoint(0, 0, 0, 0),
    MapPointBuilder.CreateMapPoint(0, 1000),
    MapPointBuilder.CreateMapPoint(1000, 1000, 10, 50)
  };

  SpatialReference sr2 = SpatialReferences.WebMercator;

  Polygon polygon = PolygonBuilder.CreatePolygon(coords, sr2);

  // polygon.HasM = true
  // polygon.Points[1].HasM = true
  // polygon.Points[1].M = NaN

  Polygon polygonNoNaNMs = GeometryEngine.Instance.CalculateNonSimpleMs(polygon, 0) as Polygon;

  // polygonNoNaNMs.Points[1].HasM = true
  // polygonNoNaNMs.Points[1].M = 25  (halfway between 0 and 50)

});

Center an envelope around X,Y

    before:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  Envelope env = EnvelopeBuilder.CreateEnvelope(1.0, 1.0, 5.0, 5.0);
  Envelope centered = GeometryEngine.CenterAt(env, 2.0, 2.0);

  // centered.Center.X = 2.0
  // centered.Center.Y = 2.0
  // centered.XMin = 0
  // centered.YMin = 0
  // centered.XMax = 4
  // centered.YMax = 4

  centered = env.CenterAt(4.0, 3.0);
  // centered.Center.X == 4.0
  // centered.Center.Y == 3.0
  // centered.XMin == 2.0
  // centered.YMin == 1.0
  // centered.XMax == 6.0
  // centered.YMax == 5.0
});

    now:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  Envelope env = EnvelopeBuilder.CreateEnvelope(1.0, 1.0, 5.0, 5.0);
  Envelope centered = GeometryEngine.Instance.CenterAt(env, 2.0, 2.0);

  // centered.Center.X = 2.0
  // centered.Center.Y = 2.0
  // centered.XMin = 0
  // centered.YMin = 0
  // centered.XMax = 4
  // centered.YMax = 4

  centered = env.CenterAt(4.0, 3.0);
  // centered.Center.X == 4.0
  // centered.Center.Y == 3.0
  // centered.XMin == 2.0
  // centered.YMin == 1.0
  // centered.XMax == 6.0
  // centered.YMax == 5.0
});

Find the centroid of geometries

    before:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  // simple polygon
  List<Coordinate2D> list2D = new List<Coordinate2D>();
  list2D.Add(new Coordinate2D(0, 0));
  list2D.Add(new Coordinate2D(0, 2));
  list2D.Add(new Coordinate2D(2, 2));
  list2D.Add(new Coordinate2D(2, 0));

  Polygon polygon = PolygonBuilder.CreatePolygon(list2D, SpatialReferences.WGS84);

  // verify it is simple
  bool isSimple = GeometryEngine.IsSimpleAsFeature(polygon);
  // find the centroid
  MapPoint centroid = GeometryEngine.Centroid(polygon);
  // centroid.X = 1
  // centroid.Y = 1


  // map Point
  MapPoint pt1 = MapPointBuilder.CreateMapPoint(1, 2, 3, 4, SpatialReferences.WGS84);
  MapPoint pt2 = MapPointBuilder.CreateMapPoint(5, 2, double.NaN, 7);

  // pt1.HasZ = true
  // pt1.HasM = true
  centroid = GeometryEngine.Centroid(pt1);
  // centroid.HasZ = true
  // centroid.HasM = true
  // pt1.IsEqual(centroid) = true


  // multipoint
  List<MapPoint> list = new List<MapPoint>() { pt1, pt2 };
  Multipoint multipoint = MultipointBuilder.CreateMultipoint(list);
  // multipoint.HasZ = true
  // multipoint.HasM = true

  centroid = GeometryEngine.Centroid(multipoint);
  // centroid.X = 3
  // centroid.Y = 2
  // centroid.HasZ = false
  // centroid.HasM = false
});

    now:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  // simple polygon
  List<Coordinate2D> list2D = new List<Coordinate2D>();
  list2D.Add(new Coordinate2D(0, 0));
  list2D.Add(new Coordinate2D(0, 2));
  list2D.Add(new Coordinate2D(2, 2));
  list2D.Add(new Coordinate2D(2, 0));

  Polygon polygon = PolygonBuilder.CreatePolygon(list2D, SpatialReferences.WGS84);

  // verify it is simple
  bool isSimple = GeometryEngine.Instance.IsSimpleAsFeature(polygon);
  // find the centroid
  MapPoint centroid = GeometryEngine.Instance.Centroid(polygon);
  // centroid.X = 1
  // centroid.Y = 1


  // map Point
  MapPoint pt1 = MapPointBuilder.CreateMapPoint(1, 2, 3, 4, SpatialReferences.WGS84);
  MapPoint pt2 = MapPointBuilder.CreateMapPoint(5, 2, double.NaN, 7);

  // pt1.HasZ = true
  // pt1.HasM = true
  centroid = GeometryEngine.Instance.Centroid(pt1);
  // centroid.HasZ = true
  // centroid.HasM = true
  // pt1.IsEqual(centroid) = true


  // multipoint
  List<MapPoint> list = new List<MapPoint>() { pt1, pt2 };
  Multipoint multipoint = MultipointBuilder.CreateMultipoint(list);
  // multipoint.HasZ = true
  // multipoint.HasM = true

  centroid = GeometryEngine.Instance.Centroid(multipoint);
  // centroid.X = 3
  // centroid.Y = 2
  // centroid.HasZ = false
  // centroid.HasM = false
});

Clip a Polyline

    before:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  // clip a polyline by an envelope

  Envelope env = EnvelopeBuilder.CreateEnvelope(2.0, 2.0, 4.0, 4.0);
  LineSegment line = LineBuilder.CreateLineSegment(new Coordinate(0, 3), new Coordinate(5.0, 3.0));
  Polyline polyline = PolylineBuilder.CreatePolyline(line);

  Geometry clipGeom = GeometryEngine.Clip(polyline, env);
});

    now:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  // clip a polyline by an envelope

  Envelope env = EnvelopeBuilder.CreateEnvelope(2.0, 2.0, 4.0, 4.0);
  LineSegment line = LineBuilder.CreateLineSegment(new Coordinate2D(0, 3), new Coordinate2D(5.0, 3.0));
  Polyline polyline = PolylineBuilder.CreatePolyline(line);

  Geometry clipGeom = GeometryEngine.Instance.Clip(polyline, env);
});

Clip a Polyline by a Polygon

    before:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  // clip a polyline by a polygon

  List<Coordinate2D> list = new List<Coordinate2D>();
  list.Add(new Coordinate2D(1.0, 1.0));
  list.Add(new Coordinate2D(1.0, 4.0));
  list.Add(new Coordinate2D(4.0, 4.0));
  list.Add(new Coordinate2D(4.0, 1.0));

  Polygon polygon = PolygonBuilder.CreatePolygon(list, SpatialReferences.WGS84);

  LineSegment crossingLine = LineBuilder.CreateLineSegment(MapPointBuilder.CreateMapPoint(0, 3), MapPointBuilder.CreateMapPoint(5.0, 3.0));
  Polyline p = PolylineBuilder.CreatePolyline(crossingLine);
  Geometry geometry = GeometryEngine.Clip(p, polygon.Extent);
});

    now:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  // clip a polyline by a polygon

  List<Coordinate2D> list = new List<Coordinate2D>();
  list.Add(new Coordinate2D(1.0, 1.0));
  list.Add(new Coordinate2D(1.0, 4.0));
  list.Add(new Coordinate2D(4.0, 4.0));
  list.Add(new Coordinate2D(4.0, 1.0));

  Polygon polygon = PolygonBuilder.CreatePolygon(list, SpatialReferences.WGS84);

  LineSegment crossingLine = LineBuilder.CreateLineSegment(MapPointBuilder.CreateMapPoint(0, 3), MapPointBuilder.CreateMapPoint(5.0, 3.0));
  Polyline p = PolylineBuilder.CreatePolyline(crossingLine);
  Geometry geometry = GeometryEngine.Instance.Clip(p, polygon.Extent);
});

Polygon contains MapPoints, Polylines, Polygons

    before:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{

  // build a polygon      
  List<MapPoint> pts = new List<MapPoint>();
  pts.Add(MapPointBuilder.CreateMapPoint(1.0, 1.0));
  pts.Add(MapPointBuilder.CreateMapPoint(1.0, 2.0));
  pts.Add(MapPointBuilder.CreateMapPoint(2.0, 2.0));
  pts.Add(MapPointBuilder.CreateMapPoint(2.0, 1.0));

  Polygon poly = PolygonBuilder.CreatePolygon(pts);

  // test if an inner point is contained
  MapPoint innerPt = MapPointBuilder.CreateMapPoint(1.5, 1.5);
  bool contains = GeometryEngine.Contains(poly, innerPt);   // contains = true

  // test a point on a boundary
  contains = GeometryEngine.Contains(poly, poly.Points[0]);     // contains = false

  // test an interior line
  MapPoint innerPt2 = MapPointBuilder.CreateMapPoint(1.25, 1.75);
  List<MapPoint> innerLinePts = new List<MapPoint>();
  innerLinePts.Add(innerPt);
  innerLinePts.Add(innerPt2);

  // test an inner polyline
  Polyline polyline = PolylineBuilder.CreatePolyline(innerLinePts);
  contains = GeometryEngine.Contains(poly, polyline);   // contains = true

  // test a line that crosses the boundary
  MapPoint outerPt = MapPointBuilder.CreateMapPoint(3, 1.5);
  List<MapPoint> crossingLinePts = new List<MapPoint>();
  crossingLinePts.Add(innerPt);
  crossingLinePts.Add(outerPt);

  polyline = PolylineBuilder.CreatePolyline(crossingLinePts);
  contains = GeometryEngine.Contains(poly, polyline);     // contains = false

  // test a polygon in polygon
  Envelope env = EnvelopeBuilder.CreateEnvelope(innerPt, innerPt2);
  contains = GeometryEngine.Contains(poly, env);      // contains = true
});

    now:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{

  // build a polygon      
  List<MapPoint> pts = new List<MapPoint>();
  pts.Add(MapPointBuilder.CreateMapPoint(1.0, 1.0));
  pts.Add(MapPointBuilder.CreateMapPoint(1.0, 2.0));
  pts.Add(MapPointBuilder.CreateMapPoint(2.0, 2.0));
  pts.Add(MapPointBuilder.CreateMapPoint(2.0, 1.0));

  Polygon poly = PolygonBuilder.CreatePolygon(pts);

  // test if an inner point is contained
  MapPoint innerPt = MapPointBuilder.CreateMapPoint(1.5, 1.5);
  bool contains = GeometryEngine.Instance.Contains(poly, innerPt);   // contains = true

  // test a point on a boundary
  contains = GeometryEngine.Instance.Contains(poly, poly.Points[0]);     // contains = false

  // test an interior line
  MapPoint innerPt2 = MapPointBuilder.CreateMapPoint(1.25, 1.75);
  List<MapPoint> innerLinePts = new List<MapPoint>();
  innerLinePts.Add(innerPt);
  innerLinePts.Add(innerPt2);

  // test an inner polyline
  Polyline polyline = PolylineBuilder.CreatePolyline(innerLinePts);
  contains = GeometryEngine.Instance.Contains(poly, polyline);   // contains = true

  // test a line that crosses the boundary
  MapPoint outerPt = MapPointBuilder.CreateMapPoint(3, 1.5);
  List<MapPoint> crossingLinePts = new List<MapPoint>();
  crossingLinePts.Add(innerPt);
  crossingLinePts.Add(outerPt);

  polyline = PolylineBuilder.CreatePolyline(crossingLinePts);
  contains = GeometryEngine.Instance.Contains(poly, polyline);     // contains = false

  // test a polygon in polygon
  Envelope env = EnvelopeBuilder.CreateEnvelope(innerPt, innerPt2);
  contains = GeometryEngine.Instance.Contains(poly, env);      // contains = true
});

Determine convex hull

    before:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  //
  // convex hull around a point - returns a point
  //

  MapPoint pt = MapPointBuilder.CreateMapPoint(2.0, 2.0);
  Geometry hull = GeometryEngine.ConvexHull(pt);
  MapPoint hullPt = hull as MapPoint;
  // nullPt.X = 2
  // hullPt.Y = 2


  List<MapPoint> list = new List<MapPoint>();
  list.Add(MapPointBuilder.CreateMapPoint(1.0, 1.0));
  list.Add(MapPointBuilder.CreateMapPoint(1.0, 2.0));
  list.Add(MapPointBuilder.CreateMapPoint(2.0, 2.0));
  list.Add(MapPointBuilder.CreateMapPoint(2.0, 1.0));

  //
  // convex hull around a multipoint - returns a polygon
  //

  // build a multiPoint
  Multipoint multiPoint = MultipointBuilder.CreateMultipoint(list);

  hull = GeometryEngine.ConvexHull(multiPoint);
  Polygon hullPoly = hull as Polygon;
  // hullPoly.Area = 1
  // hullPoly.PointCount = 5


  // 
  // convex hull around a line - returns a polyline or polygon
  // 

  List<MapPoint> polylineList = new List<MapPoint>();
  polylineList.Add(MapPointBuilder.CreateMapPoint(1.0, 1.0));
  polylineList.Add(MapPointBuilder.CreateMapPoint(2.0, 2.0));

  // 2 point straight line
  Polyline polyline = PolylineBuilder.CreatePolyline(polylineList);
  hull = GeometryEngine.ConvexHull(polyline);
  Polyline hullPolyline = hull as Polyline;
  // hullPolyline.Length = Math.Sqrt(2)
  // hullPolyline.PointCount = 2

  // 3 point angular line
  polylineList.Add(MapPointBuilder.CreateMapPoint(2.0, 1.0));
  polyline = PolylineBuilder.CreatePolyline(polylineList);
  hull = GeometryEngine.ConvexHull(polyline);
  hullPoly = hull as Polygon;
  // hullPoly.Length = 2 + Math.Sqrt(2)
  // hullPoly.Area = 0.5
  // hullPoly.PointCount = 4


  //
  // convex hull around a polygon - returns a polygon
  //

  // simple polygon
  Polygon poly = PolygonBuilder.CreatePolygon(list);
  hull = GeometryEngine.ConvexHull(poly);
  hullPoly = hull as Polygon;
  
  // hullPoly.Length = 4.0
  // hullPoly.Area = 1.0
  // hullPoly.PointCount = 5


  // polygon with concave angles
  List<MapPoint> funkyList = new List<MapPoint>();
  funkyList.Add(MapPointBuilder.CreateMapPoint(1.0, 1.0));
  funkyList.Add(MapPointBuilder.CreateMapPoint(1.5, 1.5));
  funkyList.Add(MapPointBuilder.CreateMapPoint(1.0, 2.0));
  funkyList.Add(MapPointBuilder.CreateMapPoint(2.0, 2.0));
  funkyList.Add(MapPointBuilder.CreateMapPoint(1.5, 1.5));
  funkyList.Add(MapPointBuilder.CreateMapPoint(2.0, 1.0));
  funkyList.Add(MapPointBuilder.CreateMapPoint(1.0, 1.0));

  Polygon funkyPoly = PolygonBuilder.CreatePolygon(funkyList);
  hull = GeometryEngine.ConvexHull(funkyPoly);
  hullPoly = hull as Polygon;
  // hullPoly.Length = 4.0
  // hullPoly.Area = 1.0
  // hullPoly.PointCount = 5
  // hullPoly.Points[0] = 1.0, 1.0
  // hullPoly.Points[1] = 1.0, 2.0
  // hullPoly.Points[2] = 2.0, 2.0
  // hullPoly.Points[3] = 2.0, 1.0
  // hullPoly.Points[4] = 1.0, 1.0
});

    now:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  //
  // convex hull around a point - returns a point
  //

  MapPoint pt = MapPointBuilder.CreateMapPoint(2.0, 2.0);
  Geometry hull = GeometryEngine.Instance.ConvexHull(pt);
  MapPoint hullPt = hull as MapPoint;
  // nullPt.X = 2
  // hullPt.Y = 2


  List<MapPoint> list = new List<MapPoint>();
  list.Add(MapPointBuilder.CreateMapPoint(1.0, 1.0));
  list.Add(MapPointBuilder.CreateMapPoint(1.0, 2.0));
  list.Add(MapPointBuilder.CreateMapPoint(2.0, 2.0));
  list.Add(MapPointBuilder.CreateMapPoint(2.0, 1.0));

  //
  // convex hull around a multipoint - returns a polygon
  //

  // build a multiPoint
  Multipoint multiPoint = MultipointBuilder.CreateMultipoint(list);

  hull = GeometryEngine.Instance.ConvexHull(multiPoint);
  Polygon hullPoly = hull as Polygon;
  // hullPoly.Area = 1
  // hullPoly.PointCount = 5


  // 
  // convex hull around a line - returns a polyline or polygon
  // 

  List<MapPoint> polylineList = new List<MapPoint>();
  polylineList.Add(MapPointBuilder.CreateMapPoint(1.0, 1.0));
  polylineList.Add(MapPointBuilder.CreateMapPoint(2.0, 2.0));

  // 2 point straight line
  Polyline polyline = PolylineBuilder.CreatePolyline(polylineList);
  hull = GeometryEngine.Instance.ConvexHull(polyline);
  Polyline hullPolyline = hull as Polyline;
  // hullPolyline.Length = Math.Sqrt(2)
  // hullPolyline.PointCount = 2

  // 3 point angular line
  polylineList.Add(MapPointBuilder.CreateMapPoint(2.0, 1.0));
  polyline = PolylineBuilder.CreatePolyline(polylineList);
  hull = GeometryEngine.Instance.ConvexHull(polyline);
  hullPoly = hull as Polygon;
  // hullPoly.Length = 2 + Math.Sqrt(2)
  // hullPoly.Area = 0.5
  // hullPoly.PointCount = 4


  //
  // convex hull around a polygon - returns a polygon
  //

  // simple polygon
  Polygon poly = PolygonBuilder.CreatePolygon(list);
  hull = GeometryEngine.Instance.ConvexHull(poly);
  hullPoly = hull as Polygon;
  
  // hullPoly.Length = 4.0
  // hullPoly.Area = 1.0
  // hullPoly.PointCount = 5


  // polygon with concave angles
  List<MapPoint> funkyList = new List<MapPoint>();
  funkyList.Add(MapPointBuilder.CreateMapPoint(1.0, 1.0));
  funkyList.Add(MapPointBuilder.CreateMapPoint(1.5, 1.5));
  funkyList.Add(MapPointBuilder.CreateMapPoint(1.0, 2.0));
  funkyList.Add(MapPointBuilder.CreateMapPoint(2.0, 2.0));
  funkyList.Add(MapPointBuilder.CreateMapPoint(1.5, 1.5));
  funkyList.Add(MapPointBuilder.CreateMapPoint(2.0, 1.0));
  funkyList.Add(MapPointBuilder.CreateMapPoint(1.0, 1.0));

  Polygon funkyPoly = PolygonBuilder.CreatePolygon(funkyList);
  hull = GeometryEngine.Instance.ConvexHull(funkyPoly);
  hullPoly = hull as Polygon;
  // hullPoly.Length = 4.0
  // hullPoly.Area = 1.0
  // hullPoly.PointCount = 5
  // hullPoly.Points[0] = 1.0, 1.0
  // hullPoly.Points[1] = 1.0, 2.0
  // hullPoly.Points[2] = 2.0, 2.0
  // hullPoly.Points[3] = 2.0, 1.0
  // hullPoly.Points[4] = 1.0, 1.0
});

Determine if two geometries cross

    before:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  //
  // pt on pt
  //

  MapPoint pt = MapPointBuilder.CreateMapPoint(1.0, 1.0);
  MapPoint pt2 = MapPointBuilder.CreateMapPoint(2.0, 2.0);

  bool crosses = GeometryEngine.Crosses(pt, pt2);         // crosses = false
  crosses = GeometryEngine.Crosses(pt, pt);               // crosses = false

  // 
  // pt and line
  // 

  List<MapPoint> list = new List<MapPoint>();
  list.Add(MapPointBuilder.CreateMapPoint(1.0, 1.0));
  list.Add(MapPointBuilder.CreateMapPoint(3.0, 3.0));
  list.Add(MapPointBuilder.CreateMapPoint(5.0, 1.0));

  Polyline line1 = PolylineBuilder.CreatePolyline(list);
  crosses = GeometryEngine.Crosses(line1, pt2);           // crosses = false
  crosses = GeometryEngine.Crosses(pt2, line1);           // crosses = false
  // end pt of line
  crosses = GeometryEngine.Crosses(line1, pt);            // crosses = false

  //
  // pt and polygon
  //
  List<MapPoint> polyPts = new List<MapPoint>();
  polyPts.Add(MapPointBuilder.CreateMapPoint(3.0, 2.0));
  polyPts.Add(MapPointBuilder.CreateMapPoint(3.0, 6.0));
  polyPts.Add(MapPointBuilder.CreateMapPoint(6.0, 6.0));
  polyPts.Add(MapPointBuilder.CreateMapPoint(6.0, 2.0));

  Polygon poly1 = PolygonBuilder.CreatePolygon(polyPts);
  crosses = GeometryEngine.Crosses(poly1, pt);              // crosses = false
  crosses = GeometryEngine.Crosses(pt, poly1);              // crosses = false

  // 
  // line and line
  //
  List<MapPoint> list2 = new List<MapPoint>();
  list2.Add(MapPointBuilder.CreateMapPoint(1.0, 3.0));
  list2.Add(MapPointBuilder.CreateMapPoint(3.0, 1.0));
  list2.Add(MapPointBuilder.CreateMapPoint(5.0, 3.0));

  Polyline line2 = PolylineBuilder.CreatePolyline(list2);
  crosses = GeometryEngine.Crosses(line1, line2);           // crosses = true

  //
  // line and polygon
  //
  crosses = GeometryEngine.Crosses(poly1, line1);           // crosses = true

  //
  // polygon and polygon
  //
  Envelope env = EnvelopeBuilder.CreateEnvelope(MapPointBuilder.CreateMapPoint(1.0, 1.0), MapPointBuilder.CreateMapPoint(4, 4));
  Polygon poly2 = PolygonBuilder.CreatePolygon(env);
  crosses = GeometryEngine.Crosses(poly1, poly2);           // crosses = false
});

    now:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  //
  // pt on pt
  //

  MapPoint pt = MapPointBuilder.CreateMapPoint(1.0, 1.0);
  MapPoint pt2 = MapPointBuilder.CreateMapPoint(2.0, 2.0);

  bool crosses = GeometryEngine.Instance.Crosses(pt, pt2);         // crosses = false
  crosses = GeometryEngine.Instance.Crosses(pt, pt);               // crosses = false

  // 
  // pt and line
  // 

  List<MapPoint> list = new List<MapPoint>();
  list.Add(MapPointBuilder.CreateMapPoint(1.0, 1.0));
  list.Add(MapPointBuilder.CreateMapPoint(3.0, 3.0));
  list.Add(MapPointBuilder.CreateMapPoint(5.0, 1.0));

  Polyline line1 = PolylineBuilder.CreatePolyline(list);
  crosses = GeometryEngine.Instance.Crosses(line1, pt2);           // crosses = false
  crosses = GeometryEngine.Instance.Crosses(pt2, line1);           // crosses = false
  // end pt of line
  crosses = GeometryEngine.Instance.Crosses(line1, pt);            // crosses = false

  //
  // pt and polygon
  //
  List<MapPoint> polyPts = new List<MapPoint>();
  polyPts.Add(MapPointBuilder.CreateMapPoint(3.0, 2.0));
  polyPts.Add(MapPointBuilder.CreateMapPoint(3.0, 6.0));
  polyPts.Add(MapPointBuilder.CreateMapPoint(6.0, 6.0));
  polyPts.Add(MapPointBuilder.CreateMapPoint(6.0, 2.0));

  Polygon poly1 = PolygonBuilder.CreatePolygon(polyPts);
  crosses = GeometryEngine.Instance.Crosses(poly1, pt);              // crosses = false
  crosses = GeometryEngine.Instance.Crosses(pt, poly1);              // crosses = false

  // 
  // line and line
  //
  List<MapPoint> list2 = new List<MapPoint>();
  list2.Add(MapPointBuilder.CreateMapPoint(1.0, 3.0));
  list2.Add(MapPointBuilder.CreateMapPoint(3.0, 1.0));
  list2.Add(MapPointBuilder.CreateMapPoint(5.0, 3.0));

  Polyline line2 = PolylineBuilder.CreatePolyline(list2);
  crosses = GeometryEngine.Instance.Crosses(line1, line2);           // crosses = true

  //
  // line and polygon
  //
  crosses = GeometryEngine.Instance.Crosses(poly1, line1);           // crosses = true

  //
  // polygon and polygon
  //
  Envelope env = EnvelopeBuilder.CreateEnvelope(MapPointBuilder.CreateMapPoint(1.0, 1.0), MapPointBuilder.CreateMapPoint(4, 4));
  Polygon poly2 = PolygonBuilder.CreatePolygon(env);
  crosses = GeometryEngine.Instance.Crosses(poly1, poly2);           // crosses = false
});

Cut a geometry with a polyline

    before:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  SpatialReference sr = SpatialReferences.WGS84;

  List<MapPoint> list = new List<MapPoint>();
  list.Add(MapPointBuilder.CreateMapPoint(1.0, 1.0, sr));
  list.Add(MapPointBuilder.CreateMapPoint(1.0, 4.0, sr));
  list.Add(MapPointBuilder.CreateMapPoint(4.0, 4.0, sr));
  list.Add(MapPointBuilder.CreateMapPoint(4.0, 1.0, sr));

  List<Geometry> cutGeometries;

  LineSegment line = LineBuilder.CreateLineSegment(MapPointBuilder.CreateMapPoint(0, 0, sr), MapPointBuilder.CreateMapPoint(3, 6, sr));
  Polyline cutter = PolylineBuilder.CreatePolyline(line);

  // polyline
  Polyline polyline = PolylineBuilder.CreatePolyline(list);
  bool isSimple = GeometryEngine.IsSimpleAsFeature(polyline);
  cutGeometries = GeometryEngine.Cut(polyline, cutter) as List<Geometry>;

  Polyline leftPolyline = cutGeometries[0] as Polyline;
  Polyline rightPolyline = cutGeometries[1] as Polyline;

  // leftPolyline.Points[0] = 1, 2
  // leftPolyline.Points[1] = 1, 4
  // leftPolyline.Points[2] = 2, 4

  // rightPolyline.Points.Count = 5
  // rightPolyline.Parts.Count = 2
  
  ReadOnlySegmentCollection segments0 = rightPolyline.Parts[0];
  // segments0[0].StartCoordinate = 1, 1
  // segments0[0].EndCoordinate = 1, 2

  ReadOnlySegmentCollection segments1 = rightPolyline.Parts[1];
  // segments1.Count = 2
  // segments1[0].StartCoordinate = 2, 4
  // segments1[0].EndCoordinate = 4, 4
  // segments1[1].StartCoordinate = 4, 4
  // segments1[1].EndCoordinate = 4, 1

  // polygon 
  Polygon polygon = PolygonBuilder.CreatePolygon(list);
  isSimple = GeometryEngine.IsSimpleAsFeature(polygon);
  cutGeometries = GeometryEngine.Cut(polygon, cutter) as List<Geometry>;
});

    now:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  SpatialReference sr = SpatialReferences.WGS84;

  List<MapPoint> list = new List<MapPoint>();
  list.Add(MapPointBuilder.CreateMapPoint(1.0, 1.0, sr));
  list.Add(MapPointBuilder.CreateMapPoint(1.0, 4.0, sr));
  list.Add(MapPointBuilder.CreateMapPoint(4.0, 4.0, sr));
  list.Add(MapPointBuilder.CreateMapPoint(4.0, 1.0, sr));

  List<Geometry> cutGeometries;

  LineSegment line = LineBuilder.CreateLineSegment(MapPointBuilder.CreateMapPoint(0, 0, sr), MapPointBuilder.CreateMapPoint(3, 6, sr));
  Polyline cutter = PolylineBuilder.CreatePolyline(line);

  // polyline
  Polyline polyline = PolylineBuilder.CreatePolyline(list);
  bool isSimple = GeometryEngine.Instance.IsSimpleAsFeature(polyline);
  cutGeometries = GeometryEngine.Instance.Cut(polyline, cutter) as List<Geometry>;

  Polyline leftPolyline = cutGeometries[0] as Polyline;
  Polyline rightPolyline = cutGeometries[1] as Polyline;

  // leftPolyline.Points[0] = 1, 2
  // leftPolyline.Points[1] = 1, 4
  // leftPolyline.Points[2] = 2, 4

  // rightPolyline.Points.Count = 5
  // rightPolyline.Parts.Count = 2
  
  ReadOnlySegmentCollection segments0 = rightPolyline.Parts[0];
  // segments0[0].StartCoordinate = 1, 1
  // segments0[0].EndCoordinate = 1, 2

  ReadOnlySegmentCollection segments1 = rightPolyline.Parts[1];
  // segments1.Count = 2
  // segments1[0].StartCoordinate = 2, 4
  // segments1[0].EndCoordinate = 4, 4
  // segments1[1].StartCoordinate = 4, 4
  // segments1[1].EndCoordinate = 4, 1

  // polygon 
  Polygon polygon = PolygonBuilder.CreatePolygon(list);
  isSimple = GeometryEngine.Instance.IsSimpleAsFeature(polygon);
  cutGeometries = GeometryEngine.Instance.Cut(polygon, cutter) as List<Geometry>;
});

Densify By Length

    before:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  // densify a line segment
  MapPoint startPt = MapPointBuilder.CreateMapPoint(1.0, 1.0);
  MapPoint endPt = MapPointBuilder.CreateMapPoint(1, 21);
  LineSegment line = LineBuilder.CreateLineSegment(startPt, endPt);
  Polyline polyline = PolylineBuilder.CreatePolyline(line);

  Geometry geom = GeometryEngine.DensifyByLength(polyline, 2);
  Polyline result = geom as Polyline;

  
  // densify a circular arc
  Coordinate fromPt = new Coordinate(2, 1);
  Coordinate toPt = new Coordinate(1, 2);
  Coordinate2D interiorPt = new Coordinate2D(1 + Math.Sqrt(2) / 2, 1 + Math.Sqrt(2) / 2);

  EllipticArcBuilder cab = new EllipticArcBuilder(fromPt.ToMapPoint(), toPt.ToMapPoint(), interiorPt);
  EllipticArcSegment circularArc = cab.ToSegment();
  polyline = PolylineBuilder.CreatePolyline(line);

  geom = GeometryEngine.DensifyByLength(polyline, 2);
  result = geom as Polyline;
});

    now:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  // densify a line segment
  MapPoint startPt = MapPointBuilder.CreateMapPoint(1.0, 1.0);
  MapPoint endPt = MapPointBuilder.CreateMapPoint(1, 21);
  LineSegment line = LineBuilder.CreateLineSegment(startPt, endPt);
  Polyline polyline = PolylineBuilder.CreatePolyline(line);

  Geometry geom = GeometryEngine.Instance.DensifyByLength(polyline, 2);
  Polyline result = geom as Polyline;

  
  // densify a circular arc
  MapPoint fromPt = MapPointBuilder.CreateMapPoint(2, 1);
  MapPoint toPt = MapPointBuilder.CreateMapPoint(1, 2);
  Coordinate2D interiorPt = new Coordinate2D(1 + Math.Sqrt(2) / 2, 1 + Math.Sqrt(2) / 2);

  using (EllipticArcBuilder cab = new EllipticArcBuilder(fromPt, toPt, interiorPt))
  {
    EllipticArcSegment circularArc = cab.ToSegment();
    polyline = PolylineBuilder.CreatePolyline(circularArc);
    geom = GeometryEngine.Instance.DensifyByLength(polyline, 2);
    result = geom as Polyline;
  }
});

Difference between two Polygons

    before:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  List<MapPoint> polyPts = new List<MapPoint>();
  polyPts.Add(MapPointBuilder.CreateMapPoint(3.0, 2.0));
  polyPts.Add(MapPointBuilder.CreateMapPoint(3.0, 6.0));
  polyPts.Add(MapPointBuilder.CreateMapPoint(6.0, 6.0));
  polyPts.Add(MapPointBuilder.CreateMapPoint(6.0, 2.0));

  Polygon poly1 = PolygonBuilder.CreatePolygon(polyPts);

  Envelope env = EnvelopeBuilder.CreateEnvelope(MapPointBuilder.CreateMapPoint(1.0, 1.0), MapPointBuilder.CreateMapPoint(4, 4));
  Polygon poly2 = PolygonBuilder.CreatePolygon(env);

  Geometry result = GeometryEngine.Difference(poly1, poly2);
  Polygon polyResult = result as Polygon;
  // polyResult.Area = 10.0

  result = GeometryEngine.Difference(poly2, poly1);
  polyResult = result as Polygon;
  // polyResult.Area = 7.0

});

    now:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  List<MapPoint> polyPts = new List<MapPoint>();
  polyPts.Add(MapPointBuilder.CreateMapPoint(3.0, 2.0));
  polyPts.Add(MapPointBuilder.CreateMapPoint(3.0, 6.0));
  polyPts.Add(MapPointBuilder.CreateMapPoint(6.0, 6.0));
  polyPts.Add(MapPointBuilder.CreateMapPoint(6.0, 2.0));

  Polygon poly1 = PolygonBuilder.CreatePolygon(polyPts);

  Envelope env = EnvelopeBuilder.CreateEnvelope(MapPointBuilder.CreateMapPoint(1.0, 1.0), MapPointBuilder.CreateMapPoint(4, 4));
  Polygon poly2 = PolygonBuilder.CreatePolygon(env);

  Geometry result = GeometryEngine.Instance.Difference(poly1, poly2);
  Polygon polyResult = result as Polygon;
  // polyResult.Area = 10.0

  result = GeometryEngine.Instance.Difference(poly2, poly1);
  polyResult = result as Polygon;
  // polyResult.Area = 7.0

});

Determine if two Geometries are disjoint

    before:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{

  //
  // pt on pt
  //

  MapPoint pt = MapPointBuilder.CreateMapPoint(1.0, 1.0);
  MapPoint pt2 = MapPointBuilder.CreateMapPoint(2.0, 2.5);

  bool disjoint = GeometryEngine.Disjoint(pt, pt2);       // result is true

  MultipointBuilder mpb = new MultipointBuilder();
  mpb.Add(pt);
  mpb.Add(pt2);
  Multipoint multiPoint = mpb.ToGeometry();

  disjoint = GeometryEngine.Disjoint(multiPoint, pt);     // result is false

  // 
  // pt and line
  // 

  List<MapPoint> list = new List<MapPoint>();
  list.Add(MapPointBuilder.CreateMapPoint(1.0, 1.0));
  list.Add(MapPointBuilder.CreateMapPoint(3.0, 3.0));
  list.Add(MapPointBuilder.CreateMapPoint(5.0, 1.0));

  Polyline line1 = PolylineBuilder.CreatePolyline(list);
  disjoint = GeometryEngine.Disjoint(line1, pt2);       // result is true

  disjoint = GeometryEngine.Disjoint(pt2, line1);       // result is true

  // end pt of line
  disjoint = GeometryEngine.Disjoint(line1, pt);        // result is false

  //
  // pt and polygon
  //
  List<MapPoint> polyPts = new List<MapPoint>();
  polyPts.Add(MapPointBuilder.CreateMapPoint(3.0, 2.0));
  polyPts.Add(MapPointBuilder.CreateMapPoint(3.0, 6.0));
  polyPts.Add(MapPointBuilder.CreateMapPoint(6.0, 6.0));
  polyPts.Add(MapPointBuilder.CreateMapPoint(6.0, 2.0));

  Polygon poly1 = PolygonBuilder.CreatePolygon(polyPts);
  disjoint = GeometryEngine.Disjoint(poly1, pt);          // result is true
  disjoint = GeometryEngine.Disjoint(pt, poly1);          // result is true

  // 
  // line and line
  //

  List<MapPoint> list2 = new List<MapPoint>();
  list2.Add(MapPointBuilder.CreateMapPoint(1.0, 3.0));
  list2.Add(MapPointBuilder.CreateMapPoint(3.0, 1.0));
  list2.Add(MapPointBuilder.CreateMapPoint(5.0, 3.0));

  Polyline line2 = PolylineBuilder.CreatePolyline(list2);
  disjoint = GeometryEngine.Disjoint(line1, line2);         // result is false

  //
  // line and polygon
  //
  disjoint = GeometryEngine.Disjoint(poly1, line1);         // result is false
  disjoint = GeometryEngine.Disjoint(line1, poly1);         // result is false

  //
  // polygon and polygon
  //
  Envelope env = EnvelopeBuilder.CreateEnvelope(MapPointBuilder.CreateMapPoint(1.0, 1.0), MapPointBuilder.CreateMapPoint(4, 4));
  Polygon poly2 = PolygonBuilder.CreatePolygon(env);

  disjoint = GeometryEngine.Disjoint(poly1, poly2);         // result is false


  // disjoint3D

  SpatialReference sr = SpatialReferences.WGS84;

  MapPoint pt3D_1 = MapPointBuilder.CreateMapPoint(1, 1, 1, sr);
  MapPoint pt3D_2 = MapPointBuilder.CreateMapPoint(2, 2, 2, sr);
  MapPoint pt3D_3 = MapPointBuilder.CreateMapPoint(1, 1, 2, sr);

  mpb = new MultipointBuilder();
  mpb.Add(pt3D_1);
  mpb.Add(pt3D_2);
  mpb.HasZ = true;

  multiPoint = mpb.ToGeometry();
  disjoint = GeometryEngine.Disjoint3D(multiPoint, pt3D_2);     // disjoint = false
  disjoint = GeometryEngine.Disjoint3D(multiPoint, pt3D_3);     // disjoint = true
});

    now:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{

  //
  // pt on pt
  //

  MapPoint pt = MapPointBuilder.CreateMapPoint(1.0, 1.0);
  MapPoint pt2 = MapPointBuilder.CreateMapPoint(2.0, 2.5);

  bool disjoint = GeometryEngine.Instance.Disjoint(pt, pt2);       // result is true

  using (MultipointBuilder mpb = new MultipointBuilder())
  {
    mpb.Add(pt);
    mpb.Add(pt2);
    Multipoint multiPoint = mpb.ToGeometry();

    disjoint = GeometryEngine.Instance.Disjoint(multiPoint, pt);     // result is false
  }

  // 
  // pt and line
  // 

  List<MapPoint> list = new List<MapPoint>();
  list.Add(MapPointBuilder.CreateMapPoint(1.0, 1.0));
  list.Add(MapPointBuilder.CreateMapPoint(3.0, 3.0));
  list.Add(MapPointBuilder.CreateMapPoint(5.0, 1.0));

  Polyline line1 = PolylineBuilder.CreatePolyline(list);
  disjoint = GeometryEngine.Instance.Disjoint(line1, pt2);       // result is true

  disjoint = GeometryEngine.Instance.Disjoint(pt2, line1);       // result is true

  // end pt of line
  disjoint = GeometryEngine.Instance.Disjoint(line1, pt);        // result is false

  //
  // pt and polygon
  //
  List<MapPoint> polyPts = new List<MapPoint>();
  polyPts.Add(MapPointBuilder.CreateMapPoint(3.0, 2.0));
  polyPts.Add(MapPointBuilder.CreateMapPoint(3.0, 6.0));
  polyPts.Add(MapPointBuilder.CreateMapPoint(6.0, 6.0));
  polyPts.Add(MapPointBuilder.CreateMapPoint(6.0, 2.0));

  Polygon poly1 = PolygonBuilder.CreatePolygon(polyPts);
  disjoint = GeometryEngine.Instance.Disjoint(poly1, pt);          // result is true
  disjoint = GeometryEngine.Instance.Disjoint(pt, poly1);          // result is true

  // 
  // line and line
  //

  List<MapPoint> list2 = new List<MapPoint>();
  list2.Add(MapPointBuilder.CreateMapPoint(1.0, 3.0));
  list2.Add(MapPointBuilder.CreateMapPoint(3.0, 1.0));
  list2.Add(MapPointBuilder.CreateMapPoint(5.0, 3.0));

  Polyline line2 = PolylineBuilder.CreatePolyline(list2);
  disjoint = GeometryEngine.Instance.Disjoint(line1, line2);         // result is false

  //
  // line and polygon
  //
  disjoint = GeometryEngine.Instance.Disjoint(poly1, line1);         // result is false
  disjoint = GeometryEngine.Instance.Disjoint(line1, poly1);         // result is false

  //
  // polygon and polygon
  //
  Envelope env = EnvelopeBuilder.CreateEnvelope(MapPointBuilder.CreateMapPoint(1.0, 1.0), MapPointBuilder.CreateMapPoint(4, 4));
  Polygon poly2 = PolygonBuilder.CreatePolygon(env);

  disjoint = GeometryEngine.Instance.Disjoint(poly1, poly2);         // result is false


  // disjoint3D

  SpatialReference sr = SpatialReferences.WGS84;

  MapPoint pt3D_1 = MapPointBuilder.CreateMapPoint(1, 1, 1, sr);
  MapPoint pt3D_2 = MapPointBuilder.CreateMapPoint(2, 2, 2, sr);
  MapPoint pt3D_3 = MapPointBuilder.CreateMapPoint(1, 1, 2, sr);

  using (MultipointBuilder mpb = new MultipointBuilder())
  {
    mpb.Add(pt3D_1);
    mpb.Add(pt3D_2);
    mpb.HasZ = true;

    Multipoint multiPoint = mpb.ToGeometry();
    disjoint = GeometryEngine.Instance.Disjoint3D(multiPoint, pt3D_2);     // disjoint = false
    disjoint = GeometryEngine.Instance.Disjoint3D(multiPoint, pt3D_3);     // disjoint = true
  }
});

Determine distance between two Geometries

    before:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  MapPoint pt1 = MapPointBuilder.CreateMapPoint(1.0, 1.0);
  MapPoint pt2 = MapPointBuilder.CreateMapPoint(2.0, 2.0);
  MapPoint pt3 = MapPointBuilder.CreateMapPoint(4.0, 2.0);

  //
  // pt and pt 
  //
  double d = GeometryEngine.Distance(pt1, pt2);         // d = Math.Sqrt(2)

  //
  // pt and multipoint
  //
  List<MapPoint> multiPts = new List<MapPoint>();
  multiPts.Add(pt2);
  multiPts.Add(pt3);
  Multipoint multiPoint = MultipointBuilder.CreateMultipoint(multiPts);
  d = GeometryEngine.Distance(pt1, multiPoint);         // d = Math.Sqrt(2)

  //
  // pt and envelope
  //
  Envelope env = EnvelopeBuilder.CreateEnvelope(pt1, pt2);
  d = GeometryEngine.Distance(pt1, env);                // d = 0

  //
  // pt and polyline
  //
  List<MapPoint> polylinePts = new List<MapPoint>();
  polylinePts.Add(MapPointBuilder.CreateMapPoint(2.0, 1.0));
  polylinePts.Add(pt2);
  Polyline polyline = PolylineBuilder.CreatePolyline(polylinePts);

  d = GeometryEngine.Distance(pt1, polyline);             // d = 1.0

  //
  // pt and polygon
  //
  Envelope env2 = EnvelopeBuilder.CreateEnvelope(MapPointBuilder.CreateMapPoint(3.0, 3.0), MapPointBuilder.CreateMapPoint(5.0, 5.0));
  Polygon poly = PolygonBuilder.CreatePolygon(env2);
  d = GeometryEngine.Distance(pt1, poly);                 // d = Math.Sqrt(8)

  //
  // envelope and polyline
  //
  d = GeometryEngine.Distance(env, polyline);             // d = 0

  //
  // polyline and polyline
  //
  List<MapPoint> polylineList = new List<MapPoint>();
  polylineList.Add(MapPointBuilder.CreateMapPoint(4, 3));
  polylineList.Add(MapPointBuilder.CreateMapPoint(4, 4));
  Polyline polyline2 = PolylineBuilder.CreatePolyline(polylineList);

  d = GeometryEngine.Distance(polyline, polyline2);           // d = Math.Sqrt(5)


  //
  // polygon and polygon
  //
  Polygon poly2 = PolygonBuilder.CreatePolygon(env);
  d = GeometryEngine.Distance(poly, poly2);                 // d = Math.Sqrt(2)
});

    now:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  MapPoint pt1 = MapPointBuilder.CreateMapPoint(1.0, 1.0);
  MapPoint pt2 = MapPointBuilder.CreateMapPoint(2.0, 2.0);
  MapPoint pt3 = MapPointBuilder.CreateMapPoint(4.0, 2.0);

  //
  // pt and pt 
  //
  double d = GeometryEngine.Instance.Distance(pt1, pt2);         // d = Math.Sqrt(2)

  //
  // pt and multipoint
  //
  List<MapPoint> multiPts = new List<MapPoint>();
  multiPts.Add(pt2);
  multiPts.Add(pt3);
  Multipoint multiPoint = MultipointBuilder.CreateMultipoint(multiPts);
  d = GeometryEngine.Instance.Distance(pt1, multiPoint);         // d = Math.Sqrt(2)

  //
  // pt and envelope
  //
  Envelope env = EnvelopeBuilder.CreateEnvelope(pt1, pt2);
  d = GeometryEngine.Instance.Distance(pt1, env);                // d = 0

  //
  // pt and polyline
  //
  List<MapPoint> polylinePts = new List<MapPoint>();
  polylinePts.Add(MapPointBuilder.CreateMapPoint(2.0, 1.0));
  polylinePts.Add(pt2);
  Polyline polyline = PolylineBuilder.CreatePolyline(polylinePts);

  d = GeometryEngine.Instance.Distance(pt1, polyline);             // d = 1.0

  //
  // pt and polygon
  //
  Envelope env2 = EnvelopeBuilder.CreateEnvelope(MapPointBuilder.CreateMapPoint(3.0, 3.0), MapPointBuilder.CreateMapPoint(5.0, 5.0));
  Polygon poly = PolygonBuilder.CreatePolygon(env2);
  d = GeometryEngine.Instance.Distance(pt1, poly);                 // d = Math.Sqrt(8)

  //
  // envelope and polyline
  //
  d = GeometryEngine.Instance.Distance(env, polyline);             // d = 0

  //
  // polyline and polyline
  //
  List<MapPoint> polylineList = new List<MapPoint>();
  polylineList.Add(MapPointBuilder.CreateMapPoint(4, 3));
  polylineList.Add(MapPointBuilder.CreateMapPoint(4, 4));
  Polyline polyline2 = PolylineBuilder.CreatePolyline(polylineList);

  d = GeometryEngine.Instance.Distance(polyline, polyline2);           // d = Math.Sqrt(5)


  //
  // polygon and polygon
  //
  Polygon poly2 = PolygonBuilder.CreatePolygon(env);
  d = GeometryEngine.Instance.Distance(poly, poly2);                 // d = Math.Sqrt(2)
});

Determine 3D distance between two Geometries

    before:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{

  // between points 
  MapPoint pt1 = MapPointBuilder.CreateMapPoint(1, 1, 1);
  MapPoint pt2 = MapPointBuilder.CreateMapPoint(2, 2, 2);
  MapPoint pt3 = MapPointBuilder.CreateMapPoint(10, 2, 1);

  // pt1 to pt2
  double d = GeometryEngine.Distance3D(pt1, pt2);        // d = Math.Sqrt(3)

  // pt1 to pt3
  d = GeometryEngine.Distance3D(pt1, pt3);        // d = Math.Sqrt(82)

  // pt2 to pt3
  d = GeometryEngine.Distance3D(pt2, pt3);        // d = Math.Sqrt(65)



  // intersecting lines

  List<MapPoint> list = new List<MapPoint>();
  list.Add(MapPointBuilder.CreateMapPoint(1.0, 1.0, 1.0));
  list.Add(MapPointBuilder.CreateMapPoint(3.0, 3.0, 1.0));
  list.Add(MapPointBuilder.CreateMapPoint(5.0, 1.0, 1.0));

  Polyline line1 = PolylineBuilder.CreatePolyline(list);

  List<MapPoint> list2 = new List<MapPoint>();
  list2.Add(MapPointBuilder.CreateMapPoint(1.0, 3.0, 1.0));
  list2.Add(MapPointBuilder.CreateMapPoint(3.0, 1.0, 1.0));
  list2.Add(MapPointBuilder.CreateMapPoint(5.0, 3.0, 1.0));

  Polyline line2 = PolylineBuilder.CreatePolyline(list2);

  bool intersects = GeometryEngine.Intersects(line1, line2);    // intersects = true
  d = GeometryEngine.Distance3D(line1, line2);                  // d = 0   (distance is 0 when geomtries intersect)

});

    now:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{

  // between points 
  MapPoint pt1 = MapPointBuilder.CreateMapPoint(1, 1, 1);
  MapPoint pt2 = MapPointBuilder.CreateMapPoint(2, 2, 2);
  MapPoint pt3 = MapPointBuilder.CreateMapPoint(10, 2, 1);

  // pt1 to pt2
  double d = GeometryEngine.Instance.Distance3D(pt1, pt2);        // d = Math.Sqrt(3)

  // pt1 to pt3
  d = GeometryEngine.Instance.Distance3D(pt1, pt3);        // d = Math.Sqrt(82)

  // pt2 to pt3
  d = GeometryEngine.Instance.Distance3D(pt2, pt3);        // d = Math.Sqrt(65)



  // intersecting lines

  List<MapPoint> list = new List<MapPoint>();
  list.Add(MapPointBuilder.CreateMapPoint(1.0, 1.0, 1.0));
  list.Add(MapPointBuilder.CreateMapPoint(3.0, 3.0, 1.0));
  list.Add(MapPointBuilder.CreateMapPoint(5.0, 1.0, 1.0));

  Polyline line1 = PolylineBuilder.CreatePolyline(list);

  List<MapPoint> list2 = new List<MapPoint>();
  list2.Add(MapPointBuilder.CreateMapPoint(1.0, 3.0, 1.0));
  list2.Add(MapPointBuilder.CreateMapPoint(3.0, 1.0, 1.0));
  list2.Add(MapPointBuilder.CreateMapPoint(5.0, 3.0, 1.0));

  Polyline line2 = PolylineBuilder.CreatePolyline(list2);

  bool intersects = GeometryEngine.Instance.Intersects(line1, line2);    // intersects = true
  d = GeometryEngine.Instance.Distance3D(line1, line2);                  // d = 0   (distance is 0 when geomtries intersect)

});

Expand envelopes

    before:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  Envelope env = EnvelopeBuilder.CreateEnvelope(100.0, 100.0, 500.0, 500.0);
  // env.HasZ = false

  Envelope result = GeometryEngine.Expand(env, 0.5, 0.5, true);
  // result.Center = 300, 300
  // result.XMin = 200
  // result.YMin = 200
  // result.XMax = 400
  // result.YMax = 400

  result = GeometryEngine.Expand(env, 100, 200, false);
  // result.Center = 300, 300
  // result.XMin = 0
  // result.YMin = -100
  // result.XMax = 600
  // result.YMax = 700

  try
  {
    // expand in 3 dimensions
    result = GeometryEngine.Expand(env, 0.5, 0.5, 0.5, true);
  }
  catch (InvalidOperationException e)
  {
    // the geometry is not Z-Aware
  }

  // expand a 3d envelope
  MapPoint pt1 = MapPointBuilder.CreateMapPoint(100, 100, 100);
  MapPoint pt2 = MapPointBuilder.CreateMapPoint(200, 200, 200);

  EnvelopeBuilder eb = new EnvelopeBuilder(pt1, pt2);
  eb.HasZ = true;
  env = eb.ToGeometry();
  result = GeometryEngine.Expand(env, 0.5, 0.5, 0.5, true);

  // result.Center = 150, 150, 150
  // result.XMin = 125
  // result.YMin = 125
  // result.ZMin = 125
  // result.XMax = 175
  // result.YMax = 175
  // result.ZMax = 175
});

    now:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  Envelope env = EnvelopeBuilder.CreateEnvelope(100.0, 100.0, 500.0, 500.0);
  // env.HasZ = false

  Envelope result = GeometryEngine.Instance.Expand(env, 0.5, 0.5, true);
  // result.Center = 300, 300
  // result.XMin = 200
  // result.YMin = 200
  // result.XMax = 400
  // result.YMax = 400

  result = GeometryEngine.Instance.Expand(env, 100, 200, false);
  // result.Center = 300, 300
  // result.XMin = 0
  // result.YMin = -100
  // result.XMax = 600
  // result.YMax = 700

  try
  {
    // expand in 3 dimensions
    result = GeometryEngine.Instance.Expand(env, 0.5, 0.5, 0.5, true);
  }
  catch (InvalidOperationException e)
  {
    // the geometry is not Z-Aware
  }

  // expand a 3d envelope
  MapPoint pt1 = MapPointBuilder.CreateMapPoint(100, 100, 100);
  MapPoint pt2 = MapPointBuilder.CreateMapPoint(200, 200, 200);

  using (EnvelopeBuilder eb = new EnvelopeBuilder(pt1, pt2))
  {
    eb.HasZ = true;
    env = eb.ToGeometry();
    result = GeometryEngine.Instance.Expand(env, 0.5, 0.5, 0.5, true);

    // result.Center = 150, 150, 150
    // result.XMin = 125
    // result.YMin = 125
    // result.ZMin = 125
    // result.XMax = 175
    // result.YMax = 175
    // result.ZMax = 175
  }
});

Extend a polyline

    before:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  // build a polyline
  var polyline = PolylineBuilder.CreatePolyline(new[]
  {
      MapPointBuilder.CreateMapPoint( 1,  1, 10, 20),
      MapPointBuilder.CreateMapPoint( 0,  0, 10, 20),
      MapPointBuilder.CreateMapPoint( 1, -1, 10, 20)
  });

  // build the extender line
  var extender = PolylineBuilder.CreatePolyline(new[]
  {
      MapPointBuilder.CreateMapPoint( 2, 2),
      MapPointBuilder.CreateMapPoint( 2,-2), 
  });

  // extend
  var result = GeometryEngine.Extend(polyline, extender, ExtendFlags.KeepEndAttributes);
  Polyline extendedLine = result as Polyline;
  // result.Parts[0].Points[0] = 2, 2, 10, 20
  // result.parts[0].Points[1] = 1, 1, 10, 20
  // result.Parts[0].Points[2] = 0, 0, 10, 20
  // result.Parts[0].Points[3] = 1, -1, 10, 20
  // result.Parts[0].Points[4] = 2, -2, 10, 20

  // change the flags
  result = GeometryEngine.Extend(polyline, extender, ExtendFlags.NoEndAttributes);
  extendedLine = result as Polyline;
  // result.Parts[0].Points[0] = 2, 2, 0
  // result.parts[0].Points[1] = 1, 1, 10, 20
  // result.Parts[0].Points[2] = 0, 0, 10, 20
  // result.Parts[0].Points[3] = 1, -1, 10, 20
  // result.Parts[0].Points[4] = 2, -2, 0

  // extend
  result = GeometryEngine.Extend(polyline, extender, ExtendFlags.KeepEndAttributes | ExtendFlags.NoExtendAtTo);
  extendedLine = result as Polyline;
  // result.Parts[0].Points[0] = 2, 2, 10, 20
  // result.parts[0].Points[1] = 1, 1, 10, 20
  // result.Parts[0].Points[2] = 0, 0, 10, 20
  // result.Parts[0].Points[3] = 1, -1, 10, 20


  // extend with no intersection 

  polyline = PolylineBuilder.CreatePolyline(new[]
  {
      MapPointBuilder.CreateMapPoint( 1,  1),
      MapPointBuilder.CreateMapPoint( 3,  1),
  });

  extender = PolylineBuilder.CreatePolyline(new[]
  {
      MapPointBuilder.CreateMapPoint( 1, 4),
      MapPointBuilder.CreateMapPoint( 3, 4), 
  });

  result = GeometryEngine.Extend(polyline, extender, ExtendFlags.Default);
  // result = null
});

    now:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  // build a polyline
  var polyline = PolylineBuilder.CreatePolyline(new[]
  {
      MapPointBuilder.CreateMapPoint( 1,  1, 10, 20),
      MapPointBuilder.CreateMapPoint( 0,  0, 10, 20),
      MapPointBuilder.CreateMapPoint( 1, -1, 10, 20)
  });

  // build the extender line
  var extender = PolylineBuilder.CreatePolyline(new[]
  {
      MapPointBuilder.CreateMapPoint( 2, 2),
      MapPointBuilder.CreateMapPoint( 2,-2), 
  });

  // extend
  var result = GeometryEngine.Instance.Extend(polyline, extender, ExtendFlags.KeepEndAttributes);
  Polyline extendedLine = result as Polyline;
  // result.Parts[0].Points[0] = 2, 2, 10, 20
  // result.parts[0].Points[1] = 1, 1, 10, 20
  // result.Parts[0].Points[2] = 0, 0, 10, 20
  // result.Parts[0].Points[3] = 1, -1, 10, 20
  // result.Parts[0].Points[4] = 2, -2, 10, 20

  // change the flags
  result = GeometryEngine.Instance.Extend(polyline, extender, ExtendFlags.NoEndAttributes);
  extendedLine = result as Polyline;
  // result.Parts[0].Points[0] = 2, 2, 0
  // result.parts[0].Points[1] = 1, 1, 10, 20
  // result.Parts[0].Points[2] = 0, 0, 10, 20
  // result.Parts[0].Points[3] = 1, -1, 10, 20
  // result.Parts[0].Points[4] = 2, -2, 0

  // extend
  result = GeometryEngine.Instance.Extend(polyline, extender, ExtendFlags.KeepEndAttributes | ExtendFlags.NoExtendAtTo);
  extendedLine = result as Polyline;
  // result.Parts[0].Points[0] = 2, 2, 10, 20
  // result.parts[0].Points[1] = 1, 1, 10, 20
  // result.Parts[0].Points[2] = 0, 0, 10, 20
  // result.Parts[0].Points[3] = 1, -1, 10, 20


  // extend with no intersection 

  polyline = PolylineBuilder.CreatePolyline(new[]
  {
      MapPointBuilder.CreateMapPoint( 1,  1),
      MapPointBuilder.CreateMapPoint( 3,  1),
  });

  extender = PolylineBuilder.CreatePolyline(new[]
  {
      MapPointBuilder.CreateMapPoint( 1, 4),
      MapPointBuilder.CreateMapPoint( 3, 4), 
  });

  result = GeometryEngine.Instance.Extend(polyline, extender, ExtendFlags.Default);
  // result = null
});

GeodesicBuffer

    before:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  // buffer a point
  MapPoint pt = MapPointBuilder.CreateMapPoint(1.0, 1.0, SpatialReferences.WGS84);
  Polygon outPolygon = GeometryEngine.GeodesicBuffer(pt, 5) as Polygon;

  double delta = SpatialReferences.WGS84.XYTolerance * 2 * Math.Sqrt(2);
  ReadOnlyPointCollection points = outPolygon.Points;
  foreach (MapPoint p in points)
  {
    double d = GeometryEngine.GeodesicDistance(pt, p);
    // d = 5 (+- delta)
  }

  // buffer of 0 distance produces an empty geometry
  Geometry g = GeometryEngine.GeodesicBuffer(pt, 0);
  // g.IsEmpty = true


  // buffer many points
  List<MapPoint> list = new List<MapPoint>();
  list.Add(MapPointBuilder.CreateMapPoint(1.0, 1.0, SpatialReferences.WGS84));
  list.Add(MapPointBuilder.CreateMapPoint(10.0, 20.0));
  list.Add(MapPointBuilder.CreateMapPoint(40.0, 40.0));
  list.Add(MapPointBuilder.CreateMapPoint(60.0, 60.0));

  outPolygon = GeometryEngine.GeodesicBuffer(list, 10000) as Polygon;
  // outPolygon.PartCount = 4


  // buffer different geometry types
  List<Coordinate2D> coords = new List<Coordinate2D>()
  {
    new Coordinate2D(1, 2), new Coordinate2D(10, 20), new Coordinate2D(20, 30),
    new Coordinate2D(50, 60), new Coordinate2D(70, 80), new Coordinate2D(80, 40),
    new Coordinate2D(90, 10), new Coordinate2D(110, 15), new Coordinate2D(120, 30),
    new Coordinate2D(10, 40), new Coordinate2D(-10, 40), new Coordinate2D(-10, 50)
  };

  List<Geometry> manyGeometries = new List<Geometry>
  {
    MapPointBuilder.CreateMapPoint(1.0, 1.0, SpatialReferences.WGS84), 
    PolylineBuilder.CreatePolyline(new List<Coordinate2D>(){coords[0], coords[1], coords[2]}, SpatialReferences.WGS84),
    PolylineBuilder.CreatePolyline(new List<Coordinate2D>(){coords[3], coords[4], coords[5]}),
    PolygonBuilder.CreatePolygon(new List<Coordinate2D>(){coords[9], coords[10], coords[11]})
  };

  outPolygon = GeometryEngine.GeodesicBuffer(manyGeometries, 20000) as Polygon;
});

    now:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  // buffer a point
  MapPoint pt = MapPointBuilder.CreateMapPoint(1.0, 1.0, SpatialReferences.WGS84);
  Polygon outPolygon = GeometryEngine.Instance.GeodesicBuffer(pt, 5) as Polygon;

  double delta = SpatialReferences.WGS84.XYTolerance * 2 * Math.Sqrt(2);
  ReadOnlyPointCollection points = outPolygon.Points;
  foreach (MapPoint p in points)
  {
    double d = GeometryEngine.Instance.GeodesicDistance(pt, p);
    // d = 5 (+- delta)
  }

  // buffer of 0 distance produces an empty geometry
  Geometry g = GeometryEngine.Instance.GeodesicBuffer(pt, 0);
  // g.IsEmpty = true


  // buffer many points
  List<MapPoint> list = new List<MapPoint>();
  list.Add(MapPointBuilder.CreateMapPoint(1.0, 1.0, SpatialReferences.WGS84));
  list.Add(MapPointBuilder.CreateMapPoint(10.0, 20.0));
  list.Add(MapPointBuilder.CreateMapPoint(40.0, 40.0));
  list.Add(MapPointBuilder.CreateMapPoint(60.0, 60.0));

  outPolygon = GeometryEngine.Instance.GeodesicBuffer(list, 10000) as Polygon;
  // outPolygon.PartCount = 4


  // buffer different geometry types
  List<Coordinate2D> coords = new List<Coordinate2D>()
  {
    new Coordinate2D(1, 2), new Coordinate2D(10, 20), new Coordinate2D(20, 30),
    new Coordinate2D(50, 60), new Coordinate2D(70, 80), new Coordinate2D(80, 40),
    new Coordinate2D(90, 10), new Coordinate2D(110, 15), new Coordinate2D(120, 30),
    new Coordinate2D(10, 40), new Coordinate2D(-10, 40), new Coordinate2D(-10, 50)
  };

  List<Geometry> manyGeometries = new List<Geometry>
  {
    MapPointBuilder.CreateMapPoint(1.0, 1.0, SpatialReferences.WGS84), 
    PolylineBuilder.CreatePolyline(new List<Coordinate2D>(){coords[0], coords[1], coords[2]}, SpatialReferences.WGS84),
    PolylineBuilder.CreatePolyline(new List<Coordinate2D>(){coords[3], coords[4], coords[5]}),
    PolygonBuilder.CreatePolygon(new List<Coordinate2D>(){coords[9], coords[10], coords[11]})
  };

  outPolygon = GeometryEngine.Instance.GeodesicBuffer(manyGeometries, 20000) as Polygon;
});

GeodeticDensifyByDeviation - polyline

    before:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  List<Coordinate> coords = new List<Coordinate>()
  {
    new Coordinate(-80, 0),
    new Coordinate(-20, 60),
    new Coordinate(40, 20),
    new Coordinate(0, -20),
    new Coordinate(-80, 0)
  };

  SpatialReference sr = SpatialReferences.WGS84;

  // create a polyline
  Polyline polyline = PolylineBuilder.CreatePolyline(coords, sr);

  // densify in km
  Polyline geodesicPolyline = GeometryEngine.GeodeticDensifyByDeviation(polyline, 200, LinearUnit.Kilometers, CurveType.Geodesic) as Polyline;
  // densify in m
  geodesicPolyline = GeometryEngine.GeodeticDensifyByDeviation(polyline, 200, LinearUnit.Meters, CurveType.Geodesic) as Polyline;

  // Change curve type to Loxodrome
  Polyline loxodromePolyline = GeometryEngine.GeodeticDensifyByDeviation(polyline, 200, LinearUnit.Meters, CurveType.Loxodrome) as Polyline;
});

    now:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  List<Coordinate2D> coords = new List<Coordinate2D>()
  {
    new Coordinate2D(-80, 0),
    new Coordinate2D(-20, 60),
    new Coordinate2D(40, 20),
    new Coordinate2D(0, -20),
    new Coordinate2D(-80, 0)
  };

  SpatialReference sr = SpatialReferences.WGS84;

  // create a polyline
  Polyline polyline = PolylineBuilder.CreatePolyline(coords, sr);

  // densify in km
  Polyline geodesicPolyline = GeometryEngine.Instance.GeodeticDensifyByDeviation(polyline, 200, LinearUnit.Kilometers, GeodeticCurveType.Geodesic) as Polyline;
  // densify in m
  geodesicPolyline = GeometryEngine.Instance.GeodeticDensifyByDeviation(polyline, 200, LinearUnit.Meters, GeodeticCurveType.Geodesic) as Polyline;

  // Change curve type to Loxodrome
  Polyline loxodromePolyline = GeometryEngine.Instance.GeodeticDensifyByDeviation(polyline, 200, LinearUnit.Meters, GeodeticCurveType.Loxodrome) as Polyline;
});

GeodeticDensifyByLength - polygon

    before:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  List<Coordinate> coords = new List<Coordinate>()
  {
    new Coordinate(-80, 0),
    new Coordinate(-20, 60),
    new Coordinate(40, 20),
    new Coordinate(0, -20),
    new Coordinate(-80, 0)
  };

  SpatialReference sr = SpatialReferences.WGS84;

  // create a polygon
  Polygon polygon = PolygonBuilder.CreatePolygon(coords, sr);

  // get the geodesic lengths of the polygon segments
  ReadOnlySegmentCollection segments = polygon.Parts[0];
  List<Double> geoLengths = new List<Double>(segments.Count);
  foreach (Segment s in segments)
  {
    Polyline line = PolylineBuilder.CreatePolyline(s, sr);
    double geoLen = GeometryEngine.GeodesicLength(line);
    geoLengths.Add(geoLen);
  }

  // find the max length
  geoLengths.Sort();
  double maxLen = geoLengths[geoLengths.Count - 1];

  // densify the polygon (in meters)
  Polygon densifiedPoly = GeometryEngine.GeodeticDensifyByLength(polygon, maxLen, LinearUnit.Meters, CurveType.Geodesic) as Polygon;

  // densify the polygon (in km)
  double maxSegmentLength = maxLen / 10000;
  densifiedPoly = GeometryEngine.GeodeticDensifyByLength(polygon, maxSegmentLength, LinearUnit.Kilometers, CurveType.Geodesic) as Polygon;
});

    now:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  List<Coordinate2D> coords = new List<Coordinate2D>()
  {
    new Coordinate2D(-80, 0),
    new Coordinate2D(-20, 60),
    new Coordinate2D(40, 20),
    new Coordinate2D(0, -20),
    new Coordinate2D(-80, 0)
  };

  SpatialReference sr = SpatialReferences.WGS84;

  // create a polygon
  Polygon polygon = PolygonBuilder.CreatePolygon(coords, sr);

  // get the geodesic lengths of the polygon segments
  ReadOnlySegmentCollection segments = polygon.Parts[0];
  List<Double> geoLengths = new List<Double>(segments.Count);
  foreach (Segment s in segments)
  {
    Polyline line = PolylineBuilder.CreatePolyline(s, sr);
    double geoLen = GeometryEngine.Instance.GeodesicLength(line);
    geoLengths.Add(geoLen);
  }

  // find the max length
  geoLengths.Sort();
  double maxLen = geoLengths[geoLengths.Count - 1];

  // densify the polygon (in meters)
  Polygon densifiedPoly = GeometryEngine.Instance.GeodeticDensifyByLength(polygon, maxLen, LinearUnit.Meters, GeodeticCurveType.Geodesic) as Polygon;

  // densify the polygon (in km)
  double maxSegmentLength = maxLen / 10000;
  densifiedPoly = GeometryEngine.Instance.GeodeticDensifyByLength(polygon, maxSegmentLength, LinearUnit.Kilometers, GeodeticCurveType.Geodesic) as Polygon;
});

GeodesicEllipse

    before:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  GeometryEngine.GeodesicEllipseParameter param = new GeometryEngine.GeodesicEllipseParameter();
  param.AxisDirection = 4 * Math.PI / 3;
  param.Center = new Coordinate(-120, 60);
  param.LinearUnit = LinearUnit.Meters;
  param.OutGeometryType = GeometryType.Polyline;
  param.SemiAxis1Length = 6500000;
  param.SemiAxis2Length = 1500000;
  param.VertexCount = 800;

  Geometry geometry = GeometryEngine.GeodesicEllipse(param, SpatialReferences.WGS84);
  // geometry.IsEmpty = false

  Polyline polyline = geometry as Polyline;
  // polyline.PointCount = 801
  // polyline.PartCount = 1
});

    now:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  GeodesicEllipseParameter param = new GeodesicEllipseParameter();
  param.AxisDirection = 4 * Math.PI / 3;
  param.Center = new Coordinate2D(-120, 60);
  param.LinearUnit = LinearUnit.Meters;
  param.OutGeometryType = GeometryType.Polyline;
  param.SemiAxis1Length = 6500000;
  param.SemiAxis2Length = 1500000;
  param.VertexCount = 800;

  Geometry geometry = GeometryEngine.Instance.GeodesicEllipse(param, SpatialReferences.WGS84);
  // geometry.IsEmpty = false

  Polyline polyline = geometry as Polyline;
  // polyline.PointCount = 801
  // polyline.PartCount = 1
});

Perform Geodetic Move on a set of MapPoints

    before:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  SpatialReference sr = SpatialReferences.WebMercator;
  var points = new[] { MapPointBuilder.CreateMapPoint(0, 0, sr) };
  double distance = 10;
  double azimuth = Math.PI / 2;
  var resultPoints = GeometryEngine.GeodeticMove(points, sr, distance, LinearUnit.Meters, azimuth, CurveType.Geodesic);

  // resultPoints.First().X = 10
  // resultPoints.First().Y = 0
  // resultPoints.First().SpatialReference.Wkid = sr.Wkid

  // Change LinearUnit to Miles
  resultPoints = GeometryEngine.GeodeticMove(points, sr, distance, LinearUnit.Miles, azimuth, CurveType.Geodesic);
  // resultPoints.First().X = 16093.44
  // resultPoints.First().Y = 0

  // Change curve type
  resultPoints = GeometryEngine.GeodeticMove(points, sr, distance, LinearUnit.Miles, azimuth, CurveType.Loxodrome);
  // resultPoints.First().X = 16093.44
  // resultPoints.First().Y = 0
});

    now:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  SpatialReference sr = SpatialReferences.WebMercator;
  var points = new[] { MapPointBuilder.CreateMapPoint(0, 0, sr) };
  double distance = 10;
  double azimuth = Math.PI / 2;
  var resultPoints = GeometryEngine.Instance.GeodeticMove(points, sr, distance, LinearUnit.Meters, azimuth, GeodeticCurveType.Geodesic);

  // resultPoints.First().X = 10
  // resultPoints.First().Y = 0
  // resultPoints.First().SpatialReference.Wkid = sr.Wkid

  // Change LinearUnit to Miles
  resultPoints = GeometryEngine.Instance.GeodeticMove(points, sr, distance, LinearUnit.Miles, azimuth, GeodeticCurveType.Geodesic);
  // resultPoints.First().X = 16093.44
  // resultPoints.First().Y = 0

  // Change curve type
  resultPoints = GeometryEngine.Instance.GeodeticMove(points, sr, distance, LinearUnit.Miles, azimuth, GeodeticCurveType.Loxodrome);
  // resultPoints.First().X = 16093.44
  // resultPoints.First().Y = 0
});

GeodesicSector

    before:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  GeometryEngine.GeodesicSectorParameter param = new GeometryEngine.GeodesicSectorParameter();
  param.ArcVertexCount = 50;
  param.AxisDirection = Math.PI / 4;
  param.Center = new Coordinate(0, 0);
  param.LinearUnit = LinearUnit.Meters;
  param.OutGeometryType = GeometryType.Polygon;
  param.RadiusVertexCount = 10;
  param.SectorAngle = 5 * Math.PI / 3;
  param.SemiAxis1Length = 100000;
  param.SemiAxis2Length = 20000;
  param.StartDirection = 11 * Math.PI / 6;

  Geometry geometry = GeometryEngine.GeodesicSector(param, SpatialReferences.WGS84);
  // geometry.IsEmpty = false

  Polygon polygon = geometry as Polygon;
  // polygon.PointCount = 68
  // polygon.PartCount = 1
});

    now:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  GeodesicSectorParameter param = new GeodesicSectorParameter();
  param.ArcVertexCount = 50;
  param.AxisDirection = Math.PI / 4;
  param.Center = new Coordinate2D(0, 0);
  param.LinearUnit = LinearUnit.Meters;
  param.OutGeometryType = GeometryType.Polygon;
  param.RadiusVertexCount = 10;
  param.SectorAngle = 5 * Math.PI / 3;
  param.SemiAxis1Length = 100000;
  param.SemiAxis2Length = 20000;
  param.StartDirection = 11 * Math.PI / 6;

  Geometry geometry = GeometryEngine.Instance.GeodesicSector(param, SpatialReferences.WGS84);
  // geometry.IsEmpty = false

  Polygon polygon = geometry as Polygon;
  // polygon.PointCount = 68
  // polygon.PartCount = 1
});

Retrieve coordinate systems

    before:

// get all the geographic coordinate systems
IReadOnlyList<CoordinateSystemListEntry> gcs_list = GeometryEngine.GetPredefinedCoordinateSystemList(CoordinateSystemFilter.GeographicCoordinateSystem);

// get the projected coordinate systems
IReadOnlyList<CoordinateSystemListEntry> proj_list = GeometryEngine.GetPredefinedCoordinateSystemList(CoordinateSystemFilter.ProjectedCoordinateSystem);

// get the vertical coordinate systems
IReadOnlyList<CoordinateSystemListEntry> vert_list = GeometryEngine.GetPredefinedCoordinateSystemList(CoordinateSystemFilter.VerticalCoordinateSystem);

// get geographic and projected coordinate systems
IReadOnlyList<CoordinateSystemListEntry> combined_list = GeometryEngine.GetPredefinedCoordinateSystemList(CoordinateSystemFilter.GeographicCoordinateSystem | CoordinateSystemFilter.ProjectedCoordinateSystem);

    now:

// get all the geographic coordinate systems
IReadOnlyList<CoordinateSystemListEntry> gcs_list = GeometryEngine.Instance.GetPredefinedCoordinateSystemList(CoordinateSystemFilter.GeographicCoordinateSystem);

// get the projected coordinate systems
IReadOnlyList<CoordinateSystemListEntry> proj_list = GeometryEngine.Instance.GetPredefinedCoordinateSystemList(CoordinateSystemFilter.ProjectedCoordinateSystem);

// get the vertical coordinate systems
IReadOnlyList<CoordinateSystemListEntry> vert_list = GeometryEngine.Instance.GetPredefinedCoordinateSystemList(CoordinateSystemFilter.VerticalCoordinateSystem);

// get geographic and projected coordinate systems
IReadOnlyList<CoordinateSystemListEntry> combined_list = GeometryEngine.Instance.GetPredefinedCoordinateSystemList(CoordinateSystemFilter.GeographicCoordinateSystem | CoordinateSystemFilter.ProjectedCoordinateSystem);

Get Sub-curve of a polyline or polygon

    before:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  SpatialReference sr = SpatialReferences.WGS84;

  List<Coordinate> coords = new List<Coordinate>()
  {
    new Coordinate(-111, 72),
    new Coordinate(-108, 68),
    new Coordinate(-114, 68)
  };

  Polyline polyline = PolylineBuilder.CreatePolyline(coords, sr);

  Polyline subCurve = GeometryEngine.GetSubCurve(polyline, 0, 5, GeometryEngine.AsRatioOrLength.AsLength);
  // subCurve.PartCount = 1
  // subCurve.PointCount = 2

  ReadOnlyPointCollection points = subCurve.Points;
  // points[0] = -111, 72
  // points[1] = -108, 68

  subCurve = GeometryEngine.GetSubCurve(polyline, 0, 0.5, GeometryEngine.AsRatioOrLength.AsRatio);
  // subCurve.PointCount = 3

  points = subCurve.Points;
  // points[0] = -111, 72
  // points[1] = -108, 68
  // points[2] = -108.5, 68



  List<Coordinate> coords3D = new List<Coordinate>()
  {
    new Coordinate(0, 0, 0),
    new Coordinate(0, 1, 1),
    new Coordinate(1, 1, 2),
    new Coordinate(1, 0, 3)
  };

  Polygon polygon = PolygonBuilder.CreatePolygon(coords3D, sr);

  subCurve = GeometryEngine.GetSubCurve3D(polygon, 0, 1, GeometryEngine.AsRatioOrLength.AsLength);
  // subCurve.HasZ = true

  points = subCurve.Points;
  // points.Count = 2
  // points[0] = 0, 0, 0
  // points[1] = 0, 0.70710678118654746, 0.70710678118654746

});

    now:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  SpatialReference sr = SpatialReferences.WGS84;

  List<Coordinate2D> coords = new List<Coordinate2D>()
  {
    new Coordinate2D(-111, 72),
    new Coordinate2D(-108, 68),
    new Coordinate2D(-114, 68)
  };

  Polyline polyline = PolylineBuilder.CreatePolyline(coords, sr);

  Polyline subCurve = GeometryEngine.Instance.GetSubCurve(polyline, 0, 5, AsRatioOrLength.AsLength);
  // subCurve.PartCount = 1
  // subCurve.PointCount = 2

  ReadOnlyPointCollection points = subCurve.Points;
  // points[0] = -111, 72
  // points[1] = -108, 68

  subCurve = GeometryEngine.Instance.GetSubCurve(polyline, 0, 0.5, AsRatioOrLength.AsRatio);
  // subCurve.PointCount = 3

  points = subCurve.Points;
  // points[0] = -111, 72
  // points[1] = -108, 68
  // points[2] = -108.5, 68


  List<Coordinate3D> coords3D = new List<Coordinate3D>()
  {
    new Coordinate3D(0, 0, 0),
    new Coordinate3D(0, 1, 1),
    new Coordinate3D(1, 1, 2),
    new Coordinate3D(1, 0, 3)
  };

  Polygon polygon = PolygonBuilder.CreatePolygon(coords3D, sr);

  subCurve = GeometryEngine.Instance.GetSubCurve3D(polygon, 0, 1, AsRatioOrLength.AsLength);
  // subCurve.HasZ = true

  points = subCurve.Points;
  // points.Count = 2
  // points[0] = 0, 0, 0
  // points[1] = 0, 0.70710678118654746, 0.70710678118654746

});

Intersection between two Polylines

    before:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  // determine intersection between two polylines

  List<MapPoint> pts = new List<MapPoint>();
  pts.Add(MapPointBuilder.CreateMapPoint(1.0, 1.0));
  pts.Add(MapPointBuilder.CreateMapPoint(3.0, 3.0));
  pts.Add(MapPointBuilder.CreateMapPoint(5.0, 1.0));

  Polyline line1 = PolylineBuilder.CreatePolyline(pts);

  List<MapPoint> pts2 = new List<MapPoint>();
  pts2.Add(MapPointBuilder.CreateMapPoint(1.0, 3.0));
  pts2.Add(MapPointBuilder.CreateMapPoint(3.0, 1.0));
  pts2.Add(MapPointBuilder.CreateMapPoint(5.0, 3.0));

  Polyline line2 = PolylineBuilder.CreatePolyline(pts2);

  bool intersects = GeometryEngine.Intersects(line1, line2);    // intersects = true
  Geometry g = GeometryEngine.Intersection(line1, line2, GeometryDimension.esriGeometry0Dimension);
  Multipoint resultMultipoint = g as Multipoint;

  // result is a multiPoint that intersects at (2,2) and (4,2)
});

    now:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  // determine intersection between two polylines

  List<MapPoint> pts = new List<MapPoint>();
  pts.Add(MapPointBuilder.CreateMapPoint(1.0, 1.0));
  pts.Add(MapPointBuilder.CreateMapPoint(3.0, 3.0));
  pts.Add(MapPointBuilder.CreateMapPoint(5.0, 1.0));

  Polyline line1 = PolylineBuilder.CreatePolyline(pts);

  List<MapPoint> pts2 = new List<MapPoint>();
  pts2.Add(MapPointBuilder.CreateMapPoint(1.0, 3.0));
  pts2.Add(MapPointBuilder.CreateMapPoint(3.0, 1.0));
  pts2.Add(MapPointBuilder.CreateMapPoint(5.0, 3.0));

  Polyline line2 = PolylineBuilder.CreatePolyline(pts2);

  bool intersects = GeometryEngine.Instance.Intersects(line1, line2);    // intersects = true
  Geometry g = GeometryEngine.Instance.Intersection(line1, line2, GeometryDimension.esriGeometry0Dimension);
  Multipoint resultMultipoint = g as Multipoint;

  // result is a multiPoint that intersects at (2,2) and (4,2)
});

Intersection between two Polygons

    before:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  // determine intersection between two polygons

  Envelope env1 = EnvelopeBuilder.CreateEnvelope(new Coordinate2D(3.0, 2.0), new Coordinate2D(6.0, 6.0));
  Polygon poly1 = PolygonBuilder.CreatePolygon(env1);

  Envelope env2 = EnvelopeBuilder.CreateEnvelope(new Coordinate2D(1.0, 1.0), new Coordinate2D(4.0, 4.0));
  Polygon poly2 = PolygonBuilder.CreatePolygon(env2);

  Polygon polyResult = GeometryEngine.Intersection(poly1, poly2) as Polygon;
});

    now:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  // determine intersection between two polygons

  Envelope env1 = EnvelopeBuilder.CreateEnvelope(new Coordinate2D(3.0, 2.0), new Coordinate2D(6.0, 6.0));
  Polygon poly1 = PolygonBuilder.CreatePolygon(env1);

  Envelope env2 = EnvelopeBuilder.CreateEnvelope(new Coordinate2D(1.0, 1.0), new Coordinate2D(4.0, 4.0));
  Polygon poly2 = PolygonBuilder.CreatePolygon(env2);

  Polygon polyResult = GeometryEngine.Instance.Intersection(poly1, poly2) as Polygon;
});

Determine label point for a Polygon

    before:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  // create a polygon
  List<Coordinate2D> list2D = new List<Coordinate2D>();
  list2D.Add(new Coordinate2D(1.0, 1.0));
  list2D.Add(new Coordinate2D(1.0, 2.0));
  list2D.Add(new Coordinate2D(2.0, 2.0));
  list2D.Add(new Coordinate2D(2.0, 1.0));

  Polygon polygon = PolygonBuilder.CreatePolygon(list2D);
  bool isSimple = GeometryEngine.IsSimpleAsFeature(polygon);
  MapPoint pt = GeometryEngine.LabelPoint(polygon); 
});

    now:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  // create a polygon
  List<Coordinate2D> list2D = new List<Coordinate2D>();
  list2D.Add(new Coordinate2D(1.0, 1.0));
  list2D.Add(new Coordinate2D(1.0, 2.0));
  list2D.Add(new Coordinate2D(2.0, 2.0));
  list2D.Add(new Coordinate2D(2.0, 1.0));

  Polygon polygon = PolygonBuilder.CreatePolygon(list2D);
  bool isSimple = GeometryEngine.Instance.IsSimpleAsFeature(polygon);
  MapPoint pt = GeometryEngine.Instance.LabelPoint(polygon); 
});

Move a MapPoint

    before:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  MapPoint pt = MapPointBuilder.CreateMapPoint(1.0, 3.0);

  MapPoint ptResult = GeometryEngine.Move(pt, -3.5, 2.5) as MapPoint;
  // ptResult is (-2.5, 5.5)
});

    now:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  MapPoint pt = MapPointBuilder.CreateMapPoint(1.0, 3.0);

  MapPoint ptResult = GeometryEngine.Instance.Move(pt, -3.5, 2.5) as MapPoint;
  // ptResult is (-2.5, 5.5)
});

Move a z-aware MapPoint

    before:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  MapPoint zPt = MapPointBuilder.CreateMapPoint(1.0, 3.0, 2.0);
  MapPoint zPtResult = GeometryEngine.Move(zPt, 4, 0.25, 0.5) as MapPoint;
  // zPtResult is (5.0, 3.25, 2.5);
});

    now:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  MapPoint zPt = MapPointBuilder.CreateMapPoint(1.0, 3.0, 2.0);
  MapPoint zPtResult = GeometryEngine.Instance.Move(zPt, 4, 0.25, 0.5) as MapPoint;
  // zPtResult is (5.0, 3.25, 2.5);
});

Move a Polyline

    before:

ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  List<MapPoint> pts = new List<MapPoint>();
  pts.Add(MapPointBuilder.CreateMapPoint(1.0, 1.0, 3.0));
  pts.Add(MapPointBuilder.CreateMapPoint(3.0, 3.0, 3.0));
  pts.Add(MapPointBuilder.CreateMapPoint(3, 2, 3.0));
  pts.Add(MapPointBuilder.CreateMapPoint(4.0, 2.0, 3.0));

  Polyline polyline = PolylineBuilder.CreatePolyline(pts);

  Geometry g = GeometryEngine.Move(polyline, 3, 2);
  Polyline polylineResult = g as Polyline;

  // polylineResult.Points[0] = 4.0, 3.0, 3.0
  // polylineResult.Points[1] = 6.0, 5.0, 3.0
  // polylineResult.Points[2] = 6.0, 4.0, 3.0
  // polylineResult.Points[3] = 7.0, 4.0, 3.0
});

    now:

ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  List<MapPoint> pts = new List<MapPoint>();
  pts.Add(MapPointBuilder.CreateMapPoint(1.0, 1.0, 3.0));
  pts.Add(MapPointBuilder.CreateMapPoint(3.0, 3.0, 3.0));
  pts.Add(MapPointBuilder.CreateMapPoint(3, 2, 3.0));
  pts.Add(MapPointBuilder.CreateMapPoint(4.0, 2.0, 3.0));

  Polyline polyline = PolylineBuilder.CreatePolyline(pts);

  Geometry g = GeometryEngine.Instance.Move(polyline, 3, 2);
  Polyline polylineResult = g as Polyline;

  // polylineResult.Points[0] = 4.0, 3.0, 3.0
  // polylineResult.Points[1] = 6.0, 5.0, 3.0
  // polylineResult.Points[2] = 6.0, 4.0, 3.0
  // polylineResult.Points[3] = 7.0, 4.0, 3.0
});

MovePointAlongLine

    before:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  LineSegment line = LineBuilder.CreateLineSegment(MapPointBuilder.CreateMapPoint(0, 3), MapPointBuilder.CreateMapPoint(5.0, 3.0));
  Polyline polyline = PolylineBuilder.CreatePolyline(line);
  bool simple = GeometryEngine.IsSimpleAsFeature(polyline);

  // ratio = false
  MapPoint pt = GeometryEngine.MovePointAlongLine(polyline, 1.0, false, 0.0, GeometryEngine.SegmentExtension.NoExtension);
  // pt = 1.0, 3.0

  pt = GeometryEngine.MovePointAlongLine(polyline, 1.0, false, -1.0, GeometryEngine.SegmentExtension.NoExtension);
  // pt = 1.0, 4.0

  pt = GeometryEngine.MovePointAlongLine(polyline, 1.0, false, 2.0, GeometryEngine.SegmentExtension.NoExtension);
  // pt = 1.0, 1.0

  // ratio = true
  pt = GeometryEngine.MovePointAlongLine(polyline, 0.5, true, 0, GeometryEngine.SegmentExtension.NoExtension);
  // pt = 2.5, 3.0

  // move past the line
  pt = GeometryEngine.MovePointAlongLine(polyline, 7, false, 0, GeometryEngine.SegmentExtension.NoExtension);
  // pt = 5.0, 3.0

  // move past the line with extension at "to" point
  pt = GeometryEngine.MovePointAlongLine(polyline, 7, false, 0, GeometryEngine.SegmentExtension.ExtendEmbeddedAtTo);
  // pt = 7.0, 3.0

  // negative distance with extension at "from" point
  pt = GeometryEngine.MovePointAlongLine(polyline, -2, false, 0, GeometryEngine.SegmentExtension.ExtendEmbeddedAtFrom);
  // pt = -2.0, 3.0

  // ratio = true
  pt = GeometryEngine.MovePointAlongLine(polyline, 0.5, true, 0, GeometryEngine.SegmentExtension.NoExtension);
  // pt = 2.5, 3.0


  // line with Z
  List<Coordinate> coords3D = new List<Coordinate> { new Coordinate(0, 0, 0), new Coordinate(1113195, 1118890, 5000) };
  Polyline polylineZ = PolylineBuilder.CreatePolyline(coords3D, SpatialReferences.WebMercator);
  // polylineZ.HasZ = true

  // ratio = true, no offset
  pt = GeometryEngine.MovePointAlongLine(polylineZ, 0.5, true, 0, GeometryEngine.SegmentExtension.NoExtension);
  // pt.X = 556597.5
  // pt.Y = 559445
  // pt.Z = 2500

  // ratio = true, past the line with "to" extension, no offset
  pt = GeometryEngine.MovePointAlongLine(polylineZ, 1.5, true, 0, GeometryEngine.SegmentExtension.ExtendEmbeddedAtTo);
  // pt.X = 1669792.5
  // pt.Y = 1678335
  // pt.Z = 7500

  // ratio = true, negative distance past the line with no extension, no offset
  pt = GeometryEngine.MovePointAlongLine(polylineZ, -1.5, true, 0, GeometryEngine.SegmentExtension.NoExtension);
  // pt.X = 0
  // pt.Y = 0
  // pt.Z = -7500


  // polyline with Z but 2d distance = 0
  MapPoint pt3 = MapPointBuilder.CreateMapPoint(5, 5, 0);
  MapPoint pt4 = MapPointBuilder.CreateMapPoint(5, 5, 10);
  List<MapPoint> pts = new List<MapPoint>() { pt3, pt4 };

  PolylineBuilder pb = new PolylineBuilder();
  pb.SetEmpty();
  pb.AddPart(pts);
  pb.HasZ = true;
  polyline = pb.ToGeometry();
  // polyline.Length3D = 10
  // polyline.Length = 0

  MapPoint result = GeometryEngine.MovePointAlongLine(polyline, 2, false, 0, GeometryEngine.SegmentExtension.NoExtension);
  // result = 5, 5, 2


  // polyline with length2d = 0 and length3d = 0
  MapPoint pt5 = MapPointBuilder.CreateMapPoint(5, 5, 10);
  MapPoint pt6 = MapPointBuilder.CreateMapPoint(5, 5, 10);
  pts.Clear();
  pts.Add(pt5);
  pts.Add(pt6);

  pb.SetEmpty();
  pb.AddPart(pts);
  pb.HasZ = true;
  polyline = pb.ToGeometry();
  // polyline.Length3D = 0
  // polyline.Length = 0

  result = GeometryEngine.MovePointAlongLine(polyline, 3, true, 0, GeometryEngine.SegmentExtension.NoExtension);
  // result = 5, 5, 10

  result = GeometryEngine.MovePointAlongLine(polyline, 3, true, 0, GeometryEngine.SegmentExtension.ExtendEmbeddedAtFrom);
  // result = 5, 5, 10


  // polyline with Z and M
  List<MapPoint> inputPoints = new List<MapPoint>()
  {
    MapPointBuilder.CreateMapPoint(1, 2, 3, 4),
    MapPointBuilder.CreateMapPoint(1, 2, 33, 44),
  };

  Polyline polylineZM = PolylineBuilder.CreatePolyline(inputPoints, SpatialReferences.WGS84);
  // polylineZM.HasZ = true
  // polylineZM.HasM = true

  // ratio = true, no offset
  MapPoint pointAlong = GeometryEngine.MovePointAlongLine(polylineZM, 0.5, true, 0, GeometryEngine.SegmentExtension.NoExtension);
  // pointAlong = 1, 2, 18, 24

  // ratio = true with offset
  pointAlong = GeometryEngine.MovePointAlongLine(polylineZM, 0.2, true, 2.23606797749979, GeometryEngine.SegmentExtension.NoExtension);
  // pointAlong = 1, 2, 9, 12
});

    now:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  LineSegment line = LineBuilder.CreateLineSegment(MapPointBuilder.CreateMapPoint(0, 3), MapPointBuilder.CreateMapPoint(5.0, 3.0));
  Polyline polyline = PolylineBuilder.CreatePolyline(line);
  bool simple = GeometryEngine.Instance.IsSimpleAsFeature(polyline);

  // ratio = false
  MapPoint pt = GeometryEngine.Instance.MovePointAlongLine(polyline, 1.0, false, 0.0, SegmentExtension.NoExtension);
  // pt = 1.0, 3.0

  pt = GeometryEngine.Instance.MovePointAlongLine(polyline, 1.0, false, -1.0, SegmentExtension.NoExtension);
  // pt = 1.0, 4.0

  pt = GeometryEngine.Instance.MovePointAlongLine(polyline, 1.0, false, 2.0, SegmentExtension.NoExtension);
  // pt = 1.0, 1.0

  // ratio = true
  pt = GeometryEngine.Instance.MovePointAlongLine(polyline, 0.5, true, 0, SegmentExtension.NoExtension);
  // pt = 2.5, 3.0

  // move past the line
  pt = GeometryEngine.Instance.MovePointAlongLine(polyline, 7, false, 0, SegmentExtension.NoExtension);
  // pt = 5.0, 3.0

  // move past the line with extension at "to" point
  pt = GeometryEngine.Instance.MovePointAlongLine(polyline, 7, false, 0, SegmentExtension.ExtendEmbeddedAtTo);
  // pt = 7.0, 3.0

  // negative distance with extension at "from" point
  pt = GeometryEngine.Instance.MovePointAlongLine(polyline, -2, false, 0, SegmentExtension.ExtendEmbeddedAtFrom);
  // pt = -2.0, 3.0

  // ratio = true
  pt = GeometryEngine.Instance.MovePointAlongLine(polyline, 0.5, true, 0, SegmentExtension.NoExtension);
  // pt = 2.5, 3.0


  // line with Z
  List<Coordinate3D> coords3D = new List<Coordinate3D> { new Coordinate3D(0, 0, 0), new Coordinate3D(1113195, 1118890, 5000) };
  Polyline polylineZ = PolylineBuilder.CreatePolyline(coords3D, SpatialReferences.WebMercator);
  // polylineZ.HasZ = true

  // ratio = true, no offset
  pt = GeometryEngine.Instance.MovePointAlongLine(polylineZ, 0.5, true, 0, SegmentExtension.NoExtension);
  // pt.X = 556597.5
  // pt.Y = 559445
  // pt.Z = 2500

  // ratio = true, past the line with "to" extension, no offset
  pt = GeometryEngine.Instance.MovePointAlongLine(polylineZ, 1.5, true, 0, SegmentExtension.ExtendEmbeddedAtTo);
  // pt.X = 1669792.5
  // pt.Y = 1678335
  // pt.Z = 7500

  // ratio = true, negative distance past the line with no extension, no offset
  pt = GeometryEngine.Instance.MovePointAlongLine(polylineZ, -1.5, true, 0, SegmentExtension.NoExtension);
  // pt.X = 0
  // pt.Y = 0
  // pt.Z = -7500


  // polyline with Z but 2d distance = 0
  MapPoint pt3 = MapPointBuilder.CreateMapPoint(5, 5, 0);
  MapPoint pt4 = MapPointBuilder.CreateMapPoint(5, 5, 10);
  List<MapPoint> pts = new List<MapPoint>() { pt3, pt4 };

  using (PolylineBuilder pb = new PolylineBuilder())
  {
    pb.SetEmpty();
    pb.AddPart(pts);
    pb.HasZ = true;
    polyline = pb.ToGeometry();
    // polyline.Length3D = 10
    // polyline.Length = 0

    MapPoint result = GeometryEngine.Instance.MovePointAlongLine(polyline, 2, false, 0, SegmentExtension.NoExtension);
    // result = 5, 5, 2

    // polyline with length2d = 0 and length3d = 0
    MapPoint pt5 = MapPointBuilder.CreateMapPoint(5, 5, 10);
    MapPoint pt6 = MapPointBuilder.CreateMapPoint(5, 5, 10);
    pts.Clear();
    pts.Add(pt5);
    pts.Add(pt6);

    pb.SetEmpty();
    pb.AddPart(pts);
    pb.HasZ = true;
    polyline = pb.ToGeometry();
    // polyline.Length3D = 0
    // polyline.Length = 0

    result = GeometryEngine.Instance.MovePointAlongLine(polyline, 3, true, 0, SegmentExtension.NoExtension);
    // result = 5, 5, 10

    result = GeometryEngine.Instance.MovePointAlongLine(polyline, 3, true, 0, SegmentExtension.ExtendEmbeddedAtFrom);
    // result = 5, 5, 10

  }


  // polyline with Z and M
  List<MapPoint> inputPoints = new List<MapPoint>()
  {
    MapPointBuilder.CreateMapPoint(1, 2, 3, 4),
    MapPointBuilder.CreateMapPoint(1, 2, 33, 44),
  };

  Polyline polylineZM = PolylineBuilder.CreatePolyline(inputPoints, SpatialReferences.WGS84);
  // polylineZM.HasZ = true
  // polylineZM.HasM = true

  // ratio = true, no offset
  MapPoint pointAlong = GeometryEngine.Instance.MovePointAlongLine(polylineZM, 0.5, true, 0, SegmentExtension.NoExtension);
  // pointAlong = 1, 2, 18, 24

  // ratio = true with offset
  pointAlong = GeometryEngine.Instance.MovePointAlongLine(polylineZM, 0.2, true, 2.23606797749979, SegmentExtension.NoExtension);
  // pointAlong = 1, 2, 9, 12
});

Nearest Point versus Nearest Vertex

    before:

ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  SpatialReference sr = SpatialReferences.WGS84;
  MapPoint pt = MapPointBuilder.CreateMapPoint(5, 5, sr);

  List<Coordinate> coords = new List<Coordinate>()
  {
    new Coordinate(10, 1),
    new Coordinate(10, -4),
    new Coordinate(0, -4),
    new Coordinate(0, 1),
    new Coordinate(10, 1)
  };

  Polygon polygon = PolygonBuilder.CreatePolygon(coords);

  // find the nearest point in the polygon geomtry to the pt
  GeometryEngine.ProximityResult result = GeometryEngine.NearestPoint(polygon, pt);
  // result.Point = 5, 1
  // result.SegmentIndex = 3
  // result.PartIndex = 0
  // result.PointIndex = null
  //result.Distance = 4
  //result.RightSide = false

  // find the nearest vertex in the polgyon geometry to the pt
  result = GeometryEngine.NearestVertex(polygon, pt);
  // result.Point = 10, 1
  // result.PointIndex = 0
  // result.SegmentIndex = null
  // result.PartIndex = 0
  // result.Distance = Math.Sqrt(41)
  // result.RightSide = false

});

    now:

ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  SpatialReference sr = SpatialReferences.WGS84;
  MapPoint pt = MapPointBuilder.CreateMapPoint(5, 5, sr);

  List<Coordinate2D> coords = new List<Coordinate2D>()
  {
    new Coordinate2D(10, 1),
    new Coordinate2D(10, -4),
    new Coordinate2D(0, -4),
    new Coordinate2D(0, 1),
    new Coordinate2D(10, 1)
  };

  Polygon polygon = PolygonBuilder.CreatePolygon(coords);

  // find the nearest point in the polygon geomtry to the pt
  ProximityResult result = GeometryEngine.Instance.NearestPoint(polygon, pt);
  // result.Point = 5, 1
  // result.SegmentIndex = 3
  // result.PartIndex = 0
  // result.PointIndex = null
  //result.Distance = 4
  //result.RightSide = false

  // find the nearest vertex in the polgyon geometry to the pt
  result = GeometryEngine.Instance.NearestVertex(polygon, pt);
  // result.Point = 10, 1
  // result.PointIndex = 0
  // result.SegmentIndex = null
  // result.PartIndex = 0
  // result.Distance = Math.Sqrt(41)
  // result.RightSide = false

});

Determine Nearest Point in 3D

    before:

ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  MapPoint pt1 = MapPointBuilder.CreateMapPoint(1, 1, 1);
  MapPoint pt2 = MapPointBuilder.CreateMapPoint(2, 2, 2);
  MapPoint pt3 = MapPointBuilder.CreateMapPoint(10, 2, 1);

  //
  // test pt1 to pt2
  //
  GeometryEngine.ProximityResult result = GeometryEngine.NearestPoint3D(pt1, pt2);
  // result.Point = 1,1,1
  // result.Distance = Math.Sqrt(3)
  // result.SegmentIndex = null
  // result.PartIndex = 0
  // result.PointIndex = 0
  // result.RightSide = false

  // 
  // multipoint built from pt1, pt2.   should be closer to pt2
  // 
  MultipointBuilder mpb = new MultipointBuilder(pt1);
  mpb.Add(pt2);
  mpb.HasZ = true;
  Multipoint multipoint = mpb.ToGeometry();
  result = GeometryEngine.NearestPoint3D(multipoint, pt3);

  // result.Point = 2, 2, 2
  // result.Distance = Math.Sqrt(65)
  // result.SegmentIndex = null
  // result.PartIndex = 1
  // result.PointIndex = 1
  // result.RightSide = false
});

    now:

ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  MapPoint pt1 = MapPointBuilder.CreateMapPoint(1, 1, 1);
  MapPoint pt2 = MapPointBuilder.CreateMapPoint(2, 2, 2);
  MapPoint pt3 = MapPointBuilder.CreateMapPoint(10, 2, 1);

  //
  // test pt1 to pt2
  //
  ProximityResult result = GeometryEngine.Instance.NearestPoint3D(pt1, pt2);
  // result.Point = 1,1,1
  // result.Distance = Math.Sqrt(3)
  // result.SegmentIndex = null
  // result.PartIndex = 0
  // result.PointIndex = 0
  // result.RightSide = false

  // 
  // multipoint built from pt1, pt2.   should be closer to pt2
  // 
  using (MultipointBuilder mpb = new MultipointBuilder(pt1))
  {
    mpb.Add(pt2);
    mpb.HasZ = true;
    Multipoint multipoint = mpb.ToGeometry();
    result = GeometryEngine.Instance.NearestPoint3D(multipoint, pt3);

    // result.Point = 2, 2, 2
    // result.Distance = Math.Sqrt(65)
    // result.SegmentIndex = null
    // result.PartIndex = 1
    // result.PointIndex = 1
    // result.RightSide = false
  }
});

Determine if geometries overlap

    before:

ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  MapPoint pt1 = MapPointBuilder.CreateMapPoint(1.5, 1.5);
  MapPoint pt2 = MapPointBuilder.CreateMapPoint(1.25, 1.75);
  MapPoint pt3 = MapPointBuilder.CreateMapPoint(3, 1.5);
  MapPoint pt4 = MapPointBuilder.CreateMapPoint(1.5, 2);

  //
  // point and point overlap
  //
  bool overlaps = GeometryEngine.Overlaps(pt1, pt2);        // overlaps = false
  overlaps = GeometryEngine.Overlaps(pt1, pt1);             // overlaps = false
  // Two geometries overlap if the region of their intersection is of the same dimension as the geometries involved and 
  // is not equivalent to either of the geometries.  

  List<MapPoint> pts = new List<MapPoint>();
  pts.Add(pt1);
  pts.Add(pt2);
  pts.Add(pt3);

  List<MapPoint> pts2 = new List<MapPoint>();
  pts2.Add(pt2);
  pts2.Add(pt3);
  pts2.Add(pt4);

  //
  // pt and line overlap
  //
  Polyline polyline = PolylineBuilder.CreatePolyline(pts);
  bool isSimple = GeometryEngine.IsSimpleAsFeature(polyline);         // isSimple = true
  overlaps = GeometryEngine.Overlaps(polyline, pt1);                  // overlaps = false

  //
  // line and line
  //
  Polyline polyline2 = PolylineBuilder.CreatePolyline(pts2);
  isSimple = GeometryEngine.IsSimpleAsFeature(polyline2);             // isSimple = true
  overlaps = GeometryEngine.Overlaps(polyline, polyline2);            // overlaps = true

});

    now:

ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  MapPoint pt1 = MapPointBuilder.CreateMapPoint(1.5, 1.5);
  MapPoint pt2 = MapPointBuilder.CreateMapPoint(1.25, 1.75);
  MapPoint pt3 = MapPointBuilder.CreateMapPoint(3, 1.5);
  MapPoint pt4 = MapPointBuilder.CreateMapPoint(1.5, 2);

  //
  // point and point overlap
  //
  bool overlaps = GeometryEngine.Instance.Overlaps(pt1, pt2);        // overlaps = false
  overlaps = GeometryEngine.Instance.Overlaps(pt1, pt1);             // overlaps = false
  // Two geometries overlap if the region of their intersection is of the same dimension as the geometries involved and 
  // is not equivalent to either of the geometries.  

  List<MapPoint> pts = new List<MapPoint>();
  pts.Add(pt1);
  pts.Add(pt2);
  pts.Add(pt3);

  List<MapPoint> pts2 = new List<MapPoint>();
  pts2.Add(pt2);
  pts2.Add(pt3);
  pts2.Add(pt4);

  //
  // pt and line overlap
  //
  Polyline polyline = PolylineBuilder.CreatePolyline(pts);
  bool isSimple = GeometryEngine.Instance.IsSimpleAsFeature(polyline);         // isSimple = true
  overlaps = GeometryEngine.Instance.Overlaps(polyline, pt1);                  // overlaps = false

  //
  // line and line
  //
  Polyline polyline2 = PolylineBuilder.CreatePolyline(pts2);
  isSimple = GeometryEngine.Instance.IsSimpleAsFeature(polyline2);             // isSimple = true
  overlaps = GeometryEngine.Instance.Overlaps(polyline, polyline2);            // overlaps = true

});

Project from WGS84 to WebMercator

    before:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  MapPoint pt = MapPointBuilder.CreateMapPoint(1.0, 3.0, SpatialReferences.WGS84);
  Geometry result = GeometryEngine.Project(pt, SpatialReferences.WebMercator);
  MapPoint projectedPt = result as MapPoint;
});

    now:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  MapPoint pt = MapPointBuilder.CreateMapPoint(1.0, 3.0, SpatialReferences.WGS84);
  Geometry result = GeometryEngine.Instance.Project(pt, SpatialReferences.WebMercator);
  MapPoint projectedPt = result as MapPoint;
});

Project from WGS84

    before:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  // create the polygon
  List<MapPoint> pts = new List<MapPoint>();
  pts.Add(MapPointBuilder.CreateMapPoint(1.0, 1.0, SpatialReferences.WGS84));
  pts.Add(MapPointBuilder.CreateMapPoint(1.0, 2.0, SpatialReferences.WGS84));
  pts.Add(MapPointBuilder.CreateMapPoint(2.0, 2.0, SpatialReferences.WGS84));
  pts.Add(MapPointBuilder.CreateMapPoint(2.0, 1.0, SpatialReferences.WGS84));

  Polygon polygon = PolygonBuilder.CreatePolygon(pts);
  // ensure it is simple
  bool isSimple = GeometryEngine.IsSimpleAsFeature(polygon);

  // create the spatial reference to project to
  SpatialReference northPole = SpatialReferenceBuilder.CreateSpatialReference(102018);   // north pole stereographic 

  // project
  Geometry g = GeometryEngine.Project(polygon, northPole);
});

    now:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  // create the polygon
  List<MapPoint> pts = new List<MapPoint>();
  pts.Add(MapPointBuilder.CreateMapPoint(1.0, 1.0, SpatialReferences.WGS84));
  pts.Add(MapPointBuilder.CreateMapPoint(1.0, 2.0, SpatialReferences.WGS84));
  pts.Add(MapPointBuilder.CreateMapPoint(2.0, 2.0, SpatialReferences.WGS84));
  pts.Add(MapPointBuilder.CreateMapPoint(2.0, 1.0, SpatialReferences.WGS84));

  Polygon polygon = PolygonBuilder.CreatePolygon(pts);
  // ensure it is simple
  bool isSimple = GeometryEngine.Instance.IsSimpleAsFeature(polygon);

  // create the spatial reference to project to
  SpatialReference northPole = SpatialReferenceBuilder.CreateSpatialReference(102018);   // north pole stereographic 

  // project
  Geometry g = GeometryEngine.Instance.Project(polygon, northPole);
});

QueryPointAndDistance

    before:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  // Horizontal line segment
  List<MapPoint> linePts = new List<MapPoint>();
  linePts.Add(MapPointBuilder.CreateMapPoint(1.0, 1.0, SpatialReferences.WGS84));
  linePts.Add(MapPointBuilder.CreateMapPoint(11.0, 1.0, SpatialReferences.WGS84));
  Polyline polyline = PolylineBuilder.CreatePolyline(linePts);
  bool isSimple = GeometryEngine.IsSimpleAsFeature(polyline);

  // Don't extent the segment
  GeometryEngine.SegmentExtension extension = GeometryEngine.SegmentExtension.NoExtension;

  // A point on the line segment
  MapPoint inPoint = MapPointBuilder.CreateMapPoint(2, 1, SpatialReferences.WGS84);

  double distanceAlongCurve, distanceFromCurve;
  GeometryEngine.LeftOrRightSide whichSide;
  GeometryEngine.AsRatioOrLength asRatioOrLength = GeometryEngine.AsRatioOrLength.AsLength;

  MapPoint outPoint = GeometryEngine.QueryPointAndDistance(polyline, extension, inPoint, asRatioOrLength, out distanceAlongCurve, out distanceFromCurve, out whichSide);
  // outPoint = 2, 1
  // distanceAlongCurve = 1
  // distanceFromCurve = 0
  // whichSide = GeometryEngine.LeftOrRightSide.LeftSide


  // Extend infinitely in both directions
  extension = GeometryEngine.SegmentExtension.ExtendTangents;

  // A point on the left side
  inPoint = MapPointBuilder.CreateMapPoint(16, 6, SpatialReferences.WGS84);
  asRatioOrLength = GeometryEngine.AsRatioOrLength.AsRatio;

  outPoint = GeometryEngine.QueryPointAndDistance(polyline, extension, inPoint, asRatioOrLength, out distanceAlongCurve, out distanceFromCurve, out whichSide);
  // outPoint = 16, 1
  // distanceAlongCurve = 1.5
  // distanceFromCurve = 5
  // whichSide = GeometryEngine.LeftOrRightSide.LeftSide

});

    now:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  // Horizontal line segment
  List<MapPoint> linePts = new List<MapPoint>();
  linePts.Add(MapPointBuilder.CreateMapPoint(1.0, 1.0, SpatialReferences.WGS84));
  linePts.Add(MapPointBuilder.CreateMapPoint(11.0, 1.0, SpatialReferences.WGS84));
  Polyline polyline = PolylineBuilder.CreatePolyline(linePts);
  bool isSimple = GeometryEngine.Instance.IsSimpleAsFeature(polyline);

  // Don't extent the segment
  SegmentExtension extension = SegmentExtension.NoExtension;

  // A point on the line segment
  MapPoint inPoint = MapPointBuilder.CreateMapPoint(2, 1, SpatialReferences.WGS84);

  double distanceAlongCurve, distanceFromCurve;
  LeftOrRightSide whichSide;
  AsRatioOrLength asRatioOrLength = AsRatioOrLength.AsLength;

  MapPoint outPoint = GeometryEngine.Instance.QueryPointAndDistance(polyline, extension, inPoint, asRatioOrLength, out distanceAlongCurve, out distanceFromCurve, out whichSide);
  // outPoint = 2, 1
  // distanceAlongCurve = 1
  // distanceFromCurve = 0
  // whichSide = GeometryEngine.Instance.LeftOrRightSide.LeftSide


  // Extend infinitely in both directions
  extension = SegmentExtension.ExtendTangents;

  // A point on the left side
  inPoint = MapPointBuilder.CreateMapPoint(16, 6, SpatialReferences.WGS84);
  asRatioOrLength = AsRatioOrLength.AsRatio;

  outPoint = GeometryEngine.Instance.QueryPointAndDistance(polyline, extension, inPoint, asRatioOrLength, out distanceAlongCurve, out distanceFromCurve, out whichSide);
  // outPoint = 16, 1
  // distanceAlongCurve = 1.5
  // distanceFromCurve = 5
  // whichSide = GeometryEngine.Instance.LeftOrRightSide.LeftSide

});

Determine relationship between two geometries

    before:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  // set up some geometries

  // points
  MapPoint point0 = MapPointBuilder.CreateMapPoint(0, 0, SpatialReferences.WGS84);
  MapPoint point1 = MapPointBuilder.CreateMapPoint(1, 1, SpatialReferences.WGS84);
  MapPoint point2 = MapPointBuilder.CreateMapPoint(-5, 5, SpatialReferences.WGS84);

  // multipoint
  List<MapPoint> points = new List<MapPoint>() { point0, point1, point2 };
  Multipoint multipoint = MultipointBuilder.CreateMultipoint(points, SpatialReferences.WGS84);

  // polygon 
  List<Coordinate2D> polygonCoords = new List<Coordinate2D>()
  {
    new Coordinate2D(-10, 0),
    new Coordinate2D(0, 10),
    new Coordinate2D(10, 0),
    new Coordinate2D(-10, 0)
  };
  Polygon polygon = PolygonBuilder.CreatePolygon(polygonCoords, SpatialReferences.WGS84);

  // polylines
  Polyline polyline1 = PolylineBuilder.CreatePolyline(LineBuilder.CreateLineSegment(new Coordinate(-9.1, 0.1), new Coordinate(0, 9)), SpatialReferences.WGS84);
  Polyline polyline2 = PolylineBuilder.CreatePolyline(LineBuilder.CreateLineSegment(new Coordinate(-5, 5), new Coordinate(0, 5)), SpatialReferences.WGS84);
  Polyline polyline3 = PolylineBuilder.CreatePolyline(LineBuilder.CreateLineSegment(new Coordinate(2.09, -2.04), new Coordinate(5, 10)), SpatialReferences.WGS84);
  Polyline polyline4 = PolylineBuilder.CreatePolyline(LineBuilder.CreateLineSegment(new Coordinate(10, -5), new Coordinate(10, 5)), SpatialReferences.WGS84);

  List<Segment> segments = new List<Segment>()
  {
    LineBuilder.CreateLineSegment(new Coordinate(5.05, -2.87), new Coordinate(6.35, 1.57)),
    LineBuilder.CreateLineSegment(new Coordinate(6.35, 1.57), new Coordinate(4.13, 2.59)),
    LineBuilder.CreateLineSegment(new Coordinate(4.13, 2.59), new Coordinate(5, 5))
  };
  Polyline polyline5 = PolylineBuilder.CreatePolyline(segments, SpatialReferences.WGS84);

  segments.Add(LineBuilder.CreateLineSegment(new Coordinate(5, 5), new Coordinate(10, 10)));

  Polyline polyline6 = PolylineBuilder.CreatePolyline(segments, SpatialReferences.WGS84);
  Polyline polyline7 = PolylineBuilder.CreatePolyline(polyline5);
  Polyline polyline8 = PolylineBuilder.CreatePolyline(LineBuilder.CreateLineSegment(new Coordinate(5, 5), new Coordinate(10, 10)), SpatialReferences.WGS84);

  segments.Clear();
  segments.Add(LineBuilder.CreateLineSegment(new Coordinate(0.6, 3.5), new Coordinate(0.7, 7)));
  segments.Add(LineBuilder.CreateLineSegment(new Coordinate(0.7, 7), new Coordinate(3, 9)));

  Polyline polyline9 = PolylineBuilder.CreatePolyline(segments, SpatialReferences.WGS84);

  // now do the Related tests

  // Interior/Interior Intersects
  string scl = "T********";
  bool related = GeometryEngine.Relate(polygon, polyline1, scl);     // related = true
  related = GeometryEngine.Relate(point0, point1, scl);              // related = false
  related = GeometryEngine.Relate(point0, multipoint, scl);          // related = true
  related = GeometryEngine.Relate(multipoint, polygon, scl);         // related = true
  related = GeometryEngine.Relate(multipoint, polyline1, scl);       // related = false
  related = GeometryEngine.Relate(polyline2, point2, scl);           // related = false
  related = GeometryEngine.Relate(point1, polygon, scl);             // related = true

  // Interior/Boundary Intersects
  scl = "*T*******";
  related = GeometryEngine.Relate(polygon, polyline2, scl);          // related = true
  related = GeometryEngine.Relate(polygon, polyline3, scl);          // related = false
  related = GeometryEngine.Relate(point1, polygon, scl);             // related = false

  // Boundary/Boundary Interior intersects
  scl = "***T*****";
  related = GeometryEngine.Relate(polygon, polyline4, scl);          // related = true

  // Overlaps Dim1
  scl = "1*T***T**";
  related = GeometryEngine.Relate(polygon, polyline5, scl);          // related = true

  // Crosses Area/Line (LineB crosses PolygonA)
  scl = "1020F1102";
  related = GeometryEngine.Relate(polygon, polyline6, scl);          // related = false
  related = GeometryEngine.Relate(polygon, polyline9, scl);          // related = true

  // Boundary/Boundary Touches
  scl = "F***T****";
  related = GeometryEngine.Relate(polygon, polyline7, scl);          // related = false
  related = GeometryEngine.Relate(polygon, polyline8, scl);          // related = true
});

    now:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  // set up some geometries

  // points
  MapPoint point0 = MapPointBuilder.CreateMapPoint(0, 0, SpatialReferences.WGS84);
  MapPoint point1 = MapPointBuilder.CreateMapPoint(1, 1, SpatialReferences.WGS84);
  MapPoint point2 = MapPointBuilder.CreateMapPoint(-5, 5, SpatialReferences.WGS84);

  // multipoint
  List<MapPoint> points = new List<MapPoint>() { point0, point1, point2 };
  Multipoint multipoint = MultipointBuilder.CreateMultipoint(points, SpatialReferences.WGS84);

  // polygon 
  List<Coordinate2D> polygonCoords = new List<Coordinate2D>()
  {
    new Coordinate2D(-10, 0),
    new Coordinate2D(0, 10),
    new Coordinate2D(10, 0),
    new Coordinate2D(-10, 0)
  };
  Polygon polygon = PolygonBuilder.CreatePolygon(polygonCoords, SpatialReferences.WGS84);

  // polylines
  Polyline polyline1 = PolylineBuilder.CreatePolyline(LineBuilder.CreateLineSegment(new Coordinate2D(-9.1, 0.1), new Coordinate2D(0, 9)), SpatialReferences.WGS84);
  Polyline polyline2 = PolylineBuilder.CreatePolyline(LineBuilder.CreateLineSegment(new Coordinate2D(-5, 5), new Coordinate2D(0, 5)), SpatialReferences.WGS84);
  Polyline polyline3 = PolylineBuilder.CreatePolyline(LineBuilder.CreateLineSegment(new Coordinate2D(2.09, -2.04), new Coordinate2D(5, 10)), SpatialReferences.WGS84);
  Polyline polyline4 = PolylineBuilder.CreatePolyline(LineBuilder.CreateLineSegment(new Coordinate2D(10, -5), new Coordinate2D(10, 5)), SpatialReferences.WGS84);

  List<Segment> segments = new List<Segment>()
  {
    LineBuilder.CreateLineSegment(new Coordinate2D(5.05, -2.87), new Coordinate2D(6.35, 1.57)),
    LineBuilder.CreateLineSegment(new Coordinate2D(6.35, 1.57), new Coordinate2D(4.13, 2.59)),
    LineBuilder.CreateLineSegment(new Coordinate2D(4.13, 2.59), new Coordinate2D(5, 5))
  };
  Polyline polyline5 = PolylineBuilder.CreatePolyline(segments, SpatialReferences.WGS84);

  segments.Add(LineBuilder.CreateLineSegment(new Coordinate2D(5, 5), new Coordinate2D(10, 10)));

  Polyline polyline6 = PolylineBuilder.CreatePolyline(segments, SpatialReferences.WGS84);
  Polyline polyline7 = PolylineBuilder.CreatePolyline(polyline5);
  Polyline polyline8 = PolylineBuilder.CreatePolyline(LineBuilder.CreateLineSegment(new Coordinate2D(5, 5), new Coordinate2D(10, 10)), SpatialReferences.WGS84);

  segments.Clear();
  segments.Add(LineBuilder.CreateLineSegment(new Coordinate2D(0.6, 3.5), new Coordinate2D(0.7, 7)));
  segments.Add(LineBuilder.CreateLineSegment(new Coordinate2D(0.7, 7), new Coordinate2D(3, 9)));

  Polyline polyline9 = PolylineBuilder.CreatePolyline(segments, SpatialReferences.WGS84);

  // now do the Related tests

  // Interior/Interior Intersects
  string scl = "T********";
  bool related = GeometryEngine.Instance.Relate(polygon, polyline1, scl);     // related = true
  related = GeometryEngine.Instance.Relate(point0, point1, scl);              // related = false
  related = GeometryEngine.Instance.Relate(point0, multipoint, scl);          // related = true
  related = GeometryEngine.Instance.Relate(multipoint, polygon, scl);         // related = true
  related = GeometryEngine.Instance.Relate(multipoint, polyline1, scl);       // related = false
  related = GeometryEngine.Instance.Relate(polyline2, point2, scl);           // related = false
  related = GeometryEngine.Instance.Relate(point1, polygon, scl);             // related = true

  // Interior/Boundary Intersects
  scl = "*T*******";
  related = GeometryEngine.Instance.Relate(polygon, polyline2, scl);          // related = true
  related = GeometryEngine.Instance.Relate(polygon, polyline3, scl);          // related = false
  related = GeometryEngine.Instance.Relate(point1, polygon, scl);             // related = false

  // Boundary/Boundary Interior intersects
  scl = "***T*****";
  related = GeometryEngine.Instance.Relate(polygon, polyline4, scl);          // related = true

  // Overlaps Dim1
  scl = "1*T***T**";
  related = GeometryEngine.Instance.Relate(polygon, polyline5, scl);          // related = true

  // Crosses Area/Line (LineB crosses PolygonA)
  scl = "1020F1102";
  related = GeometryEngine.Instance.Relate(polygon, polyline6, scl);          // related = false
  related = GeometryEngine.Instance.Relate(polygon, polyline9, scl);          // related = true

  // Boundary/Boundary Touches
  scl = "F***T****";
  related = GeometryEngine.Instance.Relate(polygon, polyline7, scl);          // related = false
  related = GeometryEngine.Instance.Relate(polygon, polyline8, scl);          // related = true
});

Replace NaN Zs in a polygon

    before:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  List<Coordinate> coordsZ = new List<Coordinate>() 
  { 
    new Coordinate(1, 2, double.NaN), 
    new Coordinate(4, 5, 3), 
    new Coordinate(7, 8, double.NaN) 
  };

  Polygon polygon = PolygonBuilder.CreatePolygon(coordsZ);
  // polygon.HasZ = true

  Polygon polygonZReplaced = GeometryEngine.ReplaceNaNZs(polygon, -1) as Polygon;

  // polygonZReplaced.Points[0].Z = -1
  // polygonZReplaced.Points[1].Z = 3
  // polygonZReplaced.Points[2].Z = -1
});

    now:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  List<Coordinate3D> coordsZ = new List<Coordinate3D>() 
  { 
    new Coordinate3D(1, 2, double.NaN), 
    new Coordinate3D(4, 5, 3), 
    new Coordinate3D(7, 8, double.NaN) 
  };

  Polygon polygon = PolygonBuilder.CreatePolygon(coordsZ);
  // polygon.HasZ = true

  Polygon polygonZReplaced = GeometryEngine.Instance.ReplaceNaNZs(polygon, -1) as Polygon;

  // polygonZReplaced.Points[0].Z = -1
  // polygonZReplaced.Points[1].Z = 3
  // polygonZReplaced.Points[2].Z = -1
});

Reverse the order of points in a Polygon

    before:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  List<Coordinate2D> list2D = new List<Coordinate2D>();
  list2D.Add(new Coordinate2D(1.0, 1.0));
  list2D.Add(new Coordinate2D(1.0, 2.0));
  list2D.Add(new Coordinate2D(2.0, 2.0));
  list2D.Add(new Coordinate2D(2.0, 1.0));

  Polygon polygon = PolygonBuilder.CreatePolygon(list2D);

  Geometry g = GeometryEngine.ReverseOrientation(polygon);
  Polygon gPolygon = g as Polygon;

  // gPolygon.Points[0] = 1.0, 1.0
  // gPolygon.Points[1] = 2.0, 1.0
  // gPolygon.Points[2] = 2.0, 2.0
  // gPolygon.Points[3] = 1.0, 2.0
  // gPolygon.Points[4] = 1.0, 1.0
  // gPolygon.Area = -1 * polygon.Area
});

    now:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  List<Coordinate2D> list2D = new List<Coordinate2D>();
  list2D.Add(new Coordinate2D(1.0, 1.0));
  list2D.Add(new Coordinate2D(1.0, 2.0));
  list2D.Add(new Coordinate2D(2.0, 2.0));
  list2D.Add(new Coordinate2D(2.0, 1.0));

  Polygon polygon = PolygonBuilder.CreatePolygon(list2D);

  Geometry g = GeometryEngine.Instance.ReverseOrientation(polygon);
  Polygon gPolygon = g as Polygon;

  // gPolygon.Points[0] = 1.0, 1.0
  // gPolygon.Points[1] = 2.0, 1.0
  // gPolygon.Points[2] = 2.0, 2.0
  // gPolygon.Points[3] = 1.0, 2.0
  // gPolygon.Points[4] = 1.0, 1.0
  // gPolygon.Area = -1 * polygon.Area
});

Rotate a MapPoint

    before:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  MapPoint pt = MapPointBuilder.CreateMapPoint(1.0, 3.0);
  MapPoint rotatePt = MapPointBuilder.CreateMapPoint(3.0, 3.0);

  Geometry result = GeometryEngine.Rotate(pt, rotatePt, Math.PI / 2);
  // result point is (3, 1)
});

    now:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  MapPoint pt = MapPointBuilder.CreateMapPoint(1.0, 3.0);
  MapPoint rotatePt = MapPointBuilder.CreateMapPoint(3.0, 3.0);

  Geometry result = GeometryEngine.Instance.Rotate(pt, rotatePt, Math.PI / 2);
  // result point is (3, 1)
});

Rotate a Polyline

    before:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  // rotate a polyline

  MapPoint fixedPt = MapPointBuilder.CreateMapPoint(3.0, 3.0);
  
  List<MapPoint> pts = new List<MapPoint>();
  pts.Add(MapPointBuilder.CreateMapPoint(1.0, 1.0));
  pts.Add(MapPointBuilder.CreateMapPoint(1.0, 5.0));
  pts.Add(MapPointBuilder.CreateMapPoint(5, 5));
  pts.Add(MapPointBuilder.CreateMapPoint(5.0, 1.0));
  Polyline polyline = PolylineBuilder.CreatePolyline(pts);

  Polyline rotated = GeometryEngine.Rotate(polyline, fixedPt, Math.PI / 4) as Polyline;  // rotate 45 deg
});

    now:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  // rotate a polyline

  MapPoint fixedPt = MapPointBuilder.CreateMapPoint(3.0, 3.0);
  
  List<MapPoint> pts = new List<MapPoint>();
  pts.Add(MapPointBuilder.CreateMapPoint(1.0, 1.0));
  pts.Add(MapPointBuilder.CreateMapPoint(1.0, 5.0));
  pts.Add(MapPointBuilder.CreateMapPoint(5, 5));
  pts.Add(MapPointBuilder.CreateMapPoint(5.0, 1.0));
  Polyline polyline = PolylineBuilder.CreatePolyline(pts);

  Polyline rotated = GeometryEngine.Instance.Rotate(polyline, fixedPt, Math.PI / 4) as Polyline;  // rotate 45 deg
});

Set all Zs in a polyline

    before:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  List<Coordinate> coordsZ = new List<Coordinate>() 
  { 
    new Coordinate(1, 2, 3), 
    new Coordinate(4, 5, 6), 
    new Coordinate(7, 8, double.NaN) 
  };

  Polyline polyline = PolylineBuilder.CreatePolyline(coordsZ);
  // polyline.HasZ = true

  Polyline polylineSetZ = GeometryEngine.SetConstantZ(polyline, -1) as Polyline;
  // polylineSetZ.Points[0].Z = -1
  // polylineSetZ.Points[1].Z = -1
  // polylineSetZ.Points[2].Z = -1

  polylineSetZ = GeometryEngine.SetConstantZ(polyline, double.NaN) as Polyline;
  // polyline.HasZ = true
  // polylineSetZ.Points[0].HasZ = true
  // polylineSetZ.Points[0].Z = NaN
  // polylineSetZ.Points[1].HasZ = true
  // polylineSetZ.Points[1].Z = NaN
  // polylineSetZ.Points[2].HasZ = true
  // polylineSetZ.Points[2].Z = NaN

  polylineSetZ = GeometryEngine.SetConstantZ(polyline, double.PositiveInfinity) as Polyline;
  // polyline.HasZ = true
  // polylineSetZ.Points[0].HasZ = true
  // polylineSetZ.Points[0].Z = double.PositiveInfinity
  // polylineSetZ.Points[1].HasZ = true
  // polylineSetZ.Points[1].Z = double.PositiveInfinity
  // polylineSetZ.Points[2].HasZ = true
  // polylineSetZ.Points[2].Z = double.PositiveInfinity
});

    now:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  List<Coordinate3D> coordsZ = new List<Coordinate3D>() 
  { 
    new Coordinate3D(1, 2, 3), 
    new Coordinate3D(4, 5, 6), 
    new Coordinate3D(7, 8, double.NaN) 
  };

  Polyline polyline = PolylineBuilder.CreatePolyline(coordsZ);
  // polyline.HasZ = true

  Polyline polylineSetZ = GeometryEngine.Instance.SetConstantZ(polyline, -1) as Polyline;
  // polylineSetZ.Points[0].Z = -1
  // polylineSetZ.Points[1].Z = -1
  // polylineSetZ.Points[2].Z = -1

  polylineSetZ = GeometryEngine.Instance.SetConstantZ(polyline, double.NaN) as Polyline;
  // polyline.HasZ = true
  // polylineSetZ.Points[0].HasZ = true
  // polylineSetZ.Points[0].Z = NaN
  // polylineSetZ.Points[1].HasZ = true
  // polylineSetZ.Points[1].Z = NaN
  // polylineSetZ.Points[2].HasZ = true
  // polylineSetZ.Points[2].Z = NaN

  polylineSetZ = GeometryEngine.Instance.SetConstantZ(polyline, double.PositiveInfinity) as Polyline;
  // polyline.HasZ = true
  // polylineSetZ.Points[0].HasZ = true
  // polylineSetZ.Points[0].Z = double.PositiveInfinity
  // polylineSetZ.Points[1].HasZ = true
  // polylineSetZ.Points[1].Z = double.PositiveInfinity
  // polylineSetZ.Points[2].HasZ = true
  // polylineSetZ.Points[2].Z = double.PositiveInfinity
});

Calculate area of geometry on surface of Earth's ellipsoid - ShapePreservingArea

    before:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  // pt
  MapPoint pt = MapPointBuilder.CreateMapPoint(1.0, 3.0, SpatialReferences.WebMercator);
  double area = GeometryEngine.ShapePreservingArea(pt);         // area = 0


  List<MapPoint> pts = new List<MapPoint>();
  pts.Add(MapPointBuilder.CreateMapPoint(1.0, 1.0, 3.0));
  pts.Add(MapPointBuilder.CreateMapPoint(1.0, 3.0, 3.0));
  pts.Add(MapPointBuilder.CreateMapPoint(3, 3, 3.0));
  pts.Add(MapPointBuilder.CreateMapPoint(3.0, 1.0, 3.0));

  // multipoint
  Multipoint mPt = MultipointBuilder.CreateMultipoint(pts);
  area = GeometryEngine.ShapePreservingArea(mPt);               // area = 0

  // polyline
  Polyline polyline = PolylineBuilder.CreatePolyline(pts);
  area = GeometryEngine.ShapePreservingArea(polyline);          // area = 0

  // polygon
  Polygon polygon = PolygonBuilder.CreatePolygon(pts, SpatialReferences.WGS84);
  area = GeometryEngine.ShapePreservingArea(polygon);

  polygon = PolygonBuilder.CreatePolygon(pts, SpatialReferences.WebMercator);
  area = GeometryEngine.ShapePreservingArea(polygon);
});

    now:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  // pt
  MapPoint pt = MapPointBuilder.CreateMapPoint(1.0, 3.0, SpatialReferences.WebMercator);
  double area = GeometryEngine.Instance.ShapePreservingArea(pt);         // area = 0


  List<MapPoint> pts = new List<MapPoint>();
  pts.Add(MapPointBuilder.CreateMapPoint(1.0, 1.0, 3.0));
  pts.Add(MapPointBuilder.CreateMapPoint(1.0, 3.0, 3.0));
  pts.Add(MapPointBuilder.CreateMapPoint(3, 3, 3.0));
  pts.Add(MapPointBuilder.CreateMapPoint(3.0, 1.0, 3.0));

  // multipoint
  Multipoint mPt = MultipointBuilder.CreateMultipoint(pts);
  area = GeometryEngine.Instance.ShapePreservingArea(mPt);               // area = 0

  // polyline
  Polyline polyline = PolylineBuilder.CreatePolyline(pts);
  area = GeometryEngine.Instance.ShapePreservingArea(polyline);          // area = 0

  // polygon
  Polygon polygon = PolygonBuilder.CreatePolygon(pts, SpatialReferences.WGS84);
  area = GeometryEngine.Instance.ShapePreservingArea(polygon);

  polygon = PolygonBuilder.CreatePolygon(pts, SpatialReferences.WebMercator);
  area = GeometryEngine.Instance.ShapePreservingArea(polygon);
});

Calculate length of geometry on surface of Earth's ellipsoid - ShapePreservingLength

    before:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  // pt
  MapPoint pt = MapPointBuilder.CreateMapPoint(1.0, 3.0, SpatialReferences.WebMercator);
  double len = GeometryEngine.ShapePreservingLength(pt);          // len = 0


  List<MapPoint> pts = new List<MapPoint>();
  pts.Add(MapPointBuilder.CreateMapPoint(1.0, 1.0, 3.0));
  pts.Add(MapPointBuilder.CreateMapPoint(1.0, 3.0, 3.0));
  pts.Add(MapPointBuilder.CreateMapPoint(3, 3, 3.0));
  pts.Add(MapPointBuilder.CreateMapPoint(3.0, 1.0, 3.0));

  // multipoint
  Multipoint mPt = MultipointBuilder.CreateMultipoint(pts);
  len = GeometryEngine.ShapePreservingLength(mPt);                // len = 0

  // polyline
  Polyline polyline = PolylineBuilder.CreatePolyline(pts, SpatialReferences.WGS84);
  len = GeometryEngine.ShapePreservingLength(polyline);

  // polygon
  Polygon polygon = PolygonBuilder.CreatePolygon(pts, SpatialReferences.WGS84);
  len = GeometryEngine.ShapePreservingLength(polygon);
});

    now:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  // pt
  MapPoint pt = MapPointBuilder.CreateMapPoint(1.0, 3.0, SpatialReferences.WebMercator);
  double len = GeometryEngine.Instance.ShapePreservingLength(pt);          // len = 0


  List<MapPoint> pts = new List<MapPoint>();
  pts.Add(MapPointBuilder.CreateMapPoint(1.0, 1.0, 3.0));
  pts.Add(MapPointBuilder.CreateMapPoint(1.0, 3.0, 3.0));
  pts.Add(MapPointBuilder.CreateMapPoint(3, 3, 3.0));
  pts.Add(MapPointBuilder.CreateMapPoint(3.0, 1.0, 3.0));

  // multipoint
  Multipoint mPt = MultipointBuilder.CreateMultipoint(pts);
  len = GeometryEngine.Instance.ShapePreservingLength(mPt);                // len = 0

  // polyline
  Polyline polyline = PolylineBuilder.CreatePolyline(pts, SpatialReferences.WGS84);
  len = GeometryEngine.Instance.ShapePreservingLength(polyline);

  // polygon
  Polygon polygon = PolygonBuilder.CreatePolygon(pts, SpatialReferences.WGS84);
  len = GeometryEngine.Instance.ShapePreservingLength(polygon);
});

Scale a geometry

    before:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  List<MapPoint> pts = new List<MapPoint>();
  pts.Add(MapPointBuilder.CreateMapPoint(1.0, 1.0, 3.0));
  pts.Add(MapPointBuilder.CreateMapPoint(1.0, 3.0, 3.0));
  pts.Add(MapPointBuilder.CreateMapPoint(3, 3, 3.0));
  pts.Add(MapPointBuilder.CreateMapPoint(3.0, 1.0, 3.0));

  MapPoint midPt = MapPointBuilder.CreateMapPoint(1.5, 1.5);

  // polyline
  Polyline polyline = PolylineBuilder.CreatePolyline(pts);
  // polyline.Length = 6
  // polyline.Length3D = 0
  Geometry g = GeometryEngine.Scale(polyline, midPt, 0.5, 0.5);
  Polyline resultPolyline = g as Polyline;
  // resultPolyline.length  = 3
  // resultPolyline.Points[0] = 1.25, 1.25, 3
  // resultPolyline.Points[1] = 1.25, 2.25, 3
  // resultPolyline.Points[2] = 2.25, 2.25, 3
  // resultPolyline.Points[3] = 2.25, 1.25, 3

  // 3D point - scale in 3d
  MapPoint midPtZ = MapPointBuilder.CreateMapPoint(1.5, 1.5, 1);
  g = GeometryEngine.Scale(polyline, midPtZ, 0.5, 0.5, 0.25);
  resultPolyline = g as Polyline;
  // resultPolyline.Points[0] = 1.25, 1.25, 1.5
  // resultPolyline.Points[1] = 1.25, 2.25, 1.5
  // resultPolyline.Points[2] = 2.25, 2.25, 1.5
  // resultPolyline.Points[3] = 2.25, 1.25, 1.5

});

    now:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  List<MapPoint> pts = new List<MapPoint>();
  pts.Add(MapPointBuilder.CreateMapPoint(1.0, 1.0, 3.0));
  pts.Add(MapPointBuilder.CreateMapPoint(1.0, 3.0, 3.0));
  pts.Add(MapPointBuilder.CreateMapPoint(3, 3, 3.0));
  pts.Add(MapPointBuilder.CreateMapPoint(3.0, 1.0, 3.0));

  MapPoint midPt = MapPointBuilder.CreateMapPoint(1.5, 1.5);

  // polyline
  Polyline polyline = PolylineBuilder.CreatePolyline(pts);
  // polyline.Length = 6
  // polyline.Length3D = 0
  Geometry g = GeometryEngine.Instance.Scale(polyline, midPt, 0.5, 0.5);
  Polyline resultPolyline = g as Polyline;
  // resultPolyline.length  = 3
  // resultPolyline.Points[0] = 1.25, 1.25, 3
  // resultPolyline.Points[1] = 1.25, 2.25, 3
  // resultPolyline.Points[2] = 2.25, 2.25, 3
  // resultPolyline.Points[3] = 2.25, 1.25, 3

  // 3D point - scale in 3d
  MapPoint midPtZ = MapPointBuilder.CreateMapPoint(1.5, 1.5, 1);
  g = GeometryEngine.Instance.Scale(polyline, midPtZ, 0.5, 0.5, 0.25);
  resultPolyline = g as Polyline;
  // resultPolyline.Points[0] = 1.25, 1.25, 1.5
  // resultPolyline.Points[1] = 1.25, 2.25, 1.5
  // resultPolyline.Points[2] = 2.25, 2.25, 1.5
  // resultPolyline.Points[3] = 2.25, 1.25, 1.5

});

Simplify a polyline with intersections, overlaps

    before:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  List<Coordinate> coords = new List<Coordinate>()
  {
    new Coordinate(8, 0),
    new Coordinate(8, 4),
    new Coordinate(6, 4),
    new Coordinate(8, 4),
    new Coordinate(10, 4),
    new Coordinate(8, 4)
  };

  SpatialReference sr = SpatialReferences.WGS84;

  // build a line that has segments that cross over each other
  Polyline polyline = PolylineBuilder.CreatePolyline(coords, sr);
  // polyline.PartCount = 1
  ReadOnlyPartCollection parts = polyline.Parts;
  ReadOnlySegmentCollection segments = parts[0];
  // segments.Count = 5

  //  note there is a difference between SimpleAsFeature (doesn't detect intersections and overlaps, determines if it's simple enough for gdb storage)
  //  and SimplifyPolyline  (does detect intersections etc)
  bool isSimple = GeometryEngine.IsSimpleAsFeature(polyline, false);
  // isSimple = true

  // simplify it (with force = false)
  // because it has already been deemed 'simple' (previous IsSimpleAsFeature call) no detection of intersections, overlaps occur
  Polyline simplePolyline = GeometryEngine.SimplifyPolyline(polyline, SimplifyType.Planar, false);
  // simplePolyline.PartCount = 1
  ReadOnlyPartCollection simpleParts = simplePolyline.Parts;
  ReadOnlySegmentCollection simpleSegments = simpleParts[0];
  // simpleSegments.Count = 5

  // simplify it (with force = true)
  // detection of intersections, overlaps occur 
  simplePolyline = GeometryEngine.SimplifyPolyline(polyline, SimplifyType.Planar, true);
  // simplePolyline.PartCount = 3
  simpleParts = simplePolyline.Parts;
  simpleSegments = simpleParts[0];
  // simpleSegments.Count = 1
});

    now:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  List<Coordinate2D> coords = new List<Coordinate2D>()
  {
    new Coordinate2D(8, 0),
    new Coordinate2D(8, 4),
    new Coordinate2D(6, 4),
    new Coordinate2D(8, 4),
    new Coordinate2D(10, 4),
    new Coordinate2D(8, 4)
  };

  SpatialReference sr = SpatialReferences.WGS84;

  // build a line that has segments that cross over each other
  Polyline polyline = PolylineBuilder.CreatePolyline(coords, sr);
  // polyline.PartCount = 1
  ReadOnlyPartCollection parts = polyline.Parts;
  ReadOnlySegmentCollection segments = parts[0];
  // segments.Count = 5

  //  note there is a difference between SimpleAsFeature (doesn't detect intersections and overlaps, determines if it's simple enough for gdb storage)
  //  and SimplifyPolyline  (does detect intersections etc)
  bool isSimple = GeometryEngine.Instance.IsSimpleAsFeature(polyline, false);
  // isSimple = true

  // simplify it (with force = false)
  // because it has already been deemed 'simple' (previous IsSimpleAsFeature call) no detection of intersections, overlaps occur
  Polyline simplePolyline = GeometryEngine.Instance.SimplifyPolyline(polyline, SimplifyType.Planar, false);
  // simplePolyline.PartCount = 1
  ReadOnlyPartCollection simpleParts = simplePolyline.Parts;
  ReadOnlySegmentCollection simpleSegments = simpleParts[0];
  // simpleSegments.Count = 5

  // simplify it (with force = true)
  // detection of intersections, overlaps occur 
  simplePolyline = GeometryEngine.Instance.SimplifyPolyline(polyline, SimplifyType.Planar, true);
  // simplePolyline.PartCount = 3
  simpleParts = simplePolyline.Parts;
  simpleSegments = simpleParts[0];
  // simpleSegments.Count = 1
});

Polygon touches another Polygon

    before:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  // two disjoint polygons
  Envelope env = EnvelopeBuilder.CreateEnvelope(MapPointBuilder.CreateMapPoint(4.0, 4.0), MapPointBuilder.CreateMapPoint(8, 8));
  Polygon poly1 = PolygonBuilder.CreatePolygon(env);

  Envelope env2 = EnvelopeBuilder.CreateEnvelope(MapPointBuilder.CreateMapPoint(1.0, 1.0), MapPointBuilder.CreateMapPoint(5, 5));
  Polygon poly2 = PolygonBuilder.CreatePolygon(env2);

  bool touches = GeometryEngine.Touches(poly1, poly2);    // touches = false

  // another polygon that touches the first
  Envelope env3 = EnvelopeBuilder.CreateEnvelope(MapPointBuilder.CreateMapPoint(1.0, 1.0), MapPointBuilder.CreateMapPoint(4, 4));
  Polygon poly3 = PolygonBuilder.CreatePolygon(env3);

  touches = GeometryEngine.Touches(poly1, poly3);         // touches = true
});

    now:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  // two disjoint polygons
  Envelope env = EnvelopeBuilder.CreateEnvelope(MapPointBuilder.CreateMapPoint(4.0, 4.0), MapPointBuilder.CreateMapPoint(8, 8));
  Polygon poly1 = PolygonBuilder.CreatePolygon(env);

  Envelope env2 = EnvelopeBuilder.CreateEnvelope(MapPointBuilder.CreateMapPoint(1.0, 1.0), MapPointBuilder.CreateMapPoint(5, 5));
  Polygon poly2 = PolygonBuilder.CreatePolygon(env2);

  bool touches = GeometryEngine.Instance.Touches(poly1, poly2);    // touches = false

  // another polygon that touches the first
  Envelope env3 = EnvelopeBuilder.CreateEnvelope(MapPointBuilder.CreateMapPoint(1.0, 1.0), MapPointBuilder.CreateMapPoint(4, 4));
  Polygon poly3 = PolygonBuilder.CreatePolygon(env3);

  touches = GeometryEngine.Instance.Touches(poly1, poly3);         // touches = true
});

Union two MapPoints - creates a Multipoint

    before:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  MapPoint pt1 = MapPointBuilder.CreateMapPoint(1.0, 1.0);
  MapPoint pt2 = MapPointBuilder.CreateMapPoint(2.0, 2.5);

  Geometry geometry = GeometryEngine.Union(pt1, pt2);
  Multipoint multipoint = geometry as Multipoint;   // multipoint has point count of 2
});

    now:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  MapPoint pt1 = MapPointBuilder.CreateMapPoint(1.0, 1.0);
  MapPoint pt2 = MapPointBuilder.CreateMapPoint(2.0, 2.5);

  Geometry geometry = GeometryEngine.Instance.Union(pt1, pt2);
  Multipoint multipoint = geometry as Multipoint;   // multipoint has point count of 2
});

Union two Polygons

    before:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  // union two polygons

  List<MapPoint> polyPts = new List<MapPoint>();
  polyPts.Add(MapPointBuilder.CreateMapPoint(3.0, 2.0));
  polyPts.Add(MapPointBuilder.CreateMapPoint(3.0, 6.0));
  polyPts.Add(MapPointBuilder.CreateMapPoint(6.0, 6.0));
  polyPts.Add(MapPointBuilder.CreateMapPoint(6.0, 2.0));

  Polygon poly1 = PolygonBuilder.CreatePolygon(polyPts);
  bool isSimple = GeometryEngine.IsSimpleAsFeature(poly1);

  Envelope env = EnvelopeBuilder.CreateEnvelope(MapPointBuilder.CreateMapPoint(4.0, 4.0), MapPointBuilder.CreateMapPoint(8, 8));
  Polygon poly2 = PolygonBuilder.CreatePolygon(env);
  isSimple = GeometryEngine.IsSimpleAsFeature(poly2);

  Geometry g = GeometryEngine.Union(poly1, poly2);
  Polygon polyResult = g as Polygon;
});

    now:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  // union two polygons

  List<MapPoint> polyPts = new List<MapPoint>();
  polyPts.Add(MapPointBuilder.CreateMapPoint(3.0, 2.0));
  polyPts.Add(MapPointBuilder.CreateMapPoint(3.0, 6.0));
  polyPts.Add(MapPointBuilder.CreateMapPoint(6.0, 6.0));
  polyPts.Add(MapPointBuilder.CreateMapPoint(6.0, 2.0));

  Polygon poly1 = PolygonBuilder.CreatePolygon(polyPts);
  bool isSimple = GeometryEngine.Instance.IsSimpleAsFeature(poly1);

  Envelope env = EnvelopeBuilder.CreateEnvelope(MapPointBuilder.CreateMapPoint(4.0, 4.0), MapPointBuilder.CreateMapPoint(8, 8));
  Polygon poly2 = PolygonBuilder.CreatePolygon(env);
  isSimple = GeometryEngine.Instance.IsSimpleAsFeature(poly2);

  Geometry g = GeometryEngine.Instance.Union(poly1, poly2);
  Polygon polyResult = g as Polygon;
});

Union many Polylines

    before:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  // union many polylines

  List<Coordinate2D> coords = new List<Coordinate2D>()
  {
    new Coordinate2D(1, 2), new Coordinate2D(3, 4), new Coordinate2D(4, 2),
    new Coordinate2D(5, 6), new Coordinate2D(7, 8), new Coordinate2D(8, 4),
    new Coordinate2D(9, 10), new Coordinate2D(11, 12), new Coordinate2D(12, 8),
    new Coordinate2D(10, 8), new Coordinate2D(12, 12), new Coordinate2D(14, 10)
  };

  // create Disjoint lines
  List<Polyline> manyLines = new List<Polyline>
  {
    PolylineBuilder.CreatePolyline(new List<Coordinate2D>(){coords[0], coords[1], coords[2]}, SpatialReferences.WGS84),
    PolylineBuilder.CreatePolyline(new List<Coordinate2D>(){coords[3], coords[4], coords[5]}),
    PolylineBuilder.CreatePolyline(new List<Coordinate2D>(){coords[6], coords[7], coords[8]})
  };

  Polyline polyline = GeometryEngine.Union(manyLines) as Polyline;
});

    now:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  // union many polylines

  List<Coordinate2D> coords = new List<Coordinate2D>()
  {
    new Coordinate2D(1, 2), new Coordinate2D(3, 4), new Coordinate2D(4, 2),
    new Coordinate2D(5, 6), new Coordinate2D(7, 8), new Coordinate2D(8, 4),
    new Coordinate2D(9, 10), new Coordinate2D(11, 12), new Coordinate2D(12, 8),
    new Coordinate2D(10, 8), new Coordinate2D(12, 12), new Coordinate2D(14, 10)
  };

  // create Disjoint lines
  List<Polyline> manyLines = new List<Polyline>
  {
    PolylineBuilder.CreatePolyline(new List<Coordinate2D>(){coords[0], coords[1], coords[2]}, SpatialReferences.WGS84),
    PolylineBuilder.CreatePolyline(new List<Coordinate2D>(){coords[3], coords[4], coords[5]}),
    PolylineBuilder.CreatePolyline(new List<Coordinate2D>(){coords[6], coords[7], coords[8]})
  };

  Polyline polyline = GeometryEngine.Instance.Union(manyLines) as Polyline;
});

Union many Polygons

    before:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  // union many polygons

  List<Coordinate> coordsZ = new List<Coordinate>()
  {
    new Coordinate(1, 2, 0), new Coordinate(3, 4, 1), new Coordinate(4, 2, 2),
    new Coordinate(5, 6, 3), new Coordinate(7, 8, 4), new Coordinate(8, 4, 5),
    new Coordinate(9, 10, 6), new Coordinate(11, 12, 7), new Coordinate(12, 8, 8),
    new Coordinate(10, 8, 9), new Coordinate(12, 12, 10), new Coordinate(14, 10, 11)
  };

  // create polygons
  List<Polygon> manyPolygonsZ = new List<Polygon>
  {
    PolygonBuilder.CreatePolygon(new List<Coordinate>(){coordsZ[0], coordsZ[1], coordsZ[2]}, SpatialReferences.WGS84),
    PolygonBuilder.CreatePolygon(new List<Coordinate>(){coordsZ[3], coordsZ[4], coordsZ[5]}),
    PolygonBuilder.CreatePolygon(new List<Coordinate>(){coordsZ[6], coordsZ[7], coordsZ[8]})
  };

  Polygon polygon = GeometryEngine.Union(manyPolygonsZ) as Polygon;
});

    now:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  // union many polygons

  List<Coordinate3D> coordsZ = new List<Coordinate3D>()
  {
    new Coordinate3D(1, 2, 0), new Coordinate3D(3, 4, 1), new Coordinate3D(4, 2, 2),
    new Coordinate3D(5, 6, 3), new Coordinate3D(7, 8, 4), new Coordinate3D(8, 4, 5),
    new Coordinate3D(9, 10, 6), new Coordinate3D(11, 12, 7), new Coordinate3D(12, 8, 8),
    new Coordinate3D(10, 8, 9), new Coordinate3D(12, 12, 10), new Coordinate3D(14, 10, 11)
  };

  // create polygons
  List<Polygon> manyPolygonsZ = new List<Polygon>
  {
    PolygonBuilder.CreatePolygon(new List<Coordinate3D>(){coordsZ[0], coordsZ[1], coordsZ[2]}, SpatialReferences.WGS84),
    PolygonBuilder.CreatePolygon(new List<Coordinate3D>(){coordsZ[3], coordsZ[4], coordsZ[5]}),
    PolygonBuilder.CreatePolygon(new List<Coordinate3D>(){coordsZ[6], coordsZ[7], coordsZ[8]})
  };

  Polygon polygon = GeometryEngine.Instance.Union(manyPolygonsZ) as Polygon;
});

MapPoints, Polylines, Polygons within Polygon

    before:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  // build a polygon      
  List<MapPoint> pts = new List<MapPoint>();
  pts.Add(MapPointBuilder.CreateMapPoint(1.0, 1.0));
  pts.Add(MapPointBuilder.CreateMapPoint(1.0, 2.0));
  pts.Add(MapPointBuilder.CreateMapPoint(2.0, 2.0));
  pts.Add(MapPointBuilder.CreateMapPoint(2.0, 1.0));

  Polygon poly = PolygonBuilder.CreatePolygon(pts);

  // an inner point
  MapPoint innerPt = MapPointBuilder.CreateMapPoint(1.5, 1.5);
  bool within = GeometryEngine.Within(innerPt, poly);   // within = true

  // point on a boundary
  within = GeometryEngine.Within(pts[0], poly);     // within = false

  // an interior line
  MapPoint innerPt2 = MapPointBuilder.CreateMapPoint(1.25, 1.75);
  List<MapPoint> innerLinePts = new List<MapPoint>();
  innerLinePts.Add(innerPt);
  innerLinePts.Add(innerPt2);

  Polyline polyline = PolylineBuilder.CreatePolyline(innerLinePts);
  within = GeometryEngine.Within(polyline, poly);   // within = true

  // a line that crosses the boundary
  MapPoint outerPt = MapPointBuilder.CreateMapPoint(3, 1.5);
  List<MapPoint> crossingLinePts = new List<MapPoint>();
  crossingLinePts.Add(innerPt);
  crossingLinePts.Add(outerPt);

  polyline = PolylineBuilder.CreatePolyline(crossingLinePts);
  within = GeometryEngine.Within(polyline, poly);     // within = false


  // polygon in polygon
  Envelope env = EnvelopeBuilder.CreateEnvelope(innerPt, innerPt2);
  within = GeometryEngine.Within(env, poly);      // within = true
});

    now:

// methods need to run on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  // build a polygon      
  List<MapPoint> pts = new List<MapPoint>();
  pts.Add(MapPointBuilder.CreateMapPoint(1.0, 1.0));
  pts.Add(MapPointBuilder.CreateMapPoint(1.0, 2.0));
  pts.Add(MapPointBuilder.CreateMapPoint(2.0, 2.0));
  pts.Add(MapPointBuilder.CreateMapPoint(2.0, 1.0));

  Polygon poly = PolygonBuilder.CreatePolygon(pts);

  // an inner point
  MapPoint innerPt = MapPointBuilder.CreateMapPoint(1.5, 1.5);
  bool within = GeometryEngine.Instance.Within(innerPt, poly);   // within = true

  // point on a boundary
  within = GeometryEngine.Instance.Within(pts[0], poly);     // within = false

  // an interior line
  MapPoint innerPt2 = MapPointBuilder.CreateMapPoint(1.25, 1.75);
  List<MapPoint> innerLinePts = new List<MapPoint>();
  innerLinePts.Add(innerPt);
  innerLinePts.Add(innerPt2);

  Polyline polyline = PolylineBuilder.CreatePolyline(innerLinePts);
  within = GeometryEngine.Instance.Within(polyline, poly);   // within = true

  // a line that crosses the boundary
  MapPoint outerPt = MapPointBuilder.CreateMapPoint(3, 1.5);
  List<MapPoint> crossingLinePts = new List<MapPoint>();
  crossingLinePts.Add(innerPt);
  crossingLinePts.Add(outerPt);

  polyline = PolylineBuilder.CreatePolyline(crossingLinePts);
  within = GeometryEngine.Instance.Within(polyline, poly);     // within = false


  // polygon in polygon
  Envelope env = EnvelopeBuilder.CreateEnvelope(innerPt, innerPt2);
  within = GeometryEngine.Instance.Within(env, poly);      // within = true
});

Create Projection Transformation

    before:

// methods need to be on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  SpatialReference sr4267 = SpatialReferenceBuilder.CreateSpatialReference(4267);
  SpatialReference sr4326 = SpatialReferences.WGS84;
  SpatialReference sr3857 = SpatialReferences.WebMercator;

  // Create transformation from  4267 -> 3857
  ProjectionTransformation projTransFromSRs = ArcGIS.Core.Geometry.ProjectionTransformation.Create(sr4267, sr3857);

  // create an envelope
  Envelope env = EnvelopeBuilder.CreateEnvelope(new Coordinate2D(2, 2), new Coordinate2D(3, 3), sr4267);

  // Project with one geo transform 4267 -> 3857
  Envelope projectedEnvEx = GeometryEngine.ProjectEx(env, projTransFromSRs) as Envelope;

  // Create inverse transformation, 3857 -> 4267
  ProjectionTransformation projTransFromSRsInverse = ArcGIS.Core.Geometry.ProjectionTransformation.Create(sr3857, sr4267);
  // Project the projected envelope back using the inverse transformation
  Envelope projectedEnvBack = GeometryEngine.ProjectEx(projectedEnvEx, projTransFromSRsInverse) as Envelope;

  bool isEqual = env.IsEqual(projectedEnvBack);
});

    now:

// methods need to be on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  SpatialReference sr4267 = SpatialReferenceBuilder.CreateSpatialReference(4267);
  SpatialReference sr4326 = SpatialReferences.WGS84;
  SpatialReference sr3857 = SpatialReferences.WebMercator;

  // Create transformation from  4267 -> 3857
  ProjectionTransformation projTransFromSRs = ArcGIS.Core.Geometry.ProjectionTransformation.Create(sr4267, sr3857);

  // create an envelope
  Envelope env = EnvelopeBuilder.CreateEnvelope(new Coordinate2D(2, 2), new Coordinate2D(3, 3), sr4267);

  // Project with one geo transform 4267 -> 3857
  Envelope projectedEnvEx = GeometryEngine.Instance.ProjectEx(env, projTransFromSRs) as Envelope;

  // Create inverse transformation, 3857 -> 4267
  ProjectionTransformation projTransFromSRsInverse = ArcGIS.Core.Geometry.ProjectionTransformation.Create(sr3857, sr4267);
  // Project the projected envelope back using the inverse transformation
  Envelope projectedEnvBack = GeometryEngine.Instance.ProjectEx(projectedEnvEx, projTransFromSRsInverse) as Envelope;

  bool isEqual = env.IsEqual(projectedEnvBack);
});

MapPoint - GeoCoordinateString Conversion

    before:

// methods need to be on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  SpatialReference sr = SpatialReferences.WGS84;
  SpatialReference sr2 = SpatialReferences.WebMercator;

  // create some points
  MapPoint point0 = MapPointBuilder.CreateMapPoint(0, 0, sr);
  MapPoint point1 = MapPointBuilder.CreateMapPoint(10, 20, sr);
  MapPoint point2 = GeometryEngine.Project(point1, sr2) as MapPoint;
  MapPoint pointEmpty = MapPointBuilder.CreateMapPoint(sr);
  MapPoint pointwithNoSR = MapPointBuilder.CreateMapPoint(1, 1);
  MapPoint pointZM = MapPointBuilder.CreateMapPoint(1, 2, 3, 4, sr);

  // convert to MGRS
  ToGeoCoordinateParameter mgrsParam = new ToGeoCoordinateParameter(GeoCoordinateType.MGRS);
  string geoCoordString = point0.ToGeoCoordinateString(mgrsParam);        // 31NAA6602100000

  // use the builder to create a new point from the string.  Coordinates are the same 
  MapPoint outPoint = MapPointBuilder.FromGeoCoordinateString(geoCoordString, sr, GeoCoordinateType.MGRS);    // outPoint.x = 0; outPoint.Y = 0

  geoCoordString = point1.ToGeoCoordinateString(mgrsParam);             // 32QPH0460911794
  outPoint = MapPointBuilder.FromGeoCoordinateString(geoCoordString, sr, GeoCoordinateType.MGRS);       // outPoint.X = 10; outPoint.Y = 20

  // z, m are not transformed
  geoCoordString = pointZM.ToGeoCoordinateString(mgrsParam);
  outPoint = MapPointBuilder.FromGeoCoordinateString(geoCoordString, sr, GeoCoordinateType.MGRS);     // outPoint.X = 1; outPoint.Y = 2; outPoint.Z = Nan; outPoint.M = Nan;

  // set the number of digits to 2 and convert
  mgrsParam.NumDigits = 2;
  geoCoordString = point1.ToGeoCoordinateString(mgrsParam);             // 32QPH0512
  outPoint = MapPointBuilder.FromGeoCoordinateString(geoCoordString, sr, GeoCoordinateType.MGRS);     // outPoint.X = 10; outPoint.Y = 20


  // convert to UTM
  ToGeoCoordinateParameter utmParam = new ToGeoCoordinateParameter(GeoCoordinateType.UTM);
  geoCoordString = point0.ToGeoCoordinateString(utmParam);        // 31N 166021 0000000
  geoCoordString = point1.ToGeoCoordinateString(utmParam);        // 32Q 604609 2211793

  // convert to DMS
  ToGeoCoordinateParameter dmsParam = new ToGeoCoordinateParameter(GeoCoordinateType.DMS);
  geoCoordString = point0.ToGeoCoordinateString(dmsParam);        // 00 00 00.00N 000 00 00.00E
  geoCoordString = point1.ToGeoCoordinateString(dmsParam);        // 20 00 00.00N 010 00 00.00E

  // convert to DDM
  ToGeoCoordinateParameter ddmParam = new ToGeoCoordinateParameter(GeoCoordinateType.DDM);
  geoCoordString = point0.ToGeoCoordinateString(ddmParam);        // 00 00.0000N 000 00.0000E
  geoCoordString = point1.ToGeoCoordinateString(ddmParam);        // 20 00.0000N 010 00.0000E

  // convert to DD
  ToGeoCoordinateParameter ddParam = new ToGeoCoordinateParameter(GeoCoordinateType.DD);
  geoCoordString = point0.ToGeoCoordinateString(ddParam);       // 00.000000N 000.000000E
  geoCoordString = point1.ToGeoCoordinateString(ddParam);       // 20.000000N 010.000000E
});

    now:

// methods need to be on the MCT
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  SpatialReference sr = SpatialReferences.WGS84;
  SpatialReference sr2 = SpatialReferences.WebMercator;

  // create some points
  MapPoint point0 = MapPointBuilder.CreateMapPoint(0, 0, sr);
  MapPoint point1 = MapPointBuilder.CreateMapPoint(10, 20, sr);
  MapPoint point2 = GeometryEngine.Instance.Project(point1, sr2) as MapPoint;
  MapPoint pointEmpty = MapPointBuilder.CreateMapPoint(sr);
  MapPoint pointwithNoSR = MapPointBuilder.CreateMapPoint(1, 1);
  MapPoint pointZM = MapPointBuilder.CreateMapPoint(1, 2, 3, 4, sr);

  // convert to MGRS
  ToGeoCoordinateParameter mgrsParam = new ToGeoCoordinateParameter(GeoCoordinateType.MGRS);
  string geoCoordString = point0.ToGeoCoordinateString(mgrsParam);        // 31NAA6602100000

  // use the builder to create a new point from the string.  Coordinates are the same 
  MapPoint outPoint = MapPointBuilder.FromGeoCoordinateString(geoCoordString, sr, GeoCoordinateType.MGRS);    // outPoint.x = 0; outPoint.Y = 0

  geoCoordString = point1.ToGeoCoordinateString(mgrsParam);             // 32QPH0460911794
  outPoint = MapPointBuilder.FromGeoCoordinateString(geoCoordString, sr, GeoCoordinateType.MGRS);       // outPoint.X = 10; outPoint.Y = 20

  // z, m are not transformed
  geoCoordString = pointZM.ToGeoCoordinateString(mgrsParam);
  outPoint = MapPointBuilder.FromGeoCoordinateString(geoCoordString, sr, GeoCoordinateType.MGRS);     // outPoint.X = 1; outPoint.Y = 2; outPoint.Z = Nan; outPoint.M = Nan;

  // set the number of digits to 2 and convert
  mgrsParam.NumDigits = 2;
  geoCoordString = point1.ToGeoCoordinateString(mgrsParam);             // 32QPH0512
  outPoint = MapPointBuilder.FromGeoCoordinateString(geoCoordString, sr, GeoCoordinateType.MGRS);     // outPoint.X = 10; outPoint.Y = 20


  // convert to UTM
  ToGeoCoordinateParameter utmParam = new ToGeoCoordinateParameter(GeoCoordinateType.UTM);
  geoCoordString = point0.ToGeoCoordinateString(utmParam);        // 31N 166021 0000000
  geoCoordString = point1.ToGeoCoordinateString(utmParam);        // 32Q 604609 2211793

  // convert to DMS
  ToGeoCoordinateParameter dmsParam = new ToGeoCoordinateParameter(GeoCoordinateType.DMS);
  geoCoordString = point0.ToGeoCoordinateString(dmsParam);        // 00 00 00.00N 000 00 00.00E
  geoCoordString = point1.ToGeoCoordinateString(dmsParam);        // 20 00 00.00N 010 00 00.00E

  // convert to DDM
  ToGeoCoordinateParameter ddmParam = new ToGeoCoordinateParameter(GeoCoordinateType.DDM);
  geoCoordString = point0.ToGeoCoordinateString(ddmParam);        // 00 00.0000N 000 00.0000E
  geoCoordString = point1.ToGeoCoordinateString(ddmParam);        // 20 00.0000N 010 00.0000E

  // convert to DD
  ToGeoCoordinateParameter ddParam = new ToGeoCoordinateParameter(GeoCoordinateType.DD);
  geoCoordString = point0.ToGeoCoordinateString(ddParam);       // 00.000000N 000.000000E
  geoCoordString = point1.ToGeoCoordinateString(ddParam);       // 20.000000N 010.000000E
});

Geoprocessing

Get Geoprocessing project items

    before:

var gpItems = CoreModule.CurrentProject.Items.OfType<GeoprocessingProjectItem>();

// go through all the available toolboxes
foreach (var gpItem in gpItems)
{
    var itemsInsideToolBox = await gpItem.GetItemsAsync();

    // then for each toolbox list the tools inside
    foreach (var toolItem in itemsInsideToolBox)
    {
        string newTool = String.Join(";", new string[] { toolItem.Path, toolItem.Name });
        // do something with the newTool
        // for example, add to a list to track or use them later
    }
}

    now:

var gpItems = CoreModule.CurrentProject.Items.OfType<GeoprocessingProjectItem>();

// go through all the available toolboxes
foreach (var gpItem in gpItems)
{
  var itemsInsideToolBox = gpItem.GetItems();

  // then for each toolbox list the tools inside
  foreach (var toolItem in itemsInsideToolBox)
  {
    string newTool = String.Join(";", new string[] { toolItem.Path, toolItem.Name });
    // do something with the newTool
    // for example, add to a list to track or use them later
  }
}

Layouts

Retrieve layout project items

    before:

// get all the layouts
IEnumerable<LayoutProjectItem> layouts = Project.Current.GetItems<LayoutProjectItem>();


// or get a specific layout (by name)
LayoutProjectItem layoutItem = Project.Current.GetItems<LayoutProjectItem>().FirstOrDefault(item => item.Name.Equals("MyLayout"));
if (layoutItem != null)
{
  // Delete the layout from the project
  Project.Current.RemoveAsync(layoutItem);
}

    now:

// get all the layouts
IEnumerable<LayoutProjectItem> layouts = Project.Current.GetItems<LayoutProjectItem>();


// or get a specific layout (by name)
LayoutProjectItem layoutItem = Project.Current.GetItems<LayoutProjectItem>().FirstOrDefault(item => item.Name.Equals("MyLayout"));
if (layoutItem != null)
{
  // Delete the layout from the project
  Project.Current.RemoveItem(layoutItem);
}

Update Text Element properties

    before:

// Reference a layoutitem in a project by name
LayoutProjectItem layoutItem = Project.Current.GetItems<LayoutProjectItem>().FirstOrDefault(item => item.Name.Equals("MyLayout"));
if (layoutItem != null)
{
  ArcGIS.Desktop.Framework.Threading.Tasks.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
        PlacementProperties txtPlacement = txtElm.GetPlacement();
        txtPlacement.Anchor = ArcGIS.Core.CIM.Anchor.CenterPoint;
        txtPlacement.X = x;
        txtPlacement.Y = y;
        txtElm.SetPlacement(txtPlacement);

        // Change TextProperties
        TextProperties txtProperties = new TextProperties("Hello world", "Times New Roman", 48);
        txtElm.SetTextProperties(txtProperties);
      }
    }
  });
}

    now:

// Reference a layoutitem in a project by name
LayoutProjectItem layoutItem = Project.Current.GetItems<LayoutProjectItem>().FirstOrDefault(item => item.Name.Equals("MyLayout"));
if (layoutItem != null)
{
  ArcGIS.Desktop.Framework.Threading.Tasks.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(ArcGIS.Core.CIM.Anchor.CenterPoint);
        txtElm.SetX(x);
        txtElm.SetY(y);

        // Change TextProperties
        TextProperties txtProperties = new TextProperties("Hello world", "Times New Roman", 48, "Regular");
        txtElm.SetTextProperties(txtProperties);
      }
    }
  });
}

Update a picture element

    before:

ArcGIS.Desktop.Framework.Threading.Tasks.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\LakeHuron.jpg");
    }
});

    now:

ArcGIS.Desktop.Framework.Threading.Tasks.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");
  }
});

Lock an element

    before:

// 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.

ArcGIS.Desktop.Framework.Threading.Tasks.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
        ArcGIS.Core.CIM.CIMElement CIMElement = element.Definition as ArcGIS.Core.CIM.CIMElement;
        CIMElement.Locked = true;
        element.SetDefinition(CIMElement);
      }
    }
});

    now:

// 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.

ArcGIS.Desktop.Framework.Threading.Tasks.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
      ArcGIS.Core.CIM.CIMElement CIMElement = element.GetDefinition() as ArcGIS.Core.CIM.CIMElement;
      CIMElement.Locked = true;
      element.SetDefinition(CIMElement);
    }
  }
});

Clone an element

    before:

ArcGIS.Desktop.Framework.Threading.Tasks.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)
    {
      // get the placement properties
      PlacementProperties graPlace = graphicElement.GetPlacement();

      // clone and set the new x,y
      var cloneElement = graphicElement.Clone("Clone");
      graPlace.X = graPlace.X + xOffset;
      graPlace.Y = graPlace.Y - yOffset;
      cloneElement.SetPlacement(graPlace);
    }
  }
});

    now:

ArcGIS.Desktop.Framework.Threading.Tasks.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);
    }
  }
});

Access map frame and map bookmarks from Layout

    before:

// Reference a layoutitem in a project by name
LayoutProjectItem layoutItem = Project.Current.GetItems<LayoutProjectItem>().FirstOrDefault(item => item.Name.Equals("MyLayout"));
if (layoutItem != null)
{
  ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
  {
    // Reference and load the layout associated with the layout item
    Layout layout = layoutItem.GetLayout();
    if (layout == null)
      return;

    // Reference a mapframe by name
    MapFrame mf = layout.Elements.FirstOrDefault(item => item.Name.Equals("MapFrame")) as MapFrame;
    if (mf == null)
      return;

    // get the mapframe's MapView
    ArcGIS.Desktop.Mapping.MapView mv = mf.MapView;
    if (mv == null)
      return;

    // get the map and the bookmarks
    ArcGIS.Desktop.Mapping.Map map = mf.Map;
    var bookmarks = map.GetBookmarks();
    if (bookmarks == null)
      return;

    // Loop through each bookmark
    foreach (var bookmark in bookmarks)
    {
      // Set up a PDF format and set its properties
      ArcGIS.Desktop.Mapping.PDFFormat PDF = new ArcGIS.Desktop.Mapping.PDFFormat();
      String path = String.Format(@"C:\Temp\{0}.pdf", bookmark.Name);
      PDF.OutputFileName = path;

      // Zoom to the bookmark - use 0 just in case the app backstage Navigation Transition Time is > 0 
      mv.ZoomTo(bookmark, TimeSpan.FromSeconds(0));

      // Export to PDF
      if (PDF.ValidateOutputFilePath())
        mf.Export(PDF);
    }
  });
}

    now:

// Reference a layoutitem in a project by name
LayoutProjectItem layoutItem = Project.Current.GetItems<LayoutProjectItem>().FirstOrDefault(item => item.Name.Equals("MyLayout"));
if (layoutItem != null)
{
  ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
  {
    // Reference and load the layout associated with the layout item
    Layout layout = layoutItem.GetLayout();
    if (layout == null)
      return;

    // Reference a mapframe by name
    MapFrame mf = layout.Elements.FirstOrDefault(item => item.Name.Equals("MapFrame")) as MapFrame;
    if (mf == null)
      return;

    // get the map and the bookmarks
    Bookmark bookmark = mf.Map.GetBookmarks().FirstOrDefault(b => b.Name == "Great Lakes");
    if (bookmark == null)
      return;

    // Set up a PDF format and set its properties
    ArcGIS.Desktop.Mapping.PDFFormat PDF = new ArcGIS.Desktop.Mapping.PDFFormat();
    String path = String.Format(@"C:\Temp\{0}.pdf", bookmark.Name);
    PDF.OutputFileName = path;

    // Zoom to the bookmark 
    mf.SetCamera(bookmark);

    // Export to PDF
    if (PDF.ValidateOutputFilePath())
        mf.Export(PDF);
  });
}

Export a layout

    before:

// Reference a layoutitem in a project by name
LayoutProjectItem layoutItem = Project.Current.GetItems<LayoutProjectItem>().FirstOrDefault(item => item.Name.Equals("MyLayout"));
if (layoutItem != null)
{
  ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
  {
    Layout layout = layoutItem.GetLayout();
    if (layout == null)
      return;

    // Create BMP format with appropriate settings
    ArcGIS.Desktop.Mapping.BMPFormat BMP = new ArcGIS.Desktop.Mapping.BMPFormat();
    BMP.Resolution = 300;
    BMP.OutputFileName = @"C:\temp\Layout.bmp";
    if (BMP.ValidateOutputFilePath())
    {
      layout.Export(BMP);
    }

    // Create EMF format with appropriate settings
    ArcGIS.Desktop.Mapping.EMFFormat EMF = new ArcGIS.Desktop.Mapping.EMFFormat();
    EMF.Resolution = 300;
    EMF.OutputFileName = @"C:\temp\Layout.emf";
    if (EMF.ValidateOutputFilePath())
    {
      layout.Export(EMF);
    }

    // create eps format with appropriate settings
    ArcGIS.Desktop.Mapping.EPSFormat EPS = new ArcGIS.Desktop.Mapping.EPSFormat();
    EPS.Resolution = 300;
    EPS.OutputFileName = @"C:\temp\Layout.eps";
    if (EPS.ValidateOutputFilePath())
    {
      layout.Export(EPS);
    }

    // Create GIF format with appropriate settings
    ArcGIS.Desktop.Mapping.GIFFormat GIF = new ArcGIS.Desktop.Mapping.GIFFormat();
    GIF.Resolution = 300;
    GIF.OutputFileName = @"C:\temp\Layout.gif";
    if (GIF.ValidateOutputFilePath())
    {
      layout.Export(GIF);
    }

    // Create JPEG format with appropriate settings
    ArcGIS.Desktop.Mapping.JPEGFormat JPEG = new ArcGIS.Desktop.Mapping.JPEGFormat();
    JPEG.Resolution = 300;
    JPEG.OutputFileName = @"C:\temp\Layout.jpg";
    if (JPEG.ValidateOutputFilePath())
    {
      layout.Export(JPEG);
    }

    // Create PDF format with appropriate settings
    ArcGIS.Desktop.Mapping.PDFFormat PDF = new ArcGIS.Desktop.Mapping.PDFFormat();
    PDF.Resolution = 300;
    PDF.OutputFileName = @"C:\temp\Layout.pdf";
    if (PDF.ValidateOutputFilePath())
    {
      layout.Export(PDF);
    }

    // Create PNG format with appropriate settings
    ArcGIS.Desktop.Mapping.PNGFormat PNG = new ArcGIS.Desktop.Mapping.PNGFormat();
    PNG.Resolution = 300;
    PNG.OutputFileName = @"C:\temp\Layout.png";
    if (PNG.ValidateOutputFilePath())
    {
      layout.Export(PNG);
    }

    // Create SVG format with appropriate settings
    ArcGIS.Desktop.Mapping.SVGFormat SVG = new ArcGIS.Desktop.Mapping.SVGFormat();
    SVG.Resolution = 300;
    SVG.OutputFileName = @"C:\temp\Layout.svg";
    if (SVG.ValidateOutputFilePath())
    {
      layout.Export(SVG);
    }

    // Create TGA format with appropriate settings
    ArcGIS.Desktop.Mapping.TGAFormat TGA = new ArcGIS.Desktop.Mapping.TGAFormat();
    TGA.Resolution = 300;
    TGA.OutputFileName = @"C:\temp\Layout.tga";
    if (TGA.ValidateOutputFilePath())
    {
      layout.Export(TGA);
    }

    // Create TIFF format with appropriate settings
    ArcGIS.Desktop.Mapping.TIFFFormat TIFF = new ArcGIS.Desktop.Mapping.TIFFFormat();
    TIFF.Resolution = 300;
    TIFF.OutputFileName = @"C:\temp\Layout.tif";
    if (TIFF.ValidateOutputFilePath())
    {
      layout.Export(TIFF);
    }
  });
}

    now:

// Reference a layoutitem in a project by name
LayoutProjectItem layoutItem = Project.Current.GetItems<LayoutProjectItem>().FirstOrDefault(item => item.Name.Equals("MyLayout"));
if (layoutItem != null)
{
  ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
  {
    Layout layout = layoutItem.GetLayout();
    if (layout == null)
      return;

    // Create BMP format with appropriate settings
    ArcGIS.Desktop.Mapping.BMPFormat BMP = new ArcGIS.Desktop.Mapping.BMPFormat()
    {
      Resolution = 300,
      OutputFileName = @"C:\temp\Layout.bmp"
    };
    if (BMP.ValidateOutputFilePath())
    {
      layout.Export(BMP);
    }

    // Create EMF format with appropriate settings
    ArcGIS.Desktop.Mapping.EMFFormat EMF = new ArcGIS.Desktop.Mapping.EMFFormat()
    {
      Resolution = 300,
      OutputFileName = @"C:\temp\Layout.emf"
    };
    if (EMF.ValidateOutputFilePath())
    {
      layout.Export(EMF);
    }

    // create eps format with appropriate settings
    ArcGIS.Desktop.Mapping.EPSFormat EPS = new ArcGIS.Desktop.Mapping.EPSFormat()
    {
      Resolution = 300,
      OutputFileName = @"C:\temp\Layout.eps"
    };
    if (EPS.ValidateOutputFilePath())
    {
      layout.Export(EPS);
    }

    // Create GIF format with appropriate settings
    ArcGIS.Desktop.Mapping.GIFFormat GIF = new ArcGIS.Desktop.Mapping.GIFFormat()
    {
      Resolution = 300,
      OutputFileName = @"C:\temp\Layout.gif"
    };
    if (GIF.ValidateOutputFilePath())
    {
      layout.Export(GIF);
    }

    // Create JPEG format with appropriate settings
    ArcGIS.Desktop.Mapping.JPEGFormat JPEG = new ArcGIS.Desktop.Mapping.JPEGFormat()
    {
      Resolution = 300,
      OutputFileName = @"C:\temp\Layout.jpg"
    };
    if (JPEG.ValidateOutputFilePath())
    {
      layout.Export(JPEG);
    }

    // Create PDF format with appropriate settings
    ArcGIS.Desktop.Mapping.PDFFormat PDF = new ArcGIS.Desktop.Mapping.PDFFormat()
    {
      Resolution = 300,
      OutputFileName = @"C:\temp\Layout.pdf"
    };
    if (PDF.ValidateOutputFilePath())
    {
      layout.Export(PDF);
    }

    // Create PNG format with appropriate settings
    ArcGIS.Desktop.Mapping.PNGFormat PNG = new ArcGIS.Desktop.Mapping.PNGFormat()
    {
      Resolution = 300,
      OutputFileName = @"C:\temp\Layout.png"
    };
    if (PNG.ValidateOutputFilePath())
    {
      layout.Export(PNG);
    }

    // Create SVG format with appropriate settings
    ArcGIS.Desktop.Mapping.SVGFormat SVG = new ArcGIS.Desktop.Mapping.SVGFormat()
    {
      Resolution = 300,
      OutputFileName = @"C:\temp\Layout.svg"
    };
    if (SVG.ValidateOutputFilePath())
    {
      layout.Export(SVG);
    }

    // Create TGA format with appropriate settings
    ArcGIS.Desktop.Mapping.TGAFormat TGA = new ArcGIS.Desktop.Mapping.TGAFormat()
    {
      Resolution = 300,
      OutputFileName = @"C:\temp\Layout.tga"
    };
    if (TGA.ValidateOutputFilePath())
    {
      layout.Export(TGA);
    }

    // Create TIFF format with appropriate settings
    ArcGIS.Desktop.Mapping.TIFFFormat TIFF = new ArcGIS.Desktop.Mapping.TIFFFormat()
    {
      Resolution = 300,
      OutputFileName = @"C:\temp\Layout.tif"
    };
    if (TIFF.ValidateOutputFilePath())
    {
      layout.Export(TIFF);
    }
  });
}

Export a map frame

    before:

// Reference a layoutitem in a project by name
LayoutProjectItem layoutItem = Project.Current.GetItems<LayoutProjectItem>().FirstOrDefault(item => item.Name.Equals("MyLayout"));
if (layoutItem != null)
{
  ArcGIS.Desktop.Framework.Threading.Tasks.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
      ArcGIS.Desktop.Mapping.BMPFormat BMP = new ArcGIS.Desktop.Mapping.BMPFormat();
      BMP.HasWorldFile = true;
      BMP.Resolution = 300;
      BMP.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
    }
  });
}

    now:

// Reference a layoutitem in a project by name
LayoutProjectItem layoutItem = Project.Current.GetItems<LayoutProjectItem>().FirstOrDefault(item => item.Name.Equals("MyLayout"));
if (layoutItem != null)
{
  ArcGIS.Desktop.Framework.Threading.Tasks.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
      ArcGIS.Desktop.Mapping.BMPFormat BMP = new ArcGIS.Desktop.Mapping.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
    }
  });
}

Export the active Mapview

    before:

ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  if (MapView.Active != null)
  {
    //Create BMP format with appropriate settings
    ArcGIS.Desktop.Mapping.BMPFormat bmp = new ArcGIS.Desktop.Mapping.BMPFormat();
    bmp.Resolution = 300;
    bmp.Height = 500;
    bmp.Width = 800;
    bmp.HasWorldFile = true;
    bmp.OutputFileName = @"C:\temp\MapView.bmp";

    //Export active map view
    if (bmp.ValidateOutputFilePath())
    {
      MapView.Active.Export(bmp);
    }

    // emf, eps, gif, jpeg, pdf, png, svg, tga, tiff formats also available for export
  }
});

    now:

ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  if (MapView.Active != null)
  {
    //Create BMP format with appropriate settings
    ArcGIS.Desktop.Mapping.BMPFormat bmp = new ArcGIS.Desktop.Mapping.BMPFormat()
    {
      Resolution = 300,
      Height = 500,
      Width = 800,
      HasWorldFile = true,
      OutputFileName = @"C:\temp\MapView.bmp"
    };

    //Export active map view
    if (bmp.ValidateOutputFilePath())
    {
      MapView.Active.Export(bmp);
    }

    // emf, eps, gif, jpeg, pdf, png, svg, tga, tiff formats also available for export
  }
});

MapAuthoring

How to create a new style

    before:

//Full path for the new style file (.stylx) to be created
string styleToCreate = @"C:\Temp\NewStyle.stylx";
await Project.Current.CreateStyleAsync(styleToCreate);

    now:

//Full path for the new style file (.stylx) to be created
string styleToCreate = @"C:\Temp\NewStyle.stylx";
await QueuedTask.Run(() => StyleHelper.CreateStyle(Project.Current, styleToCreate));

How to add a style to project

    before:

//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);

    now:

//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));

How to remove a style from project

    before:

//For ArcGIS Pro system styles,, just pass in the name of the style to remove from the project
await Project.Current.RemoveStyleAsync("3D Vehicles");

//For custom styles, pass in the full path to the style file on disk
string customStyleToRemove = @"C:\Temp\CustomStyle.stylx";
await Project.Current.RemoveStyleAsync(customStyleToRemove);

    now:

//For ArcGIS Pro system styles, just pass in the name of the style to remove from the project
await QueuedTask.Run(() => StyleHelper.RemoveStyle(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.RemoveStyle(Project.Current, customStyleToAdd));

How to determine if a style can be upgraded

    before:

//Pass in the full path to the style file on disk
public async Task<bool> CanUpgradeStyleAsync(string stylePath)
{
  //Add the style to the current project
  await Project.Current.AddStyleAsync(stylePath);
  StyleProjectItem style = Project.Current.GetItems<StyleProjectItem>().First(x => x.Path == stylePath);

  //returns true if style can be upgraded
  return style.CanBeUpgraded();
}

    now:

//Pass in the full path to the style file on disk
public async Task<bool> CanUpgradeStyleAsync(string stylePath)
{
  //Add the style to the current project
  await QueuedTask.Run(() => StyleHelper.AddStyle(Project.Current, stylePath));
  StyleProjectItem style = Project.Current.GetItems<StyleProjectItem>().First(x => x.Path == stylePath);

  //returns true if style can be upgraded
  return style.CanBeUpgraded();
}

How to determine if a style is read-only

    before:

//Pass in the full path to the style file on disk
public async Task<bool> IsReadOnly(string stylePath)
{
  //Add the style to the current project
  await Project.Current.AddStyleAsync(stylePath);
  StyleProjectItem style = Project.Current.GetItems<StyleProjectItem>().First(x => x.Path == stylePath);

  //returns true if style is read-only
  return style.IsReadOnly();
}

    now:

//Pass in the full path to the style file on disk
public async Task<bool> IsReadOnly(string stylePath)
{
  //Add the style to the current project
  await QueuedTask.Run(() => StyleHelper.AddStyle(Project.Current, stylePath));
  StyleProjectItem style = Project.Current.GetItems<StyleProjectItem>().First(x => x.Path == stylePath);

  //returns true if style is read-only
  return style.IsReadOnly();
}

How to determine if a style is current

    before:

//Pass in the full path to the style file on disk
public async Task<bool> IsCurrent(string stylePath)
{
  //Add the style to the current project
  await Project.Current.AddStyleAsync(stylePath);
  StyleProjectItem style = Project.Current.GetItems<StyleProjectItem>().First(x => x.Path == stylePath);

  //returns true if style matches the current Pro version
  return style.IsCurrent();
}

    now:

//Pass in the full path to the style file on disk
public async Task<bool> IsCurrent(string stylePath)
{
  //Add the style to the current project
  await QueuedTask.Run(() => StyleHelper.AddStyle(Project.Current, stylePath));
  StyleProjectItem style = Project.Current.GetItems<StyleProjectItem>().First(x => x.Path == stylePath);

  //returns true if style matches the current Pro version
  return style.IsCurrent();
}

How to upgrade a style

    before:

//Pass in the full path to the style file on disk
public async Task<bool> UpgradeStyleAsync(string stylePath)
{
  bool success = false;

  //Add the style to the current project
  await Project.Current.AddStyleAsync(stylePath);
  StyleProjectItem style = Project.Current.GetItems<StyleProjectItem>().First(x => x.Path == stylePath);

  //Verify that style can be upgraded
  if (style.CanBeUpgraded())
  {
    success = await StyleHelper.UpgradeStyleAsync(style);
  }
  //return true if style was upgraded
  return success;
}

    now:

//Pass in the full path to the style file on disk
public async Task<bool> UpgradeStyleAsync(string stylePath)
{
  bool success = false;

  //Add the style to the current project
  await QueuedTask.Run(() => StyleHelper.AddStyle(Project.Current, stylePath));
  StyleProjectItem style = Project.Current.GetItems<StyleProjectItem>().First(x => x.Path == stylePath);

  //Verify that style can be upgraded
  if (style.CanBeUpgraded())
  {
    success = await QueuedTask.Run(() => StyleHelper.UpgradeStyle(style));
  }
  //return true if style was upgraded
  return success;
}

How to construct a point symbol of a specific color and size

    before:

await QueuedTask.Run(() =>
{
  CIMPointSymbol pointSymbol = SymbolFactory.ConstructPointSymbol(ColorFactory.RedRGB, 10.0);
});

    now:

await QueuedTask.Run(() =>
{
  CIMPointSymbol pointSymbol = SymbolFactory.Instance.ConstructPointSymbol(ColorFactory.Instance.RedRGB, 10.0);
});

How to construct a point symbol of a specific color, size and shape

    before:

await QueuedTask.Run(() =>
{
  CIMPointSymbol starPointSymbol = SymbolFactory.ConstructPointSymbol(ColorFactory.RedRGB, 10.0, SimpleMarkerStyle.Star);
});

    now:

await QueuedTask.Run(() =>
{
  CIMPointSymbol starPointSymbol = SymbolFactory.Instance.ConstructPointSymbol(ColorFactory.Instance.RedRGB, 10.0, SimpleMarkerStyle.Star);
});

How to construct a point symbol from a marker

    before:

await QueuedTask.Run(() =>
{
  CIMMarker marker = SymbolFactory.ConstructMarker(ColorFactory.GreenRGB, 8.0, SimpleMarkerStyle.Pushpin);
  CIMPointSymbol pointSymbolFromMarker = SymbolFactory.ConstructPointSymbol(marker);
});

    now:

await QueuedTask.Run(() =>
{
  CIMMarker marker = SymbolFactory.Instance.ConstructMarker(ColorFactory.Instance.GreenRGB, 8.0, SimpleMarkerStyle.Pushpin);
  CIMPointSymbol pointSymbolFromMarker = SymbolFactory.Instance.ConstructPointSymbol(marker);
});

How to construct a point symbol from a file on disk

    before:

//The following file formats can be used to create the marker: DAE, 3DS, FLT, EMF, JPG, PNG, BMP, GIF
CIMMarker markerFromFile = await SymbolFactory.ConstructMarkerFromFileAsync(@"C:\Temp\fileName.dae");

CIMPointSymbol pointSymbolFromFile = SymbolFactory.ConstructPointSymbol(markerFromFile);

    now:

//The following file formats can be used to create the marker: DAE, 3DS, FLT, EMF, JPG, PNG, BMP, GIF
CIMMarker markerFromFile = await QueuedTask.Run(() => SymbolFactory.Instance.ConstructMarkerFromFile(@"C:\Temp\fileName.dae"));

CIMPointSymbol pointSymbolFromFile = SymbolFactory.Instance.ConstructPointSymbol(markerFromFile);

How to construct a polygon symbol of specific color and fill style

    before:

CIMPolygonSymbol polygonSymbol = SymbolFactory.ConstructPolygonSymbol(ColorFactory.RedRGB, SimpleFillStyle.Solid);

    now:

CIMPolygonSymbol polygonSymbol = SymbolFactory.Instance.ConstructPolygonSymbol(ColorFactory.Instance.RedRGB, SimpleFillStyle.Solid);

How to construct a polygon symbol of specific color, fill style and outline

    before:

CIMStroke outline = SymbolFactory.ConstructStroke(ColorFactory.BlueRGB, 2.0, SimpleLineStyle.Solid);
CIMPolygonSymbol fillWithOutline = SymbolFactory.ConstructPolygonSymbol(ColorFactory.RedRGB, SimpleFillStyle.Solid, outline);

    now:

CIMStroke outline = SymbolFactory.Instance.ConstructStroke(ColorFactory.Instance.BlueRGB, 2.0, SimpleLineStyle.Solid);
CIMPolygonSymbol fillWithOutline = SymbolFactory.Instance.ConstructPolygonSymbol(ColorFactory.Instance.RedRGB, SimpleFillStyle.Solid, outline);

How to construct a polygon symbol without an outline

    before:

CIMPolygonSymbol fillWithoutOutline = SymbolFactory.ConstructPolygonSymbol(ColorFactory.RedRGB, SimpleFillStyle.Solid, null);

    now:

CIMPolygonSymbol fillWithoutOutline = SymbolFactory.Instance.ConstructPolygonSymbol(ColorFactory.Instance.RedRGB, SimpleFillStyle.Solid, null);

How to construct a line symbol of specific color, size and line style

    before:

CIMLineSymbol lineSymbol = SymbolFactory.ConstructLineSymbol(ColorFactory.BlueRGB, 4.0, SimpleLineStyle.Solid);

    now:

CIMLineSymbol lineSymbol = SymbolFactory.Instance.ConstructLineSymbol(ColorFactory.Instance.BlueRGB, 4.0, SimpleLineStyle.Solid);

How to construct a line symbol from a stroke

    before:

CIMStroke stroke = SymbolFactory.ConstructStroke(ColorFactory.BlackRGB, 2.0);
CIMLineSymbol lineSymbolFromStroke = SymbolFactory.ConstructLineSymbol(stroke);

    now:

CIMStroke stroke = SymbolFactory.Instance.ConstructStroke(ColorFactory.Instance.BlackRGB, 2.0);
CIMLineSymbol lineSymbolFromStroke = SymbolFactory.Instance.ConstructLineSymbol(stroke);

How to construct a multilayer line symbol with circle markers on the line ends

    before:

//These methods must be called within the lambda passed to QueuedTask.Run
var lineStrokeRed = SymbolFactory.ConstructStroke(ColorFactory.RedRGB, 4.0);
var markerCircle = SymbolFactory.ConstructMarker(ColorFactory.RedRGB, 12, SimpleMarkerStyle.Circle);
markerCircle.MarkerPlacement = new CIMMarkerPlacementOnVertices()
{
  AngleToLine = true,
  PlaceOnEndPoints = true,
  Offset = 0
};
var lineSymbolWithCircles = new CIMLineSymbol()
{
  SymbolLayers = new CIMSymbolLayer[2] { markerCircle, lineStrokeRed }
};

    now:

//These methods must be called within the lambda passed to QueuedTask.Run
var lineStrokeRed = SymbolFactory.Instance.ConstructStroke(ColorFactory.Instance.RedRGB, 4.0);
var markerCircle = SymbolFactory.Instance.ConstructMarker(ColorFactory.Instance.RedRGB, 12, SimpleMarkerStyle.Circle);
markerCircle.MarkerPlacement = new CIMMarkerPlacementOnVertices()
{
  AngleToLine = true,
  PlaceOnEndPoints = true,
  Offset = 0
};
var lineSymbolWithCircles = new CIMLineSymbol()
{
  SymbolLayers = new CIMSymbolLayer[2] { markerCircle, lineStrokeRed }
};

How to construct a multilayer line symbol with an arrow head on the end

    before:

//These methods must be called within the lambda passed to QueuedTask.Run
var markerTriangle = SymbolFactory.ConstructMarker(ColorFactory.RedRGB, 12, SimpleMarkerStyle.Triangle);
markerTriangle.Rotation = -90; // or -90
markerTriangle.MarkerPlacement = new CIMMarkerPlacementOnLine() { AngleToLine = true, RelativeTo = PlacementOnLineRelativeTo.LineEnd };

var lineSymbolWithArrow = new CIMLineSymbol()
{
  SymbolLayers = new CIMSymbolLayer[2] { markerTriangle,
              SymbolFactory.ConstructStroke(ColorFactory.RedRGB, 2)
          }
};

    now:

//These methods must be called within the lambda passed to QueuedTask.Run
var markerTriangle = SymbolFactory.Instance.ConstructMarker(ColorFactory.Instance.RedRGB, 12, SimpleMarkerStyle.Triangle);
markerTriangle.Rotation = -90; // or -90
markerTriangle.MarkerPlacement = new CIMMarkerPlacementOnLine() { AngleToLine = true, RelativeTo = PlacementOnLineRelativeTo.LineEnd };

var lineSymbolWithArrow = new CIMLineSymbol()
{
  SymbolLayers = new CIMSymbolLayer[2] { markerTriangle,
              SymbolFactory.Instance.ConstructStroke(ColorFactory.Instance.RedRGB, 2)
          }
};

How to get symbol reference from a symbol

    before:

CIMPolygonSymbol symbol = SymbolFactory.ConstructPolygonSymbol(ColorFactory.RedRGB);

//Get symbol reference from the symbol
CIMSymbolReference symbolReference = symbol.MakeSymbolReference();

    now:

CIMPolygonSymbol symbol = SymbolFactory.Instance.ConstructPolygonSymbol(ColorFactory.Instance.RedRGB);

//Get symbol reference from the symbol
CIMSymbolReference symbolReference = symbol.MakeSymbolReference();

How to search for point symbols in a style

    before:

public Task<IList<SymbolStyleItem>> GetPointSymbolsFromStyleAsync(StyleProjectItem style, string searchString)
{
  if (style == null)
    throw new System.ArgumentNullException();

  //Search for point symbols
  return style.SearchSymbolsAsync(StyleItemType.PointSymbol, searchString);
}

    now:

public Task<IList<SymbolStyleItem>> GetPointSymbolsFromStyleAsync(StyleProjectItem style, string searchString)
{
  if (style == null)
    throw new System.ArgumentNullException();

  //Search for point symbols
  return QueuedTask.Run(() => style.SearchSymbols(StyleItemType.PointSymbol, searchString));
}

How to search for line symbols in a style

    before:

public Task<IList<SymbolStyleItem>> GetLineSymbolsFromStyleAsync(StyleProjectItem style, string searchString)
{
  if (style == null)
    throw new System.ArgumentNullException();

  //Search for line symbols
  return style.SearchSymbolsAsync(StyleItemType.LineSymbol, searchString);
}

    now:

public Task<IList<SymbolStyleItem>> GetLineSymbolsFromStyleAsync(StyleProjectItem style, string searchString)
{
  if (style == null)
    throw new System.ArgumentNullException();

  //Search for line symbols
  return QueuedTask.Run(() => style.SearchSymbols(StyleItemType.LineSymbol, searchString));
}

How to search for polygon symbols in a style

    before:

public Task<IList<SymbolStyleItem>> GetPolygonSymbolsFromStyleAsync(StyleProjectItem style, string searchString)
{
  if (style == null)
    throw new System.ArgumentNullException();

  //Search for polygon symbols
  return style.SearchSymbolsAsync(StyleItemType.PolygonSymbol, searchString);
}

    now:

public async Task<IList<SymbolStyleItem>> GetPolygonSymbolsFromStyleAsync(StyleProjectItem style, string searchString)
{
  if (style == null)
    throw new System.ArgumentNullException();

  //Search for polygon symbols
  return await QueuedTask.Run(() => style.SearchSymbols(StyleItemType.PolygonSymbol, searchString));
}

How to search for colors in a style

    before:

public Task<IList<ColorStyleItem>> GetColorsFromStyleAsync(StyleProjectItem style, string searchString)
{
  if (style == null)
    throw new System.ArgumentNullException();

  //Search for colors
  return style.SearchColorsAsync(searchString);
}

    now:

public async Task<IList<ColorStyleItem>> GetColorsFromStyleAsync(StyleProjectItem style, string searchString)
{
  if (style == null)
    throw new System.ArgumentNullException();

  //Search for colors
  return await QueuedTask.Run(() => style.SearchColors(searchString));
}

How to search for color ramps in a style

    before:

public Task<IList<ColorRampStyleItem>> GetColorRampsFromStyleAsync(StyleProjectItem style, string searchString)
{
  //StyleProjectItem can be "ColorBrewer Schemes (RGB)", "ArcGIS 2D"...
  if (style == null)
    throw new System.ArgumentNullException();

  //Search for color ramps
  //Color Ramp searchString can be "Spectral (7 Classes)", "Pastel 1 (3 Classes)", "Red-Gray (10 Classes)"..
  return style.SearchColorRampsAsync(searchString);
}

    now:

public async Task<IList<ColorRampStyleItem>> GetColorRampsFromStyleAsync(StyleProjectItem style, string searchString)
{
  //StyleProjectItem can be "ColorBrewer Schemes (RGB)", "ArcGIS 2D"...
  if (style == null)
    throw new System.ArgumentNullException();

  //Search for color ramps
  //Color Ramp searchString can be "Spectral (7 Classes)", "Pastel 1 (3 Classes)", "Red-Gray (10 Classes)"..
  return await QueuedTask.Run(() => style.SearchColorRamps(searchString));
}

How to search for north arrows in a style

    before:

public Task<IList<NorthArrowStyleItem>> GetNorthArrowsFromStyleAsync(StyleProjectItem style, string searchString)
{
  if (style == null)
    throw new System.ArgumentNullException();

  //Search for north arrows
  return style.SearchNorthArrowsAsync(searchString);
}

    now:

public Task<IList<NorthArrowStyleItem>> GetNorthArrowsFromStyleAsync(StyleProjectItem style, string searchString)
{
  if (style == null)
    throw new System.ArgumentNullException();

  //Search for north arrows
  return QueuedTask.Run(() => style.SearchNorthArrows(searchString));
}

How to search for scale bars in a style

    before:

public Task<IList<ScaleBarStyleItem>> GetScaleBarsFromStyleAsync(StyleProjectItem style, string searchString)
{
  if (style == null)
    throw new System.ArgumentNullException();

  //Search for scale bars
  return style.SearchScaleBarsAsync(searchString);
}

    now:

public Task<IList<ScaleBarStyleItem>> GetScaleBarsFromStyleAsync(StyleProjectItem style, string searchString)
{
  if (style == null)
    throw new System.ArgumentNullException();

  //Search for scale bars
  return QueuedTask.Run(() => style.SearchScaleBars(searchString));
}

How to search for label placements in a style

    before:

public Task<IList<LabelPlacementStyleItem>> GetLabelPlacementsFromStyleAsync(StyleProjectItem style, string searchString)
{
  if (style == null)
    throw new System.ArgumentNullException();

  //Search for standard label placement
  return style.SearchLabelPlacementsAsync(StyleItemType.StandardLabelPlacement, searchString);
}

    now:

public Task<IList<LabelPlacementStyleItem>> GetLabelPlacementsFromStyleAsync(StyleProjectItem style, string searchString)
{
  if (style == null)
    throw new System.ArgumentNullException();

  //Search for standard label placement
  return QueuedTask.Run(() => style.SearchLabelPlacements(StyleItemType.StandardLabelPlacement, searchString));
}

How to apply a point symbol from a style to a feature layer

    before:

// var map = MapView.Active.Map;
// if (map == null)
//        return;
// var pointFeatureLayer =
//       map.GetLayersAsFlattenedList()
//          .OfType<FeatureLayer>()
//         .Where(fl => fl.ShapeType == esriGeometryType.esriGeometryPoint);
//   await ApplySymbolToFeatureLayerAsync(pointFeatureLayer.FirstOrDefault(), "Fire Station");

    public Task ApplySymbolToFeatureLayerAsync(FeatureLayer featureLayer, string symbolName)
    {                       
        return QueuedTask.Run(async () =>
        {
            //Get the ArcGIS 2D System style from the Project
            var arcGIS2DStyle = Project.Current.GetItems<StyleProjectItem>().FirstOrDefault(s => s.Name == "ArcGIS 2D");

            //Search for the symbolName style items within the ArcGIS 2D style project item.
            var items = await arcGIS2DStyle.SearchSymbolsAsync(StyleItemType.PointSymbol, symbolName);

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

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

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

            //Apply the symbol to the feature layer's current renderer
            renderer.Symbol = symbol.MakeSymbolReference();

            //Appy the renderer to the feature layer
            featureLayer.SetRenderer(renderer);
        });            
    }

    now:

// var map = MapView.Active.Map;
// if (map == null)
//        return;
// var pointFeatureLayer =
//       map.GetLayersAsFlattenedList()
//          .OfType<FeatureLayer>()
//         .Where(fl => fl.ShapeType == esriGeometryType.esriGeometryPoint);
//   await ApplySymbolToFeatureLayerAsync(pointFeatureLayer.FirstOrDefault(), "Fire Station");

public Task ApplySymbolToFeatureLayerAsync(FeatureLayer featureLayer, string symbolName)
{
  return QueuedTask.Run(async () =>
  {
          //Get the ArcGIS 2D System style from the Project
          var arcGIS2DStyle = Project.Current.GetItems<StyleProjectItem>().FirstOrDefault(s => s.Name == "ArcGIS 2D");

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

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

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

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

          //Apply the symbol to the feature layer's current renderer
          renderer.Symbol = symbol.MakeSymbolReference();

          //Appy the renderer to the feature layer
          featureLayer.SetRenderer(renderer);
  });
}

How to apply a color ramp from a style to a feature layer

    before:

public async Task ApplyColorRampAsync(FeatureLayer featureLayer, string[] fields)
{

    StyleProjectItem style =
      Project.Current.GetItems<StyleProjectItem>().FirstOrDefault(s => s.Name == "ColorBrewer Schemes (RGB)");
    if (style == null) return;
    var colorRampList = await style.SearchColorRampsAsync("Red-Gray (10 Classes)");
    if (colorRampList == null || colorRampList.Count == 0) return;
    CIMColorRamp cimColorRamp = null;
    CIMRenderer renderer = null;
    await QueuedTask.Run(() =>
    {
        cimColorRamp = colorRampList[0].ColorRamp;
        var rendererDef = new UniqueValueRendererDefinition(fields, null, cimColorRamp);
        renderer = featureLayer?.CreateRenderer(rendererDef);
        featureLayer?.SetRenderer(renderer);
    });

}

    now:

public async Task ApplyColorRampAsync(FeatureLayer featureLayer, string[] fields)
{

    StyleProjectItem style =
      Project.Current.GetItems<StyleProjectItem>().FirstOrDefault(s => s.Name == "ColorBrewer Schemes (RGB)");
    if (style == null) return;
    var colorRampList = await QueuedTask.Run(() => style.SearchColorRamps("Red-Gray (10 Classes)"));
    if (colorRampList == null || colorRampList.Count == 0) return;
    CIMColorRamp cimColorRamp = null;
    CIMRenderer renderer = null;
    await QueuedTask.Run(() =>
    {
        cimColorRamp = colorRampList[0].ColorRamp;
        var rendererDef = new UniqueValueRendererDefinition(fields, null, cimColorRamp);
        renderer = featureLayer?.CreateRenderer(rendererDef);
        featureLayer?.SetRenderer(renderer);
    });

}

Create a new map with a default basemap layer

    before:

await QueuedTask.Run(() =>
    {
var map = MapFactory.CreateMap(mapName, basemap: Basemap.ProjectDefault);
//TODO: use the map...

    });

    now:

await QueuedTask.Run(() =>
    {
var map = MapFactory.Instance.CreateMap(mapName, basemap: Basemap.ProjectDefault);
//TODO: use the map...

    });

Open a webmap

    before:

Map map = null;

//Assume we get the selected webmap from the Project pane's Portal tab
if (Project.Current.SelectedItems.Count > 0)
{
  if (MapFactory.CanCreateMapFrom(Project.Current.SelectedItems[0]))
  {
    map = await MapFactory.CreateMapAsync(Project.Current.SelectedItems[0]);
    await ProApp.Panes.CreateMapPaneAsync(map);
  }
}

    now:

Map map = null;

//Assume we get the selected webmap from the Project pane's Portal tab
if (Project.Current.SelectedItems.Count > 0)
{
  if (MapFactory.Instance.CanCreateMapFrom(Project.Current.SelectedItems[0]))
  {
    map = MapFactory.Instance.CreateMapFromItem(Project.Current.SelectedItems[0]);
    await ProApp.Panes.CreateMapPaneAsync(map);
  }
}

Get Map Panes

    before:

public static IEnumerable<IMapPane> GetMapPanes() {
    //Sorted by Map Uri
    return ProApp.Panes.OfType<IMapPane>().OrderBy((mp) => mp.MapView.Map.URI ?? mp.MapView.Map.Name);
}

    now:

public static IEnumerable<IMapPane> GetMapPanes()
{
  //Sorted by Map Uri
  return ProApp.Panes.OfType<IMapPane>().OrderBy((mp) => mp.MapView.Map.URI ?? mp.MapView.Map.Name);
}

Create and add a layer to the active map

    before:

/*
* string url = @"c:\data\project.gdb\DEM";  //Raster dataset from a FileGeodatabase
* string url = @"c:\connections\mySDEConnection.sde\roads";  //FeatureClass of a SDE
* string url = @"c:\connections\mySDEConnection.sde\States\roads";  //FeatureClass within a FeatureDataset from a SDE
* string url = @"c:\data\roads.shp";  //Shapefile
* string url = @"c:\data\imagery.tif";  //Image from a folder
* string url = @"c:\data\mySDEConnection.sde\roads";  //.lyrx or .lpkx file
* string url = @"http://sampleserver1.arcgisonline.com/ArcGIS/rest/services/Demographics/ESRI_Census_USA/MapServer";  //map service
* string url = @"http://sampleserver6.arcgisonline.com/arcgis/rest/services/NapervilleShelters/FeatureServer/0";  //FeatureLayer off a map service or feature service
*/
string url = @"c:\data\project.gdb\roads";  //FeatureClass of a FileGeodatabase

Uri uri = new Uri(url);
await QueuedTask.Run(() => LayerFactory.CreateLayer(uri, MapView.Active.Map));

    now:

/*
* string url = @"c:\data\project.gdb\DEM";  //Raster dataset from a FileGeodatabase
* string url = @"c:\connections\mySDEConnection.sde\roads";  //FeatureClass of a SDE
* string url = @"c:\connections\mySDEConnection.sde\States\roads";  //FeatureClass within a FeatureDataset from a SDE
* string url = @"c:\data\roads.shp";  //Shapefile
* string url = @"c:\data\imagery.tif";  //Image from a folder
* string url = @"c:\data\mySDEConnection.sde\roads";  //.lyrx or .lpkx file
* string url = @"http://sampleserver1.arcgisonline.com/ArcGIS/rest/services/Demographics/ESRI_Census_USA/MapServer";  //map service
* string url = @"http://sampleserver6.arcgisonline.com/arcgis/rest/services/NapervilleShelters/FeatureServer/0";  //FeatureLayer off a map service or feature service
*/
string url = @"c:\data\project.gdb\roads";  //FeatureClass of a FileGeodatabase

Uri uri = new Uri(url);
await QueuedTask.Run(() => LayerFactory.Instance.CreateLayer(uri, MapView.Active.Map));

Create a feature layer with class breaks renderer with defaults

    before:

await QueuedTask.Run(() =>
  LayerFactory.CreateFeatureLayer(
    new Uri(@"c:\data\countydata.gdb\counties"),
    MapView.Active.Map,
    layerName: "Population Density (sq mi) Year 2010",
    rendererDefinition: new GraduatedColorsRendererDefinition("POP10_SQMI")
  )
);

    now:

await QueuedTask.Run(() =>
  LayerFactory.Instance.CreateFeatureLayer(
    new Uri(@"c:\data\countydata.gdb\counties"),
    MapView.Active.Map,
    layerName: "Population Density (sq mi) Year 2010",
    rendererDefinition: new GraduatedColorsRendererDefinition("POP10_SQMI")
  )
);

Create a feature layer with class breaks renderer

    before:

string colorBrewerSchemesName = "ColorBrewer Schemes (RGB)";
StyleProjectItem style = Project.Current.GetItems<StyleProjectItem>().First(s => s.Name == colorBrewerSchemesName);
string colorRampName = "Greens (Continuous)";
IList<ColorRampStyleItem> colorRampList = await style.SearchColorRampsAsync(colorRampName);
ColorRampStyleItem colorRamp = colorRampList[0];

await QueuedTask.Run(() =>
{
  GraduatedColorsRendererDefinition gcDef = new GraduatedColorsRendererDefinition()
  {
    ClassificationField = "CROP_ACR07",
    ClassificationMethod = ArcGIS.Core.CIM.ClassificationMethod.NaturalBreaks,
    BreakCount = 6,
    ColorRamp = colorRamp.ColorRamp,
    SymbolTemplate = SymbolFactory.ConstructPolygonSymbol(
                      ColorFactory.Green, SimpleFillStyle.Solid, null).MakeSymbolReference(),
    ExclusionClause = "CROP_ACR07 = -99",
    ExclusionSymbol = SymbolFactory.ConstructPolygonSymbol(
                      ColorFactory.Red, SimpleFillStyle.Solid, null).MakeSymbolReference(),
    ExclusionLabel = "No yield",
  };

  LayerFactory.CreateFeatureLayer(new Uri(@"c:\Data\CountyData.gdb\Counties"),
      MapView.Active.Map, layerName: "Crop", rendererDefinition: gcDef);
});

    now:

string colorBrewerSchemesName = "ColorBrewer Schemes (RGB)";
StyleProjectItem style = Project.Current.GetItems<StyleProjectItem>().First(s => s.Name == colorBrewerSchemesName);
string colorRampName = "Greens (Continuous)";
IList<ColorRampStyleItem> colorRampList = await QueuedTask.Run(() =>
{
  return style.SearchColorRamps(colorRampName);
});
ColorRampStyleItem colorRamp = colorRampList[0];

await QueuedTask.Run(() =>
{
  GraduatedColorsRendererDefinition gcDef = new GraduatedColorsRendererDefinition()
  {
    ClassificationField = "CROP_ACR07",
    ClassificationMethod = ArcGIS.Core.CIM.ClassificationMethod.NaturalBreaks,
    BreakCount = 6,
    ColorRamp = colorRamp.ColorRamp,
    SymbolTemplate = SymbolFactory.Instance.ConstructPolygonSymbol(
                      ColorFactory.Instance.GreenRGB, SimpleFillStyle.Solid, null).MakeSymbolReference(),
    ExclusionClause = "CROP_ACR07 = -99",
    ExclusionSymbol = SymbolFactory.Instance.ConstructPolygonSymbol(
                      ColorFactory.Instance.RedRGB, SimpleFillStyle.Solid, null).MakeSymbolReference(),
    ExclusionLabel = "No yield",
  };

  LayerFactory.Instance.CreateFeatureLayer(new Uri(@"c:\Data\CountyData.gdb\Counties"),
      MapView.Active.Map, layerName: "Crop", rendererDefinition: gcDef);
});

Set unique value renderer to the selected feature layer of the active map

    before:

await QueuedTask.Run(() =>
{
  String[] fields = new string[] { "Type" }; //field to be used to retrieve unique values
  CIMPointSymbol pointSym = SymbolFactory.ConstructPointSymbol(
            ColorFactory.Green, 16.0, SimpleMarkerStyle.Pushpin);  //construting a point symbol as a template symbol
  CIMSymbolReference symbolPointTemplate = pointSym.MakeSymbolReference();

  //constructing rederer definition for unique value renderer
  UniqueValueRendererDefinition uniqueValueRendererDef = new UniqueValueRendererDefinition(fields, symbolPointTemplate);

  //creating a unique value renderer
  var flyr = MapView.Active.GetSelectedLayers()[0] as FeatureLayer;
  CIMUniqueValueRenderer uniqueValueRenderer = (CIMUniqueValueRenderer)flyr.CreateRenderer(uniqueValueRendererDef);

  //setting the renderer to the feature layer
  flyr.SetRenderer(uniqueValueRenderer);
});

    now:

await QueuedTask.Run(() =>
{
  String[] fields = new string[] { "Type" }; //field to be used to retrieve unique values
  CIMPointSymbol pointSym = SymbolFactory.Instance.ConstructPointSymbol(
            ColorFactory.Instance.GreenRGB, 16.0, SimpleMarkerStyle.Pushpin);  //constructing a point symbol as a template symbol
  CIMSymbolReference symbolPointTemplate = pointSym.MakeSymbolReference();

  //constructing renderer definition for unique value renderer
  UniqueValueRendererDefinition uniqueValueRendererDef = new UniqueValueRendererDefinition(fields, symbolPointTemplate);

  //creating a unique value renderer
  var flyr = MapView.Active.GetSelectedLayers()[0] as FeatureLayer;
  CIMUniqueValueRenderer uniqueValueRenderer = (CIMUniqueValueRenderer)flyr.CreateRenderer(uniqueValueRendererDef);

  //setting the renderer to the feature layer
  flyr.SetRenderer(uniqueValueRenderer);
});

Create a query layer

    before:

await QueuedTask.Run(() =>
{
  Map map = MapView.Active.Map;
  Geodatabase geodatabase = new Geodatabase(new DatabaseConnectionFile(new Uri(@"C:\Connections\mySDE.sde")));
  CIMSqlQueryDataConnection sqldc = new CIMSqlQueryDataConnection()
  {
    WorkspaceConnectionString = geodatabase.GetConnectionString(),
    GeometryType = esriGeometryType.esriGeometryPolygon,
    OIDFields = "OBJECTID",
    Srid = "102008",
    SqlQuery = "select * from MySDE.dbo.STATES"
  };
  FeatureLayer flyr = (FeatureLayer)LayerFactory.CreateLayer(sqldc, map, layerName: "States");
});

    now:

await QueuedTask.Run(() =>
{
  Map map = MapView.Active.Map;
  Geodatabase geodatabase = new Geodatabase(new DatabaseConnectionFile(new Uri(@"C:\Connections\mySDE.sde")));
  CIMSqlQueryDataConnection sqldc = new CIMSqlQueryDataConnection()
  {
    WorkspaceConnectionString = geodatabase.GetConnectionString(),
    GeometryType = esriGeometryType.esriGeometryPolygon,
    OIDFields = "OBJECTID",
    Srid = "102008",
    SqlQuery = "select * from MySDE.dbo.STATES"
  };
  FeatureLayer flyr = (FeatureLayer)LayerFactory.Instance.CreateLayer(sqldc, map, layerName: "States");
});

Create a raster layer

    before:

string url = @"C:\Images\Italy.tif";
RasterLayer rasterLayer = (RasterLayer)LayerFactory.CreateLayer(new Uri(url), aMap);

    now:

string url = @"C:\Images\Italy.tif";
await QueuedTask.Run(() =>
{
  // Create a raster layer using a path to an image.
  // Note: You can create a raster layer from a url, project item, or data connection.
  rasterLayer = (RasterLayer)LayerFactory.Instance.CreateLayer(new Uri(url), aMap);
});

Update the raster colorizer on a raster layer

    before:

// Get the colorizer from the raster layer
CIMRasterColorizer rasterColorizer = rasterLayer.GetColorizer();
// Update raster colorizer properties
rasterColorizer.Brightness = 10;
rasterColorizer.Contrast = -5;
rasterColorizer.ResamplingType = RasterResamplingType.NearestNeighbor;
// Update the raster layer with the changed colorizer
rasterLayer.SetColorizer(rasterColorizer);

    now:

await QueuedTask.Run(() =>
{
  // Get the colorizer from the raster layer.
  CIMRasterColorizer rasterColorizer = rasterLayer.GetColorizer();
  // Update raster colorizer properties.
  rasterColorizer.Brightness = 10;
  rasterColorizer.Contrast = -5;
  rasterColorizer.ResamplingType = RasterResamplingType.NearestNeighbor;
  // Update the raster layer with the changed colorizer.
  rasterLayer.SetColorizer(rasterColorizer);
});

Update the RGB colorizer on a raster layer

    before:

// Get the colorizer from the raster layer
CIMRasterColorizer rColorizer = rasterLayer.GetColorizer();
// Check if the colorizer is an RGB colorizer
if (rColorizer is CIMRasterRGBColorizer)
{
    CIMRasterRGBColorizer rasterRGBColorizer = (CIMRasterRGBColorizer)rColorizer;
    // Update RGB colorizer properties
    rasterRGBColorizer.StretchType = RasterStretchType.ESRI;
    // Update the raster layer with the changed colorizer
    rasterLayer.SetColorizer((CIMRasterColorizer)rasterRGBColorizer);
}

    now:

await QueuedTask.Run(() =>
{
  // Get the colorizer from the raster layer.
  CIMRasterColorizer rColorizer = rasterLayer.GetColorizer();
  // Check if the colorizer is an RGB colorizer.
  if (rColorizer is CIMRasterRGBColorizer)
  {
    CIMRasterRGBColorizer rasterRGBColorizer = (CIMRasterRGBColorizer)rColorizer;
    // Update RGB colorizer properties.
    rasterRGBColorizer.StretchType = RasterStretchType.ESRI;
    // Update the raster layer with the changed colorizer.
    rasterLayer.SetColorizer((CIMRasterColorizer)rasterRGBColorizer);
  }
});

Create a mosaic layer

    before:

string url = @"C:\Images\countries.gdb\Italy";
MosaicLayer mosaicLayer = (MosaicLayer)LayerFactory.CreateLayer(new Uri(url), aMap);

    now:

MosaicLayer mosaicLayer = null;
string url = @"C:\Images\countries.gdb\Italy";
await QueuedTask.Run(() =>
{
  // Create a mosaic layer using a path to a mosaic dataset.
  // Note: You can create a mosaic layer from a url, project item, or data connection.
  mosaicLayer = (MosaicLayer)LayerFactory.Instance.CreateLayer(new Uri(url), aMap);
});

Update the sort order (mosaic method) on a mosaic layer

    before:

// Get the Image sub-layer of the mosaic
ImageServiceLayer mosaicImageSubLayer = (ImageServiceLayer)mosaicLayer.GetImageLayer();
// Get the mosaic rule
CIMMosaicRule mosaicingRule = mosaicImageSubLayer.GetMosaicRule();
// Set the Mosaic Method to Center
mosaicingRule.MosaicMethod = RasterMosaicMethod.Center;
// Update the mosaic with the changed mosaic rule
mosaicImageSubLayer.SetMosaicRule(mosaicingRule);

    now:

await QueuedTask.Run(() =>
{
  // Get the image sub-layer from the mosaic layer.
  ImageServiceLayer mosaicImageSubLayer = (ImageServiceLayer)mosaicLayer.GetImageLayer();
  // Get the mosaic rule.
  CIMMosaicRule mosaicingRule = mosaicImageSubLayer.GetMosaicRule();
  // Set the Mosaic Method to Center.
  mosaicingRule.MosaicMethod = RasterMosaicMethod.Center;
  // Update the mosaic with the changed mosaic rule.
  mosaicImageSubLayer.SetMosaicRule(mosaicingRule);
});

Update the resolve overlap (mosaic operator) on a mosaic layer

    before:

// Get the Image sub-layer of the mosaic
ImageServiceLayer mosaicImageSublayer = (ImageServiceLayer)mosaicLayer.GetImageLayer();
// Get the mosaic rule
CIMMosaicRule mosaicRule = mosaicImageSublayer.GetMosaicRule();
// Set the Mosaic Operator to Mean
mosaicRule.MosaicOperatorType = RasterMosaicOperatorType.Mean;
// Update the mosaic with the changed mosaic rule
mosaicImageSublayer.SetMosaicRule(mosaicRule);

    now:

await QueuedTask.Run(() =>
{
  // Get the image sub-layer from the mosaic layer.
  ImageServiceLayer mosaicImageSublayer = (ImageServiceLayer)mosaicLayer.GetImageLayer();
  // Get the mosaic rule.
  CIMMosaicRule mosaicRule = mosaicImageSublayer.GetMosaicRule();
  // Set the Mosaic Operator to Mean.
  mosaicRule.MosaicOperatorType = RasterMosaicOperatorType.Mean;
  // Update the mosaic with the changed mosaic rule.
  mosaicImageSublayer.SetMosaicRule(mosaicRule);
});

Create an image service layer

    before:

string url = @"http://imagery.arcgisonline.com/arcgis/services/LandsatGLS/GLS2010_Enhanced/ImageServer";
ImageServiceLayer isLayer = (ImageServiceLayer)LayerFactory.CreateLayer(new Uri(url), aMap);

    now:

ImageServiceLayer isLayer = null;
string url = 
@"http://imagery.arcgisonline.com/arcgis/services/LandsatGLS/GLS2010_Enhanced/ImageServer";
await QueuedTask.Run(() =>
{
  // Create an image service layer using the url for an image service.
  isLayer = (ImageServiceLayer)LayerFactory.Instance.CreateLayer(new Uri(url), aMap);
});

Update the raster colorizer on an image service layer

    before:

// Get the colorizer from the image service layer
CIMRasterColorizer rasterColorizer = isLayer.GetColorizer();
// Update the colorizer properties
rasterColorizer.Brightness = 10;
rasterColorizer.Contrast = -5;
rasterColorizer.ResamplingType = RasterResamplingType.NearestNeighbor;
// Update the image service layer with the changed colorizer
isLayer.SetColorizer(rasterColorizer);

    now:

await QueuedTask.Run(() =>
{
  // Get the colorizer from the image service layer.
  CIMRasterColorizer rasterColorizer = isLayer.GetColorizer();
  // Update the colorizer properties.
  rasterColorizer.Brightness = 10;
  rasterColorizer.Contrast = -5;
  rasterColorizer.ResamplingType = RasterResamplingType.NearestNeighbor;
  // Update the image service layer with the changed colorizer.
  isLayer.SetColorizer(rasterColorizer);
});

Update the RGB colorizer on an image service layer

    before:

// Get the colorizer from the image service layer
CIMRasterColorizer rColorizer = isLayer.GetColorizer();
// Check if the colorizer is an RGB colorizer
if (rColorizer is CIMRasterRGBColorizer)
{
    CIMRasterRGBColorizer rasterRGBColorizer = (CIMRasterRGBColorizer)isLayer.GetColorizer();
    // Update RGB colorizer properties
    rasterRGBColorizer.StretchType = RasterStretchType.ESRI;
    // Update the image service layer with the changed colorizer
    isLayer.SetColorizer((CIMRasterColorizer)rasterRGBColorizer);
}

    now:

await QueuedTask.Run(() =>
{
  // Get the colorizer from the image service layer.
  CIMRasterColorizer rColorizer = isLayer.GetColorizer();
  // Check if the colorizer is an RGB colorizer.
  if (rColorizer is CIMRasterRGBColorizer)
  {
    // Cast colorizer type from CIMRasterColorizer to CIMRasterRGBColorizer.
    CIMRasterRGBColorizer rasterRGBColorizer = (CIMRasterRGBColorizer)rColorizer;
    // Update RGB colorizer properties.
    rasterRGBColorizer.StretchType = RasterStretchType.ESRI;
    // Update the image service layer with the changed colorizer.
    isLayer.SetColorizer((CIMRasterColorizer)rasterRGBColorizer);
  }
});

Update the sort order (mosaic method) on an image service layer

    before:

// Get the mosaic rule of the image service
CIMMosaicRule mosaicRule = isLayer.GetMosaicRule();
// Set the Mosaic Method to Center
mosaicRule.MosaicMethod = RasterMosaicMethod.Center;
// Update the image service with the changed mosaic rule
isLayer.SetMosaicRule(mosaicRule);

    now:

await QueuedTask.Run(() =>
{
  // Get the mosaic rule of the image service.
  CIMMosaicRule mosaicRule = isLayer.GetMosaicRule();
  // Set the Mosaic Method to Center.
  mosaicRule.MosaicMethod = RasterMosaicMethod.Center;
  // Update the image service with the changed mosaic rule.
  isLayer.SetMosaicRule(mosaicRule);
});

Update the resolve overlap (mosaic operator) on an image service layer

    before:

// Get the mosaic rule of the image service
CIMMosaicRule mosaicingRule = isLayer.GetMosaicRule();
// Set the Mosaic Operator to Mean
mosaicingRule.MosaicOperatorType = RasterMosaicOperatorType.Mean;
// Update the image service with the changed mosaic rule
isLayer.SetMosaicRule(mosaicingRule);

    now:

await QueuedTask.Run(() =>
{
  // Get the mosaic rule of the image service.
  CIMMosaicRule mosaicingRule = isLayer.GetMosaicRule();
  // Set the Mosaic Operator to Mean.
  mosaicingRule.MosaicOperatorType = RasterMosaicOperatorType.Mean;
  // Update the image service with the changed mosaic rule.
  isLayer.SetMosaicRule(mosaicingRule);
});

Create a Heatmap Renderer

    before:

string colorBrewerSchemesName = "ArcGIS Colors";
StyleProjectItem style = Project.Current.GetItems<StyleProjectItem>().First(s => s.Name == colorBrewerSchemesName);
string colorRampName = "Heat Map 4 - Semitransparent";
IList<ColorRampStyleItem> colorRampList = await style.SearchColorRampsAsync(colorRampName);
ColorRampStyleItem colorRamp = colorRampList[0];

await QueuedTask.Run(() =>
{
  //defining a heatmap renderer that uses values from Population field as the weights
  HeatMapRendererDefinition heatMapDef = new HeatMapRendererDefinition()
  {
    Radius = 20,
    WeightField = "Population",
    ColorRamp = colorRamp.ColorRamp,
    RendereringQuality = 8,
    UpperLabel = "High Density",
    LowerLabel = "Low Density"
  };

  FeatureLayer flyr = MapView.Active.Map.Layers[0] as FeatureLayer;
  CIMHeatMapRenderer heatMapRndr = (CIMHeatMapRenderer)flyr.CreateRenderer(heatMapDef);
  flyr.SetRenderer(heatMapRndr);
});

    now:

string colorBrewerSchemesName = "ArcGIS Colors";
StyleProjectItem style = Project.Current.GetItems<StyleProjectItem>().First(s => s.Name == colorBrewerSchemesName);
string colorRampName = "Heat Map 4 - Semitransparent";
IList<ColorRampStyleItem> colorRampList = await QueuedTask.Run(() =>
{
  return style.SearchColorRamps(colorRampName);
});
ColorRampStyleItem colorRamp = colorRampList[0];

await QueuedTask.Run(() =>
{
  //defining a heatmap renderer that uses values from Population field as the weights
  HeatMapRendererDefinition heatMapDef = new HeatMapRendererDefinition()
  {
    Radius = 20,
    WeightField = "Population",
    ColorRamp = colorRamp.ColorRamp,
    RendereringQuality = 8,
    UpperLabel = "High Density",
    LowerLabel = "Low Density"
  };

  FeatureLayer flyr = MapView.Active.Map.Layers[0] as FeatureLayer;
  CIMHeatMapRenderer heatMapRndr = (CIMHeatMapRenderer)flyr.CreateRenderer(heatMapDef);
  flyr.SetRenderer(heatMapRndr);
});

Create an Unclassed Renderer

    before:

string colorBrewerSchemesName = "ArcGIS Colors";
StyleProjectItem style = Project.Current.GetItems<StyleProjectItem>().First(s => s.Name == colorBrewerSchemesName);
string colorRampName = "Heat Map 4 - Semitransparent";
IList<ColorRampStyleItem> colorRampList = await style.SearchColorRampsAsync(colorRampName);
ColorRampStyleItem colorRamp = colorRampList[0];

await QueuedTask.Run(() =>
{
  CIMPointSymbol pointSym = SymbolFactory.ConstructPointSymbol(ColorFactory.GreenRGB, 16.0, SimpleMarkerStyle.Diamond);
  CIMSymbolReference symbolPointTemplate = pointSym.MakeSymbolReference();

  //defining an unclassed renderer with custom upper and lower stops
  //all features with value >= 5,000,000 will be drawn with the upper color from the color ramp
  //all features with value <= 50,000 will be drawn with the lower color from the color ramp
  UnclassedColorsRendererDefinition unclassRndrDef = new UnclassedColorsRendererDefinition
                        ("Population", symbolPointTemplate, colorRamp.ColorRamp, "Highest", "Lowest", 5000000, 50000);

  //drawing features with null values with a different symbol
  unclassRndrDef.ShowNullValues = true;
  unclassRndrDef.NullValueLabel = "Unknown";
  CIMPointSymbol nullSym = SymbolFactory.ConstructPointSymbol(ColorFactory.RedRGB, 16.0, SimpleMarkerStyle.Circle);
  unclassRndrDef.NullValueSymbol = nullSym.MakeSymbolReference();
  FeatureLayer flyr = MapView.Active.Map.Layers[0] as FeatureLayer;
  CIMClassBreaksRenderer cbRndr = (CIMClassBreaksRenderer)flyr.CreateRenderer(unclassRndrDef);
  flyr.SetRenderer(cbRndr);
});

    now:

string colorBrewerSchemesName = "ArcGIS Colors";
StyleProjectItem style = Project.Current.GetItems<StyleProjectItem>().First(s => s.Name == colorBrewerSchemesName);
string colorRampName = "Heat Map 4 - Semitransparent";
IList<ColorRampStyleItem> colorRampList = await QueuedTask.Run(() =>
{
  return style.SearchColorRamps(colorRampName);
});
ColorRampStyleItem colorRamp = colorRampList[0];

await QueuedTask.Run(() =>
{
  CIMPointSymbol pointSym = SymbolFactory.Instance.ConstructPointSymbol(ColorFactory.Instance.GreenRGB, 16.0, SimpleMarkerStyle.Diamond);
  CIMSymbolReference symbolPointTemplate = pointSym.MakeSymbolReference();

  //defining an unclassed renderer with custom upper and lower stops
  //all features with value >= 5,000,000 will be drawn with the upper color from the color ramp
  //all features with value <= 50,000 will be drawn with the lower color from the color ramp
  UnclassedColorsRendererDefinition unclassRndrDef = new UnclassedColorsRendererDefinition
                              ("Population", symbolPointTemplate, colorRamp.ColorRamp, "Highest", "Lowest", 5000000, 50000)
  {

    //drawing features with null values with a different symbol
    ShowNullValues = true,
    NullValueLabel = "Unknown"
  };
  CIMPointSymbol nullSym = SymbolFactory.Instance.ConstructPointSymbol(ColorFactory.Instance.RedRGB, 16.0, SimpleMarkerStyle.Circle);
  unclassRndrDef.NullValueSymbol = nullSym.MakeSymbolReference();
  FeatureLayer flyr = MapView.Active.Map.Layers[0] as FeatureLayer;
  CIMClassBreaksRenderer cbRndr = (CIMClassBreaksRenderer)flyr.CreateRenderer(unclassRndrDef);
  flyr.SetRenderer(cbRndr);
});

Create a Proportion Renderer with max and min symbol size capped

    before:

string colorBrewerSchemesName = "ArcGIS Colors";
StyleProjectItem style = Project.Current.GetItems<StyleProjectItem>().First(s => s.Name == colorBrewerSchemesName);
string colorRampName = "Heat Map 4 - Semitransparent";
IList<ColorRampStyleItem> colorRampList = await style.SearchColorRampsAsync(colorRampName);
ColorRampStyleItem colorRamp = colorRampList[0];

await QueuedTask.Run(() =>
{
  CIMPointSymbol pointSym = SymbolFactory.ConstructPointSymbol(ColorFactory.GreenRGB, 1.0, SimpleMarkerStyle.Circle);
  CIMSymbolReference symbolPointTemplate = pointSym.MakeSymbolReference();

  //minimum symbol size is capped to 4 point while the maximum symbol size is set to 50 point
  ProportionalRendererDefinition prDef = new ProportionalRendererDefinition("POPULATION", symbolPointTemplate, 4, 50, true);
  
  //setting upper and lower size stops to stop symbols growing or shrinking beyond those thresholds
  prDef.UpperSizeStop = 5000000;  //features with values >= 5,000,000 will be drawn with maximum symbol size
  prDef.LowerSizeStop = 50000;    //features with values <= 50,000 will be drawn with minimum symbol size

  FeatureLayer flyr = MapView.Active.Map.Layers[0] as FeatureLayer;
  CIMProportionalRenderer propRndr = (CIMProportionalRenderer)flyr.CreateRenderer(prDef);
  flyr.SetRenderer(propRndr);

});

    now:

string colorBrewerSchemesName = "ArcGIS Colors";
StyleProjectItem style = Project.Current.GetItems<StyleProjectItem>().First(s => s.Name == colorBrewerSchemesName);
string colorRampName = "Heat Map 4 - Semitransparent";
IList<ColorRampStyleItem> colorRampList = await QueuedTask.Run(() =>
{
  return style.SearchColorRamps(colorRampName);
});
ColorRampStyleItem colorRamp = colorRampList[0];

await QueuedTask.Run(() =>
{
  CIMPointSymbol pointSym = SymbolFactory.Instance.ConstructPointSymbol(ColorFactory.Instance.GreenRGB, 1.0, SimpleMarkerStyle.Circle);
  CIMSymbolReference symbolPointTemplate = pointSym.MakeSymbolReference();

  //minimum symbol size is capped to 4 point while the maximum symbol size is set to 50 point
  ProportionalRendererDefinition prDef = new ProportionalRendererDefinition("POPULATION", symbolPointTemplate, 4, 50, true)
  {

    //setting upper and lower size stops to stop symbols growing or shrinking beyond those thresholds
    UpperSizeStop = 5000000,  //features with values >= 5,000,000 will be drawn with maximum symbol size
    LowerSizeStop = 50000    //features with values <= 50,000 will be drawn with minimum symbol size
  };
  FeatureLayer flyr = MapView.Active.Map.Layers[0] as FeatureLayer;
  CIMProportionalRenderer propRndr = (CIMProportionalRenderer)flyr.CreateRenderer(prDef);
  flyr.SetRenderer(propRndr);

});

Create a True Proportion Renderer

    before:

string colorBrewerSchemesName = "ArcGIS Colors";
StyleProjectItem style = Project.Current.GetItems<StyleProjectItem>().First(s => s.Name == colorBrewerSchemesName);
string colorRampName = "Heat Map 4 - Semitransparent";
IList<ColorRampStyleItem> colorRampList = await style.SearchColorRampsAsync(colorRampName);
ColorRampStyleItem colorRamp = colorRampList[0];

await QueuedTask.Run(() =>
{
  CIMPointSymbol pointSym = SymbolFactory.ConstructPointSymbol(ColorFactory.GreenRGB, 1.0, SimpleMarkerStyle.Circle);
  CIMSymbolReference symbolPointTemplate = pointSym.MakeSymbolReference();

  //Defining proportional renderer where size of symbol will be same as its value in field used in the renderer.
  ProportionalRendererDefinition prDef = new ProportionalRendererDefinition("POPULATION", esriUnits.esriMeters, symbolPointTemplate, SymbolShapes.Square, ValueRepresentations.Radius);

  FeatureLayer flyr = MapView.Active.Map.Layers[0] as FeatureLayer;
  CIMProportionalRenderer propRndr = (CIMProportionalRenderer)flyr.CreateRenderer(prDef);
  flyr.SetRenderer(propRndr);

});

    now:

string colorBrewerSchemesName = "ArcGIS Colors";
StyleProjectItem style = Project.Current.GetItems<StyleProjectItem>().First(s => s.Name == colorBrewerSchemesName);
string colorRampName = "Heat Map 4 - Semitransparent";
IList<ColorRampStyleItem> colorRampList = await QueuedTask.Run(() =>
{
  return style.SearchColorRamps(colorRampName);
});
ColorRampStyleItem colorRamp = colorRampList[0];

await QueuedTask.Run(() =>
{
  CIMPointSymbol pointSym = SymbolFactory.Instance.ConstructPointSymbol(ColorFactory.Instance.GreenRGB, 1.0, SimpleMarkerStyle.Circle);
  CIMSymbolReference symbolPointTemplate = pointSym.MakeSymbolReference();

  //Defining proportional renderer where size of symbol will be same as its value in field used in the renderer.
  ProportionalRendererDefinition prDef = new ProportionalRendererDefinition("POPULATION", esriUnits.esriMeters, symbolPointTemplate, SymbolShapes.Square, ValueRepresentations.Radius);

  FeatureLayer flyr = MapView.Active.Map.Layers[0] as FeatureLayer;
  CIMProportionalRenderer propRndr = (CIMProportionalRenderer)flyr.CreateRenderer(prDef);
  flyr.SetRenderer(propRndr);

});

Enable labeling on a layer

    before:

var featureLayer = MapView.Active.Map.GetLayersAsFlattenedList().OfType<FeatureLayer>().FirstOrDefault();
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() => {
    // toggle the label visibility
    featureLayer.SetLabelVisibility(!featureLayer.IsLabelVisible);
});

    now:

var featureLayer = MapView.Active.Map.GetLayersAsFlattenedList().OfType<FeatureLayer>().FirstOrDefault();
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  // toggle the label visibility
  featureLayer.SetLabelVisibility(!featureLayer.IsLabelVisible);
});

Access the display field for a layer

    before:

var featureLayer = MapView.Active.Map.GetLayersAsFlattenedList().OfType<FeatureLayer>().FirstOrDefault(); 
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() => {
    // get the CIM definition from the layer
    var cimFeatureDefinition = featureLayer.GetDefinition() as ArcGIS.Core.CIM.CIMBasicFeatureLayer;
    // get the view of the source table underlying the layer
    var cimDisplayTable = cimFeatureDefinition.FeatureTable;
    // this field is used as the 'label' to represent the row
    var displayField = cimDisplayTable.DisplayField;
});

    now:

var featureLayer = MapView.Active.Map.GetLayersAsFlattenedList().OfType<FeatureLayer>().FirstOrDefault();
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  // get the CIM definition from the layer
  var cimFeatureDefinition = featureLayer.GetDefinition() as ArcGIS.Core.CIM.CIMBasicFeatureLayer;
  // get the view of the source table underlying the layer
  var cimDisplayTable = cimFeatureDefinition.FeatureTable;
  // this field is used as the 'label' to represent the row
  var displayField = cimDisplayTable.DisplayField;
});

Find connected attribute field for rotation

    before:

var featureLayer = MapView.Active.Map.GetLayersAsFlattenedList().OfType<FeatureLayer>().FirstOrDefault();
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() => {
    // get the CIM renderer from the layer
    var cimRenderer = featureLayer.GetRenderer() as ArcGIS.Core.CIM.CIMSimpleRenderer;
    // get the collection of connected attributes for rotation
    var cimRotationVariable = cimRenderer.VisualVariables.OfType<ArcGIS.Core.CIM.CIMRotationVisualVariable>().FirstOrDefault();
    // the z direction is describing the heading rotation
    var rotationInfoZ = cimRotationVariable.VisualVariableInfoZ;
    var rotationExpression = rotationInfoZ.Expression; // this expression stores the field name  
});

    now:

var featureLayer = MapView.Active.Map.GetLayersAsFlattenedList().OfType<FeatureLayer>().FirstOrDefault();
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  // get the CIM renderer from the layer
  var cimRenderer = featureLayer.GetRenderer() as ArcGIS.Core.CIM.CIMSimpleRenderer;
  // get the collection of connected attributes for rotation
  var cimRotationVariable = cimRenderer.VisualVariables.OfType<ArcGIS.Core.CIM.CIMRotationVisualVariable>().FirstOrDefault();
  // the z direction is describing the heading rotation
  var rotationInfoZ = cimRotationVariable.VisualVariableInfoZ;
  var rotationExpression = rotationInfoZ.Expression; // this expression stores the field name  
});

Toggle "Scale layer symbols when reference scale is set"

    before:

var featureLayer = MapView.Active.Map.GetLayersAsFlattenedList().OfType<FeatureLayer>().FirstOrDefault(); 
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() => {
    // get the CIM layer definition
    var cimFeatureLayer = featureLayer.GetDefinition() as ArcGIS.Core.CIM.CIMFeatureLayer;
    // turn on the option to scale the symbols in this layer based in the map's reference scale
    cimFeatureLayer.ScaleSymbols = true;
});

    now:

var featureLayer = MapView.Active.Map.GetLayersAsFlattenedList().OfType<FeatureLayer>().FirstOrDefault();
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  // get the CIM layer definition
  var cimFeatureLayer = featureLayer.GetDefinition() as ArcGIS.Core.CIM.CIMFeatureLayer;
  // turn on the option to scale the symbols in this layer based in the map's reference scale
  cimFeatureLayer.ScaleSymbols = true;
});

Set the layer cache

    before:

var featureLayer = MapView.Active.Map.GetLayersAsFlattenedList().OfType<FeatureLayer>().FirstOrDefault();
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() => {
    // change the layer cache type to maximum age
    featureLayer.SetDisplayCacheType(ArcGIS.Core.CIM.DisplayCacheType.MaxAge);
    // change from the default 5 min to 2 min
    featureLayer.SetDisplayCacheMaxAge(TimeSpan.FromMinutes(2));
});

    now:

var featureLayer = MapView.Active.Map.GetLayersAsFlattenedList().OfType<FeatureLayer>().FirstOrDefault();
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  // change the layer cache type to maximum age
  featureLayer.SetDisplayCacheType(ArcGIS.Core.CIM.DisplayCacheType.MaxAge);
  // change from the default 5 min to 2 min
  featureLayer.SetDisplayCacheMaxAge(TimeSpan.FromMinutes(2));
});

Change the layer selection color

    before:

var featureLayer = MapView.Active.Map.GetLayersAsFlattenedList().OfType<FeatureLayer>().FirstOrDefault(); 
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() => {
    // get the CIM definition of the layer
    var layerDef = featureLayer.GetDefinition() as ArcGIS.Core.CIM.CIMBasicFeatureLayer;
    // disable the default symbol
    layerDef.UseSelectionSymbol = false;
    // assign a new color
    layerDef.SelectionColor = ColorFactory.RedRGB;
    // apply the definition to the layer
    featureLayer.SetDefinition(layerDef);

    if (!featureLayer.IsVisible) featureLayer.SetVisibility(true);
    //Do a selection

    MapView.Active.SelectFeatures(MapView.Active.Extent);
});

    now:

var featureLayer = MapView.Active.Map.GetLayersAsFlattenedList().OfType<FeatureLayer>().FirstOrDefault();
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
  // get the CIM definition of the layer
  var layerDef = featureLayer.GetDefinition() as ArcGIS.Core.CIM.CIMBasicFeatureLayer;
  // disable the default symbol
  layerDef.UseSelectionSymbol = false;
  // assign a new color
  layerDef.SelectionColor = ColorFactory.Instance.RedRGB;
  // apply the definition to the layer
  featureLayer.SetDefinition(layerDef);

  if (!featureLayer.IsVisible) featureLayer.SetVisibility(true);
  //Do a selection

  MapView.Active.SelectFeatures(MapView.Active.Extent);
});

MapExploration

Flash selected features

    before:

public Task FlashSelectedFeaturesAsync()
{
    return QueuedTask.Run(() =>
    {
        //Get the active map view.
        var mapView = MapView.Active;
        if (mapView == null)
            return;

        //Get the selected features from the map and filter out the standalone table selection.
        var selectedFeatures = mapView.Map.GetSelection()
            .Where(kvp => kvp.Key is BasicFeatureLayer)
            .ToDictionary(kvp => (BasicFeatureLayer) kvp.Key, kvp => kvp.Value);

        //Flash the collection of features.
        mapView.FlashFeature(selectedFeatures);
    });
}

    now:

public Task FlashSelectedFeaturesAsync()
{
  return QueuedTask.Run(() =>
  {
          //Get the active map view.
          var mapView = MapView.Active;
    if (mapView == null)
      return;

          //Get the selected features from the map and filter out the standalone table selection.
          var selectedFeatures = mapView.Map.GetSelection()
              .Where(kvp => kvp.Key is BasicFeatureLayer)
              .ToDictionary(kvp => (BasicFeatureLayer)kvp.Key, kvp => kvp.Value);

          //Flash the collection of features.
          mapView.FlashFeature(selectedFeatures);
  });
}

Show a custom pop-up

    before:

public void ShowCustomPopup()
{
    //Get the active map view.
    var mapView = MapView.Active;
    if (mapView == null)
        return;

    //Create custom popup content
    var popups = new List<PopupContent>();
    popups.Add(new PopupContent("<b>This text is bold.</b>", "Custom tooltip from HTML string"));
    popups.Add(new PopupContent(new Uri("http://www.esri.com/"), "Custom tooltip from Uri"));

    mapView.ShowCustomPopup(popups);
}

    now:

public void ShowCustomPopup()
{
  //Get the active map view.
  var mapView = MapView.Active;
  if (mapView == null)
    return;

  //Create custom popup content
  var popups = new List<PopupContent>
        {
            new PopupContent("<b>This text is bold.</b>", "Custom tooltip from HTML string"),
            new PopupContent(new Uri("http://www.esri.com/"), "Custom tooltip from Uri")
        };
  mapView.ShowCustomPopup(popups);
}

Project camera into a new spatial reference

    before:

public Task<Camera> ProjectCamera(Camera camera, ArcGIS.Core.Geometry.SpatialReference spatialReference)
{
    return QueuedTask.Run(() =>
    {
        var mapPoint = MapPointBuilder.CreateMapPoint(camera.X, camera.Y, camera.Z, camera.SpatialReference);
        var newPoint = GeometryEngine.Project(mapPoint, spatialReference) as MapPoint;
        var newCamera = new Camera()
        {
            X = newPoint.X,
            Y = newPoint.Y,
            Z = newPoint.Z,
            Scale = camera.Scale,
            Pitch = camera.Pitch,
            Heading = camera.Heading,
            Roll = camera.Roll,
            Viewpoint = camera.Viewpoint,
            SpatialReference = spatialReference
        };
        return newCamera;
    });
}

    now:

public Task<Camera> ProjectCamera(Camera camera, ArcGIS.Core.Geometry.SpatialReference spatialReference)
{
  return QueuedTask.Run(() =>
  {
    var mapPoint = MapPointBuilder.CreateMapPoint(camera.X, camera.Y, camera.Z, camera.SpatialReference);
    var newPoint = GeometryEngine.Instance.Project(mapPoint, spatialReference) as MapPoint;
    var newCamera = new Camera()
    {
      X = newPoint.X,
      Y = newPoint.Y,
      Z = newPoint.Z,
      Scale = camera.Scale,
      Pitch = camera.Pitch,
      Heading = camera.Heading,
      Roll = camera.Roll,
      Viewpoint = camera.Viewpoint,
      SpatialReference = spatialReference
    };
    return newCamera;
  });
}

Graphic Overlay

    before:

public async void GraphicOverlaySnippetTest()
{
    // get the current mapview and point
    var mapView = MapView.Active;
    if (mapView == null)
        return;
    var myextent = mapView.Extent;
    var point = myextent.Center;

    // add point graphic to the overlay at the center of the mapView
    var disposable = await QueuedTask.Run(() =>
    {
        //add these to the overlay
        return mapView.AddOverlay(point,
              SymbolFactory.ConstructPointSymbol(
                      ColorFactory.RedRGB, 30.0, SimpleMarkerStyle.Star).MakeSymbolReference());
    });

    // update the overlay with new point graphic symbol
    MessageBox.Show("Now to update the overlay...");
    await QueuedTask.Run(() =>
    {
        mapView.UpdateOverlay(disposable, point, SymbolFactory.ConstructPointSymbol(
                          ColorFactory.BlueRGB, 20.0, SimpleMarkerStyle.Circle).MakeSymbolReference());
    });

    // clear the overlay display by disposing of the graphic
    MessageBox.Show("Now to clear the overlay...");
    disposable.Dispose();

}

    now:

public async void GraphicOverlaySnippetTest()
{
  // get the current mapview and point
  var mapView = MapView.Active;
  if (mapView == null)
    return;
  var myextent = mapView.Extent;
  var point = myextent.Center;

  // add point graphic to the overlay at the center of the mapView
  var disposable = await QueuedTask.Run(() =>
  {
          //add these to the overlay
          return mapView.AddOverlay(point,
              SymbolFactory.Instance.ConstructPointSymbol(
                      ColorFactory.Instance.RedRGB, 30.0, SimpleMarkerStyle.Star).MakeSymbolReference());
  });

  // update the overlay with new point graphic symbol
  MessageBox.Show("Now to update the overlay...");
  await QueuedTask.Run(() =>
  {
    mapView.UpdateOverlay(disposable, point, SymbolFactory.Instance.ConstructPointSymbol(
                                  ColorFactory.Instance.BlueRGB, 20.0, SimpleMarkerStyle.Circle).MakeSymbolReference());
  });

  // clear the overlay display by disposing of the graphic
  MessageBox.Show("Now to clear the overlay...");
  disposable.Dispose();

}

Change symbol for a sketch tool

    before:

internal class SketchTool_WithSymbol : MapTool
{
    public SketchTool_WithSymbol()
    {
        IsSketchTool = true;
        SketchOutputMode = SketchOutputMode.Map; //Changing the Sketch Symbol is only supported with map sketches.
        SketchType = SketchGeometryType.Rectangle;
    }

    protected override Task OnToolActivateAsync(bool hasMapViewChanged)
    {
        return QueuedTask.Run(() =>
        {
            //Set the Sketch Symbol if it hasn't already been set.
            if (SketchSymbol != null)
                return;
            var polygonSymbol = SymbolFactory.ConstructPolygonSymbol(ColorFactory.CreateRGBColor(24, 69, 59),
                SimpleFillStyle.Solid,
                SymbolFactory.ConstructStroke(ColorFactory.BlackRGB, 1.0, SimpleLineStyle.Dash));
            SketchSymbol = SymbolFactory.MakeSymbolReference(polygonSymbol);
        });
    }
}

    now:

internal class SketchTool_WithSymbol : MapTool
{
  public SketchTool_WithSymbol()
  {
    IsSketchTool = true;
    SketchOutputMode = SketchOutputMode.Map; //Changing the Sketch Symbol is only supported with map sketches.
    SketchType = SketchGeometryType.Rectangle;
  }

  protected override Task OnToolActivateAsync(bool hasMapViewChanged)
  {
    return QueuedTask.Run(() =>
    {
            //Set the Sketch Symbol if it hasn't already been set.
            if (SketchSymbol != null)
        return;
      var polygonSymbol = SymbolFactory.Instance.ConstructPolygonSymbol(ColorFactory.Instance.CreateRGBColor(24, 69, 59),
                        SimpleFillStyle.Solid,
                      SymbolFactory.Instance.ConstructStroke(ColorFactory.Instance.BlackRGB, 1.0, SimpleLineStyle.Dash));
      SketchSymbol = polygonSymbol.MakeSymbolReference();
    });
  }
}

Tasks

Retrieve all the Task Items in a Project

    before:

IEnumerable<TaskProjectItem> tasks = Project.Current.GetItems<TaskProjectItem>();
foreach (var task in tasks)
{
  // do something
}

    now:

IEnumerable<TaskProjectItem> taskItems = Project.Current.GetItems<TaskProjectItem>();
foreach (var item in taskItems)
{
  // do something
}

Open a Project Task Item

    before:

// get the first project task item
var taskItem = Project.Current.GetItems<TaskProjectItem>().FirstOrDefault();
// if there isn't a project task item, return
if (taskItem == null)
  return;

try
{
  // Open it
  System.Guid guid = await TaskAssistantModule.OpenTaskItemAsync(taskItem.TaskGuid);

  // TODO - retain the guid returned for use with CloseTaskAsync
}
catch (OpenTaskException e)
{
  ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show(e.Message);
}

    now:

// get the first project task item
var taskItem = Project.Current.GetItems<TaskProjectItem>().FirstOrDefault();
// if there isn't a project task item, return
if (taskItem == null)
  return;

try
{
  // Open it
  System.Guid guid = await TaskAssistantModule.OpenTaskItemAsync(taskItem.TaskItemGuid);

  // TODO - retain the guid returned for use with CloseTaskAsync
}
catch (OpenTaskException e)
{
  ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show(e.Message);
}

Close a Task Item

    before:

// find the first project task item which is open
var taskItem = Project.Current.GetItems<TaskProjectItem>().FirstOrDefault(t => t.IsOpen == true);
// if there isn't a project task item, return
if (taskItem == null)
  return;

// close it
// NOTE : The task item will also be removed from the project
TaskAssistantModule.CloseTaskAsync(taskItem.TaskGuid);

    now:

// find the first project task item which is open
var taskItem = Project.Current.GetItems<TaskProjectItem>().FirstOrDefault(t => t.IsOpen == true);
// if there isn't a project task item, return
if (taskItem == null)
  return;

// close it
// NOTE : The task item will also be removed from the project
TaskAssistantModule.CloseTaskAsync(taskItem.TaskItemGuid);

Export a Task Item

    before:

// get the first project task item
var taskItem = Project.Current.GetItems<TaskProjectItem>().FirstOrDefault();
// if there isn't a project task item, return
if (taskItem == null)
  return;

try
{
  // export the task item to the c:\Temp folder
  string fileName = await TaskAssistantModule.ExportTaskAsync(taskItem.TaskGuid, @"c:\temp");
  ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("Task saved to " + fileName);
}
catch (ExportTaskException e)
{
  ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("Error saving task " + e.Message);
}

    now:

// get the first project task item
var taskItem = Project.Current.GetItems<TaskProjectItem>().FirstOrDefault();
// if there isn't a project task item, return
if (taskItem == null)
  return;

try
{
  // export the task item to the c:\Temp folder
  string fileName = await TaskAssistantModule.ExportTaskAsync(taskItem.TaskItemGuid, @"c:\temp");
  ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("Task saved to " + fileName);
}
catch (ExportTaskException e)
{
  ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("Error saving task " + e.Message);
}

Sharing

ArcGISPortalManager: Get a portal and Sign In, Set it Active

    before:

//Find the portal to sign in with using its Uri...
var portal = ArcGISPortalManager.Current.GetPortal(new Uri(uri, UriKind.Absolute));
if (!portal.IsSignedOn()) {
    //Calling "SignIn" will trigger the OAuth popup if your credentials are
    //not cached (eg from a previous sign in in the session)
    if (portal.SignIn().success) {
        //Set this portal as my active portal
        ArcGISPortalManager.Current.SetActivePortal(portal);
    }
}

    now:

//Find the portal to sign in with using its Uri...
var portal = ArcGISPortalManager.Current.GetPortal(new Uri(uri, UriKind.Absolute));
if (!portal.IsSignedOn())
{
  //Calling "SignIn" will trigger the OAuth popup if your credentials are
  //not cached (eg from a previous sign in in the session)
  if (portal.SignIn().success)
  {
    //Set this portal as my active portal
    ArcGISPortalManager.Current.SetActivePortal(portal);
  }
}

EsriHttpClient: Get the Current signed on User

    before:

//Reference Newtonsoft - Json.Net
  //Reference System.Net.Http
UriBuilder selfURL = new UriBuilder(PortalManager.GetActivePortal());
selfURL.Path = "sharing/rest/portals/self";
selfURL.Query = "f=json";

EsriHttpResponseMessage response = new EsriHttpClient().Get(selfURL.Uri.ToString());

dynamic portalSelf = JObject.Parse(await response.Content.ReadAsStringAsync());
// if the response doesn't contain the user information then it is essentially
// an anonymous request against the portal
if (portalSelf.user == null)
    return;
string userName = portalSelf.user.username;

    now:

//Reference Newtonsoft - Json.Net
//Reference System.Net.Http
UriBuilder selfURL = new UriBuilder(ArcGISPortalManager.Current.GetActivePortal().PortalUri)
{
  Path = "sharing/rest/portals/self",
  Query = "f=json"
};
EsriHttpResponseMessage response = new EsriHttpClient().Get(selfURL.Uri.ToString());

dynamic portalSelf = JObject.Parse(await response.Content.ReadAsStringAsync());
// if the response doesn't contain the user information then it is essentially
// an anonymous request against the portal
if (portalSelf.user == null)
    return;
string userName = portalSelf.user.username;

Get the Groups for the Current Signed on User

    before:

//Assume that you have executed the "Get the Current signed on User" snippet and have 'userName'
UriBuilder groupsURL = new UriBuilder(PortalManager.GetActivePortal());
groupsURL.Path = String.Format("sharing/rest/community/users/{0}", userName);
groupsURL.Query = "f=json";

var groupResponse = new EsriHttpClient().Get(groupsURL.Uri.ToString());
dynamic portalGroups = JObject.Parse(await groupResponse.Content.ReadAsStringAsync());

string groups = portalGroups.groups.ToString();

    now:

//Assume that you have executed the "Get the Current signed on User" snippet and have 'userName'
UriBuilder groupsURL = new UriBuilder(ArcGISPortalManager.Current.GetActivePortal().PortalUri)
{
  Path = String.Format("sharing/rest/community/users/{0}", userName),
  Query = "f=json"
};
var groupResponse = new EsriHttpClient().Get(groupsURL.Uri.ToString());
dynamic portalGroups = JObject.Parse(await groupResponse.Content.ReadAsStringAsync());

string groups = portalGroups.groups.ToString();

EsriHttpClient: Query for esri content on the active Portal

    before:

//http://www.arcgis.com/sharing/search?q=owner:esri&f=json

UriBuilder searchURL = new UriBuilder(PortalManager.GetActivePortal());
searchURL.Path = "sharing/rest/search";
searchURL.Query = "q=owner:esri&f=json";

EsriHttpClient httpClient = new EsriHttpClient();
var searchResponse = httpClient.Get(searchURL.Uri.ToString());
dynamic resultItems = JObject.Parse(await searchResponse.Content.ReadAsStringAsync());

long numberOfTotalItems = resultItems.total.Value;
long currentCount = 0;

List<dynamic> resultItemList = new List<dynamic>();
// store the first results in the list
resultItemList.AddRange(resultItems.results);
currentCount = currentCount + resultItems.num.Value;
//Up to 50
while (currentCount < numberOfTotalItems && currentCount <= 50) {
    searchURL.Query = String.Format("q=owner:esri&start={0}&f=json", resultItems.nextStart.Value);
    searchResponse = httpClient.Get(searchURL.Uri.ToString());
    resultItems = JObject.Parse(await searchResponse.Content.ReadAsStringAsync());
    resultItemList.AddRange(resultItems.results);
    currentCount = currentCount + resultItems.num.Value;
}

    now:

//http://www.arcgis.com/sharing/search?q=owner:esri&f=json

UriBuilder searchURL = new UriBuilder(ArcGISPortalManager.Current.GetActivePortal().PortalUri)
{
  Path = "sharing/rest/search",
  Query = "q=owner:esri&f=json"
};
EsriHttpClient httpClient = new EsriHttpClient();
var searchResponse = httpClient.Get(searchURL.Uri.ToString());
dynamic resultItems = JObject.Parse(await searchResponse.Content.ReadAsStringAsync());

long numberOfTotalItems = resultItems.total.Value;
long currentCount = 0;

List<dynamic> resultItemList = new List<dynamic>();
// store the first results in the list
resultItemList.AddRange(resultItems.results);
currentCount = currentCount + resultItems.num.Value;
//Up to 50
while (currentCount < numberOfTotalItems && currentCount <= 50) {
    searchURL.Query = String.Format("q=owner:esri&start={0}&f=json", resultItems.nextStart.Value);
    searchResponse = httpClient.Get(searchURL.Uri.ToString());
    resultItems = JObject.Parse(await searchResponse.Content.ReadAsStringAsync());
    resultItemList.AddRange(resultItems.results);
    currentCount = currentCount + resultItems.num.Value;
}

EsriHttpClient: Get a Web Map for the Current User and Add it to Pro

    before:

UriBuilder searchURL = new UriBuilder(PortalManager.GetActivePortal());
searchURL.Path = "sharing/rest/portals/self";
searchURL.Query = "f=json";

EsriHttpClient httpClient = new EsriHttpClient();
EsriHttpResponseMessage response = httpClient.Get(searchURL.Uri.ToString());

dynamic portalSelf = JObject.Parse(await response.Content.ReadAsStringAsync());
// if the response doesn't contain the user information then it is essentially
// an anonymous request against the portal
if (portalSelf.user == null)
    return;
string userName = portalSelf.user.username;

searchURL.Path = "sharing/rest/search";
string webMaps = "(type:\"Web Map\" OR type:\"Explorer Map\" OR type:\"Web Mapping Application\" OR type:\"Online Map\")";
searchURL.Query = string.Format("q=owner:{0} {1}&f=json", userName, webMaps);

var searchResponse = httpClient.Get(searchURL.Uri.ToString());
dynamic resultItems = JObject.Parse(await searchResponse.Content.ReadAsStringAsync());

long numberOfTotalItems = resultItems.total.Value;
if (numberOfTotalItems == 0)
    return;

List<dynamic> resultItemList = new List<dynamic>();
resultItemList.AddRange(resultItems.results);
//get the first result
dynamic item = resultItemList[0];

string itemID = item.id;
Item currentItem = ItemFactory.Create(itemID, ItemFactory.ItemType.PortalItem);

if (MapFactory.CanCreateMapFrom(currentItem)) {
    Map newMap = await MapFactory.CreateMapAsync(currentItem);
    await ProApp.Panes.CreateMapPaneAsync(newMap);
}

    now:

UriBuilder searchURL = new UriBuilder(ArcGISPortalManager.Current.GetActivePortal().PortalUri)
{
  Path = "sharing/rest/portals/self",
  Query = "f=json"
};
EsriHttpClient httpClient = new EsriHttpClient();
EsriHttpResponseMessage response = httpClient.Get(searchURL.Uri.ToString());

dynamic portalSelf = JObject.Parse(await response.Content.ReadAsStringAsync());
// if the response doesn't contain the user information then it is essentially
// an anonymous request against the portal
if (portalSelf.user == null)
    return;
string userName = portalSelf.user.username;

searchURL.Path = "sharing/rest/search";
string webMaps = "(type:\"Web Map\" OR type:\"Explorer Map\" OR type:\"Web Mapping Application\" OR type:\"Online Map\")";
searchURL.Query = string.Format("q=owner:{0} {1}&f=json", userName, webMaps);

var searchResponse = httpClient.Get(searchURL.Uri.ToString());
dynamic resultItems = JObject.Parse(await searchResponse.Content.ReadAsStringAsync());

long numberOfTotalItems = resultItems.total.Value;
if (numberOfTotalItems == 0)
    return;

List<dynamic> resultItemList = new List<dynamic>();
resultItemList.AddRange(resultItems.results);
//get the first result
dynamic item = resultItemList[0];

string itemID = item.id;
Item currentItem = ItemFactory.Instance.Create(itemID, ItemFactory.ItemType.PortalItem);

if (MapFactory.Instance.CanCreateMapFrom(currentItem)) {
    Map newMap = MapFactory.Instance.CreateMapFromItem(currentItem);
    await ProApp.Panes.CreateMapPaneAsync(newMap);
}

EsriHttpClient: Get a Service Layer and Add it to Pro

    before:

UriBuilder searchURL = new UriBuilder(PortalManager.GetActivePortal());
searchURL.Path = "sharing/rest/search";
string layers = "(type:\"Map Service\" OR type:\"Image Service\" OR type:\"Feature Service\" OR type:\"WMS\" OR type:\"KML\")";
//any public layer content
searchURL.Query = string.Format("q={0}&f=json", layers);

EsriHttpClient httpClient = new EsriHttpClient();

var searchResponse = httpClient.Get(searchURL.Uri.ToString());
dynamic resultItems = JObject.Parse(await searchResponse.Content.ReadAsStringAsync());

long numberOfTotalItems = resultItems.total.Value;
if (numberOfTotalItems == 0)
    return;

List<dynamic> resultItemList = new List<dynamic>();
resultItemList.AddRange(resultItems.results);
//get the first result
dynamic item = resultItemList[0];

string itemID = item.id;
Item currentItem = ItemFactory.Create(itemID, ItemFactory.ItemType.PortalItem);

await QueuedTask.Run(async () => {
    // if we have an item that can be turned into a layer
    // add it to the map
    if (LayerFactory.CanCreateLayerFrom(currentItem))
        LayerFactory.CreateLayer(currentItem, MapView.Active.Map);
});

    now:

UriBuilder searchURL = new UriBuilder(ArcGISPortalManager.Current.GetActivePortal().PortalUri)
{
  Path = "sharing/rest/search"
};
string layers = "(type:\"Map Service\" OR type:\"Image Service\" OR type:\"Feature Service\" OR type:\"WMS\" OR type:\"KML\")";
//any public layer content
searchURL.Query = string.Format("q={0}&f=json", layers);

EsriHttpClient httpClient = new EsriHttpClient();

var searchResponse = httpClient.Get(searchURL.Uri.ToString());
dynamic resultItems = JObject.Parse(await searchResponse.Content.ReadAsStringAsync());

long numberOfTotalItems = resultItems.total.Value;
if (numberOfTotalItems == 0)
    return;

List<dynamic> resultItemList = new List<dynamic>();
resultItemList.AddRange(resultItems.results);
//get the first result
dynamic item = resultItemList[0];

string itemID = item.id;
Item currentItem = ItemFactory.Instance.Create(itemID, ItemFactory.ItemType.PortalItem);

await QueuedTask.Run(() =>
{
  // if we have an item that can be turned into a layer
  // add it to the map
  if (LayerFactory.Instance.CanCreateLayerFrom(currentItem))
    LayerFactory.Instance.CreateLayer(currentItem, MapView.Active.Map);
});
⚠️ **GitHub.com Fallback** ⚠️