示例#1
0
        public void XYZFromReferencePoint()
        {
            var model = dynSettings.Controller.DynamoModel;

            string samplePath = Path.Combine(_testPath, @".\XYZ\XYZFromReferencePoint.dyn");
            string testPath = Path.GetFullPath(samplePath);

            model.Open(testPath);
            ReferencePoint rp;
            using (_trans = new Transaction(dynRevitSettings.Doc.Document))
            {
                _trans.Start("Create a reference point.");

                rp = dynRevitSettings.Doc.Document.FamilyCreate.NewReferencePoint(new XYZ());

                _trans.Commit();

            }
            FSharpList<FScheme.Value> args = FSharpList<FScheme.Value>.Empty;
            args = FSharpList<FScheme.Value>.Cons(FScheme.Value.NewContainer(rp), args);

            //find the XYZFromReferencePoint node
            var node = dynSettings.Controller.DynamoModel.Nodes.Where(x => x is XyzFromReferencePoint).First();

            FScheme.Value v = ((NodeWithOneOutput)node).Evaluate(args);
            Assert.IsInstanceOf(typeof(XYZ), ((FScheme.Value.Container)v).Item);
        }
示例#2
0
        /// <summary>
        /// Sets the near clipping plane distance of the view.  This is done by modifying the cropbox.  Please note that modifying the far clip distance will reset any near clip modifications.
        /// </summary>
        /// <param name="View">A Dynamo wrapped view</param>
        /// <param name="NearClipping">The Near Clipping Offset distance as a number from the camera</param>
        /// <returns name="View">Returns the modified view</returns>
        public static dynaView SetNearClippingDistance(dynaView3D View, double NearClipping)
        {
            string transactionName = "Set Near Clipping Distance";

            revitView rView = (revitView)View.InternalElement;

            revitBBxyz CropBox    = rView.CropBox;
            revitXYZ   oldMax     = CropBox.Max;
            revitXYZ   newMax     = new revitXYZ(oldMax.X, oldMax.Y, -Math.Abs(NearClipping));
            revitBBxyz NewCropBox = new revitBBxyz();

            NewCropBox.Max = newMax;
            NewCropBox.Min = CropBox.Min;

            revitDoc document = rView.Document;

            if (document.IsModifiable)
            {
                TransactionManager.Instance.EnsureInTransaction(document);
                rView.CropBox = NewCropBox;
                TransactionManager.Instance.TransactionTaskDone();
            }
            else
            {
                using (Autodesk.Revit.DB.Transaction trans = new Autodesk.Revit.DB.Transaction(document))
                {
                    trans.Start(transactionName);
                    rView.CropBox = NewCropBox;
                    trans.Commit();
                }
            }

            return(View);
        }
示例#3
0
        void Menu_UnpinElements(object sender, EventArgs args)
        {
            var doc      = Revit.ActiveUIDocument.Document;
            var elements = ToElementIds(VolatileData).
                           Where(x => x.Document.Equals(doc)).
                           Select(x => x.Document.GetElement(x.Id)).
                           Where(x => x.Pinned == true);

            if (elements.Any())
            {
                try
                {
                    using (var transaction = new DB.Transaction(doc, "Unpin elements"))
                    {
                        transaction.Start();

                        foreach (var element in elements)
                        {
                            element.Pinned = false;
                        }

                        transaction.Commit();
                    }
                }
                catch (Autodesk.Revit.Exceptions.ArgumentException)
                {
                    TaskDialog.Show("Unpin elements", $"One or more of the {TypeName} cannot be unpinned.");
                }
            }
        }
示例#4
0
        /// <summary>
        /// Renumbers the views on the sheet based on the view grid.
        /// </summary>
        /// <param name="sheet">A dynamo Sheet element</param>
        /// <param name="gridX">Size of the layout grid in the X direction</param>
        /// <param name="gridY">Size of the layout grid in the Y direction</param>
        /// <param name="originX">Location of the layout grid origin on the X axis</param>
        /// <param name="originY">Location of the layout grid origin on the Y axis</param>
        /// <returns name="Viewports">Revit viewport objects on the sheet.</returns>
        public static List <revitViewport> RenumberOnSheetByCoordinates(dynaSheet sheet, double gridX, double gridY, double originX, double originY)
        {
            string transactionName = "Renumber views on sheet";

            //  Initialize variables
            revitSheet           rSheet     = (revitSheet)sheet.InternalElement;
            revitDoc             document   = rSheet.Document;
            List <revitElemId>   rViewports = (List <revitElemId>)rSheet.GetAllViewports();
            List <revitViewport> viewports;

            //  If the document is modifieable,
            //  then a transaction is already open
            //  and function uses the Dynamo Transaction Manager.
            //  Else, open a new transaction.
            if (document.IsModifiable)
            {
                TransactionManager.Instance.EnsureInTransaction(document);
                viewports = View._tempRenumberViewports(rViewports, document);
                viewports = View._renumberViewports(viewports, gridX, gridY, originX, originY);
                TransactionManager.Instance.TransactionTaskDone();
            }
            else
            {
                using (Autodesk.Revit.DB.Transaction trans = new Autodesk.Revit.DB.Transaction(document))
                {
                    trans.Start(transactionName);
                    viewports = View._tempRenumberViewports(rViewports, document);
                    viewports = View._renumberViewports(viewports, gridX, gridY, originX, originY);
                    trans.Commit();
                }
            }

            return(viewports);
        }
示例#5
0
        public void CreateInRevitSelectInDynamoUndoInRevit()
        {
            //Create a reference point in Revit
            string         rpID;
            ReferencePoint rp;

            using (var trans = new Transaction(DocumentManager.Instance.CurrentUIDocument.Document, "CreateInRevit"))
            {
                trans.Start();

                rp   = DocumentManager.Instance.CurrentUIDocument.Document.FamilyCreate.NewReferencePoint(new XYZ());
                rpID = rp.UniqueId;

                trans.Commit();
            }

            //Select the reference point in Dynamo
            string dynFilePath = Path.Combine(workingDirectory, @".\ElementBinding\SelectInDynamo.dyn");
            string testPath    = Path.GetFullPath(dynFilePath);

            ViewModel.OpenCommand.Execute(testPath);

            var model    = ViewModel.Model;
            var selNodes = model.CurrentWorkspace.Nodes.Where(x => x is ElementSelection <Autodesk.Revit.DB.Element>);
            var selNode  = selNodes.First() as ElementSelection <Autodesk.Revit.DB.Element>;

            //selNode.SelectionResults.Add(rp);


            RunCurrentModel();


            //Undo the creation of a reference point in Revit
            Assert.Inconclusive("TO DO");
        }
示例#6
0
        /// <summary>
        /// Duplciates a view and renames it.
        /// </summary>
        /// <param name="Name">The name of the duplicated view</param>
        /// <param name="SourceView">The view to duplicate</param>
        /// <param name="DuplicateOptions">Enum ViewDuplicateOptions</param>
        /// <returns name="View">The duplicated view</returns>
        public static dynaView DuplicateView(string Name,
                                             dynaView SourceView,
                                             revitDB.ViewDuplicateOption DuplicateOptions)
        {
            string transactionName = "Duplicate View";
            Func <revitView, revitDB.ViewDuplicateOption, revitDoc, revitView> dupView = (v, vdo, doc) =>
            {
                revitElemId viewId  = v.Duplicate(vdo);
                revitView   newView = (revitView)doc.GetElement(viewId);
                newView.Name = Name;
                return(newView);
            };

            revitView rView    = (revitView)SourceView.InternalElement;
            revitDoc  document = rView.Document;
            revitView view;

            if (document.IsModifiable)
            {
                TransactionManager.Instance.EnsureInTransaction(document);
                view = dupView(rView, DuplicateOptions, document);
                TransactionManager.Instance.TransactionTaskDone();
            }
            else
            {
                using (Autodesk.Revit.DB.Transaction trans = new Autodesk.Revit.DB.Transaction(document))
                {
                    trans.Start(transactionName);
                    view = dupView(rView, DuplicateOptions, document);
                    trans.Commit();
                }
            }
            return((dynaView)view.ToDSType(true));
        }
