Program in ArcGIS using the Net framework and C

Document Sample
Program in ArcGIS using the Net framework and C Powered By Docstoc
					      Program in ArcGIS using the .Net framework and C#

Preface

In the past, ArcGIS programming was largely written in VBA (Visual Basic for
Applications) Script. This language, while useful for writing macros for applications,
lacks the depth and breadth for large scale major initiatives which programming in the
.Net framework can provide. To this end, ESRI has made it possible to program in the
.Net Framework. This new ability is still in its infancy at this time and currently there are
few resources for ArcGIS users to explore programming in the .Net environment. This
guide attempts to help users getting started with programming in .Net for ArcGIS by
making a re-creation the often-used “Hello World” in programming using a simple
ArcGIS command.




How to …..                     Program ArcGIS using .net and C#                 Page 1 of 22
                             Table of Contents

Program in ArcGIS using the .Net framework and C# _________________________ 1
    Preface____________________________________________________________ 1
    Assumed Skills _____________________________________________________ 3
    Required Software __________________________________________________ 3
    Hello ArcGIS!______________________________________________________ 3
      Step 1 – Start a new Project _________________________________________ 4
      Step 2 – Remove the Class Library____________________________________ 7
      Step 3 – Add a Command ___________________________________________ 8
      Step 4 – Setting the Public Properties_________________________________ 12
      Step 5 – Understanding Class Methods _______________________________ 12
      Step 6 – Adding References ________________________________________ 13
      Step 7 – Adding Code to he OnClick Method __________________________ 15
      Step 8 – Editing an Icon ___________________________________________ 15
      Step 9 – Building a Solution ________________________________________ 16
      Step 10 - Debugging ______________________________________________ 17
      Step 11 Adding our Command to ArcGIS _____________________________ 18
    Appendix A_______________________________________________________ 21
    Appendix B _______________________________________________________ 21




How to …..                Program ArcGIS using .net and C#          Page 2 of 22
Assumed Skills

       This guide assumes that the reader has a basic understanding of what ArcGIS and
the .Net framework is, as well as a rudimentary understanding of how object oriented
programming works. For more information about .Net and object oriented programming,
follow the links in Appendix B.

Required Software

        In order to program with ArcGIS there are two products that you will need to
have installed on your computer. First, you must have either ArcGIS Desktop, ArcGIS
ArcInfo or else have the ArcGIS Engine installed. Once these one of these are installed
you will be able to run the code you compile in the ArcGIS environment. The other
ArcGIS product you need is the Developer Tools for Microsoft.Net that provides access
to the .Net framework and the functions that ESRI has made for .Net as well as the
Developer tools that install an API for ArcObjects. It is also important to make sure that
your software is up to date, which you can do by checking the ESRI website to see if
there are updates or service packs for your software (this tutorial was written using
ArcGIS 9.2 Service Pack1).

        The other major required software is a C#.Net compiler. I recommend using
Microsoft Visual Studio, because ESRI has created various resources to make coding
faster and easier for that environment. If you are looking for a free compiler you can try
using the Microsoft Visual Studio C# Express edition, or the SharpDevelop program
which is an open-source initiative. Links to these programs are provided in Appendix B.


Hello ArcGIS!

The ESRI Developer Network provides three samples that introduce C#.Net
programming for ArcGIS. Unfortunately these were written specifically for MSVS
(Microsoft Visual Studio) 2003, and some of the steps in their tutorial do not translate to
MSVS 2005. This guide has been written for MSVS 2005.

       Getting used to the ArcGIS framework is a steep learning curve, and an
understanding of how COM (Component Object Model) works can be quite helpful.
Understanding COM will be helpful when working with the ArcObjects model, but is not
necessary for this tutorial

        After starting MSVS from either the start menu or your desktop, the opening
screen has several useful links including news articles, information of getting started and
lists your most recent projects




How to …..                    Program ArcGIS using .net and C#                 Page 3 of 22
Step 1 – Start a new Project

        In MSVS when you create a Command for ArcGIS, you need to create it in a
Project. In order to begin programming in MSVS 2005 it is necessary to create a project.

   Navigate to File > New > Project…




    This will call the New Project dialog, and if you have the .Net Developer tools
