Monday, August 15, 2016

The Arcpy Modules


The Arcpy Modules

In addition to the standard functions and classes, arcpy contains several modules. Each module contains specialized task – related functions and classes that are accessible in code by specifying arcpy and the module name as shown in below




Checklist for updating from ArcGISScripting to ArcPy

Checklist for updating from ArcGISScripting to ArcPy

All 9.3 python scripts starts with the import arcgisscripting command and are full of gp statements.  And they are still useful scripts, I have spent some time upgrading them to the new ArcPy site-package for ArcMap version 10.x

I took basic checklist from The GIS Studio  and I felt it is very helpful for me and I included some more points which I feel important.

1. Replace the import statement and remove the geoprocessing creation statement. In other words, remove this:
import arcgisscripting
gp = arcgisscripting() (or) gp=arcgisscripting.create(9.3)
gp.toolbox = "management" (or) gp.AddToolBox("C:\Program Files (x86)\ArcGIS\Desktop10.2\ArcToolbox\Toolboxes\Data Management Tools.tbx")
              

and replace it with

import arcpy
No need to specify any toolboxes in v10!

2. Replace all gp. with arcpy.  I do this with a find/replace command in my code editor. For example
gp.exists()
now becomes
arcpy.Exists()

3. Check your capitalization.  Previous versions of arcgisscripting allowed for sloppy capitalization.  Now it has to be exact and this can be a real pain to find all the mismatched cases. gp.addmessage worked before but now it has to be arcpy.AddMessage.  And note the capital “Exists” in the example above.  Now that I’ve been working with arcpy a bit I find my eye is trained, however in the beginning this was a common bug to find in my scripts and repair.
Some other examples
gp.searchcursor()  now arcpy.SearchCursor()
gp.describe() now arcpy.Describe()

4. The result tool is different.  Results were pretty straightforward up until ArcMap 9.3.  At that point they became a little more tricky.
Now, many geoprocessing tools return a result object of the derived output dataset. A print statement will display the string representation of the output.
>>result = arcpy.GetCount_management("myLayer")
>>result
<Result '879'>
>>print result
879
The result object’s getOutput method returns values as a unicode string. To convert to a different Python type, use  built-in Python functions: str(), int(), long(), float().
>>resultValue = result.getOutput(0)
>>resultValue
u'879'
>>count = int(resultValue)
>>print count
879
In your code you can smash it all together to look like this and save a few lines.  Although this makes your code less readable by other novice users that might need or want to modify the script.
>>ItemCount=int(arcpy.GetCount_management("myLayer").getOutput(0))
>>ItemCount
879

6. Replace any del gp statements.  I had been taught to always delete the gp module any time you ended the script either at the very end or in an try/except statement.  I was told that it cleaned up any memory usage.  I don’t know how true it is, but what can it hurt, right?   So my scripts are littered with
del gp
statements.  Now, if you’ve never created the geoprocessor in the first place (see step 1), these are little bombs waiting to go off when your script runs into them.  You can’t delete what doesn’t exist.  Be sure to find them all and replace them with a
del arcpy

7. The overwrite tool is different.  You’ll need to find and update all uses of it that you might have. Previously you had something like this:
gp.overwrite = 1
where 1 is true and 0 is false.  Now you can do something like:
arcpy.env.overwriteOutput = True
or even
from arcpy import env
env.overwriteOutput = True

8.  Import the env module from arcpy.  This isn’t a requirement, however I tend to use the environment settings fairly often in my scripts so implicitly importing the env module saves a bit of typing. In the example above you can use the shorter env.overwriteOutput = true statement.  Additionally, another common one that I use is the workspace setting. By importing the env module you can then use a short
env.workspace = 'c:/my/path'
statement.  If you go this route be sure to remember to put
from arcpy import env
up near the top of your scripts with the other import statements in order for these shorter statements to work.