示例#7
0
        /// <summary>
        /// Implement this method as an external command for Revit.
        /// </summary>
        /// <param name="commandData">An object that is passed to the external application
        /// which contains data related to the command,
        /// such as the application object and active view.</param>
        /// <param name="message">A message that can be set by the external application
        /// which will be displayed if a failure or cancellation is returned by
        /// the external command.</param>
        /// <param name="elements">A set of elements to which the external application
        /// can add elements that are to be highlighted in case of failure or cancellation.</param>
        /// <returns>Return the status of the external command.
        /// A result of Succeeded means that the API external method functioned as expected.
        /// Cancelled can be used to signify that the user canceled the external operation
        /// at some point. Failure should be returned if the application is unable to proceed with
        /// the operation.</returns>
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            _dbdocument = commandData.Application.ActiveUIDocument.Document;


            try
            {
                using (Autodesk.Revit.DB.Transaction tr = new Autodesk.Revit.DB.Transaction(_dbdocument, "CreateNURBS"))
                {
                    tr.Start();

                    DirectShape myDirectShape = DirectShape.CreateElement(_dbdocument, new ElementId(BuiltInCategory.OST_GenericModel));
                    myDirectShape.ApplicationId     = "TestCreateNURBS";
                    myDirectShape.ApplicationDataId = "NURBS";

                    if (null != myDirectShape)
                    {
                        myDirectShape.SetShape(CreateNurbsSurface());
                    }
                    tr.Commit();
                }
            }
            catch (Exception ex)
            {
                message = ex.Message;
                return(Result.Failed);
            }

            return(Result.Succeeded);
        }
示例#8
0
        public void CreateInDynamoModifyInRevitReRun()
        {
            //Create a reference point at (0.0, 0.0, 0.0);
            string dynFilePath = Path.Combine(workingDirectory, @".\ElementBinding\CreateOneReferencePoint.dyn");
            string testPath    = Path.GetFullPath(dynFilePath);

            ViewModel.OpenCommand.Execute(testPath);

            RunCurrentModel();


            //Change the position of the reference point
            var points = GetAllReferencePointElements();

            Assert.AreEqual(1, points.Count);
            ReferencePoint pnt = points[0] as ReferencePoint;

            Assert.IsNotNull(pnt);
            using (var trans = new Transaction(DocumentManager.Instance.CurrentUIDocument.Document, "ModifyInRevit"))
            {
                trans.Start();
                pnt.Position = new XYZ(10.0, 0.0, 0.0);
                trans.Commit();
            }

            //Run the graph once again

            RunCurrentModel();

            points = GetAllReferencePointElements();
            Assert.AreEqual(1, points.Count);
            pnt = points[0] as ReferencePoint;
            Assert.IsTrue(pnt.Position.IsAlmostEqualTo(new XYZ(0.0, 0.0, 0.0)));
        }
示例#9
0
        /// <summary>
        /// Implement this method as an external command for Revit.
        /// </summary>
        /// <param name="commandData">An object that is passed to the external application
        /// which contains data related to the command,
        /// such as the application object and active view.</param>
        /// <param name="message">A message that can be set by the external application
        /// which will be displayed if a failure or cancellation is returned by
        /// the external command.</param>
        /// <param name="elements">A set of elements to which the external application
        /// can add elements that are to be highlighted in case of failure or cancellation.</param>
        /// <returns>Return the status of the external command.
        /// A result of Succeeded means that the API external method functioned as expected.
        /// Cancelled can be used to signify that the user cancelled the external operation
        /// at some point. Failure should be returned if the application is unable to proceed with
        /// the operation.</returns>
        public virtual Result Execute(ExternalCommandData commandData
                                      , ref string message, ElementSet elements)
        {
            try
            {
                Document document             = commandData.Application.ActiveUIDocument.Document;
                Autodesk.Revit.DB.Units units = document.GetUnits();

                // show UI
                using (UnitsForm displayForm = new UnitsForm(units))
                {
                    DialogResult result = displayForm.ShowDialog();
                    if (DialogResult.OK == result)
                    {
                        using (Autodesk.Revit.DB.Transaction tran = new Autodesk.Revit.DB.Transaction(document, "SetUnits"))
                        {
                            tran.Start();
                            document.SetUnits(units);
                            tran.Commit();
                        }
                    }
                    else
                    {
                        return(Autodesk.Revit.UI.Result.Cancelled);
                    }
                }

                return(Result.Succeeded);
            }
            catch (Exception ex)
            {
                message = ex.Message;
                return(Result.Failed);
            }
        }
示例#10
0
文件: XYZTests.cs 项目: l2obin/Dynamo
        public void XYZFromReferencePoint()
        {
            var model = dynSettings.Controller.DynamoModel;

            string samplePath = Path.Combine(_testPath, @".\XYZ\XYZFromReferencePoint.dyn");
            string testPath   = Path.GetFullPath(samplePath);

            model.Open(testPath);
            ReferencePoint rp;

            using (_trans = new Transaction(dynRevitSettings.Doc.Document))
            {
                _trans.Start("Create a reference point.");

                rp = dynRevitSettings.Doc.Document.FamilyCreate.NewReferencePoint(new XYZ());

                _trans.Commit();
            }
            FSharpList <FScheme.Value> args = FSharpList <FScheme.Value> .Empty;

            args = FSharpList <FScheme.Value> .Cons(FScheme.Value.NewContainer(rp), args);

            //find the XYZFromReferencePoint node
            var node = dynSettings.Controller.DynamoModel.Nodes.Where(x => x is XyzFromReferencePoint).First();

            FScheme.Value v = ((NodeWithOneOutput)node).Evaluate(args);
            Assert.IsInstanceOf(typeof(XYZ), ((FScheme.Value.Container)v).Item);
        }
示例#11
0
        internal static List <revitViewport> _renumberViewsOnSheet(FamilyType familyType, string xGridName, string yGridName, revitSheet rSheet, revitDoc document)
        {
            string transactionName = "Renumber views on sheet";

            //  Initialize variables
            revitFamilySymbol rFamilySymbol = (revitFamilySymbol)familyType.InternalElement;

            //  Get all viewport ID's on the sheet.
            List <revitElemId>   viewportIds = (List <revitElemId>)rSheet.GetAllViewports();
            List <revitViewport> viewports   = null;

            //  Get the family Instances in view
            revitElemId symbolId = familyType.InternalElement.Id;

            revitCollector     collector      = new revitCollector(document, rSheet.Id);
            revitElementFilter filterInstance = new revitDB.FamilyInstanceFilter(document, symbolId);

            collector.OfClass(typeof(revitDB.FamilyInstance)).WherePasses(filterInstance);

            revitDB.FamilyInstance originFamily = (revitDB.FamilyInstance)collector.FirstElement();

            //  If family instance is found in the view
            //  Then renumber views.
            if (originFamily != null)
            {
                revitDB.LocationPoint location = (revitDB.LocationPoint)originFamily.Location;
                revitXYZ originPoint           = location.Point;

                double gridX = rFamilySymbol.LookupParameter(xGridName).AsDouble();
                double gridY = rFamilySymbol.LookupParameter(yGridName).AsDouble();

                //  If the document is modifieable,
                //  then a transaction is already open
                //  and function uses the Dynamo Transaction Manager.
                //  Else, open a new transaction.
                if (document.IsModifiable)
                {
                    TransactionManager.Instance.EnsureInTransaction(document);
                    viewports = View._tempRenumberViewports(viewportIds, document);
                    viewports = View._renumberViewports(viewports, gridX, gridY, originPoint.X, originPoint.Y);
                    TransactionManager.Instance.TransactionTaskDone();
                }
                else
                {
                    using (Autodesk.Revit.DB.Transaction trans = new Autodesk.Revit.DB.Transaction(document))
                    {
                        trans.Start(transactionName);
                        viewports = View._tempRenumberViewports(viewportIds, document);
                        viewports = View._renumberViewports(viewports, gridX, gridY, originPoint.X, originPoint.Y);
                        trans.Commit();
                    }
                }
            }

            return(viewports);
        }
