Load family on grid intersections (CSharp)

Load family on grid intersections (CSharp)

dwightduronidavy
Enthusiast Enthusiast
223 Views
2 Replies
Message 1 of 3

Load family on grid intersections (CSharp)

dwightduronidavy
Enthusiast
Enthusiast

Dear all,

I have created an application macro to load a particular family on all grid intersection - but I keep getting errors. Any help would be very much appreciated.

MACRO:

using System;
using Autodesk.Revit.UI;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI.Selection;
using System.Collections.Generic;
using System.Linq;

namespace DDA_CSharpModule9
{
    [Autodesk.Revit.Attributes.Transaction(Autodesk.Revit.Attributes.TransactionMode.Manual)]
    [Autodesk.Revit.DB.Macros.AddInId("E08C2870-0CEF-46D9-BEAE-3ED8994591F0")]
    public partial class ThisApplication
    {
        private void Module_Startup(object sender, EventArgs e)
        {

        }

        private void Module_Shutdown(object sender, EventArgs e)
        {

        }

        #region Revit Macros generated code

        private void InternalStartup()
        {
            this.Startup += new System.EventHandler(Module_Startup);
            this.Shutdown += new System.EventHandler(Module_Shutdown);
        }

        #endregion

        public void LoadFamilyOnGridIntersections()
        {
            UIApplication uiApp = new UIApplication(this.Application);
            UIDocument uiDoc = uiApp.ActiveUIDocument;
            Document doc = uiDoc.Document;

            string familyPath = "C:\\Users\\dda\\XXXXXXXXXX\\Documents\\01. Revit Families\\Speciality\\TestIVCoordCube.rfa";
            Family family = null;

            try
            {
                // Load family into document if not already loaded
                using (Transaction loadFamilyTransaction = new Transaction(doc, "Load Family"))
                {
                    loadFamilyTransaction.Start();

                    if (!doc.LoadFamily(familyPath, out family))
                    {
                        TaskDialog.Show("Error", String.Format("Failed to load family: {0}", familyPath));
                        return;
                    }

                    loadFamilyTransaction.Commit();
                }

                if (family == null)
                {
                    TaskDialog.Show("Error""Family could not be loaded.");
                    return;
                }

                // Collect all gridline intersections
                FilteredElementCollector gridCollector = new FilteredElementCollector(doc).OfClass(typeof(Grid));
                List<Grid> grids = gridCollector.Cast<Grid>().ToList();
                List<XYZ> intersections = new List<XYZ>();

                for (int i = 0; i < grids.Count; i++)
                {
                    for (int j = i + 1; j < grids.Count; j++)
                    {
                        Curve curve1 = grids[i].Curve;
                        Curve curve2 = grids[j].Curve;

                        if (curve1 != null && curve2 != null)
                        {
                            SetComparisonResult result = curve1.Intersect(curve2, out IntersectionResultArray intersectionResults);

                            if (result == SetComparisonResult.Overlap && intersectionResults != null)
                            {
                                foreach (IntersectionResult intersection in intersectionResults)
                                {
                                    intersections.Add(intersection.XYZPoint);
                                }
                            }
                        }
                    }
                }

                // Place family instances at grid intersections
                using (Transaction placeFamilyTransaction = new Transaction(doc, "Place Family Instances"))
                {
                    placeFamilyTransaction.Start();

                    FamilySymbol familySymbol = doc.GetElement(family.GetFamilySymbolIds().First()) as FamilySymbol;

                    if (familySymbol != null && !familySymbol.IsActive)
                    {
                        familySymbol.Activate();
                        doc.Regenerate();
                    }

                    foreach (XYZ point in intersections)
                    {
                        doc.Create.NewFamilyInstance(point, familySymbol, Autodesk.Revit.DB.Structure.StructuralType.NonStructural);
                    }

                    placeFamilyTransaction.Commit();
                }

                TaskDialog.Show("Success", String.Format("Family '{0}' loaded and placed at all grid intersections.", family.Name));
            }
            catch (Exception ex)
            {
                TaskDialog.Show("Error", String.Format("An error occurred: {0}", ex.Message));
            }
        }
    }
}

0 Likes
Accepted solutions (1)
224 Views
2 Replies
Replies (2)
Message 2 of 3

dwightduronidavy
Enthusiast
Enthusiast
Accepted solution

