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


C# JsonObject.TryGetString方法代码示例

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


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

示例1: HasSuccess

        /// <summary>
        /// check is status is equal success
        /// </summary>
        /// <param name="result">result of request</param>
        /// <returns>True if status is equal success</returns>
        private bool HasSuccess(string result)
        {
            JsonObject jsonObject = new JsonObject(result);
            string status = null;
            if (!jsonObject.Exists("status") || !jsonObject.TryGetString("status", out status))
            {
                return false;
            }

            return status == "success";
        }
开发者ID:jackyped,项目名称:blog,代码行数:16,代码来源:AGSAdmin.cs

示例2: AreasAndLengthsHandler

        private byte[] AreasAndLengthsHandler(NameValueCollection boundVariables,
            JsonObject operationInput,
            string outputFormat,
            string requesetProperties,
            out string responseProperties)
        {
            responseProperties = null;
            var errors = new ResponseContainer(HttpStatusCode.BadRequest, "");

            string base64Geometry;
            var found = operationInput.TryGetString("geometry", out base64Geometry);

            if (!found || string.IsNullOrEmpty(base64Geometry))
            {
                errors.Message = "geometry parameter is required.";

                return Json(errors);
            }

            #if !DEBUG
            _logger.LogMessage(ServerLogger.msgType.infoStandard, "AreasAndLengthsHandler", MessageCode, "Params received");
            #endif

            IGeometry geometry;
            int read;
            var factory = new GeometryEnvironmentClass() as IGeometryFactory3;
            factory.CreateGeometryFromWkbVariant(Convert.FromBase64String(base64Geometry), out geometry, out read);

            var spatialReferenceFactory = new SpatialReferenceEnvironmentClass();
            if (geometry.SpatialReference == null)
            {
                //Create a projected coordinate system and define its domain, resolution, and x,y tolerance.
                var spatialReferenceResolution = spatialReferenceFactory.CreateProjectedCoordinateSystem(3857) as ISpatialReferenceResolution;
                spatialReferenceResolution.ConstructFromHorizon();
                var spatialReferenceTolerance = spatialReferenceResolution as ISpatialReferenceTolerance;
                spatialReferenceTolerance.SetDefaultXYTolerance();
                var spatialReference = spatialReferenceResolution as ISpatialReference;

                geometry.SpatialReference = spatialReference;
            }

            #if !DEBUG
            _logger.LogMessage(ServerLogger.msgType.infoStandard, "AreasAndLengthsHandler", MessageCode, "Geometry converted");
            #endif

            if (geometry.GeometryType == esriGeometryType.esriGeometryPolygon)
            {
                var filterGeometry = (ITopologicalOperator4)geometry;
                filterGeometry.IsKnownSimple_2 = false;

                filterGeometry.Simplify();

                if (((IArea)geometry).Area < 0)
                {
                    ((ICurve)geometry).ReverseOrientation();
                }
            }

            var utmResolution = spatialReferenceFactory.CreateProjectedCoordinateSystem(26912) as ISpatialReferenceResolution;
            utmResolution.ConstructFromHorizon();
            var utmTolerance = utmResolution as ISpatialReferenceTolerance;
            utmTolerance.SetDefaultXYTolerance();
            var utmSr = utmResolution as ISpatialReference;

            geometry.Project(utmSr);

            var size = 0D;
            switch (geometry.GeometryType)
            {
                case esriGeometryType.esriGeometryPolygon:
                    size = ((IArea) geometry).Area;
                    break;
                case esriGeometryType.esriGeometryPolyline:
                    size = ((IPolyline5) geometry).Length;
                    break;
            }
            #if !DEBUG
            _logger.LogMessage(ServerLogger.msgType.infoStandard, "AreasAndLengthsHandler", MessageCode, string.Format("Returning size {0}", size.ToString(CultureInfo.InvariantCulture)));
            #endif
            return Json(new ResponseContainer<SizeResponse>(new SizeResponse(size)));
        }
开发者ID:agrc,项目名称:wri-webapi,代码行数:81,代码来源:wri-soe.cs

