public static void ExecuteSubTransaction(Document document, Action action)
        {
            using (var subTransaction = new SubTransaction(document))
            {
                try
                {
                    if (subTransaction.Start() == TransactionStatus.Started)
                    {
                        action?.Invoke();
                    }

                    if (subTransaction.Commit() != TransactionStatus.Committed)
                    {
                        subTransaction.RollBack();
                    }
                }
                catch (Exception)
                {
                    if (subTransaction.HasStarted())
                    {
                        subTransaction.RollBack();
                    }
                    throw;
                }
            }
        }
Example #2
0
 public static GCAdaptiveComponent CreateComponentByPoints(GCRevitDocument doc, FamilySymbol sym, List <XYZ> locPts)
 {
     using (var subTrans = new SubTransaction(doc.Document)) {
         if (TransactionStatus.Started == subTrans.Start())
         {
             var inst = AdaptiveComponentInstanceUtils.CreateAdaptiveComponentInstance(doc.Document, sym);
             var comp = GCAdaptiveComponent.CreateGCAdaptiveComponent(inst);
             var ids  = AdaptiveComponentInstanceUtils.GetInstancePlacementPointElementRefIds(inst);
             if (ids.Count == locPts.Count)
             {
                 for (var i = 0; i < ids.Count; i++)
                 {
                     var pt    = doc.Document.GetElement(ids[i]);
                     var trans = locPts[i] - (pt.Location as LocationPoint).Point;
                     comp.MovePointById(ids[i], trans);
                 }
                 subTrans.Commit();
                 return(comp);
             }
             else
             {
                 subTrans.RollBack();
                 throw new GCElementCreationException("The given point count does not match the instance point count");
             }
         }
         else
         {
             throw new GCElementCreationException("Could not start subtransaction for adaptive component creation");
         }
     }
 }
        public static TResult InvokeSub <TResult>(this Document doc, Func <SubTransaction, TResult> func)
        {
            using (var tr = new SubTransaction(doc))
            {
                tr.Start();

                var result = func(tr);

                var status = tr.GetStatus();
                switch (status)
                {
                case TransactionStatus.Started:
                    tr.Commit();
                    return(result);

                case TransactionStatus.Committed:
                case TransactionStatus.RolledBack:
                    return(result);

                case TransactionStatus.Error:
                    tr.RollBack();
                    return(result);

                default:
                    return(result);
                }
            }
        }
        public static void InvokeSub(this Document doc, Action <SubTransaction> action)
        {
            using (var tr = new SubTransaction(doc))
            {
                tr.Start();

                action(tr);

                var status = tr.GetStatus();
                switch (status)
                {
                case TransactionStatus.Started:
                    tr.Commit();
                    return;

                case TransactionStatus.Committed:
                case TransactionStatus.RolledBack:
                    break;

                case TransactionStatus.Error:
                    tr.RollBack();
                    return;

                default:
                    return;
                }
            }
        }
Example #5
0
        /// <summary>
        /// Get the view crop element and crop region curves
        /// </summary>
        /// <param name="view"></param>
        /// <returns></returns>
        internal static ViewCrop GetViewCrop(Autodesk.Revit.DB.View view)
        {
            var doc = DocumentManager.Instance.CurrentDBDocument;

            TransactionManager.Instance.EnsureInTransaction(doc);

            ViewCrop viewCrop;

            using (SubTransaction tGroup = new SubTransaction(doc))
            {
                tGroup.Start();

                using (SubTransaction t1 = new SubTransaction(doc))
                {
                    // Deactivate crop box
                    t1.Start();
                    view.CropBoxVisible = false;
                    t1.Commit();
                    doc.Regenerate();

                    // Get all visible elements, which does not include the crop box
                    FilteredElementCollector collector  = new FilteredElementCollector(doc, view.Id);
                    ICollection <ElementId>  shownElems = collector.ToElementIds();

                    // Activate the crop box
                    t1.Start();
                    view.CropBoxVisible = true;
                    t1.Commit();
                    doc.Regenerate();

                    // Get all visible elements, excluding everything but the crop box
                    collector = new FilteredElementCollector(doc, view.Id);
                    collector.Excluding(shownElems);

                    viewCrop.cropElement = collector.FirstElement();
                    viewCrop.cropRegion  = view.GetCropRegionShapeManager().GetCropShape().First();
                }
                tGroup.RollBack();
            }

            TransactionManager.Instance.TransactionTaskDone();

            return(viewCrop);
        }
        /// <summary>
        /// Initialize an AdaptiveComponent element
        /// </summary>
        /// <param name="pts">Points to use as reference</param>
        /// <param name="fs">FamilySymbol to place</param>
        private void InitAdaptiveComponent(Point[] pts, FamilySymbol fs)
        {
            // if the family instance is present in trace...
            var oldFam =
                ElementBinder.GetElementFromTrace <Autodesk.Revit.DB.FamilyInstance>(Document);

            // just mutate it...
            if (oldFam != null)
            {
                InternalSetFamilyInstance(oldFam);
                if (fs.InternalFamilySymbol.Id != oldFam.Symbol.Id)
                {
                    InternalSetFamilySymbol(fs);
                }
                InternalSetPositions(pts.ToXyzs());

                return;
            }

            // otherwise create a new family instance...
            TransactionManager.Instance.EnsureInTransaction(Document);

            using (Autodesk.Revit.DB.SubTransaction st = new SubTransaction(Document))
            {
                try
                {
                    st.Start();
                    var fam = AdaptiveComponentInstanceUtils.CreateAdaptiveComponentInstance(Element.Document, fs.InternalFamilySymbol);
                    InternalSetFamilyInstance(fam);
                    InternalSetPositions(pts.ToXyzs());
                    st.Commit();
                }
                catch (Exception ex)
                {
                    st.RollBack();
                    throw new ArgumentException(Revit.Properties.Resources.Adaptive_Component_Creation_Failed + ex.Message);
                }
            }

            TransactionManager.Instance.TransactionTaskDone();

            // remember this value
            ElementBinder.SetElementForTrace(this.InternalElement);
        }
Example #7
0
        /// <summary>
        /// Initialize an AdaptiveComponent element
        /// </summary>
        /// <param name="uvParams">Parameters to use as reference</param>
        /// <param name="f">Face to use as reference</param>
        /// <param name="ft">familyType to place</param>
        private void InitAdaptiveComponent(double[][] uvParams, ElementFaceReference f, FamilyType ft)
        {
            // if the family instance is present in trace...
            var oldFam =
                ElementBinder.GetElementFromTrace <Autodesk.Revit.DB.FamilyInstance>(Document);

            // just mutate it...
            if (oldFam != null)
            {
                InternalSetFamilyInstance(oldFam);
                if (ft.InternalFamilySymbol.Id != oldFam.Symbol.Id)
                {
                    InternalSetFamilySymbol(ft);
                }
                InternalSetUvsAndFace(uvParams.ToUvs(), f.InternalReference);

                return;
            }

            // otherwise create a new family instance...
            TransactionManager.Instance.EnsureInTransaction(Document);

            using (Autodesk.Revit.DB.SubTransaction st = new SubTransaction(Document))
            {
                try
                {
                    st.Start();
                    var fam = AdaptiveComponentInstanceUtils.CreateAdaptiveComponentInstance(Element.Document, ft.InternalFamilySymbol);
                    InternalSetFamilyInstance(fam);
                    InternalSetUvsAndFace(uvParams.ToUvs(), f.InternalReference);
                    st.Commit();
                }
                catch (Exception ex)
                {
                    st.RollBack();
                    throw new ArgumentException(Revit.Properties.Resources.Adaptive_Component_Creation_Failed + ex.Message);
                }
            }

            TransactionManager.Instance.TransactionTaskDone();
            ElementBinder.SetElementForTrace(InternalElement);
        }
Example #8
0
        public TransactionStatus RollBack()
        {
            if (!HasStarted())
            {
                throw new InvalidOperationException("AdaptiveTransaction is not started.");
            }

            using (this)
            {
                if (transaction is object)
                {
                    return(transaction.RollBack());
                }
                if (subTransaction is object)
                {
                    return(subTransaction.RollBack());
                }
                return(TransactionStatus.Uninitialized);
            }
        }
        public void Execute(UpdaterData data)
        {
            Document Doc = data.GetDocument();

            using (SubTransaction str = new SubTransaction(Doc))
            {
                try
                {
                    var addedElementIds    = data.GetAddedElementIds();
                    var modifiedElementIds = data.GetModifiedElementIds();
                    var deletedElementIds  = data.GetDeletedElementIds();

                    // Your Code Goes Here
                }
                catch
                {
                    str.RollBack();
                }
            }
        }
Example #10
0
        /// <summary>
        /// Create a wall, append a node to tree view
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void createWallbutton_Click(object sender, EventArgs e)
        {
            // a sub-transaction is not necessary in this case
            // it is used for illustration purposes only
            using (SubTransaction subTransaction = new SubTransaction(m_document))
            {
                // if not handled explicitly, the sub-transaction will be rolled back when leaving this block
                try
                {
                    if (subTransaction.Start() == TransactionStatus.Started)
                    {
                        using (CreateWallForm createWallForm = new CreateWallForm(m_commandData))
                        {
                            createWallForm.ShowDialog();
                            if (DialogResult.OK == createWallForm.DialogResult)
                            {
                                updateModel(true);  // immediately update the view to see the changes

                                if (subTransaction.Commit() == TransactionStatus.Committed)
                                {
                                    m_lastCreatedWall = createWallForm.CreatedWall;
                                    AddNode(OperationType.ObjectModification, "Created wall " + m_lastCreatedWall.Id.IntegerValue.ToString());
                                    UpdateButtonsStatus();
                                    return;
                                }
                            }
                            else
                            {
                                subTransaction.RollBack();
                                return;
                            }
                        }
                    }
                }
                catch (System.Exception ex)
                {
                    TaskDialog.Show("Revit", "Exception when creating a wall: " + ex.Message);
                }
            }
            TaskDialog.Show("Revit", "Creating wall failed");
        }
Example #11
0
        public static ModelLine GetSpanDirection(this Floor floor)
        {
            var doc = floor.Document;

            using (var tran = new SubTransaction(doc))
            {
                tran.Start();
                var relatedElementIds = doc.Delete(floor.Id);
                tran.RollBack();

                foreach (var id in relatedElementIds)
                {
                    var element = doc.GetElement(id);

                    if (element is ModelLine && element.Name.Contains("Span"))
                    {
                        return(element as ModelLine);
                    }
                }
            }

            return(null);
        }
Example #12
0
        private IList <Plane> CreatePlaneBound2(Document doc, XYZ startingPoint, double mainPosition, double secondPosition, double mainDirectionAmount, double secondDirectionAmount, XYZ mainDirection, XYZ secondDirection)
        {
            IList <Plane> currentPlanes = new List <Plane>();

            double xMult = (secondPosition * secondDirectionAmount);
            double yMult = (mainPosition * mainDirectionAmount);

            using (SubTransaction st = new SubTransaction(doc))
            {
                st.Start();
                XYZ firstPoint  = startingPoint + secondDirection.Multiply(xMult) + mainDirection.Multiply(yMult);
                XYZ secondPoint = firstPoint + mainDirection.Multiply(mainDirectionAmount);
                XYZ thirdPoint  = new XYZ(0, 0, 1);

                XYZ midp1 = Utils.GetPoint.getMidPoint(firstPoint, secondPoint);

                Plane currentPlane = doc.Create.NewReferencePlane(secondPoint, firstPoint, thirdPoint, doc.ActiveView).GetPlane();

                XYZ firstPoint2  = firstPoint + secondDirection.Multiply(secondDirectionAmount - Utils.ConvertM.cmToFeet(2));
                XYZ secondPoint2 = firstPoint2 + mainDirection.Multiply(mainDirectionAmount);

                XYZ midp2 = Utils.GetPoint.getMidPoint(firstPoint2, secondPoint2);

                Plane currentPlane2 = doc.Create.NewReferencePlane(firstPoint2, secondPoint2, thirdPoint, doc.ActiveView).GetPlane();

                currentPlanes.Add(currentPlane);
                currentPlanes.Add(currentPlane2);
                st.RollBack();
            }

            //normalPoint.Activate();
            //doc.Create.NewFamilyInstance(midp1 + currentPlane.Normal, normalPoint, Autodesk.Revit.DB.Structure.StructuralType.NonStructural);
            //doc.Create.NewFamilyInstance(midp2 + currentPlane2.Normal, normalPoint, Autodesk.Revit.DB.Structure.StructuralType.NonStructural);

            return(currentPlanes);
        }
Example #13
0
        /// <summary>
        /// Some preparation and check before creating room.
        /// </summary>
        /// <param name="curPhase">Current phase used to create room, all rooms will be created in this phase.</param>
        /// <returns>Number indicates how many new rooms were created.</returns>
        private int RoomCreationStart()
        {
            int nNewRoomsSize = 0;
            // transaction is used to cancel room creation when exception occurs
            SubTransaction myTransaction = new SubTransaction(m_document);
            try
            {
                // Preparation before room creation starts
                Phase curPhase = null;
                if (!RoomCreationPreparation(ref curPhase))
                {
                    return 0;
                }

                // get all existing rooms which have mapped to spreadsheet rooms.
                // we should skip the creation for those spreadsheet rooms which have been mapped by Revit rooms.
                Dictionary<int, string> existingRooms = new Dictionary<int, string>();
                foreach (Room room in m_roomData.Rooms)
                {
                    Parameter sharedParameter = room.get_Parameter(RoomsData.SharedParam);
                    if (null != sharedParameter && false == String.IsNullOrEmpty(sharedParameter.AsString()))
                    {
                        existingRooms.Add(room.Id.IntegerValue, sharedParameter.AsString());
                    }
                }

                #region Rooms Creation and Set
                myTransaction.Start();
                // create rooms with spread sheet based rooms data
                for (int row = 0; row < m_spreadRoomsTable.Rows.Count; row++)
                {
                    // get the ID column value and use it to check whether this spreadsheet room is mapped by Revit room.
                    String externaId = m_spreadRoomsTable.Rows[row][RoomsData.RoomID].ToString();
                    if (existingRooms.ContainsValue(externaId))
                    {
                        // skip the spreadsheet room creation if it's mapped by Revit room
                        continue;
                    }

                    // create rooms in specified phase, but without placing them.
                    Room newRoom = m_document.Create.NewRoom(curPhase);
                    if (null == newRoom)
                    {
                        // abort the room creation and pop up failure message
                        myTransaction.RollBack();

                        MyMessageBox("Create room failed.", MessageBoxIcon.Warning);
                        return 0;
                    }

                    // set the shared parameter's value of Revit room
                    Parameter sharedParam = newRoom.get_Parameter(RoomsData.SharedParam);
                    if (null == sharedParam)
                    {
                        // abort the room creation and pop up failure message
                        myTransaction.RollBack();
                        MyMessageBox("Failed to get shared parameter, please try again.", MessageBoxIcon.Warning);
                        return 0;
                    }
                    else
                    {
                        sharedParam.Set(externaId);
                    }

                    // Update this new room with values of spreadsheet
                    UpdateNewRoom(newRoom, row);

                    // remember how many new rooms were created, based on spread sheet data
                    nNewRoomsSize++;
                }

                // end this transaction if create all rooms successfully.
                myTransaction.Commit();
                #endregion
            }
            catch (Exception ex)
            {
                // cancel this time transaction when exception occurs
                if (myTransaction.HasStarted())
                {
                    myTransaction.RollBack();
                }

                MyMessageBox(ex.Message, MessageBoxIcon.Warning);
                return 0;
            }

            // output unplaced rooms creation message
            String strMessage = string.Empty;
            int nSkippedRooms = m_spreadRoomsTable.Rows.Count - nNewRoomsSize;
            if (nSkippedRooms > 0)
            {
                strMessage = string.Format("{0} unplaced {1} created successfully.\r\n{2} skipped, {3}",
                     nNewRoomsSize,
                     (nNewRoomsSize > 1) ? ("rooms were") : ("room was"),
                     nSkippedRooms.ToString() + ((nSkippedRooms > 1) ? (" were") : (" was")),
                     (nSkippedRooms > 1) ? ("because they were already mapped by Revit rooms.") :
                     ("because it was already mapped by Revit rooms."));
            }
            else
            {
                strMessage = string.Format("{0} unplaced {1} created successfully.",
                     nNewRoomsSize,
                     (nNewRoomsSize > 1) ? ("rooms were") : ("room was"));
            }

            // output creation message
            MyMessageBox(strMessage, MessageBoxIcon.Information);
            return nNewRoomsSize;
        }
