public JsonObject ToJsonObject() { JsonObject result = new JsonObject(); if (Attributes.Count > 0) { JsonObject attributes = new JsonObject(); foreach (KeyValuePair<string, object> kvp in Attributes) { attributes.AddObject(kvp.Key, kvp.Value); } result.AddJsonObject("attributes", attributes); } if (Geometry != null) { result.AddJsonObject("geometry", Conversion.ToJsonObject(Geometry)); } return result; }
public JsonObject ToJsonObject() { var output = new JsonObject(); output.AddJsonObject("geometry", Conversion.ToJsonObject(Geometry)); output.AddJsonObject("routeLocation", RouteLocation.ToJsonObject()); output.AddString("locatingError", Enum.GetName(typeof(esriLocatingError), LocatingError)); return(output); }
/// <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[] HelpResourceHandler(NameValueCollection boundVariables, string outputFormat, string requestProperties, out string responseProperties) { responseProperties = "{\"Content-Type\" : \"application/json\"}"; JsonObject result = new JsonObject(); JsonObject extractDataInputs = new JsonObject(); extractDataInputs.AddString("featureSet", "(string) featureSet Esri Json (obbligatorio solo per GDB/FeatureClass, Shapefile, CSV, KML)"); extractDataInputs.AddString("dataFormat", $"(string) valori consentiti: {string.Join(",", Enum.GetNames(typeof(DataFormat)))}"); extractDataInputs.AddString("outputName", "(string) nome del GDB/FeatureClass, Shapefile, CSV, KML o KMZ. Può contenere solo lettere o numeri. Il primo carattere non può essere un numero (nel caso viene messo il prefisso 'f') e, per il formato shapefile, non è possibile indicare più di 8 caratteri"); extractDataInputs.AddString("urlLayer", "(string) url del layer del servizio (obbligatorio solo per kmz)"); extractDataInputs.AddString("geometry", "(geometry) polygon Esri Json (obbligatorio solo per kmz)"); extractDataInputs.AddString("token", "(string) opzionale token se il servizio dell'urlLayer è protetto (solo per kmz)"); JsonObject extractDataOutputs = new JsonObject(); extractDataOutputs.AddString("url", "(string) url del file di output in formato compresso (.zip)"); extractDataOutputs.AddString("extraInfo", "(object) facoltativo. Per la conversione dello shapefile saranno presenti o meno due array di stringhe ('errorField' e 'invalidObjectID') se sono presenti errori di creazione campi o di creazione record"); extractDataOutputs.AddString("hasError", "(boolean). Indica se l'operazione ha un errore"); extractDataOutputs.AddString("errorDescription", "(string). Presente se hasError è true"); JsonObject extractDataParams = new JsonObject(); extractDataParams.AddString("Info", "Converte un featureSet (formato Json Esri) in file geodatabase, shapefile, csv o kmz. Il csv è consentito solo per temi di tipo point. Il kmz sarà proiettato in WGS84 ma senza trasformazione di datum"); extractDataParams.AddJsonObject("Inputs", extractDataInputs); extractDataParams.AddJsonObject("Outputs", extractDataOutputs); JsonObject dynamicLayerInputs = new JsonObject(); dynamicLayerInputs.AddString("featureSet", "(string) featureSet Esri Json"); JsonObject dynamicLayerOutputs = new JsonObject(); dynamicLayerOutputs.AddString("name", "(string) nome della feature class"); dynamicLayerOutputs.AddString("workspaceId", "(string) workspaceId"); dynamicLayerOutputs.AddString("hasError", "(boolean). Indica se l'operazione ha un errore"); dynamicLayerOutputs.AddString("errorDescription", "(string). Presente se hasError è true"); JsonObject dynamicLayerParams = new JsonObject(); dynamicLayerParams.AddString("Info", "Dynamic layer"); dynamicLayerParams.AddJsonObject("Inputs", dynamicLayerInputs); dynamicLayerParams.AddJsonObject("Outputs", dynamicLayerOutputs); JsonObject soeOperations = new JsonObject(); soeOperations.AddJsonObject("ExtractData", extractDataParams); soeOperations.AddJsonObject("DynamicLayer", dynamicLayerParams); result.AddJsonObject("Operations", soeOperations); return(result.JsonByte()); }
/// <summary> /// 将要素类序列化成json格式对象 /// </summary> /// <param name="inputFeaClass">输入要素类</param> /// <returns></returns> public static JsonObject FclassToJsonObj(IFeatureClass inputFeaClass) { //获取要素数目 IQueryFilter pQueryFilter = new QueryFilterClass(); pQueryFilter.WhereClause = null; int count = inputFeaClass.FeatureCount(pQueryFilter); //将每一个要素序列化成json数据 IFeature pFeature = null; List <JsonObject> jsonGeometries = new List <JsonObject>(); for (int i = 1; i < count; i++)//OBJECTID从1开始 { pFeature = inputFeaClass.GetFeature(i); IGeometry pGeometry = pFeature.Shape; JsonObject featureJson = new JsonObject(); JsonObject feaGeoJson = null;//几何对象 if (pGeometry != null) { feaGeoJson = Conversion.ToJsonObject(pGeometry); featureJson.AddJsonObject("geometry", feaGeoJson);//加入几何对象 } jsonGeometries.Add(featureJson); } JsonObject resultJson = new JsonObject(); resultJson.AddArray("geometries", jsonGeometries.ToArray()); return(resultJson); }
/// <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); } }
/// <summary> /// convert the current instance in JsonObject /// </summary> /// <returns>object JsonObject</returns> public JsonObject ToJsonObject() { byte[] bytes = Conversion.ToJson(this.Extent); JsonObject jo = new JsonObject(Encoding.UTF8.GetString(bytes)); IEnvelope envelope = this.Extent; if (!jo.Exists("spatialReference")) { if (envelope.SpatialReference.FactoryCode == 0) { jo.AddString("spatialReference", envelope.SpatialReference.Name); } else { jo.AddLong("spatialReference", (long)envelope.SpatialReference.FactoryCode); } } JsonObject jsonObjectRouteLayerInfo = new JsonObject(); jsonObjectRouteLayerInfo.AddString("name", this.Name); jsonObjectRouteLayerInfo.AddLong("id", (long)this.Id); jsonObjectRouteLayerInfo.AddJsonObject("extent", jo); return(jsonObjectRouteLayerInfo); }
private byte[] AnalisiGeomarketingSketchHandler(NameValueCollection boundVariables, JsonObject operationInput, string outputFormat, string requestProperties, out string responseProperties) { #region Istanzio il JSON Result JsonObject result = new JsonObject(); result.AddBoolean("hasError", false); #endregion this.RicavaInfoFc(); responseProperties = null; IGeometry geomSketch = null; JsonObject jsonPoligono = null; // CoClass ESRI per object JSON // Controllo che il TAG nel JSON 'punto' di input ci sia: if (!operationInput.TryGetJsonObject("geomSketch", out jsonPoligono)) { throw new ArgumentNullException("geomSketch"); } geomSketch = Conversion.ToGeometry(jsonPoligono, esriGeometryType.esriGeometryPolygon) as IGeometry; if (geomSketch == null) { result.AddString("errorDescription", "GiancaGIS REST SOE Geometrie: punto invalido!"); result.AddBoolean("hasError", true); throw new ArgumentException("GiancaGIS REST SOE Geometrie: punto invalido!"); } try { IRecordSet2 recordSet = this.AnalisiSpazSketchOper(geomSketch); if (recordSet.IsFeatureCollection) { result.AddJsonObject("clientiInterno", new JsonObject(Encoding.UTF8.GetString(Conversion.ToJson(recordSet)))); } else { result.AddString("clientiInterno", "Nessun cliente nell'area selezionata!"); } } catch (Exception errore) { result.AddString("errorDescription", errore.Message); result.AddBoolean("hasError", true); } return(Encoding.UTF8.GetBytes(result.ToJson())); }
private byte[] GetFeaturesOperHandler(NameValueCollection boundVariables, JsonObject operationInput, string outputFormat, string requestProperties, out string responseProperties) { responseProperties = null; JsonObject joConn; bool found = operationInput.TryGetJsonObject("connectionString", out joConn); if (!found || joConn == null) { throw new ArgumentNullException("connectionString"); } JsonObject joFC; found = operationInput.TryGetJsonObject("featureClass", out joFC); if (!found || joFC == null) { throw new ArgumentNullException("featureClass"); } JsonObject joFilter; found = operationInput.TryGetJsonObject("filterWhere", out joFilter); if (!found || joFilter == null) { throw new ArgumentNullException("filterWhere"); } JsonObject result = new JsonObject(); ConnectionJSObject connJsObj = ParamsParser.ParseConn(joConn); FeatureClassJSObject fcObj = ParamsParser.ParseFeatrureClass(joFC); FilterWhereJSObject filterObj = ParamsParser.ParseFilterWhere(joFilter); List <FeatureObject> features; string outMsg = string.Empty; FeaturesHelper helper = new FeaturesHelper(); features = helper.GetFeatures(connJsObj, fcObj, filterObj, out outMsg); List <JsonObject> featureList = new List <JsonObject>(); foreach (FeatureObject fo in features) { JsonObject jo = new JsonObject(); jo.AddArray("attributes", fo.attributes.ToArray()); jo.AddJsonObject("geometry", Conversion.ToJsonObject(fo.geometry)); featureList.Add(jo); } result.AddArray("features", featureList.ToArray()); result.AddString("outMsg", outMsg); return(Encoding.UTF8.GetBytes(result.ToJson())); }
/// <summary> /// convert the current instance in JsonObject /// </summary> /// <returns>object JsonObject</returns> public JsonObject ToJsonObject() { byte[] bytes = Conversion.ToJson(this.Extent); JsonObject jo = new JsonObject(Encoding.UTF8.GetString(bytes)); if (!jo.Exists("spatialReference")) { if (this.SpatialReference.FactoryCode == 0) { jo.AddString("spatialReference", this.SpatialReference.Name); } else { jo.AddLong("spatialReference", (long)this.SpatialReference.FactoryCode); } } JsonObject jsonObjectGeometricNetworkInfo = new JsonObject(); jsonObjectGeometricNetworkInfo.AddString("name", this.Name); jsonObjectGeometricNetworkInfo.AddLong("id", (long)this.ID); jsonObjectGeometricNetworkInfo.AddJsonObject("extent", jo); INetSchema netSchema = (INetSchema)this.GeometricNetwork.Network; INetWeight netWeight; List <JsonObject> weights = new List <JsonObject>(); for (int i = 0; i < netSchema.WeightCount; i++) { netWeight = netSchema.get_Weight(i); JsonObject weight = new JsonObject(); weight.AddLong("id", (long)netWeight.WeightID); weight.AddString("name", netWeight.WeightName); weight.AddString("type", Enum.GetName(typeof(esriWeightType), netWeight.WeightType)); weight.AddLong("bitGateSize", (long)netWeight.BitGateSize); List <JsonObject> weightAssociation = new List <JsonObject>(); IEnumNetWeightAssociation enumNetWeightAssociation = netSchema.get_WeightAssociations(netWeight.WeightID); INetWeightAssociation netWeightAssociation = enumNetWeightAssociation.Next(); while (netWeightAssociation != null) { JsonObject jsonObjectNetWeightAssociation = new JsonObject(); jsonObjectNetWeightAssociation.AddString("fieldName", netWeightAssociation.FieldName); jsonObjectNetWeightAssociation.AddString("tableName", netWeightAssociation.TableName); weightAssociation.Add(jsonObjectNetWeightAssociation); netWeightAssociation = enumNetWeightAssociation.Next(); } weight.AddArray("weightAssociation", weightAssociation.ToArray()); weights.Add(weight); } jsonObjectGeometricNetworkInfo.AddArray("weights", weights.ToArray()); return(jsonObjectGeometricNetworkInfo); }
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 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); }
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.AddLong("id", ID); jo.AddJsonObject("extent", env); return jo; }
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.AddLong("id", ID); jo.AddJsonObject("extent", env); return(jo); }
/// <summary> /// Convert to JsonObject /// </summary> /// <returns>return JsonObject of instance</returns> public JsonObject ToJsonObject() { JsonObject jsonObject = new JsonObject(); jsonObject.AddLong("id", this.MapLayerInfo.ID); jsonObject.AddString("name", this.MapLayerInfo.Name); jsonObject.AddString("type", this.MapLayerInfo.Type); JsonObject env = Conversion.ToJsonObject((IGeometry)this.MapLayerInfo.Extent, true); jsonObject.AddJsonObject("full extent", env); jsonObject.AddString("description", this.MapLayerInfo.Description); return(jsonObject); }
public byte[] HandleRESTRequest(string Capabilities, string resourceName, string operationName, string operationInput, string outputFormat, string requestProperties, out string responseProperties) { responseProperties = null; // Find the correct delegate to forward the request too IRESTRequestHandler restRequestHandler = _restSOIHelper.FindRequestHandlerDelegate <IRESTRequestHandler>(); if (restRequestHandler == null) { return(null); } /* * Add code to manipulate REST requests here */ //Note: if you want to have a clipping and spatial filter SOI for security reasons, // you must have your own custom implementation for the Query operation. // Clipping and SpatialFilter are not support in a query operation if (operationName == "export" || operationName == "identify" || operationName == "find") { var joOperationInput = new JsonObject(operationInput); if (joOperationInput.Exists("clipping")) { joOperationInput.Delete("clipping"); } var joSpatialFilter = new JsonObject(); joSpatialFilter.AddArray("excludedLayers", new object[] { }); joSpatialFilter.AddString("geometryType", "esriGeometryPolygon"); joSpatialFilter.AddJsonObject("geometry", CreateACircle()); joOperationInput.AddJsonObject("clipping", joSpatialFilter); operationInput = joOperationInput.ToJson(); } return(restRequestHandler.HandleRESTRequest( Capabilities, resourceName, operationName, operationInput, outputFormat, requestProperties, out responseProperties)); }
/// <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; })); }
//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); }
/// <summary> /// Operation Extract Data /// </summary> /// <param name="boundVariables">bound Variables</param> /// <param name="operationInput">operation Input</param> /// <param name="outputFormat">output Format</param> /// <param name="requestProperties">request Properties</param> /// <param name="responseProperties">response Properties</param> /// <returns>Extract Data</returns> private byte[] ExtractDataOperationHandler(NameValueCollection boundVariables, JsonObject operationInput, string outputFormat, string requestProperties, out string responseProperties) { responseProperties = "{\"Content-Type\" : \"application/json\"}"; try { // input parameters // input data format string dataFormatValue; bool found = operationInput.TryGetString("dataFormat", out dataFormatValue); if (!found || string.IsNullOrEmpty(dataFormatValue)) { throw new ArgumentNullException(nameof(dataFormatValue)); } DataFormat dataFormat; if (!Enum.TryParse <DataFormat>(dataFormatValue, out dataFormat)) { throw new ArgumentNullException(nameof(dataFormatValue)); } // il parametro urlLayer e geometry sono obbligatorio per il KMZ string urlLayerValue = null; JsonObject geometryValue = null; string tokenValue = null; // input featureset JsonObject featureSetValue = null; if (dataFormat == DataFormat.KMZ) { found = operationInput.TryGetString("urlLayer", out urlLayerValue); if (!found || string.IsNullOrEmpty(urlLayerValue)) { throw new ArgumentNullException(nameof(urlLayerValue)); } urlLayerValue = urlLayerValue.TrimEnd('/'); found = operationInput.TryGetString("token", out tokenValue); found = operationInput.TryGetJsonObject("geometry", out geometryValue); if (!found) { throw new ArgumentNullException(nameof(geometryValue)); } } else { found = operationInput.TryGetJsonObject("featureSet", out featureSetValue); if (!found) { throw new ArgumentNullException(nameof(featureSetValue)); } } // input outputName string outputNameValue; found = operationInput.TryGetString("outputName", out outputNameValue); if (!found || string.IsNullOrEmpty(outputNameValue)) { throw new ArgumentNullException(nameof(outputNameValue)); } // lascio solo caratteri e numeri outputNameValue = new String(outputNameValue.Where(Char.IsLetterOrDigit).ToArray()); if (string.IsNullOrEmpty(outputNameValue)) { throw new ArgumentNullException(nameof(outputNameValue)); } // se il nome inizia con un numero metto davanti una lettera if (Char.IsDigit(outputNameValue.FirstOrDefault())) { outputNameValue = $"f{outputNameValue}"; } // se il formato è shapefile il nome del file lo tronco a max 8 caratteri if ((dataFormat == DataFormat.SHAPEFILE) && (outputNameValue.Length > 8)) { outputNameValue = outputNameValue.Substring(0, 8); } // creazione cartella di output string folderNameOutput = Guid.NewGuid().ToString(); string pathOutput = System.IO.Path.Combine(this.pathOutputAGS, folderNameOutput); if (Directory.Exists(pathOutput)) { // non dovrebbe mai verificarsi throw new FactoryUtilitiesException($"Cartella {pathOutput} già esistente"); } else { Directory.CreateDirectory(pathOutput); } // cartella kmz string kmzFolder = null; // cartella shapefile string shapefileFolder = null; // cartella csv string csvFolder = null; // cartella kml string kmlFolder = null; // file geodatabase string fGDBFolder = null; JsonObject message = null; if (dataFormat == DataFormat.KMZ) { kmzFolder = System.IO.Path.Combine(pathOutput, "kmz"); Directory.CreateDirectory(kmzFolder); this.ConvertFeatureClassPointToKmz(urlLayerValue, geometryValue, tokenValue, outputNameValue, kmzFolder); } else { List <string> errorFieldShapeFile = null; List <string> invalidObjectIDShapeFile = null; IJSONReader jsonReader = new JSONReaderClass(); jsonReader.ReadFromString(featureSetValue.ToJson()); IJSONConverterGdb JSONConverterGdb = new JSONConverterGdbClass(); IPropertySet originalToNewFieldMap; IRecordSet recorset; JSONConverterGdb.ReadRecordSet(jsonReader, null, null, out recorset, out originalToNewFieldMap); IRecordSet2 recordSet2 = recorset as IRecordSet2; ITable t = null; IWorkspace workspaceGDB = null; try { // nome del file geodatabase con estensione string nameGDB = System.IO.Path.ChangeExtension(outputNameValue, Enum.GetName(typeof(FileExtension), FileExtension.gdb)); // creazione del file geodatabase workspaceGDB = Helper.CreateFileGdbWorkspace(pathOutput, nameGDB); t = recordSet2.SaveAsTable(workspaceGDB, outputNameValue); if (dataFormat == DataFormat.SHAPEFILE) { shapefileFolder = System.IO.Path.Combine(pathOutput, Enum.GetName(typeof(DataFormat), DataFormat.SHAPEFILE).ToLowerInvariant()); errorFieldShapeFile = new List <string>(); invalidObjectIDShapeFile = new List <string>(); Directory.CreateDirectory(shapefileFolder); this.ConvertFeatureClassToShapefile(workspaceGDB, outputNameValue, shapefileFolder, ref errorFieldShapeFile, ref invalidObjectIDShapeFile); if ((errorFieldShapeFile.Count > 0) || (invalidObjectIDShapeFile.Count > 0)) { message = new JsonObject(); message.AddArray("errorField", errorFieldShapeFile.ToArray()); message.AddArray("invalidObjectID", invalidObjectIDShapeFile.ToArray()); } } else if (dataFormat == DataFormat.CSV) { csvFolder = System.IO.Path.Combine(pathOutput, Enum.GetName(typeof(DataFormat), DataFormat.CSV).ToLowerInvariant()); Directory.CreateDirectory(csvFolder); this.ConvertFeatureClassPointToCsv(workspaceGDB, outputNameValue, csvFolder); } else if (dataFormat == DataFormat.KML) { // funzione per creare il file kml con la libreria SharpKml // file è senza render kmlFolder = System.IO.Path.Combine(pathOutput, Enum.GetName(typeof(DataFormat), DataFormat.KML).ToLowerInvariant()); Directory.CreateDirectory(kmlFolder); this.ConvertFeatureClassPointToKml(workspaceGDB, outputNameValue, kmlFolder); } else if (dataFormat == DataFormat.FILEGEODATABASE) { fGDBFolder = System.IO.Path.Combine(pathOutput, nameGDB); } } catch { throw; } finally { Marshal.FinalReleaseComObject(t); Marshal.FinalReleaseComObject(workspaceGDB); } } // nome del file zip con estensione string nameZip = System.IO.Path.ChangeExtension(outputNameValue, Enum.GetName(typeof(FileExtension), FileExtension.zip)); // percorso e nome file zip con estensione string pathFileOutputZip = System.IO.Path.Combine(pathOutput, nameZip); if (dataFormat == DataFormat.FILEGEODATABASE) { ZipFile.CreateFromDirectory(fGDBFolder, pathFileOutputZip, CompressionLevel.Fastest, true); } else if (dataFormat == DataFormat.SHAPEFILE) { ZipFile.CreateFromDirectory(shapefileFolder, pathFileOutputZip, CompressionLevel.Fastest, true); } else if (dataFormat == DataFormat.CSV) { ZipFile.CreateFromDirectory(csvFolder, pathFileOutputZip, CompressionLevel.Fastest, true); } else if (dataFormat == DataFormat.KML) { ZipFile.CreateFromDirectory(kmlFolder, pathFileOutputZip, CompressionLevel.Fastest, true); } else if (dataFormat == DataFormat.KMZ) { ZipFile.CreateFromDirectory(kmzFolder, pathFileOutputZip, CompressionLevel.Fastest, true); } JsonObject result = new JsonObject(); result.AddString("url", Helper.CombineUri(this.pathOutputVirtualAGS, Helper.CombineUri(folderNameOutput, nameZip))); result.AddBoolean("hasError", false); if (message != null) { result.AddJsonObject("extraInfo", message); } return(result.JsonByte()); } catch (Exception ex) { ObjectError o = new ObjectError(ex.Message); return(o.ToJsonObject().JsonByte()); } }
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 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; }
/// <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; } }
/// <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> /// 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()); }
/// <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()); }
/// <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[] AnalGeomBufferHandler(NameValueCollection boundVariables, JsonObject operationInput, string outputFormat, string requestProperties, out string responseProperties) { responseProperties = null; long?paramOID; bool found = operationInput.TryGetAsLong("OBJECTID", out paramOID); if (!found || !paramOID.HasValue) { throw new ArgumentNullException("OBJECTID invalido!"); } long?paramBuffer1; found = operationInput.TryGetAsLong("bufferCerchio1", out paramBuffer1); if (!found || !paramBuffer1.HasValue) { throw new ArgumentNullException("Valore Buffer1 invalido!!"); } long?paramBuffer2; found = operationInput.TryGetAsLong("bufferCerchio2", out paramBuffer2); if (!found || !paramBuffer2.HasValue) { throw new ArgumentNullException("Valore Buffer2 invalido!!"); } long?paramBuffer3; found = operationInput.TryGetAsLong("bufferCerchio3", out paramBuffer3); if (!found || !paramBuffer3.HasValue) { throw new ArgumentNullException("Valore Buffer3 invalido!!"); } this.RicavaInfoFc(); IFeature feature = null; this.RicavaFeatureFiliare(paramOID.Value, out feature); Dictionary <long, IPolygon> dizGeometrieBuffer = this.CostruisciBuffer(feature, paramBuffer1.Value, paramBuffer2.Value, paramBuffer3.Value); List <IRecordSet2> listaRecordSet = this.AnalisiSpazialiBufferOper(dizGeometrieBuffer); JsonObject result = new JsonObject(); result.AddJsonObject("interno", new JsonObject(Encoding.UTF8.GetString(Conversion.ToJson(listaRecordSet[0])))); result.AddJsonObject("centrale", new JsonObject(Encoding.UTF8.GetString(Conversion.ToJson(listaRecordSet[1])))); result.AddJsonObject("superiore", new JsonObject(Encoding.UTF8.GetString(Conversion.ToJson(listaRecordSet[2])))); #region Mi occupo di tirare fuori le Geometrie dei Buffer circolari e serializzarle List <IGeometry> listaGeometrie = new List <IGeometry>(); foreach (KeyValuePair <long, IPolygon> coppia in dizGeometrieBuffer) { // ATTENZIONE!!! // GLI ARCOBJECTS (METODO CONVERSION - SOE_SUPPORT) NON GESTISCE L'INSERIMENTO DI CURVE NEL JSON. // UNA TRUE CURVE DEVE ESSERE SEMPLIFICATA - DENSIFICATA COME UN INSIEME DI SEGMENTI (es: shapefile) // PRIMA DI ESSERE RESTITUITA AL CLIENT!! IPolycurve polycurve = coppia.Value as IPolycurve; polycurve.Densify(5, 0); IGeometry geo = polycurve as IGeometry; geo.SpatialReference = ((IGeoDataset)fcClienti).SpatialReference; listaGeometrie.Add(geo); } object[] objArray = Helper.GetListJsonObjects(listaGeometrie); #endregion result.AddArray("geomBuffer", objArray); return(Encoding.UTF8.GetBytes(result.ToJson())); }
//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; }
/// <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); }
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())); }
/// <summary> /// solve isolation /// </summary> /// <returns>object JsonObject</returns> public override JsonObject Solve() { try { if ((this.edgeFlags.Length == 0) && (this.junctionFlags.Length == 0)) { string message = "No input valid flags found"; if (this.flagNotFound.Count == 0) { throw new GeometricNetworkException(message); } else { JsonObject error = (new ObjectError(message)).ToJsonObject(); error.AddArray("flagsNotFound", Helper.GetListJsonObjects(this.flagNotFound)); return(error); } } INetwork network = this.geometricNetwork.Network; ITraceFlowSolverGEN traceFlowSolver = new TraceFlowSolverClass() as ITraceFlowSolverGEN; INetSolver netSolver = traceFlowSolver as INetSolver; netSolver.SourceNetwork = network; this.SetFlagsOrigin(ref traceFlowSolver); ////now create barries based on valves INetElementBarriersGEN netElementBarriersGEN = new NetElementBarriersClass() as INetElementBarriersGEN; netElementBarriersGEN.ElementType = esriElementType.esriETJunction; netElementBarriersGEN.Network = network; int[] userIds = Helper.GetOIDs(this.Valve); netElementBarriersGEN.SetBarriers(this.Valve.FeatureClassID, ref userIds); INetElementBarriers netElementBarriers = netElementBarriersGEN as INetElementBarriers; netSolver.set_ElementBarriers(esriElementType.esriETJunction, netElementBarriers); IEnumNetEID junctionEIDs; IEnumNetEID edgeEIDs; traceFlowSolver.FindFlowEndElements(esriFlowMethod.esriFMConnected, esriFlowElements.esriFEJunctionsAndEdges, out junctionEIDs, out edgeEIDs); IEIDHelper eidHelper = new EIDHelperClass(); eidHelper.GeometricNetwork = this.geometricNetwork; eidHelper.ReturnFeatures = true; List <IEIDInfo> valveEIDInfoHT = Helper.GetEIDInfoListByFeatureClass(this.Valve.FeatureClassID, junctionEIDs, eidHelper); traceFlowSolver = new TraceFlowSolverClass() as ITraceFlowSolverGEN; netSolver = traceFlowSolver as INetSolver; netSolver.SourceNetwork = network; this.SetFlagsOrigin(ref traceFlowSolver); netSolver.DisableElementClass(this.Station.FeatureClassID); traceFlowSolver.FindFlowEndElements(esriFlowMethod.esriFMConnected, esriFlowElements.esriFEJunctions, out junctionEIDs, out edgeEIDs); List <IEIDInfo> sourceEIDInfoHT = Helper.GetEIDInfoListByFeatureClass(this.Station.FeatureClassID, junctionEIDs, eidHelper); ////set up trace to find directly reachable sources traceFlowSolver = new TraceFlowSolverClass() as ITraceFlowSolverGEN; netSolver = traceFlowSolver as INetSolver; netSolver.SourceNetwork = network; this.SetFlagsOrigin(ref traceFlowSolver); ////set barriers in the network based on the saved valves ISelectionSetBarriers netElementBarrier = new SelectionSetBarriersClass(); foreach (IEIDInfo eidInfo in valveEIDInfoHT) { netElementBarrier.Add(this.Valve.FeatureClassID, eidInfo.Feature.OID); } netSolver.SelectionSetBarriers = netElementBarrier; ////run trace to find directly reachable sources(without passing valve) traceFlowSolver.FindFlowElements(esriFlowMethod.esriFMConnected, esriFlowElements.esriFEJunctionsAndEdges, out junctionEIDs, out edgeEIDs); List <IEIDInfo> sourceDirectEIDInfoHT = Helper.GetEIDInfoListByFeatureClass(this.Station.FeatureClassID, junctionEIDs, eidHelper); ////remove directly reachable sources from source array foreach (IEIDInfo eidInfo in sourceDirectEIDInfoHT) { sourceEIDInfoHT.RemoveAll(x => x.Feature.OID == eidInfo.Feature.OID); } List <IEIDInfo> noSourceValveHT = new List <IEIDInfo>(); List <IEIDInfo> hasSourceValveHT = new List <IEIDInfo>(); List <int> listBarrierIds; bool foundSource; foreach (IEIDInfo valve in valveEIDInfoHT) { foundSource = false; ////create array of all isolation valve excluding the current one listBarrierIds = new List <int>(); if (valveEIDInfoHT.Count > 1) { listBarrierIds.AddRange(valveEIDInfoHT.ConvertAll <int>(i => i.Feature.OID)); if (listBarrierIds.Contains(valve.Feature.OID)) { listBarrierIds.Remove(valve.Feature.OID); } } ////for each source attempt to trace INetFlag netFlag1; INetFlag netFlag2; foreach (IEIDInfo source in sourceEIDInfoHT) { ////setup trace to test each valve traceFlowSolver = new TraceFlowSolverClass() as ITraceFlowSolverGEN; netSolver = traceFlowSolver as INetSolver; netSolver.SourceNetwork = network; ////set the first junction flag for path finding based this current valve netFlag1 = new JunctionFlagClass(); netFlag1.UserClassID = valve.Feature.Class.ObjectClassID; netFlag1.UserID = valve.Feature.OID; netFlag1.UserSubID = 0; netFlag1.Label = "Origin"; ////set the second and last trace flag at this source netFlag2 = new JunctionFlagClass(); netFlag2.UserClassID = source.Feature.Class.ObjectClassID; netFlag2.UserID = source.Feature.OID; netFlag2.UserSubID = 0; netFlag2.Label = "Destination"; Helper.AddTwoJunctionFlagsToTraceSolver(ref traceFlowSolver, netFlag1, netFlag2); if (listBarrierIds.Count > 0) { netElementBarriersGEN = new NetElementBarriersClass() as INetElementBarriersGEN; netElementBarriersGEN.ElementType = esriElementType.esriETJunction; netElementBarriersGEN.Network = network; int[] barrierIds = listBarrierIds.ToArray(); netElementBarriersGEN.SetBarriers(this.Valve.FeatureClassID, ref barrierIds); netElementBarriers = netElementBarriersGEN as INetElementBarriers; netSolver.set_ElementBarriers(esriElementType.esriETJunction, netElementBarriers); } ////run trace object[] segCosts = new object[1]; segCosts[0] = new object(); edgeEIDs = null; traceFlowSolver.FindPath(esriFlowMethod.esriFMConnected, esriShortestPathObjFn.esriSPObjFnMinSum, out junctionEIDs, out edgeEIDs, 1, ref segCosts); if (edgeEIDs != null && edgeEIDs.Count > 0) { foundSource = true; break; } } if (foundSource) { hasSourceValveHT.Add(valve); } else { noSourceValveHT.Add(valve); } } traceFlowSolver = new TraceFlowSolverClass() as ITraceFlowSolverGEN; netSolver = traceFlowSolver as INetSolver; netSolver.SourceNetwork = network; this.SetFlagsOrigin(ref traceFlowSolver); ////set the barrier in the network based on the saved valves netElementBarrier = new SelectionSetBarriersClass(); foreach (IEIDInfo eidInfo in hasSourceValveHT) { netElementBarrier.Add(this.Valve.FeatureClassID, eidInfo.Feature.OID); } netSolver.SelectionSetBarriers = netElementBarrier; ////run last trace traceFlowSolver.FindFlowElements(esriFlowMethod.esriFMConnected, this.FlowElements, out junctionEIDs, out edgeEIDs); ////deal with out put juncEIDs and edgeEIDs JsonObject objectJson = new JsonObject(); this.SetResults(ref objectJson, edgeEIDs, junctionEIDs); objectJson.AddArray("flagsNotFound", Helper.GetListJsonObjects(this.flagNotFound)); ////valves if (hasSourceValveHT.Count > 0) { JsonObject[] featureSetValves; this.GetTrace(Helper.GetEnumNetEID(hasSourceValveHT, esriElementType.esriETJunction), out featureSetValves); objectJson.AddJsonObject("valves", featureSetValves[0]); } return(objectJson); } catch (Exception e) { return((new ObjectError(e.Message)).ToJsonObject()); } }
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()); }
/// <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 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); }