示例3: findTrainStationById

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

            string IdValue;
            bool found = operationInput.TryGetString("trainStationId", out IdValue);
            if (!found || string.IsNullOrEmpty(IdValue))
                throw new ArgumentNullException("trainStationId");


            JsonObject result = new JsonObject();
            result.AddString("stationName", "Train Station " + IdValue);

            return Encoding.UTF8.GetBytes(result.ToJson());
        }
开发者ID:Esri,项目名称:arcobjects-sdk-community-samples,代码行数:19,代码来源:NetSimpleRESTSOEWithCapabilities.cs

示例4: GetServerDirectory

        /// <summary>
        /// Get physical Path and virtual Path from directory ags
        /// </summary>
        /// <param name="directory">directory ags</param>
        /// <param name="physicalPath">physical Path</param>
        /// <param name="virtualPath">virtual Path</param>
        /// <returns>True if successfully return path</returns>
        public bool GetServerDirectory(string directory, out string physicalPath, out string virtualPath)
        {
            physicalPath = null;
            virtualPath = null;
            try
            {
                string token = this.GenerateAGSToken();
                string directoryUrl = this.urlRestAdmin + "/system/directories/" + directory + "?f=json&token=" + token;

                string result = this.GetResult(directoryUrl);

                JsonObject jsonObject = new JsonObject(result);
                if (!jsonObject.Exists("physicalPath") || !jsonObject.TryGetString("physicalPath", out physicalPath))
                {
                    throw new Exception();
                }

                jsonObject = new JsonObject(result);
                if (!jsonObject.Exists("virtualPath") || !jsonObject.TryGetString("virtualPath", out virtualPath))
                {
                    throw new Exception();
                }

                return true;
            }
            catch
            {
                return false;
            }
        }
开发者ID:jackyped,项目名称:blog,代码行数:37,代码来源:AGSAdmin.cs

示例5: 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

示例6: 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

示例7: GetNewSiteCode

 private byte[] GetNewSiteCode(NameValueCollection boundVariables, JsonObject operationInput, string outputFormat, string requestProperties, out string responseProperties)
 {
     responseProperties = null;
     string CountryCode;
     bool found = operationInput.TryGetString("CountryCode", out CountryCode);
     if (!found || string.IsNullOrEmpty(CountryCode)) throw new ArgumentNullException("CountryCode");
     string storedProcedureName = "_IWC_GetMaxSiteCode";
     SqlCommand cmd = new SqlCommand(storedProcedureName, sqlConn);
     cmd.CommandType = CommandType.StoredProcedure;
     SqlParameter param = cmd.Parameters.AddWithValue("@countryCode", CountryCode);
     SqlDataReader reader = cmd.ExecuteReader();
     string newCode = null;
     if (reader.HasRows)
     {
         while (reader.Read())
         {
             newCode = reader.GetString(0);
         }
     }
     reader.Close();
     string newnum = null;
     if (newCode != null)
     {
         newnum = Convert.ToString((Convert.ToInt32(newCode.Substring(2)) + 1));
         char pad = '0';
         newnum = newnum.PadLeft(5, pad);
     }
     if (newCode != null) newCode = CountryCode + newnum;
     JsonObject result = new JsonObject();
     result.AddString("newCode", newCode);
     return Encoding.UTF8.GetBytes(result.ToJson());
 }
开发者ID:andrewcottam,项目名称:IWC-ArcGIS-ServerObjectExtensions,代码行数:32,代码来源:InternationalWaterbirdCensusExtensions.cs

示例8: GetToken

        private string GetToken(string tokenurl)
        {
            NameValueCollection parameters = new NameValueCollection();

            parameters["username"] = m_username;

            parameters["password"] = m_password;

            parameters["client"] = "requestip";

            parameters["referer"] = "";

            parameters["ip"] = "";

            parameters["expiration"] = "10";

            parameters["f"] = "pjson";

            String postData = CreateParameters(parameters);

            string response = PostData(tokenurl, "POST", postData);

            ESRI.ArcGIS.SOESupport.JsonObject json = new JsonObject(response);

            String token = null;

            json.TryGetString("token", out token);

            return token;
        }
开发者ID:phpmaps,项目名称:Server-Object-Configuration-Example,代码行数:30,代码来源:GetManifest.cs

