コード例 #1
0
ファイル: View.cs プロジェクト: andradam75/Synthetic
        /// <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);
        }
コード例 #2
0
ファイル: View.cs プロジェクト: andradam75/Synthetic
        /// <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);
        }
コード例 #3
0
ファイル: View.cs プロジェクト: andradam75/Synthetic
        /// <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));
        }
コード例 #4
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(true);

            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(true);
            Assert.AreEqual(1, points.Count);
            pnt = points[0] as ReferencePoint;
            Assert.IsTrue(pnt.Position.IsAlmostEqualTo(new XYZ(0.0, 0.0, 0.0)));
        }
コード例 #5
0
ファイル: ID.cs プロジェクト: ozanyetkin/rhino.inside-revit
        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.");
                }
            }
        }
コード例 #6
0
ファイル: Sheet.cs プロジェクト: andradam75/Synthetic
        /// <summary>
        /// Creates a Placeholder Sheet
        /// </summary>
        /// <param name="SheetNumber">The sheet number</param>
        /// <param name="SheetTitle">The sheet title</param>
        /// <param name="document">Document to create the sheet in.</param>
        /// <returns name="Sheet">Returns the created placeholder sheet as a dynamo wrapped sheet.</returns>
        public static DynaSheet CreatePlaceHolderSheet(string SheetNumber, string SheetTitle,
                                                       [DefaultArgument("Synthetic.Revit.Document.Current()")] RevitDoc document)
        {
            RevitSheet revitSheet;

            if (document.IsModifiable)
            {
                TransactionManager.Instance.EnsureInTransaction(document);
                revitSheet             = RevitSheet.CreatePlaceholder(document);
                revitSheet.SheetNumber = SheetNumber;
                RevitDB.Parameter paramName = revitSheet.get_Parameter(RevitDB.BuiltInParameter.SHEET_NAME);
                paramName.Set(SheetTitle);
                TransactionManager.Instance.TransactionTaskDone();
            }
            else
            {
                using (Autodesk.Revit.DB.Transaction trans = new Autodesk.Revit.DB.Transaction(document))
                {
                    trans.Start("Create Placeholder Sheet");
                    revitSheet             = RevitSheet.CreatePlaceholder(document);
                    revitSheet.SheetNumber = SheetNumber;
                    RevitDB.Parameter paramName = revitSheet.get_Parameter(RevitDB.BuiltInParameter.SHEET_NAME);
                    paramName.Set(SheetTitle);
                    trans.Commit();
                }
            }


            return((DynaSheet)revitSheet.ToDSType(false));
        }
コード例 #7
0
        /// <summary>
        /// Changes the workset of an element.
        /// </summary>
        /// <param name="element">Dynamo Elements.</param>
        /// <param name="workset">A revit workset</param>
        /// <returns name="element">The element that was changed.  Returns null if the change was unsuccessfull.</returns>
        public static dynamoElement SetElementWorkset(dynamoElement element, Workset workset)
        {
            //Get Revit Document object
            revitDoc doc = DocumentManager.Instance.CurrentDBDocument;

            Autodesk.Revit.DB.Element unwrapped = element.InternalElement;

            WorksetId wId = unwrapped.WorksetId;

            Autodesk.Revit.DB.Parameter wsParam = unwrapped.get_Parameter(BuiltInParameter.ELEM_PARTITION_PARAM);
            if (wsParam == null)
            {
                return(null);
            }
            if (doc.IsModifiable)
            {
                wsParam.Set(workset.internalId.IntegerValue);
            }
            else
            {
                using (Autodesk.Revit.DB.Transaction tx = new Autodesk.Revit.DB.Transaction(doc))
                {
                    tx.Start("Change Element's Workset");
                    wsParam.Set(workset.internalId.IntegerValue);
                    tx.Commit();
                }
            }
            return(unwrapped.ToDSType(true));;
        }
