/// <summary>
        /// Compare source and target features
        /// </summary>
        /// <param name="sFeatures">Source features</param>
        /// <param name="tFeatures">Target features</param>
        /// <returns>True if the features match, false otherwise</returns>
        public static bool ValidateFeatures(FeatureCollection sFeatures, FeatureCollection tFeatures)
        {
            int sCount = 0;
            int tCount = 0;

            foreach (Feature sFeature in sFeatures)
            {
                sCount++;
                Guid sID = sFeature.Id;

                Feature tFeature = tFeatures.Where(ft => ft.Id == sID).FirstOrDefault();
                
                // Feature activation: do we see the target feature with the correct id?
                // Feature deactivation: we shouldn't see the target feature anymore when we choose to deactivate
                if ((tFeature != null && sID == tFeature.Id) || (sFeature.Deactivate && tFeature == null))
                {
                    tCount++;
                }
            }

            if (sCount != tCount)
            {
                return false;
            }

            return true;
        }
        private async void OpenFeaturesFromArcGISOnline(string itemId)
        {
            try
            {
                // Open a portal item containing a feature collection
                ArcGISPortal portal = await ArcGISPortal.CreateAsync();
                PortalItem collectionItem = await PortalItem.CreateAsync(portal, itemId);

                // Verify that the item is a feature collection
                if (collectionItem.Type == PortalItemType.FeatureCollection)
                {
                    // Create a new FeatureCollection from the item
                    FeatureCollection featCollection = new FeatureCollection(collectionItem);

                    // Create a layer to display the collection and add it to the map as an operational layer
                    FeatureCollectionLayer featCollectionLayer = new FeatureCollectionLayer(featCollection);
                    featCollectionLayer.Name = collectionItem.Title;
                    MyMapView.Map.OperationalLayers.Add(featCollectionLayer);
                }
                else
                {
                    MessageBox.Show("Portal item with ID '" + itemId + "' is not a feature collection.", "Feature Collection");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Unable to open item with ID '" + itemId + "': " + ex.Message, "Error");
            }
        }        
Ejemplo n.º 3
0
 private Task HandleRequest(IDictionary<string, object> env)
 {
     var ofc = new FeatureCollection(new OwinFeatureCollection(env));
     var t = _callback.Invoke(ofc);
     return t;
     //return TaskHelpers.Await(t, () => {Console.WriteLine("done");}, (ex) => {Console.WriteLine("failed with " + ex.ToString());});
 }
Ejemplo n.º 4
0
 private void clusterThread_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
 {
     if ((!e.Cancelled) && (e.Result != null))
     {
         Dictionary<int, Cluster> result = e.Result as Dictionary<int, Cluster>;
         if (result != null)
         {
             FeatureCollection clusters = new FeatureCollection();
             int num = 0;
             foreach (int num2 in result.Keys)
             {
                 if (result.ContainsKey(num2))
                     num = Math.Max(result[num2].Count, num);
             }
             foreach (int num3 in result.Keys)
             {
                 if (result.ContainsKey(num3) && result[num3].Features.Count == 1)
                 {
                     clusters.Add(result[num3].Features[0]);
                 }
                 else if (result.ContainsKey(num3))
                 {
                     Feature item = this.OnCreateFeature(result[num3].Features, new GeoPoint(result[num3].X, result[num3].Y), num);
                     item.DisableToolTip = true;
                     item.SetValue(Clusterer.ClusterProperty, result[num3].Features);
                     clusters.Add(item);
                 }
             }
             base.OnClusteringCompleted(clusters);
         }
     }
 }
        protected override Feature OnCreateFeature(FeatureCollection cluster, GeoPoint center, int maxClusterCount)
        {
            double sum = 0;
            Feature feature = null;
            foreach (Feature item in cluster)
            {
                if (item.Attributes.ContainsKey(AggregateColumn))
                {
                    sum += Convert.ToDouble(item.Attributes[AggregateColumn]);
                }
            }
            double size = (sum + 450) / 30;
            size = Math.Log(sum * StyleScale / 10) * 10 + 20;
            if (size < 12)
            {
                size = 12;
            }
            CustomClusterStyle s = new CustomClusterStyle();
            feature = new Feature() { Style = new CustomClusterStyle() { Size = size }, Geometry = center };
            feature.Attributes.Add("Color", InterPlateColor(size - 12, 100));
            feature.Attributes.Add("Size", size);
            feature.Attributes.Add("Count", cluster.Count);

            return feature;
        }
Ejemplo n.º 6
0
 public IServer CreateServer(IConfiguration configuration)
 {
     var information = new KestrelServerInformation(configuration);
     var serverFeatures = new FeatureCollection();
     serverFeatures.Set<IKestrelServerInformation>(information);
     serverFeatures.Set<IServerAddressesFeature>(information);
     return new KestrelServer(serverFeatures, _appLifetime, _loggerFactory.CreateLogger("Microsoft.AspNet.Server.Kestrel"));
 }
Ejemplo n.º 7
0
 public IServer CreateServer(IConfiguration configuration)
 {
     var information = new ServerInformation(configuration);
     var serverFeatures = new FeatureCollection();
     serverFeatures.Set<IServerInformation>(information);
     serverFeatures.Set<IServerAddressesFeature>(information);
     return new Server(serverFeatures, _appLifetime, _loggerFactory.CreateLogger(Server.ConfigServerAssembly));
 }
 public MainViewModel(IEnumerable<IFeature> features)
 {
     this.features = new FeatureCollection(features);
     this.featuresView = CollectionViewSource.GetDefaultView(this.features);
     this.featuresView.GroupDescriptions.Add(new PropertyGroupDescription(nameof(IFeature.GroupName)));
     this.featuresView.SortDescriptions.Add(new SortDescription(nameof(IFeature.Order), ListSortDirection.Ascending));
     this.addOrRemoveFeaturesCommand = new AsyncDelegateCommand(this.AddOrRemoveFeatures);
 } 
Ejemplo n.º 9
0
 static IFeatureCollection NewFeatureCollection()
 {
     var stub = new StubFeatures();
     var features = new FeatureCollection();
     features[typeof(IHttpRequestFeature)] = stub;
     features[typeof(IHttpResponseFeature)] = stub;
     return features;
 }
 public EditFeatures()
 {
     InitializeComponent();
     drawLayer = MyMap.Layers["DrawLayer"] as FeaturesLayer;
     tempLayer = MyMap.Layers["TempLayer"] as FeaturesLayer;
     layer = MyMap.Layers["MyLayer"] as TiledDynamicRESTLayer;
     features = new FeatureCollection();
     featureIDs = new List<int>();
 }
 public static void Initialize(FeatureCollection featureList, IUserListReader userListReader)
 {
     FeatureToggles = new List<BasicToggleType>();
     foreach (FeatureElement feature in featureList)
     {
         var toggleType = CreateToggleType(feature, userListReader);
         FeatureToggles.Add(toggleType);
     }
 }
        public void IndexerAlsoAddsItems()
        {
            var interfaces = new FeatureCollection();
            var thing = new Thing();

            interfaces[typeof(IThing)] = thing;

            Assert.Equal(interfaces[typeof(IThing)], thing);
        }
        public void SecondCallToAddThrowsException()
        {
            var interfaces = new FeatureCollection();
            var thing = new Thing();

            interfaces.Add(typeof(IThing), thing);

            Assert.Throws<ArgumentException>(() => interfaces.Add(typeof(IThing), thing));
        }
Ejemplo n.º 14
0
 public IFeatureCollection Initialize(IConfiguration configuration)
 {
     var information = new KestrelServerInformation();
     information.Initialize(configuration);
     var serverFeatures = new FeatureCollection();
     serverFeatures.Set<IKestrelServerInformation>(information);
     serverFeatures.Set<IServerAddressesFeature>(information);
     return serverFeatures;
 }
        /// <summary>
        /// Gets a stream for a given feature collection.
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        private static Action<Stream> GetGeoJsonContents(FeatureCollection model)
        {
            return stream =>
            {
                var geoJson = OsmSharp.Geo.Streams.GeoJson.GeoJsonConverter.ToGeoJson(model as FeatureCollection);

                var geoJsonBytes = System.Text.Encoding.UTF8.GetBytes(geoJson);
                stream.Write(geoJsonBytes, 0, geoJsonBytes.Length);
            };
        }
        public void AddedInterfaceIsReturned()
        {
            var interfaces = new FeatureCollection();
            var thing = new Thing();

            interfaces[typeof(IThing)] = thing;

            object thing2 = interfaces[typeof(IThing)];
            Assert.Equal(thing2, thing);
        }
        public IFeatureCollection Initialize(IConfiguration configuration)
        {
            var builder = ServerBuilder.New()
                        .SetAddress(IPAddress.Any)
                        .SetPort(5000)
                        .SetOwinApp(HandleRequest);

            var serverFeatures = new FeatureCollection();
            serverFeatures.Set<INowinServerInformation>(new NowinServerInformation(builder));
            return serverFeatures;
        }
Ejemplo n.º 18
0
        public IServer CreateServer(IConfiguration configuration)
        {
            var information = new RioSharpServerInformation();
            information.Initialize(configuration);

            var serverFeatures = new FeatureCollection();
            serverFeatures.Set<IRioSharpServerInformation>(information);
            serverFeatures.Set<IServerAddressesFeature>(information);

            return new RioSharpServer(serverFeatures, _appLifetime, _loggerFactory.CreateLogger("RioSharp.Aspnet"), _httpContextFactory);
        }
        public static void Initialize()
        {
            var featureCollection = new FeatureCollection();

            if (FeatureToggleSection.Config != null)
            {
                featureCollection = FeatureToggleSection.Config.FeatureList;
            }

            Initialize(featureCollection, new FileUserListReader());
        }
Ejemplo n.º 20
0
 public IFeatureCollection Initialize(IConfiguration configuration)
 {
     // TODO: Parse config
     var builder = ServerBuilder.New()
         .SetAddress(IPAddress.Any)
         .SetPort(configuration["port"] != null ? Int32.Parse(configuration["port"]) : 8080)
         .SetOwinApp(OwinWebSocketAcceptAdapter.AdaptWebSockets(HandleRequest));
     var serverFeatures = new FeatureCollection();
     serverFeatures.Set<NowinServerInformation>(new NowinServerInformation(builder));
     return serverFeatures;
 }
        public void SetNullValueRemoves()
        {
            var interfaces = new FeatureCollection();
            var thing = new Thing();

            interfaces.Add(typeof(IThing), thing);
            Assert.Equal(interfaces[typeof(IThing)], thing);

            interfaces[typeof(IThing)] = null;

            object thing2;
            Assert.False(interfaces.TryGetValue(typeof(IThing), out thing2));
        }
        public void SetNullValueRemoves()
        {
            var interfaces = new FeatureCollection();
            var thing = new Thing();

            interfaces[typeof(IThing)] = thing;
            Assert.Equal(interfaces[typeof(IThing)], thing);

            interfaces[typeof(IThing)] = null;

            object thing2 = interfaces[typeof(IThing)];
            Assert.Null(thing2);
        }
        public void AddedInterfaceIsReturned()
        {
            var interfaces = new FeatureCollection();
            var thing = new Thing();

            interfaces.Add(typeof(IThing), thing);

            Assert.Equal(interfaces[typeof(IThing)], thing);

            object thing2;
            Assert.True(interfaces.TryGetValue(typeof(IThing), out thing2));
            Assert.Equal(thing2, thing);
        }
        public void IndexerAlsoAddsItems()
        {
            var interfaces = new FeatureCollection();
            var thing = new Thing();

            interfaces[typeof(IThing)] = thing;

            Assert.Equal(interfaces[typeof(IThing)], thing);

            object thing2;
            Assert.True(interfaces.TryGetValue(typeof(IThing), out thing2));
            Assert.Equal(thing2, thing);
        }
Ejemplo n.º 25
0
        public void EmptyKeysNotAddedToQueryCollection(string queryString)
        {
            var features = new FeatureCollection();
            var request = new HttpRequestFeature();
            request.QueryString = queryString;
            features[typeof(IHttpRequestFeature)] = request;

            var provider = new QueryFeature(features);

            var queryCollection = provider.Query;

            Assert.Equal(0, queryCollection.Count);
        }
        private static KestrelServer CreateServer(Func<IConfiguration, IKestrelServerInformation> serverInformationFactory)
        {
            var configuration = new ConfigurationBuilder().Build();
            var information = serverInformationFactory(configuration);

            var features = new FeatureCollection();
            features.Set(information);

            var lifetime = new LifetimeNotImplemented();
            var logger = new TestKestrelTrace.TestLogger();

            return new KestrelServer(features, lifetime, logger);
        }
Ejemplo n.º 27
0
        public void KmlReadGeometryv2_0()
        {
            // initialize the geometry source.
            var kmlSource = new KmlFeatureStreamSource(
                Assembly.GetExecutingAssembly().GetManifestResourceStream("OsmSharp.Test.data.test.v2.0.kml"));

            // pull all the objects from the stream into the given collection.
            var kmlCollection = new FeatureCollection(kmlSource);
            var features = new List<Feature>(kmlCollection);

            // test collection contents.
            Assert.AreEqual(1, features.Count);
            Assert.IsInstanceOf(typeof(Point), features[0].Geometry);
        }
Ejemplo n.º 28
0
        public void KeyWithoutValuesAddedToQueryCollection(string queryString, string emptyParam)
        {
            var features = new FeatureCollection();
            var request = new HttpRequestFeature();
            request.QueryString = queryString;
            features[typeof(IHttpRequestFeature)] = request;

            var provider = new QueryFeature(features);

            var queryCollection = provider.Query;

            Assert.True(queryCollection.Keys.Contains(emptyParam));
            Assert.Equal(string.Empty, queryCollection[emptyParam]);
        }
Ejemplo n.º 29
0
        public void GpxReadGeometryv1_0()
        {
            // initialize the geometry source.
            var gpxSource = new GpxFeatureStreamSource(
                Assembly.GetExecutingAssembly().GetManifestResourceStream("OsmSharp.Test.data.test.v1.0.gpx"),
                false);

            // pull all the objects from the stream into the given collection.
            var gpxCollection = new FeatureCollection(gpxSource);
            var features = new List<Feature>(gpxCollection);

            // test collection contents.
            Assert.AreEqual(1, features.Count);
            Assert.IsInstanceOf(typeof(LineString), features[0].Geometry);
            Assert.AreEqual(424, (features[0].Geometry as LineString).Coordinates.Count);
        }
Ejemplo n.º 30
0
        public void QueryReturnsParsedQueryCollection()
        {
            // Arrange
            var features = new FeatureCollection();
            var request = new HttpRequestFeature();
            request.QueryString = "foo=bar";
            features[typeof(IHttpRequestFeature)] = request;

            var provider = new QueryFeature(features);

            // Act
            var queryCollection = provider.Query;

            // Assert
            Assert.Equal("bar", queryCollection["foo"]);
        }
Ejemplo n.º 31
0
        void HandleStyleLoaded(MapStyle obj)
        {
            IconImageSource iconImageSource = (ImageSource)"red_marker.png";

            map.Functions.AddStyleImage(iconImageSource);

            var symbolLayerIconFeatureList = new List <Feature>();

            symbolLayerIconFeatureList.Add(
                new Feature(new GeoJSON.Net.Geometry.Point(
                                new GeoJSON.Net.Geometry.Position(-33.213144, -57.225365))));
            symbolLayerIconFeatureList.Add(
                new Feature(new GeoJSON.Net.Geometry.Point(
                                new GeoJSON.Net.Geometry.Position(-33.981818, -54.14164))));
            symbolLayerIconFeatureList.Add(
                new Feature(new GeoJSON.Net.Geometry.Point(
                                new GeoJSON.Net.Geometry.Position(-30.583266, -56.990533))));

            var featureCollection = new FeatureCollection(symbolLayerIconFeatureList);

            var source = new GeoJsonSource
            {
                Id   = "feature.memory.src",
                Data = featureCollection
            };

            map.Functions.AddSource(source);

            var symbolLayer = new SymbolLayer("feature.symbol.layer", source.Id)
            {
                IconAllowOverlap = Expression.Literal(true),
                IconImage        = Expression.Literal(iconImageSource.Id),
                IconOffset       = Expression.Literal(new[] { 0.0, -9.0 })
            };

            map.Functions.AddLayer(symbolLayer);
        }
Ejemplo n.º 32
0
        public IActionResult OnGetAirports()
        {
            var configuration = new Configuration
            {
                BadDataFound = context => { Console.WriteLine($"Bad data: <{context.RawRecord}>"); }
            };

            using (var sr = new StreamReader(Path.Combine(_hostingEnvironment.WebRootPath, "airports.dat")))
                using (var reader = new CsvReader(sr, configuration))
                {
                    FeatureCollection featureCollection = new FeatureCollection();

                    while (reader.Read())
                    {
                        try
                        {
                            string name      = reader.GetField <string>(1);
                            string iataCode  = reader.GetField <string>(4);
                            double latitude  = reader.GetField <double>(6);
                            double longitude = reader.GetField <double>(7);

                            featureCollection.Features.Add(new Feature(
                                                               new Point(new Position(latitude, longitude)),
                                                               new Dictionary <string, object>
                            {
                                { "name", name },
                                { "iataCode", iataCode }
                            }));
                        }
                        catch (BadDataException ex)
                        {
                            Console.WriteLine(ex.Message);
                        }
                    }
                    return(new JsonResult(featureCollection));
                }
        }
        // GET: Polygon
        public ActionResult Index()
        {
            var latStr = Request.QueryString["lat"];
            var lngStr = Request.QueryString["lng"];

            if (string.IsNullOrEmpty(latStr) || string.IsNullOrEmpty(lngStr) ||
                !double.TryParse(latStr, out double lat) || !double.TryParse(lngStr, out double lng))
            {
                return(null);
            }


            var index = ContentSearchManager.GetIndex("sc9xp0_spatial_master");

            using (var context = index.CreateSearchContext())
            {
                var queryable = context.GetQueryable <PolygonResultItem>().InsidePolygon(s => s.Polygon, new Coordinate(lat, lng));
                var list      = queryable.ToList();
                if (list.Any())
                {
                    var res       = list.First();
                    var multiPoly = JsonConvert.DeserializeObject <MultiPolygon>(res.PolygonResult);

                    var featureCol = new FeatureCollection();
                    var feature    = new Feature(multiPoly);
                    featureCol.Features.Add(feature);

                    var viewModel = new PolygonViewModel
                    {
                        PolygonsFeature = featureCol
                    };
                    return(this.View("~/Views/Polygon.cshtml", viewModel));
                }
            }

            return(null);
        }
        private async void OpenFeaturesFromArcGISOnline(string itemId)
        {
            try
            {
                // Open a portal item containing a feature collection
                var portal = await ArcGISPortal.CreateAsync();

                var collectionItem = await PortalItem.CreateAsync(portal, itemId);

                // Verify that the item is a feature collection
                if (collectionItem.Type == PortalItemType.FeatureCollection)
                {
                    // Create a new FeatureCollection from the item
                    var featureCollection = new FeatureCollection(collectionItem);

                    // Create a layer to display the collection and add it to the map as an operational layer
                    var featureCollectionLayer = new FeatureCollectionLayer(featureCollection);
                    featureCollectionLayer.Name = collectionItem.Title;

                    _myMapView.Map.OperationalLayers.Add(featureCollectionLayer);
                }
                else
                {
                    var alertBuilder = new AlertDialog.Builder(this);
                    alertBuilder.SetTitle("Feature Collection");
                    alertBuilder.SetMessage("Portal item with ID '" + itemId + "' is not a feature collection.");
                    alertBuilder.Show();
                }
            }
            catch (Exception ex)
            {
                var alertBuilder = new AlertDialog.Builder(this);
                alertBuilder.SetTitle("Error");
                alertBuilder.SetMessage("Unable to open item with ID '" + itemId + "': " + ex.Message);
                alertBuilder.Show();
            }
        }
Ejemplo n.º 35
0
        public static FeatureCollection GetFeaturesIn(this GeometricGraph graph, float minLatitude, float minLongitude, float maxLatitude, float maxLongitude)
        {
            FeatureCollection featureCollection = new FeatureCollection();
            HashSet <uint>    uintSet           = graph.Search(minLatitude, minLongitude, maxLatitude, maxLongitude);
            HashSet <long>    longSet           = new HashSet <long>();

            GeometricGraph.EdgeEnumerator edgeEnumerator = graph.GetEdgeEnumerator();
            foreach (uint vertex1 in uintSet)
            {
                GeoCoordinateSimple vertex2 = graph.GetVertex(vertex1);
                featureCollection.Add(new Feature((Geometry) new Point(new GeoCoordinate((double)vertex2.Latitude, (double)vertex2.Longitude)), (GeometryAttributeCollection) new SimpleGeometryAttributeCollection((IEnumerable <Tag>) new Tag[1]
                {
                    Tag.Create("id", vertex1.ToInvariantString())
                })));
                edgeEnumerator.MoveTo(vertex1);
                edgeEnumerator.Reset();
                while (edgeEnumerator.MoveNext())
                {
                    if (!longSet.Contains((long)edgeEnumerator.Id))
                    {
                        longSet.Add((long)edgeEnumerator.Id);
                        List <ICoordinate>   shape             = graph.GetShape(edgeEnumerator.Current);
                        List <GeoCoordinate> geoCoordinateList = new List <GeoCoordinate>();
                        foreach (ICoordinate coordinate in shape)
                        {
                            geoCoordinateList.Add(new GeoCoordinate((double)coordinate.Latitude, (double)coordinate.Longitude));
                        }
                        LineString lineString = new LineString((IEnumerable <GeoCoordinate>)geoCoordinateList);
                        featureCollection.Add(new Feature((Geometry)lineString, (GeometryAttributeCollection) new SimpleGeometryAttributeCollection((IEnumerable <Tag>) new Tag[1]
                        {
                            Tag.Create("id", edgeEnumerator.Id.ToInvariantString())
                        })));
                    }
                }
            }
            return(featureCollection);
        }
Ejemplo n.º 36
0
        public void Start <TContext>(IHttpApplication <TContext> application)
        {
            Func <IDictionary <string, object>, Task> appFunc = async env =>
            {
                FeatureCollection features = new FeatureCollection(new OwinFeatureCollection(env));

                TContext context = application.CreateContext(features);

                try
                {
                    await application.ProcessRequestAsync(context);
                }
                catch (Exception ex)
                {
                    application.DisposeContext(context, ex);
                    throw;
                }

                application.DisposeContext(context, null);
            };

            appFunc = OwinWebSocketAcceptAdapter.AdaptWebSockets(appFunc);

            Dictionary <string, object> props = new Dictionary <string, object>
            {
                ["host.Addresses"] =
                    Features.Get <IServerAddressesFeature>()
                    .Addresses.Select(add => new Uri(add))
                    .Select(add => new Address(add.Scheme, add.Host, add.Port.ToString(), add.LocalPath).Dictionary)
                    .ToList()
            };


            Suave.Owin.OwinServerFactory.Initialize(props);

            _suaveServer = Suave.Owin.OwinServerFactory.Create(appFunc, props);
        }
Ejemplo n.º 37
0
        private async void GetFeaturesFromQuery()
        {
            try
            {
                // Create a service feature table to get features from.
                ServiceFeatureTable featTable = new ServiceFeatureTable(new Uri(FeatureLayerUrl));

                // Create a query to get all features in the table.
                QueryParameters queryParams = new QueryParameters
                {
                    WhereClause = "1=1"
                };

                // Query the table to get all features.
                FeatureQueryResult featureResult = await featTable.QueryFeaturesAsync(queryParams);

                // Create a new feature collection table from the result features.
                FeatureCollectionTable collectTable = new FeatureCollectionTable(featureResult);

                // Create a feature collection and add the table.
                FeatureCollection featCollection = new FeatureCollection();
                featCollection.Tables.Add(collectTable);

                // Create a layer to display the feature collection, add it to the map's operational layers.
                FeatureCollectionLayer featureCollectionLayer = new FeatureCollectionLayer(featCollection);
                _myMapView.Map.OperationalLayers.Add(featureCollectionLayer);

                // Zoom to the extent of the feature collection layer.
                await featureCollectionLayer.LoadAsync();

                await _myMapView.SetViewpointGeometryAsync(featureCollectionLayer.FullExtent, 50);
            }
            catch (Exception e)
            {
                new UIAlertView("Error", e.ToString(), (IUIAlertViewDelegate)null, "OK", null).Show();
            }
        }
Ejemplo n.º 38
0
        public void SetGetText()
        {
            var map = new Map(new Size(100, 100));

            var feature1 = new SimpleFeature {
                Data = 1, Geometry = new Point(50, 50)
            };
            var feature2 = new SimpleFeature {
                Data = 5, Geometry = new Point(50, 55)
            };
            var featureCollection = new FeatureCollection {
                Features = { feature1, feature2 }
            };

            var callCount = 0;

            var labelLayer = new LabelLayer
            {
                Visible             = true,
                DataSource          = featureCollection,
                Map                 = map,
                LabelStringDelegate = delegate(IFeature feature)
                {
                    callCount++;

                    feature
                    .Should().Be.OfType <SimpleFeature>();

                    return(((SimpleFeature)feature).Data.ToString());
                }
            };

            labelLayer.Render();

            callCount
            .Should("labels of 2 simple feature rendered").Be.EqualTo(2);
        }
        public void TestWriteFeatureCollectionWithFirstFeatureGeometryNull()
        {
            // Setup
            var geoJsonWriter = new GeoJsonWriter();

            string featureJson =
                "{\"type\": \"Feature\",\"geometry\": {\"type\": \"LineString\",\"coordinates\": [[0,0],[2,2],[3,2]]},\"properties\": {\"key\": \"value\"}}";
            var notNullGeometryFeature = new GeoJsonReader().Read <Feature>(featureJson);

            var attributesTable = new AttributesTable {
                { "key", "value" }
            };
            IGeometry geometry            = null;
            var       nullGeometryFeature = new Feature(geometry, attributesTable);

            var features_notNullFirst = new Collection <IFeature>
            {
                notNullGeometryFeature,
                nullGeometryFeature
            };

            var features_nullFirst = new Collection <IFeature>
            {
                nullGeometryFeature,
                notNullGeometryFeature
            };

            var featureCollection_notNullFirst = new FeatureCollection(features_notNullFirst);
            var featureCollection_nullFirst    = new FeatureCollection(features_nullFirst);

            // Act
            TestDelegate write_notNullFirst = () => geoJsonWriter.Write(featureCollection_notNullFirst);
            TestDelegate write_nullFirst    = () => geoJsonWriter.Write(featureCollection_nullFirst);

            Assert.That(write_notNullFirst, Throws.Nothing);
            Assert.That(write_nullFirst, Throws.Nothing);
        }
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            if (writer == null)
            {
                throw new ArgumentNullException("writer");
            }
            if (serializer == null)
            {
                throw new ArgumentNullException("serializer");
            }

            FeatureCollection coll = value as FeatureCollection;

            if (coll == null)
            {
                return;
            }

            writer.WriteStartObject();
            writer.WritePropertyName("type");
            writer.WriteValue(coll.Type);
            writer.WritePropertyName("features");
            serializer.Serialize(writer, coll.Features);
            if (coll.CRS != null)
            {
                writer.WritePropertyName("crs");
                serializer.Serialize(writer, coll.CRS);
            }
            var bbox = coll.BoundingBox;

            if (bbox != null)
            {
                writer.WritePropertyName("bbox");
                serializer.Serialize(writer, new[] { bbox.MinX, bbox.MinY, bbox.MaxX, bbox.MaxY }, typeof(double[]));
            }
            writer.WriteEndObject();
        }
        public async Task RunAsync(RequestDelegate handler)
        {
            Array.ForEach(_urls, url => _httpListener.Prefixes.Add(url));
            if (!_httpListener.IsListening)
            {
                // 启动HttpListener
                _httpListener.Start();
            }
            Console.WriteLine("[Info]: Server started and is listening on: {0}", string.Join(";", _urls));

            while (true)
            {
                // 等待传入的请求,该方法将阻塞进程(这里使用了await),直到收到请求
                var listenerContext = await _httpListener.GetContextAsync();

                // 打印状态行: 请求方法, URL, 协议版本
                Console.WriteLine("{0} {1} HTTP/{2}",
                                  listenerContext.Request.HttpMethod,
                                  listenerContext.Request.RawUrl,
                                  listenerContext.Request.ProtocolVersion);
                // 获取抽象封装后的HttpListenerFeature
                var feature = new HttpListenerFeature(listenerContext);
                // 获取封装后的Feature集合
                var features = new FeatureCollection()
                               .Set <IHttpRequestFeature>(feature)
                               .Set <IHttpResponseFeature>(feature);
                // 创建HttpContext
                var httpContext = new HttpContext(features);
                Console.WriteLine("[Info]: Server process one HTTP request start.");
                // 开始依次执行中间件
                await handler(httpContext);

                Console.WriteLine("[Info]: Server process one HTTP request end.");
                // 关闭响应
                listenerContext.Response.Close();
            }
        }
