当前位置: 首页>>代码示例>>C#>>正文


C# JsonObject.TryGetAsLong方法代码示例

本文整理汇总了C#中JsonObject.TryGetAsLong方法的典型用法代码示例。如果您正苦于以下问题:C# JsonObject.TryGetAsLong方法的具体用法?C# JsonObject.TryGetAsLong怎么用?C# JsonObject.TryGetAsLong使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在JsonObject的用法示例。


在下文中一共展示了JsonObject.TryGetAsLong方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: GetRasterStatisticsOperHandler

        /*
         *该函数用来实现对影像服务中的影像进行统计,统计各波段值中的最大最小值
         *
         *
         */
        private byte[] GetRasterStatisticsOperHandler(NameValueCollection boundVariables,
                                                JsonObject operationInput,
                                                    string outputFormat,
                                                    string requestProperties,
                                                out string responseProperties)
        {
            _logger.LogMessage(ServerLogger.msgType.infoDetailed, _soename + ".GetRasterStatistics", 8000, "request received");
            if (!_supportRasterItemAccess)
                throw new ArgumentException("The image service does not have a catalog and does not support this operation");
            responseProperties = null;

            long? objectID;
            //case insensitive
            bool found = operationInput.TryGetAsLong("objectID", out objectID);
            if (!found || (objectID == null))
                throw new ArgumentNullException("ObjectID");
            IRasterCatalogItem rasterCatlogItem = null;
            IRasterBandCollection rasterBandsCol = null;
            IRasterStatistics statistics = null;
            try
            {
                //获取栅格目录
                rasterCatlogItem = _mosaicCatalog.GetFeature((int)objectID) as IRasterCatalogItem;
                if (rasterCatlogItem == null)
                {
                    _logger.LogMessage(ServerLogger.msgType.infoDetailed, _soename + ".GetRasterStatistics", 8000, "request finished with exception");
                    throw new ArgumentException("The input ObjectID does not exist");
                }
            }
            catch
            {
                _logger.LogMessage(ServerLogger.msgType.infoDetailed, _soename + ".GetRasterStatistics", 8000, "request finished with exception");
                throw new ArgumentException("The input ObjectID does not exist");
            }
            JsonObject result = new JsonObject();
            try
            {
                rasterBandsCol = (IRasterBandCollection)rasterCatlogItem.RasterDataset;
                List<object> maxvalues = new List<object>();
                List<object> minvalues = new List<object>();
                List<object> standarddeviationvalues = new List<object>();
                List<object> meanvalues = new List<object>();
                for (int i = 0; i < rasterBandsCol.Count; i++)
                {
                    statistics = rasterBandsCol.Item(i).Statistics;
                    maxvalues.Add(statistics.Maximum);
                    minvalues.Add(statistics.Minimum);
                    standarddeviationvalues.Add(statistics.StandardDeviation);
                    meanvalues.Add(statistics.Mean);
                    Marshal.ReleaseComObject(statistics);
                }

                //结果序列号
                result.AddArray("maxValues", maxvalues.ToArray());
                result.AddArray("minValues", minvalues.ToArray());
                result.AddArray("meanValues", meanvalues.ToArray());
                result.AddArray("stdvValues", standarddeviationvalues.ToArray());
            }
            catch
            {
                _logger.LogMessage(ServerLogger.msgType.infoDetailed, "GetRasterStatistics", 8000, "request completed. statistics does not exist");
            }
            finally
            {
                if (rasterBandsCol != null)
                    Marshal.ReleaseComObject(rasterBandsCol);
                if (rasterCatlogItem != null)
                    Marshal.ReleaseComObject(rasterCatlogItem);
            }
            _logger.LogMessage(ServerLogger.msgType.infoDetailed, _soename + ".GetRasterStatistics", 8000, "request completed successfully");
            return Encoding.UTF8.GetBytes(result.ToJson());
        }
开发者ID:xyhxyw,项目名称:DeveloperSumit2014,代码行数:77,代码来源:Image_Services_SOE.cs

示例2: GetMetadataForLayer

        private byte[] GetMetadataForLayer(NameValueCollection boundVariables,
			JsonObject operationInput,
			string outputFormat,
			string requestProperties,
			out string responseProperties)
        {
            responseProperties = null;

            long? layerId;

            // Throw an exception if a layer ID value was not provided.
            if (!operationInput.TryGetAsLong("layer", out layerId))
            {
                throw new ArgumentNullException("layer", "The \"layer\" parameter cannot be null.");
            }

            int layerIdInt = (int)layerId.Value;
            string xml = GetMetadataXml(layerIdInt);

            if (Regex.IsMatch(outputFormat, @"(?i)html?"))
            {
                // Transform to HTML using XSLT.
                responseProperties = "{\"Content-Type\" : \"text/html\"}";
                return TransformToHtml(xml);
            }
            else if (string.Compare(outputFormat, "xml", true) == 0)
            {
                responseProperties = "{\"Content-Type\" : \"text/xml\"}";
                return Encoding.UTF8.GetBytes(xml);
            }
            else
            {
                responseProperties = "{\"Content-Type\" : \"application/json\"}";
                //JsonObject obj = new JsonObject();
                //obj.AddString("metadata", xml);
                //return Encoding.UTF8.GetBytes(obj.ToJson());

                return Encoding.UTF8.GetBytes(XmlToJson(xml));
            }
        }