Example #14
0
        private void ModifyObjects(List<RevitObject> existingObjects, List<ElementId> existingElems, Document doc, Guid uniqueId, bool profileWarning, string nickName, int runId)
        {
            // Create new Revit objects.
            //List<LyrebirdId> newUniqueIds = new List<LyrebirdId>();

            // Determine what kind of object we're creating.
            RevitObject ro = existingObjects[0];


            #region Normal Origin based FamilyInstance
            // Modify origin based family instances
            if (ro.Origin != null)
            {
                // Find the FamilySymbol
                FamilySymbol symbol = FindFamilySymbol(ro.FamilyName, ro.TypeName, doc);

                LevelType lt = FindLevelType(ro.TypeName, doc);

                GridType gt = FindGridType(ro.TypeName, doc);

                if (symbol != null || lt != null)
                {
                    // Get the hosting ID from the family.
                    Family fam = null;
                    Parameter hostParam = null;
                    int hostBehavior = 0;

                    try
                    {
                        fam = symbol.Family;
                        hostParam = fam.get_Parameter(BuiltInParameter.FAMILY_HOSTING_BEHAVIOR);
                        hostBehavior = hostParam.AsInteger();
                    }
                    catch{}

                    //FamilyInstance existingInstance = doc.GetElement(existingElems[0]) as FamilyInstance;
                    
                    using (Transaction t = new Transaction(doc, "Lyrebird Modify Objects"))
                    {
                        t.Start();
                        try
                        {
                            Schema instanceSchema = null;
                            try
                            {
                                instanceSchema = Schema.Lookup(instanceSchemaGUID);
                            }
                            catch (Exception ex)
                            {
                                Debug.WriteLine(ex.Message);
                            }
                            if (instanceSchema == null)
                            {
                                SchemaBuilder sb = new SchemaBuilder(instanceSchemaGUID);
                                sb.SetWriteAccessLevel(AccessLevel.Vendor);
                                sb.SetReadAccessLevel(AccessLevel.Public);
                                sb.SetVendorId("LMNA");

                                // Create the field to store the data in the family
                                FieldBuilder guidFB = sb.AddSimpleField("InstanceID", typeof(string));
                                guidFB.SetDocumentation("Component instance GUID from Grasshopper");
                                // Create a filed to store the run number
                                FieldBuilder runIDFB = sb.AddSimpleField("RunID", typeof(int));
                                runIDFB.SetDocumentation("RunID for when multiple runs are created from the same data");
                                // Create a field to store the GH component nickname.
                                FieldBuilder nickNameFB = sb.AddSimpleField("NickName", typeof(string));
                                nickNameFB.SetDocumentation("Component NickName from Grasshopper");

                                sb.SetSchemaName("LMNAInstanceGUID");
                                instanceSchema = sb.Finish();
                            }

                            FamilyInstance fi = null;
                            XYZ origin = XYZ.Zero;

                            if (lt != null)
                            {
                                for (int i = 0; i < existingObjects.Count; i++)
                                {
                                    RevitObject obj = existingObjects[i];
                                    Level lvl = doc.GetElement(existingElems[i]) as Level;

                                    if (lvl.ProjectElevation != (UnitUtils.ConvertToInternalUnits(obj.Origin.Z, lengthDUT)))
                                    {
                                        double offset = lvl.Elevation - lvl.ProjectElevation;
                                        lvl.Elevation = (UnitUtils.ConvertToInternalUnits(obj.Origin.Z + offset, lengthDUT));
                                    }

                                    SetParameters(lvl, obj.Parameters, doc);
                                }
                            }
                            else if (hostBehavior == 0)
                            {

                                for (int i = 0; i < existingObjects.Count; i++)
                                {
                                    RevitObject obj = existingObjects[i];
                                    fi = doc.GetElement(existingElems[i]) as FamilyInstance;

                                    // Change the family and symbol if necessary
                                    if (fi != null && (fi.Symbol.Family.Name != symbol.Family.Name || fi.Symbol.Name != symbol.Name))
                                    {
                                        try
                                        {
                                            fi.Symbol = symbol;
                                        }
                                        catch (Exception ex)
                                        {
                                            Debug.WriteLine(ex.Message);
                                        }
                                    }

                                    try
                                    {
                                        // Move family
                                        origin = new XYZ(UnitUtils.ConvertToInternalUnits(obj.Origin.X, lengthDUT), UnitUtils.ConvertToInternalUnits(obj.Origin.Y, lengthDUT), UnitUtils.ConvertToInternalUnits(obj.Origin.Z, lengthDUT));
                                        if (fi != null)
                                        {
                                            LocationPoint lp = fi.Location as LocationPoint;
                                            if (lp != null)
                                            {
                                                XYZ oldLoc = lp.Point;
                                                XYZ translation = origin.Subtract(oldLoc);
                                                ElementTransformUtils.MoveElement(doc, fi.Id, translation);
                                            }
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        TaskDialog.Show("Error", ex.Message);
                                    }

                                    // Rotate
                                    if (obj.Orientation != null)
                                    {
                                        if (Math.Round(Math.Abs(obj.Orientation.Z - 0), 10) < double.Epsilon)
                                        {
                                            XYZ orientation = fi.FacingOrientation;
                                            orientation = orientation.Multiply(-1);
                                            XYZ incomingOrientation = new XYZ(obj.Orientation.X, obj.Orientation.Y, obj.Orientation.Z);
                                            XYZ normalVector = new XYZ(0, -1, 0);

                                            double currentAngle = 0;
                                            if (orientation.X < 0 && orientation.Y < 0)
                                            {
                                                currentAngle = (2 * Math.PI) - normalVector.AngleTo(orientation);
                                            }
                                            else if (orientation.Y == 0 && orientation.X < 0)
                                            {
                                                currentAngle = 1.5 * Math.PI;
                                            }
                                            else if (orientation.X < 0)
                                            {
                                                currentAngle = (Math.PI - normalVector.AngleTo(orientation)) + Math.PI;
                                            }
                                            else
                                            {
                                                currentAngle = normalVector.AngleTo(orientation);
                                            }

                                            double incomingAngle = 0;
                                            if (incomingOrientation.X < 0 && incomingOrientation.Y < 0)
                                            {
                                                incomingAngle = (2 * Math.PI) - normalVector.AngleTo(incomingOrientation);
                                            }
                                            else if (incomingOrientation.Y == 0 && incomingOrientation.X < 0)
                                            {
                                                incomingAngle = 1.5 * Math.PI;
                                            }
                                            else if (incomingOrientation.X < 0)
                                            {
                                                incomingAngle = (Math.PI - normalVector.AngleTo(incomingOrientation)) + Math.PI;
                                            }
                                            else
                                            {
                                                incomingAngle = normalVector.AngleTo(incomingOrientation);
                                            }
                                            double angle = incomingAngle - currentAngle;
                                            //TaskDialog.Show("Test", "CurrentAngle: " + currentAngle.ToString() + "\nIncoming Angle: " + incomingAngle.ToString() + "\nResulting Rotation: " + angle.ToString() +
                                            //    "\nFacingOrientation: " + orientation.ToString() + "\nIncoming Orientation: " + incomingOrientation.ToString());
                                            Line axis = Line.CreateBound(origin, origin + XYZ.BasisZ);
                                            ElementTransformUtils.RotateElement(doc, fi.Id, axis, angle);
                                        }
                                    }

                                    SetParameters(fi, obj.Parameters, doc);
                                }
                            }
                            else
                            {
                                for (int i = 0; i < existingObjects.Count; i++)
                                {
                                    RevitObject obj = existingObjects[i];
                                    fi = doc.GetElement(existingElems[i]) as FamilyInstance;

                                    // Change the family and symbol if necessary
                                    if (fi.Symbol.Family.Name != symbol.Family.Name || fi.Symbol.Name != symbol.Name)
                                    {
                                        try
                                        {
                                            fi.Symbol = symbol;
                                        }
                                        catch (Exception ex)
                                        {
                                            Debug.WriteLine(ex.Message);
                                        }
                                    }

                                    origin = new XYZ(UnitUtils.ConvertToInternalUnits(obj.Origin.X, lengthDUT), UnitUtils.ConvertToInternalUnits(obj.Origin.Y, lengthDUT), UnitUtils.ConvertToInternalUnits(obj.Origin.Z, lengthDUT));

                                    // Find the level
                                    List<LyrebirdPoint> lbPoints = new List<LyrebirdPoint> { obj.Origin };
                                    Level lvl = GetLevel(lbPoints, doc);

                                    // Get the host
                                    if (hostBehavior == 5)
                                    {
                                        // Face based family.  Find the face and create the element
                                        XYZ normVector = new XYZ(obj.Orientation.X, obj.Orientation.Y, obj.Orientation.Z);
                                        XYZ faceVector;
                                        if (obj.FaceOrientation != null)
                                        {
                                            faceVector = new XYZ(obj.FaceOrientation.X, obj.FaceOrientation.Y, obj.FaceOrientation.Z);
                                        }
                                        else
                                        {
                                            faceVector = XYZ.BasisZ;
                                        }
                                        Face face = FindFace(origin, normVector, doc);
                                        if (face != null)
                                        {
                                            if (face.Reference.ElementId == fi.HostFace.ElementId)
                                            {
                                                //fi = doc.Create.NewFamilyInstance(face, origin, faceVector, symbol);
                                                // Just move the host and update the parameters as needed.
                                                LocationPoint lp = fi.Location as LocationPoint;
                                                if (lp != null)
                                                {
                                                    XYZ oldLoc = lp.Point;
                                                    XYZ translation = origin.Subtract(oldLoc);
                                                    ElementTransformUtils.MoveElement(doc, fi.Id, translation);
                                                }

                                                SetParameters(fi, obj.Parameters, doc);
                                            }
                                            else
                                            {
                                                FamilyInstance origInst = fi;
                                                fi = doc.Create.NewFamilyInstance(face, origin, faceVector, symbol);

                                                foreach (Parameter p in origInst.Parameters)
                                                {
                                                    try
                                                    {
                                                        Parameter newParam = fi.get_Parameter(p.GUID);
                                                        if (newParam != null)
                                                        {
                                                            switch (newParam.StorageType)
                                                            {
                                                                case StorageType.Double:
                                                                    newParam.Set(p.AsDouble());
                                                                    break;
                                                                case StorageType.ElementId:
                                                                    newParam.Set(p.AsElementId());
                                                                    break;
                                                                case StorageType.Integer:
                                                                    newParam.Set(p.AsInteger());
                                                                    break;
                                                                case StorageType.String:
                                                                    newParam.Set(p.AsString());
                                                                    break;
                                                                default:
                                                                    newParam.Set(p.AsString());
                                                                    break;
                                                            }
                                                        }
                                                    }
                                                    catch (Exception ex)
                                                    {
                                                        Debug.WriteLine(ex.Message);
                                                    }
                                                }
                                                // Delete the original instance of the family
                                                doc.Delete(origInst.Id);

                                                // Assign the parameters
                                                SetParameters(fi, obj.Parameters, doc);

                                                // Assign the GH InstanceGuid
                                                AssignGuid(fi, uniqueId, instanceSchema, runId, nickName);
                                            }
                                        }
                                    }
                                    else
                                    {
                                        // typical hosted family.  Can be wall, floor, roof or ceiling.
                                        ElementId host = FindHost(origin, hostBehavior, doc);
                                        if (host != null)
                                        {
                                            if (host.IntegerValue != fi.Host.Id.IntegerValue)
                                            {
                                                // We'll have to recreate the element
                                                FamilyInstance origInst = fi;
                                                fi = doc.Create.NewFamilyInstance(origin, symbol, doc.GetElement(host), lvl, Autodesk.Revit.DB.Structure.StructuralType.NonStructural);
                                                foreach (Parameter p in origInst.Parameters)
                                                {
                                                    try
                                                    {
                                                        Parameter newParam = fi.LookupParameter(p.Definition.Name);
                                                        if (newParam != null)
                                                        {
                                                            switch (newParam.StorageType)
                                                            {
                                                                case StorageType.Double:
                                                                    newParam.Set(p.AsDouble());
                                                                    break;
                                                                case StorageType.ElementId:
                                                                    newParam.Set(p.AsElementId());
                                                                    break;
                                                                case StorageType.Integer:
                                                                    newParam.Set(p.AsInteger());
                                                                    break;
                                                                case StorageType.String:
                                                                    newParam.Set(p.AsString());
                                                                    break;
                                                                default:
                                                                    newParam.Set(p.AsString());
                                                                    break;
                                                            }
                                                        }
                                                    }
                                                    catch (Exception ex)
                                                    {
                                                        Debug.WriteLine(ex.Message);
                                                    }
                                                }
                                                // Delete the original instance of the family
                                                doc.Delete(origInst.Id);

                                                // Assign the parameters
                                                SetParameters(fi, obj.Parameters, doc);

                                                // Assign the GH InstanceGuid
                                                AssignGuid(fi, uniqueId, instanceSchema, runId, nickName);
                                            }

                                            else
                                            {
                                                // Just move the host and update the parameters as needed.
                                                LocationPoint lp = fi.Location as LocationPoint;
                                                if (lp != null)
                                                {
                                                    XYZ oldLoc = lp.Point;
                                                    XYZ translation = origin.Subtract(oldLoc);
                                                    ElementTransformUtils.MoveElement(doc, fi.Id, translation);
                                                }

                                                // Assign the parameters
                                                SetParameters(fi, obj.Parameters, doc);
                                            }
                                        }
                                    }

                                    // Assign the parameters
                                    SetParameters(fi, obj.Parameters, doc);
                                }
                                // delete the host finder
                                ElementId hostFinderFamily = hostFinder.Symbol.Family.Id;
                                doc.Delete(hostFinder.Id);
                                doc.Delete(hostFinderFamily);
                                hostFinder = null;
                            }
                        }
                        catch (Exception ex)
                        {
                            Debug.WriteLine(ex.Message);
                        }

                        t.Commit();
                    }
                }
            }

            #endregion


            #region Adaptive Components
            FamilyInstance adaptInst;
            try
            {
                adaptInst = doc.GetElement(existingElems[0]) as FamilyInstance;
            }
            catch
            {
                adaptInst = null;
            }
            if (adaptInst != null && AdaptiveComponentInstanceUtils.IsAdaptiveComponentInstance(adaptInst))
            {
                // Find the FamilySymbol
                FamilySymbol symbol = FindFamilySymbol(ro.FamilyName, ro.TypeName, doc);

                if (symbol != null)
                {
                    using (Transaction t = new Transaction(doc, "Lyrebird Modify Objects"))
                    {
                        t.Start();
                        try
                        {
                            // Create the Schema for the instances to store the GH Component InstanceGUID and the path
                            Schema instanceSchema = null;
                            try
                            {
                                instanceSchema = Schema.Lookup(instanceSchemaGUID);
                            }
                            catch (Exception ex)
                            {
                                Debug.WriteLine(ex.Message);
                            }
                            if (instanceSchema == null)
                            {
                                SchemaBuilder sb = new SchemaBuilder(instanceSchemaGUID);
                                sb.SetWriteAccessLevel(AccessLevel.Vendor);
                                sb.SetReadAccessLevel(AccessLevel.Public);
                                sb.SetVendorId("LMNA");

                                // Create the field to store the data in the family
                                FieldBuilder guidFB = sb.AddSimpleField("InstanceID", typeof(string));
                                guidFB.SetDocumentation("Component instance GUID from Grasshopper");
                                // Create a filed to store the run number
                                FieldBuilder runIDFB = sb.AddSimpleField("RunID", typeof(int));
                                runIDFB.SetDocumentation("RunID for when multiple runs are created from the same data");
                                // Create a field to store the GH component nickname.
                                FieldBuilder nickNameFB = sb.AddSimpleField("NickName", typeof(string));
                                nickNameFB.SetDocumentation("Component NickName from Grasshopper");

                                sb.SetSchemaName("LMNAInstanceGUID");
                                instanceSchema = sb.Finish();
                            }

                            try
                            {
                                for (int i = 0; i < existingElems.Count; i++)
                                {
                                    RevitObject obj = existingObjects[i];

                                    FamilyInstance fi = doc.GetElement(existingElems[i]) as FamilyInstance;

                                    // Change the family and symbol if necessary
                                    if (fi.Symbol.Family.Name != symbol.Family.Name || fi.Symbol.Name != symbol.Name)
                                    {
                                        try
                                        {
                                            fi.Symbol = symbol;
                                        }
                                        catch (Exception ex)
                                        {
                                            Debug.WriteLine(ex.Message);
                                        }
                                    }

                                    IList<ElementId> placePointIds = new List<ElementId>();
                                    placePointIds = AdaptiveComponentInstanceUtils.GetInstancePlacementPointElementRefIds(fi);

                                    for (int ptNum = 0; ptNum < obj.AdaptivePoints.Count; ptNum++)
                                    {
                                        try
                                        {
                                            ReferencePoint rp = doc.GetElement(placePointIds[ptNum]) as ReferencePoint;
                                            XYZ pt = new XYZ(UnitUtils.ConvertToInternalUnits(obj.AdaptivePoints[ptNum].X, lengthDUT), UnitUtils.ConvertToInternalUnits(obj.AdaptivePoints[ptNum].Y, lengthDUT), UnitUtils.ConvertToInternalUnits(obj.AdaptivePoints[ptNum].Z, lengthDUT));
                                            XYZ vector = pt.Subtract(rp.Position);
                                            ElementTransformUtils.MoveElement(doc, rp.Id, vector);
                                        }
                                        catch (Exception ex)
                                        {
                                            Debug.WriteLine(ex.Message);
                                        }
                                    }

                                    // Assign the parameters
                                    SetParameters(fi, obj.Parameters, doc);
                                }

                            }
                            catch (Exception ex)
                            {
                                Debug.WriteLine(ex.Message);
                            }
                        }
                        catch (Exception ex)
                        {
                            Debug.WriteLine(ex.Message);
                        }
                        t.Commit();
                    }
                }

            }

            #endregion


            #region Curve based components
            if (ro.Curves != null && ro.Curves.Count > 0)
            {
                // Find the FamilySymbol
                FamilySymbol symbol = null;
                WallType wallType = null;
                FloorType floorType = null;
                RoofType roofType = null;
                GridType gridType = null;
                bool typeFound = false;

                FilteredElementCollector famCollector = new FilteredElementCollector(doc);

                if (ro.CategoryId == -2000011)
                {
                    famCollector.OfClass(typeof(WallType));
                    foreach (WallType wt in famCollector)
                    {
                        if (wt.Name == ro.TypeName)
                        {
                            wallType = wt;
                            typeFound = true;
                            break;
                        }
                    }
                }
                else if (ro.CategoryId == -2000032)
                {
                    famCollector.OfClass(typeof(FloorType));
                    foreach (FloorType ft in famCollector)
                    {
                        if (ft.Name == ro.TypeName)
                        {
                            floorType = ft;
                            typeFound = true;
                            break;
                        }
                    }
                }
                else if (ro.CategoryId == -2000035)
                {
                    famCollector.OfClass(typeof(RoofType));
                    foreach (RoofType rt in famCollector)
                    {
                        if (rt.Name == ro.TypeName)
                        {
                            roofType = rt;
                            typeFound = true;
                            break;
                        }
                    }
                }
                else if (ro.CategoryId == -2000220)
                {
                    famCollector.OfClass(typeof(GridType));
                    foreach (GridType gt in famCollector)
                    {
                        if (gt.Name == ro.TypeName)
                        {
                            gridType = gt;
                            typeFound = true;
                            break;
                        }
                    }
                }
                else
                {
                    symbol = FindFamilySymbol(ro.FamilyName, ro.TypeName, doc);
                    if (symbol != null)
                        typeFound = true;
                }



                if (typeFound)
                {
                    
                    using (Transaction t = new Transaction(doc, "Lyrebird Modify Objects"))
                    {
                        t.Start();
                        try
                        {
                            // Create the Schema for the instances to store the GH Component InstanceGUID and the path
                            Schema instanceSchema = null;
                            try
                            {
                                instanceSchema = Schema.Lookup(instanceSchemaGUID);
                            }
                            catch (Exception ex)
                            {
                                Debug.WriteLine(ex.Message);
                            }
                            if (instanceSchema == null)
                            {
                                SchemaBuilder sb = new SchemaBuilder(instanceSchemaGUID);
                                sb.SetWriteAccessLevel(AccessLevel.Vendor);
                                sb.SetReadAccessLevel(AccessLevel.Public);
                                sb.SetVendorId("LMNA");

                                // Create the field to store the data in the family
                                FieldBuilder guidFB = sb.AddSimpleField("InstanceID", typeof(string));
                                guidFB.SetDocumentation("Component instance GUID from Grasshopper");
                                // Create a filed to store the run number
                                FieldBuilder runIDFB = sb.AddSimpleField("RunID", typeof(int));
                                runIDFB.SetDocumentation("RunID for when multiple runs are created from the same data");
                                // Create a field to store the GH component nickname.
                                FieldBuilder nickNameFB = sb.AddSimpleField("NickName", typeof(string));
                                nickNameFB.SetDocumentation("Component NickName from Grasshopper");

                                sb.SetSchemaName("LMNAInstanceGUID");
                                instanceSchema = sb.Finish();
                            }
                            FamilyInstance fi = null;
                            Grid grid = null;
                            
                            try
                            {
                                bool supress = Properties.Settings.Default.suppressWarning;
                                bool supressedReplace = false;
                                bool supressedModify = true;
                                for (int i = 0; i < existingObjects.Count; i++)
                                {
                                    RevitObject obj = existingObjects[i];
                                    if (obj.CategoryId != -2000011 && obj.CategoryId != -2000032 && obj.CategoryId != -2000035 && obj.CategoryId != -2000220)
                                    {
                                        fi = doc.GetElement(existingElems[i]) as FamilyInstance;

                                        // Change the family and symbol if necessary
                                        if (fi.Symbol.Family.Name != symbol.Family.Name || fi.Symbol.Name != symbol.Name)
                                        {
                                            try
                                            {
                                                fi.Symbol = symbol;
                                            }
                                            catch (Exception ex)
                                            {
                                                Debug.WriteLine(ex.Message);
                                            }
                                        }
                                    }
                                    else if (obj.CategoryId == -2000220)
                                    {
                                        grid = doc.GetElement(existingElems[i]) as Grid;

                                        // Get the grid location and compare against the incoming curve
                                        Curve gridCrv = grid.Curve;
                                        LyrebirdCurve lbc = obj.Curves[0];
                                        try
                                        {
                                            Arc arc = gridCrv as Arc;
                                            if (arc != null && lbc.CurveType == "Arc")
                                            {
                                                // Test that the arcs are similar
                                                XYZ startPoint = arc.GetEndPoint(0);
                                                XYZ endPoint = arc.GetEndPoint(1);
                                                XYZ centerPoint = arc.Center;
                                                double rad = arc.Radius;

                                                XYZ lbcStartPt = new XYZ(lbc.ControlPoints[0].X, lbc.ControlPoints[0].Y, lbc.ControlPoints[0].Z);
                                                XYZ lbcEndPt = new XYZ(lbc.ControlPoints[1].X, lbc.ControlPoints[1].Y, lbc.ControlPoints[1].Z);
                                                XYZ lbcMidPt = new XYZ(lbc.ControlPoints[2].X, lbc.ControlPoints[2].Y, lbc.ControlPoints[2].Z);
                                                Arc lbcArc = Arc.Create(lbcStartPt, lbcEndPt, lbcMidPt);
                                                XYZ lbcCenterPt = lbcArc.Center;
                                                double lbcRad = lbcArc.Radius;

                                                if (centerPoint.DistanceTo(lbcCenterPt) < 0.001 && lbcRad == rad && startPoint.DistanceTo(lbcStartPt) < 0.001)
                                                {
                                                    // Do not create
                                                }
                                                else
                                                {
                                                    // Delete the grid and rebuild it with the new curve.
                                                }
                                            }
                                            else
                                            {
                                                // Probably need to rebuild the curve
                                            }
                                        }
                                        catch { }


                                        try
                                        {
                                            Line line = gridCrv as Line;
                                            if (line != null && lbc.CurveType == "Line")
                                            {
                                                // Test that the arcs are similar
                                                XYZ startPoint = line.GetEndPoint(0);
                                                XYZ endPoint = line.GetEndPoint(1);

                                                XYZ lbcStartPt = new XYZ(lbc.ControlPoints[0].X, lbc.ControlPoints[0].Y, lbc.ControlPoints[0].Z);
                                                XYZ lbcEndPt = new XYZ(lbc.ControlPoints[1].X, lbc.ControlPoints[1].Y, lbc.ControlPoints[1].Z);

                                                if (endPoint.DistanceTo(lbcEndPt) < 0.001 && startPoint.DistanceTo(lbcStartPt) < 0.001)
                                                {
                                                    // Do not create
                                                }
                                                else
                                                {
                                                    // Delete the grid and rebuild it with the new curve.
                                                }
                                            }
                                            else
                                            {
                                                // Probably need to rebuild the curve
                                            }
                                        }
                                        catch { }

                                        if (grid.GridType.Name != gridType.Name)
                                        {
                                            try
                                            {
                                                grid.GridType = gridType;
                                            }
                                            catch (Exception ex)
                                            {
                                                TaskDialog.Show("Error", ex.Message);
                                                Debug.WriteLine(ex.Message);
                                            }
                                        }
                                    }
                                    #region single line based family
                                    if (obj.Curves.Count == 1 && obj.Curves[0].CurveType != "Circle")
                                    {

                                        LyrebirdCurve lbc = obj.Curves[0];
                                        List<LyrebirdPoint> curvePoints = lbc.ControlPoints.OrderBy(p => p.Z).ToList();
                                        // linear
                                        // can be a wall or line based family.

                                        // Wall objects
                                        if (obj.CategoryId == -2000011)
                                        {
                                            // draw a wall
                                            Curve crv = null;
                                            if (lbc.CurveType == "Line")
                                            {
                                                XYZ pt1 = new XYZ(UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[0].X, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[0].Y, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[0].Z, lengthDUT));
                                                XYZ pt2 = new XYZ(UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[1].X, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[1].Y, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[1].Z, lengthDUT));
                                                crv = Line.CreateBound(pt1, pt2);
                                            }
                                            else if (lbc.CurveType == "Arc")
                                            {
                                                XYZ pt1 = new XYZ(UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[0].X, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[0].Y, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[0].Z, lengthDUT));
                                                XYZ pt2 = new XYZ(UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[1].X, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[1].Y, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[1].Z, lengthDUT));
                                                XYZ pt3 = new XYZ(UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[2].X, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[2].Y, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[2].Z, lengthDUT));
                                                crv = Arc.Create(pt1, pt3, pt2);
                                            }

                                            if (crv != null)
                                            {

                                                // Find the level
                                                Level lvl = GetLevel(lbc.ControlPoints, doc);

                                                double offset = 0;
                                                if (Math.Abs(UnitUtils.ConvertToInternalUnits(curvePoints[0].Z, lengthDUT) - lvl.Elevation) > double.Epsilon)
                                                {
                                                    offset = lvl.Elevation - UnitUtils.ConvertToInternalUnits(curvePoints[0].Z, lengthDUT);
                                                }

                                                // Modify the wall
                                                Wall w = null;
                                                try
                                                {
                                                    w = doc.GetElement(existingElems[i]) as Wall;
                                                    LocationCurve lc = w.Location as LocationCurve;
                                                    lc.Curve = crv;

                                                    // Change the family and symbol if necessary
                                                    if (w.WallType.Name != wallType.Name)
                                                    {
                                                        try
                                                        {
                                                            w.WallType = wallType;
                                                        }
                                                        catch (Exception ex)
                                                        {
                                                            Debug.WriteLine(ex.Message);
                                                        }
                                                    }
                                                }
                                                catch (Exception ex)
                                                {
                                                    TaskDialog.Show("ERROR", ex.Message);
                                                }


                                                // Assign the parameters
                                                SetParameters(w, obj.Parameters, doc);
                                            }
                                        }
                                        // See if it's a structural column
                                        else if (obj.CategoryId == -2001330)
                                        {
                                            if (symbol != null && lbc.CurveType == "Line")
                                            {
                                                Curve crv = null;
                                                XYZ origin = new XYZ(UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[0].X, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[0].Y, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[0].Z, lengthDUT));
                                                XYZ pt2 = new XYZ(UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[1].X, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[1].Y, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[1].Z, lengthDUT));
                                                crv = Line.CreateBound(origin, pt2);

                                                // Find the level
                                                //Level lvl = GetLevel(lbc.ControlPoints, doc);

                                                // Create the column
                                                //fi = doc.Create.NewFamilyInstance(origin, symbol, lvl, Autodesk.Revit.DB.Structure.StructuralType.Column);

                                                // Change it to a slanted column
                                                Parameter slantParam = fi.get_Parameter(BuiltInParameter.SLANTED_COLUMN_TYPE_PARAM);

                                                // SlantedOrVerticalColumnType has 3 options, CT_Vertical (0), CT_Angle (1), or CT_EndPoint (2)
                                                // CT_EndPoint is what we want for a line based column.
                                                slantParam.Set(2);

                                                // Set the location curve of the column to the line
                                                LocationCurve lc = fi.Location as LocationCurve;
                                                if (lc != null)
                                                {
                                                    lc.Curve = crv;
                                                }

                                                // Change the family and symbol if necessary
                                                if (fi.Symbol.Name != symbol.Name)
                                                {
                                                    try
                                                    {
                                                        fi.Symbol = symbol;
                                                    }
                                                    catch (Exception ex)
                                                    {
                                                        Debug.WriteLine(ex.Message);
                                                    }
                                                }

                                                // Assign the parameters
                                                SetParameters(fi, obj.Parameters, doc);
                                            }
                                        }

                                        else if (obj.CategoryId == -2000220)
                                        {
                                            // draw a grid
                                            Curve crv = null;
                                            if (lbc.CurveType == "Line")
                                            {
                                                XYZ pt1 = new XYZ(UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[0].X, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[0].Y, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[0].Z, lengthDUT));
                                                XYZ pt2 = new XYZ(UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[1].X, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[1].Y, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[1].Z, lengthDUT));
                                                crv = Line.CreateBound(pt1, pt2);
                                            }
                                            else if (lbc.CurveType == "Arc")
                                            {
                                                XYZ pt1 = new XYZ(UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[0].X, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[0].Y, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[0].Z, lengthDUT));
                                                XYZ pt2 = new XYZ(UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[1].X, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[1].Y, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[1].Z, lengthDUT));
                                                XYZ pt3 = new XYZ(UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[2].X, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[2].Y, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[2].Z, lengthDUT));
                                                crv = Arc.Create(pt1, pt3, pt2);
                                            }

                                            if (crv != null && grid != null)
                                            {
                                                // Determine if it's possible to edit the grid curve or if it needs to be deleted/replaced.

                                                // Assign the parameters
                                                SetParameters(grid, obj.Parameters, doc);
                                            }
                                        }

                                        // Otherwise create a family it using the line
                                        else
                                        {
                                            if (symbol != null)
                                            {
                                                Curve crv = null;

                                                if (lbc.CurveType == "Line")
                                                {
                                                    XYZ origin = new XYZ(UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[0].X, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[0].Y, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[0].Z, lengthDUT));
                                                    XYZ pt2 = new XYZ(UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[1].X, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[1].Y, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[1].Z, lengthDUT));
                                                    crv = Line.CreateBound(origin, pt2);
                                                }
                                                else if (lbc.CurveType == "Arc")
                                                {
                                                    XYZ pt1 = new XYZ(UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[0].X, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[0].Y, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[0].Z, lengthDUT));
                                                    XYZ pt2 = new XYZ(UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[1].X, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[1].Y, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[1].Z, lengthDUT));
                                                    XYZ pt3 = new XYZ(UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[2].X, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[2].Y, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[2].Z, lengthDUT));
                                                    crv = Arc.Create(pt1, pt3, pt2);
                                                }

                                                // Change the family and symbol if necessary
                                                if (fi.Symbol.Name != symbol.Name)
                                                {
                                                    try
                                                    {
                                                        fi.Symbol = symbol;
                                                    }
                                                    catch (Exception ex)
                                                    {
                                                        Debug.WriteLine(ex.Message);
                                                    }
                                                }

                                                try
                                                {
                                                    LocationCurve lc = fi.Location as LocationCurve;
                                                    lc.Curve = crv;
                                                }
                                                catch (Exception ex)
                                                {
                                                    Debug.WriteLine(ex.Message);
                                                }
                                                // Assign the parameters
                                                SetParameters(fi, obj.Parameters, doc);
                                            }
                                        }
                                    }
                                    #endregion

                                    #region Closed Curve Family
                                    else
                                    {
                                        bool replace = false;
                                        if (supress)
                                        {
                                            if (supressedReplace)
                                            {
                                                replace = true;
                                            }
                                            else
                                            {
                                                replace = false;
                                            }
                                        }
                                        if (profileWarning && !supress)
                                        {
                                            TaskDialog warningDlg = new TaskDialog("Warning")
                                            {
                                                MainInstruction = "Profile based Elements warning",
                                                MainContent =
                                                  "Elements that require updates to a profile sketch may not be updated if the number of curves in the sketch differs from the incoming curves." +
                                                  "  In such cases the element and will be deleted and replaced with new elements." +
                                                  "  Doing so will cause the loss of any elements hosted to the original instance. How would you like to proceed"
                                            };

                                            warningDlg.AddCommandLink(TaskDialogCommandLinkId.CommandLink1, "Replace the existing elements, understanding hosted elements may be lost");
                                            warningDlg.AddCommandLink(TaskDialogCommandLinkId.CommandLink2, "Only updated parameter information and not profile or location information");
                                            warningDlg.AddCommandLink(TaskDialogCommandLinkId.CommandLink3, "Cancel");
                                            //warningDlg.VerificationText = "Supress similar warnings";

                                            TaskDialogResult result = warningDlg.Show();
                                            if (result == TaskDialogResult.CommandLink1)
                                            {
                                                replace = true;
                                                supressedReplace = true;
                                                supressedModify = true;
                                                //supress = warningDlg.WasVerificationChecked();
                                            }
                                            if (result == TaskDialogResult.CommandLink2)
                                            {
                                                supressedReplace = false;
                                                supressedModify = true;
                                                //supress = warningDlg.WasVerificationChecked();
                                            }
                                            if (result == TaskDialogResult.CommandLink3)
                                            {
                                                supressedReplace = false;
                                                supressedModify = false;
                                                //supress = warningDlg.WasVerificationChecked();
                                            }
                                        }
                                        // A list of curves.  These should equate a closed planar curve from GH.
                                        // Determine category and create based on that.
                                        #region walls
                                        if (obj.CategoryId == -2000011)
                                        {
                                            // Create line based wall
                                            // Find the level
                                            Level lvl = null;
                                            double offset = 0;
                                            List<LyrebirdPoint> allPoints = new List<LyrebirdPoint>();
                                            foreach (LyrebirdCurve lc in obj.Curves)
                                            {
                                                foreach (LyrebirdPoint lp in lc.ControlPoints)
                                                {
                                                    allPoints.Add(lp);
                                                }
                                            }
                                            allPoints.Sort((x, y) => x.Z.CompareTo(y.Z));

                                            lvl = GetLevel(allPoints, doc);

                                            if (Math.Abs(allPoints[0].Z - lvl.Elevation) > double.Epsilon)
                                            {
                                                offset = allPoints[0].Z - lvl.Elevation;
                                            }

                                            // Generate the curvearray from the incoming curves
                                            List<Curve> crvArray = new List<Curve>();
                                            try
                                            {
                                                foreach (LyrebirdCurve lbc in obj.Curves)
                                                {
                                                    if (lbc.CurveType == "Circle")
                                                    {
                                                        XYZ pt1 = new XYZ(UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[0].X, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[0].Y, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[0].Z, lengthDUT));
                                                        XYZ pt2 = new XYZ(UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[1].X, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[1].Y, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[1].Z, lengthDUT));
                                                        XYZ pt3 = new XYZ(UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[2].X, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[2].Y, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[2].Z, lengthDUT));
                                                        XYZ pt4 = new XYZ(UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[3].X, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[3].Y, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[3].Z, lengthDUT));
                                                        XYZ pt5 = new XYZ(UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[4].X, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[4].Y, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[4].Z, lengthDUT));
                                                        Arc arc1 = Arc.Create(pt1, pt3, pt2);
                                                        Arc arc2 = Arc.Create(pt3, pt5, pt4);
                                                        crvArray.Add(arc1);
                                                        crvArray.Add(arc2);
                                                    }
                                                    else if (lbc.CurveType == "Arc")
                                                    {
                                                        XYZ pt1 = new XYZ(UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[0].X, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[0].Y, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[0].Z, lengthDUT));
                                                        XYZ pt2 = new XYZ(UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[1].X, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[1].Y, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[1].Z, lengthDUT));
                                                        XYZ pt3 = new XYZ(UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[2].X, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[2].Y, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[2].Z, lengthDUT));
                                                        Arc arc = Arc.Create(pt1, pt3, pt2);
                                                        crvArray.Add(arc);
                                                    }
                                                    else if (lbc.CurveType == "Line")
                                                    {
                                                        XYZ pt1 = new XYZ(UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[0].X, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[0].Y, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[0].Z, lengthDUT));
                                                        XYZ pt2 = new XYZ(UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[1].X, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[1].Y, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[1].Z, lengthDUT));
                                                        Line line = Line.CreateBound(pt1, pt2);
                                                        crvArray.Add(line);
                                                    }
                                                    else if (lbc.CurveType == "Spline")
                                                    {
                                                        List<XYZ> controlPoints = new List<XYZ>();
                                                        List<double> weights = lbc.Weights;
                                                        List<double> knots = lbc.Knots;

                                                        foreach (LyrebirdPoint lp in lbc.ControlPoints)
                                                        {
                                                            XYZ pt = new XYZ(UnitUtils.ConvertToInternalUnits(lp.X, lengthDUT), UnitUtils.ConvertToInternalUnits(lp.Y, lengthDUT), UnitUtils.ConvertToInternalUnits(lp.Z, lengthDUT));
                                                            controlPoints.Add(pt);
                                                        }

                                                        NurbSpline spline;
                                                        if (lbc.Degree < 3)
                                                            spline = NurbSpline.Create(controlPoints, weights);
                                                        else
                                                            spline = NurbSpline.Create(controlPoints, weights, knots, lbc.Degree, false, true);

                                                        crvArray.Add(spline);
                                                    }
                                                }
                                            }
                                            catch (Exception ex)
                                            {
                                                TaskDialog.Show("ERROR", ex.Message);
                                            }

                                            // Create the wall
                                            Wall w = null;
                                            if (replace)
                                            {
                                                Wall origWall = doc.GetElement(existingElems[i]) as Wall;

                                                // Find the model curves for the original wall
                                                ICollection<ElementId> ids;
                                                using (SubTransaction st = new SubTransaction(doc))
                                                {
                                                    st.Start();
                                                    ids = doc.Delete(origWall.Id);
                                                    st.RollBack();
                                                }

                                                List<ModelCurve> mLines = new List<ModelCurve>();
                                                foreach (ElementId id in ids)
                                                {
                                                    Element e = doc.GetElement(id);
                                                    if (e is ModelCurve)
                                                    {
                                                        mLines.Add(e as ModelCurve);
                                                    }
                                                }

                                                // Walls don't appear to be updatable like floors and roofs
                                                //if (mLines.Count != crvArray.Count)
                                                //{

                                                w = Wall.Create(doc, crvArray, wallType.Id, lvl.Id, false);

                                                foreach (Parameter p in origWall.Parameters)
                                                {
                                                    try
                                                    {
                                                        Parameter newParam = w.LookupParameter(p.Definition.Name);
                                                        if (newParam != null)
                                                        {
                                                            switch (newParam.StorageType)
                                                            {
                                                                case StorageType.Double:
                                                                    newParam.Set(p.AsDouble());
                                                                    break;
                                                                case StorageType.ElementId:
                                                                    newParam.Set(p.AsElementId());
                                                                    break;
                                                                case StorageType.Integer:
                                                                    newParam.Set(p.AsInteger());
                                                                    break;
                                                                case StorageType.String:
                                                                    newParam.Set(p.AsString());
                                                                    break;
                                                                default:
                                                                    newParam.Set(p.AsString());
                                                                    break;
                                                            }
                                                        }
                                                    }
                                                    catch (Exception ex)
                                                    {
                                                        //TaskDialog.Show("Errorsz", ex.Message);
                                                        Debug.WriteLine(ex.Message);
                                                    }
                                                }

                                                if (Math.Abs(offset - 0) > double.Epsilon)
                                                {
                                                    Parameter p = w.get_Parameter(BuiltInParameter.WALL_BASE_OFFSET);
                                                    p.Set(offset);
                                                }
                                                doc.Delete(origWall.Id);

                                                // Assign the parameters
                                                SetParameters(w, obj.Parameters, doc);

                                                // Assign the GH InstanceGuid
                                                AssignGuid(w, uniqueId, instanceSchema, runId, nickName);
                                            }
                                            else if (supressedModify) // Just update the parameters and don't change the wall
                                            {
                                                w = doc.GetElement(existingElems[i]) as Wall;

                                                // Change the family and symbol if necessary
                                                if (w.WallType.Name != wallType.Name)
                                                {
                                                    try
                                                    {
                                                        w.WallType = wallType;
                                                    }
                                                    catch (Exception ex)
                                                    {
                                                        Debug.WriteLine(ex.Message);
                                                    }
                                                }

                                                // Assign the parameters
                                                SetParameters(w, obj.Parameters, doc);
                                            }
                                        }
                                        #endregion

                                        #region floors
                                        else if (obj.CategoryId == -2000032)
                                        {
                                            // Create a profile based floor
                                            // Find the level
                                            Level lvl = GetLevel(obj.Curves[0].ControlPoints, doc);

                                            double offset = 0;
                                            if (Math.Abs(UnitUtils.ConvertToInternalUnits(obj.Curves[0].ControlPoints[0].Z, lengthDUT) - lvl.Elevation) > double.Epsilon)
                                            {
                                                offset = UnitUtils.ConvertToInternalUnits(obj.Curves[0].ControlPoints[0].Z, lengthDUT) - lvl.Elevation;
                                            }

                                            // Generate the curvearray from the incoming curves
                                            CurveArray crvArray = GetCurveArray(obj.Curves);

                                            // Create the floor
                                            Floor flr = null;
                                            if (replace)
                                            {
                                                Floor origFloor = doc.GetElement(existingElems[i]) as Floor;

                                                // Find the model curves for the original wall
                                                ICollection<ElementId> ids;
                                                using (SubTransaction st = new SubTransaction(doc))
                                                {
                                                    st.Start();

                                                    ids = doc.Delete(origFloor.Id);
                                                    st.RollBack();
                                                }

                                                // Get only the modelcurves
                                                List<ModelCurve> mLines = new List<ModelCurve>();
                                                foreach (ElementId id in ids)
                                                {
                                                    Element e = doc.GetElement(id);
                                                    if (e is ModelCurve)
                                                    {
                                                        mLines.Add(e as ModelCurve);
                                                    }
                                                }

                                                // Floors have an extra modelcurve for the SpanDirection.  Remove the last Item to get rid of it.
                                                mLines.RemoveAt(mLines.Count - 1);
                                                if (mLines.Count != crvArray.Size) // The sketch is different from the incoming curves so floor is recreated
                                                {
                                                    if (obj.CurveIds != null && obj.CurveIds.Count > 0)
                                                    {
                                                        // get the main profile
                                                        int crvCount = obj.CurveIds[0];
                                                        List<LyrebirdCurve> primaryCurves = obj.Curves.GetRange(0, crvCount);
                                                        crvArray = GetCurveArray(primaryCurves);
                                                        flr = doc.Create.NewFloor(crvArray, floorType, lvl, false);
                                                    }
                                                    else
                                                    {
                                                        flr = doc.Create.NewFloor(crvArray, floorType, lvl, false);
                                                    }
                                                    foreach (Parameter p in origFloor.Parameters)
                                                    {
                                                        try
                                                        {
                                                            Parameter newParam = flr.LookupParameter(p.Definition.Name);
                                                            if (newParam != null)
                                                            {
                                                                switch (newParam.StorageType)
                                                                {
                                                                    case StorageType.Double:
                                                                        newParam.Set(p.AsDouble());
                                                                        break;
                                                                    case StorageType.ElementId:
                                                                        newParam.Set(p.AsElementId());
                                                                        break;
                                                                    case StorageType.Integer:
                                                                        newParam.Set(p.AsInteger());
                                                                        break;
                                                                    case StorageType.String:
                                                                        newParam.Set(p.AsString());
                                                                        break;
                                                                    default:
                                                                        newParam.Set(p.AsString());
                                                                        break;
                                                                }
                                                            }
                                                        }
                                                        catch (Exception ex)
                                                        {
                                                            Debug.WriteLine(ex.Message);
                                                        }
                                                    }

                                                    if (Math.Abs(offset - 0) > double.Epsilon)
                                                    {
                                                        Parameter p = flr.get_Parameter(BuiltInParameter.FLOOR_HEIGHTABOVELEVEL_PARAM);
                                                        p.Set(offset);
                                                    }
                                                    doc.Delete(origFloor.Id);

                                                    // Assign the parameters
                                                    SetParameters(flr, obj.Parameters, doc);

                                                    // Assign the GH InstanceGuid
                                                    AssignGuid(flr, uniqueId, instanceSchema, runId, nickName);
                                                }
                                                else // The curves coming in should match the floor sketch.  Let's modify the floor's locationcurves to edit it's location/shape
                                                {
                                                    try
                                                    {
                                                        int crvCount = 0;
                                                        foreach (ModelCurve l in mLines)
                                                        {
                                                            LocationCurve lc = l.Location as LocationCurve;
                                                            lc.Curve = crvArray.get_Item(crvCount);
                                                            crvCount++;
                                                        }

                                                        // Change the family and symbol if necessary
                                                        if (origFloor.FloorType.Name != floorType.Name)
                                                        {
                                                            try
                                                            {
                                                                origFloor.FloorType = floorType;
                                                            }
                                                            catch (Exception ex)
                                                            {
                                                                Debug.WriteLine(ex.Message);
                                                            }
                                                        }

                                                        // Set the incoming parameters
                                                        SetParameters(origFloor, obj.Parameters, doc);
                                                    }
                                                    catch // There was an error in trying to recreate it.  Just delete the original and recreate the thing.
                                                    {
                                                        flr = doc.Create.NewFloor(crvArray, floorType, lvl, false);

                                                        // Assign the parameters in the new floor to match the original floor object.
                                                        foreach (Parameter p in origFloor.Parameters)
                                                        {
                                                            try
                                                            {
                                                                Parameter newParam = flr.LookupParameter(p.Definition.Name);
                                                                if (newParam != null)
                                                                {
                                                                    switch (newParam.StorageType)
                                                                    {
                                                                        case StorageType.Double:
                                                                            newParam.Set(p.AsDouble());
                                                                            break;
                                                                        case StorageType.ElementId:
                                                                            newParam.Set(p.AsElementId());
                                                                            break;
                                                                        case StorageType.Integer:
                                                                            newParam.Set(p.AsInteger());
                                                                            break;
                                                                        case StorageType.String:
                                                                            newParam.Set(p.AsString());
                                                                            break;
                                                                        default:
                                                                            newParam.Set(p.AsString());
                                                                            break;
                                                                    }
                                                                }
                                                            }
                                                            catch (Exception exception)
                                                            {
                                                                Debug.WriteLine(exception.Message);
                                                            }
                                                        }

                                                        if (Math.Abs(offset - 0) > double.Epsilon)
                                                        {
                                                            Parameter p = flr.get_Parameter(BuiltInParameter.FLOOR_HEIGHTABOVELEVEL_PARAM);
                                                            p.Set(offset);
                                                        }

                                                        doc.Delete(origFloor.Id);

                                                        // Set the incoming parameters
                                                        SetParameters(flr, obj.Parameters, doc);
                                                        // Assign the GH InstanceGuid
                                                        AssignGuid(flr, uniqueId, instanceSchema, runId, nickName);
                                                    }
                                                }
                                            }
                                            else if (supressedModify) // Just modify the floor and don't risk replacing it.
                                            {
                                                flr = doc.GetElement(existingElems[i]) as Floor;

                                                // Change the family and symbol if necessary
                                                if (flr.FloorType.Name != floorType.Name)
                                                {
                                                    try
                                                    {
                                                        flr.FloorType = floorType;
                                                    }
                                                    catch (Exception ex)
                                                    {
                                                        Debug.WriteLine(ex.Message);
                                                    }
                                                }
                                                // Assign the parameters
                                                SetParameters(flr, obj.Parameters, doc);
                                            }
                                        }
                                        #endregion
                                        else if (obj.CategoryId == -2000035)
                                        {
                                            // Create a RoofExtrusion
                                            // Find the level
                                            Level lvl = GetLevel(obj.Curves[0].ControlPoints, doc);

                                            double offset = 0;
                                            if (Math.Abs(UnitUtils.ConvertToInternalUnits(obj.Curves[0].ControlPoints[0].Z, lengthDUT) - lvl.Elevation) > double.Epsilon)
                                            {
                                                offset = UnitUtils.ConvertToInternalUnits(obj.Curves[0].ControlPoints[0].Z, lengthDUT) - lvl.Elevation;
                                            }

                                            // Generate the curvearray from the incoming curves
                                            CurveArray crvArray = GetCurveArray(obj.Curves);

                                            // Create the roof
                                            FootPrintRoof roof = null;
                                            ModelCurveArray roofProfile = new ModelCurveArray();

                                            if (replace)  // Try to modify or create a new roof.
                                            {
                                                FootPrintRoof origRoof = doc.GetElement(existingElems[i]) as FootPrintRoof;

                                                // Find the model curves for the original wall
                                                ICollection<ElementId> ids;
                                                using (SubTransaction st = new SubTransaction(doc))
                                                {
                                                    st.Start();
                                                    ids = doc.Delete(origRoof.Id);
                                                    st.RollBack();
                                                }

                                                // Get the sketch curves for the roof object.
                                                List<ModelCurve> mLines = new List<ModelCurve>();
                                                foreach (ElementId id in ids)
                                                {
                                                    Element e = doc.GetElement(id);
                                                    if (e is ModelCurve)
                                                    {
                                                        mLines.Add(e as ModelCurve);
                                                    }
                                                }

                                                if (mLines.Count != crvArray.Size) // Sketch curves qty doesn't match up with the incoming cuves.  Just recreate the roof.
                                                {
                                                    roof = doc.Create.NewFootPrintRoof(crvArray, lvl, roofType, out roofProfile);

                                                    // Match parameters from the original roof to it's new iteration.
                                                    foreach (Parameter p in origRoof.Parameters)
                                                    {
                                                        try
                                                        {
                                                            Parameter newParam = roof.LookupParameter(p.Definition.Name);
                                                            if (newParam != null)
                                                            {
                                                                switch (newParam.StorageType)
                                                                {
                                                                    case StorageType.Double:
                                                                        newParam.Set(p.AsDouble());
                                                                        break;
                                                                    case StorageType.ElementId:
                                                                        newParam.Set(p.AsElementId());
                                                                        break;
                                                                    case StorageType.Integer:
                                                                        newParam.Set(p.AsInteger());
                                                                        break;
                                                                    case StorageType.String:
                                                                        newParam.Set(p.AsString());
                                                                        break;
                                                                    default:
                                                                        newParam.Set(p.AsString());
                                                                        break;
                                                                }
                                                            }
                                                        }
                                                        catch (Exception ex)
                                                        {
                                                            Debug.WriteLine(ex.Message);
                                                        }
                                                    }

                                                    if (Math.Abs(offset - 0) > double.Epsilon)
                                                    {
                                                        Parameter p = roof.get_Parameter(BuiltInParameter.ROOF_LEVEL_OFFSET_PARAM);
                                                        p.Set(offset);
                                                    }

                                                    doc.Delete(origRoof.Id);

                                                    // Set the new parameters
                                                    SetParameters(roof, obj.Parameters, doc);

                                                    // Assign the GH InstanceGuid
                                                    AssignGuid(roof, uniqueId, instanceSchema, runId, nickName);
                                                }
                                                else // The curves qty lines up, lets try to modify the roof sketch so we don't have to replace it.
                                                {
                                                    if (obj.CurveIds != null && obj.CurveIds.Count > 0)
                                                    {
                                                        // Just recreate the roof
                                                        roof = doc.Create.NewFootPrintRoof(crvArray, lvl, roofType, out roofProfile);

                                                        // Match parameters from the original roof to it's new iteration.
                                                        foreach (Parameter p in origRoof.Parameters)
                                                        {
                                                            try
                                                            {
                                                                Parameter newParam = roof.LookupParameter(p.Definition.Name);
                                                                if (newParam != null)
                                                                {
                                                                    switch (newParam.StorageType)
                                                                    {
                                                                        case StorageType.Double:
                                                                            newParam.Set(p.AsDouble());
                                                                            break;
                                                                        case StorageType.ElementId:
                                                                            newParam.Set(p.AsElementId());
                                                                            break;
                                                                        case StorageType.Integer:
                                                                            newParam.Set(p.AsInteger());
                                                                            break;
                                                                        case StorageType.String:
                                                                            newParam.Set(p.AsString());
                                                                            break;
                                                                        default:
                                                                            newParam.Set(p.AsString());
                                                                            break;
                                                                    }
                                                                }
                                                            }
                                                            catch (Exception ex)
                                                            {
                                                                Debug.WriteLine(ex.Message);
                                                            }
                                                        }

                                                        if (Math.Abs(offset - 0) > double.Epsilon)
                                                        {
                                                            Parameter p = roof.get_Parameter(BuiltInParameter.ROOF_LEVEL_OFFSET_PARAM);
                                                            p.Set(offset);
                                                        }

                                                        // Set the parameters from the incoming data
                                                        SetParameters(roof, obj.Parameters, doc);

                                                        // Assign the GH InstanceGuid
                                                        AssignGuid(roof, uniqueId, instanceSchema, runId, nickName);

                                                        doc.Delete(origRoof.Id);
                                                    }
                                                    else
                                                    {
                                                        try
                                                        {
                                                            int crvCount = 0;
                                                            foreach (ModelCurve l in mLines)
                                                            {
                                                                LocationCurve lc = l.Location as LocationCurve;
                                                                lc.Curve = crvArray.get_Item(crvCount);
                                                                crvCount++;
                                                            }

                                                            // Change the family and symbol if necessary
                                                            if (origRoof.RoofType.Name != roofType.Name)
                                                            {
                                                                try
                                                                {
                                                                    origRoof.RoofType = roofType;
                                                                }
                                                                catch (Exception ex)
                                                                {
                                                                    Debug.WriteLine(ex.Message);
                                                                }
                                                            }

                                                            SetParameters(origRoof, obj.Parameters, doc);
                                                        }
                                                        catch // Modificaiton failed, lets just create a new roof.
                                                        {
                                                            roof = doc.Create.NewFootPrintRoof(crvArray, lvl, roofType, out roofProfile);

                                                            // Match parameters from the original roof to it's new iteration.
                                                            foreach (Parameter p in origRoof.Parameters)
                                                            {
                                                                try
                                                                {
                                                                    Parameter newParam = roof.LookupParameter(p.Definition.Name);
                                                                    if (newParam != null)
                                                                    {
                                                                        switch (newParam.StorageType)
                                                                        {
                                                                            case StorageType.Double:
                                                                                newParam.Set(p.AsDouble());
                                                                                break;
                                                                            case StorageType.ElementId:
                                                                                newParam.Set(p.AsElementId());
                                                                                break;
                                                                            case StorageType.Integer:
                                                                                newParam.Set(p.AsInteger());
                                                                                break;
                                                                            case StorageType.String:
                                                                                newParam.Set(p.AsString());
                                                                                break;
                                                                            default:
                                                                                newParam.Set(p.AsString());
                                                                                break;
                                                                        }
                                                                    }
                                                                }
                                                                catch (Exception ex)
                                                                {
                                                                    Debug.WriteLine(ex.Message);
                                                                }
                                                            }

                                                            if (Math.Abs(offset - 0) > double.Epsilon)
                                                            {
                                                                Parameter p = roof.get_Parameter(BuiltInParameter.ROOF_LEVEL_OFFSET_PARAM);
                                                                p.Set(offset);
                                                            }

                                                            // Set the parameters from the incoming data
                                                            SetParameters(roof, obj.Parameters, doc);

                                                            // Assign the GH InstanceGuid
                                                            AssignGuid(roof, uniqueId, instanceSchema, runId, nickName);

                                                            doc.Delete(origRoof.Id);
                                                        }
                                                    }
                                                }
                                            }
                                            else if (supressedModify) // Only update the parameters
                                            {
                                                roof = doc.GetElement(existingElems[i]) as FootPrintRoof;

                                                // Change the family and symbol if necessary
                                                if (roof.RoofType.Name != roofType.Name)
                                                {
                                                    try
                                                    {
                                                        roof.RoofType = roofType;
                                                    }
                                                    catch (Exception ex)
                                                    {
                                                        Debug.WriteLine(ex.Message);
                                                    }
                                                }
                                                // Assign the parameters
                                                SetParameters(roof, obj.Parameters, doc);
                                            }
                                        }
                                    }
                                    #endregion
                                }
                            }
                            catch (Exception ex)
                            {
                                TaskDialog.Show("Error", ex.Message);
                            }
                        }
                        catch (Exception ex)
                        {
                            Debug.WriteLine(ex.Message);
                        }
                        t.Commit();
                    }
                }


            }
            #endregion

            //return succeeded;
        }
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIApplication uiapp = commandData.Application;
            UIDocument    uidoc = uiapp.ActiveUIDocument;
            Application   app   = uiapp.Application;
            Document      doc   = uidoc.Document;

            using (Transaction tx = new Transaction(doc))
            {
                tx.Start("Mirror and List Added");
                //Line line = app.Create.NewLine(
                //  XYZ.Zero, XYZ.BasisX, true ); // 2011

                //ElementSet els = uidoc.Selection.Elements; // 2011

                //Plane plane = new Plane( XYZ.BasisY, XYZ.Zero ); // added in 2012, used until 2016

                Plane plane = Plane.CreateByNormalAndOrigin(XYZ.BasisY, XYZ.Zero); // 2017

                ICollection <ElementId> elementIds
                    = uidoc.Selection.GetElementIds(); // 2012

                using (SubTransaction t = new SubTransaction(doc))
                {
                    // determine newly added elements relying on the
                    // element sequence as returned by the filtered collector.
                    // this approach works in both Revit 2010 and 2011:

                    t.Start();

                    int n = GetElementCount(doc);

                    //doc.Mirror( els, line ); // 2011

                    //ElementTransformUtils.MirrorElements(
                    //  doc, elementIds, plane ); // 2012-2015

                    ElementTransformUtils.MirrorElements(
                        doc, elementIds, plane, true); // 2016

                    List <Element> a = GetElementsAfter(n, doc);

                    t.RollBack();
                }

                using (SubTransaction t = new SubTransaction(doc))
                {
                    // here is an idea for a new approach in 2011:
                    // determine newly added elements relying on
                    // monotonously increasing element id values:

                    t.Start();

                    FilteredElementCollector a = GetElements(doc);
                    int       i     = a.Max <Element>(e => e.Id.IntegerValue);
                    ElementId maxId = new ElementId(i);

                    // doc.Mirror( els, line ); // 2011

                    //ElementTransformUtils.MirrorElements(
                    //  doc, elementIds, plane ); // 2012-2015

                    ElementTransformUtils.MirrorElements(
                        doc, elementIds, plane, true); // 2016

                    // get all elements in document with an
                    // element id greater than maxId:

                    a = GetElementsAfter(doc, maxId);

                    Report(a);

                    t.RollBack();
                }

                using (SubTransaction t = new SubTransaction(doc))
                {
                    // similar to the above approach relying on
                    // monotonously increasing element id values,
                    // but apply a quick filter first:

                    t.Start();

                    FilteredElementCollector a = GetElements(doc);
                    int       i     = a.Max <Element>(e => e.Id.IntegerValue);
                    ElementId maxId = new ElementId(i);

                    //doc.Mirror( els, line ); // 2011

                    //ElementTransformUtils.MirrorElements(
                    //  doc, elementIds, plane ); // 2012-2015

                    ElementTransformUtils.MirrorElements(
                        doc, elementIds, plane, true); // 2016

                    // only look at non-ElementType elements
                    // instead of all document elements:

                    a = GetElements(doc);
                    a = GetElementsAfter(a, maxId);

                    Report(a);

                    t.RollBack();
                }

                using (SubTransaction t = new SubTransaction(doc))
                {
                    // use a local and temporary DocumentChanged event
                    // handler to directly obtain a list of all newly
                    // created elements.
                    // unfortunately, this canot be tested in this isolated form,
                    // since the DocumentChanged event is only triggered when the
                    // real outermost Revit transaction is committed, i.e. our
                    // local sub-transaction makes no difference. since we abort
                    // the sub-transaction before the command terminates and no
                    // elements are really added to the database, our event
                    // handler is never called:

                    t.Start();

                    app.DocumentChanged
                        += new EventHandler <DocumentChangedEventArgs>(
                               app_DocumentChanged);

                    //doc.Mirror( els, line ); // 2011

                    //ElementTransformUtils.MirrorElements(
                    //  doc, elementIds, plane ); // 2012-2015

                    ElementTransformUtils.MirrorElements(
                        doc, elementIds, plane, true); // 2016

                    app.DocumentChanged
                        -= new EventHandler <DocumentChangedEventArgs>(
                               app_DocumentChanged);

                    Debug.Assert(null == _addedElementIds,
                                 "never expected the event handler to be called");

                    if (null != _addedElementIds)
                    {
                        int n = _addedElementIds.Count;

                        string s = string.Format(_msg, n,
                                                 Util.PluralSuffix(n));

                        foreach (ElementId id in _addedElementIds)
                        {
                            Element e = doc.GetElement(id);

                            s += string.Format("\r\n  {0}",
                                               Util.ElementDescription(e));
                        }
                        Util.InfoMsg(s);
                    }

                    t.RollBack();
                }
                tx.RollBack();
            }
            return(Result.Succeeded);
        }
      /// <summary>
        /// Implements the export of element.
        /// </summary>
        /// <param name="exporterIFC">The IFC exporter object.</param>
        /// <param name="element">The element to export.</param>
        /// <param name="productWrapper">The ProductWrapper object.</param>
        public virtual void ExportElementImpl(ExporterIFC exporterIFC, Element element, ProductWrapper productWrapper)
        {
            Options options;
            View ownerView = null;

            ownerView = element.Document.GetElement(element.OwnerViewId) as View;

            if (ExporterCacheManager.ExportOptionsCache.UseActiveViewGeometry)
            {
                ownerView = ExporterCacheManager.ExportOptionsCache.ActiveView;
            }
            else
            {
                ownerView = element.Document.GetElement(element.OwnerViewId) as View;
            }

            if (ownerView == null)
            {
                options = GeometryUtil.GetIFCExportGeometryOptions();
            }
            else
            {
                options = new Options();
                options.View = ownerView;
            }
            GeometryElement geomElem = element.get_Geometry(options);

            // Default: we don't preserve the element parameter cache after export.
            bool shouldPreserveParameterCache = false;

            try
            {
                exporterIFC.PushExportState(element, geomElem);

                Autodesk.Revit.DB.Document doc = element.Document;
                using (SubTransaction st = new SubTransaction(doc))
                {
                    st.Start();

               // A long list of supported elements.  Please keep in alphabetical order by the first item in the list..
               if (element is AreaScheme)
                    {
                        AreaSchemeExporter.ExportAreaScheme(exporterIFC, element as AreaScheme, productWrapper);
                    }
                    else if (element is AssemblyInstance)
                    {
                        AssemblyInstance assemblyInstance = element as AssemblyInstance;
                        AssemblyInstanceExporter.ExportAssemblyInstanceElement(exporterIFC, assemblyInstance, productWrapper);
                    }
                    else if (element is BeamSystem)
                    {
                        if (ExporterCacheManager.BeamSystemCache.Contains(element.Id))
                            AssemblyInstanceExporter.ExportBeamSystem(exporterIFC, element as BeamSystem, productWrapper);
                        else
                        {
                            ExporterCacheManager.BeamSystemCache.Add(element.Id);
                            shouldPreserveParameterCache = true;
                        }
                    }
                    else if (element is Ceiling)
                    {
                        Ceiling ceiling = element as Ceiling;
                        CeilingExporter.ExportCeilingElement(exporterIFC, ceiling, geomElem, productWrapper);
                    }
                    else if (element is CeilingAndFloor || element is Floor)
                    {
                        // This covers both Floors and Building Pads.
                        CeilingAndFloor hostObject = element as CeilingAndFloor;
                        FloorExporter.ExportCeilingAndFloorElement(exporterIFC, hostObject, geomElem, productWrapper);
                    }
                    else if (element is ContFooting)
                    {
                        ContFooting footing = element as ContFooting;
                        FootingExporter.ExportFootingElement(exporterIFC, footing, geomElem, productWrapper);
                    }
                    else if (element is CurveElement)
                    {
                        CurveElement curveElem = element as CurveElement;
                        CurveElementExporter.ExportCurveElement(exporterIFC, curveElem, geomElem, productWrapper);
                    }
                    else if (element is CurtainSystem)
                    {
                        CurtainSystem curtainSystem = element as CurtainSystem;
                        CurtainSystemExporter.ExportCurtainSystem(exporterIFC, curtainSystem, productWrapper);
                    }
                    else if (CurtainSystemExporter.IsLegacyCurtainElement(element))
                    {
                        CurtainSystemExporter.ExportLegacyCurtainElement(exporterIFC, element, productWrapper);
                    }
                    else if (element is DuctInsulation)
                    {
                        DuctInsulation ductInsulation = element as DuctInsulation;
                        DuctInsulationExporter.ExportDuctInsulation(exporterIFC, ductInsulation, geomElem, productWrapper);
                    }
                    else if (element is DuctLining)
                    {
                        DuctLining ductLining = element as DuctLining;
                        DuctLiningExporter.ExportDuctLining(exporterIFC, ductLining, geomElem, productWrapper);
                    }
                    else if (element is ElectricalSystem)
                    {
                        ExporterCacheManager.SystemsCache.AddElectricalSystem(element.Id);
                    }
                    else if (element is FabricArea)
                    {
                        // We are exporting the fabric area as a group only.
                        FabricSheetExporter.ExportFabricArea(exporterIFC, element, productWrapper);
                    }
                    else if (element is FabricSheet)
                    {
                        FabricSheet fabricSheet = element as FabricSheet;
                        FabricSheetExporter.ExportFabricSheet(exporterIFC, fabricSheet, geomElem, productWrapper);
                    }
                    else if (element is FaceWall)
                    {
                        WallExporter.ExportWall(exporterIFC, element, null, geomElem, productWrapper);
                    }
                    else if (element is FamilyInstance)
                    {
                        FamilyInstance familyInstanceElem = element as FamilyInstance;
                        FamilyInstanceExporter.ExportFamilyInstanceElement(exporterIFC, familyInstanceElem, geomElem, productWrapper);
                    }
                    else if (element is FilledRegion)
                    {
                        FilledRegion filledRegion = element as FilledRegion;
                        FilledRegionExporter.Export(exporterIFC, filledRegion, geomElem, productWrapper);
                    }
                    else if (element is Grid)
                    {
                        ExporterCacheManager.GridCache.Add(element);
                    }
                    else if (element is Group)
                    {
                        Group group = element as Group;
                        GroupExporter.ExportGroupElement(exporterIFC, group, productWrapper);
                    }
                    else if (element is HostedSweep)
                    {
                        HostedSweep hostedSweep = element as HostedSweep;
                        HostedSweepExporter.Export(exporterIFC, hostedSweep, geomElem, productWrapper);
                    }
                    else if (element is Part)
                    {
                        Part part = element as Part;
                        if (ExporterCacheManager.ExportOptionsCache.ExportPartsAsBuildingElements)
                            PartExporter.ExportPartAsBuildingElement(exporterIFC, part, geomElem, productWrapper);
                        else
                            PartExporter.ExportStandalonePart(exporterIFC, part, geomElem, productWrapper);
                    }
                    else if (element is PipeInsulation)
                    {
                        PipeInsulation pipeInsulation = element as PipeInsulation;
                        PipeInsulationExporter.ExportPipeInsulation(exporterIFC, pipeInsulation, geomElem, productWrapper);
                    }
                    else if (element is Railing)
                    {
                        if (ExporterCacheManager.RailingCache.Contains(element.Id))
                            RailingExporter.ExportRailingElement(exporterIFC, element as Railing, productWrapper);
                        else
                        {
                            ExporterCacheManager.RailingCache.Add(element.Id);
                            RailingExporter.AddSubElementsToCache(element as Railing);
                            shouldPreserveParameterCache = true;
                        }
                    }
                    else if (RampExporter.IsRamp(element))
                    {
                        RampExporter.Export(exporterIFC, element, geomElem, productWrapper);
                    }
               else if (IsRebarType(element))
               {
                  RebarExporter.Export(exporterIFC, element, productWrapper);
               }
                    else if (element is RoofBase)
                    {
                        RoofBase roofElement = element as RoofBase;
                        RoofExporter.Export(exporterIFC, roofElement, geomElem, productWrapper);
                    }
                    else if (element is SpatialElement)
                    {
                        SpatialElement spatialElem = element as SpatialElement;
                        SpatialElementExporter.ExportSpatialElement(exporterIFC, spatialElem, productWrapper);
                    }
                    else if (IsStairs(element))
                    {
                        StairsExporter.Export(exporterIFC, element, geomElem, productWrapper);
                    }
                    else if (element is TextNote)
                    {
                        TextNote textNote = element as TextNote;
                        TextNoteExporter.Export(exporterIFC, textNote, productWrapper);
                    }
                    else if (element is TopographySurface)
                    {
                        TopographySurface topSurface = element as TopographySurface;
                        SiteExporter.ExportTopographySurface(exporterIFC, topSurface, geomElem, productWrapper);
                    }
                    else if (element is Truss)
                    {
                        if (ExporterCacheManager.TrussCache.Contains(element.Id))
                            AssemblyInstanceExporter.ExportTrussElement(exporterIFC, element as Truss, productWrapper);
                        else
                        {
                            ExporterCacheManager.TrussCache.Add(element.Id);
                            shouldPreserveParameterCache = true;
                        }
                    }
                    else if (element is Wall)
                    {
                        Wall wallElem = element as Wall;
                        WallExporter.Export(exporterIFC, wallElem, geomElem, productWrapper);
                    }
                    else if (element is WallSweep)
                    {
                        WallSweep wallSweep = element as WallSweep;
                        WallSweepExporter.Export(exporterIFC, wallSweep, geomElem, productWrapper);
                    }
                    else if (element is Zone)
                    {
                        if (ExporterCacheManager.ZoneCache.Contains(element.Id))
                            ZoneExporter.ExportZone(exporterIFC, element as Zone, productWrapper);
                        else
                        {
                            ExporterCacheManager.ZoneCache.Add(element.Id);
                            shouldPreserveParameterCache = true;
                        }
                    }
                    else
                    {
                        string ifcEnumType;
                        IFCExportType exportType = ExporterUtil.GetExportType(exporterIFC, element, out ifcEnumType);

                        // The intention with the code below is to make this the "generic" element exporter, which would export any Revit element as any IFC instance.
                        // We would then in addition have specialized functions that would convert specific Revit elements to specific IFC instances where extra information
                        // could be gathered from the element.
                        bool exported = false;
                        if (IsMEPType(exporterIFC, element, exportType))
                           exported = GenericMEPExporter.Export(exporterIFC, element, geomElem, exportType, ifcEnumType, productWrapper);
                        else if (ExportAsProxy(element, exportType))
                           exported = ProxyElementExporter.Export(exporterIFC, element, geomElem, productWrapper);
                        else if ((element is HostObject) || (element is DirectShape))
                        {
                           // This is intended to work for any element.  However, there are some hidden elements that we likely want to ignore.
                           // As such, this is currently limited to the two types of elements that we know we want to export that aren't covered above.
                           // Note the general comment that we would like to revamp this whole routine to be cleaner and simpler.
                     // Note 2: Known lists of DirectShapes that aren't exported:
                     // 1. IfcSpace (roundtripped IFC spaces).
                     // 2. Railings
                           exported = FamilyInstanceExporter.ExportGenericBuildingElement(exporterIFC, element, geomElem, exportType, ifcEnumType, productWrapper);
                        }

                        // For ducts and pipes, we will add a IfcRelCoversBldgElements during the end of export.
                        if (exported && (element is Duct || element is Pipe))
                            ExporterCacheManager.MEPCache.CoveredElementsCache.Add(element.Id);
                    }

                    if (element.AssemblyInstanceId != ElementId.InvalidElementId)
                        ExporterCacheManager.AssemblyInstanceCache.RegisterElements(element.AssemblyInstanceId, productWrapper);
                    if (element.GroupId != ElementId.InvalidElementId)
                        ExporterCacheManager.GroupCache.RegisterElements(element.GroupId, productWrapper);

                    st.RollBack();
                }
            }
            finally
            {
                exporterIFC.PopExportState();
                ExporterStateManager.PreserveElementParameterCache(element, shouldPreserveParameterCache);
            }
        }
        /// <summary>
        /// Implements the export of element.
        /// </summary>
        /// <param name="exporterIFC">The IFC exporter object.</param>
        /// <param name="element ">The element to export.</param>
        /// <param name="productWrapper">The IFCProductWrapper object.</param>
        private void ExportElementImpl(ExporterIFC exporterIFC, Element element, IFCProductWrapper productWrapper)
        {
            Options options = new Options();
            View ownerView = element.Document.get_Element(element.OwnerViewId) as View;
            if (ownerView != null)
                options.View = ownerView;
            GeometryElement geomElem = element.get_Geometry(options);

            try
            {
                exporterIFC.PushExportState(element, geomElem);

                using (SubTransaction st = new SubTransaction(element.Document))
                {
                    st.Start();

                    if (element is CurveElement)
                    {
                        CurveElement curveElem = element as CurveElement;
                        CurveElementExporter.ExportCurveElement(exporterIFC, curveElem, geomElem, productWrapper, m_CurveAnnotationCache);
                    }
                    else if (element is FamilyInstance)
                    {
                        FamilyInstance familyInstanceElem = element as FamilyInstance;
                        FamilyInstanceExporter.ExportFamilyInstanceElement(exporterIFC, familyInstanceElem, geomElem, productWrapper);
                    }
                    else if (element is Floor)
                    {
                        Floor floorElem = element as Floor;
                        FloorExporter.ExportFloor(exporterIFC, floorElem, geomElem, productWrapper);
                    }
                    else if (element is SpatialElement)
                    {
                        SpatialElement spatialElem = element as SpatialElement;
                        SpatialElementExporter.ExportSpatialElement(exporterIFC, spatialElem, productWrapper);
                    }
                    else if (element is TextNote)
                    {
                        TextNote textNote = element as TextNote;
                        TextNoteExporter.Export(exporterIFC, textNote, productWrapper, m_PresentationStyleCache);
                    }
                    else if (element is Wall)
                    {
                        Wall wallElem = element as Wall;
                        WallExporter.Export(exporterIFC, wallElem, geomElem, productWrapper);
                    }
                    else if (IsMEPType(exporterIFC, element))
                    {
                        GenericMEPExporter.Export(exporterIFC, element, geomElem, productWrapper);
                    }
                    else if (element is FilledRegion)
                    {
                        // FilledRegion is still handled by internal Revit code, but the get_Geometry call makes sure
                        // that the Owner view is clean before we get the region's GeometryElement.
                        ExporterIFCUtils.ExportElementInternal(exporterIFC, element, productWrapper);
                    }

                    st.RollBack();
                }
            }
            finally
            {
                exporterIFC.PopExportState();
            }
        }