示例#12
0
        public void CurveByPoints()
        {
            var model = dynSettings.Controller.DynamoModel;

            string samplePath = Path.Combine(_testPath, @".\Curve\CurveByPoints.dyn");
            string testPath = Path.GetFullPath(samplePath);

            model.Open(testPath);

            //cerate some points and wire them
            //to the selections
            ReferencePoint p1, p2, p3, p4;

            using (_trans = new Transaction(dynRevitSettings.Doc.Document))
            {
                _trans.Start("Create reference points for testing.");

                p1 = dynRevitSettings.Doc.Document.FamilyCreate.NewReferencePoint(new XYZ(1, 5, 12));
                p2 = dynRevitSettings.Doc.Document.FamilyCreate.NewReferencePoint(new XYZ(5, 1, 12));
                p3 = dynRevitSettings.Doc.Document.FamilyCreate.NewReferencePoint(new XYZ(12, 1, 5));
                p4 = dynRevitSettings.Doc.Document.FamilyCreate.NewReferencePoint(new XYZ(5, 12, 1));

                _trans.Commit();
            }

            var ptSelectNodes = dynSettings.Controller.DynamoModel.Nodes.Where(x => x is PointBySelection);
            if (!ptSelectNodes.Any())
                Assert.Fail("Could not find point selection nodes in dynamo graph.");

            ((PointBySelection)ptSelectNodes.ElementAt(0)).SelectedElement = p1;
            ((PointBySelection)ptSelectNodes.ElementAt(1)).SelectedElement = p2;
            ((PointBySelection)ptSelectNodes.ElementAt(2)).SelectedElement = p3;
            ((PointBySelection)ptSelectNodes.ElementAt(3)).SelectedElement = p4;

            dynSettings.Controller.RunExpression(true);

            FilteredElementCollector fec = new FilteredElementCollector(dynRevitSettings.Doc.Document);
            fec.OfClass(typeof(CurveElement));

            Assert.AreEqual(fec.ToElements().Count(), 1);

            CurveByPoints mc = (CurveByPoints)fec.ToElements().ElementAt(0);
            Assert.IsTrue(mc.IsReferenceLine);

            //now flip the switch for creating a reference curve
            var boolNode = dynSettings.Controller.DynamoModel.Nodes.Where(x => x is BoolSelector).First();

            ((BasicInteractive<bool>)boolNode).Value = false;

            dynSettings.Controller.RunExpression(true);
            Assert.AreEqual(fec.ToElements().Count(), 1);

            mc = (CurveByPoints)fec.ToElements().ElementAt(0);
            Assert.IsFalse(mc.IsReferenceLine);
        }
示例#13
0
        public void CreateInDynamoModifyInRevitToCauseFailure()
        {
            //Create a wall in Dynamo
            string dynFilePath = Path.Combine(workingDirectory, @".\ElementBinding\CreateWallInDynamo.dyn");
            string testPath    = Path.GetFullPath(dynFilePath);

            ViewModel.OpenCommand.Execute(testPath);

            RunCurrentModel();


            //Modify the wall in Revit
            using (var trans = new Transaction(DocumentManager.Instance.CurrentUIDocument.Document, "ModifyInRevit"))
            {
                bool hasError = false;
                trans.Start();

                try
                {
                    IList <Element> rps = GetAllWallElements(false);
                    Assert.AreEqual(1, rps.Count);
                    Wall       wall     = rps.First() as Wall;
                    List <XYZ> ctrlPnts = new List <XYZ>();
                    ctrlPnts.Add(new XYZ(0.0, 1.0, 0.0));
                    ctrlPnts.Add(new XYZ(1.0, 0.0, 0.0));
                    ctrlPnts.Add(new XYZ(2.0, 0.0, 0.0));
                    ctrlPnts.Add(new XYZ(3.0, 1.0, 0.0));
                    List <double> weights = new List <double>();
                    weights.Add(1.0);
                    weights.Add(1.0);
                    weights.Add(1.0);
                    weights.Add(1.0);
                    var spline       = NurbSpline.Create(ctrlPnts, weights);
                    var wallLocation = wall.Location as LocationCurve;
                    wallLocation.Curve = spline;
                }
                catch (Exception e)
                {
                    hasError = true;
                    trans.RollBack();
                }

                if (!hasError)
                {
                    trans.Commit();
                }
            }


            RunCurrentModel();

            IList <Element> rps2 = GetAllWallElements(false);

            Assert.AreEqual(1, rps2.Count);
        }
示例#14
0
        /// <summary>
        /// Removes all painted faces on an elementl
        /// </summary>
        /// <param name="Element">The element to removve painted faces</param>
        /// <returns name="Element">The modified element</returns>
        public static DynaElem RemovePaintElement(DynaElem Element)
        {
            string transactionName = "Remove Painted Faces of Element";

            RevitDoc    document  = Element.InternalElement.Document;
            RevitElemId elementId = Element.InternalElement.Id;

            RevitDB.Options         op      = new RevitDB.Options();
            RevitDB.GeometryElement geoElem = Element.InternalElement.get_Geometry(op);

            IList <RevitDB.Face> faces = new List <RevitDB.Face>();

            foreach (RevitDB.GeometryObject geo in geoElem)
            {
                if (geo is RevitDB.Solid)
                {
                    RevitDB.Solid solid = geo as RevitDB.Solid;
                    foreach (RevitDB.Face face in solid.Faces)
                    {
                        faces.Add(face);
                    }
                }
                else if (geo is RevitDB.Face)
                {
                    faces.Add(geo as RevitDB.Face);
                }

                Action <RevitElemId, IList <RevitDB.Face> > RemovePaintedFaces = (RevitElemId elemId, IList <RevitDB.Face> faceList) =>
                {
                    foreach (RevitDB.Face face in faceList)
                    {
                        document.RemovePaint(elemId, face);
                    }
                };

                if (document.IsModifiable)
                {
                    TransactionManager.Instance.EnsureInTransaction(document);
                    RemovePaintedFaces(elementId, faces);
                    TransactionManager.Instance.TransactionTaskDone();
                }
                else
                {
                    using (Autodesk.Revit.DB.Transaction trans = new Autodesk.Revit.DB.Transaction(document))
                    {
                        trans.Start(transactionName);
                        RemovePaintedFaces(elementId, faces);
                        trans.Commit();
                    }
                }
            }

            return(Element);
        }
示例#15
0
        public static IDictionary ByName(
            string name,
            [DefaultArgument("true")] bool visible,
            [DefaultArgument("\"\"")] string alias
            )
        {
            //Get Revit Document object
            revitDoc doc = DocumentManager.Instance.CurrentDBDocument;

            Workset workset = null;
            bool    created = false;

            //Only create workset if it's name isn't an empty string
            if (name != null && name != "")
            {
                //Verify that each workset isn't already in the document
                //If the workset is unique, create it
                if (WorksetTable.IsWorksetNameUnique(doc, name))
                {
                    //If the alias is already in the document
                    if (alias != null && WorksetTable.IsWorksetNameUnique(doc, alias) == false)
                    {
                        workset = GetByName(alias);
                        Rename(workset, name);
                        created = true;
                    }
                    else
                    {
                        using (Autodesk.Revit.DB.Transaction trans = new Autodesk.Revit.DB.Transaction(doc))
                        {
                            trans.Start("Create Workset");

                            workset = new Workset(doc, revitWorkset.Create(doc, name));

                            trans.Commit();
                        }
                        SetDefaultVisibility(workset, visible);
                        created = true;
                    }
                }
                // If the workset is already in the document, retrieve the workset
                else
                {
                    workset = GetByName(name);
                    created = false;
                }
            }

            return(new Dictionary <string, object>
            {
                { "workset", workset },
                { "created", created }
            });
        }
