コード例 #1
0
        internal static Relation ConvertToSimple(Osm.Xml.v0_6.relation re)
        {
            Relation relation = new Relation();

            // set id
            if (re.idSpecified)
            {
                relation.Id = re.id;
            }

            // set changeset.
            if (re.changesetSpecified)
            {
                relation.ChangeSetId = re.changeset;
            }

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

            // set timestamp.
            if (re.timestampSpecified)
            {
                relation.TimeStamp = re.timestamp;
            }

            // set uid
            if (re.uidSpecified)
            {
                relation.UserId = re.uid;
            }

            // set version
            if (re.versionSpecified)
            {
                relation.Version = re.version;
            }

            // set user
            relation.UserName = re.user;

            // set tags.
            relation.Tags = XmlSimpleConverter.ConvertToTags(re.tag);

            // set members.
            if (re.member != null && re.member.Length > 0)
            {
                relation.Members = new List<RelationMember>();
                for (int idx = 0; idx < re.member.Length; idx++)
                {
                    OsmSharp.Osm.Xml.v0_6.member mem = re.member[idx];
                    RelationMember relation_member = new RelationMember();
                    // set memberid
                    if (mem.refSpecified)
                    {
                        relation_member.MemberId = mem.@ref;
                    }

                    // set role.
                    relation_member.MemberRole = mem.role;

                    // set type.
                    if (mem.typeSpecified)
                    {
                        switch (mem.type)
                        {
                            case OsmSharp.Osm.Xml.v0_6.memberType.node:
                                relation_member.MemberType = OsmGeoType.Node;
                                break;
                            case OsmSharp.Osm.Xml.v0_6.memberType.way:
                                relation_member.MemberType = OsmGeoType.Way;
                                break;
                            case OsmSharp.Osm.Xml.v0_6.memberType.relation:
                                relation_member.MemberType = OsmGeoType.Relation;
                                break;
                        }
                    }

                    relation.Members.Add(relation_member);
                }
            }

            return relation;
        }
コード例 #2
0
ファイル: RelationProvider.cs プロジェクト: dkme/moooyo
        public static CBB.ExceptionHelper.OperationResult DeleteRelation(RelationMember obj)
        {
            try
            {
                MongoDatabase md = MongoDBHelper.MongoDB;
                MongoCollection<RelationMember> mc = md.GetCollection<RelationMember>(obj.GetCollectionName());
                IMongoQuery qc = Query.And(Query.EQ("FromMember", obj.FromMember), Query.EQ("ToMember", obj.ToMember));
                mc.Remove(qc);

                return new CBB.ExceptionHelper.OperationResult(true);
            }
            catch (System.Exception err)
            {
                throw new CBB.ExceptionHelper.OperationException(
                    CBB.ExceptionHelper.ErrType.SystemErr,
                    CBB.ExceptionHelper.ErrNo.DBOperationError,
                    err);
            }
        }
コード例 #3
0
        /// <summary>
        /// Returns the relations for the given ids.
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public override IList <Relation> GetRelations(IList <long> ids)
        {
            if (ids.Count > 0)
            {
                OracleConnection con = this.CreateConnection();

                // STEP2: Load ways.
                Dictionary <long, Relation> relations = new Dictionary <long, Relation>();
                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, visible, timestamp, version, usr, usr_id FROM relation 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();
                        Relation relation;
                        while (reader.Read())
                        {
                            long     id           = reader.GetInt64(0);
                            long?    changeset_id = reader.IsDBNull(1) ? null : (long?)reader.GetInt64(1);
                            bool?    visible      = reader.IsDBNull(2) ? null : (bool?)(reader.GetInt16(2) == 1);
                            DateTime?timestamp    = reader.IsDBNull(3) ? null : (DateTime?)reader.GetDateTime(3);
                            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.
                            relation             = new Relation();
                            relation.Id          = id;
                            relation.Version     = version;
                            relation.UserName    = user;
                            relation.UserId      = user_id;
                            relation.Visible     = visible;
                            relation.TimeStamp   = timestamp;
                            relation.ChangeSetId = changeset_id;

                            relations.Add(relation.Id.Value, relation);
                        }
                        reader.Close();
                    }
                }

                //STEP3: Load all relation-member 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 relation_id, member_type, member_id, member_role, sequence_id FROM relation_members WHERE (relation_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   relation_id = reader.GetInt64(0);
                            long   member_type = reader.GetInt16(1);
                            long?  member_id   = reader.IsDBNull(2) ? null : (long?)reader.GetInt64(2);
                            string member_role = reader.IsDBNull(3) ? null : reader.GetString(3);

                            Relation relation;
                            if (relations.TryGetValue(relation_id, out relation))
                            {
                                if (relation.Members == null)
                                {
                                    relation.Members = new List <RelationMember>();
                                }
                                RelationMember member = new RelationMember();
                                member.MemberId   = member_id;
                                member.MemberRole = member_role;
                                member.MemberType = this.ConvertMemberType(member_type);

                                relation.Members.Add(member);
                            }
                        }
                        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 relation_tags WHERE (relation_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.GetString(1);
                            object value_object = reader[2];
                            string value        = string.Empty;
                            if (value_object != null && value_object != DBNull.Value)
                            {
                                value = (string)value_object;
                            }

                            Relation relation;
                            if (relations.TryGetValue(id, out relation))
                            {
                                if (relation.Tags == null)
                                {
                                    relation.Tags = new TagsCollection();
                                }
                                relation.Tags.Add(key, value);
                            }
                        }
                        reader.Close();
                    }
                }

                return(relations.Values.ToList <Relation>());
            }
            return(new List <Relation>());
        }
コード例 #4
0
ファイル: OpenStreetMapSource.cs プロジェクト: temik911/audio
        void ParseXml(XmlDocument xmlDoc)
        {
            XmlNode mainNode = xmlDoc.SelectSingleNode("osm");

            var nodes = mainNode.SelectNodes("node");

            if (allNodes == null) {
                allNodes = new Dictionary<long, osmNode>(nodes.Count);
            }

            for (int i = 0; i < nodes.Count; i++) {
                var lat = nodes[i].Attributes["lat"].Value;
                var lon = nodes[i].Attributes["lon"].Value;
                var id  = nodes[i].Attributes["id"].Value;

                var node		= new osmNode {id = long.Parse(id), Latitude = double.Parse(lat), Longitude = double.Parse(lon)};
                node.Position	= GeoHelper.WorldToTilePos(node.Longitude, node.Latitude);

                if (!allNodes.ContainsKey(node.id)) {
                    allNodes.Add(node.id, node);
                }
            }

            var ways = mainNode.SelectNodes("way");

            if (allWays == null) {
                allWays = new Dictionary<long, osmWay>(ways.Count);
            }

            foreach (XmlNode way in ways) {
                long id = long.Parse(way.Attributes["id"].Value);

                var refNodes = way.SelectNodes("nd");
                long[] refs = new long[0];
                if (refNodes != null) {
                    refs = new long[refNodes.Count];
                    for (int i = 0; i < refNodes.Count; i++) {
                        refs[i] = long.Parse(refNodes[i].Attributes["ref"].Value);
                    }
                }

                float minX = float.MaxValue;
                float minY = float.MaxValue;
                float maxX = float.MinValue;
                float maxY = float.MinValue;

                foreach (var reff in refs) {
                    osmNode nd;
                    if (allNodes.TryGetValue(reff, out nd)) {
                        var p = nd.Position;
                        if (p.X < minX) minX = p.X;
                        if (p.Y < minY) minY = p.Y;
                        if (p.X > maxX) maxX = p.X;
                        if (p.Y > maxY) maxY = p.Y;
                    }
                }

                var bbox = new BoundingBox(new Vector3(minX, minY, -1.0f), new Vector3(maxX, maxY, 1.0f));

                osmWay osmWay = new osmWay {
                        id		= id,
                        nodeRef = refs,
                        BBox	= bbox
                    };

                var tags = way.SelectNodes("tag");
                if (tags != null) {
                    foreach (XmlNode tag in tags) {
                        var key = tag.Attributes["k"].Value;
                        var val = tag.Attributes["v"].Value;

                        if (key == "building" || key == "building:levels") {
                            osmWay.isBuilding = true;
                        }
                        if (key == "highway") {
                            osmWay.isHighway = true;
                        }
                    }
                }

                if (!allWays.ContainsKey(id)) {
                    allWays.Add(id, osmWay);
                }
            }

            var relations	= mainNode.SelectNodes("relation");

            if (allRelations == null) {
                allRelations = new Dictionary<long, osmRelation>();
            }

            foreach (XmlNode rel in relations) {
                long id = long.Parse(rel.Attributes["id"].Value);

                var refMembers = rel.SelectNodes("member");
                var members = new RelationMember[0];
                if (refMembers != null) {
                    members = new RelationMember[refMembers.Count];
                    for (int i = 0; i < refMembers.Count; i++) {

                        var rm = refMembers[i];

                        var type = rm.Attributes["type"].Value;
                        MemberType mType = MemberType.Way;
                        if (type == "node") mType = MemberType.Node;

                        long refff = long.Parse(rm.Attributes["ref"].Value);

                        MemberRole mRole = MemberRole.None;
                        var role = rm.Attributes["role"].Value;
                        if (role == "inner") mRole = MemberRole.Inner;
                        if (role == "outer") mRole = MemberRole.Outer;

                        members[i] = new RelationMember {Ref = refff, Role = mRole, Type = mType};
                    }
                }

                var refTags = rel.SelectNodes("tag");
                Dictionary<string, string> tags = new Dictionary<string, string>();
                if (refTags != null) {
                    foreach (XmlNode tag in refTags) {
                        var key = tag.Attributes["k"].Value;
                        var val = tag.Attributes["v"].Value;

                        tags.Add(key, val);
                    }
                }

                if (!allRelations.ContainsKey(id)) {
                    allRelations.Add(id, new osmRelation {Id = id, Members = members, Tags = tags});
                }
            }
        }
