Beginning ArcGIS for Desktop Development using .NET - Pouria Amirian - ebook

Beginning ArcGIS for Desktop Development using .NET ebook

Pouria Amirian

0,0
102,99 zł

Opis

Get the very most out of the ArcGIS for Desktop productsthrough ArcObjects and .NET ArcGIS for Desktop is a powerful suite of software tools forcreating and using maps, compiling, analyzing and sharinggeographic information, using maps and geographic information inapplications, and managing geographic databases. But getting thehang of ArcGIS for Desktop can be a bit tricky, even forexperienced programmers. Core components of ArcGIS platform iscalled ArcObjects. This book first introduce you the whole ArcGISplatform and the opportunities for development using variousprogramming languages. Then it focuses on ArcGIS for Desktopapplications and makes you familiar with ArcObjects from .NET pointof view. Whether you are an ArcGIS user with no background inprogramming or a programmer without experience with the ArcGISplatform, this book arms you with everything you need to get goingwith ArcGIS for Desktop development using .NET?right away. Writtenby a leading expert in geospatial information system design anddevelopment, it provides concise, step-by-step guidance,illustrated with best-practices examples, along with plenty ofready-to-use source code. In no time you?ll progress from .NETprogramming basics to understanding the full suite of ArcGIS toolsand artefacts to customising and building your own commands, toolsand extensions?all the way through application deployment. Among other things, you?ll learn to: * Object-Oriented and Interface-based programming in .NET (C# andVB.NET) * Finding relationship between classes and interfaces usingobject model diagrams * Querying data * Visualizing geographical data using various rendering * Creating various kinds of Desktop Add-Ins * Performing foreground and background geoprocessing Learn how to improve your productivity with ArcGIS forDesktop and Beginning ArcGIS for Desktop Development Using.NET

Ebooka przeczytasz w aplikacjach Legimi na:

Androidzie
iOS
czytnikach certyfikowanych
przez Legimi
Windows
10
Windows
Phone

Liczba stron: 641




CONTENTS

Part I: The Basics

Chapter 1: Why Geospatial Is Special

A Tour of Geospatial Data

Why Geospatial Is Special

Various Kinds of GIS Software

Geospatial Data Models and Storage

Esri Geodatabase

Summary

Chapter 2: Introduction to Arcgis for Desktop Applications Customization

Four Ways to Customize ArcGIS for Desktop

Customizing the User Interface

Scripting

Desktop Add-Ins

ArcObjects SDK

Summary

Part II: .NET Programming Fundamentals

Chapter 3: .NET Programming Fundamentals, Part I

The .NET Framework

The C# Language

Introduction to Object-Oriented Programming in C#

Summary

Chapter 4: .NET Programming Fundamentals, PART II

Overview of Object-Oriented Programming Concepts

Reference Types and Value Types

Brief Explanation of All .NET Types

Namespaces and Assemblies

Debugging Using Visual Studio

Structured Exception Handling

Casting Objects

Aggregation Using Collections

Reading and Writing Files

Summary

Part III: Arcobjects Programming

Chapter 5: Understanding Arcobjects Object Model Diagrams

What Is ArcObjects?

Interface-Based Programming in Brief

Understanding Object Model Diagrams

Summary

Chapter 6: Accessing Maps and Layers

Introduction to Maps and Layers In ArcObjects

General Properties of All Layers

Working with FeatureLayers

Working with RasterLayers

Adding an Existing *.lyr File to a Map

Adding *.lyr Files Using GxDialog

Saving *.lyr and *.mxd Files

Summary

Chapter 7: Working with Tables and Featureclasses

Accessing Tables and FeatureClasses

Summary

Chapter 8: Subsets of Records

Using Object Model Diagrams for Selecting Features and Rows

Working with Existing Selections

Selecting Rows and Features

Displaying Subsets of Geospatial Data

Summary

Chapter 9: Constructing and Using the Geometry of Features

Object Model Diagram for the Geometry of Features and Graphics

Displaying Geometries on the Screen

Creating a New Feature and Editing an Existing Feature’s Geometry

Working with Spatial Operators

Length, Area, Centroid, and Envelope of Geometries

Summary

Chapter 10: Rendering Geospatial Data and Using Hyperlinks and MapTips

Geospatial Data Display

Going beyond Simple Display

Summary

Chapter 11: Labeling, Exporting Activeview, and Working with Elements

Labeling

Exporting the ActiveView

Working with Elements

Summary

Chapter 12: Geoprocessing with Tools and Models

ArcObjects and the Geoprocessing Framework

Running Geoprocessing Tools

Opening a Tool’s Dialog Box in Code

Geoprocessing in the Background

Summary

Chapter 13: Feature Data Management

Use of GUID in ArcObjects

Working with the Geodatabase Model

Working with Features

Summary

Chapter 14: Advanced Topics in Arcobjects Programming and Deployment

Sharing State and Functionality between Components

Event Handling in ArcObjects

Application Extension

Add-In Deployment

Custom Component Deployment

Summary

Appendix

Introduction

Advertisements

PART I

The Basics

CHAPTER 1:

Why Geospatial Is Special

CHAPTER 2:

Introduction to ArcGIS for Desktop Applications Customization

Chapter 1

Why Geospatial Is Special

WHAT YOU WILL LEARN IN THIS CHAPTER:

Main reasons that geospatial data are special

Some sources of errors in using and collecting geospatial data

Major types of GIS software

A brief description of the ArcGIS platform

Various geospatial data storage models

Different types of Esri geodatabases

WROX.COM CODE DOWNLOADS FOR THIS CHAPTER

The wrox.com code downloads for this chapter can be found at www.wrox.com/remtitle.cgi?isbn=1118442547 on the Download Code tab. The code is in the Chapter01 folder and is individually named according to the names throughout the chapter.

Geospatial data have played a major role in human life for centuries. Almost all human activities and decisions contain geospatial components. Collecting, managing, processing, and representing various kinds of geospatial components are accomplished by various kinds of geotechnologies, including GIS (Geographical Information System), remote sensing, photogrammetry, cartography, surveying, and GPS (Global Positioning System), to name just a few. Many research organizations have identified geotechnology, nanotechnology, and biotechnology as the three most important emerging fields. There is no doubt that the need for geospatial data and use of geotechnologies will continue to grow for years to come.

GIS is the heart of geotechnologies and Esri’s ArcGIS is the most widely used and powerful commercial GIS software. In this chapter, you will learn various categories of GIS software and see how the ArcGIS platform provides software products for each category. After reading this chapter, you will know what makes the ArcGIS platform compelling to users and developers alike.

NOTEEsri is the worldwide leading supplier of GIS software and services. The company was founded as Environmental Systems Research Institute in 1969 by Jack and Laura Dangermond. Today Esri products (particularly ArcGIS for Desktop applications) have more than 40 percent of the global market share.

A TOUR OF GEOSPATIAL DATA

Nowadays, in order to create a map or collect geospatial data with a handheld GPS device, all the necessary steps are:

1. Turn on the GPS receiver.
2. Walk around and periodically click the button with the “Mark” label, or simply let the device collect data for you constantly.
3. Connect the GPS receiver to the computer and let the software draw a map for you. Even better, have the small screen of the device itself display the map.

Simple stuff, right? Collecting and using geospatial data like this is very common today. Millions of people explore the world on www.OpenStreetMap.org, which collects and updates most of its geospatial data in the mentioned fashion (called crowdsourcing). Geocaching is another fun example of using and collecting geospatial data. Geocaching is a low-cost sport in which a person (called a geocacher) uses a GPS device to find something that was hidden by other geocachers. Technically speaking, geocaching is fun outdoor navigation with GPS devices.

As a more recent simple example of using and collecting geospatial data, consider the W3C Geolocation Application Programming Interface (API) specification. This API provides the location of a device (desktop, handheld without GPS, handheld with GPS, etc.) through location information servers in standard and transparent fashion directly from the web browser. The Geolocation API is implemented in almost all modern web browsers, including Microsoft Internet Explorer, Mozilla Firefox, Google Chrome, Apple Safari, and Opera. The following Try It Out demonstrates the simplest example of using Geolocation API.

If you understand how geospatial data are used today by the Geolocation API, GPS devices, Google Earth, and so on, you might ask yourself: if collecting and using geospatial data is so simple, why do the techniques, concepts, and sciences like the Geospatial Information Science (GISc), Location Based Services (LBS), and Spatial Decision Support Systems (SDSS) exist at all? In other words, is it all about software? If it is all about software, we can use and collect geospatial data just like any other kind of data. But geospatial data are different kinds of data and special methods and techniques have to be created and developed to handle them. The following sections briefly discuss what is special about geospatial data.

WHY GEOSPATIAL IS SPECIAL

Today, all human activities and decisions have a geospatial component, and maps are the most widely used type of geospatial component. Most of the time, we are exploring maps in many different kinds of media — such as TV channels, newspapers, mobile apps, websites, and even the small display of a car navigation system to find an address, a best route, a nearest facility, tomorrow’s weather, and so on. In contrast to what they seem at first, using and collecting geospatial data are not so simple.

In its basic form, a geospatial component is a pair of geographic coordinates called latitude and longitude, which are used to represent the location of a point on the surface of the earth. The latitude and longitude belong to geographic coordinate system space, so they are called geographic coordinates.

As we already know, earth is not a perfect sphere. Mathematically speaking, among 3D shapes, spheroid provides the best approximation of earth. This approximation injects a variable amount of errors in all geospatial-related activities (from representation to processing) of geospatial data.

Spheroid is a 3D shape, so in order to represent it on the 2D plane of display screens (like a map or the screen of any device), the 3D spheroid has to be projected on a flat coordinate system. This is called projection or map projection. All map projections distort geospatial components in some way. If you take a look at Greenland (with an area of 2,166,086 km2) as it is represented in Microsoft Bing Maps (www.bing.com/maps), you will notice that it is drawn a little larger than South America (with an area of 17,840,000 km2; see Figure 1-4). This map has a map projection that distorts the area of geospatial features. In spite of this, most of the time we use and work with a projected coordinate system in which geospatial data are projected on the flat coordinate system.

FIGURE 1-4

Depending on the purpose of the map, some distortions are acceptable and others are not. Different map projections exist in order to preserve some properties of the spheroid (or any other 3D shape) at the expense of other properties. This is an additional source of error in using and collecting data. Moreover, the sources of geospatial data have their own errors too. For example, most handheld GPS devices provide accuracy for no more than several meters, which might not be acceptable in many engineering projects.

What about processing? Any kind of geospatial processing needs precise geospatial data with a known coordinate system. (As mentioned previously in this section, coordinate systems come in two flavors: projected and geographic.) Many processing methods of geospatial data can be applied to various spaces, like the human body, for example, as is done for analysis of the human body with medical images. There are also many processing methods that are specific to geospatial data, which in most cases are very complex and time consuming. Even with the horsepower of today’s computers, most PCs and laptops aren’t designed to handle the intense workload of geospatial processing. The simple reason for such a huge workload is the high volume and unstructured nature of geospatial data. For example, a polygon can have at least three and at most millions of points as its point collection.

So to manage geospatial data effectively, we have to resort to databases, in which case, each activity for querying, visualizing, editing, and geospatial processing includes interaction with the database. Besides the distinctive techniques needed for managing geospatial data inside databases (such as indexing geospatial data for quick retrieval), to make matters even more complicated, one of the unique aspects of geospatial data is the relationships that they can have. In addition to regular relational relationships (like parent-child relationships), geospatial data can have many topological relationships, which is the arrangement for how point, line, and polygon features share their geospatial components or geometry.

In addition to various kinds of errors, huge volumes of data, special types of relationships, complexity of processing, the need for coordinate systems, and various kinds of representation, editing geospatial data usually requires long transactions, which is rare in managing other kinds of data. Simply put, a transaction is a package of units of work on data that must be done in all-or-nothing mode. Editing non-geospatial data in most cases must be done in a fraction of a second (e.g., transactions in financial systems like banks). In contrast, any edit of geospatial data (inserting new features, updating and deleting existing features) might take a few minutes to several months to be completed. For this reason, geospatial data must be managed in quite different information systems. Those are the quick answers to the question asked at the beginning of this section: Why are geospatial data so special?

NOTEFor in-depth exploration of why geospatial data are special, read Geographic Information Systems and Science, third edition, by Paul A. Longley, Michael F. Goodchild, David J. Maguire, and David W. Rhind (John Wiley & Sons, Inc., 2011).

As I said at the beginning of this chapter, nearly all activities and decisions of humans contain geospatial components. Collecting, managing, processing, and representing various kinds of geospatial components are accomplished by geotechnologies, which include GIS, remote sensing, photogrammetry, cartography, surveying, and GPS, just to name a few. GIS is the heart of geotechnologies. I think of it this way: If geotechnologies were a human, GIS would be the brain.

NOTEThere are a lot of good books on geotechnologies. Most of them focus on a specific geotechnology. But if you are more interested in a brief introduction to almost all geotechnologies, then read Basics of Geomatics by Mario A. Gomarasca (Springer, 2009).

GIS consists of six components: hardware, software, people, data, methods, and network. The focus of this book is on the software component. The next section delves into the GIS software topic.

VARIOUS KINDS OF GIS SOFTWARE

Chapter 2

Introduction to ArcGIS for Desktop Applications Customization

WHAT YOU WILL LEARN IN THIS CHAPTER:

The different ways to customize ArcGIS for Desktop applications

How to create an add-in for ArcGIS Desktop

How to build custom components for ArcGIS Desktop

How to use Python in ArcGIS Desktop

WROX.COM CODE DOWNLOADS FOR THIS CHAPTER

The wrox.com code downloads for this chapter can be found at www.wrox.com/remtitle.cgi?isbn=1118442547 on the Download Code tab. The code is in the Chapter02 folder and is individually named according to the names throughout the chapter.

Esri has been providing customization in almost all its products since its inception in the 1970s. In some cases, Esri developed specific scripting languages and programming interfaces (API) for its own products in order to allow users to customize their use of the products.

The ArcGIS platform is a complete system for performing all sorts of geospatial-related activities. Also this platform is flexible enough to provide almost all its functionality to GIS professionals and developers as development kits for customization and extension. In other words, there are lots of opportunities for customizing the ArcGIS platform. The “Developer GIS” section of Chapter 1 mentions some of the opportunities that exist for developing an ArcGIS-based solution for all major computing platforms such as desktop, web, and mobile. Since the focus of this book is on ArcGIS for Desktop applications, in this chapter you are going to look at different opportunities for customizing and developing upon ArcGIS for Desktop applications.

FOUR WAYS TO CUSTOMIZE ARCGIS FOR DESKTOP

When the first version of ArcGIS released in late 1999, Esri changed its strategy from using its own specific scripting languages to standard programming languages. Since then, GIS professionals and developers have happily customized and developed their own customization in familiar and well-known programming languages such as Visual Basic. Until version 10.0 of ArcGIS, desktop applications shipped with an embedded programming language called Microsoft Visual Basic for Applications (VBA). In addition to ArcGIS, VBA is embedded in many other software products, such as the Microsoft Office package. Microsoft decided to stop supporting VBA or offering a VBA distribution license. As a result, version 10.0 of ArcGIS is the last version in which VBA can be used for development.

NOTEIn ArcGIS 10.0 and 10.1 there is no ArcObjects VBA SDK. For ­backward compatibility with previous developments in VBA, Esri offers an optional ­separate setup that needs an additional license.

That was very bad news for the ArcGIS community.

Most ArcGIS users learned customizing ArcGIS for Desktop applications through VBA. But there is good news as well; Python is the preferred scripting language in versions 10.0 and 10.1. To be specific, Python was in the ArcGIS platform for many years. But Python recently gained major growth in terms of capabilities and user communities. It is open source, and many open source projects use this programming language to develop and implement geospatial-related concepts and techniques. Python will be supported in the next versions of ArcGIS and is the best choice for writing geoprocessing scripts in ArcGIS for Desktop applications.

NOTEAs mentioned in the previous note, VBA is not supported in versions 10.0 and 10.1 natively. But you can use map documents (.mxdfiles) containing VBA code after enabling the use of VBA in ArcMap. In order to enable use of VBA in ArcGIS 10.0 or 10.1, you have to follow these steps:
1. Install ArcGIS Desktop VBA Resources for Developers.
2. Get an authorization file for VBA from Esri.

ArcGIS for Desktop applications are the flagship professional GIS products for performing all geospatial-related activities. There are quite a lot of opportunities for customization in almost every aspect of ArcGIS for Desktop. ArcGIS for Desktop applications 10.0 and 10.1 have four options for customization and development, listed below and sorted from least to most complex.

User Interface (UI) customization

Scripting

Desktop add-ins

Developing custom components using ArcObjects SDK (Extending ArcObjects)

In the upcoming sections, you look at each method to understand when and how to use each approach.

CUSTOMIZING THE USER INTERFACE

The user interface (UI) of a software product is where users of the system interact with an application in order to perform their intended activities. Software developers should provide users with all the required toolbars, tools, and commands. Also, users appreciate having all needed toolbars and tools in tidy and easy-to-reach locations in the main window of software products. It is an excellent idea to provide UI customization options to avoid crowding the main window of the software when there are lots of toolbars, tools, and commands that can be used. Users want the flexibility to arrange UI components based on their personal preferences. This is why all software producers provide some sort of customization capabilities in their own products.

NOTEMicrosoft Word provides lots of tools to work with. Even advanced users of Microsoft Word may not be completely aware of what can be done with this masterpiece word processor software. When I want to let audiences know that there are lots of things they can do with UI customization, I often ask them, “How can you do a simple calculation in Microsoft Word?” Don’t think about Microsoft Excel or even Calculator; surprisingly, it can be done inside Word. All you need to do is to add the Calculate button to the main window of Microsoft Word!

Sometimes, with a little UI customization you can give users all that they need without a single line of code. Four applications of ArcGIS for Desktop (ArcMap, ArcCatalog, ArcGlobe, and ArcScene) are shipped with dozens of built-in toolbars, tools, and commands. In this case, you can save all the UI customization in a document (such as an ArcMap map document [.mxd file]) and put this document in a public folder in a shared network place where all users have access. Next, you see how to customize the UI and what you can do with this kind of customization. In the following Try it Out, you create a new toolbar and populate it with some handy tools.

TRY IT OUT: Adding a New Toolbar and Menu to ArcMap
1. Run ArcMap.
2. Point to the Customize menu and select Customize Mode, as shown in Figure 2-1. Also note that you can open the Customize Mode window by double-clicking the empty gray area in ArcMap where all the toolbars are located.

FIGURE 2-1

3. From the Customize window, click on the New button (as shown in Figure 2-2) to create a new toolbar.

FIGURE 2-2

4. The New Toolbar window pops up. As shown in Figure 2-3, enter Useful Analysis as the toolbar name and then click on OK. The Useful Analysis toolbar should be added to the end of the toolbars list in the Customize window. You can switch it on or off by checking or unchecking the checkbox in front of the name of the toolbar. As the name suggests, you use this toolbar for placing frequently used geoprocessing tools such as Buffer, Overlay, Clip, and Spatial Join.

FIGURE 2-3

5. Check the checkbox in front of the new Useful Analysis toolbar to display it. Click on the Commands tab and wait for the lists of Categories and Commands to be populated (see Figure 2-4). Several commands can be used in ArcMap. Most of them are provided as tools and commands on the toolbars. Some other commands are provided as tools in ArcToolbox. There are also commands and tools that you can’t see on toolbars or in ArcToolbox. You can put all commands on your newly added toolbar as well as on all existing toolbars that come with ArcMap by default.

FIGURE 2-4

6. As shown in Figure 2-5, scroll down the Categories list to find Analysis Tools. These are the same tools that you can find in the Analysis Tools toolbox inside the ArcToolbox window.

FIGURE 2-5

7. Select the Buffer tool from the Commands list and drag and drop it onto your newly created toolbar. Notice that while dragging the Buffer tool, the mouse cursor is a small “x” indicating that the cursor’s current position is not a valid place to drop the tool. When the mouse cursor is over a valid command container (such as any toolbar or menu), the small “x” changes to a small “+” indicating that you can drop the tool or command to add it. After you drop the Buffer tool on the newly created toolbar, you see a small hammer icon on the toolbar. You are going to change its image. So right-click on the image of the newly added Buffer tool to see its context menu, shown in Figure 2-6.

FIGURE 2-6

8. In the context menu, select the Name option and enter any helpful text such as Buffer the Features in the Name textbox, as shown in Figure 2-7. Then select an appropriate image from available images or select the Browse for Image option to select an image on your local drive. The image should be in .png or .bmp format and usually 16 × 16 pixels. In addition, select Image and Text as the display option. As you will see, the title of the toolbar is displayed together with the tool’s image.

FIGURE 2-7

9. At this point, you have a new toolbar with only one tool. Add the Intersect, Clip, and Spatial Join tools from the Analysis Tools category to the toolbar. Change their images and set a helpful name for them (see Figure 2-8). Right-click on the Intersect tool, and from the context menu select the Begin a Group option to add a vertical bar (separator) between the Buffer and Intersect tools.

FIGURE 2-8

10. There are some other useful geoprocessing tools that are less frequently used than Buffer or Overlay that you are going to add as menu items. Scroll down the Categories list to find the New Menu item, as shown in Figure 2-9. When New Menu is selected in the Categories list, there is always a New Menu item in the Commands list. Just drag and drop the New Menu command in the Commands list to the Useful Analysis toolbar.

FIGURE 2-9

11. Rename New Menu to Other Analysis, select the Begin a Group option, and then add the Multiple Ring Buffer, Identity, and Erase tools from the Analysis Tools category to the menu in the same way that you added Buffer to the Useful Analysis toolbar. Close the Customize window. The toolbar should now look like Figure 2-10.

FIGURE 2-10

12. Save the map document using the Save command in the File menu. Name the map document CustomToolbar.mxd. If you close ArcMap and then open it, you will notice that the UI customization you just completed (the Useful Analysis toolbar) is missing. But if you open the Custom Toolbar map document (CustomToolbar.mxd), you will find the Useful Analysis toolbar.
How It Works

PART II

.NET Programming Fundamentals

CHAPTER 3:

.NET Programming Fundamentals, Part I

CHAPTER 4:

.NET Programming Fundamentals, Part II

Chapter 3

.NET Programming Fundamentals, Part I

WHAT YOU WILL LEARN IN THIS CHAPTER:

Microsoft .NET framework and its relationship to C#

General features of C# programming language

Major data types in C# and corresponding data types in .NET

Object-based manipulation

Introduction to object-oriented programming in C#

WROX.COM CODE DOWNLOADS FOR THIS CHAPTER

The wrox.com code downloads for this chapter are found at www.wrox.com/remtitle.cgi?isbn=1118442547 on the Download Code tab. The code is in the Chapter03 folder and is individually named according to the names throughout the chapter.

This chapter presents an overview of programming in the official language of .NET: C#. You learn about the fundamental aspects of this programming language. Topics such as data types, operators, loops, and conditional statements are explained. This chapter assumes you are familiar with these concepts and only teaches how to implement them in C#.

THE .NET FRAMEWORK

The .NET Framework is a collection of fundamental technologies designed to provide the common services needed to run applications. Microsoft designed the .NET Framework with certain goals in mind, such as support of industry standards, extensibility, unified programming model, improved memory management, and so forth. Following is a brief explanation of .NET Framework technologies.

.NET programming languages:

Include C#.NET (or C# for short), VB.NET (or VB for short), F#, and managed C++. The main programming languages inside the .NET Framework are C# and VB. C# and VB are similar in terms of syntax as well as performance of code execution. Though the syntax is a bit different, both use the .NET class library and are supported by the Common Language Runtime (CLR). Microsoft recently has stated that it will now aim to ensure that VB and C# contain the same functionality. According to Microsoft, choosing to program in C# or VB is just a lifestyle choice. If you are a hard-core fan of VB don’t worry. All code samples in this book are in both C# and VB. Dozens of other languages are ported into the .NET Framework, but the main languages are the mentioned ones. The unified programming model provided by .NET enables you to develop a class written in C#, which can extend the class written in VB.

.NET Framework Base Class Libraries (BCL):

The giant repository of classes that provide prebuilt functionality for everything from reading a text file to drawing graphics and textures in an online game. The class library collects thousands of pieces of prebuilt functionalities that you can use in your applications. Sometimes parts of BCL are organized into a technology set such as ADO.NET (the technology for working with databases), ASP.NET (technology for creating web applications), Windows Forms (technology for creating traditional Windows applications), and WPF (technology for creating modern Windows applications), to name just a few.

CLR (Common Language Runtime):

The fundamental component of the .NET Framework is the CLR. This is the engine that executes all .NET programs and provides an environment for managed execution of .NET applications. It manages the execution of .NET applications by providing services such as memory management, security checking, and code optimization. For this reason, .NET code which executes inside CLR is called

managed code.

In short, the CLR provides a layer of abstraction between the code and operating system.

Visual Studio:

This is not really part of the .NET Framework, but because Visual Studio is always used in .NET development it is considered a part of the .NET platform. Originally written in C#, Visual Studio provides one of the most complete and fully fledged (if not the best and most complete) integrated development environments, or IDEs, for development of all kinds of software. Visual Studio contains a complete .NET Framework, so in order to prepare your necessary tools for .NET development all you need is to install Visual Studio.

THE C# LANGUAGE

The official language of the .NET Framework is C#. Learning C# is quite simple, and you get a lot of help from Visual Studio’s coding tips and built-in IntelliSense (the code autocompletion feature of Visual Studio). The following sections provide an overview of programming in C#.

A Brief History of C#

C# is a simple, modern, general-purpose, object-oriented programming (OOP) language. During the development of the .NET Framework, the BCL were originally written using a managed code compiler system called Simple Managed C (SMC). Anders Hejlsberg (father of C#) formed a team to build a new language at the time called C-like Object Oriented Language (COOL). Microsoft has the habit of choosing sexy names for its products: ActiveX, XNA, Xbox, and so forth. For trademark reasons and maybe because COOL is not cool and sexy enough, Microsoft changed the name of the language to C#.

Basic Concepts

Like all the programming languages, C# has its own syntax. C# generally follows the syntax of the C and C++ programming languages.

Case Sensitivity

C# is case sensitive. This means whenever you define a variable, method, and so forth, you have to refer to them using the exact name and case for them. In addition, you have to write all the keywords of the language in lowercase. For example, if you want to declare an integer variable you have to type int instead of all other variations, such as Int, INT, and iNT.

Comments

Comments are valuable descriptive text that are ignored during execution and enhance the readability of the code for developers. In C#, you can comment out a single line of text using a double forward slash (//). For multiline comments, you can insert a forward slash plus asterisk (/*) at the beginning of the first line and an asterisk plus a forward slash (*/) at the end of the last line. Using multiline comments, you can comment out a block of code for test purposes. This way, you still have that block of code in your source code, which is not considered by a compiler for execution.

//this is a single line comment // feel free to write anything descriptive //even in your mother tongue /*this is a multiline comment * always use comments to explain your code * it makes it easier and faster * to understand * the code when it has some comments */

When you insert the */ in a multiline comment, note that all subsequent new lines automatically get an asterisk. However, you can remove the asterisk at the beginning of lines between /* and */ because they are unnecessary.

/*this is a multiline comment always use comments to explain your code it makes it easier and faster to understand the code when it has some comments */

C# has some other options for commenting code. You look at one of them later in this chapter in the “Methods” section.

Block Structure

In C#, blocks of code are composed of code that is grouped together for execution in loops, conditional execution, defining methods, and so forth. In all these cases (and more that you will see throughout this book), blocks of code are defined using curly braces ({}).

The following is the syntax for a code block:

{ // Code in a block }

Statement Termination Character

The C# compiler recognizes a semicolon (;) to denote the end of an executable line of code. Every statement in C# must end with a semicolon except when you are defining block structure and comments. Remember that comments are not executable code; thus, they don’t need a semicolon. All the code inside the block must have a semicolon (;); however, because the definition of a block requires a curly bracket ({) at the beginning of the block and a curly bracket (}) at the end of the block, there is no need for a semicolon (;) at the end of a block definition.

Because the C# compiler considers one line of code as a statement with one semicolon (;), you can break your code into multiple lines to enhance readability. The following two lines of code show various ways to write the same statement. You can write either

or

Variables and Data Types

Like any modern programming language, C# uses variables to store all kinds of data: numbers, text, and objects. A variable is a named location in memory. Using variables, your program can read or alter values stored in memory. Before you use a variable in your program, you must declare it. You have to provide a name and data type for the variable when declaring the variable in C#. Generally when you want to declare a variable you start with the data type followed by the name you want to use as the name of the variable.

int summation;

Specifying the data type is referred to as strong typing. Strong typing results in more efficient memory management, faster execution, and compiler type checking, all of which reduce runtime errors.

Once you declare a variable, you can assign it an initial value, either in a separate statement or within the declaration statement itself. For instance, the following code

is equivalent to this

C# safeguards you from errors by restricting you from using uninitialized variables. For example, the following code causes an error when you attempt to compile it:

So it is good idea to declare and initialize a variable in the same line of code. For this reason, always assign default values for your code (for example, 0 for numeric variables). Once you’ve declared your variables, you can freely assign values to them, as long as these values have the correct data type.

All .NET programming languages make use of the same data types with somewhat different names. For example, the Integer data type in VB is the same as int in C#. In spite of the different names, the CLR considers those data types as two different names for the same .NET data type: System.Int32. This feature provides unlimited opportunities for language integration. Because languages share the same core data types, you can easily use and even extend objects written in one .NET language in an application written in another .NET language. In the following sections, you learn about the intrinsic data types in C# and .NET, which are numeric, character, and date.

Numeric Data Types

Numeric data types can be integral or fractional. Table 3-1 summarizes the most important integral data types of C# and the equivalents in .NET.

TABLE 3-1: Integral Data Types

You have to use fractional data types when a variable should store numbers that include decimal parts. Table 3-2 briefly explains all fractional numeric data types available in .NET.

TABLE 3-2: Fractional Data Types

The default data type for integral numbers is the int data type and for fractional numbers it is double. This means the C# compiler considers each integral number as an integer and each fractional number as a double even if you declare a variable as another type and assign a number to that variable. In the following code, 123.123 is a fractional number and as a result is considered as a double to the C# compiler. If you try to assign 123.123 to a variable of type decimal or float, you get a compiler error that tells you it cannot convert double to float or decimal implicitly.

For this reason, you have to append a special character to your numbers to explicitly tell the compiler that “I know you consider every fractional number a double, but I want you to consider this number a float and assign it to the myFloat variable.” These characters, which are called type indicators, are as follows:

M

or

m

for decimal

D

or

d

for double

F

or

f

for float

L

or

l

for long

Using this special character, you can rewrite your code as follows:

NOTEType indicators are one of the few features that aren’t case sensitive in C#. The storage sizes along with the required range of values are the most important parameters when choosing a data type for a variable. An obvious reason for this fact is that the smaller the storage size, the faster the compiler can work with that data type. However, there is an exception. The C# compiler performs arithmetic operations with integers (theInt32base .NET data type) faster and more efficiently than the other numeric data types such asbyteorshort. For this reason, it’s better to use integers as counter variables even though abyteorshorttype could easily manage the maximum range of values.

Fractional data types provide another point of consideration. The float and double data types always have rounding errors, but in most cases those errors are negligible. For example, consider the following code, which results in a really small number.

The decimal data type holds a larger number of significant digits than either the float or the double data types, and it is not subject to rounding errors. The decimal data type is usually reserved for financial and scientific calculations that require a high degree of precision.

Other numeric data types also can be used in .NET, such as BigInteger and ulong (which are not covered in this book). If you are interested in other numeric data types in .NET, consult the .NET Framework documentation.

Character Data Types

In this category, C# has char and string data types for holding single characters and strings of characters, respectively. Both data types support Unicode, which means that you can easily represent and work with every language from Persian to Mandarin Chinese. The char data type can store just single unicode characters, such as “p” or “a,” and every char variable occupies 16 bits of memory. Any string variable stores a sequence of unicode characters that can include zero to about two billion characters.

C# treats any embedded backslash (\) as the start of a special escape character that specifies how the character should be printed in the output. Each escape character starts with “\” followed by a specific token. The most useful character literals are as follows:

\'

for single quote

\"

for double quote

\n

for new line

\t

for horizontal tab

\

for backward slash

Note that specifying the actual backslash character (for example, in an address of a file) requires two backslashes. Here’s an example:

Alternatively, you can use a so-called verbatim string by prefixing string literal with the @ symbol.

Boolean Data Type

The boolean data type (bool in C#) holds a 16-bit value that is interpreted as true or false. It’s used for variables that can be one of only two values, such as yes or no, on or off, or up or down (for this reason, they are often called flag variables).

Date Data Type

Dates are held as 64-bit integers. C# has no keyword for the date data type, but the .NET Framework defines a few useful data types for working with date and time: the DateTime and TimeSpan structures.

Nullable Data Types

By default, no intrinsic data types (except string) can be assigned a null value. This can become problematic when retrieving data from data structures such as a database that does allow nulls. Since the release of .NET 2.0, it has been possible to create nullable data types. Simply put, a nullable type can hold all the values of its underlying type, plus the value null. Thus, if you declare a nullable boolean, it could be assigned true or false or null. When declaring a value type variable that may be assigned a null, you make it a nullable type by placing a question mark symbol (?) after the type name.

Operations on Variables

You can use all the standard types of variable operations in C#. When working with numbers, you use various math symbols, as listed in Table 3-3. C# follows the conventional order of operations, performing exponentiation first, followed by multiplication and division, and then addition and subtraction. You can also control order by grouping sub-expressions with parentheses.

TABLE 3-3: Math Operators

OPERATOR

MEANING

+

Addition

-

Subtraction

*

Multiplication

/

Division

%

Reminder

If you divide one integer by another integer, the C# compiler performs integer division. That means it automatically discards the fractional part of the answer and returns the whole part as an integer. For example, if you divide 15 by 2, you end up with 7 instead of 7.5. The solution is to explicitly indicate that one of your numbers has a fractional data type. For example, if you replace 15 with 15d, C# will treat the 15 as a double. Also you can reach the same result by replacing 15 with 15.0, which C# will treat as a double. Either way, the division will return the expected value of 7.5. Of course, this problem doesn’t occur very often in real-world code, because then you’re usually dividing one variable by another. As long as your variables aren’t integers, it doesn’t matter what number they contain.

C# also enables you to use the addition operator (+) to join two strings, which is referred to as string concatenation.

C# also provides special shorthand assignment operators. Here are a few examples:

For other math functions, you can use .NET’s Math class. The Math class provides many useful functions for performing arithmetic and trigonometric calculations. The methods in this class are static, which means they are always available and ready to use, so there is no need to create a variable of type math to be able to use them. Feel free to explore this handy class. The following code snippets present some examples of using the Math class.

In the following Try It Out, you see some of these features in action.

NOTEThere are some other features for using complex numbers inside the .NET Framework. If you are serious about math in .NET, consult the .NET documentation.

Arrays

Arrays are the basic structures used to store data in all programming languages. They are often used to organize and work with groups of the same data type. In C#, you declare an array by suffixing an appropriate data type with brackets ([]) and then the name of your array:

string[] layerNames;

Each individual value in the array is set and accessed using its index inside the array. All arrays start at a fixed lower bound of 0. This rule has no exceptions. When you create an array in C#, you specify the number of elements. Because counting starts at 0, the highest index is actually one less than the number of elements. (In other words, if you have five elements, the highest index is four.) The new operator is used to create the array and initialize its elements to their default values. The default value for all numeric data is zero and for string is an empty string. Because the elements of the array are referenced by a zero-based index, the following array holds two elements:

To initialize the elements of an array when the array is declared, you can use curly brackets ({}) to list the values. Because the size of the array can be inferred, you do not have to state it,

C# supports multidimensional arrays. When you declare the array, you separate the size of the dimensions by commas. The following declaration creates a two-dimensional array of integers with three rows and two columns:

In this case you use curly brackets inside curly brackets to initialize the array.

Decision-Making

From many viewpoints, decision-making is the core of programming. All decision-making in all programming languages starts with an expression (called a condition) that can be evaluated to true or false. Based on the result of the evaluation of the condition, different blocks of code are executed. To build a condition, you need at least a comparison operator (shown in Table 3-4) and two literals or variables.

TABLE 3-4: Comparison Operators

In the examples shown in Table 3-4, you can replace literals with variables. You also can create composite conditions using logical operators. Logical operators combine the results of conditional operators. The three most commonly used logical operators are the And, Or, and Not operators, shown in Table 3-5.

TABLE 3-5: Logical Operators

The And operator (&&) combines two expressions and returns true if both expressions are true. The Or operator (||) combines two expressions and returns true if either one is true. The Not operator (!) switches the result of the comparison: a value of true returns false and a value of false returns true. In the case of the And operator (&&), if the first expression is false, the second expression is not evaluated. Quite the opposite is the case with the Or operator: If the first expression is evaluated to true, the second expression is not evaluated. This behavior is called short circuit.

The if statement is the heart of decision-making in any programming language. The if statement in C# is able to evaluate any combination of conditions and deal with various data types. The following code snippet demonstrates the use of the if statement,

The if block can have any number of conditions. If you test only a single condition, you don’t need to include any else blocks. Keep in mind that the if statement matches one condition at most. For example, if layerName is equal to "roads" the second condition is met and no other conditions will be evaluated.

C# also provides a switch statement that you can use to evaluate a single variable or expression for multiple possible values. The only limitation is that the variable you’re evaluating must be an integral numeric (int, short, long, and so forth), a boolean (bool), a character (char), a string (string), or a value from an enumeration. Other data types cannot be evaluated in a switch statement. In the following code snippet, each case examines the myLayer variable and tests whether it’s equal to a specific layer name:

switch (layername) { case "states": //do something with states Layer break; case "rails": case "roads": // do something with both the rails //and the roads layer break; default: // // do something with other layers break; }

Every branch in a switch statement must end with the break keyword. If you forget this keyword, the compiler will alert you and refuse to build your solution. The only exception is if you choose to stack multiple case statements directly on top of each other with no intervening code. This allows you to mimic the logical Or operator in switch statements and hence write one segment of code that handles more than one case.

Unlike the if statement, in C# the switch statement is limited to evaluating equality conditions. (Maybe this handy feature will be implemented in future versions of this powerful programming language.) However, the switch statement provides clearer syntax than the if statement for situations in which you want to test a single variable.

Iteration

All programming languages provide several ways to repeat blocks of code until a condition has been met. C# provides the following four iteration statements:

for

for

/

each

while

do

/

while

The for and foreach loops are ideal for iterating through sets of known and fixed sized data like arrays and collections (you will see some of them in the next chapter). The while and do/while statements are ideal when the number of iterations is not known until runtime or the number of iterations depends on input from the user.

The for loop is a basic statement in many programs. It allows you to execute a block of code a defined number of times using a built-in counter. To create a for loop, you need to specify a starting value, an ending condition, and the amount of increment with each iteration. The following code snippet shows a simple for block for calculating the summation of 1 to 9.

The C# foreach