示例#16
0
        /// <summary>
        /// Removes the ExternallyTaggedBRep created by the CreateBRep command from the DirectShape.
        /// After that, creates the new ExternallyTaggedBRep with other dimensions and adds it to the DirectShape.
        /// </summary>
        /// <param name="commandData">An object that is passed to the external application
        /// which contains data related to the command,
        /// such as the application object and active view.</param>
        /// <param name="message">A message that can be set by the external application
        /// which will be displayed if a failure or cancellation is returned by
        /// the external command.</param>
        /// <param name="elements">A set of elements to which the external application
        /// can add elements that are to be highlighted in case of failure or cancellation.</param>
        /// <returns>Return the status of the external command.
        /// A result of Succeeded means that the API external method functioned as expected.
        /// Cancelled can be used to signify that the user canceled the external operation
        /// at some point. Failure should be returned if the application is unable to proceed with
        /// the operation.</returns>
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            Document dbDocument = commandData.Application.ActiveUIDocument.Document;

            try
            {
                // If the UpdateBRep external command is called before the CreateBRep command
                // or the created DirectShape is manually removed or is not valid now,
                // we should call CreateBRep command at first.
                if (null == CreateBRep.CreatedDirectShape ||
                    !CreateBRep.CreatedDirectShape.IsValidObject ||
                    !CreateBRep.CreatedDirectShape.Document.Equals(dbDocument))
                {
                    if (Result.Succeeded != HelperMethods.executeCreateBRepCommand(dbDocument))
                    {
                        return(Result.Failed);
                    }
                }

                using (Autodesk.Revit.DB.Transaction transaction = new Autodesk.Revit.DB.Transaction(dbDocument, "UpdateExternallyTaggedBRep"))
                {
                    transaction.Start();

                    // Create BRep with other dimensions than CreateBRep command creates and update the geometry in the DirectShape.
                    ExternallyTaggedBRep resizedTaggedBRep = HelperMethods.createExternallyTaggedPodium(120.0, 20.0, 60.0);
                    if (null == resizedTaggedBRep)
                    {
                        return(Result.Failed);
                    }

                    // Remove the old ExternallyTaggedBRep from the DirectShape.
                    CreateBRep.CreatedDirectShape.RemoveExternallyTaggedGeometry(Podium.ExternalId);

                    // Check that the old ExternallyTaggedBRep is removed from the DirectShape.
                    if (CreateBRep.CreatedDirectShape.HasExternalGeometry(Podium.ExternalId))
                    {
                        return(Result.Failed);
                    }

                    // Add the new resized ExternallyTaggedBRep to the DirectShape.
                    CreateBRep.CreatedDirectShape.AddExternallyTaggedGeometry(resizedTaggedBRep);

                    transaction.Commit();
                }
            }
            catch (Exception ex)
            {
                message = ex.Message;
                return(Result.Failed);
            }

            return(Result.Succeeded);
        }
示例#17
0
        /// <summary>
        /// Move steel plate.
        /// </summary>
        private void MovePlate()
        {
            // Start Revit transaction.
            using (Autodesk.Revit.DB.Transaction trans = new Autodesk.Revit.DB.Transaction(_doc, "Move plate"))
            {
                trans.Start();

                // internal Revit units are in feet
                ElementTransformUtils.MoveElement(_doc, _plateId, new XYZ(-50, 0, 0));

                trans.Commit();
            }
        }
示例#18
0
        /// <summary>
        /// Implement this method as an external command for Revit.
        /// </summary>
        /// <param name="commandData">An object that is passed to the external application
        /// which contains data related to the command,
        /// such as the application object and active view.</param>
        /// <param name="message">A message that can be set by the external application
        /// which will be displayed if a failure or cancellation is returned by
        /// the external command.</param>
        /// <param name="elements">A set of elements to which the external application
        /// can add elements that are to be highlighted in case of failure or cancellation.</param>
        /// <returns>Return the status of the external command.
        /// A result of Succeeded means that the API external method functioned as expected.
        /// Cancelled can be used to signify that the user cancelled the external operation
        /// at some point. Failure should be returned if the application is unable to proceed with
        /// the operation.</returns>
        public virtual Result Execute(ExternalCommandData commandData
                                      , ref string message, ElementSet elements)
        {
            // Get the document from external command data.
            UIDocument activeDoc = commandData.Application.ActiveUIDocument;

            Autodesk.Revit.DB.Document doc = activeDoc.Document;
            if (null == doc)
            {
                return(Result.Failed);
            }

            // The transaction and its status, using Revit's Transaction class
            Autodesk.Revit.DB.Transaction trans = new Autodesk.Revit.DB.Transaction(doc, "Delete structural connection");
            TransactionStatus             ts    = TransactionStatus.Uninitialized;

            try
            {
                // We get the connection to be deleted. We use Revit's StructuralConnectionHandler class
                // for more details, please consult http://www.autodesk.com/adv-steel-api-walkthroughs-2019-enu
                StructuralConnectionHandler conn = Utilities.Functions.SelectConnection(activeDoc);
                if (null == conn)
                {
                    return(Result.Failed);
                }
                // Start the transaction.
                trans.Start();
                // Delete selected structural connection.
                doc.Delete(conn.Id);
                // Commit the transaction
                ts = trans.Commit();
                if (ts != TransactionStatus.Committed)
                {
                    message = "Failed to commit the current transaction !";
                    trans.RollBack();
                    return(Result.Failed);
                }
            }

            catch (Autodesk.Revit.Exceptions.OperationCanceledException)
            {
                if (ts != TransactionStatus.Uninitialized)
                {
                    trans.RollBack();
                }
                trans.Dispose();
                return(Result.Cancelled);
            }
            return(Result.Succeeded);
        }
示例#19
0
        public static void ConnectPipesAndMEPElementsWithConnectorsInSameLocation(List <PipeModel> pipeModels,
                                                                                  List <MEPElementModel> mepElementModels, ExternalCommandData commandData)
        {
            var uiapp = commandData.Application;
            var uidoc = uiapp.ActiveUIDocument;
            var doc   = uidoc.Document;


            //Проверяем совпадают ли точки коннекторов труб и mep элементов
            //и если совпадают - соединяем коннекторы
            using (var t = new Autodesk.Revit.DB.Transaction(doc, "Deal with connectors"))
            {
                t.Start();
                foreach (var pipeModelItem in pipeModels)
                {
                    if (!pipeModelItem.ConnectorFirst.IsValidObject || !pipeModelItem.ConnectorSecond.IsValidObject)
                    {
                        continue;
                    }
                    foreach (var mepElementModelItem in mepElementModels)
                    {
                        foreach (var mepConnector in mepElementModelItem.Connectors)
                        {
                            if (!mepConnector.IsValidObject || mepConnector.IsConnected)
                            {
                                continue;
                            }
                            if (pipeModelItem.ConnectorFirst.Origin.IsEqualByXYZ(mepConnector.Origin, 5))
                            {
                                if (!pipeModelItem.ConnectorFirst.IsConnectedTo(mepConnector) &&
                                    !pipeModelItem.ConnectorFirst.IsConnected)
                                {
                                    pipeModelItem.ConnectorFirst.ConnectTo(mepConnector);
                                }
                            }

                            if (pipeModelItem.ConnectorSecond.Origin.IsEqualByXYZ(mepConnector.Origin, 5))
                            {
                                if (!pipeModelItem.ConnectorSecond.IsConnectedTo(mepConnector) &&
                                    !pipeModelItem.ConnectorSecond.IsConnected)
                                {
                                    pipeModelItem.ConnectorSecond.ConnectTo(mepConnector);
                                }
                            }
                        }
                    }
                }
                t.Commit();
            }
        }
示例#20
0
        /// <summary>
        /// This function gets all the model curves in the current Revit document
        /// </summary>
        /// <returns>the model curves</returns>
        private static IList <Autodesk.Revit.DB.ModelCurve> GetAllModelCurves()
        {
            using (var trans = new Transaction(DocumentManager.Instance.CurrentUIDocument.Document, "FilteringElements"))
            {
                trans.Start();

                ElementClassFilter       ef  = new ElementClassFilter(typeof(Autodesk.Revit.DB.CurveElement));
                FilteredElementCollector fec = new FilteredElementCollector(DocumentManager.Instance.CurrentUIDocument.Document);
                fec.WherePasses(ef);

                trans.Commit();
                return(fec.ToElements().OfType <Autodesk.Revit.DB.ModelCurve>().ToList());
            }
        }