Ejemplo n.º 42
0
    public void ReplacingResponseBody_DoesNotCreateOnCompletedRegistration()
    {
        var features = new FeatureCollection();

        var originalStream    = new FlushAsyncCheckStream();
        var replacementStream = new FlushAsyncCheckStream();

        var responseBodyMock = new Mock <IHttpResponseBodyFeature>();

        responseBodyMock.Setup(o => o.Stream).Returns(originalStream);
        features.Set(responseBodyMock.Object);

        var responseMock = new Mock <IHttpResponseFeature>();

        features.Set(responseMock.Object);

        var context = new DefaultHttpContext(features);

        Assert.Same(originalStream, context.Response.Body);
        Assert.Same(responseBodyMock.Object, context.Features.Get <IHttpResponseBodyFeature>());

        context.Response.Body = replacementStream;

        Assert.Same(replacementStream, context.Response.Body);
        Assert.NotSame(responseBodyMock.Object, context.Features.Get <IHttpResponseBodyFeature>());

        context.Response.Body = originalStream;

        Assert.Same(originalStream, context.Response.Body);
        Assert.Same(responseBodyMock.Object, context.Features.Get <IHttpResponseBodyFeature>());

        // The real issue was not that an OnCompleted registration existed, but that it would previously flush
        // the original response body in the OnCompleted callback after the response body was disposed.
        // However, since now there's no longer an OnCompleted registration at all, it's easier to verify that.
        // https://github.com/dotnet/aspnetcore/issues/25342
        responseMock.Verify(m => m.OnCompleted(It.IsAny <Func <object, Task> >(), It.IsAny <object>()), Times.Never);
    }
