Tag Archives: arcobjects

How to query ArcIMS services with ArcObjects

IIMSServiceDescription imsServiceDescription = new IMSServiceNameClass();
imsServiceDescription.URL = @"you server here";                 
imsServiceDescription.Name = "catalog";

IIMSAxlRequest axlRequest = (IIMSAxlRequest)imsServiceDescription;
String result = axlRequest.SendAxlRequest("<GETCLIENTSERVICES/>", false, null, false, true);

IXmlPropertySet2 xmlProps = new XmlPropertySetClass();
xmlProps.SetXml(result);
object val = new object();
xmlProps.GetAttribute("RESPONSE/SERVICES/SERVICE", "NAME", out val);

object[] vals = (object[]) val;

for (int i = 0; i &lt; vals.Length; i++)
{
     Debug.WriteLine(vals[i].ToString());
}
Advertisements

Issues with persisting changes to the scale in PageLayout (LayoutView) using ArcObjects

Scenario

Now and again you may find yourself developing an application outside of ArcMap i.e. essentially an ArcEngine app.

I was developing an application that accessed an mxd via the IMapDocument interface and tried to persist a change in the map scale in the Layout View.  Every time I changed the scale and saved the mxd – however the original scale would not change and the programmatic new scale was ignored!

This was very frustrating indeed, I was sure that there must be a way to persist this change as it’s not exactly NASA missile launch code – I’m just trying to change a scale damn it!

ArcMap Scale

Highlight of the scale control in the layoutview of ArcMap

Solution

Anyway, it so happens that there is a fix, but it’s kind of unusual and not exactly intuitive or obvious to the developer coming at this problem cold.

Firstly we have to make use of some win32 API calls and most importantly to call IActiveView.Activate and pass our call to GetDesktopWindow().  This does the trick and is absolutely essential if you want to get this kind of change persisted.  Take a look at the code below to see how it’s done:

  
[DllImport("User32.dll")]
public static extern int GetDesktopWindow();

private void ChangeMyScale()
{
    IMapDocument MapDoc;
    mapDoc = new MapDocumentClass();
    mapDoc.Open(@"C:\Foo\Bar.mxd",null);
    IPageLayout pageLayout = mapDoc.PageLayout;
    IActiveView activeView = (IActiveView)pageLayout;
    activeView = (IActiveView) mapDoc.PageLayout;
    activeView.Activate(GetDesktopWindow()); //Key line!!
    mapDoc.ActiveView.FocusMap.MapScale = 10000; //Now we can change the scale!!
    activeView.Refresh();

    MessageBox.Show(@"We have an mxd called:" + mapDoc.DocumentFilename +
    "\nExtent: 1 to " + mapDoc.ActiveView.FocusMap.MapScale);

    mapDoc.Save(true, false)
    mapDoc.Close();
}

Other things to bear in mind, code such as:

MapDoc.SetActiveView((IActiveView)pageLayout)

only sets the view for the application as PageLayout, in order to get control of the specified window you have to use the Activate method:

<pre>activeView.Activate(GetDesktopWindow())

When working with the IActiveView interface on a MapDocument object, you should always first call IActiveView::Activate() in order to properly initialize the display of the PageLayout or Map object.

The MxDocument, MapServer objects, MapControl and PageLayoutControl all initialise display objects automatically after opening an MXD, but MapDocument DOES NOT DO THIS, so you should call Activate() before working with any other members of IActiveView.

So to summarise, if your application has a user interface, you should call Activate() with the hWnd of the application’s client area.  If your application runs in the background and has no windows, you retrieve a valid hWnd from the GDI GetDesktopWindow() function, part of the Win32 API.

Conclusion

I am hopeful that ESRI will change this so that you don’t have to, what I view totally unnecessary calls to the Windows API etc.  Maybe it will be fixed properly in version 10 or some other update to that, but I wouldn’t hold your breath!

Anyway I hope it’s useful to you and stops you burning lots of valuable dev time!

ESRI Snippet: Adding a graphic to a map

Really handy sometimes for debugging to make sure you are dealing with the correct geometry:

Public Sub AddGraphicToMap(ByVal map As IMap, ByVal geometry As IGeometry)

 Dim graphicsContainer As IGraphicsContainer
 Set graphicsContainer = map

 Dim element As IElement
 Set element = Nothing

 Dim rgbColor As IRgbColor
 Set rgbColor = New rgbColor
 With rgbColor
 .Red = 111
 .Green = 111
 .Blue = 111
 .UseWindowsDithering = True
 End With

 Dim simpleFillSymbol As ISimpleFillSymbol
 Set simpleFillSymbol = New simpleFillSymbol

 simpleFillSymbol.Color = rgbColor
 simpleFillSymbol.Style = esriSFSForwardDiagonal

 Dim fillShapeElement As IFillShapeElement
 Set fillShapeElement = New PolygonElement

 fillShapeElement.Symbol = simpleFillSymbol
 Set element = fillShapeElement

 If Not (element Is Nothing) Then
 element.geometry = geometry
 graphicsContainer.AddElement element, 0
 End If

End Sub

ESRI Code Snippet: Find Layer by Name

