27
Consuming ArcIMS Image Services using .NET Client Web Applications An ESRI White Paper October 2002 Environmental Systems Research Institute, Inc. 380 New York Street Redlands, California 92373-8100 ESRI White Paper i

Consuming ArcIMS Image Services using .NET Client Web ... · Consuming ArcIMS Image Services using .NET Client Web Applications An ESRI White Paper Ł October 2002 ... The .NET framework

  • Upload
    others

  • View
    4

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Consuming ArcIMS Image Services using .NET Client Web ... · Consuming ArcIMS Image Services using .NET Client Web Applications An ESRI White Paper Ł October 2002 ... The .NET framework

Consuming ArcIMS Image Services using NET Client Web Applications

An ESRI White Paper October 2002

Environmental Systems Research Institute Inc 380 New York Street Redlands California 92373-8100

ESRI White Paper i

Copyright copy 2002 Environmental Systems Research Institute Inc All rights reserved Printed in the United States of America The information contained in this document is the exclusive property of Environmental Systems Research Institute Inc This work is protected under United States copyright law and other international copyright treaties and conventions No part of this work may be reproduced or transmitted in any form or by any means electronic or mechanical including photocopying and recording or by any information storage or retrieval system except as expressly permitted in writing by Environmental Systems Research Institute Inc All requests should be sent to Attention Contracts Manager Environmental Systems Research Institute Inc 380 New York Street Redlands CA 92373-8100 USA

The information contained in this document is subject to change without notice

US GOVERNMENT RESTRICTEDLIMITED RIGHTS Any software documentation andor data delivered hereunder is subject to the terms of the License Agreement In no event shall the US Government acquire greater than RESTRICTEDLIMITED RIGHTS At a minimum use duplication or disclosure by the US Government is subject to restrictions as set forth in FAR sect52227-14 Alternates I II and III (JUN 1987) FAR sect52227-19 (JUN 1987) andor FAR sect1221112212 (Commercial Technical DataComputer Software) and DFARS sect252227-7015 (NOV 1995) (Technical Data) andor DFARS sect2277202 (Computer Software) as applicable ContractorManufacturer is Environmental Systems Research Institute Inc 380 New York Street Redlands CA 92373-8100 USA ESRI ARCINFO ArcCAD ArcView BusinessMAP MapObjects PC ARCINFO SDE and the ESRI globe logo are trademarks of Environmental Systems Research Institute Inc registered in the United States and certain other countries registration is pending in the European Community 3D Analyst ADF ARC COGO the ARC COGO logo ARC GRID the ARC GRID logo ArcInfo the ArcInfo logo the ARCINFO logo AML ARC NETWORK the ARC NETWORK logo ArcNews ARC TIN the ARC TIN logo ArcInfo LIBRARIAN ArcInfoProfessional GIS ArcInfoThe Worlds GIS ArcAtlas the ArcAtlas logo the ArcCAD logo the ArcCAD WorkBench logo ArcCatalog the ArcData logo the ArcData Online logo ARCEDIT the ARCEDIT logo ArcExplorer the ArcExplorer logo ArcExpress the ArcExpress logo ArcFM the ArcFM logo the ArcFM Viewer logo ArcGIS ArcIMS the ArcIMS logo ArcLogistics the ArcLogistics Route logo ArcMap ArcObjects ARCPLOT the ARCPLOT logo ArcPress the ArcPress logo the ArcPress for ArcView logo ArcScan the ArcScan logo ArcScene the ArcScene logo ArcSchool ArcSDE the ArcSDE logo the ArcSDE CAD Client logo ArcSdl ArcStorm the ArcStorm logo ArcSurvey ArcToolbox ArcTools the ArcTools logo ArcUSA the ArcUSA logo ArcUser the ArcView GIS logo the ArcView 3D Analyst logo the ArcView Business Analyst logo the ArcView Data Publisher logo the ArcView Image Analysis logo the ArcView Internet Map Server logo the ArcView Network Analyst logo the ArcView Spatial Analyst logo the ArcView StreetMap logo the ArcView StreetMap 2000 logo the ArcView Tracking Analyst logo ArcVoyager ArcWorld the ArcWorld logo Atlas GIS the Atlas GIS logo AtlasWare Avenue the Avenue logo the BusinessMAP logo DAK the DAK logo DATABASE INTEGRATOR DBI Kit the Digital Chart of the World logo the ESRI corporate logo the ESRI PRESS logo ESRITeam GIS ESRIThe GIS People FormEdit Geographic Design System Geography Matters GIS Day the GIS Day logo GIS by ESRI GIS for Everyone GISData Server InsiteMAP MapBeans MapCafeacute the MapCafeacute logo the MapObjects logo the MapObjects Internet Map Server logo ModelBuilder NetEngine the NetEngine logo the PC ARCINFO logo PC ARCEDIT PC ARCPLOT PC ARCSHELL PC DATA CONVERSION PC NETWORK PC OVERLAY PC STARTER KIT PC TABLES the Production Line Tool Set logo RouteMAP the RouteMAP logo the RouteMAP IMS logo Spatial Database Engine the SDE logo SML StreetMap TABLES The Worlds Leading Desktop GIS Water Writes and Your Personal Geographic Information System are trademarks and ArcData ArcOpen ArcQuest ArcWatch ArcWeb Rent-a-Tech esricom and wwwesricom are service marks of Environmental Systems Research Institute Inc The names of other companies and products herein are trademarks or registered trademarks of their respective trademark owners

ESRI White Paper ii

Consuming ArcIMS Image Services using NET Client Web Applications

An ESRI White Paper

ArcIMS An Introduction 1 What is NET 2

The NET Framework 2 The Common Language Runtime (CLR) 2 Managed Unmanaged and Unsafe code Understanding the Difference 3 NET Framework Class Libraries 4

ASPNET and Web Forms 4 NET and ArcIMS 6

Example 1 7 Example 2 12 Example 3 17

Accessing a COM Server from a NET Client 21 Summary 23

Consuming ArcIMS Image Services using NET Client Web Applications

ArcIMS An Introduction ArcIMS provides the foundation for distributing high-end geographic information systems (GIS) and mapping services via the Internet ArcIMS software enables users to integrate local data sources with Internet data sources for display query and analysis in an easy-to-use Web browser The ArcIMS Architecture consists of different types of connectors that allow you to customize client application to access specific services of the ArcIMS Server and display the results The connectors provided with ArcIMS include the ActiveX connector Servlet connector Cold Fusion connector and the Java connector Depending on the choice of these connectors you can write customized web applications using ASP DHTMLArcXML Cold Fusion or JSP The ActiveX and the Java connector expose a rich object model that makes development of client side applications relatively simple It is also possible to use the Servlet connector to send requests formatted as asArcXML strings to the ArcIMS spatial computing engine (Spatial server) and receives the response in the same ArcXML format This response can then be parsed to display the mapresult The ActiveX connector and the Servlet connector model can both be utilized within a NET programming environment to provide feature rich web applications The ArcIMS architecture also utilizes components such as the Application Server for load balancing making the entire setup highly scalable Please refer to the paper ArcIMS 4 Architecture and Functionality for a detailed review of ArcIMS architecture

Fundamentally NET can be looked at as a rich technology to produce Web Applications In some sense the term NET has now become synonymous with services more typically Web Services the ability to use Collaborative Web Applications that span

ESRI White Paper 1

heterogeneous environments Simply put web services allow you to share information or integrate with legacy systems without having to write specialized interconnection applications In this paper we will restrict the discussions and examples to using ASPNET as a unified Web development platform for building sophisticated web applications that will interact with ArcIMS Image Services

To understand and appreciate the additional benefits that NET technology brings to the table you should have some experience programming the ArcIMS client applications using the ActiveX or the Servlet connector model Also a good understanding of ArcXML syntax is essential to effectively use the Servlet connector model

Let us start by looking at what NET technology really is and get a firm handle on some of the terminologies used

What is NET NET is a new computing platform that simplifies application development in the highly distributed environment of the Internet The NET platform is built on top of the operating system NET has been influenced by other technological advances such as XML Java and COM The NET infrastructure comprises the NET framework Microsoft Visual StudioNET the NET Enterprise Servers and Microsoft WindowsNet In short the NET infrastructure refers to all the technologies that make up the environment for creating and running robust scalable and distributed applications

The following paragraphs provide a brief overview of some of the technologies and terminologies associated with NET To get more detailed information on NET there are a large number of books and information freely available on the internet that provide detailed descriptions of the technology This paper focuses on getting a broad perspective and some detailed knowledge of specific areas of the NET framework that can assist in leveraging this technology within the ArcIMS Internet Mapping Environment

The NET Framework

The NET framework is the part of the infrastructure that aids us in creating applications In simple terms the NET Framework can be discussed as containing 2 parts the CLR or the Common Language Runtime and the NET Framework Class libraries

The Common Language Runtime (CLR)

The CLR is the most important part of the NET architecture and computing paradigm It is the run-time environment in which applications written in different languages can all exist and play together providing cross-language interoperability

The mechanism for cross language interoperability is provided via the concept of Common Language Specification (CLS) a common set of rules A compiler that adheres

ESRI White Paper 2

to the rules can take code written in a specific language and port it to MSIL a Microsoft Intermediate Language Since MSIL code cannot be executed directly the CLR compiles the MSIL by using a Just-in-time (JIT) compiler into native CPU instructions as it processes the MSIL

One term that is mentioned a lot in conjunction with NET is managed code This is in fact made possible by the CLR Managed code is just code that is run under the auspices of the CLR or in other words code managed by the CLR One of the most important services provided by the CLR as part of the managed code paradigm is the concept of garbage collection NET uses automatic garbage collection to reclaim memory When memory allocated on the heap becomes orphaned or passes out of scope it is placed on a list of memory locations to be freed Periodically the system runs a garbage collection thread that returns the memory to the heap

While the runtime is designed for the software of the future it also supports legacy technology Interoperability between managed and unmanaged code enables developers to continue to use necessary COM components and DLLs

Managed Unmanaged and Unsafe code Understanding the Difference

Managed code is that code which executes under the supervision of the CLR This was dealt with in the section above The user has no control over how CLR achieves memory management type verification garbage collection and many other activities Uunmanaged code is that code which executes outside the context of the CLR The best example of this is your traditional Win32 DLLs like KERNEL32DLL USER32DLL and the COM components installed on our system How they allocate memory for their usage how memory is released how (if any) type verification takes places are some of the tasks that are undertaken by them on their own Unsafe code is a kind of cross between the managed and unmanaged codes It executes under the supervision of the CLR just like the managed code but lets you address the memory directly through the use of pointers as is done in unmanaged code A typical example would be a NET application that uses the functionality in a legacy Win32 DLL whose exported functions require the use of pointers Unless you are a NET aficionado understanding unsafe code and its implications may not be important to you But understanding the differences between Managed and Unmanaged code should provide you enough information to deal effectively with interoperability issues that needs to be dealt with while working with the ActiveX connector

ESRI White Paper 3

NET Framework Class Libraries

The NET Framework class library is a collection of reusable types that tightly integrate with the common language runtime The class library is object oriented providing types from which your own managed code can derive functionality

The NET Framework types enable you to accomplish a range of common programming tasks including tasks such as string management data collection database connectivity and file access In addition to these common tasks the class library includes types that support a variety of specialized development scenarios This paper includes examples of class libraries created by ESRI that provide rich functionality for developers to inherit in their web applications

Also the examples shown in this paper make use of ASPNET and web forms technologies As you create applications in ASPNET you will find it convenient to use many of the classes provided as part of the web forms class library

As you become familiar with the classes in the NET framework you may want to create wrapper classes that provide functionality for XML parsing internet intranet connections that inherit from base classes in the NET framework By creating your own classes you can provide reusable componentized code for building other ArcIMS client applications that require similar functionality

NET programs are deployed as assemblies An assembly is one or more EXEs or DLLs with associated metadata information The metadata about the entire assembly is stored in the assemblys manifest The manifest contains for example a list of assemblies upon which the current assembly is dependant The concept of assemblies how they can be deployed privately or publicly how they can be versioned etc is quite complex and are not discussed in this paper As always the internet serves as good source for information regarding these topics

ASPNET and Web Forms

The various web applications shown in this paper were all built using ASPNET ASPNET is the hosting environment that enables developers to use the NET Framework to target Web-based applications However ASPNET is more than just a runtime host it is a complete architecture for developing Web sites and Internet-distributed objects using managed code Both Web Forms and XML Web services use IIS and ASPNET as the publishing mechanism for applications and both have a collection of supporting classes in the NET Framework If you have used earlier versions of ASP technology it is easy to note the improvements provided by ASPNET and Web Forms For example you can develop Web Forms pages in any language that supports the NET Framework In addition ASPNET no longer needs to share the same file with your HTTP text (although it can continue to do so if you

ESRI White Paper 4

prefer) Unlike unmanaged ASP code that is always scripted and interpreted ASPNET pages are faster and easier to manage as they execute in native machine language and interact with the runtime like any managed application To summarize here are a few benefits to programming with ASPNET

Object Orientation and a large class library from which to inherit functionality Can use multiple programming languages VBNET C etc Code is always

compiled before it is run Web Forms and Web Controls present the programmer with an event driven

model very similar to the desktop environment Server side controls intelligently render html code appropriate to the target browser

Advanced crash-recovery and detection and isolation of rogue code damaging the system

Scalable architecture with extensive caching to reduce running lots of identical code for each website visitor

Debugging is much easier especially when the programming is done using an IDE like Visual StudioNet

The NET programming environment provides very good database and XML support

MSIL and the new assembly model makes deploying applications and versioning complexities an issue of the past

Provides tools to easily create webservices All the plumbing code required is effectively hidden

The diagram below shows the typical sequence of calls made during a request response cycle for a ASPNET web page Notice that the first request-response cycle is shown by steps 1 through 6 and subsequent calls are displayed as steps 7-10

ESRI White Paper 5

Because ASPNET uses compiled code instead of interpreted code subsequent requests will check to see if there has been any change to the code If not it will utilize the script engine cache to access the compiled version of the code

NET and ArcIMS In order to better understand how to build map services using ArcIMS and the NET environment this paper presents the concepts in a series of three examples The examples all written using NET compatible languages (VBNET and C) demonstrate web applications that display map images served up ESRIs ArcIMS product The examples chosen are such that they provide a good handle on the various aspects of designing web applications that server as clients to the ArcIMS Image Service The following are a brief description of the three examples

Example 1 An ASPNET application written in VBNET that utilizes COM Interop to access the functionality exposed by the ActiveX connector

Example 2 An ASPNET application written in VBNET that makes use of special classes (also developed in VBNET) to send and receive requests via the Servlet connector in ArcIMS This example also contains code that shows you how to capture page coordinates from a mouse click event on the image map control It also shows the

ESRI White Paper 6

necessary steps to convert the obtained page coordinates to map coordinates for subsequent use in zoom operations

Example 3 An ASPNET application written in C that makes use of special classes developed in C This example utilizes two approaches one using the Servlet connector and another using a C wrapper to the ActiveX connector to connect to the service using TCP

Example 1

This application is a very simple web application that demonstrates the use of an image control in a web form to display a map image served up by ArcIMS The button control reads State Names from a database and populates the DropDownList Selecting a State from the DropDownList highlights the state in the map

This example demonstrates the following

Basic web form and web controls Button Image and DropDownListcontrols Using the ActiveX connector in a NET web application using COM Interop

ESRI White Paper 7

Connecting to an access database to read a list of names (from a column) This list is then used to populate a drop down list box

Using the image control to view an image rendered by ArcIMS

ASPNET and Web Forms Programming Environment

Visual Basic NET Programming Language

Data Files

File Name Comment BPC 2002mdb Database file with a column containing state names World30stateslakescountry Shape files BPC_STATESaxl Axl file for the image service

WebForm Controls

Control Name Function ImageButton1 Control for displaying the image Button Populates the Dropdown Listbox with State Names read from the

database DropDownList1 Set AutoPostback property to TRUE

Steps to Create Application

Create a new Project Choose Visual Basic Project -gt ASPNET web application

Add Project References

ESRI White Paper 8

o Project Add References COM ArcIMS ActiveX Connector (Aims_ActiveXdll)

o Project Add References NET adodb ( adodbdll)

Add controls to the form and set the appropriate properties (NameCaption Size etc)

Right click on the WebForm1aspx file and choose Viewcode Type the code shown below Click on Build-gtSolution Press CTRL+F5 to start without debugging or F5 to Start (with debugging)

ESRI White Paper 9

Code from Web Form1aspxvb the codebehind page for the Web Form

Define and instantiate class variables Refer to the Section Accessing a COM Server from a NET Client for a discussion on using early and late binding mechanisms to instantiate COM objects

Private mapStates As aimsMap()

Private conArcIMS As aimsArcIMSConnector()

The Page_Load event sets up the connection and map parameters It also links the image URL (provided by ArcIMS) to the URL property of the Image control to display the map image

Private Sub Page_load(ByVal sender As SystemObject ByVal e As SystemEventArgs) Handles MyBaseLoad mapStates = New aimsMap() conArcIMS = New aimsArcIMSConnector() conArcIMSServerName = localhost conArcIMSServerPort = 5300 mapStatesInitMap(conArcIMS BPC_States) mapStatesWidth = 550 mapStatesHeight = 400 mapStatesRefresh()

ESRI White Paper 10

ImageButton1ImageUrl = mapStatesGetImageAsUrl

End Sub

The Button Click event makes a connection to the bpc2002mdb access database It then reads the data from the States column orders it alphabetically and then populates the DropDownList control with the ordered list of entries

Private Sub Button1_Click(ByVal sender As SystemObject ByVal e As SystemEventArgs) Handles Button1Click Dim conDB As OleDbOleDbConnection Dim cmdFetch As OleDbOleDbCommand Dim rdrStates As OleDbOleDbDataReader Dim sCon As String = Provider=MicrosoftJetOLEDB40Data Source=CArcIMSWebsiteBPC_Statesbpc2002mdb conDB = New OleDbOleDbConnection(sCon) conDBOpen() cmdFetch = New OleDbOleDbCommand(SELECT STATE_NAME FROM STATES ORDER BY STATE_NAME) cmdFetchConnection = conDB rdrStates = cmdFetchExecuteReader() While rdrStatesRead() DropDownList1ItemsAdd(New ListItem(rdrStatesGetString(0))) End While conDBClose()

End Sub

The DropDownList fires a SelectedIndexChanged event The code associated with this event uses the where expression with LayersItem()Filter to create an image with a special highlight applied to the selected state The URL of the image is linked to the image buttons URL to display the new image

Private Sub DropDownList1_SelectedIndexChanged(ByVal sender As Object ByVal e As SystemEventArgs) Handles DropDownList1SelectedIndexChanged Dim sWhere As String = STATE_NAME = amp DropDownList1SelectedItemText amp mapStatesLayersItem(4)FilterWhereExpression = sWhere mapStatesRefresh() ImageButton1ImageUrl = mapStatesGetImageAsUrl End Sub

The Page_Unload event is used for clean up code Here it is used to free memory by setting the map and connection object to Nothing

ESRI White Paper 11

Private Sub Page_unload(ByVal sender As Object ByVal e As SystemEventArgs) Handles MyBaseUnload mapStates = Nothing conArcIMS = Nothing

End Sub

Example 2

General Description

This web application demonstrates the use of two image controls in a web form to display a map image and its associated legend both images being served up by ArcIMS The web application also has controls for Zoomin Zoomout and pan

Programming Environment ASPNET and Web Forms

Programming Language Visual Basic NET

WebForm Controls

ESRI White Paper 12

Control Name Function ImgMap Control for displaying the image ImgLegend Control for displaying the legend image lstNavControls Radiobutton list controls

Data Files

Can use any datafile capable of generating an image service Replace the sf parameter in the page_load event with the appropriate image service name

Class Libraries ( Logic_classes assembly)

File Name Class Information Functionality MapVB The Cmap class has a

MustInherit Keyword and is inherited by Cviewer The MustInherit keyword specifies that a class cannot be instantiated and can be used only as a base class

PointVB Used by Cmap Crect Represents a geometric point (xy pair ) RectVB Used by Cmap Cviewer and

Webform3 in testformaspx

ViewerVB Used in Webform3 in testformaspx

Abstracts the requesting of a simple map from ArcIMS No additional entities will be added to the map (ie graphics buffer etc) The map is requested with all the default parameters with which it is served excepting extent and background color

Steps to Create Application

ESRI White Paper 13

The following section details the code found in the code behind page of the Testformaspx page

Statement to import logic_classes Makes all the functionality available in the logic_classes project available to the code in the web form

Imports logic_classes

Define a class level variable in the aspx file

Private m_objViewerMap As cViewer

Code for the page load event Uses IsPostback to determine if the extents need to be read afresh or from a previous valued stored in the session object Also instantiates the Cviewer class object You need to make sure that the extents shown in the code are appropriately changed to work with your selected image service

Private Sub Page_Load(ByVal sender As SystemObject ByVal e As SystemEventArgs) Handles MyBaseLoad

ESRI White Paper 14

Put user code to initialize the page here Dim rctExtent As cRect If Not IsPostBack Then enter appropriate extents rctExtent = New cRect(-1225173 377199 -122363678 3780374) Else rctExtent = New cRect(Session(MinX) Session(MinY) Session(MaxX) Session(MaxY)) End If m_objViewerMap = New cViewer(httplocalhostservletcomesriesrimapEsrimap _ sf _ rctExtent _ imgMapWidthValue _ imgMapHeightValue _ 000) add test markers

End Sub

Page_Prerender event code Links the output image to the Picture controls Also since HTTP is a stateless protocol the current map extents are stored in session variables for follow-up requests from the same user

Private Sub Page_PreRender(ByVal sender As Object ByVal e As SystemEventArgs) Handles MyBasePreRender imgMapImageUrl = m_objViewerMapMap() imgLegendImageUrl = m_objViewerMapLegend() Session(MinX) = m_objViewerMapExtentXMin Session(MinY) = m_objViewerMapExtentYMin Session(MaxX) = m_objViewerMapExtentXMax Session(MaxY) = m_objViewerMapExtentYMax

End Sub

Imgmap_click event is raised when the user clicks on the map Code associated with this event converts the image click coordinate to a map coordinate Then

ESRI White Paper 15

based on the radio button selection ( Zoomin Zoomout or pan) the code calls the appropriate method using the instantiated Cviewer object

Private Sub imgMap_Click(ByVal sender As Object ByVal e As SystemWebUIImageClickEventArgs) Handles imgMapClick Convert the image click coordinate to a map coordinate based on the maps current extent Dim rctCurrentExtent As cRect = m_objViewerMapExtent Dim dblX As Double = rctCurrentExtentXMin + ((eX imgMapWidthValue) (rctCurrentExtentXMax - rctCurrentExtentXMin)) Dim dblY As Double = rctCurrentExtentYMin + (((imgMapHeightValue - eY) imgMapHeightValue) (rctCurrentExtentYMax - rctCurrentExtentYMin)) If Trim(UCase(lstNavControlsSelectedItemText)) ltgt IDENTIFY Then m_objViewerMapCenterAt(dblX dblY) Select Case UCase(lstNavControlsSelectedItemText) Case ZOOM IN Center the map m_objViewerMapZoom(-1) Case ZOOM OUT m_objViewerMapZoom(1) Case PAN do nothing Case Else ErrRaise(vbObjectError + 512 imgMap_Click Invalid command) End Select Else identify End If End Sub

ESRI White Paper 16

End Class

NOTE =gt Once you have the relevant files imported into Visual Studio make sure that you configure the virtual directory as an application before you run the example

If the virtual directory is not configured as an Application you will get an error message that reads This error can be caused by a virtual directory not being configured as an application in IIS To configure a Virtual directory is simple Use the Internet Service Manager to perform the following steps

Find the folder in the virtual directory Right click and choose properties Click Create Accept all the settings and Click OK

Example 3

General Description

The program uses the catalog service (using the ltGETCLIENTSERVICESgt request) to query and list a collection of services running on the server A Radiobutton list control is used to list all the service names running on the server On selecting an appropriate image service the map image is displayed on the web form using an image control This program demonstrates two different ways to connect to the datasource Connection could be achieved using the http protocol or the TCP protocol The TCP method utilizes the TCP capability built into the ActiveX Connector Since ASPNET is a multithreaded and the ActiveX connector being Single Threaded (STA) a wrapper class with additional functionality to manage memory is used to access the methods in the ActiveX connector

ESRI White Paper 17

Programming Environment ASPNET and Web Forms

C NET Programming Language

WebForm Controls

Control Name Function ImgMap Control for displaying the image RbServices Radiobutton list controls Txtinfo Displays the name of the selected image service

Data Files

Requires a collection of image services running on an ArcIMS server The program uses the ltGETCLIENTSERVICESgt request tag to query the catalog service to list all the services running on the specified server

Class Libraries

File Name Class Information Functionality Connectioncs Abstract base class Provides abstract method

templates for the HTTPConnection and

ESRI White Paper 18

TCPConnection classes HTTPConnectioncs Inherits from Connection class Provides functionality for

sending request to service postinggetting URL content etc

TCPConnectioncs Inherits from Connection class and SystemIDisposable

Utlizes the AICLib assembly to access connection functionality built into the ActiveX connector

Datasourcecs Provides method for accessing path port host and other information

Enumerationscs Provides enumerations for AccessType and LoadType

Envelopecs Provides methods for getting and setting xy coordinates of the envelope

ImageReturnObjectcs Provides methods for settinggetting image URL image envelope and image scale

Mapcs Calls send request to service with connection and service information Parses response to obtain image URL

Servicecs Servicescs Inherits from

SystemCollectionsHashtable Composes the clientservices request and parses the response Creates a hashtable association of individual service name with its associated service object

XML helper class that provides relevant XML parsing functionality by acting as a wrapper class around NETs xml Text IO and other NET classes

XMLRequestscs Builds ArcXML strings for requests

XMLHelpercs

Steps to Create Application

ESRI White Paper 19

The NET solution contains 2 projects ArcIMS and ArcIMSSample The ArcIMS project

o References the InteropAICLib o Contains NET ArcIMS class libraries that can be used to connect and to

work with image services The ArcIMSSample project

o References the ArcIMS project o Contains the web form (webform1aspx) and the corresponding

webform1aspxcs code-behind page that connects the web page controls to relevant functionality using an event driven web forms model

Points to Note

In webform1aspxcs code session variables are used to maintain state of serialized objects In order for this to be possible notice that the relevant classes have been marked as serializable

ESRI White Paper 20

Choose the appropriate connection type based on HTTP or TCP connection For HTTP choose m_dsConnectType = ConnectionTypeInterNet and for For TCP select m_dsConnectType = ConnectionTypeIntraNet as shown in the code below

private ArcIMSDataSource getDataSource() m_ds = Session[datasource] as ArcIMSDataSource if ( m_ds == null ) m_ds = new ArcIMSDataSource() m_dsHost = localhost m_dsScheme = http m_dsPort = 80 m_dsAppServerPort = 5300 m_dsPath = servletcomesriesrimapEsrimap choose (comment uncomment) one of the following two statements to decide between TCP or HTTP type connection m_dsConnectType = ConnectionTypeIntraNet m_dsConnectType = ConnectionTypeInterNet SessionAdd(datasource m_ds) return m_ds

Accessing a COM Server from a NET Client With the introduction of the NET Framework and ASPNET COM at its basic level has not really changed Nevertheless there are a couple of issues to be aware of when making calls to a COM object from a NET managed code environment The ASPNET threading model is the Multiple Threaded Apartment (MTA) This will not interact reliably with STA components (the ActiveX connector provided with the ArcIMS setup was built as an STA component) To emphasize this issue heres a direct quote from the MSDN pages at Microsoft The ASPNET threading model is the Multiple Threaded Apartment (MTA) What this means is that components that you are using that were created for the Single Threaded Apartment (STA) will no longer perform or function reliably without taking some extra precautions in ASPNET This includes but is not limited to all COM components that have been created using Visual Basic 60 and earlier versions

To understand the issues better let us take a look at how NET deals with COM related issues The Common Language Runtime exposes COM objects through a proxy called the runtime callable wrapper (RCW) The RCWs primary function is to marshal calls between a NET client and COM object The RCW object is nothing but an object instantiated at runtime from class code contained in the Interop assembly

ESRI White Paper 21

Calling between managed and unmanaged components incurs a marshaling cost which can impede the performance of your pages When a managed client and unmanaged server are in the same apartment the Interop marshalling service handles all data marshalling However when client and server are initialized in different apartments COM marshalling is also required Therefore interoperability with COM from a NET client should take into consideration the threading model used

Figure Cross-apartment call between a NET client and COM object

As mentioned earlier ASPNET follows an MTA model by default You could use the default model to communicate with an STA COM component if there is not much of an overhead due to the cross-apartment marshalling Usually this is noticeable only when there are many calls across the boundary Another option would be to use the PageAspCompatMode property of the ASPNET client The ASPCompat=true attribute enables an STA thread pool to address performance with existing Visual Basic components on a per-page basis The runtime throws an exception if the compatibility tag is omitted and an STA component is referenced on the page If you convert the STA component to an assembly using Type Library Importer (a utility included with the NET SDK) the runtime does not detect that the component uses the STA model and does not throw an exception but your application can suffer from poor performance and possible deadlocks STA components cannot be used from NET Framework code modules (compiled NET assemblies) they can be used only from ASPNET pages

If you plan to use the ASPCOMPAT = TRUE page level directive for Example 1 remember to instantiate the COM object within the page_load event rather than constructing COM components during page construction time For example look at code examples A and B

Example A Example B ltPage Language = VB ASPCOMPAT = truegt

ltscript runat = servergt

private mapStates as new aimsMap()

private sub_load ()

ltPage Language = VB ASPCOMPAT = truegt

ltscript runat = servergt

private mapStates as aimsMap()

private sub_load ()

ESRI White Paper 22

end sub

mapStates = new aimsMap()

end sub

In example A the STA component would be instantiated at page construction time which is created from a thread that is not the STA thread that will run the page This will involve marshalling between MTA and STA threads during the construction of the page Example B shows the preferred mechanism to delay the process until later when the code executes under a STA thread It is best to construct any COM component and external resources when needed or in the Page_Load method

Also to create the object you can use either the New keyword or the CreateObject method The CreateObject method is typically used when you dont know the Program ID (ProgID) of the object you are going to create until run time (late binding) New is the recommended method for instantiating objects if you have access to the objects type library It is preferable to adopt the early binding model

Every scenario yields different performance characteristics so it is important to test adequately before deciding whether interoperability is the right choice for your application However in nearly all scenarios rewriting your COM components in managed code provides performance benefits

Summary The examples shown above provide adequate information to leverage the NET programming environment to build effective ArcIMS client applications The debugging features of a program like Visual StudioNET provide a variety of tools (break points trace etc) making the entire development experience considerably pain-free Use the debugger to understand the sequence in which calls are made One early exercise would be to look at the calling sequence of the various page related events such as page_init page_load and page_prerender Since the Web Forms code is compiled you should experience much better performance than with ASP pages that used code written in scripting languages like Javascript and VbScript

The powerful programming environment also means that you can now concentrate more on the logic of building large web applications as opposed to building simple page based asp applications Also look at the various caching mechanisms provided by ASPNET as these can be used to improve overall performance As always there are costs associated with most programming choices and this is all the more true in a web-programming environment For example consider the costs associated with using a web control as opposed to a HTML based control Use plain HTML controls instead of adopting web controls for simple items like label

ESRI White Paper 23

If you choose to use the ActiveX connector from within the NET environment make sure that you clearly understand the essentials of COM Interop and the various costs associated with marshalling The solutions outlined in this paper utilize existing ArcIMS services and should work with all versions of ArcIMS

Although all the development can be done without the use of an Integrated Development environment (IDE) like Visual StudioNET using such an environment provides convenient WYSIWYG features that can help in building and debugging the application If you do not have Visual StudioNET there are free IDEs available today that can also be used For example ASPNET Web Matrix is a community-supported easy-to-use WYSIWYG application development tool for ASPNET It can be installed via a quick 12 MB download from httpwwwaspnetwebmatrixdefaultaspx

ESRI White Paper 24

  • ArcIMS ndash An Introduction
  • What is NET
    • The NET Framework
      • The Common Language Runtime (CLR)
      • Managed Unmanaged and Unsafe code ndash Understandin
      • NET Framework Class Libraries
        • ASPNET and Web Forms
          • NET and ArcIMS
            • Example 1
            • Example 2
            • Example 3
              • Accessing a COM Server from a NET Client
              • Summary
Page 2: Consuming ArcIMS Image Services using .NET Client Web ... · Consuming ArcIMS Image Services using .NET Client Web Applications An ESRI White Paper Ł October 2002 ... The .NET framework

Copyright copy 2002 Environmental Systems Research Institute Inc All rights reserved Printed in the United States of America The information contained in this document is the exclusive property of Environmental Systems Research Institute Inc This work is protected under United States copyright law and other international copyright treaties and conventions No part of this work may be reproduced or transmitted in any form or by any means electronic or mechanical including photocopying and recording or by any information storage or retrieval system except as expressly permitted in writing by Environmental Systems Research Institute Inc All requests should be sent to Attention Contracts Manager Environmental Systems Research Institute Inc 380 New York Street Redlands CA 92373-8100 USA

The information contained in this document is subject to change without notice

US GOVERNMENT RESTRICTEDLIMITED RIGHTS Any software documentation andor data delivered hereunder is subject to the terms of the License Agreement In no event shall the US Government acquire greater than RESTRICTEDLIMITED RIGHTS At a minimum use duplication or disclosure by the US Government is subject to restrictions as set forth in FAR sect52227-14 Alternates I II and III (JUN 1987) FAR sect52227-19 (JUN 1987) andor FAR sect1221112212 (Commercial Technical DataComputer Software) and DFARS sect252227-7015 (NOV 1995) (Technical Data) andor DFARS sect2277202 (Computer Software) as applicable ContractorManufacturer is Environmental Systems Research Institute Inc 380 New York Street Redlands CA 92373-8100 USA ESRI ARCINFO ArcCAD ArcView BusinessMAP MapObjects PC ARCINFO SDE and the ESRI globe logo are trademarks of Environmental Systems Research Institute Inc registered in the United States and certain other countries registration is pending in the European Community 3D Analyst ADF ARC COGO the ARC COGO logo ARC GRID the ARC GRID logo ArcInfo the ArcInfo logo the ARCINFO logo AML ARC NETWORK the ARC NETWORK logo ArcNews ARC TIN the ARC TIN logo ArcInfo LIBRARIAN ArcInfoProfessional GIS ArcInfoThe Worlds GIS ArcAtlas the ArcAtlas logo the ArcCAD logo the ArcCAD WorkBench logo ArcCatalog the ArcData logo the ArcData Online logo ARCEDIT the ARCEDIT logo ArcExplorer the ArcExplorer logo ArcExpress the ArcExpress logo ArcFM the ArcFM logo the ArcFM Viewer logo ArcGIS ArcIMS the ArcIMS logo ArcLogistics the ArcLogistics Route logo ArcMap ArcObjects ARCPLOT the ARCPLOT logo ArcPress the ArcPress logo the ArcPress for ArcView logo ArcScan the ArcScan logo ArcScene the ArcScene logo ArcSchool ArcSDE the ArcSDE logo the ArcSDE CAD Client logo ArcSdl ArcStorm the ArcStorm logo ArcSurvey ArcToolbox ArcTools the ArcTools logo ArcUSA the ArcUSA logo ArcUser the ArcView GIS logo the ArcView 3D Analyst logo the ArcView Business Analyst logo the ArcView Data Publisher logo the ArcView Image Analysis logo the ArcView Internet Map Server logo the ArcView Network Analyst logo the ArcView Spatial Analyst logo the ArcView StreetMap logo the ArcView StreetMap 2000 logo the ArcView Tracking Analyst logo ArcVoyager ArcWorld the ArcWorld logo Atlas GIS the Atlas GIS logo AtlasWare Avenue the Avenue logo the BusinessMAP logo DAK the DAK logo DATABASE INTEGRATOR DBI Kit the Digital Chart of the World logo the ESRI corporate logo the ESRI PRESS logo ESRITeam GIS ESRIThe GIS People FormEdit Geographic Design System Geography Matters GIS Day the GIS Day logo GIS by ESRI GIS for Everyone GISData Server InsiteMAP MapBeans MapCafeacute the MapCafeacute logo the MapObjects logo the MapObjects Internet Map Server logo ModelBuilder NetEngine the NetEngine logo the PC ARCINFO logo PC ARCEDIT PC ARCPLOT PC ARCSHELL PC DATA CONVERSION PC NETWORK PC OVERLAY PC STARTER KIT PC TABLES the Production Line Tool Set logo RouteMAP the RouteMAP logo the RouteMAP IMS logo Spatial Database Engine the SDE logo SML StreetMap TABLES The Worlds Leading Desktop GIS Water Writes and Your Personal Geographic Information System are trademarks and ArcData ArcOpen ArcQuest ArcWatch ArcWeb Rent-a-Tech esricom and wwwesricom are service marks of Environmental Systems Research Institute Inc The names of other companies and products herein are trademarks or registered trademarks of their respective trademark owners

ESRI White Paper ii

Consuming ArcIMS Image Services using NET Client Web Applications

An ESRI White Paper

ArcIMS An Introduction 1 What is NET 2

The NET Framework 2 The Common Language Runtime (CLR) 2 Managed Unmanaged and Unsafe code Understanding the Difference 3 NET Framework Class Libraries 4

ASPNET and Web Forms 4 NET and ArcIMS 6

Example 1 7 Example 2 12 Example 3 17

Accessing a COM Server from a NET Client 21 Summary 23

Consuming ArcIMS Image Services using NET Client Web Applications

ArcIMS An Introduction ArcIMS provides the foundation for distributing high-end geographic information systems (GIS) and mapping services via the Internet ArcIMS software enables users to integrate local data sources with Internet data sources for display query and analysis in an easy-to-use Web browser The ArcIMS Architecture consists of different types of connectors that allow you to customize client application to access specific services of the ArcIMS Server and display the results The connectors provided with ArcIMS include the ActiveX connector Servlet connector Cold Fusion connector and the Java connector Depending on the choice of these connectors you can write customized web applications using ASP DHTMLArcXML Cold Fusion or JSP The ActiveX and the Java connector expose a rich object model that makes development of client side applications relatively simple It is also possible to use the Servlet connector to send requests formatted as asArcXML strings to the ArcIMS spatial computing engine (Spatial server) and receives the response in the same ArcXML format This response can then be parsed to display the mapresult The ActiveX connector and the Servlet connector model can both be utilized within a NET programming environment to provide feature rich web applications The ArcIMS architecture also utilizes components such as the Application Server for load balancing making the entire setup highly scalable Please refer to the paper ArcIMS 4 Architecture and Functionality for a detailed review of ArcIMS architecture

Fundamentally NET can be looked at as a rich technology to produce Web Applications In some sense the term NET has now become synonymous with services more typically Web Services the ability to use Collaborative Web Applications that span

ESRI White Paper 1

heterogeneous environments Simply put web services allow you to share information or integrate with legacy systems without having to write specialized interconnection applications In this paper we will restrict the discussions and examples to using ASPNET as a unified Web development platform for building sophisticated web applications that will interact with ArcIMS Image Services

To understand and appreciate the additional benefits that NET technology brings to the table you should have some experience programming the ArcIMS client applications using the ActiveX or the Servlet connector model Also a good understanding of ArcXML syntax is essential to effectively use the Servlet connector model

Let us start by looking at what NET technology really is and get a firm handle on some of the terminologies used

What is NET NET is a new computing platform that simplifies application development in the highly distributed environment of the Internet The NET platform is built on top of the operating system NET has been influenced by other technological advances such as XML Java and COM The NET infrastructure comprises the NET framework Microsoft Visual StudioNET the NET Enterprise Servers and Microsoft WindowsNet In short the NET infrastructure refers to all the technologies that make up the environment for creating and running robust scalable and distributed applications

The following paragraphs provide a brief overview of some of the technologies and terminologies associated with NET To get more detailed information on NET there are a large number of books and information freely available on the internet that provide detailed descriptions of the technology This paper focuses on getting a broad perspective and some detailed knowledge of specific areas of the NET framework that can assist in leveraging this technology within the ArcIMS Internet Mapping Environment

The NET Framework

The NET framework is the part of the infrastructure that aids us in creating applications In simple terms the NET Framework can be discussed as containing 2 parts the CLR or the Common Language Runtime and the NET Framework Class libraries

The Common Language Runtime (CLR)

The CLR is the most important part of the NET architecture and computing paradigm It is the run-time environment in which applications written in different languages can all exist and play together providing cross-language interoperability

The mechanism for cross language interoperability is provided via the concept of Common Language Specification (CLS) a common set of rules A compiler that adheres

ESRI White Paper 2

to the rules can take code written in a specific language and port it to MSIL a Microsoft Intermediate Language Since MSIL code cannot be executed directly the CLR compiles the MSIL by using a Just-in-time (JIT) compiler into native CPU instructions as it processes the MSIL

One term that is mentioned a lot in conjunction with NET is managed code This is in fact made possible by the CLR Managed code is just code that is run under the auspices of the CLR or in other words code managed by the CLR One of the most important services provided by the CLR as part of the managed code paradigm is the concept of garbage collection NET uses automatic garbage collection to reclaim memory When memory allocated on the heap becomes orphaned or passes out of scope it is placed on a list of memory locations to be freed Periodically the system runs a garbage collection thread that returns the memory to the heap

While the runtime is designed for the software of the future it also supports legacy technology Interoperability between managed and unmanaged code enables developers to continue to use necessary COM components and DLLs

Managed Unmanaged and Unsafe code Understanding the Difference

Managed code is that code which executes under the supervision of the CLR This was dealt with in the section above The user has no control over how CLR achieves memory management type verification garbage collection and many other activities Uunmanaged code is that code which executes outside the context of the CLR The best example of this is your traditional Win32 DLLs like KERNEL32DLL USER32DLL and the COM components installed on our system How they allocate memory for their usage how memory is released how (if any) type verification takes places are some of the tasks that are undertaken by them on their own Unsafe code is a kind of cross between the managed and unmanaged codes It executes under the supervision of the CLR just like the managed code but lets you address the memory directly through the use of pointers as is done in unmanaged code A typical example would be a NET application that uses the functionality in a legacy Win32 DLL whose exported functions require the use of pointers Unless you are a NET aficionado understanding unsafe code and its implications may not be important to you But understanding the differences between Managed and Unmanaged code should provide you enough information to deal effectively with interoperability issues that needs to be dealt with while working with the ActiveX connector

ESRI White Paper 3

NET Framework Class Libraries

The NET Framework class library is a collection of reusable types that tightly integrate with the common language runtime The class library is object oriented providing types from which your own managed code can derive functionality

The NET Framework types enable you to accomplish a range of common programming tasks including tasks such as string management data collection database connectivity and file access In addition to these common tasks the class library includes types that support a variety of specialized development scenarios This paper includes examples of class libraries created by ESRI that provide rich functionality for developers to inherit in their web applications

Also the examples shown in this paper make use of ASPNET and web forms technologies As you create applications in ASPNET you will find it convenient to use many of the classes provided as part of the web forms class library

As you become familiar with the classes in the NET framework you may want to create wrapper classes that provide functionality for XML parsing internet intranet connections that inherit from base classes in the NET framework By creating your own classes you can provide reusable componentized code for building other ArcIMS client applications that require similar functionality

NET programs are deployed as assemblies An assembly is one or more EXEs or DLLs with associated metadata information The metadata about the entire assembly is stored in the assemblys manifest The manifest contains for example a list of assemblies upon which the current assembly is dependant The concept of assemblies how they can be deployed privately or publicly how they can be versioned etc is quite complex and are not discussed in this paper As always the internet serves as good source for information regarding these topics

ASPNET and Web Forms

The various web applications shown in this paper were all built using ASPNET ASPNET is the hosting environment that enables developers to use the NET Framework to target Web-based applications However ASPNET is more than just a runtime host it is a complete architecture for developing Web sites and Internet-distributed objects using managed code Both Web Forms and XML Web services use IIS and ASPNET as the publishing mechanism for applications and both have a collection of supporting classes in the NET Framework If you have used earlier versions of ASP technology it is easy to note the improvements provided by ASPNET and Web Forms For example you can develop Web Forms pages in any language that supports the NET Framework In addition ASPNET no longer needs to share the same file with your HTTP text (although it can continue to do so if you

ESRI White Paper 4

prefer) Unlike unmanaged ASP code that is always scripted and interpreted ASPNET pages are faster and easier to manage as they execute in native machine language and interact with the runtime like any managed application To summarize here are a few benefits to programming with ASPNET

Object Orientation and a large class library from which to inherit functionality Can use multiple programming languages VBNET C etc Code is always

compiled before it is run Web Forms and Web Controls present the programmer with an event driven

model very similar to the desktop environment Server side controls intelligently render html code appropriate to the target browser

Advanced crash-recovery and detection and isolation of rogue code damaging the system

Scalable architecture with extensive caching to reduce running lots of identical code for each website visitor

Debugging is much easier especially when the programming is done using an IDE like Visual StudioNet

The NET programming environment provides very good database and XML support

MSIL and the new assembly model makes deploying applications and versioning complexities an issue of the past

Provides tools to easily create webservices All the plumbing code required is effectively hidden

The diagram below shows the typical sequence of calls made during a request response cycle for a ASPNET web page Notice that the first request-response cycle is shown by steps 1 through 6 and subsequent calls are displayed as steps 7-10

ESRI White Paper 5

Because ASPNET uses compiled code instead of interpreted code subsequent requests will check to see if there has been any change to the code If not it will utilize the script engine cache to access the compiled version of the code

NET and ArcIMS In order to better understand how to build map services using ArcIMS and the NET environment this paper presents the concepts in a series of three examples The examples all written using NET compatible languages (VBNET and C) demonstrate web applications that display map images served up ESRIs ArcIMS product The examples chosen are such that they provide a good handle on the various aspects of designing web applications that server as clients to the ArcIMS Image Service The following are a brief description of the three examples

Example 1 An ASPNET application written in VBNET that utilizes COM Interop to access the functionality exposed by the ActiveX connector

Example 2 An ASPNET application written in VBNET that makes use of special classes (also developed in VBNET) to send and receive requests via the Servlet connector in ArcIMS This example also contains code that shows you how to capture page coordinates from a mouse click event on the image map control It also shows the

ESRI White Paper 6

necessary steps to convert the obtained page coordinates to map coordinates for subsequent use in zoom operations

Example 3 An ASPNET application written in C that makes use of special classes developed in C This example utilizes two approaches one using the Servlet connector and another using a C wrapper to the ActiveX connector to connect to the service using TCP

Example 1

This application is a very simple web application that demonstrates the use of an image control in a web form to display a map image served up by ArcIMS The button control reads State Names from a database and populates the DropDownList Selecting a State from the DropDownList highlights the state in the map

This example demonstrates the following

Basic web form and web controls Button Image and DropDownListcontrols Using the ActiveX connector in a NET web application using COM Interop

ESRI White Paper 7

Connecting to an access database to read a list of names (from a column) This list is then used to populate a drop down list box

Using the image control to view an image rendered by ArcIMS

ASPNET and Web Forms Programming Environment

Visual Basic NET Programming Language

Data Files

File Name Comment BPC 2002mdb Database file with a column containing state names World30stateslakescountry Shape files BPC_STATESaxl Axl file for the image service

WebForm Controls

Control Name Function ImageButton1 Control for displaying the image Button Populates the Dropdown Listbox with State Names read from the

database DropDownList1 Set AutoPostback property to TRUE

Steps to Create Application

Create a new Project Choose Visual Basic Project -gt ASPNET web application

Add Project References

ESRI White Paper 8

o Project Add References COM ArcIMS ActiveX Connector (Aims_ActiveXdll)

o Project Add References NET adodb ( adodbdll)

Add controls to the form and set the appropriate properties (NameCaption Size etc)

Right click on the WebForm1aspx file and choose Viewcode Type the code shown below Click on Build-gtSolution Press CTRL+F5 to start without debugging or F5 to Start (with debugging)

ESRI White Paper 9

Code from Web Form1aspxvb the codebehind page for the Web Form

Define and instantiate class variables Refer to the Section Accessing a COM Server from a NET Client for a discussion on using early and late binding mechanisms to instantiate COM objects

Private mapStates As aimsMap()

Private conArcIMS As aimsArcIMSConnector()

The Page_Load event sets up the connection and map parameters It also links the image URL (provided by ArcIMS) to the URL property of the Image control to display the map image

Private Sub Page_load(ByVal sender As SystemObject ByVal e As SystemEventArgs) Handles MyBaseLoad mapStates = New aimsMap() conArcIMS = New aimsArcIMSConnector() conArcIMSServerName = localhost conArcIMSServerPort = 5300 mapStatesInitMap(conArcIMS BPC_States) mapStatesWidth = 550 mapStatesHeight = 400 mapStatesRefresh()

ESRI White Paper 10

ImageButton1ImageUrl = mapStatesGetImageAsUrl

End Sub

The Button Click event makes a connection to the bpc2002mdb access database It then reads the data from the States column orders it alphabetically and then populates the DropDownList control with the ordered list of entries

Private Sub Button1_Click(ByVal sender As SystemObject ByVal e As SystemEventArgs) Handles Button1Click Dim conDB As OleDbOleDbConnection Dim cmdFetch As OleDbOleDbCommand Dim rdrStates As OleDbOleDbDataReader Dim sCon As String = Provider=MicrosoftJetOLEDB40Data Source=CArcIMSWebsiteBPC_Statesbpc2002mdb conDB = New OleDbOleDbConnection(sCon) conDBOpen() cmdFetch = New OleDbOleDbCommand(SELECT STATE_NAME FROM STATES ORDER BY STATE_NAME) cmdFetchConnection = conDB rdrStates = cmdFetchExecuteReader() While rdrStatesRead() DropDownList1ItemsAdd(New ListItem(rdrStatesGetString(0))) End While conDBClose()

End Sub

The DropDownList fires a SelectedIndexChanged event The code associated with this event uses the where expression with LayersItem()Filter to create an image with a special highlight applied to the selected state The URL of the image is linked to the image buttons URL to display the new image

Private Sub DropDownList1_SelectedIndexChanged(ByVal sender As Object ByVal e As SystemEventArgs) Handles DropDownList1SelectedIndexChanged Dim sWhere As String = STATE_NAME = amp DropDownList1SelectedItemText amp mapStatesLayersItem(4)FilterWhereExpression = sWhere mapStatesRefresh() ImageButton1ImageUrl = mapStatesGetImageAsUrl End Sub

The Page_Unload event is used for clean up code Here it is used to free memory by setting the map and connection object to Nothing

ESRI White Paper 11

Private Sub Page_unload(ByVal sender As Object ByVal e As SystemEventArgs) Handles MyBaseUnload mapStates = Nothing conArcIMS = Nothing

End Sub

Example 2

General Description

This web application demonstrates the use of two image controls in a web form to display a map image and its associated legend both images being served up by ArcIMS The web application also has controls for Zoomin Zoomout and pan

Programming Environment ASPNET and Web Forms

Programming Language Visual Basic NET

WebForm Controls

ESRI White Paper 12

Control Name Function ImgMap Control for displaying the image ImgLegend Control for displaying the legend image lstNavControls Radiobutton list controls

Data Files

Can use any datafile capable of generating an image service Replace the sf parameter in the page_load event with the appropriate image service name

Class Libraries ( Logic_classes assembly)

File Name Class Information Functionality MapVB The Cmap class has a

MustInherit Keyword and is inherited by Cviewer The MustInherit keyword specifies that a class cannot be instantiated and can be used only as a base class

PointVB Used by Cmap Crect Represents a geometric point (xy pair ) RectVB Used by Cmap Cviewer and

Webform3 in testformaspx

ViewerVB Used in Webform3 in testformaspx

Abstracts the requesting of a simple map from ArcIMS No additional entities will be added to the map (ie graphics buffer etc) The map is requested with all the default parameters with which it is served excepting extent and background color

Steps to Create Application

ESRI White Paper 13

The following section details the code found in the code behind page of the Testformaspx page

Statement to import logic_classes Makes all the functionality available in the logic_classes project available to the code in the web form

Imports logic_classes

Define a class level variable in the aspx file

Private m_objViewerMap As cViewer

Code for the page load event Uses IsPostback to determine if the extents need to be read afresh or from a previous valued stored in the session object Also instantiates the Cviewer class object You need to make sure that the extents shown in the code are appropriately changed to work with your selected image service

Private Sub Page_Load(ByVal sender As SystemObject ByVal e As SystemEventArgs) Handles MyBaseLoad

ESRI White Paper 14

Put user code to initialize the page here Dim rctExtent As cRect If Not IsPostBack Then enter appropriate extents rctExtent = New cRect(-1225173 377199 -122363678 3780374) Else rctExtent = New cRect(Session(MinX) Session(MinY) Session(MaxX) Session(MaxY)) End If m_objViewerMap = New cViewer(httplocalhostservletcomesriesrimapEsrimap _ sf _ rctExtent _ imgMapWidthValue _ imgMapHeightValue _ 000) add test markers

End Sub

Page_Prerender event code Links the output image to the Picture controls Also since HTTP is a stateless protocol the current map extents are stored in session variables for follow-up requests from the same user

Private Sub Page_PreRender(ByVal sender As Object ByVal e As SystemEventArgs) Handles MyBasePreRender imgMapImageUrl = m_objViewerMapMap() imgLegendImageUrl = m_objViewerMapLegend() Session(MinX) = m_objViewerMapExtentXMin Session(MinY) = m_objViewerMapExtentYMin Session(MaxX) = m_objViewerMapExtentXMax Session(MaxY) = m_objViewerMapExtentYMax

End Sub

Imgmap_click event is raised when the user clicks on the map Code associated with this event converts the image click coordinate to a map coordinate Then

ESRI White Paper 15

based on the radio button selection ( Zoomin Zoomout or pan) the code calls the appropriate method using the instantiated Cviewer object

Private Sub imgMap_Click(ByVal sender As Object ByVal e As SystemWebUIImageClickEventArgs) Handles imgMapClick Convert the image click coordinate to a map coordinate based on the maps current extent Dim rctCurrentExtent As cRect = m_objViewerMapExtent Dim dblX As Double = rctCurrentExtentXMin + ((eX imgMapWidthValue) (rctCurrentExtentXMax - rctCurrentExtentXMin)) Dim dblY As Double = rctCurrentExtentYMin + (((imgMapHeightValue - eY) imgMapHeightValue) (rctCurrentExtentYMax - rctCurrentExtentYMin)) If Trim(UCase(lstNavControlsSelectedItemText)) ltgt IDENTIFY Then m_objViewerMapCenterAt(dblX dblY) Select Case UCase(lstNavControlsSelectedItemText) Case ZOOM IN Center the map m_objViewerMapZoom(-1) Case ZOOM OUT m_objViewerMapZoom(1) Case PAN do nothing Case Else ErrRaise(vbObjectError + 512 imgMap_Click Invalid command) End Select Else identify End If End Sub

ESRI White Paper 16

End Class

NOTE =gt Once you have the relevant files imported into Visual Studio make sure that you configure the virtual directory as an application before you run the example

If the virtual directory is not configured as an Application you will get an error message that reads This error can be caused by a virtual directory not being configured as an application in IIS To configure a Virtual directory is simple Use the Internet Service Manager to perform the following steps

Find the folder in the virtual directory Right click and choose properties Click Create Accept all the settings and Click OK

Example 3

General Description

The program uses the catalog service (using the ltGETCLIENTSERVICESgt request) to query and list a collection of services running on the server A Radiobutton list control is used to list all the service names running on the server On selecting an appropriate image service the map image is displayed on the web form using an image control This program demonstrates two different ways to connect to the datasource Connection could be achieved using the http protocol or the TCP protocol The TCP method utilizes the TCP capability built into the ActiveX Connector Since ASPNET is a multithreaded and the ActiveX connector being Single Threaded (STA) a wrapper class with additional functionality to manage memory is used to access the methods in the ActiveX connector

ESRI White Paper 17

Programming Environment ASPNET and Web Forms

C NET Programming Language

WebForm Controls

Control Name Function ImgMap Control for displaying the image RbServices Radiobutton list controls Txtinfo Displays the name of the selected image service

Data Files

Requires a collection of image services running on an ArcIMS server The program uses the ltGETCLIENTSERVICESgt request tag to query the catalog service to list all the services running on the specified server

Class Libraries

File Name Class Information Functionality Connectioncs Abstract base class Provides abstract method

templates for the HTTPConnection and

ESRI White Paper 18

TCPConnection classes HTTPConnectioncs Inherits from Connection class Provides functionality for

sending request to service postinggetting URL content etc

TCPConnectioncs Inherits from Connection class and SystemIDisposable

Utlizes the AICLib assembly to access connection functionality built into the ActiveX connector

Datasourcecs Provides method for accessing path port host and other information

Enumerationscs Provides enumerations for AccessType and LoadType

Envelopecs Provides methods for getting and setting xy coordinates of the envelope

ImageReturnObjectcs Provides methods for settinggetting image URL image envelope and image scale

Mapcs Calls send request to service with connection and service information Parses response to obtain image URL

Servicecs Servicescs Inherits from

SystemCollectionsHashtable Composes the clientservices request and parses the response Creates a hashtable association of individual service name with its associated service object

XML helper class that provides relevant XML parsing functionality by acting as a wrapper class around NETs xml Text IO and other NET classes

XMLRequestscs Builds ArcXML strings for requests

XMLHelpercs

Steps to Create Application

ESRI White Paper 19

The NET solution contains 2 projects ArcIMS and ArcIMSSample The ArcIMS project

o References the InteropAICLib o Contains NET ArcIMS class libraries that can be used to connect and to

work with image services The ArcIMSSample project

o References the ArcIMS project o Contains the web form (webform1aspx) and the corresponding

webform1aspxcs code-behind page that connects the web page controls to relevant functionality using an event driven web forms model

Points to Note

In webform1aspxcs code session variables are used to maintain state of serialized objects In order for this to be possible notice that the relevant classes have been marked as serializable

ESRI White Paper 20

Choose the appropriate connection type based on HTTP or TCP connection For HTTP choose m_dsConnectType = ConnectionTypeInterNet and for For TCP select m_dsConnectType = ConnectionTypeIntraNet as shown in the code below

private ArcIMSDataSource getDataSource() m_ds = Session[datasource] as ArcIMSDataSource if ( m_ds == null ) m_ds = new ArcIMSDataSource() m_dsHost = localhost m_dsScheme = http m_dsPort = 80 m_dsAppServerPort = 5300 m_dsPath = servletcomesriesrimapEsrimap choose (comment uncomment) one of the following two statements to decide between TCP or HTTP type connection m_dsConnectType = ConnectionTypeIntraNet m_dsConnectType = ConnectionTypeInterNet SessionAdd(datasource m_ds) return m_ds

Accessing a COM Server from a NET Client With the introduction of the NET Framework and ASPNET COM at its basic level has not really changed Nevertheless there are a couple of issues to be aware of when making calls to a COM object from a NET managed code environment The ASPNET threading model is the Multiple Threaded Apartment (MTA) This will not interact reliably with STA components (the ActiveX connector provided with the ArcIMS setup was built as an STA component) To emphasize this issue heres a direct quote from the MSDN pages at Microsoft The ASPNET threading model is the Multiple Threaded Apartment (MTA) What this means is that components that you are using that were created for the Single Threaded Apartment (STA) will no longer perform or function reliably without taking some extra precautions in ASPNET This includes but is not limited to all COM components that have been created using Visual Basic 60 and earlier versions

To understand the issues better let us take a look at how NET deals with COM related issues The Common Language Runtime exposes COM objects through a proxy called the runtime callable wrapper (RCW) The RCWs primary function is to marshal calls between a NET client and COM object The RCW object is nothing but an object instantiated at runtime from class code contained in the Interop assembly

ESRI White Paper 21

Calling between managed and unmanaged components incurs a marshaling cost which can impede the performance of your pages When a managed client and unmanaged server are in the same apartment the Interop marshalling service handles all data marshalling However when client and server are initialized in different apartments COM marshalling is also required Therefore interoperability with COM from a NET client should take into consideration the threading model used

Figure Cross-apartment call between a NET client and COM object

As mentioned earlier ASPNET follows an MTA model by default You could use the default model to communicate with an STA COM component if there is not much of an overhead due to the cross-apartment marshalling Usually this is noticeable only when there are many calls across the boundary Another option would be to use the PageAspCompatMode property of the ASPNET client The ASPCompat=true attribute enables an STA thread pool to address performance with existing Visual Basic components on a per-page basis The runtime throws an exception if the compatibility tag is omitted and an STA component is referenced on the page If you convert the STA component to an assembly using Type Library Importer (a utility included with the NET SDK) the runtime does not detect that the component uses the STA model and does not throw an exception but your application can suffer from poor performance and possible deadlocks STA components cannot be used from NET Framework code modules (compiled NET assemblies) they can be used only from ASPNET pages

If you plan to use the ASPCOMPAT = TRUE page level directive for Example 1 remember to instantiate the COM object within the page_load event rather than constructing COM components during page construction time For example look at code examples A and B

Example A Example B ltPage Language = VB ASPCOMPAT = truegt

ltscript runat = servergt

private mapStates as new aimsMap()

private sub_load ()

ltPage Language = VB ASPCOMPAT = truegt

ltscript runat = servergt

private mapStates as aimsMap()

private sub_load ()

ESRI White Paper 22

end sub

mapStates = new aimsMap()

end sub

In example A the STA component would be instantiated at page construction time which is created from a thread that is not the STA thread that will run the page This will involve marshalling between MTA and STA threads during the construction of the page Example B shows the preferred mechanism to delay the process until later when the code executes under a STA thread It is best to construct any COM component and external resources when needed or in the Page_Load method

Also to create the object you can use either the New keyword or the CreateObject method The CreateObject method is typically used when you dont know the Program ID (ProgID) of the object you are going to create until run time (late binding) New is the recommended method for instantiating objects if you have access to the objects type library It is preferable to adopt the early binding model

Every scenario yields different performance characteristics so it is important to test adequately before deciding whether interoperability is the right choice for your application However in nearly all scenarios rewriting your COM components in managed code provides performance benefits

Summary The examples shown above provide adequate information to leverage the NET programming environment to build effective ArcIMS client applications The debugging features of a program like Visual StudioNET provide a variety of tools (break points trace etc) making the entire development experience considerably pain-free Use the debugger to understand the sequence in which calls are made One early exercise would be to look at the calling sequence of the various page related events such as page_init page_load and page_prerender Since the Web Forms code is compiled you should experience much better performance than with ASP pages that used code written in scripting languages like Javascript and VbScript

The powerful programming environment also means that you can now concentrate more on the logic of building large web applications as opposed to building simple page based asp applications Also look at the various caching mechanisms provided by ASPNET as these can be used to improve overall performance As always there are costs associated with most programming choices and this is all the more true in a web-programming environment For example consider the costs associated with using a web control as opposed to a HTML based control Use plain HTML controls instead of adopting web controls for simple items like label

ESRI White Paper 23

If you choose to use the ActiveX connector from within the NET environment make sure that you clearly understand the essentials of COM Interop and the various costs associated with marshalling The solutions outlined in this paper utilize existing ArcIMS services and should work with all versions of ArcIMS

Although all the development can be done without the use of an Integrated Development environment (IDE) like Visual StudioNET using such an environment provides convenient WYSIWYG features that can help in building and debugging the application If you do not have Visual StudioNET there are free IDEs available today that can also be used For example ASPNET Web Matrix is a community-supported easy-to-use WYSIWYG application development tool for ASPNET It can be installed via a quick 12 MB download from httpwwwaspnetwebmatrixdefaultaspx

ESRI White Paper 24

  • ArcIMS ndash An Introduction
  • What is NET
    • The NET Framework
      • The Common Language Runtime (CLR)
      • Managed Unmanaged and Unsafe code ndash Understandin
      • NET Framework Class Libraries
        • ASPNET and Web Forms
          • NET and ArcIMS
            • Example 1
            • Example 2
            • Example 3
              • Accessing a COM Server from a NET Client
              • Summary
Page 3: Consuming ArcIMS Image Services using .NET Client Web ... · Consuming ArcIMS Image Services using .NET Client Web Applications An ESRI White Paper Ł October 2002 ... The .NET framework

Consuming ArcIMS Image Services using NET Client Web Applications

An ESRI White Paper

ArcIMS An Introduction 1 What is NET 2

The NET Framework 2 The Common Language Runtime (CLR) 2 Managed Unmanaged and Unsafe code Understanding the Difference 3 NET Framework Class Libraries 4

ASPNET and Web Forms 4 NET and ArcIMS 6

Example 1 7 Example 2 12 Example 3 17

Accessing a COM Server from a NET Client 21 Summary 23

Consuming ArcIMS Image Services using NET Client Web Applications

ArcIMS An Introduction ArcIMS provides the foundation for distributing high-end geographic information systems (GIS) and mapping services via the Internet ArcIMS software enables users to integrate local data sources with Internet data sources for display query and analysis in an easy-to-use Web browser The ArcIMS Architecture consists of different types of connectors that allow you to customize client application to access specific services of the ArcIMS Server and display the results The connectors provided with ArcIMS include the ActiveX connector Servlet connector Cold Fusion connector and the Java connector Depending on the choice of these connectors you can write customized web applications using ASP DHTMLArcXML Cold Fusion or JSP The ActiveX and the Java connector expose a rich object model that makes development of client side applications relatively simple It is also possible to use the Servlet connector to send requests formatted as asArcXML strings to the ArcIMS spatial computing engine (Spatial server) and receives the response in the same ArcXML format This response can then be parsed to display the mapresult The ActiveX connector and the Servlet connector model can both be utilized within a NET programming environment to provide feature rich web applications The ArcIMS architecture also utilizes components such as the Application Server for load balancing making the entire setup highly scalable Please refer to the paper ArcIMS 4 Architecture and Functionality for a detailed review of ArcIMS architecture

Fundamentally NET can be looked at as a rich technology to produce Web Applications In some sense the term NET has now become synonymous with services more typically Web Services the ability to use Collaborative Web Applications that span

ESRI White Paper 1

heterogeneous environments Simply put web services allow you to share information or integrate with legacy systems without having to write specialized interconnection applications In this paper we will restrict the discussions and examples to using ASPNET as a unified Web development platform for building sophisticated web applications that will interact with ArcIMS Image Services

To understand and appreciate the additional benefits that NET technology brings to the table you should have some experience programming the ArcIMS client applications using the ActiveX or the Servlet connector model Also a good understanding of ArcXML syntax is essential to effectively use the Servlet connector model

Let us start by looking at what NET technology really is and get a firm handle on some of the terminologies used

What is NET NET is a new computing platform that simplifies application development in the highly distributed environment of the Internet The NET platform is built on top of the operating system NET has been influenced by other technological advances such as XML Java and COM The NET infrastructure comprises the NET framework Microsoft Visual StudioNET the NET Enterprise Servers and Microsoft WindowsNet In short the NET infrastructure refers to all the technologies that make up the environment for creating and running robust scalable and distributed applications

The following paragraphs provide a brief overview of some of the technologies and terminologies associated with NET To get more detailed information on NET there are a large number of books and information freely available on the internet that provide detailed descriptions of the technology This paper focuses on getting a broad perspective and some detailed knowledge of specific areas of the NET framework that can assist in leveraging this technology within the ArcIMS Internet Mapping Environment

The NET Framework

The NET framework is the part of the infrastructure that aids us in creating applications In simple terms the NET Framework can be discussed as containing 2 parts the CLR or the Common Language Runtime and the NET Framework Class libraries

The Common Language Runtime (CLR)

The CLR is the most important part of the NET architecture and computing paradigm It is the run-time environment in which applications written in different languages can all exist and play together providing cross-language interoperability

The mechanism for cross language interoperability is provided via the concept of Common Language Specification (CLS) a common set of rules A compiler that adheres

ESRI White Paper 2

to the rules can take code written in a specific language and port it to MSIL a Microsoft Intermediate Language Since MSIL code cannot be executed directly the CLR compiles the MSIL by using a Just-in-time (JIT) compiler into native CPU instructions as it processes the MSIL

One term that is mentioned a lot in conjunction with NET is managed code This is in fact made possible by the CLR Managed code is just code that is run under the auspices of the CLR or in other words code managed by the CLR One of the most important services provided by the CLR as part of the managed code paradigm is the concept of garbage collection NET uses automatic garbage collection to reclaim memory When memory allocated on the heap becomes orphaned or passes out of scope it is placed on a list of memory locations to be freed Periodically the system runs a garbage collection thread that returns the memory to the heap

While the runtime is designed for the software of the future it also supports legacy technology Interoperability between managed and unmanaged code enables developers to continue to use necessary COM components and DLLs

Managed Unmanaged and Unsafe code Understanding the Difference

Managed code is that code which executes under the supervision of the CLR This was dealt with in the section above The user has no control over how CLR achieves memory management type verification garbage collection and many other activities Uunmanaged code is that code which executes outside the context of the CLR The best example of this is your traditional Win32 DLLs like KERNEL32DLL USER32DLL and the COM components installed on our system How they allocate memory for their usage how memory is released how (if any) type verification takes places are some of the tasks that are undertaken by them on their own Unsafe code is a kind of cross between the managed and unmanaged codes It executes under the supervision of the CLR just like the managed code but lets you address the memory directly through the use of pointers as is done in unmanaged code A typical example would be a NET application that uses the functionality in a legacy Win32 DLL whose exported functions require the use of pointers Unless you are a NET aficionado understanding unsafe code and its implications may not be important to you But understanding the differences between Managed and Unmanaged code should provide you enough information to deal effectively with interoperability issues that needs to be dealt with while working with the ActiveX connector

ESRI White Paper 3

NET Framework Class Libraries

The NET Framework class library is a collection of reusable types that tightly integrate with the common language runtime The class library is object oriented providing types from which your own managed code can derive functionality

The NET Framework types enable you to accomplish a range of common programming tasks including tasks such as string management data collection database connectivity and file access In addition to these common tasks the class library includes types that support a variety of specialized development scenarios This paper includes examples of class libraries created by ESRI that provide rich functionality for developers to inherit in their web applications

Also the examples shown in this paper make use of ASPNET and web forms technologies As you create applications in ASPNET you will find it convenient to use many of the classes provided as part of the web forms class library

As you become familiar with the classes in the NET framework you may want to create wrapper classes that provide functionality for XML parsing internet intranet connections that inherit from base classes in the NET framework By creating your own classes you can provide reusable componentized code for building other ArcIMS client applications that require similar functionality

NET programs are deployed as assemblies An assembly is one or more EXEs or DLLs with associated metadata information The metadata about the entire assembly is stored in the assemblys manifest The manifest contains for example a list of assemblies upon which the current assembly is dependant The concept of assemblies how they can be deployed privately or publicly how they can be versioned etc is quite complex and are not discussed in this paper As always the internet serves as good source for information regarding these topics

ASPNET and Web Forms

The various web applications shown in this paper were all built using ASPNET ASPNET is the hosting environment that enables developers to use the NET Framework to target Web-based applications However ASPNET is more than just a runtime host it is a complete architecture for developing Web sites and Internet-distributed objects using managed code Both Web Forms and XML Web services use IIS and ASPNET as the publishing mechanism for applications and both have a collection of supporting classes in the NET Framework If you have used earlier versions of ASP technology it is easy to note the improvements provided by ASPNET and Web Forms For example you can develop Web Forms pages in any language that supports the NET Framework In addition ASPNET no longer needs to share the same file with your HTTP text (although it can continue to do so if you

ESRI White Paper 4

prefer) Unlike unmanaged ASP code that is always scripted and interpreted ASPNET pages are faster and easier to manage as they execute in native machine language and interact with the runtime like any managed application To summarize here are a few benefits to programming with ASPNET

Object Orientation and a large class library from which to inherit functionality Can use multiple programming languages VBNET C etc Code is always

compiled before it is run Web Forms and Web Controls present the programmer with an event driven

model very similar to the desktop environment Server side controls intelligently render html code appropriate to the target browser

Advanced crash-recovery and detection and isolation of rogue code damaging the system

Scalable architecture with extensive caching to reduce running lots of identical code for each website visitor

Debugging is much easier especially when the programming is done using an IDE like Visual StudioNet

The NET programming environment provides very good database and XML support

MSIL and the new assembly model makes deploying applications and versioning complexities an issue of the past

Provides tools to easily create webservices All the plumbing code required is effectively hidden

The diagram below shows the typical sequence of calls made during a request response cycle for a ASPNET web page Notice that the first request-response cycle is shown by steps 1 through 6 and subsequent calls are displayed as steps 7-10

ESRI White Paper 5

Because ASPNET uses compiled code instead of interpreted code subsequent requests will check to see if there has been any change to the code If not it will utilize the script engine cache to access the compiled version of the code

NET and ArcIMS In order to better understand how to build map services using ArcIMS and the NET environment this paper presents the concepts in a series of three examples The examples all written using NET compatible languages (VBNET and C) demonstrate web applications that display map images served up ESRIs ArcIMS product The examples chosen are such that they provide a good handle on the various aspects of designing web applications that server as clients to the ArcIMS Image Service The following are a brief description of the three examples

Example 1 An ASPNET application written in VBNET that utilizes COM Interop to access the functionality exposed by the ActiveX connector

Example 2 An ASPNET application written in VBNET that makes use of special classes (also developed in VBNET) to send and receive requests via the Servlet connector in ArcIMS This example also contains code that shows you how to capture page coordinates from a mouse click event on the image map control It also shows the

ESRI White Paper 6

necessary steps to convert the obtained page coordinates to map coordinates for subsequent use in zoom operations

Example 3 An ASPNET application written in C that makes use of special classes developed in C This example utilizes two approaches one using the Servlet connector and another using a C wrapper to the ActiveX connector to connect to the service using TCP

Example 1

This application is a very simple web application that demonstrates the use of an image control in a web form to display a map image served up by ArcIMS The button control reads State Names from a database and populates the DropDownList Selecting a State from the DropDownList highlights the state in the map

This example demonstrates the following

Basic web form and web controls Button Image and DropDownListcontrols Using the ActiveX connector in a NET web application using COM Interop

ESRI White Paper 7

Connecting to an access database to read a list of names (from a column) This list is then used to populate a drop down list box

Using the image control to view an image rendered by ArcIMS

ASPNET and Web Forms Programming Environment

Visual Basic NET Programming Language

Data Files

File Name Comment BPC 2002mdb Database file with a column containing state names World30stateslakescountry Shape files BPC_STATESaxl Axl file for the image service

WebForm Controls

Control Name Function ImageButton1 Control for displaying the image Button Populates the Dropdown Listbox with State Names read from the

database DropDownList1 Set AutoPostback property to TRUE

Steps to Create Application

Create a new Project Choose Visual Basic Project -gt ASPNET web application

Add Project References

ESRI White Paper 8

o Project Add References COM ArcIMS ActiveX Connector (Aims_ActiveXdll)

o Project Add References NET adodb ( adodbdll)

Add controls to the form and set the appropriate properties (NameCaption Size etc)

Right click on the WebForm1aspx file and choose Viewcode Type the code shown below Click on Build-gtSolution Press CTRL+F5 to start without debugging or F5 to Start (with debugging)

ESRI White Paper 9

Code from Web Form1aspxvb the codebehind page for the Web Form

Define and instantiate class variables Refer to the Section Accessing a COM Server from a NET Client for a discussion on using early and late binding mechanisms to instantiate COM objects

Private mapStates As aimsMap()

Private conArcIMS As aimsArcIMSConnector()

The Page_Load event sets up the connection and map parameters It also links the image URL (provided by ArcIMS) to the URL property of the Image control to display the map image

Private Sub Page_load(ByVal sender As SystemObject ByVal e As SystemEventArgs) Handles MyBaseLoad mapStates = New aimsMap() conArcIMS = New aimsArcIMSConnector() conArcIMSServerName = localhost conArcIMSServerPort = 5300 mapStatesInitMap(conArcIMS BPC_States) mapStatesWidth = 550 mapStatesHeight = 400 mapStatesRefresh()

ESRI White Paper 10

ImageButton1ImageUrl = mapStatesGetImageAsUrl

End Sub

The Button Click event makes a connection to the bpc2002mdb access database It then reads the data from the States column orders it alphabetically and then populates the DropDownList control with the ordered list of entries

Private Sub Button1_Click(ByVal sender As SystemObject ByVal e As SystemEventArgs) Handles Button1Click Dim conDB As OleDbOleDbConnection Dim cmdFetch As OleDbOleDbCommand Dim rdrStates As OleDbOleDbDataReader Dim sCon As String = Provider=MicrosoftJetOLEDB40Data Source=CArcIMSWebsiteBPC_Statesbpc2002mdb conDB = New OleDbOleDbConnection(sCon) conDBOpen() cmdFetch = New OleDbOleDbCommand(SELECT STATE_NAME FROM STATES ORDER BY STATE_NAME) cmdFetchConnection = conDB rdrStates = cmdFetchExecuteReader() While rdrStatesRead() DropDownList1ItemsAdd(New ListItem(rdrStatesGetString(0))) End While conDBClose()

End Sub

The DropDownList fires a SelectedIndexChanged event The code associated with this event uses the where expression with LayersItem()Filter to create an image with a special highlight applied to the selected state The URL of the image is linked to the image buttons URL to display the new image

Private Sub DropDownList1_SelectedIndexChanged(ByVal sender As Object ByVal e As SystemEventArgs) Handles DropDownList1SelectedIndexChanged Dim sWhere As String = STATE_NAME = amp DropDownList1SelectedItemText amp mapStatesLayersItem(4)FilterWhereExpression = sWhere mapStatesRefresh() ImageButton1ImageUrl = mapStatesGetImageAsUrl End Sub

The Page_Unload event is used for clean up code Here it is used to free memory by setting the map and connection object to Nothing

ESRI White Paper 11

Private Sub Page_unload(ByVal sender As Object ByVal e As SystemEventArgs) Handles MyBaseUnload mapStates = Nothing conArcIMS = Nothing

End Sub

Example 2

General Description

This web application demonstrates the use of two image controls in a web form to display a map image and its associated legend both images being served up by ArcIMS The web application also has controls for Zoomin Zoomout and pan

Programming Environment ASPNET and Web Forms

Programming Language Visual Basic NET

WebForm Controls

ESRI White Paper 12

Control Name Function ImgMap Control for displaying the image ImgLegend Control for displaying the legend image lstNavControls Radiobutton list controls

Data Files

Can use any datafile capable of generating an image service Replace the sf parameter in the page_load event with the appropriate image service name

Class Libraries ( Logic_classes assembly)

File Name Class Information Functionality MapVB The Cmap class has a

MustInherit Keyword and is inherited by Cviewer The MustInherit keyword specifies that a class cannot be instantiated and can be used only as a base class

PointVB Used by Cmap Crect Represents a geometric point (xy pair ) RectVB Used by Cmap Cviewer and

Webform3 in testformaspx

ViewerVB Used in Webform3 in testformaspx

Abstracts the requesting of a simple map from ArcIMS No additional entities will be added to the map (ie graphics buffer etc) The map is requested with all the default parameters with which it is served excepting extent and background color

Steps to Create Application

ESRI White Paper 13

The following section details the code found in the code behind page of the Testformaspx page

Statement to import logic_classes Makes all the functionality available in the logic_classes project available to the code in the web form

Imports logic_classes

Define a class level variable in the aspx file

Private m_objViewerMap As cViewer

Code for the page load event Uses IsPostback to determine if the extents need to be read afresh or from a previous valued stored in the session object Also instantiates the Cviewer class object You need to make sure that the extents shown in the code are appropriately changed to work with your selected image service

Private Sub Page_Load(ByVal sender As SystemObject ByVal e As SystemEventArgs) Handles MyBaseLoad

ESRI White Paper 14

Put user code to initialize the page here Dim rctExtent As cRect If Not IsPostBack Then enter appropriate extents rctExtent = New cRect(-1225173 377199 -122363678 3780374) Else rctExtent = New cRect(Session(MinX) Session(MinY) Session(MaxX) Session(MaxY)) End If m_objViewerMap = New cViewer(httplocalhostservletcomesriesrimapEsrimap _ sf _ rctExtent _ imgMapWidthValue _ imgMapHeightValue _ 000) add test markers

End Sub

Page_Prerender event code Links the output image to the Picture controls Also since HTTP is a stateless protocol the current map extents are stored in session variables for follow-up requests from the same user

Private Sub Page_PreRender(ByVal sender As Object ByVal e As SystemEventArgs) Handles MyBasePreRender imgMapImageUrl = m_objViewerMapMap() imgLegendImageUrl = m_objViewerMapLegend() Session(MinX) = m_objViewerMapExtentXMin Session(MinY) = m_objViewerMapExtentYMin Session(MaxX) = m_objViewerMapExtentXMax Session(MaxY) = m_objViewerMapExtentYMax

End Sub

Imgmap_click event is raised when the user clicks on the map Code associated with this event converts the image click coordinate to a map coordinate Then

ESRI White Paper 15

based on the radio button selection ( Zoomin Zoomout or pan) the code calls the appropriate method using the instantiated Cviewer object

Private Sub imgMap_Click(ByVal sender As Object ByVal e As SystemWebUIImageClickEventArgs) Handles imgMapClick Convert the image click coordinate to a map coordinate based on the maps current extent Dim rctCurrentExtent As cRect = m_objViewerMapExtent Dim dblX As Double = rctCurrentExtentXMin + ((eX imgMapWidthValue) (rctCurrentExtentXMax - rctCurrentExtentXMin)) Dim dblY As Double = rctCurrentExtentYMin + (((imgMapHeightValue - eY) imgMapHeightValue) (rctCurrentExtentYMax - rctCurrentExtentYMin)) If Trim(UCase(lstNavControlsSelectedItemText)) ltgt IDENTIFY Then m_objViewerMapCenterAt(dblX dblY) Select Case UCase(lstNavControlsSelectedItemText) Case ZOOM IN Center the map m_objViewerMapZoom(-1) Case ZOOM OUT m_objViewerMapZoom(1) Case PAN do nothing Case Else ErrRaise(vbObjectError + 512 imgMap_Click Invalid command) End Select Else identify End If End Sub

ESRI White Paper 16

End Class

NOTE =gt Once you have the relevant files imported into Visual Studio make sure that you configure the virtual directory as an application before you run the example

If the virtual directory is not configured as an Application you will get an error message that reads This error can be caused by a virtual directory not being configured as an application in IIS To configure a Virtual directory is simple Use the Internet Service Manager to perform the following steps

Find the folder in the virtual directory Right click and choose properties Click Create Accept all the settings and Click OK

Example 3

General Description

The program uses the catalog service (using the ltGETCLIENTSERVICESgt request) to query and list a collection of services running on the server A Radiobutton list control is used to list all the service names running on the server On selecting an appropriate image service the map image is displayed on the web form using an image control This program demonstrates two different ways to connect to the datasource Connection could be achieved using the http protocol or the TCP protocol The TCP method utilizes the TCP capability built into the ActiveX Connector Since ASPNET is a multithreaded and the ActiveX connector being Single Threaded (STA) a wrapper class with additional functionality to manage memory is used to access the methods in the ActiveX connector

ESRI White Paper 17

Programming Environment ASPNET and Web Forms

C NET Programming Language

WebForm Controls

Control Name Function ImgMap Control for displaying the image RbServices Radiobutton list controls Txtinfo Displays the name of the selected image service

Data Files

Requires a collection of image services running on an ArcIMS server The program uses the ltGETCLIENTSERVICESgt request tag to query the catalog service to list all the services running on the specified server

Class Libraries

File Name Class Information Functionality Connectioncs Abstract base class Provides abstract method

templates for the HTTPConnection and

ESRI White Paper 18

TCPConnection classes HTTPConnectioncs Inherits from Connection class Provides functionality for

sending request to service postinggetting URL content etc

TCPConnectioncs Inherits from Connection class and SystemIDisposable

Utlizes the AICLib assembly to access connection functionality built into the ActiveX connector

Datasourcecs Provides method for accessing path port host and other information

Enumerationscs Provides enumerations for AccessType and LoadType

Envelopecs Provides methods for getting and setting xy coordinates of the envelope

ImageReturnObjectcs Provides methods for settinggetting image URL image envelope and image scale

Mapcs Calls send request to service with connection and service information Parses response to obtain image URL

Servicecs Servicescs Inherits from

SystemCollectionsHashtable Composes the clientservices request and parses the response Creates a hashtable association of individual service name with its associated service object

XML helper class that provides relevant XML parsing functionality by acting as a wrapper class around NETs xml Text IO and other NET classes

XMLRequestscs Builds ArcXML strings for requests

XMLHelpercs

Steps to Create Application

ESRI White Paper 19

The NET solution contains 2 projects ArcIMS and ArcIMSSample The ArcIMS project

o References the InteropAICLib o Contains NET ArcIMS class libraries that can be used to connect and to

work with image services The ArcIMSSample project

o References the ArcIMS project o Contains the web form (webform1aspx) and the corresponding

webform1aspxcs code-behind page that connects the web page controls to relevant functionality using an event driven web forms model

Points to Note

In webform1aspxcs code session variables are used to maintain state of serialized objects In order for this to be possible notice that the relevant classes have been marked as serializable

ESRI White Paper 20

Choose the appropriate connection type based on HTTP or TCP connection For HTTP choose m_dsConnectType = ConnectionTypeInterNet and for For TCP select m_dsConnectType = ConnectionTypeIntraNet as shown in the code below

private ArcIMSDataSource getDataSource() m_ds = Session[datasource] as ArcIMSDataSource if ( m_ds == null ) m_ds = new ArcIMSDataSource() m_dsHost = localhost m_dsScheme = http m_dsPort = 80 m_dsAppServerPort = 5300 m_dsPath = servletcomesriesrimapEsrimap choose (comment uncomment) one of the following two statements to decide between TCP or HTTP type connection m_dsConnectType = ConnectionTypeIntraNet m_dsConnectType = ConnectionTypeInterNet SessionAdd(datasource m_ds) return m_ds

Accessing a COM Server from a NET Client With the introduction of the NET Framework and ASPNET COM at its basic level has not really changed Nevertheless there are a couple of issues to be aware of when making calls to a COM object from a NET managed code environment The ASPNET threading model is the Multiple Threaded Apartment (MTA) This will not interact reliably with STA components (the ActiveX connector provided with the ArcIMS setup was built as an STA component) To emphasize this issue heres a direct quote from the MSDN pages at Microsoft The ASPNET threading model is the Multiple Threaded Apartment (MTA) What this means is that components that you are using that were created for the Single Threaded Apartment (STA) will no longer perform or function reliably without taking some extra precautions in ASPNET This includes but is not limited to all COM components that have been created using Visual Basic 60 and earlier versions

To understand the issues better let us take a look at how NET deals with COM related issues The Common Language Runtime exposes COM objects through a proxy called the runtime callable wrapper (RCW) The RCWs primary function is to marshal calls between a NET client and COM object The RCW object is nothing but an object instantiated at runtime from class code contained in the Interop assembly

ESRI White Paper 21

Calling between managed and unmanaged components incurs a marshaling cost which can impede the performance of your pages When a managed client and unmanaged server are in the same apartment the Interop marshalling service handles all data marshalling However when client and server are initialized in different apartments COM marshalling is also required Therefore interoperability with COM from a NET client should take into consideration the threading model used

Figure Cross-apartment call between a NET client and COM object

As mentioned earlier ASPNET follows an MTA model by default You could use the default model to communicate with an STA COM component if there is not much of an overhead due to the cross-apartment marshalling Usually this is noticeable only when there are many calls across the boundary Another option would be to use the PageAspCompatMode property of the ASPNET client The ASPCompat=true attribute enables an STA thread pool to address performance with existing Visual Basic components on a per-page basis The runtime throws an exception if the compatibility tag is omitted and an STA component is referenced on the page If you convert the STA component to an assembly using Type Library Importer (a utility included with the NET SDK) the runtime does not detect that the component uses the STA model and does not throw an exception but your application can suffer from poor performance and possible deadlocks STA components cannot be used from NET Framework code modules (compiled NET assemblies) they can be used only from ASPNET pages

If you plan to use the ASPCOMPAT = TRUE page level directive for Example 1 remember to instantiate the COM object within the page_load event rather than constructing COM components during page construction time For example look at code examples A and B

Example A Example B ltPage Language = VB ASPCOMPAT = truegt

ltscript runat = servergt

private mapStates as new aimsMap()

private sub_load ()

ltPage Language = VB ASPCOMPAT = truegt

ltscript runat = servergt

private mapStates as aimsMap()

private sub_load ()

ESRI White Paper 22

end sub

mapStates = new aimsMap()

end sub

In example A the STA component would be instantiated at page construction time which is created from a thread that is not the STA thread that will run the page This will involve marshalling between MTA and STA threads during the construction of the page Example B shows the preferred mechanism to delay the process until later when the code executes under a STA thread It is best to construct any COM component and external resources when needed or in the Page_Load method

Also to create the object you can use either the New keyword or the CreateObject method The CreateObject method is typically used when you dont know the Program ID (ProgID) of the object you are going to create until run time (late binding) New is the recommended method for instantiating objects if you have access to the objects type library It is preferable to adopt the early binding model

Every scenario yields different performance characteristics so it is important to test adequately before deciding whether interoperability is the right choice for your application However in nearly all scenarios rewriting your COM components in managed code provides performance benefits

Summary The examples shown above provide adequate information to leverage the NET programming environment to build effective ArcIMS client applications The debugging features of a program like Visual StudioNET provide a variety of tools (break points trace etc) making the entire development experience considerably pain-free Use the debugger to understand the sequence in which calls are made One early exercise would be to look at the calling sequence of the various page related events such as page_init page_load and page_prerender Since the Web Forms code is compiled you should experience much better performance than with ASP pages that used code written in scripting languages like Javascript and VbScript

The powerful programming environment also means that you can now concentrate more on the logic of building large web applications as opposed to building simple page based asp applications Also look at the various caching mechanisms provided by ASPNET as these can be used to improve overall performance As always there are costs associated with most programming choices and this is all the more true in a web-programming environment For example consider the costs associated with using a web control as opposed to a HTML based control Use plain HTML controls instead of adopting web controls for simple items like label

ESRI White Paper 23

If you choose to use the ActiveX connector from within the NET environment make sure that you clearly understand the essentials of COM Interop and the various costs associated with marshalling The solutions outlined in this paper utilize existing ArcIMS services and should work with all versions of ArcIMS

Although all the development can be done without the use of an Integrated Development environment (IDE) like Visual StudioNET using such an environment provides convenient WYSIWYG features that can help in building and debugging the application If you do not have Visual StudioNET there are free IDEs available today that can also be used For example ASPNET Web Matrix is a community-supported easy-to-use WYSIWYG application development tool for ASPNET It can be installed via a quick 12 MB download from httpwwwaspnetwebmatrixdefaultaspx

ESRI White Paper 24

  • ArcIMS ndash An Introduction
  • What is NET
    • The NET Framework
      • The Common Language Runtime (CLR)
      • Managed Unmanaged and Unsafe code ndash Understandin
      • NET Framework Class Libraries
        • ASPNET and Web Forms
          • NET and ArcIMS
            • Example 1
            • Example 2
            • Example 3
              • Accessing a COM Server from a NET Client
              • Summary
Page 4: Consuming ArcIMS Image Services using .NET Client Web ... · Consuming ArcIMS Image Services using .NET Client Web Applications An ESRI White Paper Ł October 2002 ... The .NET framework

Consuming ArcIMS Image Services using NET Client Web Applications

ArcIMS An Introduction ArcIMS provides the foundation for distributing high-end geographic information systems (GIS) and mapping services via the Internet ArcIMS software enables users to integrate local data sources with Internet data sources for display query and analysis in an easy-to-use Web browser The ArcIMS Architecture consists of different types of connectors that allow you to customize client application to access specific services of the ArcIMS Server and display the results The connectors provided with ArcIMS include the ActiveX connector Servlet connector Cold Fusion connector and the Java connector Depending on the choice of these connectors you can write customized web applications using ASP DHTMLArcXML Cold Fusion or JSP The ActiveX and the Java connector expose a rich object model that makes development of client side applications relatively simple It is also possible to use the Servlet connector to send requests formatted as asArcXML strings to the ArcIMS spatial computing engine (Spatial server) and receives the response in the same ArcXML format This response can then be parsed to display the mapresult The ActiveX connector and the Servlet connector model can both be utilized within a NET programming environment to provide feature rich web applications The ArcIMS architecture also utilizes components such as the Application Server for load balancing making the entire setup highly scalable Please refer to the paper ArcIMS 4 Architecture and Functionality for a detailed review of ArcIMS architecture

Fundamentally NET can be looked at as a rich technology to produce Web Applications In some sense the term NET has now become synonymous with services more typically Web Services the ability to use Collaborative Web Applications that span

ESRI White Paper 1

heterogeneous environments Simply put web services allow you to share information or integrate with legacy systems without having to write specialized interconnection applications In this paper we will restrict the discussions and examples to using ASPNET as a unified Web development platform for building sophisticated web applications that will interact with ArcIMS Image Services

To understand and appreciate the additional benefits that NET technology brings to the table you should have some experience programming the ArcIMS client applications using the ActiveX or the Servlet connector model Also a good understanding of ArcXML syntax is essential to effectively use the Servlet connector model

Let us start by looking at what NET technology really is and get a firm handle on some of the terminologies used

What is NET NET is a new computing platform that simplifies application development in the highly distributed environment of the Internet The NET platform is built on top of the operating system NET has been influenced by other technological advances such as XML Java and COM The NET infrastructure comprises the NET framework Microsoft Visual StudioNET the NET Enterprise Servers and Microsoft WindowsNet In short the NET infrastructure refers to all the technologies that make up the environment for creating and running robust scalable and distributed applications

The following paragraphs provide a brief overview of some of the technologies and terminologies associated with NET To get more detailed information on NET there are a large number of books and information freely available on the internet that provide detailed descriptions of the technology This paper focuses on getting a broad perspective and some detailed knowledge of specific areas of the NET framework that can assist in leveraging this technology within the ArcIMS Internet Mapping Environment

The NET Framework

The NET framework is the part of the infrastructure that aids us in creating applications In simple terms the NET Framework can be discussed as containing 2 parts the CLR or the Common Language Runtime and the NET Framework Class libraries

The Common Language Runtime (CLR)

The CLR is the most important part of the NET architecture and computing paradigm It is the run-time environment in which applications written in different languages can all exist and play together providing cross-language interoperability

The mechanism for cross language interoperability is provided via the concept of Common Language Specification (CLS) a common set of rules A compiler that adheres

ESRI White Paper 2

to the rules can take code written in a specific language and port it to MSIL a Microsoft Intermediate Language Since MSIL code cannot be executed directly the CLR compiles the MSIL by using a Just-in-time (JIT) compiler into native CPU instructions as it processes the MSIL

One term that is mentioned a lot in conjunction with NET is managed code This is in fact made possible by the CLR Managed code is just code that is run under the auspices of the CLR or in other words code managed by the CLR One of the most important services provided by the CLR as part of the managed code paradigm is the concept of garbage collection NET uses automatic garbage collection to reclaim memory When memory allocated on the heap becomes orphaned or passes out of scope it is placed on a list of memory locations to be freed Periodically the system runs a garbage collection thread that returns the memory to the heap

While the runtime is designed for the software of the future it also supports legacy technology Interoperability between managed and unmanaged code enables developers to continue to use necessary COM components and DLLs

Managed Unmanaged and Unsafe code Understanding the Difference

Managed code is that code which executes under the supervision of the CLR This was dealt with in the section above The user has no control over how CLR achieves memory management type verification garbage collection and many other activities Uunmanaged code is that code which executes outside the context of the CLR The best example of this is your traditional Win32 DLLs like KERNEL32DLL USER32DLL and the COM components installed on our system How they allocate memory for their usage how memory is released how (if any) type verification takes places are some of the tasks that are undertaken by them on their own Unsafe code is a kind of cross between the managed and unmanaged codes It executes under the supervision of the CLR just like the managed code but lets you address the memory directly through the use of pointers as is done in unmanaged code A typical example would be a NET application that uses the functionality in a legacy Win32 DLL whose exported functions require the use of pointers Unless you are a NET aficionado understanding unsafe code and its implications may not be important to you But understanding the differences between Managed and Unmanaged code should provide you enough information to deal effectively with interoperability issues that needs to be dealt with while working with the ActiveX connector

ESRI White Paper 3

NET Framework Class Libraries

The NET Framework class library is a collection of reusable types that tightly integrate with the common language runtime The class library is object oriented providing types from which your own managed code can derive functionality

The NET Framework types enable you to accomplish a range of common programming tasks including tasks such as string management data collection database connectivity and file access In addition to these common tasks the class library includes types that support a variety of specialized development scenarios This paper includes examples of class libraries created by ESRI that provide rich functionality for developers to inherit in their web applications

Also the examples shown in this paper make use of ASPNET and web forms technologies As you create applications in ASPNET you will find it convenient to use many of the classes provided as part of the web forms class library

As you become familiar with the classes in the NET framework you may want to create wrapper classes that provide functionality for XML parsing internet intranet connections that inherit from base classes in the NET framework By creating your own classes you can provide reusable componentized code for building other ArcIMS client applications that require similar functionality

NET programs are deployed as assemblies An assembly is one or more EXEs or DLLs with associated metadata information The metadata about the entire assembly is stored in the assemblys manifest The manifest contains for example a list of assemblies upon which the current assembly is dependant The concept of assemblies how they can be deployed privately or publicly how they can be versioned etc is quite complex and are not discussed in this paper As always the internet serves as good source for information regarding these topics

ASPNET and Web Forms

The various web applications shown in this paper were all built using ASPNET ASPNET is the hosting environment that enables developers to use the NET Framework to target Web-based applications However ASPNET is more than just a runtime host it is a complete architecture for developing Web sites and Internet-distributed objects using managed code Both Web Forms and XML Web services use IIS and ASPNET as the publishing mechanism for applications and both have a collection of supporting classes in the NET Framework If you have used earlier versions of ASP technology it is easy to note the improvements provided by ASPNET and Web Forms For example you can develop Web Forms pages in any language that supports the NET Framework In addition ASPNET no longer needs to share the same file with your HTTP text (although it can continue to do so if you

ESRI White Paper 4

prefer) Unlike unmanaged ASP code that is always scripted and interpreted ASPNET pages are faster and easier to manage as they execute in native machine language and interact with the runtime like any managed application To summarize here are a few benefits to programming with ASPNET

Object Orientation and a large class library from which to inherit functionality Can use multiple programming languages VBNET C etc Code is always

compiled before it is run Web Forms and Web Controls present the programmer with an event driven

model very similar to the desktop environment Server side controls intelligently render html code appropriate to the target browser

Advanced crash-recovery and detection and isolation of rogue code damaging the system

Scalable architecture with extensive caching to reduce running lots of identical code for each website visitor

Debugging is much easier especially when the programming is done using an IDE like Visual StudioNet

The NET programming environment provides very good database and XML support

MSIL and the new assembly model makes deploying applications and versioning complexities an issue of the past

Provides tools to easily create webservices All the plumbing code required is effectively hidden

The diagram below shows the typical sequence of calls made during a request response cycle for a ASPNET web page Notice that the first request-response cycle is shown by steps 1 through 6 and subsequent calls are displayed as steps 7-10

ESRI White Paper 5

Because ASPNET uses compiled code instead of interpreted code subsequent requests will check to see if there has been any change to the code If not it will utilize the script engine cache to access the compiled version of the code

NET and ArcIMS In order to better understand how to build map services using ArcIMS and the NET environment this paper presents the concepts in a series of three examples The examples all written using NET compatible languages (VBNET and C) demonstrate web applications that display map images served up ESRIs ArcIMS product The examples chosen are such that they provide a good handle on the various aspects of designing web applications that server as clients to the ArcIMS Image Service The following are a brief description of the three examples

Example 1 An ASPNET application written in VBNET that utilizes COM Interop to access the functionality exposed by the ActiveX connector

Example 2 An ASPNET application written in VBNET that makes use of special classes (also developed in VBNET) to send and receive requests via the Servlet connector in ArcIMS This example also contains code that shows you how to capture page coordinates from a mouse click event on the image map control It also shows the

ESRI White Paper 6

necessary steps to convert the obtained page coordinates to map coordinates for subsequent use in zoom operations

Example 3 An ASPNET application written in C that makes use of special classes developed in C This example utilizes two approaches one using the Servlet connector and another using a C wrapper to the ActiveX connector to connect to the service using TCP

Example 1

This application is a very simple web application that demonstrates the use of an image control in a web form to display a map image served up by ArcIMS The button control reads State Names from a database and populates the DropDownList Selecting a State from the DropDownList highlights the state in the map

This example demonstrates the following

Basic web form and web controls Button Image and DropDownListcontrols Using the ActiveX connector in a NET web application using COM Interop

ESRI White Paper 7

Connecting to an access database to read a list of names (from a column) This list is then used to populate a drop down list box

Using the image control to view an image rendered by ArcIMS

ASPNET and Web Forms Programming Environment

Visual Basic NET Programming Language

Data Files

File Name Comment BPC 2002mdb Database file with a column containing state names World30stateslakescountry Shape files BPC_STATESaxl Axl file for the image service

WebForm Controls

Control Name Function ImageButton1 Control for displaying the image Button Populates the Dropdown Listbox with State Names read from the

database DropDownList1 Set AutoPostback property to TRUE

Steps to Create Application

Create a new Project Choose Visual Basic Project -gt ASPNET web application

Add Project References

ESRI White Paper 8

o Project Add References COM ArcIMS ActiveX Connector (Aims_ActiveXdll)

o Project Add References NET adodb ( adodbdll)

Add controls to the form and set the appropriate properties (NameCaption Size etc)

Right click on the WebForm1aspx file and choose Viewcode Type the code shown below Click on Build-gtSolution Press CTRL+F5 to start without debugging or F5 to Start (with debugging)

ESRI White Paper 9

Code from Web Form1aspxvb the codebehind page for the Web Form

Define and instantiate class variables Refer to the Section Accessing a COM Server from a NET Client for a discussion on using early and late binding mechanisms to instantiate COM objects

Private mapStates As aimsMap()

Private conArcIMS As aimsArcIMSConnector()

The Page_Load event sets up the connection and map parameters It also links the image URL (provided by ArcIMS) to the URL property of the Image control to display the map image

Private Sub Page_load(ByVal sender As SystemObject ByVal e As SystemEventArgs) Handles MyBaseLoad mapStates = New aimsMap() conArcIMS = New aimsArcIMSConnector() conArcIMSServerName = localhost conArcIMSServerPort = 5300 mapStatesInitMap(conArcIMS BPC_States) mapStatesWidth = 550 mapStatesHeight = 400 mapStatesRefresh()

ESRI White Paper 10

ImageButton1ImageUrl = mapStatesGetImageAsUrl

End Sub

The Button Click event makes a connection to the bpc2002mdb access database It then reads the data from the States column orders it alphabetically and then populates the DropDownList control with the ordered list of entries

Private Sub Button1_Click(ByVal sender As SystemObject ByVal e As SystemEventArgs) Handles Button1Click Dim conDB As OleDbOleDbConnection Dim cmdFetch As OleDbOleDbCommand Dim rdrStates As OleDbOleDbDataReader Dim sCon As String = Provider=MicrosoftJetOLEDB40Data Source=CArcIMSWebsiteBPC_Statesbpc2002mdb conDB = New OleDbOleDbConnection(sCon) conDBOpen() cmdFetch = New OleDbOleDbCommand(SELECT STATE_NAME FROM STATES ORDER BY STATE_NAME) cmdFetchConnection = conDB rdrStates = cmdFetchExecuteReader() While rdrStatesRead() DropDownList1ItemsAdd(New ListItem(rdrStatesGetString(0))) End While conDBClose()

End Sub

The DropDownList fires a SelectedIndexChanged event The code associated with this event uses the where expression with LayersItem()Filter to create an image with a special highlight applied to the selected state The URL of the image is linked to the image buttons URL to display the new image

Private Sub DropDownList1_SelectedIndexChanged(ByVal sender As Object ByVal e As SystemEventArgs) Handles DropDownList1SelectedIndexChanged Dim sWhere As String = STATE_NAME = amp DropDownList1SelectedItemText amp mapStatesLayersItem(4)FilterWhereExpression = sWhere mapStatesRefresh() ImageButton1ImageUrl = mapStatesGetImageAsUrl End Sub

The Page_Unload event is used for clean up code Here it is used to free memory by setting the map and connection object to Nothing

ESRI White Paper 11

Private Sub Page_unload(ByVal sender As Object ByVal e As SystemEventArgs) Handles MyBaseUnload mapStates = Nothing conArcIMS = Nothing

End Sub

Example 2

General Description

This web application demonstrates the use of two image controls in a web form to display a map image and its associated legend both images being served up by ArcIMS The web application also has controls for Zoomin Zoomout and pan

Programming Environment ASPNET and Web Forms

Programming Language Visual Basic NET

WebForm Controls

ESRI White Paper 12

Control Name Function ImgMap Control for displaying the image ImgLegend Control for displaying the legend image lstNavControls Radiobutton list controls

Data Files

Can use any datafile capable of generating an image service Replace the sf parameter in the page_load event with the appropriate image service name

Class Libraries ( Logic_classes assembly)

File Name Class Information Functionality MapVB The Cmap class has a

MustInherit Keyword and is inherited by Cviewer The MustInherit keyword specifies that a class cannot be instantiated and can be used only as a base class

PointVB Used by Cmap Crect Represents a geometric point (xy pair ) RectVB Used by Cmap Cviewer and

Webform3 in testformaspx

ViewerVB Used in Webform3 in testformaspx

Abstracts the requesting of a simple map from ArcIMS No additional entities will be added to the map (ie graphics buffer etc) The map is requested with all the default parameters with which it is served excepting extent and background color

Steps to Create Application

ESRI White Paper 13

The following section details the code found in the code behind page of the Testformaspx page

Statement to import logic_classes Makes all the functionality available in the logic_classes project available to the code in the web form

Imports logic_classes

Define a class level variable in the aspx file

Private m_objViewerMap As cViewer

Code for the page load event Uses IsPostback to determine if the extents need to be read afresh or from a previous valued stored in the session object Also instantiates the Cviewer class object You need to make sure that the extents shown in the code are appropriately changed to work with your selected image service

Private Sub Page_Load(ByVal sender As SystemObject ByVal e As SystemEventArgs) Handles MyBaseLoad

ESRI White Paper 14

Put user code to initialize the page here Dim rctExtent As cRect If Not IsPostBack Then enter appropriate extents rctExtent = New cRect(-1225173 377199 -122363678 3780374) Else rctExtent = New cRect(Session(MinX) Session(MinY) Session(MaxX) Session(MaxY)) End If m_objViewerMap = New cViewer(httplocalhostservletcomesriesrimapEsrimap _ sf _ rctExtent _ imgMapWidthValue _ imgMapHeightValue _ 000) add test markers

End Sub

Page_Prerender event code Links the output image to the Picture controls Also since HTTP is a stateless protocol the current map extents are stored in session variables for follow-up requests from the same user

Private Sub Page_PreRender(ByVal sender As Object ByVal e As SystemEventArgs) Handles MyBasePreRender imgMapImageUrl = m_objViewerMapMap() imgLegendImageUrl = m_objViewerMapLegend() Session(MinX) = m_objViewerMapExtentXMin Session(MinY) = m_objViewerMapExtentYMin Session(MaxX) = m_objViewerMapExtentXMax Session(MaxY) = m_objViewerMapExtentYMax

End Sub

Imgmap_click event is raised when the user clicks on the map Code associated with this event converts the image click coordinate to a map coordinate Then

ESRI White Paper 15

based on the radio button selection ( Zoomin Zoomout or pan) the code calls the appropriate method using the instantiated Cviewer object

Private Sub imgMap_Click(ByVal sender As Object ByVal e As SystemWebUIImageClickEventArgs) Handles imgMapClick Convert the image click coordinate to a map coordinate based on the maps current extent Dim rctCurrentExtent As cRect = m_objViewerMapExtent Dim dblX As Double = rctCurrentExtentXMin + ((eX imgMapWidthValue) (rctCurrentExtentXMax - rctCurrentExtentXMin)) Dim dblY As Double = rctCurrentExtentYMin + (((imgMapHeightValue - eY) imgMapHeightValue) (rctCurrentExtentYMax - rctCurrentExtentYMin)) If Trim(UCase(lstNavControlsSelectedItemText)) ltgt IDENTIFY Then m_objViewerMapCenterAt(dblX dblY) Select Case UCase(lstNavControlsSelectedItemText) Case ZOOM IN Center the map m_objViewerMapZoom(-1) Case ZOOM OUT m_objViewerMapZoom(1) Case PAN do nothing Case Else ErrRaise(vbObjectError + 512 imgMap_Click Invalid command) End Select Else identify End If End Sub

ESRI White Paper 16

End Class

NOTE =gt Once you have the relevant files imported into Visual Studio make sure that you configure the virtual directory as an application before you run the example

If the virtual directory is not configured as an Application you will get an error message that reads This error can be caused by a virtual directory not being configured as an application in IIS To configure a Virtual directory is simple Use the Internet Service Manager to perform the following steps

Find the folder in the virtual directory Right click and choose properties Click Create Accept all the settings and Click OK

Example 3

General Description

The program uses the catalog service (using the ltGETCLIENTSERVICESgt request) to query and list a collection of services running on the server A Radiobutton list control is used to list all the service names running on the server On selecting an appropriate image service the map image is displayed on the web form using an image control This program demonstrates two different ways to connect to the datasource Connection could be achieved using the http protocol or the TCP protocol The TCP method utilizes the TCP capability built into the ActiveX Connector Since ASPNET is a multithreaded and the ActiveX connector being Single Threaded (STA) a wrapper class with additional functionality to manage memory is used to access the methods in the ActiveX connector

ESRI White Paper 17

Programming Environment ASPNET and Web Forms

C NET Programming Language

WebForm Controls

Control Name Function ImgMap Control for displaying the image RbServices Radiobutton list controls Txtinfo Displays the name of the selected image service

Data Files

Requires a collection of image services running on an ArcIMS server The program uses the ltGETCLIENTSERVICESgt request tag to query the catalog service to list all the services running on the specified server

Class Libraries

File Name Class Information Functionality Connectioncs Abstract base class Provides abstract method

templates for the HTTPConnection and

ESRI White Paper 18

TCPConnection classes HTTPConnectioncs Inherits from Connection class Provides functionality for

sending request to service postinggetting URL content etc

TCPConnectioncs Inherits from Connection class and SystemIDisposable

Utlizes the AICLib assembly to access connection functionality built into the ActiveX connector

Datasourcecs Provides method for accessing path port host and other information

Enumerationscs Provides enumerations for AccessType and LoadType

Envelopecs Provides methods for getting and setting xy coordinates of the envelope

ImageReturnObjectcs Provides methods for settinggetting image URL image envelope and image scale

Mapcs Calls send request to service with connection and service information Parses response to obtain image URL

Servicecs Servicescs Inherits from

SystemCollectionsHashtable Composes the clientservices request and parses the response Creates a hashtable association of individual service name with its associated service object

XML helper class that provides relevant XML parsing functionality by acting as a wrapper class around NETs xml Text IO and other NET classes

XMLRequestscs Builds ArcXML strings for requests

XMLHelpercs

Steps to Create Application

ESRI White Paper 19

The NET solution contains 2 projects ArcIMS and ArcIMSSample The ArcIMS project

o References the InteropAICLib o Contains NET ArcIMS class libraries that can be used to connect and to

work with image services The ArcIMSSample project

o References the ArcIMS project o Contains the web form (webform1aspx) and the corresponding

webform1aspxcs code-behind page that connects the web page controls to relevant functionality using an event driven web forms model

Points to Note

In webform1aspxcs code session variables are used to maintain state of serialized objects In order for this to be possible notice that the relevant classes have been marked as serializable

ESRI White Paper 20

Choose the appropriate connection type based on HTTP or TCP connection For HTTP choose m_dsConnectType = ConnectionTypeInterNet and for For TCP select m_dsConnectType = ConnectionTypeIntraNet as shown in the code below

private ArcIMSDataSource getDataSource() m_ds = Session[datasource] as ArcIMSDataSource if ( m_ds == null ) m_ds = new ArcIMSDataSource() m_dsHost = localhost m_dsScheme = http m_dsPort = 80 m_dsAppServerPort = 5300 m_dsPath = servletcomesriesrimapEsrimap choose (comment uncomment) one of the following two statements to decide between TCP or HTTP type connection m_dsConnectType = ConnectionTypeIntraNet m_dsConnectType = ConnectionTypeInterNet SessionAdd(datasource m_ds) return m_ds

Accessing a COM Server from a NET Client With the introduction of the NET Framework and ASPNET COM at its basic level has not really changed Nevertheless there are a couple of issues to be aware of when making calls to a COM object from a NET managed code environment The ASPNET threading model is the Multiple Threaded Apartment (MTA) This will not interact reliably with STA components (the ActiveX connector provided with the ArcIMS setup was built as an STA component) To emphasize this issue heres a direct quote from the MSDN pages at Microsoft The ASPNET threading model is the Multiple Threaded Apartment (MTA) What this means is that components that you are using that were created for the Single Threaded Apartment (STA) will no longer perform or function reliably without taking some extra precautions in ASPNET This includes but is not limited to all COM components that have been created using Visual Basic 60 and earlier versions

To understand the issues better let us take a look at how NET deals with COM related issues The Common Language Runtime exposes COM objects through a proxy called the runtime callable wrapper (RCW) The RCWs primary function is to marshal calls between a NET client and COM object The RCW object is nothing but an object instantiated at runtime from class code contained in the Interop assembly

ESRI White Paper 21

Calling between managed and unmanaged components incurs a marshaling cost which can impede the performance of your pages When a managed client and unmanaged server are in the same apartment the Interop marshalling service handles all data marshalling However when client and server are initialized in different apartments COM marshalling is also required Therefore interoperability with COM from a NET client should take into consideration the threading model used

Figure Cross-apartment call between a NET client and COM object

As mentioned earlier ASPNET follows an MTA model by default You could use the default model to communicate with an STA COM component if there is not much of an overhead due to the cross-apartment marshalling Usually this is noticeable only when there are many calls across the boundary Another option would be to use the PageAspCompatMode property of the ASPNET client The ASPCompat=true attribute enables an STA thread pool to address performance with existing Visual Basic components on a per-page basis The runtime throws an exception if the compatibility tag is omitted and an STA component is referenced on the page If you convert the STA component to an assembly using Type Library Importer (a utility included with the NET SDK) the runtime does not detect that the component uses the STA model and does not throw an exception but your application can suffer from poor performance and possible deadlocks STA components cannot be used from NET Framework code modules (compiled NET assemblies) they can be used only from ASPNET pages

If you plan to use the ASPCOMPAT = TRUE page level directive for Example 1 remember to instantiate the COM object within the page_load event rather than constructing COM components during page construction time For example look at code examples A and B

Example A Example B ltPage Language = VB ASPCOMPAT = truegt

ltscript runat = servergt

private mapStates as new aimsMap()

private sub_load ()

ltPage Language = VB ASPCOMPAT = truegt

ltscript runat = servergt

private mapStates as aimsMap()

private sub_load ()

ESRI White Paper 22

end sub

mapStates = new aimsMap()

end sub

In example A the STA component would be instantiated at page construction time which is created from a thread that is not the STA thread that will run the page This will involve marshalling between MTA and STA threads during the construction of the page Example B shows the preferred mechanism to delay the process until later when the code executes under a STA thread It is best to construct any COM component and external resources when needed or in the Page_Load method

Also to create the object you can use either the New keyword or the CreateObject method The CreateObject method is typically used when you dont know the Program ID (ProgID) of the object you are going to create until run time (late binding) New is the recommended method for instantiating objects if you have access to the objects type library It is preferable to adopt the early binding model

Every scenario yields different performance characteristics so it is important to test adequately before deciding whether interoperability is the right choice for your application However in nearly all scenarios rewriting your COM components in managed code provides performance benefits

Summary The examples shown above provide adequate information to leverage the NET programming environment to build effective ArcIMS client applications The debugging features of a program like Visual StudioNET provide a variety of tools (break points trace etc) making the entire development experience considerably pain-free Use the debugger to understand the sequence in which calls are made One early exercise would be to look at the calling sequence of the various page related events such as page_init page_load and page_prerender Since the Web Forms code is compiled you should experience much better performance than with ASP pages that used code written in scripting languages like Javascript and VbScript

The powerful programming environment also means that you can now concentrate more on the logic of building large web applications as opposed to building simple page based asp applications Also look at the various caching mechanisms provided by ASPNET as these can be used to improve overall performance As always there are costs associated with most programming choices and this is all the more true in a web-programming environment For example consider the costs associated with using a web control as opposed to a HTML based control Use plain HTML controls instead of adopting web controls for simple items like label

ESRI White Paper 23

If you choose to use the ActiveX connector from within the NET environment make sure that you clearly understand the essentials of COM Interop and the various costs associated with marshalling The solutions outlined in this paper utilize existing ArcIMS services and should work with all versions of ArcIMS

Although all the development can be done without the use of an Integrated Development environment (IDE) like Visual StudioNET using such an environment provides convenient WYSIWYG features that can help in building and debugging the application If you do not have Visual StudioNET there are free IDEs available today that can also be used For example ASPNET Web Matrix is a community-supported easy-to-use WYSIWYG application development tool for ASPNET It can be installed via a quick 12 MB download from httpwwwaspnetwebmatrixdefaultaspx

ESRI White Paper 24

  • ArcIMS ndash An Introduction
  • What is NET
    • The NET Framework
      • The Common Language Runtime (CLR)
      • Managed Unmanaged and Unsafe code ndash Understandin
      • NET Framework Class Libraries
        • ASPNET and Web Forms
          • NET and ArcIMS
            • Example 1
            • Example 2
            • Example 3
              • Accessing a COM Server from a NET Client
              • Summary
Page 5: Consuming ArcIMS Image Services using .NET Client Web ... · Consuming ArcIMS Image Services using .NET Client Web Applications An ESRI White Paper Ł October 2002 ... The .NET framework

heterogeneous environments Simply put web services allow you to share information or integrate with legacy systems without having to write specialized interconnection applications In this paper we will restrict the discussions and examples to using ASPNET as a unified Web development platform for building sophisticated web applications that will interact with ArcIMS Image Services

To understand and appreciate the additional benefits that NET technology brings to the table you should have some experience programming the ArcIMS client applications using the ActiveX or the Servlet connector model Also a good understanding of ArcXML syntax is essential to effectively use the Servlet connector model

Let us start by looking at what NET technology really is and get a firm handle on some of the terminologies used

What is NET NET is a new computing platform that simplifies application development in the highly distributed environment of the Internet The NET platform is built on top of the operating system NET has been influenced by other technological advances such as XML Java and COM The NET infrastructure comprises the NET framework Microsoft Visual StudioNET the NET Enterprise Servers and Microsoft WindowsNet In short the NET infrastructure refers to all the technologies that make up the environment for creating and running robust scalable and distributed applications

The following paragraphs provide a brief overview of some of the technologies and terminologies associated with NET To get more detailed information on NET there are a large number of books and information freely available on the internet that provide detailed descriptions of the technology This paper focuses on getting a broad perspective and some detailed knowledge of specific areas of the NET framework that can assist in leveraging this technology within the ArcIMS Internet Mapping Environment

The NET Framework

The NET framework is the part of the infrastructure that aids us in creating applications In simple terms the NET Framework can be discussed as containing 2 parts the CLR or the Common Language Runtime and the NET Framework Class libraries

The Common Language Runtime (CLR)

The CLR is the most important part of the NET architecture and computing paradigm It is the run-time environment in which applications written in different languages can all exist and play together providing cross-language interoperability

The mechanism for cross language interoperability is provided via the concept of Common Language Specification (CLS) a common set of rules A compiler that adheres

ESRI White Paper 2

to the rules can take code written in a specific language and port it to MSIL a Microsoft Intermediate Language Since MSIL code cannot be executed directly the CLR compiles the MSIL by using a Just-in-time (JIT) compiler into native CPU instructions as it processes the MSIL

One term that is mentioned a lot in conjunction with NET is managed code This is in fact made possible by the CLR Managed code is just code that is run under the auspices of the CLR or in other words code managed by the CLR One of the most important services provided by the CLR as part of the managed code paradigm is the concept of garbage collection NET uses automatic garbage collection to reclaim memory When memory allocated on the heap becomes orphaned or passes out of scope it is placed on a list of memory locations to be freed Periodically the system runs a garbage collection thread that returns the memory to the heap

While the runtime is designed for the software of the future it also supports legacy technology Interoperability between managed and unmanaged code enables developers to continue to use necessary COM components and DLLs

Managed Unmanaged and Unsafe code Understanding the Difference

Managed code is that code which executes under the supervision of the CLR This was dealt with in the section above The user has no control over how CLR achieves memory management type verification garbage collection and many other activities Uunmanaged code is that code which executes outside the context of the CLR The best example of this is your traditional Win32 DLLs like KERNEL32DLL USER32DLL and the COM components installed on our system How they allocate memory for their usage how memory is released how (if any) type verification takes places are some of the tasks that are undertaken by them on their own Unsafe code is a kind of cross between the managed and unmanaged codes It executes under the supervision of the CLR just like the managed code but lets you address the memory directly through the use of pointers as is done in unmanaged code A typical example would be a NET application that uses the functionality in a legacy Win32 DLL whose exported functions require the use of pointers Unless you are a NET aficionado understanding unsafe code and its implications may not be important to you But understanding the differences between Managed and Unmanaged code should provide you enough information to deal effectively with interoperability issues that needs to be dealt with while working with the ActiveX connector

ESRI White Paper 3

NET Framework Class Libraries

The NET Framework class library is a collection of reusable types that tightly integrate with the common language runtime The class library is object oriented providing types from which your own managed code can derive functionality

The NET Framework types enable you to accomplish a range of common programming tasks including tasks such as string management data collection database connectivity and file access In addition to these common tasks the class library includes types that support a variety of specialized development scenarios This paper includes examples of class libraries created by ESRI that provide rich functionality for developers to inherit in their web applications

Also the examples shown in this paper make use of ASPNET and web forms technologies As you create applications in ASPNET you will find it convenient to use many of the classes provided as part of the web forms class library

As you become familiar with the classes in the NET framework you may want to create wrapper classes that provide functionality for XML parsing internet intranet connections that inherit from base classes in the NET framework By creating your own classes you can provide reusable componentized code for building other ArcIMS client applications that require similar functionality

NET programs are deployed as assemblies An assembly is one or more EXEs or DLLs with associated metadata information The metadata about the entire assembly is stored in the assemblys manifest The manifest contains for example a list of assemblies upon which the current assembly is dependant The concept of assemblies how they can be deployed privately or publicly how they can be versioned etc is quite complex and are not discussed in this paper As always the internet serves as good source for information regarding these topics

ASPNET and Web Forms

The various web applications shown in this paper were all built using ASPNET ASPNET is the hosting environment that enables developers to use the NET Framework to target Web-based applications However ASPNET is more than just a runtime host it is a complete architecture for developing Web sites and Internet-distributed objects using managed code Both Web Forms and XML Web services use IIS and ASPNET as the publishing mechanism for applications and both have a collection of supporting classes in the NET Framework If you have used earlier versions of ASP technology it is easy to note the improvements provided by ASPNET and Web Forms For example you can develop Web Forms pages in any language that supports the NET Framework In addition ASPNET no longer needs to share the same file with your HTTP text (although it can continue to do so if you

ESRI White Paper 4

prefer) Unlike unmanaged ASP code that is always scripted and interpreted ASPNET pages are faster and easier to manage as they execute in native machine language and interact with the runtime like any managed application To summarize here are a few benefits to programming with ASPNET

Object Orientation and a large class library from which to inherit functionality Can use multiple programming languages VBNET C etc Code is always

compiled before it is run Web Forms and Web Controls present the programmer with an event driven

model very similar to the desktop environment Server side controls intelligently render html code appropriate to the target browser

Advanced crash-recovery and detection and isolation of rogue code damaging the system

Scalable architecture with extensive caching to reduce running lots of identical code for each website visitor

Debugging is much easier especially when the programming is done using an IDE like Visual StudioNet

The NET programming environment provides very good database and XML support

MSIL and the new assembly model makes deploying applications and versioning complexities an issue of the past

Provides tools to easily create webservices All the plumbing code required is effectively hidden

The diagram below shows the typical sequence of calls made during a request response cycle for a ASPNET web page Notice that the first request-response cycle is shown by steps 1 through 6 and subsequent calls are displayed as steps 7-10

ESRI White Paper 5

Because ASPNET uses compiled code instead of interpreted code subsequent requests will check to see if there has been any change to the code If not it will utilize the script engine cache to access the compiled version of the code

NET and ArcIMS In order to better understand how to build map services using ArcIMS and the NET environment this paper presents the concepts in a series of three examples The examples all written using NET compatible languages (VBNET and C) demonstrate web applications that display map images served up ESRIs ArcIMS product The examples chosen are such that they provide a good handle on the various aspects of designing web applications that server as clients to the ArcIMS Image Service The following are a brief description of the three examples

Example 1 An ASPNET application written in VBNET that utilizes COM Interop to access the functionality exposed by the ActiveX connector

Example 2 An ASPNET application written in VBNET that makes use of special classes (also developed in VBNET) to send and receive requests via the Servlet connector in ArcIMS This example also contains code that shows you how to capture page coordinates from a mouse click event on the image map control It also shows the

ESRI White Paper 6

necessary steps to convert the obtained page coordinates to map coordinates for subsequent use in zoom operations

Example 3 An ASPNET application written in C that makes use of special classes developed in C This example utilizes two approaches one using the Servlet connector and another using a C wrapper to the ActiveX connector to connect to the service using TCP

Example 1

This application is a very simple web application that demonstrates the use of an image control in a web form to display a map image served up by ArcIMS The button control reads State Names from a database and populates the DropDownList Selecting a State from the DropDownList highlights the state in the map

This example demonstrates the following

Basic web form and web controls Button Image and DropDownListcontrols Using the ActiveX connector in a NET web application using COM Interop

ESRI White Paper 7

Connecting to an access database to read a list of names (from a column) This list is then used to populate a drop down list box

Using the image control to view an image rendered by ArcIMS

ASPNET and Web Forms Programming Environment

Visual Basic NET Programming Language

Data Files

File Name Comment BPC 2002mdb Database file with a column containing state names World30stateslakescountry Shape files BPC_STATESaxl Axl file for the image service

WebForm Controls

Control Name Function ImageButton1 Control for displaying the image Button Populates the Dropdown Listbox with State Names read from the

database DropDownList1 Set AutoPostback property to TRUE

Steps to Create Application

Create a new Project Choose Visual Basic Project -gt ASPNET web application

Add Project References

ESRI White Paper 8

o Project Add References COM ArcIMS ActiveX Connector (Aims_ActiveXdll)

o Project Add References NET adodb ( adodbdll)

Add controls to the form and set the appropriate properties (NameCaption Size etc)

Right click on the WebForm1aspx file and choose Viewcode Type the code shown below Click on Build-gtSolution Press CTRL+F5 to start without debugging or F5 to Start (with debugging)

ESRI White Paper 9

Code from Web Form1aspxvb the codebehind page for the Web Form

Define and instantiate class variables Refer to the Section Accessing a COM Server from a NET Client for a discussion on using early and late binding mechanisms to instantiate COM objects

Private mapStates As aimsMap()

Private conArcIMS As aimsArcIMSConnector()

The Page_Load event sets up the connection and map parameters It also links the image URL (provided by ArcIMS) to the URL property of the Image control to display the map image

Private Sub Page_load(ByVal sender As SystemObject ByVal e As SystemEventArgs) Handles MyBaseLoad mapStates = New aimsMap() conArcIMS = New aimsArcIMSConnector() conArcIMSServerName = localhost conArcIMSServerPort = 5300 mapStatesInitMap(conArcIMS BPC_States) mapStatesWidth = 550 mapStatesHeight = 400 mapStatesRefresh()

ESRI White Paper 10

ImageButton1ImageUrl = mapStatesGetImageAsUrl

End Sub

The Button Click event makes a connection to the bpc2002mdb access database It then reads the data from the States column orders it alphabetically and then populates the DropDownList control with the ordered list of entries

Private Sub Button1_Click(ByVal sender As SystemObject ByVal e As SystemEventArgs) Handles Button1Click Dim conDB As OleDbOleDbConnection Dim cmdFetch As OleDbOleDbCommand Dim rdrStates As OleDbOleDbDataReader Dim sCon As String = Provider=MicrosoftJetOLEDB40Data Source=CArcIMSWebsiteBPC_Statesbpc2002mdb conDB = New OleDbOleDbConnection(sCon) conDBOpen() cmdFetch = New OleDbOleDbCommand(SELECT STATE_NAME FROM STATES ORDER BY STATE_NAME) cmdFetchConnection = conDB rdrStates = cmdFetchExecuteReader() While rdrStatesRead() DropDownList1ItemsAdd(New ListItem(rdrStatesGetString(0))) End While conDBClose()

End Sub

The DropDownList fires a SelectedIndexChanged event The code associated with this event uses the where expression with LayersItem()Filter to create an image with a special highlight applied to the selected state The URL of the image is linked to the image buttons URL to display the new image

Private Sub DropDownList1_SelectedIndexChanged(ByVal sender As Object ByVal e As SystemEventArgs) Handles DropDownList1SelectedIndexChanged Dim sWhere As String = STATE_NAME = amp DropDownList1SelectedItemText amp mapStatesLayersItem(4)FilterWhereExpression = sWhere mapStatesRefresh() ImageButton1ImageUrl = mapStatesGetImageAsUrl End Sub

The Page_Unload event is used for clean up code Here it is used to free memory by setting the map and connection object to Nothing

ESRI White Paper 11

Private Sub Page_unload(ByVal sender As Object ByVal e As SystemEventArgs) Handles MyBaseUnload mapStates = Nothing conArcIMS = Nothing

End Sub

Example 2

General Description

This web application demonstrates the use of two image controls in a web form to display a map image and its associated legend both images being served up by ArcIMS The web application also has controls for Zoomin Zoomout and pan

Programming Environment ASPNET and Web Forms

Programming Language Visual Basic NET

WebForm Controls

ESRI White Paper 12

Control Name Function ImgMap Control for displaying the image ImgLegend Control for displaying the legend image lstNavControls Radiobutton list controls

Data Files

Can use any datafile capable of generating an image service Replace the sf parameter in the page_load event with the appropriate image service name

Class Libraries ( Logic_classes assembly)

File Name Class Information Functionality MapVB The Cmap class has a

MustInherit Keyword and is inherited by Cviewer The MustInherit keyword specifies that a class cannot be instantiated and can be used only as a base class

PointVB Used by Cmap Crect Represents a geometric point (xy pair ) RectVB Used by Cmap Cviewer and

Webform3 in testformaspx

ViewerVB Used in Webform3 in testformaspx

Abstracts the requesting of a simple map from ArcIMS No additional entities will be added to the map (ie graphics buffer etc) The map is requested with all the default parameters with which it is served excepting extent and background color

Steps to Create Application

ESRI White Paper 13

The following section details the code found in the code behind page of the Testformaspx page

Statement to import logic_classes Makes all the functionality available in the logic_classes project available to the code in the web form

Imports logic_classes

Define a class level variable in the aspx file

Private m_objViewerMap As cViewer

Code for the page load event Uses IsPostback to determine if the extents need to be read afresh or from a previous valued stored in the session object Also instantiates the Cviewer class object You need to make sure that the extents shown in the code are appropriately changed to work with your selected image service

Private Sub Page_Load(ByVal sender As SystemObject ByVal e As SystemEventArgs) Handles MyBaseLoad

ESRI White Paper 14

Put user code to initialize the page here Dim rctExtent As cRect If Not IsPostBack Then enter appropriate extents rctExtent = New cRect(-1225173 377199 -122363678 3780374) Else rctExtent = New cRect(Session(MinX) Session(MinY) Session(MaxX) Session(MaxY)) End If m_objViewerMap = New cViewer(httplocalhostservletcomesriesrimapEsrimap _ sf _ rctExtent _ imgMapWidthValue _ imgMapHeightValue _ 000) add test markers

End Sub

Page_Prerender event code Links the output image to the Picture controls Also since HTTP is a stateless protocol the current map extents are stored in session variables for follow-up requests from the same user

Private Sub Page_PreRender(ByVal sender As Object ByVal e As SystemEventArgs) Handles MyBasePreRender imgMapImageUrl = m_objViewerMapMap() imgLegendImageUrl = m_objViewerMapLegend() Session(MinX) = m_objViewerMapExtentXMin Session(MinY) = m_objViewerMapExtentYMin Session(MaxX) = m_objViewerMapExtentXMax Session(MaxY) = m_objViewerMapExtentYMax

End Sub

Imgmap_click event is raised when the user clicks on the map Code associated with this event converts the image click coordinate to a map coordinate Then

ESRI White Paper 15

based on the radio button selection ( Zoomin Zoomout or pan) the code calls the appropriate method using the instantiated Cviewer object

Private Sub imgMap_Click(ByVal sender As Object ByVal e As SystemWebUIImageClickEventArgs) Handles imgMapClick Convert the image click coordinate to a map coordinate based on the maps current extent Dim rctCurrentExtent As cRect = m_objViewerMapExtent Dim dblX As Double = rctCurrentExtentXMin + ((eX imgMapWidthValue) (rctCurrentExtentXMax - rctCurrentExtentXMin)) Dim dblY As Double = rctCurrentExtentYMin + (((imgMapHeightValue - eY) imgMapHeightValue) (rctCurrentExtentYMax - rctCurrentExtentYMin)) If Trim(UCase(lstNavControlsSelectedItemText)) ltgt IDENTIFY Then m_objViewerMapCenterAt(dblX dblY) Select Case UCase(lstNavControlsSelectedItemText) Case ZOOM IN Center the map m_objViewerMapZoom(-1) Case ZOOM OUT m_objViewerMapZoom(1) Case PAN do nothing Case Else ErrRaise(vbObjectError + 512 imgMap_Click Invalid command) End Select Else identify End If End Sub

ESRI White Paper 16

End Class

NOTE =gt Once you have the relevant files imported into Visual Studio make sure that you configure the virtual directory as an application before you run the example

If the virtual directory is not configured as an Application you will get an error message that reads This error can be caused by a virtual directory not being configured as an application in IIS To configure a Virtual directory is simple Use the Internet Service Manager to perform the following steps

Find the folder in the virtual directory Right click and choose properties Click Create Accept all the settings and Click OK

Example 3

General Description

The program uses the catalog service (using the ltGETCLIENTSERVICESgt request) to query and list a collection of services running on the server A Radiobutton list control is used to list all the service names running on the server On selecting an appropriate image service the map image is displayed on the web form using an image control This program demonstrates two different ways to connect to the datasource Connection could be achieved using the http protocol or the TCP protocol The TCP method utilizes the TCP capability built into the ActiveX Connector Since ASPNET is a multithreaded and the ActiveX connector being Single Threaded (STA) a wrapper class with additional functionality to manage memory is used to access the methods in the ActiveX connector

ESRI White Paper 17

Programming Environment ASPNET and Web Forms

C NET Programming Language

WebForm Controls

Control Name Function ImgMap Control for displaying the image RbServices Radiobutton list controls Txtinfo Displays the name of the selected image service

Data Files

Requires a collection of image services running on an ArcIMS server The program uses the ltGETCLIENTSERVICESgt request tag to query the catalog service to list all the services running on the specified server

Class Libraries

File Name Class Information Functionality Connectioncs Abstract base class Provides abstract method

templates for the HTTPConnection and

ESRI White Paper 18

TCPConnection classes HTTPConnectioncs Inherits from Connection class Provides functionality for

sending request to service postinggetting URL content etc

TCPConnectioncs Inherits from Connection class and SystemIDisposable

Utlizes the AICLib assembly to access connection functionality built into the ActiveX connector

Datasourcecs Provides method for accessing path port host and other information

Enumerationscs Provides enumerations for AccessType and LoadType

Envelopecs Provides methods for getting and setting xy coordinates of the envelope

ImageReturnObjectcs Provides methods for settinggetting image URL image envelope and image scale

Mapcs Calls send request to service with connection and service information Parses response to obtain image URL

Servicecs Servicescs Inherits from

SystemCollectionsHashtable Composes the clientservices request and parses the response Creates a hashtable association of individual service name with its associated service object

XML helper class that provides relevant XML parsing functionality by acting as a wrapper class around NETs xml Text IO and other NET classes

XMLRequestscs Builds ArcXML strings for requests

XMLHelpercs

Steps to Create Application

ESRI White Paper 19

The NET solution contains 2 projects ArcIMS and ArcIMSSample The ArcIMS project

o References the InteropAICLib o Contains NET ArcIMS class libraries that can be used to connect and to

work with image services The ArcIMSSample project

o References the ArcIMS project o Contains the web form (webform1aspx) and the corresponding

webform1aspxcs code-behind page that connects the web page controls to relevant functionality using an event driven web forms model

Points to Note

In webform1aspxcs code session variables are used to maintain state of serialized objects In order for this to be possible notice that the relevant classes have been marked as serializable

ESRI White Paper 20

Choose the appropriate connection type based on HTTP or TCP connection For HTTP choose m_dsConnectType = ConnectionTypeInterNet and for For TCP select m_dsConnectType = ConnectionTypeIntraNet as shown in the code below

private ArcIMSDataSource getDataSource() m_ds = Session[datasource] as ArcIMSDataSource if ( m_ds == null ) m_ds = new ArcIMSDataSource() m_dsHost = localhost m_dsScheme = http m_dsPort = 80 m_dsAppServerPort = 5300 m_dsPath = servletcomesriesrimapEsrimap choose (comment uncomment) one of the following two statements to decide between TCP or HTTP type connection m_dsConnectType = ConnectionTypeIntraNet m_dsConnectType = ConnectionTypeInterNet SessionAdd(datasource m_ds) return m_ds

Accessing a COM Server from a NET Client With the introduction of the NET Framework and ASPNET COM at its basic level has not really changed Nevertheless there are a couple of issues to be aware of when making calls to a COM object from a NET managed code environment The ASPNET threading model is the Multiple Threaded Apartment (MTA) This will not interact reliably with STA components (the ActiveX connector provided with the ArcIMS setup was built as an STA component) To emphasize this issue heres a direct quote from the MSDN pages at Microsoft The ASPNET threading model is the Multiple Threaded Apartment (MTA) What this means is that components that you are using that were created for the Single Threaded Apartment (STA) will no longer perform or function reliably without taking some extra precautions in ASPNET This includes but is not limited to all COM components that have been created using Visual Basic 60 and earlier versions

To understand the issues better let us take a look at how NET deals with COM related issues The Common Language Runtime exposes COM objects through a proxy called the runtime callable wrapper (RCW) The RCWs primary function is to marshal calls between a NET client and COM object The RCW object is nothing but an object instantiated at runtime from class code contained in the Interop assembly

ESRI White Paper 21

Calling between managed and unmanaged components incurs a marshaling cost which can impede the performance of your pages When a managed client and unmanaged server are in the same apartment the Interop marshalling service handles all data marshalling However when client and server are initialized in different apartments COM marshalling is also required Therefore interoperability with COM from a NET client should take into consideration the threading model used

Figure Cross-apartment call between a NET client and COM object

As mentioned earlier ASPNET follows an MTA model by default You could use the default model to communicate with an STA COM component if there is not much of an overhead due to the cross-apartment marshalling Usually this is noticeable only when there are many calls across the boundary Another option would be to use the PageAspCompatMode property of the ASPNET client The ASPCompat=true attribute enables an STA thread pool to address performance with existing Visual Basic components on a per-page basis The runtime throws an exception if the compatibility tag is omitted and an STA component is referenced on the page If you convert the STA component to an assembly using Type Library Importer (a utility included with the NET SDK) the runtime does not detect that the component uses the STA model and does not throw an exception but your application can suffer from poor performance and possible deadlocks STA components cannot be used from NET Framework code modules (compiled NET assemblies) they can be used only from ASPNET pages

If you plan to use the ASPCOMPAT = TRUE page level directive for Example 1 remember to instantiate the COM object within the page_load event rather than constructing COM components during page construction time For example look at code examples A and B

Example A Example B ltPage Language = VB ASPCOMPAT = truegt

ltscript runat = servergt

private mapStates as new aimsMap()

private sub_load ()

ltPage Language = VB ASPCOMPAT = truegt

ltscript runat = servergt

private mapStates as aimsMap()

private sub_load ()

ESRI White Paper 22

end sub

mapStates = new aimsMap()

end sub

In example A the STA component would be instantiated at page construction time which is created from a thread that is not the STA thread that will run the page This will involve marshalling between MTA and STA threads during the construction of the page Example B shows the preferred mechanism to delay the process until later when the code executes under a STA thread It is best to construct any COM component and external resources when needed or in the Page_Load method

Also to create the object you can use either the New keyword or the CreateObject method The CreateObject method is typically used when you dont know the Program ID (ProgID) of the object you are going to create until run time (late binding) New is the recommended method for instantiating objects if you have access to the objects type library It is preferable to adopt the early binding model

Every scenario yields different performance characteristics so it is important to test adequately before deciding whether interoperability is the right choice for your application However in nearly all scenarios rewriting your COM components in managed code provides performance benefits

Summary The examples shown above provide adequate information to leverage the NET programming environment to build effective ArcIMS client applications The debugging features of a program like Visual StudioNET provide a variety of tools (break points trace etc) making the entire development experience considerably pain-free Use the debugger to understand the sequence in which calls are made One early exercise would be to look at the calling sequence of the various page related events such as page_init page_load and page_prerender Since the Web Forms code is compiled you should experience much better performance than with ASP pages that used code written in scripting languages like Javascript and VbScript

The powerful programming environment also means that you can now concentrate more on the logic of building large web applications as opposed to building simple page based asp applications Also look at the various caching mechanisms provided by ASPNET as these can be used to improve overall performance As always there are costs associated with most programming choices and this is all the more true in a web-programming environment For example consider the costs associated with using a web control as opposed to a HTML based control Use plain HTML controls instead of adopting web controls for simple items like label

ESRI White Paper 23

If you choose to use the ActiveX connector from within the NET environment make sure that you clearly understand the essentials of COM Interop and the various costs associated with marshalling The solutions outlined in this paper utilize existing ArcIMS services and should work with all versions of ArcIMS

Although all the development can be done without the use of an Integrated Development environment (IDE) like Visual StudioNET using such an environment provides convenient WYSIWYG features that can help in building and debugging the application If you do not have Visual StudioNET there are free IDEs available today that can also be used For example ASPNET Web Matrix is a community-supported easy-to-use WYSIWYG application development tool for ASPNET It can be installed via a quick 12 MB download from httpwwwaspnetwebmatrixdefaultaspx

ESRI White Paper 24

  • ArcIMS ndash An Introduction
  • What is NET
    • The NET Framework
      • The Common Language Runtime (CLR)
      • Managed Unmanaged and Unsafe code ndash Understandin
      • NET Framework Class Libraries
        • ASPNET and Web Forms
          • NET and ArcIMS
            • Example 1
            • Example 2
            • Example 3
              • Accessing a COM Server from a NET Client
              • Summary
Page 6: Consuming ArcIMS Image Services using .NET Client Web ... · Consuming ArcIMS Image Services using .NET Client Web Applications An ESRI White Paper Ł October 2002 ... The .NET framework

to the rules can take code written in a specific language and port it to MSIL a Microsoft Intermediate Language Since MSIL code cannot be executed directly the CLR compiles the MSIL by using a Just-in-time (JIT) compiler into native CPU instructions as it processes the MSIL

One term that is mentioned a lot in conjunction with NET is managed code This is in fact made possible by the CLR Managed code is just code that is run under the auspices of the CLR or in other words code managed by the CLR One of the most important services provided by the CLR as part of the managed code paradigm is the concept of garbage collection NET uses automatic garbage collection to reclaim memory When memory allocated on the heap becomes orphaned or passes out of scope it is placed on a list of memory locations to be freed Periodically the system runs a garbage collection thread that returns the memory to the heap

While the runtime is designed for the software of the future it also supports legacy technology Interoperability between managed and unmanaged code enables developers to continue to use necessary COM components and DLLs

Managed Unmanaged and Unsafe code Understanding the Difference

Managed code is that code which executes under the supervision of the CLR This was dealt with in the section above The user has no control over how CLR achieves memory management type verification garbage collection and many other activities Uunmanaged code is that code which executes outside the context of the CLR The best example of this is your traditional Win32 DLLs like KERNEL32DLL USER32DLL and the COM components installed on our system How they allocate memory for their usage how memory is released how (if any) type verification takes places are some of the tasks that are undertaken by them on their own Unsafe code is a kind of cross between the managed and unmanaged codes It executes under the supervision of the CLR just like the managed code but lets you address the memory directly through the use of pointers as is done in unmanaged code A typical example would be a NET application that uses the functionality in a legacy Win32 DLL whose exported functions require the use of pointers Unless you are a NET aficionado understanding unsafe code and its implications may not be important to you But understanding the differences between Managed and Unmanaged code should provide you enough information to deal effectively with interoperability issues that needs to be dealt with while working with the ActiveX connector

ESRI White Paper 3

NET Framework Class Libraries

The NET Framework class library is a collection of reusable types that tightly integrate with the common language runtime The class library is object oriented providing types from which your own managed code can derive functionality

The NET Framework types enable you to accomplish a range of common programming tasks including tasks such as string management data collection database connectivity and file access In addition to these common tasks the class library includes types that support a variety of specialized development scenarios This paper includes examples of class libraries created by ESRI that provide rich functionality for developers to inherit in their web applications

Also the examples shown in this paper make use of ASPNET and web forms technologies As you create applications in ASPNET you will find it convenient to use many of the classes provided as part of the web forms class library

As you become familiar with the classes in the NET framework you may want to create wrapper classes that provide functionality for XML parsing internet intranet connections that inherit from base classes in the NET framework By creating your own classes you can provide reusable componentized code for building other ArcIMS client applications that require similar functionality

NET programs are deployed as assemblies An assembly is one or more EXEs or DLLs with associated metadata information The metadata about the entire assembly is stored in the assemblys manifest The manifest contains for example a list of assemblies upon which the current assembly is dependant The concept of assemblies how they can be deployed privately or publicly how they can be versioned etc is quite complex and are not discussed in this paper As always the internet serves as good source for information regarding these topics

ASPNET and Web Forms

The various web applications shown in this paper were all built using ASPNET ASPNET is the hosting environment that enables developers to use the NET Framework to target Web-based applications However ASPNET is more than just a runtime host it is a complete architecture for developing Web sites and Internet-distributed objects using managed code Both Web Forms and XML Web services use IIS and ASPNET as the publishing mechanism for applications and both have a collection of supporting classes in the NET Framework If you have used earlier versions of ASP technology it is easy to note the improvements provided by ASPNET and Web Forms For example you can develop Web Forms pages in any language that supports the NET Framework In addition ASPNET no longer needs to share the same file with your HTTP text (although it can continue to do so if you

ESRI White Paper 4

prefer) Unlike unmanaged ASP code that is always scripted and interpreted ASPNET pages are faster and easier to manage as they execute in native machine language and interact with the runtime like any managed application To summarize here are a few benefits to programming with ASPNET

Object Orientation and a large class library from which to inherit functionality Can use multiple programming languages VBNET C etc Code is always

compiled before it is run Web Forms and Web Controls present the programmer with an event driven

model very similar to the desktop environment Server side controls intelligently render html code appropriate to the target browser

Advanced crash-recovery and detection and isolation of rogue code damaging the system

Scalable architecture with extensive caching to reduce running lots of identical code for each website visitor

Debugging is much easier especially when the programming is done using an IDE like Visual StudioNet

The NET programming environment provides very good database and XML support

MSIL and the new assembly model makes deploying applications and versioning complexities an issue of the past

Provides tools to easily create webservices All the plumbing code required is effectively hidden

The diagram below shows the typical sequence of calls made during a request response cycle for a ASPNET web page Notice that the first request-response cycle is shown by steps 1 through 6 and subsequent calls are displayed as steps 7-10

ESRI White Paper 5

Because ASPNET uses compiled code instead of interpreted code subsequent requests will check to see if there has been any change to the code If not it will utilize the script engine cache to access the compiled version of the code

NET and ArcIMS In order to better understand how to build map services using ArcIMS and the NET environment this paper presents the concepts in a series of three examples The examples all written using NET compatible languages (VBNET and C) demonstrate web applications that display map images served up ESRIs ArcIMS product The examples chosen are such that they provide a good handle on the various aspects of designing web applications that server as clients to the ArcIMS Image Service The following are a brief description of the three examples

Example 1 An ASPNET application written in VBNET that utilizes COM Interop to access the functionality exposed by the ActiveX connector

Example 2 An ASPNET application written in VBNET that makes use of special classes (also developed in VBNET) to send and receive requests via the Servlet connector in ArcIMS This example also contains code that shows you how to capture page coordinates from a mouse click event on the image map control It also shows the

ESRI White Paper 6

necessary steps to convert the obtained page coordinates to map coordinates for subsequent use in zoom operations

Example 3 An ASPNET application written in C that makes use of special classes developed in C This example utilizes two approaches one using the Servlet connector and another using a C wrapper to the ActiveX connector to connect to the service using TCP

Example 1

This application is a very simple web application that demonstrates the use of an image control in a web form to display a map image served up by ArcIMS The button control reads State Names from a database and populates the DropDownList Selecting a State from the DropDownList highlights the state in the map

This example demonstrates the following

Basic web form and web controls Button Image and DropDownListcontrols Using the ActiveX connector in a NET web application using COM Interop

ESRI White Paper 7

Connecting to an access database to read a list of names (from a column) This list is then used to populate a drop down list box

Using the image control to view an image rendered by ArcIMS

ASPNET and Web Forms Programming Environment

Visual Basic NET Programming Language

Data Files

File Name Comment BPC 2002mdb Database file with a column containing state names World30stateslakescountry Shape files BPC_STATESaxl Axl file for the image service

WebForm Controls

Control Name Function ImageButton1 Control for displaying the image Button Populates the Dropdown Listbox with State Names read from the

database DropDownList1 Set AutoPostback property to TRUE

Steps to Create Application

Create a new Project Choose Visual Basic Project -gt ASPNET web application

Add Project References

ESRI White Paper 8

o Project Add References COM ArcIMS ActiveX Connector (Aims_ActiveXdll)

o Project Add References NET adodb ( adodbdll)

Add controls to the form and set the appropriate properties (NameCaption Size etc)

Right click on the WebForm1aspx file and choose Viewcode Type the code shown below Click on Build-gtSolution Press CTRL+F5 to start without debugging or F5 to Start (with debugging)

ESRI White Paper 9

Code from Web Form1aspxvb the codebehind page for the Web Form

Define and instantiate class variables Refer to the Section Accessing a COM Server from a NET Client for a discussion on using early and late binding mechanisms to instantiate COM objects

Private mapStates As aimsMap()

Private conArcIMS As aimsArcIMSConnector()

The Page_Load event sets up the connection and map parameters It also links the image URL (provided by ArcIMS) to the URL property of the Image control to display the map image

Private Sub Page_load(ByVal sender As SystemObject ByVal e As SystemEventArgs) Handles MyBaseLoad mapStates = New aimsMap() conArcIMS = New aimsArcIMSConnector() conArcIMSServerName = localhost conArcIMSServerPort = 5300 mapStatesInitMap(conArcIMS BPC_States) mapStatesWidth = 550 mapStatesHeight = 400 mapStatesRefresh()

ESRI White Paper 10

ImageButton1ImageUrl = mapStatesGetImageAsUrl

End Sub

The Button Click event makes a connection to the bpc2002mdb access database It then reads the data from the States column orders it alphabetically and then populates the DropDownList control with the ordered list of entries

Private Sub Button1_Click(ByVal sender As SystemObject ByVal e As SystemEventArgs) Handles Button1Click Dim conDB As OleDbOleDbConnection Dim cmdFetch As OleDbOleDbCommand Dim rdrStates As OleDbOleDbDataReader Dim sCon As String = Provider=MicrosoftJetOLEDB40Data Source=CArcIMSWebsiteBPC_Statesbpc2002mdb conDB = New OleDbOleDbConnection(sCon) conDBOpen() cmdFetch = New OleDbOleDbCommand(SELECT STATE_NAME FROM STATES ORDER BY STATE_NAME) cmdFetchConnection = conDB rdrStates = cmdFetchExecuteReader() While rdrStatesRead() DropDownList1ItemsAdd(New ListItem(rdrStatesGetString(0))) End While conDBClose()

End Sub

The DropDownList fires a SelectedIndexChanged event The code associated with this event uses the where expression with LayersItem()Filter to create an image with a special highlight applied to the selected state The URL of the image is linked to the image buttons URL to display the new image

Private Sub DropDownList1_SelectedIndexChanged(ByVal sender As Object ByVal e As SystemEventArgs) Handles DropDownList1SelectedIndexChanged Dim sWhere As String = STATE_NAME = amp DropDownList1SelectedItemText amp mapStatesLayersItem(4)FilterWhereExpression = sWhere mapStatesRefresh() ImageButton1ImageUrl = mapStatesGetImageAsUrl End Sub

The Page_Unload event is used for clean up code Here it is used to free memory by setting the map and connection object to Nothing

ESRI White Paper 11

Private Sub Page_unload(ByVal sender As Object ByVal e As SystemEventArgs) Handles MyBaseUnload mapStates = Nothing conArcIMS = Nothing

End Sub

Example 2

General Description

This web application demonstrates the use of two image controls in a web form to display a map image and its associated legend both images being served up by ArcIMS The web application also has controls for Zoomin Zoomout and pan

Programming Environment ASPNET and Web Forms

Programming Language Visual Basic NET

WebForm Controls

ESRI White Paper 12

Control Name Function ImgMap Control for displaying the image ImgLegend Control for displaying the legend image lstNavControls Radiobutton list controls

Data Files

Can use any datafile capable of generating an image service Replace the sf parameter in the page_load event with the appropriate image service name

Class Libraries ( Logic_classes assembly)

File Name Class Information Functionality MapVB The Cmap class has a

MustInherit Keyword and is inherited by Cviewer The MustInherit keyword specifies that a class cannot be instantiated and can be used only as a base class

PointVB Used by Cmap Crect Represents a geometric point (xy pair ) RectVB Used by Cmap Cviewer and

Webform3 in testformaspx

ViewerVB Used in Webform3 in testformaspx

Abstracts the requesting of a simple map from ArcIMS No additional entities will be added to the map (ie graphics buffer etc) The map is requested with all the default parameters with which it is served excepting extent and background color

Steps to Create Application

ESRI White Paper 13

The following section details the code found in the code behind page of the Testformaspx page

Statement to import logic_classes Makes all the functionality available in the logic_classes project available to the code in the web form

Imports logic_classes

Define a class level variable in the aspx file

Private m_objViewerMap As cViewer

Code for the page load event Uses IsPostback to determine if the extents need to be read afresh or from a previous valued stored in the session object Also instantiates the Cviewer class object You need to make sure that the extents shown in the code are appropriately changed to work with your selected image service

Private Sub Page_Load(ByVal sender As SystemObject ByVal e As SystemEventArgs) Handles MyBaseLoad

ESRI White Paper 14

Put user code to initialize the page here Dim rctExtent As cRect If Not IsPostBack Then enter appropriate extents rctExtent = New cRect(-1225173 377199 -122363678 3780374) Else rctExtent = New cRect(Session(MinX) Session(MinY) Session(MaxX) Session(MaxY)) End If m_objViewerMap = New cViewer(httplocalhostservletcomesriesrimapEsrimap _ sf _ rctExtent _ imgMapWidthValue _ imgMapHeightValue _ 000) add test markers

End Sub

Page_Prerender event code Links the output image to the Picture controls Also since HTTP is a stateless protocol the current map extents are stored in session variables for follow-up requests from the same user

Private Sub Page_PreRender(ByVal sender As Object ByVal e As SystemEventArgs) Handles MyBasePreRender imgMapImageUrl = m_objViewerMapMap() imgLegendImageUrl = m_objViewerMapLegend() Session(MinX) = m_objViewerMapExtentXMin Session(MinY) = m_objViewerMapExtentYMin Session(MaxX) = m_objViewerMapExtentXMax Session(MaxY) = m_objViewerMapExtentYMax

End Sub

Imgmap_click event is raised when the user clicks on the map Code associated with this event converts the image click coordinate to a map coordinate Then

ESRI White Paper 15

based on the radio button selection ( Zoomin Zoomout or pan) the code calls the appropriate method using the instantiated Cviewer object

Private Sub imgMap_Click(ByVal sender As Object ByVal e As SystemWebUIImageClickEventArgs) Handles imgMapClick Convert the image click coordinate to a map coordinate based on the maps current extent Dim rctCurrentExtent As cRect = m_objViewerMapExtent Dim dblX As Double = rctCurrentExtentXMin + ((eX imgMapWidthValue) (rctCurrentExtentXMax - rctCurrentExtentXMin)) Dim dblY As Double = rctCurrentExtentYMin + (((imgMapHeightValue - eY) imgMapHeightValue) (rctCurrentExtentYMax - rctCurrentExtentYMin)) If Trim(UCase(lstNavControlsSelectedItemText)) ltgt IDENTIFY Then m_objViewerMapCenterAt(dblX dblY) Select Case UCase(lstNavControlsSelectedItemText) Case ZOOM IN Center the map m_objViewerMapZoom(-1) Case ZOOM OUT m_objViewerMapZoom(1) Case PAN do nothing Case Else ErrRaise(vbObjectError + 512 imgMap_Click Invalid command) End Select Else identify End If End Sub

ESRI White Paper 16

End Class

NOTE =gt Once you have the relevant files imported into Visual Studio make sure that you configure the virtual directory as an application before you run the example

If the virtual directory is not configured as an Application you will get an error message that reads This error can be caused by a virtual directory not being configured as an application in IIS To configure a Virtual directory is simple Use the Internet Service Manager to perform the following steps

Find the folder in the virtual directory Right click and choose properties Click Create Accept all the settings and Click OK

Example 3

General Description

The program uses the catalog service (using the ltGETCLIENTSERVICESgt request) to query and list a collection of services running on the server A Radiobutton list control is used to list all the service names running on the server On selecting an appropriate image service the map image is displayed on the web form using an image control This program demonstrates two different ways to connect to the datasource Connection could be achieved using the http protocol or the TCP protocol The TCP method utilizes the TCP capability built into the ActiveX Connector Since ASPNET is a multithreaded and the ActiveX connector being Single Threaded (STA) a wrapper class with additional functionality to manage memory is used to access the methods in the ActiveX connector

ESRI White Paper 17

Programming Environment ASPNET and Web Forms

C NET Programming Language

WebForm Controls

Control Name Function ImgMap Control for displaying the image RbServices Radiobutton list controls Txtinfo Displays the name of the selected image service

Data Files

Requires a collection of image services running on an ArcIMS server The program uses the ltGETCLIENTSERVICESgt request tag to query the catalog service to list all the services running on the specified server

Class Libraries

File Name Class Information Functionality Connectioncs Abstract base class Provides abstract method

templates for the HTTPConnection and

ESRI White Paper 18

TCPConnection classes HTTPConnectioncs Inherits from Connection class Provides functionality for

sending request to service postinggetting URL content etc

TCPConnectioncs Inherits from Connection class and SystemIDisposable

Utlizes the AICLib assembly to access connection functionality built into the ActiveX connector

Datasourcecs Provides method for accessing path port host and other information

Enumerationscs Provides enumerations for AccessType and LoadType

Envelopecs Provides methods for getting and setting xy coordinates of the envelope

ImageReturnObjectcs Provides methods for settinggetting image URL image envelope and image scale

Mapcs Calls send request to service with connection and service information Parses response to obtain image URL

Servicecs Servicescs Inherits from

SystemCollectionsHashtable Composes the clientservices request and parses the response Creates a hashtable association of individual service name with its associated service object

XML helper class that provides relevant XML parsing functionality by acting as a wrapper class around NETs xml Text IO and other NET classes

XMLRequestscs Builds ArcXML strings for requests

XMLHelpercs

Steps to Create Application

ESRI White Paper 19

The NET solution contains 2 projects ArcIMS and ArcIMSSample The ArcIMS project

o References the InteropAICLib o Contains NET ArcIMS class libraries that can be used to connect and to

work with image services The ArcIMSSample project

o References the ArcIMS project o Contains the web form (webform1aspx) and the corresponding

webform1aspxcs code-behind page that connects the web page controls to relevant functionality using an event driven web forms model

Points to Note

In webform1aspxcs code session variables are used to maintain state of serialized objects In order for this to be possible notice that the relevant classes have been marked as serializable

ESRI White Paper 20

Choose the appropriate connection type based on HTTP or TCP connection For HTTP choose m_dsConnectType = ConnectionTypeInterNet and for For TCP select m_dsConnectType = ConnectionTypeIntraNet as shown in the code below

private ArcIMSDataSource getDataSource() m_ds = Session[datasource] as ArcIMSDataSource if ( m_ds == null ) m_ds = new ArcIMSDataSource() m_dsHost = localhost m_dsScheme = http m_dsPort = 80 m_dsAppServerPort = 5300 m_dsPath = servletcomesriesrimapEsrimap choose (comment uncomment) one of the following two statements to decide between TCP or HTTP type connection m_dsConnectType = ConnectionTypeIntraNet m_dsConnectType = ConnectionTypeInterNet SessionAdd(datasource m_ds) return m_ds

Accessing a COM Server from a NET Client With the introduction of the NET Framework and ASPNET COM at its basic level has not really changed Nevertheless there are a couple of issues to be aware of when making calls to a COM object from a NET managed code environment The ASPNET threading model is the Multiple Threaded Apartment (MTA) This will not interact reliably with STA components (the ActiveX connector provided with the ArcIMS setup was built as an STA component) To emphasize this issue heres a direct quote from the MSDN pages at Microsoft The ASPNET threading model is the Multiple Threaded Apartment (MTA) What this means is that components that you are using that were created for the Single Threaded Apartment (STA) will no longer perform or function reliably without taking some extra precautions in ASPNET This includes but is not limited to all COM components that have been created using Visual Basic 60 and earlier versions

To understand the issues better let us take a look at how NET deals with COM related issues The Common Language Runtime exposes COM objects through a proxy called the runtime callable wrapper (RCW) The RCWs primary function is to marshal calls between a NET client and COM object The RCW object is nothing but an object instantiated at runtime from class code contained in the Interop assembly

ESRI White Paper 21

Calling between managed and unmanaged components incurs a marshaling cost which can impede the performance of your pages When a managed client and unmanaged server are in the same apartment the Interop marshalling service handles all data marshalling However when client and server are initialized in different apartments COM marshalling is also required Therefore interoperability with COM from a NET client should take into consideration the threading model used

Figure Cross-apartment call between a NET client and COM object

As mentioned earlier ASPNET follows an MTA model by default You could use the default model to communicate with an STA COM component if there is not much of an overhead due to the cross-apartment marshalling Usually this is noticeable only when there are many calls across the boundary Another option would be to use the PageAspCompatMode property of the ASPNET client The ASPCompat=true attribute enables an STA thread pool to address performance with existing Visual Basic components on a per-page basis The runtime throws an exception if the compatibility tag is omitted and an STA component is referenced on the page If you convert the STA component to an assembly using Type Library Importer (a utility included with the NET SDK) the runtime does not detect that the component uses the STA model and does not throw an exception but your application can suffer from poor performance and possible deadlocks STA components cannot be used from NET Framework code modules (compiled NET assemblies) they can be used only from ASPNET pages

If you plan to use the ASPCOMPAT = TRUE page level directive for Example 1 remember to instantiate the COM object within the page_load event rather than constructing COM components during page construction time For example look at code examples A and B

Example A Example B ltPage Language = VB ASPCOMPAT = truegt

ltscript runat = servergt

private mapStates as new aimsMap()

private sub_load ()

ltPage Language = VB ASPCOMPAT = truegt

ltscript runat = servergt

private mapStates as aimsMap()

private sub_load ()

ESRI White Paper 22

end sub

mapStates = new aimsMap()

end sub

In example A the STA component would be instantiated at page construction time which is created from a thread that is not the STA thread that will run the page This will involve marshalling between MTA and STA threads during the construction of the page Example B shows the preferred mechanism to delay the process until later when the code executes under a STA thread It is best to construct any COM component and external resources when needed or in the Page_Load method

Also to create the object you can use either the New keyword or the CreateObject method The CreateObject method is typically used when you dont know the Program ID (ProgID) of the object you are going to create until run time (late binding) New is the recommended method for instantiating objects if you have access to the objects type library It is preferable to adopt the early binding model

Every scenario yields different performance characteristics so it is important to test adequately before deciding whether interoperability is the right choice for your application However in nearly all scenarios rewriting your COM components in managed code provides performance benefits

Summary The examples shown above provide adequate information to leverage the NET programming environment to build effective ArcIMS client applications The debugging features of a program like Visual StudioNET provide a variety of tools (break points trace etc) making the entire development experience considerably pain-free Use the debugger to understand the sequence in which calls are made One early exercise would be to look at the calling sequence of the various page related events such as page_init page_load and page_prerender Since the Web Forms code is compiled you should experience much better performance than with ASP pages that used code written in scripting languages like Javascript and VbScript

The powerful programming environment also means that you can now concentrate more on the logic of building large web applications as opposed to building simple page based asp applications Also look at the various caching mechanisms provided by ASPNET as these can be used to improve overall performance As always there are costs associated with most programming choices and this is all the more true in a web-programming environment For example consider the costs associated with using a web control as opposed to a HTML based control Use plain HTML controls instead of adopting web controls for simple items like label

ESRI White Paper 23

If you choose to use the ActiveX connector from within the NET environment make sure that you clearly understand the essentials of COM Interop and the various costs associated with marshalling The solutions outlined in this paper utilize existing ArcIMS services and should work with all versions of ArcIMS

Although all the development can be done without the use of an Integrated Development environment (IDE) like Visual StudioNET using such an environment provides convenient WYSIWYG features that can help in building and debugging the application If you do not have Visual StudioNET there are free IDEs available today that can also be used For example ASPNET Web Matrix is a community-supported easy-to-use WYSIWYG application development tool for ASPNET It can be installed via a quick 12 MB download from httpwwwaspnetwebmatrixdefaultaspx

ESRI White Paper 24

  • ArcIMS ndash An Introduction
  • What is NET
    • The NET Framework
      • The Common Language Runtime (CLR)
      • Managed Unmanaged and Unsafe code ndash Understandin
      • NET Framework Class Libraries
        • ASPNET and Web Forms
          • NET and ArcIMS
            • Example 1
            • Example 2
            • Example 3
              • Accessing a COM Server from a NET Client
              • Summary
Page 7: Consuming ArcIMS Image Services using .NET Client Web ... · Consuming ArcIMS Image Services using .NET Client Web Applications An ESRI White Paper Ł October 2002 ... The .NET framework

NET Framework Class Libraries

The NET Framework class library is a collection of reusable types that tightly integrate with the common language runtime The class library is object oriented providing types from which your own managed code can derive functionality

The NET Framework types enable you to accomplish a range of common programming tasks including tasks such as string management data collection database connectivity and file access In addition to these common tasks the class library includes types that support a variety of specialized development scenarios This paper includes examples of class libraries created by ESRI that provide rich functionality for developers to inherit in their web applications

Also the examples shown in this paper make use of ASPNET and web forms technologies As you create applications in ASPNET you will find it convenient to use many of the classes provided as part of the web forms class library

As you become familiar with the classes in the NET framework you may want to create wrapper classes that provide functionality for XML parsing internet intranet connections that inherit from base classes in the NET framework By creating your own classes you can provide reusable componentized code for building other ArcIMS client applications that require similar functionality

NET programs are deployed as assemblies An assembly is one or more EXEs or DLLs with associated metadata information The metadata about the entire assembly is stored in the assemblys manifest The manifest contains for example a list of assemblies upon which the current assembly is dependant The concept of assemblies how they can be deployed privately or publicly how they can be versioned etc is quite complex and are not discussed in this paper As always the internet serves as good source for information regarding these topics

ASPNET and Web Forms

The various web applications shown in this paper were all built using ASPNET ASPNET is the hosting environment that enables developers to use the NET Framework to target Web-based applications However ASPNET is more than just a runtime host it is a complete architecture for developing Web sites and Internet-distributed objects using managed code Both Web Forms and XML Web services use IIS and ASPNET as the publishing mechanism for applications and both have a collection of supporting classes in the NET Framework If you have used earlier versions of ASP technology it is easy to note the improvements provided by ASPNET and Web Forms For example you can develop Web Forms pages in any language that supports the NET Framework In addition ASPNET no longer needs to share the same file with your HTTP text (although it can continue to do so if you

ESRI White Paper 4

prefer) Unlike unmanaged ASP code that is always scripted and interpreted ASPNET pages are faster and easier to manage as they execute in native machine language and interact with the runtime like any managed application To summarize here are a few benefits to programming with ASPNET

Object Orientation and a large class library from which to inherit functionality Can use multiple programming languages VBNET C etc Code is always

compiled before it is run Web Forms and Web Controls present the programmer with an event driven

model very similar to the desktop environment Server side controls intelligently render html code appropriate to the target browser

Advanced crash-recovery and detection and isolation of rogue code damaging the system

Scalable architecture with extensive caching to reduce running lots of identical code for each website visitor

Debugging is much easier especially when the programming is done using an IDE like Visual StudioNet

The NET programming environment provides very good database and XML support

MSIL and the new assembly model makes deploying applications and versioning complexities an issue of the past

Provides tools to easily create webservices All the plumbing code required is effectively hidden

The diagram below shows the typical sequence of calls made during a request response cycle for a ASPNET web page Notice that the first request-response cycle is shown by steps 1 through 6 and subsequent calls are displayed as steps 7-10

ESRI White Paper 5

Because ASPNET uses compiled code instead of interpreted code subsequent requests will check to see if there has been any change to the code If not it will utilize the script engine cache to access the compiled version of the code

NET and ArcIMS In order to better understand how to build map services using ArcIMS and the NET environment this paper presents the concepts in a series of three examples The examples all written using NET compatible languages (VBNET and C) demonstrate web applications that display map images served up ESRIs ArcIMS product The examples chosen are such that they provide a good handle on the various aspects of designing web applications that server as clients to the ArcIMS Image Service The following are a brief description of the three examples

Example 1 An ASPNET application written in VBNET that utilizes COM Interop to access the functionality exposed by the ActiveX connector

Example 2 An ASPNET application written in VBNET that makes use of special classes (also developed in VBNET) to send and receive requests via the Servlet connector in ArcIMS This example also contains code that shows you how to capture page coordinates from a mouse click event on the image map control It also shows the

ESRI White Paper 6

necessary steps to convert the obtained page coordinates to map coordinates for subsequent use in zoom operations

Example 3 An ASPNET application written in C that makes use of special classes developed in C This example utilizes two approaches one using the Servlet connector and another using a C wrapper to the ActiveX connector to connect to the service using TCP

Example 1

This application is a very simple web application that demonstrates the use of an image control in a web form to display a map image served up by ArcIMS The button control reads State Names from a database and populates the DropDownList Selecting a State from the DropDownList highlights the state in the map

This example demonstrates the following

Basic web form and web controls Button Image and DropDownListcontrols Using the ActiveX connector in a NET web application using COM Interop

ESRI White Paper 7

Connecting to an access database to read a list of names (from a column) This list is then used to populate a drop down list box

Using the image control to view an image rendered by ArcIMS

ASPNET and Web Forms Programming Environment

Visual Basic NET Programming Language

Data Files

File Name Comment BPC 2002mdb Database file with a column containing state names World30stateslakescountry Shape files BPC_STATESaxl Axl file for the image service

WebForm Controls

Control Name Function ImageButton1 Control for displaying the image Button Populates the Dropdown Listbox with State Names read from the

database DropDownList1 Set AutoPostback property to TRUE

Steps to Create Application

Create a new Project Choose Visual Basic Project -gt ASPNET web application

Add Project References

ESRI White Paper 8

o Project Add References COM ArcIMS ActiveX Connector (Aims_ActiveXdll)

o Project Add References NET adodb ( adodbdll)

Add controls to the form and set the appropriate properties (NameCaption Size etc)

Right click on the WebForm1aspx file and choose Viewcode Type the code shown below Click on Build-gtSolution Press CTRL+F5 to start without debugging or F5 to Start (with debugging)

ESRI White Paper 9

Code from Web Form1aspxvb the codebehind page for the Web Form

Define and instantiate class variables Refer to the Section Accessing a COM Server from a NET Client for a discussion on using early and late binding mechanisms to instantiate COM objects

Private mapStates As aimsMap()

Private conArcIMS As aimsArcIMSConnector()

The Page_Load event sets up the connection and map parameters It also links the image URL (provided by ArcIMS) to the URL property of the Image control to display the map image

Private Sub Page_load(ByVal sender As SystemObject ByVal e As SystemEventArgs) Handles MyBaseLoad mapStates = New aimsMap() conArcIMS = New aimsArcIMSConnector() conArcIMSServerName = localhost conArcIMSServerPort = 5300 mapStatesInitMap(conArcIMS BPC_States) mapStatesWidth = 550 mapStatesHeight = 400 mapStatesRefresh()

ESRI White Paper 10

ImageButton1ImageUrl = mapStatesGetImageAsUrl

End Sub

The Button Click event makes a connection to the bpc2002mdb access database It then reads the data from the States column orders it alphabetically and then populates the DropDownList control with the ordered list of entries

Private Sub Button1_Click(ByVal sender As SystemObject ByVal e As SystemEventArgs) Handles Button1Click Dim conDB As OleDbOleDbConnection Dim cmdFetch As OleDbOleDbCommand Dim rdrStates As OleDbOleDbDataReader Dim sCon As String = Provider=MicrosoftJetOLEDB40Data Source=CArcIMSWebsiteBPC_Statesbpc2002mdb conDB = New OleDbOleDbConnection(sCon) conDBOpen() cmdFetch = New OleDbOleDbCommand(SELECT STATE_NAME FROM STATES ORDER BY STATE_NAME) cmdFetchConnection = conDB rdrStates = cmdFetchExecuteReader() While rdrStatesRead() DropDownList1ItemsAdd(New ListItem(rdrStatesGetString(0))) End While conDBClose()

End Sub

The DropDownList fires a SelectedIndexChanged event The code associated with this event uses the where expression with LayersItem()Filter to create an image with a special highlight applied to the selected state The URL of the image is linked to the image buttons URL to display the new image

Private Sub DropDownList1_SelectedIndexChanged(ByVal sender As Object ByVal e As SystemEventArgs) Handles DropDownList1SelectedIndexChanged Dim sWhere As String = STATE_NAME = amp DropDownList1SelectedItemText amp mapStatesLayersItem(4)FilterWhereExpression = sWhere mapStatesRefresh() ImageButton1ImageUrl = mapStatesGetImageAsUrl End Sub

The Page_Unload event is used for clean up code Here it is used to free memory by setting the map and connection object to Nothing

ESRI White Paper 11

Private Sub Page_unload(ByVal sender As Object ByVal e As SystemEventArgs) Handles MyBaseUnload mapStates = Nothing conArcIMS = Nothing

End Sub

Example 2

General Description

This web application demonstrates the use of two image controls in a web form to display a map image and its associated legend both images being served up by ArcIMS The web application also has controls for Zoomin Zoomout and pan

Programming Environment ASPNET and Web Forms

Programming Language Visual Basic NET

WebForm Controls

ESRI White Paper 12

Control Name Function ImgMap Control for displaying the image ImgLegend Control for displaying the legend image lstNavControls Radiobutton list controls

Data Files

Can use any datafile capable of generating an image service Replace the sf parameter in the page_load event with the appropriate image service name

Class Libraries ( Logic_classes assembly)

File Name Class Information Functionality MapVB The Cmap class has a

MustInherit Keyword and is inherited by Cviewer The MustInherit keyword specifies that a class cannot be instantiated and can be used only as a base class

PointVB Used by Cmap Crect Represents a geometric point (xy pair ) RectVB Used by Cmap Cviewer and

Webform3 in testformaspx

ViewerVB Used in Webform3 in testformaspx

Abstracts the requesting of a simple map from ArcIMS No additional entities will be added to the map (ie graphics buffer etc) The map is requested with all the default parameters with which it is served excepting extent and background color

Steps to Create Application

ESRI White Paper 13

The following section details the code found in the code behind page of the Testformaspx page

Statement to import logic_classes Makes all the functionality available in the logic_classes project available to the code in the web form

Imports logic_classes

Define a class level variable in the aspx file

Private m_objViewerMap As cViewer

Code for the page load event Uses IsPostback to determine if the extents need to be read afresh or from a previous valued stored in the session object Also instantiates the Cviewer class object You need to make sure that the extents shown in the code are appropriately changed to work with your selected image service

Private Sub Page_Load(ByVal sender As SystemObject ByVal e As SystemEventArgs) Handles MyBaseLoad

ESRI White Paper 14

Put user code to initialize the page here Dim rctExtent As cRect If Not IsPostBack Then enter appropriate extents rctExtent = New cRect(-1225173 377199 -122363678 3780374) Else rctExtent = New cRect(Session(MinX) Session(MinY) Session(MaxX) Session(MaxY)) End If m_objViewerMap = New cViewer(httplocalhostservletcomesriesrimapEsrimap _ sf _ rctExtent _ imgMapWidthValue _ imgMapHeightValue _ 000) add test markers

End Sub

Page_Prerender event code Links the output image to the Picture controls Also since HTTP is a stateless protocol the current map extents are stored in session variables for follow-up requests from the same user

Private Sub Page_PreRender(ByVal sender As Object ByVal e As SystemEventArgs) Handles MyBasePreRender imgMapImageUrl = m_objViewerMapMap() imgLegendImageUrl = m_objViewerMapLegend() Session(MinX) = m_objViewerMapExtentXMin Session(MinY) = m_objViewerMapExtentYMin Session(MaxX) = m_objViewerMapExtentXMax Session(MaxY) = m_objViewerMapExtentYMax

End Sub

Imgmap_click event is raised when the user clicks on the map Code associated with this event converts the image click coordinate to a map coordinate Then

ESRI White Paper 15

based on the radio button selection ( Zoomin Zoomout or pan) the code calls the appropriate method using the instantiated Cviewer object

Private Sub imgMap_Click(ByVal sender As Object ByVal e As SystemWebUIImageClickEventArgs) Handles imgMapClick Convert the image click coordinate to a map coordinate based on the maps current extent Dim rctCurrentExtent As cRect = m_objViewerMapExtent Dim dblX As Double = rctCurrentExtentXMin + ((eX imgMapWidthValue) (rctCurrentExtentXMax - rctCurrentExtentXMin)) Dim dblY As Double = rctCurrentExtentYMin + (((imgMapHeightValue - eY) imgMapHeightValue) (rctCurrentExtentYMax - rctCurrentExtentYMin)) If Trim(UCase(lstNavControlsSelectedItemText)) ltgt IDENTIFY Then m_objViewerMapCenterAt(dblX dblY) Select Case UCase(lstNavControlsSelectedItemText) Case ZOOM IN Center the map m_objViewerMapZoom(-1) Case ZOOM OUT m_objViewerMapZoom(1) Case PAN do nothing Case Else ErrRaise(vbObjectError + 512 imgMap_Click Invalid command) End Select Else identify End If End Sub

ESRI White Paper 16

End Class

NOTE =gt Once you have the relevant files imported into Visual Studio make sure that you configure the virtual directory as an application before you run the example

If the virtual directory is not configured as an Application you will get an error message that reads This error can be caused by a virtual directory not being configured as an application in IIS To configure a Virtual directory is simple Use the Internet Service Manager to perform the following steps

Find the folder in the virtual directory Right click and choose properties Click Create Accept all the settings and Click OK

Example 3

General Description

The program uses the catalog service (using the ltGETCLIENTSERVICESgt request) to query and list a collection of services running on the server A Radiobutton list control is used to list all the service names running on the server On selecting an appropriate image service the map image is displayed on the web form using an image control This program demonstrates two different ways to connect to the datasource Connection could be achieved using the http protocol or the TCP protocol The TCP method utilizes the TCP capability built into the ActiveX Connector Since ASPNET is a multithreaded and the ActiveX connector being Single Threaded (STA) a wrapper class with additional functionality to manage memory is used to access the methods in the ActiveX connector

ESRI White Paper 17

Programming Environment ASPNET and Web Forms

C NET Programming Language

WebForm Controls

Control Name Function ImgMap Control for displaying the image RbServices Radiobutton list controls Txtinfo Displays the name of the selected image service

Data Files

Requires a collection of image services running on an ArcIMS server The program uses the ltGETCLIENTSERVICESgt request tag to query the catalog service to list all the services running on the specified server

Class Libraries

File Name Class Information Functionality Connectioncs Abstract base class Provides abstract method

templates for the HTTPConnection and

ESRI White Paper 18

TCPConnection classes HTTPConnectioncs Inherits from Connection class Provides functionality for

sending request to service postinggetting URL content etc

TCPConnectioncs Inherits from Connection class and SystemIDisposable

Utlizes the AICLib assembly to access connection functionality built into the ActiveX connector

Datasourcecs Provides method for accessing path port host and other information

Enumerationscs Provides enumerations for AccessType and LoadType

Envelopecs Provides methods for getting and setting xy coordinates of the envelope

ImageReturnObjectcs Provides methods for settinggetting image URL image envelope and image scale

Mapcs Calls send request to service with connection and service information Parses response to obtain image URL

Servicecs Servicescs Inherits from

SystemCollectionsHashtable Composes the clientservices request and parses the response Creates a hashtable association of individual service name with its associated service object

XML helper class that provides relevant XML parsing functionality by acting as a wrapper class around NETs xml Text IO and other NET classes

XMLRequestscs Builds ArcXML strings for requests

XMLHelpercs

Steps to Create Application

ESRI White Paper 19

The NET solution contains 2 projects ArcIMS and ArcIMSSample The ArcIMS project

o References the InteropAICLib o Contains NET ArcIMS class libraries that can be used to connect and to

work with image services The ArcIMSSample project

o References the ArcIMS project o Contains the web form (webform1aspx) and the corresponding

webform1aspxcs code-behind page that connects the web page controls to relevant functionality using an event driven web forms model

Points to Note

In webform1aspxcs code session variables are used to maintain state of serialized objects In order for this to be possible notice that the relevant classes have been marked as serializable

ESRI White Paper 20

Choose the appropriate connection type based on HTTP or TCP connection For HTTP choose m_dsConnectType = ConnectionTypeInterNet and for For TCP select m_dsConnectType = ConnectionTypeIntraNet as shown in the code below

private ArcIMSDataSource getDataSource() m_ds = Session[datasource] as ArcIMSDataSource if ( m_ds == null ) m_ds = new ArcIMSDataSource() m_dsHost = localhost m_dsScheme = http m_dsPort = 80 m_dsAppServerPort = 5300 m_dsPath = servletcomesriesrimapEsrimap choose (comment uncomment) one of the following two statements to decide between TCP or HTTP type connection m_dsConnectType = ConnectionTypeIntraNet m_dsConnectType = ConnectionTypeInterNet SessionAdd(datasource m_ds) return m_ds

Accessing a COM Server from a NET Client With the introduction of the NET Framework and ASPNET COM at its basic level has not really changed Nevertheless there are a couple of issues to be aware of when making calls to a COM object from a NET managed code environment The ASPNET threading model is the Multiple Threaded Apartment (MTA) This will not interact reliably with STA components (the ActiveX connector provided with the ArcIMS setup was built as an STA component) To emphasize this issue heres a direct quote from the MSDN pages at Microsoft The ASPNET threading model is the Multiple Threaded Apartment (MTA) What this means is that components that you are using that were created for the Single Threaded Apartment (STA) will no longer perform or function reliably without taking some extra precautions in ASPNET This includes but is not limited to all COM components that have been created using Visual Basic 60 and earlier versions

To understand the issues better let us take a look at how NET deals with COM related issues The Common Language Runtime exposes COM objects through a proxy called the runtime callable wrapper (RCW) The RCWs primary function is to marshal calls between a NET client and COM object The RCW object is nothing but an object instantiated at runtime from class code contained in the Interop assembly

ESRI White Paper 21

Calling between managed and unmanaged components incurs a marshaling cost which can impede the performance of your pages When a managed client and unmanaged server are in the same apartment the Interop marshalling service handles all data marshalling However when client and server are initialized in different apartments COM marshalling is also required Therefore interoperability with COM from a NET client should take into consideration the threading model used

Figure Cross-apartment call between a NET client and COM object

As mentioned earlier ASPNET follows an MTA model by default You could use the default model to communicate with an STA COM component if there is not much of an overhead due to the cross-apartment marshalling Usually this is noticeable only when there are many calls across the boundary Another option would be to use the PageAspCompatMode property of the ASPNET client The ASPCompat=true attribute enables an STA thread pool to address performance with existing Visual Basic components on a per-page basis The runtime throws an exception if the compatibility tag is omitted and an STA component is referenced on the page If you convert the STA component to an assembly using Type Library Importer (a utility included with the NET SDK) the runtime does not detect that the component uses the STA model and does not throw an exception but your application can suffer from poor performance and possible deadlocks STA components cannot be used from NET Framework code modules (compiled NET assemblies) they can be used only from ASPNET pages

If you plan to use the ASPCOMPAT = TRUE page level directive for Example 1 remember to instantiate the COM object within the page_load event rather than constructing COM components during page construction time For example look at code examples A and B

Example A Example B ltPage Language = VB ASPCOMPAT = truegt

ltscript runat = servergt

private mapStates as new aimsMap()

private sub_load ()

ltPage Language = VB ASPCOMPAT = truegt

ltscript runat = servergt

private mapStates as aimsMap()

private sub_load ()

ESRI White Paper 22

end sub

mapStates = new aimsMap()

end sub

In example A the STA component would be instantiated at page construction time which is created from a thread that is not the STA thread that will run the page This will involve marshalling between MTA and STA threads during the construction of the page Example B shows the preferred mechanism to delay the process until later when the code executes under a STA thread It is best to construct any COM component and external resources when needed or in the Page_Load method

Also to create the object you can use either the New keyword or the CreateObject method The CreateObject method is typically used when you dont know the Program ID (ProgID) of the object you are going to create until run time (late binding) New is the recommended method for instantiating objects if you have access to the objects type library It is preferable to adopt the early binding model

Every scenario yields different performance characteristics so it is important to test adequately before deciding whether interoperability is the right choice for your application However in nearly all scenarios rewriting your COM components in managed code provides performance benefits

Summary The examples shown above provide adequate information to leverage the NET programming environment to build effective ArcIMS client applications The debugging features of a program like Visual StudioNET provide a variety of tools (break points trace etc) making the entire development experience considerably pain-free Use the debugger to understand the sequence in which calls are made One early exercise would be to look at the calling sequence of the various page related events such as page_init page_load and page_prerender Since the Web Forms code is compiled you should experience much better performance than with ASP pages that used code written in scripting languages like Javascript and VbScript

The powerful programming environment also means that you can now concentrate more on the logic of building large web applications as opposed to building simple page based asp applications Also look at the various caching mechanisms provided by ASPNET as these can be used to improve overall performance As always there are costs associated with most programming choices and this is all the more true in a web-programming environment For example consider the costs associated with using a web control as opposed to a HTML based control Use plain HTML controls instead of adopting web controls for simple items like label

ESRI White Paper 23

If you choose to use the ActiveX connector from within the NET environment make sure that you clearly understand the essentials of COM Interop and the various costs associated with marshalling The solutions outlined in this paper utilize existing ArcIMS services and should work with all versions of ArcIMS

Although all the development can be done without the use of an Integrated Development environment (IDE) like Visual StudioNET using such an environment provides convenient WYSIWYG features that can help in building and debugging the application If you do not have Visual StudioNET there are free IDEs available today that can also be used For example ASPNET Web Matrix is a community-supported easy-to-use WYSIWYG application development tool for ASPNET It can be installed via a quick 12 MB download from httpwwwaspnetwebmatrixdefaultaspx

ESRI White Paper 24

  • ArcIMS ndash An Introduction
  • What is NET
    • The NET Framework
      • The Common Language Runtime (CLR)
      • Managed Unmanaged and Unsafe code ndash Understandin
      • NET Framework Class Libraries
        • ASPNET and Web Forms
          • NET and ArcIMS
            • Example 1
            • Example 2
            • Example 3
              • Accessing a COM Server from a NET Client
              • Summary
Page 8: Consuming ArcIMS Image Services using .NET Client Web ... · Consuming ArcIMS Image Services using .NET Client Web Applications An ESRI White Paper Ł October 2002 ... The .NET framework

prefer) Unlike unmanaged ASP code that is always scripted and interpreted ASPNET pages are faster and easier to manage as they execute in native machine language and interact with the runtime like any managed application To summarize here are a few benefits to programming with ASPNET

Object Orientation and a large class library from which to inherit functionality Can use multiple programming languages VBNET C etc Code is always

compiled before it is run Web Forms and Web Controls present the programmer with an event driven

model very similar to the desktop environment Server side controls intelligently render html code appropriate to the target browser

Advanced crash-recovery and detection and isolation of rogue code damaging the system

Scalable architecture with extensive caching to reduce running lots of identical code for each website visitor

Debugging is much easier especially when the programming is done using an IDE like Visual StudioNet

The NET programming environment provides very good database and XML support

MSIL and the new assembly model makes deploying applications and versioning complexities an issue of the past

Provides tools to easily create webservices All the plumbing code required is effectively hidden

The diagram below shows the typical sequence of calls made during a request response cycle for a ASPNET web page Notice that the first request-response cycle is shown by steps 1 through 6 and subsequent calls are displayed as steps 7-10

ESRI White Paper 5

Because ASPNET uses compiled code instead of interpreted code subsequent requests will check to see if there has been any change to the code If not it will utilize the script engine cache to access the compiled version of the code

NET and ArcIMS In order to better understand how to build map services using ArcIMS and the NET environment this paper presents the concepts in a series of three examples The examples all written using NET compatible languages (VBNET and C) demonstrate web applications that display map images served up ESRIs ArcIMS product The examples chosen are such that they provide a good handle on the various aspects of designing web applications that server as clients to the ArcIMS Image Service The following are a brief description of the three examples

Example 1 An ASPNET application written in VBNET that utilizes COM Interop to access the functionality exposed by the ActiveX connector

Example 2 An ASPNET application written in VBNET that makes use of special classes (also developed in VBNET) to send and receive requests via the Servlet connector in ArcIMS This example also contains code that shows you how to capture page coordinates from a mouse click event on the image map control It also shows the

ESRI White Paper 6

necessary steps to convert the obtained page coordinates to map coordinates for subsequent use in zoom operations

Example 3 An ASPNET application written in C that makes use of special classes developed in C This example utilizes two approaches one using the Servlet connector and another using a C wrapper to the ActiveX connector to connect to the service using TCP

Example 1

This application is a very simple web application that demonstrates the use of an image control in a web form to display a map image served up by ArcIMS The button control reads State Names from a database and populates the DropDownList Selecting a State from the DropDownList highlights the state in the map

This example demonstrates the following

Basic web form and web controls Button Image and DropDownListcontrols Using the ActiveX connector in a NET web application using COM Interop

ESRI White Paper 7

Connecting to an access database to read a list of names (from a column) This list is then used to populate a drop down list box

Using the image control to view an image rendered by ArcIMS

ASPNET and Web Forms Programming Environment

Visual Basic NET Programming Language

Data Files

File Name Comment BPC 2002mdb Database file with a column containing state names World30stateslakescountry Shape files BPC_STATESaxl Axl file for the image service

WebForm Controls

Control Name Function ImageButton1 Control for displaying the image Button Populates the Dropdown Listbox with State Names read from the

database DropDownList1 Set AutoPostback property to TRUE

Steps to Create Application

Create a new Project Choose Visual Basic Project -gt ASPNET web application

Add Project References

ESRI White Paper 8

o Project Add References COM ArcIMS ActiveX Connector (Aims_ActiveXdll)

o Project Add References NET adodb ( adodbdll)

Add controls to the form and set the appropriate properties (NameCaption Size etc)

Right click on the WebForm1aspx file and choose Viewcode Type the code shown below Click on Build-gtSolution Press CTRL+F5 to start without debugging or F5 to Start (with debugging)

ESRI White Paper 9

Code from Web Form1aspxvb the codebehind page for the Web Form

Define and instantiate class variables Refer to the Section Accessing a COM Server from a NET Client for a discussion on using early and late binding mechanisms to instantiate COM objects

Private mapStates As aimsMap()

Private conArcIMS As aimsArcIMSConnector()

The Page_Load event sets up the connection and map parameters It also links the image URL (provided by ArcIMS) to the URL property of the Image control to display the map image

Private Sub Page_load(ByVal sender As SystemObject ByVal e As SystemEventArgs) Handles MyBaseLoad mapStates = New aimsMap() conArcIMS = New aimsArcIMSConnector() conArcIMSServerName = localhost conArcIMSServerPort = 5300 mapStatesInitMap(conArcIMS BPC_States) mapStatesWidth = 550 mapStatesHeight = 400 mapStatesRefresh()

ESRI White Paper 10

ImageButton1ImageUrl = mapStatesGetImageAsUrl

End Sub

The Button Click event makes a connection to the bpc2002mdb access database It then reads the data from the States column orders it alphabetically and then populates the DropDownList control with the ordered list of entries

Private Sub Button1_Click(ByVal sender As SystemObject ByVal e As SystemEventArgs) Handles Button1Click Dim conDB As OleDbOleDbConnection Dim cmdFetch As OleDbOleDbCommand Dim rdrStates As OleDbOleDbDataReader Dim sCon As String = Provider=MicrosoftJetOLEDB40Data Source=CArcIMSWebsiteBPC_Statesbpc2002mdb conDB = New OleDbOleDbConnection(sCon) conDBOpen() cmdFetch = New OleDbOleDbCommand(SELECT STATE_NAME FROM STATES ORDER BY STATE_NAME) cmdFetchConnection = conDB rdrStates = cmdFetchExecuteReader() While rdrStatesRead() DropDownList1ItemsAdd(New ListItem(rdrStatesGetString(0))) End While conDBClose()

End Sub

The DropDownList fires a SelectedIndexChanged event The code associated with this event uses the where expression with LayersItem()Filter to create an image with a special highlight applied to the selected state The URL of the image is linked to the image buttons URL to display the new image

Private Sub DropDownList1_SelectedIndexChanged(ByVal sender As Object ByVal e As SystemEventArgs) Handles DropDownList1SelectedIndexChanged Dim sWhere As String = STATE_NAME = amp DropDownList1SelectedItemText amp mapStatesLayersItem(4)FilterWhereExpression = sWhere mapStatesRefresh() ImageButton1ImageUrl = mapStatesGetImageAsUrl End Sub

The Page_Unload event is used for clean up code Here it is used to free memory by setting the map and connection object to Nothing

ESRI White Paper 11

Private Sub Page_unload(ByVal sender As Object ByVal e As SystemEventArgs) Handles MyBaseUnload mapStates = Nothing conArcIMS = Nothing

End Sub

Example 2

General Description

This web application demonstrates the use of two image controls in a web form to display a map image and its associated legend both images being served up by ArcIMS The web application also has controls for Zoomin Zoomout and pan

Programming Environment ASPNET and Web Forms

Programming Language Visual Basic NET

WebForm Controls

ESRI White Paper 12

Control Name Function ImgMap Control for displaying the image ImgLegend Control for displaying the legend image lstNavControls Radiobutton list controls

Data Files

Can use any datafile capable of generating an image service Replace the sf parameter in the page_load event with the appropriate image service name

Class Libraries ( Logic_classes assembly)

File Name Class Information Functionality MapVB The Cmap class has a

MustInherit Keyword and is inherited by Cviewer The MustInherit keyword specifies that a class cannot be instantiated and can be used only as a base class

PointVB Used by Cmap Crect Represents a geometric point (xy pair ) RectVB Used by Cmap Cviewer and

Webform3 in testformaspx

ViewerVB Used in Webform3 in testformaspx

Abstracts the requesting of a simple map from ArcIMS No additional entities will be added to the map (ie graphics buffer etc) The map is requested with all the default parameters with which it is served excepting extent and background color

Steps to Create Application

ESRI White Paper 13

The following section details the code found in the code behind page of the Testformaspx page

Statement to import logic_classes Makes all the functionality available in the logic_classes project available to the code in the web form

Imports logic_classes

Define a class level variable in the aspx file

Private m_objViewerMap As cViewer

Code for the page load event Uses IsPostback to determine if the extents need to be read afresh or from a previous valued stored in the session object Also instantiates the Cviewer class object You need to make sure that the extents shown in the code are appropriately changed to work with your selected image service

Private Sub Page_Load(ByVal sender As SystemObject ByVal e As SystemEventArgs) Handles MyBaseLoad

ESRI White Paper 14

Put user code to initialize the page here Dim rctExtent As cRect If Not IsPostBack Then enter appropriate extents rctExtent = New cRect(-1225173 377199 -122363678 3780374) Else rctExtent = New cRect(Session(MinX) Session(MinY) Session(MaxX) Session(MaxY)) End If m_objViewerMap = New cViewer(httplocalhostservletcomesriesrimapEsrimap _ sf _ rctExtent _ imgMapWidthValue _ imgMapHeightValue _ 000) add test markers

End Sub

Page_Prerender event code Links the output image to the Picture controls Also since HTTP is a stateless protocol the current map extents are stored in session variables for follow-up requests from the same user

Private Sub Page_PreRender(ByVal sender As Object ByVal e As SystemEventArgs) Handles MyBasePreRender imgMapImageUrl = m_objViewerMapMap() imgLegendImageUrl = m_objViewerMapLegend() Session(MinX) = m_objViewerMapExtentXMin Session(MinY) = m_objViewerMapExtentYMin Session(MaxX) = m_objViewerMapExtentXMax Session(MaxY) = m_objViewerMapExtentYMax

End Sub

Imgmap_click event is raised when the user clicks on the map Code associated with this event converts the image click coordinate to a map coordinate Then

ESRI White Paper 15

based on the radio button selection ( Zoomin Zoomout or pan) the code calls the appropriate method using the instantiated Cviewer object

Private Sub imgMap_Click(ByVal sender As Object ByVal e As SystemWebUIImageClickEventArgs) Handles imgMapClick Convert the image click coordinate to a map coordinate based on the maps current extent Dim rctCurrentExtent As cRect = m_objViewerMapExtent Dim dblX As Double = rctCurrentExtentXMin + ((eX imgMapWidthValue) (rctCurrentExtentXMax - rctCurrentExtentXMin)) Dim dblY As Double = rctCurrentExtentYMin + (((imgMapHeightValue - eY) imgMapHeightValue) (rctCurrentExtentYMax - rctCurrentExtentYMin)) If Trim(UCase(lstNavControlsSelectedItemText)) ltgt IDENTIFY Then m_objViewerMapCenterAt(dblX dblY) Select Case UCase(lstNavControlsSelectedItemText) Case ZOOM IN Center the map m_objViewerMapZoom(-1) Case ZOOM OUT m_objViewerMapZoom(1) Case PAN do nothing Case Else ErrRaise(vbObjectError + 512 imgMap_Click Invalid command) End Select Else identify End If End Sub

ESRI White Paper 16

End Class

NOTE =gt Once you have the relevant files imported into Visual Studio make sure that you configure the virtual directory as an application before you run the example

If the virtual directory is not configured as an Application you will get an error message that reads This error can be caused by a virtual directory not being configured as an application in IIS To configure a Virtual directory is simple Use the Internet Service Manager to perform the following steps

Find the folder in the virtual directory Right click and choose properties Click Create Accept all the settings and Click OK

Example 3

General Description

The program uses the catalog service (using the ltGETCLIENTSERVICESgt request) to query and list a collection of services running on the server A Radiobutton list control is used to list all the service names running on the server On selecting an appropriate image service the map image is displayed on the web form using an image control This program demonstrates two different ways to connect to the datasource Connection could be achieved using the http protocol or the TCP protocol The TCP method utilizes the TCP capability built into the ActiveX Connector Since ASPNET is a multithreaded and the ActiveX connector being Single Threaded (STA) a wrapper class with additional functionality to manage memory is used to access the methods in the ActiveX connector

ESRI White Paper 17

Programming Environment ASPNET and Web Forms

C NET Programming Language

WebForm Controls

Control Name Function ImgMap Control for displaying the image RbServices Radiobutton list controls Txtinfo Displays the name of the selected image service

Data Files

Requires a collection of image services running on an ArcIMS server The program uses the ltGETCLIENTSERVICESgt request tag to query the catalog service to list all the services running on the specified server

Class Libraries

File Name Class Information Functionality Connectioncs Abstract base class Provides abstract method

templates for the HTTPConnection and

ESRI White Paper 18

TCPConnection classes HTTPConnectioncs Inherits from Connection class Provides functionality for

sending request to service postinggetting URL content etc

TCPConnectioncs Inherits from Connection class and SystemIDisposable

Utlizes the AICLib assembly to access connection functionality built into the ActiveX connector

Datasourcecs Provides method for accessing path port host and other information

Enumerationscs Provides enumerations for AccessType and LoadType

Envelopecs Provides methods for getting and setting xy coordinates of the envelope

ImageReturnObjectcs Provides methods for settinggetting image URL image envelope and image scale

Mapcs Calls send request to service with connection and service information Parses response to obtain image URL

Servicecs Servicescs Inherits from

SystemCollectionsHashtable Composes the clientservices request and parses the response Creates a hashtable association of individual service name with its associated service object

XML helper class that provides relevant XML parsing functionality by acting as a wrapper class around NETs xml Text IO and other NET classes

XMLRequestscs Builds ArcXML strings for requests

XMLHelpercs

Steps to Create Application

ESRI White Paper 19

The NET solution contains 2 projects ArcIMS and ArcIMSSample The ArcIMS project

o References the InteropAICLib o Contains NET ArcIMS class libraries that can be used to connect and to

work with image services The ArcIMSSample project

o References the ArcIMS project o Contains the web form (webform1aspx) and the corresponding

webform1aspxcs code-behind page that connects the web page controls to relevant functionality using an event driven web forms model

Points to Note

In webform1aspxcs code session variables are used to maintain state of serialized objects In order for this to be possible notice that the relevant classes have been marked as serializable

ESRI White Paper 20

Choose the appropriate connection type based on HTTP or TCP connection For HTTP choose m_dsConnectType = ConnectionTypeInterNet and for For TCP select m_dsConnectType = ConnectionTypeIntraNet as shown in the code below

private ArcIMSDataSource getDataSource() m_ds = Session[datasource] as ArcIMSDataSource if ( m_ds == null ) m_ds = new ArcIMSDataSource() m_dsHost = localhost m_dsScheme = http m_dsPort = 80 m_dsAppServerPort = 5300 m_dsPath = servletcomesriesrimapEsrimap choose (comment uncomment) one of the following two statements to decide between TCP or HTTP type connection m_dsConnectType = ConnectionTypeIntraNet m_dsConnectType = ConnectionTypeInterNet SessionAdd(datasource m_ds) return m_ds

Accessing a COM Server from a NET Client With the introduction of the NET Framework and ASPNET COM at its basic level has not really changed Nevertheless there are a couple of issues to be aware of when making calls to a COM object from a NET managed code environment The ASPNET threading model is the Multiple Threaded Apartment (MTA) This will not interact reliably with STA components (the ActiveX connector provided with the ArcIMS setup was built as an STA component) To emphasize this issue heres a direct quote from the MSDN pages at Microsoft The ASPNET threading model is the Multiple Threaded Apartment (MTA) What this means is that components that you are using that were created for the Single Threaded Apartment (STA) will no longer perform or function reliably without taking some extra precautions in ASPNET This includes but is not limited to all COM components that have been created using Visual Basic 60 and earlier versions

To understand the issues better let us take a look at how NET deals with COM related issues The Common Language Runtime exposes COM objects through a proxy called the runtime callable wrapper (RCW) The RCWs primary function is to marshal calls between a NET client and COM object The RCW object is nothing but an object instantiated at runtime from class code contained in the Interop assembly

ESRI White Paper 21

Calling between managed and unmanaged components incurs a marshaling cost which can impede the performance of your pages When a managed client and unmanaged server are in the same apartment the Interop marshalling service handles all data marshalling However when client and server are initialized in different apartments COM marshalling is also required Therefore interoperability with COM from a NET client should take into consideration the threading model used

Figure Cross-apartment call between a NET client and COM object

As mentioned earlier ASPNET follows an MTA model by default You could use the default model to communicate with an STA COM component if there is not much of an overhead due to the cross-apartment marshalling Usually this is noticeable only when there are many calls across the boundary Another option would be to use the PageAspCompatMode property of the ASPNET client The ASPCompat=true attribute enables an STA thread pool to address performance with existing Visual Basic components on a per-page basis The runtime throws an exception if the compatibility tag is omitted and an STA component is referenced on the page If you convert the STA component to an assembly using Type Library Importer (a utility included with the NET SDK) the runtime does not detect that the component uses the STA model and does not throw an exception but your application can suffer from poor performance and possible deadlocks STA components cannot be used from NET Framework code modules (compiled NET assemblies) they can be used only from ASPNET pages

If you plan to use the ASPCOMPAT = TRUE page level directive for Example 1 remember to instantiate the COM object within the page_load event rather than constructing COM components during page construction time For example look at code examples A and B

Example A Example B ltPage Language = VB ASPCOMPAT = truegt

ltscript runat = servergt

private mapStates as new aimsMap()

private sub_load ()

ltPage Language = VB ASPCOMPAT = truegt

ltscript runat = servergt

private mapStates as aimsMap()

private sub_load ()

ESRI White Paper 22

end sub

mapStates = new aimsMap()

end sub

In example A the STA component would be instantiated at page construction time which is created from a thread that is not the STA thread that will run the page This will involve marshalling between MTA and STA threads during the construction of the page Example B shows the preferred mechanism to delay the process until later when the code executes under a STA thread It is best to construct any COM component and external resources when needed or in the Page_Load method

Also to create the object you can use either the New keyword or the CreateObject method The CreateObject method is typically used when you dont know the Program ID (ProgID) of the object you are going to create until run time (late binding) New is the recommended method for instantiating objects if you have access to the objects type library It is preferable to adopt the early binding model

Every scenario yields different performance characteristics so it is important to test adequately before deciding whether interoperability is the right choice for your application However in nearly all scenarios rewriting your COM components in managed code provides performance benefits

Summary The examples shown above provide adequate information to leverage the NET programming environment to build effective ArcIMS client applications The debugging features of a program like Visual StudioNET provide a variety of tools (break points trace etc) making the entire development experience considerably pain-free Use the debugger to understand the sequence in which calls are made One early exercise would be to look at the calling sequence of the various page related events such as page_init page_load and page_prerender Since the Web Forms code is compiled you should experience much better performance than with ASP pages that used code written in scripting languages like Javascript and VbScript

The powerful programming environment also means that you can now concentrate more on the logic of building large web applications as opposed to building simple page based asp applications Also look at the various caching mechanisms provided by ASPNET as these can be used to improve overall performance As always there are costs associated with most programming choices and this is all the more true in a web-programming environment For example consider the costs associated with using a web control as opposed to a HTML based control Use plain HTML controls instead of adopting web controls for simple items like label

ESRI White Paper 23

If you choose to use the ActiveX connector from within the NET environment make sure that you clearly understand the essentials of COM Interop and the various costs associated with marshalling The solutions outlined in this paper utilize existing ArcIMS services and should work with all versions of ArcIMS

Although all the development can be done without the use of an Integrated Development environment (IDE) like Visual StudioNET using such an environment provides convenient WYSIWYG features that can help in building and debugging the application If you do not have Visual StudioNET there are free IDEs available today that can also be used For example ASPNET Web Matrix is a community-supported easy-to-use WYSIWYG application development tool for ASPNET It can be installed via a quick 12 MB download from httpwwwaspnetwebmatrixdefaultaspx

ESRI White Paper 24

  • ArcIMS ndash An Introduction
  • What is NET
    • The NET Framework
      • The Common Language Runtime (CLR)
      • Managed Unmanaged and Unsafe code ndash Understandin
      • NET Framework Class Libraries
        • ASPNET and Web Forms
          • NET and ArcIMS
            • Example 1
            • Example 2
            • Example 3
              • Accessing a COM Server from a NET Client
              • Summary
Page 9: Consuming ArcIMS Image Services using .NET Client Web ... · Consuming ArcIMS Image Services using .NET Client Web Applications An ESRI White Paper Ł October 2002 ... The .NET framework

Because ASPNET uses compiled code instead of interpreted code subsequent requests will check to see if there has been any change to the code If not it will utilize the script engine cache to access the compiled version of the code

NET and ArcIMS In order to better understand how to build map services using ArcIMS and the NET environment this paper presents the concepts in a series of three examples The examples all written using NET compatible languages (VBNET and C) demonstrate web applications that display map images served up ESRIs ArcIMS product The examples chosen are such that they provide a good handle on the various aspects of designing web applications that server as clients to the ArcIMS Image Service The following are a brief description of the three examples

Example 1 An ASPNET application written in VBNET that utilizes COM Interop to access the functionality exposed by the ActiveX connector

Example 2 An ASPNET application written in VBNET that makes use of special classes (also developed in VBNET) to send and receive requests via the Servlet connector in ArcIMS This example also contains code that shows you how to capture page coordinates from a mouse click event on the image map control It also shows the

ESRI White Paper 6

necessary steps to convert the obtained page coordinates to map coordinates for subsequent use in zoom operations

Example 3 An ASPNET application written in C that makes use of special classes developed in C This example utilizes two approaches one using the Servlet connector and another using a C wrapper to the ActiveX connector to connect to the service using TCP

Example 1

This application is a very simple web application that demonstrates the use of an image control in a web form to display a map image served up by ArcIMS The button control reads State Names from a database and populates the DropDownList Selecting a State from the DropDownList highlights the state in the map

This example demonstrates the following

Basic web form and web controls Button Image and DropDownListcontrols Using the ActiveX connector in a NET web application using COM Interop

ESRI White Paper 7

Connecting to an access database to read a list of names (from a column) This list is then used to populate a drop down list box

Using the image control to view an image rendered by ArcIMS

ASPNET and Web Forms Programming Environment

Visual Basic NET Programming Language

Data Files

File Name Comment BPC 2002mdb Database file with a column containing state names World30stateslakescountry Shape files BPC_STATESaxl Axl file for the image service

WebForm Controls

Control Name Function ImageButton1 Control for displaying the image Button Populates the Dropdown Listbox with State Names read from the

database DropDownList1 Set AutoPostback property to TRUE

Steps to Create Application

Create a new Project Choose Visual Basic Project -gt ASPNET web application

Add Project References

ESRI White Paper 8

o Project Add References COM ArcIMS ActiveX Connector (Aims_ActiveXdll)

o Project Add References NET adodb ( adodbdll)

Add controls to the form and set the appropriate properties (NameCaption Size etc)

Right click on the WebForm1aspx file and choose Viewcode Type the code shown below Click on Build-gtSolution Press CTRL+F5 to start without debugging or F5 to Start (with debugging)

ESRI White Paper 9

Code from Web Form1aspxvb the codebehind page for the Web Form

Define and instantiate class variables Refer to the Section Accessing a COM Server from a NET Client for a discussion on using early and late binding mechanisms to instantiate COM objects

Private mapStates As aimsMap()

Private conArcIMS As aimsArcIMSConnector()

The Page_Load event sets up the connection and map parameters It also links the image URL (provided by ArcIMS) to the URL property of the Image control to display the map image

Private Sub Page_load(ByVal sender As SystemObject ByVal e As SystemEventArgs) Handles MyBaseLoad mapStates = New aimsMap() conArcIMS = New aimsArcIMSConnector() conArcIMSServerName = localhost conArcIMSServerPort = 5300 mapStatesInitMap(conArcIMS BPC_States) mapStatesWidth = 550 mapStatesHeight = 400 mapStatesRefresh()

ESRI White Paper 10

ImageButton1ImageUrl = mapStatesGetImageAsUrl

End Sub

The Button Click event makes a connection to the bpc2002mdb access database It then reads the data from the States column orders it alphabetically and then populates the DropDownList control with the ordered list of entries

Private Sub Button1_Click(ByVal sender As SystemObject ByVal e As SystemEventArgs) Handles Button1Click Dim conDB As OleDbOleDbConnection Dim cmdFetch As OleDbOleDbCommand Dim rdrStates As OleDbOleDbDataReader Dim sCon As String = Provider=MicrosoftJetOLEDB40Data Source=CArcIMSWebsiteBPC_Statesbpc2002mdb conDB = New OleDbOleDbConnection(sCon) conDBOpen() cmdFetch = New OleDbOleDbCommand(SELECT STATE_NAME FROM STATES ORDER BY STATE_NAME) cmdFetchConnection = conDB rdrStates = cmdFetchExecuteReader() While rdrStatesRead() DropDownList1ItemsAdd(New ListItem(rdrStatesGetString(0))) End While conDBClose()

End Sub

The DropDownList fires a SelectedIndexChanged event The code associated with this event uses the where expression with LayersItem()Filter to create an image with a special highlight applied to the selected state The URL of the image is linked to the image buttons URL to display the new image

Private Sub DropDownList1_SelectedIndexChanged(ByVal sender As Object ByVal e As SystemEventArgs) Handles DropDownList1SelectedIndexChanged Dim sWhere As String = STATE_NAME = amp DropDownList1SelectedItemText amp mapStatesLayersItem(4)FilterWhereExpression = sWhere mapStatesRefresh() ImageButton1ImageUrl = mapStatesGetImageAsUrl End Sub

The Page_Unload event is used for clean up code Here it is used to free memory by setting the map and connection object to Nothing

ESRI White Paper 11

Private Sub Page_unload(ByVal sender As Object ByVal e As SystemEventArgs) Handles MyBaseUnload mapStates = Nothing conArcIMS = Nothing

End Sub

Example 2

General Description

This web application demonstrates the use of two image controls in a web form to display a map image and its associated legend both images being served up by ArcIMS The web application also has controls for Zoomin Zoomout and pan

Programming Environment ASPNET and Web Forms

Programming Language Visual Basic NET

WebForm Controls

ESRI White Paper 12

Control Name Function ImgMap Control for displaying the image ImgLegend Control for displaying the legend image lstNavControls Radiobutton list controls

Data Files

Can use any datafile capable of generating an image service Replace the sf parameter in the page_load event with the appropriate image service name

Class Libraries ( Logic_classes assembly)

File Name Class Information Functionality MapVB The Cmap class has a

MustInherit Keyword and is inherited by Cviewer The MustInherit keyword specifies that a class cannot be instantiated and can be used only as a base class

PointVB Used by Cmap Crect Represents a geometric point (xy pair ) RectVB Used by Cmap Cviewer and

Webform3 in testformaspx

ViewerVB Used in Webform3 in testformaspx

Abstracts the requesting of a simple map from ArcIMS No additional entities will be added to the map (ie graphics buffer etc) The map is requested with all the default parameters with which it is served excepting extent and background color

Steps to Create Application

ESRI White Paper 13

The following section details the code found in the code behind page of the Testformaspx page

Statement to import logic_classes Makes all the functionality available in the logic_classes project available to the code in the web form

Imports logic_classes

Define a class level variable in the aspx file

Private m_objViewerMap As cViewer

Code for the page load event Uses IsPostback to determine if the extents need to be read afresh or from a previous valued stored in the session object Also instantiates the Cviewer class object You need to make sure that the extents shown in the code are appropriately changed to work with your selected image service

Private Sub Page_Load(ByVal sender As SystemObject ByVal e As SystemEventArgs) Handles MyBaseLoad

ESRI White Paper 14

Put user code to initialize the page here Dim rctExtent As cRect If Not IsPostBack Then enter appropriate extents rctExtent = New cRect(-1225173 377199 -122363678 3780374) Else rctExtent = New cRect(Session(MinX) Session(MinY) Session(MaxX) Session(MaxY)) End If m_objViewerMap = New cViewer(httplocalhostservletcomesriesrimapEsrimap _ sf _ rctExtent _ imgMapWidthValue _ imgMapHeightValue _ 000) add test markers

End Sub

Page_Prerender event code Links the output image to the Picture controls Also since HTTP is a stateless protocol the current map extents are stored in session variables for follow-up requests from the same user

Private Sub Page_PreRender(ByVal sender As Object ByVal e As SystemEventArgs) Handles MyBasePreRender imgMapImageUrl = m_objViewerMapMap() imgLegendImageUrl = m_objViewerMapLegend() Session(MinX) = m_objViewerMapExtentXMin Session(MinY) = m_objViewerMapExtentYMin Session(MaxX) = m_objViewerMapExtentXMax Session(MaxY) = m_objViewerMapExtentYMax

End Sub

Imgmap_click event is raised when the user clicks on the map Code associated with this event converts the image click coordinate to a map coordinate Then

ESRI White Paper 15

based on the radio button selection ( Zoomin Zoomout or pan) the code calls the appropriate method using the instantiated Cviewer object

Private Sub imgMap_Click(ByVal sender As Object ByVal e As SystemWebUIImageClickEventArgs) Handles imgMapClick Convert the image click coordinate to a map coordinate based on the maps current extent Dim rctCurrentExtent As cRect = m_objViewerMapExtent Dim dblX As Double = rctCurrentExtentXMin + ((eX imgMapWidthValue) (rctCurrentExtentXMax - rctCurrentExtentXMin)) Dim dblY As Double = rctCurrentExtentYMin + (((imgMapHeightValue - eY) imgMapHeightValue) (rctCurrentExtentYMax - rctCurrentExtentYMin)) If Trim(UCase(lstNavControlsSelectedItemText)) ltgt IDENTIFY Then m_objViewerMapCenterAt(dblX dblY) Select Case UCase(lstNavControlsSelectedItemText) Case ZOOM IN Center the map m_objViewerMapZoom(-1) Case ZOOM OUT m_objViewerMapZoom(1) Case PAN do nothing Case Else ErrRaise(vbObjectError + 512 imgMap_Click Invalid command) End Select Else identify End If End Sub

ESRI White Paper 16

End Class

NOTE =gt Once you have the relevant files imported into Visual Studio make sure that you configure the virtual directory as an application before you run the example

If the virtual directory is not configured as an Application you will get an error message that reads This error can be caused by a virtual directory not being configured as an application in IIS To configure a Virtual directory is simple Use the Internet Service Manager to perform the following steps

Find the folder in the virtual directory Right click and choose properties Click Create Accept all the settings and Click OK

Example 3

General Description

The program uses the catalog service (using the ltGETCLIENTSERVICESgt request) to query and list a collection of services running on the server A Radiobutton list control is used to list all the service names running on the server On selecting an appropriate image service the map image is displayed on the web form using an image control This program demonstrates two different ways to connect to the datasource Connection could be achieved using the http protocol or the TCP protocol The TCP method utilizes the TCP capability built into the ActiveX Connector Since ASPNET is a multithreaded and the ActiveX connector being Single Threaded (STA) a wrapper class with additional functionality to manage memory is used to access the methods in the ActiveX connector

ESRI White Paper 17

Programming Environment ASPNET and Web Forms

C NET Programming Language

WebForm Controls

Control Name Function ImgMap Control for displaying the image RbServices Radiobutton list controls Txtinfo Displays the name of the selected image service

Data Files

Requires a collection of image services running on an ArcIMS server The program uses the ltGETCLIENTSERVICESgt request tag to query the catalog service to list all the services running on the specified server

Class Libraries

File Name Class Information Functionality Connectioncs Abstract base class Provides abstract method

templates for the HTTPConnection and

ESRI White Paper 18

TCPConnection classes HTTPConnectioncs Inherits from Connection class Provides functionality for

sending request to service postinggetting URL content etc

TCPConnectioncs Inherits from Connection class and SystemIDisposable

Utlizes the AICLib assembly to access connection functionality built into the ActiveX connector

Datasourcecs Provides method for accessing path port host and other information

Enumerationscs Provides enumerations for AccessType and LoadType

Envelopecs Provides methods for getting and setting xy coordinates of the envelope

ImageReturnObjectcs Provides methods for settinggetting image URL image envelope and image scale

Mapcs Calls send request to service with connection and service information Parses response to obtain image URL

Servicecs Servicescs Inherits from

SystemCollectionsHashtable Composes the clientservices request and parses the response Creates a hashtable association of individual service name with its associated service object

XML helper class that provides relevant XML parsing functionality by acting as a wrapper class around NETs xml Text IO and other NET classes

XMLRequestscs Builds ArcXML strings for requests

XMLHelpercs

Steps to Create Application

ESRI White Paper 19

The NET solution contains 2 projects ArcIMS and ArcIMSSample The ArcIMS project

o References the InteropAICLib o Contains NET ArcIMS class libraries that can be used to connect and to

work with image services The ArcIMSSample project

o References the ArcIMS project o Contains the web form (webform1aspx) and the corresponding

webform1aspxcs code-behind page that connects the web page controls to relevant functionality using an event driven web forms model

Points to Note

In webform1aspxcs code session variables are used to maintain state of serialized objects In order for this to be possible notice that the relevant classes have been marked as serializable

ESRI White Paper 20

Choose the appropriate connection type based on HTTP or TCP connection For HTTP choose m_dsConnectType = ConnectionTypeInterNet and for For TCP select m_dsConnectType = ConnectionTypeIntraNet as shown in the code below

private ArcIMSDataSource getDataSource() m_ds = Session[datasource] as ArcIMSDataSource if ( m_ds == null ) m_ds = new ArcIMSDataSource() m_dsHost = localhost m_dsScheme = http m_dsPort = 80 m_dsAppServerPort = 5300 m_dsPath = servletcomesriesrimapEsrimap choose (comment uncomment) one of the following two statements to decide between TCP or HTTP type connection m_dsConnectType = ConnectionTypeIntraNet m_dsConnectType = ConnectionTypeInterNet SessionAdd(datasource m_ds) return m_ds

Accessing a COM Server from a NET Client With the introduction of the NET Framework and ASPNET COM at its basic level has not really changed Nevertheless there are a couple of issues to be aware of when making calls to a COM object from a NET managed code environment The ASPNET threading model is the Multiple Threaded Apartment (MTA) This will not interact reliably with STA components (the ActiveX connector provided with the ArcIMS setup was built as an STA component) To emphasize this issue heres a direct quote from the MSDN pages at Microsoft The ASPNET threading model is the Multiple Threaded Apartment (MTA) What this means is that components that you are using that were created for the Single Threaded Apartment (STA) will no longer perform or function reliably without taking some extra precautions in ASPNET This includes but is not limited to all COM components that have been created using Visual Basic 60 and earlier versions

To understand the issues better let us take a look at how NET deals with COM related issues The Common Language Runtime exposes COM objects through a proxy called the runtime callable wrapper (RCW) The RCWs primary function is to marshal calls between a NET client and COM object The RCW object is nothing but an object instantiated at runtime from class code contained in the Interop assembly

ESRI White Paper 21

Calling between managed and unmanaged components incurs a marshaling cost which can impede the performance of your pages When a managed client and unmanaged server are in the same apartment the Interop marshalling service handles all data marshalling However when client and server are initialized in different apartments COM marshalling is also required Therefore interoperability with COM from a NET client should take into consideration the threading model used

Figure Cross-apartment call between a NET client and COM object

As mentioned earlier ASPNET follows an MTA model by default You could use the default model to communicate with an STA COM component if there is not much of an overhead due to the cross-apartment marshalling Usually this is noticeable only when there are many calls across the boundary Another option would be to use the PageAspCompatMode property of the ASPNET client The ASPCompat=true attribute enables an STA thread pool to address performance with existing Visual Basic components on a per-page basis The runtime throws an exception if the compatibility tag is omitted and an STA component is referenced on the page If you convert the STA component to an assembly using Type Library Importer (a utility included with the NET SDK) the runtime does not detect that the component uses the STA model and does not throw an exception but your application can suffer from poor performance and possible deadlocks STA components cannot be used from NET Framework code modules (compiled NET assemblies) they can be used only from ASPNET pages

If you plan to use the ASPCOMPAT = TRUE page level directive for Example 1 remember to instantiate the COM object within the page_load event rather than constructing COM components during page construction time For example look at code examples A and B

Example A Example B ltPage Language = VB ASPCOMPAT = truegt

ltscript runat = servergt

private mapStates as new aimsMap()

private sub_load ()

ltPage Language = VB ASPCOMPAT = truegt

ltscript runat = servergt

private mapStates as aimsMap()

private sub_load ()

ESRI White Paper 22

end sub

mapStates = new aimsMap()

end sub

In example A the STA component would be instantiated at page construction time which is created from a thread that is not the STA thread that will run the page This will involve marshalling between MTA and STA threads during the construction of the page Example B shows the preferred mechanism to delay the process until later when the code executes under a STA thread It is best to construct any COM component and external resources when needed or in the Page_Load method

Also to create the object you can use either the New keyword or the CreateObject method The CreateObject method is typically used when you dont know the Program ID (ProgID) of the object you are going to create until run time (late binding) New is the recommended method for instantiating objects if you have access to the objects type library It is preferable to adopt the early binding model

Every scenario yields different performance characteristics so it is important to test adequately before deciding whether interoperability is the right choice for your application However in nearly all scenarios rewriting your COM components in managed code provides performance benefits

Summary The examples shown above provide adequate information to leverage the NET programming environment to build effective ArcIMS client applications The debugging features of a program like Visual StudioNET provide a variety of tools (break points trace etc) making the entire development experience considerably pain-free Use the debugger to understand the sequence in which calls are made One early exercise would be to look at the calling sequence of the various page related events such as page_init page_load and page_prerender Since the Web Forms code is compiled you should experience much better performance than with ASP pages that used code written in scripting languages like Javascript and VbScript

The powerful programming environment also means that you can now concentrate more on the logic of building large web applications as opposed to building simple page based asp applications Also look at the various caching mechanisms provided by ASPNET as these can be used to improve overall performance As always there are costs associated with most programming choices and this is all the more true in a web-programming environment For example consider the costs associated with using a web control as opposed to a HTML based control Use plain HTML controls instead of adopting web controls for simple items like label

ESRI White Paper 23

If you choose to use the ActiveX connector from within the NET environment make sure that you clearly understand the essentials of COM Interop and the various costs associated with marshalling The solutions outlined in this paper utilize existing ArcIMS services and should work with all versions of ArcIMS

Although all the development can be done without the use of an Integrated Development environment (IDE) like Visual StudioNET using such an environment provides convenient WYSIWYG features that can help in building and debugging the application If you do not have Visual StudioNET there are free IDEs available today that can also be used For example ASPNET Web Matrix is a community-supported easy-to-use WYSIWYG application development tool for ASPNET It can be installed via a quick 12 MB download from httpwwwaspnetwebmatrixdefaultaspx

ESRI White Paper 24

  • ArcIMS ndash An Introduction
  • What is NET
    • The NET Framework
      • The Common Language Runtime (CLR)
      • Managed Unmanaged and Unsafe code ndash Understandin
      • NET Framework Class Libraries
        • ASPNET and Web Forms
          • NET and ArcIMS
            • Example 1
            • Example 2
            • Example 3
              • Accessing a COM Server from a NET Client
              • Summary
Page 10: Consuming ArcIMS Image Services using .NET Client Web ... · Consuming ArcIMS Image Services using .NET Client Web Applications An ESRI White Paper Ł October 2002 ... The .NET framework

necessary steps to convert the obtained page coordinates to map coordinates for subsequent use in zoom operations

Example 3 An ASPNET application written in C that makes use of special classes developed in C This example utilizes two approaches one using the Servlet connector and another using a C wrapper to the ActiveX connector to connect to the service using TCP

Example 1

This application is a very simple web application that demonstrates the use of an image control in a web form to display a map image served up by ArcIMS The button control reads State Names from a database and populates the DropDownList Selecting a State from the DropDownList highlights the state in the map

This example demonstrates the following

Basic web form and web controls Button Image and DropDownListcontrols Using the ActiveX connector in a NET web application using COM Interop

ESRI White Paper 7

Connecting to an access database to read a list of names (from a column) This list is then used to populate a drop down list box

Using the image control to view an image rendered by ArcIMS

ASPNET and Web Forms Programming Environment

Visual Basic NET Programming Language

Data Files

File Name Comment BPC 2002mdb Database file with a column containing state names World30stateslakescountry Shape files BPC_STATESaxl Axl file for the image service

WebForm Controls

Control Name Function ImageButton1 Control for displaying the image Button Populates the Dropdown Listbox with State Names read from the

database DropDownList1 Set AutoPostback property to TRUE

Steps to Create Application

Create a new Project Choose Visual Basic Project -gt ASPNET web application

Add Project References

ESRI White Paper 8

o Project Add References COM ArcIMS ActiveX Connector (Aims_ActiveXdll)

o Project Add References NET adodb ( adodbdll)

Add controls to the form and set the appropriate properties (NameCaption Size etc)

Right click on the WebForm1aspx file and choose Viewcode Type the code shown below Click on Build-gtSolution Press CTRL+F5 to start without debugging or F5 to Start (with debugging)

ESRI White Paper 9

Code from Web Form1aspxvb the codebehind page for the Web Form

Define and instantiate class variables Refer to the Section Accessing a COM Server from a NET Client for a discussion on using early and late binding mechanisms to instantiate COM objects

Private mapStates As aimsMap()

Private conArcIMS As aimsArcIMSConnector()

The Page_Load event sets up the connection and map parameters It also links the image URL (provided by ArcIMS) to the URL property of the Image control to display the map image

Private Sub Page_load(ByVal sender As SystemObject ByVal e As SystemEventArgs) Handles MyBaseLoad mapStates = New aimsMap() conArcIMS = New aimsArcIMSConnector() conArcIMSServerName = localhost conArcIMSServerPort = 5300 mapStatesInitMap(conArcIMS BPC_States) mapStatesWidth = 550 mapStatesHeight = 400 mapStatesRefresh()

ESRI White Paper 10

ImageButton1ImageUrl = mapStatesGetImageAsUrl

End Sub

The Button Click event makes a connection to the bpc2002mdb access database It then reads the data from the States column orders it alphabetically and then populates the DropDownList control with the ordered list of entries

Private Sub Button1_Click(ByVal sender As SystemObject ByVal e As SystemEventArgs) Handles Button1Click Dim conDB As OleDbOleDbConnection Dim cmdFetch As OleDbOleDbCommand Dim rdrStates As OleDbOleDbDataReader Dim sCon As String = Provider=MicrosoftJetOLEDB40Data Source=CArcIMSWebsiteBPC_Statesbpc2002mdb conDB = New OleDbOleDbConnection(sCon) conDBOpen() cmdFetch = New OleDbOleDbCommand(SELECT STATE_NAME FROM STATES ORDER BY STATE_NAME) cmdFetchConnection = conDB rdrStates = cmdFetchExecuteReader() While rdrStatesRead() DropDownList1ItemsAdd(New ListItem(rdrStatesGetString(0))) End While conDBClose()

End Sub

The DropDownList fires a SelectedIndexChanged event The code associated with this event uses the where expression with LayersItem()Filter to create an image with a special highlight applied to the selected state The URL of the image is linked to the image buttons URL to display the new image

Private Sub DropDownList1_SelectedIndexChanged(ByVal sender As Object ByVal e As SystemEventArgs) Handles DropDownList1SelectedIndexChanged Dim sWhere As String = STATE_NAME = amp DropDownList1SelectedItemText amp mapStatesLayersItem(4)FilterWhereExpression = sWhere mapStatesRefresh() ImageButton1ImageUrl = mapStatesGetImageAsUrl End Sub

The Page_Unload event is used for clean up code Here it is used to free memory by setting the map and connection object to Nothing

ESRI White Paper 11

Private Sub Page_unload(ByVal sender As Object ByVal e As SystemEventArgs) Handles MyBaseUnload mapStates = Nothing conArcIMS = Nothing

End Sub

Example 2

General Description

This web application demonstrates the use of two image controls in a web form to display a map image and its associated legend both images being served up by ArcIMS The web application also has controls for Zoomin Zoomout and pan

Programming Environment ASPNET and Web Forms

Programming Language Visual Basic NET

WebForm Controls

ESRI White Paper 12

Control Name Function ImgMap Control for displaying the image ImgLegend Control for displaying the legend image lstNavControls Radiobutton list controls

Data Files

Can use any datafile capable of generating an image service Replace the sf parameter in the page_load event with the appropriate image service name

Class Libraries ( Logic_classes assembly)

File Name Class Information Functionality MapVB The Cmap class has a

MustInherit Keyword and is inherited by Cviewer The MustInherit keyword specifies that a class cannot be instantiated and can be used only as a base class

PointVB Used by Cmap Crect Represents a geometric point (xy pair ) RectVB Used by Cmap Cviewer and

Webform3 in testformaspx

ViewerVB Used in Webform3 in testformaspx

Abstracts the requesting of a simple map from ArcIMS No additional entities will be added to the map (ie graphics buffer etc) The map is requested with all the default parameters with which it is served excepting extent and background color

Steps to Create Application

ESRI White Paper 13

The following section details the code found in the code behind page of the Testformaspx page

Statement to import logic_classes Makes all the functionality available in the logic_classes project available to the code in the web form

Imports logic_classes

Define a class level variable in the aspx file

Private m_objViewerMap As cViewer

Code for the page load event Uses IsPostback to determine if the extents need to be read afresh or from a previous valued stored in the session object Also instantiates the Cviewer class object You need to make sure that the extents shown in the code are appropriately changed to work with your selected image service

Private Sub Page_Load(ByVal sender As SystemObject ByVal e As SystemEventArgs) Handles MyBaseLoad

ESRI White Paper 14

Put user code to initialize the page here Dim rctExtent As cRect If Not IsPostBack Then enter appropriate extents rctExtent = New cRect(-1225173 377199 -122363678 3780374) Else rctExtent = New cRect(Session(MinX) Session(MinY) Session(MaxX) Session(MaxY)) End If m_objViewerMap = New cViewer(httplocalhostservletcomesriesrimapEsrimap _ sf _ rctExtent _ imgMapWidthValue _ imgMapHeightValue _ 000) add test markers

End Sub

Page_Prerender event code Links the output image to the Picture controls Also since HTTP is a stateless protocol the current map extents are stored in session variables for follow-up requests from the same user

Private Sub Page_PreRender(ByVal sender As Object ByVal e As SystemEventArgs) Handles MyBasePreRender imgMapImageUrl = m_objViewerMapMap() imgLegendImageUrl = m_objViewerMapLegend() Session(MinX) = m_objViewerMapExtentXMin Session(MinY) = m_objViewerMapExtentYMin Session(MaxX) = m_objViewerMapExtentXMax Session(MaxY) = m_objViewerMapExtentYMax

End Sub

Imgmap_click event is raised when the user clicks on the map Code associated with this event converts the image click coordinate to a map coordinate Then

ESRI White Paper 15

based on the radio button selection ( Zoomin Zoomout or pan) the code calls the appropriate method using the instantiated Cviewer object

Private Sub imgMap_Click(ByVal sender As Object ByVal e As SystemWebUIImageClickEventArgs) Handles imgMapClick Convert the image click coordinate to a map coordinate based on the maps current extent Dim rctCurrentExtent As cRect = m_objViewerMapExtent Dim dblX As Double = rctCurrentExtentXMin + ((eX imgMapWidthValue) (rctCurrentExtentXMax - rctCurrentExtentXMin)) Dim dblY As Double = rctCurrentExtentYMin + (((imgMapHeightValue - eY) imgMapHeightValue) (rctCurrentExtentYMax - rctCurrentExtentYMin)) If Trim(UCase(lstNavControlsSelectedItemText)) ltgt IDENTIFY Then m_objViewerMapCenterAt(dblX dblY) Select Case UCase(lstNavControlsSelectedItemText) Case ZOOM IN Center the map m_objViewerMapZoom(-1) Case ZOOM OUT m_objViewerMapZoom(1) Case PAN do nothing Case Else ErrRaise(vbObjectError + 512 imgMap_Click Invalid command) End Select Else identify End If End Sub

ESRI White Paper 16

End Class

NOTE =gt Once you have the relevant files imported into Visual Studio make sure that you configure the virtual directory as an application before you run the example

If the virtual directory is not configured as an Application you will get an error message that reads This error can be caused by a virtual directory not being configured as an application in IIS To configure a Virtual directory is simple Use the Internet Service Manager to perform the following steps

Find the folder in the virtual directory Right click and choose properties Click Create Accept all the settings and Click OK

Example 3

General Description

The program uses the catalog service (using the ltGETCLIENTSERVICESgt request) to query and list a collection of services running on the server A Radiobutton list control is used to list all the service names running on the server On selecting an appropriate image service the map image is displayed on the web form using an image control This program demonstrates two different ways to connect to the datasource Connection could be achieved using the http protocol or the TCP protocol The TCP method utilizes the TCP capability built into the ActiveX Connector Since ASPNET is a multithreaded and the ActiveX connector being Single Threaded (STA) a wrapper class with additional functionality to manage memory is used to access the methods in the ActiveX connector

ESRI White Paper 17

Programming Environment ASPNET and Web Forms

C NET Programming Language

WebForm Controls

Control Name Function ImgMap Control for displaying the image RbServices Radiobutton list controls Txtinfo Displays the name of the selected image service

Data Files

Requires a collection of image services running on an ArcIMS server The program uses the ltGETCLIENTSERVICESgt request tag to query the catalog service to list all the services running on the specified server

Class Libraries

File Name Class Information Functionality Connectioncs Abstract base class Provides abstract method

templates for the HTTPConnection and

ESRI White Paper 18

TCPConnection classes HTTPConnectioncs Inherits from Connection class Provides functionality for

sending request to service postinggetting URL content etc

TCPConnectioncs Inherits from Connection class and SystemIDisposable

Utlizes the AICLib assembly to access connection functionality built into the ActiveX connector

Datasourcecs Provides method for accessing path port host and other information

Enumerationscs Provides enumerations for AccessType and LoadType

Envelopecs Provides methods for getting and setting xy coordinates of the envelope

ImageReturnObjectcs Provides methods for settinggetting image URL image envelope and image scale

Mapcs Calls send request to service with connection and service information Parses response to obtain image URL

Servicecs Servicescs Inherits from

SystemCollectionsHashtable Composes the clientservices request and parses the response Creates a hashtable association of individual service name with its associated service object

XML helper class that provides relevant XML parsing functionality by acting as a wrapper class around NETs xml Text IO and other NET classes

XMLRequestscs Builds ArcXML strings for requests

XMLHelpercs

Steps to Create Application

ESRI White Paper 19

The NET solution contains 2 projects ArcIMS and ArcIMSSample The ArcIMS project

o References the InteropAICLib o Contains NET ArcIMS class libraries that can be used to connect and to

work with image services The ArcIMSSample project

o References the ArcIMS project o Contains the web form (webform1aspx) and the corresponding

webform1aspxcs code-behind page that connects the web page controls to relevant functionality using an event driven web forms model

Points to Note

In webform1aspxcs code session variables are used to maintain state of serialized objects In order for this to be possible notice that the relevant classes have been marked as serializable

ESRI White Paper 20

Choose the appropriate connection type based on HTTP or TCP connection For HTTP choose m_dsConnectType = ConnectionTypeInterNet and for For TCP select m_dsConnectType = ConnectionTypeIntraNet as shown in the code below

private ArcIMSDataSource getDataSource() m_ds = Session[datasource] as ArcIMSDataSource if ( m_ds == null ) m_ds = new ArcIMSDataSource() m_dsHost = localhost m_dsScheme = http m_dsPort = 80 m_dsAppServerPort = 5300 m_dsPath = servletcomesriesrimapEsrimap choose (comment uncomment) one of the following two statements to decide between TCP or HTTP type connection m_dsConnectType = ConnectionTypeIntraNet m_dsConnectType = ConnectionTypeInterNet SessionAdd(datasource m_ds) return m_ds

Accessing a COM Server from a NET Client With the introduction of the NET Framework and ASPNET COM at its basic level has not really changed Nevertheless there are a couple of issues to be aware of when making calls to a COM object from a NET managed code environment The ASPNET threading model is the Multiple Threaded Apartment (MTA) This will not interact reliably with STA components (the ActiveX connector provided with the ArcIMS setup was built as an STA component) To emphasize this issue heres a direct quote from the MSDN pages at Microsoft The ASPNET threading model is the Multiple Threaded Apartment (MTA) What this means is that components that you are using that were created for the Single Threaded Apartment (STA) will no longer perform or function reliably without taking some extra precautions in ASPNET This includes but is not limited to all COM components that have been created using Visual Basic 60 and earlier versions

To understand the issues better let us take a look at how NET deals with COM related issues The Common Language Runtime exposes COM objects through a proxy called the runtime callable wrapper (RCW) The RCWs primary function is to marshal calls between a NET client and COM object The RCW object is nothing but an object instantiated at runtime from class code contained in the Interop assembly

ESRI White Paper 21

Calling between managed and unmanaged components incurs a marshaling cost which can impede the performance of your pages When a managed client and unmanaged server are in the same apartment the Interop marshalling service handles all data marshalling However when client and server are initialized in different apartments COM marshalling is also required Therefore interoperability with COM from a NET client should take into consideration the threading model used

Figure Cross-apartment call between a NET client and COM object

As mentioned earlier ASPNET follows an MTA model by default You could use the default model to communicate with an STA COM component if there is not much of an overhead due to the cross-apartment marshalling Usually this is noticeable only when there are many calls across the boundary Another option would be to use the PageAspCompatMode property of the ASPNET client The ASPCompat=true attribute enables an STA thread pool to address performance with existing Visual Basic components on a per-page basis The runtime throws an exception if the compatibility tag is omitted and an STA component is referenced on the page If you convert the STA component to an assembly using Type Library Importer (a utility included with the NET SDK) the runtime does not detect that the component uses the STA model and does not throw an exception but your application can suffer from poor performance and possible deadlocks STA components cannot be used from NET Framework code modules (compiled NET assemblies) they can be used only from ASPNET pages

If you plan to use the ASPCOMPAT = TRUE page level directive for Example 1 remember to instantiate the COM object within the page_load event rather than constructing COM components during page construction time For example look at code examples A and B

Example A Example B ltPage Language = VB ASPCOMPAT = truegt

ltscript runat = servergt

private mapStates as new aimsMap()

private sub_load ()

ltPage Language = VB ASPCOMPAT = truegt

ltscript runat = servergt

private mapStates as aimsMap()

private sub_load ()

ESRI White Paper 22

end sub

mapStates = new aimsMap()

end sub

In example A the STA component would be instantiated at page construction time which is created from a thread that is not the STA thread that will run the page This will involve marshalling between MTA and STA threads during the construction of the page Example B shows the preferred mechanism to delay the process until later when the code executes under a STA thread It is best to construct any COM component and external resources when needed or in the Page_Load method

Also to create the object you can use either the New keyword or the CreateObject method The CreateObject method is typically used when you dont know the Program ID (ProgID) of the object you are going to create until run time (late binding) New is the recommended method for instantiating objects if you have access to the objects type library It is preferable to adopt the early binding model

Every scenario yields different performance characteristics so it is important to test adequately before deciding whether interoperability is the right choice for your application However in nearly all scenarios rewriting your COM components in managed code provides performance benefits

Summary The examples shown above provide adequate information to leverage the NET programming environment to build effective ArcIMS client applications The debugging features of a program like Visual StudioNET provide a variety of tools (break points trace etc) making the entire development experience considerably pain-free Use the debugger to understand the sequence in which calls are made One early exercise would be to look at the calling sequence of the various page related events such as page_init page_load and page_prerender Since the Web Forms code is compiled you should experience much better performance than with ASP pages that used code written in scripting languages like Javascript and VbScript

The powerful programming environment also means that you can now concentrate more on the logic of building large web applications as opposed to building simple page based asp applications Also look at the various caching mechanisms provided by ASPNET as these can be used to improve overall performance As always there are costs associated with most programming choices and this is all the more true in a web-programming environment For example consider the costs associated with using a web control as opposed to a HTML based control Use plain HTML controls instead of adopting web controls for simple items like label

ESRI White Paper 23

If you choose to use the ActiveX connector from within the NET environment make sure that you clearly understand the essentials of COM Interop and the various costs associated with marshalling The solutions outlined in this paper utilize existing ArcIMS services and should work with all versions of ArcIMS

Although all the development can be done without the use of an Integrated Development environment (IDE) like Visual StudioNET using such an environment provides convenient WYSIWYG features that can help in building and debugging the application If you do not have Visual StudioNET there are free IDEs available today that can also be used For example ASPNET Web Matrix is a community-supported easy-to-use WYSIWYG application development tool for ASPNET It can be installed via a quick 12 MB download from httpwwwaspnetwebmatrixdefaultaspx

ESRI White Paper 24

  • ArcIMS ndash An Introduction
  • What is NET
    • The NET Framework
      • The Common Language Runtime (CLR)
      • Managed Unmanaged and Unsafe code ndash Understandin
      • NET Framework Class Libraries
        • ASPNET and Web Forms
          • NET and ArcIMS
            • Example 1
            • Example 2
            • Example 3
              • Accessing a COM Server from a NET Client
              • Summary
Page 11: Consuming ArcIMS Image Services using .NET Client Web ... · Consuming ArcIMS Image Services using .NET Client Web Applications An ESRI White Paper Ł October 2002 ... The .NET framework

Connecting to an access database to read a list of names (from a column) This list is then used to populate a drop down list box

Using the image control to view an image rendered by ArcIMS

ASPNET and Web Forms Programming Environment

Visual Basic NET Programming Language

Data Files

File Name Comment BPC 2002mdb Database file with a column containing state names World30stateslakescountry Shape files BPC_STATESaxl Axl file for the image service

WebForm Controls

Control Name Function ImageButton1 Control for displaying the image Button Populates the Dropdown Listbox with State Names read from the

database DropDownList1 Set AutoPostback property to TRUE

Steps to Create Application

Create a new Project Choose Visual Basic Project -gt ASPNET web application

Add Project References

ESRI White Paper 8

o Project Add References COM ArcIMS ActiveX Connector (Aims_ActiveXdll)

o Project Add References NET adodb ( adodbdll)

Add controls to the form and set the appropriate properties (NameCaption Size etc)

Right click on the WebForm1aspx file and choose Viewcode Type the code shown below Click on Build-gtSolution Press CTRL+F5 to start without debugging or F5 to Start (with debugging)

ESRI White Paper 9

Code from Web Form1aspxvb the codebehind page for the Web Form

Define and instantiate class variables Refer to the Section Accessing a COM Server from a NET Client for a discussion on using early and late binding mechanisms to instantiate COM objects

Private mapStates As aimsMap()

Private conArcIMS As aimsArcIMSConnector()

The Page_Load event sets up the connection and map parameters It also links the image URL (provided by ArcIMS) to the URL property of the Image control to display the map image

Private Sub Page_load(ByVal sender As SystemObject ByVal e As SystemEventArgs) Handles MyBaseLoad mapStates = New aimsMap() conArcIMS = New aimsArcIMSConnector() conArcIMSServerName = localhost conArcIMSServerPort = 5300 mapStatesInitMap(conArcIMS BPC_States) mapStatesWidth = 550 mapStatesHeight = 400 mapStatesRefresh()

ESRI White Paper 10

ImageButton1ImageUrl = mapStatesGetImageAsUrl

End Sub

The Button Click event makes a connection to the bpc2002mdb access database It then reads the data from the States column orders it alphabetically and then populates the DropDownList control with the ordered list of entries

Private Sub Button1_Click(ByVal sender As SystemObject ByVal e As SystemEventArgs) Handles Button1Click Dim conDB As OleDbOleDbConnection Dim cmdFetch As OleDbOleDbCommand Dim rdrStates As OleDbOleDbDataReader Dim sCon As String = Provider=MicrosoftJetOLEDB40Data Source=CArcIMSWebsiteBPC_Statesbpc2002mdb conDB = New OleDbOleDbConnection(sCon) conDBOpen() cmdFetch = New OleDbOleDbCommand(SELECT STATE_NAME FROM STATES ORDER BY STATE_NAME) cmdFetchConnection = conDB rdrStates = cmdFetchExecuteReader() While rdrStatesRead() DropDownList1ItemsAdd(New ListItem(rdrStatesGetString(0))) End While conDBClose()

End Sub

The DropDownList fires a SelectedIndexChanged event The code associated with this event uses the where expression with LayersItem()Filter to create an image with a special highlight applied to the selected state The URL of the image is linked to the image buttons URL to display the new image

Private Sub DropDownList1_SelectedIndexChanged(ByVal sender As Object ByVal e As SystemEventArgs) Handles DropDownList1SelectedIndexChanged Dim sWhere As String = STATE_NAME = amp DropDownList1SelectedItemText amp mapStatesLayersItem(4)FilterWhereExpression = sWhere mapStatesRefresh() ImageButton1ImageUrl = mapStatesGetImageAsUrl End Sub

The Page_Unload event is used for clean up code Here it is used to free memory by setting the map and connection object to Nothing

ESRI White Paper 11

Private Sub Page_unload(ByVal sender As Object ByVal e As SystemEventArgs) Handles MyBaseUnload mapStates = Nothing conArcIMS = Nothing

End Sub

Example 2

General Description

This web application demonstrates the use of two image controls in a web form to display a map image and its associated legend both images being served up by ArcIMS The web application also has controls for Zoomin Zoomout and pan

Programming Environment ASPNET and Web Forms

Programming Language Visual Basic NET

WebForm Controls

ESRI White Paper 12

Control Name Function ImgMap Control for displaying the image ImgLegend Control for displaying the legend image lstNavControls Radiobutton list controls

Data Files

Can use any datafile capable of generating an image service Replace the sf parameter in the page_load event with the appropriate image service name

Class Libraries ( Logic_classes assembly)

File Name Class Information Functionality MapVB The Cmap class has a

MustInherit Keyword and is inherited by Cviewer The MustInherit keyword specifies that a class cannot be instantiated and can be used only as a base class

PointVB Used by Cmap Crect Represents a geometric point (xy pair ) RectVB Used by Cmap Cviewer and

Webform3 in testformaspx

ViewerVB Used in Webform3 in testformaspx

Abstracts the requesting of a simple map from ArcIMS No additional entities will be added to the map (ie graphics buffer etc) The map is requested with all the default parameters with which it is served excepting extent and background color

Steps to Create Application

ESRI White Paper 13

The following section details the code found in the code behind page of the Testformaspx page

Statement to import logic_classes Makes all the functionality available in the logic_classes project available to the code in the web form

Imports logic_classes

Define a class level variable in the aspx file

Private m_objViewerMap As cViewer

Code for the page load event Uses IsPostback to determine if the extents need to be read afresh or from a previous valued stored in the session object Also instantiates the Cviewer class object You need to make sure that the extents shown in the code are appropriately changed to work with your selected image service

Private Sub Page_Load(ByVal sender As SystemObject ByVal e As SystemEventArgs) Handles MyBaseLoad

ESRI White Paper 14

Put user code to initialize the page here Dim rctExtent As cRect If Not IsPostBack Then enter appropriate extents rctExtent = New cRect(-1225173 377199 -122363678 3780374) Else rctExtent = New cRect(Session(MinX) Session(MinY) Session(MaxX) Session(MaxY)) End If m_objViewerMap = New cViewer(httplocalhostservletcomesriesrimapEsrimap _ sf _ rctExtent _ imgMapWidthValue _ imgMapHeightValue _ 000) add test markers

End Sub

Page_Prerender event code Links the output image to the Picture controls Also since HTTP is a stateless protocol the current map extents are stored in session variables for follow-up requests from the same user

Private Sub Page_PreRender(ByVal sender As Object ByVal e As SystemEventArgs) Handles MyBasePreRender imgMapImageUrl = m_objViewerMapMap() imgLegendImageUrl = m_objViewerMapLegend() Session(MinX) = m_objViewerMapExtentXMin Session(MinY) = m_objViewerMapExtentYMin Session(MaxX) = m_objViewerMapExtentXMax Session(MaxY) = m_objViewerMapExtentYMax

End Sub

Imgmap_click event is raised when the user clicks on the map Code associated with this event converts the image click coordinate to a map coordinate Then

ESRI White Paper 15

based on the radio button selection ( Zoomin Zoomout or pan) the code calls the appropriate method using the instantiated Cviewer object

Private Sub imgMap_Click(ByVal sender As Object ByVal e As SystemWebUIImageClickEventArgs) Handles imgMapClick Convert the image click coordinate to a map coordinate based on the maps current extent Dim rctCurrentExtent As cRect = m_objViewerMapExtent Dim dblX As Double = rctCurrentExtentXMin + ((eX imgMapWidthValue) (rctCurrentExtentXMax - rctCurrentExtentXMin)) Dim dblY As Double = rctCurrentExtentYMin + (((imgMapHeightValue - eY) imgMapHeightValue) (rctCurrentExtentYMax - rctCurrentExtentYMin)) If Trim(UCase(lstNavControlsSelectedItemText)) ltgt IDENTIFY Then m_objViewerMapCenterAt(dblX dblY) Select Case UCase(lstNavControlsSelectedItemText) Case ZOOM IN Center the map m_objViewerMapZoom(-1) Case ZOOM OUT m_objViewerMapZoom(1) Case PAN do nothing Case Else ErrRaise(vbObjectError + 512 imgMap_Click Invalid command) End Select Else identify End If End Sub

ESRI White Paper 16

End Class

NOTE =gt Once you have the relevant files imported into Visual Studio make sure that you configure the virtual directory as an application before you run the example

If the virtual directory is not configured as an Application you will get an error message that reads This error can be caused by a virtual directory not being configured as an application in IIS To configure a Virtual directory is simple Use the Internet Service Manager to perform the following steps

Find the folder in the virtual directory Right click and choose properties Click Create Accept all the settings and Click OK

Example 3

General Description

The program uses the catalog service (using the ltGETCLIENTSERVICESgt request) to query and list a collection of services running on the server A Radiobutton list control is used to list all the service names running on the server On selecting an appropriate image service the map image is displayed on the web form using an image control This program demonstrates two different ways to connect to the datasource Connection could be achieved using the http protocol or the TCP protocol The TCP method utilizes the TCP capability built into the ActiveX Connector Since ASPNET is a multithreaded and the ActiveX connector being Single Threaded (STA) a wrapper class with additional functionality to manage memory is used to access the methods in the ActiveX connector

ESRI White Paper 17

Programming Environment ASPNET and Web Forms

C NET Programming Language

WebForm Controls

Control Name Function ImgMap Control for displaying the image RbServices Radiobutton list controls Txtinfo Displays the name of the selected image service

Data Files

Requires a collection of image services running on an ArcIMS server The program uses the ltGETCLIENTSERVICESgt request tag to query the catalog service to list all the services running on the specified server

Class Libraries

File Name Class Information Functionality Connectioncs Abstract base class Provides abstract method

templates for the HTTPConnection and

ESRI White Paper 18

TCPConnection classes HTTPConnectioncs Inherits from Connection class Provides functionality for

sending request to service postinggetting URL content etc

TCPConnectioncs Inherits from Connection class and SystemIDisposable

Utlizes the AICLib assembly to access connection functionality built into the ActiveX connector

Datasourcecs Provides method for accessing path port host and other information

Enumerationscs Provides enumerations for AccessType and LoadType

Envelopecs Provides methods for getting and setting xy coordinates of the envelope

ImageReturnObjectcs Provides methods for settinggetting image URL image envelope and image scale

Mapcs Calls send request to service with connection and service information Parses response to obtain image URL

Servicecs Servicescs Inherits from

SystemCollectionsHashtable Composes the clientservices request and parses the response Creates a hashtable association of individual service name with its associated service object

XML helper class that provides relevant XML parsing functionality by acting as a wrapper class around NETs xml Text IO and other NET classes

XMLRequestscs Builds ArcXML strings for requests

XMLHelpercs

Steps to Create Application

ESRI White Paper 19

The NET solution contains 2 projects ArcIMS and ArcIMSSample The ArcIMS project

o References the InteropAICLib o Contains NET ArcIMS class libraries that can be used to connect and to

work with image services The ArcIMSSample project

o References the ArcIMS project o Contains the web form (webform1aspx) and the corresponding

webform1aspxcs code-behind page that connects the web page controls to relevant functionality using an event driven web forms model

Points to Note

In webform1aspxcs code session variables are used to maintain state of serialized objects In order for this to be possible notice that the relevant classes have been marked as serializable

ESRI White Paper 20

Choose the appropriate connection type based on HTTP or TCP connection For HTTP choose m_dsConnectType = ConnectionTypeInterNet and for For TCP select m_dsConnectType = ConnectionTypeIntraNet as shown in the code below

private ArcIMSDataSource getDataSource() m_ds = Session[datasource] as ArcIMSDataSource if ( m_ds == null ) m_ds = new ArcIMSDataSource() m_dsHost = localhost m_dsScheme = http m_dsPort = 80 m_dsAppServerPort = 5300 m_dsPath = servletcomesriesrimapEsrimap choose (comment uncomment) one of the following two statements to decide between TCP or HTTP type connection m_dsConnectType = ConnectionTypeIntraNet m_dsConnectType = ConnectionTypeInterNet SessionAdd(datasource m_ds) return m_ds

Accessing a COM Server from a NET Client With the introduction of the NET Framework and ASPNET COM at its basic level has not really changed Nevertheless there are a couple of issues to be aware of when making calls to a COM object from a NET managed code environment The ASPNET threading model is the Multiple Threaded Apartment (MTA) This will not interact reliably with STA components (the ActiveX connector provided with the ArcIMS setup was built as an STA component) To emphasize this issue heres a direct quote from the MSDN pages at Microsoft The ASPNET threading model is the Multiple Threaded Apartment (MTA) What this means is that components that you are using that were created for the Single Threaded Apartment (STA) will no longer perform or function reliably without taking some extra precautions in ASPNET This includes but is not limited to all COM components that have been created using Visual Basic 60 and earlier versions

To understand the issues better let us take a look at how NET deals with COM related issues The Common Language Runtime exposes COM objects through a proxy called the runtime callable wrapper (RCW) The RCWs primary function is to marshal calls between a NET client and COM object The RCW object is nothing but an object instantiated at runtime from class code contained in the Interop assembly

ESRI White Paper 21

Calling between managed and unmanaged components incurs a marshaling cost which can impede the performance of your pages When a managed client and unmanaged server are in the same apartment the Interop marshalling service handles all data marshalling However when client and server are initialized in different apartments COM marshalling is also required Therefore interoperability with COM from a NET client should take into consideration the threading model used

Figure Cross-apartment call between a NET client and COM object

As mentioned earlier ASPNET follows an MTA model by default You could use the default model to communicate with an STA COM component if there is not much of an overhead due to the cross-apartment marshalling Usually this is noticeable only when there are many calls across the boundary Another option would be to use the PageAspCompatMode property of the ASPNET client The ASPCompat=true attribute enables an STA thread pool to address performance with existing Visual Basic components on a per-page basis The runtime throws an exception if the compatibility tag is omitted and an STA component is referenced on the page If you convert the STA component to an assembly using Type Library Importer (a utility included with the NET SDK) the runtime does not detect that the component uses the STA model and does not throw an exception but your application can suffer from poor performance and possible deadlocks STA components cannot be used from NET Framework code modules (compiled NET assemblies) they can be used only from ASPNET pages

If you plan to use the ASPCOMPAT = TRUE page level directive for Example 1 remember to instantiate the COM object within the page_load event rather than constructing COM components during page construction time For example look at code examples A and B

Example A Example B ltPage Language = VB ASPCOMPAT = truegt

ltscript runat = servergt

private mapStates as new aimsMap()

private sub_load ()

ltPage Language = VB ASPCOMPAT = truegt

ltscript runat = servergt

private mapStates as aimsMap()

private sub_load ()

ESRI White Paper 22

end sub

mapStates = new aimsMap()

end sub

In example A the STA component would be instantiated at page construction time which is created from a thread that is not the STA thread that will run the page This will involve marshalling between MTA and STA threads during the construction of the page Example B shows the preferred mechanism to delay the process until later when the code executes under a STA thread It is best to construct any COM component and external resources when needed or in the Page_Load method

Also to create the object you can use either the New keyword or the CreateObject method The CreateObject method is typically used when you dont know the Program ID (ProgID) of the object you are going to create until run time (late binding) New is the recommended method for instantiating objects if you have access to the objects type library It is preferable to adopt the early binding model

Every scenario yields different performance characteristics so it is important to test adequately before deciding whether interoperability is the right choice for your application However in nearly all scenarios rewriting your COM components in managed code provides performance benefits

Summary The examples shown above provide adequate information to leverage the NET programming environment to build effective ArcIMS client applications The debugging features of a program like Visual StudioNET provide a variety of tools (break points trace etc) making the entire development experience considerably pain-free Use the debugger to understand the sequence in which calls are made One early exercise would be to look at the calling sequence of the various page related events such as page_init page_load and page_prerender Since the Web Forms code is compiled you should experience much better performance than with ASP pages that used code written in scripting languages like Javascript and VbScript

The powerful programming environment also means that you can now concentrate more on the logic of building large web applications as opposed to building simple page based asp applications Also look at the various caching mechanisms provided by ASPNET as these can be used to improve overall performance As always there are costs associated with most programming choices and this is all the more true in a web-programming environment For example consider the costs associated with using a web control as opposed to a HTML based control Use plain HTML controls instead of adopting web controls for simple items like label

ESRI White Paper 23

If you choose to use the ActiveX connector from within the NET environment make sure that you clearly understand the essentials of COM Interop and the various costs associated with marshalling The solutions outlined in this paper utilize existing ArcIMS services and should work with all versions of ArcIMS

Although all the development can be done without the use of an Integrated Development environment (IDE) like Visual StudioNET using such an environment provides convenient WYSIWYG features that can help in building and debugging the application If you do not have Visual StudioNET there are free IDEs available today that can also be used For example ASPNET Web Matrix is a community-supported easy-to-use WYSIWYG application development tool for ASPNET It can be installed via a quick 12 MB download from httpwwwaspnetwebmatrixdefaultaspx

ESRI White Paper 24

  • ArcIMS ndash An Introduction
  • What is NET
    • The NET Framework
      • The Common Language Runtime (CLR)
      • Managed Unmanaged and Unsafe code ndash Understandin
      • NET Framework Class Libraries
        • ASPNET and Web Forms
          • NET and ArcIMS
            • Example 1
            • Example 2
            • Example 3
              • Accessing a COM Server from a NET Client
              • Summary
Page 12: Consuming ArcIMS Image Services using .NET Client Web ... · Consuming ArcIMS Image Services using .NET Client Web Applications An ESRI White Paper Ł October 2002 ... The .NET framework

o Project Add References COM ArcIMS ActiveX Connector (Aims_ActiveXdll)

o Project Add References NET adodb ( adodbdll)

Add controls to the form and set the appropriate properties (NameCaption Size etc)

Right click on the WebForm1aspx file and choose Viewcode Type the code shown below Click on Build-gtSolution Press CTRL+F5 to start without debugging or F5 to Start (with debugging)

ESRI White Paper 9

Code from Web Form1aspxvb the codebehind page for the Web Form

Define and instantiate class variables Refer to the Section Accessing a COM Server from a NET Client for a discussion on using early and late binding mechanisms to instantiate COM objects

Private mapStates As aimsMap()

Private conArcIMS As aimsArcIMSConnector()

The Page_Load event sets up the connection and map parameters It also links the image URL (provided by ArcIMS) to the URL property of the Image control to display the map image

Private Sub Page_load(ByVal sender As SystemObject ByVal e As SystemEventArgs) Handles MyBaseLoad mapStates = New aimsMap() conArcIMS = New aimsArcIMSConnector() conArcIMSServerName = localhost conArcIMSServerPort = 5300 mapStatesInitMap(conArcIMS BPC_States) mapStatesWidth = 550 mapStatesHeight = 400 mapStatesRefresh()

ESRI White Paper 10

ImageButton1ImageUrl = mapStatesGetImageAsUrl

End Sub

The Button Click event makes a connection to the bpc2002mdb access database It then reads the data from the States column orders it alphabetically and then populates the DropDownList control with the ordered list of entries

Private Sub Button1_Click(ByVal sender As SystemObject ByVal e As SystemEventArgs) Handles Button1Click Dim conDB As OleDbOleDbConnection Dim cmdFetch As OleDbOleDbCommand Dim rdrStates As OleDbOleDbDataReader Dim sCon As String = Provider=MicrosoftJetOLEDB40Data Source=CArcIMSWebsiteBPC_Statesbpc2002mdb conDB = New OleDbOleDbConnection(sCon) conDBOpen() cmdFetch = New OleDbOleDbCommand(SELECT STATE_NAME FROM STATES ORDER BY STATE_NAME) cmdFetchConnection = conDB rdrStates = cmdFetchExecuteReader() While rdrStatesRead() DropDownList1ItemsAdd(New ListItem(rdrStatesGetString(0))) End While conDBClose()

End Sub

The DropDownList fires a SelectedIndexChanged event The code associated with this event uses the where expression with LayersItem()Filter to create an image with a special highlight applied to the selected state The URL of the image is linked to the image buttons URL to display the new image

Private Sub DropDownList1_SelectedIndexChanged(ByVal sender As Object ByVal e As SystemEventArgs) Handles DropDownList1SelectedIndexChanged Dim sWhere As String = STATE_NAME = amp DropDownList1SelectedItemText amp mapStatesLayersItem(4)FilterWhereExpression = sWhere mapStatesRefresh() ImageButton1ImageUrl = mapStatesGetImageAsUrl End Sub

The Page_Unload event is used for clean up code Here it is used to free memory by setting the map and connection object to Nothing

ESRI White Paper 11

Private Sub Page_unload(ByVal sender As Object ByVal e As SystemEventArgs) Handles MyBaseUnload mapStates = Nothing conArcIMS = Nothing

End Sub

Example 2

General Description

This web application demonstrates the use of two image controls in a web form to display a map image and its associated legend both images being served up by ArcIMS The web application also has controls for Zoomin Zoomout and pan

Programming Environment ASPNET and Web Forms

Programming Language Visual Basic NET

WebForm Controls

ESRI White Paper 12

Control Name Function ImgMap Control for displaying the image ImgLegend Control for displaying the legend image lstNavControls Radiobutton list controls

Data Files

Can use any datafile capable of generating an image service Replace the sf parameter in the page_load event with the appropriate image service name

Class Libraries ( Logic_classes assembly)

File Name Class Information Functionality MapVB The Cmap class has a

MustInherit Keyword and is inherited by Cviewer The MustInherit keyword specifies that a class cannot be instantiated and can be used only as a base class

PointVB Used by Cmap Crect Represents a geometric point (xy pair ) RectVB Used by Cmap Cviewer and

Webform3 in testformaspx

ViewerVB Used in Webform3 in testformaspx

Abstracts the requesting of a simple map from ArcIMS No additional entities will be added to the map (ie graphics buffer etc) The map is requested with all the default parameters with which it is served excepting extent and background color

Steps to Create Application

ESRI White Paper 13

The following section details the code found in the code behind page of the Testformaspx page

Statement to import logic_classes Makes all the functionality available in the logic_classes project available to the code in the web form

Imports logic_classes

Define a class level variable in the aspx file

Private m_objViewerMap As cViewer

Code for the page load event Uses IsPostback to determine if the extents need to be read afresh or from a previous valued stored in the session object Also instantiates the Cviewer class object You need to make sure that the extents shown in the code are appropriately changed to work with your selected image service

Private Sub Page_Load(ByVal sender As SystemObject ByVal e As SystemEventArgs) Handles MyBaseLoad

ESRI White Paper 14

Put user code to initialize the page here Dim rctExtent As cRect If Not IsPostBack Then enter appropriate extents rctExtent = New cRect(-1225173 377199 -122363678 3780374) Else rctExtent = New cRect(Session(MinX) Session(MinY) Session(MaxX) Session(MaxY)) End If m_objViewerMap = New cViewer(httplocalhostservletcomesriesrimapEsrimap _ sf _ rctExtent _ imgMapWidthValue _ imgMapHeightValue _ 000) add test markers

End Sub

Page_Prerender event code Links the output image to the Picture controls Also since HTTP is a stateless protocol the current map extents are stored in session variables for follow-up requests from the same user

Private Sub Page_PreRender(ByVal sender As Object ByVal e As SystemEventArgs) Handles MyBasePreRender imgMapImageUrl = m_objViewerMapMap() imgLegendImageUrl = m_objViewerMapLegend() Session(MinX) = m_objViewerMapExtentXMin Session(MinY) = m_objViewerMapExtentYMin Session(MaxX) = m_objViewerMapExtentXMax Session(MaxY) = m_objViewerMapExtentYMax

End Sub

Imgmap_click event is raised when the user clicks on the map Code associated with this event converts the image click coordinate to a map coordinate Then

ESRI White Paper 15

based on the radio button selection ( Zoomin Zoomout or pan) the code calls the appropriate method using the instantiated Cviewer object

Private Sub imgMap_Click(ByVal sender As Object ByVal e As SystemWebUIImageClickEventArgs) Handles imgMapClick Convert the image click coordinate to a map coordinate based on the maps current extent Dim rctCurrentExtent As cRect = m_objViewerMapExtent Dim dblX As Double = rctCurrentExtentXMin + ((eX imgMapWidthValue) (rctCurrentExtentXMax - rctCurrentExtentXMin)) Dim dblY As Double = rctCurrentExtentYMin + (((imgMapHeightValue - eY) imgMapHeightValue) (rctCurrentExtentYMax - rctCurrentExtentYMin)) If Trim(UCase(lstNavControlsSelectedItemText)) ltgt IDENTIFY Then m_objViewerMapCenterAt(dblX dblY) Select Case UCase(lstNavControlsSelectedItemText) Case ZOOM IN Center the map m_objViewerMapZoom(-1) Case ZOOM OUT m_objViewerMapZoom(1) Case PAN do nothing Case Else ErrRaise(vbObjectError + 512 imgMap_Click Invalid command) End Select Else identify End If End Sub

ESRI White Paper 16

End Class

NOTE =gt Once you have the relevant files imported into Visual Studio make sure that you configure the virtual directory as an application before you run the example

If the virtual directory is not configured as an Application you will get an error message that reads This error can be caused by a virtual directory not being configured as an application in IIS To configure a Virtual directory is simple Use the Internet Service Manager to perform the following steps

Find the folder in the virtual directory Right click and choose properties Click Create Accept all the settings and Click OK

Example 3

General Description

The program uses the catalog service (using the ltGETCLIENTSERVICESgt request) to query and list a collection of services running on the server A Radiobutton list control is used to list all the service names running on the server On selecting an appropriate image service the map image is displayed on the web form using an image control This program demonstrates two different ways to connect to the datasource Connection could be achieved using the http protocol or the TCP protocol The TCP method utilizes the TCP capability built into the ActiveX Connector Since ASPNET is a multithreaded and the ActiveX connector being Single Threaded (STA) a wrapper class with additional functionality to manage memory is used to access the methods in the ActiveX connector

ESRI White Paper 17

Programming Environment ASPNET and Web Forms

C NET Programming Language

WebForm Controls

Control Name Function ImgMap Control for displaying the image RbServices Radiobutton list controls Txtinfo Displays the name of the selected image service

Data Files

Requires a collection of image services running on an ArcIMS server The program uses the ltGETCLIENTSERVICESgt request tag to query the catalog service to list all the services running on the specified server

Class Libraries

File Name Class Information Functionality Connectioncs Abstract base class Provides abstract method

templates for the HTTPConnection and

ESRI White Paper 18

TCPConnection classes HTTPConnectioncs Inherits from Connection class Provides functionality for

sending request to service postinggetting URL content etc

TCPConnectioncs Inherits from Connection class and SystemIDisposable

Utlizes the AICLib assembly to access connection functionality built into the ActiveX connector

Datasourcecs Provides method for accessing path port host and other information

Enumerationscs Provides enumerations for AccessType and LoadType

Envelopecs Provides methods for getting and setting xy coordinates of the envelope

ImageReturnObjectcs Provides methods for settinggetting image URL image envelope and image scale

Mapcs Calls send request to service with connection and service information Parses response to obtain image URL

Servicecs Servicescs Inherits from

SystemCollectionsHashtable Composes the clientservices request and parses the response Creates a hashtable association of individual service name with its associated service object

XML helper class that provides relevant XML parsing functionality by acting as a wrapper class around NETs xml Text IO and other NET classes

XMLRequestscs Builds ArcXML strings for requests

XMLHelpercs

Steps to Create Application

ESRI White Paper 19

The NET solution contains 2 projects ArcIMS and ArcIMSSample The ArcIMS project

o References the InteropAICLib o Contains NET ArcIMS class libraries that can be used to connect and to

work with image services The ArcIMSSample project

o References the ArcIMS project o Contains the web form (webform1aspx) and the corresponding

webform1aspxcs code-behind page that connects the web page controls to relevant functionality using an event driven web forms model

Points to Note

In webform1aspxcs code session variables are used to maintain state of serialized objects In order for this to be possible notice that the relevant classes have been marked as serializable

ESRI White Paper 20

Choose the appropriate connection type based on HTTP or TCP connection For HTTP choose m_dsConnectType = ConnectionTypeInterNet and for For TCP select m_dsConnectType = ConnectionTypeIntraNet as shown in the code below

private ArcIMSDataSource getDataSource() m_ds = Session[datasource] as ArcIMSDataSource if ( m_ds == null ) m_ds = new ArcIMSDataSource() m_dsHost = localhost m_dsScheme = http m_dsPort = 80 m_dsAppServerPort = 5300 m_dsPath = servletcomesriesrimapEsrimap choose (comment uncomment) one of the following two statements to decide between TCP or HTTP type connection m_dsConnectType = ConnectionTypeIntraNet m_dsConnectType = ConnectionTypeInterNet SessionAdd(datasource m_ds) return m_ds

Accessing a COM Server from a NET Client With the introduction of the NET Framework and ASPNET COM at its basic level has not really changed Nevertheless there are a couple of issues to be aware of when making calls to a COM object from a NET managed code environment The ASPNET threading model is the Multiple Threaded Apartment (MTA) This will not interact reliably with STA components (the ActiveX connector provided with the ArcIMS setup was built as an STA component) To emphasize this issue heres a direct quote from the MSDN pages at Microsoft The ASPNET threading model is the Multiple Threaded Apartment (MTA) What this means is that components that you are using that were created for the Single Threaded Apartment (STA) will no longer perform or function reliably without taking some extra precautions in ASPNET This includes but is not limited to all COM components that have been created using Visual Basic 60 and earlier versions

To understand the issues better let us take a look at how NET deals with COM related issues The Common Language Runtime exposes COM objects through a proxy called the runtime callable wrapper (RCW) The RCWs primary function is to marshal calls between a NET client and COM object The RCW object is nothing but an object instantiated at runtime from class code contained in the Interop assembly

ESRI White Paper 21

Calling between managed and unmanaged components incurs a marshaling cost which can impede the performance of your pages When a managed client and unmanaged server are in the same apartment the Interop marshalling service handles all data marshalling However when client and server are initialized in different apartments COM marshalling is also required Therefore interoperability with COM from a NET client should take into consideration the threading model used

Figure Cross-apartment call between a NET client and COM object

As mentioned earlier ASPNET follows an MTA model by default You could use the default model to communicate with an STA COM component if there is not much of an overhead due to the cross-apartment marshalling Usually this is noticeable only when there are many calls across the boundary Another option would be to use the PageAspCompatMode property of the ASPNET client The ASPCompat=true attribute enables an STA thread pool to address performance with existing Visual Basic components on a per-page basis The runtime throws an exception if the compatibility tag is omitted and an STA component is referenced on the page If you convert the STA component to an assembly using Type Library Importer (a utility included with the NET SDK) the runtime does not detect that the component uses the STA model and does not throw an exception but your application can suffer from poor performance and possible deadlocks STA components cannot be used from NET Framework code modules (compiled NET assemblies) they can be used only from ASPNET pages

If you plan to use the ASPCOMPAT = TRUE page level directive for Example 1 remember to instantiate the COM object within the page_load event rather than constructing COM components during page construction time For example look at code examples A and B

Example A Example B ltPage Language = VB ASPCOMPAT = truegt

ltscript runat = servergt

private mapStates as new aimsMap()

private sub_load ()

ltPage Language = VB ASPCOMPAT = truegt

ltscript runat = servergt

private mapStates as aimsMap()

private sub_load ()

ESRI White Paper 22

end sub

mapStates = new aimsMap()

end sub

In example A the STA component would be instantiated at page construction time which is created from a thread that is not the STA thread that will run the page This will involve marshalling between MTA and STA threads during the construction of the page Example B shows the preferred mechanism to delay the process until later when the code executes under a STA thread It is best to construct any COM component and external resources when needed or in the Page_Load method

Also to create the object you can use either the New keyword or the CreateObject method The CreateObject method is typically used when you dont know the Program ID (ProgID) of the object you are going to create until run time (late binding) New is the recommended method for instantiating objects if you have access to the objects type library It is preferable to adopt the early binding model

Every scenario yields different performance characteristics so it is important to test adequately before deciding whether interoperability is the right choice for your application However in nearly all scenarios rewriting your COM components in managed code provides performance benefits

Summary The examples shown above provide adequate information to leverage the NET programming environment to build effective ArcIMS client applications The debugging features of a program like Visual StudioNET provide a variety of tools (break points trace etc) making the entire development experience considerably pain-free Use the debugger to understand the sequence in which calls are made One early exercise would be to look at the calling sequence of the various page related events such as page_init page_load and page_prerender Since the Web Forms code is compiled you should experience much better performance than with ASP pages that used code written in scripting languages like Javascript and VbScript

The powerful programming environment also means that you can now concentrate more on the logic of building large web applications as opposed to building simple page based asp applications Also look at the various caching mechanisms provided by ASPNET as these can be used to improve overall performance As always there are costs associated with most programming choices and this is all the more true in a web-programming environment For example consider the costs associated with using a web control as opposed to a HTML based control Use plain HTML controls instead of adopting web controls for simple items like label

ESRI White Paper 23

If you choose to use the ActiveX connector from within the NET environment make sure that you clearly understand the essentials of COM Interop and the various costs associated with marshalling The solutions outlined in this paper utilize existing ArcIMS services and should work with all versions of ArcIMS

Although all the development can be done without the use of an Integrated Development environment (IDE) like Visual StudioNET using such an environment provides convenient WYSIWYG features that can help in building and debugging the application If you do not have Visual StudioNET there are free IDEs available today that can also be used For example ASPNET Web Matrix is a community-supported easy-to-use WYSIWYG application development tool for ASPNET It can be installed via a quick 12 MB download from httpwwwaspnetwebmatrixdefaultaspx

ESRI White Paper 24

  • ArcIMS ndash An Introduction
  • What is NET
    • The NET Framework
      • The Common Language Runtime (CLR)
      • Managed Unmanaged and Unsafe code ndash Understandin
      • NET Framework Class Libraries
        • ASPNET and Web Forms
          • NET and ArcIMS
            • Example 1
            • Example 2
            • Example 3
              • Accessing a COM Server from a NET Client
              • Summary
Page 13: Consuming ArcIMS Image Services using .NET Client Web ... · Consuming ArcIMS Image Services using .NET Client Web Applications An ESRI White Paper Ł October 2002 ... The .NET framework

Code from Web Form1aspxvb the codebehind page for the Web Form

Define and instantiate class variables Refer to the Section Accessing a COM Server from a NET Client for a discussion on using early and late binding mechanisms to instantiate COM objects

Private mapStates As aimsMap()

Private conArcIMS As aimsArcIMSConnector()

The Page_Load event sets up the connection and map parameters It also links the image URL (provided by ArcIMS) to the URL property of the Image control to display the map image

Private Sub Page_load(ByVal sender As SystemObject ByVal e As SystemEventArgs) Handles MyBaseLoad mapStates = New aimsMap() conArcIMS = New aimsArcIMSConnector() conArcIMSServerName = localhost conArcIMSServerPort = 5300 mapStatesInitMap(conArcIMS BPC_States) mapStatesWidth = 550 mapStatesHeight = 400 mapStatesRefresh()

ESRI White Paper 10

ImageButton1ImageUrl = mapStatesGetImageAsUrl

End Sub

The Button Click event makes a connection to the bpc2002mdb access database It then reads the data from the States column orders it alphabetically and then populates the DropDownList control with the ordered list of entries

Private Sub Button1_Click(ByVal sender As SystemObject ByVal e As SystemEventArgs) Handles Button1Click Dim conDB As OleDbOleDbConnection Dim cmdFetch As OleDbOleDbCommand Dim rdrStates As OleDbOleDbDataReader Dim sCon As String = Provider=MicrosoftJetOLEDB40Data Source=CArcIMSWebsiteBPC_Statesbpc2002mdb conDB = New OleDbOleDbConnection(sCon) conDBOpen() cmdFetch = New OleDbOleDbCommand(SELECT STATE_NAME FROM STATES ORDER BY STATE_NAME) cmdFetchConnection = conDB rdrStates = cmdFetchExecuteReader() While rdrStatesRead() DropDownList1ItemsAdd(New ListItem(rdrStatesGetString(0))) End While conDBClose()

End Sub

The DropDownList fires a SelectedIndexChanged event The code associated with this event uses the where expression with LayersItem()Filter to create an image with a special highlight applied to the selected state The URL of the image is linked to the image buttons URL to display the new image

Private Sub DropDownList1_SelectedIndexChanged(ByVal sender As Object ByVal e As SystemEventArgs) Handles DropDownList1SelectedIndexChanged Dim sWhere As String = STATE_NAME = amp DropDownList1SelectedItemText amp mapStatesLayersItem(4)FilterWhereExpression = sWhere mapStatesRefresh() ImageButton1ImageUrl = mapStatesGetImageAsUrl End Sub

The Page_Unload event is used for clean up code Here it is used to free memory by setting the map and connection object to Nothing

ESRI White Paper 11

Private Sub Page_unload(ByVal sender As Object ByVal e As SystemEventArgs) Handles MyBaseUnload mapStates = Nothing conArcIMS = Nothing

End Sub

Example 2

General Description

This web application demonstrates the use of two image controls in a web form to display a map image and its associated legend both images being served up by ArcIMS The web application also has controls for Zoomin Zoomout and pan

Programming Environment ASPNET and Web Forms

Programming Language Visual Basic NET

WebForm Controls

ESRI White Paper 12

Control Name Function ImgMap Control for displaying the image ImgLegend Control for displaying the legend image lstNavControls Radiobutton list controls

Data Files

Can use any datafile capable of generating an image service Replace the sf parameter in the page_load event with the appropriate image service name

Class Libraries ( Logic_classes assembly)

File Name Class Information Functionality MapVB The Cmap class has a

MustInherit Keyword and is inherited by Cviewer The MustInherit keyword specifies that a class cannot be instantiated and can be used only as a base class

PointVB Used by Cmap Crect Represents a geometric point (xy pair ) RectVB Used by Cmap Cviewer and

Webform3 in testformaspx

ViewerVB Used in Webform3 in testformaspx

Abstracts the requesting of a simple map from ArcIMS No additional entities will be added to the map (ie graphics buffer etc) The map is requested with all the default parameters with which it is served excepting extent and background color

Steps to Create Application

ESRI White Paper 13

The following section details the code found in the code behind page of the Testformaspx page

Statement to import logic_classes Makes all the functionality available in the logic_classes project available to the code in the web form

Imports logic_classes

Define a class level variable in the aspx file

Private m_objViewerMap As cViewer

Code for the page load event Uses IsPostback to determine if the extents need to be read afresh or from a previous valued stored in the session object Also instantiates the Cviewer class object You need to make sure that the extents shown in the code are appropriately changed to work with your selected image service

Private Sub Page_Load(ByVal sender As SystemObject ByVal e As SystemEventArgs) Handles MyBaseLoad

ESRI White Paper 14

Put user code to initialize the page here Dim rctExtent As cRect If Not IsPostBack Then enter appropriate extents rctExtent = New cRect(-1225173 377199 -122363678 3780374) Else rctExtent = New cRect(Session(MinX) Session(MinY) Session(MaxX) Session(MaxY)) End If m_objViewerMap = New cViewer(httplocalhostservletcomesriesrimapEsrimap _ sf _ rctExtent _ imgMapWidthValue _ imgMapHeightValue _ 000) add test markers

End Sub

Page_Prerender event code Links the output image to the Picture controls Also since HTTP is a stateless protocol the current map extents are stored in session variables for follow-up requests from the same user

Private Sub Page_PreRender(ByVal sender As Object ByVal e As SystemEventArgs) Handles MyBasePreRender imgMapImageUrl = m_objViewerMapMap() imgLegendImageUrl = m_objViewerMapLegend() Session(MinX) = m_objViewerMapExtentXMin Session(MinY) = m_objViewerMapExtentYMin Session(MaxX) = m_objViewerMapExtentXMax Session(MaxY) = m_objViewerMapExtentYMax

End Sub

Imgmap_click event is raised when the user clicks on the map Code associated with this event converts the image click coordinate to a map coordinate Then

ESRI White Paper 15

based on the radio button selection ( Zoomin Zoomout or pan) the code calls the appropriate method using the instantiated Cviewer object

Private Sub imgMap_Click(ByVal sender As Object ByVal e As SystemWebUIImageClickEventArgs) Handles imgMapClick Convert the image click coordinate to a map coordinate based on the maps current extent Dim rctCurrentExtent As cRect = m_objViewerMapExtent Dim dblX As Double = rctCurrentExtentXMin + ((eX imgMapWidthValue) (rctCurrentExtentXMax - rctCurrentExtentXMin)) Dim dblY As Double = rctCurrentExtentYMin + (((imgMapHeightValue - eY) imgMapHeightValue) (rctCurrentExtentYMax - rctCurrentExtentYMin)) If Trim(UCase(lstNavControlsSelectedItemText)) ltgt IDENTIFY Then m_objViewerMapCenterAt(dblX dblY) Select Case UCase(lstNavControlsSelectedItemText) Case ZOOM IN Center the map m_objViewerMapZoom(-1) Case ZOOM OUT m_objViewerMapZoom(1) Case PAN do nothing Case Else ErrRaise(vbObjectError + 512 imgMap_Click Invalid command) End Select Else identify End If End Sub

ESRI White Paper 16

End Class

NOTE =gt Once you have the relevant files imported into Visual Studio make sure that you configure the virtual directory as an application before you run the example

If the virtual directory is not configured as an Application you will get an error message that reads This error can be caused by a virtual directory not being configured as an application in IIS To configure a Virtual directory is simple Use the Internet Service Manager to perform the following steps

Find the folder in the virtual directory Right click and choose properties Click Create Accept all the settings and Click OK

Example 3

General Description

The program uses the catalog service (using the ltGETCLIENTSERVICESgt request) to query and list a collection of services running on the server A Radiobutton list control is used to list all the service names running on the server On selecting an appropriate image service the map image is displayed on the web form using an image control This program demonstrates two different ways to connect to the datasource Connection could be achieved using the http protocol or the TCP protocol The TCP method utilizes the TCP capability built into the ActiveX Connector Since ASPNET is a multithreaded and the ActiveX connector being Single Threaded (STA) a wrapper class with additional functionality to manage memory is used to access the methods in the ActiveX connector

ESRI White Paper 17

Programming Environment ASPNET and Web Forms

C NET Programming Language

WebForm Controls

Control Name Function ImgMap Control for displaying the image RbServices Radiobutton list controls Txtinfo Displays the name of the selected image service

Data Files

Requires a collection of image services running on an ArcIMS server The program uses the ltGETCLIENTSERVICESgt request tag to query the catalog service to list all the services running on the specified server

Class Libraries

File Name Class Information Functionality Connectioncs Abstract base class Provides abstract method

templates for the HTTPConnection and

ESRI White Paper 18

TCPConnection classes HTTPConnectioncs Inherits from Connection class Provides functionality for

sending request to service postinggetting URL content etc

TCPConnectioncs Inherits from Connection class and SystemIDisposable

Utlizes the AICLib assembly to access connection functionality built into the ActiveX connector

Datasourcecs Provides method for accessing path port host and other information

Enumerationscs Provides enumerations for AccessType and LoadType

Envelopecs Provides methods for getting and setting xy coordinates of the envelope

ImageReturnObjectcs Provides methods for settinggetting image URL image envelope and image scale

Mapcs Calls send request to service with connection and service information Parses response to obtain image URL

Servicecs Servicescs Inherits from

SystemCollectionsHashtable Composes the clientservices request and parses the response Creates a hashtable association of individual service name with its associated service object

XML helper class that provides relevant XML parsing functionality by acting as a wrapper class around NETs xml Text IO and other NET classes

XMLRequestscs Builds ArcXML strings for requests

XMLHelpercs

Steps to Create Application

ESRI White Paper 19

The NET solution contains 2 projects ArcIMS and ArcIMSSample The ArcIMS project

o References the InteropAICLib o Contains NET ArcIMS class libraries that can be used to connect and to

work with image services The ArcIMSSample project

o References the ArcIMS project o Contains the web form (webform1aspx) and the corresponding

webform1aspxcs code-behind page that connects the web page controls to relevant functionality using an event driven web forms model

Points to Note

In webform1aspxcs code session variables are used to maintain state of serialized objects In order for this to be possible notice that the relevant classes have been marked as serializable

ESRI White Paper 20

Choose the appropriate connection type based on HTTP or TCP connection For HTTP choose m_dsConnectType = ConnectionTypeInterNet and for For TCP select m_dsConnectType = ConnectionTypeIntraNet as shown in the code below

private ArcIMSDataSource getDataSource() m_ds = Session[datasource] as ArcIMSDataSource if ( m_ds == null ) m_ds = new ArcIMSDataSource() m_dsHost = localhost m_dsScheme = http m_dsPort = 80 m_dsAppServerPort = 5300 m_dsPath = servletcomesriesrimapEsrimap choose (comment uncomment) one of the following two statements to decide between TCP or HTTP type connection m_dsConnectType = ConnectionTypeIntraNet m_dsConnectType = ConnectionTypeInterNet SessionAdd(datasource m_ds) return m_ds

Accessing a COM Server from a NET Client With the introduction of the NET Framework and ASPNET COM at its basic level has not really changed Nevertheless there are a couple of issues to be aware of when making calls to a COM object from a NET managed code environment The ASPNET threading model is the Multiple Threaded Apartment (MTA) This will not interact reliably with STA components (the ActiveX connector provided with the ArcIMS setup was built as an STA component) To emphasize this issue heres a direct quote from the MSDN pages at Microsoft The ASPNET threading model is the Multiple Threaded Apartment (MTA) What this means is that components that you are using that were created for the Single Threaded Apartment (STA) will no longer perform or function reliably without taking some extra precautions in ASPNET This includes but is not limited to all COM components that have been created using Visual Basic 60 and earlier versions

To understand the issues better let us take a look at how NET deals with COM related issues The Common Language Runtime exposes COM objects through a proxy called the runtime callable wrapper (RCW) The RCWs primary function is to marshal calls between a NET client and COM object The RCW object is nothing but an object instantiated at runtime from class code contained in the Interop assembly

ESRI White Paper 21

Calling between managed and unmanaged components incurs a marshaling cost which can impede the performance of your pages When a managed client and unmanaged server are in the same apartment the Interop marshalling service handles all data marshalling However when client and server are initialized in different apartments COM marshalling is also required Therefore interoperability with COM from a NET client should take into consideration the threading model used

Figure Cross-apartment call between a NET client and COM object

As mentioned earlier ASPNET follows an MTA model by default You could use the default model to communicate with an STA COM component if there is not much of an overhead due to the cross-apartment marshalling Usually this is noticeable only when there are many calls across the boundary Another option would be to use the PageAspCompatMode property of the ASPNET client The ASPCompat=true attribute enables an STA thread pool to address performance with existing Visual Basic components on a per-page basis The runtime throws an exception if the compatibility tag is omitted and an STA component is referenced on the page If you convert the STA component to an assembly using Type Library Importer (a utility included with the NET SDK) the runtime does not detect that the component uses the STA model and does not throw an exception but your application can suffer from poor performance and possible deadlocks STA components cannot be used from NET Framework code modules (compiled NET assemblies) they can be used only from ASPNET pages

If you plan to use the ASPCOMPAT = TRUE page level directive for Example 1 remember to instantiate the COM object within the page_load event rather than constructing COM components during page construction time For example look at code examples A and B

Example A Example B ltPage Language = VB ASPCOMPAT = truegt

ltscript runat = servergt

private mapStates as new aimsMap()

private sub_load ()

ltPage Language = VB ASPCOMPAT = truegt

ltscript runat = servergt

private mapStates as aimsMap()

private sub_load ()

ESRI White Paper 22

end sub

mapStates = new aimsMap()

end sub

In example A the STA component would be instantiated at page construction time which is created from a thread that is not the STA thread that will run the page This will involve marshalling between MTA and STA threads during the construction of the page Example B shows the preferred mechanism to delay the process until later when the code executes under a STA thread It is best to construct any COM component and external resources when needed or in the Page_Load method

Also to create the object you can use either the New keyword or the CreateObject method The CreateObject method is typically used when you dont know the Program ID (ProgID) of the object you are going to create until run time (late binding) New is the recommended method for instantiating objects if you have access to the objects type library It is preferable to adopt the early binding model

Every scenario yields different performance characteristics so it is important to test adequately before deciding whether interoperability is the right choice for your application However in nearly all scenarios rewriting your COM components in managed code provides performance benefits

Summary The examples shown above provide adequate information to leverage the NET programming environment to build effective ArcIMS client applications The debugging features of a program like Visual StudioNET provide a variety of tools (break points trace etc) making the entire development experience considerably pain-free Use the debugger to understand the sequence in which calls are made One early exercise would be to look at the calling sequence of the various page related events such as page_init page_load and page_prerender Since the Web Forms code is compiled you should experience much better performance than with ASP pages that used code written in scripting languages like Javascript and VbScript

The powerful programming environment also means that you can now concentrate more on the logic of building large web applications as opposed to building simple page based asp applications Also look at the various caching mechanisms provided by ASPNET as these can be used to improve overall performance As always there are costs associated with most programming choices and this is all the more true in a web-programming environment For example consider the costs associated with using a web control as opposed to a HTML based control Use plain HTML controls instead of adopting web controls for simple items like label

ESRI White Paper 23

If you choose to use the ActiveX connector from within the NET environment make sure that you clearly understand the essentials of COM Interop and the various costs associated with marshalling The solutions outlined in this paper utilize existing ArcIMS services and should work with all versions of ArcIMS

Although all the development can be done without the use of an Integrated Development environment (IDE) like Visual StudioNET using such an environment provides convenient WYSIWYG features that can help in building and debugging the application If you do not have Visual StudioNET there are free IDEs available today that can also be used For example ASPNET Web Matrix is a community-supported easy-to-use WYSIWYG application development tool for ASPNET It can be installed via a quick 12 MB download from httpwwwaspnetwebmatrixdefaultaspx

ESRI White Paper 24

  • ArcIMS ndash An Introduction
  • What is NET
    • The NET Framework
      • The Common Language Runtime (CLR)
      • Managed Unmanaged and Unsafe code ndash Understandin
      • NET Framework Class Libraries
        • ASPNET and Web Forms
          • NET and ArcIMS
            • Example 1
            • Example 2
            • Example 3
              • Accessing a COM Server from a NET Client
              • Summary
Page 14: Consuming ArcIMS Image Services using .NET Client Web ... · Consuming ArcIMS Image Services using .NET Client Web Applications An ESRI White Paper Ł October 2002 ... The .NET framework

ImageButton1ImageUrl = mapStatesGetImageAsUrl

End Sub

The Button Click event makes a connection to the bpc2002mdb access database It then reads the data from the States column orders it alphabetically and then populates the DropDownList control with the ordered list of entries

Private Sub Button1_Click(ByVal sender As SystemObject ByVal e As SystemEventArgs) Handles Button1Click Dim conDB As OleDbOleDbConnection Dim cmdFetch As OleDbOleDbCommand Dim rdrStates As OleDbOleDbDataReader Dim sCon As String = Provider=MicrosoftJetOLEDB40Data Source=CArcIMSWebsiteBPC_Statesbpc2002mdb conDB = New OleDbOleDbConnection(sCon) conDBOpen() cmdFetch = New OleDbOleDbCommand(SELECT STATE_NAME FROM STATES ORDER BY STATE_NAME) cmdFetchConnection = conDB rdrStates = cmdFetchExecuteReader() While rdrStatesRead() DropDownList1ItemsAdd(New ListItem(rdrStatesGetString(0))) End While conDBClose()

End Sub

The DropDownList fires a SelectedIndexChanged event The code associated with this event uses the where expression with LayersItem()Filter to create an image with a special highlight applied to the selected state The URL of the image is linked to the image buttons URL to display the new image

Private Sub DropDownList1_SelectedIndexChanged(ByVal sender As Object ByVal e As SystemEventArgs) Handles DropDownList1SelectedIndexChanged Dim sWhere As String = STATE_NAME = amp DropDownList1SelectedItemText amp mapStatesLayersItem(4)FilterWhereExpression = sWhere mapStatesRefresh() ImageButton1ImageUrl = mapStatesGetImageAsUrl End Sub

The Page_Unload event is used for clean up code Here it is used to free memory by setting the map and connection object to Nothing

ESRI White Paper 11

Private Sub Page_unload(ByVal sender As Object ByVal e As SystemEventArgs) Handles MyBaseUnload mapStates = Nothing conArcIMS = Nothing

End Sub

Example 2

General Description

This web application demonstrates the use of two image controls in a web form to display a map image and its associated legend both images being served up by ArcIMS The web application also has controls for Zoomin Zoomout and pan

Programming Environment ASPNET and Web Forms

Programming Language Visual Basic NET

WebForm Controls

ESRI White Paper 12

Control Name Function ImgMap Control for displaying the image ImgLegend Control for displaying the legend image lstNavControls Radiobutton list controls

Data Files

Can use any datafile capable of generating an image service Replace the sf parameter in the page_load event with the appropriate image service name

Class Libraries ( Logic_classes assembly)

File Name Class Information Functionality MapVB The Cmap class has a

MustInherit Keyword and is inherited by Cviewer The MustInherit keyword specifies that a class cannot be instantiated and can be used only as a base class

PointVB Used by Cmap Crect Represents a geometric point (xy pair ) RectVB Used by Cmap Cviewer and

Webform3 in testformaspx

ViewerVB Used in Webform3 in testformaspx

Abstracts the requesting of a simple map from ArcIMS No additional entities will be added to the map (ie graphics buffer etc) The map is requested with all the default parameters with which it is served excepting extent and background color

Steps to Create Application

ESRI White Paper 13

The following section details the code found in the code behind page of the Testformaspx page

Statement to import logic_classes Makes all the functionality available in the logic_classes project available to the code in the web form

Imports logic_classes

Define a class level variable in the aspx file

Private m_objViewerMap As cViewer

Code for the page load event Uses IsPostback to determine if the extents need to be read afresh or from a previous valued stored in the session object Also instantiates the Cviewer class object You need to make sure that the extents shown in the code are appropriately changed to work with your selected image service

Private Sub Page_Load(ByVal sender As SystemObject ByVal e As SystemEventArgs) Handles MyBaseLoad

ESRI White Paper 14

Put user code to initialize the page here Dim rctExtent As cRect If Not IsPostBack Then enter appropriate extents rctExtent = New cRect(-1225173 377199 -122363678 3780374) Else rctExtent = New cRect(Session(MinX) Session(MinY) Session(MaxX) Session(MaxY)) End If m_objViewerMap = New cViewer(httplocalhostservletcomesriesrimapEsrimap _ sf _ rctExtent _ imgMapWidthValue _ imgMapHeightValue _ 000) add test markers

End Sub

Page_Prerender event code Links the output image to the Picture controls Also since HTTP is a stateless protocol the current map extents are stored in session variables for follow-up requests from the same user

Private Sub Page_PreRender(ByVal sender As Object ByVal e As SystemEventArgs) Handles MyBasePreRender imgMapImageUrl = m_objViewerMapMap() imgLegendImageUrl = m_objViewerMapLegend() Session(MinX) = m_objViewerMapExtentXMin Session(MinY) = m_objViewerMapExtentYMin Session(MaxX) = m_objViewerMapExtentXMax Session(MaxY) = m_objViewerMapExtentYMax

End Sub

Imgmap_click event is raised when the user clicks on the map Code associated with this event converts the image click coordinate to a map coordinate Then

ESRI White Paper 15

based on the radio button selection ( Zoomin Zoomout or pan) the code calls the appropriate method using the instantiated Cviewer object

Private Sub imgMap_Click(ByVal sender As Object ByVal e As SystemWebUIImageClickEventArgs) Handles imgMapClick Convert the image click coordinate to a map coordinate based on the maps current extent Dim rctCurrentExtent As cRect = m_objViewerMapExtent Dim dblX As Double = rctCurrentExtentXMin + ((eX imgMapWidthValue) (rctCurrentExtentXMax - rctCurrentExtentXMin)) Dim dblY As Double = rctCurrentExtentYMin + (((imgMapHeightValue - eY) imgMapHeightValue) (rctCurrentExtentYMax - rctCurrentExtentYMin)) If Trim(UCase(lstNavControlsSelectedItemText)) ltgt IDENTIFY Then m_objViewerMapCenterAt(dblX dblY) Select Case UCase(lstNavControlsSelectedItemText) Case ZOOM IN Center the map m_objViewerMapZoom(-1) Case ZOOM OUT m_objViewerMapZoom(1) Case PAN do nothing Case Else ErrRaise(vbObjectError + 512 imgMap_Click Invalid command) End Select Else identify End If End Sub

ESRI White Paper 16

End Class

NOTE =gt Once you have the relevant files imported into Visual Studio make sure that you configure the virtual directory as an application before you run the example

If the virtual directory is not configured as an Application you will get an error message that reads This error can be caused by a virtual directory not being configured as an application in IIS To configure a Virtual directory is simple Use the Internet Service Manager to perform the following steps

Find the folder in the virtual directory Right click and choose properties Click Create Accept all the settings and Click OK

Example 3

General Description

The program uses the catalog service (using the ltGETCLIENTSERVICESgt request) to query and list a collection of services running on the server A Radiobutton list control is used to list all the service names running on the server On selecting an appropriate image service the map image is displayed on the web form using an image control This program demonstrates two different ways to connect to the datasource Connection could be achieved using the http protocol or the TCP protocol The TCP method utilizes the TCP capability built into the ActiveX Connector Since ASPNET is a multithreaded and the ActiveX connector being Single Threaded (STA) a wrapper class with additional functionality to manage memory is used to access the methods in the ActiveX connector

ESRI White Paper 17

Programming Environment ASPNET and Web Forms

C NET Programming Language

WebForm Controls

Control Name Function ImgMap Control for displaying the image RbServices Radiobutton list controls Txtinfo Displays the name of the selected image service

Data Files

Requires a collection of image services running on an ArcIMS server The program uses the ltGETCLIENTSERVICESgt request tag to query the catalog service to list all the services running on the specified server

Class Libraries

File Name Class Information Functionality Connectioncs Abstract base class Provides abstract method

templates for the HTTPConnection and

ESRI White Paper 18

TCPConnection classes HTTPConnectioncs Inherits from Connection class Provides functionality for

sending request to service postinggetting URL content etc

TCPConnectioncs Inherits from Connection class and SystemIDisposable

Utlizes the AICLib assembly to access connection functionality built into the ActiveX connector

Datasourcecs Provides method for accessing path port host and other information

Enumerationscs Provides enumerations for AccessType and LoadType

Envelopecs Provides methods for getting and setting xy coordinates of the envelope

ImageReturnObjectcs Provides methods for settinggetting image URL image envelope and image scale

Mapcs Calls send request to service with connection and service information Parses response to obtain image URL

Servicecs Servicescs Inherits from

SystemCollectionsHashtable Composes the clientservices request and parses the response Creates a hashtable association of individual service name with its associated service object

XML helper class that provides relevant XML parsing functionality by acting as a wrapper class around NETs xml Text IO and other NET classes

XMLRequestscs Builds ArcXML strings for requests

XMLHelpercs

Steps to Create Application

ESRI White Paper 19

The NET solution contains 2 projects ArcIMS and ArcIMSSample The ArcIMS project

o References the InteropAICLib o Contains NET ArcIMS class libraries that can be used to connect and to

work with image services The ArcIMSSample project

o References the ArcIMS project o Contains the web form (webform1aspx) and the corresponding

webform1aspxcs code-behind page that connects the web page controls to relevant functionality using an event driven web forms model

Points to Note

In webform1aspxcs code session variables are used to maintain state of serialized objects In order for this to be possible notice that the relevant classes have been marked as serializable

ESRI White Paper 20

Choose the appropriate connection type based on HTTP or TCP connection For HTTP choose m_dsConnectType = ConnectionTypeInterNet and for For TCP select m_dsConnectType = ConnectionTypeIntraNet as shown in the code below

private ArcIMSDataSource getDataSource() m_ds = Session[datasource] as ArcIMSDataSource if ( m_ds == null ) m_ds = new ArcIMSDataSource() m_dsHost = localhost m_dsScheme = http m_dsPort = 80 m_dsAppServerPort = 5300 m_dsPath = servletcomesriesrimapEsrimap choose (comment uncomment) one of the following two statements to decide between TCP or HTTP type connection m_dsConnectType = ConnectionTypeIntraNet m_dsConnectType = ConnectionTypeInterNet SessionAdd(datasource m_ds) return m_ds

Accessing a COM Server from a NET Client With the introduction of the NET Framework and ASPNET COM at its basic level has not really changed Nevertheless there are a couple of issues to be aware of when making calls to a COM object from a NET managed code environment The ASPNET threading model is the Multiple Threaded Apartment (MTA) This will not interact reliably with STA components (the ActiveX connector provided with the ArcIMS setup was built as an STA component) To emphasize this issue heres a direct quote from the MSDN pages at Microsoft The ASPNET threading model is the Multiple Threaded Apartment (MTA) What this means is that components that you are using that were created for the Single Threaded Apartment (STA) will no longer perform or function reliably without taking some extra precautions in ASPNET This includes but is not limited to all COM components that have been created using Visual Basic 60 and earlier versions

To understand the issues better let us take a look at how NET deals with COM related issues The Common Language Runtime exposes COM objects through a proxy called the runtime callable wrapper (RCW) The RCWs primary function is to marshal calls between a NET client and COM object The RCW object is nothing but an object instantiated at runtime from class code contained in the Interop assembly

ESRI White Paper 21

Calling between managed and unmanaged components incurs a marshaling cost which can impede the performance of your pages When a managed client and unmanaged server are in the same apartment the Interop marshalling service handles all data marshalling However when client and server are initialized in different apartments COM marshalling is also required Therefore interoperability with COM from a NET client should take into consideration the threading model used

Figure Cross-apartment call between a NET client and COM object

As mentioned earlier ASPNET follows an MTA model by default You could use the default model to communicate with an STA COM component if there is not much of an overhead due to the cross-apartment marshalling Usually this is noticeable only when there are many calls across the boundary Another option would be to use the PageAspCompatMode property of the ASPNET client The ASPCompat=true attribute enables an STA thread pool to address performance with existing Visual Basic components on a per-page basis The runtime throws an exception if the compatibility tag is omitted and an STA component is referenced on the page If you convert the STA component to an assembly using Type Library Importer (a utility included with the NET SDK) the runtime does not detect that the component uses the STA model and does not throw an exception but your application can suffer from poor performance and possible deadlocks STA components cannot be used from NET Framework code modules (compiled NET assemblies) they can be used only from ASPNET pages

If you plan to use the ASPCOMPAT = TRUE page level directive for Example 1 remember to instantiate the COM object within the page_load event rather than constructing COM components during page construction time For example look at code examples A and B

Example A Example B ltPage Language = VB ASPCOMPAT = truegt

ltscript runat = servergt

private mapStates as new aimsMap()

private sub_load ()

ltPage Language = VB ASPCOMPAT = truegt

ltscript runat = servergt

private mapStates as aimsMap()

private sub_load ()

ESRI White Paper 22

end sub

mapStates = new aimsMap()

end sub

In example A the STA component would be instantiated at page construction time which is created from a thread that is not the STA thread that will run the page This will involve marshalling between MTA and STA threads during the construction of the page Example B shows the preferred mechanism to delay the process until later when the code executes under a STA thread It is best to construct any COM component and external resources when needed or in the Page_Load method

Also to create the object you can use either the New keyword or the CreateObject method The CreateObject method is typically used when you dont know the Program ID (ProgID) of the object you are going to create until run time (late binding) New is the recommended method for instantiating objects if you have access to the objects type library It is preferable to adopt the early binding model

Every scenario yields different performance characteristics so it is important to test adequately before deciding whether interoperability is the right choice for your application However in nearly all scenarios rewriting your COM components in managed code provides performance benefits

Summary The examples shown above provide adequate information to leverage the NET programming environment to build effective ArcIMS client applications The debugging features of a program like Visual StudioNET provide a variety of tools (break points trace etc) making the entire development experience considerably pain-free Use the debugger to understand the sequence in which calls are made One early exercise would be to look at the calling sequence of the various page related events such as page_init page_load and page_prerender Since the Web Forms code is compiled you should experience much better performance than with ASP pages that used code written in scripting languages like Javascript and VbScript

The powerful programming environment also means that you can now concentrate more on the logic of building large web applications as opposed to building simple page based asp applications Also look at the various caching mechanisms provided by ASPNET as these can be used to improve overall performance As always there are costs associated with most programming choices and this is all the more true in a web-programming environment For example consider the costs associated with using a web control as opposed to a HTML based control Use plain HTML controls instead of adopting web controls for simple items like label

ESRI White Paper 23

If you choose to use the ActiveX connector from within the NET environment make sure that you clearly understand the essentials of COM Interop and the various costs associated with marshalling The solutions outlined in this paper utilize existing ArcIMS services and should work with all versions of ArcIMS

Although all the development can be done without the use of an Integrated Development environment (IDE) like Visual StudioNET using such an environment provides convenient WYSIWYG features that can help in building and debugging the application If you do not have Visual StudioNET there are free IDEs available today that can also be used For example ASPNET Web Matrix is a community-supported easy-to-use WYSIWYG application development tool for ASPNET It can be installed via a quick 12 MB download from httpwwwaspnetwebmatrixdefaultaspx

ESRI White Paper 24

  • ArcIMS ndash An Introduction
  • What is NET
    • The NET Framework
      • The Common Language Runtime (CLR)
      • Managed Unmanaged and Unsafe code ndash Understandin
      • NET Framework Class Libraries
        • ASPNET and Web Forms
          • NET and ArcIMS
            • Example 1
            • Example 2
            • Example 3
              • Accessing a COM Server from a NET Client
              • Summary
Page 15: Consuming ArcIMS Image Services using .NET Client Web ... · Consuming ArcIMS Image Services using .NET Client Web Applications An ESRI White Paper Ł October 2002 ... The .NET framework

Private Sub Page_unload(ByVal sender As Object ByVal e As SystemEventArgs) Handles MyBaseUnload mapStates = Nothing conArcIMS = Nothing

End Sub

Example 2

General Description

This web application demonstrates the use of two image controls in a web form to display a map image and its associated legend both images being served up by ArcIMS The web application also has controls for Zoomin Zoomout and pan

Programming Environment ASPNET and Web Forms

Programming Language Visual Basic NET

WebForm Controls

ESRI White Paper 12

Control Name Function ImgMap Control for displaying the image ImgLegend Control for displaying the legend image lstNavControls Radiobutton list controls

Data Files

Can use any datafile capable of generating an image service Replace the sf parameter in the page_load event with the appropriate image service name

Class Libraries ( Logic_classes assembly)

File Name Class Information Functionality MapVB The Cmap class has a

MustInherit Keyword and is inherited by Cviewer The MustInherit keyword specifies that a class cannot be instantiated and can be used only as a base class

PointVB Used by Cmap Crect Represents a geometric point (xy pair ) RectVB Used by Cmap Cviewer and

Webform3 in testformaspx

ViewerVB Used in Webform3 in testformaspx

Abstracts the requesting of a simple map from ArcIMS No additional entities will be added to the map (ie graphics buffer etc) The map is requested with all the default parameters with which it is served excepting extent and background color

Steps to Create Application

ESRI White Paper 13

The following section details the code found in the code behind page of the Testformaspx page

Statement to import logic_classes Makes all the functionality available in the logic_classes project available to the code in the web form

Imports logic_classes

Define a class level variable in the aspx file

Private m_objViewerMap As cViewer

Code for the page load event Uses IsPostback to determine if the extents need to be read afresh or from a previous valued stored in the session object Also instantiates the Cviewer class object You need to make sure that the extents shown in the code are appropriately changed to work with your selected image service

Private Sub Page_Load(ByVal sender As SystemObject ByVal e As SystemEventArgs) Handles MyBaseLoad

ESRI White Paper 14

Put user code to initialize the page here Dim rctExtent As cRect If Not IsPostBack Then enter appropriate extents rctExtent = New cRect(-1225173 377199 -122363678 3780374) Else rctExtent = New cRect(Session(MinX) Session(MinY) Session(MaxX) Session(MaxY)) End If m_objViewerMap = New cViewer(httplocalhostservletcomesriesrimapEsrimap _ sf _ rctExtent _ imgMapWidthValue _ imgMapHeightValue _ 000) add test markers

End Sub

Page_Prerender event code Links the output image to the Picture controls Also since HTTP is a stateless protocol the current map extents are stored in session variables for follow-up requests from the same user

Private Sub Page_PreRender(ByVal sender As Object ByVal e As SystemEventArgs) Handles MyBasePreRender imgMapImageUrl = m_objViewerMapMap() imgLegendImageUrl = m_objViewerMapLegend() Session(MinX) = m_objViewerMapExtentXMin Session(MinY) = m_objViewerMapExtentYMin Session(MaxX) = m_objViewerMapExtentXMax Session(MaxY) = m_objViewerMapExtentYMax

End Sub

Imgmap_click event is raised when the user clicks on the map Code associated with this event converts the image click coordinate to a map coordinate Then

ESRI White Paper 15

based on the radio button selection ( Zoomin Zoomout or pan) the code calls the appropriate method using the instantiated Cviewer object

Private Sub imgMap_Click(ByVal sender As Object ByVal e As SystemWebUIImageClickEventArgs) Handles imgMapClick Convert the image click coordinate to a map coordinate based on the maps current extent Dim rctCurrentExtent As cRect = m_objViewerMapExtent Dim dblX As Double = rctCurrentExtentXMin + ((eX imgMapWidthValue) (rctCurrentExtentXMax - rctCurrentExtentXMin)) Dim dblY As Double = rctCurrentExtentYMin + (((imgMapHeightValue - eY) imgMapHeightValue) (rctCurrentExtentYMax - rctCurrentExtentYMin)) If Trim(UCase(lstNavControlsSelectedItemText)) ltgt IDENTIFY Then m_objViewerMapCenterAt(dblX dblY) Select Case UCase(lstNavControlsSelectedItemText) Case ZOOM IN Center the map m_objViewerMapZoom(-1) Case ZOOM OUT m_objViewerMapZoom(1) Case PAN do nothing Case Else ErrRaise(vbObjectError + 512 imgMap_Click Invalid command) End Select Else identify End If End Sub

ESRI White Paper 16

End Class

NOTE =gt Once you have the relevant files imported into Visual Studio make sure that you configure the virtual directory as an application before you run the example

If the virtual directory is not configured as an Application you will get an error message that reads This error can be caused by a virtual directory not being configured as an application in IIS To configure a Virtual directory is simple Use the Internet Service Manager to perform the following steps

Find the folder in the virtual directory Right click and choose properties Click Create Accept all the settings and Click OK

Example 3

General Description

The program uses the catalog service (using the ltGETCLIENTSERVICESgt request) to query and list a collection of services running on the server A Radiobutton list control is used to list all the service names running on the server On selecting an appropriate image service the map image is displayed on the web form using an image control This program demonstrates two different ways to connect to the datasource Connection could be achieved using the http protocol or the TCP protocol The TCP method utilizes the TCP capability built into the ActiveX Connector Since ASPNET is a multithreaded and the ActiveX connector being Single Threaded (STA) a wrapper class with additional functionality to manage memory is used to access the methods in the ActiveX connector

ESRI White Paper 17

Programming Environment ASPNET and Web Forms

C NET Programming Language

WebForm Controls

Control Name Function ImgMap Control for displaying the image RbServices Radiobutton list controls Txtinfo Displays the name of the selected image service

Data Files

Requires a collection of image services running on an ArcIMS server The program uses the ltGETCLIENTSERVICESgt request tag to query the catalog service to list all the services running on the specified server

Class Libraries

File Name Class Information Functionality Connectioncs Abstract base class Provides abstract method

templates for the HTTPConnection and

ESRI White Paper 18

TCPConnection classes HTTPConnectioncs Inherits from Connection class Provides functionality for

sending request to service postinggetting URL content etc

TCPConnectioncs Inherits from Connection class and SystemIDisposable

Utlizes the AICLib assembly to access connection functionality built into the ActiveX connector

Datasourcecs Provides method for accessing path port host and other information

Enumerationscs Provides enumerations for AccessType and LoadType

Envelopecs Provides methods for getting and setting xy coordinates of the envelope

ImageReturnObjectcs Provides methods for settinggetting image URL image envelope and image scale

Mapcs Calls send request to service with connection and service information Parses response to obtain image URL

Servicecs Servicescs Inherits from

SystemCollectionsHashtable Composes the clientservices request and parses the response Creates a hashtable association of individual service name with its associated service object

XML helper class that provides relevant XML parsing functionality by acting as a wrapper class around NETs xml Text IO and other NET classes

XMLRequestscs Builds ArcXML strings for requests

XMLHelpercs

Steps to Create Application

ESRI White Paper 19

The NET solution contains 2 projects ArcIMS and ArcIMSSample The ArcIMS project

o References the InteropAICLib o Contains NET ArcIMS class libraries that can be used to connect and to

work with image services The ArcIMSSample project

o References the ArcIMS project o Contains the web form (webform1aspx) and the corresponding

webform1aspxcs code-behind page that connects the web page controls to relevant functionality using an event driven web forms model

Points to Note

In webform1aspxcs code session variables are used to maintain state of serialized objects In order for this to be possible notice that the relevant classes have been marked as serializable

ESRI White Paper 20

Choose the appropriate connection type based on HTTP or TCP connection For HTTP choose m_dsConnectType = ConnectionTypeInterNet and for For TCP select m_dsConnectType = ConnectionTypeIntraNet as shown in the code below

private ArcIMSDataSource getDataSource() m_ds = Session[datasource] as ArcIMSDataSource if ( m_ds == null ) m_ds = new ArcIMSDataSource() m_dsHost = localhost m_dsScheme = http m_dsPort = 80 m_dsAppServerPort = 5300 m_dsPath = servletcomesriesrimapEsrimap choose (comment uncomment) one of the following two statements to decide between TCP or HTTP type connection m_dsConnectType = ConnectionTypeIntraNet m_dsConnectType = ConnectionTypeInterNet SessionAdd(datasource m_ds) return m_ds

Accessing a COM Server from a NET Client With the introduction of the NET Framework and ASPNET COM at its basic level has not really changed Nevertheless there are a couple of issues to be aware of when making calls to a COM object from a NET managed code environment The ASPNET threading model is the Multiple Threaded Apartment (MTA) This will not interact reliably with STA components (the ActiveX connector provided with the ArcIMS setup was built as an STA component) To emphasize this issue heres a direct quote from the MSDN pages at Microsoft The ASPNET threading model is the Multiple Threaded Apartment (MTA) What this means is that components that you are using that were created for the Single Threaded Apartment (STA) will no longer perform or function reliably without taking some extra precautions in ASPNET This includes but is not limited to all COM components that have been created using Visual Basic 60 and earlier versions

To understand the issues better let us take a look at how NET deals with COM related issues The Common Language Runtime exposes COM objects through a proxy called the runtime callable wrapper (RCW) The RCWs primary function is to marshal calls between a NET client and COM object The RCW object is nothing but an object instantiated at runtime from class code contained in the Interop assembly

ESRI White Paper 21

Calling between managed and unmanaged components incurs a marshaling cost which can impede the performance of your pages When a managed client and unmanaged server are in the same apartment the Interop marshalling service handles all data marshalling However when client and server are initialized in different apartments COM marshalling is also required Therefore interoperability with COM from a NET client should take into consideration the threading model used

Figure Cross-apartment call between a NET client and COM object

As mentioned earlier ASPNET follows an MTA model by default You could use the default model to communicate with an STA COM component if there is not much of an overhead due to the cross-apartment marshalling Usually this is noticeable only when there are many calls across the boundary Another option would be to use the PageAspCompatMode property of the ASPNET client The ASPCompat=true attribute enables an STA thread pool to address performance with existing Visual Basic components on a per-page basis The runtime throws an exception if the compatibility tag is omitted and an STA component is referenced on the page If you convert the STA component to an assembly using Type Library Importer (a utility included with the NET SDK) the runtime does not detect that the component uses the STA model and does not throw an exception but your application can suffer from poor performance and possible deadlocks STA components cannot be used from NET Framework code modules (compiled NET assemblies) they can be used only from ASPNET pages

If you plan to use the ASPCOMPAT = TRUE page level directive for Example 1 remember to instantiate the COM object within the page_load event rather than constructing COM components during page construction time For example look at code examples A and B

Example A Example B ltPage Language = VB ASPCOMPAT = truegt

ltscript runat = servergt

private mapStates as new aimsMap()

private sub_load ()

ltPage Language = VB ASPCOMPAT = truegt

ltscript runat = servergt

private mapStates as aimsMap()

private sub_load ()

ESRI White Paper 22

end sub

mapStates = new aimsMap()

end sub

In example A the STA component would be instantiated at page construction time which is created from a thread that is not the STA thread that will run the page This will involve marshalling between MTA and STA threads during the construction of the page Example B shows the preferred mechanism to delay the process until later when the code executes under a STA thread It is best to construct any COM component and external resources when needed or in the Page_Load method

Also to create the object you can use either the New keyword or the CreateObject method The CreateObject method is typically used when you dont know the Program ID (ProgID) of the object you are going to create until run time (late binding) New is the recommended method for instantiating objects if you have access to the objects type library It is preferable to adopt the early binding model

Every scenario yields different performance characteristics so it is important to test adequately before deciding whether interoperability is the right choice for your application However in nearly all scenarios rewriting your COM components in managed code provides performance benefits

Summary The examples shown above provide adequate information to leverage the NET programming environment to build effective ArcIMS client applications The debugging features of a program like Visual StudioNET provide a variety of tools (break points trace etc) making the entire development experience considerably pain-free Use the debugger to understand the sequence in which calls are made One early exercise would be to look at the calling sequence of the various page related events such as page_init page_load and page_prerender Since the Web Forms code is compiled you should experience much better performance than with ASP pages that used code written in scripting languages like Javascript and VbScript

The powerful programming environment also means that you can now concentrate more on the logic of building large web applications as opposed to building simple page based asp applications Also look at the various caching mechanisms provided by ASPNET as these can be used to improve overall performance As always there are costs associated with most programming choices and this is all the more true in a web-programming environment For example consider the costs associated with using a web control as opposed to a HTML based control Use plain HTML controls instead of adopting web controls for simple items like label

ESRI White Paper 23

If you choose to use the ActiveX connector from within the NET environment make sure that you clearly understand the essentials of COM Interop and the various costs associated with marshalling The solutions outlined in this paper utilize existing ArcIMS services and should work with all versions of ArcIMS

Although all the development can be done without the use of an Integrated Development environment (IDE) like Visual StudioNET using such an environment provides convenient WYSIWYG features that can help in building and debugging the application If you do not have Visual StudioNET there are free IDEs available today that can also be used For example ASPNET Web Matrix is a community-supported easy-to-use WYSIWYG application development tool for ASPNET It can be installed via a quick 12 MB download from httpwwwaspnetwebmatrixdefaultaspx

ESRI White Paper 24

  • ArcIMS ndash An Introduction
  • What is NET
    • The NET Framework
      • The Common Language Runtime (CLR)
      • Managed Unmanaged and Unsafe code ndash Understandin
      • NET Framework Class Libraries
        • ASPNET and Web Forms
          • NET and ArcIMS
            • Example 1
            • Example 2
            • Example 3
              • Accessing a COM Server from a NET Client
              • Summary
Page 16: Consuming ArcIMS Image Services using .NET Client Web ... · Consuming ArcIMS Image Services using .NET Client Web Applications An ESRI White Paper Ł October 2002 ... The .NET framework

Control Name Function ImgMap Control for displaying the image ImgLegend Control for displaying the legend image lstNavControls Radiobutton list controls

Data Files

Can use any datafile capable of generating an image service Replace the sf parameter in the page_load event with the appropriate image service name

Class Libraries ( Logic_classes assembly)

File Name Class Information Functionality MapVB The Cmap class has a

MustInherit Keyword and is inherited by Cviewer The MustInherit keyword specifies that a class cannot be instantiated and can be used only as a base class

PointVB Used by Cmap Crect Represents a geometric point (xy pair ) RectVB Used by Cmap Cviewer and

Webform3 in testformaspx

ViewerVB Used in Webform3 in testformaspx

Abstracts the requesting of a simple map from ArcIMS No additional entities will be added to the map (ie graphics buffer etc) The map is requested with all the default parameters with which it is served excepting extent and background color

Steps to Create Application

ESRI White Paper 13

The following section details the code found in the code behind page of the Testformaspx page

Statement to import logic_classes Makes all the functionality available in the logic_classes project available to the code in the web form

Imports logic_classes

Define a class level variable in the aspx file

Private m_objViewerMap As cViewer

Code for the page load event Uses IsPostback to determine if the extents need to be read afresh or from a previous valued stored in the session object Also instantiates the Cviewer class object You need to make sure that the extents shown in the code are appropriately changed to work with your selected image service

Private Sub Page_Load(ByVal sender As SystemObject ByVal e As SystemEventArgs) Handles MyBaseLoad

ESRI White Paper 14

Put user code to initialize the page here Dim rctExtent As cRect If Not IsPostBack Then enter appropriate extents rctExtent = New cRect(-1225173 377199 -122363678 3780374) Else rctExtent = New cRect(Session(MinX) Session(MinY) Session(MaxX) Session(MaxY)) End If m_objViewerMap = New cViewer(httplocalhostservletcomesriesrimapEsrimap _ sf _ rctExtent _ imgMapWidthValue _ imgMapHeightValue _ 000) add test markers

End Sub

Page_Prerender event code Links the output image to the Picture controls Also since HTTP is a stateless protocol the current map extents are stored in session variables for follow-up requests from the same user

Private Sub Page_PreRender(ByVal sender As Object ByVal e As SystemEventArgs) Handles MyBasePreRender imgMapImageUrl = m_objViewerMapMap() imgLegendImageUrl = m_objViewerMapLegend() Session(MinX) = m_objViewerMapExtentXMin Session(MinY) = m_objViewerMapExtentYMin Session(MaxX) = m_objViewerMapExtentXMax Session(MaxY) = m_objViewerMapExtentYMax

End Sub

Imgmap_click event is raised when the user clicks on the map Code associated with this event converts the image click coordinate to a map coordinate Then

ESRI White Paper 15

based on the radio button selection ( Zoomin Zoomout or pan) the code calls the appropriate method using the instantiated Cviewer object

Private Sub imgMap_Click(ByVal sender As Object ByVal e As SystemWebUIImageClickEventArgs) Handles imgMapClick Convert the image click coordinate to a map coordinate based on the maps current extent Dim rctCurrentExtent As cRect = m_objViewerMapExtent Dim dblX As Double = rctCurrentExtentXMin + ((eX imgMapWidthValue) (rctCurrentExtentXMax - rctCurrentExtentXMin)) Dim dblY As Double = rctCurrentExtentYMin + (((imgMapHeightValue - eY) imgMapHeightValue) (rctCurrentExtentYMax - rctCurrentExtentYMin)) If Trim(UCase(lstNavControlsSelectedItemText)) ltgt IDENTIFY Then m_objViewerMapCenterAt(dblX dblY) Select Case UCase(lstNavControlsSelectedItemText) Case ZOOM IN Center the map m_objViewerMapZoom(-1) Case ZOOM OUT m_objViewerMapZoom(1) Case PAN do nothing Case Else ErrRaise(vbObjectError + 512 imgMap_Click Invalid command) End Select Else identify End If End Sub

ESRI White Paper 16

End Class

NOTE =gt Once you have the relevant files imported into Visual Studio make sure that you configure the virtual directory as an application before you run the example

If the virtual directory is not configured as an Application you will get an error message that reads This error can be caused by a virtual directory not being configured as an application in IIS To configure a Virtual directory is simple Use the Internet Service Manager to perform the following steps

Find the folder in the virtual directory Right click and choose properties Click Create Accept all the settings and Click OK

Example 3

General Description

The program uses the catalog service (using the ltGETCLIENTSERVICESgt request) to query and list a collection of services running on the server A Radiobutton list control is used to list all the service names running on the server On selecting an appropriate image service the map image is displayed on the web form using an image control This program demonstrates two different ways to connect to the datasource Connection could be achieved using the http protocol or the TCP protocol The TCP method utilizes the TCP capability built into the ActiveX Connector Since ASPNET is a multithreaded and the ActiveX connector being Single Threaded (STA) a wrapper class with additional functionality to manage memory is used to access the methods in the ActiveX connector

ESRI White Paper 17

Programming Environment ASPNET and Web Forms

C NET Programming Language

WebForm Controls

Control Name Function ImgMap Control for displaying the image RbServices Radiobutton list controls Txtinfo Displays the name of the selected image service

Data Files

Requires a collection of image services running on an ArcIMS server The program uses the ltGETCLIENTSERVICESgt request tag to query the catalog service to list all the services running on the specified server

Class Libraries

File Name Class Information Functionality Connectioncs Abstract base class Provides abstract method

templates for the HTTPConnection and

ESRI White Paper 18

TCPConnection classes HTTPConnectioncs Inherits from Connection class Provides functionality for

sending request to service postinggetting URL content etc

TCPConnectioncs Inherits from Connection class and SystemIDisposable

Utlizes the AICLib assembly to access connection functionality built into the ActiveX connector

Datasourcecs Provides method for accessing path port host and other information

Enumerationscs Provides enumerations for AccessType and LoadType

Envelopecs Provides methods for getting and setting xy coordinates of the envelope

ImageReturnObjectcs Provides methods for settinggetting image URL image envelope and image scale

Mapcs Calls send request to service with connection and service information Parses response to obtain image URL

Servicecs Servicescs Inherits from

SystemCollectionsHashtable Composes the clientservices request and parses the response Creates a hashtable association of individual service name with its associated service object

XML helper class that provides relevant XML parsing functionality by acting as a wrapper class around NETs xml Text IO and other NET classes

XMLRequestscs Builds ArcXML strings for requests

XMLHelpercs

Steps to Create Application

ESRI White Paper 19

The NET solution contains 2 projects ArcIMS and ArcIMSSample The ArcIMS project

o References the InteropAICLib o Contains NET ArcIMS class libraries that can be used to connect and to

work with image services The ArcIMSSample project

o References the ArcIMS project o Contains the web form (webform1aspx) and the corresponding

webform1aspxcs code-behind page that connects the web page controls to relevant functionality using an event driven web forms model

Points to Note

In webform1aspxcs code session variables are used to maintain state of serialized objects In order for this to be possible notice that the relevant classes have been marked as serializable

ESRI White Paper 20

Choose the appropriate connection type based on HTTP or TCP connection For HTTP choose m_dsConnectType = ConnectionTypeInterNet and for For TCP select m_dsConnectType = ConnectionTypeIntraNet as shown in the code below

private ArcIMSDataSource getDataSource() m_ds = Session[datasource] as ArcIMSDataSource if ( m_ds == null ) m_ds = new ArcIMSDataSource() m_dsHost = localhost m_dsScheme = http m_dsPort = 80 m_dsAppServerPort = 5300 m_dsPath = servletcomesriesrimapEsrimap choose (comment uncomment) one of the following two statements to decide between TCP or HTTP type connection m_dsConnectType = ConnectionTypeIntraNet m_dsConnectType = ConnectionTypeInterNet SessionAdd(datasource m_ds) return m_ds

Accessing a COM Server from a NET Client With the introduction of the NET Framework and ASPNET COM at its basic level has not really changed Nevertheless there are a couple of issues to be aware of when making calls to a COM object from a NET managed code environment The ASPNET threading model is the Multiple Threaded Apartment (MTA) This will not interact reliably with STA components (the ActiveX connector provided with the ArcIMS setup was built as an STA component) To emphasize this issue heres a direct quote from the MSDN pages at Microsoft The ASPNET threading model is the Multiple Threaded Apartment (MTA) What this means is that components that you are using that were created for the Single Threaded Apartment (STA) will no longer perform or function reliably without taking some extra precautions in ASPNET This includes but is not limited to all COM components that have been created using Visual Basic 60 and earlier versions

To understand the issues better let us take a look at how NET deals with COM related issues The Common Language Runtime exposes COM objects through a proxy called the runtime callable wrapper (RCW) The RCWs primary function is to marshal calls between a NET client and COM object The RCW object is nothing but an object instantiated at runtime from class code contained in the Interop assembly

ESRI White Paper 21

Calling between managed and unmanaged components incurs a marshaling cost which can impede the performance of your pages When a managed client and unmanaged server are in the same apartment the Interop marshalling service handles all data marshalling However when client and server are initialized in different apartments COM marshalling is also required Therefore interoperability with COM from a NET client should take into consideration the threading model used

Figure Cross-apartment call between a NET client and COM object

As mentioned earlier ASPNET follows an MTA model by default You could use the default model to communicate with an STA COM component if there is not much of an overhead due to the cross-apartment marshalling Usually this is noticeable only when there are many calls across the boundary Another option would be to use the PageAspCompatMode property of the ASPNET client The ASPCompat=true attribute enables an STA thread pool to address performance with existing Visual Basic components on a per-page basis The runtime throws an exception if the compatibility tag is omitted and an STA component is referenced on the page If you convert the STA component to an assembly using Type Library Importer (a utility included with the NET SDK) the runtime does not detect that the component uses the STA model and does not throw an exception but your application can suffer from poor performance and possible deadlocks STA components cannot be used from NET Framework code modules (compiled NET assemblies) they can be used only from ASPNET pages

If you plan to use the ASPCOMPAT = TRUE page level directive for Example 1 remember to instantiate the COM object within the page_load event rather than constructing COM components during page construction time For example look at code examples A and B

Example A Example B ltPage Language = VB ASPCOMPAT = truegt

ltscript runat = servergt

private mapStates as new aimsMap()

private sub_load ()

ltPage Language = VB ASPCOMPAT = truegt

ltscript runat = servergt

private mapStates as aimsMap()

private sub_load ()

ESRI White Paper 22

end sub

mapStates = new aimsMap()

end sub

In example A the STA component would be instantiated at page construction time which is created from a thread that is not the STA thread that will run the page This will involve marshalling between MTA and STA threads during the construction of the page Example B shows the preferred mechanism to delay the process until later when the code executes under a STA thread It is best to construct any COM component and external resources when needed or in the Page_Load method

Also to create the object you can use either the New keyword or the CreateObject method The CreateObject method is typically used when you dont know the Program ID (ProgID) of the object you are going to create until run time (late binding) New is the recommended method for instantiating objects if you have access to the objects type library It is preferable to adopt the early binding model

Every scenario yields different performance characteristics so it is important to test adequately before deciding whether interoperability is the right choice for your application However in nearly all scenarios rewriting your COM components in managed code provides performance benefits

Summary The examples shown above provide adequate information to leverage the NET programming environment to build effective ArcIMS client applications The debugging features of a program like Visual StudioNET provide a variety of tools (break points trace etc) making the entire development experience considerably pain-free Use the debugger to understand the sequence in which calls are made One early exercise would be to look at the calling sequence of the various page related events such as page_init page_load and page_prerender Since the Web Forms code is compiled you should experience much better performance than with ASP pages that used code written in scripting languages like Javascript and VbScript

The powerful programming environment also means that you can now concentrate more on the logic of building large web applications as opposed to building simple page based asp applications Also look at the various caching mechanisms provided by ASPNET as these can be used to improve overall performance As always there are costs associated with most programming choices and this is all the more true in a web-programming environment For example consider the costs associated with using a web control as opposed to a HTML based control Use plain HTML controls instead of adopting web controls for simple items like label

ESRI White Paper 23

If you choose to use the ActiveX connector from within the NET environment make sure that you clearly understand the essentials of COM Interop and the various costs associated with marshalling The solutions outlined in this paper utilize existing ArcIMS services and should work with all versions of ArcIMS

Although all the development can be done without the use of an Integrated Development environment (IDE) like Visual StudioNET using such an environment provides convenient WYSIWYG features that can help in building and debugging the application If you do not have Visual StudioNET there are free IDEs available today that can also be used For example ASPNET Web Matrix is a community-supported easy-to-use WYSIWYG application development tool for ASPNET It can be installed via a quick 12 MB download from httpwwwaspnetwebmatrixdefaultaspx

ESRI White Paper 24

  • ArcIMS ndash An Introduction
  • What is NET
    • The NET Framework
      • The Common Language Runtime (CLR)
      • Managed Unmanaged and Unsafe code ndash Understandin
      • NET Framework Class Libraries
        • ASPNET and Web Forms
          • NET and ArcIMS
            • Example 1
            • Example 2
            • Example 3
              • Accessing a COM Server from a NET Client
              • Summary
Page 17: Consuming ArcIMS Image Services using .NET Client Web ... · Consuming ArcIMS Image Services using .NET Client Web Applications An ESRI White Paper Ł October 2002 ... The .NET framework

The following section details the code found in the code behind page of the Testformaspx page

Statement to import logic_classes Makes all the functionality available in the logic_classes project available to the code in the web form

Imports logic_classes

Define a class level variable in the aspx file

Private m_objViewerMap As cViewer

Code for the page load event Uses IsPostback to determine if the extents need to be read afresh or from a previous valued stored in the session object Also instantiates the Cviewer class object You need to make sure that the extents shown in the code are appropriately changed to work with your selected image service

Private Sub Page_Load(ByVal sender As SystemObject ByVal e As SystemEventArgs) Handles MyBaseLoad

ESRI White Paper 14

Put user code to initialize the page here Dim rctExtent As cRect If Not IsPostBack Then enter appropriate extents rctExtent = New cRect(-1225173 377199 -122363678 3780374) Else rctExtent = New cRect(Session(MinX) Session(MinY) Session(MaxX) Session(MaxY)) End If m_objViewerMap = New cViewer(httplocalhostservletcomesriesrimapEsrimap _ sf _ rctExtent _ imgMapWidthValue _ imgMapHeightValue _ 000) add test markers

End Sub

Page_Prerender event code Links the output image to the Picture controls Also since HTTP is a stateless protocol the current map extents are stored in session variables for follow-up requests from the same user

Private Sub Page_PreRender(ByVal sender As Object ByVal e As SystemEventArgs) Handles MyBasePreRender imgMapImageUrl = m_objViewerMapMap() imgLegendImageUrl = m_objViewerMapLegend() Session(MinX) = m_objViewerMapExtentXMin Session(MinY) = m_objViewerMapExtentYMin Session(MaxX) = m_objViewerMapExtentXMax Session(MaxY) = m_objViewerMapExtentYMax

End Sub

Imgmap_click event is raised when the user clicks on the map Code associated with this event converts the image click coordinate to a map coordinate Then

ESRI White Paper 15

based on the radio button selection ( Zoomin Zoomout or pan) the code calls the appropriate method using the instantiated Cviewer object

Private Sub imgMap_Click(ByVal sender As Object ByVal e As SystemWebUIImageClickEventArgs) Handles imgMapClick Convert the image click coordinate to a map coordinate based on the maps current extent Dim rctCurrentExtent As cRect = m_objViewerMapExtent Dim dblX As Double = rctCurrentExtentXMin + ((eX imgMapWidthValue) (rctCurrentExtentXMax - rctCurrentExtentXMin)) Dim dblY As Double = rctCurrentExtentYMin + (((imgMapHeightValue - eY) imgMapHeightValue) (rctCurrentExtentYMax - rctCurrentExtentYMin)) If Trim(UCase(lstNavControlsSelectedItemText)) ltgt IDENTIFY Then m_objViewerMapCenterAt(dblX dblY) Select Case UCase(lstNavControlsSelectedItemText) Case ZOOM IN Center the map m_objViewerMapZoom(-1) Case ZOOM OUT m_objViewerMapZoom(1) Case PAN do nothing Case Else ErrRaise(vbObjectError + 512 imgMap_Click Invalid command) End Select Else identify End If End Sub

ESRI White Paper 16

End Class

NOTE =gt Once you have the relevant files imported into Visual Studio make sure that you configure the virtual directory as an application before you run the example

If the virtual directory is not configured as an Application you will get an error message that reads This error can be caused by a virtual directory not being configured as an application in IIS To configure a Virtual directory is simple Use the Internet Service Manager to perform the following steps

Find the folder in the virtual directory Right click and choose properties Click Create Accept all the settings and Click OK

Example 3

General Description

The program uses the catalog service (using the ltGETCLIENTSERVICESgt request) to query and list a collection of services running on the server A Radiobutton list control is used to list all the service names running on the server On selecting an appropriate image service the map image is displayed on the web form using an image control This program demonstrates two different ways to connect to the datasource Connection could be achieved using the http protocol or the TCP protocol The TCP method utilizes the TCP capability built into the ActiveX Connector Since ASPNET is a multithreaded and the ActiveX connector being Single Threaded (STA) a wrapper class with additional functionality to manage memory is used to access the methods in the ActiveX connector

ESRI White Paper 17

Programming Environment ASPNET and Web Forms

C NET Programming Language

WebForm Controls

Control Name Function ImgMap Control for displaying the image RbServices Radiobutton list controls Txtinfo Displays the name of the selected image service

Data Files

Requires a collection of image services running on an ArcIMS server The program uses the ltGETCLIENTSERVICESgt request tag to query the catalog service to list all the services running on the specified server

Class Libraries

File Name Class Information Functionality Connectioncs Abstract base class Provides abstract method

templates for the HTTPConnection and

ESRI White Paper 18

TCPConnection classes HTTPConnectioncs Inherits from Connection class Provides functionality for

sending request to service postinggetting URL content etc

TCPConnectioncs Inherits from Connection class and SystemIDisposable

Utlizes the AICLib assembly to access connection functionality built into the ActiveX connector

Datasourcecs Provides method for accessing path port host and other information

Enumerationscs Provides enumerations for AccessType and LoadType

Envelopecs Provides methods for getting and setting xy coordinates of the envelope

ImageReturnObjectcs Provides methods for settinggetting image URL image envelope and image scale

Mapcs Calls send request to service with connection and service information Parses response to obtain image URL

Servicecs Servicescs Inherits from

SystemCollectionsHashtable Composes the clientservices request and parses the response Creates a hashtable association of individual service name with its associated service object

XML helper class that provides relevant XML parsing functionality by acting as a wrapper class around NETs xml Text IO and other NET classes

XMLRequestscs Builds ArcXML strings for requests

XMLHelpercs

Steps to Create Application

ESRI White Paper 19

The NET solution contains 2 projects ArcIMS and ArcIMSSample The ArcIMS project

o References the InteropAICLib o Contains NET ArcIMS class libraries that can be used to connect and to

work with image services The ArcIMSSample project

o References the ArcIMS project o Contains the web form (webform1aspx) and the corresponding

webform1aspxcs code-behind page that connects the web page controls to relevant functionality using an event driven web forms model

Points to Note

In webform1aspxcs code session variables are used to maintain state of serialized objects In order for this to be possible notice that the relevant classes have been marked as serializable

ESRI White Paper 20

Choose the appropriate connection type based on HTTP or TCP connection For HTTP choose m_dsConnectType = ConnectionTypeInterNet and for For TCP select m_dsConnectType = ConnectionTypeIntraNet as shown in the code below

private ArcIMSDataSource getDataSource() m_ds = Session[datasource] as ArcIMSDataSource if ( m_ds == null ) m_ds = new ArcIMSDataSource() m_dsHost = localhost m_dsScheme = http m_dsPort = 80 m_dsAppServerPort = 5300 m_dsPath = servletcomesriesrimapEsrimap choose (comment uncomment) one of the following two statements to decide between TCP or HTTP type connection m_dsConnectType = ConnectionTypeIntraNet m_dsConnectType = ConnectionTypeInterNet SessionAdd(datasource m_ds) return m_ds

Accessing a COM Server from a NET Client With the introduction of the NET Framework and ASPNET COM at its basic level has not really changed Nevertheless there are a couple of issues to be aware of when making calls to a COM object from a NET managed code environment The ASPNET threading model is the Multiple Threaded Apartment (MTA) This will not interact reliably with STA components (the ActiveX connector provided with the ArcIMS setup was built as an STA component) To emphasize this issue heres a direct quote from the MSDN pages at Microsoft The ASPNET threading model is the Multiple Threaded Apartment (MTA) What this means is that components that you are using that were created for the Single Threaded Apartment (STA) will no longer perform or function reliably without taking some extra precautions in ASPNET This includes but is not limited to all COM components that have been created using Visual Basic 60 and earlier versions

To understand the issues better let us take a look at how NET deals with COM related issues The Common Language Runtime exposes COM objects through a proxy called the runtime callable wrapper (RCW) The RCWs primary function is to marshal calls between a NET client and COM object The RCW object is nothing but an object instantiated at runtime from class code contained in the Interop assembly

ESRI White Paper 21

Calling between managed and unmanaged components incurs a marshaling cost which can impede the performance of your pages When a managed client and unmanaged server are in the same apartment the Interop marshalling service handles all data marshalling However when client and server are initialized in different apartments COM marshalling is also required Therefore interoperability with COM from a NET client should take into consideration the threading model used

Figure Cross-apartment call between a NET client and COM object

As mentioned earlier ASPNET follows an MTA model by default You could use the default model to communicate with an STA COM component if there is not much of an overhead due to the cross-apartment marshalling Usually this is noticeable only when there are many calls across the boundary Another option would be to use the PageAspCompatMode property of the ASPNET client The ASPCompat=true attribute enables an STA thread pool to address performance with existing Visual Basic components on a per-page basis The runtime throws an exception if the compatibility tag is omitted and an STA component is referenced on the page If you convert the STA component to an assembly using Type Library Importer (a utility included with the NET SDK) the runtime does not detect that the component uses the STA model and does not throw an exception but your application can suffer from poor performance and possible deadlocks STA components cannot be used from NET Framework code modules (compiled NET assemblies) they can be used only from ASPNET pages

If you plan to use the ASPCOMPAT = TRUE page level directive for Example 1 remember to instantiate the COM object within the page_load event rather than constructing COM components during page construction time For example look at code examples A and B

Example A Example B ltPage Language = VB ASPCOMPAT = truegt

ltscript runat = servergt

private mapStates as new aimsMap()

private sub_load ()

ltPage Language = VB ASPCOMPAT = truegt

ltscript runat = servergt

private mapStates as aimsMap()

private sub_load ()

ESRI White Paper 22

end sub

mapStates = new aimsMap()

end sub

In example A the STA component would be instantiated at page construction time which is created from a thread that is not the STA thread that will run the page This will involve marshalling between MTA and STA threads during the construction of the page Example B shows the preferred mechanism to delay the process until later when the code executes under a STA thread It is best to construct any COM component and external resources when needed or in the Page_Load method

Also to create the object you can use either the New keyword or the CreateObject method The CreateObject method is typically used when you dont know the Program ID (ProgID) of the object you are going to create until run time (late binding) New is the recommended method for instantiating objects if you have access to the objects type library It is preferable to adopt the early binding model

Every scenario yields different performance characteristics so it is important to test adequately before deciding whether interoperability is the right choice for your application However in nearly all scenarios rewriting your COM components in managed code provides performance benefits

Summary The examples shown above provide adequate information to leverage the NET programming environment to build effective ArcIMS client applications The debugging features of a program like Visual StudioNET provide a variety of tools (break points trace etc) making the entire development experience considerably pain-free Use the debugger to understand the sequence in which calls are made One early exercise would be to look at the calling sequence of the various page related events such as page_init page_load and page_prerender Since the Web Forms code is compiled you should experience much better performance than with ASP pages that used code written in scripting languages like Javascript and VbScript

The powerful programming environment also means that you can now concentrate more on the logic of building large web applications as opposed to building simple page based asp applications Also look at the various caching mechanisms provided by ASPNET as these can be used to improve overall performance As always there are costs associated with most programming choices and this is all the more true in a web-programming environment For example consider the costs associated with using a web control as opposed to a HTML based control Use plain HTML controls instead of adopting web controls for simple items like label

ESRI White Paper 23

If you choose to use the ActiveX connector from within the NET environment make sure that you clearly understand the essentials of COM Interop and the various costs associated with marshalling The solutions outlined in this paper utilize existing ArcIMS services and should work with all versions of ArcIMS

Although all the development can be done without the use of an Integrated Development environment (IDE) like Visual StudioNET using such an environment provides convenient WYSIWYG features that can help in building and debugging the application If you do not have Visual StudioNET there are free IDEs available today that can also be used For example ASPNET Web Matrix is a community-supported easy-to-use WYSIWYG application development tool for ASPNET It can be installed via a quick 12 MB download from httpwwwaspnetwebmatrixdefaultaspx

ESRI White Paper 24

  • ArcIMS ndash An Introduction
  • What is NET
    • The NET Framework
      • The Common Language Runtime (CLR)
      • Managed Unmanaged and Unsafe code ndash Understandin
      • NET Framework Class Libraries
        • ASPNET and Web Forms
          • NET and ArcIMS
            • Example 1
            • Example 2
            • Example 3
              • Accessing a COM Server from a NET Client
              • Summary
Page 18: Consuming ArcIMS Image Services using .NET Client Web ... · Consuming ArcIMS Image Services using .NET Client Web Applications An ESRI White Paper Ł October 2002 ... The .NET framework

Put user code to initialize the page here Dim rctExtent As cRect If Not IsPostBack Then enter appropriate extents rctExtent = New cRect(-1225173 377199 -122363678 3780374) Else rctExtent = New cRect(Session(MinX) Session(MinY) Session(MaxX) Session(MaxY)) End If m_objViewerMap = New cViewer(httplocalhostservletcomesriesrimapEsrimap _ sf _ rctExtent _ imgMapWidthValue _ imgMapHeightValue _ 000) add test markers

End Sub

Page_Prerender event code Links the output image to the Picture controls Also since HTTP is a stateless protocol the current map extents are stored in session variables for follow-up requests from the same user

Private Sub Page_PreRender(ByVal sender As Object ByVal e As SystemEventArgs) Handles MyBasePreRender imgMapImageUrl = m_objViewerMapMap() imgLegendImageUrl = m_objViewerMapLegend() Session(MinX) = m_objViewerMapExtentXMin Session(MinY) = m_objViewerMapExtentYMin Session(MaxX) = m_objViewerMapExtentXMax Session(MaxY) = m_objViewerMapExtentYMax

End Sub

Imgmap_click event is raised when the user clicks on the map Code associated with this event converts the image click coordinate to a map coordinate Then

ESRI White Paper 15

based on the radio button selection ( Zoomin Zoomout or pan) the code calls the appropriate method using the instantiated Cviewer object

Private Sub imgMap_Click(ByVal sender As Object ByVal e As SystemWebUIImageClickEventArgs) Handles imgMapClick Convert the image click coordinate to a map coordinate based on the maps current extent Dim rctCurrentExtent As cRect = m_objViewerMapExtent Dim dblX As Double = rctCurrentExtentXMin + ((eX imgMapWidthValue) (rctCurrentExtentXMax - rctCurrentExtentXMin)) Dim dblY As Double = rctCurrentExtentYMin + (((imgMapHeightValue - eY) imgMapHeightValue) (rctCurrentExtentYMax - rctCurrentExtentYMin)) If Trim(UCase(lstNavControlsSelectedItemText)) ltgt IDENTIFY Then m_objViewerMapCenterAt(dblX dblY) Select Case UCase(lstNavControlsSelectedItemText) Case ZOOM IN Center the map m_objViewerMapZoom(-1) Case ZOOM OUT m_objViewerMapZoom(1) Case PAN do nothing Case Else ErrRaise(vbObjectError + 512 imgMap_Click Invalid command) End Select Else identify End If End Sub

ESRI White Paper 16

End Class

NOTE =gt Once you have the relevant files imported into Visual Studio make sure that you configure the virtual directory as an application before you run the example

If the virtual directory is not configured as an Application you will get an error message that reads This error can be caused by a virtual directory not being configured as an application in IIS To configure a Virtual directory is simple Use the Internet Service Manager to perform the following steps

Find the folder in the virtual directory Right click and choose properties Click Create Accept all the settings and Click OK

Example 3

General Description

The program uses the catalog service (using the ltGETCLIENTSERVICESgt request) to query and list a collection of services running on the server A Radiobutton list control is used to list all the service names running on the server On selecting an appropriate image service the map image is displayed on the web form using an image control This program demonstrates two different ways to connect to the datasource Connection could be achieved using the http protocol or the TCP protocol The TCP method utilizes the TCP capability built into the ActiveX Connector Since ASPNET is a multithreaded and the ActiveX connector being Single Threaded (STA) a wrapper class with additional functionality to manage memory is used to access the methods in the ActiveX connector

ESRI White Paper 17

Programming Environment ASPNET and Web Forms

C NET Programming Language

WebForm Controls

Control Name Function ImgMap Control for displaying the image RbServices Radiobutton list controls Txtinfo Displays the name of the selected image service

Data Files

Requires a collection of image services running on an ArcIMS server The program uses the ltGETCLIENTSERVICESgt request tag to query the catalog service to list all the services running on the specified server

Class Libraries

File Name Class Information Functionality Connectioncs Abstract base class Provides abstract method

templates for the HTTPConnection and

ESRI White Paper 18

TCPConnection classes HTTPConnectioncs Inherits from Connection class Provides functionality for

sending request to service postinggetting URL content etc

TCPConnectioncs Inherits from Connection class and SystemIDisposable

Utlizes the AICLib assembly to access connection functionality built into the ActiveX connector

Datasourcecs Provides method for accessing path port host and other information

Enumerationscs Provides enumerations for AccessType and LoadType

Envelopecs Provides methods for getting and setting xy coordinates of the envelope

ImageReturnObjectcs Provides methods for settinggetting image URL image envelope and image scale

Mapcs Calls send request to service with connection and service information Parses response to obtain image URL

Servicecs Servicescs Inherits from

SystemCollectionsHashtable Composes the clientservices request and parses the response Creates a hashtable association of individual service name with its associated service object

XML helper class that provides relevant XML parsing functionality by acting as a wrapper class around NETs xml Text IO and other NET classes

XMLRequestscs Builds ArcXML strings for requests

XMLHelpercs

Steps to Create Application

ESRI White Paper 19

The NET solution contains 2 projects ArcIMS and ArcIMSSample The ArcIMS project

o References the InteropAICLib o Contains NET ArcIMS class libraries that can be used to connect and to

work with image services The ArcIMSSample project

o References the ArcIMS project o Contains the web form (webform1aspx) and the corresponding

webform1aspxcs code-behind page that connects the web page controls to relevant functionality using an event driven web forms model

Points to Note

In webform1aspxcs code session variables are used to maintain state of serialized objects In order for this to be possible notice that the relevant classes have been marked as serializable

ESRI White Paper 20

Choose the appropriate connection type based on HTTP or TCP connection For HTTP choose m_dsConnectType = ConnectionTypeInterNet and for For TCP select m_dsConnectType = ConnectionTypeIntraNet as shown in the code below

private ArcIMSDataSource getDataSource() m_ds = Session[datasource] as ArcIMSDataSource if ( m_ds == null ) m_ds = new ArcIMSDataSource() m_dsHost = localhost m_dsScheme = http m_dsPort = 80 m_dsAppServerPort = 5300 m_dsPath = servletcomesriesrimapEsrimap choose (comment uncomment) one of the following two statements to decide between TCP or HTTP type connection m_dsConnectType = ConnectionTypeIntraNet m_dsConnectType = ConnectionTypeInterNet SessionAdd(datasource m_ds) return m_ds

Accessing a COM Server from a NET Client With the introduction of the NET Framework and ASPNET COM at its basic level has not really changed Nevertheless there are a couple of issues to be aware of when making calls to a COM object from a NET managed code environment The ASPNET threading model is the Multiple Threaded Apartment (MTA) This will not interact reliably with STA components (the ActiveX connector provided with the ArcIMS setup was built as an STA component) To emphasize this issue heres a direct quote from the MSDN pages at Microsoft The ASPNET threading model is the Multiple Threaded Apartment (MTA) What this means is that components that you are using that were created for the Single Threaded Apartment (STA) will no longer perform or function reliably without taking some extra precautions in ASPNET This includes but is not limited to all COM components that have been created using Visual Basic 60 and earlier versions

To understand the issues better let us take a look at how NET deals with COM related issues The Common Language Runtime exposes COM objects through a proxy called the runtime callable wrapper (RCW) The RCWs primary function is to marshal calls between a NET client and COM object The RCW object is nothing but an object instantiated at runtime from class code contained in the Interop assembly

ESRI White Paper 21

Calling between managed and unmanaged components incurs a marshaling cost which can impede the performance of your pages When a managed client and unmanaged server are in the same apartment the Interop marshalling service handles all data marshalling However when client and server are initialized in different apartments COM marshalling is also required Therefore interoperability with COM from a NET client should take into consideration the threading model used

Figure Cross-apartment call between a NET client and COM object

As mentioned earlier ASPNET follows an MTA model by default You could use the default model to communicate with an STA COM component if there is not much of an overhead due to the cross-apartment marshalling Usually this is noticeable only when there are many calls across the boundary Another option would be to use the PageAspCompatMode property of the ASPNET client The ASPCompat=true attribute enables an STA thread pool to address performance with existing Visual Basic components on a per-page basis The runtime throws an exception if the compatibility tag is omitted and an STA component is referenced on the page If you convert the STA component to an assembly using Type Library Importer (a utility included with the NET SDK) the runtime does not detect that the component uses the STA model and does not throw an exception but your application can suffer from poor performance and possible deadlocks STA components cannot be used from NET Framework code modules (compiled NET assemblies) they can be used only from ASPNET pages

If you plan to use the ASPCOMPAT = TRUE page level directive for Example 1 remember to instantiate the COM object within the page_load event rather than constructing COM components during page construction time For example look at code examples A and B

Example A Example B ltPage Language = VB ASPCOMPAT = truegt

ltscript runat = servergt

private mapStates as new aimsMap()

private sub_load ()

ltPage Language = VB ASPCOMPAT = truegt

ltscript runat = servergt

private mapStates as aimsMap()

private sub_load ()

ESRI White Paper 22

end sub

mapStates = new aimsMap()

end sub

In example A the STA component would be instantiated at page construction time which is created from a thread that is not the STA thread that will run the page This will involve marshalling between MTA and STA threads during the construction of the page Example B shows the preferred mechanism to delay the process until later when the code executes under a STA thread It is best to construct any COM component and external resources when needed or in the Page_Load method

Also to create the object you can use either the New keyword or the CreateObject method The CreateObject method is typically used when you dont know the Program ID (ProgID) of the object you are going to create until run time (late binding) New is the recommended method for instantiating objects if you have access to the objects type library It is preferable to adopt the early binding model

Every scenario yields different performance characteristics so it is important to test adequately before deciding whether interoperability is the right choice for your application However in nearly all scenarios rewriting your COM components in managed code provides performance benefits

Summary The examples shown above provide adequate information to leverage the NET programming environment to build effective ArcIMS client applications The debugging features of a program like Visual StudioNET provide a variety of tools (break points trace etc) making the entire development experience considerably pain-free Use the debugger to understand the sequence in which calls are made One early exercise would be to look at the calling sequence of the various page related events such as page_init page_load and page_prerender Since the Web Forms code is compiled you should experience much better performance than with ASP pages that used code written in scripting languages like Javascript and VbScript

The powerful programming environment also means that you can now concentrate more on the logic of building large web applications as opposed to building simple page based asp applications Also look at the various caching mechanisms provided by ASPNET as these can be used to improve overall performance As always there are costs associated with most programming choices and this is all the more true in a web-programming environment For example consider the costs associated with using a web control as opposed to a HTML based control Use plain HTML controls instead of adopting web controls for simple items like label

ESRI White Paper 23

If you choose to use the ActiveX connector from within the NET environment make sure that you clearly understand the essentials of COM Interop and the various costs associated with marshalling The solutions outlined in this paper utilize existing ArcIMS services and should work with all versions of ArcIMS

Although all the development can be done without the use of an Integrated Development environment (IDE) like Visual StudioNET using such an environment provides convenient WYSIWYG features that can help in building and debugging the application If you do not have Visual StudioNET there are free IDEs available today that can also be used For example ASPNET Web Matrix is a community-supported easy-to-use WYSIWYG application development tool for ASPNET It can be installed via a quick 12 MB download from httpwwwaspnetwebmatrixdefaultaspx

ESRI White Paper 24

  • ArcIMS ndash An Introduction
  • What is NET
    • The NET Framework
      • The Common Language Runtime (CLR)
      • Managed Unmanaged and Unsafe code ndash Understandin
      • NET Framework Class Libraries
        • ASPNET and Web Forms
          • NET and ArcIMS
            • Example 1
            • Example 2
            • Example 3
              • Accessing a COM Server from a NET Client
              • Summary
Page 19: Consuming ArcIMS Image Services using .NET Client Web ... · Consuming ArcIMS Image Services using .NET Client Web Applications An ESRI White Paper Ł October 2002 ... The .NET framework

based on the radio button selection ( Zoomin Zoomout or pan) the code calls the appropriate method using the instantiated Cviewer object

Private Sub imgMap_Click(ByVal sender As Object ByVal e As SystemWebUIImageClickEventArgs) Handles imgMapClick Convert the image click coordinate to a map coordinate based on the maps current extent Dim rctCurrentExtent As cRect = m_objViewerMapExtent Dim dblX As Double = rctCurrentExtentXMin + ((eX imgMapWidthValue) (rctCurrentExtentXMax - rctCurrentExtentXMin)) Dim dblY As Double = rctCurrentExtentYMin + (((imgMapHeightValue - eY) imgMapHeightValue) (rctCurrentExtentYMax - rctCurrentExtentYMin)) If Trim(UCase(lstNavControlsSelectedItemText)) ltgt IDENTIFY Then m_objViewerMapCenterAt(dblX dblY) Select Case UCase(lstNavControlsSelectedItemText) Case ZOOM IN Center the map m_objViewerMapZoom(-1) Case ZOOM OUT m_objViewerMapZoom(1) Case PAN do nothing Case Else ErrRaise(vbObjectError + 512 imgMap_Click Invalid command) End Select Else identify End If End Sub

ESRI White Paper 16

End Class

NOTE =gt Once you have the relevant files imported into Visual Studio make sure that you configure the virtual directory as an application before you run the example

If the virtual directory is not configured as an Application you will get an error message that reads This error can be caused by a virtual directory not being configured as an application in IIS To configure a Virtual directory is simple Use the Internet Service Manager to perform the following steps

Find the folder in the virtual directory Right click and choose properties Click Create Accept all the settings and Click OK

Example 3

General Description

The program uses the catalog service (using the ltGETCLIENTSERVICESgt request) to query and list a collection of services running on the server A Radiobutton list control is used to list all the service names running on the server On selecting an appropriate image service the map image is displayed on the web form using an image control This program demonstrates two different ways to connect to the datasource Connection could be achieved using the http protocol or the TCP protocol The TCP method utilizes the TCP capability built into the ActiveX Connector Since ASPNET is a multithreaded and the ActiveX connector being Single Threaded (STA) a wrapper class with additional functionality to manage memory is used to access the methods in the ActiveX connector

ESRI White Paper 17

Programming Environment ASPNET and Web Forms

C NET Programming Language

WebForm Controls

Control Name Function ImgMap Control for displaying the image RbServices Radiobutton list controls Txtinfo Displays the name of the selected image service

Data Files

Requires a collection of image services running on an ArcIMS server The program uses the ltGETCLIENTSERVICESgt request tag to query the catalog service to list all the services running on the specified server

Class Libraries

File Name Class Information Functionality Connectioncs Abstract base class Provides abstract method

templates for the HTTPConnection and

ESRI White Paper 18

TCPConnection classes HTTPConnectioncs Inherits from Connection class Provides functionality for

sending request to service postinggetting URL content etc

TCPConnectioncs Inherits from Connection class and SystemIDisposable

Utlizes the AICLib assembly to access connection functionality built into the ActiveX connector

Datasourcecs Provides method for accessing path port host and other information

Enumerationscs Provides enumerations for AccessType and LoadType

Envelopecs Provides methods for getting and setting xy coordinates of the envelope

ImageReturnObjectcs Provides methods for settinggetting image URL image envelope and image scale

Mapcs Calls send request to service with connection and service information Parses response to obtain image URL

Servicecs Servicescs Inherits from

SystemCollectionsHashtable Composes the clientservices request and parses the response Creates a hashtable association of individual service name with its associated service object

XML helper class that provides relevant XML parsing functionality by acting as a wrapper class around NETs xml Text IO and other NET classes

XMLRequestscs Builds ArcXML strings for requests

XMLHelpercs

Steps to Create Application

ESRI White Paper 19

The NET solution contains 2 projects ArcIMS and ArcIMSSample The ArcIMS project

o References the InteropAICLib o Contains NET ArcIMS class libraries that can be used to connect and to

work with image services The ArcIMSSample project

o References the ArcIMS project o Contains the web form (webform1aspx) and the corresponding

webform1aspxcs code-behind page that connects the web page controls to relevant functionality using an event driven web forms model

Points to Note

In webform1aspxcs code session variables are used to maintain state of serialized objects In order for this to be possible notice that the relevant classes have been marked as serializable

ESRI White Paper 20

Choose the appropriate connection type based on HTTP or TCP connection For HTTP choose m_dsConnectType = ConnectionTypeInterNet and for For TCP select m_dsConnectType = ConnectionTypeIntraNet as shown in the code below

private ArcIMSDataSource getDataSource() m_ds = Session[datasource] as ArcIMSDataSource if ( m_ds == null ) m_ds = new ArcIMSDataSource() m_dsHost = localhost m_dsScheme = http m_dsPort = 80 m_dsAppServerPort = 5300 m_dsPath = servletcomesriesrimapEsrimap choose (comment uncomment) one of the following two statements to decide between TCP or HTTP type connection m_dsConnectType = ConnectionTypeIntraNet m_dsConnectType = ConnectionTypeInterNet SessionAdd(datasource m_ds) return m_ds

Accessing a COM Server from a NET Client With the introduction of the NET Framework and ASPNET COM at its basic level has not really changed Nevertheless there are a couple of issues to be aware of when making calls to a COM object from a NET managed code environment The ASPNET threading model is the Multiple Threaded Apartment (MTA) This will not interact reliably with STA components (the ActiveX connector provided with the ArcIMS setup was built as an STA component) To emphasize this issue heres a direct quote from the MSDN pages at Microsoft The ASPNET threading model is the Multiple Threaded Apartment (MTA) What this means is that components that you are using that were created for the Single Threaded Apartment (STA) will no longer perform or function reliably without taking some extra precautions in ASPNET This includes but is not limited to all COM components that have been created using Visual Basic 60 and earlier versions

To understand the issues better let us take a look at how NET deals with COM related issues The Common Language Runtime exposes COM objects through a proxy called the runtime callable wrapper (RCW) The RCWs primary function is to marshal calls between a NET client and COM object The RCW object is nothing but an object instantiated at runtime from class code contained in the Interop assembly

ESRI White Paper 21

Calling between managed and unmanaged components incurs a marshaling cost which can impede the performance of your pages When a managed client and unmanaged server are in the same apartment the Interop marshalling service handles all data marshalling However when client and server are initialized in different apartments COM marshalling is also required Therefore interoperability with COM from a NET client should take into consideration the threading model used

Figure Cross-apartment call between a NET client and COM object

As mentioned earlier ASPNET follows an MTA model by default You could use the default model to communicate with an STA COM component if there is not much of an overhead due to the cross-apartment marshalling Usually this is noticeable only when there are many calls across the boundary Another option would be to use the PageAspCompatMode property of the ASPNET client The ASPCompat=true attribute enables an STA thread pool to address performance with existing Visual Basic components on a per-page basis The runtime throws an exception if the compatibility tag is omitted and an STA component is referenced on the page If you convert the STA component to an assembly using Type Library Importer (a utility included with the NET SDK) the runtime does not detect that the component uses the STA model and does not throw an exception but your application can suffer from poor performance and possible deadlocks STA components cannot be used from NET Framework code modules (compiled NET assemblies) they can be used only from ASPNET pages

If you plan to use the ASPCOMPAT = TRUE page level directive for Example 1 remember to instantiate the COM object within the page_load event rather than constructing COM components during page construction time For example look at code examples A and B

Example A Example B ltPage Language = VB ASPCOMPAT = truegt

ltscript runat = servergt

private mapStates as new aimsMap()

private sub_load ()

ltPage Language = VB ASPCOMPAT = truegt

ltscript runat = servergt

private mapStates as aimsMap()

private sub_load ()

ESRI White Paper 22

end sub

mapStates = new aimsMap()

end sub

In example A the STA component would be instantiated at page construction time which is created from a thread that is not the STA thread that will run the page This will involve marshalling between MTA and STA threads during the construction of the page Example B shows the preferred mechanism to delay the process until later when the code executes under a STA thread It is best to construct any COM component and external resources when needed or in the Page_Load method

Also to create the object you can use either the New keyword or the CreateObject method The CreateObject method is typically used when you dont know the Program ID (ProgID) of the object you are going to create until run time (late binding) New is the recommended method for instantiating objects if you have access to the objects type library It is preferable to adopt the early binding model

Every scenario yields different performance characteristics so it is important to test adequately before deciding whether interoperability is the right choice for your application However in nearly all scenarios rewriting your COM components in managed code provides performance benefits

Summary The examples shown above provide adequate information to leverage the NET programming environment to build effective ArcIMS client applications The debugging features of a program like Visual StudioNET provide a variety of tools (break points trace etc) making the entire development experience considerably pain-free Use the debugger to understand the sequence in which calls are made One early exercise would be to look at the calling sequence of the various page related events such as page_init page_load and page_prerender Since the Web Forms code is compiled you should experience much better performance than with ASP pages that used code written in scripting languages like Javascript and VbScript

The powerful programming environment also means that you can now concentrate more on the logic of building large web applications as opposed to building simple page based asp applications Also look at the various caching mechanisms provided by ASPNET as these can be used to improve overall performance As always there are costs associated with most programming choices and this is all the more true in a web-programming environment For example consider the costs associated with using a web control as opposed to a HTML based control Use plain HTML controls instead of adopting web controls for simple items like label

ESRI White Paper 23

If you choose to use the ActiveX connector from within the NET environment make sure that you clearly understand the essentials of COM Interop and the various costs associated with marshalling The solutions outlined in this paper utilize existing ArcIMS services and should work with all versions of ArcIMS

Although all the development can be done without the use of an Integrated Development environment (IDE) like Visual StudioNET using such an environment provides convenient WYSIWYG features that can help in building and debugging the application If you do not have Visual StudioNET there are free IDEs available today that can also be used For example ASPNET Web Matrix is a community-supported easy-to-use WYSIWYG application development tool for ASPNET It can be installed via a quick 12 MB download from httpwwwaspnetwebmatrixdefaultaspx

ESRI White Paper 24

  • ArcIMS ndash An Introduction
  • What is NET
    • The NET Framework
      • The Common Language Runtime (CLR)
      • Managed Unmanaged and Unsafe code ndash Understandin
      • NET Framework Class Libraries
        • ASPNET and Web Forms
          • NET and ArcIMS
            • Example 1
            • Example 2
            • Example 3
              • Accessing a COM Server from a NET Client
              • Summary
Page 20: Consuming ArcIMS Image Services using .NET Client Web ... · Consuming ArcIMS Image Services using .NET Client Web Applications An ESRI White Paper Ł October 2002 ... The .NET framework

End Class

NOTE =gt Once you have the relevant files imported into Visual Studio make sure that you configure the virtual directory as an application before you run the example

If the virtual directory is not configured as an Application you will get an error message that reads This error can be caused by a virtual directory not being configured as an application in IIS To configure a Virtual directory is simple Use the Internet Service Manager to perform the following steps

Find the folder in the virtual directory Right click and choose properties Click Create Accept all the settings and Click OK

Example 3

General Description

The program uses the catalog service (using the ltGETCLIENTSERVICESgt request) to query and list a collection of services running on the server A Radiobutton list control is used to list all the service names running on the server On selecting an appropriate image service the map image is displayed on the web form using an image control This program demonstrates two different ways to connect to the datasource Connection could be achieved using the http protocol or the TCP protocol The TCP method utilizes the TCP capability built into the ActiveX Connector Since ASPNET is a multithreaded and the ActiveX connector being Single Threaded (STA) a wrapper class with additional functionality to manage memory is used to access the methods in the ActiveX connector

ESRI White Paper 17

Programming Environment ASPNET and Web Forms

C NET Programming Language

WebForm Controls

Control Name Function ImgMap Control for displaying the image RbServices Radiobutton list controls Txtinfo Displays the name of the selected image service

Data Files

Requires a collection of image services running on an ArcIMS server The program uses the ltGETCLIENTSERVICESgt request tag to query the catalog service to list all the services running on the specified server

Class Libraries

File Name Class Information Functionality Connectioncs Abstract base class Provides abstract method

templates for the HTTPConnection and

ESRI White Paper 18

TCPConnection classes HTTPConnectioncs Inherits from Connection class Provides functionality for

sending request to service postinggetting URL content etc

TCPConnectioncs Inherits from Connection class and SystemIDisposable

Utlizes the AICLib assembly to access connection functionality built into the ActiveX connector

Datasourcecs Provides method for accessing path port host and other information

Enumerationscs Provides enumerations for AccessType and LoadType

Envelopecs Provides methods for getting and setting xy coordinates of the envelope

ImageReturnObjectcs Provides methods for settinggetting image URL image envelope and image scale

Mapcs Calls send request to service with connection and service information Parses response to obtain image URL

Servicecs Servicescs Inherits from

SystemCollectionsHashtable Composes the clientservices request and parses the response Creates a hashtable association of individual service name with its associated service object

XML helper class that provides relevant XML parsing functionality by acting as a wrapper class around NETs xml Text IO and other NET classes

XMLRequestscs Builds ArcXML strings for requests

XMLHelpercs

Steps to Create Application

ESRI White Paper 19

The NET solution contains 2 projects ArcIMS and ArcIMSSample The ArcIMS project

o References the InteropAICLib o Contains NET ArcIMS class libraries that can be used to connect and to

work with image services The ArcIMSSample project

o References the ArcIMS project o Contains the web form (webform1aspx) and the corresponding

webform1aspxcs code-behind page that connects the web page controls to relevant functionality using an event driven web forms model

Points to Note

In webform1aspxcs code session variables are used to maintain state of serialized objects In order for this to be possible notice that the relevant classes have been marked as serializable

ESRI White Paper 20

Choose the appropriate connection type based on HTTP or TCP connection For HTTP choose m_dsConnectType = ConnectionTypeInterNet and for For TCP select m_dsConnectType = ConnectionTypeIntraNet as shown in the code below

private ArcIMSDataSource getDataSource() m_ds = Session[datasource] as ArcIMSDataSource if ( m_ds == null ) m_ds = new ArcIMSDataSource() m_dsHost = localhost m_dsScheme = http m_dsPort = 80 m_dsAppServerPort = 5300 m_dsPath = servletcomesriesrimapEsrimap choose (comment uncomment) one of the following two statements to decide between TCP or HTTP type connection m_dsConnectType = ConnectionTypeIntraNet m_dsConnectType = ConnectionTypeInterNet SessionAdd(datasource m_ds) return m_ds

Accessing a COM Server from a NET Client With the introduction of the NET Framework and ASPNET COM at its basic level has not really changed Nevertheless there are a couple of issues to be aware of when making calls to a COM object from a NET managed code environment The ASPNET threading model is the Multiple Threaded Apartment (MTA) This will not interact reliably with STA components (the ActiveX connector provided with the ArcIMS setup was built as an STA component) To emphasize this issue heres a direct quote from the MSDN pages at Microsoft The ASPNET threading model is the Multiple Threaded Apartment (MTA) What this means is that components that you are using that were created for the Single Threaded Apartment (STA) will no longer perform or function reliably without taking some extra precautions in ASPNET This includes but is not limited to all COM components that have been created using Visual Basic 60 and earlier versions

To understand the issues better let us take a look at how NET deals with COM related issues The Common Language Runtime exposes COM objects through a proxy called the runtime callable wrapper (RCW) The RCWs primary function is to marshal calls between a NET client and COM object The RCW object is nothing but an object instantiated at runtime from class code contained in the Interop assembly

ESRI White Paper 21

Calling between managed and unmanaged components incurs a marshaling cost which can impede the performance of your pages When a managed client and unmanaged server are in the same apartment the Interop marshalling service handles all data marshalling However when client and server are initialized in different apartments COM marshalling is also required Therefore interoperability with COM from a NET client should take into consideration the threading model used

Figure Cross-apartment call between a NET client and COM object

As mentioned earlier ASPNET follows an MTA model by default You could use the default model to communicate with an STA COM component if there is not much of an overhead due to the cross-apartment marshalling Usually this is noticeable only when there are many calls across the boundary Another option would be to use the PageAspCompatMode property of the ASPNET client The ASPCompat=true attribute enables an STA thread pool to address performance with existing Visual Basic components on a per-page basis The runtime throws an exception if the compatibility tag is omitted and an STA component is referenced on the page If you convert the STA component to an assembly using Type Library Importer (a utility included with the NET SDK) the runtime does not detect that the component uses the STA model and does not throw an exception but your application can suffer from poor performance and possible deadlocks STA components cannot be used from NET Framework code modules (compiled NET assemblies) they can be used only from ASPNET pages

If you plan to use the ASPCOMPAT = TRUE page level directive for Example 1 remember to instantiate the COM object within the page_load event rather than constructing COM components during page construction time For example look at code examples A and B

Example A Example B ltPage Language = VB ASPCOMPAT = truegt

ltscript runat = servergt

private mapStates as new aimsMap()

private sub_load ()

ltPage Language = VB ASPCOMPAT = truegt

ltscript runat = servergt

private mapStates as aimsMap()

private sub_load ()

ESRI White Paper 22

end sub

mapStates = new aimsMap()

end sub

In example A the STA component would be instantiated at page construction time which is created from a thread that is not the STA thread that will run the page This will involve marshalling between MTA and STA threads during the construction of the page Example B shows the preferred mechanism to delay the process until later when the code executes under a STA thread It is best to construct any COM component and external resources when needed or in the Page_Load method

Also to create the object you can use either the New keyword or the CreateObject method The CreateObject method is typically used when you dont know the Program ID (ProgID) of the object you are going to create until run time (late binding) New is the recommended method for instantiating objects if you have access to the objects type library It is preferable to adopt the early binding model

Every scenario yields different performance characteristics so it is important to test adequately before deciding whether interoperability is the right choice for your application However in nearly all scenarios rewriting your COM components in managed code provides performance benefits

Summary The examples shown above provide adequate information to leverage the NET programming environment to build effective ArcIMS client applications The debugging features of a program like Visual StudioNET provide a variety of tools (break points trace etc) making the entire development experience considerably pain-free Use the debugger to understand the sequence in which calls are made One early exercise would be to look at the calling sequence of the various page related events such as page_init page_load and page_prerender Since the Web Forms code is compiled you should experience much better performance than with ASP pages that used code written in scripting languages like Javascript and VbScript

The powerful programming environment also means that you can now concentrate more on the logic of building large web applications as opposed to building simple page based asp applications Also look at the various caching mechanisms provided by ASPNET as these can be used to improve overall performance As always there are costs associated with most programming choices and this is all the more true in a web-programming environment For example consider the costs associated with using a web control as opposed to a HTML based control Use plain HTML controls instead of adopting web controls for simple items like label

ESRI White Paper 23

If you choose to use the ActiveX connector from within the NET environment make sure that you clearly understand the essentials of COM Interop and the various costs associated with marshalling The solutions outlined in this paper utilize existing ArcIMS services and should work with all versions of ArcIMS

Although all the development can be done without the use of an Integrated Development environment (IDE) like Visual StudioNET using such an environment provides convenient WYSIWYG features that can help in building and debugging the application If you do not have Visual StudioNET there are free IDEs available today that can also be used For example ASPNET Web Matrix is a community-supported easy-to-use WYSIWYG application development tool for ASPNET It can be installed via a quick 12 MB download from httpwwwaspnetwebmatrixdefaultaspx

ESRI White Paper 24

  • ArcIMS ndash An Introduction
  • What is NET
    • The NET Framework
      • The Common Language Runtime (CLR)
      • Managed Unmanaged and Unsafe code ndash Understandin
      • NET Framework Class Libraries
        • ASPNET and Web Forms
          • NET and ArcIMS
            • Example 1
            • Example 2
            • Example 3
              • Accessing a COM Server from a NET Client
              • Summary
Page 21: Consuming ArcIMS Image Services using .NET Client Web ... · Consuming ArcIMS Image Services using .NET Client Web Applications An ESRI White Paper Ł October 2002 ... The .NET framework

Programming Environment ASPNET and Web Forms

C NET Programming Language

WebForm Controls

Control Name Function ImgMap Control for displaying the image RbServices Radiobutton list controls Txtinfo Displays the name of the selected image service

Data Files

Requires a collection of image services running on an ArcIMS server The program uses the ltGETCLIENTSERVICESgt request tag to query the catalog service to list all the services running on the specified server

Class Libraries

File Name Class Information Functionality Connectioncs Abstract base class Provides abstract method

templates for the HTTPConnection and

ESRI White Paper 18

TCPConnection classes HTTPConnectioncs Inherits from Connection class Provides functionality for

sending request to service postinggetting URL content etc

TCPConnectioncs Inherits from Connection class and SystemIDisposable

Utlizes the AICLib assembly to access connection functionality built into the ActiveX connector

Datasourcecs Provides method for accessing path port host and other information

Enumerationscs Provides enumerations for AccessType and LoadType

Envelopecs Provides methods for getting and setting xy coordinates of the envelope

ImageReturnObjectcs Provides methods for settinggetting image URL image envelope and image scale

Mapcs Calls send request to service with connection and service information Parses response to obtain image URL

Servicecs Servicescs Inherits from

SystemCollectionsHashtable Composes the clientservices request and parses the response Creates a hashtable association of individual service name with its associated service object

XML helper class that provides relevant XML parsing functionality by acting as a wrapper class around NETs xml Text IO and other NET classes

XMLRequestscs Builds ArcXML strings for requests

XMLHelpercs

Steps to Create Application

ESRI White Paper 19

The NET solution contains 2 projects ArcIMS and ArcIMSSample The ArcIMS project

o References the InteropAICLib o Contains NET ArcIMS class libraries that can be used to connect and to

work with image services The ArcIMSSample project

o References the ArcIMS project o Contains the web form (webform1aspx) and the corresponding

webform1aspxcs code-behind page that connects the web page controls to relevant functionality using an event driven web forms model

Points to Note

In webform1aspxcs code session variables are used to maintain state of serialized objects In order for this to be possible notice that the relevant classes have been marked as serializable

ESRI White Paper 20

Choose the appropriate connection type based on HTTP or TCP connection For HTTP choose m_dsConnectType = ConnectionTypeInterNet and for For TCP select m_dsConnectType = ConnectionTypeIntraNet as shown in the code below

private ArcIMSDataSource getDataSource() m_ds = Session[datasource] as ArcIMSDataSource if ( m_ds == null ) m_ds = new ArcIMSDataSource() m_dsHost = localhost m_dsScheme = http m_dsPort = 80 m_dsAppServerPort = 5300 m_dsPath = servletcomesriesrimapEsrimap choose (comment uncomment) one of the following two statements to decide between TCP or HTTP type connection m_dsConnectType = ConnectionTypeIntraNet m_dsConnectType = ConnectionTypeInterNet SessionAdd(datasource m_ds) return m_ds

Accessing a COM Server from a NET Client With the introduction of the NET Framework and ASPNET COM at its basic level has not really changed Nevertheless there are a couple of issues to be aware of when making calls to a COM object from a NET managed code environment The ASPNET threading model is the Multiple Threaded Apartment (MTA) This will not interact reliably with STA components (the ActiveX connector provided with the ArcIMS setup was built as an STA component) To emphasize this issue heres a direct quote from the MSDN pages at Microsoft The ASPNET threading model is the Multiple Threaded Apartment (MTA) What this means is that components that you are using that were created for the Single Threaded Apartment (STA) will no longer perform or function reliably without taking some extra precautions in ASPNET This includes but is not limited to all COM components that have been created using Visual Basic 60 and earlier versions

To understand the issues better let us take a look at how NET deals with COM related issues The Common Language Runtime exposes COM objects through a proxy called the runtime callable wrapper (RCW) The RCWs primary function is to marshal calls between a NET client and COM object The RCW object is nothing but an object instantiated at runtime from class code contained in the Interop assembly

ESRI White Paper 21

Calling between managed and unmanaged components incurs a marshaling cost which can impede the performance of your pages When a managed client and unmanaged server are in the same apartment the Interop marshalling service handles all data marshalling However when client and server are initialized in different apartments COM marshalling is also required Therefore interoperability with COM from a NET client should take into consideration the threading model used

Figure Cross-apartment call between a NET client and COM object

As mentioned earlier ASPNET follows an MTA model by default You could use the default model to communicate with an STA COM component if there is not much of an overhead due to the cross-apartment marshalling Usually this is noticeable only when there are many calls across the boundary Another option would be to use the PageAspCompatMode property of the ASPNET client The ASPCompat=true attribute enables an STA thread pool to address performance with existing Visual Basic components on a per-page basis The runtime throws an exception if the compatibility tag is omitted and an STA component is referenced on the page If you convert the STA component to an assembly using Type Library Importer (a utility included with the NET SDK) the runtime does not detect that the component uses the STA model and does not throw an exception but your application can suffer from poor performance and possible deadlocks STA components cannot be used from NET Framework code modules (compiled NET assemblies) they can be used only from ASPNET pages

If you plan to use the ASPCOMPAT = TRUE page level directive for Example 1 remember to instantiate the COM object within the page_load event rather than constructing COM components during page construction time For example look at code examples A and B

Example A Example B ltPage Language = VB ASPCOMPAT = truegt

ltscript runat = servergt

private mapStates as new aimsMap()

private sub_load ()

ltPage Language = VB ASPCOMPAT = truegt

ltscript runat = servergt

private mapStates as aimsMap()

private sub_load ()

ESRI White Paper 22

end sub

mapStates = new aimsMap()

end sub

In example A the STA component would be instantiated at page construction time which is created from a thread that is not the STA thread that will run the page This will involve marshalling between MTA and STA threads during the construction of the page Example B shows the preferred mechanism to delay the process until later when the code executes under a STA thread It is best to construct any COM component and external resources when needed or in the Page_Load method

Also to create the object you can use either the New keyword or the CreateObject method The CreateObject method is typically used when you dont know the Program ID (ProgID) of the object you are going to create until run time (late binding) New is the recommended method for instantiating objects if you have access to the objects type library It is preferable to adopt the early binding model

Every scenario yields different performance characteristics so it is important to test adequately before deciding whether interoperability is the right choice for your application However in nearly all scenarios rewriting your COM components in managed code provides performance benefits

Summary The examples shown above provide adequate information to leverage the NET programming environment to build effective ArcIMS client applications The debugging features of a program like Visual StudioNET provide a variety of tools (break points trace etc) making the entire development experience considerably pain-free Use the debugger to understand the sequence in which calls are made One early exercise would be to look at the calling sequence of the various page related events such as page_init page_load and page_prerender Since the Web Forms code is compiled you should experience much better performance than with ASP pages that used code written in scripting languages like Javascript and VbScript

The powerful programming environment also means that you can now concentrate more on the logic of building large web applications as opposed to building simple page based asp applications Also look at the various caching mechanisms provided by ASPNET as these can be used to improve overall performance As always there are costs associated with most programming choices and this is all the more true in a web-programming environment For example consider the costs associated with using a web control as opposed to a HTML based control Use plain HTML controls instead of adopting web controls for simple items like label

ESRI White Paper 23

If you choose to use the ActiveX connector from within the NET environment make sure that you clearly understand the essentials of COM Interop and the various costs associated with marshalling The solutions outlined in this paper utilize existing ArcIMS services and should work with all versions of ArcIMS

Although all the development can be done without the use of an Integrated Development environment (IDE) like Visual StudioNET using such an environment provides convenient WYSIWYG features that can help in building and debugging the application If you do not have Visual StudioNET there are free IDEs available today that can also be used For example ASPNET Web Matrix is a community-supported easy-to-use WYSIWYG application development tool for ASPNET It can be installed via a quick 12 MB download from httpwwwaspnetwebmatrixdefaultaspx

ESRI White Paper 24

  • ArcIMS ndash An Introduction
  • What is NET
    • The NET Framework
      • The Common Language Runtime (CLR)
      • Managed Unmanaged and Unsafe code ndash Understandin
      • NET Framework Class Libraries
        • ASPNET and Web Forms
          • NET and ArcIMS
            • Example 1
            • Example 2
            • Example 3
              • Accessing a COM Server from a NET Client
              • Summary
Page 22: Consuming ArcIMS Image Services using .NET Client Web ... · Consuming ArcIMS Image Services using .NET Client Web Applications An ESRI White Paper Ł October 2002 ... The .NET framework

TCPConnection classes HTTPConnectioncs Inherits from Connection class Provides functionality for

sending request to service postinggetting URL content etc

TCPConnectioncs Inherits from Connection class and SystemIDisposable

Utlizes the AICLib assembly to access connection functionality built into the ActiveX connector

Datasourcecs Provides method for accessing path port host and other information

Enumerationscs Provides enumerations for AccessType and LoadType

Envelopecs Provides methods for getting and setting xy coordinates of the envelope

ImageReturnObjectcs Provides methods for settinggetting image URL image envelope and image scale

Mapcs Calls send request to service with connection and service information Parses response to obtain image URL

Servicecs Servicescs Inherits from

SystemCollectionsHashtable Composes the clientservices request and parses the response Creates a hashtable association of individual service name with its associated service object

XML helper class that provides relevant XML parsing functionality by acting as a wrapper class around NETs xml Text IO and other NET classes

XMLRequestscs Builds ArcXML strings for requests

XMLHelpercs

Steps to Create Application

ESRI White Paper 19

The NET solution contains 2 projects ArcIMS and ArcIMSSample The ArcIMS project

o References the InteropAICLib o Contains NET ArcIMS class libraries that can be used to connect and to

work with image services The ArcIMSSample project

o References the ArcIMS project o Contains the web form (webform1aspx) and the corresponding

webform1aspxcs code-behind page that connects the web page controls to relevant functionality using an event driven web forms model

Points to Note

In webform1aspxcs code session variables are used to maintain state of serialized objects In order for this to be possible notice that the relevant classes have been marked as serializable

ESRI White Paper 20

Choose the appropriate connection type based on HTTP or TCP connection For HTTP choose m_dsConnectType = ConnectionTypeInterNet and for For TCP select m_dsConnectType = ConnectionTypeIntraNet as shown in the code below

private ArcIMSDataSource getDataSource() m_ds = Session[datasource] as ArcIMSDataSource if ( m_ds == null ) m_ds = new ArcIMSDataSource() m_dsHost = localhost m_dsScheme = http m_dsPort = 80 m_dsAppServerPort = 5300 m_dsPath = servletcomesriesrimapEsrimap choose (comment uncomment) one of the following two statements to decide between TCP or HTTP type connection m_dsConnectType = ConnectionTypeIntraNet m_dsConnectType = ConnectionTypeInterNet SessionAdd(datasource m_ds) return m_ds

Accessing a COM Server from a NET Client With the introduction of the NET Framework and ASPNET COM at its basic level has not really changed Nevertheless there are a couple of issues to be aware of when making calls to a COM object from a NET managed code environment The ASPNET threading model is the Multiple Threaded Apartment (MTA) This will not interact reliably with STA components (the ActiveX connector provided with the ArcIMS setup was built as an STA component) To emphasize this issue heres a direct quote from the MSDN pages at Microsoft The ASPNET threading model is the Multiple Threaded Apartment (MTA) What this means is that components that you are using that were created for the Single Threaded Apartment (STA) will no longer perform or function reliably without taking some extra precautions in ASPNET This includes but is not limited to all COM components that have been created using Visual Basic 60 and earlier versions

To understand the issues better let us take a look at how NET deals with COM related issues The Common Language Runtime exposes COM objects through a proxy called the runtime callable wrapper (RCW) The RCWs primary function is to marshal calls between a NET client and COM object The RCW object is nothing but an object instantiated at runtime from class code contained in the Interop assembly

ESRI White Paper 21

Calling between managed and unmanaged components incurs a marshaling cost which can impede the performance of your pages When a managed client and unmanaged server are in the same apartment the Interop marshalling service handles all data marshalling However when client and server are initialized in different apartments COM marshalling is also required Therefore interoperability with COM from a NET client should take into consideration the threading model used

Figure Cross-apartment call between a NET client and COM object

As mentioned earlier ASPNET follows an MTA model by default You could use the default model to communicate with an STA COM component if there is not much of an overhead due to the cross-apartment marshalling Usually this is noticeable only when there are many calls across the boundary Another option would be to use the PageAspCompatMode property of the ASPNET client The ASPCompat=true attribute enables an STA thread pool to address performance with existing Visual Basic components on a per-page basis The runtime throws an exception if the compatibility tag is omitted and an STA component is referenced on the page If you convert the STA component to an assembly using Type Library Importer (a utility included with the NET SDK) the runtime does not detect that the component uses the STA model and does not throw an exception but your application can suffer from poor performance and possible deadlocks STA components cannot be used from NET Framework code modules (compiled NET assemblies) they can be used only from ASPNET pages

If you plan to use the ASPCOMPAT = TRUE page level directive for Example 1 remember to instantiate the COM object within the page_load event rather than constructing COM components during page construction time For example look at code examples A and B

Example A Example B ltPage Language = VB ASPCOMPAT = truegt

ltscript runat = servergt

private mapStates as new aimsMap()

private sub_load ()

ltPage Language = VB ASPCOMPAT = truegt

ltscript runat = servergt

private mapStates as aimsMap()

private sub_load ()

ESRI White Paper 22

end sub

mapStates = new aimsMap()

end sub

In example A the STA component would be instantiated at page construction time which is created from a thread that is not the STA thread that will run the page This will involve marshalling between MTA and STA threads during the construction of the page Example B shows the preferred mechanism to delay the process until later when the code executes under a STA thread It is best to construct any COM component and external resources when needed or in the Page_Load method

Also to create the object you can use either the New keyword or the CreateObject method The CreateObject method is typically used when you dont know the Program ID (ProgID) of the object you are going to create until run time (late binding) New is the recommended method for instantiating objects if you have access to the objects type library It is preferable to adopt the early binding model

Every scenario yields different performance characteristics so it is important to test adequately before deciding whether interoperability is the right choice for your application However in nearly all scenarios rewriting your COM components in managed code provides performance benefits

Summary The examples shown above provide adequate information to leverage the NET programming environment to build effective ArcIMS client applications The debugging features of a program like Visual StudioNET provide a variety of tools (break points trace etc) making the entire development experience considerably pain-free Use the debugger to understand the sequence in which calls are made One early exercise would be to look at the calling sequence of the various page related events such as page_init page_load and page_prerender Since the Web Forms code is compiled you should experience much better performance than with ASP pages that used code written in scripting languages like Javascript and VbScript

The powerful programming environment also means that you can now concentrate more on the logic of building large web applications as opposed to building simple page based asp applications Also look at the various caching mechanisms provided by ASPNET as these can be used to improve overall performance As always there are costs associated with most programming choices and this is all the more true in a web-programming environment For example consider the costs associated with using a web control as opposed to a HTML based control Use plain HTML controls instead of adopting web controls for simple items like label

ESRI White Paper 23

If you choose to use the ActiveX connector from within the NET environment make sure that you clearly understand the essentials of COM Interop and the various costs associated with marshalling The solutions outlined in this paper utilize existing ArcIMS services and should work with all versions of ArcIMS

Although all the development can be done without the use of an Integrated Development environment (IDE) like Visual StudioNET using such an environment provides convenient WYSIWYG features that can help in building and debugging the application If you do not have Visual StudioNET there are free IDEs available today that can also be used For example ASPNET Web Matrix is a community-supported easy-to-use WYSIWYG application development tool for ASPNET It can be installed via a quick 12 MB download from httpwwwaspnetwebmatrixdefaultaspx

ESRI White Paper 24

  • ArcIMS ndash An Introduction
  • What is NET
    • The NET Framework
      • The Common Language Runtime (CLR)
      • Managed Unmanaged and Unsafe code ndash Understandin
      • NET Framework Class Libraries
        • ASPNET and Web Forms
          • NET and ArcIMS
            • Example 1
            • Example 2
            • Example 3
              • Accessing a COM Server from a NET Client
              • Summary
Page 23: Consuming ArcIMS Image Services using .NET Client Web ... · Consuming ArcIMS Image Services using .NET Client Web Applications An ESRI White Paper Ł October 2002 ... The .NET framework

The NET solution contains 2 projects ArcIMS and ArcIMSSample The ArcIMS project

o References the InteropAICLib o Contains NET ArcIMS class libraries that can be used to connect and to

work with image services The ArcIMSSample project

o References the ArcIMS project o Contains the web form (webform1aspx) and the corresponding

webform1aspxcs code-behind page that connects the web page controls to relevant functionality using an event driven web forms model

Points to Note

In webform1aspxcs code session variables are used to maintain state of serialized objects In order for this to be possible notice that the relevant classes have been marked as serializable

ESRI White Paper 20

Choose the appropriate connection type based on HTTP or TCP connection For HTTP choose m_dsConnectType = ConnectionTypeInterNet and for For TCP select m_dsConnectType = ConnectionTypeIntraNet as shown in the code below

private ArcIMSDataSource getDataSource() m_ds = Session[datasource] as ArcIMSDataSource if ( m_ds == null ) m_ds = new ArcIMSDataSource() m_dsHost = localhost m_dsScheme = http m_dsPort = 80 m_dsAppServerPort = 5300 m_dsPath = servletcomesriesrimapEsrimap choose (comment uncomment) one of the following two statements to decide between TCP or HTTP type connection m_dsConnectType = ConnectionTypeIntraNet m_dsConnectType = ConnectionTypeInterNet SessionAdd(datasource m_ds) return m_ds

Accessing a COM Server from a NET Client With the introduction of the NET Framework and ASPNET COM at its basic level has not really changed Nevertheless there are a couple of issues to be aware of when making calls to a COM object from a NET managed code environment The ASPNET threading model is the Multiple Threaded Apartment (MTA) This will not interact reliably with STA components (the ActiveX connector provided with the ArcIMS setup was built as an STA component) To emphasize this issue heres a direct quote from the MSDN pages at Microsoft The ASPNET threading model is the Multiple Threaded Apartment (MTA) What this means is that components that you are using that were created for the Single Threaded Apartment (STA) will no longer perform or function reliably without taking some extra precautions in ASPNET This includes but is not limited to all COM components that have been created using Visual Basic 60 and earlier versions

To understand the issues better let us take a look at how NET deals with COM related issues The Common Language Runtime exposes COM objects through a proxy called the runtime callable wrapper (RCW) The RCWs primary function is to marshal calls between a NET client and COM object The RCW object is nothing but an object instantiated at runtime from class code contained in the Interop assembly

ESRI White Paper 21

Calling between managed and unmanaged components incurs a marshaling cost which can impede the performance of your pages When a managed client and unmanaged server are in the same apartment the Interop marshalling service handles all data marshalling However when client and server are initialized in different apartments COM marshalling is also required Therefore interoperability with COM from a NET client should take into consideration the threading model used

Figure Cross-apartment call between a NET client and COM object

As mentioned earlier ASPNET follows an MTA model by default You could use the default model to communicate with an STA COM component if there is not much of an overhead due to the cross-apartment marshalling Usually this is noticeable only when there are many calls across the boundary Another option would be to use the PageAspCompatMode property of the ASPNET client The ASPCompat=true attribute enables an STA thread pool to address performance with existing Visual Basic components on a per-page basis The runtime throws an exception if the compatibility tag is omitted and an STA component is referenced on the page If you convert the STA component to an assembly using Type Library Importer (a utility included with the NET SDK) the runtime does not detect that the component uses the STA model and does not throw an exception but your application can suffer from poor performance and possible deadlocks STA components cannot be used from NET Framework code modules (compiled NET assemblies) they can be used only from ASPNET pages

If you plan to use the ASPCOMPAT = TRUE page level directive for Example 1 remember to instantiate the COM object within the page_load event rather than constructing COM components during page construction time For example look at code examples A and B

Example A Example B ltPage Language = VB ASPCOMPAT = truegt

ltscript runat = servergt

private mapStates as new aimsMap()

private sub_load ()

ltPage Language = VB ASPCOMPAT = truegt

ltscript runat = servergt

private mapStates as aimsMap()

private sub_load ()

ESRI White Paper 22

end sub

mapStates = new aimsMap()

end sub

In example A the STA component would be instantiated at page construction time which is created from a thread that is not the STA thread that will run the page This will involve marshalling between MTA and STA threads during the construction of the page Example B shows the preferred mechanism to delay the process until later when the code executes under a STA thread It is best to construct any COM component and external resources when needed or in the Page_Load method

Also to create the object you can use either the New keyword or the CreateObject method The CreateObject method is typically used when you dont know the Program ID (ProgID) of the object you are going to create until run time (late binding) New is the recommended method for instantiating objects if you have access to the objects type library It is preferable to adopt the early binding model

Every scenario yields different performance characteristics so it is important to test adequately before deciding whether interoperability is the right choice for your application However in nearly all scenarios rewriting your COM components in managed code provides performance benefits

Summary The examples shown above provide adequate information to leverage the NET programming environment to build effective ArcIMS client applications The debugging features of a program like Visual StudioNET provide a variety of tools (break points trace etc) making the entire development experience considerably pain-free Use the debugger to understand the sequence in which calls are made One early exercise would be to look at the calling sequence of the various page related events such as page_init page_load and page_prerender Since the Web Forms code is compiled you should experience much better performance than with ASP pages that used code written in scripting languages like Javascript and VbScript

The powerful programming environment also means that you can now concentrate more on the logic of building large web applications as opposed to building simple page based asp applications Also look at the various caching mechanisms provided by ASPNET as these can be used to improve overall performance As always there are costs associated with most programming choices and this is all the more true in a web-programming environment For example consider the costs associated with using a web control as opposed to a HTML based control Use plain HTML controls instead of adopting web controls for simple items like label

ESRI White Paper 23

If you choose to use the ActiveX connector from within the NET environment make sure that you clearly understand the essentials of COM Interop and the various costs associated with marshalling The solutions outlined in this paper utilize existing ArcIMS services and should work with all versions of ArcIMS

Although all the development can be done without the use of an Integrated Development environment (IDE) like Visual StudioNET using such an environment provides convenient WYSIWYG features that can help in building and debugging the application If you do not have Visual StudioNET there are free IDEs available today that can also be used For example ASPNET Web Matrix is a community-supported easy-to-use WYSIWYG application development tool for ASPNET It can be installed via a quick 12 MB download from httpwwwaspnetwebmatrixdefaultaspx

ESRI White Paper 24

  • ArcIMS ndash An Introduction
  • What is NET
    • The NET Framework
      • The Common Language Runtime (CLR)
      • Managed Unmanaged and Unsafe code ndash Understandin
      • NET Framework Class Libraries
        • ASPNET and Web Forms
          • NET and ArcIMS
            • Example 1
            • Example 2
            • Example 3
              • Accessing a COM Server from a NET Client
              • Summary
Page 24: Consuming ArcIMS Image Services using .NET Client Web ... · Consuming ArcIMS Image Services using .NET Client Web Applications An ESRI White Paper Ł October 2002 ... The .NET framework

Choose the appropriate connection type based on HTTP or TCP connection For HTTP choose m_dsConnectType = ConnectionTypeInterNet and for For TCP select m_dsConnectType = ConnectionTypeIntraNet as shown in the code below

private ArcIMSDataSource getDataSource() m_ds = Session[datasource] as ArcIMSDataSource if ( m_ds == null ) m_ds = new ArcIMSDataSource() m_dsHost = localhost m_dsScheme = http m_dsPort = 80 m_dsAppServerPort = 5300 m_dsPath = servletcomesriesrimapEsrimap choose (comment uncomment) one of the following two statements to decide between TCP or HTTP type connection m_dsConnectType = ConnectionTypeIntraNet m_dsConnectType = ConnectionTypeInterNet SessionAdd(datasource m_ds) return m_ds

Accessing a COM Server from a NET Client With the introduction of the NET Framework and ASPNET COM at its basic level has not really changed Nevertheless there are a couple of issues to be aware of when making calls to a COM object from a NET managed code environment The ASPNET threading model is the Multiple Threaded Apartment (MTA) This will not interact reliably with STA components (the ActiveX connector provided with the ArcIMS setup was built as an STA component) To emphasize this issue heres a direct quote from the MSDN pages at Microsoft The ASPNET threading model is the Multiple Threaded Apartment (MTA) What this means is that components that you are using that were created for the Single Threaded Apartment (STA) will no longer perform or function reliably without taking some extra precautions in ASPNET This includes but is not limited to all COM components that have been created using Visual Basic 60 and earlier versions

To understand the issues better let us take a look at how NET deals with COM related issues The Common Language Runtime exposes COM objects through a proxy called the runtime callable wrapper (RCW) The RCWs primary function is to marshal calls between a NET client and COM object The RCW object is nothing but an object instantiated at runtime from class code contained in the Interop assembly

ESRI White Paper 21

Calling between managed and unmanaged components incurs a marshaling cost which can impede the performance of your pages When a managed client and unmanaged server are in the same apartment the Interop marshalling service handles all data marshalling However when client and server are initialized in different apartments COM marshalling is also required Therefore interoperability with COM from a NET client should take into consideration the threading model used

Figure Cross-apartment call between a NET client and COM object

As mentioned earlier ASPNET follows an MTA model by default You could use the default model to communicate with an STA COM component if there is not much of an overhead due to the cross-apartment marshalling Usually this is noticeable only when there are many calls across the boundary Another option would be to use the PageAspCompatMode property of the ASPNET client The ASPCompat=true attribute enables an STA thread pool to address performance with existing Visual Basic components on a per-page basis The runtime throws an exception if the compatibility tag is omitted and an STA component is referenced on the page If you convert the STA component to an assembly using Type Library Importer (a utility included with the NET SDK) the runtime does not detect that the component uses the STA model and does not throw an exception but your application can suffer from poor performance and possible deadlocks STA components cannot be used from NET Framework code modules (compiled NET assemblies) they can be used only from ASPNET pages

If you plan to use the ASPCOMPAT = TRUE page level directive for Example 1 remember to instantiate the COM object within the page_load event rather than constructing COM components during page construction time For example look at code examples A and B

Example A Example B ltPage Language = VB ASPCOMPAT = truegt

ltscript runat = servergt

private mapStates as new aimsMap()

private sub_load ()

ltPage Language = VB ASPCOMPAT = truegt

ltscript runat = servergt

private mapStates as aimsMap()

private sub_load ()

ESRI White Paper 22

end sub

mapStates = new aimsMap()

end sub

In example A the STA component would be instantiated at page construction time which is created from a thread that is not the STA thread that will run the page This will involve marshalling between MTA and STA threads during the construction of the page Example B shows the preferred mechanism to delay the process until later when the code executes under a STA thread It is best to construct any COM component and external resources when needed or in the Page_Load method

Also to create the object you can use either the New keyword or the CreateObject method The CreateObject method is typically used when you dont know the Program ID (ProgID) of the object you are going to create until run time (late binding) New is the recommended method for instantiating objects if you have access to the objects type library It is preferable to adopt the early binding model

Every scenario yields different performance characteristics so it is important to test adequately before deciding whether interoperability is the right choice for your application However in nearly all scenarios rewriting your COM components in managed code provides performance benefits

Summary The examples shown above provide adequate information to leverage the NET programming environment to build effective ArcIMS client applications The debugging features of a program like Visual StudioNET provide a variety of tools (break points trace etc) making the entire development experience considerably pain-free Use the debugger to understand the sequence in which calls are made One early exercise would be to look at the calling sequence of the various page related events such as page_init page_load and page_prerender Since the Web Forms code is compiled you should experience much better performance than with ASP pages that used code written in scripting languages like Javascript and VbScript

The powerful programming environment also means that you can now concentrate more on the logic of building large web applications as opposed to building simple page based asp applications Also look at the various caching mechanisms provided by ASPNET as these can be used to improve overall performance As always there are costs associated with most programming choices and this is all the more true in a web-programming environment For example consider the costs associated with using a web control as opposed to a HTML based control Use plain HTML controls instead of adopting web controls for simple items like label

ESRI White Paper 23

If you choose to use the ActiveX connector from within the NET environment make sure that you clearly understand the essentials of COM Interop and the various costs associated with marshalling The solutions outlined in this paper utilize existing ArcIMS services and should work with all versions of ArcIMS

Although all the development can be done without the use of an Integrated Development environment (IDE) like Visual StudioNET using such an environment provides convenient WYSIWYG features that can help in building and debugging the application If you do not have Visual StudioNET there are free IDEs available today that can also be used For example ASPNET Web Matrix is a community-supported easy-to-use WYSIWYG application development tool for ASPNET It can be installed via a quick 12 MB download from httpwwwaspnetwebmatrixdefaultaspx

ESRI White Paper 24

  • ArcIMS ndash An Introduction
  • What is NET
    • The NET Framework
      • The Common Language Runtime (CLR)
      • Managed Unmanaged and Unsafe code ndash Understandin
      • NET Framework Class Libraries
        • ASPNET and Web Forms
          • NET and ArcIMS
            • Example 1
            • Example 2
            • Example 3
              • Accessing a COM Server from a NET Client
              • Summary
Page 25: Consuming ArcIMS Image Services using .NET Client Web ... · Consuming ArcIMS Image Services using .NET Client Web Applications An ESRI White Paper Ł October 2002 ... The .NET framework

Calling between managed and unmanaged components incurs a marshaling cost which can impede the performance of your pages When a managed client and unmanaged server are in the same apartment the Interop marshalling service handles all data marshalling However when client and server are initialized in different apartments COM marshalling is also required Therefore interoperability with COM from a NET client should take into consideration the threading model used

Figure Cross-apartment call between a NET client and COM object

As mentioned earlier ASPNET follows an MTA model by default You could use the default model to communicate with an STA COM component if there is not much of an overhead due to the cross-apartment marshalling Usually this is noticeable only when there are many calls across the boundary Another option would be to use the PageAspCompatMode property of the ASPNET client The ASPCompat=true attribute enables an STA thread pool to address performance with existing Visual Basic components on a per-page basis The runtime throws an exception if the compatibility tag is omitted and an STA component is referenced on the page If you convert the STA component to an assembly using Type Library Importer (a utility included with the NET SDK) the runtime does not detect that the component uses the STA model and does not throw an exception but your application can suffer from poor performance and possible deadlocks STA components cannot be used from NET Framework code modules (compiled NET assemblies) they can be used only from ASPNET pages

If you plan to use the ASPCOMPAT = TRUE page level directive for Example 1 remember to instantiate the COM object within the page_load event rather than constructing COM components during page construction time For example look at code examples A and B

Example A Example B ltPage Language = VB ASPCOMPAT = truegt

ltscript runat = servergt

private mapStates as new aimsMap()

private sub_load ()

ltPage Language = VB ASPCOMPAT = truegt

ltscript runat = servergt

private mapStates as aimsMap()

private sub_load ()

ESRI White Paper 22

end sub

mapStates = new aimsMap()

end sub

In example A the STA component would be instantiated at page construction time which is created from a thread that is not the STA thread that will run the page This will involve marshalling between MTA and STA threads during the construction of the page Example B shows the preferred mechanism to delay the process until later when the code executes under a STA thread It is best to construct any COM component and external resources when needed or in the Page_Load method

Also to create the object you can use either the New keyword or the CreateObject method The CreateObject method is typically used when you dont know the Program ID (ProgID) of the object you are going to create until run time (late binding) New is the recommended method for instantiating objects if you have access to the objects type library It is preferable to adopt the early binding model

Every scenario yields different performance characteristics so it is important to test adequately before deciding whether interoperability is the right choice for your application However in nearly all scenarios rewriting your COM components in managed code provides performance benefits

Summary The examples shown above provide adequate information to leverage the NET programming environment to build effective ArcIMS client applications The debugging features of a program like Visual StudioNET provide a variety of tools (break points trace etc) making the entire development experience considerably pain-free Use the debugger to understand the sequence in which calls are made One early exercise would be to look at the calling sequence of the various page related events such as page_init page_load and page_prerender Since the Web Forms code is compiled you should experience much better performance than with ASP pages that used code written in scripting languages like Javascript and VbScript

The powerful programming environment also means that you can now concentrate more on the logic of building large web applications as opposed to building simple page based asp applications Also look at the various caching mechanisms provided by ASPNET as these can be used to improve overall performance As always there are costs associated with most programming choices and this is all the more true in a web-programming environment For example consider the costs associated with using a web control as opposed to a HTML based control Use plain HTML controls instead of adopting web controls for simple items like label

ESRI White Paper 23

If you choose to use the ActiveX connector from within the NET environment make sure that you clearly understand the essentials of COM Interop and the various costs associated with marshalling The solutions outlined in this paper utilize existing ArcIMS services and should work with all versions of ArcIMS

Although all the development can be done without the use of an Integrated Development environment (IDE) like Visual StudioNET using such an environment provides convenient WYSIWYG features that can help in building and debugging the application If you do not have Visual StudioNET there are free IDEs available today that can also be used For example ASPNET Web Matrix is a community-supported easy-to-use WYSIWYG application development tool for ASPNET It can be installed via a quick 12 MB download from httpwwwaspnetwebmatrixdefaultaspx

ESRI White Paper 24

  • ArcIMS ndash An Introduction
  • What is NET
    • The NET Framework
      • The Common Language Runtime (CLR)
      • Managed Unmanaged and Unsafe code ndash Understandin
      • NET Framework Class Libraries
        • ASPNET and Web Forms
          • NET and ArcIMS
            • Example 1
            • Example 2
            • Example 3
              • Accessing a COM Server from a NET Client
              • Summary
Page 26: Consuming ArcIMS Image Services using .NET Client Web ... · Consuming ArcIMS Image Services using .NET Client Web Applications An ESRI White Paper Ł October 2002 ... The .NET framework

end sub

mapStates = new aimsMap()

end sub

In example A the STA component would be instantiated at page construction time which is created from a thread that is not the STA thread that will run the page This will involve marshalling between MTA and STA threads during the construction of the page Example B shows the preferred mechanism to delay the process until later when the code executes under a STA thread It is best to construct any COM component and external resources when needed or in the Page_Load method

Also to create the object you can use either the New keyword or the CreateObject method The CreateObject method is typically used when you dont know the Program ID (ProgID) of the object you are going to create until run time (late binding) New is the recommended method for instantiating objects if you have access to the objects type library It is preferable to adopt the early binding model

Every scenario yields different performance characteristics so it is important to test adequately before deciding whether interoperability is the right choice for your application However in nearly all scenarios rewriting your COM components in managed code provides performance benefits

Summary The examples shown above provide adequate information to leverage the NET programming environment to build effective ArcIMS client applications The debugging features of a program like Visual StudioNET provide a variety of tools (break points trace etc) making the entire development experience considerably pain-free Use the debugger to understand the sequence in which calls are made One early exercise would be to look at the calling sequence of the various page related events such as page_init page_load and page_prerender Since the Web Forms code is compiled you should experience much better performance than with ASP pages that used code written in scripting languages like Javascript and VbScript

The powerful programming environment also means that you can now concentrate more on the logic of building large web applications as opposed to building simple page based asp applications Also look at the various caching mechanisms provided by ASPNET as these can be used to improve overall performance As always there are costs associated with most programming choices and this is all the more true in a web-programming environment For example consider the costs associated with using a web control as opposed to a HTML based control Use plain HTML controls instead of adopting web controls for simple items like label

ESRI White Paper 23

If you choose to use the ActiveX connector from within the NET environment make sure that you clearly understand the essentials of COM Interop and the various costs associated with marshalling The solutions outlined in this paper utilize existing ArcIMS services and should work with all versions of ArcIMS

Although all the development can be done without the use of an Integrated Development environment (IDE) like Visual StudioNET using such an environment provides convenient WYSIWYG features that can help in building and debugging the application If you do not have Visual StudioNET there are free IDEs available today that can also be used For example ASPNET Web Matrix is a community-supported easy-to-use WYSIWYG application development tool for ASPNET It can be installed via a quick 12 MB download from httpwwwaspnetwebmatrixdefaultaspx

ESRI White Paper 24

  • ArcIMS ndash An Introduction
  • What is NET
    • The NET Framework
      • The Common Language Runtime (CLR)
      • Managed Unmanaged and Unsafe code ndash Understandin
      • NET Framework Class Libraries
        • ASPNET and Web Forms
          • NET and ArcIMS
            • Example 1
            • Example 2
            • Example 3
              • Accessing a COM Server from a NET Client
              • Summary
Page 27: Consuming ArcIMS Image Services using .NET Client Web ... · Consuming ArcIMS Image Services using .NET Client Web Applications An ESRI White Paper Ł October 2002 ... The .NET framework

If you choose to use the ActiveX connector from within the NET environment make sure that you clearly understand the essentials of COM Interop and the various costs associated with marshalling The solutions outlined in this paper utilize existing ArcIMS services and should work with all versions of ArcIMS

Although all the development can be done without the use of an Integrated Development environment (IDE) like Visual StudioNET using such an environment provides convenient WYSIWYG features that can help in building and debugging the application If you do not have Visual StudioNET there are free IDEs available today that can also be used For example ASPNET Web Matrix is a community-supported easy-to-use WYSIWYG application development tool for ASPNET It can be installed via a quick 12 MB download from httpwwwaspnetwebmatrixdefaultaspx

ESRI White Paper 24

  • ArcIMS ndash An Introduction
  • What is NET
    • The NET Framework
      • The Common Language Runtime (CLR)
      • Managed Unmanaged and Unsafe code ndash Understandin
      • NET Framework Class Libraries
        • ASPNET and Web Forms
          • NET and ArcIMS
            • Example 1
            • Example 2
            • Example 3
              • Accessing a COM Server from a NET Client
              • Summary