9. Tool name suffixed with toolbox name. Below SelectLayerByAttribute tool exists in Data Management tools. In arcpy it’s suffixed with toolbox (_management) name. Its alias name of Data Management tools.
gp.SelectLayerByAttribute()
now become
arcpy.SelectLayerByAttribute_management()


That’s it! At least for now.  If I find I run into some more common things to remember I’ll update this posting. And please let me know if you have run into any tips while updating your scripts in the comments below.

Saturday, September 19, 2015

Getting started with ArcObjects 1


Getting started with ArcObjects 1

In this post we will see how to use the ArcGis templates in .Net, how to create the default toolbar and add some default command buttons in the toolbar.

Expected prerequisites for this session is 1.DotNet 2010 and 2.ArcGIS 10.2 should be installed your desktop. Installations part we will cover in coming posts.

Run DotNet 2010 with administrator privileges
Create new project by clicking on File -> New -> Project

 From installed templates list select ArcGIS -> Extending ArcObjects then choose Class Library (ArcMap) and .Net Framework 4. If you want you can change the Project Name, Location and Solution name by changing the below textbox text.
.
Once you done with all click on OK button. Right now i am creating with default name ArcMapClassLibrary1. As soon as you click on OK, you will prompt with other wizard as shown in below
For now i suggest to select all the Assemblies under Desktop ArcMap by holding Ctrl and select. Then click Add, you can see all the selected items listed below. Then click Finish.
You can see one empty class with some default code as shown in below.


Select the project and right click and choose add -> NewItem as shown below
As soon as you choose you select you can prompt with Add New Item wizard.
Goto ArcGIS -> Extending ArcObjects select Base Toolbar. If you want you can change the name. I changes it as "BloggerTestToolbar.cs".

Click Add. You will prompt with another wizard


choose Desktop ArcMap and click OK. You can see one template added to your project with some Namespaces, COM Registration Functions, Guid, ProgId, some methods and some commented code as shown in below.

Change the caption, and uncomment the constructor code as shown in below. I changed the caption to "My Blogger First C# Toolbar".

Once its done, its done. You created your first ArcMap tool bar with Zoom, Undo and Redo commands. Don't believe.... build your application and open the ArcMap, Go to Customize -> Customize Mode..

Toolbars -> search for your toolbar and select
New toolbar created with Zoom, Undo and Redo commands. Its as simple as we don't believe.You can add layers and you can play with these buttons.

In next post we will see how its possible and some important points on this toolbar class.






Saturday, September 5, 2015

How to read ArcObjects - Object Model Diagrams - 3

Reading Object Model Diagrams

In last post we learned about UML - Class types. If anyone missed please refer the below link :

In this post we will discuss about UML Properties and Methods.

UML Property symbols:

Read and write property - 
All classes have properties on then shown with the barbell symbol as shown above. Chicken class has 3 properties like Age, Color and Name.

Read only property -
Some of the properties have a left-sided barbell, means we can only get this value, we cannot change it to something else (read only). Here, for chicken we could get reference to its wing, but we could not give it a different wing.

Write only property - 
Some of the properties have a right-side barbell. we can edit the value, but we can never find out what it is. Here, for chicken we could change the password, but we never know what the current password setting is.

Property Values -
To the right of each property are a colon and then a type. This is the value type that the property holds. Age holds an integer value like 1,2,3... Some properties holds objects or reference of objects. So, here, the wing property would give us a reference to a wing object.

UML Method symbols:
Classes also have methods. Methods are shown with an arrow symbol. Methods are like the actions that an object can perform.

Some methods returns the values, some don't. Fly does not return any value. It carries out its operation and that't it. LayEgg, on the other hand, carries out it's operation and returns an Egg object for us. This is how chicken creates egg with LayEgg method.


Wednesday, August 26, 2015

How to read ArcObjects - Object Model Diagrams - 2


Reading Object Model Diagrams


In last post we learned about UML - Relationship symobls like Association, Multiplicity, Is Composed of, Creates a and Is a type of. If anyone missed please refer below link :

In this post we will continue (UML Classes, properties and methods).

