C# soe二次开发创建项目,并添加到server服务上
1.安装好arcdestop,arcengine环境,可参考:
https://www.cnblogs.com/hjyjack9563-bk/articles/16066361.html
2.本次是arcengine10.1+visual studio2010项目创建:
- 新建项目
- 配置一个全局IFeatureClass m_FeatureClass
- 设置生命周期开始时调试
- 释放
- 获取服务图层数据
- 接口编写
完整代码

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Collections.Specialized; using System.Runtime.InteropServices; using ESRI.ArcGIS.esriSystem; using ESRI.ArcGIS.Server; using ESRI.ArcGIS.Geometry; using ESRI.ArcGIS.Geodatabase; using ESRI.ArcGIS.Carto; using ESRI.ArcGIS.SOESupport; using ESRI.ArcGIS.Geoprocessing; using ESRI.ArcGIS.DataSourcesGDB; using ESRI.ArcGIS.AnalysisTools; using ESRI.ArcGIS.Geoprocessor; using ESRI.ArcGIS.DataSourcesFile; using System.ServiceModel.Web; using System.Runtime.Serialization; using System.Runtime.Serialization.Json; using System.IO; using System.Web.Script.Serialization; using Newtonsoft.Json.Linq; using ESRI.ArcGIS.GISClient; //TODO: sign the project (project properties > signing tab > sign the assembly) // this is strongly suggested if the dll will be registered using regasm.exe <your>.dll /codebase namespace jinanCommon { [ComVisible(true)] [Guid("c05307f8-fa6b-4d6b-98ef-469e36f2d19b")] [ClassInterface(ClassInterfaceType.None)] [ServerObjectExtension("MapServer", AllCapabilities = "", DefaultCapabilities = "", Description = "Insert SOE Description here", DisplayName = "jinanCommon", Properties = "", SupportsREST = true, SupportsSOAP = false)] public class jinanCommon : IServerObjectExtension, IObjectConstruct, IRESTRequestHandler { private string soe_name; private IPropertySet configProps; private IServerObjectHelper serverObjectHelper; private ServerLogger logger; private IRESTRequestHandler reqHandler; private IFeatureClass m_FeatureClass = null; public jinanCommon() { soe_name = this.GetType().Name; logger = new ServerLogger(); reqHandler = new SoeRestImpl(soe_name, CreateRestSchema()) as IRESTRequestHandler; } #region IServerObjectExtension Members public void Init(IServerObjectHelper pSOH) { //生命周期开始时调试 System.Diagnostics.Debugger.Launch(); serverObjectHelper = pSOH; } public void Shutdown() { this.soe_name = null; this.m_FeatureClass = null; this.logger = null; this.serverObjectHelper = null; this.configProps = null; this.reqHandler = null; } #endregion #region IObjectConstruct Members public void Construct(IPropertySet props) { configProps = props; try { //获取数据 IMapServer3 mapServer = (IMapServer3)serverObjectHelper.ServerObject; IMapLayerInfo layerInfo; IMapLayerInfos layerInfos = mapServer.GetServerInfo(mapServer.DefaultMapName).MapLayerInfos; // 获取查询图层id int layercount = layerInfos.Count; int layerIndex = 0; IMapServerDataAccess dataAccess = (IMapServerDataAccess)mapServer; this.m_FeatureClass = (IFeatureClass)dataAccess.GetDataSource(mapServer.DefaultMapName, layerIndex); if (this.m_FeatureClass == null) { logger.LogMessage(ServerLogger.msgType.error, "Construct", 8000, "SOE custom error: Layer name not found."); return; } } catch (Exception e) { } } #endregion #region IRESTRequestHandler Members public string GetSchema() { return reqHandler.GetSchema(); } public byte[] HandleRESTRequest(string Capabilities, string resourceName, string operationName, string operationInput, string outputFormat, string requestProperties, out string responseProperties) { return reqHandler.HandleRESTRequest(Capabilities, resourceName, operationName, operationInput, outputFormat, requestProperties, out responseProperties); } #endregion private RestResource CreateRestSchema() { RestResource rootRes = new RestResource(soe_name, false, RootResHandler); RestOperation sampleOper = new RestOperation("sampleOperation", new string[] { "parm1", "parm2" }, new string[] { "json" }, SampleOperHandler); rootRes.operations.Add(sampleOper); //地类分析 压占分析 shp数据下载 //shp数据下载 本图层 字段长度只能到10 RestOperation sampleOpershpdown = new RestOperation("ExportToShp", new string[] { "exportPath", "where" }, new string[] { "json" }, ExportToShp); //rootRes.operations.Add(sampleOpershpdown); RestOperation sampleOpershpdown1 = new RestOperation("ExportToShp1", new string[] { "exportPath", "where" }, new string[] { "json" }, ExportToShp1); rootRes.operations.Add(sampleOpershpdown1); //shp数据下载 外传features RestOperation sampleOpershpdown2 = new RestOperation("JsonExportToShp", new string[] { "exportPath", "features" }, new string[] { "json" }, JsonExportToShp); rootRes.operations.Add(sampleOpershpdown2); //压占分析 RestOperation sampleOper6 = new RestOperation("yzAnalysis", new string[] { "features" }, new string[] { "json" }, yzAnalysis); rootRes.operations.Add(sampleOper6); RestOperation sampleOper7 = new RestOperation("yzAnalysisFW", new string[] { "serverUrl", "serverIds", "where", "MapName" }, new string[] { "json" }, yzAnalysisFW); rootRes.operations.Add(sampleOper7); //点缓冲分析查询包含内的要素 RestOperation pbufsampleOper = new RestOperation("PointBuffer", new string[] { "pgeometry", "pRadius", "where" }, new string[] { "json" }, PointBufferContain); rootRes.operations.Add(pbufsampleOper); //面缓冲分析查询包含内的要素 RestOperation pbufsampleOper1 = new RestOperation("PolygonBuffer", new string[] { "pgeometry", "pRadius", "where" }, new string[] { "json" }, PolygonBufferContain); rootRes.operations.Add(pbufsampleOper1); //xian缓冲分析查询包含内的要素 RestOperation plinebufsampleOper = new RestOperation("PolylineBuffer", new string[] { "pgeometry", "pRadius", "where" }, new string[] { "json" }, PolylineBufferContain); rootRes.operations.Add(plinebufsampleOper); return rootRes; } private byte[] RootResHandler(NameValueCollection boundVariables, string outputFormat, string requestProperties, out string responseProperties) { responseProperties = null; JsonObject result = new JsonObject(); result.AddString("hello", "world"); result.AddString("ExportToShp接口", "字段长度只能到10;exportPath:输出路径;where:服务图层的筛选;(注意:是导出图层的数据作为shp;所保存的路径是在部署arcgis的本机上的)"); result.AddString("JsonExportToShp接口", "字段长度只能到10;exportPath:输出路径;features:是传过来的要素集json,以图层服务接口为准的格式:{'geometryType':'esriGeometryPolygon','spatialReference': {'wkid': 4490,latestWkid:4490},'fields':[{name:'BSM',type:'esriFieldTypeString',alias:'标识码',length:18},{name:'XZQDM',type:'esriFieldTypeString',alias:'行政区代码',length:19}],'features':['attributes':{BSM:'tst1',XZQDM:'002'},geometry:{}]}"); result.AddString("yzAnalysis接口", "(features与图层服务)用于传多个features与服务是否有压占相交,例子用于开发园区的三线压占分析,features:是传过来的要素集json,例子:var gg = {features:{'geometryType':'esriGeometryPolygon','features':[attributes:{},geometry],[]}}(有局限性:字符串太长会导致请求不成功,或者利用请求本地json文件方法,或者是请求接口方法来获取json数据)"); result.AddString("yzAnalysisFW接口", "(服务与服务之间)(优化)用于服务查询多个features与另一个服务是否有压占相交,主要用于开发园区的三线压占分析,例子:serverUrl:http://19.15.73.111/arcgisserver12/rest/services/KFYQ/KFQY_dissolve/MapServer, serverIds:1,2, where:'objectid=1', MapName:图层名"); return Encoding.UTF8.GetBytes(result.ToJson()); } private byte[] SampleOperHandler(NameValueCollection boundVariables, JsonObject operationInput, string outputFormat, string requestProperties, out string responseProperties) { responseProperties = null; string parm1Value; bool found = operationInput.TryGetString("parm1", out parm1Value); if (!found || string.IsNullOrEmpty(parm1Value)) throw new ArgumentNullException("parm1"); string parm2Value; found = operationInput.TryGetString("parm2", out parm2Value); if (!found || string.IsNullOrEmpty(parm2Value)) throw new ArgumentNullException("parm2"); JsonObject result = new JsonObject(); result.AddString("parm1", parm1Value); result.AddString("parm2", parm2Value); return Encoding.UTF8.GetBytes(result.ToJson()); } //shp private byte[] ExportToShp(NameValueCollection boundVariables, JsonObject operationInput, string outputFormat, string requestProperties, out string responseProperties) { responseProperties = null; string where; string exportPath; bool found1 = operationInput.TryGetString("exportPath", out exportPath); bool found2 = operationInput.TryGetString("where", out where); if (!found1 || null == exportPath) throw new ArgumentNullException("exportPath"); string res = ""; try { string filePath = exportPath; FileInfo pfileinfo = new FileInfo(filePath); string folder = pfileinfo.DirectoryName; string shapeName = pfileinfo.Name; if (!Directory.Exists(folder)) { Directory.CreateDirectory(folder); } // int index = filePath.LastIndexOf('\\'); // string folder = filePath.Substring(0, index); // string shapeName = filePath.Substring(index + 1); IWorkspaceFactory pWSF = new ShapefileWorkspaceFactoryClass(); IFeatureWorkspace pFWS = (IFeatureWorkspace)pWSF.OpenFromFile(folder, 0); //定义坐标系 IGeoDataset pGeods = this.m_FeatureClass as IGeoDataset; ISpatialReferenceFactory pSRF = new SpatialReferenceEnvironmentClass(); //ISpatialReference pSpatialReference = pSRF.CreateGeographicCoordinateSystem(4490); ISpatialReference pSpatialReference = pGeods.SpatialReference; //创建字段编辑所需要的接口 IFields pFields = new FieldsClass(); IFieldsEdit pFieldsEdit = pFields as IFieldsEdit; //给字段属性、类型赋值 IField pField = new FieldClass(); IFieldEdit pFieldEdit = (IFieldEdit)pField; pFieldEdit.Name_2 = "Shape"; pFieldEdit.Type_2 = esriFieldType.esriFieldTypeGeometry; IGeometryDef pGeometryDef = new GeometryDefClass(); IGeometryDefEdit pGDefEdit = (IGeometryDefEdit)pGeometryDef; pGDefEdit.GeometryType_2 = this.m_FeatureClass.ShapeType; //pGDefEdit.GeometryType_2 = esriGeometryType.esriGeometryPolygon; //pGDefEdit.GeometryType_2 = esriGeometryType.esriGeometryPolyline; //pGDefEdit.GeometryType_2 = esriGeometryType.esriGeometryPoint; pGDefEdit.SpatialReference_2 = pSpatialReference; //判断z值 var tempfea = this.m_FeatureClass.Search(null, false).NextFeature(); //if (pGeometryDef.HasZ) { // IZAware pZAware = (IZAware)tempfea.ShapeCopy; // pZAware.ZAware = true; // IZ iz1 = (IZ)tempfea; // iz1.SetConstantZ(0); //} //else //{ // IZAware pZAware = (IZAware)tempfea.ShapeCopy; // pZAware.ZAware = false; //} pFieldEdit.GeometryDef_2 = pGeometryDef; pFieldsEdit.AddField(pField); // 添加自定义字段 //pFieldsEdit.AddField(generateField("BSM", "标识码", esriFieldType.esriFieldTypeString, 18, false, true)); //pFieldsEdit.AddField(generateField("DLMC", "地类名称", esriFieldType.esriFieldTypeString, 18, false, true)); IFields tempfds = tempfea.Class.Fields; for (int j = 0; j <= tempfds.FieldCount - 1; j++) { if (tempfds.get_Field(j).AliasName == "SHAPE" || tempfds.get_Field(j).AliasName == "Shape" || tempfds.get_Field(j).Type == esriFieldType.esriFieldTypeOID) { } else { pFieldsEdit.AddField(generateField(tempfds.get_Field(j).Name, tempfds.get_Field(j).AliasName, tempfds.get_Field(j).Type, tempfds.get_Field(j).Length, tempfds.get_Field(j).IsNullable, tempfds.get_Field(j).Required)); } } IFeatureClass pFeatureClass; pFeatureClass = pFWS.CreateFeatureClass(shapeName, pFields, null, null, esriFeatureType.esriFTSimple, "Shape", ""); // 点 //IPoint pPoint = new PointClass(); //pPoint.X = 113.23; //pPoint.Y = 23.33; //IFeature pFeature = pFeatureClass.CreateFeature(); //pFeature.Shape = pPoint; //pFeature.Store(); // 面 ISpatialFilter spatialFilter = new SpatialFilterClass(); spatialFilter.WhereClause = where; IFeatureCursor fcursor = this.m_FeatureClass.Search(spatialFilter, false); IFeature pfea; while ((pfea = fcursor.NextFeature()) != null) { IFeature newFea = pFeatureClass.CreateFeature(); //判断z值 IZAware pZAware = (IZAware)pfea.Shape; if (this.m_FeatureClass.ShapeType.ToString() == "esriGeometryPolyline" && pZAware.ZAware) { pZAware.ZAware = false; } newFea.Shape = pfea.ShapeCopy; IFields pFds = pfea.Class.Fields; string tempkey; for (int j = 0; j <= pFds.FieldCount - 1; j++) { if (pFds.get_Field(j).AliasName == "SHAPE" || pFds.get_Field(j).AliasName == "Shape" || pFds.get_Field(j).AliasName == "FID") { } else { tempkey = pFds.get_Field(j).AliasName; if (tempkey.Length > 10) { tempkey = tempkey.Substring(0, 10); } if (newFea.Fields.FindField(tempkey) != -1) { newFea.set_Value(newFea.Fields.FindField(tempkey), pfea.get_Value(j)); } //newFea.set_Value(newFea.Fields.FindField(pFds.get_Field(j).AliasName), pfea.get_Value(j)); } } //newFea.set_Value(newFea.Fields.FindField("BSM"), pfea.get_Value(pfea.Fields.FindField("BSM"))); //newFea.set_Value(newFea.Fields.FindField("DLMC"), pfea.get_Value(pfea.Fields.FindField("DLMC"))); newFea.Store(); //string bsm = pfea.get_Value(pfea.Fields.FindField("BSM")).ToString(); } Marshal.ReleaseComObject(fcursor); res = "导出成功,已保存到路径" + filePath; } catch (Exception e) { res = "导出失败"; } JsonObject resultJson = new JsonObject(); resultJson.AddString("shp导出结果:", res); byte[] result = Encoding.UTF8.GetBytes(resultJson.ToJson()); return result; } private byte[] ExportToShp1(NameValueCollection boundVariables, JsonObject operationInput, string outputFormat, string requestProperties, out string responseProperties) { responseProperties = null; string where; string exportPath; bool found1 = operationInput.TryGetString("exportPath", out exportPath); bool found2 = operationInput.TryGetString("where", out where); if (!found1 || null == exportPath) throw new ArgumentNullException("exportPath"); string res = ""; string filePath = exportPath; FileInfo pfileinfo = new FileInfo(filePath); string folder = pfileinfo.DirectoryName; string shapeName = pfileinfo.Name; if (!Directory.Exists(folder)) { Directory.CreateDirectory(folder); } IQueryFilter pQueryFilter = new QueryFilterClass(); pQueryFilter.WhereClause = where; bool tempbol = ExportShp(this.m_FeatureClass, pQueryFilter, filePath); if (tempbol) { res = "导出成功,已保存到路径" + filePath; } else { res = "导出失败"; } JsonObject resultJson = new JsonObject(); resultJson.AddString("shp导出结果:", res); byte[] result = Encoding.UTF8.GetBytes(resultJson.ToJson()); return result; } // 导出要素类shp private bool ExportShp(IFeatureClass pSourceFeatureClass, IQueryFilter pQueryFilter, string filePath) { // 源数据工作空间(GDB) IDataset pSourceDataset = pSourceFeatureClass as IDataset; IFeatureClassName pSourceFeatureClassName = pSourceDataset.FullName as IFeatureClassName; IWorkspace pSourceWorkspace = pSourceDataset.Workspace; // 目标数据工作空间(SHP) IWorkspaceFactory pTargetWorkspaceFactory = new ShapefileWorkspaceFactory(); IWorkspace pTargetWorkspace = pTargetWorkspaceFactory.OpenFromFile(System.IO.Path.GetDirectoryName(filePath), 0); IDataset pTargetDataSet = pTargetWorkspace as IDataset; // 设置目标数据属性 IWorkspaceName pTargetWorkspaceName = pTargetDataSet.FullName as IWorkspaceName; IFeatureClassName pTargetFeatureClassName = new FeatureClassName() as IFeatureClassName; IDatasetName pTargetDatasetName = pTargetFeatureClassName as IDatasetName; pTargetDatasetName.WorkspaceName = pTargetWorkspaceName; pTargetDatasetName.Name = System.IO.Path.GetFileName(filePath); // 检查字段 IFieldChecker pFieldChecker = new FieldChecker(); pFieldChecker.InputWorkspace = pSourceWorkspace; pFieldChecker.ValidateWorkspace = pTargetWorkspace; // 字段转换 IFields pSourceFields = pSourceFeatureClass.Fields; IFields pTargetFields = null; IEnumFieldError pEnumFieldError = null; pFieldChecker.Validate(pSourceFields, out pEnumFieldError, out pTargetFields); // 数据转换 IFeatureDataConverter pFeatureDataConverter = new FeatureDataConverter(); try { pFeatureDataConverter.ConvertFeatureClass(pSourceFeatureClassName, pQueryFilter, null, pTargetFeatureClassName, null, pTargetFields, "", 1000, 0); return true; } catch { return false; } } //GP-导出shp private bool GPExportShp(IFeatureClass pSourceFeatureClass, string filePath) { Geoprocessor gp = new Geoprocessor(); gp.OverwriteOutput = true; ESRI.ArcGIS.ConversionTools.FeatureClassToShapefile covertToshp = new ESRI.ArcGIS.ConversionTools.FeatureClassToShapefile(); covertToshp.Input_Features = pSourceFeatureClass; covertToshp.Output_Folder = filePath; try { gp.Execute(covertToshp, null); return true; } catch { return false; } } private byte[] JsonExportToShp(NameValueCollection boundVariables, JsonObject operationInput, string outputFormat, string requestProperties, out string responseProperties) { responseProperties = null; JsonObject features; string exportPath; bool found1 = operationInput.TryGetString("exportPath", out exportPath); bool found2 = operationInput.TryGetJsonObject("features", out features); if (!found1 || null == exportPath) throw new ArgumentNullException("exportPath"); if (!found2 || null == features) throw new ArgumentNullException("features"); string res = ""; try { //解析features Dictionary<string, string> feaDict = new Dictionary<string, string>(); string jsonString = features.ToJson(); JObject job = JObject.Parse(jsonString); JArray jarfeatures = JArray.Parse(job["features"].ToString()); JArray jarfields = JArray.Parse(job["fields"].ToString()); string filePath = exportPath; FileInfo pfileinfo = new FileInfo(filePath); string folder = pfileinfo.DirectoryName; string shapeName = pfileinfo.Name; if (!Directory.Exists(folder)) { Directory.CreateDirectory(folder); } IWorkspaceFactory pWSF = new ShapefileWorkspaceFactoryClass(); IFeatureWorkspace pFWS = (IFeatureWorkspace)pWSF.OpenFromFile(folder, 0); //创建字段编辑所需要的接口 IFields pFields = new FieldsClass(); IFieldsEdit pFieldsEdit = pFields as IFieldsEdit; //给字段属性、类型赋值 IField pField = new FieldClass(); IFieldEdit pFieldEdit = (IFieldEdit)pField; pFieldEdit.Name_2 = "Shape"; pFieldEdit.Type_2 = esriFieldType.esriFieldTypeGeometry; IGeometryDef pGeometryDef = new GeometryDefClass(); IGeometryDefEdit pGDefEdit = (IGeometryDefEdit)pGeometryDef; var tempGeometryType = esriGeometryType.esriGeometryPolygon; pGDefEdit.GeometryType_2 = esriGeometryType.esriGeometryPolygon; if (job["geometryType"].ToString().ToLower().IndexOf("polyline") >= 0) { pGDefEdit.GeometryType_2 = esriGeometryType.esriGeometryPolyline; tempGeometryType = esriGeometryType.esriGeometryPolyline; } else if (job["geometryType"].ToString().ToLower().IndexOf("point") >= 0) { pGDefEdit.GeometryType_2 = esriGeometryType.esriGeometryPoint; tempGeometryType = esriGeometryType.esriGeometryPoint; } //定义坐标系 ISpatialReferenceFactory pSRF = new SpatialReferenceEnvironmentClass(); ISpatialReference pSpatialReference = pSRF.CreateGeographicCoordinateSystem(4490); if (JObject.Parse(job["spatialReference"].ToString())["wkid"].ToString() != null) { pSpatialReference = pSRF.CreateGeographicCoordinateSystem(Convert.ToInt32(JObject.Parse(job["spatialReference"].ToString())["wkid"])); } pGDefEdit.SpatialReference_2 = pSpatialReference; pFieldEdit.GeometryDef_2 = pGeometryDef; pFieldsEdit.AddField(pField); // 添加自定义字段 foreach (var item in jarfields) { pFieldsEdit.AddField(generateField(item["name"].ToString(), item["alias"].ToString(), (item["type"].ToString() == "esriFieldTypeString" ? esriFieldType.esriFieldTypeString : (item["type"].ToString() == "esriFieldTypeDouble" ? esriFieldType.esriFieldTypeDouble : esriFieldType.esriFieldTypeInteger)), (item["length"] != null ? Convert.ToInt32(item["length"].ToString()) : 50), false, true)); } //pFieldsEdit.AddField(generateField("BSM", "标识码", esriFieldType.esriFieldTypeString, 18, false, true)); IFeatureClass pFeatureClass; pFeatureClass = pFWS.CreateFeatureClass(shapeName, pFields, null, null, esriFeatureType.esriFTSimple, "Shape", ""); //添加要素 foreach (var item in jarfeatures) { IFeature newFea = pFeatureClass.CreateFeature(); //几何geometry赋值 JSONReader reader = new JSONReader(); reader.ReadFromString(item["geometry"].ToString()); IJSONConverterGeometry converter = new JSONConverterGeometryClass(); IGeometry pgeometry = converter.ReadGeometry(reader, tempGeometryType, false, false); //IGeometry pgeometry = converter.ReadGeometry(reader, esriGeometryType.esriGeometryPolygon, false, false); newFea.Shape = pgeometry; //属性赋值 Dictionary<string, string> tempdic = new Dictionary<string, string>(); tempdic = item["attributes"].ToObject<Dictionary<string, string>>(); string tempkey; foreach (var item1 in tempdic) { tempkey = item1.Key; if (tempkey.Length > 10) { tempkey = tempkey.Substring(0, 10); } if (newFea.Fields.FindField(tempkey) != -1) { newFea.set_Value(newFea.Fields.FindField(tempkey), item1.Value); } //newFea.set_Value(newFea.Fields.FindField(item1.Key), item1.Value); } newFea.Store(); } //IPoint pPoint = new PointClass(); //pPoint.X = 113.23; //pPoint.Y = 23.33; //IFeature pFeature = pFeatureClass.CreateFeature(); //pFeature.Shape = pPoint; //pFeature.Store(); res = "导出成功,已保存到路径" + filePath; } catch (Exception e) { res = "导出失败"; } JsonObject resultJson = new JsonObject(); resultJson.AddString("导出结果:", res); byte[] result = Encoding.UTF8.GetBytes(resultJson.ToJson()); return result; } private byte[] yzAnalysis(NameValueCollection boundVariables, JsonObject operationInput, string outputFormat, string requestProperties, out string responseProperties) { responseProperties = null; JsonObject features; bool found = operationInput.TryGetJsonObject("features", out features); if (!found) throw new ArgumentNullException("features"); Dictionary<string, string> feaDict = new Dictionary<string, string>(); string jsonString = features.ToJson(); JObject job = JObject.Parse(jsonString); JArray jar = JArray.Parse(job["features"].ToString()); List<JsonObject> pJoList = new List<JsonObject>(); JavaScriptSerializer Serializer = new JavaScriptSerializer(); var tempGeometryType = esriGeometryType.esriGeometryPolygon; if (job["geometryType"].ToString().ToLower().IndexOf("polyline") >= 0) { tempGeometryType = esriGeometryType.esriGeometryPolyline; } else if (job["geometryType"].ToString().ToLower().IndexOf("point") >= 0) { tempGeometryType = esriGeometryType.esriGeometryPoint; } foreach (var item in jar) { JSONReader reader = new JSONReader(); reader.ReadFromString(item["geometry"].ToString()); IJSONConverterGeometry converter = new JSONConverterGeometryClass(); IGeometry pgeometry = converter.ReadGeometry(reader, tempGeometryType, false, false); //IGeometry pgeometry = converter.ReadGeometry(reader, esriGeometryType.esriGeometryPolygon, false, false); ISpatialFilter sf = new SpatialFilterClass(); sf.Geometry = pgeometry; sf.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects; int temp = this.m_FeatureClass.FeatureCount(sf); if (temp > 0) { JsonObject tempJson1 = new JsonObject(); JsonObject jsonobj1 = new JsonObject(); Dictionary<string, string> tempdic = new Dictionary<string, string>(); tempdic = item["attributes"].ToObject<Dictionary<string, string>>(); foreach (var item1 in tempdic) { jsonobj1.AddString(item1.Key, item1.Value); } tempJson1.AddJsonObject("attributes", jsonobj1); tempJson1.AddJsonObject("geometry", Conversion.ToJsonObject(pgeometry)); pJoList.Add(tempJson1); } } JsonObject resultJson = new JsonObject(); resultJson.AddArray("features", pJoList.ToArray()); byte[] result = Encoding.UTF8.GetBytes(resultJson.ToJson()); return result; } private byte[] yzAnalysisFW(NameValueCollection boundVariables, JsonObject operationInput, string outputFormat, string requestProperties, out string responseProperties) { responseProperties = null; string serverUrl; string serverIds; string where; string MapName = "图层"; string servertype = "services"; bool found = operationInput.TryGetString("serverUrl", out serverUrl); bool found1 = operationInput.TryGetString("serverIds", out serverIds); bool found2 = operationInput.TryGetString("where", out where); bool found3 = operationInput.TryGetString("MapName", out MapName); if (!found) throw new ArgumentNullException("features"); if (!found1) throw new ArgumentNullException("serverIds"); string[] ids = serverIds.Split(','); //图层id 0,1.. var tempserver = serverUrl.Substring(0, serverUrl.IndexOf(servertype)) + servertype; var tempgg = serverUrl.Substring(serverUrl.IndexOf(servertype)); var tempindex = servertype.Length + 1; var servername = tempgg.Substring(tempindex, tempgg.Substring(tempindex).IndexOf("/MapServer")); List<IAGSServerObjectName> tempServerObjectName = GetMapServer("http://127.0.0.1:6080/arcgis/rest/services", servername, false); //List<IAGSServerObjectName> tempServerObjectName = GetMapServer(tempserver, servername, false); List<IFeature> pList = new List<IFeature>(); if (tempServerObjectName.Count > 0) { var pServerObjectName = tempServerObjectName[0]; //query.WhereClause = "1=1";//设置SQL语句 foreach (var i in ids) { IName pName = (IName)pServerObjectName; //访问地图服务 IAGSServerObject pServerObject = (IAGSServerObject)pName.Open(); IMapServer pMapServer = (IMapServer)pServerObject; int id = Convert.ToInt32(i); IRecordSet set = new RecordSet(); try { //查询 IQueryFilter qy = new QueryFilter(); set = pMapServer.QueryFeatureData(MapName, id, qy); ITable table = set.Table; IFeatureClass fc = table as IFeatureClass; if (found2) { qy.WhereClause = where; } IFeatureCursor cursor = fc.Search(qy, false); IFeature feature = null; ISpatialFilter sf = new SpatialFilterClass(); while ((feature = cursor.NextFeature()) != null) { //listFeature.Add(feature); //与本图层进行叠加 sf.Geometry = feature.ShapeCopy as IGeometry; sf.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects; int temp = this.m_FeatureClass.FeatureCount(sf); if (temp > 0) { pList.Add(feature); } } Marshal.ReleaseComObject(cursor); } catch { // listFeature = null;//当查询结果为空,即查询运算式出错时 } } } return GetResultJson(pList); } //点缓冲区分析 private byte[] PointBufferContain(NameValueCollection boundVariables, JsonObject operationInput, string outputFormat, string requestProperties, out string responseProperties) { responseProperties = null; string where; // long? index; double? BufferRadius; JsonObject geometry; bool found = operationInput.TryGetString("where", out where); bool found2 = operationInput.TryGetAsDouble("pRadius", out BufferRadius); bool found3 = operationInput.TryGetJsonObject("pgeometry", out geometry); if (!found3 || null == geometry) throw new ArgumentNullException("pgeometry"); if (!found2 || !BufferRadius.HasValue) throw new ArgumentNullException("BufferRadius"); //json转geometry JSONReader reader = new JSONReader(); reader.ReadFromString(geometry.ToJson()); IJSONConverterGeometry converter = new JSONConverterGeometryClass(); IGeometry pGeometry = converter.ReadGeometry(reader, esriGeometryType.esriGeometryPoint, false, false); //index = int.Parse(type.Replace("'", "")); //IMapServer3 mapServer = (IMapServer3)serverObjectHelper.ServerObject; //IMapServerDataAccess dataAccess = (IMapServerDataAccess)mapServer; //var FeatureClass = (IFeatureClass)dataAccess.GetDataSource(mapServer.DefaultMapName, Convert.ToInt32(index)); ITopologicalOperator pTO = null; IGeometry pBufferGeo = null; pTO = pGeometry as ITopologicalOperator; pBufferGeo = pTO.Buffer(Convert.ToDouble(BufferRadius)); // pTO.Simplify(); ISpatialFilter sf = new SpatialFilterClass(); sf.WhereClause = where; sf.Geometry = pBufferGeo; sf.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects; sf.GeometryField = this.m_FeatureClass.ShapeFieldName; ISpatialReference sr = (this.m_FeatureClass as IGeoDataset).SpatialReference; sf.set_OutputSpatialReference(this.m_FeatureClass.ShapeFieldName, sr); IFeatureCursor pFCur = this.m_FeatureClass.Search(sf, false); IFeature pFea; List<IFeature> pJoList = new List<IFeature>(); while ((pFea = pFCur.NextFeature()) != null) { pJoList.Add(pFea); } Marshal.ReleaseComObject(pFCur); return GetResultJson(pJoList); } //面缓冲区分析 private byte[] PolygonBufferContain(NameValueCollection boundVariables, JsonObject operationInput, string outputFormat, string requestProperties, out string responseProperties) { responseProperties = null; string where; // long? index; double? BufferRadius; JsonObject geometry; bool found = operationInput.TryGetString("where", out where); bool found2 = operationInput.TryGetAsDouble("pRadius", out BufferRadius); bool found3 = operationInput.TryGetJsonObject("pgeometry", out geometry); if (!found3 || null == geometry) throw new ArgumentNullException("pgeometry"); if (!found2 || !BufferRadius.HasValue) throw new ArgumentNullException("BufferRadius"); //json转geometry JSONReader reader = new JSONReader(); reader.ReadFromString(geometry.ToJson()); IJSONConverterGeometry converter = new JSONConverterGeometryClass(); IGeometry pGeometry = converter.ReadGeometry(reader, esriGeometryType.esriGeometryPolygon, false, false); //index = int.Parse(type.Replace("'", "")); //IMapServer3 mapServer = (IMapServer3)serverObjectHelper.ServerObject; //IMapServerDataAccess dataAccess = (IMapServerDataAccess)mapServer; //var FeatureClass = (IFeatureClass)dataAccess.GetDataSource(mapServer.DefaultMapName, Convert.ToInt32(index)); ITopologicalOperator pTO = null; IGeometry pBufferGeo = null; pTO = pGeometry as ITopologicalOperator; pBufferGeo = pTO.Buffer(Convert.ToDouble(BufferRadius)); // pTO.Simplify(); ISpatialFilter sf = new SpatialFilterClass(); sf.WhereClause = where; sf.Geometry = pBufferGeo; sf.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects; sf.GeometryField = this.m_FeatureClass.ShapeFieldName; ISpatialReference sr = (this.m_FeatureClass as IGeoDataset).SpatialReference; sf.set_OutputSpatialReference(this.m_FeatureClass.ShapeFieldName, sr); IFeatureCursor pFCur = this.m_FeatureClass.Search(sf, false); IFeature pFea; List<IFeature> pJoList = new List<IFeature>(); List<JsonObject> pJoList1 = new List<JsonObject>(); JsonObject tempj = new JsonObject(); tempj.AddJsonObject("geometry", Conversion.ToJsonObject(pBufferGeo)); tempj.AddString("mc", "buf"); pJoList1.Add(tempj); while ((pFea = pFCur.NextFeature()) != null) { //pJoList.Add(pFea); JsonObject tempJson = new JsonObject(); tempJson.AddJsonObject("geometry", Conversion.ToJsonObject(pFea.ShapeCopy)); pJoList1.Add(tempJson); } Marshal.ReleaseComObject(pFCur); //return GetResultJson(pJoList); JsonObject resultJson = new JsonObject(); resultJson.AddArray("feature", pJoList1.ToArray()); byte[] result = Encoding.UTF8.GetBytes(resultJson.ToJson()); return result; } //线缓冲区分析 GP private byte[] PolylineBufferContain(NameValueCollection boundVariables, JsonObject operationInput, string outputFormat, string requestProperties, out string responseProperties) { responseProperties = null; string where; // long? index; double? BufferRadius; JsonObject geometry; bool found = operationInput.TryGetString("where", out where); bool found2 = operationInput.TryGetAsDouble("pRadius", out BufferRadius); bool found3 = operationInput.TryGetJsonObject("pgeometry", out geometry); if (!found3 || null == geometry) throw new ArgumentNullException("pgeometry"); if (!found2 || !BufferRadius.HasValue) throw new ArgumentNullException("BufferRadius"); //json转geometry JSONReader reader = new JSONReader(); reader.ReadFromString(geometry.ToJson()); IJSONConverterGeometry converter = new JSONConverterGeometryClass(); IGeometry pGeometry = converter.ReadGeometry(reader, esriGeometryType.esriGeometryPolyline, false, false); //chaungjiang IFeatureWorkspace pWs = null; IFeatureClass tempclass = null; try { string filePath = "E://tempshp//temp.gdb"; FileInfo pfileinfo = new FileInfo(filePath); string folder = pfileinfo.DirectoryName; string shapeName = pfileinfo.Name; shapeName = "templine"; if (!Directory.Exists(folder)) { //Directory.CreateDirectory(folder); IWorkspaceFactory pWsFac = new FileGDBWorkspaceFactoryClass(); var workspace_name_gdb = pWsFac.Create("E://tempshp//", "temp.gdb", null, 0); pWs = pWsFac.Open(workspace_name_gdb.ConnectionProperties, 0) as IFeatureWorkspace; //定义坐标系 IGeoDataset pGeods = this.m_FeatureClass as IGeoDataset; ISpatialReferenceFactory pSRF = new SpatialReferenceEnvironmentClass(); //ISpatialReference pSpatialReference = pSRF.CreateGeographicCoordinateSystem(4490); ISpatialReference pSpatialReference = pGeods.SpatialReference; //创建字段编辑所需要的接口 IFields pFields = new FieldsClass(); IFieldsEdit pFieldsEdit = pFields as IFieldsEdit; //给字段属性、类型赋值 IField pField = new FieldClass(); IFieldEdit pFieldEdit = (IFieldEdit)pField; pFieldEdit.Name_2 = "Shape"; pFieldEdit.Type_2 = esriFieldType.esriFieldTypeGeometry; IGeometryDef pGeometryDef = new GeometryDefClass(); IGeometryDefEdit pGDefEdit = (IGeometryDefEdit)pGeometryDef; //pGDefEdit.GeometryType_2 = this.m_FeatureClass.ShapeType; pGDefEdit.GeometryType_2 = esriGeometryType.esriGeometryPolyline; pGDefEdit.SpatialReference_2 = pSpatialReference; pFieldEdit.GeometryDef_2 = pGeometryDef; pFieldsEdit.AddField(pField); tempclass = pWs.CreateFeatureClass(shapeName, pFields, null, null, esriFeatureType.esriFTSimple, "Shape", ""); IFeature tempf = tempclass.CreateFeature(); tempf.Shape = pGeometry; tempf.Store(); } else { IWorkspaceFactory pWsFac = new FileGDBWorkspaceFactoryClass(); pWs = (IFeatureWorkspace)pWsFac.OpenFromFile(filePath, 0); tempclass = pWs.OpenFeatureClass(shapeName); //删除要素 IQueryFilter pQueryFilter = new QueryFilterClass(); IFeatureCursor pFeatureCursor = tempclass.Search(pQueryFilter, false); IFeature pFeature = pFeatureCursor.NextFeature(); while (pFeature != null) { pFeature.Delete(); pFeature = pFeatureCursor.NextFeature(); } Marshal.ReleaseComObject(pFeatureCursor); //添加要素 IFeature tempf = tempclass.CreateFeature(); tempf.Shape = pGeometry; tempf.Store(); } } catch (Exception e) { } Geoprocessor gp = new Geoprocessor(); gp.OverwriteOutput = true; ESRI.ArcGIS.AnalysisTools.Buffer buffer = new ESRI.ArcGIS.AnalysisTools.Buffer(tempclass, "E://tempshp//temp.gdb//plinebuff", BufferRadius + " " + "Meters"); //ESRI.ArcGIS.AnalysisTools.Buffer buffer = new ESRI.ArcGIS.AnalysisTools.Buffer(layer, this.OutputPath, "100"+" "+"Meters" ); buffer.dissolve_option = "ALL";//这个要设成ALL,否则相交部分不会融合 buffer.line_side = "FULL";//默认是"FULL",最好不要改否则出错 buffer.line_end_type = "ROUND";//默认是"ROUND",最好不要改否则出错 //execute the buffer tool (very easy :-)) IGeoProcessorResult results = null; IFeatureClass tempbuffclass = null; try { results = (IGeoProcessorResult)gp.Execute(buffer, null); string buffpath = results.ReturnValue.ToString(); //IWorkspaceFactory pWSF = new ShapefileWorkspaceFactoryClass(); //IFeatureWorkspace pFWS = (IFeatureWorkspace)pWSF.OpenFromFile(System.IO.Path.GetDirectoryName(buffpath), 0); //tempbuffclass = pFWS.OpenFeatureClass(System.IO.Path.GetFileName(buffpath)); tempbuffclass = pWs.OpenFeatureClass("plinebuff"); } catch (Exception ex) { } IGeometry pBufferGeo = null; if (tempbuffclass != null) { pBufferGeo = tempbuffclass.Search(null, false).NextFeature().ShapeCopy; } ISpatialFilter sf = new SpatialFilterClass(); sf.WhereClause = where; sf.Geometry = pBufferGeo; sf.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects; sf.GeometryField = this.m_FeatureClass.ShapeFieldName; ISpatialReference sr = (this.m_FeatureClass as IGeoDataset).SpatialReference; sf.set_OutputSpatialReference(this.m_FeatureClass.ShapeFieldName, sr); IFeatureCursor pFCur = this.m_FeatureClass.Search(sf, false); IFeature pFea; List<IFeature> pJoList = new List<IFeature>(); List<JsonObject> pJoList1 = new List<JsonObject>(); JsonObject tempj = new JsonObject(); tempj.AddJsonObject("geometry", Conversion.ToJsonObject(pBufferGeo)); tempj.AddString("mc", "buf"); pJoList1.Add(tempj); while ((pFea = pFCur.NextFeature()) != null) { //pJoList.Add(pFea); JsonObject tempJson = new JsonObject(); tempJson.AddJsonObject("geometry", Conversion.ToJsonObject(pFea.ShapeCopy)); pJoList1.Add(tempJson); } Marshal.ReleaseComObject(pFCur); //return GetResultJson(pJoList); JsonObject resultJson = new JsonObject(); resultJson.AddArray("feature", pJoList1.ToArray()); byte[] result = Encoding.UTF8.GetBytes(resultJson.ToJson()); return result; } //获取服务 public List<IAGSServerObjectName> GetMapServer(string pHostOrUrl, string pServiceName, bool pIsLAN) { List<IAGSServerObjectName> ListServerObjectName = new List<IAGSServerObjectName>(); string[] pServiceNameArr = pServiceName.Split(';'); //设置连接属性 IPropertySet pPropertySet = new PropertySetClass(); if (pIsLAN) pPropertySet.SetProperty("machine", pHostOrUrl); else pPropertySet.SetProperty("url", pHostOrUrl); //打开连接 IAGSServerConnectionFactory pFactory = new AGSServerConnectionFactory(); //Type factoryType = Type.GetTypeFromProgID( // "esriGISClient.AGSServerConnectionFactory"); //IAGSServerConnectionFactory agsFactory = (IAGSServerConnectionFactory) // Activator.CreateInstance(factoryType); IAGSServerConnection pConnection = pFactory.Open(pPropertySet, 0); //Get the image server. IAGSEnumServerObjectName pServerObjectNames = pConnection.ServerObjectNames; pServerObjectNames.Reset(); IAGSServerObjectName ServerObjectName = pServerObjectNames.Next(); while (ServerObjectName != null) { if (pServiceNameArr.Contains(ServerObjectName.Name) && (ServerObjectName.Type == "MapServer")) { ListServerObjectName.Add(ServerObjectName); break; } //if ((ServerObjectName.Name.ToLower() == pServiceName.ToLower()) && // (ServerObjectName.Type == "MapServer")) //{ // ListServerObjectName.Add(ServerObjectName); // //break; //} ServerObjectName = pServerObjectNames.Next(); } Marshal.ReleaseComObject(pFactory); //返回对象 return ListServerObjectName; } //字段设置 //创建字段 private static IField generateField(string name, string alias, esriFieldType type, int length, bool nullable, bool required) { IField field = new FieldClass(); IFieldEdit fieldEdit = field as IFieldEdit; fieldEdit.Name_2 = name; fieldEdit.AliasName_2 = alias; fieldEdit.Type_2 = type; switch (type) { case esriFieldType.esriFieldTypeBlob: fieldEdit.Length_2 = length; break; case esriFieldType.esriFieldTypeDate: break; case esriFieldType.esriFieldTypeDouble: fieldEdit.Precision_2 = length; fieldEdit.Scale_2 = 2; break; case esriFieldType.esriFieldTypeGUID: break; case esriFieldType.esriFieldTypeGeometry: break; case esriFieldType.esriFieldTypeGlobalID: break; case esriFieldType.esriFieldTypeInteger: fieldEdit.Precision_2 = length; break; case esriFieldType.esriFieldTypeOID: break; case esriFieldType.esriFieldTypeRaster: break; case esriFieldType.esriFieldTypeSingle: fieldEdit.Precision_2 = length; fieldEdit.Scale_2 = 2; break; case esriFieldType.esriFieldTypeSmallInteger: fieldEdit.Precision_2 = length; break; case esriFieldType.esriFieldTypeString: fieldEdit.Length_2 = length; break; case esriFieldType.esriFieldTypeXML: fieldEdit.Length_2 = length; break; default: break; } fieldEdit.IsNullable_2 = nullable; fieldEdit.Required_2 = required; return field; } //返回geojson数据 private byte[] GetResultGeoJson(List<IFeature> pList) { List<JsonObject> pJoList = null; if (pList != null) { IFeature pfea = null; pJoList = new List<JsonObject>(); string fieldvalue; for (int i = 0; i < pList.Count; i++) { if (i == 10000) break; JsonObject tempJson = new JsonObject(); pfea = pList[i]; //List<JsonObject> tempJoList = new List<JsonObject>(); //tempJoList.Add(Conversion.ToJsonObject(pfea.ShapeCopy)); var geo = Conversion.ToJsonObject(pfea.ShapeCopy); Dictionary<string, object> geoDict = new Dictionary<string, object>(); JavaScriptSerializer Serializer = new JavaScriptSerializer(); //json字符串转为对象, 反序列化 geoDict = Serializer.Deserialize<Dictionary<string, object>>(geo.ToJson()); JsonObject geojsonobj = new JsonObject(); object coordinates = geoDict["rings"]; geojsonobj.AddString("type", "Polygon"); geojsonobj.AddObject("coordinates", coordinates); tempJson.AddJsonObject("geometry", geojsonobj); //tempJson.AddJsonObject("geometry", Conversion.ToJsonObject(pfea.ShapeCopy)); //tempJoList = null; //tempJoList = new List<JsonObject>(); IFields pFields = pfea.Class.Fields; JsonObject jsonobj = new JsonObject(); for (int j = 0; j <= pFields.FieldCount - 1; j++) { fieldvalue = pfea.get_Value(j) == null ? "" : pfea.get_Value(j).ToString(); if (pFields.get_Field(j).AliasName == "SHAPE" || pFields.get_Field(j).AliasName == "Shape") { fieldvalue = pfea.ShapeCopy.GeometryType.ToString(); } jsonobj.AddString(pFields.get_Field(j).AliasName, fieldvalue); //tempJoList.Add(jsonobj); } IPoint centerPoint = new PointClass();//获得要素的中心点 IArea pArea = pfea.Shape as IArea; pArea.QueryCentroid(centerPoint); jsonobj.AddString("centroid", centerPoint.X + "," + centerPoint.Y); tempJson.AddJsonObject("properties", jsonobj); tempJson.AddString("type", "Feature"); pJoList.Add(tempJson); } } JsonObject resultJson = new JsonObject(); resultJson.AddString("type", "FeatureCollection"); resultJson.AddArray("features", pJoList.ToArray()); byte[] result = Encoding.UTF8.GetBytes(resultJson.ToJson()); return result; } //返回json数据 private byte[] GetResultJson(List<IFeature> pList) { List<JsonObject> pJoList = null; if (pList != null) { IFeature pfea = null; pJoList = new List<JsonObject>(); string fieldvalue; for (int i = 0; i < pList.Count; i++) { if (i == 10000) break; JsonObject tempJson = new JsonObject(); pfea = pList[i]; //List<JsonObject> tempJoList = new List<JsonObject>(); //tempJoList.Add(Conversion.ToJsonObject(pfea.ShapeCopy)); tempJson.AddJsonObject("geometry", Conversion.ToJsonObject(pfea.ShapeCopy)); //tempJoList = null; //tempJoList = new List<JsonObject>(); IFields pFields = pfea.Class.Fields; JsonObject jsonobj = new JsonObject(); for (int j = 0; j <= pFields.FieldCount - 1; j++) { fieldvalue = pfea.get_Value(j) == null ? "" : pfea.get_Value(j).ToString(); if (pFields.get_Field(j).AliasName == "SHAPE" || pFields.get_Field(j).AliasName == "Shape") { fieldvalue = pfea.ShapeCopy.GeometryType.ToString(); } jsonobj.AddString(pFields.get_Field(j).AliasName, fieldvalue); //tempJoList.Add(jsonobj); } tempJson.AddJsonObject("attributes", jsonobj); pJoList.Add(tempJson); } } JsonObject resultJson = new JsonObject(); resultJson.AddArray("feature", pJoList.ToArray()); byte[] result = Encoding.UTF8.GetBytes(resultJson.ToJson()); return result; } } }
编译,重新生成后,找到.soe文件
打开自己部署好的arcgisserver :
http://127.0.0.1:6080/arcgis/manager
登录后,选择“站点”---->“拓展”---->“添加拓展”,如图
然后找到刚才生成的.soe文件,上传即可完成。
最后在需要的服务的“功能”勾选上所对应的拓展即可,“保存并重新启动”,服务的拓展就完成。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律