Ejemplo n.º 1
0
        public GPSData Read(TextReader reader)
        {
            reader.ThrowIfNull("reader");

            var data = new GPSData();
            var gpx = LoadGpx(reader);
            foreach (var track in gpx.trk)
            {
                var way = new Way();
                foreach (var trackSegment in track.trkseg)
                {
                    foreach (var trackPoint in trackSegment.trkpt)
                    {
                        way.Add(new WayPoint
                        {
                            Latitude = trackPoint.lat,
                            Longitude = trackPoint.lon,
                            Elevation = trackPoint.eleSpecified ? (decimal?)trackPoint.ele : null
                        });
                    }
                }
                data.Add(way);
            }
            return data;
        }
Ejemplo n.º 2
0
	void Start()
	{
		// Initialize the variables
		leftBottomPosition = new Vector2(-1,-1);
		hDistance = widthInCells;
		vDistance = heightInCells;
		way = Way.North;
		
		// Check if any wall placing item has height more then 1, throw error
		if(onWalls)
		{
			if(heightInCells > 1)
			{
				Debug.LogError("Item No: "+no+" and Item Name: "+name+" must have Height: 1");
			}
		}
		// Check if any wall placing item has other then four type way type, throw error
		if(onWalls)
		{
			if(wayType != WayType.FourWay)
			{
				Debug.LogError("Item No: "+no+" and Item Name: "+name+" must have Way Type: Four Way");
			}
		}
	}
Ejemplo n.º 3
0
 /// <summary>
 /// Processes the given way.
 /// </summary>
 /// <param name="way"></param>
 public override void AddWay(Way way)
 {
     if (way.Tags != null)
     {
         _tagsIndex.Add(way.Tags);
     }
 }
Ejemplo n.º 4
0
 public LimitOrder(Market market, Way way, decimal price, int quantity, bool allowPartialExecution)
 {
     this.Market = market;
     this.AllowPartialExecution = allowPartialExecution;
     this.Way = way;
     this.Price = price;
     this.Quantity = quantity;
 }
Ejemplo n.º 5
0
    static void Main(string[] args)
    {


      Way w = new Way();
      
      
    }
Ejemplo n.º 6
0
 public OrderDescription(Market targetMarket, Way orderWay, int quantity, decimal orderPrice, bool allowPartial)
 {
     this.TargetMarket = targetMarket;
     this.OrderWay = orderWay;
     this.Quantity = quantity;
     this.OrderPrice = orderPrice;
     this.AllowPartial = allowPartial;
 }
 public InvestorInstructionDto(InvestorInstructionIdentifierDto uniqueIdentifier, Way way, int quantity, decimal price, bool allowPartialExecution = false, DateTime? goodTill = null)
 {
     this.UniqueIdentifier = uniqueIdentifier;
     this.Way = way;
     this.Quantity = quantity;
     this.Price = price;
     this.AllowPartialExecution = allowPartialExecution;
     this.GoodTill = goodTill;
 }
Ejemplo n.º 8
0
        /// <summary>
        /// A Slide transition.
        /// </summary>
        /// <param name="sceneManager">The SceneManager</param>
        /// <paramparam name="direction">The Way to slide. Use the Way enumeration</paramparam>
        public Slide(ScreenManager sceneManager, Way way)
            : base(sceneManager)
        {
            this.way = way;
            this.waitTime = 300;

            if ((int)way > 1)
                direction = -1;

            SwitchWay(way);
        }
Ejemplo n.º 9
0
        public void Constructor_ID_CreatesNewEmptyWayAndInitializesProperties()
        {
            int id = 11;

            Way target = new Way(id);

            Assert.Equal(id, target.ID);
            Assert.Equal(SRIDList.WSG84, target.Srid);
            Assert.Empty(target.Nodes);
            Assert.Empty(target.Tags);
            Assert.Null(target.Metadata);
        }
Ejemplo n.º 10
0
        public Slide(ScreenManager sceneManager, Way way, Texture2D texture)
            : base(sceneManager, texture)
        {
            this.way = way;
            this.waitTime = 300;

            if ((int)way > 1)
                direction = -1;

            SwitchWay(way);

            this.texture = texture;
        }
Ejemplo n.º 11
0
 public static byte[] GeoProcessingWay(Way way, GeoTypeOGC geoTypeOgc)
 {
     switch (geoTypeOgc)
     {
         case GeoTypeOGC.LineString:
             return GeoProcessing.ConstructLineString(way.Nodes, way);
             break;
         case GeoTypeOGC.Polygon:
             return GeoProcessing.ConstructPolygon(way.Nodes, way);
             break;
     }
     throw new TypeLoadException("Geo type " + geoTypeOgc + " using Way not supported");
 }
Ejemplo n.º 12
0
        /// <summary>
        /// Initializes a new instance of the WayInfo class with data from specific Way
        /// </summary>
        /// <param name="way">The way to get data from</param>
        public WayInfo(Way way)
        {
            if (way == null) {
                throw new ArgumentNullException("Way parameter cannot be null", "way");
            }

            this.ID = way.ID;
            this.Tags = way.Tags;
            this.Metadata = way.Metadata;

            this.Nodes = new List<int>(way.Nodes.Count);
            foreach (var node in way.Nodes) {
                this.Nodes.Add(node.ID);
            }
        }
Ejemplo n.º 13
0
        public void Constructor_ID_Nodes_CreatesWayAddsNodesAndInitializesProperties()
        {
            int id = 11;
            Way target = new Way(id, _nodes);

            Assert.Equal(id, target.ID);
            Assert.Equal(SRIDList.WSG84, target.Srid);
            Assert.Equal(_nodes.Count, target.Nodes.Count);
            for (int i = 0; i < _nodes.Count; i++) {
                Assert.Same(_nodes[i], target.Nodes[i]);
            }

            Assert.Empty(target.Tags);
            Assert.Null(target.Metadata);
        }
Ejemplo n.º 14
0
        public OsmDatabaseTests()
        {
            _nodeData = new Node[3];
            _nodeData[0] = new Node(1);
            _nodeData[1] = new Node(2);
            _nodeData[2] = new Node(3);

            _wayData = new Way[2];
            _wayData[0] = new Way(1, _nodeData);
            _wayData[1] = new Way(2, _nodeData.Skip(1));

            _relationData = new Relation[2];
            _relationData[0] = new Relation(1, new RelationMember[] { new RelationMember(_wayData[0], "way"), new RelationMember(_nodeData[0], "node") });
            _relationData[1] = new Relation(2, new RelationMember[] { new RelationMember(_relationData[0], "relation"), new RelationMember(_nodeData[0], "node") });

            _data = _nodeData.Concat<IOsmGeometry>(_wayData).Concat<IOsmGeometry>(_relationData).ToArray();
        }
Ejemplo n.º 15
0
 public Car(Graphics model, Graphics gc, Map map, CurrentPosition pos, Bitmap bmp)
 {
     this.model = model;
     this.gc = gc;
     this.map = map;
     carImg = Image.FromFile("menti.gif");
     currentX = initialX - 1;
     currentY = initialY - 1;
     this.pos = pos;
     this.pos.X = 1;
     this.pos.Y = 1;
     this.pos.VelocityX = 100;
     this.pos.VelocityY = 0;
     this.bmp = bmp;
     way = Way.LEFT;
     move();
 }
Ejemplo n.º 16
0
        void ParseMap()
        {
            var xml = new XmlDocument();
            xml.LoadXml(File.ReadAllText("../../map.xml"));
            var prs = xml.DocumentElement;
            //var list = xml.DocumentElement.SelectNodes("/node");
            //Debugger.Break();
            //var prs = XElement.Parse(File.ReadAllText("../../map.xml"));
            //var lms = prs.Elements("node").ToArray();

            var b = prs.SelectSingleNode("bounds");
            map.minlat = float.Parse(b.Attributes["minlat"].Value);
            map.minlon = float.Parse(b.Attributes["minlon"].Value);

            map.maxlat = float.Parse(b.Attributes["maxlat"].Value);
            map.maxlon = float.Parse(b.Attributes["maxlon"].Value);

            foreach (XmlNode xmlnode in prs.SelectNodes("node"))
            {
                Node n = new Node();
                n.id = int.Parse(xmlnode.Attributes["id"].Value);
                n.lat = float.Parse(xmlnode.Attributes["lat"].Value);
                n.lon = float.Parse(xmlnode.Attributes["lon"].Value);
                n.x = (n.lon - map.minlon) / (map.maxlon - map.minlon);
                n.y = (n.lat - map.minlat) / (map.maxlat - map.minlat);
                
                foreach (XmlNode tg in xmlnode.SelectNodes("tag"))
                {
                    n.tags.Add(new Tag { k = tg.Attributes["k"].Value });
                    n.tags.Add(new Tag { v = tg.Attributes["v"].Value });
                }
                map.nodes.Add(n);
            }
            foreach (XmlNode xmlnode in prs.SelectNodes("way"))
            {
                Way way = new Way();
                foreach (XmlNode nd in xmlnode.SelectNodes("nd"))
                {
                    var node = map.nodes.First(a => a.id == int.Parse(nd.Attributes["ref"].Value));
                    way.nodes.Add(node);
                }
                map.ways.Add(way);
            }
        }
Ejemplo n.º 17
0
        public IGameObject BuildWay(Tile tile, Rule rule, Way way)
        {
            // create parent object for waypoint. Use factory to handle object creation on proper thread.
            var parent = _gameObjectFactory.CreateNew("waypoints " + way.Id, tile.GameObject);
            foreach (var coordinate in way.Points)
            {
                // detect position
                var position = GeoProjection.ToMapCoordinate(tile.RelativeNullPoint, coordinate);
                var elevation = _elevationProvider.GetElevation(coordinate);

                // create new gameobject on main thread.
                Observable.Start(() =>
                {
                    var sphere = GameObject.CreatePrimitive(PrimitiveType.Sphere);
                    sphere.transform.position = new Vector3((float) position.X, elevation + 1, (float) position.Y);
                    sphere.transform.parent = parent.GetComponent<GameObject>().transform;
                }, Scheduler.MainThread);
            }
            // return null as we don't need to attach behaviours
            return null;
        }
Ejemplo n.º 18
0
    private void LoadWays()
    {
        foreach (XmlNode xmlnode in prs.SelectNodes("way"))
        {
            Way way = new Way();
            List<CPoint2D> points = new List<CPoint2D>();
            foreach (XmlNode nd in xmlnode.SelectNodes("nd"))
            {
                var id = int.Parse(nd.Attributes["ref"].Value);
                var node = map.nodes[id];
                way.nodes.Add(node);
                points.Add(new CPoint2D(node.x, node.y));
            }
            way.points = points;
            var cpolyShape = new CPolygonShape(way.points.ToArray());
            cpolyShape.CutEar();

            foreach (XmlNode tg in xmlnode.SelectNodes("tag"))
                way.tags.Add(new Tag { k = tg.Attributes["k"].Value, v = tg.Attributes["v"].Value });


            map.ways.Add(way);            
        }
    }
Ejemplo n.º 19
0
 public MarketOrder(Market market, Way buy, int quantity)
 {
     this.Market = market;
     this.buy = buy;
     this.quantity = quantity;
 }
Ejemplo n.º 20
0
    private void CreateGroundArea(Way w)
    {
        Vector3[] nodes = new Vector3[w.nodes.Count];
        Vector2[] xz = new Vector2[w.nodes.Count];

        float height = 0;

        if (w.height != 0)
            height = w.height;

        Vector3 centroid = new Vector3();
        for (int a = 0; a < w.nodes.Count; a++)
        {
            RaycastHit hit;
            Node n = w.nodes[a];
            nodes[a] = new Vector3((float)((n.easthing - offsetPositionX) / precision), 5000, (float)((n.northing - offsetPositionZ) / precision));
            if (Physics.Raycast(nodes[a], -Vector3.up, out hit, Mathf.Infinity, layerMask))
            {
                nodes[a].y = hit.point.y + height + 0.5f;
            }
            else
            {
                nodes[a].y = 1;
            }
            xz[a] = new Vector2((float)((n.easthing - offsetPositionX) / precision), (float)((n.northing - offsetPositionZ) / precision));
            centroid += nodes[a];
        }
        centroid /= w.nodes.Count;
        centroid.y += 1;

          //  Vector3 position = new Vector3(centroid.x, 5000, centroid.z);
        float baseHeight = 0;

        /*RaycastHit hit;
        if (Physics.Raycast(position, -Vector3.up, out hit, Mathf.Infinity, layerMask))
        {
            baseHeight = hit.point.y;
        }*/
        //centroid = new Vector3(centroid.x, centroid.y + baseHeight, centroid.z);
        GameObject build = new GameObject();
        //build.transform.position = new Vector3(0, centroid.y, 0);
        build.name = w.id.ToString();
        mapManager.mapHash.Add(w.id);
        wayList.Add(w.id);
        build.isStatic = true;
        build.transform.parent = this.transform;
        GameObject roof = new GameObject();
           // roof.transform.position = new Vector3(0, centroid.y, 0);
        roof.name = (2 * w.id).ToString();
        mapManager.mapHash.Add(2 * w.id);
        wayList.Add(2 * w.id);
        roof.isStatic = true;
        if (w.name != null)
        {
            GameObject label = new GameObject();
            FloatingLabel lb = label.AddComponent<FloatingLabel>();
            lb.text = w.name;
            lb.transform.position = centroid;
            lb.target = GameObject.FindGameObjectWithTag("Player").transform;
            label.transform.parent = build.transform;
        }
        roof.transform.parent = build.transform;

        Vector2[] xzRoof = new Vector2[w.nodes.Count - 1];

        for (int a = 0; a < xzRoof.Length; a++)
        {
            xzRoof[a] = xz[a];
        }

        Triangulator tr = new Triangulator(xzRoof);

        int[] indices = tr.Triangulate();
        // Create the mesh
        Mesh roofm = new Mesh();
        roofm.vertices = nodes;
        roofm.triangles = indices;

        Vector2[] uvs = new Vector2[nodes.Length];
        for (int a = 0; a < nodes.Length; a++)
        {
            if (a < nodes.Length - 1)
            {
                uvs[a] = new Vector2(Mathf.Abs(nodes[a].x) / nodes[nodes.Length - 1].x, Mathf.Abs(nodes[a].z) / nodes[nodes.Length - 1].x);
            }
            else
            {
                uvs[a] = new Vector2(1, 1);
            }
        }

        roofm.uv = uvs;
        roofm.RecalculateNormals();
        roofm.RecalculateBounds();

        roof.AddComponent(typeof(MeshRenderer));
        MeshFilter filter2 = roof.AddComponent(typeof(MeshFilter)) as MeshFilter;
        roof.AddComponent<MeshCollider>();
        filter2.mesh = roofm;
        if (w.type == WayType.Parking)
            roof.GetComponent<MeshRenderer>().material = Resources.Load("Materials/Parking Material") as Material;
        if (w.type == WayType.Park)
            roof.GetComponent<MeshRenderer>().material = Resources.Load("Materials/Park Material") as Material;
        if (w.type == WayType.RiverBank)
            roof.GetComponent<MeshRenderer>().material = Resources.Load("Materials/River Material") as Material;

        roof.transform.parent = transform;
    }
Ejemplo n.º 21
0
 /// <summary>
 /// Tries to get the way with the given id.
 /// </summary>
 /// <param name="id"></param>
 /// <param name="way"></param>
 /// <returns></returns>
 public abstract bool TryGetWay(long id, out Way way);
        /// <summary>
        /// Adds a way.
        /// </summary>
        /// <param name="way"></param>
        public override void AddWay(Way way)
        {
            DataRow way_row = _wayTable.NewRow();

            // format data and create parameters.
            long?id = way.Id.Value;  // id should always contain a value.

            way_row["id"] = id.ConvertToDBValue <long>();

            long?changeset_id = way.ChangeSetId;

            way_row["changeset_id"] = changeset_id.ConvertToDBValue <long>();

            if (!way.Visible.HasValue)
            {
                way_row["visible"] = DBNull.Value;
            }
            else
            {
                way_row["visible"] = way.Visible.Value ? 1 : 0;
            }

            DateTime?timestamp = way.TimeStamp;

            way_row["timestamp"] = timestamp.ConvertToDBValue <DateTime>();

            ulong?version = way.Version;

            way_row["version"] = version.ConvertToDBValue <ulong>();

            // set the usr
            way_row["usr"]    = way.UserName;
            way_row["usr_id"] = way.UserId.ConvertToDBValue <long>();

            // add the way and it's tags.
            _wayTable.Rows.Add(way_row);

            // tags.
            if (way.Tags != null)
            {
                foreach (Tag tag in way.Tags)
                {
                    string key   = tag.Key;
                    string value = tag.Value;

                    if (key == null || key.Length == 0)
                    {
                        //throw new Exception();
                    }
                    else
                    {
                        DataRow tag_row = _wayTagsTable.NewRow();
                        tag_row["way_id"] = id;
                        tag_row["key"]    = key.Truncate(255);
                        tag_row["value"]  = value.Truncate(255);

                        _wayTagsTable.Rows.Add(tag_row);
                    }
                }
            }

            // insert way nodes.
            if (way.Nodes != null)
            {
                long way_id = way.Id.Value;
                for (int idx = 0; idx < way.Nodes.Count; idx++)
                {
                    long node_id = way.Nodes[idx];

                    DataRow tag_row = _wayNodesTable.NewRow();
                    tag_row["way_id"]      = id;
                    tag_row["node_id"]     = node_id;
                    tag_row["sequence_id"] = idx;

                    _wayNodesTable.Rows.Add(tag_row);
                }
            }

            // bulk insert if needed.
            if (_wayTable.Rows.Count >= _batch_ways)
            {
                this.BulkCopy(_wayTable, "way", _batch_ways);
                this.BulkCopy(_wayTagsTable, "way_tags");
                this.BulkCopy(_wayNodesTable, "way_nodes");
                this.CreateWayTables();
            }
        }
Ejemplo n.º 23
0
        public MapElement(RepresentationConverter projection, Tile baseTile, Vector correctionVector, Way way)
        {
            this.Tile = baseTile;
            Tags      = way.Tags;
            IsClosed  = true;

            PathFigureCollection waySegments = new PathFigureCollection();

            foreach (var geoPointList in way.GeoPoints)
            {
                PathFigure waySegment = new PathFigure();
                waySegment.Segments = new PathSegmentCollection();
                var geoPointEnumerator = geoPointList.GetEnumerator();
                geoPointEnumerator.MoveNext();

                var mappoint = projection.GeoPointToMappoint(geoPointEnumerator.Current, baseTile.ZoomFactor);
                waySegment.StartPoint = (Point)mappoint - correctionVector;

                Point?lastPoint = null;
                while (geoPointEnumerator.MoveNext())
                {
                    mappoint  = projection.GeoPointToMappoint(geoPointEnumerator.Current, baseTile.ZoomFactor);
                    lastPoint = (Point)mappoint - correctionVector;
                    waySegment.Segments.Add(new LineSegment(lastPoint.Value, true));
                }
                waySegments.Add(waySegment);
                if (lastPoint == null || lastPoint.Value != waySegment.StartPoint)
                {
                    IsClosed = false;
                }
            }

            WayGeometry         = new PathGeometry();
            WayGeometry.Figures = waySegments;

            Point?mapPoint = way.LabelPosition == null ? (Point?)null : (Point)projection.GeoPointToMappoint(way.LabelPosition, baseTile.ZoomFactor);

            Position = mapPoint == null ? null : (mapPoint + correctionVector);

            RenderInstructions = new List <RenderInstruction>();
        }
Ejemplo n.º 24
0
        internal static Way ConvertToSimple(Osm.Xml.v0_6.way wa)
        {
            Way way = new Way();

            // set id
            if (wa.idSpecified)
            {
                way.Id = wa.id;
            }

            // set changeset.
            if (wa.changesetSpecified)
            {
                way.ChangeSetId = wa.changeset;
            }

            // set visible.
            if (wa.visibleSpecified)
            {
                way.Visible = wa.visible;
            }
            else
            { // if visible is not specified it is default true.
                way.Visible = true;
            }

            // set timestamp.
            if (wa.timestampSpecified)
            {
                way.TimeStamp = wa.timestamp;
            }

            // set uid
            if (wa.uidSpecified)
            {
                way.UserId = wa.uid;
            }

            // set version
            if (wa.versionSpecified)
            {
                way.Version = wa.version;
            }

            // set user
            way.UserName = wa.user;

            // set tags.
            way.Tags = XmlSimpleConverter.ConvertToTags(wa.tag);

            // set nodes.
            if (wa.nd != null && wa.nd.Length > 0)
            {
                way.Nodes = new List <long>();
                for (int idx = 0; idx < wa.nd.Length; idx++)
                {
                    way.Nodes.Add(wa.nd[idx].@ref);
                }
            }

            return(way);
        }
Ejemplo n.º 25
0
        /// <summary>
        /// Moves to the next object.
        /// </summary>
        /// <returns></returns>
        public override bool MoveNext()
        {
            if (!_cachingDone)
            { // first seek & cache.
                this.Seek();
                _cachingDone = true;
            }

            while (_simpleSource.MoveNext())
            { // there is data.
                OsmGeo currentSimple = _simpleSource.Current();

                switch (currentSimple.Type)
                {
                case OsmGeoType.Node:
                    // create complete version.
                    _current = currentSimple as Node;

                    if (_current != null && _current.Tags == null)
                    {     // make sure nodes have a default tag collection that is empty not null.
                        _current.Tags = new OsmSharp.Collections.Tags.TagsCollection();
                    }
                    if (_nodesToInclude.Contains(currentSimple.Id.Value))
                    {     // node needs to be cached.
                        _dataCache.AddNode(currentSimple as Node);
                        _nodesToInclude.Remove(currentSimple.Id.Value);
                    }
                    break;

                case OsmGeoType.Way:
                    // create complete way.
                    _current = CompleteWay.CreateFrom(currentSimple as Way, _dataCache);

                    if (_waysToInclude.Contains(currentSimple.Id.Value))
                    {     // keep the way because it is needed later on.
                        _dataCache.AddWay(currentSimple as Way);
                        _waysToInclude.Remove(currentSimple.Id.Value);
                    }
                    else
                    {     // only report that the nodes have been used when the way can be let-go.
                        Way way = currentSimple as Way;
                        if (way.Nodes != null)
                        {     // report usage.
                            way.Nodes.ForEach(x => this.ReportNodeUsage(x));
                        }
                    }
                    break;

                case OsmGeoType.Relation:
                    // create complate relation.
                    _current = CompleteRelation.CreateFrom(currentSimple as Relation, _dataCache);

                    if (!_relationsToInclude.Contains(currentSimple.Id.Value))
                    {     // only report relation usage when the relation can be let go.
                        Relation relation = currentSimple as Relation;
                        if (relation.Members != null)
                        {
                            foreach (RelationMember member in relation.Members)
                            {
                                switch (member.MemberType.Value)
                                {
                                case OsmGeoType.Node:
                                    this.ReportNodeUsage(member.MemberId.Value);
                                    break;

                                case OsmGeoType.Way:
                                    this.ReportWayUsage(member.MemberId.Value);
                                    break;

                                case OsmGeoType.Relation:
                                    this.ReportRelationUsage(member.MemberId.Value);
                                    break;
                                }
                            }
                        }
                    }
                    break;
                }
                if (_current != null)
                { // only return complete objects.
                    return(true);
                }
            }
            return(false);
        }
Ejemplo n.º 26
0
 public void Remove(Way wayIn) =>
 _ways.DeleteOne(way => way.Id == wayIn.Id);
Ejemplo n.º 27
0
        /// <summary>
        /// Adds a given way.
        /// </summary>
        /// <param name="way"></param>
        public override void AddWay(Way way)
        {
            if (!_preIndexMode && _waysToCache != null &&
                _waysToCache.Contains(way.Id.Value))
            { // cache this way?
                _dataCache.AddWay(way);
            }

            // initialize the way interpreter.
            if (_interpreter.EdgeInterpreter.IsRoutable(way.Tags))
            {         // the way is a road.
                if (_preIndexMode)
                {     // index relevant and used nodes.
                    if (way.Nodes != null)
                    { // this way has nodes.
                        // add new routable tags type.
                        var routableWayTags = new TagsCollection(way.Tags);
                        routableWayTags.RemoveAll(x =>
                        {
                            return(!_interpreter.IsRelevantRouting(x.Key) &&
                                   !Vehicle.IsRelevantForOneOrMore(x.Key));
                        });
                        if (_storeTags)
                        {
                            _tagsIndex.Add(routableWayTags);
                        }

                        int wayNodesCount = way.Nodes.Count;
                        for (int idx = 0; idx < wayNodesCount; idx++)
                        {
                            var node = way.Nodes[idx];
                            if (_preIndex.Contains(node))
                            { // node is relevant.
                                _relevantNodes.Add(node);
                            }
                            else
                            { // node is used.
                                _preIndex.Add(node);
                            }
                        }

                        if (wayNodesCount > 0)
                        { // first node is always relevant.
                            _relevantNodes.Add(way.Nodes[0]);
                            if (wayNodesCount > 1)
                            { // last node is always relevant.
                                _relevantNodes.Add(way.Nodes[wayNodesCount - 1]);
                            }
                        }
                    }
                }
                else
                {     // add actual edges.
                    if (way.Nodes != null && way.Nodes.Count > 1)
                    { // way has at least two nodes.
                        if (this.CalculateIsTraversable(_interpreter.EdgeInterpreter, _tagsIndex,
                                                        way.Tags))
                        { // the edge is traversable, add the edges.
                            uint?       from          = this.AddRoadNode(way.Nodes[0]);
                            long        fromNodeId    = way.Nodes[0];
                            List <long> intermediates = new List <long>();
                            for (int idx = 1; idx < way.Nodes.Count; idx++)
                            { // the to-node.
                                long currentNodeId = way.Nodes[idx];
                                if (!_collectIntermediates ||
                                    _relevantNodes.Contains(currentNodeId) ||
                                    idx == way.Nodes.Count - 1)
                                { // node is an important node.
                                    uint?to       = this.AddRoadNode(currentNodeId);
                                    long toNodeId = currentNodeId;

                                    // add the edge(s).
                                    if (from.HasValue && to.HasValue)
                                    { // add a road edge.
                                        while (from.Value == to.Value)
                                        {
                                            if (intermediates.Count > 0)
                                            {
                                                uint?dummy = this.AddRoadNode(intermediates[0]);
                                                intermediates.RemoveAt(0);
                                                if (dummy.HasValue && from.Value != dummy.Value)
                                                {
                                                    this.AddRoadEdge(way.Tags, from.Value, dummy.Value, null);
                                                    from = dummy;
                                                }
                                            }
                                            else
                                            { // no use to continue.
                                                break;
                                            }
                                        }
                                        // build coordinates.
                                        var intermediateCoordinates = new List <GeoCoordinateSimple>(intermediates.Count);
                                        for (int coordIdx = 0; coordIdx < intermediates.Count; coordIdx++)
                                        {
                                            ICoordinate coordinate;
                                            if (!_coordinates.TryGet(intermediates[coordIdx], out coordinate))
                                            {
                                                break;
                                            }
                                            intermediateCoordinates.Add(new GeoCoordinateSimple()
                                            {
                                                Latitude  = coordinate.Latitude,
                                                Longitude = coordinate.Longitude
                                            });
                                        }

                                        if (intermediateCoordinates.Count == intermediates.Count &&
                                            from.Value != to.Value)
                                        { // all coordinates have been found.
                                            this.AddRoadEdge(way.Tags, from.Value, to.Value, intermediateCoordinates);
                                        }
                                    }

                                    // if this way has a restriction save the collapsed nodes information.
                                    if (_restricedWays.Contains(way.Id.Value) && to.HasValue && from.HasValue)
                                    { // loop over all intermediates and save.
                                        var collapsedInfo = new KeyValuePair <KeyValuePair <long, uint>, KeyValuePair <long, uint> >(
                                            new KeyValuePair <long, uint>(fromNodeId, from.Value), new KeyValuePair <long, uint>(toNodeId, to.Value));
                                        foreach (var intermedidate in intermediates)
                                        {
                                            _collapsedNodes[intermedidate] = collapsedInfo;
                                        }
                                    }

                                    from = to; // the to node becomes the from.
                                    intermediates.Clear();
                                }
                                else
                                { // this node is just an intermediate.
                                    intermediates.Add(currentNodeId);
                                }
                            }
                        }
                    }
                }
            }
        }
Ejemplo n.º 28
0
 public Way Create(Way way)
 {
     _ways.InsertOne(way);
     Program.Elements++;
     return(way);
 }
Ejemplo n.º 29
0
 public void Update(string id, Way wayIn) =>
 _ways.ReplaceOne(way => way.Id == id, wayIn);
Ejemplo n.º 30
0
        public void APITestWayCreateGetDelete()
        {
            // intialize the connection.
            var apiInstance = new APIConnection("http://api06.dev.openstreetmap.org/",
                                                "osmsharp", "osmsharp");

            // open a changeset.
            apiInstance.ChangeSetOpen("Simple Way Creation Test");

            // initialize the way.
            var way = new Way();

            way.Tags = new SimpleTagsCollection();
            way.Tags.Add("type", "testway");
            way.Nodes   = new List <long>();
            way.Visible = true;

            // initialize the nodes.
            var node = new Node();

            node.Latitude  = -0.494497;
            node.Longitude = -24.119325;
            node.Tags      = new SimpleTagsCollection();
            node.Tags.Add("type", "testnode1");
            node.Visible = true;
            node         = apiInstance.NodeCreate(node);
            way.Nodes.Add(node.Id.Value);
            node           = new Node();
            node.Latitude  = -0.494497 + 0.0001f;
            node.Longitude = -24.119325 + 0.0001f;
            node.Tags      = new SimpleTagsCollection();
            node.Tags.Add("type", "testnode2");
            node.Visible = true;
            node         = apiInstance.NodeCreate(node);
            way.Nodes.Add(node.Id.Value);

            // save the way.
            way = apiInstance.WayCreate(way);

            // close the changeset.
            apiInstance.ChangeSetClose();

            // check if the id now has a value.
            Assert.IsTrue(way.Id.HasValue);

            // get the new way id.
            long wayId = way.Id.Value;

            // get the way again: a way can only be deleted using the correct changesetid and version.
            way = apiInstance.WayGet(way.Id.Value);

            // open new changeset.
            apiInstance.ChangeSetOpen("Simple Way Delete Test");

            // get the way.
            apiInstance.WayDelete(way);

            // close the current changeset.
            apiInstance.ChangeSetClose();

            // get the way.
            Way apiWay = apiInstance.WayGet(way.Id.Value);

            Assert.IsNull(apiWay);
        }
Ejemplo n.º 31
0
        public void APITestWayCreateGetUpdate()
        {
            // intialize the connection.
            var apiInstance = new APIConnection("http://api06.dev.openstreetmap.org/",
                                                "osmsharp", "osmsharp");

            // open a changeset.
            apiInstance.ChangeSetOpen("Simple Way Creation Test");

            // initialize the way.
            var way = new Way();

            way.Tags = new SimpleTagsCollection();
            way.Tags.Add("type", "testway");
            way.Nodes   = new List <long>();
            way.Visible = true;

            // initialize the nodes.
            var node = new Node();

            node.Latitude  = -0.494497;
            node.Longitude = -24.119325;
            node.Tags      = new SimpleTagsCollection();
            node.Tags.Add("type", "testnode1");
            node.Visible = true;
            node         = apiInstance.NodeCreate(node);
            way.Nodes.Add(node.Id.Value);
            node           = new Node();
            node.Latitude  = -0.494497 + 0.0001f;
            node.Longitude = -24.119325 + 0.0001f;
            node.Tags      = new SimpleTagsCollection();
            node.Tags.Add("type", "testnode2");
            node.Visible = true;
            node         = apiInstance.NodeCreate(node);
            way.Nodes.Add(node.Id.Value);

            // save the way.
            way = apiInstance.WayCreate(way);

            // close the changeset.
            apiInstance.ChangeSetClose();

            // check if the id now has a value.
            Assert.IsTrue(way.Id.HasValue);

            // get the new way id.
            long wayId = way.Id.Value;

            // open new changeset.
            apiInstance.ChangeSetOpen("Simple Way Update Test");

            // get the way.
            Way apiWay = apiInstance.WayGet(way.Id.Value);

            apiWay.Tags.Add("another_tag", "test adding a tag!");
            apiInstance.WayUpdate(apiWay);

            // close the current changeset.
            apiInstance.ChangeSetClose();

            // get the api way.
            apiWay = apiInstance.WayGet(way.Id.Value);

            Assert.AreEqual(2, apiWay.Tags.Count);
            Assert.IsTrue(apiWay.Tags.ContainsKey("another_tag"));
            Assert.AreEqual("test adding a tag!", apiWay.Tags["another_tag"]);
        }
Ejemplo n.º 32
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="id"></param>
 /// <param name="way"></param>
 /// <returns></returns>
 public override bool TryGetWay(long id, out Way way)
 {
     return(_ways.TryGetValue(id, out way));
 }
Ejemplo n.º 33
0
        public void TestWriteWay()
        {
            // build source stream.
            var sourceWay = new Way()
            {
                Id    = 1,
                Nodes = new long[] { 1, 2 }
            };
            var sourceObjects = new OsmGeo[] {
                sourceWay
            };

            // build pfb stream target.
            using (var stream = new MemoryStream())
            {
                var target = new PBFOsmStreamTarget(stream);
                target.RegisterSource(sourceObjects);
                target.Pull();

                stream.Seek(0, SeekOrigin.Begin);
                var resultObjects = new List <OsmGeo>(new PBFOsmStreamSource(stream));

                Assert.IsNotNull(resultObjects);
                Assert.AreEqual(1, resultObjects.Count);

                Assert.AreEqual(sourceObjects[0].Id, resultObjects[0].Id);
                Assert.AreEqual(0, resultObjects[0].ChangeSetId);
                Assert.AreEqual(OsmSharp.IO.PBF.PBFExtensions.FromUnixTime(0), resultObjects[0].TimeStamp);
                Assert.AreEqual(0, resultObjects[0].UserId);
                Assert.AreEqual(sourceObjects[0].UserName, resultObjects[0].UserName);
                Assert.AreEqual(0, resultObjects[0].Version);

                var resultWay = resultObjects[0] as Way;
                Assert.AreEqual(sourceWay.Nodes.Length, resultWay.Nodes.Length);
                Assert.AreEqual(sourceWay.Nodes[0], resultWay.Nodes[0]);
                Assert.AreEqual(sourceWay.Nodes[1], resultWay.Nodes[1]);
            }

            // build source stream.
            sourceWay = new Way()
            {
                Id    = 1,
                Nodes = new long[] { 1, 2 }
            };
            sourceWay.Tags = new TagsCollection();
            sourceWay.Tags.Add("highway", "residential");
            sourceObjects = new OsmGeo[] {
                sourceWay
            };

            // build pfb stream target.
            using (var stream = new MemoryStream())
            {
                var target = new PBFOsmStreamTarget(stream);
                target.RegisterSource(sourceObjects);
                target.Pull();

                stream.Seek(0, SeekOrigin.Begin);
                var resultObjects = new List <OsmGeo>(new PBFOsmStreamSource(stream));

                Assert.IsNotNull(resultObjects);
                Assert.AreEqual(1, resultObjects.Count);

                Assert.AreEqual(sourceObjects[0].Id, resultObjects[0].Id);
                Assert.AreEqual(0, resultObjects[0].ChangeSetId);
                Assert.AreEqual(OsmSharp.IO.PBF.PBFExtensions.FromUnixTime(0), resultObjects[0].TimeStamp);
                Assert.AreEqual(0, resultObjects[0].UserId);
                Assert.AreEqual(string.Empty, resultObjects[0].UserName);
                Assert.AreEqual(0, resultObjects[0].Version);
                Assert.AreEqual(sourceObjects[0].Tags.Count, resultObjects[0].Tags.Count);
                Assert.IsTrue(resultObjects[0].Tags.Contains(sourceObjects[0].Tags.First <Tag>()));

                var resultWay = resultObjects[0] as Way;
                Assert.AreEqual(sourceWay.Nodes.Length, resultWay.Nodes.Length);
                Assert.AreEqual(sourceWay.Nodes[0], resultWay.Nodes[0]);
                Assert.AreEqual(sourceWay.Nodes[1], resultWay.Nodes[1]);
            }

            // build source stream.
            sourceWay = new Way()
            {
                Id    = 1,
                Nodes = new long[] { 1, 2 }
            };
            sourceWay.Tags = new TagsCollection();
            sourceWay.Tags.Add("highway", "residential");
            sourceWay.ChangeSetId = 1;
            sourceWay.TimeStamp   = DateTime.Now;
            sourceWay.UserId      = 1;
            sourceWay.UserName    = "******";
            sourceWay.Version     = 3;
            sourceWay.Visible     = true;
            sourceObjects         = new OsmGeo[] {
                sourceWay
            };

            // build pfb stream target.
            using (var stream = new MemoryStream())
            {
                var target = new PBFOsmStreamTarget(stream);
                target.RegisterSource(sourceObjects);
                target.Pull();

                stream.Seek(0, SeekOrigin.Begin);
                var resultObjects = new List <OsmGeo>(new PBFOsmStreamSource(stream));

                Assert.IsNotNull(resultObjects);
                Assert.AreEqual(1, resultObjects.Count);

                Assert.AreEqual(sourceObjects[0].Id, resultObjects[0].Id);
                Assert.AreEqual(sourceObjects[0].ChangeSetId, resultObjects[0].ChangeSetId);
                Assert.AreEqual(sourceObjects[0].TimeStamp.Value.Ticks, resultObjects[0].TimeStamp.Value.Ticks, 10000000);
                Assert.AreEqual(sourceObjects[0].UserId, resultObjects[0].UserId);
                Assert.AreEqual(sourceObjects[0].UserName, resultObjects[0].UserName);
                Assert.AreEqual(sourceObjects[0].Version, resultObjects[0].Version);
                Assert.AreEqual(sourceObjects[0].Tags.Count, resultObjects[0].Tags.Count);
                Assert.IsTrue(resultObjects[0].Tags.Contains(sourceObjects[0].Tags.First <Tag>()));

                var resultWay = resultObjects[0] as Way;
                Assert.AreEqual(sourceWay.Nodes.Length, resultWay.Nodes.Length);
                Assert.AreEqual(sourceWay.Nodes[0], resultWay.Nodes[0]);
                Assert.AreEqual(sourceWay.Nodes[1], resultWay.Nodes[1]);
            }
        }
Ejemplo n.º 34
0
 public override System.Collections.IEnumerator Build(Way n, MapChunkLoader mcl)
 {
     throw new NotImplementedException();
 }
Ejemplo n.º 35
0
        /// <summary>
        /// Adds a given way.
        /// </summary>
        /// <param name="way"></param>
        public override void AddWay(Way way)
        {
            if (!_preIndexMode && _waysToCache != null &&
                _waysToCache.Contains(way.Id.Value))
            { // cache this way?
                _dataCache.AddWay(way);
            }

            // initialize the way interpreter.
            if (_interpreter.EdgeInterpreter.IsRoutable(way.Tags))
            {     // the way is a road.
                if (_preIndexMode)
                { // index only relevant nodes.
                    if (way.Nodes != null)
                    {
                        foreach (long node in way.Nodes)
                        {
                            if (_preIndex.Contains(node))
                            {
                                _usedTwiceOrMore.Add(node);
                            }
                            else
                            {
                                _preIndex.Add(node); // node is relevant.
                            }
                        }
                    }
                }
                else
                {
                    // add the forward edges.
                    //if (!interpreter.IsOneWayReverse())
                    if (true) // add backward edges too!
                    {         // loop over all edges.
                        if (way.Nodes != null && way.Nodes.Count > 1)
                        {     // way has at least two nodes.
                            // keep the relevant tags.
                            TagsCollection relevantTags = new SimpleTagsCollection();
                            foreach (var relevantTag in way.Tags)
                            {
                                if (_interpreter.IsRelevant(relevantTag.Key))
                                {
                                    relevantTags.Add(relevantTag);
                                }
                            }


                            if (this.CalculateIsTraversable(_interpreter.EdgeInterpreter, _tagsIndex,
                                                            relevantTags))
                            { // the edge is traversable, add the edges.
                                uint?from = this.AddRoadNode(way.Nodes[0]);
                                for (int idx = 1; idx < way.Nodes.Count; idx++)
                                { // the to-node.
                                    uint?to = this.AddRoadNode(way.Nodes[idx]);
                                    // add the edge(s).
                                    if (from.HasValue && to.HasValue)
                                    {     // add a road edge.
                                        if (!this.AddRoadEdge(relevantTags, true, from.Value, to.Value))
                                        { // add the reverse too if it has been indicated that this was needed.
                                            this.AddRoadEdge(relevantTags, false, to.Value, from.Value);
                                        }
                                    }
                                    from = to; // the to node becomes the from.
                                }
                            }
                        }
                    }
                }
            }
        }
Ejemplo n.º 36
0
 public OrderExecutedEventArgs(decimal price, int quantity, Way way)
 {
     this.Price = price;
     this.Quantity = quantity;
     this.Way = way;
 }
Ejemplo n.º 37
0
 /// <summary>
 /// Adds a way
 /// </summary>
 public abstract void AddWay(Way way);
Ejemplo n.º 38
0
    public MapManager(XmlDocument XMLFile)
    {
        XmlNode node = XMLFile["osm"];
        Debug.Log(node.InnerText);

        nm = new NodeManager();
        nodes = new List<Node>();
        ways = new List<Way>();
        trees = new List<Node>();

        // How to traverse nodes in the file
        // (this loops over just the declaration and the root, since they are the only
        // two top-level children of the XmlDocument object)
        foreach (XmlElement cnode in node.ChildNodes)
        {

            if(cnode.LocalName == "node")
            {
                Node tempNode = new Node();
                tempNode.id = long.Parse(cnode.GetAttribute("id"));

                tempNode.changeset = long.Parse(cnode.GetAttribute("changeset"));

                tempNode.lat = double.Parse(cnode.GetAttribute("lat"));

                tempNode.lon = double.Parse(cnode.GetAttribute("lon"));

                tempNode.timestamp = cnode.GetAttribute("timestamp");

                tempNode.uid = long.Parse(cnode.GetAttribute("uid"));

                tempNode.user = cnode.GetAttribute("user");

                tempNode.version = int.Parse(cnode.GetAttribute("version"));

                convertor = new GeoUTMConverter();

                convertor.ToUTM(tempNode.lat,tempNode.lon);

                tempNode.northing = convertor.Y;

                tempNode.easthing = convertor.X;

                XmlNode xmlNode = cnode as XmlNode;

                foreach (XmlElement xmlNodeRef in xmlNode.ChildNodes)
                {
                    if(xmlNodeRef.LocalName == "tag")
                    {
                        string key = xmlNodeRef.GetAttribute("k");
                        string value = xmlNodeRef.GetAttribute("v");

                        if (key.Contains("natural"))
                        {
                            if (value.Contains("tree"))
                            {
                                tempNode.type = NodeType.Tree;
                                trees.Add(tempNode);
                            }
                        }
                    }
                }

                nm.nodes[tempNode.id] = tempNode;

                nodes.Add(tempNode);
            }
            if(cnode.LocalName == "way")
            {
                GeoUTMConverter converter = new GeoUTMConverter();
                XmlNode xmlWay = cnode as XmlNode;
                Way tempWay = new Way();
                tempWay.type = WayType.Residential;
                tempWay.changeset = long.Parse(cnode.GetAttribute("changeset"));
                tempWay.id = long.Parse(cnode.GetAttribute("id"));
                tempWay.timestamp = cnode.GetAttribute("timestamp");
                tempWay.uid = long.Parse(cnode.GetAttribute("uid"));
                tempWay.user = cnode.GetAttribute("user");
                tempWay.version = int.Parse(cnode.GetAttribute("version"));

                bool toAdd = true;
                foreach (XmlElement xmlNodeRef in xmlWay.ChildNodes)
                {
                    if(xmlNodeRef.LocalName == "nd")
                    {
                        long nodeRef = long.Parse(xmlNodeRef.GetAttribute("ref"));
                        Node tempNode = nm.nodes[nodeRef];

                        tempWay.nodes.Add(tempNode);
                    }
                    if(xmlNodeRef.LocalName == "tag")
                    {
                        string key = xmlNodeRef.GetAttribute("k");
                        string value = xmlNodeRef.GetAttribute("v");
                        if(key.Contains("building"))
                        {
                            tempWay.type = WayType.Building;
                        }
                        if(key.Contains("amenity"))
                        {
                            if(value.Contains("parking"))
                                tempWay.type = WayType.Parking;
                        }
                        if(key.Contains ("landuse"))
                        {
                            if(value.Contains("grass"))
                            {
                                tempWay.type = WayType.Park;
                            }
                        }
                        if(key.Contains("highway"))
                        {
                            tempWay.type = WayType.Residential;
                            if(value.Contains("residential"))
                            {
                                tempWay.type = WayType.Residential;
                            }
                            else if(value.Contains("footway"))
                            {
                                tempWay.type = WayType.Footway;
                            }
                            else if(value.Contains("motorway"))
                            {
                                tempWay.type = WayType.Motorway;
                            }
                        }

                        if(key.Contains("leisure"))
                        {
                            if(value.Contains("park"))
                            {
                                tempWay.type = WayType.Park;
                            }
                        }
                        if(key.Contains("waterway"))
                        {
                            if(value.Contains("river"))
                                tempWay.type = WayType.River;
                            if (value.Contains("riverbank"))
                                tempWay.type = WayType.RiverBank;
                        }
                        if(key.Contains("bridge"))
                        {
                            tempWay.height += 3;
                        }
                        if(key.Contains("name"))
                        {
                            tempWay.name = value;
                        }
                        if(key.Contains("height"))
                        {
                            tempWay.height = int.Parse(Regex.Replace(value, "[^-,.0-9]", "")); // Remove everything non-numeric
                        }
                        if(key.Contains("area"))
                        {
                            toAdd = false;
                        }
                        if(key.Contains ("natural"))
                        {
                            if (value.Contains("water"))
                                tempWay.type = WayType.RiverBank;
                        }
                    }

                }

                if(toAdd)
                ways.Add(tempWay);
            }
        }
    }
Ejemplo n.º 39
0
 /// <summary>
 /// visit实际进行访问的地方
 /// </summary>
 internal abstract void VisitUpdate(Way re);
Ejemplo n.º 40
0
        /// <summary>
        /// Moves to the next object.
        /// </summary>
        /// <returns></returns>
        public override bool MoveNext()
        {
            if (!_cachingDone)
            { // first seek & cache.
                this.Seek();
                this.CacheRelations();
                _cachingDone = true;
            }

            if (this.Source.MoveNext())
            { // there is data.
                OsmGeo currentSimple = this.Source.Current();

                // make sure the object needs to be included.
                while (!this.IsChild(currentSimple) &&
                       !this.Include(currentSimple))
                {     // don't include this object!
                    if (!this.Source.MoveNext())
                    { // oeps no more data!
                        return(false);
                    }
                    currentSimple = this.Source.Current();
                }

                switch (currentSimple.Type)
                {
                case OsmGeoType.Node:
                    // create complete version.
                    _current = currentSimple;
                    if (_nodesToInclude.Contains(currentSimple.Id.Value))
                    {     // node needs to be cached.
                        _dataCache.AddNode(currentSimple as Node);
                        _nodesToInclude.Remove(currentSimple.Id.Value);
                    }
                    break;

                case OsmGeoType.Way:
                    // create complete way.
                    _current = currentSimple;

                    if (_waysToInclude.Contains(currentSimple.Id.Value))
                    {     // keep the way because it is needed later on.
                        _dataCache.AddWay(currentSimple as Way);
                        _waysToInclude.Remove(currentSimple.Id.Value);
                    }
                    else
                    {     // only report that the nodes have been used when the way can be let-go.
                        Way way = currentSimple as Way;
                        if (way.Nodes != null)
                        {     // report usage.
                            way.Nodes.ForEach(x => this.ReportNodeUsage(x));
                        }
                    }
                    break;

                case OsmGeoType.Relation:
                    // create complate relation.
                    _current = currentSimple;

                    if (!_relationsToInclude.Contains(currentSimple.Id.Value))
                    {     // only report relation usage when the relation can be let go.
                        Relation relation = currentSimple as Relation;
                        if (relation.Members != null)
                        {
                            foreach (RelationMember member in relation.Members)
                            {
                                switch (member.MemberType.Value)
                                {
                                case OsmGeoType.Node:
                                    this.ReportNodeUsage(member.MemberId.Value);
                                    break;

                                case OsmGeoType.Way:
                                    this.ReportWayUsage(member.MemberId.Value);
                                    break;

                                case OsmGeoType.Relation:
                                    this.ReportRelationUsage(member.MemberId.Value);
                                    break;
                                }
                            }
                        }
                    }
                    break;
                }
                return(true);
            }
            return(false);
        }
Ejemplo n.º 41
0
        public void CanInsertAndGetRelation()
        {
            // ARRANGE
            var way1 = new Way()
            {
                Id          = 1,
                Coordinates = new List <GeoCoordinate>()
                {
                    new GeoCoordinate(52, 13), new GeoCoordinate(52.1f, 13.1f)
                },
                Tags = new Dictionary <string, string>()
                {
                    { "key11", "value11" }, { "key12", "value12" }
                }.ToTags()
            };
            var offset1 = _store.Insert(way1);
            var way2    = new Way()
            {
                Id          = 2,
                Coordinates = new List <GeoCoordinate>()
                {
                    new GeoCoordinate(53, 14), new GeoCoordinate(53.1f, 14.1f)
                },
                Tags = new Dictionary <string, string>()
                {
                    { "key21", "value21" }, { "key22", "value22" }
                }.ToTags()
            };
            var offset2 = _store.Insert(way2);

            var relation = new Relation()
            {
                Id      = 3,
                Members = new List <RelationMember>()
                {
                    new RelationMember()
                    {
                        Role   = "inner",
                        Offset = offset1
                    },
                    new RelationMember()
                    {
                        Role   = "outer",
                        Offset = offset2
                    }
                },
                Tags = new Dictionary <string, string>()
                {
                    { "type", "multipolygon" }
                }.ToTags()
            };

            // ACT
            var offset = _store.Insert(relation);
            var result = _store.Get(offset) as Relation;

            // ASSERT
            Assert.IsNotNull(result);
            Assert.AreEqual(relation.Id, result.Id);
            Assert.AreEqual(relation.Tags, result.Tags);
            Assert.AreEqual(2, result.Members.Count);
            AssertWays(way1, result.Members[0].Member as Way);
            AssertWays(way2, result.Members[1].Member as Way);
        }