Ejemplo n.º 43
0
        public void geojson_feature_with_null_crs_should_be_serialized()
        {
            const string      json   = @"
{
	""type"" : ""FeatureCollection"",
	""totalFeatures"" : 5,
	""features"" : [{
			""type"" : ""Feature"",
			""geometry"" : null,
			""properties"" : {
				""kommunnamn"" : ""Karlskrona""
			}
		}
	],
	""crs"" : null
}
";
            GeoJsonReader     reader = new GeoJsonReader();
            FeatureCollection coll   = reader.Read <FeatureCollection>(json);

            Assert.That(coll, Is.Not.Null);
            Assert.That(coll.CRS, Is.Null);
            Assert.That(coll.Count, Is.EqualTo(1));
        }
Ejemplo n.º 44
0
        /// <summary>
        /// Checks if a feature is active
        /// </summary>
        /// <param name="web">Web to operate against</param>
        /// <param name="featureID">ID of the feature to check</param>
        /// <returns>True if active, false otherwise</returns>
        public static bool IsFeatureActive(this Web web, Guid featureID)
        {
            bool featureIsActive = false;

            FeatureCollection clientSiteFeatures = web.Features;

            web.Context.Load(clientSiteFeatures);
            web.Context.ExecuteQuery();
            Feature iprFeature = clientSiteFeatures.GetById(featureID);

            web.Context.Load(iprFeature);
            web.Context.ExecuteQuery();

            if (iprFeature != null && iprFeature.IsPropertyAvailable("DefinitionId") && iprFeature.DefinitionId.Equals(featureID))
            {
                featureIsActive = true;
            }
            else
            {
                featureIsActive = false;
            }

            return(featureIsActive);
        }
