static public void Execute(atom.Trace context, int level, IHtmlCollection <IElement> data)
 {
     if ((data != null) && (data.Length > 0))
     {
         context.
         SetComment(GetArraySize(data), "").
         Send(NAME.SOURCE.PREVIEW, NAME.TYPE.FOLDER, level, "[[Links]]");
         foreach (var a_Context in data)
         {
             var a_Name1 = GetFirstLine(NodeExtensions.Text(a_Context));
             var a_Name2 = GetFirstLine(NodeExtensions.HyperReference(a_Context, a_Context.GetAttribute("Href"))?.Href);
             if (string.IsNullOrEmpty(a_Name1))
             {
                 a_Name1 = GetFirstLine(a_Context.InnerHtml);
             }
             if ((string.IsNullOrEmpty(a_Name1) == false) || (string.IsNullOrEmpty(a_Name2) == false))
             {
                 context.
                 SetUrl(a_Name2, "").
                 SetComment("[[Link]]", HINT.DATA_TYPE).
                 Send(NAME.SOURCE.PREVIEW, NAME.TYPE.INFO, level + 1, a_Name1);
             }
         }
     }
 }
        public override void OnDraw(Graphics g)
        {
            if ((Control.ModifierKeys & Keys.Control) == Keys.Control)
            {
                var allOtherNodes = diagram.Nodes.Except(selectedObjectsPositions.Keys).ToArray();
                if (allOtherNodes.Length > 0)
                {
                    int  xClosestToCursor;
                    Node closestNodeX;
                    bool left;
                    bool selLeft;
                    int  yClosestToCursor;
                    Node closestNodeY;
                    bool top;
                    bool selTop;

                    var bbox = NodeExtensions.GetBoundingBox(selectedObjectsPositions.Keys.Select(n => n.Area));

                    GetClosestGuideline(bbox, allOtherNodes, out xClosestToCursor, out yClosestToCursor, out closestNodeX, out closestNodeY, out left, out selLeft, out top, out selTop);

                    try
                    {
                        Rectangle closestXArea = closestNodeX.Area;
                        closestXArea.Offset((int)(diagram.AutoScrollPosition.X / diagram.Zoom), (int)(diagram.AutoScrollPosition.Y / diagram.Zoom));
                        closestXArea = closestXArea.Zoom(diagram.Zoom);

                        Rectangle closestYArea = closestNodeY.Area;
                        closestYArea.Offset((int)(diagram.AutoScrollPosition.X / diagram.Zoom), (int)(diagram.AutoScrollPosition.Y / diagram.Zoom));
                        closestYArea = closestYArea.Zoom(diagram.Zoom);

                        if (xClosestToCursor < 10)
                        {
                            if (left)
                            {
                                g.DrawLine(Pens.LimeGreen, new Point(closestXArea.Left, 0), new Point(closestXArea.Left, diagram.Height));
                            }
                            else
                            {
                                g.DrawLine(Pens.LimeGreen, new Point(closestXArea.Right, 0), new Point(closestXArea.Right, diagram.Height));
                            }
                        }

                        if (yClosestToCursor < 10)
                        {
                            if (top)
                            {
                                g.DrawLine(Pens.LimeGreen, new Point(0, closestYArea.Top), new Point(diagram.Width, closestYArea.Top));
                            }
                            else
                            {
                                g.DrawLine(Pens.LimeGreen, new Point(0, closestYArea.Bottom), new Point(diagram.Width, closestYArea.Bottom));
                            }
                        }
                    }
                    catch (System.NullReferenceException e)
                    {
                    }
                }
            }
        }
示例#3
0
        private MarkNode CreateNodeMark(IEnumerable <OffsetMark> offsetMarks)
        {
            IList <Tuple <int, OffsetMark> > paras;

            if (!offsetMarks.Any())
            {
                paras = new List <Tuple <int, OffsetMark> >()
                {
                }
            }
            ;
            else
            {
                paras = offsetMarks.Select(x => new Tuple <int, OffsetMark>(x.Total, x)).ToList();
            }
            var top = NodeExtensions.CreateNodes(
                paras,
                () => new MarkNode(),
                (offsetMark, globalIndex, index) => new MarkNode()
            {
                OffsetMark  = offsetMark,
                GlobalIndex = globalIndex,
                Index       = index
            });

            return(top);
        }