Example #18
0
        /// <summary>
        /// Some preparation and check before creating room.
        /// </summary>
        /// <param name="curPhase">Current phase used to create room, all rooms will be created in this phase.</param>
        /// <returns>Number indicates how many new rooms were created.</returns>
        private int RoomCreationStart()
        {
            int nNewRoomsSize = 0;
            // transaction is used to cancel room creation when exception occurs
            SubTransaction myTransaction = new SubTransaction(m_document);

            try
            {
                // Preparation before room creation starts
                Phase curPhase = null;
                if (!RoomCreationPreparation(ref curPhase))
                {
                    return(0);
                }

                // get all existing rooms which have mapped to spreadsheet rooms.
                // we should skip the creation for those spreadsheet rooms which have been mapped by Revit rooms.
                Dictionary <int, string> existingRooms = new Dictionary <int, string>();
                foreach (Room room in m_roomData.Rooms)
                {
                    Parameter sharedParameter = room.LookupParameter(RoomsData.SharedParam);
                    if (null != sharedParameter && false == String.IsNullOrEmpty(sharedParameter.AsString()))
                    {
                        existingRooms.Add(room.Id.IntegerValue, sharedParameter.AsString());
                    }
                }

                #region Rooms Creation and Set
                myTransaction.Start();
                // create rooms with spread sheet based rooms data
                for (int row = 0; row < m_spreadRoomsTable.Rows.Count; row++)
                {
                    // get the ID column value and use it to check whether this spreadsheet room is mapped by Revit room.
                    String externaId = m_spreadRoomsTable.Rows[row][RoomsData.RoomID].ToString();
                    if (existingRooms.ContainsValue(externaId))
                    {
                        // skip the spreadsheet room creation if it's mapped by Revit room
                        continue;
                    }

                    // create rooms in specified phase, but without placing them.
                    Room newRoom = m_document.Create.NewRoom(curPhase);
                    if (null == newRoom)
                    {
                        // abort the room creation and pop up failure message
                        myTransaction.RollBack();

                        MyMessageBox("Create room failed.", MessageBoxIcon.Warning);
                        return(0);
                    }

                    // set the shared parameter's value of Revit room
                    Parameter sharedParam = newRoom.LookupParameter(RoomsData.SharedParam);
                    if (null == sharedParam)
                    {
                        // abort the room creation and pop up failure message
                        myTransaction.RollBack();
                        MyMessageBox("Failed to get shared parameter, please try again.", MessageBoxIcon.Warning);
                        return(0);
                    }
                    else
                    {
                        sharedParam.Set(externaId);
                    }

                    // Update this new room with values of spreadsheet
                    UpdateNewRoom(newRoom, row);

                    // remember how many new rooms were created, based on spread sheet data
                    nNewRoomsSize++;
                }

                // end this transaction if create all rooms successfully.
                myTransaction.Commit();
                #endregion
            }
            catch (Exception ex)
            {
                // cancel this time transaction when exception occurs
                if (myTransaction.HasStarted())
                {
                    myTransaction.RollBack();
                }

                MyMessageBox(ex.Message, MessageBoxIcon.Warning);
                return(0);
            }

            // output unplaced rooms creation message
            String strMessage    = string.Empty;
            int    nSkippedRooms = m_spreadRoomsTable.Rows.Count - nNewRoomsSize;
            if (nSkippedRooms > 0)
            {
                strMessage = string.Format("{0} unplaced {1} created successfully.\r\n{2} skipped, {3}",
                                           nNewRoomsSize,
                                           (nNewRoomsSize > 1) ? ("rooms were") : ("room was"),
                                           nSkippedRooms.ToString() + ((nSkippedRooms > 1) ? (" were") : (" was")),
                                           (nSkippedRooms > 1) ? ("because they were already mapped by Revit rooms.") :
                                           ("because it was already mapped by Revit rooms."));
            }
            else
            {
                strMessage = string.Format("{0} unplaced {1} created successfully.",
                                           nNewRoomsSize,
                                           (nNewRoomsSize > 1) ? ("rooms were") : ("room was"));
            }

            // output creation message
            MyMessageBox(strMessage, MessageBoxIcon.Information);
            return(nNewRoomsSize);
        }