コード例 #5
0
ファイル: CacheHelper.cs プロジェクト: vogelb/ambeth
        protected void EnsureInitializedRelationsIntern3(Object obj, PrefetchPath[] cachePaths, ILinkedMap <Type, PrefetchPath[]> entityTypeToPrefetchPaths,
                                                         IMap <ICacheIntern, IISet <IObjRef> > cacheToOrisToLoad, IMap <ICacheIntern, IMap <IObjRelation, bool> > cacheToOrelsToLoad,
                                                         IMap <ICacheIntern, IISet <IObjRef> > cacheToOrisLoadedHistory, IMap <ICacheIntern, IISet <IObjRelation> > cacheToOrelsLoadedHistory,
                                                         AlreadyHandledSet alreadyHandledSet, IList <PrefetchCommand> cascadeLoadItems)
        {
            if (obj == null)
            {
                return;
            }
            if (!alreadyHandledSet.PutIfNotExists(obj, cachePaths, true))
            {
                return;
            }
            if (obj is IndirectValueHolderRef)
            {
                IndirectValueHolderRef vhk = (IndirectValueHolderRef)obj;
                HandleValueHolder(vhk, cachePaths, cacheToOrisToLoad, cacheToOrelsToLoad, cacheToOrisLoadedHistory, cacheToOrelsLoadedHistory,
                                  alreadyHandledSet, cascadeLoadItems);
                // Do nothing because this is only to prefetch RootCache entries
                return;
            }
            else if (obj is DirectValueHolderRef)
            {
                DirectValueHolderRef vhk = (DirectValueHolderRef)obj;
                if (!HandleValueHolder(vhk, cachePaths, cacheToOrisToLoad, cacheToOrelsToLoad, cacheToOrisLoadedHistory, cacheToOrelsLoadedHistory,
                                       alreadyHandledSet, cascadeLoadItems))
                {
                    return;
                }
                // force valueholder init. at this point we know that all related items are already in the cache. there will be no roundtrip
                // to the server
                if (vhk.Member == null)
                {
                    obj = vhk.Vhc;
                }
                else
                {
                    obj = vhk.Member.GetValue(vhk.Vhc);
                }
            }
            if (obj == null)
            {
                // this check is necessary because even if we create only instances of DirectValueHolderRef in cases where there is a not initalized relation
                // even then it might be possible that a concurrent thread initializes the valueholder to null (e.g. an empty to-one relation)
                return;
            }
            if ((cachePaths == null || cachePaths.Length == 0) && entityTypeToPrefetchPaths == null)
            {
                return;
            }
            if (obj is IEnumerable)
            {
                var items = new List <Object>();
                foreach (Object item in (IEnumerable)obj)
                {
                    if (item == null)
                    {
                        continue;
                    }
                    items.Add(item);
                }
                foreach (Object item in items)
                {
                    EnsureInitializedRelationsIntern3(item, cachePaths, entityTypeToPrefetchPaths, cacheToOrisToLoad, cacheToOrelsToLoad,
                                                      cacheToOrisLoadedHistory, cacheToOrelsLoadedHistory, alreadyHandledSet, cascadeLoadItems);
                }
                return;
            }
            IEntityMetaData metaData = ((IEntityMetaDataHolder)obj).Get__EntityMetaData();

            if (cachePaths == null || cachePaths.Length == 0)
            {
                if (entityTypeToPrefetchPaths != null)
                {
                    cachePaths = entityTypeToPrefetchPaths.Get(metaData.EntityType);
                }
                if (cachePaths == null || cachePaths.Length == 0)
                {
                    return;
                }
            }
            RelationMember[] relationMembers = metaData.RelationMembers;
            if (relationMembers.Length == 0)
            {
                return;
            }
            IValueHolderContainer vhc = (IValueHolderContainer)obj;

            for (int a = cachePaths.Length; a-- > 0;)
            {
                PrefetchPath path = cachePaths[a];

                int            relationIndex = path.memberIndex;
                RelationMember member        = relationMembers[relationIndex];

                if (ValueHolderState.INIT != vhc.Get__State(relationIndex))
                {
                    DirectValueHolderRef vhk = new DirectValueHolderRef(vhc, member);
                    EnsureInitializedRelationsIntern3(vhk, path.children, entityTypeToPrefetchPaths, cacheToOrisToLoad, cacheToOrelsToLoad, cacheToOrisLoadedHistory,
                                                      cacheToOrelsLoadedHistory, alreadyHandledSet, cascadeLoadItems);
                    continue;
                }
                Object memberValue = member.GetValue(obj);
                if (memberValue == null)
                {
                    continue;
                }
                EnsureInitializedRelationsIntern3(memberValue, path.children, entityTypeToPrefetchPaths, cacheToOrisToLoad, cacheToOrelsToLoad,
                                                  cacheToOrisLoadedHistory, cacheToOrelsLoadedHistory, alreadyHandledSet, cascadeLoadItems);
            }
        }
コード例 #6
0
        internal static Relation ConvertToSimple(Osm.Xml.v0_6.relation re)
        {
            Relation relation = new Relation();

            // set id
            if (re.idSpecified)
            {
                relation.Id = re.id;
            }

            // set changeset.
            if (re.changesetSpecified)
            {
                relation.ChangeSetId = re.changeset;
            }

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

            // set timestamp.
            if (re.timestampSpecified)
            {
                relation.TimeStamp = re.timestamp;
            }

            // set uid
            if (re.uidSpecified)
            {
                relation.UserId = re.uid;
            }

            // set version
            if (re.versionSpecified)
            {
                relation.Version = re.version;
            }

            // set user
            relation.UserName = re.user;

            // set tags.
            relation.Tags = XmlSimpleConverter.ConvertToTags(re.tag);

            // set members.
            if (re.member != null && re.member.Length > 0)
            {
                relation.Members = new List <RelationMember>();
                for (int idx = 0; idx < re.member.Length; idx++)
                {
                    OsmSharp.Osm.Xml.v0_6.member mem = re.member[idx];
                    RelationMember relation_member   = new RelationMember();
                    // set memberid
                    if (mem.refSpecified)
                    {
                        relation_member.MemberId = mem.@ref;
                    }

                    // set role.
                    relation_member.MemberRole = mem.role;

                    // set type.
                    if (mem.typeSpecified)
                    {
                        switch (mem.type)
                        {
                        case OsmSharp.Osm.Xml.v0_6.memberType.node:
                            relation_member.MemberType = OsmGeoType.Node;
                            break;

                        case OsmSharp.Osm.Xml.v0_6.memberType.way:
                            relation_member.MemberType = OsmGeoType.Way;
                            break;

                        case OsmSharp.Osm.Xml.v0_6.memberType.relation:
                            relation_member.MemberType = OsmGeoType.Relation;
                            break;
                        }
                    }

                    relation.Members.Add(relation_member);
                }
            }

            return(relation);
        }
コード例 #7
0
ファイル: EntityMetaData.cs プロジェクト: vogelb/ambeth
        public void Initialize(ICacheModification cacheModification, IEntityFactory entityFactory)
        {
            this.cacheModification = cacheModification;
            this.entityFactory     = entityFactory;
            if (AlternateIdMemberIndicesInPrimitives == null)
            {
                AlternateIdMemberIndicesInPrimitives = EmptyShortArray;
            }

            if (PrimitiveMembers == null)
            {
                PrimitiveMembers = EmptyPrimitiveMembers;
            }
            else
            {
                // Array.Sort<INamed>(PrimitiveMembers, namedItemComparer);
            }
            List <PrimitiveMember> primitiveToManyMembers = new List <PrimitiveMember>();

            foreach (PrimitiveMember primitiveMember in PrimitiveMembers)
            {
                if (primitiveMember.IsToMany)
                {
                    primitiveToManyMembers.Add(primitiveMember);
                }
            }
            this.primitiveToManyMembers = primitiveToManyMembers.ToArray();

            if (RelationMembers == null)
            {
                RelationMembers = EmptyRelationMembers;
            }
            else
            {
                // Array.Sort<INamed>(RelationMembers, namedItemComparer);
            }

            if (AlternateIdMembers == null)
            {
                AlternateIdMembers = EmptyPrimitiveMembers;
            }
            else
            {
                // Array.Sort<INamed>(AlternateIdMembers, namedItemComparer);
            }

            nameToMemberDict.Clear();
            relMemberToIndexDict.Clear();
            relMemberNameToIndexDict.Clear();
            primMemberToIndexDict.Clear();
            primMemberNameToIndexDict.Clear();
            if (IdMember != null)
            {
                PrimitiveMember idMember = IdMember;
                nameToMemberDict.Add(idMember.Name, idMember);
                if (idMember is CompositeIdMember)
                {
                    foreach (PrimitiveMember member in ((CompositeIdMember)idMember).Members)
                    {
                        nameToMemberDict.Add(member.Name, member);
                    }
                }
            }
            if (VersionMember != null)
            {
                nameToMemberDict.Add(VersionMember.Name, VersionMember);
            }
            for (int a = PrimitiveMembers.Length; a-- > 0;)
            {
                Member member = PrimitiveMembers[a];
                nameToMemberDict.Add(member.Name, member);
                primMemberNameToIndexDict.Add(member.Name, a);
                primMemberToIndexDict.Add(member, a);
                if (Object.ReferenceEquals(member, IdMember) || Object.ReferenceEquals(member, VersionMember) || Object.ReferenceEquals(member, UpdatedByMember) ||
                    Object.ReferenceEquals(member, UpdatedOnMember) || Object.ReferenceEquals(member, CreatedByMember) || Object.ReferenceEquals(member, CreatedOnMember))
                {
                    // technical members must never be merge relevant
                    SetMergeRelevant(member, false);
                }
            }
            for (int a = RelationMembers.Length; a-- > 0;)
            {
                RelationMember member = RelationMembers[a];
                nameToMemberDict.Add(member.Name, member);
                relMemberNameToIndexDict.Add(member.Name, a);
                relMemberToIndexDict.Add(member, a);
            }
            memberNameToIdIndexDict.Clear();
            if (IdMember != null)
            {
                memberNameToIdIndexDict.Add(IdMember.Name, ObjRef.PRIMARY_KEY_INDEX);
            }
            AlternateIdMemberIndicesInPrimitives = new int[AlternateIdMembers.Length][];
            for (int idIndex = AlternateIdMembers.Length; idIndex-- > 0;)
            {
                int[]    compositeIndex    = null;
                Member   alternateIdMember = AlternateIdMembers[idIndex];
                Member[] memberItems;
                if (alternateIdMember is CompositeIdMember)
                {
                    memberItems = ((CompositeIdMember)alternateIdMember).Members;
                }
                else
                {
                    memberItems = new Member[] { alternateIdMember };
                }
                compositeIndex = new int[memberItems.Length];

                for (int compositePosition = compositeIndex.Length; compositePosition-- > 0;)
                {
                    compositeIndex[compositePosition] = -1;
                    Member memberItem = memberItems[compositePosition];
                    for (int primitiveIndex = PrimitiveMembers.Length; primitiveIndex-- > 0;)
                    {
                        if (memberItem.Equals(PrimitiveMembers[primitiveIndex]))
                        {
                            compositeIndex[compositePosition] = primitiveIndex;
                            break;
                        }
                    }
                    if (compositeIndex[compositePosition] == -1)
                    {
                        throw new Exception("AlternateId is not a primitive: " + memberItem);
                    }
                }
                AlternateIdMemberIndicesInPrimitives[idIndex] = compositeIndex;
                memberNameToIdIndexDict.Add(alternateIdMember.Name, (sbyte)idIndex);
            }

            if (TypesRelatingToThis != null && TypesRelatingToThis.Length > 0)
            {
                for (int i = TypesRelatingToThis.Length; i-- > 0;)
                {
                    typesRelatingToThisSet.Add(TypesRelatingToThis[i]);
                }
            }
            if (CreatedByMember != null)
            {
                ChangeInterningBehavior(CreatedByMember, true);
            }
            if (UpdatedByMember != null)
            {
                ChangeInterningBehavior(UpdatedByMember, true);
            }
            SetTechnicalMember(IdMember);
            SetTechnicalMember(VersionMember);
            SetTechnicalMember(CreatedByMember);
            SetTechnicalMember(CreatedOnMember);
            SetTechnicalMember(UpdatedByMember);
            SetTechnicalMember(UpdatedOnMember);
        }