示例#4
0
        public SolutionSearchBase <TState, TAction> Search(
            ISearchProblem <TState, TAction> problem)
        {
            var rootNode = Node <TState, TAction> .Root(problem.InitialState);

            if (problem.GoalTest(rootNode.State))
            {
                return(new SolutionFound <TState, TAction>(rootNode));
            }

            var frontier = new BasicPriorityQueue <double, FrontierItem <TState, TAction> >(
                x => x.Evaluation);

            var explored = new HashSet <TState>(sComparer);

            frontier.Enqueue(new FrontierItem <TState, TAction>(rootNode,
                                                                EvaluationFuntion(problem, rootNode)));

            while (frontier.Count > 0)
            {
                var element = frontier.Dequeue();

                if (problem.GoalTest(element.Node.State))
                {
                    return(new SolutionFound <TState, TAction>(element.Node));
                }

                explored.Add(element.Node.State);

                var actions = problem.Actions(element.Node.State);

                foreach (var action in actions)
                {
                    var child = NodeExtensions.ChildNode(problem, element.Node, action);

                    var childElement = new FrontierItem <TState, TAction>(child,
                                                                          EvaluationFuntion(problem, child));

                    var comparedChild = frontier.CherryPeek(
                        x => sComparer.Equals(x.Node.State, childElement.Node.State));

                    bool stateInFrontier = comparedChild != default;

                    bool containsState = explored.Contains(child.State) || stateInFrontier;

                    if (!containsState)
                    {
                        frontier.Enqueue(childElement);
                    }
                    else if (stateInFrontier &&
                             comparedChild.Evaluation > childElement.Evaluation)
                    {
                        frontier.ReplaceWith(comparedChild, childElement);
                    }
                }
            }

            return(new SolutionFailure <TState, TAction>());
        }
示例#5
0
 public static INode[] GetTouchingPaths(ISourceFile sourceFile, IReadOnlyList <int> positions, System.Threading.CancellationToken token)
 {
     return(NodeExtensions.TryGetNodesAtPositions(
                sourceFile,
                positions,
                isNodeAcceptable: (n) => n.Kind.IsWord() || n.IsPathLikeLiteral(),
                token: token));
 }
        public CompilationUnitSyntax ComputeRoot(CompilationUnitSyntax root)
        {
            var newProperty = NodeExtensions.Nicefy(_property
                                                    .WithAccessorList(null)
                                                    .WithExpressionBody(ArrowExpressionClause(GetExpression()))
                                                    .WithSemicolon(SemicolonToken.ToToken()));

            return(root.ReplaceNode(_property as SyntaxNode, newProperty as SyntaxNode));
        }
示例#7
0
        public static INode GetTouchingWord(ISourceFile sourceFile, int position, System.Threading.CancellationToken token)
        {
            NodeExtensions.TryGetNodeAtPosition(
                sourceFile,
                position,
                isNodeAcceptable: (n) => n.Kind.IsWord() || n.IsStringLikeLiteral(),
                token: token,
                currentNode: out var node);

            return(node);
        }
示例#8
0
        public CompilationUnitSyntax ComputeRoot(CompilationUnitSyntax root)
        {
            var statement = SyntaxFactoryExtensions.ToReturnStatement(_property.ExpressionBody.Expression) as ReturnStatementSyntax;
            var getter    = AccessorDeclaration(GetAccessorDeclaration, Block(statement));

            var newProperty = NodeExtensions.Nicefy(_property
                                                    .WithExpressionBody(null)
                                                    .WithAccessorList(AccessorList(new[] { getter }.ToSyntaxList()))
                                                    .WithSemicolon(None.ToToken()));

            return(root.ReplaceNode(_property as SyntaxNode, newProperty as SyntaxNode));
        }
示例#9
0
        public void ComputePositionBackAndForth()
        {
            string code =
                @"namespace X {
    enum Foo {value = 42}
}";

            var sourceFile = ParsingHelper.ParseSourceFile(code);

            var enumMember = NodeWalkerEx.GetDescendantNodes(sourceFile).First(n => n.Node.Kind == SyntaxKind.EnumMember).Node.Cast <IEnumMember>();
            var lineInfo   = enumMember.GetLineInfo(sourceFile);

            NodeExtensions.TryConvertLineOffsetToPosition(sourceFile, lineInfo.Line, lineInfo.Position, out var position);
            Assert.Equal(enumMember.GetNodeStartPositionWithoutTrivia(), position);
            Assert.Equal(enumMember.Name, GetNodeAtPosition(sourceFile, position));
        }