Example #19
0
        public QaqcRLSRequest(UIApplication uiApp, String text)
        {
            MainUI       uiForm = BARevitTools.Application.thisApp.newMainUi;
            DataGridView dgv    = uiForm.qaqcRLSDataGridView;
            RVTDocument  doc    = uiApp.ActiveUIDocument.Document;

            List <ElementId> unswitchableElements = new List <ElementId>();

            //Creating a DataTable for this tool's operations
            DataTable  dt = new DataTable();
            DataColumn elementIdColumn = dt.Columns.Add("Element Id", typeof(ElementId));
            DataColumn groupNameColumn = dt.Columns.Add("Group Name", typeof(String));

            if (uiForm.qaqcRLSReplaceComboBox.Text == "<Replace>")
            {
                //If the user has not selected a line style to replace, remind them
                MessageBox.Show("Select the line style to replace");
            }
            else if (uiForm.qaqcRLSReplaceWithComboBox.Text == "<With>")
            {
                //If the user has not selected a line style to use as a replacement, remind them
                MessageBox.Show("Select the line style to replace with");
            }
            else
            {
                //Otherwise, they did a good job following instructions and they can continue. Get the line styles to use from the dictionary
                Category replaceStyle     = uiForm.qaqcLineStyleDict[uiForm.qaqcRLSReplaceComboBox.Text.ToString()];
                Category replaceWithStyle = uiForm.qaqcLineStyleDict[uiForm.qaqcRLSReplaceWithComboBox.Text.ToString()];
                //The Projection style is needed from the line style to use in the replacement
                GraphicsStyle setStyle = replaceWithStyle.GetGraphicsStyle(GraphicsStyleType.Projection);

                //Start a new transaction
                Transaction t1 = new Transaction(doc, "ConvertLines");
                t1.Start();

                //Collect all of the lines in the project, then cycle through them
                var lineCollector = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Lines).ToElements();
                foreach (CurveElement elem in lineCollector)
                {
                    //Get the name of the line style and the GroupId of the group it belongs to
                    string    lineStyleName = elem.LineStyle.Name;
                    ElementId groupId       = elem.GroupId;

                    //If the name of the line style is the same as the one to replace, and its GroupId is -1 (no group), continue
                    if (lineStyleName == uiForm.qaqcRLSReplaceComboBox.Text.ToString() && Convert.ToInt32(elem.GroupId.ToString()) == -1)
                    {
                        //Create a boolean variable to save the pinned state
                        bool wasPinned = false;

                        //If the line is pinned, unpin it and set the wasPinned variable to true
                        if (elem.Pinned)
                        {
                            elem.Pinned = false;
                            wasPinned   = true;
                        }

                        //Then, set the line's line style to the style to use in the replacement
                        try
                        {
                            elem.LineStyle = setStyle;
                        }
                        catch (Exception e)
                        {
                            //If it could not be switched, add it to the list
                            MessageBox.Show(e.ToString());
                            unswitchableElements.Add(elem.Id);
                            continue;
                        }

                        //If the line had been pinned, repin it
                        if (wasPinned)
                        {
                            elem.Pinned = true;
                        }
                    }

                    //If the line style matched the name of the line style to replace, but it belonged to a group, add the line to the list of elements that could not be switched
                    else if (lineStyleName == uiForm.qaqcRLSReplaceComboBox.Text.ToString() && Convert.ToInt32(elem.GroupId.ToString()) != -1)
                    {
                        unswitchableElements.Add(elem.Id);
                    }
                    else
                    {
                        continue;
                    }
                }
                t1.Commit();

                //Start another transaction
                Transaction t2 = new Transaction(doc, "ReplaceRegions");
                t2.Start();
                //Next, evaluate all filled regions for their sketch boundary lines
                var regionCollector = new FilteredElementCollector(doc).OfClass(typeof(FilledRegion)).ToElements().ToList();
                foreach (FilledRegion region in regionCollector)
                {
                    //Get the ID of the filled region
                    ElementId regionId = region.Id;
                    //Start a subtransaction because the region must be deleted to get the sketch lines that were deleted.
                    SubTransaction st2 = new SubTransaction(doc);
                    st2.Start();
                    //Collect the list of element Ids deleted from the deletion
                    List <ElementId> deletedIds = doc.Delete(regionId).ToList();
                    //Roll back the subtransaction to undelete the filled region
                    st2.RollBack();

                    //Now we know what sketch lines belong to the filled region. Evaluate each ElementId from the subtransaction
                    foreach (ElementId id in deletedIds)
                    {
                        Element regionSubElem = doc.GetElement(id);
                        //Determine if the element is a detail line
                        if (regionSubElem.GetType().ToString() == "Autodesk.Revit.DB.DetailLine")
                        {
                            //If it is a detail line, get the curve of the line, then its line style name
                            CurveElement curveElement        = regionSubElem as CurveElement;
                            string       sketchLineStyleName = curveElement.LineStyle.Name;
                            //If the line style name matches the name of the line style to replace, and the region does not belong to a group, continue
                            if (sketchLineStyleName == uiForm.qaqcRLSReplaceComboBox.Text.ToString() && Convert.ToInt32(region.GroupId.ToString()) == -1)
                            {
                                //Again, determin if the region was pinned, just like the lines
                                bool wasPinned = false;
                                if (region.Pinned)
                                {
                                    region.Pinned = false;
                                    wasPinned     = true;
                                }

                                try
                                {
                                    //Change the line style of the curve
                                    curveElement.LineStyle = setStyle;
                                    XYZ z = XYZ.BasisZ;
                                    //Then, move the region up and then down in the Z axis to cause a redraw.
                                    ElementTransformUtils.MoveElement(doc, region.Id, z);
                                    ElementTransformUtils.MoveElement(doc, region.Id, -z);
                                }
                                catch (Exception e)
                                {
                                    //If the region's sketch lines could not be switched, add it to the list of elements that could not be switched
                                    MessageBox.Show(e.ToString());
                                    unswitchableElements.Add(region.Id);
                                    continue;
                                }

                                if (wasPinned)
                                {
                                    region.Pinned = true;
                                }
                            }
                            //If the region belonged to a group, add it to the list of elements that could not be switched immediately
                            else if (sketchLineStyleName == uiForm.qaqcRLSReplaceComboBox.Text.ToString() && Convert.ToInt32(region.GroupId.ToString()) != -1)
                            {
                                unswitchableElements.Add(region.Id);
                                continue;
                            }
                            else
                            {
                                continue;
                            }
                        }
                        else
                        {
                            continue;
                        }
                    }
                }
                t2.Commit();

                //Now, for each element in the unswitchableElements list...
                foreach (ElementId elemId in unswitchableElements)
                {
                    //Create a new row and fill it out with the ElementId and group name if it exists
                    DataRow row = dt.NewRow();
                    row["Element Id"] = elemId;
                    if (doc.GetElement(elemId).GroupId.IntegerValue != -1)
                    {
                        row["Group Name"] = doc.GetElement(doc.GetElement(elemId).GroupId).Name;
                    }
                    else
                    {
                        row["Group Name"] = "";
                    }
                    dt.Rows.Add(row);
                }

                //Bind the DataTable to the DataGridView
                BindingSource bs = new BindingSource();
                bs.DataSource  = dt;
                dgv.DataSource = bs;
                //Turn off the blank column at the beginning of the rows
                dgv.RowHeadersVisible = false;
                //Set the row selection to be full row selection
                dgv.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
                //Sort the rows by the group name
                dgv.Sort(dgv.Columns["Group Name"], ListSortDirection.Ascending);

                //If the user wanted to delete the line styles, and nothing is preventing it because the DataTable has no rows, continue
                if (uiForm.qaqcRLSDeleteCheckBox.Checked && dt.Rows.Count == 0)
                {
                    //New transaction
                    Transaction t = new Transaction(doc, String.Format("Delete{0}", replaceStyle.Name));
                    t.Start();
                    try
                    {
                        //Delete the linestyle
                        doc.Delete(replaceStyle.Id);
                        t.Commit();
                        //Reset the combo boxes from the MainUI and reset them with new data of existing Line Styles
                        uiForm.qaqcRLSReplaceComboBox.Text = "<Replace>";
                        uiForm.qaqcRLSReplaceComboBox.Items.Clear();
                        uiForm.qaqcRLSReplaceWithComboBox.Items.Clear();
                        uiForm.qaqcRLSReplaceWithComboBox.Text = "<With>";
                        uiForm.QaqcRLSSetReplaceComboBox(uiForm, doc);
                    }
                    catch
                    {
                        //If the deletion fails, roll back the transaction and let the user know
                        t.RollBack();
                        MessageBox.Show(String.Format("Could not delete {0}", replaceStyle.Name));
                    }
                }
                else
                {
                    //If there were instances that could not be switched, report this to the user, and instruct them to check the table for the groups where the instances occur
                    MessageBox.Show(String.Format("Could not delete {0} because {1} instances could not be switched. See the the table for instances in groups +" +
                                                  "that could not be switched.", replaceStyle.Name, dgv.Rows.Count.ToString()));
                }
            }
        }
        /// <summary>
        /// Export spatial elements, including rooms, areas and spaces. 2nd level space boundaries.
        /// </summary>
        /// <param name="ifcExporter">
        /// The Exporter object.
        /// </param>
        /// <param name="exporterIFC">
        /// The ExporterIFC object.
        /// </param>
        /// <param name="document">
        /// The Revit document.
        /// </param>
        /// <param name="filterView">
        /// The view not exported.
        /// </param>
        /// <param name="spaceExported">
        /// The output boolean value indicates if exported successfully.
        /// </param>
        public static void ExportSpatialElement2ndLevel(BIM.IFC.Exporter.Exporter ifcExporter, ExporterIFC exporterIFC, Document document, View filterView)
        {
            using (SubTransaction st = new SubTransaction(document))
            {
                st.Start();

                bool createEnergyAnalysisDetailModelFailed = false;
                EnergyAnalysisDetailModel model = null;
                try
                {
                    IFCFile file = exporterIFC.GetFile();
                    using (IFCTransaction tr = new IFCTransaction(file))
                    {

                        EnergyAnalysisDetailModelOptions options = new EnergyAnalysisDetailModelOptions();
                        options.Tier = EnergyAnalysisDetailModelTier.SecondLevelBoundaries; //2nd level space boundaries
                        options.SimplifyCurtainSystems = true;
                        try
                        {
                            model = EnergyAnalysisDetailModel.Create(document, options);
                        }
                        catch (Exception)
                        {
                            createEnergyAnalysisDetailModelFailed = true;
                            throw;
                        }
                        IList<EnergyAnalysisSpace> spaces = model.GetAnalyticalSpaces();

                        foreach (EnergyAnalysisSpace space in spaces)
                        {
                            SpatialElement spatialElement = document.get_Element(space.SpatialElementId) as SpatialElement;

                            if (spatialElement == null)
                                continue;

                            //quick reject
                            bool isArea = spatialElement is Area;
                            if (isArea)
                            {
                                if (!IsAreaGrossInterior(exporterIFC, spatialElement))
                                    continue;
                            }

                            //current view only
                            if (filterView != null && !ElementFilteringUtil.IsElementVisible(filterView, spatialElement))
                                continue;
                            //

                            if (!ElementFilteringUtil.ShouldCategoryBeExported(exporterIFC, spatialElement))
                                continue;

                            Options geomOptions = new Options();
                            View ownerView = spatialElement.Document.get_Element(spatialElement.OwnerViewId) as View;
                            if (ownerView != null)
                                geomOptions.View = ownerView;
                            GeometryElement geomElem = spatialElement.get_Geometry(geomOptions);

                            try
                            {
                                exporterIFC.PushExportState(spatialElement, geomElem);

                                using (IFCProductWrapper productWrapper = IFCProductWrapper.Create(exporterIFC, true))
                                {
                                    ElementId levelId = spatialElement.Level != null ? spatialElement.Level.Id : ElementId.InvalidElementId;
                                    using (IFCPlacementSetter setter = IFCPlacementSetter.Create(exporterIFC, spatialElement, null, null, levelId))
                                    {
                                        try
                                        {
                                            CreateIFCSpace(exporterIFC, spatialElement, productWrapper, setter);
                                        }
                                        catch (System.Exception)
                                        {
                                            continue;
                                        }
                                        //get boundary information from surfaces
                                        IList<EnergyAnalysisSurface> surfaces = space.GetAnalyticalSurfaces();
                                        foreach (EnergyAnalysisSurface surface in surfaces)
                                        {
                                            Element boundingElement = GetBoundaryElement(document, surface.OriginatingElementId);
                                            if (boundingElement == null)
                                                continue;

                                            IList<EnergyAnalysisOpening> openings = surface.GetAnalyticalOpenings();
                                            IFCAnyHandle connectionGeometry = CreateConnectionSurfaceGeometry(file, surface, openings);
                                            CreateIFCSpaceBoundary(file, exporterIFC, spatialElement, boundingElement, connectionGeometry);

                                            // try to add doors and windows for host objects if appropriate.
                                            if (boundingElement is HostObject)
                                            {
                                                foreach (EnergyAnalysisOpening opening in openings)
                                                {
                                                    Element openingBoundingElem = GetBoundaryElement(document, opening.OriginatingElementId);
                                                    IFCAnyHandle openingConnectionGeom = CreateConnectionSurfaceGeometry(file, opening);
                                                    CreateIFCSpaceBoundary(file, exporterIFC, spatialElement, openingBoundingElem, openingConnectionGeom);
                                                }
                                            }
                                        }
                                        ExporterIFCUtils.CreateSpatialElementPropertySet(exporterIFC, spatialElement, productWrapper);
                                        ifcExporter.ExportElementProperties(exporterIFC, spatialElement, productWrapper);
                                        ifcExporter.ExportElementQuantities(exporterIFC, spatialElement, productWrapper);
                                    }
                                }
                            }
                            finally
                            {
                                exporterIFC.PopExportState();
                            }
                        }
                        tr.Commit();
                    }
                }
                catch (System.Exception ex)
                {
                    document.Application.WriteJournalComment("IFC error: " + ex.ToString(), true);
                }
                finally
                {
                    if (model != null)
                        EnergyAnalysisDetailModel.Destroy(model);
                }

                //if failed, just export the space element
                if (createEnergyAnalysisDetailModelFailed)
                {
                    IFCFile file = exporterIFC.GetFile();
                    using (IFCTransaction tr = new IFCTransaction(file))
                    {
                        ElementFilter spatialElementFilter = ElementFilteringUtil.GetSpatialElementFilter(document, exporterIFC);
                        FilteredElementCollector collector = (filterView == null) ? new FilteredElementCollector(document) : new FilteredElementCollector(document, filterView.Id);
                        collector.WherePasses(spatialElementFilter);
                        foreach (Element elem in collector)
                        {
                            SpatialElement spatialElement = elem as SpatialElement;

                            if (spatialElement == null)
                                continue;

                            //current view only
                            if (filterView != null && !ElementFilteringUtil.IsElementVisible(filterView, spatialElement))
                                continue;
                            //
                            if (!ElementFilteringUtil.ShouldCategoryBeExported(exporterIFC, spatialElement))
                                continue;

                            Options geomOptions = new Options();
                            View ownerView = spatialElement.Document.get_Element(spatialElement.OwnerViewId) as View;
                            if (ownerView != null)
                                geomOptions.View = ownerView;
                            GeometryElement geomElem = spatialElement.get_Geometry(geomOptions);

                            try
                            {
                                exporterIFC.PushExportState(spatialElement, geomElem);

                                using (IFCProductWrapper productWrapper = IFCProductWrapper.Create(exporterIFC, true))
                                {
                                    ElementId levelId = spatialElement.Level != null ? spatialElement.Level.Id : ElementId.InvalidElementId;
                                    using (IFCPlacementSetter setter = IFCPlacementSetter.Create(exporterIFC, spatialElement, null, null, levelId))
                                    {
                                        try
                                        {
                                            CreateIFCSpace(exporterIFC, spatialElement, productWrapper, setter);
                                        }
                                        catch (System.Exception)
                                        {
                                            continue;
                                        }
                                        if (!(spatialElement is Area))
                                            ExporterIFCUtils.CreateSpatialElementPropertySet(exporterIFC, spatialElement, productWrapper);
                                        ifcExporter.ExportElementProperties(exporterIFC, spatialElement, productWrapper);
                                        ifcExporter.ExportElementQuantities(exporterIFC, spatialElement, productWrapper);
                                    }
                                }
                            }
                            finally
                            {
                                exporterIFC.PopExportState();
                            }
                        }
                        tr.Commit();
                    }
                }
                st.RollBack();
            }
        }