Ejemplo n.º 42
0
 public OrderExecutedEventArgs(decimal price, int quantity, Way way)
 {
     this.Price    = price;
     this.Quantity = quantity;
     this.Way      = way;
 }
Ejemplo n.º 43
0
        public void TestWriteMix()
        {
            var sourceNode = new Node()
            {
                Id        = 1,
                Latitude  = 1.1f,
                Longitude = 1.2f
            };

            sourceNode.Tags = new TagsCollection();
            sourceNode.Tags.Add("highway", "residential");
            sourceNode.ChangeSetId = 1;
            sourceNode.TimeStamp   = DateTime.Now;
            sourceNode.UserId      = 1;
            sourceNode.UserName    = "******";
            sourceNode.Version     = 3;
            sourceNode.Visible     = true;

            var sourceWay = new Way()
            {
                Id    = 1,
                Nodes = new long[] { 1, 2 }
            };

            sourceWay.Tags = new TagsCollection();
            sourceWay.Tags.Add("highway", "residential");
            sourceWay.ChangeSetId = 1;
            sourceWay.TimeStamp   = DateTime.Now;
            sourceWay.UserId      = 1;
            sourceWay.UserName    = "******";
            sourceWay.Version     = 3;
            sourceWay.Visible     = true;

            var sourceRelation = new Relation()
            {
                Id      = 1,
                Members = new RelationMember[]
                {
                    new RelationMember()
                    {
                        Id   = 1,
                        Role = "fake role",
                        Type = OsmGeoType.Node
                    },
                    new RelationMember()
                    {
                        Id   = 1,
                        Role = "fake role",
                        Type = OsmGeoType.Way
                    }
                }
            };

            sourceRelation.Tags = new TagsCollection();
            sourceRelation.Tags.Add("highway", "residential");
            sourceRelation.ChangeSetId = 1;
            sourceRelation.TimeStamp   = DateTime.Now;
            sourceRelation.UserId      = 1;
            sourceRelation.UserName    = "******";
            sourceRelation.Version     = 3;
            sourceRelation.Visible     = true;

            var sourceObjects = new OsmGeo[] {
                sourceNode,
                sourceWay,
                sourceRelation
            };

            // build pfb stream target.
            using (var stream = new MemoryStream())
            {
                var target = new PBFOsmStreamTarget(stream);
                target.RegisterSource(sourceObjects);
                target.Pull();

                stream.Seek(0, SeekOrigin.Begin);
                var resultObjects = new List <OsmGeo>(new PBFOsmStreamSource(stream));

                Assert.IsNotNull(resultObjects);
                Assert.AreEqual(3, resultObjects.Count);

                Assert.AreEqual(sourceObjects[0].Id, resultObjects[0].Id);
                Assert.AreEqual(sourceObjects[0].ChangeSetId, resultObjects[0].ChangeSetId);
                Assert.AreEqual(sourceObjects[0].TimeStamp.Value.Ticks, resultObjects[0].TimeStamp.Value.Ticks, 10000000);
                Assert.AreEqual(sourceObjects[0].UserId, resultObjects[0].UserId);
                Assert.AreEqual(sourceObjects[0].UserName, resultObjects[0].UserName);
                Assert.AreEqual(sourceObjects[0].Version, resultObjects[0].Version);
                Assert.AreEqual(sourceObjects[0].Tags.Count, resultObjects[0].Tags.Count);
                Assert.IsTrue(resultObjects[0].Tags.Contains(sourceObjects[0].Tags.First <Tag>()));

                var resultNode = resultObjects[0] as Node;
                Assert.AreEqual(sourceNode.Latitude.Value, resultNode.Latitude.Value, .0001f);
                Assert.AreEqual(sourceNode.Longitude.Value, resultNode.Longitude.Value, .0001f);

                Assert.AreEqual(sourceObjects[1].Id, resultObjects[1].Id);
                Assert.AreEqual(sourceObjects[1].ChangeSetId, resultObjects[1].ChangeSetId);
                Assert.AreEqual(sourceObjects[1].TimeStamp.Value.Ticks, resultObjects[1].TimeStamp.Value.Ticks, 10000000);
                Assert.AreEqual(sourceObjects[1].UserId, resultObjects[1].UserId);
                Assert.AreEqual(sourceObjects[1].UserName, resultObjects[1].UserName);
                Assert.AreEqual(sourceObjects[1].Version, resultObjects[1].Version);
                Assert.AreEqual(sourceObjects[1].Tags.Count, resultObjects[1].Tags.Count);
                Assert.IsTrue(resultObjects[1].Tags.Contains(sourceObjects[1].Tags.First <Tag>()));

                var resultWay = resultObjects[1] as Way;
                Assert.AreEqual(sourceWay.Nodes.Length, resultWay.Nodes.Length);
                Assert.AreEqual(sourceWay.Nodes[0], resultWay.Nodes[0]);
                Assert.AreEqual(sourceWay.Nodes[1], resultWay.Nodes[1]);

                Assert.AreEqual(sourceObjects[2].Id, resultObjects[2].Id);
                Assert.AreEqual(sourceObjects[2].ChangeSetId, resultObjects[2].ChangeSetId);
                Assert.AreEqual(sourceObjects[2].TimeStamp.Value.Ticks, resultObjects[2].TimeStamp.Value.Ticks, 10000000);
                Assert.AreEqual(sourceObjects[2].UserId, resultObjects[2].UserId);
                Assert.AreEqual(sourceObjects[2].UserName, resultObjects[2].UserName);
                Assert.AreEqual(sourceObjects[2].Version, resultObjects[2].Version);
                Assert.AreEqual(sourceObjects[2].Tags.Count, resultObjects[2].Tags.Count);
                Assert.IsTrue(resultObjects[2].Tags.Contains(sourceObjects[2].Tags.First <Tag>()));

                var resultRelation = resultObjects[2] as Relation;
                Assert.AreEqual(sourceRelation.Members.Length, resultRelation.Members.Length);
                Assert.AreEqual(sourceRelation.Members[0].Id, resultRelation.Members[0].Id);
                Assert.AreEqual(sourceRelation.Members[0].Role, resultRelation.Members[0].Role);
                Assert.AreEqual(sourceRelation.Members[0].Type, resultRelation.Members[0].Type);
                Assert.AreEqual(sourceRelation.Members[1].Id, resultRelation.Members[1].Id);
                Assert.AreEqual(sourceRelation.Members[1].Role, resultRelation.Members[1].Role);
                Assert.AreEqual(sourceRelation.Members[1].Type, resultRelation.Members[1].Type);
            }
        }
Ejemplo n.º 44
0
 public Class_id(string n, Way k, Type t) : base(n, k, t)
 {
 }
Ejemplo n.º 45
0
    private void CreateRoad(Way w)
    {
        //GameObject go = new GameObject();
        //go.name = "Road";
        PolyLine pl = new PolyLine(w.id.ToString());
        pl.SetOffset(offsetPositionX, offsetPositionZ);
        pl.heigth = w.height;

        if (w.type == WayType.Footway)
        {
            pl.material = Resources.Load("Materials/Footway Material") as Material;
            pl.width = 1;
        }
        if (w.type == WayType.Motorway)
        {
            pl.material = Resources.Load("Materials/Road Material") as Material;
            pl.width = 4;
            pl.lanes = 2;
        }
        if (w.type == WayType.Residential)
        {
            pl.material = Resources.Load("Materials/Road Material") as Material;
            pl.width = 2;
        }
        if (w.type == WayType.River)
        {
            pl.material = Resources.Load("Materials/River Material") as Material;
            pl.width = 8;
        }
        //Road road = go.AddComponent<Road>();
        //road.groundOffset = 0.01f;
        //road.points.Clear();
        //road.roadWidth = 0.1f;// (float)(road.roadWidth/precision);
        //road.mat = (Material)Resources.LoadAssetAtPath("Assets/RoadTool/Example/Texture/Materials/Road.mat", typeof(Material));
        for (int a = 0; a < w.nodes.Count; a++)
        {
            Node n = w.nodes[a];

            Vector3 position = new Vector3((float)(n.easthing - offsetPositionX), 5000, (float)(n.northing - offsetPositionZ));
            float baseHeight = 0;
            RaycastHit hit;

            if (Physics.Raycast(position, -Vector3.up, out hit, Mathf.Infinity, layerMask))
            {
                baseHeight = hit.point.y;
            }
            n.height = baseHeight;
            //Vector3 v = newn. Vector3((float)(((float)n.easthing-offsetPositionX)/precision),(float)0.0,(float)(((float)n.northing-offsetPositionZ)/precision));
            //road.points.Insert(0, v);
            pl.Add(n);

        }
        pl.Close(transform);
        //go.isStatic = true;
        //road.Refresh();
        //go.transform.parent = transform;
    }
        /// <summary>
        /// Moves to the next object.
        /// </summary>
        /// <returns></returns>
        public override bool MoveNext()
        {
            if (!_cachingDone)
            { // first seek & cache.
                this.Seek();
                this.CacheRelations();
                _cachingDone = true;
            }

            while (_simpleSource.MoveNext())
            { // there is data.
                OsmGeo currentSimple = _simpleSource.Current();

                if (currentSimple.Id == 198214128 || currentSimple.Id == 1014892489)
                {
                    System.Diagnostics.Debug.WriteLine("");
                }

                switch (currentSimple.Type)
                {
                case OsmGeoType.Node:
                    // create complete version.
                    _current = CompleteNode.CreateFrom(currentSimple as Node);
                    if (_nodesToInclude.Contains(currentSimple.Id.Value))
                    {     // node needs to be cached.
                        _dataCache.AddNode(currentSimple as Node);
                        _nodesToInclude.Remove(currentSimple.Id.Value);
                    }
                    break;

                case OsmGeoType.Way:
                    // create complete way.
                    _current = CompleteWay.CreateFrom(currentSimple as Way, _dataCache);

                    if (_waysToInclude.Contains(currentSimple.Id.Value))
                    {     // keep the way because it is needed later on.
                        _dataCache.AddWay(currentSimple as Way);
                        _waysToInclude.Remove(currentSimple.Id.Value);
                    }
                    else
                    {     // only report that the nodes have been used when the way can be let-go.
                        Way way = currentSimple as Way;
                        if (way.Nodes != null)
                        {     // report usage.
                            way.Nodes.ForEach(x => this.ReportNodeUsage(x));
                        }
                    }
                    break;

                case OsmGeoType.Relation:
                    // create complate relation.
                    _current = CompleteRelation.CreateFrom(currentSimple as Relation, _dataCache);

                    if (!_relationsToInclude.Contains(currentSimple.Id.Value))
                    {     // only report relation usage when the relation can be let go.
                        Relation relation = currentSimple as Relation;
                        if (relation.Members != null)
                        {
                            foreach (RelationMember member in relation.Members)
                            {
                                switch (member.MemberType.Value)
                                {
                                case OsmGeoType.Node:
                                    this.ReportNodeUsage(member.MemberId.Value);
                                    break;

                                case OsmGeoType.Way:
                                    this.ReportWayUsage(member.MemberId.Value);
                                    break;

                                case OsmGeoType.Relation:
                                    this.ReportRelationUsage(member.MemberId.Value);
                                    break;
                                }
                            }
                        }
                    }
                    break;
                }
                if (_current != null)
                { // only return complete objects.
                    return(true);
                }
            }
            return(false);
        }