コード例 #8
0
ファイル: CacheHelper.cs プロジェクト: vogelb/ambeth
        protected void ProcessPendingOrelsAndObjRefs(ILinkedMap <Type, PrefetchPath[]> entityTypeToPrefetchPath,
                                                     AlreadyHandledSet alreadyHandledSet, IdentityLinkedMap <ICacheIntern, IISet <IObjRef> > cacheToOrisLoadedHistory,
                                                     IdentityLinkedMap <ICacheIntern, IISet <IObjRelation> > cacheToOrelsLoadedHistory, IdentityLinkedMap <ICacheIntern, IISet <IObjRef> > cacheToOrisToLoad,
                                                     IdentityLinkedMap <ICacheIntern, IMap <IObjRelation, bool> > cacheToOrelsToLoad, List <PrefetchCommand> pendingPrefetchCommands,
                                                     List <Object> hardRefList)
        {
            // all relation members where at least one instance of the owning entity type needs a prefetch on this member in the immediate next step
            MergePrefetchPathsCache mergePrefetchPathsCache = new MergePrefetchPathsCache(EntityMetaDataProvider);

            IdentityLinkedSet <Member> prioMembers = PrioMembersProvider.GetPrioMembers(entityTypeToPrefetchPath, pendingPrefetchCommands, mergePrefetchPathsCache);

            LoadAndAddOrels(cacheToOrelsToLoad, hardRefList, cacheToOrelsLoadedHistory, cacheToOrisToLoad, prioMembers);
            LoadAndAddOris(cacheToOrisToLoad, hardRefList, cacheToOrisLoadedHistory);

            while (pendingPrefetchCommands.Count > 0)
            {
                PrefetchCommand[] currentPrefetchCommands = pendingPrefetchCommands.ToArray();
                // Clear the items to be ready for cascaded items in new batch recursion step
                pendingPrefetchCommands.Clear();
                if (prioMembers.Count > 0)
                {
                    for (int a = 0, size = currentPrefetchCommands.Length; a < size; a++)
                    {
                        PrefetchCommand      prefetchCommand = currentPrefetchCommands[a];
                        DirectValueHolderRef valueHolder     = prefetchCommand.valueHolder;
                        if (!prioMembers.Contains(valueHolder.Member))
                        {
                            currentPrefetchCommands[a] = null;
                            pendingPrefetchCommands.Add(prefetchCommand);
                        }
                    }
                }
                GuiThreadHelper.InvokeInGuiAndWait(delegate()
                {
                    ICacheModification cacheModification = CacheModification;
                    ValueHolderContainerMixin valueHolderContainerMixin = ValueHolderContainerMixin;
                    bool oldActive = cacheModification.Active;
                    if (!oldActive)
                    {
                        cacheModification.Active = true;
                    }
                    try
                    {
                        foreach (PrefetchCommand prefetchCommand in currentPrefetchCommands)
                        {
                            if (prefetchCommand == null)
                            {
                                continue;
                            }
                            DirectValueHolderRef valueHolder = prefetchCommand.valueHolder;
                            PrefetchPath[] cachePaths        = prefetchCommand.prefetchPaths;

                            RelationMember member = valueHolder.Member;
                            // Merge the root prefetch path with the relative prefetch path
                            cachePaths = mergePrefetchPathsCache.MergePrefetchPaths(member.ElementType, cachePaths, entityTypeToPrefetchPath);

                            IObjRefContainer vhc = valueHolder.Vhc;
                            ICacheIntern targetCache;
                            bool doSetValue = false;
                            if (valueHolder is IndirectValueHolderRef)
                            {
                                IndirectValueHolderRef valueHolderKey = (IndirectValueHolderRef)valueHolder;
                                targetCache = valueHolderKey.RootCache;
                            }
                            else
                            {
                                targetCache = ((IValueHolderContainer)vhc).__TargetCache;
                                doSetValue  = true;
                            }
                            int relationIndex = vhc.Get__EntityMetaData().GetIndexByRelation(member);
                            IObjRef[] objRefs = vhc.Get__ObjRefs(relationIndex);
                            Object obj        = valueHolderContainerMixin.GetValue(vhc, relationIndex, member, targetCache, objRefs, CacheDirective.FailEarly);
                            if (doSetValue && obj != null)
                            {
                                member.SetValue(vhc, obj);
                            }
                            EnsureInitializedRelationsIntern3(obj, cachePaths, entityTypeToPrefetchPath, cacheToOrisToLoad, cacheToOrelsToLoad, cacheToOrisLoadedHistory,
                                                              cacheToOrelsLoadedHistory, alreadyHandledSet, pendingPrefetchCommands);
                        }
                    }
                    finally
                    {
                        if (!oldActive)
                        {
                            cacheModification.Active = false;
                        }
                    }
                });
                // Remove all oris which have already been tried to load before
                if (cacheToOrisToLoad.Count == 0 && cacheToOrelsToLoad.Count == 0 && pendingPrefetchCommands.Count == 0)
                {
                    return;
                }
                prioMembers = PrioMembersProvider.GetPrioMembers(entityTypeToPrefetchPath, pendingPrefetchCommands, mergePrefetchPathsCache);
                LoadAndAddOrels(cacheToOrelsToLoad, hardRefList, cacheToOrelsLoadedHistory, cacheToOrisToLoad, prioMembers);
                LoadAndAddOris(cacheToOrisToLoad, hardRefList, cacheToOrisLoadedHistory);
            }
        }
コード例 #9
0
        public void TestFilterSort()
        {
            // execute
            var filter = new OsmStreamFilterSort();

            filter.RegisterSource(new OsmGeo[] {
                Node.Create(1, 0, 0),
                Node.Create(2, 1, 0),
                Node.Create(3, 0, 1),
                Way.Create(1, 1, 2, 3)
            });
            var list = new List <OsmGeo>(
                filter);

            // verify.
            Assert.IsNotNull(list);
            Assert.AreEqual(4, list.Count);
            Assert.AreEqual(1, list[0].Id);
            Assert.AreEqual(2, list[1].Id);
            Assert.AreEqual(3, list[2].Id);
            Assert.AreEqual(1, list[3].Id);

            // reset.
            filter.Reset();
            list = new List <OsmGeo>(
                filter);

            // verify.
            Assert.IsNotNull(list);
            Assert.AreEqual(4, list.Count);
            Assert.AreEqual(1, list[0].Id);
            Assert.AreEqual(2, list[1].Id);
            Assert.AreEqual(3, list[2].Id);
            Assert.AreEqual(1, list[3].Id);

            // execute
            filter = new OsmStreamFilterSort();
            filter.RegisterSource(new OsmGeo[] {
                Node.Create(1, 0, 0),
                Node.Create(2, 1, 0),
                Way.Create(1, 1, 2, 3),
                Node.Create(3, 0, 1)
            });
            list = new List <OsmGeo>(
                filter);

            // verify.
            Assert.IsNotNull(list);
            Assert.AreEqual(4, list.Count);
            Assert.AreEqual(1, list[0].Id);
            Assert.AreEqual(2, list[1].Id);
            Assert.AreEqual(3, list[2].Id);
            Assert.AreEqual(1, list[3].Id);

            // execute
            filter = new OsmStreamFilterSort();
            filter.RegisterSource(new OsmGeo[] {
                Node.Create(1, 0, 0),
                Node.Create(2, 1, 0),
                Way.Create(1, 1, 2, 3),
                Relation.Create(1,
                                new TagsCollection(
                                    Tag.Create("type", "multipolygon")),
                                RelationMember.Create(1, "outer", OsmGeoType.Way)),
                Node.Create(3, 0, 1)
            });
            list = new List <OsmGeo>(
                filter);

            // verify.
            Assert.IsNotNull(list);
            Assert.AreEqual(5, list.Count);
            Assert.AreEqual(1, list[0].Id);
            Assert.AreEqual(2, list[1].Id);
            Assert.AreEqual(3, list[2].Id);
            Assert.AreEqual(1, list[3].Id);
            Assert.AreEqual(1, list[4].Id);

            // reset.
            filter.Reset();
            list = new List <OsmGeo>(
                filter);

            // verify.
            Assert.IsNotNull(list);
            Assert.AreEqual(5, list.Count);
            Assert.AreEqual(1, list[0].Id);
            Assert.AreEqual(2, list[1].Id);
            Assert.AreEqual(3, list[2].Id);
            Assert.AreEqual(1, list[3].Id);
            Assert.AreEqual(1, list[4].Id);
        }
コード例 #10
0
 /// <summary>
 /// Initializes a new instance of the RelationMemberInfo structure with values from specific RelationMember.
 /// </summary>
 /// <param name="source">The RelationMember object to copy valyes from.</param>
 public RelationMemberInfo(RelationMember source)
 {
     this.Reference  = source.Member.ID;
     this.MemberType = source.MemberType;
     this.Role       = source.Role;
 }
コード例 #11
0
        protected void HandleValueHolderContainer(IValueHolderContainer vhc, RelationMember[] relationMembers, IObjRef[][] relations)
        {
            ICacheHelper cacheHelper = this.CacheHelper;
            ICacheIntern parent      = this.Parent;
            IProxyHelper proxyHelper = this.ProxyHelper;

            for (int relationIndex = relationMembers.Length; relationIndex-- > 0;)
            {
                RelationMember relationMember    = relationMembers[relationIndex];
                IObjRef[]      relationsOfMember = relations[relationIndex];

                if (!CascadeLoadMode.EAGER.Equals(relationMember.CascadeLoadMode))
                {
                    if (ValueHolderState.INIT != vhc.Get__State(relationIndex))
                    {
                        // Update ObjRef information within the entity and do nothing else
                        vhc.Set__ObjRefs(relationIndex, relationsOfMember);
                        continue;
                    }
                }
                // We can safely access to relation if we want to
                if (relationsOfMember == null)
                {
                    // Reset value holder state because we do not know the content currently
                    vhc.Set__Uninitialized(relationIndex, null);
                    continue;
                }
                Object relationValue = relationMember.GetValue(vhc);
                if (relationsOfMember.Length == 0)
                {
                    if (!relationMember.IsToMany)
                    {
                        if (relationValue != null)
                        {
                            // Relation has to be flushed
                            relationMember.SetValue(vhc, null);
                        }
                    }
                    else
                    {
                        if (relationValue != null)
                        {
                            // Reuse existing collection
                            ListUtil.ClearList(relationValue);
                        }
                        else
                        {
                            // We have to create a new empty collection
                            relationValue = cacheHelper.CreateInstanceOfTargetExpectedType(relationMember.RealType, relationMember.ElementType);
                            relationMember.SetValue(vhc, relationValue);
                        }
                    }
                    continue;
                }
                // So we know the new content (which is not empty) and we know that the current content is already initialized
                // Now we have to refresh the current content eagerly

                // load entities as if we were an "eager valueholder" here
                IList <Object> potentialNewItems = parent.GetObjects(new List <IObjRef>(relationsOfMember), this, CacheDirective.None);
                if (OverwriteToManyRelations)
                {
                    Object newRelationValue = cacheHelper.ConvertResultListToExpectedType(potentialNewItems, relationMember.RealType,
                                                                                          relationMember.ElementType);
                    // Set new to-many-relation, even if there has not changed anything in its item content
                    relationMember.SetValue(vhc, newRelationValue);
                    continue;
                }
                IList <Object> relationItems = ListUtil.AnyToList(relationValue);

                bool diff = (relationItems.Count != potentialNewItems.Count);
                if (!diff)
                {
                    for (int b = potentialNewItems.Count; b-- > 0;)
                    {
                        if (!Object.ReferenceEquals(potentialNewItems[b], relationItems[b]))
                        {
                            diff = true;
                            break;
                        }
                    }
                }
                if (!diff)
                {
                    // Nothing to do
                    continue;
                }
                if (relationValue != null && relationMember.IsToMany)
                {
                    // Reuse existing collection
                    ListUtil.ClearAndFillList(relationValue, relationItems);
                }
                else
                {
                    // We have to create a new empty collection or replace the to-one value
                    Object newRelationValue = cacheHelper.ConvertResultListToExpectedType(potentialNewItems, relationMember.RealType,
                                                                                          relationMember.ElementType);
                    relationMember.SetValue(vhc, newRelationValue);
                }
            }
        }
コード例 #12
0
        /// <summary>
        /// Converts an Xml relation to an Osm domain model relation.
        /// </summary>
        /// <param name="xml_obj"></param>
        /// <returns></returns>
        public static Relation ConvertFrom(this relation xml_obj)
        {
            // create a new node and immidiately set the id.
            Relation new_obj = new Relation();

            new_obj.Id = xml_obj.id;

            // set the members
            new_obj.Members = new List <RelationMember>(xml_obj.member.Length);
            for (int idx = 0; idx < xml_obj.member.Length; idx++)
            {
                member         member       = xml_obj.member[idx];
                RelationMember simpleMember = new RelationMember();
                simpleMember.MemberId   = member.@ref;
                simpleMember.MemberRole = member.role;
                if (member.refSpecified && member.typeSpecified)
                {
                    switch (member.type)
                    {
                    case memberType.node:
                        simpleMember.MemberType = OsmGeoType.Node;
                        break;

                    case memberType.relation:
                        simpleMember.MemberType = OsmGeoType.Relation;
                        break;

                    case memberType.way:
                        simpleMember.MemberType = OsmGeoType.Way;
                        break;
                    }
                }
                else
                { // way cannot be converted; member could not be created!
                    return(null);
                }
                new_obj.Members.Add(simpleMember);
            }

            // set the tags.
            if (xml_obj.tag != null)
            {
                foreach (Osm.Xml.v0_6.tag tag in xml_obj.tag)
                {
                    new_obj.Tags.Add(tag.k, tag.v);
                }
            }

            // set the user info.
            if (xml_obj.uidSpecified)
            {
                new_obj.UserId = xml_obj.uid;
            }
            new_obj.UserName = xml_obj.user;

            // set the changeset info.
            if (xml_obj.changesetSpecified)
            {
                new_obj.ChangeSetId = xml_obj.changeset;
            }

            // set the timestamp flag.
            if (xml_obj.timestampSpecified)
            {
                new_obj.TimeStamp = xml_obj.timestamp;
            }

            // set the visible flag.
            new_obj.Visible = xml_obj.visible;
            return(new_obj);
        }