Example #21
0
        /// <summary>
        /// Compute the Eastings, Northings, OrthogonalHeight from the selected SiteTransformationBasis
        /// </summary>
        /// <param name="doc">The document</param>
        /// <param name="wcsBasis">The selected coordinate base</param>
        /// <returns>A Tuple for Eastings, Northings, and OrthogonalHeight</returns>
        public static (double eastings, double northings, double orthogonalHeight, double angleTN, double origAngleTN) GeoReferenceInformation
            (Document doc, SiteTransformBasis wcsBasis, ProjectLocation projLocation = null)
        {
            double eastings         = 0.0;
            double northings        = 0.0;
            double orthogonalHeight = 0.0;
            double angleTN          = 0.0;
            double origAngleTN      = 0.0;

            using (Transaction tr = new Transaction(doc))
            {
                try
                {
                    tr.Start("Temp Project Location change");
                }
                catch { }

                using (SubTransaction tempSiteLocTr = new SubTransaction(doc))
                {
                    tempSiteLocTr.Start();
                    if (projLocation != null)
                    {
                        doc.ActiveProjectLocation = projLocation;
                    }

                    BasePoint surveyPoint      = BasePoint.GetSurveyPoint(doc);
                    BasePoint projectBasePoint = BasePoint.GetProjectBasePoint(doc);
                    (double svNorthings, double svEastings, double svElevation, double svAngle, double pbNorthings,
                     double pbEastings, double pbElevation, double pbAngle) = ProjectLocationInfo(doc, surveyPoint.Position, projectBasePoint.Position);
                    origAngleTN = pbAngle;

                    switch (wcsBasis)
                    {
                    case SiteTransformBasis.Internal:
                        Transform rotationTrfAtInternal = Transform.CreateRotationAtPoint(new XYZ(0, 0, 1), svAngle, XYZ.Zero);
                        XYZ       intPointOffset        = rotationTrfAtInternal.OfPoint(surveyPoint.Position);
                        northings        = svNorthings - intPointOffset.Y;
                        eastings         = svEastings - intPointOffset.X;
                        orthogonalHeight = surveyPoint.SharedPosition.Z - surveyPoint.Position.Z;
                        angleTN          = -svAngle;
                        break;

                    case SiteTransformBasis.InternalInTN:
                        rotationTrfAtInternal = Transform.CreateRotationAtPoint(new XYZ(0, 0, 1), svAngle, XYZ.Zero);
                        intPointOffset        = rotationTrfAtInternal.OfPoint(surveyPoint.Position);
                        northings             = svNorthings - intPointOffset.Y;
                        eastings         = svEastings - intPointOffset.X;
                        orthogonalHeight = surveyPoint.SharedPosition.Z - surveyPoint.Position.Z;
                        angleTN          = 0.0;
                        break;

                    case SiteTransformBasis.Project:
                        northings        = pbNorthings;
                        eastings         = pbEastings;
                        orthogonalHeight = pbElevation;
                        angleTN          = -pbAngle;
                        break;

                    case SiteTransformBasis.ProjectInTN:
                        northings        = pbNorthings;
                        eastings         = pbEastings;
                        orthogonalHeight = pbElevation;
                        angleTN          = 0.0;
                        break;

                    case SiteTransformBasis.Shared:
                        northings        = 0.0;
                        eastings         = 0.0;
                        orthogonalHeight = 0.0;
                        angleTN          = 0.0;
                        break;

                    case SiteTransformBasis.Site:
                        northings        = svNorthings;
                        eastings         = svEastings;
                        orthogonalHeight = svElevation;
                        angleTN          = 0.0;
                        break;

                    default:
                        northings        = 0.0;
                        eastings         = 0.0;
                        orthogonalHeight = 0.0;
                        angleTN          = 0.0;
                        break;
                    }
                    tempSiteLocTr.RollBack();
                }
            }

            return(eastings, northings, orthogonalHeight, angleTN, origAngleTN);
        }
        /// <summary>
        /// Implements the export of element.
        /// </summary>
        /// <param name="exporterIFC">The IFC exporter object.</param>
        /// <param name="element">The element to export.</param>
        /// <param name="filterView">The view to export, if it exists.</param>
        /// <param name="productWrapper">The ProductWrapper object.</param>
        public virtual void ExportElementImpl(ExporterIFC exporterIFC, Element element, Autodesk.Revit.DB.View filterView,
            ProductWrapper productWrapper)
        {
            Options options;
            View ownerView = element.Document.GetElement(element.OwnerViewId) as View;
            if (ownerView == null)
            {
                options = GeometryUtil.GetIFCExportGeometryOptions();
            }
            else
            {
                options = new Options();
                options.View = ownerView;
            }
            GeometryElement geomElem = element.get_Geometry(options);

            try
            {
                exporterIFC.PushExportState(element, geomElem);

                using (SubTransaction st = new SubTransaction(element.Document))
                {
                    st.Start();

                    if (element is AssemblyInstance)
                    {
                        AssemblyInstance assemblyInstance = element as AssemblyInstance;
                        AssemblyInstanceExporter.ExportAssemblyInstanceElement(exporterIFC, assemblyInstance, productWrapper);
                    }
                    else if (element is Ceiling)
                    {
                        Ceiling ceiling = element as Ceiling;
                        CeilingExporter.ExportCeilingElement(exporterIFC, ceiling, geomElem, productWrapper);
                    }
                    else if (element is CeilingAndFloor || element is Floor)
                    {
                        // This covers both Floors and Building Pads.
                        HostObject hostObject = element as HostObject;
                        FloorExporter.Export(exporterIFC, hostObject, geomElem, productWrapper);
                    }
                    else if (element is ContFooting)
                    {
                        ContFooting footing = element as ContFooting;
                        FootingExporter.ExportFootingElement(exporterIFC, footing, geomElem, productWrapper);
                    }
                    else if (element is CurveElement)
                    {
                        CurveElement curveElem = element as CurveElement;
                        CurveElementExporter.ExportCurveElement(exporterIFC, curveElem, geomElem, productWrapper);
                    }
                    else if (element is DuctInsulation)
                    {
                        DuctInsulation ductInsulation = element as DuctInsulation;
                        DuctInsulationExporter.ExportDuctInsulation(exporterIFC, ductInsulation, geomElem, productWrapper);
                    }
                    else if (element is DuctLining)
                    {
                        DuctLining ductLining = element as DuctLining;
                        DuctLiningExporter.ExportDuctLining(exporterIFC, ductLining, geomElem, productWrapper);
                    }
                    else if (element is FamilyInstance)
                    {
                        FamilyInstance familyInstanceElem = element as FamilyInstance;
                        FamilyInstanceExporter.ExportFamilyInstanceElement(exporterIFC, familyInstanceElem, geomElem, productWrapper);
                    }
                    else if (element is FilledRegion)
                    {
                        FilledRegion filledRegion = element as FilledRegion;
                        FilledRegionExporter.Export(exporterIFC, filledRegion, geomElem, productWrapper);
                    }
                    else if (element is Grid)
                    {
                        ExporterCacheManager.GridCache.Add(element);
                    }
                    else if (element is HostedSweep)
                    {
                        HostedSweep hostedSweep = element as HostedSweep;
                        HostedSweepExporter.Export(exporterIFC, hostedSweep, geomElem, productWrapper);
                    }
                    else if (element is Part)
                    {
                        Part part = element as Part;
                        if (ExporterCacheManager.ExportOptionsCache.ExportPartsAsBuildingElements)
                            PartExporter.ExportPartAsBuildingElement(exporterIFC, part, geomElem, productWrapper);
                        else
                            PartExporter.ExportStandalonePart(exporterIFC, part, geomElem, productWrapper);
                    }
                    else if (element is Railing)
                    {
                        if (ExporterCacheManager.RailingCache.Contains(element.Id))
                            RailingExporter.ExportRailingElement(exporterIFC, element as Railing, productWrapper);
                        else
                        {
                            ExporterCacheManager.RailingCache.Add(element.Id);
                            RailingExporter.AddSubElementsToCache(element as Railing);
                        }
                    }
                    else if (RampExporter.IsRamp(element))
                    {
                        RampExporter.Export(exporterIFC, element, geomElem, productWrapper);
                    }
                    else if (element is Rebar || element is AreaReinforcement || element is PathReinforcement)
                    {
                        RebarExporter.Export(exporterIFC, element, filterView, productWrapper);
                    }
                    else if (element is SpatialElement)
                    {
                        SpatialElement spatialElem = element as SpatialElement;
                        SpatialElementExporter.ExportSpatialElement(exporterIFC, spatialElem, productWrapper);
                    }
                    else if (IsStairs(element))
                    {
                        StairsExporter.Export(exporterIFC, element, geomElem, productWrapper);
                    }
                    else if (element is TextNote)
                    {
                        TextNote textNote = element as TextNote;
                        TextNoteExporter.Export(exporterIFC, textNote, productWrapper);
                    }
                    else if (element is TopographySurface)
                    {
                        TopographySurface topSurface = element as TopographySurface;
                        SiteExporter.ExportTopographySurface(exporterIFC, topSurface, geomElem, productWrapper);
                    }
                    else if (element is Wall)
                    {
                        Wall wallElem = element as Wall;
                        WallExporter.Export(exporterIFC, wallElem, geomElem, productWrapper);
                    }
                    else if (element is FaceWall)
                    {
                        WallExporter.ExportWall(exporterIFC, element, geomElem, productWrapper);
                    }
                    else if (element is WallSweep)
                    {
                        WallSweep wallSweep = element as WallSweep;
                        WallSweepExporter.Export(exporterIFC, wallSweep, geomElem, productWrapper);
                    }
                    else if (element is RoofBase)
                    {
                        RoofBase roofElement = element as RoofBase;
                        RoofExporter.Export(exporterIFC, roofElement, geomElem, productWrapper);
                    }
                    else if (element is CurtainSystem)
                    {
                        CurtainSystem curtainSystem = element as CurtainSystem;
                        CurtainSystemExporter.ExportCurtainSystem(exporterIFC, curtainSystem, productWrapper);
                    }
                    else if (CurtainSystemExporter.IsLegacyCurtainElement(element))
                    {
                        CurtainSystemExporter.ExportLegacyCurtainElement(exporterIFC, element, productWrapper);
                        PropertyUtil.CreateInternalRevitPropertySets(exporterIFC, element, productWrapper);
                    }
                    else
                    {
                        string ifcEnumType;
                        IFCExportType exportType = ExporterUtil.GetExportType(exporterIFC, element, out ifcEnumType);

                        if (IsMEPType(exporterIFC, element, exportType))
                        {
                            GenericMEPExporter.Export(exporterIFC, element, geomElem, productWrapper);
                        }
                        else if (ExportAsProxy(element, exportType))
                        {
                            ProxyElementExporter.Export(exporterIFC, element, geomElem, productWrapper);
                        }
                    }

                    if (element.AssemblyInstanceId != ElementId.InvalidElementId)
                        ExporterCacheManager.AssemblyInstanceCache.RegisterElements(element.AssemblyInstanceId, productWrapper);

                    st.RollBack();
                }
            }
            finally
            {
                exporterIFC.PopExportState();
            }
        }
