Exemplo n.º 1
0
        /// <summary>
        /// Gets a feature collection with features representing the stop links.
        /// </summary>
        /// <returns></returns>
        public static FeatureCollection GetStopLinks(this MultimodalDb db,
                                                     Profile profile, uint stopId)
        {
            var features = new FeatureCollection();

            var stopEnumerator = db.TransitDb.GetStopsEnumerator();

            if (stopEnumerator.MoveTo(stopId))
            {
                var stopLocation = new GeoAPI.Geometries.Coordinate(stopEnumerator.Longitude, stopEnumerator.Latitude);
                var attributes   = new AttributesTable();
                attributes.AddAttribute("stop_id", stopId);
                features.Add(new Feature(new Point(stopLocation), attributes));

                var stopLinksDb = db.GetStopLinksDb(profile).GetEnumerator();
                stopLinksDb.MoveTo(stopId);
                while (stopLinksDb.MoveNext())
                {
                    var routerPoint  = new RouterPoint(0, 0, stopLinksDb.EdgeId, stopLinksDb.Offset);
                    var linkLocation = routerPoint.LocationOnNetwork(db.RouterDb).ToCoordinate();

                    attributes = new AttributesTable();
                    attributes.AddAttribute("edge_id", stopLinksDb.EdgeId.ToInvariantString());
                    attributes.AddAttribute("offset", stopLinksDb.Offset.ToInvariantString());
                    features.Add(new Feature(new Point(linkLocation), attributes));
                    features.Add(new Feature(new LineString(new GeoAPI.Geometries.Coordinate[] { stopLocation, linkLocation }), new AttributesTable()));
                }
            }
            return(features);
        }
Exemplo n.º 2
0
        private static Feature SafelyActivateWebFeature(ClientRuntimeContext context, FeatureCollection features,
                                                        FeatureDefinition featureModel, Microsoft.SharePoint.Client.FeatureDefinitionScope scope)
        {
            var result = features.Add(featureModel.Id, featureModel.ForceActivate, scope);

            try
            {
                context.ExecuteQueryWithTrace();
            }
            catch (Exception e)
            {
                // sandbox site/web features?
                // they need to ne activated with SPFeatureDefinitionScope.Site scope
                if ((featureModel.Scope == FeatureDefinitionScope.Site || featureModel.Scope == FeatureDefinitionScope.Web) &&
                    e.Message.ToUpper().Contains(featureModel.Id.ToString("D").ToUpper()))
                {
                    result = features.Add(featureModel.Id, featureModel.ForceActivate, Microsoft.SharePoint.Client.FeatureDefinitionScope.Site);
                    context.ExecuteQueryWithTrace();
                }
                else
                {
                    throw e;
                }
            }

            return(result);
        }
Exemplo n.º 3
0
        ///<inheritdoc />
        public FeatureCollection ToGeoJson(GpxFile gpx)
        {
            var collection     = new FeatureCollection();
            var points         = gpx.Waypoints ?? new List <GpxWaypoint>();
            var pointsFeatures = points.Select(point => new Feature(new Point(CreateGeoPosition(point)), CreateProperties(point.Name, point.Description)));

            pointsFeatures.ToList().ForEach(f => collection.Add(f));

            var routes         = gpx.Routes ?? new List <GpxRoute>();
            var routesFeatures = routes.Select(route => new Feature(new LineString(route.Waypoints.Select(CreateGeoPosition).ToArray()), CreateProperties(route.Name, route.Description)));

            routesFeatures.ToList().ForEach(f => collection.Add(f));

            foreach (var track in gpx.Tracks ?? new List <GpxTrack>())
            {
                if (track.Segments.Length == 1)
                {
                    var lineStringFeature = new Feature(new LineString(track.Segments[0].Waypoints.Select(CreateGeoPosition).ToArray()), CreateProperties(track.Name, track.Description));
                    collection.Add(lineStringFeature);
                    continue;
                }
                var lineStringList = track.Segments.Select(segment => new LineString(segment.Waypoints.Select(CreateGeoPosition).ToArray()) as LineString).ToArray();
                var feature        = new Feature(new MultiLineString(lineStringList), CreateMultiLineProperties(track.Name, gpx.Metadata.Creator, track.Description));
                collection.Add(feature);
            }
            return(collection);
        }
Exemplo n.º 4
0
        public async Task UsesIdentifierFeature_IfAlreadyPresentOnContext()
        {
            // Arrange
            var requestIdentifierFeature = new HttpRequestIdentifierFeature()
            {
                TraceIdentifier = Guid.NewGuid().ToString()
            };
            var features = new FeatureCollection();

            features.Add(typeof(IHttpRequestFeature), new HttpRequestFeature());
            features.Add(typeof(IHttpRequestIdentifierFeature), requestIdentifierFeature);
            features.Add(typeof(IHttpResponseFeature), new HttpResponseFeature());
            var context       = new DefaultHttpContext(features);
            var loggerFactory = new LoggerFactory();

            loggerFactory.AddProvider(new ElmLoggerProvider(new ElmStore(), new ElmOptions()));

            // Act & Assert
            var errorPageMiddleware = new ElmCaptureMiddleware((innerContext) =>
            {
                Assert.Same(requestIdentifierFeature, innerContext.GetFeature <IHttpRequestIdentifierFeature>());
                return(Task.FromResult(0));
            }, loggerFactory, new TestElmOptions());

            await errorPageMiddleware.Invoke(context);

            Assert.Same(requestIdentifierFeature, context.GetFeature <IHttpRequestIdentifierFeature>());
        }
Exemplo n.º 5
0
        public async Task UpdatesTraceIdentifier_IfNullOrEmpty(string requestId)
        {
            // Arrange
            var requestIdentifierFeature = new HttpRequestIdentifierFeature()
            {
                TraceIdentifier = requestId
            };
            var features = new FeatureCollection();

            features.Add(typeof(IHttpRequestIdentifierFeature), requestIdentifierFeature);
            features.Add(typeof(IHttpRequestFeature), new HttpRequestFeature());
            features.Add(typeof(IHttpResponseFeature), new HttpResponseFeature());
            var context       = new DefaultHttpContext(features);
            var loggerFactory = new LoggerFactory();

            loggerFactory.AddProvider(new ElmLoggerProvider(new ElmStore(), new ElmOptions()));

            // Act & Assert
            var errorPageMiddleware = new ElmCaptureMiddleware((innerContext) =>
            {
                var feature = innerContext.GetFeature <IHttpRequestIdentifierFeature>();
                Assert.NotNull(feature);
                Assert.False(string.IsNullOrEmpty(feature.TraceIdentifier));
                return(Task.FromResult(0));
            }, loggerFactory, new TestElmOptions());

            await errorPageMiddleware.Invoke(context);

            Assert.Equal(requestId, context.GetFeature <IHttpRequestIdentifierFeature>().TraceIdentifier);
        }
Exemplo n.º 6
0
        public override async Task WriteResponseBodyAsync(OutputFormatterWriteContext context,
                                                          Encoding selectedEncoding)
        {
            var response = context.HttpContext.Response;

            var features = new FeatureCollection();

            if (context.Object is IEnumerable <Feature> fs)
            {
                foreach (var f in fs)
                {
                    features.Add(f);
                }
            }
            else if (context.Object is IAsyncEnumerable <Feature> afs)
            {
                await foreach (var f in afs)
                {
                    features.Add(f);
                }
            }
            else
            {
                throw new ArgumentException("Cannot write response body for the given type.");
            }

            var textWriter = new StringWriter();

            _serializer.Serialize(textWriter, features);

            await response.WriteAsync(textWriter.ToString());
        }
Exemplo n.º 7
0
        private static FeatureCollection FeatureCollection(string geoJson)
        {
            var reader = new GeoJsonReader();

            var featureCollection = new FeatureCollection();

            try
            {
                featureCollection =
                    reader.Read <FeatureCollection>(geoJson);
                if (featureCollection.Count == 0)
                {
                    var feature =
                        reader.Read <Feature>(geoJson);
                    featureCollection.Add(feature);
                }
            }
            catch (Exception)
            {
                var feature =
                    reader.Read <Feature>(geoJson);
                featureCollection.Add(feature);
            }
            return(featureCollection);
        }
Exemplo n.º 8
0
        /// <summary>
        /// Converts this route to a feature collection.
        /// </summary>
        /// <returns></returns>
        public FeatureCollection ToFeatureCollection()
        {
            var featureCollection = new FeatureCollection();

            if (this.Segments == null)
            {
                return(featureCollection);
            }
            for (int i = 0; i < this.Segments.Length; i++)
            {
                // create a line string for the current segment.
                if (i > 0)
                { // but only do so when there is a previous point available.
                    var segmentLineString = new LineString(
                        new GeoCoordinate(this.Segments[i - 1].Latitude, this.Segments[i - 1].Longitude),
                        new GeoCoordinate(this.Segments[i].Latitude, this.Segments[i].Longitude));

                    var segmentTags     = this.Segments[i].Tags;
                    var attributesTable = new SimpleGeometryAttributeCollection();
                    if (segmentTags != null)
                    { // there are tags.
                        foreach (var tag in segmentTags)
                        {
                            attributesTable.Add(tag.Key, tag.Value);
                        }
                    }
                    attributesTable.Add("time", this.Segments[i].Time);
                    attributesTable.Add("distance", this.Segments[i].Distance);
                    if (this.Segments[i].Vehicle != null)
                    {
                        attributesTable.Add("vehicle", this.Segments[i].Vehicle);
                    }
                    featureCollection.Add(new Feature(segmentLineString, attributesTable));
                }

                // create points.
                if (this.Segments[i].Points != null)
                {
                    foreach (var point in this.Segments[i].Points)
                    {
                        // build attributes.
                        var currentPointTags = point.Tags;
                        var attributesTable  = new SimpleGeometryAttributeCollection();
                        if (currentPointTags != null)
                        { // there are tags.
                            foreach (var tag in currentPointTags)
                            {
                                attributesTable.Add(tag.Key, tag.Value);
                            }
                        }

                        // build feature.
                        var pointGeometry = new Point(new GeoCoordinate(point.Latitude, point.Longitude));
                        featureCollection.Add(new Feature(pointGeometry, attributesTable));
                    }
                }
            }
            return(featureCollection);
        }
Exemplo n.º 9
0
        /// <summary>
        /// Generates a feature collection with one LineString per instruction and all poi's as Points.
        /// </summary>
        /// <returns></returns>
        private FeatureCollection GetFeatures(Route route, List <Instruction> instructions)
        {
            var featureCollection = new FeatureCollection();

            for (int i = 0; i < instructions.Count; i++)
            {
                var instruction = instructions[i];
                var coordinates = new List <GeoCoordinate>();
                for (int segmentIdx = instruction.FirstSegmentIdx; segmentIdx <= instruction.LastSegmentIdx; segmentIdx++)
                {
                    coordinates.Add(new GeoCoordinate(route.Segments[segmentIdx].Latitude, route.Segments[segmentIdx].Longitude));
                }

                // build attributes.
                var currentArcTags  = instruction.MetaData;
                var attributesTable = new SimpleGeometryAttributeCollection();
                if (currentArcTags != null)
                { // there are tags.
                    foreach (var tag in currentArcTags)
                    {
                        if (tag.Value != null)
                        {
                            var t = tag.Value.GetType();
                            if (t.IsPrimitive || t == typeof(Decimal) || t == typeof(String))
                            {
                                attributesTable.Add(tag.Key, tag.Value);
                            }
                        }
                    }
                }

                // build feature.
                var lineString = new LineString(coordinates);
                featureCollection.Add(new Feature(lineString, attributesTable));

                // build poi-features if any.
                if (instruction.Pois != null)
                {
                    foreach (var poi in instruction.Pois)
                    {
                        // build attributes.
                        var poiTags            = poi.Tags;
                        var poiAttributesTable = new SimpleGeometryAttributeCollection();
                        if (poiTags != null)
                        { // there are tags.
                            foreach (var tag in poiTags)
                            {
                                poiAttributesTable.Add(tag.Key, tag.Value);
                            }
                        }

                        // build feature.
                        var point = new Point(poi.Location);
                        featureCollection.Add(new Feature(point, poiAttributesTable));
                    }
                }
            }
            return(featureCollection);
        }
        public void SecondCallToAddThrowsException()
        {
            var interfaces = new FeatureCollection();
            var thing = new Thing();

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

            Assert.Throws<ArgumentException>(() => interfaces.Add(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));
        }