示例9: ReportDomainsHandler

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

            string strSDELayerName;
            bool found = operationInput.TryGetString("SDEName", out strSDELayerName);
            if (!found || string.IsNullOrEmpty(strSDELayerName))
                throw new ArgumentNullException("SDEName");

            IStandaloneTable pStandAloneTable = GetLayerfromSDE(strSDELayerName);
            IField pField;

            Dictionary<string, Dictionary<string, string>> dicResults = new Dictionary<string, Dictionary<string, string>>();
            Dictionary<string, string> dicDomainValues;

            for (int i = 0; i <= pStandAloneTable.Table.Fields.FieldCount - 1; i++)
            {
                pField = pStandAloneTable.Table.Fields.get_Field(i);

                IDomain pDomain;
                pDomain = pField.Domain;

                if (pDomain != null)
                {
                    //PrintDomainValues(pField.Name, pDomain.DomainID);

                    dicDomainValues = new Dictionary<string, string>();

                    ICodedValueDomain pCodedValueDomain;
                    pCodedValueDomain = pDomain as ICodedValueDomain;
                    if (pCodedValueDomain != null)
                    {
                        //Console.WriteLine(pField.Name + ": " + pDomain.DomainID.ToString());
                        //Console.WriteLine("------------------------------------------");
                        for (int k = 0; k <= pCodedValueDomain.CodeCount - 1; k++)
                        {
                            string name = pCodedValueDomain.get_Value(k).ToString();
                            string value = pCodedValueDomain.get_Name(k).ToString();
                            dicDomainValues.Add(name, value);
                            //Console.WriteLine(name + ", " + value);
                        }
                        //Console.WriteLine("------------------------------------------");
                        //Console.WriteLine(Environment.NewLine);

                        dicResults.Add(pField.Name, dicDomainValues);
                    }

                }

            }

            JsonObject result = new JsonObject();
            result.AddObject("Domains", dicResults);
            //result.AddString("SDEName", strSDELayerName);

            return Encoding.UTF8.GetBytes(result.ToJson());
        }
开发者ID:ericoneal,项目名称:GetDomains,代码行数:61,代码来源:GetDomains.cs

示例10: Handler

        public static byte[] Handler(NameValueCollection boundVariables, JsonObject operationInput,
                                     string outputFormat, string requestProperties, out string responseProperties)
        {
            responseProperties = null;

            double? milepost;
            var found = operationInput.TryGetAsDouble("milepost", out milepost);
            if (!found || !milepost.HasValue)
            {
                throw new ArgumentNullException("milepost");
            }

            double? routeNumber;
            found = operationInput.TryGetAsDouble("routeNumber", out routeNumber);
            if (!found || !routeNumber.HasValue)
            {
                throw new ArgumentNullException("routeNumber");
            }

            string routeType;
            found = operationInput.TryGetString("routeType", out routeType);
            if (!found || string.IsNullOrEmpty(routeType))
            {
                throw new ArgumentNullException("routeType");
            }

            var connector = SdeConnectorFactory.Create(LayerName);

            if (connector == null)
            {
                return Json(new
                    {
                        Message = "Database does not exist for {0}".With(LayerName)
                    });
            }

            var workspace = connector.Connect();

            var featureWorkSpace = workspace as IFeatureWorkspace;

            if (featureWorkSpace == null)
            {
                return Json(new
                    {
                        Message = "Error connecting to SDE."
                    });
            }

            var response =
                CommandExecutor.ExecuteCommand(
                    new FindRouteMilepostCommand(milepost.Value.ToString(CultureInfo.InvariantCulture), routeType,
                                                 routeNumber.Value.ToString("0000"), LayerName,
                                                 featureWorkSpace));

            if (response == null)
            {
                return Json(new
                    {
                        Message =
                                "No mile post found for {0} on route {1}{2}".With(milepost, routeNumber, routeType)
                    });
            }

            return Json(response);
        }
开发者ID:agrc,项目名称:api.mapserv.utah.gov,代码行数:65,代码来源:RouteMilePostRestEndpoint.cs