installed correctly on your machine there will be a few ESRI templates listed along with
whatever other packages you have installed, such as the Visual C# or Visual C++
templates.


Step 1.2 – Choose a Project Template


How to …..                     Program ArcGIS using .net and C#             Page 4 of 22
    In the Project Types list, expand Visual C# > ArcGIS > Desktop folders. In the
    Templates box, Select Class Library (ArcMap).




     At the bottom of the New Project dialog, there is a textbox for entering in the Name
of your project, and the Location where the project will be saved. There is also a textbox
for the solution name and a check box for creating a new directory where the solution
will be saved. By default, the solution will be named the same name as the project name,
and the checkbox will be checked. Leave these as their default values as it makes your
life easier this way. Before clicking OK to create the project, double check that you have
spelled the name of the project correctly, because once the project has been created it is
difficult to go back and fix a silly spelling mistake (in fact, almost all cases its easier just
to start again and import your code than to try to change the project name).

Step 1.3

    Click OK!

    The next screen that will appear is the ArcGIS Project Wizard. This Wizard will
allow you to add any references to the ArcGIS framework that you may need. When you
know what you will be specifically programming for ArcGIS, you can select them here.
We don’t need any of them for our guide now, so we won’t add any.



How to …..                      Program ArcGIS using .net and C#                   Page 5 of 22
Step 1.4

   Click Finish




        Once you click Finish, you will be faced with a near empty page. This page is a
default class that has 3 lines of code that specify some COM information.




How to …..                   Program ArcGIS using .net and C#               Page 6 of 22
        We don’t need this file however, because we are not creating a class. We could, at
this point add code to turn this class into a command, but it is far easier to use the ESRI
template for a button, that is already installed. What we will do next is delete this class
from our project, and add the ESRI tool template file. On the right hand side of the
MSVS you will see that there is a Solution Explorer button that will show you all of the
files and references in the project. If this is not visible you can make it visible by clicking
on View > Solution Explorer.


Step 2 – Remove the Class Library

Step 2.1

   Right click on Class1.cs in the Solution Explorer and select Delete.




How to …..                     Program ArcGIS using .net and C#                  Page 7 of 22
   This will take you back to the Start Page of MSVS, but don’t worry, you are still in
your project, which you can confirm by checking the Solution Explorer.


Step 3 – Add a Command

Step 3.1

   In the Solution Explorer, right click on the HelloArcGIS that is in bold typeface.
   Select Add > New Item.




How to …..                   Program ArcGIS using .net and C#               Page 8 of 22
         Now you are faced with the New Item dialog. From here you can choose from
   a number of different templates; select make a new Base Command.

Step 3.2 – Select a File template

   At the Add New Item Dialog Select Base Command. Leave the Name textbox as
   the default and click Add.




How to …..                   Program ArcGIS using .net and C#         Page 9 of 22
   The next screen gives you an opportunity to make the command accessible from a
number of ArcGIS programs, we want to make this command for ArcMap.

Step 3.3
   Select Desktop ArcMap Command, Click OK.




How to …..                  Program ArcGIS using .net and C#            Page 10 of
22
      Whew! Now we finally have something that we can get coding in!




How to …..                Program ArcGIS using .net and C#             Page 11 of
22
    In this file there are three things to take note of, the COM registration code, the public
properties and the Overridden Class Methods.
    The COM registration code is what allows ArcMap to use your command. When you
compile this project, your code turns into a DLL and gets registered with the computer
using what is called a GUID. The COM code here is what is responsible for creating this
GUID and registering the DLL.
    The public properties look blank by default like this:
base.m_category = ""; //localizable text
base.m_caption = ""; //localizable text
base.m_message = ""; //localizable text
base.m_toolTip = ""; //localizable text
base.m_name = "";   //unique id, non-localizable (e.g.
"MyCategory_ArcMapCommand")

        These tell ArcMap how to classify your command, and the various information
that will be available to users in ArcGIS about the command.


Step 4 – Setting the Public Properties

Step 4.1

   Edit each of the public properties of your command so that they relfect the
   command you are creating.