示例#10
0
        public SolutionSearchBase <TState, TAction> Search(ISearchProblem <TState, TAction> problem)
        {
            var rootNode = Node <TState, TAction> .Root(problem.InitialState);

            if (problem.GoalTest(rootNode.State))
            {
                return(new SolutionFound <TState, TAction>(rootNode));
            }


            var frontier = new Stack <Node <TState, TAction> >();

            var explored = new HashSet <TState>(sComparer);

            frontier.Push(rootNode);

            while (frontier.Count > 0)
            {
                var node = frontier.Pop();

                explored.Add(node.State);

                var actions = problem.Actions(node.State);

                foreach (var action in actions)
                {
                    var child = NodeExtensions.ChildNode(problem, node, action);

                    bool containsState = explored.Contains(child.State) ||
                                         frontier.Contains(child, nComparer);

                    if (!containsState)
                    {
                        if (problem.GoalTest(child.State))
                        {
                            return(new SolutionFound <TState, TAction>(child));
                        }

                        frontier.Push(child);
                    }
                }
            }

            return(new SolutionFailure <TState, TAction>());
        }
示例#11
0
        private SolutionSearchBase <TState, TAction> RecursiveDLS(
            Node <TState, TAction> node, ISearchProblem <TState, TAction> problem, int limit)
        {
            if (problem.GoalTest(node.State))
            {
                return(new SolutionFound <TState, TAction>(node));
            }
            else if (limit == 0)
            {
                return(new SolutionCutoff <TState, TAction>());
            }
            else
            {
                var cutoffOccurred = false;

                var actions = problem.Actions(node.State);

                foreach (var action in actions)
                {
                    var child = NodeExtensions.ChildNode(problem, node, action);

                    var result = RecursiveDLS(child, problem, limit - 1);

                    if (result.GetType() == typeof(SolutionCutoff <TState, TAction>))
                    {
                        cutoffOccurred = true;
                    }
                    else if (result.GetType() != typeof(SolutionFailure <TState, TAction>))
                    {
                        return(result);
                    }
                }

                if (cutoffOccurred)
                {
                    return(new SolutionCutoff <TState, TAction>());
                }
                else
                {
                    return(new SolutionFailure <TState, TAction>());
                }
            }
        }
示例#12
0
        public void ComputePositionBackAndForthWithWeirdCommentsInside()
        {
            string code =
                @"
const x = 42;
/*
* Some comment
*/
namespace X {
    // simple comment
    enum /*another comment*/ Foo {/*and yet another comment*/value = 42}
}";

            var sourceFile = ParsingHelper.ParseSourceFile(code);

            var enumMember = NodeWalkerEx.GetDescendantNodes(sourceFile).First(n => n.Node.Kind == SyntaxKind.EnumMember).Node.Cast <IEnumMember>();
            var lineInfo   = enumMember.GetLineInfo(sourceFile);

            NodeExtensions.TryConvertLineOffsetToPosition(sourceFile, lineInfo.Line, lineInfo.Position, out var position);
            Assert.Equal(enumMember.GetNodeStartPositionWithoutTrivia(), position);
            Assert.Equal(enumMember.Name, GetNodeAtPosition(sourceFile, position));
        }
        /// <summary>
        /// Update the bounds of the node to fully wrap all the children nodes
        /// </summary>
        public void UpdateBounds()
        {
            // if not suspended
            if (!freezeBoundingBox)
            {
                // adjust the position and size to fit
                if (Children.Count > 0)
                {
                    var bbox = NodeExtensions.GetBoundingBox(Children.Select(c => c.Area));
                    bbox.Inflate(parent.GridSize.Width, parent.GridSize.Height);

                    var padding = paddingForText / parent.GridSize.Height * parent.GridSize.Height;
                    this.Position = new Point(bbox.Location.X, bbox.Location.Y - padding).RoundTo(parent.GridSize.Width, parent.GridSize.Height);
                    this.nodeSize = new Size(bbox.Size.Width, bbox.Size.Height + padding);
                }
            }

            // if the current container has a parent container, update its bounds to fit (because the current container node size & position could be changed
            if (Container != null)
            {
                Container.UpdateBounds();
            }
        }