示例11: MakeDomainOptionsHandler

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

            string strSDELayerName;
            bool found = operationInput.TryGetString("SDEName", out strSDELayerName);
            if (!found || string.IsNullOrEmpty(strSDELayerName))
                throw new ArgumentNullException("SDEName");

            string strFieldName;
            found = operationInput.TryGetString("fieldname", out strFieldName);
            if (!found || string.IsNullOrEmpty(strSDELayerName))
                throw new ArgumentNullException("fieldname");

            IStandaloneTable pStandAloneTable = GetLayerfromSDE(strSDELayerName);
            IField pField;

            Dictionary<string, string> dicDomainValues;

            option opt = new option();
            opt.Result = "OK";
            List<Dictionary<string, string>> lstDics = new List<Dictionary<string, string>>();

            int iFieldIndex = pStandAloneTable.Table.Fields.FindField(strFieldName);
            if (iFieldIndex != -1)
            {
                pField = pStandAloneTable.Table.Fields.get_Field(iFieldIndex);

                IDomain pDomain;
                pDomain = pField.Domain;

                if (pDomain != null)
                {

                    ICodedValueDomain pCodedValueDomain;
                    pCodedValueDomain = pDomain as ICodedValueDomain;
                    if (pCodedValueDomain != null)
                    {

                        for (int k = 0; k <= pCodedValueDomain.CodeCount - 1; k++)
                        {
                            dicDomainValues = new Dictionary<string, string>();
                            string name = pCodedValueDomain.get_Value(k).ToString();
                            string value = pCodedValueDomain.get_Name(k).ToString();
                            dicDomainValues.Add("DisplayText", value);
                            dicDomainValues.Add("Value", name);
                            lstDics.Add(dicDomainValues);
                        }

                    }

                }

            }
            else
            {
                opt.Result = "Field not found";
            }

            JsonObject result = new JsonObject();
            result.AddString("Result", opt.Result);
            result.AddObject("Options", lstDics);

            return Encoding.UTF8.GetBytes(result.ToJson());
        }
开发者ID:ericoneal,项目名称:GetDomains,代码行数:69,代码来源:GetDomains.cs

示例12: Handler

        /// <summary>
        ///     Handles the incoming rest requests
        /// </summary>
        /// <param name="boundVariables"> The bound variables. </param>
        /// <param name="operationInput"> The operation input. </param>
        /// <param name="outputFormat"> The output format. </param>
        /// <param name="requestProperties"> The request properties. </param>
        /// <param name="responseProperties"> The response properties. </param>
        /// <returns> </returns>
        /// <exception cref="System.ArgumentNullException"></exception>
        public static byte[] Handler(NameValueCollection boundVariables, JsonObject operationInput,
                                     string outputFormat, string requestProperties,
                                     out string responseProperties)
        {
            responseProperties = null;
            var errors = new ErrorModel(400);

            string layerName;
            double? utmx, utmy;
            object[] attributeListObj;

            var found = operationInput.TryGetString("layerName", out layerName);
            if (!found || string.IsNullOrEmpty(layerName))
            {
                throw new ArgumentNullException("layerName");
            }

            found = operationInput.TryGetAsDouble("utmx", out utmx);
            if (!found || !utmx.HasValue)
            {
                throw new ArgumentNullException("utmx");
            }

            found = operationInput.TryGetAsDouble("utmy", out utmy);
            if (!found || !utmy.HasValue)
            {
                throw new ArgumentNullException("utmy");
            }

            found = operationInput.TryGetArray("attributeList", out attributeListObj);
            if (!found || attributeListObj == null || attributeListObj.Length < 1)
            {
                throw new ArgumentNullException("attributeList");
            }

            var attributeList = attributeListObj.Cast<string>().ToArray();

            var searchArgs = new PointInPolyArgs(layerName, utmx.Value, utmy.Value, attributeList);

            var connector = SdeConnectorFactory.Create(layerName);

            if (connector == null)
            {
                return Json(new
                    {
                        Message = "Database does not exist for {0}".With(layerName)
                    });
            }

            var workspace = connector.Connect();

            var featureWorkSpace = workspace as IFeatureWorkspace;

            if (featureWorkSpace == null)
            {
                return Json(new
                    {
                        Message = "Error connecting to SDE."
                    });
            }

            var response = CommandExecutor.ExecuteCommand(new PointInPolygoinQueryCommand(searchArgs, featureWorkSpace));

            if (response == null)
            {
                return Json(new
                    {
                        Message = "No features found in {2} at the location {0}, {1}.".With(
                            searchArgs.Point.X, searchArgs.Point.Y, searchArgs.LayerName)
                    });
            }

            return Json(response);
        }