Ejemplo n.º 45
0
        public void QueryJSONTest()
        {
            var id       = "id";
            var point    = new Point(new GeographicPosition(30.0, 110.0));
            var feature  = new Feature(point);
            var features = new List <Feature>();

            features.Add(feature);
            var collection = new FeatureCollection(features);
            var array      = new FeatureCollection[] { collection };
            var expected   = JsonConvert.SerializeObject(array);

            var url     = String.Join("/", new string[] { urlPrefix, db1, "layers", id, "data" });
            var handler = new MockHttpHandler(url, "POST", (req, res, param) =>
            {
                var result     = new RestResult();
                result.Success = true;
                result.Count   = 1;
                result.Data    = JsonConvert.SerializeObject(array);
                return(JsonConvert.SerializeObject(result));
            });

            mockServer.AddRequestHandler(handler);

            try
            {
                var db     = new MapDB(db1);
                var filter = new QueryFilter();
                var actual = db.QueryJSON(filter, 0, 10, new string[] { id });
                Assert.AreEqual(expected, actual);
            }
            catch (Exception ex)
            {
                Assert.Fail(ex.Message);
            }
        }
Ejemplo n.º 46
0
        public void FilterFeaturesUsingTimeRange()
        {
            var features = new[]
            {
                new TimeDependentFeature {
                    Time = new DateTime(2000, 1, 1)
                },
                new TimeDependentFeature {
                    Time = new DateTime(2001, 1, 1)
                },
                new TimeDependentFeature {
                    Time = new DateTime(2002, 1, 1)
                }
            };

            var featureCollection = new FeatureCollection(features, typeof(TimeDependentFeature))
            {
                TimeSelectionStart = new DateTime(2001, 1, 1),
                TimeSelectionEnd   = new DateTime(2001, 2, 1)
            };

            featureCollection.Features.Count
            .Should().Be.EqualTo(1);
        }
