internal RelationInfo CreateByName(IInternalObjectDBTransaction tr, string name, Type interfaceType) { name = string.Intern(name); uint id; if (!_name2Id.TryGetValue(name, out id)) { id = _freeId++; _name2Id[name] = id; tr.KeyValueDBTransaction.SetKeyPrefixUnsafe(ObjectDB.RelationNamesPrefix); var nameWriter = new ByteBufferWriter(); nameWriter.WriteString(name); var idWriter = new ByteBufferWriter(); idWriter.WriteVUInt32(id); tr.KeyValueDBTransaction.CreateOrUpdateKeyValue(nameWriter.Data, idWriter.Data); } RelationInfo relation; if (_id2Relation.TryGetValue(id, out relation)) { throw new BTDBException($"Relation with name '{name}' was already initialized"); } var clientType = FindClientType(interfaceType); relation = new RelationInfo(id, name, _relationInfoResolver, interfaceType, clientType, tr); _id2Relation[id] = relation; return relation; }
public void Read_ReadsRelationWithTagsAndUnknownElement() { OsmXmlReader target = new OsmXmlReader(new MemoryStream(XmlTestData.osm_relation_with_tags_and_unknown_element), new OsmXmlReaderSettings() { ReadMetadata = false }); RelationInfo readRelation = target.Read() as RelationInfo; this.CompareRelation(_relationTags, readRelation); }
public void Read_ReadsRelationWithAllProperties_NoCompresion() { PbfReader target = new PbfReader(TestDataReader.OpenPbf("pbf-n-relation-all-properties.pbf"), new OsmReaderSettings() { ReadMetadata = true }); RelationInfo readRelation = target.Read() as RelationInfo; this.CompareRelation(_relationProperties, readRelation); }
public void Read_SkipsRelationMetadataIfProcessMetadataIsFalse_NoCompresion() { PbfReader target = new PbfReader(TestDataReader.OpenPbf("pbf-n-relation-all-properties.pbf"), new OsmReaderSettings() { ReadMetadata = false }); RelationInfo readRelation = target.Read() as RelationInfo; Assert.Null(readRelation.Metadata); }
public void ParentRelation() { RelationInfo relationInfo = _DatabaseSchema.GetSchema().FindRelationByName("ContactToBike"); foreach (FieldInfo fi in relationInfo.Table.Fields) { Assert.AreEqual(relationInfo, fi.ParentRelation); Assert.IsNull(fi.ParentClass); } }
public void Read_ReadsRelationWithTags_NoCompresion() { PbfReader target = new PbfReader(TestDataReader.OpenPbf("pbf-n-relation-tags.pbf"), new OsmReaderSettings() { ReadMetadata = false }); RelationInfo readRelation = target.Read() as RelationInfo; this.CompareRelation(_relationTags, readRelation); }
public void Read_ReadsRelationWithRelationMember() { OsmXmlReader target = new OsmXmlReader(new MemoryStream(XmlTestData.osm_relation_relation), new OsmXmlReaderSettings() { ReadMetadata = false }); RelationInfo readRelation = target.Read() as RelationInfo; this.CompareRelation(_relationRelation, readRelation); }
/// <summary> /// Reads Relation from the currnt element in the _xmlReader. /// </summary> /// <returns>Information about parsed relation.</returns> private RelationInfo ReadRelation() { string attId = _xmlReader.GetAttribute("id"); if (attId == null) { throw new Sys.XmlException("Attribute 'id' is missing."); } var relationId = long.Parse(attId, System.Globalization.CultureInfo.InvariantCulture); EntityMetadata additionalInfo = null; if (this.Settings.ReadMetadata) { additionalInfo = this.ReadMetadata(); } RelationInfo relation = new RelationInfo(relationId, new TagsCollection(), new List <RelationMemberInfo>(), additionalInfo); if (false == _xmlReader.IsEmptyElement) { _xmlReader.Read(); while (_xmlReader.NodeType != Sys.XmlNodeType.EndElement) { switch (_xmlReader.NodeType) { case Sys.XmlNodeType.Element: switch (_xmlReader.Name) { case "member": relation.Members.Add(this.ReadRelationMember()); continue; case "tag": relation.Tags.Add(this.ReadTag()); continue; default: _xmlReader.Skip(); continue; } default: _xmlReader.Skip(); break; } } } _xmlReader.Skip(); return(relation); }
public override bool ShouldCacheRelation(RelationInfo relation, ClassInfo classInfo) { if (classInfo.Cardinality == ClassCardinality.Small) { return(true); } else { return(false); } }
public void RelationInfo_Constructor_ShouldSetProperties() { var info = new RelationInfo( typeof(Resource).GetProperty(nameof(Resource.Age)), typeof(Resource), RelationKind.HasMany); Assert.That(info.PropertyInfo, Is.EqualTo(typeof(Resource).GetProperty(nameof(Resource.Age)))); Assert.That(info.ResourceType, Is.EqualTo(typeof(Resource))); Assert.That(info.Kind, Is.EqualTo(RelationKind.HasMany)); }
//关系解析 public static RelationInfo relationParse(XmlNode root) { if (root == null) { return(null); } RelationInfo relationInfo = new RelationInfo(); XmlNodeList nodeList = root.ChildNodes; foreach (XmlNode childNode in nodeList) { string childNodeName = childNode.Name; if (childNodeName == "package") { relationInfo.package = childNode.InnerText; } else if (childNodeName == "name") { relationInfo.name = childNode.InnerText; } else if (childNodeName == "alias") { relationInfo.alias = childNode.InnerText; } else if (childNodeName == "clientObject") { XmlNodeList keyNodeList = childNode.ChildNodes; if (keyNodeList.Count == 2) { string package = keyNodeList[0].Attributes["value"].Value; string name = keyNodeList[1].Attributes["value"].Value; relationInfo.clientObject = package + "." + name; } } else if (childNodeName == "supplierObject") { XmlNodeList keyNodeList = childNode.ChildNodes; if (keyNodeList.Count == 2) { string package = keyNodeList[0].Attributes["value"].Value; string name = keyNodeList[1].Attributes["value"].Value; relationInfo.supplierObject = package + "." + name; } } else if (childNodeName == "resource") { resourceParse(childNode, relationInfo.rs); } } setMetaDataAlias(relationInfo); relationInfo.fullName = relationInfo.package + "." + relationInfo.name; relationMap[relationInfo.fullName] = relationInfo; return(relationInfo); }
public override void Write(ByteArray by) { base.Write(by); ushort count = (ushort)list.Count; by.WriteUShort(count); for (int i = 0; i < count; ++i) { RelationInfo obj = list[i]; obj.Write(by); } }
protected override async void Run(Session session, C2G_JoinChatRoom message, Action <G2C_JoinChatRoom> reply) { G2C_JoinChatRoom response = new G2C_JoinChatRoom(); response.IsSuccess = false; try { DBProxyComponent dBProxyComponent = Game.Scene.GetComponent <DBProxyComponent>(); var acounts = await dBProxyComponent.Query <RelationInfo>("{'_Account' : '" + message.Account + "'}"); var acountsC = await dBProxyComponent.Query <ChatRoom>("{'_Account' : '" + message.ChatRoomID + "'}"); if (acounts.Count > 0) { RelationInfo info = acounts[0] as RelationInfo; ChatRoom infoC = acountsC[0] as ChatRoom; if (message.Type == 1) { //加入聊天室 info._ChatRoomList.Add(message.ChatRoomID); infoC._UserList.Add(message.Account); response.IsSuccess = true; response.Message = "添加聊天室编号成功"; } else if (message.Type == 2) { //退出聊天室 info._ChatRoomList.Remove(message.ChatRoomID); infoC._UserList.Remove(message.Account); response.IsSuccess = true; response.Message = "删除聊天室编号成功"; } await dBProxyComponent.Save(info); await dBProxyComponent.Save(infoC); } else { response.IsSuccess = false; response.Message = "聊天室数据库异常"; Log.Debug(MethodBase.GetCurrentMethod().DeclaringType.FullName + "." + MethodBase.GetCurrentMethod().Name + "聊天室数据库异常"); } reply(response); } catch (Exception e) { response.Message = MethodBase.GetCurrentMethod().DeclaringType.FullName + "." + MethodBase.GetCurrentMethod().Name + "聊天室加入或退出失败,服务器维护中。"; ReplyError(response, e, reply); } }
protected override async void Run(Session session, C2G_QueryChatRoom message, Action <G2C_QueryChatRoom> reply) { G2C_QueryChatRoom response = new G2C_QueryChatRoom(); response.IsSuccess = false; try { DBProxyComponent dBProxyComponent = Game.Scene.GetComponent <DBProxyComponent>(); var acountsC = await dBProxyComponent.Query <ChatRoom>("{'_id' : '" + message.ChatRoomID + "'}"); if (acountsC.Count > 0) { ChatRoom chatRoom = acountsC[0] as ChatRoom; if (chatRoom._State == 2) { var acounts = await dBProxyComponent.Query <RelationInfo>("{'_id' : '" + message.Acount + "'}"); RelationInfo info = acounts[0] as RelationInfo; info._ChatRoomList.Remove(message.ChatRoomID); response.IsSuccess = true; response.Message = "聊天室已删除退出聊天室成功"; await dBProxyComponent.Save(info); } else { response.GroupType = chatRoom._GroupType; response.CreateDate = chatRoom._CreateDate; response.ManagePassword = chatRoom._ManagePassword; response.PublicBorad = chatRoom._PublicBorad; response.Name = chatRoom._Name; response.UserList = RepeatedFieldAndListChangeTool.ListToRepeatedField(chatRoom._UserList); response.DateMessageIDList = RepeatedFieldAndListChangeTool.ListToRepeatedField(chatRoom._DateMessageIDList); response.IsSuccess = true; response.Message = "聊天室获取成功"; } } else { response.IsSuccess = false; response.Message = "聊天室数据库异常"; Log.Debug(MethodBase.GetCurrentMethod().DeclaringType.FullName + "." + MethodBase.GetCurrentMethod().Name + "聊天室数据库异常"); } reply(response); } catch (Exception e) { response.Message = MethodBase.GetCurrentMethod().DeclaringType.FullName + "." + MethodBase.GetCurrentMethod().Name + "聊天室获取失败,服务器维护中。"; ReplyError(response, e, reply); } }
private void CompareRelation(RelationInfo expected, RelationInfo actual) { Assert.Equal(expected.ID, actual.ID); Assert.Equal(expected.Members.Count, actual.Members.Count); for (int i = 0; i < expected.Members.Count; i++) { Assert.Equal(expected.Members[i], actual.Members[i]); } this.CompareTags(expected.Tags, actual.Tags); this.CompareEntityDetails(expected.Metadata, actual.Metadata); }
private bool IsWater(OSMMetaManager manager, RelationInfo relationInfo) { if (relationInfo.ContainsKeyValue(manager, "waterway", "river")) { return(false); // not area } if (relationInfo.ContainsKeyValue(manager, "type", "waterway")) { return(false); // not area } return(relationInfo.ContainsKeyValue(manager, "natural", "water")); }
public void Constructor_Relation_SetsProperties() { Relation relation = new Relation(100, new RelationMember[0], new TagsCollection()) { Metadata = new EntityMetadata() }; RelationInfo target = new RelationInfo(relation); Assert.Equal(relation.ID, target.ID); Assert.Same(relation.Tags, target.Tags); Assert.Same(relation.Metadata, target.Metadata); }
public override void Read(ByteArray by) { base.Read(by); list.Clear(); ushort count = by.ReadUShort(); for (int i = 0; i < count; ++i) { RelationInfo obj = new RelationInfo(); obj.Read(by); list.Add(obj); } }
protected override async void Run(Session session, C2G_AddChatRoom message, Action <G2C_AddChatRoom> reply) { G2C_AddChatRoom response = new G2C_AddChatRoom(); response.IsSuccess = false; try { DBProxyComponent dBProxyComponent = Game.Scene.GetComponent <DBProxyComponent>(); var acounts = await dBProxyComponent.Query <RelationInfo>("{'_Account' : '" + message.Account + "'}"); if (acounts.Count > 0) { ChatRoom relationInfo = ComponentFactory.Create <ChatRoom>(); relationInfo._CreateDate = message.CreateDate; relationInfo._GroupType = message.GroupType; relationInfo._InvAccountID = message.Account; relationInfo._ManagePassword = message.ManagePassword; relationInfo._Name = message.Name; relationInfo._PublicBorad = message.PublicBorad; relationInfo._State = 1; relationInfo._UserList = new List <long>(); relationInfo._DateMessageIDList = new List <string>(); relationInfo._UserList.Add(message.Account); RelationInfo info = acounts[0] as RelationInfo; //给聊天室创建者好友列表添加聊天室 info._ChatRoomList.Add(relationInfo.Id); response.IsSuccess = true; response.ChatRoomid = relationInfo.Id; response.Message = "创建聊天室编号成功"; Log.Debug(MethodBase.GetCurrentMethod().DeclaringType.FullName + "." + MethodBase.GetCurrentMethod().Name + "创建聊天室编号成功"); await dBProxyComponent.Save(info); await dBProxyComponent.Save(relationInfo); } else { response.IsSuccess = false; response.Message = "聊天室数据库异常"; Log.Debug(MethodBase.GetCurrentMethod().DeclaringType.FullName + "." + MethodBase.GetCurrentMethod().Name + "聊天室数据库异常"); } reply(response); } catch (Exception e) { response.Message = MethodBase.GetCurrentMethod().DeclaringType.FullName + "." + MethodBase.GetCurrentMethod().Name + "聊天室创建失败,服务器维护中。"; ReplyError(response, e, reply); } }
public void Constructor_PropertiesWithoutEntityDetails_SetsProperties() { int id = 45; TagsCollection tags = new TagsCollection(); List <RelationMemberInfo> members = new List <RelationMemberInfo>(); RelationInfo target = new RelationInfo(id, tags, members); Assert.Equal(EntityType.Relation, target.EntityType); Assert.Equal(id, target.ID); Assert.Same(tags, target.Tags); Assert.Same(members, target.Members); Assert.Null(target.Metadata); }
protected override async void Run(Session session, C2G_QueryRelationInfo message, Action <G2C_QueryRelationInfo> reply) { G2C_QueryRelationInfo response = new G2C_QueryRelationInfo(); RelationInfo RelationInfo = null; try { DBProxyComponent dBProxyComponent = Game.Scene.GetComponent <DBProxyComponent>(); var acounts = await dBProxyComponent.Query <RelationInfo>("{ '_AccountID': " + message.AccountID + "}"); if (acounts.Count <= 0) { RelationInfo Info = ComponentFactory.Create <RelationInfo>(); Info._AccountID = message.AccountID; Info._InfoID = 0; Info._FriendIDList = new List <long>(); Info._BlackIDList = new List <long>(); Info._GroupList = new List <long>(); Info._ChatRoomList = new List <long>(); await dBProxyComponent.Save(Info); await dBProxyComponent.SaveLog(Info); } else { RelationInfo = acounts[0] as RelationInfo; response.InfoID = RelationInfo._InfoID; response.FriendIDList = RepeatedFieldAndListChangeTool.ListToRepeatedField(RelationInfo._FriendIDList); response.BlackIDList = RepeatedFieldAndListChangeTool.ListToRepeatedField(RelationInfo._BlackIDList); response.GroupList = RepeatedFieldAndListChangeTool.ListToRepeatedField(RelationInfo._GroupList); response.ChatRoomList = RepeatedFieldAndListChangeTool.ListToRepeatedField(RelationInfo._ChatRoomList); } await dBProxyComponent.Save(RelationInfo); await dBProxyComponent.SaveLog(RelationInfo); reply(response); } catch (Exception e) { response.Message = "数据库异常"; ReplyError(response, e, reply); } }
public void Constructor_Relation_SetsRelationMembers() { Relation relation = new Relation(100, new RelationMember[] { new RelationMember(new Node(1)), new RelationMember(new Node(2)) }, new TagsCollection()) { Metadata = new EntityMetadata() }; RelationInfo target = new RelationInfo(relation); Assert.Equal(relation.Geometries.Count, target.Members.Count); for (int i = 0; i < relation.Geometries.Count; i++) { Assert.Equal(relation.Geometries[i].Member.ID, target.Members[i].Reference); } }
private static void UpdateInfo(RelationInfo info, Pawn guest) { var relations = PawnsFinder.AllMapsCaravansAndTravelingTransportPods_Alive_OfPlayerFaction.Where(p => p.relations != null).SelectMany(p => GetRelations(guest, p)).ToArray(); info.hasRelationship = relations.Length > 0; info.lastUpdateTick = GenTicks.TicksGame; var sb = new StringBuilder(); foreach (var relation in relations) { sb.AppendLine("Relationship".Translate(relation.def.GetGenderSpecificLabelCap(guest), relation.colonist.Label, relation.colonist)); } info.tooltip = sb.ToString(); }
/// <summary> /// Processes all relations from the PrimitiveGroup and adds them to the output queue. /// </summary> /// <param name="block">The PrimitiveBlock that contains specified PrimitiveGroup.</param> /// <param name="group">The PrimitiveGroup with nodes to process.</param> private void ProcessRelations(PrimitiveBlock block, PrimitiveGroup group) { if (group.Relations == null) { return; } foreach (var relation in group.Relations) { long memberRefStore = 0; List <RelationMemberInfo> members = new List <RelationMemberInfo>(); for (int i = 0; i < relation.MemberIds.Count; i++) { memberRefStore += (long)relation.MemberIds[i]; string role = block.StringTable[relation.RolesIndexes[i]]; EntityType memberType = 0; switch (relation.Types[i]) { case PbfRelationMemberType.Node: memberType = EntityType.Node; break; case PbfRelationMemberType.Way: memberType = EntityType.Way; break; case PbfRelationMemberType.Relation: memberType = EntityType.Relation; break; } members.Add(new RelationMemberInfo() { MemberType = memberType, Reference = memberRefStore, Role = role }); } List <Tag> tags = new List <Tag>(); if (relation.Keys != null) { for (int i = 0; i < relation.Keys.Count; i++) { tags.Add(new Tag(block.StringTable[relation.Keys[i]], block.StringTable[relation.Values[i]])); } } EntityMetadata metadata = this.ProcessMetadata(relation.Metadata, block); RelationInfo parsed = new RelationInfo((long)relation.ID, new TagsCollection(tags), members, metadata); _cache.Enqueue(parsed); } }
public RelationInfo FindRelation(string RelationName) { var RelationInfo = new RelationInfo() { RelationName = RelationName }; if (Relations.TryGetValue(RelationInfo, out RelationInfo) == false) { throw new Exception($"Relation with name '{RelationName}' is not found at '{TableName}' of TableFinder."); } else { return(RelationInfo); } }
public static SoqlBooleanExpression CollectionFor(CollectionManyToManyInfo coll, SoodaObject parent) { SoqlPathExpression needle = new SoqlPathExpression(coll.GetItemClass().GetFirstPrimaryKeyField().Name); RelationInfo relation = coll.GetRelationInfo(); SoqlQueryExpression query = new SoqlQueryExpression(); query.SelectExpressions.Add(new SoqlPathExpression(relation.Table.Fields[coll.MasterField].Name)); query.SelectAliases.Add(string.Empty); query.From.Add(relation.Name); query.FromAliases.Add(string.Empty); query.WhereClause = FieldEquals(relation.Table.Fields[1 - coll.MasterField].Name, parent); SoqlExpressionCollection haystack = new SoqlExpressionCollection(); haystack.Add(query); return(new SoqlBooleanInExpression(needle, haystack)); }
protected override async void Run(Session session, C2G_AddBlackID message, Action <G2C_AddBlackID> reply) { G2C_AddBlackID response = new G2C_AddBlackID(); response.IsSuccess = false; try { DBProxyComponent dBProxyComponent = Game.Scene.GetComponent <DBProxyComponent>(); var acounts = await dBProxyComponent.Query <RelationInfo>("{'_Account' : '" + message.Account + "'}"); if (acounts.Count > 0) { RelationInfo info = acounts[0] as RelationInfo; if (message.Type == 1) { //添加黑名单,删除好友列表 info._BlackIDList.Insert(0, message.BlackID); info._FriendIDList.Remove(message.BlackID); response.IsSuccess = true; response.Message = "添加黑名单成功"; } else if (message.Type == 2) { //删除黑名单,添加好友 info._BlackIDList.Remove(message.BlackID); info._FriendIDList.Insert(0, message.BlackID); response.IsSuccess = true; response.Message = "删除黑名单成功"; } await dBProxyComponent.Save(info); } else { response.IsSuccess = false; response.Message = "好友列表数据库异常"; Log.Debug(MethodBase.GetCurrentMethod().DeclaringType.FullName + "." + MethodBase.GetCurrentMethod().Name + "好友列表数据库异常"); } reply(response); } catch (Exception e) { response.Message = MethodBase.GetCurrentMethod().DeclaringType.FullName + "." + MethodBase.GetCurrentMethod().Name + "好友列表获取或创建失败,服务器维护中。"; ReplyError(response, e, reply); } }
public OsmXmlReaderTests() { _details = new EntityMetadata() { Timestamp = new DateTime(2010, 11, 19, 22, 5, 56, DateTimeKind.Utc), Uid = 127998, User = "******", Visible = true, Version = 2, Changeset = 6410629 }; _node = new NodeInfo(1, 50.4, 16.2, new TagsCollection()); _nodeTags = new NodeInfo(2, 50.4, 16.2, new TagsCollection(new Tag[] { new Tag("name", "test"), new Tag("name-2", "test-2") })); _nodeProperties = new NodeInfo(3, 50.4, 16.2, new TagsCollection(), _details); _way = new WayInfo(1, new TagsCollection(), new long[] { 10, 11, 12 }); _wayTags = new WayInfo(2, new TagsCollection(new Tag[] { new Tag("name", "test"), new Tag("name-2", "test-2") }), new long[] { 10, 11, 12 }); _wayProperties = new WayInfo(1, new TagsCollection(), new long[] { 10, 11, 12 }, _details); _wayWithoutNodes = new WayInfo(1, new TagsCollection(), new long[] { }); _relationNode = new RelationInfo(1, new TagsCollection(), new RelationMemberInfo[] { new RelationMemberInfo() { MemberType = EntityType.Node, Reference = 10, Role = "test" } }); _relationWay = new RelationInfo(1, new TagsCollection(), new RelationMemberInfo[] { new RelationMemberInfo() { MemberType = EntityType.Way, Reference = 10, Role = "test" } }); _relationRelation = new RelationInfo(1, new TagsCollection(), new RelationMemberInfo[] { new RelationMemberInfo() { MemberType = EntityType.Relation, Reference = 10, Role = "test" } }); _relationTags = new RelationInfo( 2, new TagsCollection(new Tag[] { new Tag("name", "test"), new Tag("name-2", "test-2") }), new RelationMemberInfo[] { new RelationMemberInfo() { MemberType = EntityType.Node, Reference = 10, Role = "test" } }); _relationProperties = new RelationInfo(1, new TagsCollection(), new RelationMemberInfo[] { new RelationMemberInfo() { MemberType = EntityType.Node, Reference = 10, Role = "test" } }, _details); _relationWithoutMembers = new RelationInfo(1, new TagsCollection(), new RelationMemberInfo[] { }); }
private string GetLoadRefObjectSelectStatement(RelationInfo relationInfo, int masterColumn) { string query; if (cacheLoadRefObjectSelectStatement[masterColumn].TryGetValue(relationInfo, out query)) { return(query); } string soqlQuery = String.Format("select mt.{0}.* from {2} mt where mt.{1} = {{0}}", relationInfo.Table.Fields[masterColumn].Name, relationInfo.Table.Fields[1 - masterColumn].Name, relationInfo.Name); query = SoqlToSql(SoqlParser.ParseQuery(soqlQuery), relationInfo.Schema, false); cacheLoadRefObjectSelectStatement[masterColumn][relationInfo] = query; return(query); }
public override List <Error> Validate(JObject input, Field field) { List <Error> errors = new List <Error>(); if (field.Options != null) { JToken value = input[field.Name]; if (input[field.Name] == null) { return(errors); } RelationInfo relationInfo = relationInfoService.GetFromOptions(field, input); if (!string.IsNullOrEmpty(relationInfo.LookupCollection)) { FilterDefinition <BsonDocument> filter = FilterDefinition <BsonDocument> .Empty; if (relationInfo.IsMultiple) { Builders <BsonDocument> .Filter.In <BsonObjectId>("_id", relationInfo.Values); } else { filter = Builders <BsonDocument> .Filter.Eq("_id", relationInfo.Values.FirstOrDefault()); } long match = cRUDService.Count(relationInfo.LookupCollection, filter); if (match < 1) { errors.Add(new Error() { Code = "REL-01", Title = "Item not found on lookup collection", Description = "" }); } } return(errors); } return(new List <Error>(errors)); }
private static GridPanel GetCategoryPanel(RelationInfo link) { CategoryItem categoryItem = new CategoryItem(Client.ContentDatabase.GetItem(link.Category)); GridPanel categoryPanel = new GridPanel(); string categoryFullName = categoryItem.CategoryName; string categoryName = categoryItem.DisplayName; categoryPanel.Controls.Add(new Literal(string.Format("{0} ({1:F0}%)", categoryName, link.Weight)) { Class = "categoryName" }); categoryPanel.Controls.Add( new Literal(string.Format("{0}", categoryFullName.Substring(0, categoryFullName.Length - categoryName.Length - 1))) { Class = "categoryPath" }); categoryPanel.Attributes["class"] = "categoryPanel"; return(categoryPanel); }
public virtual int CreateTable(RelationInfo relationInfo) { var tableName = relationInfo.MappingTable; var queryBuilder = new StringBuilder(); if (relationInfo.RelationKind == RelationInfo.RELATION_1_1 || relationInfo.RelationKind == RelationInfo.RELATION_1_N) { var originalTable = relationInfo.OriginalMetadata.MappingTable; queryBuilder.Append("ALTER TABLE " + tableName + " "); queryBuilder.Append("ADD COLUMN " + relationInfo.OriginalKey + " BIGINT(20) NULL, "); queryBuilder.Append("ADD FOREIGN KEY (" + relationInfo.OriginalKey + ") REFERENCES " + originalTable + " (Id) ON DELETE SET NULL, "); queryBuilder.Append("ADD INDEX (" + relationInfo.OriginalKey + ")"); } else if (relationInfo.RelationKind == RelationInfo.RELATION_N_N) { var originalTable = relationInfo.OriginalMetadata.MappingTable; var partnerTable = relationInfo.PartnerMetadata.MappingTable; queryBuilder.Append("CREATE TABLE IF NOT EXISTS " + tableName + "("); queryBuilder.Append("Id BIGINT(20) NOT NULL AUTO_INCREMENT PRIMARY KEY,"); queryBuilder.Append(relationInfo.OriginalKey + " BIGINT(20) NOT NULL, "); queryBuilder.Append("FOREIGN KEY (" + relationInfo.OriginalKey + ") REFERENCES " + originalTable + " (Id) ON DELETE CASCADE, "); queryBuilder.Append(relationInfo.PartnerKey + " BIGINT(20) NOT NULL, "); queryBuilder.Append("FOREIGN KEY (" + relationInfo.PartnerKey + ") REFERENCES " + partnerTable + " (Id) ON DELETE CASCADE, "); queryBuilder.Append("INDEX (" + relationInfo.OriginalKey + "), "); queryBuilder.Append("INDEX (" + relationInfo.PartnerKey + "), "); queryBuilder.Append("CONSTRAINT UNIQUE (`" + relationInfo.OriginalKey + "`, `" + relationInfo.PartnerKey + "`)"); queryBuilder.Append(")"); } using (var connection = connectionManager.GetUpdateConnection()) { var command = connection.CreateCommand(); command.CommandText = queryBuilder.ToString(); return command.ExecuteNonQuery(); } }
private void UpdateNNRelation(IDictionary<IDbObject, long> objectGraph, IDbObject o, DbConnection connection, RelationInfo relation, DbCommand command, string mappingTable, List<long> persistentRelation, PropertyInfo propertyInfo) { var listCurrentPropertyValue = (IList)propertyInfo.GetValue(o, null); if (listCurrentPropertyValue != null) { for (var i = 0; i < listCurrentPropertyValue.Count; i++) { var item = (IDbObject)listCurrentPropertyValue[i]; if (item == null) continue; var itemId = item.Id; if (persistentRelation.Contains(itemId)) { if (!objectGraph.ContainsKey(item)) { Update(item, connection, objectGraph); } persistentRelation.Remove(itemId); } else { if (itemId == 0) { Insert(item, connection, objectGraph); } else if (!objectGraph.ContainsKey(item)) { Update(item, connection, objectGraph); } try { command.CommandText = "INSERT INTO " + mappingTable + " ( `" + relation.OriginalKey + "`, `" + relation.PartnerKey + "`) VALUES (" + o.Id + ", " + item.Id + ")"; command.ExecuteNonQuery(); } catch { } } } } if (persistentRelation.Count > 0) { command.CommandText = "DELETE FROM " + mappingTable + " WHERE `" + relation.OriginalKey + "` = " + o.Id + " AND `" + relation.PartnerKey + "` = @partnerId"; command.Prepare(); command.Parameters.Add(new MySqlParameter("@partnerId", persistentRelation[0])); command.ExecuteNonQuery(); for (var i = 1; i < persistentRelation.Count; i++) { command.Parameters["@partnerId"].Value = persistentRelation[i]; command.ExecuteNonQuery(); } } }
/// <summary> /// Writes relation to the output stream. /// </summary> /// <param name="info">The relation to be written.</param> private void WriteRelation(RelationInfo info) { _writer.WriteStartElement("relation"); _writer.WriteAttributeString("id", info.ID.ToString(_culture)); if (this.Settings.WriteMetadata) { this.WriteMetadata(info.Metadata); } this.WriteTags(info.Tags); for (int i = 0; i < info.Members.Count; i++) { _writer.WriteStartElement("member"); _writer.WriteAttributeString("ref", info.Members[i].Reference.ToString(_culture)); _writer.WriteAttributeString("role", info.Members[i].Role); _writer.WriteAttributeString("type", info.Members[i].MemberType.ToString().ToLower()); _writer.WriteEndElement(); } _writer.WriteEndElement(); }
private void AddRelationSymbol(int symbol, int arity) { if (_relations.Contains(symbol)) return; _relations[symbol] = new RelationInfo(symbol, arity); _groundFacts[symbol] = new List<GroundFact>(); Logger.Debug(string.Format("MetaGDL: Adding relation symbol: {0} ({1})", symbol, _parser.SymbolTable[symbol])); }
private object GetExistingID(IDbConnection connection, RelationInfo info, object thisKey) { var criteria = new Criteria(info.OtherKeyField.PropertyName ?? info.OtherKeyField.Name) == new ValueCriteria(thisKey); if (!ReferenceEquals(null, info.FilterField)) { var flt = new Criteria(info.FilterField.PropertyName ?? info.FilterField.Name); if (info.FilterValue == null) criteria &= flt.IsNull(); else criteria &= flt == new ValueCriteria(info.FilterValue); } var existing = info.ListHandlerFactory().Process(connection, new ListRequest { ColumnSelection = ColumnSelection.KeyOnly, Criteria = criteria }).Entities; if (existing.Count > 1) throw new Exception(String.Format("Found multiple extension rows for UpdatableExtension '{0}'", info.Attr.Alias)); if (existing.Count == 0) return null; return ((Field)((IIdRow)existing[0]).IdField).AsObject((Row)existing[0]); }
private bool CheckPresenceValue(RelationInfo info, Row row) { if (!ReferenceEquals(null, info.PresenceField)) { if (!(info.PresenceField is BooleanField) && info.PresenceValue is Boolean) { if (info.PresenceField.IsNull(row) == (bool)info.PresenceValue) return false; } else { var newRow = row.CreateNew(); info.PresenceField.AsObject(newRow, info.PresenceField.ConvertValue( info.PresenceValue, CultureInfo.InvariantCulture)); if (info.PresenceField.IndexCompare(row, newRow) != 0) return false; } } return true; }
public bool ActivateFor(Row row) { var attrs = row.GetType().GetCustomAttributes<UpdatableExtensionAttribute>(); if (attrs == null || !attrs.Any()) return false; var sourceByExpression = row.GetFields().ToLookup(x => BracketLocator.ReplaceBrackets(x.Expression.TrimToEmpty(), BracketRemoverDialect.Instance)); this.infoList = attrs.Select(attr => { var info = new RelationInfo(); info.Attr = attr; var rowType = attr.RowType; if (rowType.GetIsAbstract() || !typeof(Row).IsAssignableFrom(rowType)) { throw new ArgumentException(String.Format( "Row type '{1}' has an ExtensionRelation attribute " + "but its specified extension row type '{0}' is not a valid row class!", rowType.FullName, row.GetType().FullName)); } info.RowFactory = FastReflection.DelegateForConstructor<Row>(rowType); info.ListHandlerFactory = FastReflection.DelegateForConstructor<IListRequestProcessor>( typeof(ListRequestHandler<>).MakeGenericType(rowType)); info.SaveHandlerFactory = FastReflection.DelegateForConstructor<ISaveRequestProcessor>( typeof(SaveRequestHandler<>).MakeGenericType(rowType)); info.SaveRequestFactory = FastReflection.DelegateForConstructor<ISaveRequest>( typeof(SaveRequest<>).MakeGenericType(rowType)); info.DeleteHandlerFactory = FastReflection.DelegateForConstructor<IDeleteRequestProcessor>( typeof(DeleteRequestHandler<>).MakeGenericType(rowType)); var thisKey = attr.ThisKey; if (string.IsNullOrEmpty(thisKey)) { if (!(row is IIdRow)) { throw new ArgumentException(String.Format( "Row type '{0}' has an ExtensionRelation attribute " + "but its ThisKey is not specified!", row.GetType().FullName)); } info.ThisKeyField = (Field)(((IIdRow)row).IdField); } else { info.ThisKeyField = row.FindFieldByPropertyName(attr.ThisKey) ?? row.FindField(attr.ThisKey); if (ReferenceEquals(info.ThisKeyField, null)) throw new ArgumentException(String.Format("Field '{0}' doesn't exist in row of type '{1}'." + "This field is specified for an ExtensionRelation attribute", attr.ThisKey, row.GetType().FullName)); } var ext = info.RowFactory(); var otherKey = attr.OtherKey; if (string.IsNullOrEmpty(otherKey)) { info.OtherKeyField = ext.FindField(info.ThisKeyField.Name); if (ReferenceEquals(info.OtherKeyField, null) && ext is IIdRow) info.OtherKeyField = (Field)(((IIdRow)row).IdField); if (ReferenceEquals(info.OtherKeyField, null)) throw new ArgumentException(String.Format( "Row type '{1}' has an ExtensionRelation attribute " + "but its OtherKey is not specified!", row.GetType().FullName)); } else { info.OtherKeyField = ext.FindFieldByPropertyName(attr.OtherKey) ?? ext.FindField(attr.OtherKey); if (ReferenceEquals(info.OtherKeyField, null)) throw new ArgumentException(String.Format("Field '{0}' doesn't exist in row of type '{1}'." + "This field is specified for an ExtensionRelation attribute on '{2}'", attr.OtherKey, ext.GetType().FullName, row.GetType().FullName)); } if (!string.IsNullOrEmpty(attr.FilterField)) { info.FilterField = ext.FindFieldByPropertyName(attr.FilterField) ?? ext.FindField(attr.FilterField); if (ReferenceEquals(info.FilterField, null)) throw new ArgumentException(String.Format("Field '{0}' doesn't exist in row of type '{1}'." + "This field is specified as FilterField for an ExtensionRelation attribute on '{2}'", attr.OtherKey, ext.GetType().FullName, row.GetType().FullName)); info.FilterValue = info.FilterField.ConvertValue(attr.FilterValue, CultureInfo.InvariantCulture); } if (!string.IsNullOrEmpty(attr.PresenceField)) { info.PresenceField = ext.FindFieldByPropertyName(attr.PresenceField) ?? ext.FindField(attr.PresenceField); if (ReferenceEquals(info.PresenceField, null)) throw new ArgumentException(String.Format("Field '{0}' doesn't exist in row of type '{1}'." + "This field is specified as PresenceField as an ExtensionRelation attribute.", attr.PresenceField, row.GetType().FullName)); info.PresenceValue = attr.PresenceValue; } var extFields = ext.GetFields(); var alias = attr.Alias; var aliasPrefix = attr.Alias + "_"; var joinByKey = new HashSet<string>(extFields.Joins.Keys, StringComparer.OrdinalIgnoreCase); Func<string, string> mapAlias = x => { if (x == "t0" || x == "T0") return alias; if (!joinByKey.Contains(x)) return x; return aliasPrefix + x; }; Func<string, string> mapExpression = x => { if (x == null) return null; return JoinAliasLocator.ReplaceAliases(x, mapAlias); }; info.Mappings = new List<Tuple<Field, Field>>(); foreach (var field in extFields) { if (ReferenceEquals(info.OtherKeyField, field)) continue; if (ReferenceEquals(info.FilterField, field)) continue; var expression = field.Expression.TrimToEmpty(); if (string.IsNullOrEmpty(expression)) continue; expression = mapExpression(expression); expression = BracketLocator.ReplaceBrackets(expression, BracketRemoverDialect.Instance); var match = sourceByExpression[expression].FirstOrDefault(); if (ReferenceEquals(null, match)) continue; if (match.IsTableField()) continue; if (ReferenceEquals(info.ThisKeyField, match)) continue; if (field.GetType() != match.GetType()) throw new ArgumentException(String.Format( "Row type '{0}' has an ExtensionRelation attribute to '{1}'." + "Their '{2}' and '{3}' fields are matched but they have different types ({4} and {5})!", row.GetType().FullName, ext.GetType().FullName, field.PropertyName ?? field.Name, match.PropertyName ?? match.Name, field.GetType().Name, match.GetType().Name)); info.Mappings.Add(new Tuple<Field, Field>(match, field)); } if (info.Mappings.Count == 0) throw new ArgumentException(String.Format( "Row type '{0}' has an ExtensionRelation attribute " + "but no view fields could be matched to extension row '{1}'!", row.GetType().FullName, ext.GetType().FullName)); return info; }).ToList(); return true; }
private void Update11Relation(IDictionary<IDbObject, long> objectGraph, IDbObject o, DbConnection connection, RelationInfo relation, DbCommand command, string mappingTable, List<long> persistentRelation, PropertyInfo propertyInfo) { var propertyValue = (IDbObject) propertyInfo.GetValue(o, null); if (propertyValue != null) { var itemId = propertyValue.Id; if (persistentRelation.Contains(itemId)) { persistentRelation.Remove(propertyValue.Id); if (!objectGraph.ContainsKey(propertyValue)) { Update(propertyValue, connection, objectGraph); } } else { if (itemId == 0) { Insert(propertyValue, connection, objectGraph); } else if (!objectGraph.ContainsKey(propertyValue)) { Update(propertyValue, connection, objectGraph); } command.CommandText = "UPDATE " + mappingTable + " SET `" + relation.OriginalKey + "` = " + o.Id + " WHERE Id = " + propertyValue.Id; command.ExecuteNonQuery(); } } if (persistentRelation.Count > 0) { command.CommandText = "UPDATE " + mappingTable + " SET `" + relation.OriginalKey + "` = NULL WHERE Id = @id"; command.Prepare(); command.Parameters.Add(new MySqlParameter("@Id", persistentRelation[0])); command.ExecuteNonQuery(); for (var i = 1; i < persistentRelation.Count; i++) { command.Parameters["@Id"].Value = persistentRelation[i]; command.ExecuteNonQuery(); } } }