开发者ID:agrc,项目名称:api.mapserv.utah.gov,代码行数:84,代码来源:FeatureAttributesRestEndpoint.cs

示例13: Handler

        /// <summary>
        ///     Handles the incoming rest requests
        /// </summary>
        /// <param name="boundVariables"> The bound variables. </param>
        /// <param name="operationInput"> The operation input. </param>
        /// <param name="outputFormat"> The output format. </param>
        /// <param name="requestProperties"> The request properties. </param>
        /// <param name="responseProperties"> The response properties. </param>
        /// <returns> </returns>
        /// <exception cref="System.ArgumentNullException"></exception>
        public static byte[] Handler(NameValueCollection boundVariables, JsonObject operationInput,
                                     string outputFormat, string requestProperties,
                                     out string responseProperties)
        {
            responseProperties = null;
            var errors = new ErrorModel(400);

            string layerName;
            double? utmx, utmy;

            var found = operationInput.TryGetString("layerName", out layerName);
            if (!found || string.IsNullOrEmpty(layerName))
            {
                throw new ArgumentNullException("layerName");
            }

            found = operationInput.TryGetAsDouble("utmx", out utmx);
            if (!found || !utmx.HasValue)
            {
                throw new ArgumentNullException("utmx");
            }

            found = operationInput.TryGetAsDouble("utmy", out utmy);
            if (!found || !utmy.HasValue)
            {
                throw new ArgumentNullException("utmy");
            }

            var connector = SdeConnectorFactory.Create(layerName);

            if (connector == null)
            {
                return Json(new
                    {
                        Message = "Database does not exist for {0}".With(layerName)
                    });
            }

            var workspace = connector.Connect();

            var featureWorkSpace = workspace as IFeatureWorkspace;

            if (featureWorkSpace == null)
            {
                errors.Message = "Error connecting to SDE.";

                return Json(errors);
            }

            var rasterArgs = new RasterArgs(layerName, utmx, utmy);

            var response =
                CommandExecutor.ExecuteCommand(new GetValueFromRasterCommand(rasterArgs,
                                                                             featureWorkSpace as IRasterWorkspaceEx));

            if (response == null)
            {
                errors.Message = "No features found in {2} at the location {0}, {1}.".With(
                    rasterArgs.X, rasterArgs.Y, rasterArgs.LayerName);

                return Json(errors);
            }

            return Json(response);
        }
开发者ID:agrc,项目名称:api.mapserv.utah.gov,代码行数:75,代码来源:RasterValuesRestEndpoint.cs

示例14: 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

示例15: GetUserSiteCodes

 private Byte[] GetUserSiteCodes(NameValueCollection boundVariables, JsonObject operationInput, string outputFormat, string requestProperties, out string responseProperties)
 {
     responseProperties = null;
     String userID;
     bool found = operationInput.TryGetString("userID", out userID);
     if (!found || (userID == null)) throw new ArgumentNullException("userID");
     SqlCommand cmd = new SqlCommand("_IWC_GetUserSites", sqlConn);
     cmd.CommandType = CommandType.StoredProcedure;
     SqlParameter param = cmd.Parameters.AddWithValue("@userID", userID);
     SqlDataReader reader = cmd.ExecuteReader();
     String siteCodes = null;
     if (reader.HasRows)
     {
         while (reader.Read())
         {
             siteCodes = siteCodes + "'" + reader.GetString(0) + "',";
         }
         siteCodes = siteCodes.Substring(0, siteCodes.Length - 1);
     }
     reader.Close();
     JsonObject jObject = new JsonObject();
     jObject.AddString("siteCodes", siteCodes);
     return Encoding.UTF8.GetBytes(jObject.ToJson());
 }
开发者ID:andrewcottam,项目名称:IWC-ArcGIS-ServerObjectExtensions,代码行数:24,代码来源:InternationalWaterbirdCensusExtensions.cs


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