Exemplo n.º 1
0
        /// <summary>
        /// set edge and junction for results
        /// </summary>
        /// <param name="objectJson">object JsonObject</param>
        /// <param name="edgeEIDs">object IEnumNetEID for edge</param>
        /// <param name="junctionEIDs">object IEnumNetEID for junction</param>
        protected void SetResults(ref JsonObject objectJson, IEnumNetEID edgeEIDs, IEnumNetEID junctionEIDs)
        {
            if ((this.FlowElements == esriFlowElements.esriFEEdges) || (this.FlowElements == esriFlowElements.esriFEJunctionsAndEdges))
            {
                if (edgeEIDs == null)
                {
                    throw new GeometricNetworkException("No traced edges found");
                }
                else
                {
                    if (edgeEIDs.Count > this.MaxFeatures)
                    {
                        throw new GeometricNetworkException(edgeEIDs.Count.ToString(CultureInfo.InvariantCulture) + " features were traced which exceeds the limit of " + this.MaxFeatures);
                    }
                }
            }

            if ((this.FlowElements == esriFlowElements.esriFEJunctions) || (this.FlowElements == esriFlowElements.esriFEJunctionsAndEdges))
            {
                if (junctionEIDs == null)
                {
                    throw new GeometricNetworkException("No traced junctions found");
                }
                else
                {
                    if (junctionEIDs.Count > this.MaxFeatures)
                    {
                        throw new GeometricNetworkException(junctionEIDs.Count.ToString(CultureInfo.InvariantCulture) + " features were traced which exceeds the limit of " + this.MaxFeatures);
                    }
                }
            }

            if (this.FlowElements == esriFlowElements.esriFEEdges || this.FlowElements == esriFlowElements.esriFEJunctionsAndEdges)
            {
                if (edgeEIDs.Count == 0)
                {
                    objectJson.AddArray("edges", (new List <JsonObject>()).ToArray());
                }
                else
                {
                    JsonObject[] featureSet;
                    this.GetTrace(edgeEIDs, out featureSet);
                    objectJson.AddArray("edges", featureSet);
                }
            }

            if (this.FlowElements == esriFlowElements.esriFEJunctions || this.FlowElements == esriFlowElements.esriFEJunctionsAndEdges)
            {
                if (junctionEIDs.Count == 0)
                {
                    objectJson.AddArray("junctions", (new List <JsonObject>()).ToArray());
                }
                else
                {
                    JsonObject[] featureSet;
                    this.GetTrace(junctionEIDs, out featureSet);
                    objectJson.AddArray("junctions", featureSet);
                }
            }
        }
Exemplo n.º 2
0
        private byte[] QueryPoint(ESRI.ArcGIS.Geometry.IPoint location, double distance)
        {
            if (distance <= 0.0)
                throw new ArgumentOutOfRangeException("distance");
            // Buffer the point.
            ITopologicalOperator topologicalOperator = (ESRI.ArcGIS.Geometry.ITopologicalOperator)location;
            IGeometry queryGeometry = topologicalOperator.Buffer(distance);
            // Query the feature class.
            ISpatialFilter spatialFilter = new ESRI.ArcGIS.Geodatabase.SpatialFilter();
            spatialFilter.Geometry = queryGeometry;
            spatialFilter.SpatialRel = ESRI.ArcGIS.Geodatabase.esriSpatialRelEnum.esriSpatialRelIntersects;
            spatialFilter.GeometryField = m_fcToQuery.ShapeFieldName;
            IFeatureCursor resultsFeatureCursor = m_fcToQuery.Search(spatialFilter, true);
            // Loop through the features, clip each geometry to the buffer
            // and total areas by attribute value.
            topologicalOperator = (ESRI.ArcGIS.Geometry.ITopologicalOperator)queryGeometry;
            int classFieldIndex = m_fcToQuery.FindField(m_mapFieldToQuery);
            // System.Collections.Specialized.ListDictionary summaryStatsDictionary = new System.Collections.Specialized.ListDictionary();
            Dictionary<string, double> summaryStatsDictionary = new Dictionary<string, double>();
            // Initialize a list to hold JSON geometries.
            List<JsonObject> jsonGeometries = new List<JsonObject>();

            IFeature resultsFeature = null;
            while ((resultsFeature = resultsFeatureCursor.NextFeature()) != null)
            {
                // Clip the geometry.
                IPolygon clippedResultsGeometry = (IPolygon)topologicalOperator.Intersect(resultsFeature.Shape,
                    ESRI.ArcGIS.Geometry.esriGeometryDimension.esriGeometry2Dimension);
                clippedResultsGeometry.Densify(0, 0); // Densify to maintain curved appearance when converted to JSON. 
                // Convert the geometry to JSON and add it to the list.
                JsonObject jsonClippedResultsGeometry = Conversion.ToJsonObject(clippedResultsGeometry);
                jsonGeometries.Add(jsonClippedResultsGeometry);
                // Get statistics.
                IArea area = (IArea)clippedResultsGeometry;
                string resultsClass = resultsFeature.get_Value(classFieldIndex) as string;
                // If the class is already in the dictionary, add the current feature's area to the existing entry.
                if (summaryStatsDictionary.ContainsKey(resultsClass))
                    summaryStatsDictionary[resultsClass] = (double)summaryStatsDictionary[resultsClass] + area.Area;
                else
                    summaryStatsDictionary[resultsClass] = area.Area;
            }
            // Use a helper method to get a JSON array of area records.
            JsonObject[] areaResultJson = CreateJsonRecords(summaryStatsDictionary) as JsonObject[];
            // Create a JSON object of the geometry results and the area records.
            JsonObject resultJsonObject = new JsonObject();
            resultJsonObject.AddArray("geometries", jsonGeometries.ToArray());
            resultJsonObject.AddArray("records", areaResultJson);
            // Get byte array of json and return results.
            byte[] result = Encoding.UTF8.GetBytes(resultJsonObject.ToJson());
            return result;
        }
Exemplo n.º 3
0
        /// <summary>
        /// 将要素类序列化成json格式对象
        /// </summary>
        /// <param name="inputFeaClass">输入要素类</param>
        /// <returns></returns>
        public static JsonObject FclassToJsonObj(IFeatureClass inputFeaClass)
        {
            //获取要素数目
            IQueryFilter pQueryFilter = new QueryFilterClass();

            pQueryFilter.WhereClause = null;
            int count = inputFeaClass.FeatureCount(pQueryFilter);

            //将每一个要素序列化成json数据
            IFeature          pFeature       = null;
            List <JsonObject> jsonGeometries = new List <JsonObject>();

            for (int i = 1; i < count; i++)//OBJECTID从1开始
            {
                pFeature = inputFeaClass.GetFeature(i);
                IGeometry  pGeometry   = pFeature.Shape;
                JsonObject featureJson = new JsonObject();
                JsonObject feaGeoJson  = null;//几何对象
                if (pGeometry != null)
                {
                    feaGeoJson = Conversion.ToJsonObject(pGeometry);
                    featureJson.AddJsonObject("geometry", feaGeoJson);//加入几何对象
                }

                jsonGeometries.Add(featureJson);
            }

            JsonObject resultJson = new JsonObject();

            resultJson.AddArray("geometries", jsonGeometries.ToArray());
            return(resultJson);
        }
Exemplo n.º 4
0
        /// <summary>
        /// Handler operation Identify Route
        /// </summary>
        /// <param name="boundVariables">list of variables bound</param>
        /// <param name="operationInput">input of operation</param>
        /// <param name="outputFormat">format of output</param>
        /// <param name="requestProperties">list of request properties</param>
        /// <param name="responseProperties">list of response properties </param>
        /// <returns>response in byte</returns>
        private byte[] IdentifyRouteOperHandler(NameValueCollection boundVariables, JsonObject operationInput, string outputFormat, string requestProperties, out string responseProperties)
        {
            responseProperties = "{\"Content-Type\" : \"application/json\"}";
            string methodName   = MethodBase.GetCurrentMethod().Name;
            int    routeLayerID = Convert.ToInt32(boundVariables["RouteLayersID"], CultureInfo.InvariantCulture);

            esriUnits routeMeasureUnit = DSUtility.GetMeasureUnit(operationInput, MeasureUnit.routeMeasureUnit);

            IFeatureClass  featureClass          = this.GetRouteFeatureClass(routeLayerID);
            string         routeIDFieldNameValue = DSUtility.GetRouteIDFieldName(operationInput, featureClass.OIDFieldName);
            IRouteLocator2 routeLocator          = DSUtility.GetRouteLocator(featureClass, routeIDFieldNameValue, routeMeasureUnit);

            double?tolerance;
            bool   found = operationInput.TryGetAsDouble("tolerance", out tolerance);

            if (!found || !tolerance.HasValue)
            {
                tolerance = 0.0;
            }

            JsonObject jsonLocation;

            if (!operationInput.TryGetJsonObject("location", out jsonLocation))
            {
                throw new ArgumentException("Invalid location", methodName);
            }

            IPoint location = Conversion.ToGeometry(jsonLocation, esriGeometryType.esriGeometryPoint) as IPoint;

            if (location == null)
            {
                throw new ArgumentException("Invalid location", methodName);
            }

            IEnvelope envelope = location.Envelope;

            envelope.Expand(tolerance.Value, tolerance.Value, false);

            IRouteMeasurePointLocation routeMeasurePointLocation = new RouteMeasurePointLocationClass();
            IRouteLocation             routeLocation;
            IFeature   feature;
            JsonObject result = new JsonObject();

            List <JsonObject>        measures   = new List <JsonObject>();
            IEnumRouteIdentifyResult enumResult = routeLocator.Identify(envelope, string.Empty);

            for (int i = 1; i <= enumResult.Count; i++)
            {
                enumResult.Next(out routeLocation, out feature);
                routeMeasurePointLocation = (IRouteMeasurePointLocation)routeLocation;
                JsonObject measure = new JsonObject();
                measure.AddString("routeID", routeLocation.RouteID.ToString());
                measure.AddDouble("measure", routeMeasurePointLocation.Measure);
                measures.Add(measure);
            }

            result.AddArray("location", measures.ToArray());

            return(result.JsonByte());
        }