Finally got it working!!!!
Herewith correct code:

Note:  Loaded from within Active Document

using System;
using Autodesk.Revit.UI;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI.Selection;
using System.Collections.Generic;
using System.Linq;

namespace DDA_CSharpModule9
{
    [Autodesk.Revit.Attributes.Transaction(Autodesk.Revit.Attributes.TransactionMode.Manual)]
    [Autodesk.Revit.DB.Macros.AddInId("E08C2870-0CEF-46D9-BEAE-3ED8994591F0")]
    public partial class ThisApplication
    {
        private void Module_Startup(object sender, EventArgs e) { }

        private void Module_Shutdown(object sender, EventArgs e) { }

        #region Revit Macros generated code
        private void InternalStartup()
        {
            this.Startup += new System.EventHandler(Module_Startup);
            this.Shutdown += new System.EventHandler(Module_Shutdown);
        }
        #endregion

        public void LoadFamilyOnGridIntersections()
        {
            UIApplication uiApp = new UIApplication(this.Application);
            UIDocument uiDoc = uiApp.ActiveUIDocument;
            Document doc = uiDoc.Document;

            // Get list of all family symbols in the active document
            FilteredElementCollector familyCollector = new FilteredElementCollector(doc)
                .OfClass(typeof(FamilySymbol));
            List<FamilySymbol> familySymbols = familyCollector.Cast<FamilySymbol>().ToList();

            // Find the "TestIVCoordCube" family symbol
            FamilySymbol targetFamilySymbol = familySymbols.FirstOrDefault(fs => fs.FamilyName == "TestIVCoordCube");
            if (targetFamilySymbol == null)
            {
                TaskDialog.Show("Error", String.Format("Could not find the 'TestIVCoordCube' family in the active document."));
                return;
            }

            // Activate the family symbol if not already active
            if (!targetFamilySymbol.IsActive)
            {
                using (Transaction activateTransaction = new Transaction(doc, "Activate Family Symbol"))
                {
                    activateTransaction.Start();
                    targetFamilySymbol.Activate();
                    doc.Regenerate();
                    activateTransaction.Commit();
                }
            }

            // Collect grid line intersections
            List<XYZ> intersections = GetGridIntersections(doc);

            try
            {
                // Place family instances transaction
                using (Transaction placeFamilyTransaction = new Transaction(doc, "Place Family Instances"))
                {
                    placeFamilyTransaction.Start();

                    // Place family instances at each intersection
                    foreach (XYZ point in intersections)
                    {
                        doc.Create.NewFamilyInstance(
                            point,
                            targetFamilySymbol,
                            Autodesk.Revit.DB.Structure.StructuralType.NonStructural
                        );
                    }

                    placeFamilyTransaction.Commit();
                }

                // Success message
                int instanceCount = intersections.Count;
                TaskDialog.Show("Success", String.Format("Family '{0}' placed at {1} grid intersections.", targetFamilySymbol.FamilyName, instanceCount));
            }
            catch (Exception ex)
            {
                // Error handling
                TaskDialog.Show("Error", String.Format("An error occurred: {0}", ex.Message));
                throw;
            }
        }

        private List<XYZ> GetGridIntersections(Document doc)
        {
            List<XYZ> intersections = new List<XYZ>();

            // Collect grid lines
            FilteredElementCollector gridCollector = new FilteredElementCollector(doc)
                .OfClass(typeof(Grid));
            List<Grid> grids = gridCollector.Cast<Grid>().ToList();

            // Find grid intersections
            for (int i = 0; i < grids.Count; i++)
            {
                for (int j = i + 1; j < grids.Count; j++)
                {
                    Curve curve1 = grids[i].Curve;
                    Curve curve2 = grids[j].Curve;

                    if (curve1 != null && curve2 != null)
                    {
                        IntersectionResultArray intersectionResults;
                        SetComparisonResult result = curve1.Intersect(curve2, out intersectionResults);

                        if (result == SetComparisonResult.Overlap && intersectionResults != null)
                        {
                            foreach (IntersectionResult intersection in intersectionResults)
                            {
                                intersections.Add(intersection.XYZPoint);
                            }
                        }
                    }
                }
            }

            return intersections;
        }
    }
}



0 Likes
Message 3 of 3

dwightduronidavy
Enthusiast
Enthusiast

Would love to know how to load family via File Path...
Thanks

0 Likes