Exemplo n.º 12
0
        public static FeatureCollection GetFeaturesIn(this RouterDb db, float minLatitude, float minLongitude, float maxLatitude, float maxLongitude)
        {
            RoutingNetwork    network           = db.Network;
            FeatureCollection featureCollection = new FeatureCollection();
            HashSet <uint>    uintSet1          = network.GeometricGraph.Search(minLatitude, minLongitude, maxLatitude, maxLongitude);
            HashSet <long>    longSet           = new HashSet <long>();

            RoutingNetwork.EdgeEnumerator edgeEnumerator = network.GetEdgeEnumerator();
            HashSet <uint> uintSet2 = new HashSet <uint>();

            foreach (uint vertex1 in uintSet1)
            {
                GeoCoordinateSimple vertex2 = network.GeometricGraph.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             = network.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);
                        RouterDb   db1        = db;
                        EdgeData   data       = edgeEnumerator.Data;
                        int        profile    = (int)data.Profile;
                        data = edgeEnumerator.Data;
                        int metaId = (int)data.MetaId;
                        TagsCollectionBase profileAndMeta = db1.GetProfileAndMeta((uint)profile, (uint)metaId);
                        profileAndMeta.AddOrReplace(Tag.Create("id", edgeEnumerator.Id.ToInvariantString()));
                        featureCollection.Add(new Feature((Geometry)lineString, (GeometryAttributeCollection) new SimpleGeometryAttributeCollection((IEnumerable <Tag>)profileAndMeta)));
                        if (!uintSet1.Contains(edgeEnumerator.To))
                        {
                            uintSet2.Add(edgeEnumerator.To);
                        }
                    }
                }
            }
            foreach (uint vertex1 in uintSet2)
            {
                GeoCoordinateSimple vertex2 = network.GeometricGraph.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())
                })));
            }
            return(featureCollection);
        }
        public static FeatureCollection ToFeatureCollection(this RouterDb routerDb, SnapPoint snapPoint)
        {
            var features = new FeatureCollection();

            features.Add(routerDb.ToFeature(snapPoint.EdgeId));
            var locationOnNetwork = routerDb.LocationOnNetwork(snapPoint);

            features.Add(new Feature(new Point(new Coordinate(locationOnNetwork.Longitude, locationOnNetwork.Latitude)), new AttributesTable()));
            return(features);
        }
Exemplo n.º 14
0
        /// <summary>
        /// Converts this route to a feature collection.
        /// </summary>
        public static FeatureCollection ToFeatureCollection(this Route route)
        {
            var featureCollection = new FeatureCollection();

            if (route.Shape == null)
            {
                return(featureCollection);
            }

            if (route.ShapeMeta == null)
            { // if there is no meta data, just use one linestring.
                var linestring = route.ToLineString();
                var attributes = route.Attributes.ToAttributesTable();
                featureCollection.Add(new Feature(linestring, attributes));
            }
            else
            { // one linestring per meta-object.
                var previous = route.ShapeMeta[0];
                for (var i = 1; i < route.ShapeMeta.Length; i++)
                {
                    var current = route.ShapeMeta[i];
                    if (current.Shape < previous.Shape)
                    {
                        Logging.Logger.Log("RouteExtensions", Logging.TraceEventType.Warning,
                                           "Invalid meta-data detected on route. One of the meta-description has a shape index smaller than the previous one.");
                    }
                    var shape = new GeoAPI.Geometries.Coordinate[current.Shape - previous.Shape + 1];
                    for (var s = previous.Shape; s <= current.Shape; s++)
                    {
                        if (s < 0 || s >= route.Shape.Length)
                        {
                            throw new Exception("Invalid meta-data object: shape-index outside of the range of shapepoints.");
                        }
                        shape[s - previous.Shape] = route.Shape[s].ToCoordinate();
                    }
                    var attributes = current.Attributes.ToAttributesTable();
                    featureCollection.Add(new Feature(new LineString(shape), attributes));
                    previous = current;
                }
            }

            if (route.Stops != null)
            {
                for (var i = 0; i < route.Stops.Length; i++)
                {
                    featureCollection.Add(new Feature(
                                              new Point(new GeoAPI.Geometries.Coordinate(
                                                            route.Stops[i].Coordinate.ToCoordinate())),
                                              route.Stops[i].Attributes.ToAttributesTable()));
                }
            }
            return(featureCollection);
        }
Exemplo n.º 15
0
        /// <summary>
        /// Converts this referenced location to a geometry.
        /// </summary>
        /// <returns></returns>
        public FeatureCollection ToFeatures()
        {
            var featureCollection = new FeatureCollection();
            var geometryFactory   = new GeometryFactory();

            // build coordinates list.
            var coordinates = new List <Coordinate>();

            for (int idx = 0; idx < this.Edges.Length; idx++)
            {
                float latitude, longitude;
                _graph.GetVertex(this.Vertices[idx], out latitude, out longitude);
                coordinates.Add(new Coordinate(longitude, latitude));

                var edge      = this.Edges[idx];
                var edgeShape = this.EdgeShapes[idx];
                if (edgeShape != null)
                {
                    for (int coordIdx = 0; coordIdx < edgeShape.Length; coordIdx++)
                    {
                        coordinates.Add(new Coordinate()
                        {
                            X = edgeShape[coordIdx].Longitude,
                            Y = edgeShape[coordIdx].Latitude
                        });
                    }
                }

                var tags  = _graph.TagsIndex.Get(edge.Tags);
                var table = tags.ToAttributes();

                _graph.GetVertex(this.Vertices[idx + 1], out latitude, out longitude);
                coordinates.Add(new Coordinate(longitude, latitude));

                featureCollection.Add(new Feature(geometryFactory.CreateLineString(coordinates.ToArray()), table));
                coordinates.Clear();
            }

            var positiveLocation           = this.GetPositiveOffsetLocation(_graph).ToGeoAPICoordinate();
            var positiveLocationAttributes = new AttributesTable();

            positiveLocationAttributes.AddAttribute("type", "positive_offset_location");
            featureCollection.Add(new Feature(new Point(positiveLocation), positiveLocationAttributes));
            var negativeLocation           = this.GetNegativeOffsetLocation(_graph).ToGeoAPICoordinate();
            var negativeLocationAttributes = new AttributesTable();

            negativeLocationAttributes.AddAttribute("type", "negative_offset_location");
            featureCollection.Add(new Feature(new Point(negativeLocation), positiveLocationAttributes));

            return(featureCollection);
        }
Exemplo n.º 16
0
        public static FeatureCollection ToFeatureCollection(this Route route)
        {
            FeatureCollection featureCollection = new FeatureCollection();

            if (route.Segments == null)
            {
                return(featureCollection);
            }
            for (int index = 0; index < route.Segments.Count; ++index)
            {
                if (index > 0)
                {
                    LineString lineString = new LineString(new GeoCoordinate[2]
                    {
                        new GeoCoordinate((double)route.Segments[index - 1].Latitude, (double)route.Segments[index - 1].Longitude),
                        new GeoCoordinate((double)route.Segments[index].Latitude, (double)route.Segments[index].Longitude)
                    });
                    RouteTags[] tags = route.Segments[index].Tags;
                    SimpleGeometryAttributeCollection attributeCollection = new SimpleGeometryAttributeCollection();
                    if (tags != null)
                    {
                        foreach (RouteTags routeTags in tags)
                        {
                            attributeCollection.Add(routeTags.Key, (object)routeTags.Value);
                        }
                    }
                    attributeCollection.Add("time", (object)route.Segments[index].Time);
                    attributeCollection.Add("distance", (object)route.Segments[index].Distance);
                    attributeCollection.Add("profile", (object)route.Segments[index].Profile);
                    featureCollection.Add(new Feature((Geometry)lineString, (GeometryAttributeCollection)attributeCollection));
                }
                if (route.Segments[index].Points != null)
                {
                    foreach (RouteStop point1 in route.Segments[index].Points)
                    {
                        RouteTags[] tags = point1.Tags;
                        SimpleGeometryAttributeCollection attributeCollection = new SimpleGeometryAttributeCollection();
                        if (tags != null)
                        {
                            foreach (RouteTags routeTags in tags)
                            {
                                attributeCollection.Add(routeTags.Key, (object)routeTags.Value);
                            }
                        }
                        Point point2 = new Point(new GeoCoordinate((double)point1.Latitude, (double)point1.Longitude));
                        featureCollection.Add(new Feature((Geometry)point2, (GeometryAttributeCollection)attributeCollection));
                    }
                }
            }
            return(featureCollection);
        }
        /// <summary>
        /// Returns a list of municipalities in GeoJSON format
        /// </summary>
        /// <returns></returns>
        public HttpResponseMessage Get()
        {
            var session = SessionManager.Session;

            var municipalities = session.Query <Municipality>().ToList();

            FeatureCollection collection = new FeatureCollection();

            foreach (var municipality in municipalities)
            {
                var feature = new Feature
                {
                    Geometry   = municipality.Geom,
                    Attributes = new AttributesTable(),
                };

                feature.Attributes.AddAttribute("id", municipality.Id);
                feature.Attributes.AddAttribute("name", municipality.Name);
                feature.Attributes.AddAttribute("no", municipality.MunicipalityNo);
                feature.Attributes.AddAttribute("type", "municipality");

                collection.Add(feature);
            }

            var jsonSerializer = new GeoJsonSerializer();
            var sw             = new StringWriter();

            jsonSerializer.Serialize(sw, collection);
            return(Response(sw.ToString()));
        }
        private static void Log(Dictionary <string, IGeometry> shapes, string step, Stopwatch watch)
        {
            watch.Stop();
            Console.WriteLine(step + $": {watch.ElapsedMilliseconds / 1000m} seconds");

            if (OutputFolder == null)
            {
                return;
            }

            var geoJson  = new GeoJsonWriter();
            var features = new FeatureCollection();

            foreach (var result in shapes)
            {
                var feature = new Feature();
                feature.Geometry = result.Value;
                var attributesTable = new AttributesTable();
                if (result.Key != null)
                {
                    attributesTable.Add("Id", result.Key);
                }
                feature.Attributes = attributesTable;
                features.Add(feature);
            }
            var json = geoJson.Write(features);

            File.WriteAllText(OutputFolder + $@"{step}.json", json);
        }
Exemplo n.º 19
0
        /// <summary>
        /// Converts one feature into a feature collection.
        /// </summary>
        public static FeatureCollection ToFeatures(this Feature feature)
        {
            var features = new FeatureCollection();

            features.Add(feature);
            return(features);
        }
Exemplo n.º 20
0
        /// <summary>
        /// Converts the given line location to features.
        /// </summary>
        public static FeatureCollection ToFeatures(this LineLocation line)
        {
            var featureCollection = new FeatureCollection();

            featureCollection.Add(line.First.ToFeature());
            if (line.Intermediate != null)
            {
                foreach (var p in line.Intermediate)
                {
                    featureCollection.Add(p.ToFeature());
                }
            }
            featureCollection.Add(line.Last.ToFeature());

            return(featureCollection);
        }
 public static void AddRange(this FeatureCollection featureCollection, IEnumerable <Feature> features)
 {
     foreach (var feature in features)
     {
         featureCollection.Add(feature);
     }
 }
Exemplo n.º 22
0
        public async Task <IActionResult> PostFindUnmappedPartsFromGpsTrace([FromQuery] int traceId)
        {
            var file = await CreateOsmGateway().GetTraceData(traceId);

            if (file == null)
            {
                return(BadRequest("Invalid trace id: " + traceId));
            }
            using (var memoryStream = new MemoryStream())
            {
                await file.Stream.CopyToAsync(memoryStream);

                var gpxBytes = await _dataContainerConverterService.Convert(memoryStream.ToArray(), file.FileName, DataContainerConverterService.GPX);

                var gpx         = gpxBytes.ToGpx().UpdateBounds();
                var highwayType = GetHighwayType(gpx);
                var gpxItmLines = GpxToItmLineStrings(gpx);
                if (!gpxItmLines.Any())
                {
                    return(BadRequest("File does not contain any traces..."));
                }
                var manipulatedItmLines = await _addibleGpxLinesFinderService.GetLines(gpxItmLines);

                var attributesTable = new AttributesTable {
                    { "highway", highwayType }
                };
                attributesTable.Add("source", "trace id: " + traceId);
                var featureCollection = new FeatureCollection();
                foreach (var line in manipulatedItmLines)
                {
                    featureCollection.Add(new Feature(ToWgs84LineString(line.Coordinates), attributesTable));
                }
                return(Ok(featureCollection));
            }
        }
Exemplo n.º 23
0
        public void FeatureCollectionAddTest()
        {
            FeatureCollection collection = new FeatureCollection(this.identifier, null);

            collection.Add(this.mockFeatures[0]);
            collection.Count.ShouldBe(1);
            collection[this.mockFeatures[0].Identifier].ShouldBe(this.mockFeatures[0]);

            collection.Add(this.mockFeatures[1]);
            collection.Count.ShouldBe(2);
            collection[this.mockFeatures[0].Identifier].ShouldBe(this.mockFeatures[0]);
            collection[this.mockFeatures[1].Identifier].ShouldBe(this.mockFeatures[1]);

            Should.Throw <ArgumentNullException>(() => collection.Add(null));
            Should.Throw <ArgumentException>(() => collection.Add(this.mockFeatures[0]));
        }
Exemplo n.º 24
0
        /// <summary>
        /// Writes a layer of the tile to the given stream.
        /// </summary>
        /// <param name="tile">The vector tile.</param>
        /// <param name="stream">The stream to write to.</param>
        public static void Write(this VectorTile tile, Stream stream)
        {
            var featureCollection = new FeatureCollection();

            foreach (var layer in tile.Layers)
            {
                if (layer == null)
                {
                    continue;
                }

                foreach (var feature in layer.Features)
                {
                    featureCollection.Add(feature);
                }
            }

            if (featureCollection.Count == 0)
            {
                return;
            }

            var streamWriter = new StreamWriter(stream, Encoding.Default, 1024, true);

            Serializer.Serialize(streamWriter, featureCollection);
            streamWriter.Flush();
        }
Exemplo n.º 25
0
        public static FeatureCollection GetFeatureCollection(ShapefileDataReader reader)
        {
            FeatureCollection features = new FeatureCollection();

            using (reader)
            {
                var header = reader.DbaseHeader;
                while (reader.Read())
                {
                    var feature    = new Feature();
                    var attributes = new AttributesTable();

                    for (var i = 0; i < header.NumFields; i++)
                    {
                        attributes.Add(header.Fields[i].Name, reader.GetValue(i));
                    }

                    feature.Geometry   = reader.Geometry;
                    feature.Attributes = attributes;
                    features.Add(feature);
                }
            }

            return(features);
        }
Exemplo n.º 26
0
        [Test] //not working in UI?
        public void CanRemovePointFromLine()
        {
            var mapControl = new MapControl();

            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);

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

            mapControl.SelectTool.Select(firstFeature);

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

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

            curveTool.OnMouseMove(new Coordinate(50, 0), new MouseEventArgs(MouseButtons.None, 1, 0, 0, 0));
            curveTool.OnMouseDown(new Coordinate(50, 0), args); // delete tracker

            Assert.AreEqual(2, firstFeature.Geometry.Coordinates.Length);
            Assert.AreEqual(100.0, firstFeature.Geometry.Coordinates[1].X);
        }
        private void CreateOfflinePoisFile(List <Feature> features)
        {
            var collection = new FeatureCollection();

            foreach (var feature in features)
            {
                collection.Add(feature);
            }
            var outputMemStream = new MemoryStream();

            using (var zipStream = new ZipOutputStream(outputMemStream))
            {
                zipStream.SetLevel(9);

                var newEntry = new ZipEntry("pois/pois.geojson")
                {
                    DateTime = DateTime.Now
                };
                zipStream.PutNextEntry(newEntry);
                StreamUtils.Copy(new MemoryStream(collection.ToBytes()), zipStream, new byte[4096]);
                zipStream.CloseEntry();

                CreateImagesJsonFiles(features, zipStream);
                zipStream.Finish();
                outputMemStream.Position = 0;

                _fileSystemHelper.WriteAllBytes("pois.ihm", outputMemStream.ToArray());
            }
        }
Exemplo n.º 28
0
        public void TestAddSelection()
        {
            var mapControl = new MapControl();
            var layerData  = new FeatureCollection();

            var layer = new VectorLayer {
                Visible = false, DataSource = layerData
            };
            var feature = new Node {
                Geometry = new Point(0, 0)
            };

            layerData.FeatureType = typeof(Node);
            layerData.Add(feature);

            mapControl.Map.Layers.Add(layer);

            Assert.AreEqual(0, mapControl.SelectTool.SelectedTrackersCount);

            mapControl.SelectTool.AddSelection(new IFeature[0]);

            Assert.AreEqual(0, mapControl.SelectTool.SelectedTrackersCount, "No features should be added as none are passed");

            mapControl.SelectTool.AddSelection(new[] { feature });

            Assert.AreEqual(0, mapControl.SelectTool.SelectedTrackersCount, "No features should be added as none are visible");

            layer.Visible = true;
            mapControl.SelectTool.AddSelection(new[] { feature });

            Assert.AreEqual(1, mapControl.SelectTool.SelectedTrackersCount);
        }
Exemplo n.º 29
0
        public void CanAddPointToLine()
        {
            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(100, 0) }));

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

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

            mapControl.SelectTool.Select(firstFeature);

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

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

            curveTool.OnMouseMove(new Coordinate(50, 1000), new MouseEventArgs(MouseButtons.None, 1, 0, 0, 0));
            curveTool.OnMouseDown(new Coordinate(50, 1000), args);
            curveTool.OnMouseUp(new Coordinate(50, 1000), args);

            Assert.AreEqual(3, firstFeature.Geometry.Coordinates.Length);
            Assert.AreEqual(50.0, firstFeature.Geometry.Coordinates[1].X);
            Assert.AreEqual(0, firstFeature.Geometry.Coordinates[1].Y);
        }
Exemplo n.º 30
0
        public static FeatureCollection ToGeojson(IEnumerable <object> entity)
        {
            if (entity == null)
            {
                return(null);
            }

            var fc = new FeatureCollection();

            foreach (object item in entity)
            {
                var feat = new Feature();
                feat.Attributes = new AttributesTable();
                PropertyInfo[] arrayPropertyInfos = item.GetType().GetProperties();

                foreach (PropertyInfo property in arrayPropertyInfos)
                {
                    if (property.PropertyType.Name == "Geometry")
                    {
                        feat.Geometry = (Geometry)property.GetValue(item);
                    }
                    else if (property.GetValue(item) != null)
                    {
                        feat.Attributes.Add(property.Name, property.GetValue(item));
                    }
                }
                fc.Add(feat);
            }
            return(fc);
        }
Exemplo n.º 31
0
        /// <summary>
        /// Converts this referenced location to a geometry.
        /// </summary>
        /// <returns></returns>
        public FeatureCollection ToFeatures()
        {
            // create the geometry factory.
            var geometryFactory = new GeometryFactory();

            // create the feature collection.
            var featureCollection = new FeatureCollection();

            //// create a point feature at each point in the grid.
            //double lonDiff = (this.LowerLeftLongitude - this.UpperRightLongitude) / this.Columns;
            //double latDiff = (this.UpperRightLatitude - this.LowerLeftLatitude) / this.Rows;
            //for (int column = 0; column < this.Columns; column++)
            //{
            //    double longitude = this.LowerLeftLongitude - (column * lonDiff);
            //    for (int row = 0; row < this.Rows; row++)
            //    {
            //        double latitude = this.UpperRightLatitude - (row * latDiff);
            //        var point = geometryFactory.CreatePoint(new Coordinate(longitude, latitude));
            //        var pointAttributes = new AttributesTable();
            //        featureCollection.Add(new Feature(point, pointAttributes));
            //    }
            //}

            // create a lineair ring.
            var lineairRingAttributes = new AttributesTable();

            featureCollection.Add(new Feature(geometryFactory.CreateLinearRing(new Coordinate[] {
                new Coordinate(this.LowerLeftLongitude, this.LowerLeftLatitude),
                new Coordinate(this.LowerLeftLongitude, this.UpperRightLatitude),
                new Coordinate(this.UpperRightLongitude, this.UpperRightLatitude),
                new Coordinate(this.UpperRightLongitude, this.LowerLeftLatitude),
                new Coordinate(this.LowerLeftLongitude, this.LowerLeftLatitude)
            }), lineairRingAttributes));
            return(featureCollection);
        }
        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 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);
        }
Exemplo n.º 34
0
        /// <summary>${WP_mapping_Clusterer_method_ClusterFeaturesAsync_D}</summary>
        /// <param name="features">${WP_mapping_Clusterer_method_ClusterFeaturesAsync_param_features}</param>
        /// <param name="resolution">${WP_mapping_Clusterer_method_ClusterFeaturesAsync_param_resolution}</param>
        public override void ClusterFeaturesAsync(IEnumerable<Feature> features, double resolution)
        {
            if (features == null)
            {
                base.OnClusteringCompleted(new FeatureCollection());
            }
            else
            {
                if (this.clusterThread != null)
                {
                    this.clusterThread.RunWorkerCompleted -= new RunWorkerCompletedEventHandler(clusterThread_RunWorkerCompleted);
                    if (this.clusterThread.IsBusy)
                    {
                        this.clusterThread.CancelAsync();
                    }
                    this.clusterThread = null;
                }
                this.clusterThread = new BackgroundWorker() { WorkerSupportsCancellation = true };
                this.clusterThread.RunWorkerCompleted += new RunWorkerCompletedEventHandler(clusterThread_RunWorkerCompleted);
                
                featuresClone = new FeatureCollection();
                foreach (Feature item in features)
                {
                    featuresClone.Add(item);
                }

                geosClone = new ObservableCollection<GeoRegion>();
                if (this.RegionCollection != null)
                {
                    foreach (var geo in this.RegionCollection)
                    {
                        geosClone.Add(geo);
                    }
                }

                this.clusterThread.DoWork += (s, e) =>
                {
                    e.Result = ClusterGeoPoints(featuresClone, this.Radius, resolution, this.clusterThread, geosClone);
                };
                this.clusterThread.RunWorkerAsync(new object[] { featuresClone, resolution, geosClone, this.Dispatcher });
            }
        }
Exemplo n.º 35
0
        /// <summary>
        /// FeaturedefinitionScope.None is the way to go OOTB features. http://stackoverflow.com/questions/17803291/failing-to-activate-a-feature-using-com-in-sharepoint-2010
        /// Both Site Collection and Web scoped custom features MUST use Scope.Site.
        /// </summary>
        /// <param name="clientContext"></param>
        /// <param name="featureInfo"></param>
        /// <param name="featureCollection"></param>
        /// <param name="scope"></param>
        private static void ActivateFeatureInCollection(ClientContext clientContext, ShFeature featureInfo, FeatureCollection featureCollection, FeatureDefinitionScope scope)
        {
            clientContext.Load(featureCollection);
            clientContext.ExecuteQuery();

            if (!DoesFeatureExistInCollection(featureCollection, featureInfo.FeatureId))
            {
                try
                {
                    Log.Info("Activating feature   " + featureInfo.FeatureName);
                    featureCollection.Add(featureInfo.FeatureId, true, scope);
                    clientContext.ExecuteQuery();
                }
                catch (ServerException)
                {
                    // Out of the box features will bomb using other scopes than FeatureDefinitionScope.None
                    // This is why we first try with the correct scope, then fallback to Scope.None
                    featureCollection.Add(featureInfo.FeatureId, true, FeatureDefinitionScope.None);
                    clientContext.ExecuteQuery();
                }
            }
        }
Exemplo n.º 36
0
        private static Feature SafelyActivateWebFeature(ClientRuntimeContext context, FeatureCollection features,
            FeatureDefinition featureModel, Microsoft.SharePoint.Client.FeatureDefinitionScope scope)
        {
            var result = features.Add(featureModel.Id, featureModel.ForceActivate, scope);

            try
            {
                context.ExecuteQueryWithTrace();
            }
            catch (Exception e)
            {
                // sandbox site/web features?
                // they need to ne activated with SPFeatureDefinitionScope.Site scope
                if ((featureModel.Scope == FeatureDefinitionScope.Site || featureModel.Scope == FeatureDefinitionScope.Web)
                    && e.Message.ToUpper().Contains(featureModel.Id.ToString("D").ToUpper()))
                {
                    result = features.Add(featureModel.Id, featureModel.ForceActivate, Microsoft.SharePoint.Client.FeatureDefinitionScope.Site);
                    context.ExecuteQueryWithTrace();
                }
                else
                {
                    throw e;
                }
            }

            return result;
        }
        /// <summary>
        /// Gets a feature collection representing the given route based on the given aggregation type.
        /// </summary>
        /// <param name="route"></param>
        /// <param name="aggregationType"></param>
        /// <returns></returns>
        public override FeatureCollection GetFeatures(Route route, RouteAggregationType aggregationType)
        {
            if (route == null) { throw new ArgumentNullException("route"); }
            if (aggregationType == RouteAggregationType.All)
            {  // one LineString.
                var featureCollection = new FeatureCollection();
                var coordinates = route.GetPoints();
                if (coordinates.Count > 1)
                {
                    var lineString = new LineString(coordinates.ToArray());

                    var attributes = new SimpleGeometryAttributeCollection();
                    attributes.Add("osmsharp:total_time", route.TotalTime.ToInvariantString());
                    attributes.Add("osmsharp:total_distance", route.TotalDistance.ToInvariantString());

                    var feature = new Feature(lineString, attributes);

                    featureCollection.Add(feature);
                }
                return featureCollection;
            }
            else if(aggregationType == RouteAggregationType.Modal)
            { // modal.
                // aggregate.
                var aggregator = new ModalAggregator(new OsmRoutingInterpreter());
                var microPlanner = new ModalMicroPlanner(new ModalLanguageGenerator(), new OsmRoutingInterpreter());
                var aggregated = aggregator.Aggregate(route);
                var instructions = InstructionGenerator.Generate(microPlanner, route, aggregated);

                return this.GetFeatures(route, instructions);
            }
            else // modal and instructions.
            { // instructions.
                var instructions = this.GetInstructions(route);

                return this.GetFeatures(route, instructions);
            }
        }
Exemplo n.º 38
0
        /// <summary>
        /// Converts this route to a feature collection.
        /// </summary>
        /// <returns></returns>
        public FeatureCollection ToFeatureCollection()
        {
            var featureCollection = new FeatureCollection();
            if(this.Segments == null)
            {
                return featureCollection;
            }
            for (int i = 0; i < this.Segments.Length; i++)
            {
                // create a line string for the current segment.
                if (i > 0)
                { // but only do so when there is a previous point available.
                    var segmentLineString = new LineString(
                        new GeoCoordinate(this.Segments[i - 1].Latitude, this.Segments[i - 1].Longitude),
                        new GeoCoordinate(this.Segments[i].Latitude, this.Segments[i].Longitude));

                    var segmentTags = this.Segments[i].Tags;
                    var attributesTable = new SimpleGeometryAttributeCollection();
                    if (segmentTags != null)
                    { // there are tags.
                        foreach (var tag in segmentTags)
                        {
                            attributesTable.Add(tag.Key, tag.Value);
                        }
                    }
                    attributesTable.Add("time", this.Segments[i].Time);
                    attributesTable.Add("distance", this.Segments[i].Distance);
                    if (this.Segments[i].Vehicle != null)
                    {
                        attributesTable.Add("vehicle", this.Segments[i].Vehicle);
                    }
                    featureCollection.Add(new Feature(segmentLineString, attributesTable));
                }

                // create points.
                if (this.Segments[i].Points != null)
                {
                    foreach (var point in this.Segments[i].Points)
                    {
                        // build attributes.
                        var currentPointTags = point.Tags;
                        var attributesTable = new SimpleGeometryAttributeCollection();
                        if (currentPointTags != null)
                        { // there are tags.
                            foreach (var tag in currentPointTags)
                            {
                                attributesTable.Add(tag.Key, tag.Value);
                            }
                        }

                        // build feature.
                        var pointGeometry = new Point(new GeoCoordinate(point.Latitude, point.Longitude));
                        featureCollection.Add(new Feature(pointGeometry, attributesTable));
                    }
                }
            }
            return featureCollection;
        }
Exemplo n.º 39
0
        private void ProcessFeature(
                    object modelHost,
                    ClientRuntimeContext context,
                    FeatureCollection features,
                    FeatureDefinition featureModel,
                    Microsoft.SharePoint.Client.FeatureDefinitionScope scope)
        {
            var currentFeature = GetFeature(features, featureModel);
            var featureActivated = IsFeatureActivated(features, featureModel);

            InvokeOnModelEvent(this, new ModelEventArgs
            {
                CurrentModelNode = null,
                Model = null,
                EventType = ModelEventType.OnProvisioning,
                Object = currentFeature,
                ObjectType = typeof(Feature),
                ObjectDefinition = featureModel,
                ModelHost = modelHost
            });

            if (!featureActivated)
            {
                Feature tmpFeature;

                if (featureModel.Enable)
                {
                    tmpFeature = features.Add(featureModel.Id, featureModel.ForceActivate, scope);
                    context.ExecuteQuery();
                }
                else
                {
                    tmpFeature = GetFeature(features, featureModel);
                }

                InvokeOnModelEvent(this, new ModelEventArgs
                {
                    CurrentModelNode = null,
                    Model = null,
                    EventType = ModelEventType.OnProvisioned,
                    Object = tmpFeature,
                    ObjectType = typeof(Feature),
                    ObjectDefinition = featureModel,
                    ModelHost = modelHost
                });
            }
            else
            {
                if (featureModel.Enable && featureModel.ForceActivate)
                {
                    var f = features.Add(featureModel.Id, featureModel.ForceActivate, scope);

                    InvokeOnModelEvent(this, new ModelEventArgs
                    {
                        CurrentModelNode = null,
                        Model = null,
                        EventType = ModelEventType.OnProvisioned,
                        Object = f,
                        ObjectType = typeof(Feature),
                        ObjectDefinition = featureModel,
                        ModelHost = modelHost
                    });

                    context.ExecuteQuery();
                }
                else if (!featureModel.Enable)
                {
                    features.Remove(featureModel.Id, featureModel.ForceActivate);

                    InvokeOnModelEvent(this, new ModelEventArgs
                    {
                        CurrentModelNode = null,
                        Model = null,
                        EventType = ModelEventType.OnProvisioned,
                        Object = null,
                        ObjectType = typeof(Feature),
                        ObjectDefinition = featureModel,
                        ModelHost = modelHost
                    });

                    context.ExecuteQuery();
                }
                else
                {
                    var tmpFeature = GetFeature(features, featureModel);

                    InvokeOnModelEvent(this, new ModelEventArgs
                    {
                        CurrentModelNode = null,
                        Model = null,
                        EventType = ModelEventType.OnProvisioned,
                        Object = tmpFeature,
                        ObjectType = typeof(Feature),
                        ObjectDefinition = featureModel,
                        ModelHost = modelHost
                    });
                }
            }
        }