A handy code snippet from Neil Clemmons who is a prolific trouble shooter on the ESRI forums.  Sometimes it’s handy to have a bit of VBA code to find a layer by name and this code does the job very well.  Of course you can apply the same logic in any language and application context you see fit.

Public Function GetLayerByFeatureClass(vMap As Variant, sFeatureClassName As String, Optional bMessages As Boolean = True) As ILayer
     Dim pApplication As IApplication
     Dim pMxDocument As IMxDocument
     Dim pCompositeLayer As ICompositeLayer
     Dim pMap As IMap
     Dim l As Long
     Dim m As Long
     
     On Error GoTo ErrorHandler
     
     ' Get map reference from vMap parameter.
     If TypeOf vMap Is IMxApplication Then
          Set pApplication = vMap
          Set pMxDocument = pApplication.Document
          Set pMap = pMxDocument.FocusMap
     ElseIf TypeOf vMap Is IMxDocument Then
          Set pMxDocument = vMap
          Set pMap = pMxDocument.FocusMap
     ElseIf TypeOf vMap Is IMap Then
          Set pMap = vMap
     Else
          If bMessages Then MsgBox "vMap parameter does not implement an interface supported by this function.", vbOKOnly, "GetLayerByFeatureClass()"
          
          Exit Function
     End If
     
     ' Process each layer in the map.
     For l = 0 To pMap.LayerCount - 1
          Set GetLayerByFeatureClass = LayerByFeatureClass(pMap.Layer(l), sFeatureClassName, bMessages)
          If Not GetLayerByFeatureClass Is Nothing Then Exit Function
     Next l
     
     ' Give layer not found message.
     If bMessages Then MsgBox "The layer '" & sFeatureClassName & "' could not be found in the map.", vbOKOnly, "GetLayerByFeatureClass()"
Exit Function
ErrorHandler:
     If bMessages Then ErrorMessage "modAOUtilities:GetLayerByFeatureClass()"
End Function

' Written by: Neil Clemmons
' Date Created: 12/26/2002
' Date Modified:
' Description:  Helper function for GetLayerByFeatureClass().  Uses recursion to find layers that may be inside nested
'               group layers.  If this function returns a value other than Nothing, the layer has been found and
'               the search will stop.  Otherwise, the search will continue until all layers have been processed.
Private Function LayerByFeatureClass(pLayer As ILayer, sName As String, bMessages As Boolean) As ILayer
     Dim pDataset As IDataset
     Dim pReturnLayer As ILayer
     Dim pFeatureLayer As IFeatureLayer
     Dim pCompositeLayer As ICompositeLayer
     Dim l As Long
     
     On Error GoTo ErrorHandler
     
     ' If layer is a feature layer, get it's underlying dataset.
     If TypeOf pLayer Is IFeatureLayer Then
          Set pFeatureLayer = pLayer
          Set pDataset = pFeatureLayer.FeatureClass
          
          ' Set return layer and exit if this layer is the layer being sought.
          If UCase$(pDataset.Name) = UCase$(sName) Then
               Set LayerByFeatureClass = pLayer
               Exit Function
          End If
     End If
     
     ' Exit if layer is not a group layer.  Not setting return value will cause search to continue.
     If Not TypeOf pLayer Is IGroupLayer Then Exit Function
     
     ' Process each layer in the group layer.
     Set pCompositeLayer = pLayer
     For l = 0 To pCompositeLayer.Count - 1
          ' Use recursion to traverse nested group layers.
          Set pReturnLayer = LayerByFeatureClass(pCompositeLayer.Layer(l), sName, bMessages)
          
          ' If layer was found, set return value and exit.
          If Not pReturnLayer Is Nothing Then
               Set LayerByFeatureClass = pReturnLayer
               Exit Function
          End If
     Next l
Exit Function
ErrorHandler:
     If bMessages Then ErrorMessage "modAOUtilitiesLayerByName()"
End Function

Connecting to AGS to get IMap

Want to know how connect to your AGS server and get a handle on IMap of your published AGS map service.  The following code should give you the basic bare bones code that you need in order to do that – note stuff in “” should be applicable to your environment.

BTW – I find that getting a handle on IMap is useful in a great many ArcObjects based programming – so just thought I should post.

private String _host = "myServerName";
private String _username = "joebloggs";
private String _password = "password";
private String _domain = "myDomainName";
public void connectToServer()throws IOException
    {
        try {
            IServerContext serverContext = null;
            IServerConnection serverConnection = new ServerConnection();
            ServerInitializer serverInitializer = null;
            IServerObjectManager som = null;

            serverInitializer = new ServerInitializer();
            serverInitializer.initializeServer(_domain, _username, _password);
            serverConnection.connect(_host);
            som = serverConnection.getServerObjectManager();
            serverContext = som.createServerContext("publishedMapServiceName", "MapServer");

            IMapServer mapServer = (IMapServer) serverContext.getServerObject();
            IMapServerObjects mapServObjs = (IMapServerObjects) mapServer;

            IMap map = mapServObjs.getMap(mapServer.getDefaultMapName());

            serverContext.releaseContext();

        } catch (UnknownHostException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (AutomationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }