public JsonObject ToJsonObject() { byte[] jsonBytes = Conversion.ToJson((IGeometry)this.Extent); JsonObject env = new JsonObject(Encoding.UTF8.GetString(jsonBytes)); JsonObject jo = new JsonObject(); jo.AddString("name", Name); jo.AddString("type", Type); jo.AddLong("id", ID); jo.AddString("description", Description); jo.AddJsonObject("extent", env); return jo; }
public JsonObject ToJsonObject() { JsonObject jo = new JsonObject(); jo.AddString("name", Name); jo.AddLong("id", ID); return jo; }
public JsonObject ToJsonObject() { JsonObject result = new JsonObject(); result.AddString("name", Name); result.AddLong("id", ID); IRasterProps props = Raster as IRasterProps; result.AddLong("rows", props.Width); result.AddLong("columns", props.Height); result.AddJsonObject("extent", Conversion.ToJsonObject(props.Extent)); return result; }
private byte[] RootResHandler(NameValueCollection boundVariables, string outputFormat, string requestProperties, out string responseProperties) { responseProperties = null; JsonObject infoJSON = new JsonObject(); infoJSON.AddString("name", ".Net Edit Features REST SOE"); infoJSON.AddString("description", "This SOE adds and edits features to a selected layer in the host map service. " + "Note that this SOE is not designed to work with map services that have features stored in SDC data format." + " The \"layers\" subresource returns all layers in the map service." + " The \"editFeature\" operation allows editing an existing feature in the layer indicated by this SOE's layerId property.\n" + " The \"addFeatures\" operation allows addition of a new feature to the layer indicated by this SOE's layerId property.\n" + " The acceptableSchema JSON below indicates the correct schema that could be used to add/edit features. This schema belongs to the layer " + "selected for editing by the ArcGIS Server administrator via the SOE's layerId property. This property's value can be " + "modified using ArcGIS Manager."); // validation - ensure user has provided right layer id property value. if (this.layerId > this.layerInfos.Count - 1) { return createErrorObject(406, "Layer Id " + this.layerId + " is invalid.", new String[] { "Acceptable layer ids are between 0 and " + (layerInfos.Count - 1) + ".", "Also ensure that the id points to a feature layer." }); } // inform the user that edits can be done only on feature layers, if no // feature layer corresponds to user-provided layerId if (this.editLayerInfo == null) { this.editLayerInfo = this.layerInfos.get_Element(this.layerId); if (!this.editLayerInfo.IsFeatureLayer) { return createErrorObject( 403, "The layerId property of this SOE currently points to a layer (id: " + this.layerId + ") that is not a feature layer.", new String[] { "Only feature layers can be edited by this SOE.", "Modify SOE's layerId property using ArcGIS Manager or ArcGIS Desktop's Service Editor." }); } } // Grab the fc powering the layer if its null, which means it did not get initialized in construct(), thereby // suggesting that the layerId property value is incorrect. if (this.fc == null) { // The down side of grabbing fc here is // that a new instance of fc is created once for every request. // Can't create fc in init(), since layerId property value for a // particular service is not necessarily available always when init() is invoked. this.fc = (IFeatureClass) this.mapServerDataAccess.GetDataSource(this.mapServerInfo.Name, this.layerId); if (this.fc == null) { // if its still null, return error return createErrorObject( 406, "Incorrect layer id provided.", new String[] { "Please provide layer id of a feature layer." }); } } infoJSON.AddString("Layer selected for editing", editLayerInfo.Name.ToString() + " (" + layerId + ")"); JsonObject schemaJSON = getSchemaJSON(); infoJSON.AddObject("acceptableSchema", schemaJSON); return Encoding.UTF8.GetBytes(infoJSON.ToJson()); }
private JsonObject GetErrorResponse(string message) { var error = new JsonObject(); error.AddLong("code", 0); error.AddString("message", message); var response = new JsonObject(); response.AddJsonObject("error", error); return response; }
private byte[] editFeatureOperHandler(NameValueCollection boundVariables, JsonObject operationInput, string outputFormat, string requestProperties, out string responseProperties) { responseProperties = null; // get the id of the feature to be edited object featureIdObj; operationInput.TryGetObject("featureId", out featureIdObj); int updateFeatureId = Convert.ToInt32(featureIdObj.ToString()); object featureJSONObj; operationInput.TryGetObject("featureJSON", out featureJSONObj); JsonObject updateFeatureJSON = (JsonObject)featureJSONObj; // set a filter for the specific feature QueryFilter queryFilter = new QueryFilter(); if (this.fc == null) { return(createErrorObject( 406, "Incorrect layer id provided.", new String[] { "Please provide layer id of a feature layer." })); } IClass myClass = (IClass)this.fc; queryFilter.WhereClause = myClass.OIDFieldName + "=" + updateFeatureId; IFeatureCursor featureCursor = this.fc.Search(queryFilter, false); // attempt retrieval of the feature and check if it does exist IFeatureCursor myFeatureCursor = (IFeatureCursor)featureCursor; IFeature updateFeature = myFeatureCursor.NextFeature(); if (updateFeature == null) { return(createErrorObject( 406, "Incorrect feature id provided.", new String[] { "No feature exists for feature id " + updateFeatureId + "." })); } JsonObject response = new JsonObject(); // edit feature string result = System.Text.Encoding.GetEncoding("utf-8").GetString(performEdits(updateFeature, updateFeatureJSON)); featureCursor.Flush(); if (result.Equals(System.Boolean.TrueString)) { response.AddString("status", "success"); response.AddString("message", "Feature " + updateFeatureId + " updated"); } else { response.AddString("status", "failure"); response.AddString("message", result); } // send response back to client app return(Encoding.UTF8.GetBytes(response.ToJson())); }
private byte[] PropertiesResHandler(NameValueCollection boundVariables, string outputFormat, string requestProperties, out string responseProperties) { responseProperties = "{\"Content-Type\" : \"application/json\"}"; JsonObject result = new JsonObject(); result.AddString("layers", this.layerType); result.AddString("returnFormat", this.returnFormat); result.AddLong("maxNumFeatures", this.maxNumFeatures); result.AddBoolean("isEditable", this.isEditable); return Encoding.UTF8.GetBytes(result.ToJson()); }
/// <summary> /// Returns JSON representation of Help resource. This resource is not a collection. /// </summary> /// <param name="boundVariables">list of variables bound</param> /// <param name="outputFormat">format of output</param> /// <param name="requestProperties">list of request properties</param> /// <param name="responseProperties">list of response properties </param> /// <returns>String JSON representation of Help resource.</returns> private byte[] HelpResHandler(NameValueCollection boundVariables, string outputFormat, string requestProperties, out string responseProperties) { responseProperties = "{\"Content-Type\" : \"application/json\"}"; JsonObject result = new JsonObject(); JsonObject soeResources = new JsonObject(); soeResources.AddString("RouteLayers", "A list of polylineM layers in the map."); result.AddJsonObject("Resources", soeResources); JsonObject getIdentifyRouteInputs = new JsonObject(); getIdentifyRouteInputs.AddString("location", "(geometry) Point"); getIdentifyRouteInputs.AddString("tolerance", "(number) optional but if you don't set, soe set 0 so you could no have results"); getIdentifyRouteInputs.AddString("routeMeasureUnit", "(enum) optional default is esriUnknownUnits"); getIdentifyRouteInputs.AddString("routeIDFieldName", "(string)"); JsonObject getIdentifyRouteOutput = new JsonObject(); JsonObject getIdentifyRouteOutputLoc = new JsonObject(); getIdentifyRouteOutputLoc.AddString("routeID", "(string, double, int) depends fieldtype routeIDFieldName"); getIdentifyRouteOutputLoc.AddString("measure", "(number)"); getIdentifyRouteOutput.AddArray("location (array)", new JsonObject[] { getIdentifyRouteOutputLoc }); JsonObject getIdentifyRouteParams = new JsonObject(); getIdentifyRouteParams.AddString("Info", "Identify Route operation. To learn more about formatting the input geometries, input geometry, please visit the 'Geometry Objects' section of the ArcGIS Server REST documentation."); getIdentifyRouteParams.AddJsonObject("Inputs", getIdentifyRouteInputs); getIdentifyRouteParams.AddJsonObject("Outputs", getIdentifyRouteOutput); JsonObject getPointLocationInputs = new JsonObject(); getPointLocationInputs.AddString("routeIDFieldName", "(string)"); getPointLocationInputs.AddString("routeID", "(string, double, int) depends fieldtype routeIDFieldName"); getPointLocationInputs.AddString("measure", "(number)"); getPointLocationInputs.AddString("lateralOffset", "(number) optional default = 0"); getPointLocationInputs.AddString("routeMeasureUnit", "(enum) optional default = esriUnknownUnits"); getPointLocationInputs.AddString("routeLocationMeasureUnit", "(enum) optional default = esriUnknownUnits"); JsonObject getPointLocationOutput = new JsonObject(); getPointLocationOutput.AddString("geometries", "(geometry) point or multipoint"); JsonObject getPointLocationParams = new JsonObject(); getPointLocationParams.AddString("Info", "Point Location operation."); getPointLocationParams.AddJsonObject("Inputs", getPointLocationInputs); getPointLocationParams.AddJsonObject("Outputs", getPointLocationOutput); JsonObject getLineLocationInputs = new JsonObject(); getLineLocationInputs.AddString("routeIDFieldName", "(string)"); getLineLocationInputs.AddString("routeID", "(string, double, int) depends fieldtype routeIDFieldName"); getLineLocationInputs.AddString("fromMeasure", "(number) optional if you set toMeasure"); getLineLocationInputs.AddString("toMeasure", "(number) optional if you set fromMeasure"); getLineLocationInputs.AddString("lateralOffset", "(number) optional default = 0"); getLineLocationInputs.AddString("routeMeasureUnit", "(enum) optional default = esriUnknownUnits"); getLineLocationInputs.AddString("routeLocationMeasureUnit", "(enum) optional default = esriUnknownUnits"); JsonObject getLineLocationOutput = new JsonObject(); getLineLocationOutput.AddString("geometries", "(geometry) polyline"); JsonObject getLineLocationParams = new JsonObject(); getLineLocationParams.AddString("Info", "Line Location operation."); getLineLocationParams.AddJsonObject("Inputs", getLineLocationInputs); getLineLocationParams.AddJsonObject("Outputs", getLineLocationOutput); JsonObject getIdentifyRouteExInputs = new JsonObject(); getIdentifyRouteExInputs.AddString("location", "(geometry) Point"); getIdentifyRouteExInputs.AddString("routeID", "(string, double, int) depends fieldtype routeIDFieldName"); getIdentifyRouteExInputs.AddString("tolerance", "(number) optional but if you don't set, soe set 0 so you could no have results"); getIdentifyRouteExInputs.AddString("routeMeasureUnit", "(enum) optional default = esriUnknownUnits"); getIdentifyRouteExInputs.AddString("routeIDFieldName", "(string)"); getIdentifyRouteExInputs.AddString("segmentExtension", "(enum) optional default = esriNoExtension"); JsonObject getIdentifyRouteExOutput = new JsonObject(); JsonObject getIdentifyRouteExOutputLoc = new JsonObject(); getIdentifyRouteExOutputLoc.AddString("routeID", "(string, double, int) depends fieldtype routeIDFieldName"); getIdentifyRouteExOutputLoc.AddString("measure", "(number)"); getIdentifyRouteExOutputLoc.AddString("location", "(geometry) point"); getIdentifyRouteExOutput.AddArray("location (array)", new JsonObject[] { getIdentifyRouteExOutputLoc }); JsonObject getIdentifyRouteExParams = new JsonObject(); getIdentifyRouteExParams.AddString("Info", "Identify Route Ex operation. To learn more about formatting the input geometries, input geometry, please visit the 'Geometry Objects' section of the ArcGIS Server REST documentation."); getIdentifyRouteExParams.AddJsonObject("Inputs", getIdentifyRouteExInputs); getIdentifyRouteExParams.AddJsonObject("Outputs", getIdentifyRouteExOutput); JsonObject soeOperations = new JsonObject(); soeOperations.AddJsonObject("IdentifyRoute", getIdentifyRouteParams); soeOperations.AddJsonObject("PointLocation", getPointLocationParams); soeOperations.AddJsonObject("LineLocation", getLineLocationParams); soeOperations.AddJsonObject("IdentifyRouteEx", getIdentifyRouteExParams); result.AddJsonObject("Operations", soeOperations); return(result.JsonByte()); }
private byte[] RootResHandler(NameValueCollection boundVariables, string outputFormat, string requestProperties, out string responseProperties) { responseProperties = null; JsonObject result = new JsonObject(); result.AddString("hello", "world"); return Encoding.UTF8.GetBytes(result.ToJson()); }
/* *该方法通过纯粹的Arcobject的方式实现最大似然分类 * * * * */ private byte[] DoClassifyHandler(NameValueCollection boundVariables, JsonObject operationInput, string outputFormat, string requestProperties, out string responseProperties) { _logger.LogMessage(ServerLogger.msgType.infoDetailed, _soename + ".GetRasterStatistics", 8000, "request received"); if (!_supportRasterItemAccess) throw new ArgumentException("The image service does not have a catalog and does not support this operation"); responseProperties = null; long? objectID; long? classCount; //case insensitive bool found = operationInput.TryGetAsLong("objectID", out objectID); if (!found || (objectID == null)) throw new ArgumentNullException("ObjectID"); found = operationInput.TryGetAsLong("classnumber", out classCount); if (!found || (objectID == null)) throw new ArgumentNullException("classnumber"); IRasterCatalogItem rasterCatlogItem = null; try { rasterCatlogItem = _mosaicCatalog.GetFeature((int)objectID) as IRasterCatalogItem; if (rasterCatlogItem == null) { _logger.LogMessage(ServerLogger.msgType.infoDetailed, _soename + ".GetRasterStatistics", 8000, "request finished with exception"); throw new ArgumentException("The input ObjectID does not exist"); } } catch { _logger.LogMessage(ServerLogger.msgType.infoDetailed, _soename + ".GetRasterStatistics", 8000, "request finished with exception"); throw new ArgumentException("The input ObjectID does not exist"); } JsonObject result = new JsonObject(); string outputurl = ""; try { IRasterDataset pRasterDataSet = rasterCatlogItem.RasterDataset; IGeoDataset pGeo = pRasterDataSet as IGeoDataset; string inPath = @"D:\arcgisserver\directories\arcgisoutput\imageserver\test2_ImageServer"; string gsgname = System.DateTime.Now.ToString().Replace("/", "").Replace(":", "").Replace(" ", "") + ".gsg"; string gsgPath = System.IO.Path.Combine(inPath, gsgname); bool bcreatesignaturefile = Classify.CreateSignaturefile(pRasterDataSet, Convert.ToInt32(classCount), gsgPath); if (bcreatesignaturefile) { IMultivariateOp pMultivarateOp = new RasterMultivariateOpClass(); IGeoDataset pGeoDatasetResult = pMultivarateOp.MLClassify(pGeo, gsgPath, false, esriGeoAnalysisAPrioriEnum.esriGeoAnalysisAPrioriEqual, Type.Missing, Type.Missing); IEnvelope pEnvelp = new EnvelopeClass(); string outurl = "http://localhost:6080/arcgis/rest/directories/arcgisoutput/imageserver/test2_ImageServer/"; pEnvelp.PutCoords(116.56075474, 40.29407147, 116.63105347, 40.34514666); // string dd = ExportImage.ExportLayerImage((IRaster)pGeoDatasetResult, bbox, new string[] { "400", "400" }, outurl, fileDir); outputurl = ExportImage.CreateJPEGFromActiveView((IRaster)pGeoDatasetResult, pEnvelp, outurl, inPath); } } catch { } result.AddString("url", outputurl); return Encoding.UTF8.GetBytes(result.ToJson()); }
private byte[] NetworkTraceHandler(NameValueCollection boundVariables, JsonObject operationInput, string outputFormat, string requestProperties, out string responseProperties) { var watch = System.Diagnostics.Stopwatch.StartNew(); responseProperties = null; string traceTypeStr; bool found = operationInput.TryGetString(TracingDirParameterName, out traceTypeStr); if (!found || string.IsNullOrEmpty(traceTypeStr)) { throw new ArgumentNullException(TracingDirParameterName + " is required"); } traceTypeStr = traceTypeStr.ToUpper(); bool?isUpstream = null; if ("TRACE_UPSTREAM" == traceTypeStr) { isUpstream = true; } else if ("TRACE_DOWNSTREAM" == traceTypeStr) { isUpstream = false; } if (false == isUpstream.HasValue) { throw new ArgumentException("Not valid Trace_Task_type"); } long?outEPSG; found = operationInput.TryGetAsLong(OutputEPSGParameterName, out outEPSG); if (!found || !outEPSG.HasValue || outEPSG <= 0) { throw new ArgumentNullException(OutputEPSGParameterName + " is required"); } if (outEPSG < 1) { throw new ArgumentException(OutputEPSGParameterName + " is not valid"); } JsonObject flagJSON = null; object[] flagArray = null; JsonObject[] flagJsonArray = null; if (false == operationInput.TryGetJsonObject(FlagParameterName, out flagJSON) || null == flagJSON) { throw new ArgumentNullException(FlagParameterName + " is required"); } if (flagJSON.TryGetArray("features", out flagArray)) { try { flagJsonArray = flagArray.Cast <JsonObject>().ToArray(); } catch { throw new ArgumentException("invalid Flags json format"); } } //Found the flag List <int> ftrList = null; if (null != flagJsonArray && 1 == flagJsonArray.Length) { JsonObject flagFeature = null; if (flagJsonArray[0].TryGetJsonObject("geometry", out flagFeature)) { if (null == flagFeature) { throw new ArgumentException("invalid Flags json format with geometry"); } double? x, y; long? epsg; JsonObject srsObj; if (true == flagFeature.TryGetJsonObject("spatialReference", out srsObj)) { if (false == srsObj.TryGetAsLong("wkid", out epsg) || epsg <= 0) { throw new ArgumentException("No valid wikd found for flag feature."); } } else { throw new ArgumentException("No spatial reference found for flag feature."); } if (flagFeature.TryGetAsDouble("x", out x) && flagFeature.TryGetAsDouble("y", out y)) { if (!x.HasValue || !y.HasValue) { throw new ArgumentException("invalid Flag coordinate"); } IPoint pnt1 = new PointClass(); pnt1.X = x.Value; pnt1.Y = y.Value; IGeometryArray pntArr1 = new GeometryArrayClass(); pntArr1.Add(pnt1); IGeometryArray geomArr = AOUtilities.TransfromGeometriesFrom2((uint)epsg, (uint)this.m_networkEPSG, pntArr1); if (null == geomArr || 1 != geomArr.Count) { throw new ArgumentException("invalid Flag coordinate for reprojection"); } pnt1 = geomArr.get_Element(0) as IPoint; StartFlagEdge flag = NetworkHelper.GetStartFlagEdge(this.m_networkContext, pnt1.X, pnt1.Y, TracingSOE.m_searchDistance, TracingSOE.m_searchTolerance, FlowLineName, this.m_flowDirFieldIndex, InvalidFlowDirValue, logger); StopperJunctions stoppers = null; if (null != flag) { List <IPoint> barrierPnts = null; JsonObject barriersJSON = null; object[] barrierArray = null; JsonObject[] barrierJsonArray = null; if (true == operationInput.TryGetJsonObject(BarrierParameterName, out barriersJSON) || null != barriersJSON) { if (barriersJSON.TryGetArray("features", out barrierArray)) { try { barrierJsonArray = barrierArray.Cast <JsonObject>().ToArray(); barrierPnts = ParseVirtualBarriers(barrierJsonArray, (uint)epsg); } catch { throw new ArgumentException("invalid Barriers json format"); } } if (null != barrierPnts && barrierPnts.Count > 0) { stoppers = NetworkHelper.GetStoppers(this.m_networkContext, barrierPnts, isUpstream.Value, TracingSOE.m_searchDistance, TracingSOE.m_searchTolerance, FlowLineName, JunctionName, logger); } } } ftrList = AOUtilities.StreamTrace(this.m_networkContext.GeometricNetwork, flag, this.m_disabledFeatureClassIDs, stoppers, isUpstream.Value, this.m_maxFeatureCount, logger); } } } IRecordSet records = null; if (null != ftrList && ftrList.Count > 0) { records = AOUtilities.GetRecordSetFromFeatureClass(this.m_networkContext.GetEdgeFeatureClassByAliasName(FlowLineName), ftrList, this.m_outputFields, (uint)outEPSG.Value); } JsonObject result = new JsonObject(); if (null != records) { result.AddJsonObject("value", new JsonObject(System.Text.Encoding.UTF8.GetString(Conversion.ToJson(records)))); } else { result.AddString("output", "{}"); } watch.Stop(); this.logger.LogMessage(ServerLogger.msgType.debug, "NetworkTraceHandler", 973, "Tracing taked: " + watch.ElapsedMilliseconds.ToString() + " ms"); result.AddLong("time(ms)", watch.ElapsedMilliseconds); return(Encoding.UTF8.GetBytes(result.ToJson())); }
private byte[] getSpeciesListForBBoxHandler(NameValueCollection boundVariables, JsonObject operationInput, string outputFormat, string requestProperties, out string responseProperties) { responseProperties = null; long? txmin; long? txmax; long? tymin; long? tymax; operationInput.TryGetAsLong("txmin", out txmin); operationInput.TryGetAsLong("txmax", out txmax); operationInput.TryGetAsLong("tymin", out tymin); operationInput.TryGetAsLong("tymax", out tymax); Type factoryType = Type.GetTypeFromProgID("esriDataSourcesGDB.FileGDBWorkspaceFactory"); //open a connection to the species data table IWorkspaceFactory workspaceFactory = (IWorkspaceFactory)Activator.CreateInstance(factoryType); IWorkspace workspace = workspaceFactory.OpenFromFile("D:\\GIS Data\\Andrew\\PilotSpeciesData.gdb", 0); //TODO make this more sustainable IFeatureWorkspace featureWorkspace = (IFeatureWorkspace)workspace; IQueryDef queryDef = featureWorkspace.CreateQueryDef(); //create a query to get the data IQueryDef2 queryDef2 = (IQueryDef2)queryDef; queryDef2.Tables = "Species"; //specify the tables queryDef2.SubFields = "Species.tax_id,Species.friendly_name"; //specify the fields that you will return queryDef2.WhereClause = "tax_id IN (SELECT species_ID from PilotSpeciesData where mx between " + txmin.ToString() + " and " + txmax.ToString() + " and my between " + tymin.ToString() + " and " + tymax.ToString() + ")"; //create the query queryDef2.PrefixClause = "DISTINCT"; ICursor cursor = queryDef2.Evaluate(); int friendly_nameIndex = cursor.FindField("Species.friendly_name"); IRow row = null; String s = ""; while ((row = cursor.NextRow()) != null) //get the resultset and iterate through the records { s = s + row.get_Value(friendly_nameIndex) + ","; } JsonObject result = new JsonObject(); result.AddString("species", s); //write the results return Encoding.UTF8.GetBytes(result.ToJson()); //return the results }
private byte[] ExecuteStoredProcedureHandler(NameValueCollection boundVariables, JsonObject operationInput, string outputFormat, string requestProperties, out string responseProperties) { responseProperties = null; string retString = ""; try { //return Encoding.UTF8.GetBytes(retStrn); //return null; string pipeDelimetedStringValuePairsForStoredProc = ""; bool found = operationInput.TryGetString("ParamValuePairs", out pipeDelimetedStringValuePairsForStoredProc); if (!found || string.IsNullOrEmpty(pipeDelimetedStringValuePairsForStoredProc)) { throw new ArgumentNullException("ParamValuePairs"); } string extra; found = operationInput.TryGetString("Extra", out extra); if (!found || string.IsNullOrEmpty(extra)) { throw new ArgumentNullException("extra"); } responseProperties = null; IServerEnvironment3 senv = GetServerEnvironment() as IServerEnvironment3; JsonObject result = new JsonObject(); JsonObject suinfoj = new JsonObject(); //get user info and serialize into JSON IServerUserInfo suinfo = senv.UserInfo; if (null != suinfo) { suinfoj.AddString("currentUser", suinfo.Name); IEnumBSTR roles = suinfo.Roles; List <string> rolelist = new List <string>(); if (null != roles) { string role = roles.Next(); while (!string.IsNullOrEmpty(role)) { rolelist.Add(role); role = roles.Next(); } } suinfoj.AddArray("roles", rolelist.ToArray()); result.AddJsonObject("serverUserInfo", suinfoj); } else { result.AddJsonObject("serverUserInfo", null); } IServerObject so = serverObjectHelper.ServerObject; retString = "got so>"; string progString = ""; retString += "> Stored Proc via oleDB ";// + ex.Message; OleDbConnection con = new OleDbConnection(); string paramsThatParsed = ""; con.ConnectionString = @"Provider =SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=" + extra.Split(',')[0] + ";Data Source=" + extra.Split(',')[1];// @"Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=TestDB;Data Source=PC684"; // string storedProcedureName = "dbo.apLITSaveChanges"; bool isStatusOutput = Convert.ToBoolean(extra.Split(',')[2]); //the connection string below uses integrated security which is usually superior to storing credential in visible text //con.ConnectionString = @"Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=TestDB;Data Source=PC684"; //con.Open(); //retString += ">opened connection"; string SQLString = ""; OleDbCommand cmd = new OleDbCommand(storedProcedureName, con); cmd.CommandType = System.Data.CommandType.StoredProcedure; string userName = "******"; if (suinfo.Name != null) { userName = suinfo.Name; } cmd.Parameters.AddWithValue("@WindowsLogin", userName); SQLString += "@WindowsLogin='******'"; //SQLString += "@WindowsLogin="******">created command"; string[] paramValsForStoredProc = pipeDelimetedStringValuePairsForStoredProc.Split('|'); foreach (string paramVal in paramValsForStoredProc) { string param = paramVal.Split(',')[0]; paramsThatParsed += "," + param; string val = paramVal.Split(',')[1]; retString += ">param and value : " + param + " = " + val; param = "@" + param; if (param.ToUpper().Contains("GEOLOCID")) { int i = int.Parse(val); cmd.Parameters.AddWithValue(param, i); SQLString += ", " + param + "= " + i; } else if (param.ToUpper() == "@LATITUDE" || param.ToUpper() == "@LONGITUDE") { double d = double.Parse(val); cmd.Parameters.AddWithValue(param, d); SQLString += ", " + param + "= " + d; } else if (param.ToUpper() == "@STATUS") { if (isStatusOutput) { //cmd.Parameters[param].Direction = ParameterDirection.Output; retString += ">Set direction of status parameter to output"; SQLString += ", @STATUS = @localstatus OUTPUT"; } } else { cmd.Parameters.AddWithValue(param, val); //SQLString += ", " + param + "= " + val ; SQLString += ", " + param + "= '" + val + "'"; } }//CurGeoLocID,NewGeoLocID,Address,City,ZipCode,Latitude,Longitude,FacilityName,AppID,WindowsLogin,ServerName,ServerName,Status SQLString = "exec dbo.apLITSaveChanges " + SQLString; if (isStatusOutput) { SQLString = "DECLARE @localstatus varchar(256);" + SQLString; } string retStrn = UseAOToCreateUpdateFeatures(SQLString); return(Encoding.UTF8.GetBytes(retStrn)); return(null); cmd.Connection = con; cmd.ExecuteNonQuery(); return(Encoding.UTF8.GetBytes(result.ToJson() + " - " + retString.ToString())); } catch (Exception ex) { return(Encoding.UTF8.GetBytes("ERROR " + ex.ToString() + " : " + retString.ToString())); } }
private byte[] editFeatureOperHandler(NameValueCollection boundVariables, JsonObject operationInput, string outputFormat, string requestProperties, out string responseProperties) { responseProperties = null; // get the id of the feature to be edited object featureIdObj; operationInput.TryGetObject("featureId", out featureIdObj); int updateFeatureId = Convert.ToInt32(featureIdObj.ToString()); object featureJSONObj; operationInput.TryGetObject("featureJSON", out featureJSONObj); JsonObject updateFeatureJSON = (JsonObject)featureJSONObj; // set a filter for the specific feature QueryFilter queryFilter = new QueryFilter(); if (this.fc == null) { return createErrorObject( 406, "Incorrect layer id provided.", new String[] { "Please provide layer id of a feature layer." }); } IClass myClass = (IClass) this.fc; queryFilter.WhereClause = myClass.OIDFieldName + "=" + updateFeatureId; IFeatureCursor featureCursor = this.fc.Search(queryFilter, false); // attempt retrieval of the feature and check if it does exist IFeatureCursor myFeatureCursor = (IFeatureCursor) featureCursor; IFeature updateFeature = myFeatureCursor.NextFeature(); if (updateFeature == null) { return createErrorObject( 406, "Incorrect feature id provided.", new String[] { "No feature exists for feature id " + updateFeatureId + "." }); } JsonObject response = new JsonObject(); // edit feature string result = System.Text.Encoding.GetEncoding("utf-8").GetString(performEdits(updateFeature, updateFeatureJSON)); featureCursor.Flush(); if (result.Equals(System.Boolean.TrueString)) { response.AddString("status", "success"); response.AddString("message", "Feature " + updateFeatureId + " updated"); } else { response.AddString("status", "failure"); response.AddString("message", result); } // send response back to client app return Encoding.UTF8.GetBytes(response.ToJson()); }
private byte[] GetNewSiteCode(NameValueCollection boundVariables, JsonObject operationInput, string outputFormat, string requestProperties, out string responseProperties) { responseProperties = null; string CountryCode; bool found = operationInput.TryGetString("CountryCode", out CountryCode); if (!found || string.IsNullOrEmpty(CountryCode)) throw new ArgumentNullException("CountryCode"); string storedProcedureName = "_IWC_GetMaxSiteCode"; SqlCommand cmd = new SqlCommand(storedProcedureName, sqlConn); cmd.CommandType = CommandType.StoredProcedure; SqlParameter param = cmd.Parameters.AddWithValue("@countryCode", CountryCode); SqlDataReader reader = cmd.ExecuteReader(); string newCode = null; if (reader.HasRows) { while (reader.Read()) { newCode = reader.GetString(0); } } reader.Close(); string newnum = null; if (newCode != null) { newnum = Convert.ToString((Convert.ToInt32(newCode.Substring(2)) + 1)); char pad = '0'; newnum = newnum.PadLeft(5, pad); } if (newCode != null) newCode = CountryCode + newnum; JsonObject result = new JsonObject(); result.AddString("newCode", newCode); return Encoding.UTF8.GetBytes(result.ToJson()); }
private byte[] NumberOfTrainStationsResHandler(NameValueCollection boundVariables, string outputFormat, string requestProperties, out string responseProperties) { responseProperties = "{\"Content-Type\" : \"application/json\"}"; JsonObject result = new JsonObject(); result.AddString("numberOfTrainStations", "100"); return Encoding.UTF8.GetBytes(result.ToJson()); }
private Byte[] GetUserSiteCodes(NameValueCollection boundVariables, JsonObject operationInput, string outputFormat, string requestProperties, out string responseProperties) { responseProperties = null; String userID; bool found = operationInput.TryGetString("userID", out userID); if (!found || (userID == null)) throw new ArgumentNullException("userID"); SqlCommand cmd = new SqlCommand("_IWC_GetUserSites", sqlConn); cmd.CommandType = CommandType.StoredProcedure; SqlParameter param = cmd.Parameters.AddWithValue("@userID", userID); SqlDataReader reader = cmd.ExecuteReader(); String siteCodes = null; if (reader.HasRows) { while (reader.Read()) { siteCodes = siteCodes + "'" + reader.GetString(0) + "',"; } siteCodes = siteCodes.Substring(0, siteCodes.Length - 1); } reader.Close(); JsonObject jObject = new JsonObject(); jObject.AddString("siteCodes", siteCodes); return Encoding.UTF8.GetBytes(jObject.ToJson()); }
private byte[] RootResHandler(NameValueCollection boundVariables, string outputFormat, string requestProperties, out string responseProperties) { responseProperties = null; JsonObject result = new JsonObject(); result.AddString("Description", "Get raster item statistics in a mosaic dataset"); result.AddBoolean("SupportRasterItemAccess", _supportRasterItemAccess); return Encoding.UTF8.GetBytes(result.ToJson()); }
private byte[] RootResHandler(NameValueCollection boundVariables, string outputFormat, string requestProperties, out string responseProperties) { responseProperties = null; JsonObject result = new JsonObject(); result.AddString("Description", "The International Waterbird Census Server Object Extensions are utility REST services for managing and querying the IWC database."); return Encoding.UTF8.GetBytes(result.ToJson()); }
private void button_Click(object sender, RoutedEventArgs e) { JsonObject jo = new JsonObject(); try { jo.AddString("host", textBoxHost.Text != "" ? textBoxHost.Text : "127.0.0.1"); jo.AddLong("port", textBoxPort.Text != "" ? long.Parse(textBoxPort.Text) : 27017); jo.AddString("db", textBoxDBName.Text != "" ? textBoxDBName.Text : "torrents"); jo.AddString("user", textBoxUser.Text != "" ? textBoxUser.Text : ""); jo.AddString("pwd", textBoxPassword.Text != "" ? textBoxPassword.Text : ""); jo.AddLong("threadnum", (comboBox.SelectedIndex + 1) * 4); jo.AddString("server", textBoxServer.Text != "" ? textBoxServer.Text : "http://www.ac168.info/bt/"); jo.AddString("target", textBoxTarget.Text != "" ? textBoxTarget.Text : "http://www.ac168.info/bt/thread.php?fid=4&page={0}"); jo.AddString("tor_server", textBoxTorServer.Text != "" ? textBoxTorServer.Text : "http://www.jandown.com/fetch.php"); jo.AddString("save_type", textBoxSaveType.Text != "" ? textBoxSaveType.Text : "db"); jo.AddString("path", textBoxPath.Text != "" ? textBoxPath.Text : "G:\\迅雷下载\\Torrents\\"); jo.AddString("list_identify", textBoxListIdentify.Text != "" ? textBoxListIdentify.Text : "class"); jo.AddString("list_type", textBoxListType.Text != "" ? textBoxListType.Text : "tr"); jo.AddString("list_identify_text", textBoxListIdentifyText.Text != "" ? textBoxListIdentifyText.Text : "tr3 t_one"); jo.AddString("list_element", textBoxListElement.Text != "" ? textBoxListElement.Text : "dd"); jo.AddString("content_identify", textBoxContentIdentify.Text != "" ? textBoxContentIdentify.Text : "class"); jo.AddString("content_type", textBoxContentType.Text != "" ? textBoxContentType.Text : "div"); jo.AddString("content_identify_text", textBoxContentIdentifyText.Text != "" ? textBoxContentIdentifyText.Text : "tpc_content"); StreamWriter sw = new StreamWriter("Config.json", false); sw.Write(jo.ToJson()); sw.Flush(); sw.Close(); } catch { } this.Close(); }
private byte[] UpdateCheckedCount(NameValueCollection boundVariables, JsonObject operationInput, string outputFormat, string requestProperties, out string responseProperties) { responseProperties = null; long? id; long? checkedVal; bool found = operationInput.TryGetAsLong("id", out id); if (!found) throw new ArgumentNullException("id"); found = operationInput.TryGetAsLong("checked", out checkedVal); if (!found) throw new ArgumentNullException("checked"); string storedProcedureName = "_IWC_UpdateChecked"; SqlCommand cmd = new SqlCommand(storedProcedureName, sqlConn); cmd.CommandType = CommandType.StoredProcedure; SqlParameter param1 = cmd.Parameters.AddWithValue("@id", id); SqlParameter param2 = cmd.Parameters.AddWithValue("@checked", checkedVal); cmd.ExecuteNonQuery(); JsonObject result = new JsonObject(); result.AddString("results", "Done"); return Encoding.UTF8.GetBytes(result.ToJson()); }
/// <summary> /// Handler operation Identify Route Ex /// </summary> /// <param name="boundVariables">list of variables bound</param> /// <param name="operationInput">input of operation</param> /// <param name="outputFormat">format of output</param> /// <param name="requestProperties">list of request properties</param> /// <param name="responseProperties">list of response properties </param> /// <returns>response in byte</returns> private byte[] IdentifyRouteExOperHandler(NameValueCollection boundVariables, JsonObject operationInput, string outputFormat, string requestProperties, out string responseProperties) { responseProperties = "{\"Content-Type\" : \"application/json\"}"; string methodName = MethodBase.GetCurrentMethod().Name; int routeLayerID = Convert.ToInt32(boundVariables["RouteLayersID"], CultureInfo.InvariantCulture); esriUnits routeMeasureUnit = DSUtility.GetMeasureUnit(operationInput, MeasureUnit.routeMeasureUnit); esriSegmentExtension segmentExtension = DSUtility.GetSegmentExtension(operationInput); IFeatureClass featureClass = this.GetRouteFeatureClass(routeLayerID); JsonObject jsonLocation; if (!operationInput.TryGetJsonObject("location", out jsonLocation)) { throw new ArgumentException("Invalid location", methodName); } IPoint location = Conversion.ToGeometry(jsonLocation, esriGeometryType.esriGeometryPoint) as IPoint; if (location == null) { throw new ArgumentException("Invalid location", methodName); } string routeIDFieldNameValue = DSUtility.GetRouteIDFieldName(operationInput); IFields fields = featureClass.Fields; int indexField = fields.FindField(routeIDFieldNameValue); if (indexField == -1) { throw new DynamicSegmentationException(string.Format(CultureInfo.InvariantCulture, "routeIDFieldName {0} not found!", routeIDFieldNameValue)); } object routeID; bool found = operationInput.TryGetObject("routeID", out routeID); if (!found) { throw new DynamicSegmentationException("routeID not valid"); } double?tolerance; found = operationInput.TryGetAsDouble("tolerance", out tolerance); if (!found || !tolerance.HasValue) { tolerance = 0.0; } IField field = fields.get_Field(indexField); this.CheckRouteID(routeID, field); IRouteLocator2 routeLocator = DSUtility.GetRouteLocator(featureClass, routeIDFieldNameValue, routeMeasureUnit); IQueryFilter queryFilter = new QueryFilterClass(); queryFilter.SubFields = routeLocator.RouteIDFieldName; queryFilter.AddField(routeLocator.RouteFeatureClass.ShapeFieldName); string where = string.Format("{0} = {1}{2}{1}", routeLocator.RouteIDFieldNameDelimited, routeLocator.RouteIDIsString ? "'" : string.Empty, routeID); queryFilter.WhereClause = where; IPoint locationNearest = null; IFeatureCursor featureCursor = null; try { featureCursor = routeLocator.RouteFeatureClass.Search(queryFilter, true); IFeature featureRoute = featureCursor.NextFeature(); if (featureRoute == null) { throw new DynamicSegmentationException(string.Format(CultureInfo.InvariantCulture, "Feature with value {0} not found!", routeID)); } IProximityOperator proximityOperator = featureRoute.ShapeCopy as IProximityOperator; locationNearest = proximityOperator.ReturnNearestPoint(location, segmentExtension); } catch { throw; } finally { if (featureCursor != null) { Marshal.ReleaseComObject(featureCursor); } } IEnvelope envelope = locationNearest.Envelope; envelope.Expand(tolerance.Value, tolerance.Value, false); IRouteMeasurePointLocation routeMeasurePointLocation = new RouteMeasurePointLocationClass(); IRouteLocation routeLocation; IFeature feature; JsonObject result = new JsonObject(); List <JsonObject> measures = new List <JsonObject>(); IEnumRouteIdentifyResult enumResult = routeLocator.Identify(envelope, where); for (int i = 1; i <= enumResult.Count; i++) { enumResult.Next(out routeLocation, out feature); routeMeasurePointLocation = (IRouteMeasurePointLocation)routeLocation; JsonObject measure = new JsonObject(); measure.AddString("routeID", routeLocation.RouteID.ToString()); measure.AddDouble("measure", routeMeasurePointLocation.Measure); measure.AddJsonObject("location", Conversion.ToJsonObject(locationNearest, true)); measures.Add(measure); } result.AddArray("location", measures.ToArray()); return(result.JsonByte()); }
private byte[] ValidateData(NameValueCollection boundVariables, JsonObject operationInput, string outputFormat, string requestProperties, out string responseProperties) { responseProperties = null; string validationType; bool found = operationInput.TryGetString("validationType", out validationType); if (!found || string.IsNullOrEmpty(validationType)) throw new ArgumentNullException("validationType"); JsonObject data; found = operationInput.TryGetJsonObject("data", out data); if (!found || (data == null)) throw new ArgumentNullException("data"); object[] records; data.TryGetArray("records", out records); string invalidIDs = ""; if (records.Length > 0) invalidIDs = GetInvalidIDs(records, validationType); JsonObject result = new JsonObject(); result.AddString("validationType", validationType); result.AddString("invalidIDs", invalidIDs); return Encoding.UTF8.GetBytes(result.ToJson()); }
private byte[] RootResHandler(NameValueCollection boundVariables, string outputFormat, string requestProperties, out string responseProperties) { responseProperties = null; JsonObject infoJSON = new JsonObject(); infoJSON.AddString("name", ".Net Edit Features REST SOE"); infoJSON.AddString("description", "This SOE adds and edits features to a selected layer in the host map service. " + "Note that this SOE is not designed to work with map services that have features stored in SDC data format." + " The \"layers\" subresource returns all layers in the map service." + " The \"editFeature\" operation allows editing an existing feature in the layer indicated by this SOE's layerId property.\n" + " The \"addFeatures\" operation allows addition of a new feature to the layer indicated by this SOE's layerId property.\n" + " The acceptableSchema JSON below indicates the correct schema that could be used to add/edit features. This schema belongs to the layer " + "selected for editing by the ArcGIS Server administrator via the SOE's layerId property. This property's value can be " + "modified using ArcGIS Manager."); // validation - ensure user has provided right layer id property value. if (this.layerId > this.layerInfos.Count - 1) { return(createErrorObject(406, "Layer Id " + this.layerId + " is invalid.", new String[] { "Acceptable layer ids are between 0 and " + (layerInfos.Count - 1) + ".", "Also ensure that the id points to a feature layer." })); } // inform the user that edits can be done only on feature layers, if no // feature layer corresponds to user-provided layerId if (this.editLayerInfo == null) { this.editLayerInfo = this.layerInfos.get_Element(this.layerId); if (!this.editLayerInfo.IsFeatureLayer) { return(createErrorObject( 403, "The layerId property of this SOE currently points to a layer (id: " + this.layerId + ") that is not a feature layer.", new String[] { "Only feature layers can be edited by this SOE.", "Modify SOE's layerId property using ArcGIS Manager or ArcGIS Desktop's Service Editor." })); } } // Grab the fc powering the layer if its null, which means it did not get initialized in construct(), thereby // suggesting that the layerId property value is incorrect. if (this.fc == null) { // The down side of grabbing fc here is // that a new instance of fc is created once for every request. // Can't create fc in init(), since layerId property value for a // particular service is not necessarily available always when init() is invoked. this.fc = (IFeatureClass)this.mapServerDataAccess.GetDataSource(this.mapServerInfo.Name, this.layerId); if (this.fc == null) { // if its still null, return error return(createErrorObject( 406, "Incorrect layer id provided.", new String[] { "Please provide layer id of a feature layer." })); } } infoJSON.AddString("Layer selected for editing", editLayerInfo.Name.ToString() + " (" + layerId + ")"); JsonObject schemaJSON = getSchemaJSON(); infoJSON.AddObject("acceptableSchema", schemaJSON); return(Encoding.UTF8.GetBytes(infoJSON.ToJson())); }
private byte[] GetSource(NameValueCollection boundVariables, JsonObject operationInput, string outputFormat, string requestProperties, out string responseProperties) { responseProperties = null; // long? idnoValue; //out parameter for the ID_NO as a long operationInput.TryGetAsLong("ID_NO", out idnoValue); //get the ID_NO parameter IQueryFilter queryFilter = new QueryFilterClass(); //instantiate a filter for the passed species queryFilter.WhereClause = "ID_NO='" + idnoValue + "'"; //set the where clause IFeatureCursor featureCursor = speciesFeatureClass.Search(queryFilter, false); //get the feature cursor to the matching features IFeature feature = null; //for iterating through the features int index = speciesFeatureClass.Fields.FindField("CITATION"); List<string> sources = new List<string>(); List<JsonObject> jsonObjects = new List<JsonObject>(); while ((feature = featureCursor.NextFeature()) != null) //iterate through the matching features { string source = feature.get_Value(index) as string; if (InList(sources, source) == false) { JsonObject sourceJson = new JsonObject(); sourceJson.AddString("Source", source); jsonObjects.Add(sourceJson); sources.Add(source); } } JsonObject result = new JsonObject(); //create the return json object result.AddArray("sources", jsonObjects.ToArray()); return Encoding.UTF8.GetBytes(result.ToJson()); //return the json }
//Retrieves feature schema for selected layer that could be used to provide data for editing. private JsonObject getSchemaJSON() { Fields fields = (Fields)editLayerInfo.Fields; int fieldCount = fields.FieldCount; JsonObject attributeJsonObject = new JsonObject(); for (int i = 0; i < fieldCount; i++) { Field field = (Field)fields.get_Field(i); String typeStr = null; switch (field.Type) { case esriFieldType.esriFieldTypeBlob: typeStr = "Blob"; break; case esriFieldType.esriFieldTypeDate: typeStr = "Date"; break; case esriFieldType.esriFieldTypeDouble: typeStr = "Double"; break; case esriFieldType.esriFieldTypeInteger: typeStr = "Integer"; break; case esriFieldType.esriFieldTypeRaster: typeStr = "Raster"; break; case esriFieldType.esriFieldTypeSmallInteger: typeStr = "Integer"; break; case esriFieldType.esriFieldTypeString: typeStr = "String"; break; case esriFieldType.esriFieldTypeXML: typeStr = "XML"; break; default: break; } if (typeStr != null && typeStr.Length > 0 && field.Editable) { attributeJsonObject.AddString(field.Name, typeStr); } } JsonObject featuresJsonObject = new JsonObject(); featuresJsonObject.AddJsonObject("attributes", attributeJsonObject); JsonObject geometryJson = new JsonObject(); switch (((IFeatureClass)fc).ShapeType) { case esriGeometryType.esriGeometryPoint: geometryJson.AddString("x", "x"); geometryJson.AddString("y", "y"); geometryJson.AddString("z", "z"); break; case esriGeometryType.esriGeometryMultipoint: geometryJson.AddString("hasM", "true | false"); geometryJson.AddString("hasZ", "true | false"); geometryJson.AddString("points", "[ [ x1, y1, z1, m1 ] , [ x2, y2, z2, m2 ], ... ]"); break; case esriGeometryType.esriGeometryPolyline: geometryJson.AddString("hasM", "true | false"); geometryJson.AddString("hasZ", "true | false"); geometryJson.AddString("paths", "[" + "[ [x11, y11, z11, m11], [x12, y12, z12, m12] ]," + "[ [x21, y21, z21, m21], [x22, y22, z22, m22] ]]"); break; case esriGeometryType.esriGeometryPolygon: geometryJson.AddString("hasM", "true | false"); geometryJson.AddString("hasZ", "true | false"); geometryJson.AddString ("rings", "[" + "[ [x11, y11, z11, m11], [x12, y12, z12, m12], ..., [x11, y11, z11, m11] ]," + "[ [x21, y21, z21, m21], [x22, y22, z22, m22], ..., [x21, y21, z21, m21] ]]"); break; default: break; } JsonObject srJson = new JsonObject(); srJson.AddString("wkid", "wkid"); geometryJson.AddJsonObject("spatialReference", srJson); featuresJsonObject.AddJsonObject("geometry", geometryJson); return(featuresJsonObject); }
private byte[] GetSpeciesExtentHandler(NameValueCollection boundVariables, JsonObject operationInput, string outputFormat, string requestProperties, out string responseProperties) { responseProperties = "{\"Content-Type\" : \"text/javascript\"}"; long? idnoValue; //out parameter for the ID_NO as a long operationInput.TryGetAsLong("ID_NO", out idnoValue); //get the ID_NO parameter IQueryFilter queryFilter = new QueryFilterClass(); //instantiate a filter for the passed species queryFilter.WhereClause = "ID_NO='" + idnoValue + "' AND Legend<>''"; //set the where clause IFeatureCursor featureCursor = speciesFeatureClass.Search(queryFilter, false); //get the feature cursor to the matching features IFeature feature = null; //for iterating through the features IGeometryCollection pGeometryCollection = new GeometryBagClass() as IGeometryCollection; //instantiate a geometry bag to get the extent object obj = Type.Missing; //needed to add geometries to the geometry bag while ((feature = featureCursor.NextFeature()) != null) //iterate through the matching features and add the geometries to the geometry bag { pGeometryCollection.AddGeometry(feature.ShapeCopy, ref obj, ref obj); //add the geometry } JsonObject result = new JsonObject(); //create the return json object IEnvelope extent = (pGeometryCollection as IGeometry).Envelope; //get the extent of the geometry bag JsonObject jsonExtent = Conversion.ToJsonObject(extent); //convert the extent to json //TODO: Set the spatial reference for the extent in the SOE - at the moment it is set in the client code result.AddObject("extent", jsonExtent); //write the extent to the result object result.AddString("featureCount", pGeometryCollection.GeometryCount.ToString()); //get the number of features return Encoding.UTF8.GetBytes(result.ToJson()); //return the json }
private byte[] DescribeLayersHandler(NameValueCollection boundVariables, JsonObject operationInput, string outputFormat, string requestProperties, out string responseProperties) { responseProperties = null; JsonObject tResult = new JsonObject(); tResult.AddLong("AvailableLayerCount", m_ExtractableParams.Count); JsonObject tLayersJson = new JsonObject(); foreach (ExtractionLayerConfig layer in m_ExtractableParams){ //int id = layer.LayerID; string lyrName = layer.LayerName; string requestParameter = layer.ParamName; string extractionType = layer.ExtractionType.ToString(); JsonObject tLayerJson = new JsonObject(); //tLayerJson.AddLong("LayerId", id); tLayerJson.AddString("LayerName",lyrName); tLayerJson.AddString("LayerDescription", layer.LayerDescription); tLayerJson.AddString("ExtractionType", extractionType); if (layer.HasCategories) { IFeatureClass tLayerAsFc = (IFeatureClass)layer.LayerDataset; string tCatName = tLayerAsFc.Fields.get_Field(layer.CategoryField).Name; tLayerJson.AddString("CategoryField", tCatName); } tLayersJson.AddObject(requestParameter,tLayerJson); } tResult.AddObject("Extractions", tLayersJson); byte[] tOutput = System.Text.Encoding.UTF8.GetBytes(tResult.ToJson()); return tOutput; }
// Helper method to read the items in a dictionary and make a JSON object from them. private JsonObject[] CreateJsonRecords(Dictionary<string, double> inListDictionary) { JsonObject[] jsonRecordsArray = new JsonObject[inListDictionary.Count]; int i = 0; // Loop through dictionary. foreach (KeyValuePair<string, double> kvp in inListDictionary) { // Get the current key and value. string currentKey = kvp.Key.ToString(); string currentValue = kvp.Value.ToString(); // Add the key and value to a JSON object. JsonObject currentKeyValue = new JsonObject(); currentKeyValue.AddString(m_mapLayerNameToQuery, currentKey); currentKeyValue.AddString("value", currentValue); // Add the record object to an array. jsonRecordsArray.SetValue(currentKeyValue, i); i++; } return jsonRecordsArray; }
private byte[] addNewFeatureOperHandler(NameValueCollection boundVariables, JsonObject operationInput, string outputFormat, string requestProperties, out string responseProperties) { responseProperties = null; // get the feature JSON JsonObject newFeatureJSON = null; operationInput.TryGetJsonObject("featureJSON", out newFeatureJSON); // add the new feature IFeature newFeature; var bytes = addFeature(newFeatureJSON, out newFeature); if (null == newFeature) return bytes; //return error // send response back to client app var response = new JsonObject(); response.AddString("status", "success"); response.AddString("message", "Feature " + newFeature.OID + " added."); return Encoding.UTF8.GetBytes(response.ToJson()); }
/// <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 / create service" ; JsonObject jsonObject = new JsonObject(); jsonObject.AddString ( "serviceName" , "Test" ); jsonObject.AddString ( "type" , Enum . GetName ( typeof ( ServiceType ) ServiceType . MapServer)); jsonObject.AddString ( "description" , "This is an example" ); jsonObject.AddString ( "capabilities" , "Map, Query, Data" ); jsonObject.AddString ( "ClusterName" , "default" ); jsonObject.AddLong ( "minInstancesPerNode" , 1); jsonObject.AddLong ( "maxInstancesPerNode" , 2); jsonObject.AddLong ( "maxWaitTime" , 60); jsonObject.AddLong ( "maxStartupTime" , 300); jsonObject.AddLong ( "MaxIdleTime" , 1800); jsonObject.AddLong ( "maxUsageTime" , 600); jsonObject.AddLong ( "recycleInterval" , 24); 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", 100); // optional 100 jsonObjectProperties.AddString("virtualCacheDir", this.urlRestServer + "/arcgiscache"); // optional jsonObjectProperties.AddLong("maxImageHeight", 2048); // optional 2048 jsonObjectProperties.AddLong("maxRecordCount", 1000); // optional 500 // Starting at ArcGIS 10.1, Map Server Definition ( .msd ) files have been // replaced with Service Definition Draft ( .sddraft ) and Service Definition ( .sd ) files. // In the case of a map service, you must specify a map service definition (MSD) file in your JSON. // This file synthesizes information from your ArcMap document (MXD) in a format that can be understood and // drawn by ArcGIS Server. You must use the arcpy.mapping module to analyze your map and create the MSD before // you can go ahead with creating the service. This part requires a machine licensed for ArcGIS for Desktop. // Other service types do not require you to use arcpy.mapping or create an MSD. jsonObjectProperties.AddString("filePath", @"C:\AvGis\Test\mappa\UTM_ReteFognaria.msd"); // required jsonObjectProperties.AddLong("maxImageWidth", 2048); // optional 2048 jsonObjectProperties.AddBoolean("cacheOnDemand", false); // optional false jsonObjectProperties.AddString("virtualOutputDir", this.urlRestServer + "/arcgisoutput"); jsonObjectProperties.AddString ( "outputDir" , @ "C: \ arcgisserver \ directories \ arcgisoutput" ) / / required jsonObjectProperties.AddString ( "supportedImageReturnTypes" , "MIME + URL" ), / / optional MIME + URL jsonObjectProperties.AddBoolean ( " isCached " , false ) / / false optional jsonObjectProperties.AddBoolean ( "ignoreCache" , false ) / / false optional jsonObjectProperties.AddBoolean ( "clientCachingAllowed" , false ) / / optional true jsonObjectProperties.AddString ( "Cached" , @ " 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; } }
//Retrieves feature schema for selected layer that could be used to provide data for editing. private JsonObject getSchemaJSON() { Fields fields = (Fields) editLayerInfo.Fields; int fieldCount = fields.FieldCount; JsonObject attributeJsonObject = new JsonObject(); for (int i = 0; i < fieldCount; i++) { Field field = (Field)fields.get_Field(i); String typeStr = null; switch (field.Type) { case esriFieldType.esriFieldTypeBlob: typeStr = "Blob"; break; case esriFieldType.esriFieldTypeDate: typeStr = "Date"; break; case esriFieldType.esriFieldTypeDouble: typeStr = "Double"; break; case esriFieldType.esriFieldTypeInteger: typeStr = "Integer"; break; case esriFieldType.esriFieldTypeRaster: typeStr = "Raster"; break; case esriFieldType.esriFieldTypeSmallInteger: typeStr = "Integer"; break; case esriFieldType.esriFieldTypeString: typeStr = "String"; break; case esriFieldType.esriFieldTypeXML: typeStr = "XML"; break; default: break; } if (typeStr != null && typeStr.Length > 0 && field.Editable) { attributeJsonObject.AddString(field.Name, typeStr); } } JsonObject featuresJsonObject = new JsonObject(); featuresJsonObject.AddJsonObject("attributes", attributeJsonObject); JsonObject geometryJson = new JsonObject(); switch (((IFeatureClass)fc).ShapeType) { case esriGeometryType.esriGeometryPoint: geometryJson.AddString("x", "x"); geometryJson.AddString("y", "y"); geometryJson.AddString("z", "z"); break; case esriGeometryType.esriGeometryMultipoint: geometryJson.AddString("hasM", "true | false"); geometryJson.AddString("hasZ", "true | false"); geometryJson.AddString("points", "[ [ x1, y1, z1, m1 ] , [ x2, y2, z2, m2 ], ... ]"); break; case esriGeometryType.esriGeometryPolyline: geometryJson.AddString("hasM", "true | false"); geometryJson.AddString("hasZ", "true | false"); geometryJson.AddString("paths", "[" + "[ [x11, y11, z11, m11], [x12, y12, z12, m12] ]," + "[ [x21, y21, z21, m21], [x22, y22, z22, m22] ]]"); break; case esriGeometryType.esriGeometryPolygon: geometryJson.AddString("hasM", "true | false"); geometryJson.AddString("hasZ", "true | false"); geometryJson.AddString ("rings", "[" + "[ [x11, y11, z11, m11], [x12, y12, z12, m12], ..., [x11, y11, z11, m11] ]," + "[ [x21, y21, z21, m21], [x22, y22, z22, m22], ..., [x21, y21, z21, m21] ]]"); break; default: break; } JsonObject srJson = new JsonObject(); srJson.AddString("wkid", "wkid"); geometryJson.AddJsonObject("spatialReference", srJson); featuresJsonObject.AddJsonObject("geometry", geometryJson); return featuresJsonObject; }
private byte[] RootResHandler(NameValueCollection boundVariables, string outputFormat, string requestProperties, out string responseProperties) { responseProperties = null; IServerEnvironment3 senv = GetServerEnvironment() as IServerEnvironment3; JsonObject result = new JsonObject(); JsonObject suinfoj = new JsonObject(); //get user info and serialize into JSON IServerUserInfo suinfo = senv.UserInfo; if (null != suinfo) { suinfoj.AddString("currentUser", suinfo.Name); IEnumBSTR roles = suinfo.Roles; List<string> rolelist = new List<string>(); if (null != roles) { string role = roles.Next(); while (!string.IsNullOrEmpty(role)) { rolelist.Add(role); role = roles.Next(); } } suinfoj.AddArray("roles", rolelist.ToArray()); result.AddJsonObject("serverUserInfo", suinfoj); } else { result.AddJsonObject("serverUserInfo", null); } return Encoding.UTF8.GetBytes(result.ToJson()); }
private byte[] findTrainStationById(NameValueCollection boundVariables, JsonObject operationInput, string outputFormat, string requestProperties, out string responseProperties) { responseProperties = null; string IdValue; bool found = operationInput.TryGetString("trainStationId", out IdValue); if (!found || string.IsNullOrEmpty(IdValue)) throw new ArgumentNullException("trainStationId"); JsonObject result = new JsonObject(); result.AddString("stationName", "Train Station " + IdValue); 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()); }
/* *通过调用影像服务的形式实现最大最大似然分类 */ private byte[] ExcuteFuncHandler(NameValueCollection boundVariables, JsonObject operationInput, string outputFormat, string requestProperties, out string responseProperties) { _logger.LogMessage(ServerLogger.msgType.infoDetailed, _soename + ".GetRasterStatistics", 8000, "request received"); if (!_supportRasterItemAccess) throw new ArgumentException("The image service does not have a catalog and does not support this operation"); responseProperties = null; long? objectID; long? classCount; //case insensitive bool found = operationInput.TryGetAsLong("objectID", out objectID); if (!found || (objectID == null)) throw new ArgumentNullException("ObjectID"); found = operationInput.TryGetAsLong("classnumber", out classCount); if (!found || (objectID == null)) throw new ArgumentNullException("classnumber"); IRasterCatalogItem rasterCatlogItem = null; try { rasterCatlogItem = _mosaicCatalog.GetFeature((int)objectID) as IRasterCatalogItem; if (rasterCatlogItem == null) { _logger.LogMessage(ServerLogger.msgType.infoDetailed, _soename + ".GetRasterStatistics", 8000, "request finished with exception"); throw new ArgumentException("The input ObjectID does not exist"); } } catch { _logger.LogMessage(ServerLogger.msgType.infoDetailed, _soename + ".GetRasterStatistics", 8000, "request finished with exception"); throw new ArgumentException("The input ObjectID does not exist"); } JsonObject result = new JsonObject(); string outputurl = ""; try { // rasterBandsCol = (IRasterBandCollection)rasterCatlogItem.RasterDataset; IRasterDataset pRasterDataSet = rasterCatlogItem.RasterDataset; string gsgname = System.DateTime.Now.ToString().Replace("/", "").Replace(":", "").Replace(" ", "") + ".gsg"; string gsgpath = System.IO.Path.Combine(@"d:\", gsgname); bool bcreatesignaturefile = Classify.CreateSignaturefile(pRasterDataSet, Convert.ToInt32(classCount), gsgpath); if (bcreatesignaturefile) { IRaster pRaster = pRasterDataSet.CreateDefaultRaster(); string imagePath = Classify.ApplyMLClassifyFunction(pImageSever, pRaster, gsgpath); outputurl = "http://localhost:6080/arcgis/" + imagePath; } } catch { } result.AddString("url", outputurl); return Encoding.UTF8.GetBytes(result.ToJson()); }
/// <summary> /// Build Meta Info /// </summary> private void BuildMeta() { IFeatureClass fc_poi = m_fcName.Open() as IFeatureClass; IGeoDataset ds_poi = fc_poi as IGeoDataset; int xmin = (int)Math.Floor(ds_poi.Extent.XMin); int ymin = (int)Math.Floor(ds_poi.Extent.YMin); int xmax = (int)Math.Ceiling(ds_poi.Extent.XMax); int ymax = (int)Math.Ceiling(ds_poi.Extent.YMax); int size = int.Parse(this.tbxSize.Text); int step = (int)Math.Ceiling((xmax - xmin) * 1.0 / size); string ns = "poi:" + this.tbxCacheName.Text + ":"; IDatabase client = m_redis.GetDatabase(); client.StringSet(ns + "size", size.ToString()); client.StringSet(ns + "xmin", xmin.ToString()); client.StringSet(ns + "ymin", ymin.ToString()); client.StringSet(ns + "xmax", xmax.ToString()); client.StringSet(ns + "ymax", ymax.ToString()); client.StringSet(ns + "step", step.ToString()); JsonObject response = new JsonObject(); List <JsonObject> ls_fields_cache = new List <JsonObject>(); for (int i = 0; i < fc_poi.Fields.FieldCount; i++) { IField field = fc_poi.Fields.get_Field(i); JsonObject js_f = new JsonObject(); js_f.AddString("name", field.Name); js_f.AddString("type", Enum.GetName(typeof(esriFieldType), field.Type)); js_f.AddString("alias", field.AliasName); if (field.Type == esriFieldType.esriFieldTypeString) { js_f.AddString("length", field.Length.ToString()); } else { js_f.AddString("length", ""); } ls_fields_cache.Add(js_f); } response.AddArray("fields", ls_fields_cache.ToArray()); if (fc_poi.ShapeType == esriGeometryType.esriGeometryPoint) { response.AddString("geometryType", "esriGeometryPoint"); } else if (fc_poi.ShapeType == esriGeometryType.esriGeometryPolyline) { response.AddString("geometryType", "esriGeometryPolyline"); } else if (fc_poi.ShapeType == esriGeometryType.esriGeometryPolygon) { response.AddString("geometryType", "esriGeometryPolygon"); } IGeoDataset gds_poi = fc_poi as IGeoDataset; JsonObject js_sr = new JsonObject(); js_sr.AddLong("wkid", gds_poi.SpatialReference.FactoryCode); response.AddJsonObject("spatialReference", js_sr); client.StringSet(ns + "response", response.ToJson()); client.SetAdd("poi:caches", this.tbxCacheName.Text); }
/// <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", 1); jsonObject.AddLong("maxInstancesPerNode", 2); jsonObject.AddLong("maxWaitTime", 60); jsonObject.AddLong("maxStartupTime", 300); jsonObject.AddLong("maxIdleTime", 1800); jsonObject.AddLong("maxUsageTime", 600); jsonObject.AddLong("recycleInterval", 24); 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", 100); // optional 100 jsonObjectProperties.AddString("virtualCacheDir", this.urlRestServer + "/arcgiscache"); // optional jsonObjectProperties.AddLong("maxImageHeight", 2048); // optional 2048 jsonObjectProperties.AddLong("maxRecordCount", 1000); // 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", 2048); // 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> /// Build Cache Backgroud worker /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) { int size = int.Parse(this.tbxSize.Text); IFeatureClass fc_poi = m_fcName.Open() as IFeatureClass; IGeoDataset ds_poi = fc_poi as IGeoDataset; int xmin = (int)Math.Floor(ds_poi.Extent.XMin); int ymin = (int)Math.Floor(ds_poi.Extent.YMin); int xmax = (int)Math.Ceiling(ds_poi.Extent.XMax); int ymax = (int)Math.Ceiling(ds_poi.Extent.YMax); List <JsonObject> ls_fields_cache = new List <JsonObject>(); if (!(fc_poi.Extension is IAnnotationClassExtension)) { for (int i = 0; i < fc_poi.Fields.FieldCount; i++) { IField field = fc_poi.Fields.get_Field(i); JsonObject js_f = new JsonObject(); js_f.AddString("name", field.Name); js_f.AddString("type", Enum.GetName(typeof(esriFieldType), field.Type)); js_f.AddString("alias", field.AliasName); if (field.Type == esriFieldType.esriFieldTypeString) { js_f.AddString("length", field.Length.ToString()); } else { js_f.AddString("length", ""); } ls_fields_cache.Add(js_f); } } IDatabase client = m_redis.GetDatabase(); int grid_id = 0; string ns = "poi:" + this.tbxCacheName.Text + ":"; for (int y = ymin; y <= ymax; y += size) { for (int x = xmin; x <= xmax; x += size) { List <String> str_poi_grid = new List <String>(); List <JsonObject> ls_features = new List <JsonObject>(); //String str_response = client.StringGet(ns+"response"); //JsonObject response = new JsonObject(str_response); JsonObject response = new JsonObject(); IEnvelope box = new EnvelopeClass(); box.XMin = x; box.YMin = y; box.XMax = x + size; box.YMax = y + size; ISpatialFilter filter_poi = new SpatialFilterClass(); filter_poi.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects; filter_poi.Geometry = box; filter_poi.SubFields = "*"; IFeatureCursor cur_poi = fc_poi.Search(filter_poi, true); IFeature fea_poi = cur_poi.NextFeature(); while (fea_poi != null) { JsonObject js_fea = new JsonObject(); if (!(fea_poi is IAnnotationFeature)) { JsonObject js_attributes = new JsonObject(); int i = 0; foreach (JsonObject js_field in ls_fields_cache) { object value = fea_poi.get_Value(i); string fieldtype; js_field.TryGetString("type", out fieldtype); string fieldname; js_field.TryGetString("name", out fieldname); #region if (fieldtype == Enum.GetName(typeof(esriFieldType), esriFieldType.esriFieldTypeString)) { js_attributes.AddString(fieldname, value.ToString()); } else if (fieldtype == Enum.GetName(typeof(esriFieldType), esriFieldType.esriFieldTypeOID)) { js_attributes.AddLong(fieldname, long.Parse(value.ToString())); } else if (fieldtype == Enum.GetName(typeof(esriFieldType), esriFieldType.esriFieldTypeInteger)) { if (value.ToString() == "") { value = 0; } js_attributes.AddLong(fieldname, long.Parse(value.ToString())); } else if (fieldtype == Enum.GetName(typeof(esriFieldType), esriFieldType.esriFieldTypeSmallInteger)) { if (value.ToString() == "") { value = 0; } js_attributes.AddLong(fieldname, long.Parse(value.ToString())); } else if (fieldtype == Enum.GetName(typeof(esriFieldType), esriFieldType.esriFieldTypeDouble)) { if (value.ToString() == "") { value = 0; } js_attributes.AddDouble(fieldname, double.Parse(value.ToString())); } else if (fieldtype == Enum.GetName(typeof(esriFieldType), esriFieldType.esriFieldTypeDate)) { if (value.ToString() == "") { value = DateTime.MinValue; } js_attributes.AddDate(fieldname, DateTime.Parse(value.ToString())); } else if (fieldtype == Enum.GetName(typeof(esriFieldType), esriFieldType.esriFieldTypeSingle)) { if (value.ToString() == "") { value = 0; } js_attributes.AddBoolean(fieldname, bool.Parse(value.ToString())); } #endregion i++; } js_fea.AddJsonObject("attributes", js_attributes); js_fea.AddJsonObject("geometry", Conversion.ToJsonObject(fea_poi.Shape)); } else { IAnnotationFeature anno_fea = fea_poi as IAnnotationFeature; ITextElement ele = anno_fea.Annotation as ITextElement; //string text = ele.Text.Replace(System.Environment.NewLine, " "); string text = ele.Text; ITextSymbol sym = ele.Symbol; IFontDisp font = sym.Font; double symsize = sym.Size; string fontname = font.Name; decimal fontsize = font.Size; string.Format(@"a"":"""); JsonObject js_symbol = new JsonObject( string.Format(@"{{""type"" : ""esriTS"",""color"": [255,255,255],""haloSize"" : 0,""haloColor"" : [255,255,255,0],""verticalAlignment"" : ""bottom"",""horizontalAlignment"" : ""center"",""size"": {0},""angle"": 0,""xoffset"": 0,""yoffset"": 0,""font"" : {{""family"" : ""{2}"",""size"" : {3},""style"" : ""normal"",""weight"" : ""normal"",""decoration"" : ""none""}},""text"":""{1}""}}", symsize, text, fontname, fontsize)); js_fea.AddJsonObject("symbol", js_symbol); IArea pshp = fea_poi.Shape as IArea; js_fea.AddJsonObject("geometry", Conversion.ToJsonObject(pshp.Centroid)); } ls_features.Add(js_fea); fea_poi = cur_poi.NextFeature(); } response.AddArray("features", ls_features.ToArray()); client.StringSet(ns + grid_id.ToString(), response.ToJson()); ReleaseCOMObject(cur_poi); grid_id++; progressBar1.BeginInvoke((Action)(() => { progressBar1.Increment(1); })); } } MessageBox.Show("Build Cache Successfully!"); this.button1.BeginInvoke((Action)(() => { ListCaches(); this.button1.Enabled = true; })); }
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"); string outputSTR = null; IPropertySet propertySet = new PropertySet(); propertySet.SetProperty("URL", "http://localhost:6080/arcgis/admin"); propertySet.SetProperty("USER", "yourServerAdminUsername") ; propertySet.SetProperty("PASSWORD", "yourServerAdminPassword"); propertySet.SetProperty("ConnectionMode", esriAGSConnectionMode.esriAGSConnectionModeAdmin); propertySet.SetProperty("ServerType", esriAGSServerType.esriAGSServerTypeDiscovery); IAGSServerConnectionFactory agsServerConnectionFactory = new AGSServerConnectionFactory(); IAGSServerConnectionAdmin agsServerConnection = agsServerConnectionFactory.Open(propertySet, 0) as IAGSServerConnectionAdmin; IServerObjectAdmin servAdmin = agsServerConnection.ServerObjectAdmin; IEnumServerDirectory pEnumServDir = servAdmin.GetServerDirectories(); pEnumServDir.Reset(); IServerDirectory2 pServDir = pEnumServDir.Next() as IServerDirectory2; while (pServDir != null) { string cleaningMd = pServDir.CleaningMode.ToString(); //cleanup mode string descrip = pServDir.Description.ToString(); //Description int fileAge = pServDir.MaxFileAge; //Max File Age string path = pServDir.Path; //physical path string url = pServDir.URL; //virtual path string type = pServDir.Type.ToString(); pServDir = pEnumServDir.Next() as IServerDirectory2; outputSTR = outputSTR + "cleanup mode: " + cleaningMd + "\n" + "Description: " + descrip + "\n" + "Max File Age: " + fileAge + "\n" + "physical path: " + path + "\n" + "virtual path: " + url + "\n" + "type: " + type.ToString() + "\r\n"; } JsonObject result = new JsonObject(); result.AddString("parm1", parm1Value); result.AddString("parm2", outputSTR); return Encoding.UTF8.GetBytes(result.ToJson()); }
private byte[] OperazioneRestDownloadFeatureHandler(NameValueCollection boundVariables, JsonObject operationInput, string outputFormat, string requestProperties, out string responseProperties) { responseProperties = null; #region Istanzio il JSON Result JsonObject result = new JsonObject(); result.AddBoolean("hasError", false); #endregion bool found = operationInput.TryGetArray("listaOID", out object[] paramListaOID); if (!found || paramListaOID == null) { throw new ArgumentNullException("listaOID"); } bool okParam2 = operationInput.TryGetString("URLServiceLayer", out string paramURL); if (!okParam2 || paramURL == String.Empty) { throw new ArgumentNullException("URLServiceLayer"); } IGeoProcessor2 gp = new GeoProcessor() as IGeoProcessor2; gp.OverwriteOutput = true; try { result.AddArray("interno", paramListaOID); // Ricavo Feature Class dietro al Service Layer IFeatureClass featureClass = MapServiceHelper_GiancaGIS.RicavaFCDaURLServiceLayer(this.serverObjectHelper, paramURL); IFeatureLayer fLayer = new FeatureLayerClass { FeatureClass = featureClass, Name = "Mio Layer", SpatialReference = ((IGeoDataset)featureClass).SpatialReference }; IFeatureSelection featureSelection = fLayer as IFeatureSelection; IQueryFilter2 queryFilter = new QueryFilterClass { WhereClause = "OBJECTID IN (" + String.Join(",", paramListaOID) + ")" }; featureSelection.SelectFeatures(queryFilter, esriSelectionResultEnum.esriSelectionResultNew, false); this.CreaWorkSpaceOutput(out IWorkspaceName WorkspaceNameOUT, out string pathFGDB); IVariantArray parameters = new VarArrayClass(); parameters.Add(fLayer); parameters.Add(System.IO.Path.Combine(pathFGDB, "output")); gp.Execute("CopyFeatures_management", parameters, null); this.ZippaFGDB(System.IO.Path.GetDirectoryName(pathFGDB), out string pathZip); result.AddString("zip", pathZip); } catch (Exception errore) { object severity = null; string errGp = gp.GetMessages(ref severity); if (!string.IsNullOrEmpty(errGp)) { result.AddBoolean("GeoProcessingError", true); result.AddString("erroreGp", errGp); } result.AddString("errorDescription", errore.Message); result.AddBoolean("hasError", true); } return(Encoding.UTF8.GetBytes(result.ToJson())); }