Exemplo n.º 40
0
        private async Task<FeatureCollection> GetFeatures(XElement ele, string spatialPropName)
        {
            Dictionary<string, string> attributes = new Dictionary<string, string>();
            FeatureCollection fs = new FeatureCollection();
            if (ele != null)
            {
                //加属性
                foreach (KeyValuePair<string, string> itemPair in (from subItem in ele.Elements()
                                                                   where (subItem.Name.LocalName != spatialPropName)
                                                                   select new KeyValuePair<string, string>(subItem.Name.LocalName, subItem.Value)
                 ))
                {
                    attributes.Add(itemPair.Key, itemPair.Value);
                }

                XElement geoElement = string.IsNullOrEmpty(spatialPropName) ? null : ele.Element(XName.Get(spatialPropName, this.FeatureNS));

                if (geoElement != null)
                {

                    XElement firstNode = geoElement.FirstNode as XElement;
                    string geometryTypeName = firstNode != null ? firstNode.Name.LocalName : string.Empty;
                    GeometryType type;

                    #region 这段代码主要用来处理混淆问题。如果删除这段代码,SampleCode的相应案例无法正常运行。
                    try
                    {
                        Enum.Parse(typeof(GeometryType), geometryTypeName, true);
                    }
                    catch (Exception e)
                    {
                        throw new OverflowException("转化出错了", e);
                    }
                    #endregion

                    await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                    {
                        if (Enum.TryParse<GeometryType>(geometryTypeName, true, out type))
                        {
                            if (type == GeometryType.Point)
                            {
                                GeoPoint point = this.ParsePointCoordinates((geoElement.FirstNode as XElement).Value);
                                Feature col = new Feature();
                                foreach (var v in attributes)
                                {
                                    col.Attributes.Add(v.Key, v.Value);
                                }
                                col.Geometry = point;
                                fs.Add(col);
                            }
                            else if (type == GeometryType.LineString)
                            {
                                XElement lineStrEle = geoElement.Element(XName.Get("LineString", nameSpacePair["gml"]));
                                GeoLine line = ParseLineCoordinates(lineStrEle);
                                Feature col = new Feature();
                                foreach (var v in attributes)
                                {
                                    col.Attributes.Add(v.Key, v.Value);
                                }
                                col.Geometry = line;
                                fs.Add(col);
                            }
                            else if (type == GeometryType.Polygon)
                            {
                                XElement polygonEle = geoElement.Element(XName.Get("Polygon", nameSpacePair["gml"]));
                                GeoRegion region = ParseRegionCoordinates(polygonEle);
                                Feature col = new Feature();
                                foreach (var v in attributes)
                                {
                                    col.Attributes.Add(v.Key, v.Value);
                                }
                                col.Geometry = region;
                                fs.Add(col);
                            }
                            else if (type == GeometryType.MultiPoint)
                            {
                                //TODO:处理多点。
                                //暂时不做处理。
                            }
                            else if (type == GeometryType.MultiLineString)
                            {
                                IEnumerable<XElement> lineStringMemberEle = geoElement.Descendants(XName.Get("lineStringMember", nameSpacePair["gml"]));
                                foreach (XElement els in lineStringMemberEle)
                                {
                                    GeoLine line = ParseMultiLineCoordinates(els);
                                    Feature col = new Feature();
                                    foreach (var v in attributes)
                                    {
                                        col.Attributes.Add(v.Key, v.Value);
                                    }
                                    col.Geometry = line;
                                    fs.Add(col);
                                }

                            }
                            else if (type == GeometryType.MultiPolygon)
                            {
                                IEnumerable<XElement> polygonMemberEle = geoElement.Descendants(XName.Get("polygonMember", nameSpacePair["gml"]));

                                foreach (XElement els in polygonMemberEle)
                                {
                                    GeoRegion region = ParseMultiRegionCoordinates(els);
                                    Feature col = new Feature();
                                    foreach (var v in attributes)
                                    {
                                        col.Attributes.Add(v.Key, v.Value);
                                    }

                                    col.Geometry = region;
                                    fs.Add(col);
                                }
                            }
                        }
                    });
                }
            }
            return fs;
        }
        /// <summary>
        /// Activates or deactivates a site collection or web scoped feature
        /// </summary>
        /// <param name="features">Feature Collection which contains the feature</param>
        /// <param name="featureID">ID of the feature to activate/deactivate</param>
        /// <param name="activate">True to activate, false to deactivate the feature</param>
        /// <param name="scope">Scope of the feature definition</param>
        /// <param name="pollingIntervalSeconds">The time in seconds between polls for "IsActive"</param>
        private static void ProcessFeatureInternal(FeatureCollection features, Guid featureID, bool activate, FeatureDefinitionScope scope, int pollingIntervalSeconds = 30)
        {
            if (activate)
            {
                // Feature enabling can take a long time, especially in case of the publishing feature...so let's make it more reliable
                bool cancel = false;
                features.Add(featureID, true, scope);

                if (pollingIntervalSeconds < 5)
                {
                    pollingIntervalSeconds = 5;
                }

                // Kick off a thread that checks for the feature activation to be complete
                Task.Run(() =>
                {
                    while (!cancel)
                    {
                        Thread.Sleep(TimeSpan.FromSeconds(pollingIntervalSeconds));

                        if (!cancel)
                        {
                            cancel = IsFeatureActiveInternal(features, featureID);
                            Log.Info(Constants.LOGGING_SOURCE, CoreResources.FeatureExtensions_ProcessFeatureInternal_FeatureActivationState, cancel, featureID);
                        }
                    }
                });

                // Kick off a thread that enables the feature
                Task.Run(() =>
                {
                    try
                    {
                        features.Context.ExecuteQueryRetry();
                        Log.Info(Constants.LOGGING_SOURCE, CoreResources.FeatureExtensions_ProcessFeatureInternal_FeatureActive, featureID);
                    }
                    catch(Exception ex)
                    {
                        Log.Info(Constants.LOGGING_SOURCE, CoreResources.FeatureExtensions_ProcessFeatureInternal_FeatureException, ex.ToString());
                    }
                    finally
                    {
                        cancel = true;
                    }
                }).Wait();
            }
            else
            {
                try
                {
                    features.Remove(featureID, false);
                    features.Context.ExecuteQueryRetry();
                }
                catch (Exception ex)
                {
                    Log.Error(Constants.LOGGING_SOURCE, CoreResources.FeatureExtensions_FeatureActivationProblem, featureID, ex.Message);
                }
            }
        }
        private void wc_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                if (LoadFailed != null)
                    LoadFailed(this, new RssLoadFailedEventArgs()
                    {
                        ex = new Exception("Error in Reading the RSS feed. Try Again later!", e.Error),
                        UserState = e.UserState
                    });
                return;
            }
            FeatureCollection features = new FeatureCollection();
            using (Stream s = e.Result)
            {
                SyndicationFeed feed;
                List<SyndicationItem> feedItems = new List<SyndicationItem>();

                using (XmlReader reader = XmlReader.Create(s))
                {
                    feed = SyndicationFeed.Load(reader);
                    foreach (SyndicationItem feedItem in feed.Items)
                    {
                        SyndicationElementExtensionCollection ec = feedItem.ElementExtensions;

                        string x = "";
                        string y = "";

                        foreach (SyndicationElementExtension ee in ec)
                        {
                            XmlReader xr = ee.GetReader();
                            switch (ee.OuterName)
                            {
                                case ("lat"):
                                    {
                                        y = xr.ReadElementContentAsString();
                                        break;
                                    }
                                case ("long"):
                                    {
                                        x = xr.ReadElementContentAsString();
                                        break;
                                    }
                                case ("point"):
                                    {
                                        string sp = xr.ReadElementContentAsString();
                                        string[] sxsy = sp.Split(new char[] { ' ' });
                                        x = sxsy[1];
                                        y = sxsy[0];
                                        break;
                                    }
                            }
                        }

                        if (!string.IsNullOrEmpty(x))
                        {
                            //TODO:这儿还有一个转换,不能通用...
                            Point2D point2D = MercatorUtility.LatLonToMeters(new Point2D(Convert.ToDouble(x), Convert.ToDouble(y)));
                            Feature feature = new Feature()
                            {
                                Geometry = new GeoPoint(point2D.X, point2D.Y)

                            };

                            //属性这里也比较不好统一
                            feature.Attributes.Add("Title", feedItem.Title.Text);
                            feature.Attributes.Add("Summary", feedItem.Summary.Text);
                            feature.Attributes.Add("PublishDate", feedItem.PublishDate);
                            feature.Attributes.Add("Id", feedItem.Id);
                            features.Add(feature);
                        }
                    }
                }
            }

            if (LoadCompleted != null)
            {
                LoadCompleted(this, new RssLoadedEventArgs(){Features = features,UserState = e.UserState});
            }
        }
Exemplo n.º 43
0
        /// <summary>
        /// Converts the given route to a line string.
        /// </summary>
        /// <returns></returns>
        public override FeatureCollection GetFeatures(Route route, RouteAggregationType aggregationType)
        {
            if (aggregationType == RouteAggregationType.All ||
                aggregationType == RouteAggregationType.Modal)
            { // one mode, one LineString.
                var featureCollection = new FeatureCollection();
                var coordinates = route.GetPoints();
                if (coordinates.Count > 1)
                {
                    var lineString = new LineString(coordinates.ToArray());

                    var attributes = new SimpleGeometryAttributeCollection();
                    attributes.Add("osmsharp:total_time", route.TotalTime.ToInvariantString());
                    attributes.Add("osmsharp:total_distance", route.TotalDistance.ToInvariantString());

                    var feature = new Feature(lineString, attributes);

                    featureCollection.Add(feature);
                }
                return featureCollection;
            }
            else
            { // one LineString per instruction.
                var instructions = this.GetInstructions(route);
                var featureCollection = new FeatureCollection();
                for (int i = 0; i < instructions.Count; i++)
                {
                    var instruction = instructions[i];
                    var coordinates = new List<GeoCoordinate>();
                    for (int segmentIdx = instruction.FirstSegmentIdx; segmentIdx <= instruction.LastSegmentIdx; segmentIdx++)
                    {
                        coordinates.Add(new GeoCoordinate(route.Segments[segmentIdx].Latitude, route.Segments[segmentIdx].Longitude));
                    }

                    // build attributes.
                    var currentArcTags = instruction.MetaData;
                    var attributesTable = new SimpleGeometryAttributeCollection();
                    if (currentArcTags != null)
                    { // there are tags.
                        foreach (var tag in currentArcTags)
                        {
                            if (tag.Value != null)
                            {
                                var t = tag.Value.GetType();
                                if (t.IsPrimitive || t == typeof(Decimal) || t == typeof(String))
                                {
                                    attributesTable.Add(tag.Key, tag.Value);
                                }
                            }
                        }
                    }

                    // build feature.
                    var lineString = new LineString(coordinates);
                    featureCollection.Add(new Feature(lineString, attributesTable));

                    // build poi-features if any.
                    if (instruction.Pois != null)
                    {
                        foreach (var poi in instruction.Pois)
                        {
                            // build attributes.
                            var poiTags = poi.Tags;
                            var poiAttributesTable = new SimpleGeometryAttributeCollection();
                            if (poiTags != null)
                            { // there are tags.
                                foreach (var tag in poiTags)
                                {
                                    poiAttributesTable.Add(tag.Key, tag.Value);
                                }
                            }

                            // build feature.
                            var point = new Point(poi.Location);
                            featureCollection.Add(new Feature(point, poiAttributesTable));
                        }
                    }
                }
                return featureCollection;
            }
        }