Exemplo n.º 5
0
        //customLayers/{customLayersID}
        //returns json with simplified layerinfo (name, id, extent)
        private byte[] CustomLayer(NameValueCollection boundVariables, string outputFormat, string requestProperties, out string responseProperties)
        {
            responseProperties = "{\"Content-Type\" : \"application/json\"}";

            if (null == boundVariables["customLayersID"])
            {
                JsonObject obj = new JsonObject();

                // put collection code here
                CustomLayerInfo[] layerInfos = GetLayerInfos();

                JsonObject[] jos = new JsonObject[layerInfos.Length];

                for (int i = 0; i < layerInfos.Length; i++)
                {
                    jos[i] = layerInfos[i].ToJsonObject();
                }

                obj.AddArray("customLayers", jos);

                return(Encoding.UTF8.GetBytes(obj.ToJson()));
            }

            //layerID
            int layerID = Convert.ToInt32(boundVariables["customLayersID"]);

            //execute
            CustomLayerInfo layerInfo = GetLayerInfo(layerID);

            string json = layerInfo.ToJsonObject().ToJson();

            return(Encoding.UTF8.GetBytes(json));
        }
Exemplo n.º 6
0
        private byte[] GetFeaturesOperHandler(NameValueCollection boundVariables,
                                              JsonObject operationInput,
                                              string outputFormat,
                                              string requestProperties,
                                              out string responseProperties)
        {
            responseProperties = null;

            JsonObject joConn;
            bool       found = operationInput.TryGetJsonObject("connectionString", out joConn);

            if (!found || joConn == null)
            {
                throw new ArgumentNullException("connectionString");
            }

            JsonObject joFC;

            found = operationInput.TryGetJsonObject("featureClass", out joFC);
            if (!found || joFC == null)
            {
                throw new ArgumentNullException("featureClass");
            }

            JsonObject joFilter;

            found = operationInput.TryGetJsonObject("filterWhere", out joFilter);
            if (!found || joFilter == null)
            {
                throw new ArgumentNullException("filterWhere");
            }

            JsonObject result = new JsonObject();

            ConnectionJSObject   connJsObj = ParamsParser.ParseConn(joConn);
            FeatureClassJSObject fcObj     = ParamsParser.ParseFeatrureClass(joFC);
            FilterWhereJSObject  filterObj = ParamsParser.ParseFilterWhere(joFilter);

            List <FeatureObject> features;
            string         outMsg = string.Empty;
            FeaturesHelper helper = new FeaturesHelper();

            features = helper.GetFeatures(connJsObj, fcObj, filterObj, out outMsg);
            List <JsonObject> featureList = new List <JsonObject>();

            foreach (FeatureObject fo in features)
            {
                JsonObject jo = new JsonObject();
                jo.AddArray("attributes", fo.attributes.ToArray());
                jo.AddJsonObject("geometry", Conversion.ToJsonObject(fo.geometry));
                featureList.Add(jo);
            }
            result.AddArray("features", featureList.ToArray());
            result.AddString("outMsg", outMsg);

            return(Encoding.UTF8.GetBytes(result.ToJson()));
        }
Exemplo n.º 7
0
        /// <summary>
        /// convert the current instance in JsonObject
        /// </summary>
        /// <returns>object JsonObject</returns>
        public JsonObject ToJsonObject()
        {
            byte[]     bytes = Conversion.ToJson(this.Extent);
            JsonObject jo    = new JsonObject(Encoding.UTF8.GetString(bytes));

            if (!jo.Exists("spatialReference"))
            {
                if (this.SpatialReference.FactoryCode == 0)
                {
                    jo.AddString("spatialReference", this.SpatialReference.Name);
                }
                else
                {
                    jo.AddLong("spatialReference", (long)this.SpatialReference.FactoryCode);
                }
            }

            JsonObject jsonObjectGeometricNetworkInfo = new JsonObject();

            jsonObjectGeometricNetworkInfo.AddString("name", this.Name);
            jsonObjectGeometricNetworkInfo.AddLong("id", (long)this.ID);
            jsonObjectGeometricNetworkInfo.AddJsonObject("extent", jo);

            INetSchema        netSchema = (INetSchema)this.GeometricNetwork.Network;
            INetWeight        netWeight;
            List <JsonObject> weights = new List <JsonObject>();

            for (int i = 0; i < netSchema.WeightCount; i++)
            {
                netWeight = netSchema.get_Weight(i);
                JsonObject weight = new JsonObject();
                weight.AddLong("id", (long)netWeight.WeightID);
                weight.AddString("name", netWeight.WeightName);
                weight.AddString("type", Enum.GetName(typeof(esriWeightType), netWeight.WeightType));
                weight.AddLong("bitGateSize", (long)netWeight.BitGateSize);

                List <JsonObject>         weightAssociation        = new List <JsonObject>();
                IEnumNetWeightAssociation enumNetWeightAssociation = netSchema.get_WeightAssociations(netWeight.WeightID);
                INetWeightAssociation     netWeightAssociation     = enumNetWeightAssociation.Next();
                while (netWeightAssociation != null)
                {
                    JsonObject jsonObjectNetWeightAssociation = new JsonObject();
                    jsonObjectNetWeightAssociation.AddString("fieldName", netWeightAssociation.FieldName);
                    jsonObjectNetWeightAssociation.AddString("tableName", netWeightAssociation.TableName);
                    weightAssociation.Add(jsonObjectNetWeightAssociation);
                    netWeightAssociation = enumNetWeightAssociation.Next();
                }

                weight.AddArray("weightAssociation", weightAssociation.ToArray());
                weights.Add(weight);
            }

            jsonObjectGeometricNetworkInfo.AddArray("weights", weights.ToArray());

            return(jsonObjectGeometricNetworkInfo);
        }
Exemplo n.º 8
0
        /// <summary>
        /// handler of resource root
        /// </summary>
        /// <param name="boundVariables">list of variables bound</param>
        /// <param name="outputFormat">format of output</param>
        /// <param name="requestProperties">list of request properties</param>
        /// <param name="responseProperties">list of response properties </param>
        /// <returns>root resource in format output in byte</returns>
        private byte[] RootResHandler(NameValueCollection boundVariables, string outputFormat, string requestProperties, out string responseProperties)
        {
            responseProperties = "{\"Content-Type\" : \"application/json\"}";
            JsonObject[] objectArray = System.Array.ConvertAll(this.routeLayerInfos.ToArray(), i => i.ToJsonObject());

            JsonObject jsonObject = new JsonObject();

            jsonObject.AddString("Description", "Dynamic Segmentation Utility SOE Rest");
            jsonObject.AddArray("routeLayers", objectArray);
            return(jsonObject.JsonByte());
        }
Exemplo n.º 9
0
        /// <summary>
        /// Returns a JSON serialized array listing all of the feature layers in the map service, converted to a byte array.
        /// </summary>
        /// <param name="boundVariables">Not used by this method, but required for method signature..</param>
        /// <param name="outputFormat">The only supported format is "json".</param>
        /// <param name="requestProperties">Not used by this method, but required for method signature.</param>
        /// <param name="responseProperties">Not used by this method, but required for method signature</param>
        /// <returns></returns>
        private byte[] GetIdsOfLayersThatHaveMetadata(NameValueCollection boundVariables,
                                                      string outputFormat,
                                                      string requestProperties,
                                                      out string responseProperties)
        {
            responseProperties = null;
            var        idArray = GetIdsOfLayersThatHaveMetadata();
            JsonObject output  = new JsonObject();

            output.AddArray("layerIds", idArray.Select(i => i as object).ToArray());
            return(Encoding.UTF8.GetBytes(output.ToJson()));
        }
Exemplo n.º 10
0
        private byte[] FindRouteLocationsHandler(NameValueCollection boundVariables,
                                                 JsonObject operationInput,
                                                 string outputFormat,
                                                 string requestProperties,
                                                 out string responseProperties)
        {
            responseProperties = null;

            if (!operationInput.TryGetAsLong("layer", out long?layerId))
            {
                throw new ArgumentException("Layer ID not provided");
            }


            bool hasLocations = operationInput.TryGetArray("locations", out object[] locationsArray);

            if (!hasLocations)
            {
                throw new ArgumentException($"Expected \"locations\" to be a JSON array: {operationInput.ToJson()}", "locations");
            }

            var locations = locationsArray.Cast <JsonObject>().ToRouteLocations();

            IRouteLocator2 routeLocator = serverObjectHelper.GetRouteLocator(layerId.GetValueOrDefault(0), routeIdFieldName);

            var located = locations.Select(loc =>
            {
                routeLocator.Locate(loc, out IGeometry result, out esriLocatingError locatingError);
                return(new LocationResult
                {
                    RouteLocation = loc,
                    Geometry = result,
                    LocatingError = locatingError
                });
            });

            var output = new JsonObject();

            output.AddArray("results", located.Select(l => l.ToJsonObject()).ToArray());
            return(Encoding.UTF8.GetBytes(output.ToJson()));

            //byte[] bytes;
            //var serializer = JsonSerializer.CreateDefault();
            //using (var memoryStream = new MemoryStream())
            //using (var textWriter = new StreamWriter(memoryStream, Encoding.UTF8))
            //{
            //    serializer.Serialize(textWriter, located);
            //    bytes = memoryStream.GetBuffer();
            //}
            //return bytes;
        }
Exemplo n.º 11
0
 /// <summary>
 /// resource RouteLayer
 /// </summary>
 /// <param name="boundVariables">list of variables bound</param>
 /// <param name="outputFormat">format of output</param>
 /// <param name="requestProperties">list of request properties</param>
 /// <param name="responseProperties">list of response properties </param>
 /// <returns>resource in byte</returns>
 private byte[] RouteLayer(NameValueCollection boundVariables, string outputFormat, string requestProperties, out string responseProperties)
 {
     responseProperties = "{\"Content-Type\" : \"application/json\"}";
     if (boundVariables["RouteLayersID"] == null)
     {
         JsonObject[] objectArray = System.Array.ConvertAll(this.routeLayerInfos.ToArray(), i => i.ToJsonObject());
         JsonObject   jsonObject  = new JsonObject();
         jsonObject.AddArray("routeLayers", objectArray);
         return(jsonObject.JsonByte());
     }
     else
     {
         int layerID = Convert.ToInt32(boundVariables["RouteLayersID"], CultureInfo.InvariantCulture);
         return(this.GetRouteLayerInfo(layerID).ToJsonObject().JsonByte());
     }
 }
Exemplo n.º 12
0
        public byte[] HandleRESTRequest(string Capabilities, string resourceName, string operationName,
                                        string operationInput, string outputFormat, string requestProperties, out string responseProperties)
        {
            responseProperties = null;

            // Find the correct delegate to forward the request too
            IRESTRequestHandler restRequestHandler = _restSOIHelper.FindRequestHandlerDelegate <IRESTRequestHandler>();

            if (restRequestHandler == null)
            {
                return(null);
            }

            /*
             * Add code to manipulate REST requests here
             */
            //Note: if you want to have a clipping and spatial filter SOI for security reasons,
            //      you must have your own custom implementation for the Query operation.
            //      Clipping and SpatialFilter are not support in a query operation
            if (operationName == "export" || operationName == "identify" || operationName == "find")
            {
                var joOperationInput = new JsonObject(operationInput);

                if (joOperationInput.Exists("clipping"))
                {
                    joOperationInput.Delete("clipping");
                }

                var joSpatialFilter = new JsonObject();
                joSpatialFilter.AddArray("excludedLayers", new object[] {  });
                joSpatialFilter.AddString("geometryType", "esriGeometryPolygon");
                joSpatialFilter.AddJsonObject("geometry", CreateACircle());
                joOperationInput.AddJsonObject("clipping", joSpatialFilter);

                operationInput = joOperationInput.ToJson();
            }

            return(restRequestHandler.HandleRESTRequest(
                       Capabilities, resourceName, operationName, operationInput,
                       outputFormat, requestProperties, out responseProperties));
        }
        private byte[] LayersResHandler(NameValueCollection boundVariables, string outputFormat, string requestProperties, out string responseProperties)
        {
            responseProperties = null;

            CustomLayerInfo[] layerInfos = GetLayerInfos();

            JsonObject[] jos = new JsonObject[layerInfos.Length];

            for (int i = 0; i < layerInfos.Length; i++)
            {
                jos[i] = layerInfos[i].ToJsonObject();
            }

            JsonObject result = new JsonObject();

            result.AddArray("layersInfo", jos);

            string json = result.ToJson();

            return(Encoding.UTF8.GetBytes(json));
        }
    //customLayers/{customLayersID}
    //returns json with simplified layerinfo (name, id, extent)
    private byte[] CustomLayer(NameValueCollection boundVariables, string outputFormat, string requestProperties, out string responseProperties)
    {
      responseProperties = "{\"Content-Type\" : \"application/json\"}";

      if (null == boundVariables["customLayersID"] )
      {
          JsonObject obj = new JsonObject();

          // put collection code here
          CustomLayerInfo[] layerInfos = GetLayerInfos();

          JsonObject[] jos = new JsonObject[layerInfos.Length];

          for (int i = 0; i < layerInfos.Length; i++)
              jos[i] = layerInfos[i].ToJsonObject();

          obj.AddArray("customLayers", jos);

          return Encoding.UTF8.GetBytes(obj.ToJson());
      }

      //layerID
      int layerID = Convert.ToInt32(boundVariables["customLayersID"]);

      //execute
      CustomLayerInfo layerInfo = GetLayerInfo(layerID);

      string json = layerInfo.ToJsonObject().ToJson();

      return Encoding.UTF8.GetBytes(json);
    }
        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()));
        }
Exemplo n.º 16
0
        /// <summary>
        /// Handler operation Identify Route Ex
        /// </summary>
        /// <param name="boundVariables">list of variables bound</param>
        /// <param name="operationInput">input of operation</param>
        /// <param name="outputFormat">format of output</param>
        /// <param name="requestProperties">list of request properties</param>
        /// <param name="responseProperties">list of response properties </param>
        /// <returns>response in byte</returns>
        private byte[] IdentifyRouteExOperHandler(NameValueCollection boundVariables, JsonObject operationInput, string outputFormat, string requestProperties, out string responseProperties)
        {
            responseProperties = "{\"Content-Type\" : \"application/json\"}";
            string methodName   = MethodBase.GetCurrentMethod().Name;
            int    routeLayerID = Convert.ToInt32(boundVariables["RouteLayersID"], CultureInfo.InvariantCulture);

            esriUnits            routeMeasureUnit = DSUtility.GetMeasureUnit(operationInput, MeasureUnit.routeMeasureUnit);
            esriSegmentExtension segmentExtension = DSUtility.GetSegmentExtension(operationInput);
            IFeatureClass        featureClass     = this.GetRouteFeatureClass(routeLayerID);

            JsonObject jsonLocation;

            if (!operationInput.TryGetJsonObject("location", out jsonLocation))
            {
                throw new ArgumentException("Invalid location", methodName);
            }

            IPoint location = Conversion.ToGeometry(jsonLocation, esriGeometryType.esriGeometryPoint) as IPoint;

            if (location == null)
            {
                throw new ArgumentException("Invalid location", methodName);
            }

            string  routeIDFieldNameValue = DSUtility.GetRouteIDFieldName(operationInput);
            IFields fields     = featureClass.Fields;
            int     indexField = fields.FindField(routeIDFieldNameValue);

            if (indexField == -1)
            {
                throw new DynamicSegmentationException(string.Format(CultureInfo.InvariantCulture, "routeIDFieldName {0} not found!", routeIDFieldNameValue));
            }

            object routeID;
            bool   found = operationInput.TryGetObject("routeID", out routeID);

            if (!found)
            {
                throw new DynamicSegmentationException("routeID not valid");
            }

            double?tolerance;

            found = operationInput.TryGetAsDouble("tolerance", out tolerance);
            if (!found || !tolerance.HasValue)
            {
                tolerance = 0.0;
            }

            IField field = fields.get_Field(indexField);

            this.CheckRouteID(routeID, field);

            IRouteLocator2 routeLocator = DSUtility.GetRouteLocator(featureClass, routeIDFieldNameValue, routeMeasureUnit);

            IQueryFilter queryFilter = new QueryFilterClass();

            queryFilter.SubFields = routeLocator.RouteIDFieldName;
            queryFilter.AddField(routeLocator.RouteFeatureClass.ShapeFieldName);
            string where            = string.Format("{0} = {1}{2}{1}", routeLocator.RouteIDFieldNameDelimited, routeLocator.RouteIDIsString ? "'" : string.Empty, routeID);
            queryFilter.WhereClause = where;

            IPoint         locationNearest = null;
            IFeatureCursor featureCursor   = null;

            try
            {
                featureCursor = routeLocator.RouteFeatureClass.Search(queryFilter, true);
                IFeature featureRoute = featureCursor.NextFeature();
                if (featureRoute == null)
                {
                    throw new DynamicSegmentationException(string.Format(CultureInfo.InvariantCulture, "Feature with value {0} not found!", routeID));
                }

                IProximityOperator proximityOperator = featureRoute.ShapeCopy as IProximityOperator;
                locationNearest = proximityOperator.ReturnNearestPoint(location, segmentExtension);
            }
            catch
            {
                throw;
            }
            finally
            {
                if (featureCursor != null)
                {
                    Marshal.ReleaseComObject(featureCursor);
                }
            }

            IEnvelope envelope = locationNearest.Envelope;

            envelope.Expand(tolerance.Value, tolerance.Value, false);

            IRouteMeasurePointLocation routeMeasurePointLocation = new RouteMeasurePointLocationClass();
            IRouteLocation             routeLocation;
            IFeature   feature;
            JsonObject result = new JsonObject();

            List <JsonObject>        measures   = new List <JsonObject>();
            IEnumRouteIdentifyResult enumResult = routeLocator.Identify(envelope, where);

            for (int i = 1; i <= enumResult.Count; i++)
            {
                enumResult.Next(out routeLocation, out feature);
                routeMeasurePointLocation = (IRouteMeasurePointLocation)routeLocation;
                JsonObject measure = new JsonObject();
                measure.AddString("routeID", routeLocation.RouteID.ToString());
                measure.AddDouble("measure", routeMeasurePointLocation.Measure);
                measure.AddJsonObject("location", Conversion.ToJsonObject(locationNearest, true));
                measures.Add(measure);
            }

            result.AddArray("location", measures.ToArray());

            return(result.JsonByte());
        }
Exemplo n.º 17
0
 private byte[] RootHandler(NameValueCollection boundVariables, string outputFormat, string requestProperties, out string responseProperties)
 {
     responseProperties = null;
     JsonObject result = new JsonObject();
     result.AddArray("layers", m_layers.Values.Select(i => i.ToJsonObject()).ToArray<JsonObject>());
     return Encoding.UTF8.GetBytes(result.ToJson());
 }
 private JsonObject GetWISynonyms(object[] records, Boolean? excludeWISiteCodes)
 {
     DataTable dt = new DataTable();
     DataColumn syn = new DataColumn("syn", typeof(string));
     dt.Columns.Add(syn);
     DataRow row;
     string code;
     row = dt.NewRow();
     foreach (JsonObject obj in records)
     {
         row = dt.NewRow();
         obj.TryGetString("s", out code);//the synonym parameter is just named 's' in the json to keep it small
         row["syn"] = code;
         dt.Rows.Add(row);
     }
     string storedProcedureName = null;
     if (excludeWISiteCodes == true)
     {
         storedProcedureName = "IWC_GetWISiteSynonymsExcludingWISiteCodes";
     }
     else
     {
         storedProcedureName = "IWC_GetWISiteSynonyms";
     }
     SqlCommand cmd = new SqlCommand(storedProcedureName, sqlConn);
     cmd.CommandType = CommandType.StoredProcedure;
     SqlParameter param = cmd.Parameters.AddWithValue("@data", dt);
     param.SqlDbType = SqlDbType.Structured;
     SqlDataReader reader = cmd.ExecuteReader();
     List<SiteSynonym> siteCodes = new List<SiteSynonym>();
     SiteSynonym[] siteCodesArray = null;
     if (reader.HasRows)
     {
         while (reader.Read())
         {
             SiteSynonym siteObj = new SiteSynonym();
             siteObj.s = reader.GetString(0);
             siteObj.c = reader.GetString(1);
             siteCodes.Add(siteObj);
         }
         siteCodesArray = siteCodes.ToArray();
     }
     reader.Close();
     JsonObject jsonObj = new JsonObject();
     jsonObj.AddArray("siteCodes", siteCodesArray);
     return jsonObj;
 }
Exemplo n.º 19
0
        /// <summary>
        /// Returns JSON representation of Help resource. This resource is not a collection.
        /// </summary>
        /// <param name="boundVariables">list of variables bound</param>
        /// <param name="outputFormat">format of output</param>
        /// <param name="requestProperties">list of request properties</param>
        /// <param name="responseProperties">list of response properties </param>
        /// <returns>String JSON representation of Help resource.</returns>
        private byte[] HelpResHandler(NameValueCollection boundVariables, string outputFormat, string requestProperties, out string responseProperties)
        {
            responseProperties = "{\"Content-Type\" : \"application/json\"}";

            JsonObject result = new JsonObject();

            JsonObject soeResources = new JsonObject();

            soeResources.AddString("RouteLayers", "A list of polylineM layers in the map.");
            result.AddJsonObject("Resources", soeResources);

            JsonObject getIdentifyRouteInputs = new JsonObject();

            getIdentifyRouteInputs.AddString("location", "(geometry) Point");
            getIdentifyRouteInputs.AddString("tolerance", "(number) optional but if you don't set, soe set 0 so you could no have results");
            getIdentifyRouteInputs.AddString("routeMeasureUnit", "(enum) optional default is esriUnknownUnits");
            getIdentifyRouteInputs.AddString("routeIDFieldName", "(string)");

            JsonObject getIdentifyRouteOutput    = new JsonObject();
            JsonObject getIdentifyRouteOutputLoc = new JsonObject();

            getIdentifyRouteOutputLoc.AddString("routeID", "(string, double, int) depends fieldtype routeIDFieldName");
            getIdentifyRouteOutputLoc.AddString("measure", "(number)");
            getIdentifyRouteOutput.AddArray("location (array)", new JsonObject[] { getIdentifyRouteOutputLoc });

            JsonObject getIdentifyRouteParams = new JsonObject();

            getIdentifyRouteParams.AddString("Info", "Identify Route operation. To learn more about formatting the input geometries, input geometry, please visit the 'Geometry Objects' section of the ArcGIS Server REST documentation.");
            getIdentifyRouteParams.AddJsonObject("Inputs", getIdentifyRouteInputs);
            getIdentifyRouteParams.AddJsonObject("Outputs", getIdentifyRouteOutput);

            JsonObject getPointLocationInputs = new JsonObject();

            getPointLocationInputs.AddString("routeIDFieldName", "(string)");
            getPointLocationInputs.AddString("routeID", "(string, double, int) depends fieldtype routeIDFieldName");
            getPointLocationInputs.AddString("measure", "(number)");
            getPointLocationInputs.AddString("lateralOffset", "(number) optional default = 0");
            getPointLocationInputs.AddString("routeMeasureUnit", "(enum) optional default = esriUnknownUnits");
            getPointLocationInputs.AddString("routeLocationMeasureUnit", "(enum) optional default = esriUnknownUnits");

            JsonObject getPointLocationOutput = new JsonObject();

            getPointLocationOutput.AddString("geometries", "(geometry) point or multipoint");

            JsonObject getPointLocationParams = new JsonObject();

            getPointLocationParams.AddString("Info", "Point Location operation.");
            getPointLocationParams.AddJsonObject("Inputs", getPointLocationInputs);
            getPointLocationParams.AddJsonObject("Outputs", getPointLocationOutput);

            JsonObject getLineLocationInputs = new JsonObject();

            getLineLocationInputs.AddString("routeIDFieldName", "(string)");
            getLineLocationInputs.AddString("routeID", "(string, double, int) depends fieldtype routeIDFieldName");
            getLineLocationInputs.AddString("fromMeasure", "(number) optional if you set toMeasure");
            getLineLocationInputs.AddString("toMeasure", "(number) optional if you set fromMeasure");
            getLineLocationInputs.AddString("lateralOffset", "(number) optional default = 0");
            getLineLocationInputs.AddString("routeMeasureUnit", "(enum) optional default = esriUnknownUnits");
            getLineLocationInputs.AddString("routeLocationMeasureUnit", "(enum) optional default = esriUnknownUnits");

            JsonObject getLineLocationOutput = new JsonObject();

            getLineLocationOutput.AddString("geometries", "(geometry) polyline");

            JsonObject getLineLocationParams = new JsonObject();

            getLineLocationParams.AddString("Info", "Line Location operation.");
            getLineLocationParams.AddJsonObject("Inputs", getLineLocationInputs);
            getLineLocationParams.AddJsonObject("Outputs", getLineLocationOutput);

            JsonObject getIdentifyRouteExInputs = new JsonObject();

            getIdentifyRouteExInputs.AddString("location", "(geometry) Point");
            getIdentifyRouteExInputs.AddString("routeID", "(string, double, int) depends fieldtype routeIDFieldName");
            getIdentifyRouteExInputs.AddString("tolerance", "(number) optional but if you don't set, soe set 0 so you could no have results");
            getIdentifyRouteExInputs.AddString("routeMeasureUnit", "(enum) optional default = esriUnknownUnits");
            getIdentifyRouteExInputs.AddString("routeIDFieldName", "(string)");
            getIdentifyRouteExInputs.AddString("segmentExtension", "(enum) optional default = esriNoExtension");

            JsonObject getIdentifyRouteExOutput    = new JsonObject();
            JsonObject getIdentifyRouteExOutputLoc = new JsonObject();

            getIdentifyRouteExOutputLoc.AddString("routeID", "(string, double, int) depends fieldtype routeIDFieldName");
            getIdentifyRouteExOutputLoc.AddString("measure", "(number)");
            getIdentifyRouteExOutputLoc.AddString("location", "(geometry) point");

            getIdentifyRouteExOutput.AddArray("location (array)", new JsonObject[] { getIdentifyRouteExOutputLoc });

            JsonObject getIdentifyRouteExParams = new JsonObject();

            getIdentifyRouteExParams.AddString("Info", "Identify Route Ex operation. To learn more about formatting the input geometries, input geometry, please visit the 'Geometry Objects' section of the ArcGIS Server REST documentation.");
            getIdentifyRouteExParams.AddJsonObject("Inputs", getIdentifyRouteExInputs);
            getIdentifyRouteExParams.AddJsonObject("Outputs", getIdentifyRouteExOutput);

            JsonObject soeOperations = new JsonObject();

            soeOperations.AddJsonObject("IdentifyRoute", getIdentifyRouteParams);
            soeOperations.AddJsonObject("PointLocation", getPointLocationParams);
            soeOperations.AddJsonObject("LineLocation", getLineLocationParams);
            soeOperations.AddJsonObject("IdentifyRouteEx", getIdentifyRouteExParams);

            result.AddJsonObject("Operations", soeOperations);

            return(result.JsonByte());
        }
Exemplo n.º 20
0
        /// <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;
            }));
        }
Exemplo n.º 21
0
        /// <summary>
        /// Build Meta Info
        /// </summary>
        private void BuildMeta()
        {
            IFeatureClass fc_poi = m_fcName.Open() as IFeatureClass;
            IGeoDataset ds_poi = fc_poi as IGeoDataset;
            int xmin = (int)Math.Floor(ds_poi.Extent.XMin);
            int ymin = (int)Math.Floor(ds_poi.Extent.YMin);
            int xmax = (int)Math.Ceiling(ds_poi.Extent.XMax);
            int ymax = (int)Math.Ceiling(ds_poi.Extent.YMax);
            int size = int.Parse(this.tbxSize.Text);
            int step = (int)Math.Ceiling((xmax - xmin) * 1.0 / size);
            string ns = "poi:" + this.tbxCacheName.Text + ":";

            IDatabase client = m_redis.GetDatabase();
            client.StringSet(ns + "size", size.ToString());
            client.StringSet(ns + "xmin", xmin.ToString());
            client.StringSet(ns + "ymin", ymin.ToString());
            client.StringSet(ns + "xmax", xmax.ToString());
            client.StringSet(ns + "ymax", ymax.ToString());
            client.StringSet(ns + "step", step.ToString());


            JsonObject response = new JsonObject();

            List<JsonObject> ls_fields_cache = new List<JsonObject>();
            for (int i = 0; i < fc_poi.Fields.FieldCount; i++)
            {
                IField field = fc_poi.Fields.get_Field(i);
                JsonObject js_f = new JsonObject();
                js_f.AddString("name", field.Name);
                js_f.AddString("type", Enum.GetName(typeof(esriFieldType), field.Type));
                js_f.AddString("alias", field.AliasName);
                if (field.Type == esriFieldType.esriFieldTypeString)
                {
                    js_f.AddString("length", field.Length.ToString());
                }
                else
                {
                    js_f.AddString("length", "");
                }
                ls_fields_cache.Add(js_f);
            }
            response.AddArray("fields", ls_fields_cache.ToArray());
            if (fc_poi.ShapeType == esriGeometryType.esriGeometryPoint)
            {
                response.AddString("geometryType", "esriGeometryPoint");
            }
            else if (fc_poi.ShapeType == esriGeometryType.esriGeometryPolyline)
            {
                response.AddString("geometryType", "esriGeometryPolyline");
            }
            else if (fc_poi.ShapeType == esriGeometryType.esriGeometryPolygon)
            {
                response.AddString("geometryType", "esriGeometryPolygon");
            }
            IGeoDataset gds_poi = fc_poi as IGeoDataset;
            JsonObject js_sr = new JsonObject();
            js_sr.AddLong("wkid", gds_poi.SpatialReference.FactoryCode);
            response.AddJsonObject("spatialReference", js_sr);

            client.StringSet(ns + "response", response.ToJson());

            client.SetAdd("poi:caches", this.tbxCacheName.Text);

        }