Ejemplo n.º 47
0
        public IActionResult OnGetVMS()
        {
            {
                FeatureCollection featureCollection = new FeatureCollection();

                //-----Hardcoded name, long, lat for now --------
                for (int i = 0; i < 2; i++)
                {
                    string name      = "Board Name";
                    double longitude = 101.6986777;
                    double latitude  = 3.170816062;

                    featureCollection.Features.Add(new Feature(
                                                       new Point(new Position(longitude, latitude)),
                                                       new Dictionary <string, object>
                    {
                        { "name", name }
                    }));
                }

                JsonResult myjasonresult = new JsonResult(featureCollection);
                return(myjasonresult);
            }
        }
Ejemplo n.º 48
0
        // For testing
        internal KestrelServer(ITransportFactory transportFactory, ServiceContext serviceContext)
        {
            if (transportFactory == null)
            {
                throw new ArgumentNullException(nameof(transportFactory));
            }

            _transportFactory = transportFactory;
            ServiceContext    = serviceContext;

            var httpHeartbeatManager = new HttpHeartbeatManager(serviceContext.ConnectionManager);

            _heartbeat = new Heartbeat(
                new IHeartbeatHandler[] { serviceContext.DateHeaderValueManager, httpHeartbeatManager },
                serviceContext.SystemClock,
                DebuggerWrapper.Singleton,
                Trace);

            Features         = new FeatureCollection();
            _serverAddresses = new ServerAddressesFeature();
            Features.Set(_serverAddresses);

            HttpCharacters.Initialize();
        }