Exemplo n.º 44
0
        /// <summary>
        /// Interprets an OSM-object and returns the corresponding geometry.
        /// </summary>
        /// <param name="osmObject"></param>
        /// <returns></returns>
        public override FeatureCollection Interpret(ICompleteOsmGeo osmObject)
        {
            // DISCLAIMER: this is a very very very simple geometry interpreter and
            // contains hardcoded all relevant tags.

            var collection = new FeatureCollection();
            TagsCollectionBase tags;
            if (osmObject != null)
            {
                switch (osmObject.Type)
                {
                    case CompleteOsmType.Node:
                        var newCollection = new TagsCollection(
                            osmObject.Tags);
                        newCollection.RemoveKey("FIXME");
                        newCollection.RemoveKey("node");
                        newCollection.RemoveKey("source");

                        if (newCollection.Count > 0)
                        { // there is still some relevant information left.
                            collection.Add(new Feature(new Point((osmObject as Node).Coordinate),
                                new SimpleGeometryAttributeCollection(osmObject.Tags)));
                        }
                        break;
                    case CompleteOsmType.Way:
                        tags = osmObject.Tags;

                        bool isArea = false;
                        if ((tags.ContainsKey("building") && !tags.IsFalse("building")) ||
                            (tags.ContainsKey("landuse") && !tags.IsFalse("landuse")) ||
                            (tags.ContainsKey("amenity") && !tags.IsFalse("amenity")) ||
                            (tags.ContainsKey("harbour") && !tags.IsFalse("harbour")) ||
                            (tags.ContainsKey("historic") && !tags.IsFalse("historic")) ||
                            (tags.ContainsKey("leisure") && !tags.IsFalse("leisure")) ||
                            (tags.ContainsKey("man_made") && !tags.IsFalse("man_made")) ||
                            (tags.ContainsKey("military") && !tags.IsFalse("military")) ||
                            (tags.ContainsKey("natural") && !tags.IsFalse("natural")) ||
                            (tags.ContainsKey("office") && !tags.IsFalse("office")) ||
                            (tags.ContainsKey("place") && !tags.IsFalse("place")) ||
                            (tags.ContainsKey("power") && !tags.IsFalse("power")) ||
                            (tags.ContainsKey("public_transport") && !tags.IsFalse("public_transport")) ||
                            (tags.ContainsKey("shop") && !tags.IsFalse("shop")) ||
                            (tags.ContainsKey("sport") && !tags.IsFalse("sport")) ||
                            (tags.ContainsKey("tourism") && !tags.IsFalse("tourism")) ||
                            (tags.ContainsKey("waterway") && !tags.IsFalse("waterway")) ||
                            (tags.ContainsKey("wetland") && !tags.IsFalse("wetland")) ||
                            (tags.ContainsKey("water") && !tags.IsFalse("water")) ||
                            (tags.ContainsKey("aeroway") && !tags.IsFalse("aeroway")))
                        { // these tags usually indicate an area.
                            isArea = true;
                        }

                        if (tags.IsTrue("area"))
                        { // explicitly indicated that this is an area.
                            isArea = true;
                        }
                        else if (tags.IsFalse("area"))
                        { // explicitly indicated that this is not an area.
                            isArea = false;
                        }

                        if (isArea)
                        { // area tags leads to simple polygon
                            var lineairRing = new Feature(new LineairRing((osmObject as CompleteWay).GetCoordinates().ToArray<GeoCoordinate>()),
                                new SimpleGeometryAttributeCollection(tags));
                            collection.Add(lineairRing);
                        }
                        else
                        { // no area tag leads to just a line.
                            var lineString = new Feature(new LineString((osmObject as CompleteWay).GetCoordinates().ToArray<GeoCoordinate>()),
                                new SimpleGeometryAttributeCollection(tags));
                            collection.Add(lineString);
                        }
                        break;
                    case CompleteOsmType.Relation:
                        var relation = (osmObject as CompleteRelation);
                        tags = relation.Tags;

                        string typeValue;
                        if (tags.TryGetValue("type", out typeValue))
                        { // there is a type in this relation.
                            if (typeValue == "multipolygon")
                            { // this relation is a multipolygon.
                                var feature = this.InterpretMultipolygonRelation(relation);
                                if (feature != null)
                                { // add the geometry.
                                    collection.Add(feature);
                                }
                            }
                            else if (typeValue == "boundary")
                            { // this relation is a boundary.

                            }
                        }
                        break;
                }
            }
            return collection;
        }
Exemplo n.º 45
0
        /// <summary>${iServer2_Query_Recordset_method_toFeatureSet_D}</summary>
        public FeatureCollection ToFeatureSet()
        {
            FeatureCollection featureSet = new FeatureCollection();
            if (this.Records == null)
            {
                return featureSet;
            }
            foreach (Record record in this.Records)
            {
                Feature feature = new Feature();

                ServerGeometry shape = record.Shape;
                if (shape != null)
                {
                    switch (shape.Feature)
                    {
                        case ServerFeatureType.Unknown:
                            break;
                        case ServerFeatureType.Point:
                            feature.Geometry = shape.ToGeoPoint();
                            break;
                        case ServerFeatureType.Line:
                            feature.Geometry = shape.ToGeoLine();
                            break;
                        case ServerFeatureType.Polygon:
                            feature.Geometry = shape.ToGeoRegion();
                            break;
                        case ServerFeatureType.Text:
                            break;
                        case ServerFeatureType.LineM:
                            break;
                        default:
                            feature.Geometry = null;
                            break;
                    }
                }
                //List<string> values = record.FieldValues;
                //List<string> key = this.ReturnFields; //没有用Caption

                if (record.FieldValues != null)
                {
                    for (int i = 0; i < this.ReturnFields.Count; i++)
                    {
                        feature.Attributes.Add(this.ReturnFields[i], record.FieldValues[i]);
                    }
                }
                featureSet.Add(feature);
            }
            return featureSet;
        }
Exemplo n.º 46
0
        /// <summary>
        /// Activates or deactivates a site collection or web scoped feature
        /// </summary>
        /// <param name="features">Feature Collection which contains the feature</param>
        /// <param name="featureID">ID of the feature to activate/deactivate</param>
        /// <param name="activate">True to activate, false to deactivate the feature</param>
        /// <param name="scope">Scope of the feature definition</param>
        private static void ProcessFeatureInternal(FeatureCollection features, Guid featureID, bool activate, FeatureDefinitionScope scope)
        {
            features.Context.Load(features);
            features.Context.ExecuteQueryRetry();

            // The original number of active features...use this to track if the feature activation went OK
            int oldCount = features.Count();

            if (activate)
            {
                // GetById does not seem to work for site scoped features...if (clientSiteFeatures.GetById(featureID) == null)

                // FeatureDefinitionScope defines how the features have been deployed. All OOB features are farm deployed
                features.Add(featureID, true, scope);
                features.Context.ExecuteQueryRetry();

                // retry logic needed to make this more bulletproof :-(
                features.Context.Load(features);
                features.Context.ExecuteQueryRetry();

                int tries = 0;
                int currentCount = features.Count();
                while (currentCount <= oldCount && tries < 5)
                {
                    tries++;
                    features.Add(featureID, true, scope);
                    features.Context.ExecuteQueryRetry();
                    features.Context.Load(features);
                    features.Context.ExecuteQueryRetry();
                    currentCount = features.Count();
                }
            }
            else
            {
                try
                {
                    features.Remove(featureID, false);
                    features.Context.ExecuteQueryRetry();
                }
                catch (Exception ex)
                {
                    Log.Error(Constants.LOGGING_SOURCE, CoreResources.FeatureExtensions_FeatureActivationProblem, featureID, ex.Message);
                }
            }
        }
Exemplo n.º 47
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);
         }
     }
 }
