TitlePages

Showing posts with label ESRI Addins. Show all posts
Showing posts with label ESRI Addins. Show all posts

Thursday, 15 January 2015

Modifying the Vertices of a Polyline in ArcMap using ArcObjects

Modifying the Vertices of a Polyline using ArcObjects


1.Start the Editing Mode in the Editor Toolbar

2.This will create an edit session

3.Using the editor tool select the polyline feature you want to edit

4.Click on our Custom tool

5.The vertices of our polyline will be visible

6.Save the edits

7.Stop editing and complete the session

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using ESRI.ArcGIS.ArcMapUI;
using ESRI.ArcGIS.Framework;
using ESRI.ArcGIS.esriSystem;
using ESRI.ArcGIS.Editor;
using ESRI.ArcGIS.Display;
using ESRI.ArcGIS.Controls;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.Geometry;


namespace ToolTest
{
    public class poli : ESRI.ArcGIS.Desktop.AddIns.Tool
    {
        public static Boolean mousedown = false;
        public static IEditor3 meditor=null;
        IEditSketch3 editsketch = meditor as IEditSketch3;

        public poli()
        {
        }

        protected override void OnMouseDown(ESRI.ArcGIS.Desktop.AddIns.Tool.MouseEventArgs arg)
        {
            if (mousedown == false)
            {

                meditor = GetEditorFromArcMap(ArcMap.ThisApplication) as IEditor3;
                //IWorkspace workspace = (GetFeatureLayerFromLayerIndexNumber((ArcMap.Application.Document as IActiveView), 1).FeatureClass as IWorkspace);
                //if(meditor.EditState!=esriEditState.esriStateEditing)
                //meditor.StartEditing(workspace);






                IEditSketch3 editsketch = meditor as IEditSketch3;
                editsketch.GeometryType = esriGeometryType.esriGeometryPolyline;


                 IEditTaskSearch editTaskSearch = meditor as IEditTaskSearch;
 IEditTask editTask = editTaskSearch.get_TaskByUniqueName("GarciaUI_ModifyFeatureTask");

  //Set the task returned to the current edit task.
 if (editTask != null)
 {
     meditor.CurrentTask = editTask;
 }
                ISketchOperation sk = new SketchOperationClass();
                sk.Start(meditor);

             

             
            }
            if(mousedown==true)
            {
                if(editsketch.Geometry==null)
                {
                    IPolyline poly;
                    poly = editsketch as IPolyline;
                    editsketch.FinishSketch();

                }
                else
                {
                    mousedown=false;
                }


            }
       

         
        }


        protected override void OnMouseUp(ESRI.ArcGIS.Desktop.AddIns.Tool.MouseEventArgs arg)
        {
         
        }

public ESRI.ArcGIS.Editor.IEditor2 GetEditorFromArcMap(ESRI.ArcGIS.ArcMapUI.IMxApplication mxApplication)
{
  if(mxApplication == null)
  {
    return null;
  }
  ESRI.ArcGIS.esriSystem.UID uid = new ESRI.ArcGIS.esriSystem.UIDClass();
  uid.Value = "{F8842F20-BB23-11D0-802B-0000F8037368}";
  ESRI.ArcGIS.Framework.IApplication application = mxApplication as ESRI.ArcGIS.Framework.IApplication; // Dynamic Cast
  ESRI.ArcGIS.esriSystem.IExtension extension = application.FindExtensionByCLSID(uid);
  ESRI.ArcGIS.Editor.IEditor2 editor2 = extension as ESRI.ArcGIS.Editor.IEditor2; // Dynamic Cast

  return editor2;
}




public ESRI.ArcGIS.Carto.IFeatureLayer GetFeatureLayerFromLayerIndexNumber(ESRI.ArcGIS.Carto.IActiveView activeView, System.Int32 layerIndex)
{
    if (activeView == null || layerIndex < 0)
    {
        return null;
    }
    ESRI.ArcGIS.Carto.IMap map = activeView.FocusMap;
    if (layerIndex < map.LayerCount && map.get_Layer(layerIndex) is ESRI.ArcGIS.Carto.IFeatureLayer)
    {
        return (ESRI.ArcGIS.Carto.IFeatureLayer)activeView.FocusMap.get_Layer(layerIndex); // Explicit Cast
    }
    else
    {
        return null;
    }
}
public ESRI.ArcGIS.Geometry.IPointCollection4 modifyFirstVertexOfAPolyline
(ESRI.ArcGIS.Geometry.IGeometryCollection geometryCollection_Polyline,
System.Double searchRadius, System.Double offsetX, System.Double offsetY)
{
    ESRI.ArcGIS.Geometry.IPolyline polyline = (ESRI.ArcGIS.Geometry.IPolyline)
        geometryCollection_Polyline;
    ESRI.ArcGIS.Geometry.IPoint queryPoint = polyline.FromPoint;

    ESRI.ArcGIS.Geometry.IPoint hitPoint = new ESRI.ArcGIS.Geometry.PointClass();

    //Define and initialize the variables that will get populated from the .HitTest() method.
    System.Double hitDistance = 0;
    System.Int32 hitPartIndex = 0;
    System.Int32 hitSegmentIndex = 0;
    System.Boolean rightSide = false;

    ESRI.ArcGIS.Geometry.IHitTest hitTest = (ESRI.ArcGIS.Geometry.IHitTest)
        geometryCollection_Polyline;
    System.Boolean foundGeometry = hitTest.HitTest(queryPoint, searchRadius,
        ESRI.ArcGIS.Geometry.esriGeometryHitPartType.esriGeometryPartVertex,
        hitPoint, ref hitDistance, ref hitPartIndex, ref hitSegmentIndex, ref
        rightSide);

    if (foundGeometry == true)
    {
        ESRI.ArcGIS.Geometry.IGeometry geometry =
            geometryCollection_Polyline.get_Geometry(hitPartIndex);
        ESRI.ArcGIS.Geometry.IPointCollection4 pointCollection =
            (ESRI.ArcGIS.Geometry.IPointCollection4)geometry;
        ESRI.ArcGIS.Geometry.IPoint transformPoint = pointCollection.get_Point
            (hitSegmentIndex);

        ESRI.ArcGIS.Geometry.ITransform2D transform2D =
            (ESRI.ArcGIS.Geometry.ITransform2D)transformPoint;
        transform2D.Move(offsetX, offsetY);

        ESRI.ArcGIS.Geometry.IPoint afterMovePoint = (ESRI.ArcGIS.Geometry.IPoint)
            transform2D;

        //The point is not updated in the polyline until the next line is called.
        pointCollection.UpdatePoint(hitSegmentIndex, (ESRI.ArcGIS.Geometry.IPoint)
            transform2D);

        return pointCollection;
    }

    return null;

}