开发者ID:WaimakaririGeospatial,项目名称:LayerMetadataSoe,代码行数:40,代码来源:LayerMetadata.cs

示例3: DoClassifyHandler

        /*
         *该方法通过纯粹的Arcobject的方式实现最大似然分类        *
         *
         * *
         */
        private byte[] DoClassifyHandler(NameValueCollection boundVariables, JsonObject operationInput, string outputFormat, string requestProperties, out string responseProperties)
        {
            _logger.LogMessage(ServerLogger.msgType.infoDetailed, _soename + ".GetRasterStatistics", 8000, "request received");
            if (!_supportRasterItemAccess)
                throw new ArgumentException("The image service does not have a catalog and does not support this operation");
            responseProperties = null;

            long? objectID;
            long? classCount;
            //case insensitive
            bool found = operationInput.TryGetAsLong("objectID", out objectID);
            if (!found || (objectID == null))
                throw new ArgumentNullException("ObjectID");

            found = operationInput.TryGetAsLong("classnumber", out classCount);
            if (!found || (objectID == null))
                throw new ArgumentNullException("classnumber");
            IRasterCatalogItem rasterCatlogItem = null;
            try
            {
                rasterCatlogItem = _mosaicCatalog.GetFeature((int)objectID) as IRasterCatalogItem;
                if (rasterCatlogItem == null)
                {
                    _logger.LogMessage(ServerLogger.msgType.infoDetailed, _soename + ".GetRasterStatistics", 8000, "request finished with exception");
                    throw new ArgumentException("The input ObjectID does not exist");
                }
            }
            catch
            {
                _logger.LogMessage(ServerLogger.msgType.infoDetailed, _soename + ".GetRasterStatistics", 8000, "request finished with exception");
                throw new ArgumentException("The input ObjectID does not exist");
            }
            JsonObject result = new JsonObject();
            string outputurl = "";
            try
            {

                IRasterDataset pRasterDataSet = rasterCatlogItem.RasterDataset;

                IGeoDataset pGeo = pRasterDataSet as IGeoDataset;

                string inPath = @"D:\arcgisserver\directories\arcgisoutput\imageserver\test2_ImageServer";
                string gsgname = System.DateTime.Now.ToString().Replace("/", "").Replace(":", "").Replace(" ", "") + ".gsg";
                string gsgPath = System.IO.Path.Combine(inPath, gsgname);

                bool bcreatesignaturefile = Classify.CreateSignaturefile(pRasterDataSet, Convert.ToInt32(classCount), gsgPath);
                if (bcreatesignaturefile)
                {
                    IMultivariateOp pMultivarateOp = new RasterMultivariateOpClass();
                    IGeoDataset pGeoDatasetResult = pMultivarateOp.MLClassify(pGeo, gsgPath, false, esriGeoAnalysisAPrioriEnum.esriGeoAnalysisAPrioriEqual, Type.Missing, Type.Missing);

                    IEnvelope pEnvelp = new EnvelopeClass();

                    string outurl = "http://localhost:6080/arcgis/rest/directories/arcgisoutput/imageserver/test2_ImageServer/";
                    pEnvelp.PutCoords(116.56075474, 40.29407147, 116.63105347, 40.34514666);
                    // string dd = ExportImage.ExportLayerImage((IRaster)pGeoDatasetResult, bbox, new string[] { "400", "400" }, outurl, fileDir);
                    outputurl = ExportImage.CreateJPEGFromActiveView((IRaster)pGeoDatasetResult, pEnvelp, outurl, inPath);
                }
            }

            catch
            {

            }
            result.AddString("url", outputurl);
            return Encoding.UTF8.GetBytes(result.ToJson());
        }
开发者ID:xyhxyw,项目名称:DeveloperSumit2014,代码行数:72,代码来源:Image_Services_SOE.cs