Exemplo n.º 48
0
        /// <summary>
        /// Activates or deactivates a site collection or web scoped feature
        /// </summary>
        /// <param name="features">Feature Collection which contains the feature</param>
        /// <param name="featureID">ID of the feature to activate/deactivate</param>
        /// <param name="activate">True to activate, false to deactivate the feature</param>
        /// <param name="scope">Scope of the feature definition</param>
        /// <param name="pollingIntervalSeconds">The time in seconds between polls for "IsActive"</param>
        private static void ProcessFeatureInternal(FeatureCollection features, Guid featureID, bool activate, FeatureDefinitionScope scope, int pollingIntervalSeconds = 30)
        {
            if (activate)
            {
                // Feature enabling can take a long time, especially in case of the publishing feature...so let's make it more reliable
                features.Add(featureID, true, scope);

                if (pollingIntervalSeconds < 5)
                {
                    pollingIntervalSeconds = 5;
                }

                try
                {
                    string clientTag = $"{PnPCoreUtilities.PnPCoreVersionTag}:ProcessFeatureInternal";
                    if (clientTag.Length > 32)
                    {
                        clientTag = clientTag.Substring(0, 32);
                    }
                    features.Context.ClientTag = clientTag;
                    // Don't update this to ExecuteQueryRetry
                    features.Context.ExecuteQuery();
                    Log.Info(Constants.LOGGING_SOURCE, CoreResources.FeatureExtensions_ProcessFeatureInternal_FeatureActive, featureID);
                }
                catch (Exception ex)
                {
                    Log.Info(Constants.LOGGING_SOURCE, CoreResources.FeatureExtensions_ProcessFeatureInternal_FeatureException, ex.ToString());

                    // Don't wait for a "feature not found" exception, which is the typical exception we'll see
                    if (ex.HResult != -2146233088)
                    {
                        int retryAttempts = 10;
                        int retryCount = 0;

                        // wait and keep checking if the feature is active
                        while (retryAttempts > retryCount)
                        {
                            Thread.Sleep(TimeSpan.FromSeconds(pollingIntervalSeconds));
                            if (IsFeatureActiveInternal(features, featureID, true))
                            {
                                retryCount = retryAttempts;
                                Log.Info(Constants.LOGGING_SOURCE, CoreResources.FeatureExtensions_ProcessFeatureInternal_FeatureActivationState, true, featureID);
                            }
                            else
                            {
                                retryCount++;
                                Log.Info(Constants.LOGGING_SOURCE, CoreResources.FeatureExtensions_ProcessFeatureInternal_FeatureActivationState, false, featureID);
                            }
                        }
                    }
                }
            }
            else
            {
                try
                {
                    features.Remove(featureID, false);
                    features.Context.ExecuteQueryRetry();
                }
                catch (Exception ex)
                {
                    Log.Error(Constants.LOGGING_SOURCE, CoreResources.FeatureExtensions_FeatureActivationProblem, featureID, ex.Message);
                }
            }
        }
        /// <summary>
        /// Generates a feature collection with one LineString per instruction and all poi's as Points.
        /// </summary>
        /// <returns></returns>
        private FeatureCollection GetFeatures(Route route, List<Instruction> instructions)
        {
            var featureCollection = new FeatureCollection();
            for (int i = 0; i < instructions.Count; i++)
            {
                var instruction = instructions[i];
                var coordinates = new List<GeoCoordinate>();
                for (int segmentIdx = instruction.FirstSegmentIdx; segmentIdx <= instruction.LastSegmentIdx; segmentIdx++)
                {
                    coordinates.Add(new GeoCoordinate(route.Segments[segmentIdx].Latitude, route.Segments[segmentIdx].Longitude));
                }

                // build attributes.
                var currentArcTags = instruction.MetaData;
                var attributesTable = new SimpleGeometryAttributeCollection();
                if (currentArcTags != null)
                { // there are tags.
                    foreach (var tag in currentArcTags)
                    {
                        if (tag.Value != null)
                        {
                            var t = tag.Value.GetType();
                            if (t.IsPrimitive || t == typeof(Decimal) || t == typeof(String))
                            {
                                attributesTable.Add(tag.Key, tag.Value);
                            }
                        }
                    }
                }

                // build feature.
                var lineString = new LineString(coordinates);
                featureCollection.Add(new Feature(lineString, attributesTable));

                // build poi-features if any.
                if (instruction.Pois != null)
                {
                    foreach (var poi in instruction.Pois)
                    {
                        // build attributes.
                        var poiTags = poi.Tags;
                        var poiAttributesTable = new SimpleGeometryAttributeCollection();
                        if (poiTags != null)
                        { // there are tags.
                            foreach (var tag in poiTags)
                            {
                                poiAttributesTable.Add(tag.Key, tag.Value);
                            }
                        }

                        // build feature.
                        var point = new Point(poi.Location);
                        featureCollection.Add(new Feature(point, poiAttributesTable));
                    }
                }
            }
            return featureCollection;
        }
        /// <summary>
        /// Creates the multi modal nancy module.
        /// </summary>
        public MultimodalModule()
        {
            JsonSettings.MaxJsonLength = Int32.MaxValue;

            Get["{instance}/multimodal"] = _ =>
            {
                this.EnableCors();

                // get request id.
                ulong requestId = MultimodalModule.GetRequestId();

                // get instance and check if active.
                string instance = _.instance;
                if (!ApiBootstrapper.IsActive(instance))
                { // oeps, instance not active!
                    return Negotiate.WithStatusCode(HttpStatusCode.NotFound);
                }

                // check transit support.
                if (!ApiBootstrapper.Get(instance).TransitSupport)
                { // not found, this is not active!
                    return Negotiate.WithStatusCode(HttpStatusCode.NotFound);
                }

                var startTicks = DateTime.Now.Ticks;
                OsmSharp.Logging.Log.TraceEvent(string.Format("MultimodalModal.{0}", instance), OsmSharp.Logging.TraceEventType.Information,
                    string.Format("Multimodal request #{1} from {0}.", this.Request.UserHostAddress, requestId));
                try
                {
                    // bind the query if any.
                    var query = this.Bind<RoutingQuery>();

                    // parse location.
                    if (string.IsNullOrWhiteSpace(query.loc))
                    { // no loc parameters.
                        return Negotiate.WithStatusCode(HttpStatusCode.NotAcceptable).WithModel("loc parameter not found or request invalid.");
                    }
                    var locs = query.loc.Split(',');
                    if (locs.Length < 2)
                    { // less than two loc parameters.
                        return Negotiate.WithStatusCode(HttpStatusCode.NotAcceptable).WithModel("only one loc parameter found or request invalid.");
                    }
                    var coordinates = new GeoCoordinate[locs.Length / 2];
                    for (int idx = 0; idx < coordinates.Length; idx++)
                    {
                        double lat, lon;
                        if (double.TryParse(locs[idx * 2], System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out lat) &&
                            double.TryParse(locs[idx * 2 + 1], System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out lon))
                        { // parsing was successful.
                            coordinates[idx] = new GeoCoordinate(lat, lon);
                        }
                        else
                        { // invalid formatting.
                            return Negotiate.WithStatusCode(HttpStatusCode.NotAcceptable).WithModel("location coordinates are invalid.");
                        }
                    }

                    // get vehicle.
                    string vehicleName = "car"; // assume car is the default.
                    if (!string.IsNullOrWhiteSpace(query.vehicle))
                    { // a vehicle was defined.
                        vehicleName = query.vehicle;
                    }
                    var vehicles = new List<Vehicle>();
                    var vehicleNames = vehicleName.Split('|');
                    for (int idx = 0; idx < vehicleNames.Length; idx++)
                    {
                        var vehicle = Vehicle.GetByUniqueName(vehicleNames[idx]);
                        if (vehicle == null)
                        { // vehicle not found or not registered.
                            return Negotiate.WithStatusCode(HttpStatusCode.NotAcceptable).WithModel(string.Format("vehicle with name '{0}' not found.", vehicleName));
                        }
                        vehicles.Add(vehicle);
                    }

                    // get operators.
                    HashSet<string> operators = null;
                    if (query.operators != null)
                    { // a vehicle was defined.
                        operators = new HashSet<string>();
                        var operatorNames = query.operators.Split('|');
                        for (int idx = 0; idx < operatorNames.Length; idx++)
                        {
                            operators.Add(operatorNames[idx]);
                        }
                    }

                    bool instructions = false;
                    if (!string.IsNullOrWhiteSpace(query.instructions))
                    { // there is an instruction flag.
                        instructions = query.instructions == "true";
                    }

                    bool complete = false;
                    if (!string.IsNullOrWhiteSpace(query.complete))
                    { // there is a complete flag.
                        complete = query.complete == "true";
                    }

                    bool fullFormat = false;
                    if (!string.IsNullOrWhiteSpace(query.format))
                    { // there is a format field.
                        fullFormat = query.format == "osmsharp";
                    }

                    bool departure = false;
                    if (!string.IsNullOrWhiteSpace(query.departure))
                    { // there is a format field.
                        departure = query.departure == "true";
                    }

                    // check conflicting parameters.
                    if (!complete && instructions)
                    { // user wants an incomplete route but instructions, this is impossible.
                        complete = true;
                    }

                    // parse time.
                    if (string.IsNullOrWhiteSpace(query.time))
                    { // there is a format field.
                        return Negotiate.WithStatusCode(HttpStatusCode.NotAcceptable).WithModel("No valid time parameter found.");
                    }
                    DateTime dt;
                    string pattern = "yyyyMMddHHmm";
                    if (!DateTime.TryParseExact(query.time, pattern, CultureInfo.InvariantCulture,
                                               DateTimeStyles.None,
                                               out dt))
                    { // could not parse date.
                        return Negotiate.WithStatusCode(HttpStatusCode.NotAcceptable).WithModel(
                            string.Format("No valid time parameter found, could not parse date: {0}. Expected to be in format yyyyMMddHHmm."));
                    }

                    var aggregationType = RouteAggregationType.All;
                    if (!string.IsNullOrWhiteSpace(query.aggregate))
                    { // there is an aggregation field.
                        switch (query.aggregate.ToLowerInvariant())
                        {
                            case "instructions":
                                aggregationType = RouteAggregationType.Instructions;
                                break;
                            case "modal":
                                aggregationType = RouteAggregationType.Modal;
                                break;
                        }
                    }

                    bool otm = false;
                    if (!string.IsNullOrWhiteSpace(query.type))
                    { // custom type of routing request.
                        if (query.type == "otm")
                        {
                            otm = true;
                        }
                    }

                    if (!otm)
                    {
                        // calculate route.
                        var route = ApiBootstrapper.Get(instance).GetTransitRoute(dt, vehicles, coordinates, operators, complete);
                        var endTicks = DateTime.Now.Ticks;
                        OsmSharp.Logging.Log.TraceEvent("MultimodalModal", OsmSharp.Logging.TraceEventType.Information,
                            string.Format("Multimodal request #{1} from {0} finished in {2}ms.", this.Request.UserHostAddress, requestId,
                                (new TimeSpan(endTicks - startTicks)).TotalMilliseconds.ToInvariantString()));

                        if (route == null)
                        { // route could not be calculated.
                            return null;
                        }
                        if (route != null && instructions)
                        { // also calculate instructions.
                            var instruction = ApiBootstrapper.Get(instance).GetInstructions(route);

                            if (fullFormat)
                            {
                                return Negotiate.WithStatusCode(HttpStatusCode.OK).WithModel(new CompleteRoute()
                                {
                                    Route = route,
                                    Instructions = instruction
                                });
                            }
                            else
                            { // return a GeoJSON object.
                                var featureCollection = ApiBootstrapper.Get(instance).GetFeatures(route, aggregationType);
                                return Negotiate.WithStatusCode(HttpStatusCode.OK).WithModel(featureCollection);
                            }
                        }
                        if (fullFormat)
                        { // return a complete route but no instructions.
                            return Negotiate.WithStatusCode(HttpStatusCode.OK).WithModel(route);
                        }
                        else
                        { // return a GeoJSON object.
                            var featureCollection = ApiBootstrapper.Get(instance).GetFeatures(route, aggregationType);
                            return Negotiate.WithStatusCode(HttpStatusCode.OK).WithModel(featureCollection);
                        }
                    }
                    else
                    {
                        // calculate route.
                        var routes = ApiBootstrapper.Get(instance).GetTransitOneToMany(dt, vehicles, coordinates, operators, complete);
                        if (routes == null)
                        { // route could not be calculated.
                            return null;
                        }
                        if (routes != null && instructions)
                        { // also calculate instructions.
                            if (fullFormat)
                            {
                                throw new NotSupportedException();
                            }
                            else
                            { // return a GeoJSON object.
                                var featureCollection = new FeatureCollection();
                                foreach (var route in routes)
                                {
                                    if (route != null)
                                    {
                                        var routeFeatures = ApiBootstrapper.Get(instance).GetFeatures(route, aggregationType);
                                        if (routeFeatures != null)
                                        {
                                            foreach (var feature in routeFeatures)
                                            {
                                                featureCollection.Add(feature);
                                            }
                                        }
                                    }
                                }
                                return Negotiate.WithStatusCode(HttpStatusCode.OK).WithModel(featureCollection);
                            }
                        }

                        if (fullFormat)
                        {
                            return Negotiate.WithStatusCode(HttpStatusCode.OK).WithModel(routes);
                        }
                        else
                        { // return a GeoJSON object.
                            var featureCollection = new FeatureCollection();
                            foreach (var route in routes)
                            {
                                if (route != null)
                                {
                                    var routeFeatures = ApiBootstrapper.Get(instance).GetFeatures(route, aggregationType);
                                    if (routeFeatures != null)
                                    {
                                        foreach (var feature in routeFeatures)
                                        {
                                            featureCollection.Add(feature);
                                        }
                                    }
                                }
                            }
                            return Negotiate.WithStatusCode(HttpStatusCode.OK).WithModel(featureCollection);
                        }
                    }
                }
                catch (Exception)
                { // an unhandled exception!
                    OsmSharp.Logging.Log.TraceEvent(string.Format("MultimodalModal.{0}", instance), OsmSharp.Logging.TraceEventType.Information,
                        string.Format("Multimodal request #{1} from {0} failed.", this.Request.UserHostAddress, requestId));
                    return Negotiate.WithStatusCode(HttpStatusCode.InternalServerError);
                }
            };
            Options["{instance}/multimodal/range"] = _ =>
            {
                this.EnableCors();

                // get instance and check if active.
                string instance = _.instance;
                if (!ApiBootstrapper.IsActive(instance))
                { // oeps, instance not active!
                    return Negotiate.WithStatusCode(HttpStatusCode.NotFound);
                }

                return Negotiate.WithStatusCode(HttpStatusCode.OK);
            };
            Get["{instance}/multimodal/range"] = _ =>
            {
                this.EnableCors();

                // get request id.
                ulong requestId = MultimodalModule.GetRequestId();

                // get instance and check if active.
                string instance = _.instance;
                if (!ApiBootstrapper.IsActive(instance))
                { // oeps, instance not active!
                    return Negotiate.WithStatusCode(HttpStatusCode.NotFound);
                }

                long requestStart = DateTime.Now.Ticks;

                OsmSharp.Logging.Log.TraceEvent(string.Format("MultimodalModal.{0}", instance), OsmSharp.Logging.TraceEventType.Information,
                    string.Format("Multimodal range request #{1} from {0}.", this.Request.UserHostAddress, requestId));
                try
                {

                    // bind the query if any.
                    var query = this.Bind<RangeQuery>();

                    // parse location.
                    if (string.IsNullOrWhiteSpace(query.loc))
                    { // no loc parameters.
                        return Negotiate.WithStatusCode(HttpStatusCode.NotAcceptable).WithModel("loc parameter not found or request invalid.");
                    }
                    var locs = query.loc.Split(',');
                    if (locs.Length < 2)
                    { // less than two loc parameters.
                        return Negotiate.WithStatusCode(HttpStatusCode.NotAcceptable).WithModel("only one loc parameter found or request invalid.");
                    }
                    var coordinates = new GeoCoordinate[locs.Length / 2];
                    for (int idx = 0; idx < coordinates.Length; idx++)
                    {
                        double lat, lon;
                        if (double.TryParse(locs[idx * 2], System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out lat) &&
                            double.TryParse(locs[idx * 2 + 1], System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out lon))
                        { // parsing was successful.
                            coordinates[idx] = new GeoCoordinate(lat, lon);
                        }
                        else
                        { // invalid formatting.
                            return Negotiate.WithStatusCode(HttpStatusCode.NotAcceptable).WithModel("location coordinates are invalid.");
                        }
                    }

                    // get vehicle.
                    string vehicleName = "car"; // assume car is the default.
                    if (!string.IsNullOrWhiteSpace(query.vehicle))
                    { // a vehicle was defined.
                        vehicleName = query.vehicle;
                    }
                    var vehicles = new List<Vehicle>();
                    var vehicleNames = vehicleName.Split('|');
                    for (int idx = 0; idx < vehicleNames.Length; idx++)
                    {
                        var vehicle = Vehicle.GetByUniqueName(vehicleNames[idx]);
                        if (vehicle == null)
                        { // vehicle not found or not registered.
                            return Negotiate.WithStatusCode(HttpStatusCode.NotAcceptable).WithModel(string.Format("vehicle with name '{0}' not found.", vehicleName));
                        }
                        vehicles.Add(vehicle);
                    }

                    // parse time.
                    if (string.IsNullOrWhiteSpace(query.time))
                    { // there is a format field.
                        return Negotiate.WithStatusCode(HttpStatusCode.NotAcceptable).WithModel("No valid time parameter found.");
                    }
                    DateTime dt;
                    string pattern = "yyyyMMddHHmm";
                    if (!DateTime.TryParseExact(query.time, pattern, CultureInfo.InvariantCulture,
                                               DateTimeStyles.None,
                                               out dt))
                    { // could not parse date.
                        return Negotiate.WithStatusCode(HttpStatusCode.NotAcceptable).WithModel(
                            string.Format("No valid time parameter found, could not parse date: {0}. Expected to be in format yyyyMMddHHmm."));
                    }

                    // calculate route.
                    int max;
                    if(!int.TryParse(query.max, out max))
                    {// could not parse date.
                        return Negotiate.WithStatusCode(HttpStatusCode.NotAcceptable).WithModel(
                            string.Format("No valid max time parameter found, could not parse: {0}.", query.max));
                    }
                    int zoom;
                    if (!int.TryParse(query.zoom, out zoom))
                    {// could not parse date.
                        zoom = 16;
                    }
                    var range = ApiBootstrapper.Get(instance).GetWithinRange(dt, vehicles, coordinates[0], max, zoom);
                    long afterRequest = DateTime.Now.Ticks;
                    OsmSharp.Logging.Log.TraceEvent(string.Format("MultimodalModal.{0}", instance), OsmSharp.Logging.TraceEventType.Information,
                        string.Format("Multimodal range request #{1} from {0} finished after {2}ms.", this.Request.UserHostAddress, requestId, (new TimeSpan(afterRequest - requestStart)).TotalMilliseconds));

                    // output all vertex and times.
                    var vertexAndTimes = new List<VertexAndTime>();
                    foreach (var rangeEntry in range)
                    {
                        double time = max - rangeEntry.Item3;
                        if (time > 0)
                        {
                            time = (int)((time / max) * 100) + 25;
                            vertexAndTimes.Add(new VertexAndTime()
                                {
                                    lat = rangeEntry.Item1.Latitude,
                                    lon = rangeEntry.Item1.Longitude,
                                    value = time,
                                    id = rangeEntry.Item2
                                });
                        }
                    }
                    return Negotiate.WithStatusCode(HttpStatusCode.OK).WithModel(new OsmSharp.Service.Routing.Multimodal.Domain.Queries.Range()
                        {
                            max = 125,
                            data = vertexAndTimes.ToArray()
                        });
                }
                catch (Exception)
                { // an unhandled exception!
                    OsmSharp.Logging.Log.TraceEvent(string.Format("MultimodalModal.{0}", instance), OsmSharp.Logging.TraceEventType.Information,
                        string.Format("Multimodal range request #{1} from {0} failed.", this.Request.UserHostAddress, requestId));
                    return Negotiate.WithStatusCode(HttpStatusCode.InternalServerError);
                }
            };
            Get["{instance}/alongjustone"] = _ =>
            {
                this.EnableCors();

                // get request id.
                var requestId = MultimodalModule.GetRequestId();

                // get instance and check if active.
                string instance = _.instance;
                if (!ApiBootstrapper.IsActive(instance))
                { // oeps, instance not active!
                    return Negotiate.WithStatusCode(HttpStatusCode.NotFound);
                }

                OsmSharp.Logging.Log.TraceEvent(string.Format("MultimodalModal.{0}", instance), OsmSharp.Logging.TraceEventType.Information,
                    string.Format("Along just one request #{1} from {0}.", this.Request.UserHostAddress, requestId));
                try
                {
                    // bind the query if any.
                    var query = this.Bind<RoutingQuery>();

                    // parse location.
                    if (string.IsNullOrWhiteSpace(query.loc))
                    { // no loc parameters.
                        return Negotiate.WithStatusCode(HttpStatusCode.NotAcceptable).WithModel("loc parameter not found or request invalid.");
                    }
                    var locs = query.loc.Split(',');
                    if (locs.Length < 6)
                    { // less than two loc parameters.
                        return Negotiate.WithStatusCode(HttpStatusCode.NotAcceptable).WithModel("only two loc parameter found or request invalid.");
                    }
                    var coordinates = new GeoCoordinate[locs.Length / 2];
                    for (int idx = 0; idx < coordinates.Length; idx++)
                    {
                        double lat, lon;
                        if (double.TryParse(locs[idx * 2], System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out lat) &&
                            double.TryParse(locs[idx * 2 + 1], System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out lon))
                        { // parsing was successful.
                            coordinates[idx] = new GeoCoordinate(lat, lon);
                        }
                        else
                        { // invalid formatting.
                            return Negotiate.WithStatusCode(HttpStatusCode.NotAcceptable).WithModel("location coordinates are invalid.");
                        }
                    }

                    // get vehicle.
                    string vehicleName = "car"; // assume car is the default.
                    if (!string.IsNullOrWhiteSpace(query.vehicle))
                    { // a vehicle was defined.
                        vehicleName = query.vehicle;
                    }
                    var vehicles = new List<Vehicle>();
                    var vehicleNames = vehicleName.Split('|');
                    for (int idx = 0; idx < vehicleNames.Length; idx++)
                    {
                        var vehicle = Vehicle.GetByUniqueName(vehicleNames[idx]);
                        if (vehicle == null)
                        { // vehicle not found or not registered.
                            return Negotiate.WithStatusCode(HttpStatusCode.NotAcceptable).WithModel(string.Format("vehicle with name '{0}' not found.", vehicleName));
                        }
                        vehicles.Add(vehicle);
                    }

                    if(vehicles.Count > 2)
                    {
                        return Negotiate.WithStatusCode(HttpStatusCode.NotAcceptable).WithModel("More than two vehicle profiles found.");
                    }

                    bool instructions = false;
                    if (!string.IsNullOrWhiteSpace(query.instructions))
                    { // there is an instruction flag.
                        instructions = query.instructions == "true";
                    }

                    bool complete = false;
                    if (!string.IsNullOrWhiteSpace(query.complete))
                    { // there is a complete flag.
                        complete = query.complete == "true";
                    }

                    bool fullFormat = false;
                    if (!string.IsNullOrWhiteSpace(query.format))
                    { // there is a format field.
                        fullFormat = query.format == "osmsharp";
                    }

                    bool departure = false;
                    if (!string.IsNullOrWhiteSpace(query.departure))
                    { // there is a format field.
                        departure = query.departure == "true";
                    }

                    // check conflicting parameters.
                    if (!complete && instructions)
                    { // user wants an incomplete route but instructions, this is impossible.
                        complete = true;
                    }

                    var aggregationType = RouteAggregationType.All;
                    if (!string.IsNullOrWhiteSpace(query.aggregate))
                    { // there is an aggregation field.
                        switch (query.aggregate.ToLowerInvariant())
                        {
                            case "instructions":
                                aggregationType = RouteAggregationType.Instructions;
                                break;
                            case "modal":
                                aggregationType = RouteAggregationType.Modal;
                                break;
                        }
                    }

                    // calculate route.
                    var route = ApiBootstrapper.Get(instance).GetRouteAlongOne(vehicles, coordinates);
                    OsmSharp.Logging.Log.TraceEvent("MultimodalModal", OsmSharp.Logging.TraceEventType.Information,
                        string.Format("Along one request #{1} from {0} finished.", this.Request.UserHostAddress, requestId));

                    if (route == null)
                    { // route could not be calculated.
                        return null;
                    }
                    if (route != null && instructions)
                    { // also calculate instructions.
                        if (fullFormat)
                        {
                            var instruction = ApiBootstrapper.Get(instance).GetInstructions(route);
                            return Negotiate.WithStatusCode(HttpStatusCode.OK).WithModel(new CompleteRoute()
                            {
                                Route = route,
                                Instructions = instruction
                            });
                        }
                        else
                        {// return a GeoJSON object.
                            var featureCollection = ApiBootstrapper.Get(instance).GetFeatures(route, aggregationType);
                            return Negotiate.WithStatusCode(HttpStatusCode.OK).WithModel(featureCollection);
                        }
                    }

                    if (fullFormat)
                    { // return a complete route but no instructions.
                        return Negotiate.WithStatusCode(HttpStatusCode.OK).WithModel(route);
                    }
                    else
                    { // return a GeoJSON object.
                        var featureCollection = ApiBootstrapper.Get(instance).GetFeatures(route, aggregationType);

                        return Negotiate.WithStatusCode(HttpStatusCode.OK).WithModel(featureCollection);
                    }
                }
                catch (Exception)
                { // an unhandled exception!
                    OsmSharp.Logging.Log.TraceEvent(string.Format("MultimodalModal.{0}", instance), OsmSharp.Logging.TraceEventType.Information,
                        string.Format("Multimodal request #{1} from {0} failed.", this.Request.UserHostAddress, requestId));
                    return Negotiate.WithStatusCode(HttpStatusCode.InternalServerError);
                }
            };
            Get["{instance}/multimodal/status"] = _ =>
            {
                // get instance and check if active.
                string instance = _.instance;

                if (ApiBootstrapper.IsActive(instance))
                {
                    return Negotiate.WithStatusCode(HttpStatusCode.OK).WithModel(new Status()
                    {
                        Available = true,
                        Info = "Initialized."
                    });
                }
                return Negotiate.WithStatusCode(HttpStatusCode.OK).WithModel(new Status()
                {
                    Available = false,
                    Info = "Not initialized."
                });
            };
            Get["{instance}/multimodal/network"] = _ =>
            {
                // get instance and check if active.
                string instance = _.instance;
                if (!ApiBootstrapper.IsActive(instance))
                { // oeps, instance not active!
                    return Negotiate.WithStatusCode(HttpStatusCode.NotFound);
                }

                try
                {
                    this.EnableCors();

                    // get request id.
                    ulong requestId = MultimodalModule.GetRequestId();

                    // bind the query if any.
                    var query = this.Bind<BoxQuery>();

                    double left, right, top, bottom;
                    if (string.IsNullOrWhiteSpace(query.left) ||
                        !double.TryParse(query.left, System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out left))
                    {
                        return Negotiate.WithStatusCode(HttpStatusCode.NotAcceptable).WithModel("box coordinates are invalid.");
                    }
                    if (string.IsNullOrWhiteSpace(query.right) ||
                        !double.TryParse(query.right, System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out right))
                    {
                        return Negotiate.WithStatusCode(HttpStatusCode.NotAcceptable).WithModel("box coordinates are invalid.");
                    }
                    if (string.IsNullOrWhiteSpace(query.top) ||
                        !double.TryParse(query.top, System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out top))
                    {
                        return Negotiate.WithStatusCode(HttpStatusCode.NotAcceptable).WithModel("box coordinates are invalid.");
                    }
                    if (string.IsNullOrWhiteSpace(query.bottom) ||
                        !double.TryParse(query.bottom, System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out bottom))
                    {
                        return Negotiate.WithStatusCode(HttpStatusCode.NotAcceptable).WithModel("box coordinates are invalid.");
                    }

                    var features = ApiBootstrapper.Get(instance).GetNeworkFeatures(new GeoCoordinateBox(new GeoCoordinate(top, left), new GeoCoordinate(bottom, right)));
                    return OsmSharp.Geo.Streams.GeoJson.GeoJsonConverter.ToGeoJson(features);
                }
                catch (Exception)
                { // an unhandled exception!
                    return Negotiate.WithStatusCode(HttpStatusCode.InternalServerError);
                }
            };
        }