Ejemplo n.º 49
0
        public void ParsingCollectionWithBoundingBox()
        {
            /*
             * Parsing GeoJSON issue related to Bounding Box #178
             */

            var json = "{ \"type\": \"FeatureCollection\", " +
                       "\"features\": [{\"type\": \"Feature\",\"properties\": {},\"geometry\": {\"type\": \"Polygon\"," +
                       "\"bbox\": [-105.46875,38.788345355085625,-102.98583984374999,40.27952566881291]," +
                       "\"coordinates\": [[[-105.46875,38.788345355085625],[-102.98583984374999,38.788345355085625]," +
                       "[-102.98583984374999,40.27952566881291],[-105.46875,40.27952566881291]," +
                       "[-105.46875,38.788345355085625]]] }} ]}";

            var rdr = new GeoJsonReader();
            FeatureCollection fc = null;
            var cbb = Feature.ComputeBoundingBoxWhenItIsMissing;

            Feature.ComputeBoundingBoxWhenItIsMissing = true;
            Assert.DoesNotThrow(() => fc = rdr.Read <FeatureCollection>(json));
            Assert.That(fc != null);
            Assert.That(fc.Count, Is.EqualTo(1));
            Assert.That(fc.BoundingBox, Is.EqualTo(new Envelope(new Coordinate(-105.46875, 38.788345355085625), new Coordinate(-102.98583984374999, 40.27952566881291))));
            Feature.ComputeBoundingBoxWhenItIsMissing = cbb;
        }
    private void OnDrawSelectFeatureID()
    {
        var oldSelected = selectedFeatureClass;

        selectedFeatureClass = (FeatureClasses)EditorGUILayout.EnumPopup("Feature Class", selectedFeatureClass);

        if (oldSelected != selectedFeatureClass)
        {
            var classFeatures = FeatureCollection.GetClassFeatures(selectedFeatureClass);
            selectedFeatureNames = classFeatures.Values.ToList();
        }

        int oldFeatureID = selectedFeatureID;

        selectedFeatureID = EditorGUILayout.Popup("Feature Name", selectedFeatureID, selectedFeatureNames.ToArray());

        if (oldFeatureID != selectedFeatureID)
        {
            var featureName   = selectedFeatureNames[selectedFeatureID];
            var classFeatures = FeatureCollection.GetClassFeatures(selectedFeatureClass);
            featureCondition.FeatureID = classFeatures.FirstOrDefault(x => x.Value == featureName).Key;
            EditorUtility.SetDirty(featureCondition);
        }
    }
        public async Task Then_If_The_Route_Ukprn_Does_Not_Match_Value_In_Claim_Then_Fails(
            int ukprn,
            int routeUkprn,
            ProviderUkPrnRequirement providerRequirement,
            [Frozen] Mock <IHttpContextAccessor> httpContextAccessor,
            ProviderAuthorizationHandler authorizationHandler)
        {
            //Arrange
            var responseMock = new FeatureCollection();
            var httpContext  = new DefaultHttpContext(responseMock);

            httpContext.Request.RouteValues.Add("ukprn", routeUkprn);
            httpContextAccessor.Setup(_ => _.HttpContext).Returns(httpContext);
            var claim           = new Claim(ProviderClaims.ProviderUkprn, ukprn.ToString());
            var claimsPrinciple = new ClaimsPrincipal(new[] { new ClaimsIdentity(new[] { claim }) });
            var context         = new AuthorizationHandlerContext(new [] { providerRequirement }, claimsPrinciple, null);

            //Act
            await authorizationHandler.HandleAsync(context);

            //Assert
            Assert.IsFalse(context.HasSucceeded);
            Assert.IsTrue(context.HasFailed);
        }