Exemplo n.º 22
0
 public JsonObject ToJsonObject()
 {
     JsonObject result = new JsonObject();
     if (DisplayFieldName != null) {
         result.AddString("displayFieldName", DisplayFieldName);
     }
     if (Fields.Count > 0) {
         JsonObject[] fields = new JsonObject[Fields.Count];
         for (int i = 0; i < Fields.Count; i += 1) {
             IField field = Fields[i];
             JsonObject fjson = new JsonObject();
             fjson.AddString("name", field.Name);
             fjson.AddString("alias", field.AliasName);
             fjson.AddString("type", FIELD_TYPE_NAMES[(int)field.Type]);
             fjson.AddLong("length", field.Length);
             fields[i] = fjson;
         }
         result.AddArray("fields", fields);
     }
     if (GeometryType != esriGeometryType.esriGeometryAny) {
         result.AddString("geometryType", GEOMETRY_TYPE_NAMES[(int)GeometryType]);
     }
     if (Features.Count > 0) {
         JsonObject[] features = new JsonObject[Features.Count];
         for (int i = 0; i < Features.Count; i += 1) {
             features[i] = Features[i].ToJsonObject();
         }
         result.AddArray("features", features);
     }
     return result;
 }
        /// <summary>
        /// solve isolation
        /// </summary>
        /// <returns>object JsonObject</returns>
        public override JsonObject Solve()
        {
            try
            {
                if ((this.edgeFlags.Length == 0) && (this.junctionFlags.Length == 0))
                {
                    string message = "No input valid flags found";
                    if (this.flagNotFound.Count == 0)
                    {
                        throw new GeometricNetworkException(message);
                    }
                    else
                    {
                        JsonObject error = (new ObjectError(message)).ToJsonObject();
                        error.AddArray("flagsNotFound", Helper.GetListJsonObjects(this.flagNotFound));

                        return(error);
                    }
                }

                INetwork network = this.geometricNetwork.Network;

                ITraceFlowSolverGEN traceFlowSolver = new TraceFlowSolverClass() as ITraceFlowSolverGEN;
                INetSolver          netSolver       = traceFlowSolver as INetSolver;
                netSolver.SourceNetwork = network;

                this.SetFlagsOrigin(ref traceFlowSolver);

                ////now create barries based on valves
                INetElementBarriersGEN netElementBarriersGEN = new NetElementBarriersClass() as INetElementBarriersGEN;
                netElementBarriersGEN.ElementType = esriElementType.esriETJunction;
                netElementBarriersGEN.Network     = network;
                int[] userIds = Helper.GetOIDs(this.Valve);
                netElementBarriersGEN.SetBarriers(this.Valve.FeatureClassID, ref userIds);
                INetElementBarriers netElementBarriers = netElementBarriersGEN as INetElementBarriers;
                netSolver.set_ElementBarriers(esriElementType.esriETJunction, netElementBarriers);

                IEnumNetEID junctionEIDs;
                IEnumNetEID edgeEIDs;
                traceFlowSolver.FindFlowEndElements(esriFlowMethod.esriFMConnected, esriFlowElements.esriFEJunctionsAndEdges, out junctionEIDs, out edgeEIDs);

                IEIDHelper eidHelper = new EIDHelperClass();
                eidHelper.GeometricNetwork = this.geometricNetwork;
                eidHelper.ReturnFeatures   = true;

                List <IEIDInfo> valveEIDInfoHT = Helper.GetEIDInfoListByFeatureClass(this.Valve.FeatureClassID, junctionEIDs, eidHelper);

                traceFlowSolver         = new TraceFlowSolverClass() as ITraceFlowSolverGEN;
                netSolver               = traceFlowSolver as INetSolver;
                netSolver.SourceNetwork = network;

                this.SetFlagsOrigin(ref traceFlowSolver);

                netSolver.DisableElementClass(this.Station.FeatureClassID);
                traceFlowSolver.FindFlowEndElements(esriFlowMethod.esriFMConnected, esriFlowElements.esriFEJunctions, out junctionEIDs, out edgeEIDs);

                List <IEIDInfo> sourceEIDInfoHT = Helper.GetEIDInfoListByFeatureClass(this.Station.FeatureClassID, junctionEIDs, eidHelper);

                ////set up trace to find directly reachable sources
                traceFlowSolver         = new TraceFlowSolverClass() as ITraceFlowSolverGEN;
                netSolver               = traceFlowSolver as INetSolver;
                netSolver.SourceNetwork = network;

                this.SetFlagsOrigin(ref traceFlowSolver);

                ////set barriers in the network based on the saved valves
                ISelectionSetBarriers netElementBarrier = new SelectionSetBarriersClass();
                foreach (IEIDInfo eidInfo in valveEIDInfoHT)
                {
                    netElementBarrier.Add(this.Valve.FeatureClassID, eidInfo.Feature.OID);
                }

                netSolver.SelectionSetBarriers = netElementBarrier;

                ////run trace to find directly reachable sources(without passing valve)
                traceFlowSolver.FindFlowElements(esriFlowMethod.esriFMConnected, esriFlowElements.esriFEJunctionsAndEdges, out junctionEIDs, out edgeEIDs);
                List <IEIDInfo> sourceDirectEIDInfoHT = Helper.GetEIDInfoListByFeatureClass(this.Station.FeatureClassID, junctionEIDs, eidHelper);

                ////remove directly reachable sources from source array
                foreach (IEIDInfo eidInfo in sourceDirectEIDInfoHT)
                {
                    sourceEIDInfoHT.RemoveAll(x => x.Feature.OID == eidInfo.Feature.OID);
                }

                List <IEIDInfo> noSourceValveHT  = new List <IEIDInfo>();
                List <IEIDInfo> hasSourceValveHT = new List <IEIDInfo>();

                List <int> listBarrierIds;
                bool       foundSource;

                foreach (IEIDInfo valve in valveEIDInfoHT)
                {
                    foundSource = false;

                    ////create array of all isolation valve excluding the current one
                    listBarrierIds = new List <int>();
                    if (valveEIDInfoHT.Count > 1)
                    {
                        listBarrierIds.AddRange(valveEIDInfoHT.ConvertAll <int>(i => i.Feature.OID));
                        if (listBarrierIds.Contains(valve.Feature.OID))
                        {
                            listBarrierIds.Remove(valve.Feature.OID);
                        }
                    }

                    ////for each source attempt to trace
                    INetFlag netFlag1;
                    INetFlag netFlag2;
                    foreach (IEIDInfo source in sourceEIDInfoHT)
                    {
                        ////setup trace to test each valve
                        traceFlowSolver         = new TraceFlowSolverClass() as ITraceFlowSolverGEN;
                        netSolver               = traceFlowSolver as INetSolver;
                        netSolver.SourceNetwork = network;

                        ////set the first junction flag for path finding based this current valve
                        netFlag1             = new JunctionFlagClass();
                        netFlag1.UserClassID = valve.Feature.Class.ObjectClassID;
                        netFlag1.UserID      = valve.Feature.OID;
                        netFlag1.UserSubID   = 0;
                        netFlag1.Label       = "Origin";

                        ////set the second and last trace flag at this source
                        netFlag2             = new JunctionFlagClass();
                        netFlag2.UserClassID = source.Feature.Class.ObjectClassID;
                        netFlag2.UserID      = source.Feature.OID;
                        netFlag2.UserSubID   = 0;
                        netFlag2.Label       = "Destination";

                        Helper.AddTwoJunctionFlagsToTraceSolver(ref traceFlowSolver, netFlag1, netFlag2);

                        if (listBarrierIds.Count > 0)
                        {
                            netElementBarriersGEN             = new NetElementBarriersClass() as INetElementBarriersGEN;
                            netElementBarriersGEN.ElementType = esriElementType.esriETJunction;
                            netElementBarriersGEN.Network     = network;
                            int[] barrierIds = listBarrierIds.ToArray();
                            netElementBarriersGEN.SetBarriers(this.Valve.FeatureClassID, ref barrierIds);
                            netElementBarriers = netElementBarriersGEN as INetElementBarriers;
                            netSolver.set_ElementBarriers(esriElementType.esriETJunction, netElementBarriers);
                        }

                        ////run trace
                        object[] segCosts = new object[1];
                        segCosts[0] = new object();
                        edgeEIDs    = null;
                        traceFlowSolver.FindPath(esriFlowMethod.esriFMConnected, esriShortestPathObjFn.esriSPObjFnMinSum, out junctionEIDs, out edgeEIDs, 1, ref segCosts);
                        if (edgeEIDs != null && edgeEIDs.Count > 0)
                        {
                            foundSource = true;
                            break;
                        }
                    }

                    if (foundSource)
                    {
                        hasSourceValveHT.Add(valve);
                    }
                    else
                    {
                        noSourceValveHT.Add(valve);
                    }
                }

                traceFlowSolver         = new TraceFlowSolverClass() as ITraceFlowSolverGEN;
                netSolver               = traceFlowSolver as INetSolver;
                netSolver.SourceNetwork = network;

                this.SetFlagsOrigin(ref traceFlowSolver);

                ////set the barrier in the network based on the saved valves
                netElementBarrier = new SelectionSetBarriersClass();
                foreach (IEIDInfo eidInfo in hasSourceValveHT)
                {
                    netElementBarrier.Add(this.Valve.FeatureClassID, eidInfo.Feature.OID);
                }

                netSolver.SelectionSetBarriers = netElementBarrier;

                ////run last trace
                traceFlowSolver.FindFlowElements(esriFlowMethod.esriFMConnected, this.FlowElements, out junctionEIDs, out edgeEIDs);

                ////deal with out put juncEIDs and edgeEIDs
                JsonObject objectJson = new JsonObject();
                this.SetResults(ref objectJson, edgeEIDs, junctionEIDs);
                objectJson.AddArray("flagsNotFound", Helper.GetListJsonObjects(this.flagNotFound));

                ////valves
                if (hasSourceValveHT.Count > 0)
                {
                    JsonObject[] featureSetValves;
                    this.GetTrace(Helper.GetEnumNetEID(hasSourceValveHT, esriElementType.esriETJunction), out featureSetValves);
                    objectJson.AddJsonObject("valves", featureSetValves[0]);
                }

                return(objectJson);
            }
            catch (Exception e)
            {
                return((new ObjectError(e.Message)).ToJsonObject());
            }
        }
        private byte[] LayersResHandler(NameValueCollection boundVariables, string outputFormat, string requestProperties, out string responseProperties)
        {
            responseProperties = null;

            CustomLayerInfo[] layerInfos = GetLayerInfos();

            JsonObject[] jos = new JsonObject[layerInfos.Length];

            for (int i = 0; i < layerInfos.Length; i++)
                jos[i] = layerInfos[i].ToJsonObject();

            JsonObject result = new JsonObject();
            result.AddArray("layersInfo", jos);

            string json = result.ToJson();

            return Encoding.UTF8.GetBytes(json);
        }
        /// <summary>
        /// Traverse the topology graph, <see cref="ITopologyGraph"/>, to visit topology elements <see cref="ITopologyElement"/>
        /// </summary>
        /// <param name="featureDataset">Feature dataset object</param>
        /// <param name="topologyName">The topology name</param>
        /// <param name="featureClassName">The feature class name</param>
        /// <param name="originFeatureObjectId">Feature ObjectId from the feature class, <paramref name="featureClassName"/></param>
        /// <returns>A JSON object <see cref="JsonObject"/> containing parcels' id and address</returns>
        /// <remarks>
        /// This method builds the topology graph around origin parcel feature and traverse the topology graph to fetch its adjoining parcels and their addresses
        /// </remarks>
        public JsonObject TraverseTopologyGraph(IFeatureDataset featureDataset, string topologyName, string featureClassName, int originFeatureObjectId)
        {
            // Fetch feature class by name
            IFeatureClass parcelFeatureClass = GetFeatureClass(featureDataset, featureClassName);

            // Fetch topology by name from feature dataset
            ITopology topology = GetTopologyFromFeatureDataset(featureDataset, topologyName);

            // Get the origin parcel feature identified by ObjectID
            IFeature parcelFeature = GetFeature(parcelFeatureClass, originFeatureObjectId);

            ITopologyGraph topologyGraph = topology.Cache;

            // Build the topology graph around the origin parcel feature
            topologyGraph.Build(parcelFeature.Shape.Envelope, false);

            IEnumTopologyEdge enumTopologyEdge = topologyGraph.GetParentEdges(parcelFeatureClass, originFeatureObjectId);

            enumTopologyEdge.Reset();

            List <dynamic> taxParcelIds = new List <dynamic>();

            IEnvelope topologyParentsEnvelope             = new EnvelopeClass();
            Dictionary <int, IPoint> parcelsToCentroidMap = new Dictionary <int, IPoint>();

            for (int topoEdgeCount = 0; topoEdgeCount < enumTopologyEdge.Count; topoEdgeCount++)
            {
                ITopologyEdge topologyEdge = enumTopologyEdge.Next();

                // Parents of the topology edge
                IEnumTopologyParent parents = topologyEdge.Parents;
                parents.Reset();

                for (int parentsCount = 0; parentsCount < parents.Count; parentsCount++)
                {
                    esriTopologyParent parent         = parents.Next();
                    int           parentFID           = parent.m_FID;
                    IFeatureClass parentFC            = parent.m_pFC;
                    IFeature      parentParcelFeature = parentFC.GetFeature(parentFID);

                    // Get the index of 'ParcelType' field from the parcel feature class
                    int parcelTypeIndex = parentParcelFeature.Fields.FindField("PARCELTYPE");

                    // Get parcel type value
                    int parcelTypeValue = Convert.ToInt32(parentParcelFeature.Value[parcelTypeIndex]);

                    // Avoid duplicates and skip parcels with 'RowOverlap' subtype
                    if (parentFC == parcelFeatureClass && !taxParcelIds.Contains(parentFID) && parentFID != originFeatureObjectId && (parcelTypeValue < 8 && parcelTypeValue > 0))
                    {
                        taxParcelIds.Add(parentFID);

                        // Envelope of a parcel
                        IEnvelope parcelEnvelope = parentParcelFeature.Extent.Envelope;

                        // Centroid of a parcel
                        IArea  parcelArea     = parcelEnvelope as IArea;
                        IPoint parcelCentroid = parcelArea.Centroid;

                        // Add parcel id and centroid to the mapping dictionary
                        parcelsToCentroidMap.Add(parentFID, parcelCentroid);

                        // Union of the adjoining parcels' envelope
                        topologyParentsEnvelope.Union(parcelEnvelope);
                    }
                }
            }

            // Update topology graph to include adjoining parcels
            topologyGraph.Build(topologyParentsEnvelope, false);

            JsonObject jsonObject = new JsonObject();

            // Get adjoining parcels and their addresses
            List <string> parcelWithAddressList = GetParcelsWithAddress(topologyGraph, parcelsToCentroidMap);

            // Format JSON array
            jsonObject.AddArray($"Adjoining parcels of {originFeatureObjectId}", parcelWithAddressList?.ToArray());
            return(jsonObject);
        }
