C# 调用ArcGIS server admin api
一、AGS server admin api 介绍
1.1什么是admin api
AGS Server Admin api 官方的称呼是 AGS Server administrator api, 通过这名字也可以猜出该api的作用,通过该api可以管理arcgis server。ArcGIS Server常见的管理功能有安装配置、server 日志、站点的监测配置等,详细的Server管理内容,可以参考ArcGIS Server的官方帮助的管理arcgis Server。
1.2 admin api 作用
通常ArcGIS Server的管理是通过在manager页面中进行的。但是arcgis server manager所呈现的管理功能其后台也是通过调用admin api。也就是说manager页面的管理是esri通过调用admin api开发出来的web 端的server管理工具。有些server的管理工具在manager找不到,但是可以从admin中页面中获得。
通过调研admin api 完全可以开发一个管理工具来替代manager,从中根据自己的业务需求定制所需要的功能。一句话概括就是使用admin api可以二次开发出server管理系统。目前使用admin api开发比较好的产品为,捷泰天域开发的oneMap,其就是一个通过调用admin api开发出的server管理工具,通过oneMap可以方便的实现manger 已有的功能,也可以实现诸如日志统计分析、管理数据的统计,并将统计信息已图表的形式呈现这种manger没有呈现的功能。
如果用户不想基于admin api 开发新的server管理系统,而想对ArcGIS server manager中的内容进行更改,可以直接进行admin页面中,链接格式如下:http://localhost:6080/arcgis/admin/login,可以在这里面对manager进行管理。
Tips: 10.2 server的admin 中添加了站点的备份与恢复
1.3 admin api的实质
admin api 的实质也就是rest api,通过发送参数为json格式的http请求,实现操作。则可以看出,只要任何可以发送http请求的编程语言都可以用来调用admin api,像java,python,c# 等,本文就采用C# 调用Admin api进行示例。
二、使用C#调用admin api
admin api 通常调用遵循以下步骤:
1.获取token
根据站点用户名和密码生成token和证书
private string GenerateAGSToken()
{
try
{
string urlGenerateToken = string.Format("{0}/generateToken", this.urlRestAdmin);
string credential = string.Format("username={0}&password={1}&client=requestip&expiration=&f=json", this.username, this.password);
string result = this.GetResult(urlGenerateToken, credential); JsonObject jsonObject = new JsonObject(result);
string token = null;
if (!jsonObject.Exists("token") || !jsonObject.TryGetString("token", out token))
{
throw new Exception("Token not found!");
} return token;
}
catch(Exception ex)
{
return string.Empty;
}
}
2.构建json格式的参数
根据执行的操作所需要的参数,构建json格式的参数,这里以创建服务操作作为例子,进行json字符串的构建。这里使用的JsonObject对象为SOE开发中的链接库ESRI.ArcGIS.SOESupport.dll 所带。
public bool CreateService()
{
try
{
string token = this.GenerateAGSToken();
string serviceUrl = this.urlRestAdmin + "/services/createService"; JsonObject jsonObject = new JsonObject();
jsonObject.AddString("serviceName", "Test");
//服务类型
jsonObject.AddString("type", Enum.GetName(typeof(ServiceType), ServiceType.GPServer));
jsonObject.AddString("description", "This is an example");
//不同的服务类型,其capabilities是不同的,地图服务的为Map,query和data
// jsonObject.AddString("capabilities", "Map,Query,Data"); jsonObject.AddString("capabilities","Uploads");//gp 服务的capabilities
jsonObject.AddString("clusterName", "default");
jsonObject.AddLong("minInstancesPerNode", );
jsonObject.AddLong("maxInstancesPerNode", );
jsonObject.AddLong("maxWaitTime", );
jsonObject.AddLong("maxStartupTime", );
jsonObject.AddLong("maxIdleTime", );
jsonObject.AddLong("maxUsageTime", );
jsonObject.AddLong("recycleInterval", );
jsonObject.AddString("loadBalancing", Enum.GetName(typeof(LoadBalancing), LoadBalancing.ROUND_ROBIN));
jsonObject.AddString("isolationLevel", Enum.GetName(typeof(IsolationLevel), IsolationLevel.HIGH)); JsonObject jsonObjectProperties = new JsonObject(); // see for a list complete http://resources.arcgis.com/en/help/server-admin-api/serviceTypes.html
jsonObjectProperties.AddLong("maxBufferCount", ); // optional 100
jsonObjectProperties.AddString("virtualCacheDir", this.urlRestServer + "/arcgiscache"); // optional
jsonObjectProperties.AddLong("maxImageHeight", ); // optional 2048
jsonObjectProperties.AddLong("maxRecordCount", ); // optional 500 //10.1中服务是通过msd的形式发布的,所以创建地图服务时候将mxd转换成msd的形式,创建msd的形式而其他服务的数据发布形式,参考上面的链接 // jsonObjectProperties.AddString("filePath", @"C:\AvGis\Test\mappa\UTM_ReteFognaria.msd"); //地图服务 required jsonObjectProperties.AddString( "toolbox",@"d:\Buffer.tbx");//gp服务使用的是路径创建gp服务的路径 jsonObjectProperties.AddLong("maxImageWidth", ); // optional 2048
jsonObjectProperties.AddBoolean("cacheOnDemand", false); // optional false
jsonObjectProperties.AddString("virtualOutputDir", this.urlRestServer + "/arcgisoutput");
jsonObjectProperties.AddString("outputDir", @"C:\arcgisserver\directories\arcgisoutput");
jsonObjectProperties.AddString("jobsDirectory", @"C:\arcgisserver\directories\arcgisjobs"); // required
jsonObjectProperties.AddString("supportedImageReturnTypes", "MIME+URL"); // optional MIME+URL
jsonObjectProperties.AddBoolean("isCached", false); // optional false
jsonObjectProperties.AddBoolean("ignoreCache", false); // optional false
jsonObjectProperties.AddBoolean("clientCachingAllowed", false); // optional true
jsonObjectProperties.AddString("cacheDir", @"C:\arcgisserver\directories\arcgiscache"); // optional jsonObject.AddJsonObject("properties", jsonObjectProperties); string result = this.GetResult(serviceUrl, "service=" +HttpUtility.UrlEncode(jsonObject.ToJson()) + "&f=json&token=" + token);
return this.HasSuccess(result); }
catch
{
return false;
}
}
admin api中的各项参数,详见admin api的帮助:http://resources.arcgis.com/en/help/server-admin-api/,参数分为required和optional。
3.发送http请求
admin api可以支持两者get和post请求。server管理功能中有些操作是不支持get请求的。
get请求
private string GetResult(string url)
{
try
{
WebRequest request = WebRequest.Create(url);
WebResponse response = request.GetResponse();
using (Stream responseStream = response.GetResponseStream())
{
using (StreamReader reader = new StreamReader(responseStream))
{
return reader.ReadToEnd();
}
}
}
catch
{
throw;
}
}
post请求
rivate string GetResult(string url, string postContent)
{
try
{
WebRequest request = WebRequest.Create(url);
byte[] content = Encoding.UTF8.GetBytes(postContent);
request.ContentLength = content.Length;
request.ContentType = "application/x-www-form-urlencoded";
request.Method = WebRequestMethods.Http.Post;
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(content, , content.Length);
requestStream.Close();
WebResponse response = request.GetResponse();
using (Stream responseStream = response.GetResponseStream())
{
using (StreamReader reader = new StreamReader(responseStream))
{
return reader.ReadToEnd();
}
}
}
}
catch
{
throw;
}
}
4.接收请求
三、完整的代码
代码中涉及到服务的发布、删除、文件夹的创建等
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web; //// ///// namespace Studioat.ArcGIS.Server.Administrator
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
using ESRI.ArcGIS.SOESupport; /// <summary>
/// 服务类型
/// </summary>
public enum ServiceType
{
MapServer,
GeocodeServer,
SearchServer,
IndexingLauncher,
IndexGenerator,
GeometryServer,
GeoDataServer,
GPServer,
GlobeServer,
ImageServer
} /// <summary>
/// 负载平衡
/// </summary>
public enum LoadBalancing
{
ROUND_ROBIN,
FAIL_OVER
} /// <summary>
/// isolation level
///
/// </summary>
public enum IsolationLevel
{
LOW,
HIGH
} /// <summary>
/// administrative API Rest
/// </summary>
public class AGSAdmin
{
private string username;
private string password;
private string urlRestAdmin;
private string urlRestServer; /// <summary>
/// Initializes a new instance of the <see cref="AGSAdmin"/> class.
/// </summary>
/// <param name="serverName">server name</param>
/// <param name="port">port of server</param>
/// <param name="username">username administrator</param>
/// <param name="password">password administrator</param>
public AGSAdmin(string serverName, int port, string username, string password)
{
this.username = username;
this.password = password;
string url = string.Format("http://{0}:{1}/arcgis", serverName, port.ToString());
this.urlRestAdmin = url + "/admin";
this.urlRestServer = url + "/server";
} /// <summary>
/// Prevents a default instance of the <see cref="AGSAdmin"/> class from being created.
/// </summary>
private AGSAdmin()
{
} /// <summary>
/// Create arcgis server folder
/// </summary>
/// <param name="folderName">Folder name</param>
/// <param name="description">Description of the folder</param>
/// <returns>True if successfully created</returns>
public bool CreateServerFolder(string folderName, string description)
{
try
{
string token = this.GenerateAGSToken();
string folderUrl = this.urlRestAdmin + "/services/" + folderName + "?f=json&token=" + token;
string resultExistsFolder = this.GetResult(folderUrl);
if (!this.HasError(resultExistsFolder))
{
return true; // exists
}
else
{
string createFolderUrl = this.urlRestAdmin + "/services/createFolder";
string postContent = string.Format("folderName={0}&description={1}&f=json&token={2}", folderName, description, token);
string result = this.GetResult(createFolderUrl, postContent);
return this.HasSuccess(result);
}
}
catch
{
return false;
}
} /// <summary>
/// Get physical Path and virtual Path from directory ags
/// </summary>
/// <param name="directory">directory ags</param>
/// <param name="physicalPath">physical Path</param>
/// <param name="virtualPath">virtual Path</param>
/// <returns>True if successfully return path</returns>
public bool GetServerDirectory(string directory, out string physicalPath, out string virtualPath)
{
physicalPath = null;
virtualPath = null;
try
{
string token = this.GenerateAGSToken();
string directoryUrl = this.urlRestAdmin + "/system/directories/" + directory + "?f=json&token=" + token; string result = this.GetResult(directoryUrl); JsonObject jsonObject = new JsonObject(result);
if (!jsonObject.Exists("physicalPath") || !jsonObject.TryGetString("physicalPath", out physicalPath))
{
throw new Exception();
} jsonObject = new JsonObject(result);
if (!jsonObject.Exists("virtualPath") || !jsonObject.TryGetString("virtualPath", out virtualPath))
{
throw new Exception();
} return true;
}
catch
{
return false;
}
} /// <summary>
/// Delete Service
/// </summary>
/// <param name="serviceName">Service Name</param>
/// <param name="serviceType">Server Type</param>
/// <returns>True if successfully deleted</returns>
public bool DeleteService(string serviceName, ServiceType serviceType)
{
try
{
string token = this.GenerateAGSToken();
string serviceUrl = this.urlRestAdmin + "/services/" + serviceName + "." + Enum.GetName(typeof(ServiceType), serviceType) + "/delete";
string result = this.GetResult(serviceUrl, "f=json&token=" + token);
return this.HasSuccess(result);
}
catch
{
return false;
}
} /// <summary>
/// Start Service
/// </summary>
/// <param name="serviceName">Service Name</param>
/// <param name="serviceType">Server Type</param>
/// <returns>True if successfully started</returns>
public bool StartService(string serviceName, ServiceType serviceType)
{
try
{
string token = this.GenerateAGSToken();
string serviceUrl = this.urlRestAdmin + "/services/" + serviceName + "." + Enum.GetName(typeof(ServiceType), serviceType) + "/start";
string result = this.GetResult(serviceUrl, "f=json&token=" + token);
return this.HasSuccess(result);
}
catch
{
return false;
}
} /// <summary>
/// 停止服务
/// </summary>
/// <param name="serviceName">Service Name</param>
/// <param name="serviceType">Server Type</param>
/// <returns>True if successfully stopped</returns>
public bool StopService(string serviceName, ServiceType serviceType)
{
try
{
string token = this.GenerateAGSToken();
string serviceUrl = this.urlRestAdmin + "/services/" + serviceName + "." + Enum.GetName(typeof(ServiceType), serviceType) + "/stop";
string result = this.GetResult(serviceUrl, "f=json&token=" + token);
return this.HasSuccess(result);
}
catch
{
return false;
}
} /// <summary>
/// 列举服务
/// </summary>
public void ListServices()
{
this.ListServices(null);
} /// <summary>
/// list of services in folder
/// </summary>
/// <param name="folder">name of folder</param>
public void ListServices(string folder)
{
try
{
string token = this.GenerateAGSToken();
string serviceUrl = this.urlRestAdmin + "/services/" + folder;
string postcontent = "f=json&token=" + token;
string result = this.GetResult(serviceUrl, postcontent); JsonObject jsonObject = new JsonObject(result);
object[] folders = null;
if (jsonObject.Exists("folders") && jsonObject.TryGetArray("folders", out folders))
{
foreach (string subfolder in folders)
{
this.ListServices(subfolder);
}
} object[] services = null;
if (jsonObject.Exists("services") && jsonObject.TryGetArray("services", out services))
{
IEnumerable<JsonObject> jsonObjectService = services.Cast<JsonObject>();
jsonObjectService.ToList().ForEach(jo =>
{
string serviceName;
jo.TryGetString("serviceName", out serviceName);
string folderName;
jo.TryGetString("folderName", out folderName);
Console.WriteLine(folderName + "/" + serviceName);
});
}
}
catch
{
throw;
}
} /// <summary>
/// create service type MapServer
/// </summary>
/// <returns>>True if successfully created</returns>
public bool CreateService()
{
try
{
string token = this.GenerateAGSToken();
string serviceUrl = this.urlRestAdmin + "/services/createService"; JsonObject jsonObject = new JsonObject();
jsonObject.AddString("serviceName", "Test");
//服务类型
jsonObject.AddString("type", Enum.GetName(typeof(ServiceType), ServiceType.GPServer));
jsonObject.AddString("description", "This is an example");
//不同的服务类型,其capabilities是不同的,地图服务的为Map,query和data
// jsonObject.AddString("capabilities", "Map,Query,Data"); jsonObject.AddString("capabilities","Uploads");//gp 服务的capabilities
jsonObject.AddString("clusterName", "default");
jsonObject.AddLong("minInstancesPerNode", );
jsonObject.AddLong("maxInstancesPerNode", );
jsonObject.AddLong("maxWaitTime", );
jsonObject.AddLong("maxStartupTime", );
jsonObject.AddLong("maxIdleTime", );
jsonObject.AddLong("maxUsageTime", );
jsonObject.AddLong("recycleInterval", );
jsonObject.AddString("loadBalancing", Enum.GetName(typeof(LoadBalancing), LoadBalancing.ROUND_ROBIN));
jsonObject.AddString("isolationLevel", Enum.GetName(typeof(IsolationLevel), IsolationLevel.HIGH)); JsonObject jsonObjectProperties = new JsonObject(); // see for a list complete http://resources.arcgis.com/en/help/server-admin-api/serviceTypes.html
jsonObjectProperties.AddLong("maxBufferCount", ); // optional 100
jsonObjectProperties.AddString("virtualCacheDir", this.urlRestServer + "/arcgiscache"); // optional
jsonObjectProperties.AddLong("maxImageHeight", ); // optional 2048
jsonObjectProperties.AddLong("maxRecordCount", ); // optional 500 //10.1中服务是通过msd的形式发布的,所以创建地图服务时候将mxd转换成msd的形式,创建msd的形式而其他服务的数据发布形式,参考上面的链接 // jsonObjectProperties.AddString("filePath", @"C:\AvGis\Test\mappa\UTM_ReteFognaria.msd"); //地图服务 required jsonObjectProperties.AddString( "toolbox",@"d:\Buffer.tbx");//gp服务使用的是路径创建gp服务的路径 jsonObjectProperties.AddLong("maxImageWidth", ); // optional 2048
jsonObjectProperties.AddBoolean("cacheOnDemand", false); // optional false
jsonObjectProperties.AddString("virtualOutputDir", this.urlRestServer + "/arcgisoutput");
jsonObjectProperties.AddString("outputDir", @"C:\arcgisserver\directories\arcgisoutput");
jsonObjectProperties.AddString("jobsDirectory", @"C:\arcgisserver\directories\arcgisjobs"); // required
jsonObjectProperties.AddString("supportedImageReturnTypes", "MIME+URL"); // optional MIME+URL
jsonObjectProperties.AddBoolean("isCached", false); // optional false
jsonObjectProperties.AddBoolean("ignoreCache", false); // optional false
jsonObjectProperties.AddBoolean("clientCachingAllowed", false); // optional true
jsonObjectProperties.AddString("cacheDir", @"C:\arcgisserver\directories\arcgiscache"); // optional jsonObject.AddJsonObject("properties", jsonObjectProperties); string result = this.GetResult(serviceUrl, "service=" +HttpUtility.UrlEncode(jsonObject.ToJson()) + "&f=json&token=" + token);
return this.HasSuccess(result); }
catch
{
return false;
}
} /// <summary>
/// check is status is equal success
/// </summary>
/// <param name="result">result of request</param>
/// <returns>True if status is equal success</returns>
private bool HasSuccess(string result)
{
JsonObject jsonObject = new JsonObject(result);
string status = null;
if (!jsonObject.Exists("status") || !jsonObject.TryGetString("status", out status))
{
return false;
} return status == "success";
} /// <summary>
///错误信息判断
/// </summary>
/// <param name="result">result of request</param>
/// <returns>True if status is equal error</returns>
private bool HasError(string result)
{
JsonObject jsonObject = new JsonObject(result);
string status = null;
if (!jsonObject.Exists("status") || !jsonObject.TryGetString("status", out status))
{
return false;
} return status == "error";
} /// <summary>
/// get请求
/// </summary>
/// <param name="url">get 请求url</param>
/// <returns>return response</returns>
private string GetResult(string url)
{
try
{
WebRequest request = WebRequest.Create(url);
WebResponse response = request.GetResponse();
using (Stream responseStream = response.GetResponseStream())
{
using (StreamReader reader = new StreamReader(responseStream))
{
return reader.ReadToEnd();
}
}
}
catch
{
throw;
}
} /// <summary>
/// post请求
/// </summary>
/// <param name="url">请求url</param>
/// <param name="postContent">post content</param>
/// <returns></returns>
private string GetResult(string url, string postContent)
{
try
{
WebRequest request = WebRequest.Create(url);
byte[] content = Encoding.UTF8.GetBytes(postContent);
request.ContentLength = content.Length;
request.ContentType = "application/x-www-form-urlencoded";
request.Method = WebRequestMethods.Http.Post;
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(content, , content.Length);
requestStream.Close();
WebResponse response = request.GetResponse();
using (Stream responseStream = response.GetResponseStream())
{
using (StreamReader reader = new StreamReader(responseStream))
{
return reader.ReadToEnd();
}
}
}
}
catch
{
throw;
}
} /// <summary>
/// 产生token
/// </summary>
/// <returns>返回一个toke,采用默认的过期时间令牌</returns>
private string GenerateAGSToken()
{
try
{
string urlGenerateToken = string.Format("{0}/generateToken", this.urlRestAdmin);
string credential = string.Format("username={0}&password={1}&client=requestip&expiration=&f=json", this.username, this.password);
string result = this.GetResult(urlGenerateToken, credential); JsonObject jsonObject = new JsonObject(result);
string token = null;
if (!jsonObject.Exists("token") || !jsonObject.TryGetString("token", out token))
{
throw new Exception("Token not found!");
} return token;
}
catch(Exception ex)
{
return string.Empty;
}
}
}
}
工程文件下载:https://github.com/myyouthlife/blog/tree/master/Studioat.ArcGIS.Server.Administrator
C# 调用ArcGIS server admin api的更多相关文章
- arcgis engine 调用arcgis server服务
首先需要添加两个引用: using ESRI.ArcGIS.GISClient;using ESRI.ArcGIS.DataSourcesRaster; /// <summary> /// ...
- OpenLayers调用arcgis server发布的地图服务
有两种方式可以调用arcgis server发布的地图服务,一种是rest,一种是wms. 地图的投影为900913,arcgis server为10.0版本,地图服务的空间参考为3857. 与 ...
- OpenLayers调用ArcGIS Server发布的WFS服务
OpenLayers调用ArcGIS Server发布的WFS服务 原创: 蔡建良 2013-08-20 一. 开发环境 1) Openlayers2.13+arcgis server9.3 2) W ...
- C#中winform下利用ArcEngine调用ArcGIS Server发布的服务 AE 10
开发环境:vs2010 + AE 10 测试 public Form1() { ESRI.ArcGIS.RuntimeManager.Bind(ESRI.ArcGIS.ProductCode.Engi ...
- C#中winform下利用ArcEngine调用ArcGIS Server发布的服务 AE9.3
主要使用了AE中的IAGSServerOject接口及IMapServer接口.Private void GetServerTest_Click(object sender, EventArgs e) ...
- ArcGIS Server JavaScript API 各命名空间的含义【转】
1.esri 命名空间 所有的对象都是在 esri 命名空间下的,esri 有自己的属性和方法. 如 esri.version 返回当前 JavaScript API 的版本号.e ...
- ArcGIS Server JavaScript API中ESRI字体下载
---------------------------------------------------------------------------------- import sys, os im ...
- 移动端调用ArcGIS Server 10.1服务
1.最好用mdb数据源,不要用shp文件作为数据源,一是属性字段长度超过5个字符会被截断,二是中文会变成乱码. 2.mxd的layer的坐标系要是WGS1984(4362),不然属性查询不出来.
- 应用ArcGIS Server JavaScript API实现地图卷帘效果实现
var maskDynamicMapServiceLayer = null; var maskDynamicMapServiceLayerDiv = null; var pointNumb = 0; ...
随机推荐
- JDBC进行Oracle数据库操作。
1,按照Oracle 2,创建数据库脚步 DROP TABLE person ; DROP SEQUENCE myseq ;//设置自增序列. CREATE SEQUENCE myseq ; CREA ...
- Eclipse 安装应用SVN地址
SVN插件下载地址及更新地址,你根据需要选择你需要的版本.现在最新是1.8.xLinks for 1.8.x Release:Eclipse update site URL: http://subcl ...
- SVN环境搭建(2)
原文地址:http://www.penglig.com/post-73.html TortoiseSVN的使用. 首先打开VisualSVN Server Manager,如图: 可以在窗口的右边看到 ...
- WPF入门教程系列一
WPF入门教程 一. 前言 公司项目基于WPF开发,最近项目上线有点空闲时间写一篇基于wpf的基础教材,WPF也是近期才接触,学习WPF也是在网上查资料与微软的MSDN进行学习,写本博客的目为了温 ...
- Apache Rewrite 规则详解
在开篇之前: 我想说这篇文章其实是我刚刚接触Rewrite的时候学习的文档,应属转载,但是在这里我不想写明原地址,原因是文章中大多数给出的配置命令经实验都是错误的.需要原文的可以在谷歌上搜索一下&qu ...
- UDP与TCP报文格式,字段意义
UDP报文 1.UDP有两个字段:数据字段和首部字段. 首部字段 首部字段很简单,只有8个字节,由4个字段组成,每个字段的长度都是两个字节. 1)源端口:源端口号.在需要对方回信时选用.不需要时可 ...
- 测试xxxxxxxx
测试sdfs xxxxxxxbgssdfsdf f sd=JS-demp.zip f /** * @author John Smith <john.smith@example.com> ...
- 判断当前VC 是push还是present的
NSArray *viewcontrollers=self.navigationController.viewControllers; if (viewcontrollers.count>1) ...
- Ireport常用操作汇总
1.四则运算 new java.lang.Double(($F{fincome}.doubleValue())/($F{fhomePopulation}.intValue()))
- C++语言基础(6)-const 关键字
在类中,如果你不希望某些数据被修改,可以使用const关键字加以限定.const 可以用来修饰成员变量.成员函数以及对象. 一 const 成员变量 const 成员变量的用法和普通 const 变量 ...