Auto Layout not working

I am trying to generate a diagram with autolayout nodes, however autolayout does not seem to be working and all the nodes are bunched up in the top left corner of the canvas. You have to drag them out individually. my code is below.


Image_7504_1706779736419

    <SfDiagramComponent Height="600px" Nodes="@Nodes" Connectors="@connectors" NodeCreating="@OnNodeCreating" ConnectorCreating="@OnConnectorCreating" Layout="@Layout">


    </SfDiagramComponent>



@code {

    private SfDiagramComponent diagram;

    private DiagramObjectCollection<Node> Nodes = new DiagramObjectCollection<Node>();

    private DiagramObjectCollection<Connector> connectors = new DiagramObjectCollection<Connector>();





    Layout Layout = new Layout()

    {

        Type = LayoutType.OrganizationalChart,

        HorizontalSpacing = 40,

        VerticalSpacing = 40,

        Margin = new LayoutMargin() { Left = 100, Top = 100 }

    };



    private void OnNodeCreating(IDiagramObject obj)

    {

        Node node = obj as Node;

        node.Height = 70;

        node.Width = 100;

        //Initializing the default node's shape style.

        node.Style = new ShapeStyle() { StrokeWidth = 1, StrokeColor = "Black" };

        node.Annotations = new DiagramObjectCollection<ShapeAnnotation>()

        {

            new ShapeAnnotation { Style = new TextStyle() { Bold = true },Content = node.Annotations[0].Content }

        };

    }


    private void OnConnectorCreating(IDiagramObject connector)

    {

        (connector as Connector).Type = ConnectorSegmentType.Orthogonal;

    }




    protected override async Task OnInitializedAsync()

    {

        // Initialization logic here

    }


    protected override async Task OnAfterRenderAsync(bool firstRender)

    {

        if (firstRender)

        {

            var WorkspaceName = await PageStateService.getCurrentWorkspaceName();

            var VersionID = await PageStateService.getCurrentPBIVersion();

            var Version = await PowerBIService.GetPowerBIInstanceVersionByID(VersionID);

            var RootModel = await PowerBIService.DeserialiseJsonData(Version.JsonData);


            Workspace workspace = RootModel.SelectMany(x => x.Workspaces).FirstOrDefault(x => x.Name == WorkspaceName);


            CreateDiagramNodes(workspace);


            if (diagram != null)

            {

                //await diagram.DoLayout();

            }

        }

        else

        {

            if (diagram != null)

            {

                await diagram.DoLayout();

                StateHasChanged();

            }

        }

    }


    private void CreateDiagramNodes(Workspace workspace)

    {

        double offsetX = 100, offsetY = 100;

        int nodeIndex = 1; // Index to ensure unique node IDs


        Node rootNode = CreateNode(workspace.Name, ref offsetX, ref offsetY, $"{workspace.Name}_{nodeIndex++}");

        Nodes.Add(rootNode);

        Console.WriteLine($"Added root node: {rootNode.ID}");


        foreach (var report in workspace.Reports)

        {

            Node reportNode = CreateNode(report.Name, ref offsetX, ref offsetY, $"{workspace.Name}_Report_{nodeIndex++}");

            Nodes.Add(reportNode);

            connectors.Add(CreateConnector(rootNode.ID, reportNode.ID));

            Console.WriteLine($"Added report node: {reportNode.ID}");


            var datasetsinreports = workspace.Datasets.Where(x => report.DatasetId.Contains(x.Id)).ToList();

            foreach (var dataset in datasetsinreports)

            {

                Node datasetNode = CreateNode(dataset.Name, ref offsetX, ref offsetY, $"{workspace.Name}_Dataset_{nodeIndex++}");

                Nodes.Add(datasetNode);

                connectors.Add(CreateConnector(reportNode.ID, datasetNode.ID));

                Console.WriteLine($"Added dataset node: {datasetNode.ID}");


                foreach (var table in dataset.Tables)

                {

                    Node tableNode = CreateNode(table.Name, ref offsetX, ref offsetY, $"{workspace.Name}_Table_{nodeIndex++}");

                    Nodes.Add(tableNode);

                    connectors.Add(CreateConnector(datasetNode.ID, tableNode.ID));

                    Console.WriteLine($"Added table node: {tableNode.ID}");

                }


                foreach (var user in dataset.Users)

                {

                    Node userNode = CreateNode(user.EmailAddress, ref offsetX, ref offsetY, $"{workspace.Name}_User_{nodeIndex++}");

                    Nodes.Add(userNode);

                    connectors.Add(CreateConnector(datasetNode.ID, userNode.ID));

                    Console.WriteLine($"Added user node: {userNode.ID}");

                }

            }

        }

    }


    private Node CreateNode(string name, ref double offsetX, ref double offsetY, string nodeId)

    {

        return new Node

        {

            ID = nodeId,

            Annotations = new DiagramObjectCollection<ShapeAnnotation>() { new ShapeAnnotation() { Content = name } },

            Width = 200,

            Height = 60,

            BorderColor = "#357BD2",

            BorderWidth = 2,

            Style = new ShapeStyle { StrokeColor = "#357BD2" },

            Shape = new FlowShape() { Type = NodeShapes.Flow, Shape = NodeFlowShapes.Card },


        };

    }


    private Connector CreateConnector(string sourceId, string targetId)

    {

        return new Connector

        {

            SourceID = sourceId,

            TargetID = targetId,

            Type = ConnectorSegmentType.Orthogonal

        };

    }



1 Reply

SU Sumathi Uthayakumar Syncfusion Team February 2, 2024 07:29 AM UTC

Hi Gary,


We have validated the shared code snippet. In that code snippet, you attempted to add nodes with annotations and connectors using the Add method. If you want to add nodes with annotations at runtime, you need to use the AddDiagramElements method of the SfDiagramComponent. This method first measures the passed elements and then re-renders the complete diagram component in a single operation. Please refer to the documentation below regarding the AddDiagramElements method.


UG link: https://blazor.syncfusion.com/documentation/diagram/nodes/nodes#how-to-add-node-with-annotations-at-runtime


Note: In the shared sample, we have provided some delay to equalize the time it takes for you to fetch data from some services.


We noticed that you added an annotation in the NodeCreating event and also in the CreateNode method. You should only add the annotation to either the CreateNode method or the NodeCreating Event, and there is no need to add the same annotation in two different places. The NodeCreating event helps you define the default properties of the node. The node creation is triggered when the diagram is initialized. This method is invoked every time a node is created. In the NodeCreating event, you can customize the node properties.


We have prepared a simple sample and shared it for your reference.


Sample link: https://blazorplayground.syncfusion.com/VNLTjLtMKGaurYBL



Regards,


Loader.
Up arrow icon