コード例 #13
0
        /// <summary>
        /// Converts a domain model relation to an Xml relation.
        /// </summary>
        /// <param name="dom_obj"></param>
        /// <returns></returns>
        public static relation ConvertTo(this OsmSharp.Osm.Relation dom_obj)
        {
            relation xml_obj = new relation();

            // set the changeset.
            if (dom_obj.ChangeSetId.HasValue)
            {
                xml_obj.changeset          = dom_obj.ChangeSetId.Value;
                xml_obj.changesetSpecified = true;
            }

            // set the id.
            if (dom_obj.Id.HasValue)
            {
                xml_obj.id          = dom_obj.Id.Value;
                xml_obj.idSpecified = true;
            }
            else
            {
                xml_obj.idSpecified = false;
            }

            if (dom_obj.Tags != null)
            {
                xml_obj.tag = new tag[dom_obj.Tags.Count];
                int idx = 0;
                foreach (var tag in dom_obj.Tags)
                {
                    tag t = new tag();
                    t.k = tag.Key;
                    t.v = tag.Value;
                    xml_obj.tag[idx] = t;
                    idx++;
                }
            }

            // set the timestamp.
            if (dom_obj.TimeStamp.HasValue)
            {
                xml_obj.timestamp          = dom_obj.TimeStamp.Value;
                xml_obj.timestampSpecified = true;
            }

            // set the user data.
            if (dom_obj.UserId.HasValue)
            {
                xml_obj.uid          = dom_obj.UserId.Value;
                xml_obj.uidSpecified = true;
            }
            xml_obj.user = xml_obj.user;

            // set the version.
            if (dom_obj.Version.HasValue)
            {
                xml_obj.version          = (ulong)dom_obj.Version.Value;
                xml_obj.versionSpecified = true;
            }

            // set the visible.
            if (dom_obj.Visible.HasValue)
            {
                xml_obj.visible          = dom_obj.Visible.Value;
                xml_obj.visibleSpecified = true;
            }
            else
            {
                xml_obj.visibleSpecified = false;
            }

            // set the way-specific properties.
            xml_obj.member = new member[dom_obj.Members.Count];
            for (int idx = 0; idx < dom_obj.Members.Count; idx++)
            {
                RelationMember dom_member = dom_obj.Members[idx];
                member         m          = new member();

                if (dom_member.MemberType.HasValue)
                {
                    switch (dom_member.MemberType.Value)
                    {
                    case OsmGeoType.Node:
                        m.type          = memberType.node;
                        m.typeSpecified = true;
                        break;

                    case OsmGeoType.Relation:
                        m.type          = memberType.relation;
                        m.typeSpecified = true;
                        break;

                    case OsmGeoType.Way:
                        m.type          = memberType.way;
                        m.typeSpecified = true;
                        break;
                    }
                }
                else
                {
                    m.typeSpecified = false;
                }

                if (dom_member.MemberId.HasValue)
                {
                    m.@ref         = dom_member.MemberId.Value;
                    m.refSpecified = true;
                }
                else
                {
                    m.refSpecified = false;
                }
                m.role = dom_member.MemberRole;

                xml_obj.member[idx] = m;
            }

            return(xml_obj);
        }
コード例 #14
0
        void ParseXml(XmlDocument xmlDoc)
        {
            XmlNode mainNode = xmlDoc.SelectSingleNode("osm");

            var nodes = mainNode.SelectNodes("node");

            if (allNodes == null)
            {
                allNodes = new Dictionary <long, osmNode>(nodes.Count);
            }

            for (int i = 0; i < nodes.Count; i++)
            {
                var lat = nodes[i].Attributes["lat"].Value;
                var lon = nodes[i].Attributes["lon"].Value;
                var id  = nodes[i].Attributes["id"].Value;

                var node = new osmNode {
                    id = long.Parse(id), Latitude = double.Parse(lat), Longitude = double.Parse(lon)
                };
                node.Position = GeoHelper.WorldToTilePos(node.Longitude, node.Latitude);

                if (!allNodes.ContainsKey(node.id))
                {
                    allNodes.Add(node.id, node);
                }
            }

            var ways = mainNode.SelectNodes("way");

            if (allWays == null)
            {
                allWays = new Dictionary <long, osmWay>(ways.Count);
            }

            foreach (XmlNode way in ways)
            {
                long id = long.Parse(way.Attributes["id"].Value);

                var    refNodes = way.SelectNodes("nd");
                long[] refs     = new long[0];
                if (refNodes != null)
                {
                    refs = new long[refNodes.Count];
                    for (int i = 0; i < refNodes.Count; i++)
                    {
                        refs[i] = long.Parse(refNodes[i].Attributes["ref"].Value);
                    }
                }

                float minX = float.MaxValue;
                float minY = float.MaxValue;
                float maxX = float.MinValue;
                float maxY = float.MinValue;

                foreach (var reff in refs)
                {
                    osmNode nd;
                    if (allNodes.TryGetValue(reff, out nd))
                    {
                        var p = nd.Position;
                        if (p.X < minX)
                        {
                            minX = p.X;
                        }
                        if (p.Y < minY)
                        {
                            minY = p.Y;
                        }
                        if (p.X > maxX)
                        {
                            maxX = p.X;
                        }
                        if (p.Y > maxY)
                        {
                            maxY = p.Y;
                        }
                    }
                }

                var bbox = new BoundingBox(new Vector3(minX, minY, -1.0f), new Vector3(maxX, maxY, 1.0f));


                osmWay osmWay = new osmWay {
                    id      = id,
                    nodeRef = refs,
                    BBox    = bbox
                };


                var tags = way.SelectNodes("tag");
                if (tags != null)
                {
                    foreach (XmlNode tag in tags)
                    {
                        var key = tag.Attributes["k"].Value;
                        var val = tag.Attributes["v"].Value;

                        if (key == "building" || key == "building:levels")
                        {
                            osmWay.isBuilding = true;
                        }
                        if (key == "highway")
                        {
                            osmWay.isHighway = true;
                        }
                    }
                }

                if (!allWays.ContainsKey(id))
                {
                    allWays.Add(id, osmWay);
                }
            }


            var relations = mainNode.SelectNodes("relation");

            if (allRelations == null)
            {
                allRelations = new Dictionary <long, osmRelation>();
            }

            foreach (XmlNode rel in relations)
            {
                long id = long.Parse(rel.Attributes["id"].Value);

                var refMembers = rel.SelectNodes("member");
                var members    = new RelationMember[0];
                if (refMembers != null)
                {
                    members = new RelationMember[refMembers.Count];
                    for (int i = 0; i < refMembers.Count; i++)
                    {
                        var rm = refMembers[i];

                        var        type  = rm.Attributes["type"].Value;
                        MemberType mType = MemberType.Way;
                        if (type == "node")
                        {
                            mType = MemberType.Node;
                        }

                        long refff = long.Parse(rm.Attributes["ref"].Value);

                        MemberRole mRole = MemberRole.None;
                        var        role  = rm.Attributes["role"].Value;
                        if (role == "inner")
                        {
                            mRole = MemberRole.Inner;
                        }
                        if (role == "outer")
                        {
                            mRole = MemberRole.Outer;
                        }

                        members[i] = new RelationMember {
                            Ref = refff, Role = mRole, Type = mType
                        };
                    }
                }


                var refTags = rel.SelectNodes("tag");
                Dictionary <string, string> tags = new Dictionary <string, string>();
                if (refTags != null)
                {
                    foreach (XmlNode tag in refTags)
                    {
                        var key = tag.Attributes["k"].Value;
                        var val = tag.Attributes["v"].Value;

                        tags.Add(key, val);
                    }
                }

                if (!allRelations.ContainsKey(id))
                {
                    allRelations.Add(id, new osmRelation {
                        Id = id, Members = members, Tags = tags
                    });
                }
            }
        }
コード例 #15
0
        public override void AddRelation(Relation simpleRelation)
        {
            relation relation1 = new relation();

            relation1.idSpecified = false;
            long?nullable;

            if (simpleRelation.Id.HasValue)
            {
                relation1.idSpecified = true;
                relation relation2 = relation1;
                nullable = simpleRelation.Id;
                long num = nullable.Value;
                relation2.id = num;
            }
            relation1.changesetSpecified = false;
            nullable = simpleRelation.ChangeSetId;
            if (nullable.HasValue)
            {
                relation relation2 = relation1;
                nullable = simpleRelation.ChangeSetId;
                long num = nullable.Value;
                relation2.changeset          = num;
                relation1.changesetSpecified = true;
            }
            relation1.visibleSpecified = false;
            if (simpleRelation.Visible.HasValue)
            {
                relation1.visible          = simpleRelation.Visible.Value;
                relation1.visibleSpecified = true;
            }
            relation1.timestampSpecified = false;
            if (simpleRelation.TimeStamp.HasValue)
            {
                relation1.timestamp          = simpleRelation.TimeStamp.Value;
                relation1.timestampSpecified = true;
            }
            relation1.uidSpecified = false;
            nullable = simpleRelation.UserId;
            if (nullable.HasValue)
            {
                relation relation2 = relation1;
                nullable = simpleRelation.UserId;
                long num = nullable.Value;
                relation2.uid          = num;
                relation1.uidSpecified = true;
            }
            relation1.user = simpleRelation.UserName;
            relation1.tag  = this.ConvertToXmlTags(simpleRelation.Tags);
            if (simpleRelation.Members != null)
            {
                relation1.member = new member[simpleRelation.Members.Count];
                for (int index = 0; index < simpleRelation.Members.Count; ++index)
                {
                    member         member1 = new member();
                    RelationMember member2 = simpleRelation.Members[index];
                    member1.refSpecified = false;
                    nullable             = member2.MemberId;
                    if (nullable.HasValue)
                    {
                        member member3 = member1;
                        nullable = member2.MemberId;
                        long num = nullable.Value;
                        member3.@ref         = num;
                        member1.refSpecified = true;
                    }
                    member1.typeSpecified = false;
                    if (member2.MemberType.HasValue)
                    {
                        switch (member2.MemberType.Value)
                        {
                        case OsmGeoType.Node:
                            member1.type = memberType.node;
                            break;

                        case OsmGeoType.Way:
                            member1.type = memberType.way;
                            break;

                        case OsmGeoType.Relation:
                            member1.type = memberType.relation;
                            break;
                        }
                        member1.typeSpecified = true;
                    }
                    member1.role            = member2.MemberRole;
                    relation1.member[index] = member1;
                }
            }
            if (simpleRelation.Version.HasValue)
            {
                relation1.version          = simpleRelation.Version.Value;
                relation1.versionSpecified = true;
            }
            XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces();

            namespaces.Add(string.Empty, string.Empty);
            MemoryStream      memoryStream = new MemoryStream();
            XmlWriterSettings settings     = this._settings;
            XmlWriter         xmlWriter    = XmlWriter.Create((Stream)memoryStream, settings);

            new XmlSerializer(typeof(relation), string.Empty).Serialize(xmlWriter, (object)relation1, namespaces);
            Stream stream = this._stream;

            memoryStream.WriteTo(stream);
            this._stream.Flush();
            this._streamWriter.WriteLine();
            this._streamWriter.Flush();
        }