示例#21
0
        public void CreateInRevitSelectInDynamoSelectDifferentElement()
        {
            //This is to test that when a node is binding with a new element, the information related to binding
            //has actually changed.

            //Create two reference points in Revit
            string         rpID1, rpID2;
            ReferencePoint rp1, rp2;

            using (var trans = new Transaction(DocumentManager.Instance.CurrentUIDocument.Document, "CreateInRevit"))
            {
                trans.Start();

                rp1   = DocumentManager.Instance.CurrentUIDocument.Document.FamilyCreate.NewReferencePoint(new XYZ());
                rpID1 = rp1.UniqueId;
                rp2   = DocumentManager.Instance.CurrentUIDocument.Document.FamilyCreate.NewReferencePoint(new XYZ(10, 0, 0));
                rpID2 = rp2.UniqueId;

                trans.Commit();
            }

            //Select the first reference point in Dynamo
            string dynFilePath = Path.Combine(workingDirectory, @".\ElementBinding\SelectInDynamo.dyn");
            string testPath    = Path.GetFullPath(dynFilePath);

            ViewModel.OpenCommand.Execute(testPath);

            var model    = ViewModel.Model;
            var selNodes = model.CurrentWorkspace.Nodes.Where(x => x is ElementSelection <Autodesk.Revit.DB.Element>);
            var selNode  = selNodes.First() as ElementSelection <Autodesk.Revit.DB.Element>;
            IEnumerable <Element> selection1 = new[] { rp1 };

            selNode.UpdateSelection(selection1);

            RunCurrentModel();

            var id1 = selNode.SelectionResults.First();

            //Select the second reference point in Dynamo
            IEnumerable <Element> selection2 = new[] { rp2 };

            selNode.UpdateSelection(selection2);

            RunCurrentModel();

            var id2 = selNode.SelectionResults.First();

            //Ensure the element binding is not the same
            Assert.IsTrue(!id1.Equals(id2));
        }
示例#22
0
        /// <summary>
        /// Makes the main part of the CreateBRep external command actions.
        /// See CreateBRep.Execute method summary for the details.
        /// </summary>
        /// <param name="document">A Document that will be used for Transaction and DirectShape creation.</param>
        public static Result executeCreateBRepCommand(Document document)
        {
            // Create the ExternallyTaggedBRep named "Podium".
            ExternallyTaggedBRep taggedBRep = HelperMethods.createExternallyTaggedPodium(40.0, 12.0, 30.0);

            if (null == taggedBRep)
            {
                return(Result.Failed);
            }

            using (Autodesk.Revit.DB.Transaction transaction = new Autodesk.Revit.DB.Transaction(document, "CreateExternallyTaggedBRep"))
            {
                transaction.Start();

                // Create the new DirectShape for this open Document and add the created ExternallyTaggedBRep to this DirectShape.
                CreateBRep.CreatedDirectShape = HelperMethods.createDirectShapeWithExternallyTaggedBRep(document, taggedBRep);
                if (null == CreateBRep.CreatedDirectShape)
                {
                    return(Result.Failed);
                }

                // Retrieve the ExternallyTaggedBRep by its ExternalId from the DirectShape and check that the returned BRep is valid.
                ExternallyTaggedBRep retrievedBRep = CreateBRep.CreatedDirectShape.GetExternallyTaggedGeometry(taggedBRep.ExternalId) as ExternallyTaggedBRep;
                if (null == retrievedBRep)
                {
                    return(Result.Failed);
                }

                // Retrieve the Face by its ExternalGeometryId from the ExternallyTaggedBRep and check that the returned face is valid.
                // "faceRiser1" is a hardcoded ExternalGeometryId of the one Face in the "Podium" BRep, see Podium.cs file.
                Face retrievedFace = retrievedBRep.GetTaggedGeometry(new ExternalGeometryId("faceRiser1")) as Face;
                if (null == retrievedFace)
                {
                    return(Result.Failed);
                }

                // Retrieve the Edge by its ExternalGeometryId from the ExternallyTaggedBRep and check that the returned edge is valid.
                // "edgeLeftRiser1" is a hardcoded ExternalGeometryId of the one Edge in the "Podium" BRep, see Podium.cs file.
                Edge retrievedEdge = retrievedBRep.GetTaggedGeometry(new ExternalGeometryId("edgeLeftRiser1")) as Edge;
                if (null == retrievedEdge)
                {
                    return(Result.Failed);
                }

                transaction.Commit();

                return(Result.Succeeded);
            }
        }
示例#23
0
        public void CreateInDynamoDeleteInRevit()
        {
            //This test case is to test that elements can be created via Dynamo.
            //After they are deleted in Revit, we can still create them via Dynamo.

            //Create a reference point in Dynamo
            string dynFilePath = Path.Combine(workingDirectory, @".\ElementBinding\CreateInDynamo.dyn");
            string testPath    = Path.GetFullPath(dynFilePath);

            ViewModel.OpenCommand.Execute(testPath);


            RunCurrentModel();


            var model    = ViewModel.Model;
            var selNodes = model.CurrentWorkspace.Nodes.Where(x => string.Equals(x.GUID.ToString(), "6a79717b-7438-458a-a725-587be0ba84fd"));

            Assert.IsTrue(selNodes.Any());
            var node = selNodes.First();
            var id1  = GetBindingElementIdForNode(node.GUID);

            //Delete all reference points in Revit
            using (var trans = new Transaction(DocumentManager.Instance.CurrentUIDocument.Document, "DeleteInRevit"))
            {
                trans.Start();

                IList <Element> rps   = GetAllReferencePointElements(false);
                var             rpIDs = rps.Select(x => x.Id);
                DocumentManager.Instance.CurrentDBDocument.Delete(rpIDs.ToList());

                trans.Commit();
            }

            //Run the graph again

            RunCurrentModel();

            var id2 = GetBindingElementIdForNode(node.GUID);

            //Check the number of reference points
            //This also verifies MAGN-2317
            IList <Element> newRps = GetAllReferencePointElements(true);

            Assert.AreEqual(1, newRps.Count());

            //Ensure the binding elements are different
            Assert.IsTrue(!id1.Equals(id2));
        }
示例#24
0
        protected void CommitTransaction(DB.Document doc, DB.Transaction transaction)
        {
            var options = transaction.GetFailureHandlingOptions();

#if !DEBUG
            options = options.SetClearAfterRollback(true);
#endif
            options = options.SetDelayedMiniWarnings(true);
            options = options.SetForcedModalHandling(true);
            options = options.SetFailuresPreprocessor(this);
            options = options.SetTransactionFinalizer(this);

            // Disable Rhino UI if any warning-error dialog popup
            {
                External.EditScope editScope = null;
                EventHandler <DialogBoxShowingEventArgs> _ = null;
                try
                {
                    Revit.ApplicationUI.DialogBoxShowing += _ = (sender, args) =>
                    {
                        if (editScope is null)
                        {
                            editScope = new External.EditScope();
                        }
                    };

                    if (transaction.GetStatus() == DB.TransactionStatus.Started)
                    {
                        OnBeforeCommit(doc, transaction.GetName());

                        transaction.Commit(options);
                    }
                    else
                    {
                        transaction.RollBack(options);
                    }
                }
                finally
                {
                    Revit.ApplicationUI.DialogBoxShowing -= _;

                    if (editScope is IDisposable disposable)
                    {
                        disposable.Dispose();
                    }
                }
            }
        }