示例#14
0
        public virtual void UpdateSlots()
        {
            var validNames = new List <int>();

            if (referencedGraph == null)
            {
                RemoveSlotsNameNotMatching(validNames);
                return;
            }

            var props = referencedGraph.properties;

            foreach (var prop in props)
            {
                var           propType = prop.propertyType;
                SlotValueType slotType;

                switch (propType)
                {
                case PropertyType.Color:
                    slotType = SlotValueType.Vector4;
                    break;

                case PropertyType.Texture:
                    slotType = SlotValueType.Texture2D;
                    break;

                case PropertyType.Cubemap:
                    slotType = SlotValueType.Cubemap;
                    break;

                case PropertyType.Gradient:
                    slotType = SlotValueType.Gradient;
                    break;

                case PropertyType.Vector1:
                    slotType = SlotValueType.Vector1;
                    break;

                case PropertyType.Vector2:
                    slotType = SlotValueType.Vector2;
                    break;

                case PropertyType.Vector3:
                    slotType = SlotValueType.Vector3;
                    break;

                case PropertyType.Vector4:
                    slotType = SlotValueType.Vector4;
                    break;

                case PropertyType.Matrix2:
                    slotType = SlotValueType.Matrix2;
                    break;

                case PropertyType.Matrix3:
                    slotType = SlotValueType.Matrix3;
                    break;

                case PropertyType.Matrix4:
                    slotType = SlotValueType.Matrix4;
                    break;

                default:
                    throw new ArgumentOutOfRangeException();
                }

                var          id   = prop.guid.GetHashCode();
                MaterialSlot slot = MaterialSlot.CreateMaterialSlot(slotType, id, prop.displayName, prop.referenceName, SlotType.Input, prop.defaultValue);
                // copy default for texture for niceness
                if (slotType == SlotValueType.Texture2D && propType == PropertyType.Texture)
                {
                    var tSlot = slot as Texture2DInputMaterialSlot;
                    var tProp = prop as TextureShaderProperty;
                    if (tSlot != null && tProp != null)
                    {
                        tSlot.texture = tProp.value.texture;
                    }
                }
                // copy default for cubemap for niceness
                else if (slotType == SlotValueType.Cubemap && propType == PropertyType.Cubemap)
                {
                    var tSlot = slot as CubemapInputMaterialSlot;
                    var tProp = prop as CubemapShaderProperty;
                    if (tSlot != null && tProp != null)
                    {
                        tSlot.cubemap = tProp.value.cubemap;
                    }
                }
                AddSlot(slot);
                validNames.Add(id);
            }

            var subGraphOutputNode = outputNode;

            if (outputNode != null)
            {
                foreach (var slot in NodeExtensions.GetInputSlots <MaterialSlot>(subGraphOutputNode))
                {
                    AddSlot(MaterialSlot.CreateMaterialSlot(slot.valueType, slot.id, slot.RawDisplayName(), slot.shaderOutputName, SlotType.Output, Vector4.zero));
                    validNames.Add(slot.id);
                }
            }

            RemoveSlotsNameNotMatching(validNames);
        }
示例#15
0
 private static INode GetNodeAtPosition(ISourceFile sourceFile, int position)
 {
     NodeExtensions.TryGetNodeAtPosition(sourceFile, position, out INode result);
     return(result);
 }
        private void MoveNode(MouseEventArgs e, bool snapToGrid)
        {
            int offX = e.X - orgPos.X;
            int offY = e.Y - orgPos.Y;


            var allOtherNodes = diagram.Nodes.Except(selectedObjectsPositions.Keys).ToArray();

            if (allOtherNodes.Length > 0 && (Control.ModifierKeys & Keys.Control) == Keys.Control)
            {
                int  xClosestToCursor;
                Node closestNodeX;
                bool left;
                bool selLeft;
                int  yClosestToCursor;
                Node closestNodeY;
                bool top;
                bool selTop;

                var bbox = NodeExtensions.GetBoundingBox(selectedObjectsPositions.Keys.Select(n => n.Area));
                GetClosestGuideline(bbox, allOtherNodes, out xClosestToCursor, out yClosestToCursor, out closestNodeX, out closestNodeY, out left, out selLeft, out top, out selTop);



                foreach (var pair in selectedObjectsPositions)
                {
                    int posX = pair.Value.X + offX;
                    int posY = pair.Value.Y + offY;
                    if (xClosestToCursor < 10)
                    {
                        if (left)
                        {
                            if (selLeft)
                            {
                                posX = closestNodeX.Area.Left;
                            }
                            else
                            {
                                posX = closestNodeX.Area.Left - pair.Key.Area.Width;
                            }
                        }
                        else
                        {
                            if (selLeft)
                            {
                                posX = closestNodeX.Area.Right;
                            }
                            else
                            {
                                posX = closestNodeX.Area.Right - pair.Key.Area.Width;
                            }
                        }
                    }
                    if (yClosestToCursor < 10)
                    {
                        if (top)
                        {
                            if (selTop)
                            {
                                posY = closestNodeY.Area.Top;
                            }
                            else
                            {
                                posY = closestNodeY.Area.Top - pair.Key.Area.Height;
                            }
                        }
                        else
                        {
                            if (selTop)
                            {
                                posY = closestNodeY.Area.Bottom;
                            }
                            else
                            {
                                posY = closestNodeY.Area.Bottom - pair.Key.Area.Height;
                            }
                        }
                    }


                    pair.Key.Position = new Point(posX, posY);
                }
            }
            else
            {
                foreach (var pair in selectedObjectsPositions)
                {
                    int posX = pair.Value.X + offX;
                    int posY = pair.Value.Y + offY;

                    if (snapToGrid)
                    {
                        pair.Key.Position = new Point(posX, posY).RoundTo(diagram.GridSize.Width, diagram.GridSize.Height);
                    }
                    else
                    {
                        pair.Key.Position = new Point(posX, posY);
                    }
                }
            }

            diagram.Redraw();
        }