コード例 #8
0
        private void Load()
        {
            DirectoryInfo d        = new DirectoryInfo(_data.Setting.GetFolderPath());
            var           p        = d.GetFiles().ToList();
            string        filename = lb_view.SelectedItem.ToString();
            string        pathfile = "";

            foreach (var item in p)
            {
                if (item.Name.Replace(".json", "") == filename)
                {
                    pathfile = item.FullName;
                    break;
                }
            }
            var             json    = File.ReadAllText(pathfile);
            CegParameterSet dictemp = JsonConvert.DeserializeObject <CegParameterSet>(json);

            a.ViewSheet viewSheet = _doc.ActiveView as a.ViewSheet;
            using (a.Transaction tran = new a.Transaction(_doc, "Set Parameter Sheet"))
            {
                tran.Start();
                foreach (var item in dictemp.Parameters)
                {
                    foreach (var item2 in _data.dic.Parameters)
                    {
                        if (item.Value.Name == item2.Value.Name)
                        {
                            a.Parameter pa = viewSheet.LookupParameter(item2.Value.Name);
                            if (pa != null)
                            {
                                a.InternalDefinition definition = pa.Definition as a.InternalDefinition;
                                if (definition.BuiltInParameter != a.BuiltInParameter.SHEET_NAME && definition.BuiltInParameter != a.BuiltInParameter.SHEET_NUMBER)
                                {
                                    switch (item2.Value.Type)
                                    {
                                    case a.StorageType.Double:
                                        pa.Set(item.Value.AsDouble);
                                        break;

                                    case a.StorageType.String:
                                        pa.Set(item.Value.AsString);
                                        break;

                                    case a.StorageType.Integer:
                                        pa.Set(item.Value.AsInteger);
                                        break;

                                    default:
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }
                tran.Commit();
            }
            Close();
        }
コード例 #9
0
        public void CreateAllInThisParameterGroup(string targetGroup)
        {
            Autodesk.Revit.DB.Transaction docTransaction = RevitInterface.NewTransaction("mertens3d.com - parameterJerk - Create Shared Parameter");
            try
            {
                docTransaction.Start();
                foreach (DefinitionGroup group in RevitInterface.SharedParameterFile.Groups)
                {
                    if ((group.Name.Equals(targetGroup, StringComparison.OrdinalIgnoreCase)))
                    {
                        foreach (ExternalDefinition oneExternalDef in group.Definitions)
                        {
                            // MessageBox.Show(oneExternalDef.ParameterGroup.ToString())
                            RevitInterface.FamilyManager.AddParameter(oneExternalDef, BuiltInParameterGroup.PG_GRAPHICS, true);
                            // BuiltInParameterGroup.PG_GRAPHICS
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }

            docTransaction.Commit();
        }
コード例 #10
0
        /// <summary>
        /// Loads one ore more family documents into a specified family document.
        /// </summary>
        /// <param name="pathToContainerFamily">Path to the document into which the families will be loaded.</param>
        /// <param name="pathToFamiliesToLoad">Path to the families to load.</param>
        /// <returns></returns>
        public static bool LoadFamilyIntoFamilyDocument(string pathToContainerFamily, string[] pathToFamiliesToLoad)
        {
            Autodesk.Revit.DB.Document familyDoc = null;

            var app = DocumentManager.Instance.CurrentUIApplication.Application;

            familyDoc = app.OpenDocumentFile(pathToContainerFamily);

            if (!familyDoc.IsFamilyDocument)
            {
                throw new ArgumentException("The specified document is not a family document (.rfa)");
            }

            using (Autodesk.Revit.DB.Transaction transaction = new Autodesk.Revit.DB.Transaction(familyDoc))
            {
                if (transaction.Start("Load family into family") == TransactionStatus.Started)
                {
                    for (int i = 0; i < pathToFamiliesToLoad.Length; i++)
                    {
                        familyDoc.LoadFamily(pathToFamiliesToLoad[i]);
                    }

                    if (TransactionStatus.Committed != transaction.Commit())
                    {
                        transaction.RollBack();
                    }
                }
            }

            // The Close() method saves the document
            familyDoc.Close();

            return(true);
        }
コード例 #11
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);
            }
        }
コード例 #12
0
        private void importOneParameter(string requestedParameterName, Autodesk.Revit.DB.Document targetDoc)
        {
            DefinitionFile m_sharedParamFile;
            // = ptr2TargetDoc.Application.OpenSharedParameterFile
            FamilyManager m_Manager = targetDoc.FamilyManager;

            // ptr2TargetDoc.Application.SharedParametersFilename = p_fileName
            m_sharedParamFile = targetDoc.Application.OpenSharedParameterFile();
            foreach (DefinitionGroup Group in m_sharedParamFile.Groups)
            {
                foreach (ExternalDefinition oneExternalDef in Group.Definitions)
                {
                    if ((oneExternalDef.Name.ToLower() == requestedParameterName.ToLower()))
                    {
                        Autodesk.Revit.DB.Transaction docTransaction = new Autodesk.Revit.DB.Transaction(targetDoc);
                        docTransaction.SetName("mertens3d.com - parameterJerk - Create Shared Parameter");
                        try
                        {
                            docTransaction.Start();
                            // m_Manager.AddParameter(oneExternalDef, oneExternalDef.ParameterGroup, True)
                            // see http://spiderinnet.typepad.com/blog/2011/04/parameter-of-revit-api-15-set-familyparameter.html
                            FamilyParameter returnedParameter = m_Manager.AddParameter(oneExternalDef, _groupParameterUnderEnum, _isInstance);
                            docTransaction.Commit();
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.ToString());
                        }
                    }
                }
            }
        }
コード例 #13
0
ファイル: Elements.cs プロジェクト: andradam75/Synthetic
        /// <summary>
        /// Overwrite an elements parameters with the parameter values from a source element.
        /// </summary>
        /// <param name="Element">Destination element</param>
        /// <param name="SourceElement">Source element for the parameter values</param>
        /// <returns name="Element">The destination element</returns>
        public static DynaElem TransferParameters(DynaElem Element, DynaElem SourceElement)
        {
            string transactionName = "Transfer Parameter Between Elements";

            Action <DynaElem, DynaElem> transfer = (sElem, dElem) =>
            {
                _transferParameters(sElem.InternalElement, dElem.InternalElement);
            };

            RevitDoc document = Element.InternalElement.Document;

            if (document.IsModifiable)
            {
                TransactionManager.Instance.EnsureInTransaction(document);
                transfer(SourceElement, Element);
                TransactionManager.Instance.TransactionTaskDone();
            }
            else
            {
                using (Autodesk.Revit.DB.Transaction trans = new Autodesk.Revit.DB.Transaction(document))
                {
                    trans.Start(transactionName);
                    transfer(SourceElement, Element);
                    trans.Commit();
                }
            }
            return(Element);
        }
コード例 #14
0
ファイル: ElementBindingTests.cs プロジェクト: hipigod/Dynamo
        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);

            ViewModel.OpenCommand.Execute(testPath);

            var model    = ViewModel.Model;
            var selNodes = model.AllNodes.Where(x => x is DSElementSelection);
            var selNode  = selNodes.First() as DSElementSelection;

            selNode.SelectedElement = rpID;

            Assert.DoesNotThrow(() => ViewModel.Model.RunExpression());

            //Undo the creation of a reference point in Revit
            Assert.Inconclusive("TO DO");
        }
コード例 #15
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 Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            // This commands provide interact with active document
            UIApplication uiapp = commandData.Application;
            UIDocument    uidoc = uiapp.ActiveUIDocument;

            Autodesk.Revit.ApplicationServices.Application app = uiapp.Application;
            RVTDoc doc        = uidoc.Document;
            View   activeView = doc.ActiveView;

            using (RVTransaction t = new RVTransaction(doc))
            {
                // Start the transaction
                t.Start("Sample Command");

                try
                {
                    //SteelConnectionOptions.MatchPropertiesDetailedStructuralConnection(uidoc);
                }
                catch (OperationCanceledException)
                {
                    return(Result.Failed);
                }

                catch (Exception e)
                {
                    TaskDialog.Show("ERROR", e.Message);
                }
                // Commit the transaction
                t.Commit();
            }

            return(Result.Succeeded);
        }
コード例 #16
0
        public void XYZFromReferencePoint()
        {
            var model = dynSettings.Controller.DynamoModel;

            string samplePath = Path.Combine(_testPath, @".\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);
        }
コード例 #17
0
ファイル: XYZTests.cs プロジェクト: riteshchandawar/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);
        }
