private static RelationMetaDatum[] MapRelationTags(NodeRelation nodeRelation) { var nodeRelationTags = nodeRelation.NodeRelationTags.Select(x => new RelationMetaDatum(x.Name, x.Value)).ToArray(); return(nodeRelationTags); }
/// <summary>Use this constructor to make a ChildNodeInsertPoint at either the first or last position (not somewhere in the middle)</summary> internal ChildNodeInsertPoint(VertexControl adornedVertex, NodeRelation relation) : base(adornedVertex) { Center = adornedVertex.GetDesiredCenter(); Vector beforeVector; Matrix beforeMatrix = Matrix.Identity; Vector afterVector; Matrix afterMatrix = Matrix.Identity; switch (relation) { case NodeRelation.First: Vector leftVector = Center - new Point(Center.X - adornedVertex.DesiredSize.Height * 2.5, Center.Y); beforeMatrix.Rotate(30); beforeVector = beforeMatrix.Transform(leftVector); afterMatrix.Rotate(-30); afterVector = afterMatrix.Transform(leftVector); BeforePoint = Center - beforeVector; AfterPoint = Center - afterVector; Radius = afterVector.Length; break; case NodeRelation.Last: Vector rightVector = Center - new Point(Center.X + adornedVertex.DesiredSize.Height * 2.5, Center.Y); beforeMatrix.Rotate(30); beforeVector = beforeMatrix.Transform(rightVector); afterMatrix.Rotate(-30); afterVector = afterMatrix.Transform(rightVector); BeforePoint = Center - beforeVector; AfterPoint = Center - afterVector; break; } // Setting IsHitTestVisible=false prevents the adorner from stealing DragOver events from the adorned vertex IsHitTestVisible = false; }
public async Task <IActionResult> PutNodeRelation([FromRoute] int id, [FromBody] NodeRelation nodeRelation) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } if (id != nodeRelation.ParentId) { return(BadRequest()); } _context.Entry(nodeRelation).State = EntityState.Modified; try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!NodeRelationExists(id)) { return(NotFound()); } else { throw; } } return(NoContent()); }
public async Task <IActionResult> PostNodeRelation([FromBody] NodeRelation nodeRelation) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } _context.NodeRelations.Add(nodeRelation); try { await _context.SaveChangesAsync(); } catch (DbUpdateException) { if (NodeRelationExists(nodeRelation.ParentId)) { return(new StatusCodeResult(StatusCodes.Status409Conflict)); } else { throw; } } return(CreatedAtAction("GetNodeRelation", new { id = nodeRelation.ParentId }, nodeRelation)); }
public IActionResult Post(int?parentId, [FromBody] NodeDto value) { try { var node = _cgDbContext.Nodes.Include(s => s.NodeRelation).FirstOrDefault(s => s.Id == value.Id); if (node == null) { node = new Node(); node.rowguid = new Guid(); node.IsActive = true; _cgDbContext.Nodes.Add(node); } node.Page = value.Page; node.NodeTypeId = value.NodeTypeId; node.Name = value.Name; //node.IsActive = value.IsActive; if (node.NodeRelation == null) { node.NodeRelation = new List <NodeRelation>(); } if (value.ParentNodes == null) { value.ParentNodes = new List <int>(); } foreach (var pr in value.ParentNodes) { var parentNode = node.NodeRelation.FirstOrDefault(s => s.ParentNodeId == pr); if (parentNode == null) { parentNode = new NodeRelation() { ParentNodeId = pr }; node.NodeRelation.Add(parentNode); } parentNode.IsActive = true; } foreach (var parent in node.NodeRelation) { if (!value.ParentNodes.Contains(parent.ParentNodeId)) { parent.IsActive = false; } } _cgDbContext.SaveChanges(); return(Ok(_mapper.Map <NodeDto>(node))); } catch (Exception ex) { return(BadRequest("An error has occured cannot save data")); } }
/// <summary> /// This will check if the relation passed in already exists in the source, if so it updates it Ordinal value /// </summary> /// <param name="relations"></param> /// <param name="r"></param> public static void UpdateOrdinal(this ICollection<NodeRelation> relations, NodeRelation r) { //check by id, if not (since the r.id is empty), then match by the composite key of a relation var found = relations.SingleOrDefault(x => x.Id == r.Id) ?? relations.SingleOrDefault(x => x.StartNode.Id == r.StartNode.Id && x.EndNode.Id == r.EndNode.Id && x.NodeRelationType.Name == r.NodeRelationType.Name); if (found != null) { found.Ordinal = r.Ordinal; } }
/// <summary> /// 获取摄像头列表及分组信息 /// </summary> /// <param name="fromMonitorSys">如果该值为true,则实时从监控平台获取,否则从融合网关缓存获取</param> /// <param name="cameraList">摄像头列表</param> /// <param name="groupList">组信息</param> /// <param name="nodeRelationListT">分组关系</param> /// <returns></returns> public SmcErr GetAllCameras(out List <Camera> cameraList, out List <CameraGroup> groupList, out List <NodeRelation> nodeRelationListT) { monitorManageServiceGetCameraList.Stop(); isGetDevicesFinish = false; NLogEx.LoggerEx logEx = new NLogEx.LoggerEx(log); logEx.Trace("Enter: TiandyVideoMonitor.GetAllCameras()."); SmcErr err = new CgwError(); cameraList = new List <Camera>(); groupList = new List <CameraGroup>(); nodeRelationListT = new List <NodeRelation>(); if (this.cameraOperateLock.TryEnterReadLock(CgwConst.ENTER_LOCK_WAIT_TIME)) { try { #region 深度克隆数据 foreach (KeyValuePair <string, TiandyCamera> tiandyCameraKeyValue in this.tiandyCameraDictionary) { TiandyCamera tiandyCamera = tiandyCameraKeyValue.Value; //从缓存获取 Camera camera = new Camera(tiandyCamera.No, tiandyCamera.Name); cameraList.Add(camera); } foreach (KeyValuePair <string, CameraGroup> groupDicKeyValue in this.groupDic) { CameraGroup cameraGroupTemp = new CameraGroup(groupDicKeyValue.Value.No, groupDicKeyValue.Value.Name); groupList.Add(cameraGroupTemp); } foreach (NodeRelation nodeRelation in this.nodeRelationList) { NodeRelation nodeRelationTemp = new NodeRelation(nodeRelation.No, nodeRelation.Path, nodeRelation.Type); nodeRelationListT.Add(nodeRelationTemp); } #endregion } catch (Exception e) { err.SetErrorNo(CgwError.GET_ALL_CAMERAS_FAILED); logEx.Error("Get all cameras failed.Execption message:{0}", e.Message); return(err); } finally { this.cameraOperateLock.ExitReadLock(); } } monitorManageServiceGetCameraList.Start(); logEx.Info("Get all cameras success."); return(err); }
/// <summary> /// This will check if the relation passed in already exists in the source, if so it updates it Ordinal value /// </summary> /// <param name="relations"></param> /// <param name="r"></param> public static void UpdateOrdinal(this ICollection <NodeRelation> relations, NodeRelation r) { //check by id, if not (since the r.id is empty), then match by the composite key of a relation var found = relations.SingleOrDefault(x => x.Id == r.Id) ?? relations.SingleOrDefault(x => x.StartNode.Id == r.StartNode.Id && x.EndNode.Id == r.EndNode.Id && x.NodeRelationType.Name == r.NodeRelationType.Name); if (found != null) { found.Ordinal = r.Ordinal; } }
private RelationById MapNodeRelation(NodeRelation nodeRelation) { IRelatableEntity startMapped; IRelatableEntity endMapped; var nodeRelationTags = MapRelationTags(nodeRelation); return(new RelationById(new HiveId(nodeRelation.StartNode.Id), new HiveId(nodeRelation.EndNode.Id), new RelationType(nodeRelation.NodeRelationType.Alias), nodeRelation.Ordinal, nodeRelationTags)); if (nodeRelation.StartNode is AttributeSchemaDefinition) { startMapped = FrameworkContext.TypeMappers.MapToIntent <EntitySchema>(nodeRelation.StartNode); } else { startMapped = FrameworkContext.TypeMappers.Map <TypedEntity>( nodeRelation.StartNode.NodeVersions.OrderByDescending(x => x.DateCreated).FirstOrDefault()); } if (nodeRelation.EndNode is AttributeSchemaDefinition) { endMapped = FrameworkContext.TypeMappers.MapToIntent <EntitySchema>(nodeRelation.EndNode); } else { endMapped = FrameworkContext.TypeMappers.Map <TypedEntity>( nodeRelation.EndNode.NodeVersions.OrderByDescending(x => x.DateCreated).FirstOrDefault()); } //TODO: Need to move to RdbmsModelMapper but doesn't seem to be wired up at the moment var nodeRelations = nodeRelation.NodeRelationTags.Select(x => new RelationMetaDatum(x.Name, x.Value)).ToArray(); return(new Relation(new RelationType(nodeRelation.NodeRelationType.Alias), startMapped, endMapped, nodeRelation.Ordinal, nodeRelations)); }
private string PutNodeRelation() { try { var model = new NodeRelation() { ChildNodeCode = "Bottoms", ParentNodeCode = "Books", SortOrder = 0 }; var json = JsonConvert.SerializeObject(model); var xml = SerializeObjectToXml(typeof(NodeRelation), model); var result = Put("episerverapi/commerce/nodes/Books/noderelations/Bottoms", new StringContent(json, Encoding.UTF8, "application/json")).Result.Content.ReadAsStringAsync().Result; WriteTextFile(Path.Combine(_nodeRelationOutputPath, "PutJson.txt"), result); result = Put("episerverapi/commerce/nodes/Books/noderelations/Bottoms", new StringContent(xml, Encoding.UTF8, "text/xml")).Result.Content.ReadAsStringAsync().Result; WriteTextFile(Path.Combine(_nodeRelationOutputPath, "PutXml.xml"), result); return("Put node relation complete....."); } catch (Exception ex) { return(ex.Message); } }
private static void CreateAndAddRelationTags(IReadonlyRelation <IRelatableEntity, IRelatableEntity> incomingRelation, NodeRelation dbRelation) { dbRelation.NodeRelationTags.Clear(); var newRelationMetadata = incomingRelation.MetaData.Select(x => new NodeRelationTag() { Name = x.Key, Value = x.Value, NodeRelation = dbRelation }); newRelationMetadata.ForEach(x => dbRelation.NodeRelationTags.Add(x)); }
public void AddRelation(IReadonlyRelation <IRelatableEntity, IRelatableEntity> item, AbstractScopedCache repositoryScopedCache) { var sessionIdAsString = GetSessionId().ToString("n"); using (DisposableTimer.TraceDuration <NhSessionHelper>("In AddRelation for session " + sessionIdAsString, "End AddRelation for session " + sessionIdAsString)) { // Get the source and destination items from the Nh session var sourceNode = NhSession.Get <Node>((Guid)item.SourceId.Value); var destNode = NhSession.Get <Node>((Guid)item.DestinationId.Value); // Check the Nh session is already aware of the items if (sourceNode == null || destNode == null) { string extraMessage = string.Empty; if (sourceNode == null) { extraMessage = "Source {0} cannot be found.\n".InvariantFormat(item.SourceId.Value); } if (destNode == null) { extraMessage += "Destination {0} cannot be found.".InvariantFormat(item.DestinationId.Value); } throw new InvalidOperationException( "Before adding a relation between source {0} and destination {1}, you must call AddOrUpdate with those items or they must already exist in the datastore.\n{2}" .InvariantFormat(item.SourceId, item.DestinationId, extraMessage)); } // Try to load an existing relation of the same type between the two var relationType = GetOrCreateNodeRelationType(item.Type.RelationName, repositoryScopedCache); // Grab the existing relation (if exists) using the compound key of start node / end node / relation type var cacheKey = GenerateCacheKeyForRelation(item, relationType); NodeRelation relationToReturn = repositoryScopedCache.GetOrCreateTyped( cacheKey, () => { return(NhSession .QueryOver <NodeRelation>() .Where(x => x.StartNode == sourceNode && x.EndNode == destNode && x.NodeRelationType == relationType) .Cacheable() .SingleOrDefault()); }); // Avoid a duplicate by checking if one already exists if (relationToReturn != null) { // Make sure existing relation has ordinal relationToReturn.Ordinal = item.Ordinal; } else { // Create a new relation relationToReturn = new NodeRelation { StartNode = sourceNode, EndNode = destNode, NodeRelationType = relationType, Ordinal = item.Ordinal }; relationToReturn = NhSession.Merge(relationToReturn) as NodeRelation; } // Ensure metadata correct on existing or new entity CreateAndAddRelationTags(item, relationToReturn); } }
/// <summary> /// 获取摄像头列表及分组信息 /// </summary> /// <param name="isRealTime">是否实时获取,融合网关有个缓存,间隔一段时间获取,默认是从融合网关获取列表,如果该值为true,则实时获取</param> /// <param name="cameraList">摄像头列表</param> /// <param name="groupList">组信息</param> /// <param name="nodeRelationList">分组关系</param> /// <returns></returns> public SmcErr GetAllCameras(bool fromMonitorSys, out List <Camera> cameraList, out List <CameraGroup> groupList, out List <NodeRelation> nodeRelationList) { cameraList = new List <Camera>(); groupList = new List <CameraGroup>(); nodeRelationList = new List <NodeRelation>(); for (int i = 1; i < 10000; i++) { Camera cs = new Camera("41552873131314642203" + i.ToString(), i.ToString()); cs.DeviceType = "01"; cs.Status = CameraStatus.Online; //cs.ParentID = "41552873135005642565"; cameraList.Add(cs); } //CameraGroup group = new CameraGroup("41552873135005642565","group"); //groupList.Add(group); //NodeRelation rea = new NodeRelation("41552873135005642565", new List<string>(), NodeType.GROUP); //nodeRelationList.Add(rea); for (int i = 1; i < 10000; i++) { NodeRelation rea1 = new NodeRelation("41552873131314642203" + i.ToString(), new List <string>(), NodeType.CAMERA); nodeRelationList.Add(rea1); } return(new CgwError()); //NLogEx.LoggerEx logEx = new NLogEx.LoggerEx(log); //logEx.Trace("Enter: T28181VideoMonitor.GetAllCameras()."); //SmcErr err = new CgwError(); //cameraList = new List<Camera>(); //groupList = new List<CameraGroup>(); //nodeRelationList = new List<NodeRelation>(); //if (fromMonitorSys) //{ // //开始查询设备列表 // Thread th = new Thread(new ThreadStart(() // => // { // GetAllCamerasTimer(null, null); // })); // th.Priority = ThreadPriority.Highest; // th.Start(); // //等待结束查询 // th.Join(); //} //if (this.cameraOperateLock.TryEnterReadLock(CgwConst.ENTER_LOCK_WAIT_TIME)) //{ // try // { // #region 深度克隆数据 // foreach (Camera ivsCamera in this.cameraList) // { // //从缓存获取 // Camera camera = new Camera(ivsCamera.No, ivsCamera.Name); // camera.Status = ivsCamera.Status; // cameraList.Add(camera); // } // foreach (CameraGroup cameraGroup in this.groupList) // { // CameraGroup cameraGroupTemp = new CameraGroup(cameraGroup.No, cameraGroup.Name); // groupList.Add(cameraGroupTemp); // } // foreach (NodeRelation nodeRelation in this.nodeRelationList) // { // NodeRelation nodeRelationTemp = new NodeRelation(nodeRelation.No, nodeRelation.Path, nodeRelation.Type); // nodeRelationList.Add(nodeRelationTemp); // } // #endregion // } // catch (Exception e) // { // err.SetErrorNo(CgwError.GET_ALL_CAMERAS_FAILED); // logEx.Error("Get all cameras failed.Execption message:{0}", e.Message); // return err; // } // finally // { // this.cameraOperateLock.ExitReadLock(); // } //} //logEx.Info("cameraList.{0}", cameraList.Count); //logEx.Info("groupList.{0}", groupList.Count); //logEx.Info("nodeRelationList.{0}", nodeRelationList.Count); //logEx.Info("Get all cameras success."); //return err; }
public static void EnsureSeedData(this SituatorContext context) { var empathy = context.Skills.Add(new Skill { Name = "Empathy" }).Entity; var reactivity = context.Skills.Add(new Skill { Name = "Reactivity" }).Entity; var aggressivity = context.Skills.Add(new Skill { Name = "Aggressivity" }).Entity; var leadership = context.Skills.Add(new Skill { Name = "Leadership" }).Entity; var energetic = context.Skills.Add(new Skill { Name = "Energetic" }).Entity; var course = new Course { Category = "Education", Description = "...", Title = "This is a Course" }; var rootNode = new Node { IsRoot = true, Text = "Team building course", VideoUrl = "/", Course = course, Scores = new List <Score> { new Score { Skill = empathy, Point = 0 }, new Score { Skill = reactivity, Point = 0 }, new Score { Skill = aggressivity, Point = 0 }, new Score { Skill = leadership, Point = 0 }, new Score { Skill = energetic, Point = 0 } }, PositionX = 350, PositionY = 50 }; var NodeA = context.Nodes.Add(new Node { IsRoot = false, IsLeaf = true, Text = "Choice: A", VideoUrl = "/", Course = course, Scores = new List <Score> { new Score { Skill = empathy, Point = 3 }, new Score { Skill = reactivity, Point = 6 }, new Score { Skill = aggressivity, Point = 4 }, new Score { Skill = leadership, Point = 2 }, new Score { Skill = energetic, Point = 1 } }, PositionX = 200, PositionY = 200 }).Entity; var NodeB = context.Nodes.Add(new Node { IsRoot = false, IsLeaf = true, Text = "Choice: B", VideoUrl = "/", Course = course, Scores = new List <Score> { new Score { Skill = empathy, Point = 4 }, new Score { Skill = reactivity, Point = 7 }, new Score { Skill = aggressivity, Point = 4 }, new Score { Skill = leadership, Point = 2 }, new Score { Skill = energetic, Point = 8 } }, PositionX = 350, PositionY = 200 }).Entity; var NodeC = context.Nodes.Add(new Node { IsRoot = false, IsLeaf = true, Text = "Choice C", VideoUrl = "/", Course = course, Scores = new List <Score> { new Score { Skill = empathy, Point = 0 }, new Score { Skill = reactivity, Point = 5 }, new Score { Skill = aggressivity, Point = 5 }, new Score { Skill = leadership, Point = 4 }, new Score { Skill = energetic, Point = 1 } }, PositionX = 500, PositionY = 200 }).Entity; var NodeAA = context.Nodes.Add(new Node { IsRoot = false, IsLeaf = true, Text = "Choice AA", VideoUrl = "/", Course = course, Scores = new List <Score> { new Score { Skill = empathy, Point = 1 }, new Score { Skill = reactivity, Point = 4 }, new Score { Skill = aggressivity, Point = 2 }, new Score { Skill = leadership, Point = 2 }, new Score { Skill = energetic, Point = 1 } }, PositionX = 200, PositionY = 400 }).Entity; var NodeAB = context.Nodes.Add(new Node { IsRoot = false, IsLeaf = true, Text = "Choice AB", VideoUrl = "/", Course = course, Scores = new List <Score> { new Score { Skill = empathy, Point = 8 }, new Score { Skill = reactivity, Point = 0 }, new Score { Skill = aggressivity, Point = 0 }, new Score { Skill = leadership, Point = 1 }, new Score { Skill = energetic, Point = 2 } }, PositionX = 350, PositionY = 400 }).Entity; var NodeAC = context.Nodes.Add(new Node { IsRoot = false, IsLeaf = true, Text = "Choice AC", VideoUrl = "/", Course = course, Scores = new List <Score> { new Score { Skill = empathy, Point = 0 }, new Score { Skill = reactivity, Point = 1 }, new Score { Skill = aggressivity, Point = 0 }, new Score { Skill = leadership, Point = 2 }, new Score { Skill = energetic, Point = 8 } }, PositionX = 500, PositionY = 400 }).Entity; var relations = new NodeRelation[] { new NodeRelation { Parent = rootNode, Child = NodeA }, new NodeRelation { Parent = rootNode, Child = NodeB }, new NodeRelation { Parent = rootNode, Child = NodeC }, new NodeRelation { Parent = NodeA, Child = NodeAA }, new NodeRelation { Parent = NodeA, Child = NodeAB }, new NodeRelation { Parent = NodeA, Child = NodeAC } }; foreach (var rel in relations) { context.NodeRelations.Add(rel); } course.Nodes.Add(rootNode); course.Nodes.Add(NodeA); course.Nodes.Add(NodeB); course.Nodes.Add(NodeC); course.Nodes.Add(NodeAA); course.Nodes.Add(NodeAB); course.Nodes.Add(NodeAC); context.SaveChanges(); }
public override QueryOver <NodeVersion> VisitFieldPredicate(FieldPredicateExpression node) { var fieldName = node.SelectorExpression.FieldName; var valueKey = node.SelectorExpression.ValueKey; var fieldValue = node.ValueExpression.Value; switch (fieldName.ToLowerInvariant()) { case "id": Guid idValue = GetIdValue(node); switch (node.ValueExpression.ClauseType) { case ValuePredicateType.Equal: return(QueryOver.Of <NodeVersion>().Where(x => x.Node.Id == idValue).Select(x => x.Id)); case ValuePredicateType.NotEqual: return(QueryOver.Of <NodeVersion>().Where(x => x.Node.Id != idValue).Select(x => x.Id));; default: throw new InvalidOperationException( "Cannot query an item by id by any other operator than == or !="); } } NodeVersion aliasNodeVersion = null; Attribute aliasAttribute = null; AttributeDefinition aliasAttributeDefinition = null; AttributeStringValue aliasStringValue = null; AttributeLongStringValue aliasLongStringValue = null; NodeRelation aliasNodeRelation = null; AttributeDateValue aliasDateValue = null; //TODO: This is going to need to lookup more than string values var queryString = QueryOver.Of <NodeVersion>(() => aliasNodeVersion) .JoinQueryOver <Attribute>(() => aliasNodeVersion.Attributes, () => aliasAttribute) .JoinQueryOver <AttributeDefinition>(() => aliasAttribute.AttributeDefinition, () => aliasAttributeDefinition) .Left.JoinQueryOver <AttributeStringValue>(() => aliasAttribute.AttributeStringValues, () => aliasStringValue) .Left.JoinQueryOver <AttributeLongStringValue>(() => aliasAttribute.AttributeLongStringValues, () => aliasLongStringValue) .Left.JoinQueryOver(() => aliasAttribute.AttributeDateValues, () => aliasDateValue) //select the field name... .Where(x => aliasAttributeDefinition.Alias == fieldName); if (!valueKey.IsNullOrWhiteSpace()) { //if the value key is specified, then add that to the query queryString = queryString.And(() => aliasStringValue.ValueKey == valueKey || aliasLongStringValue.ValueKey == valueKey).Select(x => x.Id); } //now, select the field value.... switch (node.ValueExpression.ClauseType) { case ValuePredicateType.Equal: var sqlCeCompatibleQuery = Restrictions.Or( Restrictions.Eq( Projections.Property <AttributeStringValue>(x => aliasStringValue.Value), fieldValue), Restrictions.Like( Projections.Property <AttributeLongStringValue>(x => aliasLongStringValue.Value), fieldValue as string, MatchMode.Exact)); return(queryString.And(sqlCeCompatibleQuery).Select(x => x.Id)); case ValuePredicateType.NotEqual: return(queryString.And(x => aliasStringValue.Value != fieldValue).Select(x => x.Id)); case ValuePredicateType.MatchesWildcard: case ValuePredicateType.Contains: return(queryString.And(Restrictions.Like(Projections.Property <AttributeStringValue>(x => aliasStringValue.Value), fieldValue as string, MatchMode.Anywhere)).Select(x => x.Id)); case ValuePredicateType.StartsWith: return(queryString.And(Restrictions.Like(Projections.Property <AttributeStringValue>(x => aliasStringValue.Value), fieldValue as string, MatchMode.Start)).Select(x => x.Id)); case ValuePredicateType.EndsWith: return(queryString.And(Restrictions.Like(Projections.Property <AttributeStringValue>(x => aliasStringValue.Value), fieldValue as string, MatchMode.End)).Select(x => x.Id)); case ValuePredicateType.LessThanOrEqual: return (queryString.And( Restrictions.Le(Projections.Property <AttributeDateValue>(x => aliasDateValue.Value), (DateTimeOffset)fieldValue))); case ValuePredicateType.GreaterThanOrEqual: return (queryString.And( Restrictions.Ge(Projections.Property <AttributeDateValue>(x => aliasDateValue.Value), (DateTimeOffset)fieldValue))); default: throw new InvalidOperationException( "This linq provider doesn't support a ClauseType of {0} for field {1}".InvariantFormat( node.ValueExpression.ClauseType.ToString(), fieldName)); } }
/// <summary> /// 获取摄像头列表及分组信息 /// </summary> private void GetAllCamerasMethod() { NLogEx.LoggerEx logEx = new NLogEx.LoggerEx(log); logEx.Trace("Enter: IvsVideoMonitor.GetAllCamerasMethod()."); try { //1、获取系统中所有的域 List <IvsDomainRoute> ivsDomainRouteList; logEx.Trace("Call ivsSdkClient.GetDomainRoute()."); int result = this.ivsSdkClient.GetDomainRoute(out ivsDomainRouteList); if (result == CgwConst.IVS_SDK_SUCCESS_TAG) { logEx.Info("GetDomainRoute success.List count:{0}", ivsDomainRouteList.Count); } else { logEx.Error("GetDomainRoute failed.Ivs sdk error code:{0}", result); ClearCamera(); isRefreshSucess = false; return; } List <Camera> cameraListTemp = new List <Camera>(); List <CameraGroup> groupListTemp = new List <CameraGroup>(); List <NodeRelation> nodeRelationListTemp = new List <NodeRelation>(); Dictionary <string, NodeRelation> nodeRelationDicTemp = new Dictionary <string, NodeRelation>(); foreach (IvsDomainRoute route in ivsDomainRouteList) { //加上此判断条件的话,子域将不会作查目录处理,不合理,故注释掉 //if (route.ParentDomain != "") //{ // continue; //} Dictionary <string, IvsCameraGroup> ivsCameraGroupDic; logEx.Trace("Call ivsSdkClient.GetDeviceGroupList({0},{1},out groupCount, out ivsCameraGroupDic).", route.DomainCode, CgwConst.IVS_SDK_ROOTGROUP_TAG); result = this.ivsSdkClient.GetDeviceGroupList(route.DomainCode, CgwConst.IVS_SDK_ROOTGROUP_TAG, out ivsCameraGroupDic); if (result == CgwConst.IVS_SDK_SUCCESS_TAG) { logEx.Info("GetDeviceGroupList success.Current group count:{0}", ivsCameraGroupDic.Count); } else { logEx.Error("GetDeviceGroupList failed.Ivs sdk error code:{0}", result); ClearCamera(); isRefreshSucess = false; return; } //域也当做分组使用 string encodeDomainNo = CgwConst.IVS_SDK_ROOTGROUP_TAG + CgwConst.IVS_SDK_DOMAINCODE_SEPARATOR_TAG + route.DomainCode; CameraGroup domainGroup = new CameraGroup(encodeDomainNo, route.DomainName); groupListTemp.Add(domainGroup); List <string> pathDomainList = new List <string>(); RecursionGroupPath(route.DomainCode, ivsDomainRouteList, ref pathDomainList); NodeRelation nodeDomainRelation = new NodeRelation(encodeDomainNo, pathDomainList, CgwMonitorManage.Common.NodeType.GROUP); nodeRelationDicTemp.Add(encodeDomainNo, nodeDomainRelation); foreach (KeyValuePair <string, IvsCameraGroup> ivsCameraGroupKeyValue in ivsCameraGroupDic) { IvsCameraGroup group = ivsCameraGroupKeyValue.Value; string encodeGroupNo = group.GroupNo + CgwConst.IVS_SDK_DOMAINCODE_SEPARATOR_TAG + group.DomainCode; //添加组信息 CameraGroup cameraGroup = new CameraGroup(encodeGroupNo, group.GroupName); groupListTemp.Add(cameraGroup); List <string> pathList = new List <string>(); RecursionPath(group.GroupNo, ivsCameraGroupDic, ref pathList); NodeRelation nodeRelation = new NodeRelation(encodeGroupNo, pathList, CgwMonitorManage.Common.NodeType.GROUP); nodeRelationDicTemp.Add(encodeGroupNo, nodeRelation); } } //添加所有组节点 nodeRelationListTemp.AddRange(nodeRelationDicTemp.Values); List <IvsCamera> ivsCameraPageList = new List <IvsCamera>(); int cameraCount = 0; logEx.Trace("Call ivsSdkClient.GetDeviceList"); //查询第一页记录,同时获取摄像头个数 result = this.ivsSdkClient.GetDeviceList(CgwConst.PAGE_FIRST_INDEX, CgwConst.PAGE_LAST_INDEX, out cameraCount, out ivsCameraPageList); List <IvsCamera> ivsCameraLeaveList = new List <IvsCamera>(); //如果总记录大于一页的总记录数 if (cameraCount > CgwConst.PAGE_LAST_INDEX) { //一次将剩下所有记录查询出来 result = this.ivsSdkClient.GetDeviceList(CgwConst.PAGE_LAST_INDEX + 1, cameraCount, out cameraCount, out ivsCameraLeaveList); } if (result == CgwConst.IVS_SDK_SUCCESS_TAG) { logEx.Info("GetDeviceList success.Current group count:{0}", cameraCount); ivsCameraPageList.AddRange(ivsCameraLeaveList); } else { logEx.Error("GetDeviceList failed.Ivs sdk error code:{0}", result); ClearCamera(); isRefreshSucess = false; return; } foreach (IvsCamera ivsCamera in ivsCameraPageList) { Camera camera = new Camera(ivsCamera.No, ivsCamera.Name); camera.Status = ivsCamera.Status; List <string> cameraPathList = new List <string>(); //string encodeGroupNo = ivsCamera.GroupNo + CgwConst.IVS_SDK_DOMAINCODE_SEPARATOR_TAG + ivsCamera.DomainCode;//摄像头所属组号错误(与群组组号混淆了)。 string encodeGroupNo = ivsCamera.GroupNo; if (nodeRelationDicTemp.ContainsKey(encodeGroupNo)) { //如果自定义分组里面包含该摄像头的父节点,需要设置分组路径 cameraPathList.AddRange(nodeRelationDicTemp[encodeGroupNo].Path); cameraPathList.Add(encodeGroupNo); } NodeRelation nodeRelation = new NodeRelation(camera.No, cameraPathList, CgwMonitorManage.Common.NodeType.CAMERA); //解决问题单DTS2013080201001,规避因IVS服务器存在摄像头重复的bug导致融合网关异常的问题 if (!nodeRelationDicTemp.ContainsKey(camera.No)) { cameraListTemp.Add(camera); nodeRelationDicTemp.Add(camera.No, nodeRelation); } nodeRelationListTemp.Add(nodeRelation); } //nodeRelationListTemp.AddRange(nodeRelationDicTemp.Values); DateTime dtStart = DateTime.Now; DateTime dtNow = new DateTime(); while (!isGetDevicesFinish) { dtNow = DateTime.Now; if ((dtNow - dtStart).TotalSeconds > refreshDeviceListOverTime) { isRefreshSucess = false; return; } Thread.Sleep(1); continue; } //将实时获取的值放到缓存 if (this.cameraOperateLock.TryEnterWriteLock(CgwConst.ENTER_LOCK_WAIT_TIME)) { try { this.cameraList = cameraListTemp; this.groupList = groupListTemp; this.nodeRelationList = nodeRelationListTemp; isRefreshSucess = true; } catch (Exception ex) { isRefreshSucess = false; logEx.Error("Set the list to the buffer failed. ", ex.Message); } finally { this.cameraOperateLock.ExitWriteLock(); } } else { isRefreshSucess = false; } } catch (System.Exception ex) { logEx.Error("GetAllCamerasMethod failed.Exception message:{0}", ex.Message); isRefreshSucess = false; } }
/// <summary> /// SubDendriteを距離閾値に従ってMainDendriteに接続 /// </summary> public void ConnectSubDendritesToMainDendrite() { // nodelist[0] : main // nodelist[1:] : sub List <List <DendriteNode> > nodelist = new List <List <DendriteNode> >(); //メインクラスタの分岐,端点ノードを取得 List <DendriteNode> pnode = main_dendrite.GetEdgeNodeAndBranchNodes(); nodelist.Add(pnode); NotMergedSubDendritesIdx = new HashSet <int>(); for (int i = 0; i < sub_dendrites.Count; i++) { //サブクラスタの分岐,端点ノードを取得 List <DendriteNode> node = sub_dendrites[i].GetEdgeNodeAndBranchNodes(); nodelist.Add(node); NotMergedSubDendritesIdx.Add(i); } var Q = new SkewHeap <NodeRelation>(); for (int i = 0; i < nodelist[0].Count; i++) { for (int j = 1; j < nodelist.Count; j++) { double normMin = double.MaxValue; int argMin = -1; for (int k = 0; k < nodelist[j].Count; k++) { double d = nodelist[0][i].EuclideanDistanceTo(nodelist[j][k]); if (d <= normMin) { normMin = d; argMin = k; } } if (argMin != -1 && normMin <= param.distanceThreshold) { Q.Push(new NodeRelation(normMin, i, j, argMin)); } } } while (true) { NodeRelation rel = null; while (Q.Empty() == false) { rel = Q.Pop(); if (nodelist[rel.SlaveClusterIdx].Count > 0) { break; } } if (Q.Empty()) { break; } DendriteNode parent = nodelist[0][rel.MasterNodeIdx]; DendriteNode cand = nodelist[rel.SlaveClusterIdx][rel.SlaveNodeIdx]; //連結ノードにお互いを追加 cand.AddConnectedNode(parent); parent.AddConnectedNode(cand); int mainNodeSizePrev = nodelist[0].Count; //連結したサブノードリストはメインノードリストに吸収 nodelist[0].AddRange(nodelist[rel.SlaveClusterIdx]); //サブを消去 nodelist[rel.SlaveClusterIdx].Clear(); // マージされた NotMergedSubDendritesIdx.Remove(rel.SlaveClusterIdx - 1); // 吸収されたサブノードから、吸収されていないサブノードまでの距離を算出 for (int i = mainNodeSizePrev; i < nodelist[0].Count; i++) { for (int j = 1; j < nodelist.Count; j++) { double normMin = double.MaxValue; int argMin = -1; for (int k = 0; k < nodelist[j].Count; k++) { double d = nodelist[0][i].EuclideanDistanceTo(nodelist[j][k]); if (d <= normMin) { normMin = d; argMin = k; } } if (argMin != -1 && normMin <= param.distanceThreshold) { Q.Push(new NodeRelation(normMin, i, j, argMin)); } } } } main_dendrite.ChangeRootNode(main_dendrite.root); pnode = main_dendrite.GetEdgeNodes(); // どうしてFirstでなくてLastなのかよく分からない main_dendrite.ChangeRootNode(pnode.Last()); }
/// <summary> /// 递归天地伟业返回的自定义设备列表,只获取分组节点(TypeId为1000)和通道(摄像头)节点(TypeId为5),舍弃其他节点(如主机,中间件服务器等) /// </summary> /// <param name="customTree">天地伟业返回的自定义设备列表树</param> /// <param name="pathList">节点路径,如果为跟节点,传null即可,主要是用于递归函数处理</param> /// <param name="groupDic">组列表</param> /// <param name="nodeRelationDic">组、摄像头关系列表Dic,不能重复</param> /// <param name="nodeRelationListT">组、摄像头关系列表,可以重复,解决同一摄像头在不同分组下,融合网关报错的问题</param> /// private void RecursionCameraGroup(List <Resource> customTree, List <string> pathList, Dictionary <string, CameraGroup> groupDic, Dictionary <string, NodeRelation> nodeRelationDic, List <NodeRelation> nodeRelationListT) { NLogEx.LoggerEx logEx = new NLogEx.LoggerEx(log); if (customTree == null) { logEx.Error("RecursionCameraGroup failed.CustomTree is null."); return; } if (pathList == null) { pathList = new List <string>(); } if (groupDic == null) { groupDic = new Dictionary <string, CameraGroup>(); } if (nodeRelationDic == null) { nodeRelationDic = new Dictionary <string, NodeRelation>(); } if (nodeRelationListT == null) { nodeRelationListT = new List <NodeRelation>(); } foreach (Resource custom in customTree) { //TypeId为5时,表示该节点为通道,对应一个摄像头 if (((int)NodeType.CAMERA).ToString().Equals(custom.TypeId)) { //pathList.Add(custom.Id); NodeRelation nodeRelation = new NodeRelation(custom.Id, new List <string>(pathList), CgwMonitorManage.Common.NodeType.CAMERA); if (!nodeRelationDic.ContainsKey(custom.Id)) { nodeRelationDic.Add(custom.Id, nodeRelation); } nodeRelationListT.Add(nodeRelation); //获取完路径后,要返回上一级路径 //pathList.Remove(custom.Id); } //TypeId为1000时,表示该节点为分组 else if (((int)NodeType.GROUP).ToString().Equals(custom.TypeId)) { //添加组信息 CameraGroup cameraGroup = new CameraGroup(custom.Id, custom.Caption); groupDic.Add(custom.Id, cameraGroup); NodeRelation nodeRelation = new NodeRelation(custom.Id, new List <string>(pathList), CgwMonitorManage.Common.NodeType.GROUP); if (!nodeRelationDic.ContainsKey(custom.Id)) { nodeRelationDic.Add(custom.Id, nodeRelation); } nodeRelationListT.Add(nodeRelation); //添加分组关系 pathList.Add(custom.Id); //如果是组,还需要递归处理,遍历子节点 RecursionCameraGroup(custom.items, pathList, groupDic, nodeRelationDic, nodeRelationListT); //获取完路径后,要返回上一级路径 pathList.Remove(custom.Id); } else { //其他类型节点不做处理 } } }
public override QueryOver <NodeVersion> VisitFieldPredicate(FieldPredicateExpression node) { var fieldName = node.SelectorExpression.FieldName; var valueKey = node.SelectorExpression.ValueKey; var fieldValue = node.ValueExpression.Value; var fieldValueType = fieldValue != null?fieldValue.GetType() : typeof(string); switch (fieldName.ToLowerInvariant()) { case "id": Guid idValue = GetIdValue(node); switch (node.ValueExpression.ClauseType) { case ValuePredicateType.Equal: return(QueryOver.Of <NodeVersion>().Where(x => x.Node.Id == idValue).Select(x => x.Id)); case ValuePredicateType.NotEqual: return(QueryOver.Of <NodeVersion>().Where(x => x.Node.Id != idValue).Select(x => x.Id));; default: throw new InvalidOperationException( "Cannot query an item by id by any other operator than == or !="); } } // First look up the types of the main field AttributeDefinition defAlias = null; AttributeType typeAlias = null; var attributeType = _activeSession.QueryOver <AttributeDefinition>(() => defAlias) .JoinAlias(() => defAlias.AttributeType, () => typeAlias) .Where(() => defAlias.Alias == fieldName) .Select(x => typeAlias.PersistenceTypeProvider) .List <string>(); var typesAlreadyEstablished = new List <string>(); var typesToQuery = new List <DataSerializationTypes>(); foreach (var type in attributeType) { var typeName = type; if (typesAlreadyEstablished.Contains(typeName)) { continue; } try { typesAlreadyEstablished.Add(typeName); var persisterType = Type.GetType(typeName, false); if (persisterType != null) { var persisterInstance = Activator.CreateInstance(persisterType) as IAttributeSerializationDefinition; if (persisterInstance != null) { typesToQuery.Add(persisterInstance.DataSerializationType); } } } catch (Exception) { throw; } } // U5-789 // Workaround pending a better check of what data is actually saved // An issue arose because previous data had been saved in long-string, // but the datatype changed to be just string, therefore only string was // being queried despite all the data residing still in long-string if (typesToQuery.Contains(DataSerializationTypes.String) && !typesToQuery.Contains(DataSerializationTypes.LongString)) { typesToQuery.Add(DataSerializationTypes.LongString); } NodeVersion aliasNodeVersion = null; Attribute aliasAttribute = null; AttributeDefinition aliasAttributeDefinition = null; AttributeStringValue aliasStringValue = null; AttributeLongStringValue aliasLongStringValue = null; AttributeIntegerValue aliasIntegerValue = null; AttributeDecimalValue aliasDecimalValue = null; NodeRelation aliasNodeRelation = null; AttributeDateValue aliasDateValue = null; QueryOver <NodeVersion, AttributeDefinition> queryExtender = QueryOver.Of <NodeVersion>(() => aliasNodeVersion) .JoinQueryOver <Attribute>(() => aliasNodeVersion.Attributes, () => aliasAttribute) .JoinQueryOver <AttributeDefinition>(() => aliasAttribute.AttributeDefinition, () => aliasAttributeDefinition); int numberOfMatchesEvaluated = 0; AbstractCriterion restrictionBuilder = null; foreach (var dataSerializationTypese in typesToQuery.Distinct()) { AbstractCriterion restriction = null; Expression <Func <object> > propertyExpression = null; Expression <Func <object> > subkeyExpression = null; List <ValuePredicateType> validClauseTypes = null; var useLikeMatchForStrings = false; switch (dataSerializationTypese) { case DataSerializationTypes.SmallInt: case DataSerializationTypes.LargeInt: case DataSerializationTypes.Boolean: queryExtender = queryExtender.Left.JoinAlias(() => aliasAttribute.AttributeIntegerValues, () => aliasIntegerValue); propertyExpression = () => aliasIntegerValue.Value; subkeyExpression = () => aliasIntegerValue.ValueKey; validClauseTypes = new List <ValuePredicateType>() { ValuePredicateType.Equal, ValuePredicateType.GreaterThan, ValuePredicateType.GreaterThanOrEqual, ValuePredicateType.LessThan, ValuePredicateType.LessThanOrEqual, ValuePredicateType.NotEqual }; break; case DataSerializationTypes.Decimal: queryExtender = queryExtender.Left.JoinAlias(() => aliasAttribute.AttributeDecimalValues, () => aliasDecimalValue); propertyExpression = () => aliasDecimalValue.Value; subkeyExpression = () => aliasDecimalValue.ValueKey; validClauseTypes = new List <ValuePredicateType>() { ValuePredicateType.Equal, ValuePredicateType.GreaterThan, ValuePredicateType.GreaterThanOrEqual, ValuePredicateType.LessThan, ValuePredicateType.LessThanOrEqual, ValuePredicateType.NotEqual }; break; case DataSerializationTypes.String: queryExtender = queryExtender.Left.JoinAlias(() => aliasAttribute.AttributeStringValues, () => aliasStringValue); propertyExpression = () => aliasStringValue.Value; subkeyExpression = () => aliasStringValue.ValueKey; validClauseTypes = new List <ValuePredicateType>() { ValuePredicateType.Equal, ValuePredicateType.NotEqual, ValuePredicateType.Contains, ValuePredicateType.StartsWith, ValuePredicateType.EndsWith, ValuePredicateType.MatchesWildcard }; break; case DataSerializationTypes.LongString: queryExtender = queryExtender.Left.JoinAlias(() => aliasAttribute.AttributeLongStringValues, () => aliasLongStringValue); propertyExpression = () => aliasLongStringValue.Value; subkeyExpression = () => aliasLongStringValue.ValueKey; useLikeMatchForStrings = true; validClauseTypes = new List <ValuePredicateType>() { ValuePredicateType.Equal, ValuePredicateType.NotEqual, ValuePredicateType.Contains, ValuePredicateType.StartsWith, ValuePredicateType.EndsWith, ValuePredicateType.MatchesWildcard }; break; case DataSerializationTypes.Date: queryExtender = queryExtender.Left.JoinAlias(() => aliasAttribute.AttributeDateValues, () => aliasDateValue); propertyExpression = () => aliasDateValue.Value; subkeyExpression = () => aliasDateValue.ValueKey; validClauseTypes = new List <ValuePredicateType>() { ValuePredicateType.Equal, ValuePredicateType.GreaterThan, ValuePredicateType.GreaterThanOrEqual, ValuePredicateType.LessThan, ValuePredicateType.LessThanOrEqual, ValuePredicateType.NotEqual, ValuePredicateType.Empty }; break; } if (!validClauseTypes.Contains(node.ValueExpression.ClauseType)) { throw new InvalidOperationException("A field of type {0} cannot be queried with operator {1}".InvariantFormat(dataSerializationTypese.ToString(), node.ValueExpression.ClauseType.ToString())); } switch (node.ValueExpression.ClauseType) { case ValuePredicateType.Equal: restriction = GetRestrictionEq(fieldValue, useLikeMatchForStrings, propertyExpression, subkeyExpression, valueKey); break; case ValuePredicateType.NotEqual: restriction = !GetRestrictionEq(fieldValue, useLikeMatchForStrings, propertyExpression); break; case ValuePredicateType.LessThan: restriction = GetRestrictionLt(fieldValue, propertyExpression); break; case ValuePredicateType.LessThanOrEqual: restriction = GetRestrictionLtEq(fieldValue, propertyExpression); break; case ValuePredicateType.GreaterThan: restriction = GetRestrictionGt(fieldValue, propertyExpression); break; case ValuePredicateType.GreaterThanOrEqual: restriction = GetRestrictionGtEq(fieldValue, propertyExpression); break; case ValuePredicateType.Contains: restriction = GetRestrictionContains(fieldValue, propertyExpression); break; case ValuePredicateType.StartsWith: restriction = GetRestrictionStarts(fieldValue, propertyExpression); break; case ValuePredicateType.EndsWith: restriction = GetRestrictionEnds(fieldValue, propertyExpression); break; } if (restriction != null) { if (numberOfMatchesEvaluated == 0) { restrictionBuilder = restriction; numberOfMatchesEvaluated++; } else { restrictionBuilder = Restrictions.Or(restriction, restrictionBuilder); } } } if (restrictionBuilder != null) { queryExtender = queryExtender.Where(restrictionBuilder); } queryExtender = queryExtender .And(x => aliasAttributeDefinition.Alias == fieldName); return(queryExtender.Select(x => x.Id)); }
/// <summary> /// 获取摄像头列表及分组信息 /// </summary> private void GetAllCamerasMethod() { NLogEx.LoggerEx logEx = new NLogEx.LoggerEx(log); logEx.Trace("Enter: TiandyVideoMonitor.GetAllCamerasTimer()."); try { //调用天地伟业http接口获取天地伟业设备管理树列表 List <Resource> resourceTree = this.httpClient.GetResourceTree(); if (resourceTree == null) { logEx.Error("GetResourceTree failed."); ClearCamera(); isRefreshSucess = false; return; } //调用天地伟业http接口获取自定义设备树列表 List <Resource> customTree = this.httpClient.GetCustomTree(); if (customTree == null) { logEx.Error("GetCustomTree failed."); ClearCamera(); isRefreshSucess = false; return; } Dictionary <string, TiandyCamera> tiandyCameraDictionaryTemp = new Dictionary <string, TiandyCamera>(); Dictionary <string, Host> hostDictionaryTemp = new Dictionary <string, Host>(); Dictionary <string, MediaServer> mediaServerDictionaryTemp = new Dictionary <string, MediaServer>(); //递归处理,将摄像头、主机、流媒体服务器遍历出来 RecursionCamera(resourceTree, tiandyCameraDictionaryTemp, hostDictionaryTemp, mediaServerDictionaryTemp); Dictionary <string, CameraGroup> groupDicTemp = new Dictionary <string, CameraGroup>(); Dictionary <string, NodeRelation> nodeRelationDicTemp = new Dictionary <string, NodeRelation>(); List <NodeRelation> nodeRelationListTemp = new List <NodeRelation>(); //递归处理,获取组,摄像头、分组关系 RecursionCameraGroup(customTree, null, groupDicTemp, nodeRelationDicTemp, nodeRelationListTemp); //对于未分组的摄像头,父节点设置为空 foreach (KeyValuePair <string, TiandyCamera> tiandyCameraKeyValue in tiandyCameraDictionaryTemp) { if (!nodeRelationDicTemp.ContainsKey(tiandyCameraKeyValue.Key)) { NodeRelation nodeRelation = new NodeRelation(tiandyCameraKeyValue.Key, new List <string>(), CgwMonitorManage.Common.NodeType.CAMERA); nodeRelationListTemp.Add(nodeRelation); } } DateTime dtStart = DateTime.Now; DateTime dtNow = new DateTime(); while (!isGetDevicesFinish) { dtNow = DateTime.Now; if ((dtNow - dtStart).TotalSeconds > refreshDeviceListOverTime) { isRefreshSucess = false; return; } Thread.Sleep(1); continue; } if (this.cameraOperateLock.TryEnterWriteLock(CgwConst.ENTER_LOCK_WAIT_TIME)) { try { this.tiandyCameraDictionary = tiandyCameraDictionaryTemp; this.hostDictionary = hostDictionaryTemp; this.mediaServerDictionary = mediaServerDictionaryTemp; this.groupDic = groupDicTemp; this.nodeRelationList = nodeRelationListTemp; isRefreshSucess = true; } catch (Exception ex) { isRefreshSucess = false; logEx.Error("Recursion camera failed.Execption message:{0}", ex.Message); } finally { this.cameraOperateLock.ExitWriteLock(); } } } catch (System.Exception ex) { isRefreshSucess = false; logEx.Error("GetAllCamerasTimer catch Exception:{0}", ex.Message); } }
/// <summary>Configure the ChildOrderings of this ParentElementBuilder so <paramref name="childToOrder"/> has relation <paramref name="relation"/> to <paramref name="childToOrderRelativeTo"/>.</summary> public void SetChildOrdering(IElementTreeNode childToOrder, IElementTreeNode childToOrderRelativeTo, NodeRelation relation) { switch (relation) { case NodeRelation.First: IElementTreeNode firstExistingChild = Children.OrderBy(child => child).FirstOrDefault(child => !ChildOrderings.Any(ordering => ordering.After == child)); if (firstExistingChild != null) { ChildOrderings.Add(new ChildOrdering { Before = childToOrder, After = firstExistingChild }); } break; case NodeRelation.Before: ChildOrdering existingOrderingBeforeRelativeChild = ChildOrderings.FirstOrDefault(ordering => ordering.After == childToOrderRelativeTo); if (existingOrderingBeforeRelativeChild != null) { ChildOrderings.Add(new ChildOrdering { Before = childToOrder, After = existingOrderingBeforeRelativeChild.After }); existingOrderingBeforeRelativeChild.After = childToOrder; } else { ChildOrderings.Add(new ChildOrdering { Before = childToOrder, After = childToOrderRelativeTo }); } break; case NodeRelation.After: ChildOrdering existingOrderingAfterRelativeChild = ChildOrderings.FirstOrDefault(ordering => ordering.Before == childToOrderRelativeTo); if (existingOrderingAfterRelativeChild != null) { ChildOrderings.Add(new ChildOrdering { Before = existingOrderingAfterRelativeChild.Before, After = childToOrder }); existingOrderingAfterRelativeChild.Before = childToOrder; } else { ChildOrderings.Add(new ChildOrdering { Before = childToOrderRelativeTo, After = childToOrder }); } break; case NodeRelation.Last: IElementTreeNode lastExistingChild = Children.OrderBy(child => child).FirstOrDefault(child => !ChildOrderings.Any(ordering => ordering.Before == child)); if (lastExistingChild != null) { ChildOrderings.Add(new ChildOrdering { Before = lastExistingChild, After = childToOrder }); } break; default: throw new ArgumentException("Unhandled relation type while trying to set ChildOrdering"); } }
/// <summary> /// 获取摄像头和组之间的关联 /// </summary> /// <param name="cameraListTemp">摄像机列表</param> /// <param name="groupListTemp">分组列表</param> /// <param name="nodeRelationListTemp">组关系列表</param> private void GetCameraAndGroupRelation(List <Camera> cameraListTemp, List <CameraGroup> groupListTemp, List <NodeRelation> nodeRelationListTemp) { NLogEx.LoggerEx logEx = new NLogEx.LoggerEx(log); logEx.Trace("Enter: T28181VideoMonitor.GetCameraAndGroupRelation()."); try { //查询摄像机的父节点,保存摄像机父节点关系列表 foreach (Camera ca in cameraListTemp) { //IVS 摄像机子设备通过主设备跟父节点关联,子设备没有父节点 if (ca.DeviceType == "01") { continue; } //摄像机没有父节点 if (string.IsNullOrEmpty(ca.ParentID)) { NodeRelation nodeRelation = new NodeRelation(ca.No, null, NodeType.CAMERA); nodeRelationListTemp.Add(nodeRelation); } else { string parentID = ca.ParentID; //获取所有父节点路径 List <string> pathList = new List <string>(); FindNodeRelationPath(parentID, groupListTemp, ref pathList); if (pathList.Count > 1) { //按照从顶到底排序 pathList.Reverse(); } ////查询主设备的子设备 //Camera camera = cameraListTemp.Find((x) // => //{ // if (x.ParentID == ca.No) // { // return true; // } // else // { // return false; // } //}); //if (camera != null) //{ //节点关系列表中将摄像机代替摄像机主设备 NodeRelation nodeRelation = new NodeRelation(ca.No, pathList, NodeType.CAMERA); nodeRelationListTemp.Add(nodeRelation); //} } } //设备列表过滤掉摄像机主设备 cameraListTemp.RemoveAll((x) => { if (x.DeviceType == "00") { return(true); } else { return(false); } }); //查询设备组的父节点,保存设备组父节点关系列表 foreach (CameraGroup cg in groupListTemp) { //设备组没有父节点 if (string.IsNullOrEmpty(cg.ParentID)) { NodeRelation nodeRelation = new NodeRelation(cg.No, null, NodeType.GROUP); nodeRelationListTemp.Add(nodeRelation); } else { string parentID = cg.ParentID; //获取分组所有父节点路径 List <string> pathList = new List <string>(); FindNodeRelationPath(parentID, groupListTemp, ref pathList); if (pathList.Count > 1) { //按照从顶到底排序 pathList.Reverse(); } //保存分组的父节点列表 NodeRelation nodeRelation = new NodeRelation(cg.No, pathList, NodeType.GROUP); nodeRelationListTemp.Add(nodeRelation); } } //将实时获取的值放到缓存 if (this.cameraOperateLock.TryEnterWriteLock(CgwConst.ENTER_LOCK_WAIT_TIME)) { try { this.cameraList = cameraListTemp; this.groupList = groupListTemp; this.nodeRelationList = nodeRelationListTemp; } catch (Exception ex) { logEx.Error("Set the list to the buffer failed. ", ex.Message); } finally { this.cameraOperateLock.ExitWriteLock(); } } } catch (System.Exception ex) { logEx.Error("GetCameraAndGroupRelation failed. {0} ", ex.Message); } }