        protected override void OnUpdate()
        {
            Enabled = ArcMap.Application != null;
        }
    }

}

Wednesday, 24 December 2014

ArcGIS Python Mapping Module


Arc Python to interact with Arc-map

What is ArcPy Mapping and Why is it actually used for :

Arcpy.mapping was built for the professional GIS analyst (as well as for developers). Traditionally, the scenarios listed above had to be done using ArcObjects and it often proved to be a very difficult programming environment to learn for the average GIS professional. Arcpy.mapping is a courser-grained object model, meaning that the functions are designed in a way that a single arcpy.mapping function can replace many lines of ArcObjects code. The following is a very simple example of how arcpy.mapping can be used to reference an existing map document and export it to a PDF document with only two lines of code.

To explore the Overall Arcpy mapping Module use the following PDF:

Arcpy Python Mapping Module


Code for Getting the reference to the MXD :

YourMXD= arcpy.mapping.MapDocument("path to the MXD")

To export the above MXD to PDF using arcpy:

arcpy.mapping.ExportToPdf(YourMXD,"your pdf file")



Get Reference to the Current Arcmap
Pointer to a MXD present on the Disk


Map Layout Document in the Arc map
Layout View of the Map Document

Arcpy.mapping is not a replacement for ArcObjects but rather an alternative for the different scenarios it supports. ArcObjects is still necessary for finer-grain development and application customization, whereas arcpy.mapping is intended for automating the contents of existing map documents and layer files.



Creating Geodatabases using Arcpy or Model builder

Creating Geo-databases in Arc Map

What is a Geodatabase:
  • A geodatabase is the common data storage and management framework for all the ArcGIS Products. It combines Geo (spatial data) with Database (data repository) to create a central data repository for all the spatial data storage and management in your ArcGIS platform.
  • It can be leveraged in desktop, server, or mobile environments and allows you to store GIS data in a central location for easy access and management.
The geodatabase offers you the ability to
  • Store a rich collection of spatial data in a centralized location.
  • Apply sophisticated rules and relationships to the data.
  • Define advanced geospatial relational models (e.g., topologies, networks).
  • Maintain integrity of spatial data with a consistent, accurate database.
  • Work within a multiuser access and editing environment.
  • Integrate spatial data with other IT databases.
  • Easily scale your storage solution.
  • Support custom features and behavior.
  • Leverage your spatial data to its full potential.
Arc-map geodatabase can be created using various way:
  1. Manually creating through Arc-Catalog
  2. Using the Model workflow to create it Programmatic-ally
  3. Using the Python integrated to Create Geodatabase Programmatic
  1. Model for Creating Feature Class
Model to create Geodatabase in ArcGIS
Set the workspace and OutputFC as the Model parameter

AddField will add a column to the newly created Feature class and can be populated with the user defined values

The Search, Insert or Update cursor can be used to manipulate the values present in the new Feature class

