Posts

Showing posts with the label arcobject

Code snippet: To highlight selected feature in ArcMap programmatically using ArcObjects

Code snippet to highlight selected feature in ArcMap programmatically using ArcObjects and return the  STGeomFromWKB    string of selected feature. To return the geometry you should import   Microsoft.SqlServer.Types   from Nuget and  SqlServerSpatial140.dll   from  C:\Windows\System32 using System; using System.Collections.Generic; using System.Data.SqlTypes; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Windows; using ESRI.ArcGIS.ArcMapUI; using ESRI.ArcGIS.Carto; using ESRI.ArcGIS.Catalog; using ESRI.ArcGIS.CatalogUI; using ESRI.ArcGIS.Desktop.AddIns; using ESRI.ArcGIS.Display; using ESRI.ArcGIS.esriSystem; using ESRI.ArcGIS.Framework; using ESRI.ArcGIS.Geodatabase; using ESRI.ArcGIS.Geometry; using Microsoft.SqlServer.Types; namespace Test.Addin.ArcCommands { class SelectFeatureTool : ESRI.ArcGIS.Desktop.AddIns.Tool { ...

Code Snippet: Select feature polygon(s) on Mouse Click ArcObjects C#

Code snippet of custom feature(s) selection tool on mouse click and highlight it using ArcObjects and C#. class SelectFeatureTool : ESRI.ArcGIS.Desktop.AddIns.Tool { protected override void OnMouseDown(MouseEventArgs arg) { IMxDocument mxDocument = ArcMap.Application.Document as IMxDocument; IActiveView activeView = mxDocument.ActiveView; IMap map = mxDocument.FocusMap; ILayer layer = map.get_Layer(0); //Get 1st Layer IFeatureLayer featureLayer = (IFeatureLayer) layer; IPoint identifyPoint = activeView.ScreenDisplay.DisplayTransformation.ToMapPoint(arg.X, arg.Y); ESRI.ArcGIS.Carto.IIdentify identifyLayer = (IIdentify)layer; IArray array = identifyLayer.Identify(identifyPoint); int oid = -1; if (array != null) { object obj = array.get_Element(0); IFeatureIdentifyObj fobj = obj as IFeatureIdentifyObj; IRowIdentifyObject ir...

Catch Exception - Attempted to read or write protected memory in ESRI ArcObjects .Net 4.0 Framework

First - Don't write the code to throw "Attempted to read or write protected memory" ..it is bad. Second - If you are working on legacy codes and COM objects that throws "Attempted to read or write protected memory" while writing ArcMap add-ins, catch exceptions to prevent application crash, in my case ArcMap. Step #1 - Add following snippet to config file - app.config for Arc-addin <configuration> <runtime> < legacyCorruptedStateExceptionsPolicy enabled = "true" /> </ runtime > </ configuration > Step #2 Add - [HandleProcessCorruptedStateExceptions] [SecurityCritical] on the top of function you are tying catch the exception [HandleProcessCorruptedStateExceptions] [SecurityCritical] public IFeatureLayer GetOrCreateFeatureLayer ( string path , esriGeometryType type , ISpatialReference sr ) { //body }

Code snippet : Create/update polygon attribute fields using Ogr and ESRI Arcobjects

A code snippet example to check if a feature is standalone ESRI Shape or featureclass inside ESRI Gdb, then add new filed or update attribute value in attribute table .... standalone shape/features are created/updated using GDAL/OGR implementation and feature/featureclass stored in ESRI personal GDB are created/updated using ESRI ArcObjects.  Any solution to replace later with GDAL/Ogr is highly appreciated.  Please comment below if you find one. public void AddUpdateAttributeField(string oldFeatureFile) { DriverUtils.RegisterOgrDriver(); DataSource dataSource; Layer layer; var isShapeFile = IsShapeInGdb(oldFeatureFile); if (isShapeFile) { dataSource = Ogr.Open(oldFeatureFile, 1); //second argument in open specifies mode of data, 1 RW & 0 readonly mode layer = dataSource.GetLayerByIndex(0); FieldDefn gdalFiedlDefn = new FieldDefn("FID_GDAL",FieldType.OFTInteger); la...

Clip a raster from feature shape file using C# and ArcObject's geoprocessor

Code snippet in clipping a raster from feature shape file using C# and ArcObject's geoprocessor - public static void ClipRaster(string inRaster, string inClipFeature, string outTempRaster) { Clip clipTool = new Clip(); //set clip parameters clipTool.in_raster = inRaster; clipTool.out_raster = outTempRaster; //clip extent clipTool.in_template_dataset = inClipFeature; Geoprocessor gp = new Geoprocessor(); gp.OverwriteOutput = true; gp.AddOutputsToMap = false; try { IGeoProcessorResult result = (IGeoProcessorResult)gp.ExecuteAsync(clipTool); while(result.Status != esriJobStatus.esriJobSucceeded) { //Console.WriteLine(result.Status.ToString()); System.Threading.Thread.Sleep(100); } } catch (Exception ex) { object level = 0; Console.WriteLi...

Calculate zonal-statistics using ESRI ArcObjects and C#

Import the following references in the project. using ESRI.ArcGIS.Geoprocessor; using ESRI.ArcGIS.SpatialAnalystTools; using ESRI.ArcGIS.esriSystem; This solution is only works for single band raster. For multi-band raster zonal statistics I will make a separate post soon. public static void ComputeZonalStatisticsFromEsri(string feature, string zoneField, string valueRaster, string outputTable) { ESRI.ArcGIS.RuntimeManager.Bind(ESRI.ArcGIS.ProductCode.Desktop); ESRI.ArcGIS.RuntimeManager.BindLicense(ESRI.ArcGIS.ProductCode.Desktop); UID pUid = new UIDClass(); pUid.Value = "esriSpatialAnalystUI.SAExtension"; // Add Spatial Analyst extension to the license manager. object v = null; IExtensionManagerAdmin extensionManagerAdmin = new ExtensionManagerClass(); extensionManagerAdmin.AddExtension(pUid, ref v); // Enable the license. IExtensionManager extensionMana...

Feature to Raster Conversion Using C# and ArcGIS

Import ArcGIS.ConversionTools and ArcGIS.Geoprocessor then pass the file paths as param into following function you will get the resulting raster out of shapefile. using ESRI.ArcGIS.ConversionTools; using ESRI.ArcGIS.Geoprocessor; public static void Rasterize(string inputFeature, string outRaster, string fieldName, int cellSize) { //Runtime manager to find the ESRI product installed in the system ESRI.ArcGIS.RuntimeManager.Bind(ESRI.ArcGIS.ProductCode.Desktop); Geoprocessor geoprocessor = new Geoprocessor(); geoprocessor.OverwriteOutput = true; FeatureToRaster featureToRaster = new FeatureToRaster(); featureToRaster.cell_size = cellSize; featureToRaster.in_features = inputFeature; featureToRaster.out_raster = outRaster; featureToRaster.field = fieldName; geoprocessor.Execute(featureToRaster, null); }

Draw features in ArcMap using ArcGIS Addin tool (Arcobject's IRubberband Interface)

protected override void OnMouseDown(ESRI.ArcGIS.Desktop.AddIns.Tool.MouseEventArgs arg) { //create geometery if (ArcMap.Document != null) { IScreenDisplay screenDisplay = ArcMap.Document.ActiveView.ScreenDisplay; // Constants screenDisplay.StartDrawing(screenDisplay.hDC, (System.Int16)esriScreenCache.esriNoScreenCache); // Explicit Cast IRgbColor rgbColor = new RgbColorClass(); rgbColor.Red = 255; rgbColor.Transparency = 75; IColor color = rgbColor; // Implicit Cast ISimpleFillSymbol simpleFillSymbol = new SimpleFillSymbolClass(); simpleFillSymbol.Color = color; //Draw geometry ISymbol symbol = simpleFillSymbol as ISymbol; // Dynamic Cast IRubberBand rubberBand = new RubberPolygonClass(); IGeometry geometry = rubberBand.TrackNew(screenDisplay, symbol); //check for va...

Getting into ESRI ArcGIS Add-in Development in .Net and ArcObjects

Image
Recently, I landed into a project for ArcGIS/ArcMap Desktop add-in development using ArcObjects in C#. I am a newbie in both ArcObjects and add-in development. Googling through I got tons of snippets on the ArcMap add-in development, but I was not familiar with tailoring them to make a working application. Then, I started to look after Youtube and Amazon to see if any good basic books or tutorials that gives me basic concepts on tailoring the  ArcObjects/.Net snippets. On youtube, I came across a video tutorials series on “.Net programming with ArcOjects” , an excellent tutorial on ArcObjects and .Net development with sample Gis data and codes to download  by Hussein Nasser. I watched all 15 episodes on add-in development using VB.Net. From the Amazon, I bought a book entitled, “Beginning ArcGIS for Desktop Development using .NET ” by Pouria Amirian, with a blind believe on the reviewers, but it turned out the  The book is wonderful! The author does an excell...

Parenting Win-form and WPF form in ArcMap

Parenting of Win-form windows and WPF windows within a ArcMap application using C#.Net code snippets- Step 1: Create a ArcMapWrapper.cs, wrapper class         using System;         using System.Windows.Forms;         using ESRI.ArcGIS.Framework;         namespace ArcMapClassLibrary2         {                 class ArcMapWrapper : IWin32Window                {                      private IApplication _arcMapApplication;                      public ArcMapWrapper( IApplication mApplication)                     {                        _arcMapApplicatio...

Create standalone feature class and feature class inside feature dataset on Geodatabase using ArcObjects

public void StartUp() { try { //create gdb const string path = "D:/SampleDatasets/NewShp"; const string fileGDBName = "sample.gdb"; const string fileGDBAddress = path + "/" + fileGDBName; const string featureDatasetname="polygonFeatureClasses"; const string featureClassname = "MytestPolygons"; if (System.IO.Directory.Exists(fileGDBAddress)) { Console.WriteLine("already exist"); // return; } Type factoryType = Type.GetTypeFromProgID("esriDataSourcesGDB.FileGDBWorkspaceFactory"); IWorkspaceFactory workspaceFactory = (IWorkspaceFactory)Activator.CreateInstance(factoryType); IWorkspaceName workspaceName = workspaceFactory.Create(path, fileGDBName, null,ArcMap.Application.hWnd); MessageBox.Show("gbd created!");   //Create feature dataset ...

GIS Programming for GIS Analyst using Python

Image
Penn state has a nice collection of ArcGIS & Python programming step by step guide for their GEOG 485 students, which is also available for non-students via Penn state website.  This course’s is main aim is to make student able to use the Python scripting language to automate GIS tasks in ArcMap, assemble ArcView geoprocessing tools into models to solve GIS problems, and run the tools from scripts to automate GIS tasks.  Although n o previous programming experience is assumed, the course's target is to make a student as a GIS programmer/analyst in ArcGIS and Python environment.  The course is basically divided into four parts:

Solved: AutomationException 0x80004005 - Unspecified error

I was writing ArcGIS extension for Geoprocessing using JAVA and ArcObjects 10. My need was to process about 1000 PRISM raster datasets globally to compute various environments. My application did work up to 45- 50 raster files without any problems in loop, then if fails with “ AutomationException 0x80004005 - Unspecified error ”. If I restarted the application again works for next 45-50 raster files and then crashes with the same error. I still couldn’t figure out what was the exact cause for application failure-my guess is it may be due to memory management/garbage collection problem among ArcGIS COM objects and JAVA objects. Fortunately, I solved this issue by reinitializing ArcGIS engine (hope re-initialization breaks the locks and flushes the garbage) after 20 raster files processing. Now, the application works well without any breaks but little bit slower while initializing the ArcGIS engine after 20 raster files processing.