Exemplo n.º 26
0
        private byte[] ExecuteStoredProcedureHandler(NameValueCollection boundVariables,
                                                     JsonObject operationInput,
                                                     string outputFormat,
                                                     string requestProperties,
                                                     out string responseProperties)
        {
            responseProperties = null;
            string retString = "";

            try
            {
                //return Encoding.UTF8.GetBytes(retStrn);
                //return null;

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

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

                responseProperties = null;
                IServerEnvironment3 senv    = GetServerEnvironment() as IServerEnvironment3;
                JsonObject          result  = new JsonObject();
                JsonObject          suinfoj = new JsonObject();
                //get user info and serialize into JSON
                IServerUserInfo suinfo = senv.UserInfo;
                if (null != suinfo)
                {
                    suinfoj.AddString("currentUser", suinfo.Name);

                    IEnumBSTR     roles    = suinfo.Roles;
                    List <string> rolelist = new List <string>();
                    if (null != roles)
                    {
                        string role = roles.Next();
                        while (!string.IsNullOrEmpty(role))
                        {
                            rolelist.Add(role);
                            role = roles.Next();
                        }
                    }

                    suinfoj.AddArray("roles", rolelist.ToArray());
                    result.AddJsonObject("serverUserInfo", suinfoj);
                }
                else
                {
                    result.AddJsonObject("serverUserInfo", null);
                }

                IServerObject so = serverObjectHelper.ServerObject;
                retString = "got so>";

                string progString = "";
                retString += "> Stored Proc via oleDB ";// + ex.Message;
                OleDbConnection con = new OleDbConnection();
                string          paramsThatParsed = "";



                con.ConnectionString = @"Provider =SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=" + extra.Split(',')[0] + ";Data Source=" + extra.Split(',')[1];// @"Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=TestDB;Data Source=PC684"; //
                string storedProcedureName = "dbo.apLITSaveChanges";
                bool   isStatusOutput      = Convert.ToBoolean(extra.Split(',')[2]);
                //the connection string below uses integrated security which is usually superior to storing credential in visible text
                //con.ConnectionString = @"Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=TestDB;Data Source=PC684";
                //con.Open();
                //retString += ">opened connection";
                string       SQLString = "";
                OleDbCommand cmd       = new OleDbCommand(storedProcedureName, con);
                cmd.CommandType = System.Data.CommandType.StoredProcedure;
                string userName = "******";
                if (suinfo.Name != null)
                {
                    userName = suinfo.Name;
                }
                cmd.Parameters.AddWithValue("@WindowsLogin", userName);
                SQLString += "@WindowsLogin='******'";
                //SQLString += "@WindowsLogin="******">created command";
                string[] paramValsForStoredProc = pipeDelimetedStringValuePairsForStoredProc.Split('|');
                foreach (string paramVal in paramValsForStoredProc)
                {
                    string param = paramVal.Split(',')[0];
                    paramsThatParsed += "," + param;
                    string val = paramVal.Split(',')[1];
                    retString += ">param and value : " + param + " = " + val;

                    param = "@" + param;
                    if (param.ToUpper().Contains("GEOLOCID"))
                    {
                        int i = int.Parse(val);
                        cmd.Parameters.AddWithValue(param, i);
                        SQLString += ", " + param + "= " + i;
                    }
                    else if (param.ToUpper() == "@LATITUDE" || param.ToUpper() == "@LONGITUDE")
                    {
                        double d = double.Parse(val);
                        cmd.Parameters.AddWithValue(param, d);
                        SQLString += ", " + param + "=  " + d;
                    }
                    else if (param.ToUpper() == "@STATUS")
                    {
                        if (isStatusOutput)
                        {
                            //cmd.Parameters[param].Direction = ParameterDirection.Output;
                            retString += ">Set direction of status parameter to output";
                            SQLString += ", @STATUS = @localstatus OUTPUT";
                        }
                    }
                    else
                    {
                        cmd.Parameters.AddWithValue(param, val);
                        //SQLString += ", " + param + "=  " + val ;
                        SQLString += ", " + param + "=  '" + val + "'";
                    }
                }//CurGeoLocID,NewGeoLocID,Address,City,ZipCode,Latitude,Longitude,FacilityName,AppID,WindowsLogin,ServerName,ServerName,Status
                SQLString = "exec dbo.apLITSaveChanges " + SQLString;
                if (isStatusOutput)
                {
                    SQLString = "DECLARE @localstatus varchar(256);" + SQLString;
                }
                string retStrn = UseAOToCreateUpdateFeatures(SQLString);
                return(Encoding.UTF8.GetBytes(retStrn));

                return(null);

                cmd.Connection = con;
                cmd.ExecuteNonQuery();

                return(Encoding.UTF8.GetBytes(result.ToJson() + "  -  " + retString.ToString()));
            }
            catch (Exception ex)
            {
                return(Encoding.UTF8.GetBytes("ERROR   " + ex.ToString() + "  :  " + retString.ToString()));
            }
        }