示例#17
0
        private void Register <T>(T node, NodeFlags flags, DocNodeType type, string name, Action <T> visit)
            where T : INode
        {
            var injected = NodeExtensions.IsInjectedForDScript(node);

            if (injected)
            {
                return;
            }

            var visibility = DocNodeVisibility.Private;

            if ((flags & NodeFlags.Export) != 0)
            {
                visibility = DocNodeVisibility.Internal;
            }

            if ((flags & NodeFlags.ScriptPublic) != 0 || type == DocNodeType.Namespace)
            {
                visibility = DocNodeVisibility.Public;
            }

            List <string> triviaContent = new List <string>();

            AddComments(node, triviaContent);

            if (type == DocNodeType.EnumMember || type == DocNodeType.Value || type == DocNodeType.Property)
            {
                // For these edge nodes, we can safely visit their children to seek out other documentation.
                // The documentation chunks may be in the wrong order due to search order, but the results will be complete.
                node.ForEachChildRecursively <TypeScript.Net.Types.Node>(
                    n =>
                {
                    AddComments(n, triviaContent);

                    return(null);
                },
                    recurseThroughIdentifiers: true);
            }
            else
            {
                if (node.Decorators?.Length > 0)
                {
                    foreach (var decorator in node.Decorators.Elements)
                    {
                        AddComments(decorator, triviaContent);
                    }
                }
            }

            string appendix = string.Empty;

            // Handle Tool.option attribute
            IPropertyAccessExpression propertyAccessExpression;
            ICallExpression           callExpression;
            IIdentifier        propertyIdentifier;
            ILiteralExpression literal;

            if (node.Decorators?.Count > 0 &&
                (callExpression = node.Decorators.Elements[0].Expression.As <ICallExpression>()) != null &&
                (propertyAccessExpression = callExpression.Expression.As <IPropertyAccessExpression>()) != null &&
                (propertyIdentifier = propertyAccessExpression.Expression.As <IIdentifier>()) != null &&
                propertyIdentifier.Text == "Tool" &&
                propertyAccessExpression.Name.Text == "option" &&
                callExpression.Arguments.Count > 0 &&
                (literal = callExpression.Arguments[0].As <ILiteralExpression>()) != null)
            {
                appendix = $"Tool option {literal.Text}";
            }

            DocNode newNode;
            var     parent = m_declarations.Peek();

            if (parent != null)
            {
                newNode = parent.GetOrAdd(type, visibility, m_path, name, triviaContent, appendix);
            }
            else
            {
                newNode = m_module.GetOrAdd(type, visibility, m_path, name, triviaContent, appendix);
            }

            m_declarations.Push(newNode);
            visit(node);
            m_declarations.Pop();
        }