示例4: ExcuteFuncHandler

        /*
         *通过调用影像服务的形式实现最大最大似然分类
         */
        private byte[] ExcuteFuncHandler(NameValueCollection boundVariables, JsonObject operationInput, string outputFormat, string requestProperties, out string responseProperties)
        {
            _logger.LogMessage(ServerLogger.msgType.infoDetailed, _soename + ".GetRasterStatistics", 8000, "request received");
            if (!_supportRasterItemAccess)
                throw new ArgumentException("The image service does not have a catalog and does not support this operation");
            responseProperties = null;

            long? objectID;
            long? classCount;
            //case insensitive
            bool found = operationInput.TryGetAsLong("objectID", out objectID);
            if (!found || (objectID == null))
                throw new ArgumentNullException("ObjectID");

            found = operationInput.TryGetAsLong("classnumber", out classCount);
            if (!found || (objectID == null))
                throw new ArgumentNullException("classnumber");

            IRasterCatalogItem rasterCatlogItem = null;
            try
            {
                rasterCatlogItem = _mosaicCatalog.GetFeature((int)objectID) as IRasterCatalogItem;
                if (rasterCatlogItem == null)
                {
                    _logger.LogMessage(ServerLogger.msgType.infoDetailed, _soename + ".GetRasterStatistics", 8000, "request finished with exception");
                    throw new ArgumentException("The input ObjectID does not exist");
                }
            }
            catch
            {
                _logger.LogMessage(ServerLogger.msgType.infoDetailed, _soename + ".GetRasterStatistics", 8000, "request finished with exception");
                throw new ArgumentException("The input ObjectID does not exist");
            }
            JsonObject result = new JsonObject();
            string outputurl = "";
            try
            {
                // rasterBandsCol = (IRasterBandCollection)rasterCatlogItem.RasterDataset;
                IRasterDataset pRasterDataSet = rasterCatlogItem.RasterDataset;

                string gsgname = System.DateTime.Now.ToString().Replace("/", "").Replace(":", "").Replace(" ", "") + ".gsg";
                string gsgpath = System.IO.Path.Combine(@"d:\", gsgname);

                bool bcreatesignaturefile = Classify.CreateSignaturefile(pRasterDataSet, Convert.ToInt32(classCount), gsgpath);
                if (bcreatesignaturefile)
                {
                    IRaster pRaster = pRasterDataSet.CreateDefaultRaster();
                    string imagePath = Classify.ApplyMLClassifyFunction(pImageSever, pRaster, gsgpath);

                    outputurl = "http://localhost:6080/arcgis/" + imagePath;
                }
            }

            catch
            {

            }
            result.AddString("url", outputurl);
            return Encoding.UTF8.GetBytes(result.ToJson());
        }
开发者ID:xyhxyw,项目名称:DeveloperSumit2014,代码行数:63,代码来源:Image_Services_SOE.cs

示例5: CreateWatershedHandler

        private byte[] CreateWatershedHandler(NameValueCollection boundVariables,
            JsonObject operationInput,
            string outputFormat,
            string requestProperties,
            out string responseProperties)
        {
            responseProperties = null;

            #region Process the REST arguments
            // hydroshed_id - REQUIRED - to identify the overall result
            string search_id;
            bool found = operationInput.TryGetString("search_id", out search_id);
            if (!found || string.IsNullOrEmpty(search_id))
            {
                throw new ArgumentNullException("search_id");
            }
            // input point - REQUIRED - the search location
            JsonObject jsonPoint;
            found = operationInput.TryGetJsonObject("location", out jsonPoint);
            if (!found)
            {
                throw new ArgumentNullException("location");
            }
            IPoint locationpoint = Conversion.ToGeometry(jsonPoint, esriGeometryType.esriGeometryPoint) as IPoint;
            long? jsonWkid;
            found = operationInput.TryGetAsLong("input_wkid", out jsonWkid);
            if (!found)
            {
                throw new ArgumentNullException("input_wkid", "WKID numeric value for spatial reference of input point must be provided");
            }
            if (jsonWkid.HasValue)
            {
                int wkid = (int)jsonWkid.Value;
                ISpatialReferenceFactory2 tInSRFac = new SpatialReferenceEnvironment() as ISpatialReferenceFactory2;
                ISpatialReference tInSR = tInSRFac.CreateSpatialReference(wkid);
                locationpoint.SpatialReference = tInSR;
            }
            // extent - OPTIONAL - we will use full extent if not provided but this is slow!!
            // TODO maybe preferable to have the extent looked up in the SOE rather than expecting it as a parameter
            JsonObject jsonExtent;
            found = operationInput.TryGetJsonObject("extent", out jsonExtent);
            IGeometry tAnalysisEnvelope;
            if (found && jsonExtent != null)
            {
                logger.LogMessage(ServerLogger.msgType.debug, "process input params", 8000, "Found input extent json object ");
                tAnalysisEnvelope = convertAnyJsonGeometry(jsonExtent);
                logger.LogMessage(ServerLogger.msgType.debug, "process input params", 8000, "Input extent processed ok ");
                try
                {
                    logger.LogMessage(ServerLogger.msgType.debug, "process input params", 8000, "Input extent height*width are: " + tAnalysisEnvelope.Envelope.Height.ToString() + " * " + tAnalysisEnvelope.Envelope.Width.ToString());
                }
                catch (NullReferenceException nre)
                {
                    logger.LogMessage(ServerLogger.msgType.debug, "Processing parameters", 8000, "Problem reading input extent, exception was " + nre.Message + " at " + nre.StackTrace);
                }
            }
            else
            {
                tAnalysisEnvelope = null;
                logger.LogMessage(ServerLogger.msgType.debug, "process input params", 8000, "No input extent parameter requested ");
            }
            List<ExtractionLayerConfig> extractionRequests = new List<ExtractionLayerConfig>();
            foreach (ExtractionLayerConfig tExtLayerInfo in m_ExtractableParams)
            {
                string jsonParam = tExtLayerInfo.ParamName;
                bool? wasRequested;
                found = operationInput.TryGetAsBoolean(jsonParam, out wasRequested);
                if (found && wasRequested.HasValue && (bool)wasRequested)
                {
                    extractionRequests.Add(tExtLayerInfo);
                }
            }
            // check whether to return as json structured object or all flattened onto attributes of the
            // polygon
            bool returnAsPolygonAttributes=false;
            if (extractionRequests.Count > 0)
            {
                bool? nullableBool;
                found = operationInput.TryGetAsBoolean("extractToPolygonAttributes", out nullableBool);
                if (found && nullableBool.HasValue)
                {
                    returnAsPolygonAttributes = (bool)nullableBool;
                }
            }
            #endregion

            #region Do the actual watershed extraction
            // Modified the computeWatershed method to return both the raster and converted polygon versions of the
            // watershed. Because the polygon version, if made by unioning separate polygons, is multipart, and
            // although this is what we want to return to the user, the raster extraction operations can't handle
            // that so we run them with a raster mask input instead. Returning both here saves the extraction methods
            // from converting back to a raster.
            IGeoDataset tWatershedPolyGDS;
            IGeoDataset tWatershedRasterGDS;
            if (tAnalysisEnvelope != null)
            {
                KeyValuePair<IGeoDataset, IGeoDataset> tPair = computeWatershed(locationpoint, tAnalysisEnvelope.Envelope);
                tWatershedPolyGDS = tPair.Value;
                tWatershedRasterGDS = tPair.Key;
            }
//.........这里部分代码省略.........
开发者ID:harry-gibson,项目名称:watershed-soe,代码行数:101,代码来源:WatershedSOE.cs

示例6: ExtractByPolygonHandler

 private byte[] ExtractByPolygonHandler(NameValueCollection boundVariables,
     JsonObject operationInput,
     string outputFormat,
     string requestProperties,
     out string responseProperties)
 {
     string search_id;
     bool found = operationInput.TryGetString("search_id", out search_id);
     if (!found || string.IsNullOrEmpty(search_id))
     {
         throw new ArgumentNullException("search_id");
     }
     // input polygon - REQUIRED - the polygon to summarise data within
     JsonObject jsonPolygon;
     found = operationInput.TryGetJsonObject("polygon", out jsonPolygon);
     if (!found)
     {
         throw new ArgumentNullException("polygon");
     }
     IPolygon extractionPolygon = Conversion.ToGeometry(jsonPolygon, esriGeometryType.esriGeometryPolygon) as IPolygon;
     long? jsonWkid;
     found = operationInput.TryGetAsLong("input_wkid", out jsonWkid);
     if (!found)
     {
         throw new ArgumentNullException("input_wkid", "WKID numeric value for spatial reference of input point must be provided");
     }
     if (jsonWkid.HasValue)
     {
         int wkid = (int)jsonWkid.Value;
         ISpatialReferenceFactory2 tInSRFac = new SpatialReferenceEnvironment() as ISpatialReferenceFactory2;
         ISpatialReference tInSR = tInSRFac.CreateSpatialReference(wkid);
         extractionPolygon.SpatialReference = tInSR;
     }
     else
     {
         // we won't get here
         extractionPolygon.SpatialReference = new UnknownCoordinateSystemClass();
     }
     bool? reqReturnAsAttributes;
     bool returnAsAttributes = false;
     found = operationInput.TryGetAsBoolean("extractToPolygonAttributes", out reqReturnAsAttributes);
     if (found && reqReturnAsAttributes.HasValue)
     {
         returnAsAttributes = (bool)reqReturnAsAttributes;
     }
     List<ExtractionLayerConfig> extractionRequests = new List<ExtractionLayerConfig>();
     foreach (ExtractionLayerConfig tExtLayerInfo in m_ExtractableParams)
     {
         string jsonParam = tExtLayerInfo.ParamName;
         bool? wasRequested;
         found = operationInput.TryGetAsBoolean(jsonParam, out wasRequested);
         if (found && wasRequested.HasValue && (bool)wasRequested)
         {
             extractionRequests.Add(tExtLayerInfo);
         }
     }
     logger.LogMessage(ServerLogger.msgType.debug, "ExtractByPolygonHandler", 99,
                   "Processed inputs, attempting " + extractionRequests.Count.ToString() + " extractions");
     // now need to convert the IPolygon to a geodataset, (a polygon one) for feature
     // extractions.
     IWorkspace inMemWksp = CreateInMemoryWorkspace() as IWorkspace;
     IFeatureWorkspace inMemFeatWksp = inMemWksp as IFeatureWorkspace;
     IFeatureClass tPolyAsFC = CreateFeatureClassFromGeometry(extractionPolygon, inMemFeatWksp, extractionPolygon.SpatialReference.FactoryCode);
     IArea tArea = extractionPolygon as IArea;
     if (AddAField(tPolyAsFC,"Total_Area",esriFieldType.esriFieldTypeDouble))
     {
         IFeatureCursor tFCursor = tPolyAsFC.Search(null,false);
         IFeature tPolyAsFeature = tFCursor.NextFeature();
         tPolyAsFeature.set_Value(tPolyAsFC.FindField("Total_Area"),tArea.Area);
         tPolyAsFeature.Store();
     }
     IGeoDataset tPolygonGDS = tPolyAsFC as IGeoDataset;
     // now do the extractions from it
     ExtractionResultCollection tExtractionResults =
         ProcessExtractions(search_id,tPolygonGDS, null, extractionRequests);
     // Warning! Don't go assuming that the suggestively-named responseProperties can be set to anything
     // helpful to describe, say, response properties. Try setting it to anything other than null
     // (that I have tried) and you get "500 Unexpected Error" message and lose the best part of an
     // afternoon working out why!
     //responseProperties = "Extractions processed successfully";
     responseProperties = null;
     logger.LogMessage(ServerLogger.msgType.debug, "ExtractByPolygonHandler", 99,
                   "Extractions complete, returning feature");
     if (returnAsAttributes)
     {
         IRecordSetInit returnRecSet = new RecordSetClass();
         IGeoDataset tFinalGDS = tExtractionResults.ResultsAsAttributedGeodataset;
         returnRecSet.SetSourceTable(tFinalGDS as ITable, null);
         IRecordSet recset = returnRecSet as IRecordSet;
         byte[] jsonFeature = Conversion.ToJson(recset);
         return jsonFeature;
     }
     else
     {
         JsonObject tResultsAsJson = tExtractionResults.ResultsAsJson;
         byte[] jsonFeatures = System.Text.Encoding.UTF8.GetBytes(tResultsAsJson.ToJson());
         return jsonFeatures;
     }
 }
开发者ID:harry-gibson,项目名称:watershed-soe,代码行数:99,代码来源:WatershedSOE.cs

示例7: ExportGeoJsonHandler


//.........这里部分代码省略.........
                        {
                            ISpatialReference sr = null;
                            if (useBboxSR)
                            {
                                sr = helper.GetSpatialReference(bboxSRID);
                                if (sr == null)
                                {
                                    //erroneous srid, ignore bounding box
                                    useBbox = false;
                                }
                            }
                            else
                            {
                                sr = helper.getWGS84();
                            }
                            if (useBbox)
                            {
                                queryGeom = new Polygon() as IPolygon;
                                IPointCollection coll = queryGeom as IPointCollection;
                                coll.AddPoint(new Point() { X = xmin, Y = ymin, SpatialReference = sr });
                                coll.AddPoint(new Point() { X = xmin, Y = ymax, SpatialReference = sr });
                                coll.AddPoint(new Point() { X = xmax, Y = ymax, SpatialReference = sr });
                                coll.AddPoint(new Point() { X = xmax, Y = ymin, SpatialReference = sr });
                                coll.AddPoint(new Point() { X = xmin, Y = ymin, SpatialReference = sr });
                                queryGeom.SpatialReference = sr;
                            }
                        }
                        else
                        {
                            useBbox = false;
                        }
                    }
                    else
                    {
                        useBbox = false;
                    }
                }
                catch
                {
                    useBbox = false;
                }
            }

            long? layerOrdinal;
            found = operationInput.TryGetAsLong("layer", out layerOrdinal); //.TryGetString("layer", out parm2Value);
            if (!found)
            {
                throw new ArgumentNullException("layer");
            }

            string s = "";

            ESRI.ArcGIS.Carto.IMapServer mapServer = (ESRI.ArcGIS.Carto.IMapServer)serverObjectHelper.ServerObject;
            ESRI.ArcGIS.Carto.IMapServerDataAccess mapServerObjects = (ESRI.ArcGIS.Carto.IMapServerDataAccess)mapServer;
            var lyr = mapServerObjects.GetDataSource(mapServer.DefaultMapName, Convert.ToInt32(layerOrdinal));

            if (lyr is IFeatureClass)
            {
                IFeatureClass fclass = (IFeatureClass)lyr;
                retval = "{\"shape\": \"" + fclass.ShapeFieldName + "\"}";
                IQueryFilter filter = null;
                if (useBbox)
                {
                    IGeoDataset gds = fclass as IGeoDataset;
                    filter = new SpatialFilterClass();
                    ISpatialFilter spf = filter as ISpatialFilter;
                    spf.Geometry = helper.TransformShapeCS(queryGeom, queryGeom.SpatialReference, gds.SpatialReference);
                    spf.GeometryField = fclass.ShapeFieldName;
                    spf.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects;
                }
                else
                {
                    filter = new QueryFilterClass();
                }
                filter.set_OutputSpatialReference(fclass.ShapeFieldName, getWGS84());
                if (applyQuery)
                {
                    filter.WhereClause = whereClause;
                }

                IFeatureCursor curs = fclass.Search(filter, false);
                //apply extension methods here
                try
                {
                    s = curs.ToGeoJson();
                    Marshal.ReleaseComObject(curs);

                }
                catch (Exception ex)
                {
                    s = ex.GetBaseException().ToString(); //.StackTrace;
                }
                retval = s;
            }
            else
            {
                throw new Exception("Layer " + layerOrdinal.ToString() + " is not a feature layer.");
            }
            return Encoding.UTF8.GetBytes(retval);
        }