Ejemplo n.º 52
0
        public void ActualDeleteTriggersBeginEdit()
        {
            MapControl mapControl = new MapControl();

            SelectTool selectTool = mapControl.SelectTool;

            VectorLayer       vectorLayer = new VectorLayer();
            FeatureCollection layer2Data  = new FeatureCollection();

            vectorLayer.DataSource = layer2Data;
            layer2Data.FeatureType = typeof(Feature);

            layer2Data.Add(new Point(4, 5));
            layer2Data.Add(new Point(0, 1));
            mapControl.Map.Layers.Add(vectorLayer);

            var featureMutator = mocks.StrictMock <IFeatureInteractor>();
            var editableObject = mocks.StrictMock <IEditableObject>();

            featureMutator.Expect(fm => fm.EditableObject).Return(editableObject).Repeat.Any();
            featureMutator.Expect(fm => fm.AllowDeletion()).Return(true).Repeat.Any();
            featureMutator.Expect(fm => fm.Delete()).Repeat.Once();
            editableObject.Expect(eo => eo.BeginEdit(null)).IgnoreArguments().Repeat.Once(); //expect BeginEdit!
            editableObject.Expect(eo => eo.EndEdit()).IgnoreArguments().Repeat.Once();

            mocks.ReplayAll();

            selectTool.Select((IFeature)layer2Data.Features[0]);

            selectTool.SelectedFeatureInteractors.Clear();
            selectTool.SelectedFeatureInteractors.Add(featureMutator); //inject our own feature editor

            mapControl.DeleteTool.DeleteSelection();

            mocks.VerifyAll();
        }
Ejemplo n.º 53
0
        //public IEnumerable<Parceltbl> getCadastralLayers()
        //{
        //    var cadastralMaps = _context.Parceltbl
        //        .FromSql("EXECUTE cadastralDataSp")
        //        .ToList();
        //    return cadastralMaps;
        //}

        public FeatureCollection getCadastralLayers()
        {
            var geojsonndata = new FeatureCollection()
            {
                CRS = new GeoJSON.Net.CoordinateReferenceSystem.NamedCRS("urn:ogc:def:crs:OGC::CRS84")
            };
            var cadastralMaps = _context.AndroidViewtbl.ToList();
            var wktParcels    = new WKTWriter();

            cadastralMaps.ForEach(sa =>
            {
                var wkt = wktParcels.Write(sa.Polygon);
                SqlGeometry sqlGeometry           = SqlGeometry.Parse(new System.Data.SqlTypes.SqlString(wkt));
                var geojsonobject                 = sqlGeometry.ToGeoJSONGeometry();
                androidViewModel androidViewModel = new androidViewModel();

                androidViewModel.Id = sa.Id;
                //var geojson = JsonConvert.DeserializeObject<Polygon>(geojsonobject);
                var feature = new Feature(geojsonobject, androidViewModel);

                geojsonndata.Features.Add(feature);
            });
            return(geojsonndata);
        }
Ejemplo n.º 54
0
        public KestrelServer(IOptions <KestrelServerOptions> options, IApplicationLifetime applicationLifetime, ILoggerFactory loggerFactory)
        {
            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }

            if (applicationLifetime == null)
            {
                throw new ArgumentNullException(nameof(applicationLifetime));
            }

            if (loggerFactory == null)
            {
                throw new ArgumentNullException(nameof(loggerFactory));
            }

            Options = options.Value ?? new KestrelServerOptions();
            _applicationLifetime = applicationLifetime;
            _logger          = loggerFactory.CreateLogger(typeof(KestrelServer).GetTypeInfo().Namespace);
            Features         = new FeatureCollection();
            _serverAddresses = new ServerAddressesFeature();
            Features.Set <IServerAddressesFeature>(_serverAddresses);
        }