コード例 #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 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);
        }
コード例 #19
0
        public void CurveByPoints()
        {
            var model = dynSettings.Controller.DynamoModel;

            string samplePath = Path.Combine(_testPath, @".\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);
        }
コード例 #20
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");
        }
コード例 #21
0
        public void CreateInDynamoModifyInRevit()
        {
            //Create a wall in Dynamo
            string dynFilePath = Path.Combine(_testPath, @".\ElementBinding\CreateWallInDynamo.dyn");
            string testPath    = Path.GetFullPath(dynFilePath);

            ViewModel.OpenCommand.Execute(testPath);
            Assert.DoesNotThrow(() => ViewModel.Model.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();
            }
        }
コード例 #22
0
        private void button1_Click(object sender, EventArgs e)
        {
            var lstdata = Renamesheetcmd.ListSheet;
            var listASs = (from x in lstdata select x.RAssemblyname).Distinct().ToList();

            a.Transaction transaction = new a.Transaction(_doc, "aa");

            transaction.Start();

            foreach (var assembly in listASs)
            {
                try
                {
                    //
                    var lstCungtenASs = from x in lstdata where x.RAssemblyname == assembly select x;
                    var i             = 1;
                    foreach (var dt in lstCungtenASs)
                    {
                        var vs = _doc.GetElement(dt.Sheet) as a.ViewSheet;

                        vs.Name        = assembly;
                        vs.SheetNumber = i.ToString();
                        i++;
                    }
                }
                catch
                {
                }
            }
            transaction.Commit();


            Close();
        }