コード例 #16
0
        /// <summary>
        /// Adds a relation to the target.
        /// </summary>
        /// <param name="relation"></param>
        public override void AddRelation(Relation relation)
        {
            if (!relation.Id.HasValue)
            {
                return;
            }

            DataRow relationRow = _relationTable.NewRow();

            // format data and create parameters.
            relationRow["id"]           = relation.Id.Value;
            relationRow["changeset_id"] = relation.ChangeSetId.ConvertToDBValue();
            relationRow["visible"]      = relation.Visible.HasValue ? (object)(relation.Visible.Value ? 1 : 0) : DBNull.Value;
            relationRow["timestamp"]    = relation.TimeStamp.ConvertToDBValue();
            relationRow["version"]      = relation.Version.ConvertToDBValue();
            relationRow["usr"]          = relation.UserName == null ? DBNull.Value : (object)relation.UserName.Truncate(SQLServerSchemaConstants.RelationUsr);
            relationRow["usr_id"]       = relation.UserId.ConvertToDBValue();

            // add the node and it's tags.
            _relationTable.Rows.Add(relationRow);

            // tags.
            if (relation.Tags != null)
            {
                foreach (Tag tag in relation.Tags)
                {
                    DataRow tagRow = _relationTagsTable.NewRow();
                    tagRow["relation_id"] = relation.Id.Value;
                    tagRow["key"]         = tag.Key.Truncate(SQLServerSchemaConstants.RelationTagsKey);
                    tagRow["value"]       = tag.Value.Truncate(SQLServerSchemaConstants.RelationTagsValue);

                    _relationTagsTable.Rows.Add(tagRow);
                }
            }

            // member.
            if (relation.Members != null)
            {
                for (int idx = 0; idx < relation.Members.Count; idx++)
                {
                    RelationMember member = relation.Members[idx];

                    DataRow tagRow = _relationMembersTable.NewRow();
                    tagRow["relation_id"] = relation.Id.Value;
                    tagRow["member_type"] = this.ConvertMemberType(relation.Members[idx].MemberType.Value).Value;
                    tagRow["member_id"]   = member.MemberId;
                    tagRow["member_role"] = member.MemberRole.Truncate(SQLServerSchemaConstants.RelationMemberRole);
                    tagRow["sequence_id"] = idx;

                    _relationMembersTable.Rows.Add(tagRow);
                }
            }

            // bulk insert if needed.
            if (_relationTable.Rows.Count >= BatchRelations)
            {
                BulkCopy(_relationTable, "relation");
                BulkCopy(_relationTagsTable, "relation_tags");
                BulkCopy(_relationMembersTable, "relation_members");
                CreateRelationTables();
            }
        }
コード例 #17
0
        public void TestStyleOsmStreamRelationAreas()
        {
            List <OsmGeo> result = this.FilterUsingStyleInterpreter(new OsmGeo[] {
                Node.Create(1, 0, 0),
                Node.Create(2, 1, 0),
                Node.Create(3, 0, 1),
                Way.Create(1, 1, 2, 3),
                Relation.Create(1, new SimpleTagsCollection(
                                    Tag.Create("type", "multipolygon")),
                                RelationMember.Create(1, "way", OsmGeoType.Way))
            }.ToOsmStreamSource(),
                                                                    "area { " +
                                                                    "   color: black; " +
                                                                    "} ");

            Assert.IsNotNull(result);
            Assert.AreEqual(5, result.Count);
            Assert.IsTrue(result.Any(x => x is Node &&
                                     x.Id == 1 &&
                                     (x as Node).Latitude == 0 &&
                                     (x as Node).Longitude == 0));
            Assert.IsTrue(result.Any(x => x is Node &&
                                     x.Id == 2 &&
                                     (x as Node).Latitude == 1 &&
                                     (x as Node).Longitude == 0));
            Assert.IsTrue(result.Any(x => x is Node &&
                                     x.Id == 3 &&
                                     (x as Node).Latitude == 0 &&
                                     (x as Node).Longitude == 1));
            Assert.IsTrue(result.Any(x => x is Way &&
                                     x.Id == 1 &&
                                     (x as Way).Nodes != null &&
                                     (x as Way).Nodes.Count == 3 &&
                                     (x as Way).Nodes[0] == 1 &&
                                     (x as Way).Nodes[1] == 2 &&
                                     (x as Way).Nodes[2] == 3));
            Assert.IsTrue(result.Any(x => x is Relation &&
                                     x.Id == 1 &&
                                     (x as Relation).Members != null &&
                                     (x as Relation).Members.Count == 1 &&
                                     (x as Relation).Members[0].MemberId == 1));

            result = this.FilterUsingStyleInterpreter(new OsmGeo[] {
                Node.Create(1, 0, 0),
                Node.Create(2, 1, 0),
                Node.Create(3, 0, 1),
                Node.Create(4, 1, 1),
                Way.Create(1, 1, 2, 3),
                Way.Create(2, 1, 2, 4),
                Relation.Create(1, RelationMember.Create(1, "way", OsmGeoType.Way)),
                Relation.Create(2, new SimpleTagsCollection(
                                    Tag.Create("type", "boundary")), RelationMember.Create(2, "way", OsmGeoType.Way))
            }.ToOsmStreamSource(),
                                                      "area { " +
                                                      "   color: black; " +
                                                      "} ");

            Assert.IsNotNull(result);
            Assert.AreEqual(5, result.Count);
            Assert.IsTrue(result.Any(x => x is Node &&
                                     x.Id == 1 &&
                                     (x as Node).Latitude == 0 &&
                                     (x as Node).Longitude == 0));
            Assert.IsTrue(result.Any(x => x is Node &&
                                     x.Id == 2 &&
                                     (x as Node).Latitude == 1 &&
                                     (x as Node).Longitude == 0));
            Assert.IsTrue(result.Any(x => x is Node &&
                                     x.Id == 4 &&
                                     (x as Node).Latitude == 1 &&
                                     (x as Node).Longitude == 1));
            Assert.IsTrue(result.Any(x => x is Way &&
                                     x.Id == 2 &&
                                     (x as Way).Nodes != null &&
                                     (x as Way).Nodes.Count == 3 &&
                                     (x as Way).Nodes[0] == 1 &&
                                     (x as Way).Nodes[1] == 2 &&
                                     (x as Way).Nodes[2] == 4));
            Assert.IsTrue(result.Any(x => x is Relation &&
                                     x.Id == 2 &&
                                     (x as Relation).Members != null &&
                                     (x as Relation).Members.Count == 1 &&
                                     (x as Relation).Members[0].MemberId == 2));
        }
コード例 #18
0
ファイル: CacheHelper.cs プロジェクト: vogelb/ambeth
        protected void LoadAndAddOrels(ICacheIntern cache, IMap <IObjRelation, bool> orelsToLoad, IList <Object> hardRefList,
                                       IMap <ICacheIntern, IISet <IObjRelation> > cacheToOrelsLoadedHistory, ILinkedMap <ICacheIntern, IISet <IObjRef> > cacheToOrisToLoad,
                                       IdentityLinkedSet <Member> prioMembers)
        {
            IList <IObjRelation> objRelList;

            if (prioMembers.Count > 0)
            {
                objRelList = new List <IObjRelation>(orelsToLoad.Count);
                IEntityMetaDataProvider entityMetaDataProvider = this.EntityMetaDataProvider;
                foreach (Entry <IObjRelation, Boolean> entry in orelsToLoad)
                {
                    IObjRelation    objRel       = entry.Key;
                    IEntityMetaData metaData     = entityMetaDataProvider.GetMetaData(objRel.RealType);
                    RelationMember  memberByName = (RelationMember)metaData.GetMemberByName(objRel.MemberName);
                    if (!prioMembers.Contains(memberByName))
                    {
                        continue;
                    }
                    objRelList.Add(objRel);
                }
            }
            else
            {
                objRelList = orelsToLoad.KeyList();
            }
            IList <IObjRelationResult> objRelResults = cache.GetObjRelations(objRelList, cache, CacheDirective.ReturnMisses);

            IISet <IObjRef> orisToLoad = null;

            for (int a = 0, size = objRelResults.Count; a < size; a++)
            {
                IObjRelation       objRel       = objRelList[a];
                IObjRelationResult objRelResult = objRelResults[a];
                bool objRefsOnly = orelsToLoad.Remove(objRel);
                if (objRelResult == null)
                {
                    continue;
                }
                if (orelsToLoad.Get(objRel))
                {
                    // fetch only the objRefs, not the objects themselves
                    continue;
                }
                IObjRef[] relations = objRelResult.Relations;

                if (relations.Length == 0 || objRefsOnly)
                {
                    // fetch only the objRefs, not the objects themselves
                    continue;
                }
                if (orisToLoad == null)
                {
                    orisToLoad = cacheToOrisToLoad.Get(cache);
                    if (orisToLoad == null)
                    {
                        orisToLoad = new CHashSet <IObjRef>();
                        cacheToOrisToLoad.Put(cache, orisToLoad);
                    }
                }
                orisToLoad.AddAll(relations);
            }
            IISet <IObjRelation> orelsLoadedHistory = cacheToOrelsLoadedHistory.Get(cache);

            if (orelsLoadedHistory == null)
            {
                orelsLoadedHistory = new CHashSet <IObjRelation>();
                cacheToOrelsLoadedHistory.Put(cache, orelsLoadedHistory);
            }
            orelsLoadedHistory.AddAll(objRelList);
        }
コード例 #19
0
        /// <summary>
        /// Adds a relation to this target.
        /// </summary>
        /// <param name="simpleRelation"></param>
        public override void AddRelation(Relation simpleRelation)
        {
            var re = new OsmSharp.Osm.Xml.v0_6.relation();

            re.idSpecified = false;
            if (simpleRelation.Id.HasValue)
            {
                re.idSpecified = true;
                re.id          = simpleRelation.Id.Value;
            }

            // set changeset.
            re.changesetSpecified = false;
            if (simpleRelation.ChangeSetId.HasValue)
            {
                re.changeset          = simpleRelation.ChangeSetId.Value;
                re.changesetSpecified = true;
            }

            // set visible.
            re.visibleSpecified = false;
            if (simpleRelation.Visible.HasValue)
            {
                re.visible          = simpleRelation.Visible.Value;
                re.visibleSpecified = true;
            }

            // set timestamp.
            re.timestampSpecified = false;
            if (simpleRelation.TimeStamp.HasValue)
            {
                re.timestamp          = simpleRelation.TimeStamp.Value;
                re.timestampSpecified = true;
            }

            // set uid
            re.uidSpecified = false;
            if (simpleRelation.UserId.HasValue)
            {
                re.uid          = simpleRelation.UserId.Value;
                re.uidSpecified = true;
            }

            // set user
            re.user = simpleRelation.UserName;

            // set tags.
            re.tag = this.ConvertToXmlTags(simpleRelation.Tags);

            // set members.
            if (simpleRelation.Members != null)
            {
                re.member = new OsmSharp.Osm.Xml.v0_6.member[simpleRelation.Members.Count];
                for (int idx = 0; idx < simpleRelation.Members.Count; idx++)
                {
                    var            mem         = new OsmSharp.Osm.Xml.v0_6.member();
                    RelationMember memberToAdd = simpleRelation.Members[idx];

                    // set memberid
                    mem.refSpecified = false;
                    if (memberToAdd.MemberId.HasValue)
                    {
                        mem.@ref         = memberToAdd.MemberId.Value;
                        mem.refSpecified = true;
                    }

                    // set type
                    mem.typeSpecified = false;
                    if (memberToAdd.MemberType.HasValue)
                    {
                        switch (memberToAdd.MemberType.Value)
                        {
                        case OsmGeoType.Node:
                            mem.type = OsmSharp.Osm.Xml.v0_6.memberType.node;
                            break;

                        case OsmGeoType.Way:
                            mem.type = OsmSharp.Osm.Xml.v0_6.memberType.way;
                            break;

                        case OsmGeoType.Relation:
                            mem.type = OsmSharp.Osm.Xml.v0_6.memberType.relation;
                            break;
                        }
                        mem.typeSpecified = true;
                    }

                    mem.role = memberToAdd.MemberRole;

                    re.member[idx] = mem;
                }
            }

            // set version.
            if (simpleRelation.Version.HasValue)
            {
                re.version          = simpleRelation.Version.Value;
                re.versionSpecified = true;
            }

            // serialize relation.
            _serRelation.Serialize(_writer, re);
            _writer.Flush();
            _textWriter.Write(_textWriter.NewLine);
        }