For achieving the above functionality it is advised to write a python code using the arcpy library.

To know more detailed step by step information about the creating a feature class in the Geodatabase
Click here - Create Geodatabase Feature Class - PDF




Exporting the feature class to CSV Format


Exporting Geodatabase toComma Separated Value Format

Let start creating an python addin for converting the feature class in your geodatabase to CSV format.So that everyone can understand your feature class and its values.
  • If you are very new to python addin then go through- How to start with python addin 
  • The input feature class and output csv file path are hard coded in the sample program
  • For dynamic conversion get the path of the files through a variable and pass it as a parameter to the defined functions
Comma Seperated values
CSV Fromat



def ex_fc_to_csv(fc, out_csv):
    """
    Export all vertex in a line or poly feature class to a csv with OID
   
    example

        import geom_snippets
        geom_snippets.ex_fc_to_csv(r"c:\proj\fc1.shp", r"c:\proj\fc1.csv")

    output csv looks like this

        1,56019.99998067904,69118.00001450378
        1,56159.99998080942,69026.0000144181
        1,56359.999980995686,68913.00001431286
        2,34985.00002508866,68936.00001433428
        2,35178.000025268404,68805.00001421227

    """
    import csv
    import json

    with open(out_csv, 'w') as csvfile:
        csvwriter = csv.writer(csvfile, delimiter=',', lineterminator='\n')

        with arcpy.da.SearchCursor(fc,
                                   field_names=("OID@","SHAPE@JSON")) as cursor:
            for row in cursor:
                geom = json.loads(row[1])
                for path in geom['paths']:
                    for pt in path:
                        csvwriter.writerow([row[0]] + pt)

Friday, 12 December 2014

How to check for condition in Geoprocessing Service or Model Builder

How to check for if/else conditions in Geoprocessing Service


TOOL USED:  
Arc python and Script tool
Python script will be deployed in the ARC Toolbox to create the Conversion Tool 

WORKING OF THE TOOL:
Script tool is created in the ArcMap and the required input & Output Parameter are set. The script tool source is set to the custom python code present in an Python file(.py)
Out motive is to use check for the count of a features in an feature class and performing an conditional Execution

PROCEDURE:
  • Open ArcMap 10.0+ 
  • Create your own Geometric Network or Open your Existing Geometric Network
  • Add your Geometric network to the Table of contents in the ArcMap as Shown Below


·         Create a new Model in your myToolBox .Right Click on MyToolBox > New > Model.Following window will appear on the Screen 







  •    Add your desired feature class to the Model. (Right Click on any empty space and select ADD DATA  and select your feature class in the object browser)
  • ·         Add Get Count and Calculate value Model from the System Toolbox Connect the model as shown below 






  • ·         Now open calculate value Model and in the Expression Textbox call the function Calculate(%RowCount%)
  • ·         Here %RowCount% will act as an Inline Variable and Compiler automatically replace the %RowCount% with the value of the rowcount field
  • ·         At the Code block defined the function Calculate as

def calculate(row):
if row>0:
return true
else:
return false
  • ·         Make the return Data type as Boolean
  • ·         The output Boolean can be set as a precondition for any model. So that the Model  get executes only when the output of calculate value is true






How to create Graphical User Interface in Arcpy

To Show GUI in your Script tool of your ArcMap



Python consist of  huge number of GUI frameworks (or toolkits) available for it, from TkInter to a number of other cross-platform solutions.

In your case we going to use the default TkInter Module to access the windows form from the python script tool.
TkInter is being proposed as the most interactive and easy to program module in Python GUI framework

1. Create a new Script tool in the Arcmap's ArcCatalog window in your desired location
2. Copy the below codes in to a notepad file and save it as python .py extension
3.Go to the script tool and Right Click > Properties > Parameter
4.Browse to your newly created python code as the source file to execute
5.All is well.Start GUI python from TkInter. Happy Programming




from Tkinter import *
import datetime
from array import *



root = Tk()
logo = PhotoImage(file="Image.Gif")
w2 = Label(root,
           image=logo).grid(row=0,column=1)
explanation = """Team Geo Zoner"""
w2 = Label(root, 
          compound = CENTER,
           fg="Red",
           bg="black",
           font="Times 55 bold",
          text=explanation)
w2.grid(row=0,column=0)

p=str(datetime.datetime.now().isoformat())
texter="Your Heading Goes Here"+str(p);
w3 = Label(root, 
          compound = CENTER,
           fg="Green",
           font="Times 20 bold",
          text=texter)
w3.grid(row=1,column=0)

Parameters = ['Number of Inputs','Number of Ouputs','Number of Processing Parameters','Number of Intermediate data']

r = 2
i=1
for c in Parameters:
    Label(text=c, relief=RIDGE,width=25).grid(row=r,column=0)
    Entry(text="Value", relief=SUNKEN,width=10).grid(row=r,column=1)
    r = r + 1
    i = i + 1