示例#25
0
        /// <summary>
        /// Creates one model curve on a plane with an origin at 0,0,0
        /// </summary>
        /// <param name="mc1"></param>
        protected void CreateOneModelCurve(out ModelCurve mc1)
        {
            //create two model curves
            using (_trans = _trans = new Transaction(DocumentManager.Instance.CurrentUIDocument.Document, "CreateTwoModelCurves"))
            {
                _trans.Start();

                var p1 = new Plane(XYZ.BasisZ, XYZ.Zero);

                SketchPlane sp1 = DocumentManager.Instance.CurrentUIDocument.Document.FamilyCreate.NewSketchPlane(p1);
                Curve       c1  = DocumentManager.Instance.CurrentUIApplication.Application.Create.NewLineBound(XYZ.Zero, new XYZ(1, 0, 0));
                mc1 = DocumentManager.Instance.CurrentUIDocument.Document.FamilyCreate.NewModelCurve(c1, sp1);

                _trans.Commit();
            }
        }
示例#26
0
        /// <summary>
        /// Creates one model curve on a plane with an origin at 0,0,0
        /// </summary>
        /// <param name="mc1"></param>
        protected void CreateOneModelCurve(out ModelCurve mc1)
        {
            //create two model curves
            using (_trans = _trans = new Transaction(dynRevitSettings.Doc.Document, "CreateTwoModelCurves"))
            {
                _trans.Start();

                Plane p1 = new Plane(XYZ.BasisZ, XYZ.Zero);

                SketchPlane sp1 = dynRevitSettings.Doc.Document.FamilyCreate.NewSketchPlane(p1);
                Curve       c1  = dynRevitSettings.Revit.Application.Create.NewLineBound(XYZ.Zero, new XYZ(1, 0, 0));
                mc1 = dynRevitSettings.Doc.Document.FamilyCreate.NewModelCurve(c1, sp1);

                _trans.Commit();
            }
        }
示例#27
0
        protected override void TrySolveInstance(IGH_DataAccess DA, DB.Document doc)
        {
            var filePath = string.Empty;

            if (!DA.GetData("Path", ref filePath))
            {
                return;
            }

            var overrideFamily = false;

            if (!DA.GetData("OverrideFamily", ref overrideFamily))
            {
                return;
            }

            var overrideParameters = false;

            if (!DA.GetData("OverrideParameters", ref overrideParameters))
            {
                return;
            }

            using (var transaction = new DB.Transaction(doc))
            {
                transaction.Start(Name);

                if (doc.LoadFamily(filePath, new FamilyLoadOptions(overrideFamily, overrideParameters), out var family))
                {
                    transaction.Commit();
                }
                else
                {
                    var name = Path.GetFileNameWithoutExtension(filePath);
                    using (var collector = new DB.FilteredElementCollector(doc).OfClass(typeof(DB.Family)))
                        family = collector.Cast <DB.Family>().Where(x => x.Name == name).FirstOrDefault();

                    if (family is object && overrideFamily == false)
                    {
                        AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, $"Family '{name}' already loaded!");
                    }
                }

                DA.SetData("Family", family);
            }
        }