コード例 #20
0
ファイル: CacheHelper.cs プロジェクト: vogelb/ambeth
        protected bool HandleValueHolder(DirectValueHolderRef vhr, PrefetchPath[] cachePaths, IMap <ICacheIntern, IISet <IObjRef> > cacheToOrisToLoad,
                                         IMap <ICacheIntern, IMap <IObjRelation, bool> > cacheToOrelsToLoad, IMap <ICacheIntern, IISet <IObjRef> > cacheToOrisLoadedHistory,
                                         IMap <ICacheIntern, IISet <IObjRelation> > cacheToOrelsLoadedHistory, AlreadyHandledSet alreadyHandledSet, IList <PrefetchCommand> cascadeLoadItems)
        {
            RelationMember member       = vhr.Member;
            bool           newOriToLoad = false;

            if (vhr is IndirectValueHolderRef)
            {
                RootCacheValue  rcv           = (RootCacheValue)vhr.Vhc;
                ICacheIntern    rootCache     = ((IndirectValueHolderRef)vhr).RootCache;
                IEntityMetaData metaData      = EntityMetaDataProvider.GetMetaData(rcv.EntityType);
                int             relationIndex = metaData.GetIndexByRelation(member);
                IObjRef[]       rcvObjRefs    = rcv.GetRelation(relationIndex);
                if (rcvObjRefs == null)
                {
                    IObjRelation        self = ValueHolderContainerMixin.GetSelf(rcv, member.Name);
                    ISet <IObjRelation> orelsLoadedHistory = cacheToOrelsLoadedHistory.Get(rootCache);
                    if (orelsLoadedHistory == null || !orelsLoadedHistory.Contains(self))
                    {
                        IMap <IObjRelation, bool> orelsToLoad = cacheToOrelsToLoad.Get(rootCache);
                        if (orelsToLoad == null)
                        {
                            orelsToLoad = new HashMap <IObjRelation, bool>();
                            cacheToOrelsToLoad.Put(rootCache, orelsToLoad);
                        }
                        orelsToLoad.Put(self, vhr.ObjRefsOnly);
                        AddCascadeLoadItem(vhr, cachePaths, cascadeLoadItems);
                    }
                    return(false);
                }
                else if (!vhr.ObjRefsOnly && rcvObjRefs.Length > 0)
                {
                    ISet <IObjRef> orisLoadedHistory = cacheToOrisLoadedHistory.Get(rootCache);
                    for (int b = rcvObjRefs.Length; b-- > 0;)
                    {
                        IObjRef ori = rcvObjRefs[b];
                        if (orisLoadedHistory != null && orisLoadedHistory.Contains(ori))
                        {
                            // Object has been tried to load before but it is obviously not in the cache
                            // So the load must have been failed somehow. It is assumed that the entity
                            // is not persisted in the database anymore (deleted before) so the ORI is illegal.
                            // We cleanup the ValueHolder so that future calls will not lead to
                            // another unnecessary roundtrip to the server
                            rcvObjRefs[b] = null;
                            continue;
                        }
                        IISet <IObjRef> orisToLoad = cacheToOrisToLoad.Get(rootCache);
                        if (orisToLoad == null)
                        {
                            orisToLoad = new CHashSet <IObjRef>();
                            cacheToOrisToLoad.Put(rootCache, orisToLoad);
                        }
                        orisToLoad.Add(ori);
                        newOriToLoad = true;
                    }
                    if (newOriToLoad)
                    {
                        AddCascadeLoadItem(vhr, cachePaths, cascadeLoadItems);
                    }
                }
                return(false);
            }
            IValueHolderContainer vhc = (IValueHolderContainer)vhr.Vhc;
            int relationIndex2        = vhc.Get__EntityMetaData().GetIndexByRelationName(member.Name);

            if (ValueHolderState.INIT == vhc.Get__State(relationIndex2))
            {
                return(true);
            }
            ICacheIntern cache = vhc.__TargetCache;

            IObjRef[] objRefs = vhc.Get__ObjRefs(relationIndex2);
            if (objRefs == null)
            {
                IObjRelation        self  = vhc.Get__Self(relationIndex2);
                List <IObjRelation> orels = new List <IObjRelation>();
                orels.Add(self);
                IList <IObjRelationResult> orelResults = cache.GetObjRelations(orels, cache, failEarlyReturnMisses);
                IObjRelationResult         orelResult  = orelResults[0];
                if (orelResult == null)
                {
                    ISet <IObjRelation> orelsLoadedHistory = cacheToOrelsLoadedHistory.Get(cache);
                    if (orelsLoadedHistory == null || !orelsLoadedHistory.Contains(self))
                    {
                        IMap <IObjRelation, bool> orelsToLoad = cacheToOrelsToLoad.Get(cache);
                        if (orelsToLoad == null)
                        {
                            orelsToLoad = new HashMap <IObjRelation, bool>();
                            cacheToOrelsToLoad.Put(cache, orelsToLoad);
                        }
                        orelsToLoad.Put(self, vhr.ObjRefsOnly);
                        AddCascadeLoadItem(vhr, cachePaths, cascadeLoadItems);
                    }
                    return(false);
                }
                objRefs = orelResult.Relations;
                if (objRefs != null)
                {
                    vhc.Set__ObjRefs(relationIndex2, objRefs);
                }
            }
            if (!vhr.ObjRefsOnly && objRefs != null && objRefs.Length > 0)
            {
                IList <Object> loadedObjects = cache.GetObjects(new List <IObjRef>(objRefs), cache, failEarlyReturnMisses);
                try
                {
                    for (int b = objRefs.Length; b-- > 0;)
                    {
                        IObjRef ori          = objRefs[b];
                        Object  loadedObject = loadedObjects[b];
                        if (loadedObject != null)
                        {
                            continue;
                        }
                        ISet <IObjRef> orisLoadedHistory = cacheToOrisLoadedHistory.Get(cache);
                        if (orisLoadedHistory != null && orisLoadedHistory.Contains(ori))
                        {
                            // Object has been tried to load before but it is obviously not in the cache
                            // So the load must have been failed somehow. It is assumed that the entity
                            // is not persisted in the database anymore (deleted before) so the ORI is illegal.
                            // We cleanup the ValueHolder so that future calls will not lead to
                            // another unnecessary roundtrip to the server
                            objRefs[b] = null;
                            continue;
                        }
                        IISet <IObjRef> orisToLoad = cacheToOrisToLoad.Get(cache);
                        if (orisToLoad == null)
                        {
                            orisToLoad = new CHashSet <IObjRef>();
                            cacheToOrisToLoad.Put(cache, orisToLoad);
                        }
                        orisToLoad.Add(ori);
                        newOriToLoad = true;
                    }
                }
                finally
                {
                    loadedObjects.Clear();
                    loadedObjects = null;
                }
            }
            if (objRefs == null || newOriToLoad)
            {
                AddCascadeLoadItem(vhr, cachePaths, cascadeLoadItems);
                return(false);
            }
            return(true);
        }
コード例 #21
0
 /// <summary>
 /// Builds a redis key for the relation members relation list.
 /// </summary>
 /// <param name="member"></param>
 /// <returns></returns>
 public static string BuildMemberRelationListRedisKey(RelationMember member)
 {
     return(PrimitiveExtensions.BuildMemberRelationListRedisKey(member.MemberType.Value, member.MemberId.Value));
 }
コード例 #22
0
        /// <summary>
        /// Adds a relation to this target.
        /// </summary>
        /// <param name="simpleRelation"></param>
        public override void AddRelation(Relation simpleRelation)
        {
            var re = new OsmSharp.Osm.Xml.v0_6.relation();

            re.idSpecified = false;
            if (simpleRelation.Id.HasValue)
            {
                re.idSpecified = true;
                re.id          = simpleRelation.Id.Value;
            }

            // set changeset.
            re.changesetSpecified = false;
            if (simpleRelation.ChangeSetId.HasValue)
            {
                re.changeset          = simpleRelation.ChangeSetId.Value;
                re.changesetSpecified = true;
            }

            // set visible.
            re.visibleSpecified = false;
            if (simpleRelation.Visible.HasValue)
            {
                re.visible          = simpleRelation.Visible.Value;
                re.visibleSpecified = true;
            }

            // set timestamp.
            re.timestampSpecified = false;
            if (simpleRelation.TimeStamp.HasValue)
            {
                re.timestamp          = simpleRelation.TimeStamp.Value;
                re.timestampSpecified = true;
            }

            // set uid
            re.uidSpecified = false;
            if (simpleRelation.UserId.HasValue)
            {
                re.uid          = simpleRelation.UserId.Value;
                re.uidSpecified = true;
            }

            // set user
            re.user = simpleRelation.UserName;

            // set tags.
            re.tag = this.ConvertToXmlTags(simpleRelation.Tags);

            // set members.
            if (simpleRelation.Members != null)
            {
                re.member = new OsmSharp.Osm.Xml.v0_6.member[simpleRelation.Members.Count];
                for (int idx = 0; idx < simpleRelation.Members.Count; idx++)
                {
                    var            mem         = new OsmSharp.Osm.Xml.v0_6.member();
                    RelationMember memberToAdd = simpleRelation.Members[idx];

                    // set memberid
                    mem.refSpecified = false;
                    if (memberToAdd.MemberId.HasValue)
                    {
                        mem.@ref         = memberToAdd.MemberId.Value;
                        mem.refSpecified = true;
                    }

                    // set type
                    mem.typeSpecified = false;
                    if (memberToAdd.MemberType.HasValue)
                    {
                        switch (memberToAdd.MemberType.Value)
                        {
                        case OsmGeoType.Node:
                            mem.type = OsmSharp.Osm.Xml.v0_6.memberType.node;
                            break;

                        case OsmGeoType.Way:
                            mem.type = OsmSharp.Osm.Xml.v0_6.memberType.way;
                            break;

                        case OsmGeoType.Relation:
                            mem.type = OsmSharp.Osm.Xml.v0_6.memberType.relation;
                            break;
                        }
                        mem.typeSpecified = true;
                    }

                    mem.role = memberToAdd.MemberRole;

                    re.member[idx] = mem;
                }
            }

            // set version.
            if (simpleRelation.Version.HasValue)
            {
                re.version          = simpleRelation.Version.Value;
                re.versionSpecified = true;
            }

            XmlSerializerNamespaces emptyNamespace = new XmlSerializerNamespaces();

            emptyNamespace.Add(String.Empty, String.Empty);

            // serialize node.
            var       memoryStream = new MemoryStream();
            XmlWriter writer       = XmlWriter.Create(memoryStream, _settings);
            var       serRel       = new XmlSerializer(typeof(Osm.Xml.v0_6.relation), string.Empty);

            serRel.Serialize(writer, re, emptyNamespace);
            memoryStream.WriteTo(_stream);
            _stream.Flush();
            _streamWriter.WriteLine();
            _streamWriter.Flush();
        }