示例#18
0
        /// <summary>
        /// Deletes the items from the database.
        /// </summary>
        /// <param name="serviceProvider">The application service provider.</param>
        /// <param name="token">The cancellation token for the task.</param>
        public async Task DeleteAsync(IServiceProvider serviceProvider, CancellationToken token)
        {
            // Check if there weren't any valid items found.
            if (Items == null)
            {
                // Throw an exception.
                throw new TaskException("No valid items could be found with the provided data.");
            }
            // Get the total number of batches.
            var count = Math.Ceiling((double)Items.Count() / ApplicationDbContext.BatchSize);

            // Go over each batch.
            for (var index = 0; index < count; index++)
            {
                // Check if the cancellation was requested.
                if (token.IsCancellationRequested)
                {
                    // Break.
                    break;
                }
                // Get the items in the current batch.
                var batchItems = Items
                                 .Skip(index * ApplicationDbContext.BatchSize)
                                 .Take(ApplicationDbContext.BatchSize);
                // Get the IDs of the items in the current batch.
                var batchIds = batchItems.Select(item => item.Id);
                // Define the list of items to get.
                var nodes = new List <Node>();
                // Use a new scope.
                using (var scope = serviceProvider.CreateScope())
                {
                    // Use a new context instance.
                    using var context = scope.ServiceProvider.GetRequiredService <ApplicationDbContext>();
                    // Get the items with the provided IDs.
                    var items = context.Nodes
                                .Where(item => batchIds.Contains(item.Id));
                    // Check if there were no items found.
                    if (items == null || !items.Any())
                    {
                        // Continue.
                        continue;
                    }
                    // Get the items found.
                    nodes = items
                            .ToList();
                }
                // Get the IDs of the items.
                var nodeIds = nodes
                              .Select(item => item.Id);
                // Delete the dependent entities.
                await NodeExtensions.DeleteDependentAnalysesAsync(nodeIds, serviceProvider, token);

                await NodeExtensions.DeleteDependentNetworksAsync(nodeIds, serviceProvider, token);

                await NodeExtensions.DeleteDependentNodeCollectionsAsync(nodeIds, serviceProvider, token);

                await NodeExtensions.DeleteDependentEdgesAsync(nodeIds, serviceProvider, token);

                // Delete the related entities.
                await NodeExtensions.DeleteRelatedEntitiesAsync <DatabaseNodeFieldNode>(nodeIds, serviceProvider, token);

                await NodeExtensions.DeleteRelatedEntitiesAsync <DatabaseNode>(nodeIds, serviceProvider, token);

                // Delete the items.
                await IEnumerableExtensions.DeleteAsync(nodes, serviceProvider, token);
            }
        }