コード例 #23
0
ファイル: Elements.cs プロジェクト: andradam75/Synthetic
        /// <summary>
        /// Copy elements to the same location between documents.  Can be used to copy system types or view templates between documents.  Model elements are copied in the same location.  If the elements already exist, Revit will give you an option to either duplicate the types or cancel the operation.  Please note that documents are to be a Autodesk.Revit.DB.Document objects, not a Dynamo wrapped Revit Document.
        /// </summary>
        /// <param name="sourceDoc">The source document to copy items from.</param>
        /// <param name="elementIds">List of Element Ids of elements to be copied.</param>
        /// <param name="destinationDoc">The destination document.</param>
        /// <returns></returns>
        public static List <RevitElemId> CopyElements(RevitDoc sourceDoc, List <int> elementIds, RevitDoc destinationDoc)
        {
            string             transactionName = "Copy Elements from document " + sourceDoc.Title;
            List <RevitElemId> copiedElemsIds;
            List <RevitElemId> revitElemIds = new List <RevitElemId>();

            Func <RevitDoc, List <RevitElemId>, RevitDoc, List <RevitElemId> > copy = (sDoc, elemIds, dDoc) =>
            {
                Autodesk.Revit.DB.CopyPasteOptions cpo = new Autodesk.Revit.DB.CopyPasteOptions();
                return((List <RevitElemId>)Autodesk.Revit.DB.ElementTransformUtils.CopyElements(sDoc, elemIds, dDoc, null, cpo));
            };

            foreach (int id in elementIds)
            {
                revitElemIds.Add(new RevitElemId(id));
            }

            if (destinationDoc.IsModifiable)
            {
                TransactionManager.Instance.EnsureInTransaction(destinationDoc);
                copiedElemsIds = copy(sourceDoc, revitElemIds, destinationDoc);
                TransactionManager.Instance.TransactionTaskDone();
            }
            else
            {
                using (Autodesk.Revit.DB.Transaction trans = new Autodesk.Revit.DB.Transaction(destinationDoc))
                {
                    trans.Start(transactionName);
                    copiedElemsIds = copy(sourceDoc, revitElemIds, destinationDoc);
                    trans.Commit();
                }
            }

            return(copiedElemsIds);
        }
