// Get the active document from UI
Document doc = UIDoc.Document;
// Get the first open view's ID to work in the context of an active view
ElementId activeViewId = UIDoc.GetOpenUIViews()[0].ViewId;
View activeView = doc.GetElement(activeViewId) as View;
// Collect all Railing in the active view
List<Railing> railingsInView = new FilteredElementCollector(doc, activeViewId)
.OfClass(typeof(Railing))
.Cast<Railing>()
.ToList();
Logger.AppendLine($"Found {railingsInView.Count} railing(s) in the active view.");
foreach (Railing railing in railingsInView)
{
Logger.AppendLine($"\n--- Railing: {railing.Id.IntegerValue} ---");
// Get the dependent elements (e.g., balusters, top rails, handrails)
ICollection<ElementId> dependentElementIds = railing.GetDependentElements(null);
foreach (ElementId dependentId in dependentElementIds)
{
Element dependentElement = doc.GetElement(dependentId);
// --- TopRail ---
if (dependentElement is TopRail topRail)
{
TopRailType topRailType = doc.GetElement(topRail.GetTypeId()) as TopRailType;
if (topRailType != null)
{
Material material = GetMaterialFromParameters(doc, topRailType);
Logger.AppendLine($"Top Rail Material: {(material != null ? material.Name : "null")}");
}
}
// --- HandRail ---
else if (dependentElement is HandRail handRail)
{
HandRailType handRailType = doc.GetElement(handRail.GetTypeId()) as HandRailType;
if (handRailType != null)
{
Material material = GetMaterialFromParameters(doc, handRailType);
Logger.AppendLine($"Hand Rail Material: {(material != null ? material.Name : "null")}");
}
}
// --- Baluster (FamilyInstance) ---
else if (dependentElement is FamilyInstance baluster)
{
Material material = GetMaterialFromParameters(doc, baluster);
Logger.AppendLine($"Baluster Material: {(material != null ? material.Name : "null")}");
}
}
}
// Helper method to get material from parameters or category
Material GetMaterialFromParameters(Document doc, Element element)
{
foreach (Parameter param in element.Parameters)
{
Definition def = param.Definition;
if (param.StorageType == StorageType.ElementId &&
def.GetDataType() == SpecTypeId.Reference.Material)
{
ElementId materialId = param.AsElementId();
if (materialId != ElementId.InvalidElementId)
{
return doc.GetElement(materialId) as Material;
}
}
}
// Fallback: try getting from Category
return element.Category != null ? element.Category.Material : null;
}