Exemplo n.º 27
0
 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
 }
        /// <summary>
        /// operation solve trace
        /// </summary>
        /// <returns>solve trace</returns>
        public override JsonObject Solve()
        {
            try
            {
                if ((this.edgeFlags.Length == 0) && (this.junctionFlags.Length == 0))
                {
                    string message = "No input valid flags found";
                    if (this.flagNotFound.Count == 0)
                    {
                        throw new GeometricNetworkException(message);
                    }
                    else
                    {
                        JsonObject error = (new ObjectError(message)).ToJsonObject();
                        error.AddArray("flagsNotFound", Helper.GetListJsonObjects(this.flagNotFound));
                        if (this.barrierNotFound.Count > 0)
                        {
                            error.AddArray("barriersNotFound", Helper.GetListJsonObjects(this.barrierNotFound));
                        }

                        return(error);
                    }
                }

                ITraceFlowSolverGEN traceFlowSolver = new TraceFlowSolverClass() as ITraceFlowSolverGEN;
                INetSolver          netSolver       = traceFlowSolver as INetSolver;
                INetwork            network         = this.geometricNetwork.Network;
                netSolver.SourceNetwork = network;

                // flag origin
                this.SetFlagsOrigin(ref traceFlowSolver);

                // barrier
                this.SetBarriers(ref traceFlowSolver);

                // set disabled layers
                foreach (int i in this.DisableLayers)
                {
                    netSolver.DisableElementClass(i);
                }

                // set weight
                this.SetWeights(ref traceFlowSolver);

                if ((this.TraceSolverType != TraceSolverType.FindCircuits) && (this.TraceSolverType != TraceSolverType.FindCommonAncestors))
                {
                    // The TraceIndeterminateFlow property affects the trace results of trace solvers whose FlowMethod parameter is esriFMUpstream or esriFMDownstream
                    if ((this.FlowMethod == esriFlowMethod.esriFMDownstream) || (this.FlowMethod == esriFlowMethod.esriFMUpstream))
                    {
                        traceFlowSolver.TraceIndeterminateFlow = this.TraceIndeterminateFlow;
                    }
                }

                IEnumNetEID junctionEIDs = null;
                IEnumNetEID edgeEIDs     = null;
                object      totalCost;
                int         count;
                object[]    segmentCosts;

                JsonObject objectJson = new JsonObject();
                switch (this.TraceSolverType)
                {
                case TraceSolverType.FindAccumulation:
                    traceFlowSolver.FindAccumulation(this.FlowMethod, this.FlowElements, out junctionEIDs, out edgeEIDs, out totalCost);
                    objectJson.AddDouble("totalCost", (double)totalCost);
                    break;

                case TraceSolverType.FindCircuits:
                    traceFlowSolver.FindCircuits(this.FlowElements, out junctionEIDs, out edgeEIDs);
                    break;

                case TraceSolverType.FindCommonAncestors:
                    traceFlowSolver.FindCommonAncestors(this.FlowElements, out junctionEIDs, out edgeEIDs);
                    break;

                case TraceSolverType.FindFlowElements:
                    traceFlowSolver.FindFlowElements(this.FlowMethod, this.FlowElements, out junctionEIDs, out edgeEIDs);
                    break;

                case TraceSolverType.FindFlowEndElements:
                    traceFlowSolver.FindFlowEndElements(this.FlowMethod, this.FlowElements, out junctionEIDs, out edgeEIDs);
                    break;

                case TraceSolverType.FindFlowUnreachedElements:
                    traceFlowSolver.FindFlowUnreachedElements(this.FlowMethod, this.FlowElements, out junctionEIDs, out edgeEIDs);
                    break;

                case TraceSolverType.FindPath:
                    count = Math.Max(this.junctionFlags.Length, this.edgeFlags.Length);
                    if (count < 2)
                    {
                        throw new GeometricNetworkException("Edge or junction found < 2!");
                    }

                    --count;
                    segmentCosts = new object[count];
                    traceFlowSolver.FindPath(this.FlowMethod, this.ShortestPathObjFn, out junctionEIDs, out edgeEIDs, count, ref segmentCosts);
                    objectJson.AddArray("segmentCosts", segmentCosts);
                    break;

                case TraceSolverType.FindSource:
                    count        = this.junctionFlags.Length + this.edgeFlags.Length;
                    segmentCosts = new object[count];
                    traceFlowSolver.FindSource(this.FlowMethod, this.ShortestPathObjFn, out junctionEIDs, out edgeEIDs, count, ref segmentCosts);
                    objectJson.AddArray("segmentCosts", segmentCosts);
                    break;

                case TraceSolverType.FindLongest:
                    // get end junctions in upstream
                    IEnumNetEID junctionEIDsFindLongest = null;
                    IEnumNetEID edgeEIDsFindLongest     = null;
                    traceFlowSolver.FindFlowEndElements(esriFlowMethod.esriFMUpstream, esriFlowElements.esriFEJunctions, out junctionEIDsFindLongest, out edgeEIDsFindLongest);

                    int?   eidLongest       = null;
                    double eidLongestLenght = double.MinValue;

                    if (junctionEIDsFindLongest.Count > 0)
                    {
                        double eidLongestLenghtCurrent = double.NaN;
                        for (int i = 0; i < junctionEIDsFindLongest.Count; i++)
                        {
                            int         netEIDCurrent       = junctionEIDsFindLongest.Next();
                            object[]    segmentLenghts      = new object[1];
                            IEnumNetEID junctionEIDsLongest = null;
                            IEnumNetEID edgeEIDsLongest     = null;

                            INetFlag     netFlag = new JunctionFlagClass();
                            INetElements netElements = this.geometricNetwork.Network as INetElements;
                            int          featureClassID, featureID, subID;
                            netElements.QueryIDs(netEIDCurrent, esriElementType.esriETJunction, out featureClassID, out featureID, out subID);

                            netFlag.UserClassID = featureClassID;
                            netFlag.UserID      = featureID;
                            netFlag.UserSubID   = subID;

                            IJunctionFlag[] junctionFlags = new IJunctionFlag[] { this.junctionFlags[0], netFlag as IJunctionFlag };
                            traceFlowSolver.PutJunctionOrigins(ref junctionFlags);

                            traceFlowSolver.FindPath(esriFlowMethod.esriFMUpstream, esriShortestPathObjFn.esriSPObjFnMinMax, out junctionEIDsLongest, out edgeEIDsLongest, 1, ref segmentLenghts);
                            if (segmentLenghts[0] != null)
                            {
                                eidLongestLenghtCurrent = Convert.ToDouble(segmentLenghts[0]);
                                if (eidLongestLenghtCurrent > eidLongestLenght)
                                {
                                    eidLongestLenght = eidLongestLenghtCurrent;
                                    eidLongest       = netEIDCurrent;
                                    edgeEIDs         = edgeEIDsLongest;
                                    junctionEIDs     = junctionEIDsLongest;
                                }
                            }
                        }
                    }
                    else
                    {
                        throw new GeometricNetworkException("Junction end not found!");
                    }

                    if (eidLongest.HasValue)
                    {
                        objectJson.AddDouble("totalCost", eidLongestLenght);
                    }
                    else
                    {
                        throw new GeometricNetworkException("EID longest not found!");
                    }

                    break;

                default:
                    throw new GeometricNetworkException("Trace solver type not found");
                }

                this.SetResults(ref objectJson, edgeEIDs, junctionEIDs);
                objectJson.AddArray("flagsNotFound", Helper.GetListJsonObjects(this.flagNotFound));
                objectJson.AddArray("barriersNotFound", Helper.GetListJsonObjects(this.barrierNotFound));
                return(objectJson);
            }
            catch (Exception e)
            {
                return((new ObjectError(e.Message)).ToJsonObject());
            }
        }
        private byte[] QueryPoint(ESRI.ArcGIS.Geometry.IPoint location, double distance)
        {
            if (distance <= 0.0)
                throw new ArgumentOutOfRangeException("distance");
            // Buffer the point.
            ITopologicalOperator topologicalOperator = (ESRI.ArcGIS.Geometry.ITopologicalOperator)location;
            IGeometry queryGeometry = topologicalOperator.Buffer(distance);
            // Query the feature class.
            ISpatialFilter spatialFilter = new ESRI.ArcGIS.Geodatabase.SpatialFilter();
            spatialFilter.Geometry = queryGeometry;
            spatialFilter.SpatialRel = ESRI.ArcGIS.Geodatabase.esriSpatialRelEnum.esriSpatialRelIntersects;
            spatialFilter.GeometryField = m_fcToQuery.ShapeFieldName;
            IFeatureCursor resultsFeatureCursor = m_fcToQuery.Search(spatialFilter, true);
            // Loop through the features, clip each geometry to the buffer
            // and total areas by attribute value.
            topologicalOperator = (ESRI.ArcGIS.Geometry.ITopologicalOperator)queryGeometry;
            int classFieldIndex = m_fcToQuery.FindField(m_mapFieldToQuery);
            // System.Collections.Specialized.ListDictionary summaryStatsDictionary = new System.Collections.Specialized.ListDictionary();
            Dictionary<string, double> summaryStatsDictionary = new Dictionary<string, double>();
            // Initialize a list to hold JSON geometries.
            List<JsonObject> jsonGeometries = new List<JsonObject>();

            IFeature resultsFeature = null;
            while ((resultsFeature = resultsFeatureCursor.NextFeature()) != null)
            {
                // Clip the geometry.
                IPolygon clippedResultsGeometry = (IPolygon)topologicalOperator.Intersect(resultsFeature.Shape,
                    ESRI.ArcGIS.Geometry.esriGeometryDimension.esriGeometry2Dimension);
                clippedResultsGeometry.Densify(0, 0); // Densify to maintain curved appearance when converted to JSON. 
                // Convert the geometry to JSON and add it to the list.
                JsonObject jsonClippedResultsGeometry = Conversion.ToJsonObject(clippedResultsGeometry);
                jsonGeometries.Add(jsonClippedResultsGeometry);
                // Get statistics.
                IArea area = (IArea)clippedResultsGeometry;
                string resultsClass = resultsFeature.get_Value(classFieldIndex) as string;
                // If the class is already in the dictionary, add the current feature's area to the existing entry.
                if (summaryStatsDictionary.ContainsKey(resultsClass))
                    summaryStatsDictionary[resultsClass] = (double)summaryStatsDictionary[resultsClass] + area.Area;
                else
                    summaryStatsDictionary[resultsClass] = area.Area;
            }
            // Use a helper method to get a JSON array of area records.
            JsonObject[] areaResultJson = CreateJsonRecords(summaryStatsDictionary) as JsonObject[];
            // Create a JSON object of the geometry results and the area records.
            JsonObject resultJsonObject = new JsonObject();
            resultJsonObject.AddArray("geometries", jsonGeometries.ToArray());
            resultJsonObject.AddArray("records", areaResultJson);
            // Get byte array of json and return results.
            byte[] result = Encoding.UTF8.GetBytes(resultJsonObject.ToJson());
            return result;
        }
Exemplo n.º 30
0
        /// <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());
            }
        }