示例#28
0
        // Private Sub bindSharedParameterToFile()
        //     Dim userResponse As MessageBox.ShowResult
        //     userResponse = MessageBox.Show("Create the Shared Parameter " & vbCrLf & vbTab & thisParameterName & vbCrLf & "?", MessageBox.ShowStyle.YesNo)
        //     If userResponse = MessageBox.ShowResult.Yes Then
        //         'first we need to make sure the shared parameters file is setup correctly
        //         'If ptr2SharedParametersFile.checkStageForSetup() Then
        //         Dim docTransaction As New Autodesk.Revit.DB.Transaction(ptr2TargetDoc)
        //         docTransaction.SetName("mertens3d.com - parameterJerk - Create Shared Parameter")
        //         docTransaction.Start()
        //         'If Not ptr2SharedParametersFile.doesParameterAlreadyExistInGroup(thisParameterName) Then
        //         '    ptr2SharedParametersFile.addParameterToGroup(thisParameterName)
        //         'End If
        //         'now we need to add to the file
        //         bindParameterToFile()
        //         docTransaction.Commit()
        //         'Else
        //         '    MessageBox.Show("Canceled - Create New Parameter")
        //         'End If
        //     End If
        // End Sub
        // Private Sub createNONSharedParameterInFile()
        //     Dim docTransaction As New Autodesk.Revit.DB.Transaction(ptr2TargetDoc)
        //     docTransaction.SetName("mertens3d.com - parameterJerk - Create Shared Parameter")
        //     docTransaction.Start()
        //     'now we need to add to the file
        //     'bindParameterToFile()
        //     'we want it in the project, so bind to a category
        //     Dim cats As CategorySet = ptr2TargetDoc.Application.Create.NewCategorySet
        //     cats.Insert(ptr2TargetDoc.Settings.Categories.Item(BuiltInCategory.OST_ProjectInformation))
        //     'create a binding - instance or type
        //     Dim bind As InstanceBinding = ptr2TargetDoc.Application.Create.NewInstanceBinding(cats)
        //     ptr2TargetDoc.ParameterBindings.Insert(sharedParameterFileDef, bind, BuiltInParameterGroup.PG_TEXT)
        //     docTransaction.Commit()
        // End Sub
        // Private Sub bindParameterToFile()
        //     MessageBox.Show("bindParameterToFile")
        //     Dim m_Manager As FamilyManager = Nothing
        //     m_Manager = ptr2TargetDoc.FamilyManager
        //     Try
        //         MessageBox.Show("_thisExternalDefinition: " & _thisExternalDefinition.ToString())
        //         m_Manager.AddParameter(_thisExternalDefinition, _parameterGroup, True)
        //     Catch ex As Exception
        //         MessageBox.Show(ex.ToString())
        //     End Try
        // End Sub
        private void deleteExistingParameter(FamilyParameter paramToDelete, Autodesk.Revit.DB.Document targetDoc)
        {
            FamilyManager mgr = targetDoc.FamilyManager;

            JerkHub.Ptr2Debug.AddToDebug(("Deleting existing parameter: " + paramToDelete.Definition.Name));
            Autodesk.Revit.DB.Transaction docTransaction = new Autodesk.Revit.DB.Transaction(targetDoc);
            docTransaction.SetName("delete existing parameter");
            try
            {
                docTransaction.Start();
                mgr.RemoveParameter(paramToDelete);
                docTransaction.Commit();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
示例#29
0
        public RevitUI.Result Execute(RevitUI.ExternalCommandData commandData, ref string message, RevitDB.ElementSet elements)
        {
            try
            {
                RevitDB.Transaction tran = new RevitDB.Transaction(commandData.Application.ActiveUIDocument.Document, "Journaling");
                tran.Start();
                Journaling deal = new Journaling(commandData);
                deal.Run();
                tran.Commit();

                return(RevitUI.Result.Succeeded);
            }
            catch (Exception ex)
            {
                message = ex.Message;
                return(RevitUI.Result.Failed);
            }
        }
示例#30
0
        /// <summary>
        /// Sets the Default Visibility of a workset within a document.
        /// </summary>
        /// <param name="workset">The workset that you wish to set the visibility of.</param>
        /// <param name="visible">The visibility of the workset</param>
        /// <returns name="workset">A Revit workset</returns>
        public static Workset SetDefaultVisibility(Workset workset, bool visible)
        {
            //Get Revit Document object
            revitDoc doc = DocumentManager.Instance.CurrentDBDocument;

            using (Autodesk.Revit.DB.Transaction trans = new Autodesk.Revit.DB.Transaction(doc))
            {
                trans.Start("Set Workset Default Visibility");

                // Set the workset’s default visibility
                WorksetDefaultVisibilitySettings defaultVisibility = WorksetDefaultVisibilitySettings.GetWorksetDefaultVisibilitySettings(doc);
                defaultVisibility.SetWorksetVisibility(workset.internalId, visible);

                trans.Commit();
                defaultVisibility.Dispose();
            }
            return(workset);
        }
示例#31
0
        /// <summary>
        /// Matches View3D's orientation and cropbox to an orthagonal view.  Also sets the View3D to isometric.
        /// </summary>
        /// <param name="View3D">The 3D view to change orientation and crop</param>
        /// <param name="SourceView">The source orthogonal view to acquire orientation and cropbox</param>
        /// <param name="Offset">Offset of the camera from the view direction of the source view</param>
        /// <returns name="View3D"></returns>
        public static DynaView3D View3dOrientToggleIsometric(DynaView3D View3D, DynaView SourceView, double Offset)
        {
            string transactionName = "View3dOrientToggleIsometric";

            RevitView3D rView       = (RevitView3D)View3D.InternalElement;
            RevitView   rSourceView = (RevitView)SourceView.InternalElement;

            RevitDoc document = rView.Document;

            // Cropbox
            RevitBB  cropbox = rSourceView.CropBox;
            RevitXYZ origin  = cropbox.Transform.Origin;

            // View Orientation
            RevitXYZ rEyePosition      = origin.Add(rSourceView.ViewDirection.Normalize().Multiply(Offset));
            RevitXYZ rUpDirection      = rSourceView.UpDirection;
            RevitXYZ rForwardDirection = rSourceView.ViewDirection.Negate();

            RevitViewOrientation viewOrient = new RevitViewOrientation(rEyePosition, rUpDirection, rForwardDirection);

            Action <RevitView3D, RevitViewOrientation, RevitBB> orientView = (view, orient, cropbb) =>
            {
                view.ToggleToIsometric();
                view.SetOrientation(orient);
                view.CropBox = cropbb;
            };

            if (document.IsModifiable)
            {
                TransactionManager.Instance.EnsureInTransaction(document);
                orientView(rView, viewOrient, cropbox);
                TransactionManager.Instance.TransactionTaskDone();
            }
            else
            {
                using (Autodesk.Revit.DB.Transaction trans = new Autodesk.Revit.DB.Transaction(document))
                {
                    trans.Start(transactionName);
                    orientView(rView, viewOrient, cropbox);
                    trans.Commit();
                }
            }
            return(View3D);
        }
示例#32
0
        /// <summary>
        /// Overwrites the parameters of an element with the parameters of an element from a different document.  Associated elements such as materials may be duplicated in the document.
        /// </summary>
        /// <param name="Element"></param>
        /// <param name="SourceElement"></param>
        /// <returns></returns>
        public static RevitElem TransferElements(
            RevitElem Element,
            RevitElem SourceElement)
        {
            RevitDoc destinationDoc = Element.Document;
            RevitDoc sourceDoc      = SourceElement.Document;

            string transactionName = "Element overwritten from " + sourceDoc.Title;

            RevitElem returnElem;

            Func <RevitElem, RevitDoc, RevitElem, RevitDoc, RevitElem> transfer = (dElem, dDoc, sElem, sDoc) =>
            {
                List <RevitElemId> revitElemIds = new List <RevitElemId>();
                revitElemIds.Add(sElem.Id);

                Autodesk.Revit.DB.CopyPasteOptions cpo = new Autodesk.Revit.DB.CopyPasteOptions();
                List <RevitElemId> ids = (List <RevitElemId>)Autodesk.Revit.DB.ElementTransformUtils.CopyElements(sDoc, revitElemIds, dDoc, null, cpo);

                RevitElem tempElem = dDoc.GetElement(ids[0]);
                _transferParameters(tempElem, dElem);
                destinationDoc.Delete(tempElem.Id);

                return(dElem);
            };

            if (destinationDoc.IsModifiable)
            {
                TransactionManager.Instance.EnsureInTransaction(destinationDoc);
                returnElem = transfer(Element, destinationDoc, SourceElement, sourceDoc);
                TransactionManager.Instance.TransactionTaskDone();
            }
            else
            {
                using (Autodesk.Revit.DB.Transaction trans = new Autodesk.Revit.DB.Transaction(destinationDoc))
                {
                    trans.Start(transactionName);
                    returnElem = transfer(Element, destinationDoc, SourceElement, sourceDoc);
                    trans.Commit();
                }
            }

            return(returnElem);
        }
示例#33
0
        /// <summary>
        /// This function gets all the walls in the current Revit document
        /// </summary>
        /// <param name="startNewTransaction">whether do the filtering in a new transaction</param>
        /// <returns>the walls</returns>
        private static IList<Element> GetAllWallElements(bool startNewTransaction)
        {
            if (startNewTransaction)
            {
                using (var trans = new Transaction(DocumentManager.Instance.CurrentUIDocument.Document, "FilteringElements"))
                {
                    trans.Start();

                    ElementClassFilter ef = new ElementClassFilter(typeof(Wall));
                    FilteredElementCollector fec = new FilteredElementCollector(DocumentManager.Instance.CurrentUIDocument.Document);
                    fec.WherePasses(ef);

                    trans.Commit();
                    return fec.ToElements();
                }
            }
            else
            {
                ElementClassFilter ef = new ElementClassFilter(typeof(Wall));
                FilteredElementCollector fec = new FilteredElementCollector(DocumentManager.Instance.CurrentUIDocument.Document);
                fec.WherePasses(ef);
                return fec.ToElements();
            }
        }
示例#34
0
        /// <summary>
        /// Creates one model curve on a plane with an origin at 0,0,0
        /// </summary>
        /// <param name="mc1"></param>
        protected void CreateOneModelCurve(out ModelCurve mc1)
        {
            //create two model curves
            using (_trans = _trans = new Transaction(DocumentManager.Instance.CurrentUIDocument.Document, "CreateTwoModelCurves"))
            {
                _trans.Start();

                var p1 = new Plane(XYZ.BasisZ, XYZ.Zero);

                SketchPlane sp1 = DocumentManager.Instance.CurrentUIDocument.Document.FamilyCreate.NewSketchPlane(p1);
                Curve c1 = DocumentManager.Instance.CurrentUIApplication.Application.Create.NewLineBound(XYZ.Zero, new XYZ(1, 0, 0));
                mc1 = DocumentManager.Instance.CurrentUIDocument.Document.FamilyCreate.NewModelCurve(c1, sp1);

                _trans.Commit();
            }
        }
示例#35
0
文件: COVER.cs 项目: nixz/covise
        public void idleUpdate(object sender, Autodesk.Revit.UI.Events.IdlingEventArgs e)
        {
            e.SetRaiseWithoutDelay();

              UIApplication uiapp = sender as UIApplication;
              Document doc = uiapp.ActiveUIDocument.Document;
              UIDocument uidoc = uiapp.ActiveUIDocument;

              if (COVER.Instance.messageQueue.Count > 0)
              {
              using (Autodesk.Revit.DB.Transaction transaction = new Autodesk.Revit.DB.Transaction(doc))
              {
                  FailureHandlingOptions failOpt = transaction.GetFailureHandlingOptions();

                  failOpt.SetClearAfterRollback(true);
                  failOpt.SetFailuresPreprocessor( new NoWarningsAndErrors());
                  transaction.SetFailureHandlingOptions(failOpt);

                  if (transaction.Start("changeParameters") == Autodesk.Revit.DB.TransactionStatus.Started)
                  {
                      while (COVER.Instance.messageQueue.Count > 0)
                      {
                          COVERMessage m = COVER.Instance.messageQueue.Dequeue();
                          COVER.Instance.handleMessage(m.message, m.messageType,doc,uidoc);
                          if (Autodesk.Revit.DB.TransactionStatus.Committed != transaction.Commit())
                          {
                              // Autodesk.Revit.UI.TaskDialog.Show("Failure", "Transaction could not be committed");
                              //an error occured end resolution was cancled thus this change can't be committed.
                              // just ignore it and dont bug the user
                          }
                          return;
                      }
                  }
              }
              }
        }
示例#36
0
文件: COVER.cs 项目: nixz/covise
            /// <summary>
            /// Execute method invoked by Revit via the 
            /// external event as a reaction to a call 
            /// to its Raise method.
            /// </summary>
            public void Execute(Autodesk.Revit.UI.UIApplication a)
            {
                // As far as I can tell, the external event
                  // should work fine even when switching between
                  // different documents. That, however, remains
                  // to be tested in more depth (or at all).

                  //Document doc = a.ActiveUIDocument.Document;

                  //Debug.Assert( doc.Title.Equals( _doc.Title ),
                  //  "oops ... different documents ... test this" );
                  UIDocument uidoc = a.ActiveUIDocument;
                  using (Autodesk.Revit.DB.Transaction transaction = new Autodesk.Revit.DB.Transaction(a.ActiveUIDocument.Document))
                  {
                  FailureHandlingOptions failOpt = transaction.GetFailureHandlingOptions();

                  failOpt.SetClearAfterRollback(true);
                  failOpt.SetFailuresPreprocessor(new NoWarningsAndErrors());
                  transaction.SetFailureHandlingOptions(failOpt);
                  if (transaction.Start("changeParameters") == Autodesk.Revit.DB.TransactionStatus.Started)
                  {
                      while (COVER.Instance.messageQueue.Count > 0)
                      {
                          COVERMessage m = COVER.Instance.messageQueue.Dequeue();
                          COVER.Instance.handleMessage(m.message, m.messageType, a.ActiveUIDocument.Document,uidoc);
                          if (Autodesk.Revit.DB.TransactionStatus.Committed != transaction.Commit())
                          {
                              // Autodesk.Revit.UI.TaskDialog.Show("Failure", "Transaction could not be committed");
                              //an error occured end resolution was cancled thus this change can't be committed.
                              // just ignore it and dont bug the user
                          }
                          return;
                      }
                  }
                  }
            }
示例#37
0
        public void CreateInDynamoDeleteInRevit()
        {
            //This test case is to test that elements can be created via Dynamo.
            //After they are deleted in Revit, we can still create them via Dynamo.

            //Create a reference point in Dynamo
            string dynFilePath = Path.Combine(_testPath, @".\ElementBinding\CreateInDynamo.dyn");
            string testPath = Path.GetFullPath(dynFilePath);

            Controller.DynamoViewModel.OpenCommand.Execute(testPath);
            Assert.DoesNotThrow(() => Controller.RunExpression());
            var model = Controller.DynamoModel;
            var selNodes = model.AllNodes.Where(x => string.Equals(x.GUID.ToString(), "6a79717b-7438-458a-a725-587be0ba84fd"));
            Assert.IsTrue(selNodes.Any());
            var node = selNodes.First();
            var id1 = GetBindingElementIdForNode(node.GUID);

            //Delete all reference points in Revit
            using (var trans = new Transaction(DocumentManager.Instance.CurrentUIDocument.Document, "DeleteInRevit"))
            {
                trans.Start();

                IList<Element> rps = GetAllReferencePointElements(false);
                var rpIDs = rps.Select(x => x.Id);
                DocumentManager.Instance.CurrentDBDocument.Delete(rpIDs.ToList());

                trans.Commit();
            }

            //Run the graph again
            Assert.DoesNotThrow(() => Controller.RunExpression());
            var id2 = GetBindingElementIdForNode(node.GUID);

            //Check the number of reference points
            //This also verifies MAGN-2317
            IList<Element> newRps = GetAllReferencePointElements(true);
            Assert.AreEqual(1, newRps.Count());

            //Ensure the binding elements are different
            Assert.IsTrue(!id1.Equals(id2));
        }
示例#38
0
        public void CreateInDynamoModifyInRevit()
        {
            //Create a wall in Dynamo
            string dynFilePath = Path.Combine(_testPath, @".\ElementBinding\CreateWallInDynamo.dyn");
            string testPath = Path.GetFullPath(dynFilePath);

            Controller.DynamoViewModel.OpenCommand.Execute(testPath);
            Assert.DoesNotThrow(() => Controller.RunExpression());

            //Modify the wall in Revit
            using (var trans = new Transaction(DocumentManager.Instance.CurrentUIDocument.Document, "DeleteInRevit"))
            {
                trans.Start();

                IList<Element> rps = GetAllWallElements(false);
                Assert.AreEqual(1, rps.Count);
                Wall wall = rps.First() as Wall;
                //Modify the wall to cause a failure
                Assert.Inconclusive("TO DO");
                wall.Flip();
                DocumentManager.Instance.CurrentDBDocument.Delete(wall);

                trans.Commit();
            }
        }
示例#39
0
        public void CreateInRevitSelectInDynamoUndoInRevit()
        {
            //Create a reference point in Revit
            ElementId rpID;
            using (var trans = new Transaction(DocumentManager.Instance.CurrentUIDocument.Document, "CreateInRevit"))
            {
                trans.Start();

                ReferencePoint rp = DocumentManager.Instance.CurrentUIDocument.Document.FamilyCreate.NewReferencePoint(new XYZ());
                rpID = rp.Id;

                trans.Commit();
            }

            //Select the reference point in Dynamo
            string dynFilePath = Path.Combine(_testPath, @".\ElementBinding\SelectInDynamo.dyn");
            string testPath = Path.GetFullPath(dynFilePath);

            Controller.DynamoViewModel.OpenCommand.Execute(testPath);

            var model = Controller.DynamoModel;
            var selNodes = model.AllNodes.Where(x => x is DSElementSelection);
            var selNode = selNodes.First() as DSElementSelection;
            selNode.SelectedElement = rpID;

            Assert.DoesNotThrow(() => Controller.RunExpression());

            //Undo the creation of a reference point in Revit
            Assert.Inconclusive("TO DO");
        }
示例#40
0
        public void CreateInRevitSelectInDynamoSelectDifferentElement()
        {
            //This is to test that when a node is binding with a new element, the information related to binding
            //has actually changed.

            //Create two reference points in Revit
            ElementId rpID1, rpID2;
            using (var trans = new Transaction(DocumentManager.Instance.CurrentUIDocument.Document, "CreateInRevit"))
            {
                trans.Start();

                ReferencePoint rp1 = DocumentManager.Instance.CurrentUIDocument.Document.FamilyCreate.NewReferencePoint(new XYZ());
                rpID1 = rp1.Id;
                ReferencePoint rp2 = DocumentManager.Instance.CurrentUIDocument.Document.FamilyCreate.NewReferencePoint(new XYZ(10, 0, 0));
                rpID2 = rp2.Id;

                trans.Commit();
            }

            //Select the first reference point in Dynamo
            string dynFilePath = Path.Combine(_testPath, @".\ElementBinding\SelectInDynamo.dyn");
            string testPath = Path.GetFullPath(dynFilePath);

            Controller.DynamoViewModel.OpenCommand.Execute(testPath);

            var model = Controller.DynamoModel;
            var selNodes = model.AllNodes.Where(x => x is DSElementSelection);
            var selNode = selNodes.First() as DSElementSelection;
            selNode.SelectedElement = rpID1;
            Assert.DoesNotThrow(() => Controller.RunExpression());
            var id1 = selNode.SelectedElement;

            //Select the second reference point in Dynamo
            selNode.SelectedElement = rpID2;
            Assert.DoesNotThrow(() => Controller.RunExpression());
            var id2 = selNode.SelectedElement;

            //Ensure the element binding is not the same
            Assert.IsTrue(!id1.Equals(id2));
        }
示例#41
0
        /// <summary>
        /// Creates one model curve on a plane with an origin at 0,0,0
        /// </summary>
        /// <param name="mc1"></param>
        protected void CreateOneModelCurve(out ModelCurve mc1)
        {
            //create two model curves
            using (_trans = _trans = new Transaction(dynRevitSettings.Doc.Document, "CreateTwoModelCurves"))
            {
                _trans.Start();

                Plane p1 = new Plane(XYZ.BasisZ, XYZ.Zero);

                SketchPlane sp1 = dynRevitSettings.Doc.Document.FamilyCreate.NewSketchPlane(p1);
                Curve c1 = dynRevitSettings.Revit.Application.Create.NewLineBound(XYZ.Zero, new XYZ(1, 0, 0));
                mc1 = dynRevitSettings.Doc.Document.FamilyCreate.NewModelCurve(c1, sp1);

                _trans.Commit();
            }
        }