base.m_category = "ArcGuides"; //localizable text
base.m_caption = "Hello World For ArcGIS"; //localizable text
base.m_message = "This tool welcomes new ArcGIS users to the ArcGIS
Framework!"; //localizable text
base.m_toolTip = "Hello World"; //localizable text
base.m_name = "HelloArcGIS";   //unique id, non-localizable (e.g.
"MyCategory_ArcMapCommand")

       The Overridden Class Methods will appear in a MSVS code region,
             , and contains the code blocks that we will be editing.


Step 5 – Understanding Class Methods

Step 5.1

   Expand the Overridden Class Methods code region

           #region Overriden Class Methods

           /// <summary>

How to …..                     Program ArcGIS using .net and C#                 Page 12 of
22
           /// Occurs when this command is created
           /// </summary>
           /// <param name="hook">Instance of the application</param>
           public override void OnCreate(object hook)
           {
               if (hook == null)
                   return;

               m_application = hook as IApplication;

               //Disable if it is not ArcMap
               if (hook is IMxApplication)
                    base.m_enabled = true;
               else
                    base.m_enabled = false;

               // TODO:   Add other initialization code
           }

           /// <summary>
           /// Occurs when this command is clicked
           /// </summary>
           public override void OnClick()
           {
               // TODO: Add Command1.OnClick implementation
           }

                 #endregion

        The two methods that are here provide important functions for programming in
ArcGIS. The OnCreate method is useful because it is called and run first, before any
other code in the class and when you are programming with ArcObjects It may be useful
to create objects that are persistent throughout the code.
        The OnClick code is what we are most interested in. This is where you code in
what happens when a user clicks on your command. In the tradition of Hello World, we
are going to have a message box pop up and say “Hello ArcGIS!” In order to get access
to the MessageBox method that we will be calling, we need to add a reference to the
System.Windows.Forms DLL and namespace.


Step 6 – Adding References

Step 6.1

   Click on Project > Add Reference




How to …..                   Program ArcGIS using .net and C#            Page 13 of
22
       Here we see all of the various DLLs that MSVS has access to reference.

Step 6.2
   Scroll down and select the System.Windows.Forms DLL. Click OK




        The project now have access to use any of the namespaces in the
System.Windows.Forms DLL. Namespaces are essentially collections of classes in .Net,
and in fact you are coding in your own namespace called HelloArcGIS, you can see this
by looking just below all of the using commands. Since we now have access to all of the
namespaces that are in the System.Windows.Forms DLL, we need to code in that we are
using the System.Windows.Forms namespace.

How to …..                  Program ArcGIS using .net and C#              Page 14 of
22
Step 6.3
   Modify the using statements so that they now read:

using   System;
using   System.Drawing;
using   System.Runtime.InteropServices;
using   ESRI.ArcGIS.ADF.BaseClasses;
using   ESRI.ArcGIS.ADF.CATIDs;
using   ESRI.ArcGIS.Framework;
using   ESRI.ArcGIS.ArcMapUI;
using   System.Windows.Forms;

      Now that we have access to the MessageBox class, we can simply modify the
OnCreate code so that it displays a message box that says Hello ArcGIS!

Step 7 – Adding Code to he OnClick Method
   Modify the OnClick method so that the code to display a message box is included

          public override void OnClick()
          {
              MessageBox.Show("Hello ArcGIS!","Arc Guides");
          }

        We are now finished coding our tool, quick eh? The last thing we need to do
before compiling our code is to create a snazzy looking icon for arc. MSVS creates a
default Command1.bmp which you can see in the Solution Explorer.


Step 8 – Editing an Icon
   Double click on Command1.bmp in the Solution Explorer to open up the bmp
   editor in MSVS, edit the bmp in any way you would like using the tools included
   in MSVS.

* N.B.* Start by making the entire image the color of the background, because this is the
transparent color.




How to …..                   Program ArcGIS using .net and C#                Page 15 of
22
         Finally we are ready to compile our project.


Step 9 – Building a Solution
   Click on Build > Build Solution.




       Hopefully there are no errors. If there are, they will be listed in the output window
   at the bottom of MSVS, and you should be able to click on them to fix the error. As
   an example I have written the line of code,
                MessageBox.Show("Hello ArcGIS!","Arc Guides");
   As,
                Message_Box.Show("Hello ArcGIS!","Arc Guides");

How to …..                     Program ArcGIS using .net and C#               Page 16 of
22
   to illustrate a possible source for error. In the compiler output window, there is now
   an error listed and the line of the offending line of code has been underlined to
   highlight the source of the error




       Now that we have compiled our project without build errors, we can try it out!