コード例 #23
0
        private bool DoMoveNextRelation()
        {
            if (_relationReader == null)
            {
                OracleCommand relation_command = new OracleCommand("select * from relation order by id");
                relation_command.Connection = _connection;
                _relationReader             = relation_command.ExecuteReader();
                if (!_relationReader.Read())
                {
                    _relationReader.Close();
                }
                OracleCommand relation_tag_command = new OracleCommand("select * from relation_tags order by relation_id");
                relation_tag_command.Connection = _connection;
                _relationTagReader = relation_tag_command.ExecuteReader();
                if (!_relationTagReader.IsClosed && !_relationTagReader.Read())
                {
                    _relationTagReader.Close();
                }
                OracleCommand relation_node_command = new OracleCommand("select * from relation_members order by relation_id,sequence_id");
                relation_node_command.Connection = _connection;
                _relationMemberReader            = relation_node_command.ExecuteReader();
                if (!_relationMemberReader.IsClosed && !_relationMemberReader.Read())
                {
                    _relationMemberReader.Close();
                }
            }

            // read next relation.
            if (!_relationReader.IsClosed)
            {
                // load/parse data.
                long     id           = _relationReader.GetInt64(0);
                long     changeset_id = _relationReader.GetInt64(1);
                DateTime timestamp    = _relationReader.GetDateTime(2);
                bool     visible      = _relationReader.GetInt64(3) == 1;
                long     version      = _relationReader.GetInt64(4);
                string   user         = _relationReader.GetString(5);
                long     uid          = _relationReader.GetInt64(6);
                Relation relation     = new Relation();
                relation.Id          = id;
                relation.ChangeSetId = changeset_id;
                relation.TimeStamp   = timestamp;
                relation.UserId      = null;
                relation.UserName    = null;
                relation.Version     = (ulong)version;
                relation.Visible     = visible;
                relation.UserName    = user;
                relation.UserId      = uid;

                if (!_relationTagReader.IsClosed)
                {
                    long returned_id = _relationTagReader.GetInt64(0);
                    while (returned_id == relation.Id.Value)
                    {
                        if (relation.Tags == null)
                        {
                            relation.Tags = new TagsCollection();
                        }
                        string key   = _relationTagReader.GetString(1);
                        string value = _relationTagReader.GetString(2);

                        relation.Tags.Add(key, value);

                        if (!_relationTagReader.Read())
                        {
                            _relationTagReader.Close();
                            returned_id = -1;
                        }
                        else
                        {
                            returned_id = _relationTagReader.GetInt64(0);
                        }
                    }
                }
                if (!_relationMemberReader.IsClosed)
                {
                    long returned_id = _relationMemberReader.GetInt64(0);
                    while (returned_id == relation.Id.Value)
                    {
                        if (relation.Members == null)
                        {
                            relation.Members = new List <RelationMember>();
                        }
                        string member_type = _relationMemberReader.GetString(1);
                        long   member_id   = _relationMemberReader.GetInt64(2);
                        object member_role = _relationMemberReader.GetValue(3);

                        RelationMember member = new RelationMember();
                        member.MemberId = member_id;
                        if (member_role != DBNull.Value)
                        {
                            member.MemberRole = member_role as string;
                        }
                        switch (member_type)
                        {
                        case "Node":
                            member.MemberType = OsmGeoType.Node;
                            break;

                        case "Way":
                            member.MemberType = OsmGeoType.Way;
                            break;

                        case "Relation":
                            member.MemberType = OsmGeoType.Relation;
                            break;
                        }

                        relation.Members.Add(member);

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

                // set the current variable!
                _current = relation;

                // advance the reader(s).
                if (!_relationReader.Read())
                {
                    _relationReader.Close();
                }
                if (!_relationTagReader.IsClosed && !_relationTagReader.Read())
                {
                    _relationTagReader.Close();
                }
                if (!_relationMemberReader.IsClosed && !_relationMemberReader.Read())
                {
                    _relationMemberReader.Close();
                }
                return(true);
            }
            else
            {
                _relationReader.Close();
                _relationReader.Dispose();
                _relationReader = null;

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

                _currentType = OsmGeoType.Relation;

                return(false);
            }
        }
コード例 #24
0
ファイル: Encoder.cs プロジェクト: hungdluit/OsmSharp
        public static OsmSharp.Osm.Relation DecodeRelation(PrimitiveBlock block, Relation pbfRelation, OsmSharp.Osm.Relation relation)
        {
            if (relation.Members != null && relation.Members.Count > 0)
            {
                relation.Members.Clear();
            }
            if (relation.Tags != null)
            {
                relation.Tags.Clear();
            }
            if (relation.Members == null)
            {
                relation.Members = new List <RelationMember>(pbfRelation.memids.Count);
            }
            if (relation.Tags == null)
            {
                relation.Tags = (TagsCollectionBase) new TagsCollection(pbfRelation.keys.Count);
            }
            relation.Id = new long?(pbfRelation.id);
            long num = 0;

            for (int index = 0; index < pbfRelation.types.Count; ++index)
            {
                num += pbfRelation.memids[index];
                string         str            = Encoding.UTF8.GetString(block.stringtable.s[pbfRelation.roles_sid[index]]);
                RelationMember relationMember = new RelationMember();
                relationMember.MemberId   = new long?(num);
                relationMember.MemberRole = str;
                switch (pbfRelation.types[index])
                {
                case Relation.MemberType.NODE:
                    relationMember.MemberType = new OsmGeoType?(OsmGeoType.Node);
                    break;

                case Relation.MemberType.WAY:
                    relationMember.MemberType = new OsmGeoType?(OsmGeoType.Way);
                    break;

                case Relation.MemberType.RELATION:
                    relationMember.MemberType = new OsmGeoType?(OsmGeoType.Relation);
                    break;
                }
                relation.Members.Add(relationMember);
            }
            for (int index = 0; index < pbfRelation.keys.Count; ++index)
            {
                string key = Encoding.UTF8.GetString(block.stringtable.s[(int)pbfRelation.keys[index]]);
                string str = Encoding.UTF8.GetString(block.stringtable.s[(int)pbfRelation.vals[index]]);
                relation.Tags.Add(new Tag(key, str));
            }
            if (pbfRelation.info != null)
            {
                relation.ChangeSetId = new long?(pbfRelation.info.changeset);
                relation.TimeStamp   = new DateTime?(Encoder.DecodeTimestamp(pbfRelation.info.timestamp, (long)block.date_granularity));
                relation.UserId      = new long?((long)pbfRelation.info.uid);
                relation.UserName    = (string)null;
                if (block.stringtable != null)
                {
                    relation.UserName = Encoding.UTF8.GetString(block.stringtable.s[pbfRelation.info.user_sid]);
                }
                relation.Version = new ulong?((ulong)pbfRelation.info.version);
            }
            relation.Visible = new bool?(true);
            return(relation);
        }
コード例 #25
0
        /// <summary>
        /// Adds a relation.
        /// </summary>
        /// <param name="relation"></param>
        public override void AddRelation(Relation relation)
        {
            DataRow relation_row = _relationTable.NewRow();

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

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

            long?changeset_id = relation.ChangeSetId;

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

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

            DateTime?timestamp = relation.TimeStamp;

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

            ulong?version = relation.Version;

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

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

            // add the node and it's tags.
            _relationTable.Rows.Add(relation_row);

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

                    DataRow tag_row = _relationTagsTable.NewRow();
                    tag_row["relation_id"] = id;
                    tag_row["key"]         = key.Truncate(255);
                    tag_row["value"]       = value.Truncate(255);

                    _relationTagsTable.Rows.Add(tag_row);
                }
            }

            // member.
            if (relation.Members != null)
            {
                long relation_id = relation.Id.Value;

                for (int idx = 0; idx < relation.Members.Count; idx++)
                {
                    RelationMember member = relation.Members[idx];;

                    DataRow tag_row = _relationMembersTable.NewRow();
                    tag_row["relation_id"] = id;
                    tag_row["member_type"] = member.MemberType;
                    tag_row["member_id"]   = member.MemberId;
                    tag_row["member_role"] = member.MemberRole;
                    tag_row["sequence_id"] = idx;

                    _relationMembersTable.Rows.Add(tag_row);
                }
            }

            // bulk insert if needed.
            if (_relationTable.Rows.Count >= _batch_relations)
            {
                this.BulkCopy(_relationTable, "relation");
                this.BulkCopy(_relationTagsTable, "relation_tags");
                this.BulkCopy(_relationMembersTable, "relation_members");
                this.CreateRelationTables();
            }
        }