Class Types :

Abstract Class - 
The Bird class is called an abstract class. Abstract class means that we cannot make any of these objects. In reality, they are no birds. They are type of birds. The abstract call is really just there for generalization and inheritance purposes. Common characteristics that are inherited by any subclass. 

CoClass -
The Chicken is a CoClass. A Coclass means you can create objects from these classes. Anytime we see a CoClass means we can write two lines of code to make one of these objects. 

These are ours starting point. If you are not sure where to start writing code, you can locate a CoClass on any diagram and, in two lines of code, you can make an object out of it.

Class - 
Classes cannot directly create objects, but objects of a class can be created as a property of another class or instantiated by objects from another class.

we cannot make Egg or Wings. Other objects have to do the creation for us.We can see it on the diagram here with the "creates" relationship symbol.Chicken creates eggs. If we want Egg object, we have to go to the chicken and have it make the Egg for us. If we don't have a Chicken, its a CoClass, we can make one with two lines of code and get it to make the Egg.

That's the end of classes. We will continue UML properties and methods in the next post.


Sunday, August 23, 2015

How to read ArcObjects - Object Model Diagrams - 1

Reading Object Model Diagrams

As a senior developer i got to know that who all are having hands on experience on ArcObject, are also not able to read the OMD diagrams and somebody really don't know what are OMD's are. This is the reason i created this post who really want to know the basics.

Here all the screenshot and some of the text i am using are copied from one of the ESRI seminar .

Object model diagrams are almost like road maps of ArcGIS system. Similar to the way you'd use a map to learn a new city, we use the object model diagrams to learn how the ArcObjects are organized. If we plan to go new place, we discuss with who familiar with that area or we search the root in google maps or other source to familiarize with the roads and landmarks before actually go there. You use the map to do that, first you understand the map and it's symbols based on the legend given in the map because its tells us what all the different colors and different symbols mean.

Where to find the OMD's :
Go to installation path ArcGIS -> DeveloperKitxx(version no) -> Diagrams. 
Ex:C:\Program Files (x86)\ArcGIS\DeveloperKit10.2\Diagrams

Once you open the folder you will find no.of different .pdf files in a will organized manner. 
Ex: EditorObjectModel.pdf, GeometryObjectModel.pdf, DotNetGeoprocessorObjectModel.pdf

When start reading the OMD, they look a little bit complex first too, but once start looking on that we will get lot of information.They are about 70+ diagrams to show all the thousands of classes.

The diagrams use, or are drawn with, the Unified Modeling Language. Its an industry standard when creating these diagrams. Before going to OMD we should know the below UML symbols.



What are all those UML symbols mean in the legend?

Lets discuss Relationship symbols in this post.

UML made of many symbols, but we really need to know about 12 of then to write some code.
The one - liner symbol called Association. These two classes or objects created out of these classes, are associated with each other. Here chicken has an associated nest. Relationship is one to one.

Association can be more than just a one to one relationship. It can be one to many. The star here signifies a many or multiplicity relationship. The class the star is closest to, that's many object.
The farm has many chickens.


The multiplicity reltionship can have an actual number. The number that has the closest to the object that has the multiplicity. Here a chicken as two wings.

The composed-of symbol has solid diamond. The object with the diamond is the composed-of object. Composed-of means that two objects go together all the time.You would not see one without of other.When we are moving chicken the composed-of object with go together, if we delete this object the composed-of object would get deleted. Here a chicken is composed of two wings.

The dashed line and the arrow indicates a creates relationship. Here one type of objects creates another one. Here a chicken create egg.

The last relationship Is a type of, here, is shown as triangle. When you see this symbol, you should think inheritance. Birds have some properties and methods that are inherited by chicken. Here we could say chicken is a type of bird.

That is the end of the relationship symbols.

UML class symbols and properties and method symbols, how to code using these object and using programmers interfaces we will see in the next post.


Migrating ArcGIS 9.3.x Desktop custom components to ArcGIS 10.x using .Net

  
     Migrating ArcGIS 9.3.x Desktop custom 
