/// <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); } }
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[] DeleteOperHandler(NameValueCollection boundVariables, JsonObject operationInput, string outputFormat, string requestProperties, out string responseProperties) { responseProperties = null; object[] fileNames; bool found = operationInput.TryGetArray("fileNames", out fileNames); if (!found || fileNames == null || fileNames.Length == 0) { throw new ArgumentNullException("fileNames"); } JsonObject result = new JsonObject(); ExportMap export = new ExportMap(); bool tmpIsOk = false; string outMsg = string.Empty; List <string> fileList = new List <string>(); foreach (object o in fileNames) { fileList.Add(o.ToString()); } tmpIsOk = export.DeleteFile(fileList, out outMsg); result.AddBoolean("deleted", tmpIsOk); result.AddString("errMsg", outMsg); return(Encoding.UTF8.GetBytes(result.ToJson())); }
/// <summary> /// return a object JsonObject /// </summary> /// <returns>object Json Object</returns> public override JsonObject ToJsonObject() { JsonObject result = base.ToJsonObject(); result.AddString("errorDescription", this.Message); result.AddBoolean("hasError", true); return(result); }
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[] 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())); }
private byte[] DeleteFeaturesOperHandler(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 can not parse to jsonobject"); } JsonObject joFC; found = operationInput.TryGetJsonObject("featureClass", out joFC); if (!found || joFC == null) { throw new ArgumentNullException("featureClass can not parse to jsonobject"); } JsonObject joFilter; found = operationInput.TryGetJsonObject("filterWhere", out joFilter); if (!found || joFilter == null) { throw new ArgumentNullException("filterWhere can not parse to jsonobject"); } JsonObject result = new JsonObject(); ConnectionJSObject connJsObj = ParamsParser.ParseConn(joConn); FeatureClassJSObject fcObj = ParamsParser.ParseFeatrureClass(joFC); FilterWhereJSObject filterObj = ParamsParser.ParseFilterWhere(joFilter); bool isok = false; int count = 0; string outMsg = string.Empty; FeaturesHelper helper = new FeaturesHelper(); isok = helper.DeleteFeatures(connJsObj, fcObj, filterObj, out count, out outMsg); result.AddBoolean("isSucess", isok); result.AddLong("recordCount", count); result.AddString("outMsg", outMsg); return(Encoding.UTF8.GetBytes(result.ToJson())); }
/// <summary> /// Operation Dynamic Layer /// </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>Dynamic Layer</returns> private byte[] DynamicLayerOperationHandler(NameValueCollection boundVariables, JsonObject operationInput, string outputFormat, string requestProperties, out string responseProperties) { responseProperties = "{\"Content-Type\" : \"application/json\"}"; try { JsonObject featureSet; bool found = operationInput.TryGetJsonObject("featureSet", out featureSet); if (!found) { throw new ArgumentNullException(nameof(featureSet)); } if (this.workspace == null) { throw new FactoryUtilitiesException("Workspace non impostato!"); } if (string.IsNullOrWhiteSpace(this.workspaceId)) { throw new FactoryUtilitiesException("WorkspaceId non impostato!"); } IJSONReader jsonReader = new JSONReaderClass(); jsonReader.ReadFromString(featureSet.ToJson()); IJSONConverterGdb JSONConverterGdb = new JSONConverterGdbClass(); IPropertySet originalToNewFieldMap; IRecordSet recorset; JSONConverterGdb.ReadRecordSet(jsonReader, null, null, out recorset, out originalToNewFieldMap); IRecordSet2 recordSet2 = recorset as IRecordSet2; string featureClassName = string.Format("D{0}{1}", DateTime.Now.ToString("yyyyMMdd"), Guid.NewGuid().ToString()).Replace("-", ""); recordSet2.SaveAsTable(this.workspace, featureClassName); JsonObject result = new JsonObject(); result.AddString("name", featureClassName); result.AddString("workspaceId", this.workspaceId); result.AddBoolean("hasError", false); return(result.JsonByte()); } catch (Exception ex) { ObjectError o = new ObjectError(ex.Message); return(o.ToJsonObject().JsonByte()); } }
/// <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> /// 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()); } }
/// <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[] 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> /// 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; })); }
/// <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; } }
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()); }
/// <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; } }
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())); }