1 gis server 简单的说,gis server是一个管理server object manager 和 container的服务器。
2 server object manager 是运行在gis server上的一个服务,管理在server object container 中运行的server object。
3 server object container 是一个进程,可以运行在一台或多台机器上,server object 就运行在这个进程之中。
4 server object 分为mapserver和geocodeserver两种,mapserver主要是用来发布地图,geocodeserver是用来进行地理定位。
5 pooled server object 池式的,池式的server object 提前构造,实例能被多个应用程序对话共享,返回池中的实例必须复原,进行stateless(无状态的)使用。
6
non-pooled server object 非池式的,server object
仅能为一个应用程序对话所使用,使用时,创建一个server object的实例,使用完毕后,server object返回gis
server,实例销毁。对 gis server 进行 stateful(状态)使用。
7 arcgis server有3类编程接口:
server api:server api是arcobjects的部分类库,用来连接gis server,使用server object。
.net web controls
java web controls
web controls 是分别针对不同服务器程序开发平台而言。
这些天在看这个东西,以前没学过AO,现在看的头大了,痛苦。
以下zz
服
务器上下文( Server
Context):一个服务器上下文是运行一组服务器对象的服务器上的保留空间。可以将服务器上下文想象成一个进程,由运行服务器对象的服务器管理。服务
器上下文提供了一种在相同空间和“进程”中创建对象的方法,并作为一个运行的服务器对象,在同一个服务器上下文中工作的对象合作更好。
1) 连接到GIS Server
服
务器API 提供GISServerConnection 对象完成与GIS Server 的连接。GISServerConnec2tion
提供一个接口IGISServerConnection ,该接口拥有一个用于连接GIS Server 的Connect 方法。
IGISServerConnection connection = new IGISServerConnection () ;
connection. Connect (winxp - sp2) ;
Web 控件由一个ServerConnection 对象完成对GIS Server 的连接。
ESRI.
ArcGIS. Server . WebControls. ServerConnection connection = new ESRI.
ArcGIS. Server . WebControls.ServerConnection () ;
connection. Host = "winxp - sp2" ;
connection. Connect () ;
客户端应用连接到服务器时,必须确保运行客户端的操作系统以ArcGIS Server 用户组或者ArcGIS Server 管理员组的成员身份登陆,否则连接返回错误。
2) 获取服务器对象
服务器对象由SOM 管理,并运行于服务器
上下文中。通过服务器上下文获取服务器对象并
在任务完成后释放服务器上下文。
IServerObjectManager m_pSOM = connection. ServerObjectManager ;
IServerContext m_pServerContext = m_pSOM. CreateServerContext (" testMap" , "MapServer" ) ;
IMapServer pMapServer = m_pServerContext . ServerObject as IMapServer ;
m_pServerContext . ReleaseContext () ;
3) 使用服务器对象
通过服务器对象,可以引用其他相关细粒度的ArcObject s。以下代码示例获取服务器对象所提供的地图资源的第一个图层(矢量图层) 中所有要素的个数:
IMapServerObject s pMapServerObject s = ( IMapServerObject s) pMapServer ;
IMap pMap = pMapServerObject s. get_Map (pMapServer .
DefaultMapName) ;
IFeatureLayer p FLayer = ( IFeatureLayer) pMap. get_Layer(0) ;
IFeatureClass p FeatureClass = p FLayer . FeatureClass ;
int i = p FeatureClass. FeatureCount (null) ;
——————————————————————————————————————————————
Reduce ArcGIS Server Boilerplate Code By Implementing IDisposable
四月 19, 2009When programming with ArcObjects and ArcGIS Server, code often follows a common pattern of connecting to ArcGIS Server, getting hold of an IServerContext, doing some work, and releasing the context. This leads to a lot of unnecessarily repeated setup and teardown code, usually taking a form similar to the following example:
IServerContext context = null;
try
{
IGISServerConnection conn = new GISServerConnectionClass()
as IGISServerConnection;
// Connect as ASPNET or NETWORK SERVICE.
// Get optional host setting from web.config,
// or use localhost if not found.
string host = ConfigurationManager.AppSettings["AGSHost"];
if (String.IsNullOrEmpty(host))
{
host = "localhost";
}
// Make connection
conn.Connect(host);
IServerObjectManager som = conn.ServerObjectManager;
context = som.CreateServerContext("MyServer", "MapServer");
// Do some stuff with the server context
}
finally
{
if (context != null)
{
context.ReleaseContext();
}
}
In this example, there is a lot of boilerplate happening just to get to the server context and do something interesting. Seeing this kind of code repeated throughout an ArcGIS Server project made me a little queasy as it violates the DRY Principle, so that got me thinking about how to eliminate it. [more]
I decided to create a wrapper class that handles making the connection and implements IServerContext and IDisposable. Inspiration for this idea comes from the .NET SqlConnection class, which also implements IDisposable and can therefore be instantiated inside of a using block to automatically close the connection and release any resources when the using block goes out of scope. (See this David Hayden post for a basic discussion of why this is a good thing.) Proper implementation of IDisposable is known as the Dispose Pattern and is documented both here and in Cwalina and Adams excellent Framework Design Guidelines.
With this new class, we can reduce the boilerplate code block to the following:
using (ArcGisServerContext context = new ArcGisServerContext("MyServer",
ArcGisServiceType.MapServer))
{
// Do some stuff with the server context
}
Notice also the use of an Enum to indicate the server type, thus eliminating one of the error prone hard coded strings as well. (In a real application, I would also retrieve the value “MyServer” from a config or resource file.) The Enum is defined like so:
public enum ArcGisServiceType
{
MapServer,
GeocodeServer,
GlobeServer,
GPServer,
GeoDataServer,
GeometryServer,
ImageServer,
}
and the ArcGISServerContext class is implemented as follows:
using System;
using System.Configuration;
using ESRI.ArcGIS.Server;
public class ArcGisServerContext : IServerContext, IDisposable
{
#region Fields
private IServerContext serverContext;
#endregion
#region Constructors()
// Here you can add overloaded constructors to take additional
// arguments such as login credentials - Or you could alter the
// constructor to use an ArcGIS Server Identity from web.config.
// This example just connects as the current user, which will be
// ASPNET or NETWORK SERVICE if running under IIS on Wind XP or 2003.
public ArcGisServerContext(string serviceName,
ArcGisServiceType serviceType)
{
IGISServerConnection conn = new GISServerConnectionClass()
as IGISServerConnection;
// Get optional host setting from web.config,
// or use localhost if not found.
string host = ConfigurationManager.AppSettings["AGSHost"];
if (String.IsNullOrEmpty(host))
{
host = "localhost";
}
// Make connection and cache IServerContext
conn.Connect(host);
IServerObjectManager som = conn.ServerObjectManager;
serverContext = som.CreateServerContext(serviceName,
serviceType.ToString());
}
#endregion
#region IServerContext Implementation
// These methods just pass through to the cached server context
public object CreateObject(string clsid)
{
return serverContext.CreateObject(clsid);
}
public object GetObject(string name)
{
return serverContext.GetObject(name);
}
public object LoadObject(string str)
{
return serverContext.LoadObject(str);
}
public void ReleaseContext()
{
serverContext.ReleaseContext();
}
public void Remove(string name)
{
serverContext.Remove(name);
}
public void RemoveAll()
{
serverContext.RemoveAll();
}
public string SaveObject(object obj)
{
return serverContext.SaveObject(obj);
}
public IServerObject ServerObject
{
get { return serverContext.ServerObject; }
}
public void SetObject(string name, object obj)
{
serverContext.SetObject(name, obj);
}
#endregion
#region IDisposable Implementation
// Implementation of the Dispose Pattern
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
// Release the server context
if (disposing)
{
if (serverContext != null)
{
serverContext.ReleaseContext();
}
}
}
#endregion
}
It’s really pretty simple, and it sure is nice not to have to copy / paste or keep re-typing the same boilerplate code over and over.
Hope this helps!
——————————————————————————————————————————
WCF IGISServerConnection连接GIS server 问题
这段时间在写WCF,遇到一个很奇怪的问题,将WCF发布到IIS上后 IGISServerConnection.connet时总是不能连接。具体错误如下:
在 DCIPLServiceClient.ff()
很奇怪 ,用vs直接运行时能连接上的,不会报错。期间各种网上说的方法都试过,还是不成功。后来改用ADF来连接,不再报错。
To make use of ArcObjects via ArcGIS Server in your application, you must connect directly to the GIS server, which requires network access to the Server Object Manager (SOM).
ArcGIS Server Connection objects
You can connect to a GIS Server using the ArcGIS Server library (ESRI.ArcGIS.Server) or the ArcGIS Connection library (ESRI.ArcGIS.ADF.Connection ).
The Server library connects to the GIS server through the GISServerConnection object. The GISServerConnection object supports a single interface (in addition to IUnknown): IGISServerConnection.IGISServerConnection has a Connect method that connects the application to the GIS server. The GISServerConnection object provides connections to the GIS server and access to the ServerObjectManagerand ServerObjectAdmin objects. The identity of the connecting user is not explicitly defined. Instead, the identity of the application is used.
The GISServerConnectionClass is a .NET generated wrapper for the GISServerConnection COM object.
ESRI.ArcGIS.Server.GISServerConnectionClass gisconnection; gisconnection = new ESRI.ArcGIS.Server.GISServerConnectionClass(); gisconnection.Connect("localhost"); ESRI.ArcGIS.Server.IServerObjectManager SOM = gisconnection.ServerObjectManager;
The Connection library is a native .NET assembly with the same connection capabilities as the Server library, plus some additional management options. In most cases, you should use the Connection library to connect to ArcGIS Server. It connects to the GIS server through the AGSServerConnection class in the ESRI.ArcGIS.ADF.Connection assembly. The Connection library also contains a ConnectionManager class to manage fail-over and round-robin capabilities within the client. See the section titled Using the Connection Manager for more information.
ESRI.ArcGIS.ADF.Identity identity = new ESRI.ArcGIS.ADF.Identity("user", "passwd", "domain"); ESRI.ArcGIS.ADF.Connection.AGS.AGSServerConnection agsconnection; agsconnection = new ESRI.ArcGIS.ADF.Connection.AGS.AGSServerConnection("hostname", identity); agsconnection.Connect(); IServerObjectManager SOM = agsconnection.ServerObjectManager;
Dim identity As ESRI.ArcGIS.ADF.Identity = New ESRI.ArcGIS.ADF.Identity("user", "passwd", "domain") Dim ags_onnection As ESRI.ArcGIS.ADF.Connection.AGS.AGSServerConnection agsconnection = New ESRI.ArcGIS.ADF.Connection.AGS.AGSServerConnection("hostname", identity) agsconnection.Connect Dim SOM As IServerObjectManager = agsconnection.ServerObjectManager
Connecting to the GIS Server: Security
For a client application to connect to ArcGIS Server, the application must be running as an operating system user that is a member of one of the following two operating system user groups defined on the ArcGIS server machines: the ArcGIS Server users group (agsusers) or ArcGIS Server administrators group (agsadmin). If the user the application is running as is not a member of either of those groups, then Connect will return an error.
In addition to the Connect method, the IGISServerConnection interface has two properties: ServerObjectManager and ServerObjectAdmin. If the application is running as a user in the users or administrators group, the application can access the ServerObjectManager property, which returns an IServerObjectManager interface. The IServerObjectManager interface provides methods for accessing and creating objects within the server for use by applications.
To access the ServerObjectAdmin property, the application must be running as a user who is a member of the administrators group. If the connected user is not a member of this group, attempts to access the ServerObjectAdmin property will fail. The ServerObjectAdmin property returns the IServerObjectAdmin interface, which provides methods for administering the various aspects of the server, such as server object configurations and server machines. Unless you are writing a GIS server administration application, your application does not need to make use of the IServerObjectAdmin interface.
The ServerObjectManager object provides methods for getting information about the GIS server and for creating server contexts for use by an application.
The ServerObjectAdmin object provides methods for administrating the GIS server and its server objects.
When connecting to the server using the native .NET connection object from a Web application or Web service, you must also think about impersonation. Your Web application or Web service must connect to the GIS server as a user in the agsusers group. The identity of the process or thread in determines the account you used to access the GIS Server. Process identity is associated with the user account under which a process is running. For ASP.NET Web applications or Web services you can impersonate a user at runtime by adding the identity tag to the web.config file and defining the appropriate attributes.
<identity impersonate="true" userName="mydomain\myuser" password="mypassword" />If you do not use impersonation in an ASP.NET application, then it will attempt to connect to the GIS server using the identity of the ASP.NET worker process, which may be ASPNET or NETWORK SERVICE, depending on the platform and machine settings.
Thread level impersonation is provided via the Connection library discussed earlier. An Identity object is created with account credentials of a user in the agsusers group on the GIS Server. When the AGSServerConnection is instantiated, it is provided the Identity object as a constructor parameter. The identity is used for the duration of the connection, which may involve concurrent access from multiple threads in the same process. The following code illustrates how a multi-threaded application creates concurrent connections to one or more GIS Servers using different identities:
[C#]
public partial class _Default : System.Web.UI.Page { private UserThread m_thread; protected void Button1_Click(object sender, EventArgs e) { m_thread = new UserThread(); Thread t = new Thread(new ThreadStart(m_thread.Connection1)); t.Start(); Thread t2 = new Thread(new ThreadStart(m_thread.Connection2)); t2.Start(); } } public class UserThread { public void Connection1() { ESRI.ArcGIS.ADF.Identity id = new ESRI.ArcGIS.ADF.Identity("user1", "pass1", "domain1"); ESRI.ArcGIS.ADF.Connection.AGS.AGSServerConnection agsconn; agsconn = new ESRI.ArcGIS.ADF.Connection.AGS.AGSServerConnection("server1", id); agsconn.Connect(); if (!agsconn.IsConnected) { agsconn.Dispose(); return; } ESRI.ArcGIS.Server.IServerObjectManager som = agsconn.ServerObjectManager; string servertype = "MapServer"; string serverobjectname = "Canada"; ESRI.ArcGIS.Server.IServerContext servercontext = som.CreateServerContext(serverobjectname, servertype); IMapServer ms = (IMapServer) servercontext.ServerObject; System.Threading.Thread.Sleep(10000); servercontext.ReleaseContext(); agsconn.Dispose(); } public void Connection2() { ESRI.ArcGIS.ADF.Identity id = new ESRI.ArcGIS.ADF.Identity("user2", "pass2", "domain2"); ESRI.ArcGIS.ADF.Connection.AGS.AGSServerConnection agsconn; agsconn = new ESRI.ArcGIS.ADF.Connection.AGS.AGSServerConnection("server2", id); agsconn.Connect(); if (!agsconn.IsConnected) { agsconn.Dispose(); return; } ESRI.ArcGIS.Server.IServerObjectManager som = agsconn.ServerObjectManager; string servertype = "MapServer"; string serverobjectname = "USA"; ESRI.ArcGIS.Server.IServerContext servercontext = som.CreateServerContext(serverobjectname, servertype); IMapServer ms = (IMapServer)servercontext.ServerObject; servercontext.ReleaseContext(); agsconn.Dispose(); } }
代码中有两个数据表:mapinfo(存储地图信息,key:地图GUID),LayerInfo(存储图层信息,包括其在SDE中的名称,以及最主要的其属于哪个地图的地图GUID),代码中的MapGUID即为地图GUID。
一下为其全部代码:
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using ESRI.ArcGIS.Server.WebControls;
using ESRI.ArcGIS.Server;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.ADF.Web.Display.Symbol;
using ESRI.ArcGIS.Display;
using ESRI.ArcGIS.DataSourcesRaster;
using System.IO;
using ESRI.ArcGIS.esriSystem;
using System.Drawing;
public partial class ServerManager : System.Web.UI.Page
{
string HostName = "zhangye";
string MapServerUserName = "ArcGISSOM";
string MapserverPass = "123456";
string MxdPah = @"F:\BaseData";
private static string connectionString = "server=172.39.8.215;uid=sa;pwd=sa;database=gis_data";
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["MapGUID"] == null || Request.QueryString["MapGUID"] == "")
{
Response.Write("创建失败");
return;
}
string MapName = Request.QueryString["MapGUID"];
if (isExistService(MapName))
{
Response.Write("创建成功");
return;
}
if (isExistMxd(MxdPah, MapName))
{
string MxdFullPath = MxdPah + "\\" + MapName + ".mxd";
CreateServices(MxdFullPath, MapName);
Response.Write("创建成功");
return;
}
else
{
if (CreateMxd(MxdPah, MapName))
{
string MxdFullPath = MxdPah + "\\" + MapName + ".mxd";
CreateServices(MxdFullPath, MapName);
Response.Write("创建成功");
return;
}
}
}
private DataTable GetMapLayersList(string MapGUID)
{
DataSet pDs = SqlHelper.ExecuteDataset(connectionString,
CommandType.Text, "select * from LayerInfo where MapID='"+MapGUID+"'");
DataTable dt = pDs.Tables[0];
return dt;
}
#region 创建服务、地图文档以及服务上下文
#region 创建地图服务
private bool CreateServices(string MapPath, string ServerName)
{
IGISServerConnection pGISServerConnection;
pGISServerConnection = new GISServerConnectionClass();
pGISServerConnection.Connect(HostName);
IServerObjectAdmin pServerObjectAdmin;
pServerObjectAdmin = pGISServerConnection.ServerObjectAdmin;
IServerObjectConfiguration2 configuration = (IServerObjectConfiguration2)pServerObjectAdmin.CreateConfiguration();
configuration.Name = ServerName;//发布Service的名称,必填
configuration.TypeName = "MapServer";//发布服务的类型,如:MapServer,GeocodeServer
IPropertySet props = configuration.Properties;
props.SetProperty("FilePath", MapPath);//设置MXD的路径
#region 一下的property并非必须,只要一个filepath就可以发布
props.SetProperty("OutputDir", "c:\\arcgisserver\\arcgisoutput");//图片的输出目录
props.SetProperty("VirtualOutPutDir", "http://zhangye/arcgisoutput");//图片输出的虚拟路径
props.SetProperty("SupportedImageReturnTypes", "URL");//支持的图片类型
props.SetProperty("MaxImageHeight", "2048");//图片的最大高度
props.SetProperty("MaxRecordCount", "500");//返回记录的最大条数
props.SetProperty("MaxBufferCount", "100");//缓冲区分析的最大数目
props.SetProperty("MaxImageWidth", "2048");//图片的最大宽度
props.SetProperty("IsCached", "false");//是否切片
props.SetProperty("CacheOnDemand", "false");//是否主动切片
props.SetProperty("IgnoreCache", "false");//是否忽略切片
props.SetProperty("ClientCachingAllowed", "true");//是否允许客户端缓冲
props.SetProperty("CacheDir", "c:\\arcgisserver\\arcgiscache\\NewService");//切片的输出路径
props.SetProperty("SOMCacheDir", "c:\\arcgisserver\\arcgiscache");//som的切片输出路径
//configuration.Description = "NewService";//Service的描述
configuration.IsolationLevel =
esriServerIsolationLevel.esriServerIsolationHigh;//或者
esriServerIsolationLow,esriServerIsolationAny
configuration.IsPooled = true;//是否池化
configuration.MaxInstances = 2;//最多的实例数
configuration.MinInstances = 1;//最少的实例数
////设置刷新
IPropertySet recycleProp = configuration.RecycleProperties;
recycleProp.SetProperty("StartTime", "00:00");//刷新开始时间
recycleProp.SetProperty("Interval", "3600");//刷新间隔
////设置是否开启REST服务
IPropertySet infoProp = configuration.Info;
infoProp.SetProperty("WebEnabled", "true");//是否提供REST服务
infoProp.SetProperty("WebCapabilities", "Map,Query,Data");//提供何种服务
//configuration.StartupType = esriStartupType.esriSTAutomatic;//或者esriSTManual
//configuration.UsageTimeout = 120;//客户端占用一个服务的最长时间
//configuration.WaitTimeout = 120;//客户端申请一个服务的最长等待时间
#endregion
//添加服务到Server
pServerObjectAdmin.AddConfiguration(configuration);
//启动服务
pServerObjectAdmin.StartConfiguration(ServerName, "MapServer");
return true;
}
#endregion
private bool CreateMxd(string MxdPath, string MxdName)
{
IMapDocument pMapDocument = CreateObject("esriCarto.MapDocument") as IMapDocument;
if (MxdPath.Substring(MxdPath.Length - 1) != @"\")
MxdPath += @"\";
pMapDocument.New(MxdPath + MxdName + ".mxd");
AddLayerToMxd(pMapDocument, MxdName);
if (pMapDocument == null)
return false;
if (pMapDocument.get_IsReadOnly(MxdPath + MxdName + ".mxd") == true)
{
return false;
}
pMapDocument.Save(true, false);
return true;
}
private bool AddLayerToMxd(IMapDocument pMapDocument,string MapGUID)
{
DataTable dt = GetMapLayersList(MapGUID);
IMap pMap = pMapDocument.get_Map(0);
IMapLayers mapLayer = pMap as IMapLayers;
mapLayer.ClearLayers();
for (int i = 0; i < dt.Rows.Count; i++)
{
DataRow dr = dt.Rows[i];
if ((int)dr["LayerType"] == 1)
{
IRasterDataset pRDataSet = GetRasterRasterDataset(dr["LayerStoreName"].ToString());
IRasterLayer pRLayer = CreateObject("esriCarto.RasterLayer") as IRasterLayer;
pRLayer.CreateFromDataset(pRDataSet);
RanderRaster(pRLayer);
mapLayer.AddLayer(pRLayer as ILayer);
}
else
{
IFeatureClass pFeatureClass = GetFeatureClass(dr["LayerStoreName"].ToString());
IFeatureLayer pFLayer = CreateObject("esriCarto.FeatureLayer") as IFeatureLayer;
pFLayer.FeatureClass = pFeatureClass;
IGeoFeatureLayer pGeoFeatureLayer = (IGeoFeatureLayer)pFLayer;
pGeoFeatureLayer.AnnotationProperties.Clear();
//IAnnotateLayerPropertiesCollection pAnnoLayerPropsColl =
CreateObject("esriCarto.AnnotateLayerPropertiesCollection");
IAnnotateLayerPropertiesCollection pAnnoLayerPropsColl = pGeoFeatureLayer.AnnotationProperties;
ILabelEngineLayerProperties pLabelEngine =
CreateObject("esriCarto.LabelEngineLayerProperties") as
ILabelEngineLayerProperties;
pLabelEngine.Expression = "[CONTOUR]";
ITextSymbol pSym = CreateObject("esriDisplay.TextSymbol") as ITextSymbol;
pSym.Color = GetRGBColor(0, 200, 200);
pSym.Size = 12;
pLabelEngine.Symbol = pSym;
IAnnotateLayerProperties pAnnoLayerProps = (IAnnotateLayerProperties)pLabelEngine;
pAnnoLayerPropsColl.Add(pAnnoLayerProps);
pGeoFeatureLayer.DisplayAnnotation = true;
mapLayer.AddLayer(pFLayer as ILayer);
}
}
IMxdContents pMxdC = pMap as IMxdContents;
pMapDocument.ReplaceContents(pMxdC);
return true;
}
private IColor GetRGBColor(int R, int G, int B)
{
IColor pColor = CreateObject("esriDisplay.RgbColor") as IColor;
pColor.RGB = B * 65536 + G * 256 + R;
return pColor;
}
#region 栅格图层渲染
private void RanderRaster(IRasterLayer pNewLayer)
{
IRasterBandCollection pNewCol = (IRasterBandCollection)pNewLayer.Raster;
IRasterBand pNewBand = pNewCol.Item(0);
pNewBand.ComputeStatsAndHist();
IRasterStretchColorRampRenderer pSRender
=CreateObject("esriCarto.RasterStretchColorRampRenderer") as
IRasterStretchColorRampRenderer;
IRasterRenderer pRender = (IRasterRenderer)pSRender;
pRender.Raster = pNewLayer.Raster;
pRender.Update();
IMultiPartColorRamp mpcr =CreateObject("esriDisplay.MultiPartColorRamp") as IMultiPartColorRamp;
IAlgorithmicColorRamp Alg1 =CreateObject("esriDisplay.AlgorithmicColorRamp") as IAlgorithmicColorRamp;
IAlgorithmicColorRamp Alg2 =CreateObject("esriDisplay.AlgorithmicColorRamp") as IAlgorithmicColorRamp;
IRgbColor c1 =CreateObject("esriDisplay.RgbColor") as IRgbColor;
IRgbColor c2 =CreateObject("esriDisplay.RgbColor") as IRgbColor;
IRgbColor c3 =CreateObject("esriDisplay.RgbColor") as IRgbColor;
c3.Red = 255; c3.Green = 150; c3.Blue = 150;
c2.Red = 255; c2.Green = 255; c2.Blue = 150;
c1.Red = 150; c1.Green = 255; c1.Blue = 255;
Alg1.FromColor = c1; Alg1.ToColor = c2;
Alg2.FromColor = c2; Alg2.ToColor = c3;
mpcr.AddRamp(Alg1);
mpcr.AddRamp(Alg2);
mpcr.Size = 255;
bool IsOk;
mpcr.CreateRamp(out IsOk);
pSRender.ColorRamp = mpcr;
pNewLayer.Renderer = pRender;
}
#endregion
private IServerContext CreateServerContext(string ServerName, string UserName, string PassWord)
{
ESRI.ArcGIS.ADF.Identity identity = new ESRI.ArcGIS.ADF.Identity(UserName, PassWord, "");
ESRI.ArcGIS.ADF.Connection.AGS.AGSServerConnection agsConnection = new
ESRI.ArcGIS.ADF.Connection.AGS.AGSServerConnection(ServerName,
identity);
agsConnection.Connect();
if (agsConnection.IsConnected)
{
try
{
IServerObjectManager som = agsConnection.ServerObjectManager;
IServerContext pServerContext = som.CreateServerContext("zys", "MapServer");
return pServerContext;
}
catch (Exception e)
{
return null;
}
}
return null;
}
#region ServerContext CreateObject函数
private object CreateObject(string ObjectCLSID)
{
IServerContext pServerContext = CreateServerContext(HostName,MapServerUserName,MapserverPass);
if (pServerContext == null) return null;
try
{
return pServerContext.CreateObject(ObjectCLSID);
}
catch
{
return null;
}
finally
{
pServerContext.ReleaseContext();
}
}
#endregion
#endregion
#region 判断服务、文档是否存在
/// <summary>
/// 判断是否存在该服务
/// </summary>
/// <param name="serviceName"></param>
/// <returns></returns>
private bool isExistService(string serviceName)
{
ServerConnection pServerConnection = new ESRI.ArcGIS.Server.WebControls.ServerConnection(HostName);//地图服务机器名
pServerConnection.Connect();
IServerObjectAdmin pServerSOA = pServerConnection.ServerObjectAdmin;
try
{
IServerObjectConfiguration pConfig = pServerSOA.GetConfiguration(serviceName, "MapServer");
return true;
}
catch (Exception e)
{
return false;
}
}
private bool isExistMxd(string MxdPath, string MapName)
{
if (MxdPath.Substring(MxdPath.Length - 1) != @"\")
MxdPath += @"\";
if (File.Exists(MxdPath + MapName + ".mxd"))
{
return true;
}
return false;
}
#endregion
#region SDE连接以及数据获取
string SDEServer = "gisserver";
string Instance = "5151";
string DataBase = "gis_data";
string SDEUser = "sde";
string PassWord = "sde";
private IPropertySet GetProPerty()
{
IPropertySet propertySet = (IPropertySet)CreateObject("esriSystem.PropertySet");
propertySet.SetProperty("SERVER", SDEServer);
propertySet.SetProperty("INSTANCE", Instance);
propertySet.SetProperty("DATABASE", DataBase);
propertySet.SetProperty("USER", SDEUser);
propertySet.SetProperty("PASSWORD", PassWord);
propertySet.SetProperty("VERSION", "sde.DEFAULT");
return propertySet;
}
private IWorkspace OpenSDEWorkSpace(IPropertySet pPropSet)
{
IWorkspace pWorkSpace = null;
IWorkspaceFactory pSdeFact = (IWorkspaceFactory)CreateObject("esriDataSourcesGDB.SdeWorkspaceFactory");
try
{
pWorkSpace = pSdeFact.Open(pPropSet, 0);
}
catch (Exception e)
{
}
return pWorkSpace;
}
private IRasterWorkspaceEx OpenSdeRasterWsp()
{
try
{
IPropertySet pProPerty = GetProPerty();
IRasterWorkspaceEx pRasterWsp = OpenSDEWorkSpace(pProPerty) as IRasterWorkspaceEx;
return pRasterWsp;
}
catch (Exception e)
{
return null;
}
}
private IFeatureWorkspace OpenSdeFeatureWsp()
{
try
{
IPropertySet pProPerty = GetProPerty();
IFeatureWorkspace pRasterWsp = OpenSDEWorkSpace(pProPerty) as IFeatureWorkspace;
return pRasterWsp;
}
catch (Exception e)
{
return null;
}
}
private IRasterDataset GetRasterRasterDataset(string RasterName)
{
IRasterWorkspaceEx pRasterWspEx = OpenSdeRasterWsp();
if (pRasterWspEx == null) return null;
IRasterDataset pRasterDataset=pRasterWspEx.OpenRasterDataset(RasterName);
return pRasterDataset;
}
private IFeatureClass GetFeatureClass(string FeatureName)
{
IFeatureWorkspace pFeatureWspEx = OpenSdeFeatureWsp();
if (pFeatureWspEx == null) return null;
IFeatureClass pFeatureClass = pFeatureWspEx.OpenFeatureClass(FeatureName);
return pFeatureClass;
}
#endregion
}
我的实现方式是利用中转的方式,意思是我做一个页面,放到服务器上,客户端填写地块编号后,直接提交到这个页面上;在这个页面上利用 ArcServer的API查找对应的地块,并找出该地块的外接矩形的坐标,合成一个ArcServer的WMS服务地址,利用重定向转到这个地址上去。
问题就在于中间这个页面该如何写呢?经过不断摸索,不断上网找资料,终于实现了该功能。
- .指定连接用的用户
- 连接到服务器
- 获取SOM对象
- 设置对应的地图名字和服务类型,获取上下文(IServerContext)
- .获取IMapServerObjects
- 通过IMapServerObjects获取IMap对象
- 获取要查询的图层和属性
- 设置查询用的Filter
- 调用Search查询
处理结果大概步骤如下:
首先引入相应的命名空间:
using ESRI.ArcGIS.ADF;
using ESRI.ArcGIS.ADF.Connection;
using ESRI.ArcGIS.ADF.Connection.AGS;
using ESRI.ArcGIS.Server;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.Geometry;
using ESRI.ArcGIS.Geodatabase;
1.指定连接用的用户
ESRI.ArcGIS.ADF.Identity id = new ESRI.ArcGIS.ADF.Identity();
id.UserName = "Administrator";
id.Password = "password";
id.Domain = "服务器的计算机名字";
string agsServerName = "服务器的IP地址";
2.连接到服务器
要通过程序来连接到GISServer,主要有两个对象可以使 用:ESRI.ArcGIS.Server.GISServerConnection(实现了IGISServerConnection2接口)和 ESRI.ArcGIS.ADF.Connection.AGS.AGSServerConnection。前者是com对象,后者是原生的.net对 象。
先来看ESRI.ArcGIS.Server.GISServerConnection。使用方法如下:
ESRI.ArcGIS.Server.IGISServerConnection2 pGISSC=
new ESRI.ArcGIS.Server.GISServerConnectionClass();
pGISSC.Connect("yourservername");
ESRI.ArcGIS.Server.IServerObjectAdmin pAdm = pGISSC.ServerObjectAdmin;
注意,要成功获得pGISSC.ServerObjectAdmin属性得有一个前提条件,就是运行当前AGS程序的用户必须是agsadmin 组里的成员。那么接下来就可以通过IServerObjectAdmin来对GISServer进行管理了;如果运行当前AGS程序的用户只是 agsuser组里的成员,那么你只能获得ServerObjectManager,从而通过IServerObjectManager来创建AO对象, 但是不能对GISServer进行管理;如果运行当前AGS程序的用户既不是agsuser成员也不是agsadmin成员,那么在connect的时候 就会报错了。可以看出ESRI.ArcGIS.Server.GISServerConnection对象不能显式指定连接GIS Server的用户。
下面再来看ESRI.ArcGIS.ADF.Connection.AGS.AGSServerConnection。这是ADF中的.net对 象,通常推荐使用这个对象来进行连接工作,因为它可以指定使用特定的账户身份来连接GIS Server,就是下面的Identity:
ESRI.ArcGIS.ADF.Identity identity = new ESRI.ArcGIS.ADF.Identity("username", "password", "domain");
ESRI.ArcGIS.ADF.Connection.AGS.AGSServerConnection agsconnection =
newESRI.ArcGIS.ADF.Connection.AGS.AGSServerConnection("yourgisservername",identity);
agsconnection.Connect();
ESRI.ArcGIS.Server.IServerObjectAdmin pAdm = agsconnection.ServerObjectAdmin;
同样的,要成功获得pAdm,Identity中指定的用户必须是agsadmin成员。如果你的网站,在调试时可以运行,而发布后“拒绝访问”,那么首先检查web.config的identity,如果使用了以上代码,请确保使用的user在正确的用户组中。
这里我就采用第一种方法,如下:
AGSServerConnection agsConn = new AGSServerConnection(agsServerName, id);
try
{
agsConn.Connect();
if (!agsConn.IsConnected)
{
agsConn.Dispose();
return "";
}
}
catch (Exception ex)
{
return "";
}
3.获取SOM对象
IServerObjectManager som = agsConn.ServerObjectManager;
4.设置对应的地图名字和服务类型,获取上下文(IServerContext)
要获取当前的severContext。而获取IServerContext有两种方法:
1)、通过当前Resorces得到
if (form == null)
{
return;
}
MapControl mapControl = (MapControl)form.findComponent((String)paramMap.get("mapId"));
if (mapControl == null)
{
return;
}
WebMap webMap = mapControl.getWebMap();
WebContext webContext = webMap.getWebContext();
// 得到当前服务的IServerContext
AGSLocalMapResource mapResource =
(AGSLocalMapResource)webContext.getResources().get ("ags1");MapServer
mapServer = mapResource.getLocalMapServer();
IServerContext serverContext =mapResource.getServerContext();
2)、通过IP链接得到(也就是我要用的方法)
IServerObjectManager som = agsConn.ServerObjectManager;
string servertype = "MapServer";
string serverobjectname = "GZ"; //对应的地图名
IServerContext severContext = som.CreateServerContext(serverobjectname, servertype);
IMapServer pMapServer = severContext.ServerObject as IMapServer;
IMapServerObjects pMapServerObjs = pMapServer as IMapServerObjects;
IMap pMap =pMapServerObjs.get_Map(pMapServer.DefaultMapName);
5.获取IMapServerObjects
IMapServer pMapServer = severContext.ServerObject as IMapServer;
IMapServerObjects pMapServerObjs = pMapServer as IMapServerObjects;
6.通过IMapServerObjects获取IMap对象
IMap pMap = pMapServerObjs.get_Map(pMapServer.DefaultMapName);
7.获取要查询的图层和属性
//得到查询的图层
ILayer workAreaLayer = pMap.get_Layer(7);
IFeatureLayer loopFeatureLayer = (FeatureLayer)(workAreaLayer);
IFeatureClass loopFeatureClass =loopFeatureLayer.FeatureClass;
8.设置查询用的Filter
ISpatialFilter spatialFilter = (ISpatialFilter)severContext.CreateObject("esriGeoDatabase.SpatialFilter");
string shpFld = loopFeatureClass.ShapeFieldName;
spatialFilter.GeometryField = shpFld;
//指定要使用的空间操作
spatialFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects;
//创建where表达式,这里只要要素
spatialFilter.WhereClause = "图号='" + no + "'";
IQueryFilter queryFilter=new QueryFilterClass();
queryFilter = (IQueryFilter)spatialFilter;
9.调用Search查询
IFeatureCursor featureCursor = loopFeatureClass.Search(queryFilter, false);
//第一个返回的要素
IFeature feature = featureCursor.NextFeature();
10.处理结果
IGeometry geo = feature.Shape;
string box = geo.Envelope.XMin.ToString() + "," + geo.Envelope.YMin.ToString();
box += "," + geo.Envelope.XMax.ToString() + "," + geo.Envelope.YMax.ToString();
这个Shape是查询结果中第一个地物的外接矩形,大家可以根据自己的业务使用。这里我是要使用Shape的左下和右上两个坐标点,拼接到WMS中去。
——————————————————————————
These were the recommendations from ESRI when I
reached out to them for help. I'm still evaluating which path will
work best for me (assuming I can get it to work at all). I think option
"C" is the path I am most likely to have success with based on my early
testing.
A) Using COM IGISServerConnectionClass: You would need to add and identity to the web.config with a user in the agsusers group. (see code fragment below) B)Use ADF connection ESRI.ArcGIS.ADF.Identity identity = new ESRI.ArcGIS.ADF.Identity("user", "passwd", "domain"); ESRI.ArcGIS.ADF.Connection.AGS.AGSServerConnection agsconnection; agsconnection = new ESRI.ArcGIS.ADF.Connection.AGS.AGSServerConnection("hostname", identity); agsconnection.Connect(); IServerObjectManager SOM = agsconnection.ServerObjectManager; Both A and B above are very well explained in this link http://resources.esri.com/help/9.3/ArcGISServer/adf/dotnet/developer/ArcGIS/ArcObjects/connect_gis_server.htm C) USE SOAP to connect to GPServer string endpoint = "http://MyWebServer/arcgis/services/MyGPServiceName/GPServer"; ESRI.ArcGIS.ADF.ArcGISServer.GPServerProxy gpserver = new ESRI.ArcGIS.ADF.ArcGISServer.GPServerProxy(endpoint); The link below provides better explanation on method "C". http://resources.esri.com/help/9.3/ArcGISServer/adf/dotnet/developer/ArcGIS/SOAP/gp_overview.htm |
|
|
在使用ArcGIS Server ArcObjects API的时候,一般都需要首先以local方式连接到GIS Server,那么在9.2版本中有两个类可以连接到GIS Server。一个是ESRI.ArcGIS.Server.GISServerConnectionClass类,另一个是 ESRI.ArcGIS.ADF.Connection.AGS.AGSServerConnection类。
ESRI.ArcGIS.Server.GISServerConnectionClass类是对COM类封装以后
的.NET类,在连接GIS Server时没有显式的指定用户,那么连接GIS
Server是使用的是什么用户呢?其实是使用的web应用的用户,如果在web.config中有identity的节点,那么就是它了。连接的代码如
下:
[C#]
ESRI.ArcGIS.Server.GISServerConnectionClass gisconnection;
gisconnection = new ESRI.ArcGIS.Server.GISServerConnectionClass();
gisconnection.Connect("servername");
ESRI.ArcGIS.Server.IServerObjectManager som = gisconnection.ServerObjectManager;
ESRI.ArcGIS.ADF.Connection.AGS.AGSServerConnection类是一个
纯粹的.NET类,其实整个ESRI.ArcGIS.ADF.Connection类库中的类都是.NET类。我们在连接server时最好使用
AGSServerConnection。这个类需要显式的指定身份信息,用法如下:
[C#]
ESRI.ArcGIS.ADF.Identity identity = new ESRI.ArcGIS.ADF.Identity("user", "passwd", "domain");
ESRI.ArcGIS.ADF.Connection.AGS.AGSServerConnection agsconnection;
agsconnection = new ESRI.ArcGIS.ADF.Connection.AGS.AGSServerConnection("hostname", identity);
agsconnection.Connect();
IServerObjectManager som = agsconnection.ServerObjectManager;
——————————————————————————————————————————————————————————
程序实现mxd文档发布成MapService服务
2010-11-11 13:54:16| 分类: GIS | 标签:mxd mapservice服务 |字号 订阅
Dim hostname As String = "Administrator"
Dim serverName As String = "rd-chx"
If txtFilePath.Text = "" Then
MessageBox.Show(Me, "请选择要发布成地图服务的文档")
Return
End If
If txtServiceName.Text = "" Then
MessageBox.Show(Me, "请输入地图服务的名称")
Return
End If
Dim filepath As String = txtFilePath.Text
Dim servicesName As String = txtServiceName.Text
Dim servicesType As String = "MapServer"
Dim id As ESRI.ArcGIS.ADF.Identity = New ESRI.ArcGIS.ADF.Identity(hostname, "asdfghjkl", "RD-CHX")
Dim agsconn As ESRI.ArcGIS.ADF.Connection.AGS.AGSServerConnection
agsconn = New ESRI.ArcGIS.ADF.Connection.AGS.AGSServerConnection(serverName, id)
agsconn.Connect()
Dim som As IServerObjectManager = agsconn.ServerObjectManager
Dim svrObjAdmin As IServerObjectAdmin = agsconn.ServerObjectAdmin
Dim svrObjConf As IServerObjectConfiguration2 = DirectCast(svrObjAdmin.CreateConfiguration, IServerObjectConfiguration2)
Dim publishedServicesConf As IEnumServerObjectConfiguration = svrObjAdmin.GetConfigurations()
'判断MapServer列表中是否有重名
Dim tempSvrObjConf As IServerObjectConfiguration2
For i As Integer = 0 To publishedServicesConf.Count - 1
tempSvrObjConf = DirectCast(publishedServicesConf.Next, IServerObjectConfiguration2)
Dim name As String = tempSvrObjConf.Name
If name = servicesName Then
MessageBox.Show(Me, "该名称的服务已经存在,请重新命名!")
Return
End If
Next
svrObjConf.Name = servicesName
svrObjConf.TypeName = servicesType
svrObjConf.IsPooled = True
svrObjConf.MinInstances = 1
svrObjConf.MaxInstances = 1
svrObjConf.WaitTimeout = 10
svrObjConf.UsageTimeout = 120
Dim props As ESRI.ArcGIS.esriSystem.IPropertySet = svrObjConf.Properties
props.SetProperty("FilePath", filepath)
'以下的property并非必须,只需要一个filepath就可以发布服务
props.SetProperty("OutputDir", "c:\\arcgisserver\\arcgisoutput") '图片的输出目录
Dim VirtualOutPutDir As String = "http://" + hostname + "/arcgisoutput"
props.SetProperty("VirtualOutPutDir", VirtualOutPutDir) '图片输出的虚拟路径
props.SetProperty("SupportedImageReturnTypes", "URL") '支持的图片类型
props.SetProperty("MaxImageHeight", "2048") '图片的最大高度
props.SetProperty("MaxRecordCount", "500") '返回记录的最大条数
props.SetProperty("MaxBufferCount", "100") '缓冲区分析的最大数目
props.SetProperty("MaxImageWidth", "2048") '图片的最大宽度
props.SetProperty("IsCached", "false") '是否切片
props.SetProperty("CacheOnDemand", "false") '是否主动切片
props.SetProperty("IgnoreCache", "false") '是否忽略切片
props.SetProperty("ClientCachingAllowed", "true") '是否允许客户端缓冲
Dim CacheDir As String = "c:\\arcgisserver\\arcgiscache\\" + serverName
props.SetProperty("CacheDir", CacheDir) '切片的输出路径
props.SetProperty("SOMCacheDir", "c:\\arcgisserver\\arcgiscache") 'som的切片输出路径
svrObjAdmin.AddConfiguration(svrObjConf)
svrObjAdmin.StartConfiguration(svrObjConf.Name, svrObjConf.TypeName)
MessageBox.Show(Me, "地图服务发布成功!")