コード例 #26
0
        private bool DoMoveNextRelation()
        {
            if (_relationReader == null)
            {
                OracleCommand relation_command = new OracleCommand("select * from relation order by id");
                relation_command.Connection = _connection;
                _relationReader = relation_command.ExecuteReader();
                if (!_relationReader.Read())
                {
                    _relationReader.Close();
                }
                OracleCommand relation_tag_command = new OracleCommand("select * from relation_tags order by relation_id");
                relation_tag_command.Connection = _connection;
                _relationTagReader = relation_tag_command.ExecuteReader();
                if (!_relationTagReader.IsClosed && !_relationTagReader.Read())
                {
                    _relationTagReader.Close();
                }
                OracleCommand relation_node_command = new OracleCommand("select * from relation_members order by relation_id,sequence_id");
                relation_node_command.Connection = _connection;
                _relationMemberReader = relation_node_command.ExecuteReader();
                if (!_relationMemberReader.IsClosed && !_relationMemberReader.Read())
                {
                    _relationMemberReader.Close();
                }
            }

            // read next relation.
            if (!_relationReader.IsClosed)
            {
                // load/parse data.
                long id = _relationReader.GetInt64(0);
                long changeset_id = _relationReader.GetInt64(1);
                DateTime timestamp = _relationReader.GetDateTime(2);
                bool visible = _relationReader.GetInt64(3) == 1;
                long version = _relationReader.GetInt64(4);
                string user = _relationReader.GetString(5);
                long uid = _relationReader.GetInt64(6);
                Relation relation = new Relation();
                relation.Id = id;
                relation.ChangeSetId = changeset_id;
                relation.TimeStamp = timestamp;
                relation.UserId = null;
                relation.UserName = null;
                relation.Version = (ulong)version;
                relation.Visible = visible;
                relation.UserName = user;
                relation.UserId = uid;

                if (!_relationTagReader.IsClosed)
                {
                    long returned_id = _relationTagReader.GetInt64(0);
                    while (returned_id == relation.Id.Value)
                    {
                        if (relation.Tags == null)
                        {
                            relation.Tags = new TagsCollection();
                        }
                        string key = _relationTagReader.GetString(1);
                        string value = _relationTagReader.GetString(2);

                        relation.Tags.Add(key, value);

                        if (!_relationTagReader.Read())
                        {
                            _relationTagReader.Close();
                            returned_id = -1;
                        }
                        else
                        {
                            returned_id = _relationTagReader.GetInt64(0);
                        }
                    }
                }
                if (!_relationMemberReader.IsClosed)
                {
                    long returned_id = _relationMemberReader.GetInt64(0);
                    while (returned_id == relation.Id.Value)
                    {
                        if (relation.Members == null)
                        {
                            relation.Members = new List<RelationMember>();
                        }
                        string member_type = _relationMemberReader.GetString(1);
                        long member_id = _relationMemberReader.GetInt64(2);
                        object member_role = _relationMemberReader.GetValue(3);

                        RelationMember member = new RelationMember();
                        member.MemberId = member_id;
                        if (member_role != DBNull.Value)
                        {
                            member.MemberRole = member_role as string;
                        }
                        switch (member_type)
                        {
                            case "Node":
                                member.MemberType = OsmGeoType.Node;
                                break;
                            case "Way":
                                member.MemberType = OsmGeoType.Way;
                                break;
                            case "Relation":
                                member.MemberType = OsmGeoType.Relation;
                                break;
                        }

                        relation.Members.Add(member);

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

                // set the current variable!
                _current = relation;

                // advance the reader(s).
                if (!_relationReader.Read())
                {
                    _relationReader.Close();
                }
                if (!_relationTagReader.IsClosed && !_relationTagReader.Read())
                {
                    _relationTagReader.Close();
                }
                if (!_relationMemberReader.IsClosed && !_relationMemberReader.Read())
                {
                    _relationMemberReader.Close();
                }
                return true;
            }
            else
            {
                _relationReader.Close();
                _relationReader.Dispose();
                _relationReader = null;

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

                _currentType = OsmGeoType.Relation;

                return false;
            }
        }
コード例 #27
0
        public void TestSimpleToCompleteMultipleUsages()
        {
            // execute
            List <ICompleteOsmGeo> completeList = this.PullToCompleteList(new OsmGeo[] {
                Node.Create(1, 0, 0),
                Node.Create(2, 1, 0),
                Node.Create(3, 0, 1),
                Node.Create(4, 2, 0),
                Node.Create(5, 0, 2),
                Way.Create(1, 1, 2, 3),
                Way.Create(2, 1, 4, 5),
                Way.Create(3, 3, 2, 5),
                Way.Create(5, 10, 11, 12),
                Relation.Create(1,
                                RelationMember.Create(1, "way", OsmGeoType.Way)),
                Relation.Create(2,
                                RelationMember.Create(1, "way", OsmGeoType.Way),
                                RelationMember.Create(1, "relation", OsmGeoType.Relation)),
                Relation.Create(3,
                                RelationMember.Create(1, "node", OsmGeoType.Node),
                                RelationMember.Create(2, "node", OsmGeoType.Node),
                                RelationMember.Create(3, "node", OsmGeoType.Node)),
                Relation.Create(4,
                                RelationMember.Create(10, "node", OsmGeoType.Node),
                                RelationMember.Create(11, "node", OsmGeoType.Node),
                                RelationMember.Create(12, "node", OsmGeoType.Node))
            });

            // verify.
            Assert.IsNotNull(completeList);
            Assert.AreEqual(11, completeList.Count);
            Assert.IsTrue(completeList.Any(x => (x.Id == 1 && (x is Node) &&
                                                 (x as Node).Coordinate.Latitude == 0 &&
                                                 (x as Node).Coordinate.Longitude == 0)));
            Assert.IsTrue(completeList.Any(x => (x.Id == 2 && (x is Node) &&
                                                 (x as Node).Coordinate.Latitude == 1 &&
                                                 (x as Node).Coordinate.Longitude == 0)));
            Assert.IsTrue(completeList.Any(x => (x.Id == 3 && (x is Node) &&
                                                 (x as Node).Coordinate.Latitude == 0 &&
                                                 (x as Node).Coordinate.Longitude == 1)));
            Assert.IsTrue(completeList.Any(x => (x.Id == 4 && (x is Node) &&
                                                 (x as Node).Coordinate.Latitude == 2 &&
                                                 (x as Node).Coordinate.Longitude == 0)));
            Assert.IsTrue(completeList.Any(x => (x.Id == 5 && (x is Node) &&
                                                 (x as Node).Coordinate.Latitude == 0 &&
                                                 (x as Node).Coordinate.Longitude == 2)));

            Assert.IsTrue(completeList.Any(x => (x.Id == 1 && (x is CompleteWay) &&
                                                 (x as CompleteWay).Nodes.Count == 3 &&
                                                 (x as CompleteWay).Nodes[0].Id == 1 &&
                                                 (x as CompleteWay).Nodes[0].Coordinate.Latitude == 0 &&
                                                 (x as CompleteWay).Nodes[0].Coordinate.Longitude == 0 &&
                                                 (x as CompleteWay).Nodes[1].Id == 2 &&
                                                 (x as CompleteWay).Nodes[1].Coordinate.Latitude == 1 &&
                                                 (x as CompleteWay).Nodes[1].Coordinate.Longitude == 0 &&
                                                 (x as CompleteWay).Nodes[2].Id == 3 &&
                                                 (x as CompleteWay).Nodes[2].Coordinate.Latitude == 0 &&
                                                 (x as CompleteWay).Nodes[2].Coordinate.Longitude == 1)));
            Assert.IsTrue(completeList.Any(x => (x.Id == 2 && (x is CompleteWay) &&
                                                 (x as CompleteWay).Nodes.Count == 3 &&
                                                 (x as CompleteWay).Nodes[0].Id == 1 &&
                                                 (x as CompleteWay).Nodes[0].Coordinate.Latitude == 0 &&
                                                 (x as CompleteWay).Nodes[0].Coordinate.Longitude == 0 &&
                                                 (x as CompleteWay).Nodes[1].Id == 4 &&
                                                 (x as CompleteWay).Nodes[1].Coordinate.Latitude == 2 &&
                                                 (x as CompleteWay).Nodes[1].Coordinate.Longitude == 0 &&
                                                 (x as CompleteWay).Nodes[2].Id == 5 &&
                                                 (x as CompleteWay).Nodes[2].Coordinate.Latitude == 0 &&
                                                 (x as CompleteWay).Nodes[2].Coordinate.Longitude == 2)));
            Assert.IsTrue(completeList.Any(x => (x.Id == 3 && (x is CompleteWay) &&
                                                 (x as CompleteWay).Nodes.Count == 3 &&
                                                 (x as CompleteWay).Nodes[0].Id == 3 &&
                                                 (x as CompleteWay).Nodes[0].Coordinate.Latitude == 0 &&
                                                 (x as CompleteWay).Nodes[0].Coordinate.Longitude == 1 &&
                                                 (x as CompleteWay).Nodes[1].Id == 2 &&
                                                 (x as CompleteWay).Nodes[1].Coordinate.Latitude == 1 &&
                                                 (x as CompleteWay).Nodes[1].Coordinate.Longitude == 0 &&
                                                 (x as CompleteWay).Nodes[2].Id == 5 &&
                                                 (x as CompleteWay).Nodes[2].Coordinate.Latitude == 0 &&
                                                 (x as CompleteWay).Nodes[2].Coordinate.Longitude == 2)));
            Assert.IsFalse(completeList.Any(x => (x.Id == 5 && (x is CompleteWay))));

            Assert.IsTrue(completeList.Any(x => (x.Id == 1 && (x is CompleteRelation) &&
                                                 (x as CompleteRelation).Members.Count == 1)));
            Assert.IsTrue(completeList.Any(x => (x.Id == 2 && (x is CompleteRelation) &&
                                                 (x as CompleteRelation).Members.Count == 2)));
            Assert.IsTrue(completeList.Any(x => (x.Id == 3 && (x is CompleteRelation) &&
                                                 (x as CompleteRelation).Members.Count == 3)));
        }
コード例 #28
0
ファイル: RelationProvider.cs プロジェクト: dkme/moooyo
        public static CBB.ExceptionHelper.OperationResult AddRelation(RelationMember obj,RelationOperationType t)
        {
            try
            {
                MongoDatabase md = MongoDBHelper.MongoDB;
                MongoCollection<RelationMember> mc = md.GetCollection<RelationMember>(obj.GetCollectionName());
                if (t == RelationOperationType.OnlyOneTimes && mc.Count(Query.And(Query.EQ("FromMember", obj.FromMember), Query.EQ("ToMember", obj.ToMember))) > 0)
                {
                    return new CBB.ExceptionHelper.OperationResult(false, "OverrideOneTimes");
                }
                if (t == RelationOperationType.OneOperationEachHour && mc.Count(Query.And(Query.EQ("FromMember", obj.FromMember), Query.EQ("ToMember", obj.ToMember), Query.GT("CreatedTime", DateTime.Now.AddHours(-1)))) > 0)
                {
                    return new CBB.ExceptionHelper.OperationResult(false, "OverrideOneTimesThisHour");
                }
                if (t == RelationOperationType.OneOperationEachDay && mc.Count(Query.And(Query.EQ("FromMember", obj.FromMember), Query.EQ("ToMember", obj.ToMember), Query.GT("CreatedTime", DateTime.Now.AddDays(-1)))) > 0)
                {
                    return new CBB.ExceptionHelper.OperationResult(false, "OverrideOneTimesThisDay");
                }
                mc.Save(obj);
                return new CBB.ExceptionHelper.OperationResult(true);

            }
            catch (System.Exception err)
            {
                throw new CBB.ExceptionHelper.OperationException(
                    CBB.ExceptionHelper.ErrType.SystemErr,
                    CBB.ExceptionHelper.ErrNo.DBOperationError,
                    err);
            }
        }
コード例 #29
0
        public IList <IEntityMetaData> GetMetaData(IList <Type> entityTypes)
        {
            List <IEntityMetaData> result = new List <IEntityMetaData>();

            for (int a = entityTypes.Count; a-- > 0;)
            {
                Type entityType = entityTypes[a];

                List <Type>    typesRelatingToThis  = new List <Type>();
                IList <String> primitiveMemberNames = new List <String>();
                IList <String> relationMemberNames  = new List <String>();

                FillMetaData(entityType, typesRelatingToThis, primitiveMemberNames, relationMemberNames);

                List <PrimitiveMember> primitiveMembers = new List <PrimitiveMember>();
                foreach (String primitiveMemberName in primitiveMemberNames)
                {
                    PrimitiveMember primitiveMember = MemberTypeProvider.GetPrimitiveMember(entityType, primitiveMemberName);
                    if (primitiveMember == null)
                    {
                        throw new Exception("No member with name '" + primitiveMemberName + "' found on entity type '" + entityType.FullName + "'");
                    }
                    primitiveMembers.Add(primitiveMember);
                }
                List <RelationMember> relationMembers = new List <RelationMember>();
                foreach (String relationMemberName in relationMemberNames)
                {
                    RelationMember relationMember = MemberTypeProvider.GetRelationMember(entityType, relationMemberName);
                    if (relationMember == null)
                    {
                        throw new Exception("No member with name '" + relationMemberName + "' found on entity type '" + entityType.FullName + "'");
                    }
                    relationMembers.Add(relationMember);
                }
                EntityMetaData emd = new EntityMetaData();
                emd.EntityType      = entityType;
                emd.IdMember        = MemberTypeProvider.GetPrimitiveMember(entityType, "Id");
                emd.VersionMember   = MemberTypeProvider.GetPrimitiveMember(entityType, "Version");
                emd.UpdatedByMember = MemberTypeProvider.GetPrimitiveMember(entityType, "UpdatedBy");
                emd.UpdatedOnMember = MemberTypeProvider.GetPrimitiveMember(entityType, "UpdatedOn");
                emd.CreatedByMember = MemberTypeProvider.GetPrimitiveMember(entityType, "CreatedBy");
                emd.CreatedOnMember = MemberTypeProvider.GetPrimitiveMember(entityType, "CreatedOn");

                if (emd.UpdatedByMember != null)
                {
                    primitiveMembers.Add(emd.UpdatedByMember);
                }
                if (emd.UpdatedOnMember != null)
                {
                    primitiveMembers.Add(emd.UpdatedOnMember);
                }
                if (emd.CreatedByMember != null)
                {
                    primitiveMembers.Add(emd.CreatedByMember);
                }
                if (emd.CreatedOnMember != null)
                {
                    primitiveMembers.Add(emd.CreatedOnMember);
                }
                emd.PrimitiveMembers    = primitiveMembers.ToArray();
                emd.RelationMembers     = relationMembers.ToArray();
                emd.TypesRelatingToThis = typesRelatingToThis.ToArray();

                emd.Initialize(CacheModification, EntityFactory);
                result.Add(emd);
            }
            return(result);
        }
コード例 #30
0
ファイル: RelationProvider.cs プロジェクト: dkme/moooyo
        public static CBB.ExceptionHelper.OperationResult UpdateFavorerVisitCount(RelationMember obj)
        {
            try
            {
                MongoDatabase md = MongoDBHelper.MongoDB;
                MongoCollection<RelationMember> mc = md.GetCollection<RelationMember>(obj.GetCollectionName());
                IMongoQuery qc = Query.And(Query.EQ("FromMember", obj.FromMember), Query.EQ("ToMember", obj.ToMember));
                IMongoUpdate ud = Update.Combine(
                    Update.Inc("VisitCount", 1)
                    );
                mc.Update(qc, ud, UpdateFlags.Upsert);

                return new CBB.ExceptionHelper.OperationResult(true);
            }
            catch (System.Exception err)
            {
                throw new CBB.ExceptionHelper.OperationException(
                    CBB.ExceptionHelper.ErrType.SystemErr,
                    CBB.ExceptionHelper.ErrNo.DBOperationError,
                    err);
            }
        }
コード例 #31
0
        protected void ImplementConstructors()
        {
            if (metaData.RelationMembers.Length == 0)
            {
                return;
            }
            RelationMember[]       relationMembers = metaData.RelationMembers;
            List <FieldInstance[]> fieldsList      = new List <FieldInstance[]>();

            for (int a = relationMembers.Length; a-- > 0;)
            {
                RelationMember relationMember = relationMembers[a];
                relationMember = (RelationMember)GetApplicableMember(relationMember);
                if (relationMember == null)
                {
                    // member is handled in another type
                    continue;
                }
                String        propertyName = relationMember.Name;
                String        fieldName    = ValueHolderIEC.GetObjRefsFieldName(propertyName);
                FieldInstance field        = State.GetAlreadyImplementedField(fieldName);

                String        fieldName2 = ValueHolderIEC.GetInitializedFieldName(propertyName);
                FieldInstance field2     = State.GetAlreadyImplementedField(fieldName2);

                fieldsList.Add(new FieldInstance[] { field, field2 });
            }
            if (fieldsList.Count == 0)
            {
                return;
            }
            PropertyInstance p_emptyRelations = ImplementAssignedReadonlyProperty("EmptyRelations", ObjRef.EMPTY_ARRAY);

            OverrideConstructors(delegate(IClassVisitor cv, ConstructorInstance superConstructor)
            {
                IMethodVisitor mv = cv.VisitMethod(superConstructor);
                mv.LoadThis();
                mv.LoadArgs();
                mv.InvokeSuperOfCurrentMethod();

                LocalVariableInfo loc_emptyRelations = mv.NewLocal <IObjRef[]>();
                LocalVariableInfo loc_lazyState      = mv.NewLocal <ValueHolderState>();
                mv.CallThisGetter(p_emptyRelations);
                mv.StoreLocal(loc_emptyRelations);
                mv.PushEnum(ValueHolderState.LAZY);
                mv.StoreLocal(loc_lazyState);
                foreach (FieldInstance[] fields in fieldsList)
                {
                    mv.PutThisField(fields[0], delegate(IMethodVisitor mv2)
                    {
                        mv2.LoadLocal(loc_emptyRelations);
                    });
                    mv.PutThisField(fields[1], delegate(IMethodVisitor mv2)
                    {
                        mv2.LoadLocal(loc_lazyState);
                    });
                }
                mv.ReturnValue();
                mv.EndMethod();
            });
        }