Ejemplo n.º 47
0
 ///// <summary>
 ///// Returns a enumerable of all nodes in this cache.
 ///// </summary>
 ///// <returns></returns>
 //public abstract IEnumerable<Node> GetNodes();
 /// <summary>
 /// Adds a new way.
 /// </summary>
 /// <param name="way"></param>
 public abstract void AddWay(Way way);
Ejemplo n.º 48
0
 /// <summary>
 /// Tries to get the way with the given id
 /// </summary>
 public abstract bool TryGetWay(long id, out Way way);
Ejemplo n.º 49
0
 /// <summary>
 /// Adds a way to the target.
 /// </summary>
 /// <param name="simpleWay"></param>
 public abstract void AddWay(Way simpleWay);
 /// <summary>
 /// Adds a way.
 /// </summary>
 /// <param name="way"></param>
 public override void AddWay(Way way)
 {
     _stream.Append(way);
 }
Ejemplo n.º 51
0
        /// <summary>
        /// Returns all ways containing the given nodes.
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public override IList <Way> GetWays(IList <long> ids)
        {
            if (ids.Count > 0)
            {
                OracleConnection con = this.CreateConnection();

                // STEP2: Load ways.
                Dictionary <long, Way> ways = new Dictionary <long, Way>();
                string           sql;
                OracleCommand    com;
                OracleDataReader reader;
                for (int idx_1000 = 0; idx_1000 <= ids.Count / 1000; idx_1000++)
                {
                    int start_idx = idx_1000 * 1000;
                    int stop_idx  = System.Math.Min((idx_1000 + 1) * 1000, ids.Count);

                    sql = "SELECT id, changeset_id, timestamp, visible, version, usr, usr_id FROM way WHERE (id IN ({0})) ";
                    string ids_string = this.ConstructIdList(ids, start_idx, stop_idx);
                    if (ids_string.Length > 0)
                    {
                        sql            = string.Format(sql, ids_string);
                        com            = new OracleCommand(sql);
                        com.Connection = con;
                        reader         = com.ExecuteReader();
                        Way way;
                        while (reader.Read())
                        {
                            long     id           = reader.GetInt64(0);
                            long?    changeset_id = reader.IsDBNull(1) ? null : (long?)reader.GetInt64(1);
                            DateTime?timestamp    = reader.IsDBNull(2) ? null : (DateTime?)reader.GetDateTime(2);
                            bool?    visible      = reader.IsDBNull(3) ? null : (bool?)(reader.GetInt16(3) == 1);
                            ulong?   version      = reader.IsDBNull(4) ? null : (ulong?)reader.GetInt64(4);
                            string   user         = reader.IsDBNull(5) ? null : reader.GetString(5);
                            long?    user_id      = reader.IsDBNull(6) ? null : (long?)reader.GetInt64(6);

                            // create way.
                            way             = new Way();
                            way.Id          = id;
                            way.Version     = version;
                            way.UserName    = user;
                            way.UserId      = user_id;
                            way.Visible     = visible;
                            way.TimeStamp   = timestamp;
                            way.ChangeSetId = changeset_id;

                            ways.Add(way.Id.Value, way);
                        }
                        reader.Close();
                    }
                }

                //STEP3: Load all node-way relations
                List <long> missing_node_ids = new List <long>();
                for (int idx_1000 = 0; idx_1000 <= ids.Count / 1000; idx_1000++)
                {
                    int start_idx = idx_1000 * 1000;
                    int stop_idx  = System.Math.Min((idx_1000 + 1) * 1000, ids.Count);

                    sql = "SELECT way_id, node_id, sequence_id FROM way_nodes WHERE (way_id IN ({0})) ORDER BY sequence_id";
                    string ids_string = this.ConstructIdList(ids, start_idx, stop_idx);
                    if (ids_string.Length > 0)
                    {
                        sql            = string.Format(sql, ids_string);
                        com            = new OracleCommand(sql);
                        com.Connection = con;
                        reader         = com.ExecuteReader();
                        while (reader.Read())
                        {
                            long id          = reader.GetInt64(0);
                            long node_id     = reader.GetInt64(1);
                            long sequence_id = reader.GetInt64(2);

                            Way way;
                            if (ways.TryGetValue(id, out way))
                            {
                                if (way.Nodes == null)
                                {
                                    way.Nodes = new List <long>();
                                }
                                way.Nodes.Add(node_id);
                            }
                        }
                        reader.Close();
                    }
                }

                //STEP4: Load all tags.
                for (int idx_1000 = 0; idx_1000 <= ids.Count / 1000; idx_1000++)
                {
                    int start_idx = idx_1000 * 1000;
                    int stop_idx  = System.Math.Min((idx_1000 + 1) * 1000, ids.Count);

                    sql = "SELECT * FROM way_tags WHERE (way_id IN ({0})) ";
                    string ids_string = this.ConstructIdList(ids, start_idx, stop_idx);
                    if (ids_string.Length > 0)
                    {
                        sql            = string.Format(sql, ids_string);
                        com            = new OracleCommand(sql);
                        com.Connection = con;
                        reader         = com.ExecuteReader();
                        while (reader.Read())
                        {
                            long   id  = reader.GetInt64(0);
                            string key = reader.IsDBNull(1) ? null : reader.GetString(1);
                            string val = reader.IsDBNull(2) ? null : reader.GetString(2);

                            Way way;
                            if (ways.TryGetValue(id, out way))
                            {
                                if (way.Tags == null)
                                {
                                    way.Tags = new TagsCollection();
                                }
                                way.Tags.Add(key, val);
                            }
                        }
                        reader.Close();
                    }
                }

                return(ways.Values.ToList <Way>());
            }
            return(new List <Way>());
        }
Ejemplo n.º 52
0
        private bool MoveNextWay()
        {
            if (_wayReader == null)
            {
                OracleCommand way_command = new OracleCommand("select * from way order by id");
                way_command.Connection = _connection;
                _wayReader             = way_command.ExecuteReader();
                if (!_wayReader.Read())
                {
                    _wayReader.Close();
                }
                OracleCommand way_tag_command = new OracleCommand("select * from way_tags order by way_id");
                way_tag_command.Connection = _connection;
                _wayTagReader = way_tag_command.ExecuteReader();
                if (!_wayTagReader.IsClosed && !_wayTagReader.Read())
                {
                    _wayTagReader.Close();
                }
                OracleCommand way_node_command = new OracleCommand("select * from way_nodes order by way_id,sequence_id");
                way_node_command.Connection = _connection;
                _wayNodeReader = way_node_command.ExecuteReader();
                if (!_wayNodeReader.IsClosed && !_wayNodeReader.Read())
                {
                    _wayNodeReader.Close();
                }
            }

            // read next way.
            if (!_wayReader.IsClosed)
            {
                // load/parse data.
                long     id           = _wayReader.GetInt64(0);
                long     changeset_id = _wayReader.GetInt64(1);
                DateTime timestamp    = _wayReader.GetDateTime(2);
                bool     visible      = _wayReader.GetInt64(3) == 1;
                long     version      = _wayReader.GetInt64(4);
                string   user         = _wayReader.GetString(5);
                long     uid          = _wayReader.GetInt64(6);

                Way way = new Way();
                way.Id          = id;
                way.ChangeSetId = changeset_id;
                way.TimeStamp   = timestamp;
                way.UserId      = uid;
                way.UserName    = user;
                way.Version     = (ulong)version;
                way.Visible     = visible;

                if (!_wayTagReader.IsClosed)
                {
                    long returned_id = _wayTagReader.GetInt64(_wayTagReader.GetOrdinal("way_id"));
                    while (returned_id == way.Id.Value)
                    {
                        if (way.Tags == null)
                        {
                            way.Tags = new SimpleTagsCollection();
                        }
                        string key   = _wayTagReader.GetString(1);
                        string value = _wayTagReader.GetString(2);

                        way.Tags.Add(key, value);

                        if (!_wayTagReader.Read())
                        {
                            _wayTagReader.Close();
                            returned_id = -1;
                        }
                        else
                        {
                            returned_id = _wayTagReader.GetInt64(0);
                        }
                    }
                }
                if (!_wayNodeReader.IsClosed)
                {
                    long returned_id = _wayNodeReader.GetInt64(_wayNodeReader.GetOrdinal("way_id"));
                    while (returned_id == way.Id.Value)
                    {
                        if (way.Nodes == null)
                        {
                            way.Nodes = new List <long>();
                        }
                        long node_id = _wayNodeReader.GetInt64(1);

                        way.Nodes.Add(node_id);

                        if (!_wayNodeReader.Read())
                        {
                            _wayNodeReader.Close();
                            returned_id = -1;
                        }
                        else
                        {
                            returned_id = _wayNodeReader.GetInt64(0);
                        }
                    }
                }

                // set the current variable!
                _current = way;

                // advance the reader(s).
                if (!_wayReader.Read())
                {
                    _wayReader.Close();
                }
                if (!_wayTagReader.IsClosed && !_wayTagReader.Read())
                {
                    _wayTagReader.Close();
                }
                if (!_wayNodeReader.IsClosed && !_wayNodeReader.Read())
                {
                    _wayNodeReader.Close();
                }
                return(true);
            }
            else
            {
                _wayReader.Close();
                _wayReader.Dispose();
                _wayReader = null;

                _wayTagReader.Close();
                _wayTagReader.Dispose();
                _wayTagReader = null;

                _current_type = OsmGeoType.Relation;

                return(false);
            }
        }