components to ArcGIS 10.x
   

                              Prepared by – Ravisankara Kumar
                             Sr.Software Engineer – GIS

Summary

This topic explains what's required to migrate custom components from ArcGIS 9.3.x to 
ArcGIS 10.x. Custom components created in 9.3.x require a recompile against the 10.x 
assemblies.

Before you can migrate ArcGIS 9.3 makes sure that

  1.       ArcGIS 10.x for Desktop (Basic, Standard, or Advanced) must be installed.
  2.     .     Make sure Visual Studio 2010 is installed on your machine. To build .NET applications       with ArcGIS for Desktop, the Microsoft .NET Framework 3.5.1 is required.
  3.      Must have the ArcObjects .NET SDK installed to develop .NET-based custom         components.
For ArcGIS Desktop custom components created using Visual Studio 2008, need to open the  projects in Visual Studio 2010 and run the Microsoft upgrade wizard.

To change the location of the external program, right-click the project and select properties.              In the project properties, select Debug and change the external program path to its new location.   The following screen shot shows the default setting of the Start external program option in      ArcGIS 10.x:



Starting at ArcGIS 10.x, the functionality of the ESRI.ArcGIS.ADF assembly was split into    multiple assemblies to separate development tasks performed by ArcGIS Server from ArcGIS Engine and ArcGIS for Desktop developers. To allow custom components that use this assembly created in ArcGIS 9.3.x to work in the 10.x architecture, perform the following steps:

·         Remove the reference to the original ESRI.ArcGIS.ADF assembly.
·         Add a reference to the ESRI.ArcGIS.ADF.Local assembly.



To have a successful compile of a migrated ArcGIS 9.3.x Visual Studio development project,  confirm that all Esri assemblies have the Specific Version property set to false.

Visual Studio automatically uses the new version of the assembly to compile. To do this,           follow these steps:
·         Select an Esri assembly in the Visual Studio Solution Explorer. Right-click the assembly and       select Properties. The Properties dialog box appears.
·         Set the Specific Version property to False as shown in the following screen shot:

Updating component category registration (9.3.x only)

Starting at ArcGIS 10, ArcGIS applications no longer read components from the registry.        Custom components still need to be registered as all COM components do; however, ArcGIS       now uses Extensible Markup Language (XML) tables to store component associations instead.     This more flexible and efficient pattern allows ArcGIS to map component activations to the     version appropriate application.

To properly register your custom component with ArcGIS, registration should be done using           the Esri-provided ESRIRegAsm.exe utility. This utility replaces the standard Microsoft     RegAsm.exe and RegSvr32.exe utilities. Call ESRIRegAsm.exe directly, supplying the      appropriate product target as an argument To use the ESRIRegAsm utility to register your      ArcGIS for Desktop custom components at compile time (to more easily debug and test your components),


Follow these steps:
1.     In Visual Studio, right-click the project name in the Solution Explorer and select       Unload Project as shown in the following screen shot:

2.     Right-click the project name in the Solution Explorer and select Edit <project name>                   as shown in the following screen shot:
3.    Add the following MSBuild code to your project. Place the code at the bottom of your           project file above the closing project tag.
[XML]
<Target Name="BeforeClean">
  <Exec
    WorkingDirectory="$(CommonProgramFiles)\ArcGIS\bin"
    Command="esriRegasm.exe &quot;$(TargetPath)&quot; /p:Desktop /u /s"
    Condition="Exists('$(TargetPath)')"/>
</Target>
<Target Name="AfterBuild">
  <Exec
    WorkingDirectory="$(CommonProgramFiles)\ArcGIS\bin"
    Command="esriRegasm.exe &quot;$(TargetPath)&quot; /p:Desktop /s"/>
</Target>
See the following screen shot that shows the code in the project file:

4.    Right-click the project name in the Solution Explorer, select Reload Project, then save the   project.

5.       Build and run the project to debug your application.

Good Luck :)