root.title("GISSTUDY")
root.mainloop()

Thursday, 11 December 2014

Performance issues on ArcGIS Geoprocessing Service

How to improve Geo-processing Execution Speed

Geoprocessing services hosted in the ArcGIS server needs to be pretty fast and accurate. User will always want the service to be the fastest. Since ArcGIS Server will be able to service multiple users at one instant of time, inefficient services can overload your server and increase the processing time. The more efficient and intelligent your services, the more users can be serviced with the same computing resources at a smaller amount of time.

Below are some of the tips and techniques that helps in increasing the performance of your Geo-processing Services.

Use local paths to data and resources

The more faster the data requires to be processed is accessible by the server the more faster your service will be.It is good to copy your data to the server rather than placing it on the shared location and asking the server to access it.(Copying the server will be effective only if the Geo processing input data is very small in size and also when the input data is not dynamic)
Reading data from the local area network will be slow compared to accessing the data from the local disk.. 


Reading and Writing the Intermediate data IN_Memory


The service execution speed will get increased by multiple times when the intermediate data is allowed to stored in the machine memory(RAM).Input and output operation is the slowest of all the computing operations.In Geoprocessing storing the intermediate data in a file geodatabase or personnel Geodatabase will take maximum of the execution time.
Please be sure the data which your are storing in the memory as an intermediate data need not be necessary after the execution is complete.Because once the execution is complete the data in the memory will get cleared.Don't write large amount of data to the in_memory as it may affect the performance of the processing service.
To write to your computer's memory, use the pathname in_memory, as follows:
          in_memory\your featureclassname




Use layers from a source map document

If a service uses a source map document instead of feature classes and datasets, it will tremendously increase the performance of the service.Your models and scripts can use map layers from the source map document so that it will impose less load on the processor and significantly decrease the execution time. A layer references a dataset on disk or feature class on a geodatabase, and some layers cache properties about the dataset. Therefore by using dataset layer instead of the direct dsataset or feature class,there is a performance advantage because ArcMap opens the dataset once, caches basic properties of the dataset, and keeps the dataset open. When the Service executes, the dataset need not to be  reopened because the source map document already it is opened and it will gives us a performance boost.


Write data to shapefiles

Storing the data to shapefiles is a bit faster than writing to other formats but writing data to memory, described above, is the fastest of all. Even then there is further more limitations on the shapefiles such field names should be  as 10 character , no null values, and limited support for date/time, to name a few. This become more helpful if the you are running your model locally on your Desktop

Tuesday, 9 December 2014

ArcObjects to add a flag to the Geometric Network .Net

Creating a Flag in ArcMap using ArcObjects .NET


1. Add a new add-in component to the CreatingOutputs solution and name the component
AddFlagTool. Select Tool as the type of add-in, set the confi guration of the tool as shown in

2. Enter the following using directives at the top of the AddFlagTool.cs fi le’s code window:
using ESRI.ArcGIS.ArcMapUI;
using ESRI.ArcGIS.Geometry;
using ESRI.ArcGIS.Display;
using ESRI.ArcGIS.Carto;
3. You are going to write the code for handling the OnMouseDown event. In other words, you want
your code to be executed when a user clicks somewhere in the main window of the software application. Because all the events and their handlers are defined in the base class of all tools(ESRI.ArcGIS.Desktop.AddIns.Tool), you have to override the necessary handlers. So write
the following code in the AddflagTool.cs file inside the definition for the AddflagTool class and outside of any method: protected override
As soon as you type these two keywords and press the spacebar, you will see the list of all available handlers.
Find OnMouseDown in the list as shown in  below Figure and press Enter.




4.On the Mouse down event call the add flag function in the another library

5.For the Add flag function add the following code in the other library addflag function

        public static void AddFlag(IPoint pPnt, IApplication app, double snapTol)
        {
            //IProgressDialogFactory pProDFact = null;
            //IStepProgressor pStepPro = null;
            //IProgressDialog2 pProDlg = null;
            //ITrackCancel pTrkCan = null;
            IGeometricNetwork gn = null;
            IPoint snappedPoint = null;
            IFlagDisplay pFlagDisplay = null;
            INetFlag startNetFlag = null;

            INetworkAnalysisExt pNetAnalysisExt = null;
            IMap pMap = null;
            UID pID = null;
            int EID = -1;


            try
            {

                pID = new UID();

                pID.Value = "esriEditorExt.UtilityNetworkAnalysisExt";
                pNetAnalysisExt = (INetworkAnalysisExt)app.FindExtensionByCLSID(pID);
                gn = pNetAnalysisExt.CurrentNetwork;

                pMap = (app.Document as IMxDocument).FocusMap;
                startNetFlag = Globals.GetJunctionFlagWithGN(ref pPnt, ref pMap, ref gn, snapTol,out snappedPoint, out EID, out  pFlagDisplay, true) as INetFlag;
                if (startNetFlag == null)
                {
                    //startNetFlag = Globals.GetEdgeFlag(ref pPnt, ref pMap, ref gnList, snapTol, ref gnIdx, out snappedPoint, out EID, out distanceAlong, out  pFlagDisplay, true) as INetFlag;
                }


                if (app != null)
                {
                    
                    Globals.AddFlagToGN(ref pNetAnalysisExt, ref  gn, ref pFlagDisplay);
                    //  pFlagDisplay
                    pNetAnalysisExt = null;
                    pID = null;

                }



            }
            catch (Exception)
            {
                
                throw;
            }
        }