开发者ID:flyingliang,项目名称:AGSOpenFormats,代码行数:101,代码来源:GeoJSONSOE.cs

示例8: VectorTileHandler

        /// <summary>
        /// Creates and Serves vector tiles
        /// </summary>
        /// <param name="boundVariables"></param>
        /// <param name="operationInput"></param>
        /// <param name="outputFormat"></param>
        /// <param name="requestProperties"></param>
        /// <param name="responseProperties"></param>
        /// <returns></returns>
        private byte[] VectorTileHandler(NameValueCollection boundVariables,
                                                  JsonObject operationInput,
                                                      string outputFormat,
                                                      string requestProperties,
                                                  out string responseProperties)
        {
            //responseProperties = null;
            responseProperties = null; //"Content-Type:application/json";
            ESRI.ArcGIS.SOESupport.AutoTimer timer = new AutoTimer();

            const string methodName = "VectorTileHandler";

            try
            {
                long? layerIndex;
                long? zoom;
                long? row;
                long? col;
                string jsonFormatParam;
                TileFormat jsonFormat = TileFormat.EsriJson; // Defaulting to EsriJson
                if (!operationInput.TryGetAsLong("l", out layerIndex))
                    throw new ArgumentNullException("layer");
                if (!operationInput.TryGetAsLong("z", out zoom))
                    throw new ArgumentNullException("zoom");
                if (!operationInput.TryGetAsLong("y", out row))
                    throw new ArgumentNullException("row");
                if (!operationInput.TryGetAsLong("x", out col))
                    throw new ArgumentNullException("col");
                if (operationInput.TryGetString("jf", out jsonFormatParam))
                {
                    if (!string.IsNullOrEmpty(jsonFormatParam))
                    {
                        jsonFormatParam = jsonFormatParam.ToLower().Trim();
                        Enum.GetNames(typeof(TileFormat)).ToList().ForEach(n =>
                        {
                            if (n.ToLower() == jsonFormatParam)
                            {
                                jsonFormat = (TileFormat)Enum.Parse(typeof(TileFormat), jsonFormatParam, true);
                            }
                        });
                    }
                }

                //System.Diagnostics.Debug.WriteLine(string.Format("l:{0}, r:{1}, c:{2}", zoom, row, col));

                // Check to see if the tile exists on disk...
                //  <cache-root>\<layerId>\<zoom>\<row>\<col>.esrijson;
                //i.e. to be consistent with Esri tile caching structure
                string tilePath = string.Format(@"{0}\{1}\{2}\{3}\{4}.{5}",
                    _vectorCacheRootDirectory, layerIndex, zoom.Value,
                    row.Value, col.Value, jsonFormat.ToString().ToLower());
                if (File.Exists(tilePath))
                {
                    // Fetch tile contents from disk
                    _dtsLogger.LogInfo(soe_name, methodName, "Time: " + timer.Elapsed.ToString());
                    logger.LogMessage(ServerLogger.msgType.infoSimple, methodName, -1, "Time: " + timer.Elapsed.ToString());
                    return this.ReadTileFile(tilePath);
                }
                else
                {
                    // Write new files to disk

                    IMapServer3 mapServer = serverObjectHelper.ServerObject as IMapServer3;
                    if (mapServer == null)
                    {
                        throw new InvalidOperationException("Unable to access the map server.");
                    }

                    // Get the bbox. Returns an envelope in WGS84 (4326).
                    IEnvelope env102100 = TileUtil.GetEnvelopeFromZoomRowCol((int)zoom.Value, (int)row.Value, (int)col.Value);
                    //_dtsLogger.LogInfo(soe_name, methodName, this.GeometryToXml(env4326));

                    // Convert envelope to polygon b/c QueryData does not support spatialfilter geometry using envelope
                    IPolygon polygon102100 = this.CreatePolygonFromEnvelope(env102100);

                    // Use QueryData and generalize result geometries based on zoom level
                    IQueryResultOptions resultOptions = new QueryResultOptionsClass();
                    // i.e; IRecordSet to support BOTH json and geojson
                    resultOptions.Format = esriQueryResultFormat.esriQueryResultRecordSetAsObject;
                    IMapTableDescription tableDescription =
                        this.GetTableDescription(mapServer, (int)layerIndex, (int)zoom);

                    // Create spatial filter
                    ISpatialFilter spatialFilter = new SpatialFilterClass();
                    spatialFilter.Geometry = polygon102100;
                    spatialFilter.GeometryField = "Shape";
                    spatialFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects;
                    //TODO:  Subfields should be configurable
                    spatialFilter.SubFields = "*";

                    // Execute query
//.........这里部分代码省略.........
开发者ID:dtsagile,项目名称:arcstache,代码行数:101,代码来源:ArcStache.cs

示例9: ExportCsvHandler

        private byte[] ExportCsvHandler(NameValueCollection boundVariables,
                                          JsonObject operationInput,
                                              string outputFormat,
                                              string requestProperties,
                                          out string responseProperties)
        {
            string retval = "";
            StringBuilder sb = new StringBuilder();
            string s = "";
            bool applyQuery = true;
            bool? applyHeader = true;
            //bool? applyGeoms = true;
            bool addHeader = false;
            //bool addGeoms = false;
            responseProperties = "{\"Content-Type\" : \"text/csv\"}";

            string whereClause = "";
            bool found = operationInput.TryGetString("query", out whereClause);
            if (!found || string.IsNullOrEmpty(whereClause))
            {
                //then no definition query
                applyQuery = false;
            }

            long? layerOrdinal;
            found = operationInput.TryGetAsLong("layer", out layerOrdinal); //.TryGetString("layer", out parm2Value);
            if (!found)
            {
                throw new ArgumentNullException("layer");
            }

            bool useHeader = operationInput.TryGetAsBoolean("headers", out applyHeader);
            if (useHeader)
            {
                if ((bool)applyHeader)
                {
                    addHeader = true;
                }
            }

            //bool useGeoms = operationInput.TryGetAsBoolean("addgeoms", out applyGeoms);
            //if (useGeoms)
            //{
            //    if ((bool)applyGeoms)
            //    {
            //        addGeoms = true;
            //    }
            //}

            ESRI.ArcGIS.Carto.IMapServer mapServer = (ESRI.ArcGIS.Carto.IMapServer)serverObjectHelper.ServerObject;
            ESRI.ArcGIS.Carto.IMapServerDataAccess mapServerObjects = (ESRI.ArcGIS.Carto.IMapServerDataAccess)mapServer;
            var lyr = mapServerObjects.GetDataSource(mapServer.DefaultMapName, Convert.ToInt32(layerOrdinal));
            if (lyr is IFeatureClass)
            {
                IFeatureClass fclass = (IFeatureClass)lyr;
                IQueryFilter filter = new QueryFilterClass();
                filter.set_OutputSpatialReference(fclass.ShapeFieldName, getWGS84());
                if (applyQuery)
                {
                    filter.WhereClause = whereClause;
                }
                IFeatureCursor curs = fclass.Search(filter, false);
                try
                {
                    //();
                    s = curs.ToCSV(addHeader);
                    Marshal.ReleaseComObject(curs);

                }
                catch (Exception ex)
                {
                    s = ex.GetBaseException().ToString(); //.StackTrace;
                }
                retval = s;
                sb.Append(retval);
            }
            else
            {
                throw new Exception("Layer " + layerOrdinal.ToString() + " is not a feature layer.");
            }

            return Encoding.UTF8.GetBytes(sb.ToString());
        }
开发者ID:flyingliang,项目名称:AGSOpenFormats,代码行数:83,代码来源:GeoJSONSOE.cs

示例10: GetSpeciesExtentHandler

 private byte[] GetSpeciesExtentHandler(NameValueCollection boundVariables,
                                           JsonObject operationInput,
                                               string outputFormat,
                                               string requestProperties,
                                           out string responseProperties)
 {
     responseProperties = "{\"Content-Type\" : \"text/javascript\"}";
     long? idnoValue; //out parameter for the ID_NO as a long
     operationInput.TryGetAsLong("ID_NO", out idnoValue); //get the ID_NO parameter
     IQueryFilter queryFilter = new QueryFilterClass(); //instantiate a filter for the passed species
     queryFilter.WhereClause = "ID_NO='" + idnoValue + "' AND Legend<>''"; //set the where clause
     IFeatureCursor featureCursor = speciesFeatureClass.Search(queryFilter, false); //get the feature cursor to the matching features
     IFeature feature = null; //for iterating through the features
     IGeometryCollection pGeometryCollection = new GeometryBagClass() as IGeometryCollection; //instantiate a geometry bag to get the extent
     object obj = Type.Missing; //needed to add geometries to the geometry bag
     while ((feature = featureCursor.NextFeature()) != null) //iterate through the matching features and add the geometries to the geometry bag
     {
         pGeometryCollection.AddGeometry(feature.ShapeCopy, ref obj, ref obj); //add the geometry
     }
     JsonObject result = new JsonObject(); //create the return json object
     IEnvelope extent = (pGeometryCollection as IGeometry).Envelope; //get the extent of the geometry bag
     JsonObject jsonExtent = Conversion.ToJsonObject(extent); //convert the extent to json
     //TODO: Set the spatial reference for the extent in the SOE - at the moment it is set in the client code
     result.AddObject("extent", jsonExtent); //write the extent to the result object
     result.AddString("featureCount", pGeometryCollection.GeometryCount.ToString()); //get the number of features
     return Encoding.UTF8.GetBytes(result.ToJson()); //return the json
 }
开发者ID:andrewcottam,项目名称:IUCNRedListSOEs,代码行数:27,代码来源:IUCNRedListSOE.cs

示例11: GetSource

 private byte[] GetSource(NameValueCollection boundVariables, JsonObject operationInput, string outputFormat, string requestProperties, out string responseProperties)
 {
     responseProperties = null; //
     long? idnoValue; //out parameter for the ID_NO as a long
     operationInput.TryGetAsLong("ID_NO", out idnoValue); //get the ID_NO parameter
     IQueryFilter queryFilter = new QueryFilterClass(); //instantiate a filter for the passed species
     queryFilter.WhereClause = "ID_NO='" + idnoValue + "'"; //set the where clause
     IFeatureCursor featureCursor = speciesFeatureClass.Search(queryFilter, false); //get the feature cursor to the matching features
     IFeature feature = null; //for iterating through the features
     int index = speciesFeatureClass.Fields.FindField("CITATION");
     List<string> sources = new List<string>();
     List<JsonObject> jsonObjects = new List<JsonObject>();
     while ((feature = featureCursor.NextFeature()) != null) //iterate through the matching features
     {
         string source = feature.get_Value(index) as string;
         if (InList(sources, source) == false)
         {
             JsonObject sourceJson = new JsonObject();
             sourceJson.AddString("Source", source);
             jsonObjects.Add(sourceJson);
             sources.Add(source);
         }
     }
     JsonObject result = new JsonObject(); //create the return json object
     result.AddArray("sources", jsonObjects.ToArray());
     return Encoding.UTF8.GetBytes(result.ToJson()); //return the json
 }
开发者ID:andrewcottam,项目名称:IUCNRedListSOEs,代码行数:27,代码来源:IUCNRedListSOE.cs

示例12: UpdateCheckedCount

 private byte[] UpdateCheckedCount(NameValueCollection boundVariables, JsonObject operationInput, string outputFormat, string requestProperties, out string responseProperties)
 {
     responseProperties = null;
     long? id;
     long? checkedVal;
     bool found = operationInput.TryGetAsLong("id", out id);
     if (!found) throw new ArgumentNullException("id");
     found = operationInput.TryGetAsLong("checked", out checkedVal);
     if (!found) throw new ArgumentNullException("checked");
     string storedProcedureName = "_IWC_UpdateChecked";
     SqlCommand cmd = new SqlCommand(storedProcedureName, sqlConn);
     cmd.CommandType = CommandType.StoredProcedure;
     SqlParameter param1 = cmd.Parameters.AddWithValue("@id", id);
     SqlParameter param2 = cmd.Parameters.AddWithValue("@checked", checkedVal);
     cmd.ExecuteNonQuery();
     JsonObject result = new JsonObject();
     result.AddString("results", "Done");
     return Encoding.UTF8.GetBytes(result.ToJson());
 }
开发者ID:andrewcottam,项目名称:IWC-ArcGIS-ServerObjectExtensions,代码行数:19,代码来源:InternationalWaterbirdCensusExtensions.cs

示例13: getSpeciesListForBBoxHandler

 private byte[] getSpeciesListForBBoxHandler(NameValueCollection boundVariables, JsonObject operationInput, string outputFormat, string requestProperties, out string responseProperties)
 {
     responseProperties = null;
     long? txmin;
     long? txmax;
     long? tymin;
     long? tymax;
     operationInput.TryGetAsLong("txmin", out txmin);
     operationInput.TryGetAsLong("txmax", out txmax);
     operationInput.TryGetAsLong("tymin", out tymin);
     operationInput.TryGetAsLong("tymax", out tymax);
     Type factoryType = Type.GetTypeFromProgID("esriDataSourcesGDB.FileGDBWorkspaceFactory"); //open a connection to the species data table
     IWorkspaceFactory workspaceFactory = (IWorkspaceFactory)Activator.CreateInstance(factoryType);
     IWorkspace workspace = workspaceFactory.OpenFromFile("D:\\GIS Data\\Andrew\\PilotSpeciesData.gdb", 0); //TODO make this more sustainable
     IFeatureWorkspace featureWorkspace = (IFeatureWorkspace)workspace;
     IQueryDef queryDef = featureWorkspace.CreateQueryDef(); //create a query to get the data
     IQueryDef2 queryDef2 = (IQueryDef2)queryDef;
     queryDef2.Tables = "Species"; //specify the tables
     queryDef2.SubFields = "Species.tax_id,Species.friendly_name"; //specify the fields that you will return
     queryDef2.WhereClause = "tax_id IN (SELECT species_ID from PilotSpeciesData where mx between  " + txmin.ToString() + " and " + txmax.ToString() + " and my between " + tymin.ToString() + " and " + tymax.ToString() + ")"; //create the query
     queryDef2.PrefixClause = "DISTINCT";
     ICursor cursor = queryDef2.Evaluate();
     int friendly_nameIndex = cursor.FindField("Species.friendly_name");
     IRow row = null;
     String s = "";
     while ((row = cursor.NextRow()) != null) //get the resultset and iterate through the records
     {
         s = s + row.get_Value(friendly_nameIndex) + ",";
     }
     JsonObject result = new JsonObject();
     result.AddString("species", s); //write the results
     return Encoding.UTF8.GetBytes(result.ToJson()); //return the results
 }
开发者ID:andrewcottam,项目名称:eSpeciesSOEs,代码行数:33,代码来源:eSpeciesSOE.cs


注:本文中的JsonObject.TryGetAsLong方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。