示例#19
0
        /// <summary>
        /// Edits the items in the database.
        /// </summary>
        /// <param name="serviceProvider">The application service provider.</param>
        /// <param name="token">The cancellation token for the task.</param>
        public async Task EditAsync(IServiceProvider serviceProvider, CancellationToken token)
        {
            // Check if there weren't any valid items found.
            if (Items == null)
            {
                // Throw an exception.
                throw new TaskException("No valid items could be found with the provided data.");
            }
            // Check if the exception item should be shown.
            var showExceptionItem = Items.Count() > 1;
            // Get the total number of batches.
            var count = Math.Ceiling((double)Items.Count() / ApplicationDbContext.BatchSize);

            // Go over each batch.
            for (var index = 0; index < count; index++)
            {
                // Check if the cancellation was requested.
                if (token.IsCancellationRequested)
                {
                    // Break.
                    break;
                }
                // Get the items in the current batch.
                var batchItems = Items
                                 .Skip(index * ApplicationDbContext.BatchSize)
                                 .Take(ApplicationDbContext.BatchSize);
                // Get the IDs of the items in the current batch.
                var batchIds = batchItems
                               .Where(item => !string.IsNullOrEmpty(item.Id))
                               .Select(item => item.Id)
                               .Distinct();
                // Get the IDs of the related entities that appear in the current batch.
                var batchDatabaseNodeFieldIds = batchItems
                                                .Where(item => item.DatabaseNodeFieldNodes != null)
                                                .Select(item => item.DatabaseNodeFieldNodes)
                                                .SelectMany(item => item)
                                                .Where(item => item.DatabaseNodeField != null)
                                                .Select(item => item.DatabaseNodeField)
                                                .Where(item => !string.IsNullOrEmpty(item.Id))
                                                .Select(item => item.Id)
                                                .Distinct();
                // Define the list of items to get.
                var nodes = new List <Node>();
                var databaseNodeFields = new List <DatabaseNodeField>();
                // Define the dependent list of items to get.
                var analysisInputs = new List <AnalysisInputModel>();
                var networkInputs  = new List <NetworkInputModel>();
                var edgeInputs     = new List <EdgeInputModel>();
                // Use a new scope.
                using (var scope = serviceProvider.CreateScope())
                {
                    // Use a new context instance.
                    using var context = scope.ServiceProvider.GetRequiredService <ApplicationDbContext>();
                    // Get the items with the provided IDs.
                    var items = context.Nodes
                                .Where(item => !item.DatabaseNodes.Any(item1 => item1.Database.DatabaseType.Name == "Generic"))
                                .Where(item => batchIds.Contains(item.Id));
                    // Check if there were no items found.
                    if (items == null || !items.Any())
                    {
                        // Continue.
                        continue;
                    }
                    // Get the items found.
                    nodes = items
                            .ToList();
                    // Get the related entities that appear in the current batch.
                    databaseNodeFields = context.DatabaseNodeFields
                                         .Include(item => item.Database)
                                         .Where(item => item.Database.DatabaseType.Name != "Generic")
                                         .Where(item => batchDatabaseNodeFieldIds.Contains(item.Id))
                                         .ToList();
                }
                // Get the IDs of the items.
                var nodeIds = nodes
                              .Select(item => item.Id);
                // Save the items to edit.
                var nodesToEdit = new List <Node>();
                // Go over each item in the current batch.
                foreach (var batchItem in batchItems)
                {
                    // Get the corresponding item.
                    var node = nodes
                               .FirstOrDefault(item => item.Id == batchItem.Id);
                    // Check if there was no item found.
                    if (node == null)
                    {
                        // Continue.
                        continue;
                    }
                    // Check if there are no database node field nodes provided.
                    if (batchItem.DatabaseNodeFieldNodes == null || !batchItem.DatabaseNodeFieldNodes.Any())
                    {
                        // Throw an exception.
                        throw new TaskException("There were no database node field nodes provided.", showExceptionItem, batchItem);
                    }
                    // Get the database node field nodes.
                    var databaseNodeFieldNodes = batchItem.DatabaseNodeFieldNodes
                                                 .Where(item => item.DatabaseNodeField != null)
                                                 .Where(item => !string.IsNullOrEmpty(item.DatabaseNodeField.Id))
                                                 .Where(item => !string.IsNullOrEmpty(item.Value))
                                                 .Select(item => (item.DatabaseNodeField.Id, item.Value))
                                                 .Distinct()
                                                 .Where(item => databaseNodeFields.Any(item1 => item1.Id == item.Item1))
                                                 .Select(item => new DatabaseNodeFieldNode
                    {
                        DatabaseNodeFieldId = item.Item1,
                        Value = item.Item2
                    });
                    // Check if there were no database node fields found.
                    if (databaseNodeFieldNodes == null)
                    {
                        // Throw an exception.
                        throw new TaskException("There were no database node fields found.", showExceptionItem, batchItem);
                    }
                    // Check if there were no searchable database node fields found.
                    var databaseNodeFieldIds = databaseNodeFieldNodes
                                               .Select(item => item.DatabaseNodeFieldId)
                                               .Distinct();
                    var currentDatabaseNodeFields = databaseNodeFields
                                                    .Where(item => databaseNodeFieldIds.Contains(item.Id));
                    if (!currentDatabaseNodeFields.Any(item => item.IsSearchable))
                    {
                        // Throw an exception.
                        throw new TaskException("There were no searchable database node fields found.", showExceptionItem, batchItem);
                    }
                    // Update the node.
                    node.Name = !string.IsNullOrEmpty(batchItem.Name) ? batchItem.Name :
                                (databaseNodeFieldNodes
                                 .FirstOrDefault(item => item.DatabaseNodeFieldId == currentDatabaseNodeFields
                                                 .FirstOrDefault(item => item.IsSearchable)?.Id)?.Value ??
                                 "Unnamed node");
                    node.Description            = batchItem.Description;
                    node.DatabaseNodeFieldNodes = databaseNodeFieldNodes.ToList();
                    node.DatabaseNodes          = currentDatabaseNodeFields
                                                  .Select(item => item.Database)
                                                  .Distinct()
                                                  .Select(item => new DatabaseNode
                    {
                        DatabaseId = item.Id
                    })
                                                  .ToList();
                    // Add the node to the list.
                    nodesToEdit.Add(node);
                }
                // Delete the dependent entities.
                await NodeExtensions.DeleteDependentAnalysesAsync(nodeIds, serviceProvider, token);

                await NodeExtensions.DeleteDependentNetworksAsync(nodeIds, serviceProvider, token);

                await NodeExtensions.DeleteDependentNodeCollectionsAsync(nodeIds, serviceProvider, token);

                await NodeExtensions.DeleteDependentEdgesAsync(nodeIds, serviceProvider, token);

                // Delete the related entities.
                await NodeExtensions.DeleteRelatedEntitiesAsync <DatabaseNodeFieldNode>(nodeIds, serviceProvider, token);

                await NodeExtensions.DeleteRelatedEntitiesAsync <DatabaseNode>(nodeIds, serviceProvider, token);

                // Edit the items.
                await IEnumerableExtensions.EditAsync(nodesToEdit, serviceProvider, token);
            }
        }
示例#20
0
 /// <summary>
 /// Returns whether the <paramref name="node"/> is injected.
 /// In other words: The node is added after the parsing is over.
 /// </summary>
 public static bool IsInjectedForDScript(this INode node)
 {
     return(NodeExtensions.IsInjectedForDScript(node));
 }