5. The above function will make a call to the getJunctionflag code.create a function block called "getjunctionflag" with the class library Global  and place the below code:



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ESRI.ArcGIS.SystemUI;
using ESRI.ArcGIS.Geometry;
using ESRI.ArcGIS.GeoDatabaseUI;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.Framework;
using ESRI.ArcGIS.esriSystem;
using ESRI.ArcGIS.Display;
using ESRI.ArcGIS.DataSourcesGDB;
using ESRI.ArcGIS.DataSourcesFile;
using ESRI.ArcGIS.CartoUI;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.ArcMapUI;
using ESRI.ArcGIS.ArcMap;
using ESRI.ArcGIS.NetworkAnalysis;
using ESRI.ArcGIS.NetworkAnalyst;
using ESRI.ArcGIS.EditorExt;



namespace Toolkit
{
    class Globals
    {
        public enum GNTypes
        {
            Flags = 1, Barries = 2, Results = 3

        };

        public enum flagType { EdgeFlag, JunctionFlag, EdgeBarrier, JunctionBarrier };
    

        public static IJunctionFlag GetJunctionFlagWithGN(ref IPoint point, ref IMap map, ref IGeometricNetwork gn, double snapTol, out IPoint snappedPoint, out int EID, out  IFlagDisplay pFlagDisplay, bool Flag)
        {
            //Initialize output variables
            snappedPoint = null;
            EID = -1;
            pFlagDisplay = null;
            int FCID = -1, FID = -1, subID = -1;

            IGeoDataset pDS = null;
            IPointToEID pointToEID = null;
            INetElements netElements = null;
            INetFlag junctionFlag = null;
            try
            {
                pFlagDisplay = null;

                pDS = gn.FeatureDataset as IGeoDataset;
                point.Project(pDS.SpatialReference);



                pointToEID = new PointToEIDClass() as IPointToEID;

                // find the nearest junction element to this Point
                pointToEID.GeometricNetwork = gn as IGeometricNetwork;
                pointToEID.SourceMap = map;
                pointToEID.SnapTolerance = snapTol;

                try
                {
                    pointToEID.GetNearestJunction(point, out EID, out snappedPoint);
                }
                catch (Exception ex)
                {

                }


                if (snappedPoint == null)
                    return null;

                // convert the EID to a feature class ID, feature ID, and sub ID
                netElements = gn.Network as INetElements;

                try
                {
                    netElements.QueryIDs(EID, esriElementType.esriETJunction, out FCID, out FID, out subID);
                }
                catch (Exception ex)
                {

                    return null;
                }

                //Create flag for start of trace
                junctionFlag = new JunctionFlagClass() as INetFlag;
                junctionFlag.UserClassID = FCID;
                junctionFlag.UserID = FID;
                junctionFlag.UserSubID = subID;

                if (junctionFlag is IEdgeFlag)
                {
                    pFlagDisplay = new EdgeFlagDisplayClass();

                    if (Flag)
                        pFlagDisplay.Symbol = CreateNetworkFlagBarrierSymbol(flagType.EdgeFlag) as ISymbol;
                    else
                        pFlagDisplay.Symbol = CreateNetworkFlagBarrierSymbol(flagType.EdgeBarrier) as ISymbol;
                }
                else
                {
                    pFlagDisplay = new JunctionFlagDisplayClass();
                    if (Flag)
                        pFlagDisplay.Symbol = CreateNetworkFlagBarrierSymbol(flagType.JunctionFlag) as ISymbol;
                    else
                        pFlagDisplay.Symbol = CreateNetworkFlagBarrierSymbol(flagType.JunctionBarrier) as ISymbol;
                }

                pFlagDisplay.ClientClassID = FCID;
                pFlagDisplay.FeatureClassID = FID;
                pFlagDisplay.SubID = subID;
                pFlagDisplay.Geometry = snappedPoint;

                return junctionFlag as IJunctionFlag;
            }
            catch
            {
                return null;
            }
            finally
            {
                pDS = null;
                pointToEID = null;
                netElements = null;

            }


        }