コード例 #24
0
ファイル: Sheet.cs プロジェクト: andradam75/Synthetic
        /// <summary>
        /// Adds a Revision to a Sheet
        /// </summary>
        /// <param name="Sheet">Dynamo wrapped Sheet element</param>
        /// <param name="Revision">Dynamo wrapped Revision element</param>
        /// <returns name="Sheet">Returns the modified sheet.</returns>
        public static DynaSheet AddRevision(DynaSheet Sheet, DynaRevision Revision)
        {
            RevitSheet    revitSheet    = (RevitSheet)Sheet.InternalElement;
            RevitRevision revitRevision = (RevitRevision)Revision.InternalElement;

            RevitDoc document = revitSheet.Document;

            List <RevitDB.ElementId> revisions = (List <RevitDB.ElementId>)revitSheet.GetAdditionalRevisionIds();

            if (!revisions.Contains(revitRevision.Id))
            {
                revisions.Add(revitRevision.Id);
            }

            if (document.IsModifiable)
            {
                TransactionManager.Instance.EnsureInTransaction(document);
                revitSheet.SetAdditionalRevisionIds(revisions);
                TransactionManager.Instance.TransactionTaskDone();
            }
            else
            {
                using (Autodesk.Revit.DB.Transaction trans = new Autodesk.Revit.DB.Transaction(document))
                {
                    trans.Start("Set Revision on Sheet");
                    revitSheet.SetAdditionalRevisionIds(revisions);
                    trans.Commit();
                }
            }

            return(Sheet);
        }
コード例 #25
0
ファイル: View.cs プロジェクト: andradam75/Synthetic
        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);
        }
コード例 #26
0
 protected void BeginTransaction(DB.Document document)
 {
     CurrentTransaction = new DB.Transaction(document, Name);
     if (CurrentTransaction.Start() != DB.TransactionStatus.Started)
     {
         CurrentTransaction.Dispose();
         CurrentTransaction = null;
         throw new InvalidOperationException($"Unable to start Transaction '{Name}'");
     }
 }
コード例 #27
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);
        }
コード例 #28
0
ファイル: CurveTests.cs プロジェクト: riteshchandawar/Dynamo
        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);
        }
コード例 #29
0
ファイル: Elements.cs プロジェクト: andradam75/Synthetic
        /// <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);
        }
コード例 #30
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 }
            });
        }
コード例 #31
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);
        }
コード例 #32
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();
            }
        }
コード例 #33
0
ファイル: ElementBindingTests.cs プロジェクト: heegwon/Dynamo
        /// <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
ファイル: 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;
                      }
                  }
                  }
            }
コード例 #35
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();
            }
        }
コード例 #36
0
ファイル: ElementBindingTests.cs プロジェクト: heegwon/Dynamo
        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));
        }
コード例 #37
0
ファイル: ElementBindingTests.cs プロジェクト: heegwon/Dynamo
        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();
            }
        }
コード例 #38
0
ファイル: ElementBindingTests.cs プロジェクト: heegwon/Dynamo
        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");
        }
コード例 #39
0
ファイル: ElementBindingTests.cs プロジェクト: heegwon/Dynamo
        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));
        }
コード例 #40
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;
                      }
                  }
              }
              }
        }
コード例 #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();
            }
        }