Example #23
0
        void SetTangentLockInProfileSketch1(
            Document famdoc,
            Form [] extrusions)
        {
            ICollection <ElementId> delIds = null;
            List <ElementId>        enmIDs = new List <ElementId>();

            using (SubTransaction delTrans = new SubTransaction(famdoc))
            {
                try
                {
                    delTrans.Start();
                    delIds = famdoc.Delete(extrusions[0].Id);
                    delTrans.RollBack();
                }
                catch (Exception ex)
                {
                    System.Windows.MessageBox.Show(ex.ToString());
                }
            }

            // Get the model lines in the profile and use the
            // end points for reference the sketch dimensions diameter

            List <ModelArc>  mArcsR1 = new List <ModelArc>();
            List <ModelArc>  mArcsR2 = new List <ModelArc>();
            List <ModelLine> mLines  = new List <ModelLine>();

            foreach (ElementId id in delIds)
            {
                enmIDs.Add(id);
            }

            for (int i = 0; i < enmIDs.Count; i++)
            {
                Element ele = famdoc.GetElement(enmIDs[i]);
                if (ele is ModelArc)
                {
                    ModelArc ma = ele as ModelArc;
                    Curve    c  = ma.GeometryCurve;
                    Arc      a  = c as Arc;

                    if (Math.Round(r1, 6) == Math.Round(a.Radius, 6))
                    {
                        mArcsR1.Add(ma);
                    }
                    if (Math.Round(r2, 6) == Math.Round(a.Radius, 6))
                    {
                        mArcsR2.Add(ma);
                    }
                }
                if (ele is ModelLine)
                {
                    ModelLine ml       = ele as ModelLine;
                    Element   before   = null;
                    Element   after    = null;
                    ElementId beforeId = null;
                    ElementId afterId  = null;

                    if (i > 0)
                    {
                        before   = famdoc.GetElement(enmIDs[i - 1]);
                        beforeId = enmIDs[i - 1];
                    }
                    else
                    {
                        before   = famdoc.GetElement(enmIDs[enmIDs.Count - 1]);
                        beforeId = enmIDs[enmIDs.Count - 1];
                    }
                    if (i == enmIDs.Count - 1)
                    {
                        after   = famdoc.GetElement(enmIDs[0]);
                        afterId = enmIDs[0];
                    }
                    else
                    {
                        after   = famdoc.GetElement(enmIDs[i + 1]);
                        afterId = enmIDs[i + 1];
                    }

                    if (before is ModelArc && after is ModelArc)
                    {
                        ml.SetTangentLock(0, beforeId, true);
                        ml.SetTangentLock(1, afterId, true);
                    }
                }
            }
        }
Example #24
0
        /// <summary>
        /// Implements the export of element.
        /// </summary>
        /// <param name="exporterIFC">The IFC exporter object.</param>
        /// <param name="element">The element to export.</param>
        /// <param name="productWrapper">The ProductWrapper object.</param>
        public virtual void ExportElementImpl(ExporterIFC exporterIFC, Element element, ProductWrapper productWrapper)
        {
            Options options;
            View ownerView = element.Document.GetElement(element.OwnerViewId) as View;
            if (ownerView == null)
            {
                options = GeometryUtil.GetIFCExportGeometryOptions();
            }
            else
            {
                options = new Options();
                options.View = ownerView;
            }
            GeometryElement geomElem = element.get_Geometry(options);

            // Default: we don't preserve the element parameter cache after export.
            bool shouldPreserveParameterCache = false;

            try
            {
                exporterIFC.PushExportState(element, geomElem);

                Autodesk.Revit.DB.Document doc = element.Document;
                using (SubTransaction st = new SubTransaction(doc))
                {
                    st.Start();

                    // A long list of supported elements.  Please keep in alphabetical order.
                    if (element is AreaReinforcement || element is PathReinforcement || element is Rebar)
                    {
                        RebarExporter.Export(exporterIFC, element, productWrapper);
                    }
                    else if (element is AreaScheme)
                    {
                        AreaSchemeExporter.ExportAreaScheme(exporterIFC, element as AreaScheme, productWrapper);
                    }
                    else if (element is AssemblyInstance)
                    {
                        AssemblyInstance assemblyInstance = element as AssemblyInstance;
                        AssemblyInstanceExporter.ExportAssemblyInstanceElement(exporterIFC, assemblyInstance, productWrapper);
                    }
                    else if (element is BeamSystem)
                    {
                        if (ExporterCacheManager.BeamSystemCache.Contains(element.Id))
                            AssemblyInstanceExporter.ExportBeamSystem(exporterIFC, element as BeamSystem, productWrapper);
                        else
                        {
                            ExporterCacheManager.BeamSystemCache.Add(element.Id);
                            shouldPreserveParameterCache = true;
                        }
                    }
                    else if (element is Ceiling)
                    {
                        Ceiling ceiling = element as Ceiling;
                        CeilingExporter.ExportCeilingElement(exporterIFC, ceiling, geomElem, productWrapper);
                    }
                    else if (element is CeilingAndFloor || element is Floor)
                    {
                        // This covers both Floors and Building Pads.
                        CeilingAndFloor hostObject = element as CeilingAndFloor;
                        FloorExporter.ExportCeilingAndFloorElement(exporterIFC, hostObject, geomElem, productWrapper);
                    }
                    else if (element is ContFooting)
                    {
                        ContFooting footing = element as ContFooting;
                        FootingExporter.ExportFootingElement(exporterIFC, footing, geomElem, productWrapper);
                    }
                    else if (element is CurveElement)
                    {
                        CurveElement curveElem = element as CurveElement;
                        CurveElementExporter.ExportCurveElement(exporterIFC, curveElem, geomElem, productWrapper);
                    }
                    else if (element is CurtainSystem)
                    {
                        CurtainSystem curtainSystem = element as CurtainSystem;
                        CurtainSystemExporter.ExportCurtainSystem(exporterIFC, curtainSystem, productWrapper);
                    }
                    else if (CurtainSystemExporter.IsLegacyCurtainElement(element))
                    {
                        CurtainSystemExporter.ExportLegacyCurtainElement(exporterIFC, element, productWrapper);
                    }
                    else if (element is DuctInsulation)
                    {
                        DuctInsulation ductInsulation = element as DuctInsulation;
                        DuctInsulationExporter.ExportDuctInsulation(exporterIFC, ductInsulation, geomElem, productWrapper);
                    }
                    else if (element is DuctLining)
                    {
                        DuctLining ductLining = element as DuctLining;
                        DuctLiningExporter.ExportDuctLining(exporterIFC, ductLining, geomElem, productWrapper);
                    }
                    else if (element is ElectricalSystem)
                    {
                        ExporterCacheManager.SystemsCache.AddElectricalSystem(element.Id);
                    }
                    else if (element is FabricArea)
                    {
                        // We are exporting the fabric area as a group only.
                        FabricSheetExporter.ExportFabricArea(exporterIFC, element, productWrapper);
                    }
                    else if (element is FabricSheet)
                    {
                        FabricSheet fabricSheet = element as FabricSheet;
                        FabricSheetExporter.ExportFabricSheet(exporterIFC, fabricSheet, geomElem, productWrapper);
                    }
                    else if (element is FaceWall)
                    {
                        WallExporter.ExportWall(exporterIFC, element, null, geomElem, productWrapper);
                    }
                    else if (element is FamilyInstance)
                    {
                        FamilyInstance familyInstanceElem = element as FamilyInstance;
                        FamilyInstanceExporter.ExportFamilyInstanceElement(exporterIFC, familyInstanceElem, geomElem, productWrapper);
                    }
                    else if (element is FilledRegion)
                    {
                        FilledRegion filledRegion = element as FilledRegion;
                        FilledRegionExporter.Export(exporterIFC, filledRegion, geomElem, productWrapper);
                    }
                    else if (element is Grid)
                    {
                        ExporterCacheManager.GridCache.Add(element);
                    }
                    else if (element is Group)
                    {
                        Group group = element as Group;
                        GroupExporter.ExportGroupElement(exporterIFC, group, productWrapper);
                    }
                    else if (element is HostedSweep)
                    {
                        HostedSweep hostedSweep = element as HostedSweep;
                        HostedSweepExporter.Export(exporterIFC, hostedSweep, geomElem, productWrapper);
                    }
                    else if (element is Part)
                    {
                        Part part = element as Part;
                        if (ExporterCacheManager.ExportOptionsCache.ExportPartsAsBuildingElements)
                            PartExporter.ExportPartAsBuildingElement(exporterIFC, part, geomElem, productWrapper);
                        else
                            PartExporter.ExportStandalonePart(exporterIFC, part, geomElem, productWrapper);
                    }
                    else if (element is PipeInsulation)
                    {
                        PipeInsulation pipeInsulation = element as PipeInsulation;
                        PipeInsulationExporter.ExportPipeInsulation(exporterIFC, pipeInsulation, geomElem, productWrapper);
                    }
                    else if (element is Railing)
                    {
                        if (ExporterCacheManager.RailingCache.Contains(element.Id))
                            RailingExporter.ExportRailingElement(exporterIFC, element as Railing, productWrapper);
                        else
                        {
                            ExporterCacheManager.RailingCache.Add(element.Id);
                            RailingExporter.AddSubElementsToCache(element as Railing);
                            shouldPreserveParameterCache = true;
                        }
                    }
                    else if (RampExporter.IsRamp(element))
                    {
                        RampExporter.Export(exporterIFC, element, geomElem, productWrapper);
                    }
                    else if (element is RoofBase)
                    {
                        RoofBase roofElement = element as RoofBase;
                        RoofExporter.Export(exporterIFC, roofElement, geomElem, productWrapper);
                    }
                    else if (element is SpatialElement)
                    {
                        SpatialElement spatialElem = element as SpatialElement;
                        SpatialElementExporter.ExportSpatialElement(exporterIFC, spatialElem, productWrapper);
                    }
                    else if (IsStairs(element))
                    {
                        StairsExporter.Export(exporterIFC, element, geomElem, productWrapper);
                    }
                    else if (element is TextNote)
                    {
                        TextNote textNote = element as TextNote;
                        TextNoteExporter.Export(exporterIFC, textNote, productWrapper);
                    }
                    else if (element is TopographySurface)
                    {
                        TopographySurface topSurface = element as TopographySurface;
                        SiteExporter.ExportTopographySurface(exporterIFC, topSurface, geomElem, productWrapper);
                    }
                    else if (element is Truss)
                    {
                        if (ExporterCacheManager.TrussCache.Contains(element.Id))
                            AssemblyInstanceExporter.ExportTrussElement(exporterIFC, element as Truss, productWrapper);
                        else
                        {
                            ExporterCacheManager.TrussCache.Add(element.Id);
                            shouldPreserveParameterCache = true;
                        }
                    }
                    else if (element is Wall)
                    {
                        Wall wallElem = element as Wall;
                        WallExporter.Export(exporterIFC, wallElem, geomElem, productWrapper);
                    }
                    else if (element is WallSweep)
                    {
                        WallSweep wallSweep = element as WallSweep;
                        WallSweepExporter.Export(exporterIFC, wallSweep, geomElem, productWrapper);
                    }
                    else if (element is Zone)
                    {
                        if (ExporterCacheManager.ZoneCache.Contains(element.Id))
                            ZoneExporter.ExportZone(exporterIFC, element as Zone, productWrapper);
                        else
                        {
                            ExporterCacheManager.ZoneCache.Add(element.Id);
                            shouldPreserveParameterCache = true;
                        }
                    }
                    else
                    {
                        string ifcEnumType;
                        IFCExportType exportType = ExporterUtil.GetExportType(exporterIFC, element, out ifcEnumType);

                        bool exported = false;
                        if (IsMEPType(exporterIFC, element, exportType))
                            exported = GenericMEPExporter.Export(exporterIFC, element, geomElem, exportType, ifcEnumType, productWrapper);
                        else if (ExportAsProxy(element, exportType))
                            exported = ProxyElementExporter.Export(exporterIFC, element, geomElem, productWrapper);

                        // For ducts and pipes, we will add a IfcRelCoversBldgElements during the end of export.
                        if (exported && (element is Duct || element is Pipe))
                            ExporterCacheManager.MEPCache.CoveredElementsCache.Add(element.Id);
                    }

                    if (element.AssemblyInstanceId != ElementId.InvalidElementId)
                        ExporterCacheManager.AssemblyInstanceCache.RegisterElements(element.AssemblyInstanceId, productWrapper);
                    if (element.GroupId != ElementId.InvalidElementId)
                        ExporterCacheManager.GroupCache.RegisterElements(element.GroupId, productWrapper);

                    st.RollBack();
                }
            }
            finally
            {
                exporterIFC.PopExportState();
                ExporterStateManager.PreserveElementParameterCache(element, shouldPreserveParameterCache);
            }
        }