        public static ISimpleMarkerSymbol CreateNetworkFlagBarrierSymbol(flagType flgType)
        {
            ISimpleMarkerSymbol pSymbolFlag = null;
            switch (flgType)
            {
                case flagType.EdgeFlag:
                    pSymbolFlag = new SimpleMarkerSymbolClass();
                    pSymbolFlag.Style = esriSimpleMarkerStyle.esriSMSSquare;
                    pSymbolFlag.Angle = 0;
                    //pSymbolFlag.Color = 
                    pSymbolFlag.Outline = true;
                    pSymbolFlag.OutlineSize = 1;
                    //pSymbolFlag.OutlineColor = GetColor(0, 0, 0);
                    pSymbolFlag.Size = 10; //TODO: UserConfig
                    break;
                case flagType.JunctionFlag:

                    pSymbolFlag = new SimpleMarkerSymbolClass();
                    pSymbolFlag.Style = esriSimpleMarkerStyle.esriSMSCircle;
                    pSymbolFlag.Angle = 0;
                    //pSymbolFlag.Color = GetColor(0, 255, 0);
                    pSymbolFlag.Outline = true;
                    pSymbolFlag.OutlineSize = 1;
                    //pSymbolFlag.OutlineColor = GetColor(0, 0, 0);
                    pSymbolFlag.Size = 10; //TODO: UserConfig
                    break;
                case flagType.EdgeBarrier:


                    pSymbolFlag = new SimpleMarkerSymbolClass();
                    pSymbolFlag.Style = esriSimpleMarkerStyle.esriSMSDiamond;
                    pSymbolFlag.Angle = 0;
                    //pSymbolFlag.Color = GetColor(255, 0, 0);
                    pSymbolFlag.Outline = true;
                    pSymbolFlag.OutlineSize = 1;
                    //pSymbolFlag.OutlineColor = GetColor(0, 0, 0);
                    pSymbolFlag.Size = 10; //TODO: UserConfig
                    break;
                case flagType.JunctionBarrier:

                    pSymbolFlag = new SimpleMarkerSymbolClass();
                    pSymbolFlag.Style = esriSimpleMarkerStyle.esriSMSX;
                    pSymbolFlag.Angle = 0;
                    //pSymbolFlag.Color = GetColor(255, 0, 0);
                    pSymbolFlag.Outline = true;
                    pSymbolFlag.OutlineSize = 1;
                    //pSymbolFlag.OutlineColor = GetColor(0, 0, 0);
                    pSymbolFlag.Size = 10; //TODO: UserConfig
                    break;
                default:
                    pSymbolFlag = new SimpleMarkerSymbolClass();
                    pSymbolFlag.Style = esriSimpleMarkerStyle.esriSMSCircle;
                    pSymbolFlag.Angle = 0;
                    //pSymbolFlag.Color = GetColor(0, 255, 0);
                    pSymbolFlag.Outline = true;
                    pSymbolFlag.OutlineSize = 1;
                    //pSymbolFlag.OutlineColor = GetColor(0, 0, 0);
                    pSymbolFlag.Size = 10; //TODO: UserConfig
                    break;
            }
            return pSymbolFlag;

        }

        public static void AddFlagToGN(ref INetworkAnalysisExt pNetworkAnalysisExt, ref ESRI.ArcGIS.Geodatabase.IGeometricNetwork pGeomNet, ref  IFlagDisplay pFlagDsiplay)
        {
            INetworkAnalysisExtFlags pNetworkAnalysisExtFlags = null;

            try
            {
                if (pNetworkAnalysisExt.CurrentNetwork != pGeomNet)
                {
                    pNetworkAnalysisExt.CurrentNetwork = pGeomNet;
                }


                pNetworkAnalysisExtFlags = (INetworkAnalysisExtFlags)pNetworkAnalysisExt;



                if (pFlagDsiplay is IEdgeFlagDisplay)
                {

                    pNetworkAnalysisExtFlags.AddEdgeFlag(pFlagDsiplay as IEdgeFlagDisplay);

                }
                else
                {

                    pNetworkAnalysisExtFlags.AddJunctionFlag(pFlagDsiplay as IJunctionFlagDisplay);
                }
            }
            catch
            {

            }
            finally
            {
                pNetworkAnalysisExtFlags = null;
            }


        }
    }
}

6. Run code and set the default debug application as ArcMap

7. Once the ArcMap is open go to customise code and in the command tab add the tool to your window

8.click on the tool will add an flag symbol to the map(use f5 to refresh the map)

Wednesday, 26 November 2014

Custom Geoprocessing Tool


Arcobjects Geoprocessing Procedure:



1. Create a geoprocessor object and set its properties.
2. Set the appropriate values for the tool’s parameters.
3. Execute a tool using the geoprocessor object’s Execute() method.

In order to create a geoprocessor object, the IGeoProcessor2 interface can be used. This interface
is defined in the geoprocessing library of ArcObjects and is implemented by the GeoProcessor
CoClass.