Ejemplo n.º 53
0
 public static double Area(this Way way)
 {
     //is the way closed? maybe a warning is needed
     return(Geometry.Query.Area(way.ToUTMPolyline()));
 }
Ejemplo n.º 54
0
 /// <summary>
 /// Processes a way.
 /// </summary>
 /// <param name="block"></param>
 /// <param name="way"></param>
 void IPBFOsmPrimitiveConsumer.ProcessWay(PrimitiveBlock block, Way way)
 {
     this.QueuePrimitive(block, way);
 }
Ejemplo n.º 55
0
 public abstract IEnumerator Build(Way w, MapChunkLoader mcl);
Ejemplo n.º 56
0
 /// <summary>
 /// Adds a way to the target.
 /// </summary>
 /// <param name="simpleWay"></param>
 public abstract void AddWay(Way simpleWay);
Ejemplo n.º 57
0
 /// <summary>
 /// Processes a way.
 /// </summary>
 /// <param name="block"></param>
 /// <param name="way"></param>
 void IPBFOsmPrimitiveConsumer.ProcessWay(PrimitiveBlock block, Way way)
 {
     this.QueuePrimitive(block, way);
 }
Ejemplo n.º 58
0
        public void TestMappings()
        {
            Assert.AreEqual(0, session.Query <Visit>().ToList().Count);
            Assert.IsNotNull(session);
            Assert.IsTrue(session.IsConnected);
            Assert.IsTrue(session.IsOpen);

            // test insert and updates
            using (var transaction = session.BeginTransaction())
            {
                var visit = new Visit
                {
                    ExternalReference = "someKey",
                    NumberOfChildren  = 10,
                    Street            = "somestreet",
                    Year    = 2018,
                    Zip     = 5600,
                    City    = "Lenzburg",
                    Desired = new List <Period> {
                        new Period {
                            Start = DateTime.Now
                        }
                    },
                    Unavailable = new List <Period> {
                        new Period {
                            End = DateTime.Today
                        }
                    }
                };

                visit = session.Merge(visit);
                Assert.AreEqual(10, visit.NumberOfChildren);
                visit.NumberOfChildren = 5;
                var updatedVisit = session.Get <Visit>(visit.Id);
                Assert.AreEqual(visit.NumberOfChildren, updatedVisit.NumberOfChildren);

                var visit2 = new Visit
                {
                    ExternalReference = "someKey2",
                    NumberOfChildren  = 3,
                    Street            = "some other street",
                    Year        = 2018,
                    Zip         = 5000,
                    City        = "Aarau",
                    Desired     = new List <Period>(),
                    Unavailable = new List <Period>()
                };
                visit2 = session.Merge(visit2);

                var way = new Way
                {
                    Distance = 100,
                    Duration = 200,
                    From     = visit,
                    To       = visit2
                };
                var way2 = new Way
                {
                    Distance = 200,
                    Duration = 100,
                    From     = visit2,
                    To       = visit
                };

                way  = session.Merge(way);
                way2 = session.Merge(way2);
                transaction.Commit();
            }

            // check relations
            using (var transaction = session.BeginTransaction())
            {
                var managedVisits  = session.Query <Visit>().ToList();
                var managedWays    = session.Query <Way>().ToList();
                var managedPeriods = session.Query <Period>().ToList();
                Assert.AreEqual(2, managedPeriods.Count);
                Assert.AreEqual(2, managedVisits.Count);
                Assert.AreEqual(2, managedWays.Count);
                var visit = managedVisits.First();
                Assert.AreEqual(visit.Desired.First().Id, managedPeriods.FirstOrDefault(p => p.Start != null)?.Id);
                Assert.AreEqual(visit.Unavailable.First().Id,
                                managedPeriods.FirstOrDefault(p => p.Start == null)?.Id);
                Assert.AreEqual(1, managedWays.Count(w => w.From.Id == visit.Id));
                Assert.AreEqual(1, managedWays.Count(w => w.To.Id == visit.Id));
                transaction.Commit();
            }

            // check delete cascading
            using (var transaction = session.BeginTransaction())
            {
                var managedVisits = session.Query <Visit>().ToList();
                foreach (var managedVisit in managedVisits)
                {
                    session.Delete(managedVisit);
                }

                var allPeriods = session.Query <Period>().ToList();
                var allWays    = session.Query <Way>().ToList();
                Assert.AreEqual(0, allPeriods.Count);
                Assert.AreEqual(0, allWays.Count);
                transaction.Commit();
            }

            // also check if db is updated
            session.Clear();
            using (var transaction = session.BeginTransaction())
            {
                var allPeriods = session.Query <Period>().ToList();
                var allWays    = session.Query <Way>().ToList();
                Assert.AreEqual(0, allPeriods.Count);
                Assert.AreEqual(0, allWays.Count);
                transaction.Commit();
            }
        }
Ejemplo n.º 59
0
 public OrderBook(Way way)
 {
     orderway = way;
 }
Ejemplo n.º 60
0
        /// <summary>
        /// Tests read/writing a way.
        /// </summary>
        protected void TestWayReadWrite()
        {
            this.NotifyEmptyExpected(); // empty test database.

            // create a test-way.
            Way way = new Way();

            way.Id = 1;

            // create a target, add the way, create a source and verify way in db.
            var target = this.CreateDataStreamTarget();

            target.Initialize();
            target.AddWay(way);
            target.Flush();
            target.Close();
            var dataSource = this.CreateDataSource();
            Way foundWay   = dataSource.GetWay(1);

            this.CompareWays(way, foundWay);

            this.NotifyEmptyExpected(); // empty test database.

            // create a test-way.
            way          = new Way();
            way.Id       = 1;
            way.UserName = "******";

            // create a target, add the way, create a source and verify way in db.
            target = this.CreateDataStreamTarget();
            target.Initialize();
            target.AddWay(way);
            target.Flush();
            target.Close();
            dataSource = this.CreateDataSource();
            foundWay   = dataSource.GetWay(1);
            this.CompareWays(way, foundWay);

            this.NotifyEmptyExpected(); // empty test database.

            // create a test-way.
            way          = new Way();
            way.Id       = 1;
            way.UserName = "******";
            way.UserId   = 10;

            // create a target, add the way, create a source and verify way in db.
            target = this.CreateDataStreamTarget();
            target.Initialize();
            target.AddWay(way);
            target.Flush();
            target.Close();
            dataSource = this.CreateDataSource();
            foundWay   = dataSource.GetWay(1);
            this.CompareWays(way, foundWay);

            this.NotifyEmptyExpected(); // empty test database.

            // create a test-way.
            way          = new Way();
            way.Id       = 1;
            way.UserName = "******";
            way.UserId   = 10;
            way.Version  = 1;

            // create a target, add the way, create a source and verify way in db.
            target = this.CreateDataStreamTarget();
            target.Initialize();
            target.AddWay(way);
            target.Flush();
            target.Close();
            dataSource = this.CreateDataSource();
            foundWay   = dataSource.GetWay(1);
            this.CompareWays(way, foundWay);

            this.NotifyEmptyExpected(); // empty test database.

            // create a test-way.
            way          = new Way();
            way.Id       = 1;
            way.UserName = "******";
            way.UserId   = 10;
            way.Version  = 1;
            way.Visible  = true;

            // create a target, add the way, create a source and verify way in db.
            target = this.CreateDataStreamTarget();
            target.Initialize();
            target.AddWay(way);
            target.Flush();
            target.Close();
            dataSource = this.CreateDataSource();
            foundWay   = dataSource.GetWay(1);
            this.CompareWays(way, foundWay);

            this.NotifyEmptyExpected(); // empty test database.

            // create a test-way.
            way           = new Way();
            way.Id        = 1;
            way.UserName  = "******";
            way.UserId    = 10;
            way.Version   = 1;
            way.Visible   = true;
            way.TimeStamp = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day,
                                         DateTime.Now.Hour, DateTime.Now.Minute, DateTime.Now.Second);

            // create a target, add the way, create a source and verify way in db.
            target = this.CreateDataStreamTarget();
            target.Initialize();
            target.AddWay(way);
            target.Flush();
            target.Close();
            dataSource = this.CreateDataSource();
            foundWay   = dataSource.GetWay(1);
            this.CompareWays(way, foundWay);


            this.NotifyEmptyExpected(); // empty test database.

            // create a test-way.
            way           = new Way();
            way.Id        = 1;
            way.UserName  = "******";
            way.UserId    = 10;
            way.Version   = 1;
            way.Visible   = true;
            way.TimeStamp = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day,
                                         DateTime.Now.Hour, DateTime.Now.Minute, DateTime.Now.Second);
            way.Tags = new SimpleTagsCollection();
            way.Tags.Add("tag", "value");

            // create a target, add the way, create a source and verify way in db.
            target = this.CreateDataStreamTarget();
            target.Initialize();
            target.AddWay(way);
            target.Flush();
            target.Close();
            dataSource = this.CreateDataSource();
            foundWay   = dataSource.GetWay(1);
            this.CompareWays(way, foundWay);

            this.NotifyEmptyExpected(); // empty test database.

            // create a test-way.
            way           = new Way();
            way.Id        = 1;
            way.UserName  = "******";
            way.UserId    = 10;
            way.Version   = 1;
            way.Visible   = true;
            way.TimeStamp = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day,
                                         DateTime.Now.Hour, DateTime.Now.Minute, DateTime.Now.Second);
            way.Nodes = new List <long>();
            way.Nodes.Add(1);
            way.Nodes.Add(2);
            way.Nodes.Add(3);
            way.Nodes.Add(1);

            // create a target, add the way, create a source and verify way in db.
            target = this.CreateDataStreamTarget();
            target.Initialize();
            target.AddWay(way);
            target.Flush();
            target.Close();
            dataSource = this.CreateDataSource();
            foundWay   = dataSource.GetWay(1);
            this.CompareWays(way, foundWay);
        }