There are two ways to do this, we can open up ArcGIS and access the button, or we can
run our project through MSVS and then if there is a problem with the code, we can use
debugging tools such as catching exceptions and using breakpoints.


Step 10 - Debugging
   Click on Debug > Start Debugging




How to …..                   Program ArcGIS using .net and C#                 Page 17 of
22
    Now your project should open up ArcGIS. As we are not working with any ArcGIS
data, start ArcMap with a new empty map. To access your tool, you will need to add it to
a toolbar.


Step 11 Adding our Command to ArcGIS

Step 11.1
   Right click on a menu bar in ArcMap and select the Customize… button.




How to …..                   Program ArcGIS using .net and C#              Page 18 of
22
   Now we have the Customize dialog open. All of the commands that ArcGIS has
access to are listed here, by category and then by tool.

Step 11.2 – Loading a Command
   Select the Commands tab, and then locate ArcGuides in the Categories list.
   Select “Hello Word For ArcGIS” and click and drag it onto an ArcMap toolbar.




How to …..                 Program ArcGIS using .net and C#           Page 19 of
22
   Voliá we are done, congratulations! Click on your new command, and enjoy!




How to …..                 Program ArcGIS using .net and C#             Page 20 of
22
Appendix A
Summary of Steps
   1. Navigate to File > New > Project…
   2. In the Project Types bar, expand the Visual C# (or the Visual Basic if you want to
       use VB) and expand the ArcGIS subfolder. In this Subfolder will be the Desktop
       folder (Or MapInfo, or Engine if you have that installed). Once this is selected
       you will see a number of options in the Templates box, Select Class Library
       (ArcMap).
   3. Click OK!
   4. Click Finish
   5. Right click on Class1.cs in the Solution Explorer and select Delete.
   6. In the Solution Explorer, right click on the HelloArcGIS that is in bold typeface.
       Select Add > New Item.
   7. At the Add New Item Dialog Select Base Command. Leave the Name textbox as
       the default and click Add.
   8. Select Desktop ArcMap Command, Click OK.
   9. Edit each of the public properties of your command so that they relfect the
       command you are creating.
   10. Expand the Overridden Class Methods code region
   11. Click on Project > Add Reference
   12. Scroll down and select the System.Windows.Forms DLL. Click OK
   13. Modify the using statements (See text for more info, page 11)
   14. Modify the OnClick method so that the code to display a message box is included
   15. Double click on Command1.bmp in the Solution Explorer to open up the bmp
       editor in MSVS, edit the bmp in any way you would like using the tools included
       in MSVS
   16. Click on Build > Build Solution
   17. Click on Debug > Start Debugging
   18. Right click on a menu bar in ArcMap and select the Customize… button
   19. Select the Commands tab, and then locate ArcGuides in the Categories list. Select
       “Hello Word For ArcGIS” and click and drag it onto an ArcMap toolbar



Appendix B
Useful Links:

www.campus.esri.com: The ESRI virtual campus is a great starting point for users that
are new to ArcGIS, and even for seasoned veterans of ArcGIS. The campus provides
avenues to both online and in class courses in ArcGIS in many different streams. This
site, however, lacks sufficient information on programming using .Net with ArcGIS.

www.edn.esri.com: The ESRI Developer Network is community that was created to
provide programmers a place to search the ESRI API, look up code samples, find


How to …..                   Program ArcGIS using .net and C#              Page 21 of
22
community videos, and participate in online forums to ask programming questions and
help others who need help.

http://msdn2.microsoft.com/en-us/vstudio/aa973782.aspx: The Microsoft Visual Studio
product page.

http://msdn2.microsoft.com: Microsoft Developer Network: the starting location for all
.Net enquiries and includes the .Net API.

http://sharpdevelop.net/OpenSource/SD/: SharpDevelop program page. SharpDevelop is
an open source IDE for C#.Net Programming.

http://www.codeproject.com: The Code Project, a site that houses thousands of articles
that explain how to use .Net in every language supported by .Net. Every article contains
sample code and explanations, with paragraph information to add context to the code
presented.




How to …..                   Program ArcGIS using .net and C#               Page 22 of
22