IGeoProcessor2 gp = new GeoProcessorClass();
//add the result of geoprocessing as a new layer to Map
gp.AddOutputsToMap = true;
//if output of geoprocessing exists before the execution of tool
//it will be overwritten
gp.OverwriteOutput = true;

Assume that you want to create Thiessen polygons for the cities FeatureClass to create proximal
zones for all cities. The proximal zones represent full areas where any location inside the zone is
closer to its associated city than any other city. Based on the Create Thiessen Polygons reference
page, you have to provide at least an input point FeatureLayer and the path to the output
FeatureClass.
In order to create and set each parameter, the IVariantArray interface of the System library must
be used.

IVariantArray parameters = new VarArrayClass();

Each parameter has to be added to the IVariantArray interface in the exact order that is specified
on the tool’s reference page.

//in_features
parameters.Add(@"D:\DataFolder\fileGDB.gdb\cities");
//out_feature_class
parameters.Add(@"D:\DataFolder\fileGDB.gdb\citiesThiessen");
//fields_to_copy(Optional)
parameters.Add("ALL");

As it is illustrated on the Create Thiessen Polygons reference page, the third parameter is optional.
You can simply not add any value to IVariantArray or, as shown in the preceding code, you can
provide an appropriate value for the optional parameter. You can skip the optional parameter
using an empty string as input to IVariantArray’s Add() method. For example, look at the
reference page of the Buffer tool; you can see that three of the seven available parameters are
mandatory. The following code demonstrates how to skip the fourth parameter and specify the
fifth parameter:

//1-in_features
parameters.Add(@"D:\test.gdb\cities");
//2-out_feature_class
parameters.Add(@"D:\test.gdb\citiesBuffer");
//3-buffer_distance_or_field
parameters.Add("50 kilometers");
//4-line_side(Optional)
parameters.Add("");
//5-line_end_type(Optional)
parameters.Add("ROUND");
//6 &7 there is no need to provide empty string
//for the rest of parameters since you don't want to set them
After setting all the required parameters, all you need to run a tool is to call the Execute() method
of the geoprocessor object. The Execute() method solicits the name of the tool and its parameters.

gp.Execute("CreateThiessenPolygons_analysis", parameters, null);
The following code shows the complete code for this example. In order to run the code, you need to
add references to the Geoprocessing and System libraries of ArcObjects:
IGeoProcessor2 gp = new GeoProcessorClass();
//add the result of geoprocessing as a new layer to Map
gp.AddOutputsToMap = true;
//if output of geoprocessing exists before the execution of tool
//it will be overwritten
gp.OverwriteOutput = true;
IVariantArray parameters = new VarArrayClass();
//in_features
parameters.Add(@"D:\DataFolder\fileGDB.gdb\cities");
//out_feature_class
parameters.Add(@"D:\DataFolder\fileGDB.gdb\citiesThiessen");
//fields_to_copy(Optional)
parameters.Add("ALL");
//or parameters.Add("");
gp.Execute("CreateThiessenPolygons_analysis", parameters, null);


The Geoprocessing library of ArcObjects is accessible through the ESRI.ArcGIS.Geoprocessing
namespace. This library contains a few hundred types which can be used to run and manage tools
and GIS workfl ows. You learned earlier in this section that IGeoProcessor2 is the main interface of
this library and the easiest way to run a geoprocessing tool is to call its Execute() method.
However, using IGeoProcessor2 is not the only approach to run a geoprocessing tool or model.
There are some managed assemblies created by Esri to performing geoprocessing in a managed
way. A managed way means there is a native .NET assembly (the Geoprocessor assembly) that is
a wrapper for some types in the Geoprocessing library of ArcObjects, and there are other .NET
assemblies for each system toolbox.
These native .NET assemblies provide an even easier way to run a system tool. In general, the
procedure for running a tool using the Geoprocessor-managed assembly is the same as running a tool

Wednesday, 19 November 2014

ESRI Addin Button to Zoom to Selected Layer in TOC

Software Required:
  1. Microsoft Visual Studio 2010 +
  2. ArcMap 10.2 or more
  3. ArcObjects SDK for .Net Installed

Procedure:

  • Open Visual Studio 2010
  • Create a New Project > Visual C#> ArcGIS>Desktop Addins >ArcMap Add In
  • ArcMap Addin Wizard will appear on the Screen.Give a desired name for your Addin and click Next
  • In the Addin Types Enable Button checkbox and provide description for it.This will appear as a button tooltip in your ArcMap application.Click finish to end the wizard.
  • Now go the Solution Explorer(View>Soln Explorer) and open the Addinname.cs file if it doesn't appear in your screen.
  • Replace the content of the file with the following data on the onclick() method of the button.cs file.
  • Add the References(Right click references in Solution Explorer and select Add References) based on your classes usage
C#