Example #25
0
        /***************************************************/

        private static FreeFormProfile FreeFormProfileFromRevit(this FamilySymbol familySymbol, RevitSettings settings)
        {
            XYZ direction;

            if (familySymbol.Family.FamilyPlacementType == FamilyPlacementType.CurveDrivenStructural)
            {
                direction = XYZ.BasisX;
            }
            else if (familySymbol.Family.FamilyPlacementType == FamilyPlacementType.TwoLevelsBased)
            {
                direction = XYZ.BasisZ;
            }
            else
            {
                BH.Engine.Reflection.Compute.RecordWarning("The profile of a family type could not be found. ElementId: " + familySymbol.Id.IntegerValue.ToString());
                return(null);
            }

            // Check if one and only one solid exists to make sure that the column is a single piece
            Solid   solid   = null;
            Options options = new Options();

            options.DetailLevel = ViewDetailLevel.Fine;
            options.IncludeNonVisibleObjects = false;

            // Activate the symbol temporarily if not active, then extract its geometry (open either transaction or subtransaction, depending on whether one is already open).
            if (!familySymbol.IsActive)
            {
                Document doc = familySymbol.Document;
                if (!doc.IsModifiable)
                {
                    using (Transaction tempTransaction = new Transaction(doc, "Temp activate family symbol"))
                    {
                        tempTransaction.Start();

                        familySymbol.Activate();
                        doc.Regenerate();
                        solid = familySymbol.get_Geometry(options).SingleSolid();
                        if (solid != null)
                        {
                            solid = SolidUtils.Clone(solid);
                        }

                        tempTransaction.RollBack();
                    }
                }
                else
                {
                    using (SubTransaction tempTransaction = new SubTransaction(doc))
                    {
                        tempTransaction.Start();

                        familySymbol.Activate();
                        doc.Regenerate();
                        solid = familySymbol.get_Geometry(options).SingleSolid();
                        if (solid != null)
                        {
                            solid = SolidUtils.Clone(solid);
                        }

                        tempTransaction.RollBack();
                    }
                }
            }
            else
            {
                solid = familySymbol.get_Geometry(options).SingleSolid();
            }

            if (solid == null)
            {
                BH.Engine.Reflection.Compute.RecordWarning("The profile of a family type could not be found because it is empty or it consists of more than one solid. ElementId: " + familySymbol.Id.IntegerValue.ToString());
                return(null);
            }

            Autodesk.Revit.DB.Face face = null;
            foreach (Autodesk.Revit.DB.Face f in solid.Faces)
            {
                if (f is PlanarFace && (f as PlanarFace).FaceNormal.Normalize().IsAlmostEqualTo(-direction, 0.001))
                {
                    if (face == null)
                    {
                        face = f;
                    }
                    else
                    {
                        BH.Engine.Reflection.Compute.RecordWarning("The profile of a family type could not be found. ElementId: " + familySymbol.Id.IntegerValue.ToString());
                        return(null);
                    }
                }
            }

            if (face == null)
            {
                BH.Engine.Reflection.Compute.RecordWarning("The profile of a family type could not be found. ElementId: " + familySymbol.Id.IntegerValue.ToString());
                return(null);
            }

            List <ICurve> profileCurves = new List <ICurve>();

            foreach (EdgeArray curveArray in (face as PlanarFace).EdgeLoops)
            {
                foreach (Edge c in curveArray)
                {
                    ICurve curve = c.AsCurve().IFromRevit();
                    if (curve == null)
                    {
                        BH.Engine.Reflection.Compute.RecordWarning("The profile of a family type could not be converted due to curve conversion issues. ElementId: " + familySymbol.Id.IntegerValue.ToString());
                        return(null);
                    }
                    profileCurves.Add(curve);
                }
            }

            if (profileCurves.Count != 0)
            {
                BH.oM.Geometry.Point centroid = solid.ComputeCentroid().PointFromRevit();
                Vector tan = direction.VectorFromRevit().Normalise();

                // Adjustment of the origin to global (0,0,0).
                Vector adjustment = oM.Geometry.Point.Origin - centroid + (centroid - profileCurves[0].IStartPoint()).DotProduct(tan) * tan;
                if (adjustment.Length() > settings.DistanceTolerance)
                {
                    profileCurves = profileCurves.Select(x => x.ITranslate(adjustment)).ToList();
                }

                // Check if the curves are in the horizontal plane, if not then align them.
                if (familySymbol.Family.FamilyPlacementType == FamilyPlacementType.CurveDrivenStructural)
                {
                    // First rotate the profile to align its local plane with global XY, then rotate to align its local Z with global Y.
                    double angle = Math.PI * 0.5;
                    profileCurves = profileCurves.Select(x => x.IRotate(oM.Geometry.Point.Origin, Vector.YAxis, angle)).ToList();
                    profileCurves = profileCurves.Select(x => x.IRotate(oM.Geometry.Point.Origin, Vector.ZAxis, angle)).ToList();
                }
            }

            return(BHS.Create.FreeFormProfile(profileCurves));
        }
        /// <summary>
        /// Exports spatial elements, including rooms, areas and spaces. 2nd level space boundaries.
        /// </summary>
        /// <param name="ifcExporter">The Exporter object.</param>
        /// <param name="exporterIFC"> The ExporterIFC object.</param>
        /// <param name="document">The Revit document.</param>
        /// <returns>The set of exported spaces.  This is used to try to export using the standard routine for spaces that failed.</returns>
        public static ISet<ElementId> ExportSpatialElement2ndLevel(Revit.IFC.Export.Exporter.Exporter ifcExporter, ExporterIFC exporterIFC, Document document)
        {
            ISet<ElementId> exportedSpaceIds = new HashSet<ElementId>();

            using (SubTransaction st = new SubTransaction(document))
            {
                st.Start();

                EnergyAnalysisDetailModel model = null;
                try
                {
                    View filterView = ExporterCacheManager.ExportOptionsCache.FilterViewForExport;
                    IFCFile file = exporterIFC.GetFile();
                    using (IFCTransaction transaction = new IFCTransaction(file))
                    {

                        EnergyAnalysisDetailModelOptions options = new EnergyAnalysisDetailModelOptions();
                        options.Tier = EnergyAnalysisDetailModelTier.SecondLevelBoundaries; //2nd level space boundaries
                        options.SimplifyCurtainSystems = true;
                        try
                        {
                            model = EnergyAnalysisDetailModel.Create(document, options);
                        }
                        catch (System.Exception)
                        {
                            return exportedSpaceIds;
                        }

                        IList<EnergyAnalysisSpace> spaces = model.GetAnalyticalSpaces();
                        foreach (EnergyAnalysisSpace space in spaces)
                        {
                            SpatialElement spatialElement = document.GetElement(space.CADObjectUniqueId) as SpatialElement;

                            if (spatialElement == null)
                                continue;

                            //current view only
                            if (!ElementFilteringUtil.IsElementVisible(spatialElement))
                                continue;

                            if (!ElementFilteringUtil.ShouldElementBeExported(exporterIFC, spatialElement, false))
                                continue;

                            if (ElementFilteringUtil.IsRoomInInvalidPhase(spatialElement))
                                continue;

                            Options geomOptions = GeometryUtil.GetIFCExportGeometryOptions();
                            View ownerView = spatialElement.Document.GetElement(spatialElement.OwnerViewId) as View;
                            if (ownerView != null)
                                geomOptions.View = ownerView;
                            GeometryElement geomElem = spatialElement.get_Geometry(geomOptions);

                            try
                            {
                                exporterIFC.PushExportState(spatialElement, geomElem);

                                using (ProductWrapper productWrapper = ProductWrapper.Create(exporterIFC, true))
                                {
                                    using (PlacementSetter setter = PlacementSetter.Create(exporterIFC, spatialElement))
                                    {
                                        // We won't use the SpatialElementGeometryResults, as these are 1st level boundaries, not 2nd level.
                                        SpatialElementGeometryResults results = null;
                                        if (!CreateIFCSpace(exporterIFC, spatialElement, productWrapper, setter, out results))
                                            continue;

                                        exportedSpaceIds.Add(spatialElement.Id);

                                        XYZ offset = GetSpaceBoundaryOffset(setter);

                                        //get boundary information from surfaces
                                        IList<EnergyAnalysisSurface> surfaces = space.GetAnalyticalSurfaces();
                                        foreach (EnergyAnalysisSurface surface in surfaces)
                                        {
                                            Element boundingElement = GetBoundaryElement(document, surface.CADLinkUniqueId, surface.CADObjectUniqueId);

                                            IList<EnergyAnalysisOpening> openings = surface.GetAnalyticalOpenings();
                                            IFCAnyHandle connectionGeometry = CreateConnectionSurfaceGeometry(exporterIFC, surface, openings, offset);
                                            CreateIFCSpaceBoundary(file, exporterIFC, spatialElement, boundingElement, setter.LevelId, connectionGeometry);

                                            // try to add doors and windows for host objects if appropriate.
                                            if (boundingElement is HostObject)
                                            {
                                                foreach (EnergyAnalysisOpening opening in openings)
                                                {
                                                    Element openingBoundingElem = GetBoundaryElement(document, opening.CADLinkUniqueId, opening.CADObjectUniqueId);
                                                    IFCAnyHandle openingConnectionGeom = CreateConnectionSurfaceGeometry(exporterIFC, opening, offset);
                                                    CreateIFCSpaceBoundary(file, exporterIFC, spatialElement, openingBoundingElem, setter.LevelId, openingConnectionGeom);
                                                }
                                            }
                                        }
                                        CreateZoneInfos(exporterIFC, file, spatialElement, productWrapper);
                                        CreateSpaceOccupantInfo(exporterIFC, file, spatialElement, productWrapper);

                                        ExporterUtil.ExportRelatedProperties(exporterIFC, spatialElement, productWrapper);
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                ifcExporter.HandleUnexpectedException(ex, exporterIFC, spatialElement);
                            }
                            finally
                            {
                                exporterIFC.PopExportState();
                            }
                        }
                        transaction.Commit();
                    }
                }
                finally
                {
                    if (model != null)
                        EnergyAnalysisDetailModel.Destroy(model);
                }

                st.RollBack();
                return exportedSpaceIds;
            }
        }
Example #27
0
        /// <summary>
        /// Create a wall, append a node to tree view
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void createWallbutton_Click(object sender, EventArgs e)
        {
            // a sub-transaction is not necessary in this case
            // it is used for illustration purposes only
            using (SubTransaction subTransaction = new SubTransaction(m_document))
            {
               // if not handled explicitly, the sub-transaction will be rolled back when leaving this block
               try
               {
                  if (subTransaction.Start() == TransactionStatus.Started)
                  {
                     using (CreateWallForm createWallForm = new CreateWallForm(m_commandData))
                     {
                        createWallForm.ShowDialog();
                        if (DialogResult.OK == createWallForm.DialogResult)
                        {
                           updateModel(true);  // immediately update the view to see the changes

                           if (subTransaction.Commit() == TransactionStatus.Committed)
                           {
                              m_lastCreatedWall = createWallForm.CreatedWall;
                              AddNode(OperationType.ObjectModification, "Created wall " + m_lastCreatedWall.Id.IntegerValue.ToString());
                              UpdateButtonsStatus();
                              return;
                           }
                        }
                        else
                        {
                           subTransaction.RollBack();
                           return;
                        }
                     }
                  }
               }
               catch (System.Exception ex)
               {
                  MessageBox.Show("Exception when creating a wall: " + ex.Message);
               }
            }
            MessageBox.Show("Creating wall failed");
        }
        /// <summary>
        /// Exports spatial elements, including rooms, areas and spaces. 2nd level space boundaries.
        /// </summary>
        /// <param name="ifcExporter">
        /// The Exporter object.
        /// </param>
        /// <param name="exporterIFC">
        /// The ExporterIFC object.
        /// </param>
        /// <param name="document">
        /// The Revit document.
        /// </param>
        /// <param name="filterView">
        /// The view not exported.
        /// </param>
        /// <param name="spaceExported">
        /// The output boolean value indicates if exported successfully.
        /// </param>
        public static void ExportSpatialElement2ndLevel(BIM.IFC.Exporter.Exporter ifcExporter, ExporterIFC exporterIFC, Document document, View filterView, ref bool spaceExported)
        {
            using (SubTransaction st = new SubTransaction(document))
            {
                st.Start();

                EnergyAnalysisDetailModel model = null;
                try
                {
                    IFCFile file = exporterIFC.GetFile();
                    using (IFCTransaction transaction = new IFCTransaction(file))
                    {

                        EnergyAnalysisDetailModelOptions options = new EnergyAnalysisDetailModelOptions();
                        options.Tier = EnergyAnalysisDetailModelTier.SecondLevelBoundaries; //2nd level space boundaries
                        options.SimplifyCurtainSystems = true;
                        try
                        {
                            model = EnergyAnalysisDetailModel.Create(document, options);
                        }
                        catch (System.Exception)
                        {
                            spaceExported = false;
                            return;
                        }

                        IList<EnergyAnalysisSpace> spaces = model.GetAnalyticalSpaces();
                        spaceExported = true;

                        foreach (EnergyAnalysisSpace space in spaces)
                        {
                            SpatialElement spatialElement = document.GetElement(space.SpatialElementId) as SpatialElement;

                            if (spatialElement == null)
                                continue;

                            //quick reject
                            bool isArea = spatialElement is Area;
                            if (isArea)
                            {
                                if (!IsAreaGrossInterior(exporterIFC, spatialElement))
                                    continue;
                            }

                            //current view only
                            if (filterView != null && !ElementFilteringUtil.IsElementVisible(filterView, spatialElement))
                                continue;
                            //

                            if (!ElementFilteringUtil.ShouldCategoryBeExported(exporterIFC, spatialElement))
                                continue;

                            Options geomOptions = GeometryUtil.GetIFCExportGeometryOptions();
                            View ownerView = spatialElement.Document.GetElement(spatialElement.OwnerViewId) as View;
                            if (ownerView != null)
                                geomOptions.View = ownerView;
                            GeometryElement geomElem = spatialElement.get_Geometry(geomOptions);

                            try
                            {
                                exporterIFC.PushExportState(spatialElement, geomElem);

                                using (ProductWrapper productWrapper = ProductWrapper.Create(exporterIFC, true))
                                {
                                    ElementId levelId = spatialElement.Level != null ? spatialElement.Level.Id : ElementId.InvalidElementId;
                                    using (IFCPlacementSetter setter = IFCPlacementSetter.Create(exporterIFC, spatialElement, null, null, levelId))
                                    {
                                        if (!CreateIFCSpace(exporterIFC, spatialElement, productWrapper, setter))
                                            continue;

                                        XYZ offset = GetSapceBoundaryOffset(setter);

                                        //get boundary information from surfaces
                                        IList<EnergyAnalysisSurface> surfaces = space.GetAnalyticalSurfaces();
                                        foreach (EnergyAnalysisSurface surface in surfaces)
                                        {
                                            Element boundingElement = GetBoundaryElement(document, surface.OriginatingElementId);

                                            IList<EnergyAnalysisOpening> openings = surface.GetAnalyticalOpenings();
                                            IFCAnyHandle connectionGeometry = CreateConnectionSurfaceGeometry(file, surface, openings, offset);
                                            CreateIFCSpaceBoundary(file, exporterIFC, spatialElement, boundingElement, setter.LevelId, connectionGeometry);

                                            // try to add doors and windows for host objects if appropriate.
                                            if (boundingElement is HostObject)
                                            {
                                                foreach (EnergyAnalysisOpening opening in openings)
                                                {
                                                    Element openingBoundingElem = GetBoundaryElement(document, opening.OriginatingElementId);
                                                    IFCAnyHandle openingConnectionGeom = CreateConnectionSurfaceGeometry(file, opening, offset);
                                                    CreateIFCSpaceBoundary(file, exporterIFC, spatialElement, openingBoundingElem, setter.LevelId, openingConnectionGeom);
                                                }
                                            }
                                        }
                                        PropertyUtil.CreateInternalRevitPropertySets(exporterIFC, spatialElement, productWrapper);
                                        CreateZoneInfos(exporterIFC, file, spatialElement, productWrapper);
                                        CreateSpaceOccupantInfo(exporterIFC, file, spatialElement, productWrapper);
                                        ifcExporter.ExportElementProperties(exporterIFC, spatialElement, productWrapper);
                                        ifcExporter.ExportElementQuantities(exporterIFC, spatialElement, productWrapper);
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                ifcExporter.HandleUnexpectedException(ex, exporterIFC, spatialElement);
                            }
                            finally
                            {
                                exporterIFC.PopExportState();
                            }
                        }
                        transaction.Commit();
                    }
                }
                finally
                {
                    if (model != null)
                        EnergyAnalysisDetailModel.Destroy(model);
                }

                st.RollBack();
            }
        }
Example #29
0
        void SetTangentLockInProfileSketch2(
            Document famdoc,
            Form[] extrusions)
        {
            ICollection <ElementId> delIds = null;
            List <ElementId>        enmIDs = new List <ElementId>();

            using (SubTransaction delTrans = new SubTransaction(famdoc))
            {
                try
                {
                    delTrans.Start();
                    delIds = famdoc.Delete(extrusions[0].Id);
                    delTrans.RollBack();
                }
                catch (Exception ex)
                {
                    System.Windows.MessageBox.Show(ex.ToString());
                }
            }

            // Get the model lines in the profile and use the end
            // points for reference the sketch dimensions diameter

            List <ModelArc>  mArcsR1 = new List <ModelArc>();
            List <ModelArc>  mArcsR2 = new List <ModelArc>();
            List <ModelLine> mLines  = new List <ModelLine>();

            foreach (ElementId id in delIds)
            {
                enmIDs.Add(id);
            }

            for (int i = 0; i < enmIDs.Count; i++)
            {
                Element ele = famdoc.GetElement(enmIDs[i]);
                if (ele is ModelArc)
                {
                    ModelArc ma = ele as ModelArc;
                    Curve    c  = ma.GeometryCurve;
                    Arc      a  = c as Arc;

                    if (Math.Round(r1, 6) == Math.Round(a.Radius, 6))
                    {
                        mArcsR1.Add(ma);
                    }
                    if (Math.Round(r2, 6) == Math.Round(a.Radius, 6))
                    {
                        mArcsR2.Add(ma);
                    }
                }
                if (ele is ModelLine)
                {
                    ModelLine ml       = ele as ModelLine;
                    ElementId beforeId = null;
                    ElementId afterId  = null;

                    ISet <ElementId> joinedBefore = ml.GetAdjoinedCurveElements(0);
                    foreach (ElementId id in joinedBefore)
                    {
                        Element joinedEle = famdoc.GetElement(id);

                        if (joinedEle is ModelArc)
                        {
                            beforeId = id;
                            break;
                        }
                    }
                    ISet <ElementId> joinedAfter = ml.GetAdjoinedCurveElements(1);
                    foreach (ElementId id in joinedAfter)
                    {
                        Element joinedEle = famdoc.GetElement(id);

                        if (joinedEle is ModelArc)
                        {
                            afterId = id;
                            break;
                        }
                    }

                    if (beforeId != null &&
                        afterId != null &&
                        ml.HasTangentJoin(0, beforeId) &&
                        ml.HasTangentJoin(1, afterId))
                    {
                        ml.SetTangentLock(0, beforeId, true);
                        ml.SetTangentLock(1, afterId, true);
                    }
                }
            }
        }
        /// <summary>
        /// Получение сортированных элементов из спецификации с установленной галочкой "Для каждого экземпляра"
        /// </summary>
        /// <param name="viewSchedule">Вид спецификации</param>
        /// <param name="elements">Элементы, полученные с этого вида</param>
        private List <Element> GetSortedElementsFromItemizedSchedule(ViewSchedule viewSchedule, List <Element> elements)
        {
            var sortedElements = new List <Element>();

            var builtInParameter = GetBuiltInParameterForElements(elements);

            if (builtInParameter == null)
            {
                return(sortedElements);
            }

            using (var transaction = new SubTransaction(viewSchedule.Document))
            {
                transaction.Start();

                // Разделитель
                const string separator = "$ElementId=";

                // Записываем Id всех элементов в параметр "Комментарий"
                elements.ForEach(e =>
                {
                    if (e.GroupId != ElementId.InvalidElementId)
                    {
                        (e.Document.GetElement(e.GroupId) as Group)?.UngroupMembers();
                    }

                    var parameter = e.get_Parameter(builtInParameter.Value);
                    parameter.Set(parameter.AsString() + separator + e.Id.IntegerValue);
                });

                // К спецификации добавляем поле. Код из справки, за исключением try {} catch{}
                AddFieldToSchedule(viewSchedule, builtInParameter.Value, out _);

                // Ну и сама магия - просто читаем получившуюся спецификацию по ячейкам и получаем
                // элементы уже в том порядке, в котором мы их видим в спецификации
                var sectionData = viewSchedule.GetTableData().GetSectionData(SectionType.Body);
                for (var r = sectionData.FirstRowNumber; r <= sectionData.LastRowNumber; r++)
                {
                    for (var c = sectionData.FirstColumnNumber; c <= sectionData.LastColumnNumber; c++)
                    {
                        var cellValue = viewSchedule.GetCellText(SectionType.Body, r, c);
                        if (cellValue.Contains(separator))
                        {
                            var idStr = cellValue.Split(separator.ToCharArray()).Last();
                            if (!string.IsNullOrEmpty(idStr))
                            {
                                // Делаем устойчивым к ошибкам - при наличии ошибок все равно код завершится,
                                // а я буду знать о возможных проблемах. На мой взгляд лучше, чем полное прерывание метода
                                try
                                {
                                    sortedElements.Add(viewSchedule.Document.GetElement(new ElementId(Convert.ToInt32(idStr))));
                                }
                                catch (Exception exception)
                                {
                                    ExceptionBox.Show(exception);
                                }
                            }
                        }
                    }
                }

                // Откатываем транзакцию
                transaction.RollBack();
            }

            return(sortedElements);
        }
        /// <summary>
        /// Return a reference to the topmost face of the given element.
        /// </summary>
        private Reference FindTopMostReference(Element e)
        {
            Reference ret = null;
            Document  doc = e.Document;

            #region Revit 2012
#if _2012
            using (SubTransaction t = new SubTransaction(doc))
            {
                t.Start();

                // Create temporary 3D view

                //View3D view3D = doc.Create.NewView3D( // 2012
                //  viewDirection ); // 2012

                ViewFamilyType vft
                    = new FilteredElementCollector(doc)
                      .OfClass(typeof(ViewFamilyType))
                      .Cast <ViewFamilyType>()
                      .FirstOrDefault <ViewFamilyType>(x =>
                                                       ViewFamily.ThreeDimensional == x.ViewFamily);

                Debug.Assert(null != vft,
                             "expected to find a valid 3D view family type");

                View3D view = View3D.CreateIsometric(doc, vft.Id); // 2013

                XYZ eyePosition      = XYZ.BasisZ;
                XYZ upDirection      = XYZ.BasisY;
                XYZ forwardDirection = -XYZ.BasisZ;

                view.SetOrientation(new ViewOrientation3D(
                                        eyePosition, upDirection, forwardDirection));

                XYZ viewDirection = -XYZ.BasisZ;

                BoundingBoxXYZ bb = e.get_BoundingBox(view);

                XYZ max = bb.Max;

                XYZ minAtMaxElevation = Create.NewXYZ(
                    bb.Min.X, bb.Min.Y, max.Z);

                XYZ centerOfTopOfBox = 0.5
                                       * (minAtMaxElevation + max);

                centerOfTopOfBox += 10 * XYZ.BasisZ;

                // Cast a ray through the model
                // to find the topmost surface

#if DEBUG
                //ReferenceArray references
                //  = doc.FindReferencesByDirection(
                //    centerOfTopOfBox, viewDirection, view3D ); // 2011

                IList <ReferenceWithContext> references
                    = doc.FindReferencesWithContextByDirection(
                          centerOfTopOfBox, viewDirection, view); // 2012

                double closest = double.PositiveInfinity;

                //foreach( Reference r in references )
                //{
                //  // 'Autodesk.Revit.DB.Reference.Element' is
                //  // obsolete: Property will be removed. Use
                //  // Document.GetElement(Reference) instead.
                //  //Element re = r.Element; // 2011

                //  Element re = doc.GetElement( r ); // 2012

                //  if( re.Id.IntegerValue == e.Id.IntegerValue
                //    && r.ProximityParameter < closest )
                //  {
                //    ret = r;
                //    closest = r.ProximityParameter;
                //  }
                //}

                foreach (ReferenceWithContext r in references)
                {
                    Element re = doc.GetElement(
                        r.GetReference()); // 2012

                    if (re.Id.IntegerValue == e.Id.IntegerValue &&
                        r.Proximity < closest)
                    {
                        ret     = r.GetReference();
                        closest = r.Proximity;
                    }
                }

                string stable_reference = null == ret ? null
          : ret.ConvertToStableRepresentation(doc);
#endif // DEBUG

                ReferenceIntersector ri
                    = new ReferenceIntersector(
                          e.Id, FindReferenceTarget.Element, view);

                ReferenceWithContext r2 = ri.FindNearest(
                    centerOfTopOfBox, viewDirection);

                if (null == r2)
                {
                    Debug.Print("ReferenceIntersector.FindNearest returned null!");
                }
                else
                {
                    ret = r2.GetReference();

                    Debug.Assert(stable_reference.Equals(ret
                                                         .ConvertToStableRepresentation(doc)),
                                 "expected same reference from "
                                 + "FindReferencesWithContextByDirection and "
                                 + "ReferenceIntersector");
                }
                t.RollBack();
            }
#endif // _2012
            #endregion // Revit 2012

            Options opt = doc.Application.Create
                          .NewGeometryOptions();

            opt.ComputeReferences = true;

            GeometryElement geo = e.get_Geometry(opt);

            foreach (GeometryObject obj in geo)
            {
                GeometryInstance inst = obj as GeometryInstance;

                if (null != inst)
                {
                    geo = inst.GetSymbolGeometry();
                    break;
                }
            }

            Solid solid = geo.OfType <Solid>()
                          .First <Solid>(sol => null != sol);

            double z = double.MinValue;

            foreach (Face f in solid.Faces)
            {
                BoundingBoxUV b        = f.GetBoundingBox();
                UV            p        = b.Min;
                UV            q        = b.Max;
                UV            midparam = p + 0.5 * (q - p);
                XYZ           midpoint = f.Evaluate(midparam);
                XYZ           normal   = f.ComputeNormal(midparam);

                if (Util.PointsUpwards(normal))
                {
                    if (midpoint.Z > z)
                    {
                        z   = midpoint.Z;
                        ret = f.Reference;
                    }
                }
            }
            return(ret);
        }
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIApplication uiapp = commandData.Application;
              UIDocument uidoc = uiapp.ActiveUIDocument;
              Application app = uiapp.Application;
              Document doc = uidoc.Document;

              using ( Transaction tx = new Transaction( doc ) )
              {
            tx.Start( "Mirror and List Added" );
            //Line line = app.Create.NewLine(
            //  XYZ.Zero, XYZ.BasisX, true ); // 2011

            //ElementSet els = uidoc.Selection.Elements; // 2011

            //Plane plane = new Plane( XYZ.BasisY, XYZ.Zero ); // added in 2012, used until 2016

            Plane plane = Plane.CreateByNormalAndOrigin( XYZ.BasisY, XYZ.Zero ); // 2017

            ICollection<ElementId> elementIds
              = uidoc.Selection.GetElementIds(); // 2012

            using ( SubTransaction t = new SubTransaction( doc ) )
            {
              // determine newly added elements relying on the
              // element sequence as returned by the filtered collector.
              // this approach works in both Revit 2010 and 2011:

              t.Start();

              int n = GetElementCount( doc );

              //doc.Mirror( els, line ); // 2011

              //ElementTransformUtils.MirrorElements(
              //  doc, elementIds, plane ); // 2012-2015

              ElementTransformUtils.MirrorElements(
            doc, elementIds, plane, true ); // 2016

              List<Element> a = GetElementsAfter( n, doc );

              t.RollBack();
            }

            using ( SubTransaction t = new SubTransaction( doc ) )
            {
              // here is an idea for a new approach in 2011:
              // determine newly added elements relying on
              // monotonously increasing element id values:

              t.Start();

              FilteredElementCollector a = GetElements( doc );
              int i = a.Max<Element>( e => e.Id.IntegerValue );
              ElementId maxId = new ElementId( i );

              // doc.Mirror( els, line ); // 2011

              //ElementTransformUtils.MirrorElements(
              //  doc, elementIds, plane ); // 2012-2015

              ElementTransformUtils.MirrorElements(
            doc, elementIds, plane, true ); // 2016

              // get all elements in document with an
              // element id greater than maxId:

              a = GetElementsAfter( doc, maxId );

              Report( a );

              t.RollBack();
            }

            using ( SubTransaction t = new SubTransaction( doc ) )
            {
              // similar to the above approach relying on
              // monotonously increasing element id values,
              // but apply a quick filter first:

              t.Start();

              FilteredElementCollector a = GetElements( doc );
              int i = a.Max<Element>( e => e.Id.IntegerValue );
              ElementId maxId = new ElementId( i );

              //doc.Mirror( els, line ); // 2011

              //ElementTransformUtils.MirrorElements(
              //  doc, elementIds, plane ); // 2012-2015

              ElementTransformUtils.MirrorElements(
            doc, elementIds, plane, true ); // 2016

              // only look at non-ElementType elements
              // instead of all document elements:

              a = GetElements( doc );
              a = GetElementsAfter( a, maxId );

              Report( a );

              t.RollBack();
            }

            using ( SubTransaction t = new SubTransaction( doc ) )
            {
              // use a local and temporary DocumentChanged event
              // handler to directly obtain a list of all newly
              // created elements.
              // unfortunately, this canot be tested in this isolated form,
              // since the DocumentChanged event is only triggered when the
              // real outermost Revit transaction is committed, i.e. our
              // local sub-transaction makes no difference. since we abort
              // the sub-transaction before the command terminates and no
              // elements are really added to the database, our event
              // handler is never called:

              t.Start();

              app.DocumentChanged
            += new EventHandler<DocumentChangedEventArgs>(
              app_DocumentChanged );

              //doc.Mirror( els, line ); // 2011

              //ElementTransformUtils.MirrorElements(
              //  doc, elementIds, plane ); // 2012-2015

              ElementTransformUtils.MirrorElements(
            doc, elementIds, plane, true ); // 2016

              app.DocumentChanged
            -= new EventHandler<DocumentChangedEventArgs>(
              app_DocumentChanged );

              Debug.Assert( null == _addedElementIds,
            "never expected the event handler to be called" );

              if ( null != _addedElementIds )
              {
            int n = _addedElementIds.Count;

            string s = string.Format( _msg, n,
              Util.PluralSuffix( n ) );

            foreach ( ElementId id in _addedElementIds )
            {
              Element e = doc.GetElement( id );

              s += string.Format( "\r\n  {0}",
                Util.ElementDescription( e ) );
            }
            Util.InfoMsg( s );
              }

              t.RollBack();
            }
            tx.RollBack();
              }
              return Result.Succeeded;
        }