Exemplo n.º 31
0
        private byte[] RootResHandler(NameValueCollection boundVariables, string outputFormat, string requestProperties, out string responseProperties)
        {
            responseProperties = null;

            IServerEnvironment3 senv = GetServerEnvironment() as IServerEnvironment3;

            JsonObject result = new JsonObject();

            JsonObject suinfoj = new JsonObject();

            //get user info and serialize into JSON
            IServerUserInfo suinfo = senv.UserInfo;
            if (null != suinfo)
            {
                suinfoj.AddString("currentUser", suinfo.Name);
                IEnumBSTR roles = suinfo.Roles;
                List<string> rolelist = new List<string>();
                if (null != roles)
                {
                    string role = roles.Next();
                    while (!string.IsNullOrEmpty(role))
                    {
                        rolelist.Add(role);
                        role = roles.Next();
                    }
                }

                suinfoj.AddArray("roles", rolelist.ToArray());
                result.AddJsonObject("serverUserInfo", suinfoj);
            }
            else
            {
                result.AddJsonObject("serverUserInfo", null);
            }

            return Encoding.UTF8.GetBytes(result.ToJson());
        }
        private byte[] AnalGeomBufferHandler(NameValueCollection boundVariables,
                                             JsonObject operationInput,
                                             string outputFormat,
                                             string requestProperties,
                                             out string responseProperties)
        {
            responseProperties = null;

            long?paramOID;
            bool found = operationInput.TryGetAsLong("OBJECTID", out paramOID);

            if (!found || !paramOID.HasValue)
            {
                throw new ArgumentNullException("OBJECTID invalido!");
            }

            long?paramBuffer1;

            found = operationInput.TryGetAsLong("bufferCerchio1", out paramBuffer1);
            if (!found || !paramBuffer1.HasValue)
            {
                throw new ArgumentNullException("Valore Buffer1 invalido!!");
            }

            long?paramBuffer2;

            found = operationInput.TryGetAsLong("bufferCerchio2", out paramBuffer2);
            if (!found || !paramBuffer2.HasValue)
            {
                throw new ArgumentNullException("Valore Buffer2 invalido!!");
            }

            long?paramBuffer3;

            found = operationInput.TryGetAsLong("bufferCerchio3", out paramBuffer3);
            if (!found || !paramBuffer3.HasValue)
            {
                throw new ArgumentNullException("Valore Buffer3 invalido!!");
            }

            this.RicavaInfoFc();

            IFeature feature = null;

            this.RicavaFeatureFiliare(paramOID.Value, out feature);

            Dictionary <long, IPolygon> dizGeometrieBuffer =
                this.CostruisciBuffer(feature, paramBuffer1.Value, paramBuffer2.Value, paramBuffer3.Value);

            List <IRecordSet2> listaRecordSet =
                this.AnalisiSpazialiBufferOper(dizGeometrieBuffer);

            JsonObject result = new JsonObject();

            result.AddJsonObject("interno",
                                 new JsonObject(Encoding.UTF8.GetString(Conversion.ToJson(listaRecordSet[0]))));
            result.AddJsonObject("centrale",
                                 new JsonObject(Encoding.UTF8.GetString(Conversion.ToJson(listaRecordSet[1]))));

            result.AddJsonObject("superiore",
                                 new JsonObject(Encoding.UTF8.GetString(Conversion.ToJson(listaRecordSet[2]))));

            #region Mi occupo di tirare fuori le Geometrie dei Buffer circolari e serializzarle
            List <IGeometry> listaGeometrie = new List <IGeometry>();
            foreach (KeyValuePair <long, IPolygon> coppia in dizGeometrieBuffer)
            {
                // ATTENZIONE!!!

                // GLI ARCOBJECTS (METODO CONVERSION - SOE_SUPPORT) NON GESTISCE L'INSERIMENTO DI CURVE NEL JSON.
                // UNA TRUE CURVE DEVE ESSERE SEMPLIFICATA - DENSIFICATA COME UN INSIEME DI SEGMENTI (es: shapefile)
                // PRIMA DI ESSERE RESTITUITA AL CLIENT!!

                IPolycurve polycurve = coppia.Value as IPolycurve;
                polycurve.Densify(5, 0);

                IGeometry geo = polycurve as IGeometry;
                geo.SpatialReference = ((IGeoDataset)fcClienti).SpatialReference;

                listaGeometrie.Add(geo);
            }

            object[] objArray = Helper.GetListJsonObjects(listaGeometrie);
            #endregion

            result.AddArray("geomBuffer", objArray);

            return(Encoding.UTF8.GetBytes(result.ToJson()));
        }
Exemplo n.º 33
0
        /// <summary>
        /// Build Meta Info
        /// </summary>
        private void BuildMeta()
        {
            IFeatureClass fc_poi = m_fcName.Open() as IFeatureClass;
            IGeoDataset   ds_poi = fc_poi as IGeoDataset;
            int           xmin   = (int)Math.Floor(ds_poi.Extent.XMin);
            int           ymin   = (int)Math.Floor(ds_poi.Extent.YMin);
            int           xmax   = (int)Math.Ceiling(ds_poi.Extent.XMax);
            int           ymax   = (int)Math.Ceiling(ds_poi.Extent.YMax);
            int           size   = int.Parse(this.tbxSize.Text);
            int           step   = (int)Math.Ceiling((xmax - xmin) * 1.0 / size);
            string        ns     = "poi:" + this.tbxCacheName.Text + ":";

            IDatabase client = m_redis.GetDatabase();

            client.StringSet(ns + "size", size.ToString());
            client.StringSet(ns + "xmin", xmin.ToString());
            client.StringSet(ns + "ymin", ymin.ToString());
            client.StringSet(ns + "xmax", xmax.ToString());
            client.StringSet(ns + "ymax", ymax.ToString());
            client.StringSet(ns + "step", step.ToString());


            JsonObject response = new JsonObject();

            List <JsonObject> ls_fields_cache = new List <JsonObject>();

            for (int i = 0; i < fc_poi.Fields.FieldCount; i++)
            {
                IField     field = fc_poi.Fields.get_Field(i);
                JsonObject js_f  = new JsonObject();
                js_f.AddString("name", field.Name);
                js_f.AddString("type", Enum.GetName(typeof(esriFieldType), field.Type));
                js_f.AddString("alias", field.AliasName);
                if (field.Type == esriFieldType.esriFieldTypeString)
                {
                    js_f.AddString("length", field.Length.ToString());
                }
                else
                {
                    js_f.AddString("length", "");
                }
                ls_fields_cache.Add(js_f);
            }
            response.AddArray("fields", ls_fields_cache.ToArray());
            if (fc_poi.ShapeType == esriGeometryType.esriGeometryPoint)
            {
                response.AddString("geometryType", "esriGeometryPoint");
            }
            else if (fc_poi.ShapeType == esriGeometryType.esriGeometryPolyline)
            {
                response.AddString("geometryType", "esriGeometryPolyline");
            }
            else if (fc_poi.ShapeType == esriGeometryType.esriGeometryPolygon)
            {
                response.AddString("geometryType", "esriGeometryPolygon");
            }
            IGeoDataset gds_poi = fc_poi as IGeoDataset;
            JsonObject  js_sr   = new JsonObject();

            js_sr.AddLong("wkid", gds_poi.SpatialReference.FactoryCode);
            response.AddJsonObject("spatialReference", js_sr);

            client.StringSet(ns + "response", response.ToJson());

            client.SetAdd("poi:caches", this.tbxCacheName.Text);
        }
Exemplo n.º 34
0
        /*
         *该函数用来实现对影像服务中的影像进行统计,统计各波段值中的最大最小值
         *
         *
         */
        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());
        }
Exemplo n.º 35
0
        /// <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>
        /// Returns a JSON serialized array listing all of the feature layers in the map service, converted to a byte array.
        /// </summary>
        /// <param name="boundVariables">Not used by this method, but required for method signature..</param>
        /// <param name="outputFormat">The only supported format is "json".</param>
        /// <param name="requestProperties">Not used by this method, but required for method signature.</param>
        /// <param name="responseProperties">Not used by this method, but required for method signature</param>
        /// <returns></returns>
        private byte[] GetIdsOfLayersThatHaveMetadata(NameValueCollection boundVariables,
			string outputFormat,
			string requestProperties,
			out string responseProperties)
        {
            responseProperties = null;
            var idArray = GetIdsOfLayersThatHaveMetadata();
            JsonObject output = new JsonObject();
            output.AddArray("layerIds", idArray.Select(i => i as object).ToArray());
            return Encoding.UTF8.GetBytes(output.ToJson());
        }
        private byte[] OperazioneRestDownloadFeatureHandler(NameValueCollection boundVariables,
                                                            JsonObject operationInput,
                                                            string outputFormat,
                                                            string requestProperties,
                                                            out string responseProperties)
        {
            responseProperties = null;

            #region Istanzio il JSON Result
            JsonObject result = new JsonObject();
            result.AddBoolean("hasError", false);
            #endregion

            bool found = operationInput.TryGetArray("listaOID", out object[] paramListaOID);
            if (!found || paramListaOID == null)
            {
                throw new ArgumentNullException("listaOID");
            }

            bool okParam2 = operationInput.TryGetString("URLServiceLayer", out string paramURL);
            if (!okParam2 || paramURL == String.Empty)
            {
                throw new ArgumentNullException("URLServiceLayer");
            }

            IGeoProcessor2 gp = new GeoProcessor() as IGeoProcessor2;
            gp.OverwriteOutput = true;

            try
            {
                result.AddArray("interno", paramListaOID);

                // Ricavo Feature Class dietro al Service Layer
                IFeatureClass featureClass = MapServiceHelper_GiancaGIS.RicavaFCDaURLServiceLayer(this.serverObjectHelper, paramURL);

                IFeatureLayer fLayer = new FeatureLayerClass
                {
                    FeatureClass     = featureClass,
                    Name             = "Mio Layer",
                    SpatialReference = ((IGeoDataset)featureClass).SpatialReference
                };

                IFeatureSelection featureSelection = fLayer as IFeatureSelection;


                IQueryFilter2 queryFilter = new QueryFilterClass
                {
                    WhereClause = "OBJECTID IN (" + String.Join(",", paramListaOID) + ")"
                };

                featureSelection.SelectFeatures(queryFilter, esriSelectionResultEnum.esriSelectionResultNew, false);


                this.CreaWorkSpaceOutput(out IWorkspaceName WorkspaceNameOUT, out string pathFGDB);

                IVariantArray parameters = new VarArrayClass();
                parameters.Add(fLayer);
                parameters.Add(System.IO.Path.Combine(pathFGDB, "output"));

                gp.Execute("CopyFeatures_management", parameters, null);

                this.ZippaFGDB(System.IO.Path.GetDirectoryName(pathFGDB), out string pathZip);
                result.AddString("zip", pathZip);
            }
            catch (Exception errore)
            {
                object severity = null;
                string errGp    = gp.GetMessages(ref severity);
                if (!string.IsNullOrEmpty(errGp))
                {
                    result.AddBoolean("GeoProcessingError", true);
                    result.AddString("erroreGp", errGp);
                }

                result.AddString("errorDescription", errore.Message);
                result.AddBoolean("hasError", true);
            }

            return(Encoding.UTF8.GetBytes(result.ToJson()));
        }