protected override void OnClick()
        {
IMxDocument mdoc = ArcMap.Application.Document as IMxDocument;

//the following two lines of code are the same
IActiveView activeView = mdoc.ActiveView;
//IActiveView activeView = mdoc.FocusMap as IActiveView;
//get the selected layer in the Table of Contents
ILayer lr = mdoc.SelectedLayer;
//check if there is a selected layer or not
if (lr != null)
{
activeView.Extent = lr.AreaOfInterest;
//invoking Refresh method
//results in redrawing the whole view
activeView.Refresh();
}
}
  • Save your Current project .Don't run your Code.
  • Go to Properties>Addinname Properties>Debug option.Set your ArcMap as the External program for debugging the code
  • Run the Code.
  • ArcMap Application will now open.Go to Customize>Customize mode>Command.Right now you will see your Addin name in the category list click on it, respective button will get displayed on the rightcommands window.
  • Drag the Button and put it in the Menu bar.
  • You get the ESRI Addin file bin>Debug folder of your project location
  • Now its party time :) Share your work with other through the Addin file

Create a Display Flow Arrows Addin


ArcMAP ESRI Add-in for Display flow arrows for Utility Geometric Network


Software Required:
Microsoft Visual Studio 2010 +
ArcMap 10.2 or more
ArcObjects SDK for .Net Installed

Procedure:

  • Open Visual Studio 2010
  • Create a New Project > Visual C#> ArcGIS>Desktop Addins >ArcMap Add In
  • ArcMap Addin Wizard will appear on the Screen.Give a desired name for your Addin and click Next
  • In the Addin Types Enable Button checkbox and provide description for it.This will appear as a button tooltip in your ArcMap application.Click finish to end the wizard.
  • Now go the Solution Explorer(View>Soln Explorer) and open the Addinname.cs file if it doesn't appear in your screen.
  • Replace the content of the file with the following data.
  • Add the References(Right click references in Solution Explorer and select Add References) based on your classes usage


//Add the references in to the current namespace
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using ESRI.ArcGIS.ArcMapUI;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.EditorExt;
using ESRI.ArcGIS.Framework;
using ESRI.ArcGIS.esriSystem;
using ESRI.ArcGIS.Editor;
using ESRI.ArcGIS.NetworkAnalystTools;
using ESRI.ArcGIS.Geometry;
using ESRI.ArcGIS.Geodatabase;



namespace Flow
{
    public class FlowArrow : ESRI.ArcGIS.Desktop.AddIns.Button
    {
//Declare the interface Variable
        public IUtilityNetworkAnalysisExtFlow utilarr;
        public IUtilityNetworkAnalysisExt utilflow;
        public INetworkAnalysisExt netExt;

        public FlowArrow()
        {
//Get the reference to the Utility Analyst Toolbar using the UID Reference
            UID pUID = new UIDClass();
            pUID.Value = "esriEditorExt.UtilityNetworkAnalysisExt";
            netExt = ArcMap.Application.FindExtensionByCLSID(pUID) as INetworkAnalysisExt;

            UID uidutilflow = new UIDClass();
            uidutilflow.Value = "esriEditorExt.UtilityNetworkAnalysisExt";
            utilflow = ArcMap.Application.FindExtensionByCLSID(uidutilflow) as IUtilityNetworkAnalysisExt;

            
            
        }

        protected override void OnClick()
        {
            message m = new message();
    
            IGeometricNetwork gn = null;
            
            // get the current network

            IMxDocument mxd=ArcMap.Application.Document as IMxDocument;
            IMap map=mxd.FocusMap;
            IActiveView av = map as IActiveView;
            gn = netExt.CurrentNetwork;

            if (gn != null && utilflow!= null)
            {
                utilflow = netExt as IUtilityNetworkAnalysisExt;
                utilarr = utilflow as IUtilityNetworkAnalysisExtFlow;
                utilarr.ShowFlow = !(utilarr.ShowFlow);
                av.Refresh();
            }

       
            
            // refresh the display to update the flow direction arrows
            IActiveView mapView = ArcMap.Document.ActiveView;
            mapView.PartialRefresh(esriViewDrawPhase.esriViewGraphics, null, null);

        }
        protected override void OnUpdate()
        {
//Enable the Button once the operation is Successful
           //Enabled=True;
        }

        
   
    }

}

Code to get flow arrow using ArcObjects
Display flow arrow using Arcobjects

  • Save your Current project .Don't run your Code.
  • Go to Properties>Addinname Properties>Debug option.Set your ArcMap as the External program for debugging the code
  • Run the Code.
  • ArcMap Application will open.Now go to Customize>Customize mode>Command.Right now you will see your Addin name in the category list click on it.After that the button will get displayed on the commands window.
  • Drag the Button and put it in the Menu bar.
  • You get the ESRI Addin file bin>Debug folder of your project location
  • Now its party time :) Share your work with other through the Addin file