public Result Execute(
ExternalCommandData commandData,
ref string message,
ElementSet elements)
{
UIApplication uiapp = commandData.Application;
UIDocument uidoc = uiapp.ActiveUIDocument;
Document doc = uidoc.Document;
Selection sel = uidoc.Selection;
Element sel_elem = null;
ElementType sel_elem_type = null;
foreach (ElementId eId in sel.GetElementIds())
{
sel_elem = doc.GetElement(eId);
var type_id = sel_elem.GetTypeId();
sel_elem_type = doc.GetElement(type_id) as ElementType;
break;
}
FamilyInstance beam = sel_elem as FamilyInstance;
if ((beam == null) || (beam.StructuralType != Autodesk.Revit.DB.Structure.StructuralType.Beam))
{
message = "Please select exactly one beam element.";
return Result.Failed;
}
LocationCurve lc = beam.Location as LocationCurve;
Line line = lc.Curve as Line;
if (null == line)
{
message = "Unable to retrieve beam location line.";
return Result.Failed;
}
ViewFamilyType vft
= new FilteredElementCollector(doc)
.OfClass(typeof(ViewFamilyType))
.Cast<ViewFamilyType>()
.FirstOrDefault<ViewFamilyType>(x =>
ViewFamily.Detail == x.ViewFamily);
XYZ firstPoint = line.GetEndPoint(0);
XYZ secondPoint = line.GetEndPoint(1);
XYZ line_direction = secondPoint - firstPoint;
double minZ = firstPoint.Z;
double maxZ = secondPoint.Z;
double width = line_direction.GetLength();
double offset = 0.1 * width;
XYZ midpoint = (firstPoint + secondPoint) / 2;
XYZ minSecionBox; XYZ maxSectionBox;
line_direction = line_direction.Normalize();
XYZ up_direction = XYZ.BasisZ;
XYZ view_direction = line_direction.CrossProduct(up_direction).Normalize();
if (minZ != maxZ)
{
up_direction = view_direction.CrossProduct(line_direction).Normalize();
}
Transform t = Transform.Identity;
t.Origin = midpoint;
t.BasisX = line_direction;
t.BasisY = up_direction;
t.BasisZ = view_direction;
minSecionBox = new XYZ(-width / 2 - offset, -offset, -offset);
maxSectionBox = new XYZ(width / 2 + offset, offset, 0);
BoundingBoxXYZ sectionBox = new BoundingBoxXYZ();
sectionBox.Transform = t;
sectionBox.Min = minSecionBox;
sectionBox.Max = maxSectionBox;
ViewSection section = null;
using (Transaction tx = new Transaction(doc))
{
tx.Start("Create Beam Section View");
section = ViewSection.CreateDetail(doc, vft.Id, sectionBox);
tx.Commit();
}
return Result.Succeeded;
}