How to add a MapServer as a layer in ArcMap


The code below demonstrates how to connect to a GIS Server and add a MapServer as a layer in ArcMap

How to use

  1. Paste the code into your VBA Application.
  2. Change the name of the GIS server to connect to and the MapServer name to open.
  3. Call AddMapServerLayer.
[VBA]
Public Sub AddMapServerLayer()
    
    Dim pMxDoc As IMxDocument
    Dim pMap As IMap
    Dim pAV As IActiveView
    Dim pAGSServerConnectionFactory As IAGSServerConnectionFactory
    Dim pProps As IPropertySet2
    Dim pAGSConnection As IAGSServerConnection
    Dim pEnumSOName As IAGSEnumServerObjectName
    Dim pSOName As IAGSServerObjectName
    Dim pName As IName
    Dim pMapServer As IMapServer
    Dim pMSLayer As IMapServerLayer
    
    ' connect to the GIS server
    Set pAGSServerConnectionFactory = New AGSServerConnectionFactory
    Set pProps = New PropertySet
    pProps.SetProperty "machine", "doug"
    Set pAGSConnection = pAGSServerConnectionFactory.Open(pProps, 0)
    
    'Get the MapServer
    Set pEnumSOName = pAGSConnection.ServerObjectNames
    Set pSOName = pEnumSOName.Next
    Do Until pSOName Is Nothing
        If pSOName.Name = "GDBRaster" Then Exit Do
        Set pSOName = pEnumSOName.Next
    Loop
    
    If pSOName Is Nothing Then Exit Sub
    
    Set pName = pSOName
    Set pMapServer = pName.Open
    
    'Create new layer
    Set pMSLayer = New MapServerLayer
    pMSLayer.ServerConnect pSOName, pMapServer.DefaultMapName
    
    'Add layer to map
    Set pMxDoc = ThisDocument
    Set pMap = pMxDoc.FocusMap
    Set pAV = pMap
    pMap.AddLayer pMSLayer
    pAV.Refresh
End Sub