示例#21
0
        public virtual void UpdateSlots()
        {
            var validNames = new List <int>();

            if (referencedGraph == null)
            {
                RemoveSlotsNameNotMatching(validNames, true);
                return;
            }

            var props = referencedGraph.properties;

            foreach (var prop in props)
            {
                var           propType = prop.propertyType;
                SlotValueType slotType;

                switch (propType)
                {
                case PropertyType.Color:
                    slotType = SlotValueType.Vector4;
                    break;

                case PropertyType.Texture2D:
                    slotType = SlotValueType.Texture2D;
                    break;

                case PropertyType.Texture2DArray:
                    slotType = SlotValueType.Texture2DArray;
                    break;

                case PropertyType.Texture3D:
                    slotType = SlotValueType.Texture3D;
                    break;

                case PropertyType.Cubemap:
                    slotType = SlotValueType.Cubemap;
                    break;

                case PropertyType.Gradient:
                    slotType = SlotValueType.Gradient;
                    break;

                case PropertyType.Vector1:
                    slotType = SlotValueType.Vector1;
                    break;

                case PropertyType.Vector2:
                    slotType = SlotValueType.Vector2;
                    break;

                case PropertyType.Vector3:
                    slotType = SlotValueType.Vector3;
                    break;

                case PropertyType.Vector4:
                    slotType = SlotValueType.Vector4;
                    break;

                case PropertyType.Boolean:
                    slotType = SlotValueType.Boolean;
                    break;

                case PropertyType.Matrix2:
                    slotType = SlotValueType.Matrix2;
                    break;

                case PropertyType.Matrix3:
                    slotType = SlotValueType.Matrix3;
                    break;

                case PropertyType.Matrix4:
                    slotType = SlotValueType.Matrix4;
                    break;

                default:
                    throw new ArgumentOutOfRangeException();
                }

                var propertyString = prop.guid.ToString();
                var propertyIndex  = m_PropertyGuids.IndexOf(propertyString);
                if (propertyIndex < 0)
                {
                    propertyIndex = m_PropertyGuids.Count;
                    m_PropertyGuids.Add(propertyString);
                    m_PropertyIds.Add(prop.guid.GetHashCode());
                }
                var          id   = m_PropertyIds[propertyIndex];
                MaterialSlot slot = MaterialSlot.CreateMaterialSlot(slotType, id, prop.displayName, prop.referenceName, SlotType.Input, prop.defaultValue, ShaderStageCapability.All);
                // copy default for texture for niceness
                if (slotType == SlotValueType.Texture2D && propType == PropertyType.Texture2D)
                {
                    var tSlot = slot as Texture2DInputMaterialSlot;
                    var tProp = prop as TextureShaderProperty;
                    if (tSlot != null && tProp != null)
                    {
                        tSlot.texture = tProp.value.texture;
                    }
                }
                // copy default for texture array for niceness
                else if (slotType == SlotValueType.Texture2DArray && propType == PropertyType.Texture2DArray)
                {
                    var tSlot = slot as Texture2DArrayInputMaterialSlot;
                    var tProp = prop as Texture2DArrayShaderProperty;
                    if (tSlot != null && tProp != null)
                    {
                        tSlot.textureArray = tProp.value.textureArray;
                    }
                }
                // copy default for texture 3d for niceness
                else if (slotType == SlotValueType.Texture3D && propType == PropertyType.Texture3D)
                {
                    var tSlot = slot as Texture3DInputMaterialSlot;
                    var tProp = prop as Texture3DShaderProperty;
                    if (tSlot != null && tProp != null)
                    {
                        tSlot.texture = tProp.value.texture;
                    }
                }
                // copy default for cubemap for niceness
                else if (slotType == SlotValueType.Cubemap && propType == PropertyType.Cubemap)
                {
                    var tSlot = slot as CubemapInputMaterialSlot;
                    var tProp = prop as CubemapShaderProperty;
                    if (tSlot != null && tProp != null)
                    {
                        tSlot.cubemap = tProp.value.cubemap;
                    }
                }
                AddSlot(slot);
                validNames.Add(id);
            }

            if (outputNode != null)
            {
                var outputStage = ((SubGraphOutputNode)outputNode).effectiveShaderStage;

                foreach (var slot in NodeExtensions.GetInputSlots <MaterialSlot>(outputNode))
                {
                    AddSlot(MaterialSlot.CreateMaterialSlot(slot.valueType, slot.id, slot.RawDisplayName(),
                                                            slot.shaderOutputName, SlotType.Output, Vector4.zero, outputStage));
                    validNames.Add(slot.id);
                }
            }

            RemoveSlotsNameNotMatching(validNames);
        }
示例#22
0
            public void ThrowsArgumentNullException_WhenNodeIsNull()
            {
                var ex = Assert.Throws <ArgumentNullException>(() => NodeExtensions.GetValue <string>(null, "foo"));

                ex.Should().NotBeNull();
            }