Ejemplo n.º 55
0
        public void TestConvertFeatureCollection()
        {
            // arrange
            var featureCollection = new FeatureCollection();
            var geom = new Geometry {
                type = "Polygon"
            };

            double[,] numbers = { { 1, 2 }, { 3, 4 } };
            geom.coordinates  = numbers;
            var feature = new Feature {
                geometry = geom
            };

            feature.id = "1";
            feature.Properties.Add("LOWPARCELID", "1902226080");
            featureCollection.features.Add(feature);

            // act
            var result = featureCollection.ToEsriJJson();

            // assert
            Assert.IsTrue(result.geometryType == "esriGeometryPolygon");
        }
Ejemplo n.º 56
0
        public void CanMovePointOfLine()
        {
            var mapControl = new MapControl {
                AllowDrop = false
            };

            var vectorLayer = new VectorLayer();
            var layerData   = new FeatureCollection();

            vectorLayer.DataSource = layerData;
            layerData.FeatureType  = typeof(CloneableFeature);

            layerData.Add(new LineString(new[] { new Coordinate(0, 0), new Coordinate(50, 0), new Coordinate(100, 0) }));

            mapControl.Map.Layers.Add(vectorLayer);
            vectorLayer.CoordinateTransformation = _amt;

            var firstFeature = (IFeature)layerData.Features[0];

            mapControl.SelectTool.Select(firstFeature);
            //((LineStringFeatureInteractor)mapControl.SelectTool.GetFeatureInteractor(vectorLayer, firstFeature)).MoveVerticesAllowed = true;

            var curveTool = mapControl.GetToolByType <CurvePointTool>();

            curveTool.IsActive = true;
            var args = new MouseEventArgs(MouseButtons.Left, 1, 0, 0, 0);

            curveTool.OnMouseMove(new Coordinate(50.1, 999.9), new MouseEventArgs(MouseButtons.None, 1, 0, 0, 0));
            curveTool.OnMouseDown(new Coordinate(50.1, 999.9), args);
            curveTool.OnMouseMove(new Coordinate(60, 1010), new MouseEventArgs(MouseButtons.Left, 1, 0, 0, 0));
            curveTool.OnMouseUp(new Coordinate(60, 1010), args);

            Assert.AreEqual(3, firstFeature.Geometry.Coordinates.Length);
            Assert.AreEqual(60.0, firstFeature.Geometry.Coordinates[1].X);
            Assert.AreEqual(10, firstFeature.Geometry.Coordinates[1].Y);
        }
        /// <summary>
        /// Convert a GeoJSON FeatureCollection into an ArcGIS FeatureSet
        /// </summary>
        /// <typeparam name="TGeometry">The type of GeoJSON geometry to convert. Can be Point, MultiPoint, LineString, MultiLineString, Polygon, MultiPolygon</typeparam>
        /// <param name="featureCollection">A collection of one or more features of the same geometry type</param>
        /// <returns>A converted set of features that can be used in ArcGIS Server operations</returns>
        public static List <Feature <IGeometry> > ToFeatures <TGeometry>(this FeatureCollection <TGeometry> featureCollection)
            where TGeometry : IGeoJsonGeometry
        {
            if (featureCollection == null || featureCollection.Features == null || !featureCollection.Features.Any())
            {
                return(null);
            }

            var features = new List <Feature <IGeometry> >();

            foreach (var geoJson in featureCollection.Features)
            {
                var geometry = geoJson.Geometry.ToGeometry(_typeMap[geoJson.Geometry.Type]());
                if (geometry == null)
                {
                    continue;
                }

                features.Add(new Feature <IGeometry> {
                    Geometry = geometry, Attributes = geoJson.Properties
                });
            }
            return(features);
        }
Ejemplo n.º 58
0
        public void http_context_should_return_null_api_version_when_the_value_is_invalid()
        {
            // arrange
            var featureCollection = new FeatureCollection();
            var serviceProvider   = new Mock <IServiceProvider>();
            var query             = new Mock <IQueryCollection>();
            var request           = new Mock <HttpRequest>();
            var httpContext       = new Mock <HttpContext>();

            featureCollection.Set <IApiVersioningFeature>(new ApiVersioningFeature(httpContext.Object));
            serviceProvider.Setup(sp => sp.GetService(typeof(IApiVersionReader))).Returns(new QueryStringApiVersionReader());
            query.SetupGet(q => q["api-version"]).Returns(new StringValues("abc"));
            request.SetupGet(r => r.Query).Returns(query.Object);
            request.SetupGet(r => r.HttpContext).Returns(() => httpContext.Object);
            httpContext.SetupGet(c => c.Features).Returns(featureCollection);
            httpContext.SetupGet(c => c.Request).Returns(request.Object);
            httpContext.SetupProperty(c => c.RequestServices, serviceProvider.Object);

            // act
            var result = httpContext.Object.GetRequestedApiVersion();

            // assert
            result.Should().BeNull();
        }
        public void geojson_should_serialize_an_array_witn_a_single_item()
        {
            const string      json   = @"
{
  ""type"": ""FeatureCollection"",
  ""features"": [
    {
      ""type"": ""Feature"",
      ""geometry"": {
        ""type"": ""Point"",
        ""coordinates"": [
          1.0,
          2.0
        ]
      },
      ""properties"": {
        ""foo"": [
            {
              ""zee1"": ""xyz1""
            }
          ]
      }
    }
  ]
}
";
            GeoJsonReader     reader = new GeoJsonReader();
            FeatureCollection coll   = reader.Read <FeatureCollection>(json);

            Assert.IsNotNull(coll);

            GeoJsonWriter writer = new GeoJsonWriter();
            string        s      = writer.Write(coll);

            Assert.IsNotNull(s);
        }
Ejemplo n.º 60
0
        public FunctionalTests()
        {
            var featureCollection = new FeatureCollection();

            featureCollection.Set <IServerAddressesFeature>(new ServerAddressesFeature());

            var server = new TestServer(WebHost.CreateDefaultBuilder()
                                        .ConfigureServices(x =>
            {
                x.AddSingleton <IGetActorsQuery, GetActorsQuery>();
                x.AddSingleton <IGetActorByIdQuery, GetActorByIdQuery>();
                x.AddSingleton <IDeleteActorCommand, DeleteActorCommand>();
                x.AddRouting();
                x.AddCarter();
            })
                                        .Configure(x =>
            {
                x.UseRouting();
                x.UseEndpoints(e => e.MapCarter());
            }), featureCollection
                                        );

            this.client = server.CreateClient();
        }