Skip to content
TheChatArchiveThe Chat Archive
Geminigemini-2.5-flash· GoogleHugging Face LMArena Human Preference 140K

could you check my code in C# for tekla api

From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with Metallama-4-maverick-03-26-experimental’s answer.
  1. User

    could you check my code in C# for tekla api

  2. Gemini Assistant

    Absolutely! I'd be happy to help you review your C# code for the Tekla API.

    To give you the best feedback, please paste your code here using the code block formatting (csharp ... your code ... ) and also include the following information:

    1. What is the code supposed to do? (e.g., "It's supposed to create a specific type of beam," "It modifies UDAs of selected parts," "It exports geometry to a file.")
    2. What Tekla Structures version are you using? (e.g., 2023, 2022 SPX, 2021)
    3. Are you encountering any specific issues or errors? (e.g., "The code crashes," "It doesn't create the object correctly," "It's too slow," "I'm getting a NullReferenceException.")
    4. Is this a part of a larger application, a simple script, or a plugin?
    5. What have you tried so far to debug or solve the problem (if any)?

    When reviewing your code, I'll pay attention to (among other things):

    • Correctness and Logic: Does the code achieve its intended goal? Are there any logical flaws?
    • Tekla API Usage:
      • Are you correctly instantiating and using the Model object?
      • Are you using Model.CommitChanges() appropriately to save modifications to the model database?
      • Are you handling object selection and enumeration efficiently (e.g., using ModelObjectSelector, ModelObjectEnumerator)?
      • Are you correctly creating, modifying, and deleting Tekla objects (parts, bolts, welds, assemblies, etc.)?
      • Are you setting object properties (UDAs, phases, attributes) correctly?
      • Are you handling coordinate systems and transformations properly?
      • Are you disposing of IDisposable objects (like ModelObjectEnumerator) using using statements?
    • Error Handling: What happens if an object isn't found, or an API call fails? Are you using try-catch blocks where necessary?
    • Performance:
      • Is the code efficient, especially if it operates on many objects or large models?
      • Are you avoiding unnecessary database queries or recalculations?
      • Are you using transactions or batch operations if available and appropriate?
    • Readability and Maintainability:
      • Is the code well-structured, easy to understand, and commented where necessary?
      • Are variable and method names clear and descriptive?
      • Does it follow C# best practices?
    • Potential Edge Cases: Does the code handle unexpected inputs or model states gracefully?

    Looking forward to seeing your code!

  3. User

    using System; using Tekla.Structures.Model; using Tekla.Structures.Model.UI;

    public class RebarCopier { public static void Main() { Model model = new Model(); if (!model.GetConnectionStatus()) { Console.WriteLine("Tekla Structures is not connected."); return; }

        Picker picker = new Picker();
        Console.WriteLine("Select the source part:");
        Part sourcePart = picker.PickObject(Picker.PickObjectEnum.PICK_ONE_PART) as Part;
    
        Console.WriteLine("Select the target part:");
        Part targetPart = picker.PickObject(Picker.PickObjectEnum.PICK_ONE_PART) as Part;
    
        if (sourcePart == null || targetPart == null)
        {
            Console.WriteLine("Invalid selection.");
            return;
        }
    
        ModelObjectEnumerator rebarEnum = sourcePart.GetReinforcements();
    
        while (rebarEnum.MoveNext())
        {
            if (rebarEnum.Current is SingleRebar originalRebar)
            {
                if (originalRebar.Class == 100 || originalRebar.Class == 30)
                    continue;
    
                SingleRebar newRebar = new SingleRebar
                {
                    Father = targetPart,
                    Size = originalRebar.Size,
                    Grade = originalRebar.Grade,
                    Name = originalRebar.Name,
                    Class = originalRebar.Class,
                    NumberingSeries = originalRebar.NumberingSeries,
                    StartHook = originalRebar.StartHook,
                    EndHook = originalRebar.EndHook,
                    Polygon = originalRebar.Polygon,
                    OnPlaneOffsets = originalRebar.OnPlaneOffsets,
                    FromPlaneOffset = originalRebar.FromPlaneOffset
                };
    
                if (!newRebar.Insert())
                {
                    Console.WriteLine("Failed to insert SingleRebar.");
                }
            }
            else if (rebarEnum.Current is RebarGroup originalGroup)
            {
                if (originalGroup.Class == 100 || originalGroup.Class == 30)
                    continue;
    
                RebarGroup newGroup = new RebarGroup
                {
                    Father = targetPart,
                    Size = originalGroup.Size,
                    Grade = originalGroup.Grade,
                    Name = originalGroup.Name,
                    Class = originalGroup.Class,
                    NumberingSeries = originalGroup.NumberingSeries,
                    StartHook = originalGroup.StartHook,
                    EndHook = originalGroup.EndHook,
                    Polygons = originalGroup.Polygons,
                    OnPlaneOffsets = originalGroup.OnPlaneOffsets,
                    FromPlaneOffset = originalGroup.FromPlaneOffset,
                    SpacingType = originalGroup.SpacingType,
                    Spacings = originalGroup.Spacings
                };
    
                if (!newGroup.Insert())
                {
                    Console.WriteLine("Failed to insert RebarGroup.");
                }
            }
        }
    
        model.CommitChanges();
        Console.WriteLine("Rebars copied successfully.");
    }
    

    }

  4. Gemini Assistant

    This is a good start for a Tekla API script! You've correctly handled the Tekla connection, picking objects, iterating through reinforcements, and inserting new objects.

    However, there's a critical flaw in how you're copying the rebar geometry (Polygon/Polygons). The Polygon property of SingleRebar and Polygons of RebarGroup are defined in the local coordinate system of their Father part.

    If your sourcePart and targetPart are in different global locations or have different orientations, simply copying the Polygon/Polygons will result in the rebar appearing at the original global coordinates relative to the target part, not in the desired relative position.

    Let's break down the review and provide the necessary improvements.


    Code Review and Improvements

    1. Critical Issue: Rebar Geometry Transformation

    • Problem: As explained above, originalRebar.Polygon contains points relative to sourcePart's local coordinate system. When you assign it to newRebar.Polygon and set newRebar.Father = targetPart, Tekla will interpret these points relative to targetPart's local coordinate system. If sourcePart and targetPart are not identical in position and orientation, the rebar will be placed incorrectly.
    • Solution: You need to transform the rebar's polygon points from sourcePart's coordinate system to targetPart's coordinate system. This involves using Tekla.Structures.Geometry3d.Matrix and the CoordinateSystem of the parts.

    2. Best Practice: using statement for ModelObjectEnumerator

    • ModelObjectEnumerator implements IDisposable. It's good practice to wrap it in a using statement to ensure it's properly disposed of, releasing any unmanaged resources.

    3. Clarification: Rebar Class Filtering

    • You have if (originalRebar.Class == 100 || originalRebar.Class == 30) continue;.
      • Tekla's default classes are 1-100. Classes like 30 and 100 are typically used for concrete parts, not rebar. Rebar usually uses classes like 1, 2, 3... or other custom classes defined by the user.
      • Are you sure you want to skip rebar with these classes? If you're using these classes for rebar in your model, then it's fine. If not, this condition might be inadvertently skipping valid rebar. It's not an error, but something to be aware of.

    4. Error Handling & User Feedback

    • The Console.WriteLine("Failed to insert SingleRebar."); is good, but you might want to add more context, like which rebar failed or why (though the API doesn't always give detailed reasons for Insert() failure).

    5. Consider RebarSet (Newer Tekla Versions)

    • For Tekla Structures 2021 and newer, RebarSet is the preferred way to create and manage reinforcement, offering more control and flexibility. If you're working with a recent Tekla version, you might want to extend this script to handle RebarSet as well, or exclusively use RebarSet for new rebar creation if that's your standard. For simple copying, SingleRebar and RebarGroup still work fine.

    Corrected and Improved Code

    Here's the updated code with the geometry transformation and other improvements:

    using System;
    using System.Collections.Generic; // Required for List<Point>
    using Tekla.Structures.Model;
    using Tekla.Structures.Model.UI;
    using Tekla.Structures.Geometry3d; // Required for Point, Matrix, CoordinateSystem
    
    public class RebarCopier
    {
        public static void Main()
        {
            Model model = new Model();
            if (!model.GetConnectionStatus())
            {
                Console.WriteLine("Tekla Structures is not connected.");
                return;
            }
    
            Picker picker = new Picker();
            Console.WriteLine("Select the source part:");
            Part sourcePart = picker.PickObject(Picker.PickObjectEnum.PICK_ONE_PART) as Part;
    
            Console.WriteLine("Select the target part:");
            Part targetPart = picker.PickObject(Picker.PickObjectEnum.PICK_ONE_PART) as Part;
    
            if (sourcePart == null || targetPart == null)
            {
                Console.WriteLine("Invalid selection. Please select two parts.");
                return;
            }
            
            // Get the coordinate systems of the source and target parts
            CoordinateSystem sourceCS = sourcePart.GetLocalCoordinateSystem();
            CoordinateSystem targetCS = targetPart.GetLocalCoordinateSystem();
    
            // Calculate the transformation matrix needed to move points from sourceCS to targetCS
            // 1. Transform from sourceCS local to global
            // 2. Transform from global to targetCS local
            Matrix sourceToGlobal = new Matrix(sourceCS); // Creates matrix from CS
            Matrix globalToTarget = targetCS.Inverse();   // Inverse of targetCS transformation
    
            Matrix transformationMatrix = sourceToGlobal.Multiply(globalToTarget);
    
            int copiedCount = 0;
            int failedCount = 0;
    
            // Use a 'using' statement for ModelObjectEnumerator to ensure proper disposal
            using (ModelObjectEnumerator rebarEnum = sourcePart.GetReinforcements())
            {
                while (rebarEnum.MoveNext())
                {
                    if (rebarEnum.Current is SingleRebar originalRebar)
                    {
                        // Review this class filter if rebar uses these classes in your model
                        if (originalRebar.Class == 100 || originalRebar.Class == 30)
                        {
                            Console.WriteLine($"Skipping SingleRebar with Class {originalRebar.Class}.");
                            continue;
                        }
    
                        SingleRebar newRebar = new SingleRebar
                        {
                            Father = targetPart,
                            Size = originalRebar.Size,
                            Grade = originalRebar.Grade,
                            Name = originalRebar.Name,
                            Class = originalRebar.Class,
                            NumberingSeries = originalRebar.NumberingSeries,
                            StartHook = originalRebar.StartHook,
                            EndHook = originalRebar.EndHook,
                            OnPlaneOffsets = originalRebar.OnPlaneOffsets,
                            FromPlaneOffset = originalRebar.FromPlaneOffset,
                            RadiusValues = originalRebar.RadiusValues // Also copy radius values for hooks if present
                        };
    
                        // --- TRANSFORM POLYGON POINTS ---
                        List<Point> transformedPolygon = new List<Point>();
                        foreach (Point p in originalRebar.Polygon)
                        {
                            transformedPolygon.Add(transformationMatrix.Transform(p));
                        }
                        newRebar.Polygon = transformedPolygon;
    
                        if (newRebar.Insert())
                        {
                            copiedCount++;
                        }
                        else
                        {
                            Console.WriteLine($"Failed to insert SingleRebar (ID: {originalRebar.Identifier.ID}).");
                            failedCount++;
                        }
                    }
                    else if (rebarEnum.Current is RebarGroup originalGroup)
                    {
                        // Review this class filter if rebar uses these classes in your model
                        if (originalGroup.Class == 100 || originalGroup.Class == 30)
                        {
                            Console.WriteLine($"Skipping RebarGroup with Class {originalGroup.Class}.");
                            continue;
                        }
    
                        RebarGroup newGroup = new RebarGroup
                        {
                            Father = targetPart,
                            Size = originalGroup.Size,
                            Grade = originalGroup.Grade,
                            Name = originalGroup.Name,
                            Class = originalGroup.Class,
                            NumberingSeries = originalGroup.NumberingSeries,
                            StartHook = originalGroup.StartHook,
                            EndHook = originalGroup.EndHook,
                            OnPlaneOffsets = originalGroup.OnPlaneOffsets,
                            FromPlaneOffset = originalGroup.FromPlaneOffset,
                            SpacingType = originalGroup.SpacingType,
                            Spacings = originalGroup.Spacings,
                            RadiusValues = originalGroup.RadiusValues // Also copy radius values for hooks if present
                        };
    
                        // --- TRANSFORM POLYGONS POINTS ---
                        List<List<Point>> transformedPolygons = new List<List<Point>>();
                        foreach (List<Point> polygon in originalGroup.Polygons)
                        {
                            List<Point> transformedSinglePolygon = new List<Point>();
                            foreach (Point p in polygon)
                            {
                                transformedSinglePolygon.Add(transformationMatrix.Transform(p));
                            }
                            transformedPolygons.Add(transformedSinglePolygon);
                        }
                        newGroup.Polygons = transformedPolygons;
    
                        if (newGroup.Insert())
                        {
                            copiedCount++;
                        }
                        else
                        {
                            Console.WriteLine($"Failed to insert RebarGroup (ID: {originalGroup.Identifier.ID}).");
                            failedCount++;
                        }
                    }
                    // You might also want to handle RebarSet if you're on TS2021+
                    // else if (rebarEnum.Current is RebarSet originalRebarSet)
                    // {
                    //     // ... logic to copy RebarSet ...
                    // }
                }
            }
    
            model.CommitChanges();
            Console.WriteLine($"Rebar copying complete. {copiedCount} rebars copied, {failedCount} failed.");
        }
    }
    
    

    Explanation of Transformation Logic

    1. sourcePart.GetLocalCoordinateSystem(): This gives you the CoordinateSystem object that defines the local axes and origin of the sourcePart relative to the model's global origin.
    2. targetPart.GetLocalCoordinateSystem(): Same for the targetPart.
    3. Matrix sourceToGlobal = new Matrix(sourceCS);: This creates a transformation matrix that, when applied to a point defined in sourceCS, will convert it to a point in the global coordinate system.
    4. Matrix globalToTarget = targetCS.Inverse();: targetCS.Inverse() gives you the transformation matrix that converts a point from the global coordinate system to the local coordinate system of targetPart.
    5. Matrix transformationMatrix = sourceToGlobal.Multiply(globalToTarget);: This is the crucial step. We compose the two transformations:
      • First, take a point from the sourcePart's local system (originalRebar.Polygon points are in this system).
      • Transform it to the global system using sourceToGlobal.
      • Then, transform that global point to the targetPart's local system using globalToTarget.
      • The resulting transformationMatrix can directly convert Polygon points from the sourcePart's local system to the targetPart's local system.
    6. transformedPolygon.Add(transformationMatrix.Transform(p));: Inside the loops, each point p from the originalRebar.Polygon (or originalGroup.Polygons) is transformed using this transformationMatrix before being assigned to the new rebar's polygon property.

    With these changes, your rebar copier should now correctly position the reinforcement relative to the targetPart, regardless of its global location or orientation compared to the sourcePart.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.