示例#1
0
 /// <summary>
 /// Rollback transaction group button click event
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 private void btnRollbackTransGroup_Click(object sender, EventArgs e)
 {
     if (m_transactionGroup != null)
     {
         m_transactionGroup.RollBack();
         AddNode(OperationType.RollbackTransactionGroup);
         m_transaction     = null;
         m_lastCreatedWall = null;
         UpdateButtonsStatus();
     }
 }
示例#2
0
        public Result AlignElements(ExternalCommandData commandData, ref string message, AlignType alignType)
        {
            UIDocument UIdoc = commandData.Application.ActiveUIDocument;
            Document   doc   = UIdoc.Document;

            using (TransactionGroup txg = new TransactionGroup(doc))
            {
                try
                {
                    // Add Your Code Here
                    AlignTag(UIdoc, alignType, txg);

                    // Return Success
                    return(Result.Succeeded);
                }

                catch (Autodesk.Revit.Exceptions.OperationCanceledException exceptionCanceled)
                {
                    //message = exceptionCanceled.Message;
                    if (txg.HasStarted())
                    {
                        txg.RollBack();
                    }
                    return(Result.Cancelled);
                }
                catch (ErrorMessageException errorEx)
                {
                    // checked exception need to show in error messagebox
                    message = errorEx.Message;
                    if (txg.HasStarted())
                    {
                        txg.RollBack();
                    }
                    return(Result.Failed);
                }
                catch (Exception ex)
                {
                    // unchecked exception cause command failed
                    message = ex.Message;
                    //Trace.WriteLine(ex.ToString());
                    if (txg.HasStarted())
                    {
                        txg.RollBack();
                    }
                    return(Result.Failed);
                }
            }
        }
示例#3
0
        public void CreateFloorFromLink()
        {
            using (var tg = new TransactionGroup(m_doc))
            {
                tg.Start("Create Floors");
                try
                {
                    foreach (var lrp in selectedLinkedRooms)
                    {
                        var room           = lrp.LinkedRoom;
                        var edgeArrayArray = GetRoomBoundaries(room, lrp.TransformValue);
                        var curveArrayList = CreateProfiles(edgeArrayArray);
                        var floorType      = FindFloorType(room);
                        var newFloor       = CreateNewFloor(room, curveArrayList, floorType);


                        if (null != newFloor)
                        {
                            createdFloors.Add(newFloor);
                        }
                    }
                    tg.Assimilate();
                }
                catch (Exception ex)
                {
                    tg.RollBack();
                    MessageBox.Show("Cannot create floors from the selected linked room.\n" + ex.Message, "Create Floors from Linked Rooms", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
        }
        public static void InvokeGroup(this Document doc, Action <TransactionGroup> action, string name = "default")
        {
            using (var tr = new TransactionGroup(doc, name))
            {
                tr.Start();

                action(tr);

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

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

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

                default:
                    return;
                }
            }
        }
示例#5
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            _dbdocument = commandData.Application.ActiveUIDocument.Document;


            TransactionGroup outerGroup = new TransactionGroup(_dbdocument, "preview control");

            outerGroup.Start();

            try
            {
                PreviewModel form = new PreviewModel(commandData.Application.Application, new ElementId(-1));
                form.ShowDialog();
            }
            catch (Exception e)
            {
                throw e;
            }
            finally
            {
                outerGroup.RollBack();
            }

            return(Result.Succeeded);
        }
示例#6
0
 //reverts ALL transactions since the class was created
 public void RevertTransactions()
 {
     if (transactionList.HasStarted())
     {
         transactionList.RollBack();
     }
 }
示例#7
0
        /// <summary>
        /// Rollback all changes and close this form
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cancelButton_Click(object sender, EventArgs e)
        {
            if (m_transCount > 0)
            {
                if (TaskDialogResult.No ==
                    TaskDialog.Show("Warning", "By canceling this dialog, all modifications to the model will be discarded."
                                    + " Do you want to proceed?", TaskDialogCommonButtons.Yes | TaskDialogCommonButtons.No))
                {
                    this.DialogResult = DialogResult.None;
                    return;
                }
            }

            // if there is still an active transaction, roll it back now, silently
            if ((null != m_transaction) && (m_transaction.GetStatus() == TransactionStatus.Started))
            {
                m_transaction.RollBack();
            }

            // if there are still transaction groups open, roll them back now, silently
            if ((null != m_transactionGroup) && (m_transactionGroup.GetStatus() == TransactionStatus.Started))
            {
                HandleNestedTransactionGroups(OperationType.RollbackTransactionGroup);
            }

            // silently roll back the main (hidden) transaction group
            if ((null != m_mainTtransactionGroup) && (m_mainTtransactionGroup.GetStatus() == TransactionStatus.Started))
            {
                m_mainTtransactionGroup.RollBack();
            }

            this.DialogResult = DialogResult.Cancel;
            this.Close();
        }
示例#8
0
        public Result Execute(
            ExternalCommandData commandData,
            ref string message, ElementSet elements)
        {
            UIApplication uiApp = commandData.Application;

            _uiDoc = uiApp.ActiveUIDocument;
            _doc   = _uiDoc.Document;

            SettingsUsr.Init();

            // this cleaned up the text display problem
            //			Application.SetCompatibleTextRenderingDefault(false);

            using (TransactionGroup tg = new TransactionGroup(_doc, "measure points"))
            {
                tg.Start();
                Process(_uiDoc, _doc);

                if (tg.GetStatus() == TransactionStatus.Started)
                {
                    tg.RollBack();
                }
            }

            return(Result.Succeeded);
        }
        public static TResult InvokeGroup <TResult>(this Document doc, Func <TransactionGroup, TResult> func, string name = "default")
        {
            using (var tr = new TransactionGroup(doc, name))
            {
                tr.Start();

                var result = func(tr);

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

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

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

                default:
                    return(result);
                }
            }
        }
示例#10
0
        /// <summary>
        /// This method implements the external command within
        /// Revit.
        /// </summary>
        /// <param name="commandData">An ExternalCommandData
        /// object which contains reference to Application and
        /// View needed by external command.</param>
        /// <param name="message">Error message can be returned
        /// by external command. This will be displayed only if
        /// the command status was "Failed". There is a limit
        /// of 1023 characters for this message; strings longer
        /// than this will be truncated.</param>
        /// <param name="elements">Element set indicating
        /// problem elements to display in the failure dialog.
        /// This will be used only if the command status was
        /// "Failed".</param>
        /// <returns>The result indicates if the execution
        /// fails, succeeds, or was canceled by user. If it
        /// does not succeed, Revit will undo any changes made
        /// by the external command.</returns>
        Result IExternalCommand.Execute(
            ExternalCommandData commandData, ref string message
            , ElementSet elements)
        {
            ResourceManager res_mng = new ResourceManager(
                GetType());
            ResourceManager def_res_mng = new ResourceManager(
                typeof(Properties.Resources));

            Result result = Result.Failed;

            try {
                UIApplication ui_app = commandData?.Application
                ;
                UIDocument  ui_doc = ui_app?.ActiveUIDocument;
                Application app    = ui_app?.Application;
                Document    doc    = ui_doc?.Document;

                /* Wrap all transactions into the transaction
                 * group. At first we get the transaction group
                 * localized name. */
                var tr_gr_name = UIBuilder.GetResourceString(
                    GetType(), typeof(Properties.Resources),
                    "_transaction_group_name");

                using (var tr_gr = new TransactionGroup(doc,
                                                        tr_gr_name)) {
                    if (TransactionStatus.Started == tr_gr
                        .Start())
                    {
                        /* Here do your work or the set of
                         * works... */
                        if (DoWork(commandData, ref message,
                                   elements))
                        {
                            tr_gr.Assimilate();
                            tr_gr.Commit();
                            result = Result.Succeeded;
                        }
                        else
                        {
                            tr_gr.RollBack();
                        }
                    }
                }
            }
            catch (Exception ex) {
                TaskDialog.Show(def_res_mng.GetString("_Error")
                                , ex.Message);

                result = Result.Failed;
            }
            finally {
                res_mng.ReleaseAllResources();
                def_res_mng.ReleaseAllResources();
            }

            return(result);
        }
示例#11
0
        /// <summary>
        /// Animate the transparency of an element. This will export images of the element, then revert the element back to where it was.
        /// Inspired by the Bad Monkeys team.
        /// </summary>
        /// <param name="element">The element to set transparency to.</param>
        /// <param name="startPercentage">The transparency start percent.</param>
        /// <param name="endPercentage">The transparency end percent.</param>
        /// <param name="iterations">Numnber of images.</param>
        /// <param name="directoryPath">Where to save the images.</param>
        /// <param name="view">View to export from.</param>
        /// <returns name="element">The element.</returns>
        /// <search>
        ///  rhythm
        /// </search>
        public static object AnimateTransparency(List <global::Revit.Elements.Element> element, int startPercentage, int endPercentage, int iterations, string directoryPath, global::Revit.Elements.Element view)
        {
            Autodesk.Revit.DB.Document doc = DocumentManager.Instance.CurrentDBDocument;
            UIDocument uiDocument          = new UIDocument(doc);

            Autodesk.Revit.DB.View internalView = (Autodesk.Revit.DB.View)view.InternalElement;
            //create a new form!
            DefaultProgressForm statusBar = new DefaultProgressForm("Exporting Images", "Exporting image {0} of " + iterations.ToString(), "Animate Element Transparency", iterations + 1);
            double d           = (endPercentage - startPercentage) / (iterations - 1.0);
            int    incrementor = Convert.ToInt32(d);


            //starts a transaction group so we can roolback the changes after
            using (TransactionGroup transactionGroup = new TransactionGroup(doc, "group"))
            {
                TransactionManager.Instance.ForceCloseTransaction();
                transactionGroup.Start();
                using (Transaction t2 = new Transaction(doc, "Modify parameter"))
                {
                    int num2 = 0;
                    while (startPercentage <= endPercentage)
                    {
                        statusBar.Activate();
                        t2.Start();
                        //declare the graphic settings overrides
                        OverrideGraphicSettings ogs = new OverrideGraphicSettings();
                        //solid fill id
                        ElementId pattId = new ElementId(20);
                        //set the overrides to the graphic settings
                        ogs.SetSurfaceTransparency(startPercentage);
                        foreach (var e in element)
                        {
                            //apply the changes to view
                            internalView.SetElementOverrides(e.InternalElement.Id, ogs);
                        }
                        t2.Commit();

                        uiDocument.RefreshActiveView();
                        var exportOpts = new ImageExportOptions
                        {
                            FilePath              = directoryPath + num2.ToString(),
                            FitDirection          = FitDirectionType.Horizontal,
                            HLRandWFViewsFileType = ImageFileType.PNG,
                            ImageResolution       = ImageResolution.DPI_300,
                            ShouldCreateWebSite   = false
                        };
                        doc.ExportImage(exportOpts);
                        ++num2;
                        startPercentage = startPercentage + incrementor;
                        statusBar.Increment();
                    }
                }
                transactionGroup.RollBack();
            }
            statusBar.Close();

            return(element);
        }
示例#12
0
        public void RenameAllExecuted(object param)
        {
            using (TransactionGroup tg = new TransactionGroup(m_doc))
            {
                tg.Start("Rename Families");
                try
                {
                    ProgressManager.InitializeProgress("Renaming.. ", typeProperties.Count);
                    for (int i = 0; i < typeProperties.Count; i++)
                    {
                        ProgressManager.StepForward();
                        FamilyTypeProperties ftp = typeProperties[i];
                        if (ftp.IsLinked)
                        {
                            continue;
                        }

                        ElementType eType = m_doc.GetElement(ftp.FamilyTypeId) as ElementType;
                        if (null != eType)
                        {
                            using (Transaction trans = new Transaction(m_doc))
                            {
                                trans.Start("Rename");
                                try
                                {
                                    if (eType is FamilySymbol)
                                    {
                                        (eType as FamilySymbol).Family.Name = ftp.FamilyName;
                                    }

                                    eType.Name = ftp.TypeName;
                                    trans.Commit();

                                    typeProperties[i].CurrentFamilyName = ftp.FamilyName;
                                    typeProperties[i].CurrentTypeName   = ftp.TypeName;
                                    typeProperties[i].IsLinked          = true;
                                    typeProperties[i].ToolTip           = "Current Family Name: " + ftp.FamilyName + ", Current Tyle Name: " + ftp.TypeName;
                                    typeProperties[i].IsSelected        = false;
                                }
                                catch (Exception ex)
                                {
                                    trans.RollBack();
                                    string message = ex.Message;
                                }
                            }
                        }
                    }
                    ProgressManager.FinalizeProgress();
                    this.StatusText = fileName;
                    tg.Assimilate();
                }
                catch (Exception ex)
                {
                    tg.RollBack();
                    MessageBox.Show("Failed to rename families and types.\n" + ex.Message, "Rename Families and Types", MessageBoxButton.OK, MessageBoxImage.Warning);
                }
            }
        }
        public bool RunViewAnalysis(ProgressBar progressBar, TextBlock statusLable)
        {
            bool result = true;

            using (TransactionGroup tg = new TransactionGroup(m_doc))
            {
                tg.Start("Run View Analysis");
                try
                {
                    UpdateLableDelegate updateLabelDelegate = new UpdateLableDelegate(statusLable.SetValue);

                    List <int> keys         = roomDictionary.Keys.ToList();
                    int        finishedRoom = 0;
                    foreach (int roomId in keys)
                    {
                        if (AbortFlag.GetAbortFlag())
                        {
                            return(false);
                        }

                        using (Transaction trans = new Transaction(m_doc))
                        {
                            trans.Start("Find Visibility");
                            try
                            {
                                RoomData rData    = roomDictionary[roomId];
                                string   roomInfo = rData.RoomObj.Name + " (" + finishedRoom + " of " + keys.Count + ")";
                                Dispatcher.CurrentDispatcher.Invoke(updateLabelDelegate, System.Windows.Threading.DispatcherPriority.Background, new object[] { TextBlock.TextProperty, roomInfo });
                                progressBar.Visibility = System.Windows.Visibility.Visible;

                                RoomData updatedData = FindVisibility(rData, progressBar);

                                roomDictionary.Remove(roomId);
                                roomDictionary.Add(roomId, updatedData);
                                finishedRoom++;
                                trans.Commit();
                            }
                            catch (Exception ex)
                            {
                                trans.RollBack();
                                result = false;
                                string message = ex.Message;
                            }
                        }
                    }

                    tg.Assimilate();
                }
                catch (Exception ex)
                {
                    result = false;
                    MessageBox.Show("Failed to run view analysis.\n" + ex.Message, "Run View Analysis", MessageBoxButton.OK, MessageBoxImage.Warning);
                    tg.RollBack();
                }
            }
            return(result);
        }
示例#14
0
        private bool AssignParameter(XYZLocation xyzLocation)
        {
            var assigned = false;

            using (var tg = new TransactionGroup(m_doc))
            {
                tg.Start("Assign Parameters");
                try
                {
                    foreach (var eId in instanceIds)
                    {
                        using (var trans = new Transaction(m_doc))
                        {
                            trans.Start("Assign Parameter");
                            try
                            {
                                var instance = m_doc.GetElement(eId) as FamilyInstance;
                                if (null != instance)
                                {
                                    var locationPt = instance.Location as LocationPoint;
                                    var point      = locationPt.Point;

                                    XYZ location1;
                                    XYZ location2;

                                    xyzLocation.GetTransformedValues(point, out location1, out location2);

                                    //assign parameters
                                    var paramSet = SetParameterValue(instance, "XYZ_Location_1_Description", xyzLocation.Description1);
                                    paramSet = SetParameterValue(instance, "XYZ_Location_1_X", location1.X);
                                    paramSet = SetParameterValue(instance, "XYZ_Location_1_Y", location1.Y);
                                    paramSet = SetParameterValue(instance, "XYZ_Location_1_Z", location1.Z);
                                    paramSet = SetParameterValue(instance, "XYZ_Location_2_Description", xyzLocation.Description2);
                                    paramSet = SetParameterValue(instance, "XYZ_Location_2_X", location2.X);
                                    paramSet = SetParameterValue(instance, "XYZ_Location_2_Y", location2.Y);
                                    paramSet = SetParameterValue(instance, "XYZ_Location_2_Z", location2.Z);
                                }
                                trans.Commit();
                            }
                            catch (Exception ex)
                            {
                                trans.RollBack();
                                var messag = ex.Message;
                            }
                        }
                    }
                    tg.Assimilate();
                }
                catch (Exception ex)
                {
                    tg.RollBack();
                    var message = ex.Message;
                }
            }
            return(assigned);
        }
示例#15
0
        public bool CreateCeilingFromLink()
        {
            var created = false;

            using (var tg = new TransactionGroup(Doc))
            {
                tg.Start("Create Ceilings");
                var failureMessages = new StringBuilder();
                try
                {
                    foreach (var lrp in selectedLinkedRooms)
                    {
                        var         room          = lrp.LinkedRoom;
                        var         ceilingsFound = new List <Ceiling>();
                        CeilingType ceilingType   = null;

                        using (var trans = new Transaction(Doc))
                        {
                            trans.Start("Create a Ceiling");
                            try
                            {
                                ceilingsFound = FindCeilings(room, lrp.TransformValue);
                                if (ceilingsFound.Count > 0)
                                {
                                    ceilingType = FindCeilingType(room);
                                }
                                trans.Commit();
                            }
                            catch (Exception ex)
                            {
                                trans.RollBack();
                                failureMessages.AppendLine(room.Name + ": " + ex.Message);
                            }
                        }

                        if (ceilingsFound.Count > 0 && null != ceilingType)
                        {
                            var copiedCeilings = CreateCeilings(room, ceilingsFound, ceilingType, ref failureMessages);
                            if (copiedCeilings.Count > 0 && !createdCeilings.ContainsKey(room.Id.IntegerValue))
                            {
                                createdCeilings.Add(room.Id.IntegerValue, copiedCeilings);
                                created = true;
                            }
                        }
                    }
                    tg.Assimilate();
                }
                catch (Exception ex)
                {
                    tg.RollBack();
                    MessageBox.Show("Cannot create ceilings from the selected rooms.\n" + ex.Message, "Create Ceilings", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
            return(created);
        }
示例#16
0
        public Dictionary <ElementId, string> Purge(params ElementId[] elementIds)
        {
            if (elementIds == null)
            {
                return(null);
            }

            Dictionary <ElementId, string> result = new Dictionary <ElementId, string>();

            if (elementIds.Length == 0)
            {
                return(result);
            }

            Application application = document.Application;

            application.DocumentChanged += Application_DocumentChanged;

            foreach (ElementId elementId in elementIds)
            {
                string name = document.GetElement(elementId)?.Name;

                using (TransactionGroup transactionGroup = new TransactionGroup(document, "Purge Materials"))
                {
                    transactionGroup.Start();
                    using (Transaction transaction = new Transaction(document, "Purge Material"))
                    {
                        transaction.Start();
                        checkElements = true;
                        document.Delete(elementId);
                        transaction.Commit();
                    }

                    checkElements = false;

                    if (purge)
                    {
                        transactionGroup.Assimilate();
                        result[elementId] = name;
                    }
                    else
                    {
                        transactionGroup.RollBack();
                    }
                }
            }

            application.DocumentChanged -= Application_DocumentChanged;

            Initialize();

            return(result);
        }
示例#17
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 Autodesk.Revit.UI.Result Execute(ExternalCommandData commandData, ref string message, Autodesk.Revit.DB.ElementSet elements)
        {
            // data verification
            if (null == commandData.Application.ActiveUIDocument)
            {
                return(Autodesk.Revit.UI.Result.Failed);
            }

            MyDocument mydocument = new MyDocument(commandData);



            // check whether the mass is kind of parallelepiped
            CurtainSystem.MassChecker checker = new CurtainSystem.MassChecker(mydocument);
            bool validMass = checker.CheckSelectedMass();

            if (!validMass)
            {
                message = Properties.Resources.MSG_InvalidSelection;
                return(Result.Cancelled);
            }

            UI.CurtainForm   curtainForm      = null;
            TransactionGroup transactionGroup = new TransactionGroup(commandData.Application.ActiveUIDocument.Document);

            try
            {
                transactionGroup.Start("CurtainSystemOperation");
                curtainForm = new UI.CurtainForm(mydocument);

                if (null != curtainForm && false == curtainForm.IsDisposed)
                {
                    curtainForm.ShowDialog();
                }

                transactionGroup.Commit();
            }
            catch (System.Exception ex)
            {
                transactionGroup.RollBack();
                message = ex.Message;
                return(Result.Failed);
            }
            finally
            {
                if (null != curtainForm && false == curtainForm.IsDisposed)
                {
                    curtainForm.Dispose();
                }
            }

            return(Autodesk.Revit.UI.Result.Succeeded);
        }
示例#18
0
        public Result AlignElements(ExternalCommandData commandData, ref string message, AlignType alignType)
        {
            UIDocument activeUiDocument = commandData.Application.ActiveUIDocument;

            using (TransactionGroup txg = new TransactionGroup(activeUiDocument.Document))
            {
                try
                {
                    this.AlignTag(activeUiDocument, alignType, txg);
                    return((Result)0);
                }
                catch (Autodesk.Revit.Exceptions.OperationCanceledException ex)
                {
                    if (txg.HasStarted())
                    {
                        txg.RollBack();
                    }
                    return((Result)1);
                }
                catch (ErrorMessageException ex)
                {
                    message = ex.Message;
                    if (txg.HasStarted())
                    {
                        txg.RollBack();
                    }
                    return(Result.Failed);
                }
                catch (Exception ex)
                {
                    message = ex.Message;
                    if (txg.HasStarted())
                    {
                        txg.RollBack();
                    }
                    return(Result.Failed);
                }
            }
        }
示例#19
0
        /// <summary>
        /// 处理方法
        /// </summary>
        /// <param name="inputCommandData"></param>
        /// <param name="useDoc"></param>
        private void WorkHanlder(Autodesk.Revit.UI.ExternalCommandData inputCommandData, Document useDoc)
        {
            //Ui层事务组
            using (TransactionGroup useGroup = new TransactionGroup(useDoc, "uiGroup"))
            {
                try
                {
                    useGroup.Start();
                    //利用UI准备请求
                    m_useRequestMaker.PrepareRequest();
                    useGroup.Assimilate();
                }
                catch (Exception ex)
                {
                    useGroup.RollBack();
                    throw ex;
                }
            }

            //若存在响应处理器
            if (null != m_useResponseHanlder)
            {
                m_useResponseHanlder.AddStartTime(DateTime.Now);
            }

            //获得请求封装
            var lstInputRequest = m_useRequestMaker.GetAllInputRequest();

            List <RevitModelRequest> lstRevitModelRequest = new List <RevitModelRequest>();

            Group(inputCommandData, lstInputRequest, lstRevitModelRequest);

            //响应列表
            List <RevitModelRebuildResponse> lstUseResponse = new List <RevitModelRebuildResponse>();

            ReBuild(useDoc, lstRevitModelRequest, lstUseResponse);

            //若存在响应处理器
            if (null != m_useResponseHanlder)
            {
                m_useResponseHanlder.AddEndTime(DateTime.Now);
                //注册响应
                foreach (var oneResponse in lstUseResponse)
                {
                    m_useResponseHanlder.AddOneResponse(oneResponse);
                }

                //处理响应
                m_useResponseHanlder.HanlderResponse();
            }
        }
示例#20
0
        public static DirectShapeContainer ConverToDirectShape(Document doc, RhinoGeometryContainer container)
        {
            DirectShapeContainer shapeContainer = new DirectShapeContainer();

            try
            {
                using (TransactionGroup tg = new TransactionGroup(doc))
                {
                    tg.Start("Start Convert");
                    try
                    {
                        //Brep
                        foreach (RhinoObjectInfo rInfo in container.Breps)
                        {
                            using (Transaction trans = new Transaction(doc))
                            {
                                try
                                {
                                    trans.Start("Convert To DirectShape");
                                    DirectShapeInfo shapeInfo = ConvertBrep(doc, rInfo);
                                    if (shapeInfo.DirectShapeId != ElementId.InvalidElementId)
                                    {
                                        shapeContainer.DirectShapes.Add(shapeInfo);
                                    }
                                    trans.Commit();
                                }
                                catch (Exception ex)
                                {
                                    trans.RollBack();
                                    MessageBox.Show("Cannot Connvert.\n" + ex.Message);
                                    string message = ex.Message;
                                }
                            }
                        }
                        tg.Assimilate();
                    }
                    catch (Exception ex)
                    {
                        string message = ex.Message;
                        MessageBox.Show("Cannot Connvert.\n" + ex.Message);
                        tg.RollBack();
                    }
                }
            }
            catch (Exception ex)
            {
                string message = ex.Message;
                MessageBox.Show("Cannot Connvert.\n" + ex.Message);
            }
            return(shapeContainer);
        }
示例#21
0
        public void PurgeMaterials(Document doc)
        {
            Application app = doc.Application;

            app.DocumentChanged += documentChanged_PurgeMaterials;
            List <Element> materials           = new FilteredElementCollector(doc).OfClass(typeof(Material)).ToList();
            string         deletedMaterials    = "";
            int            unusedMaterialCount = 0;

            foreach (Element material in materials)
            {
                modifiedByDeleteMaterial = 0;
                materialName             = material.Name + " (id " + material.Id + ")";
                using (TransactionGroup tg = new TransactionGroup(doc, "Delete Material: " + materialName))
                {
                    tg.Start();
                    using (Transaction t = new Transaction(doc, "delete material"))
                    {
                        t.Start();
                        checkForPurgeMaterials = true;
                        doc.Delete(material.Id);

                        // commit the transaction to trigger the DocumentChanged event
                        t.Commit();
                    }
                    checkForPurgeMaterials = false;

                    if (modifiedByDeleteMaterial == 1)
                    {
                        unusedMaterialCount++;
                        deletedMaterials += materialName + Environment.NewLine;
                        tg.Assimilate();
                    }
                    else // rollback the transaction group to undo the deletion
                    {
                        tg.RollBack();
                    }
                }
            }

            TaskDialog td = new TaskDialog("Info");

            td.MainInstruction = "Deleted " + unusedMaterialCount + " materials";
            td.MainContent     = deletedMaterials;
            td.Show();

            app.DocumentChanged -= documentChanged_PurgeMaterials;
        }
示例#22
0
        /// <summary>
        /// 重建
        /// </summary>
        /// <param name="useDoc"></param>
        /// <param name="lstRevitModelRequest"></param>
        /// <param name="lstUseResponse"></param>
        private void ReBuild(Document useDoc, List <RevitModelRequest> lstRevitModelRequest, List <RevitModelRebuildResponse> lstUseResponse)
        {
            TransactionGroup useTransactionGroup = new TransactionGroup(useDoc, "quickModel");

            try
            {
                useTransactionGroup.Start();

                foreach (var oneRebuildeRequest in lstRevitModelRequest)
                {
                    RevitModelRebuildResponse tempResponse = new RevitModelRebuildResponse();
                    tempResponse.UseRequest = oneRebuildeRequest;

                    string useHanlderName = GetHanlderName <RebuilderAttribute>(oneRebuildeRequest);

                    if (string.IsNullOrWhiteSpace(useHanlderName) || !m_dicUseRebuilderMap.ContainsKey(useHanlderName))
                    {
                        tempResponse.IfSucess = false;
                    }
                    else
                    {
                        Element createdElement = null;

                        var useHanlder = m_dicUseRebuilderMap[useHanlderName];

                        tempResponse.IfSucess       = useHanlder.TryRebuildRevitModel(useDoc, oneRebuildeRequest, out createdElement);
                        tempResponse.CreatedElement = createdElement;
                    }
                    lstUseResponse.Add(tempResponse);
                }
                useTransactionGroup.Assimilate();
            }
            catch (Exception)
            {
                useTransactionGroup.RollBack();

                //响应回置
                foreach (var oneResponse in lstUseResponse)
                {
                    oneResponse.IfSucess       = false;
                    oneResponse.CreatedElement = null;
                }
            }
        }
示例#23
0
        } //main method

        //---------------------------------华丽的分割线---------------------------------

        //以下为各种method

        //对整个视图的元素MARK进行文字注释
        public void VIewTextMark(Document doc, ElementId viewid)
        {
            Autodesk.Revit.DB.View view = doc.GetElement(viewid) as Autodesk.Revit.DB.View;

            //提取文档中特定的族-自定义墙身-阳台、转角窗、窗、设备平台
            IList <Element>         collector_4temp = (new FilteredElementCollector(doc, viewid)).OfClass(typeof(FamilyInstance)).OfCategory(BuiltInCategory.OST_GenericModel).WhereElementIsNotElementType().ToElements();
            IList <Element>         lst_eles_4      = getFieldFinstance(collector_4temp, "围护构件"); //获取特定字段的族实例
            ICollection <ElementId> lst_eles_4_ids  = ELEsToeleIds(doc, lst_eles_4);              //将元素列表转化为Id列表

            //提取文档中所有内建门窗族的实例
            IList <Element> collector_DoWn = (new FilteredElementCollector(doc, viewid)).OfClass(typeof(FamilyInstance)).WherePasses(new LogicalOrFilter(new ElementCategoryFilter(BuiltInCategory.OST_Doors), new ElementCategoryFilter(BuiltInCategory.OST_Windows))).WhereElementIsNotElementType().ToElements();
            //列表合并
            IList <Element>         collector_DoWn_4   = collector_DoWn.Union(lst_eles_4).ToList();
            ICollection <ElementId> collector_DoWn_ids = ELEsToeleIds(doc, collector_DoWn);//将元素列表转化为Id列表

            //提取文档中的幕墙元素
            IList <Element>         collector_glasswall         = (new FilteredElementCollector(doc, viewid)).OfCategory(BuiltInCategory.OST_Walls).WhereElementIsNotElementType().ToElements();
            IList <Element>         lst_collector_glasswall     = getFieldFinstance(collector_glasswall, "幕墙"); //获取特定字段的族实例
            ICollection <ElementId> lst_collector_glasswall_ids = ELEsToeleIds(doc, lst_collector_glasswall);   //将元素列表转化为Id列表

            //列表合并
            IList <Element>         collector_DoWn_4_gW     = collector_DoWn_4.Union(lst_collector_glasswall).ToList();
            ICollection <ElementId> collector_DoWn_4_gW_ids = ELEsToeleIds(doc, collector_DoWn_4_gW);//将元素列表转化为Id列表

            //开展事务组,文字注释标记
            using (TransactionGroup transGroup = new TransactionGroup(doc, "创建文字注释标记"))
            {
                if (transGroup.Start() == TransactionStatus.Started)
                {
                    foreach (ElementId eleId in collector_DoWn_4_gW_ids)//遍历所有实例元素
                    {
                        transCreatMoveTNT(doc, eleId, view, lst_eles_4_ids, collector_DoWn_ids, lst_collector_glasswall_ids);
                    }
                    transGroup.Assimilate();
                }
                else
                {
                    transGroup.RollBack();
                }
            }
            //ShowTaskDialog("Revit2020-操作成功提示", "内建门、窗\n\r" + "自定义墙身-阳台\n\r" + "自定义墙身-窗\n\r" + "自定义墙身-转角窗\n\r" + "自定义墙身-阳台\n\r" + "上述族实例在相关视图已经二维文字注释完毕");
        }
示例#24
0
        /// <summary>
        /// This node will attempt to rotate a plan view into a 3D view. Use at your own risk!
        /// </summary>
        /// <param name="viewPlan">The plan view to rotate</param>
        /// <param name="rotationLine">The line to rotate along.</param>
        /// <param name="inputAngle">The plan view to get outline from.</param>
        /// <returns name="cropBox">The cropBox.</returns>
        /// <search>
        /// view, outline,rhythm
        /// </search>
        public static object Rotate(global::Revit.Elements.Element viewPlan, global::Revit.Elements.ModelCurve rotationLine, double inputAngle)
        {
            Autodesk.Revit.DB.Document doc          = DocumentManager.Instance.CurrentDBDocument;
            Autodesk.Revit.DB.View     internalView = (Autodesk.Revit.DB.View)viewPlan.InternalElement;
            var viewBbox = internalView.CropBox;

            Autodesk.Revit.DB.ModelCurve internalLine = (Autodesk.Revit.DB.ModelCurve)rotationLine.InternalElement;

            Autodesk.Revit.DB.Line rotationLineBound = Autodesk.Revit.DB.Line.CreateBound(internalLine.GeometryCurve.GetEndPoint(0), internalLine.GeometryCurve.GetEndPoint(1));

            Autodesk.Revit.DB.Element cropBoxElement = null;
            using (TransactionGroup tGroup = new TransactionGroup(doc))
            {
                tGroup.Start("Temp to find crop box element");
                using (Transaction t2 = new Transaction(doc, "Temp to find crop box element"))
                {
                    // Deactivate crop box
                    t2.Start();
                    internalView.CropBoxVisible = false;
                    t2.Commit();
                    // Get all visible elements;
                    // this excludes hidden crop box
                    FilteredElementCollector collector  = new FilteredElementCollector(doc, internalView.Id);
                    ICollection <ElementId>  shownElems = collector.ToElementIds();
                    // Activate crop box
                    t2.Start();
                    internalView.CropBoxVisible = true;
                    t2.Commit();
                    // Get all visible elements excluding
                    // everything except the crop box
                    collector = new FilteredElementCollector(doc, internalView.Id);
                    collector.Excluding(shownElems);
                    cropBoxElement = collector.FirstElement();
                }
                tGroup.RollBack();
            }
            TransactionManager.Instance.EnsureInTransaction(doc);
            ElementTransformUtils.RotateElement(doc, cropBoxElement.Id, rotationLineBound, inputAngle);
            TransactionManager.Instance.TransactionTaskDone();

            return(cropBoxElement);
        }
示例#25
0
        public Result Execute(
            ExternalCommandData commandData,
            ref string message, ElementSet elements)
        {
            UIApplication uiApp = commandData.Application;
            Document      _doc  = uiApp.ActiveUIDocument.Document;

            DlxMeasure mx = DlxMeasure.Instance();

            // this cleaned up the text display problem
            //			Application.SetCompatibleTextRenderingDefault(false);
            using (TransactionGroup tg = new TransactionGroup(_doc, "AO delux measure"))
            {
                tg.Start();
                mx.Measure(uiApp);
                tg.RollBack();
            }

            return(Result.Succeeded);
        }
 public static void ExecuteTransactionGroup(Document document, Action action, string transactionGroupName)
 {
     using (var transactionGroup = new TransactionGroup(document, transactionGroupName))
     {
         try
         {
             transactionGroup.Start();
             action();
             transactionGroup.Assimilate();
         }
         catch
         {
             if (transactionGroup.HasStarted())
             {
                 transactionGroup.RollBack();
             }
             throw;
         }
     }
 }
示例#27
0
        /// <summary>
        /// This method implements the external command within
        /// Revit.
        /// </summary>
        /// <param name="commandData">An ExternalCommandData
        /// object which contains reference to Application and
        /// View needed by external command.</param>
        /// <param name="message">Error message can be returned
        /// by external command. This will be displayed only if
        /// the command status was "Failed". There is a limit
        /// of 1023 characters for this message; strings longer
        /// than this will be truncated.</param>
        /// <param name="elements">Element set indicating
        /// problem elements to display in the failure dialog.
        /// This will be used only if the command status was
        /// "Failed".</param>
        /// <returns>The result indicates if the execution
        /// fails, succeeds, or was canceled by user. If it
        /// does not succeed, Revit will undo any changes made
        /// by the external command.</returns>
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            Result result = Result.Failed;

            try
            {
                UIApplication ui_app = commandData?.Application;
                UIDocument    ui_doc = ui_app?.ActiveUIDocument;
                Application   app    = ui_app?.Application;
                Document      doc    = ui_doc?.Document;

                var tr_gr_name = "3DView";
                using (var tr_gr = new TransactionGroup(doc, tr_gr_name))
                {
                    if (TransactionStatus.Started == tr_gr.Start())
                    {
                        if (DoWork(commandData, ref message,
                                   elements))
                        {
                            if (TransactionStatus.Committed ==
                                tr_gr.Assimilate())
                            {
                                result = Result.Succeeded;
                            }
                        }
                    }
                    else
                    {
                        tr_gr.RollBack();
                    }
                }
            }
            catch (Exception ex)
            {
                TaskDialog.Show("Error", ex.Message);
                result = Result.Failed;
            }

            return(result);
        }
示例#28
0
        public void AlignTag(AlignType alignType, TransactionGroup txg, ICollection <ElementId> selectedIds, Document document)
        {
            // 1. First Proposed Change
            //    First check if there is something that's been seleted, and if so - operate on that
            //    However, if the Uidoc.Slection is empty, prompt for selection.
            //    This allows you to stay on the 'Add-ins' Tab and keep using the 'Align' tab without going back and forth to 'Modify'
            //    TO-DO: Should we disselect after we are done? (delete the boolean stuff if you don't think it's worth disselecting)

            using (Transaction tx = new Transaction(document))
            {
                txg.Start(AlignTypeToText(alignType));

                tx.Start("Prepare tags");
                Debug.WriteLine(DateTime.Now.ToString() + " - Start Prepare tags");

                List <AnnotationElement> annotationElements = RetriveAnnotationElementsFromSelection(document, tx, selectedIds);

                txg.RollBack();
                Debug.WriteLine(DateTime.Now.ToString() + " - Rollback Prepare tags");

                txg.Start(AlignTypeToText(alignType));

                tx.Start(AlignTypeToText(alignType));
                Debug.WriteLine(DateTime.Now.ToString() + " - Start align tags");

                if (annotationElements.Count > 1)
                {
                    AlignAnnotationElements(annotationElements, alignType, document);
                }

                Debug.WriteLine(DateTime.Now.ToString() + " - Commit align tags");

                tx.Commit();

                txg.Assimilate();
            }
        }
示例#29
0
        public void RenameSelectedExecuted(object param)
        {
            using (TransactionGroup tg = new TransactionGroup(m_doc))
            {
                tg.Start("Rename Families");
                try
                {
                    if (selectedModelIndex > -1 && selectedCategoryIndex > -1)
                    {
                        string modelName    = modelNames[selectedModelIndex];
                        string categoryName = categoryNames[selectedCategoryIndex];

                        var itemFound = from item in typeProperties where item.ModelName == modelName && item.CategoryName == categoryName && item.IsSelected select item;
                        ProgressManager.InitializeProgress("Renaming.. ", itemFound.Count());
                        if (itemFound.Count() > 0)
                        {
                            foreach (FamilyTypeProperties ftp in itemFound)
                            {
                                ProgressManager.StepForward();
                                if (ftp.IsLinked)
                                {
                                    continue;
                                }
                                int index = typeProperties.IndexOf(ftp);

                                ElementType symbol = m_doc.GetElement(ftp.FamilyTypeId) as ElementType;
                                if (null != symbol)
                                {
                                    using (Transaction trans = new Transaction(m_doc))
                                    {
                                        trans.Start("Rename");
                                        try
                                        {
                                            if (symbol is FamilySymbol)
                                            {
                                                (symbol as FamilySymbol).Family.Name = ftp.FamilyName;
                                            }
                                            symbol.Name = ftp.TypeName;

                                            trans.Commit();

                                            typeProperties[index].CurrentFamilyName = ftp.FamilyName;
                                            typeProperties[index].CurrentTypeName   = ftp.TypeName;
                                            typeProperties[index].IsLinked          = true;
                                            typeProperties[index].ToolTip           = "Current Family Name: " + ftp.FamilyName + ", Current Tyle Name: " + ftp.TypeName;
                                            typeProperties[index].IsSelected        = false;
                                        }
                                        catch (Exception ex)
                                        {
                                            trans.RollBack();
                                            string message = ex.Message;
                                        }
                                    }
                                }
                            }
                        }
                        ProgressManager.FinalizeProgress();
                        this.StatusText = fileName;
                    }
                    tg.Assimilate();
                }
                catch (Exception ex)
                {
                    tg.RollBack();
                    MessageBox.Show("Failed to rename families and types.\n" + ex.Message, "Rename Families and Types", MessageBoxButton.OK, MessageBoxImage.Warning);
                }
            }
        }
示例#30
0
文件: Command.cs 项目: AMEE/revit
        /// <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 Autodesk.Revit.UI.Result Execute(ExternalCommandData commandData, ref string message, Autodesk.Revit.DB.ElementSet elements)
        {
            // data verification
             if (null == commandData.Application.ActiveUIDocument)
             {
            return Autodesk.Revit.UI.Result.Failed;
             }

             MyDocument mydocument = new MyDocument(commandData);

             // check whether the mass is kind of parallelepiped
             CurtainSystem.MassChecker checker = new CurtainSystem.MassChecker(mydocument);
             bool validMass = checker.CheckSelectedMass();

             if (!validMass)
             {
            message = Properties.Resources.MSG_InvalidSelection;
            return Result.Cancelled;
             }

             UI.CurtainForm curtainForm = null;
             TransactionGroup transactionGroup = new TransactionGroup(commandData.Application.ActiveUIDocument.Document);
             try
             {
            transactionGroup.Start("CurtainSystemOperation");
            curtainForm = new UI.CurtainForm(mydocument);

            if (null != curtainForm && false == curtainForm.IsDisposed)
            {
               curtainForm.ShowDialog();
            }

            transactionGroup.Commit();
             }
             catch (System.Exception ex)
             {
             	transactionGroup.RollBack();
            message = ex.Message;
            return Result.Failed;
             }
             finally
             {
            if (null != curtainForm && false == curtainForm.IsDisposed)
            {
               curtainForm.Dispose();
            }
             }

             return Autodesk.Revit.UI.Result.Succeeded;
        }
        /// <summary>
        /// 获取当前模型指定视图内的所有最外层的墙体
        /// Get all the outermost walls in the
        /// specified view of the current model
        /// </summary>
        /// <param name="doc"></param>
        /// <param name="view">视图,默认是当前激活的视图
        /// View, default is currently active view</param>
        public static List <ElementId> GetOutermostWalls(
            Document doc,
            View view = null)
        {
            double offset = Util.MmToFoot(1000);

            if (view == null)
            {
                view = doc.ActiveView;
            }

            #region Obsolete code using wall location line instad of bounding box
            //获取顶点 最小x,最大y ; 最大x,最小y

#if BEFORE_USING_BOUNDING_BOX
            List <Wall> wallList = new FilteredElementCollector(doc)
                                   .OfClass(typeof(Wall))
                                   .Cast <Wall>()
                                   .ToList();

            double maxX = -1D;
            double minX = -1D;
            double maxY = -1D;
            double minY = -1D;

            wallList.ForEach((wall) =>
            {
                Curve curve = (wall.Location as LocationCurve).Curve;
                XYZ xyz1    = curve.GetEndPoint(0);
                XYZ xyz2    = curve.GetEndPoint(1);

                double _minX = Math.Min(xyz1.X, xyz2.X);
                double _maxX = Math.Max(xyz1.X, xyz2.X);
                double _minY = Math.Min(xyz1.Y, xyz2.Y);
                double _maxY = Math.Max(xyz1.Y, xyz2.Y);

                if (curve.IsCyclic)
                {
                    Arc arc        = curve as Arc;
                    double _radius = arc.Radius;
                    //粗略对x和y 加/减
                    _maxX += _radius;
                    _minX -= _radius;
                    _maxY += _radius;
                    _minY += _radius;
                }

                if (minX == -1)
                {
                    minX = _minX;
                }
                if (maxX == -1)
                {
                    maxX = _maxX;
                }
                if (maxY == -1)
                {
                    maxY = _maxY;
                }
                if (minY == -1)
                {
                    minY = _minY;
                }

                if (_minX < minX)
                {
                    minX = _minX;
                }
                if (_maxX > maxX)
                {
                    maxX = _maxX;
                }
                if (_maxY > maxY)
                {
                    maxY = _maxY;
                }
                if (_minY < minY)
                {
                    minY = _minY;
                }
            });
            double     minX   = bb.Min.X - offset;
            double     maxX   = bb.Max.X + offset;
            double     minY   = bb.Min.Y - offset;
            double     maxY   = bb.Max.Y + offset;
            CurveArray curves = new CurveArray();
            Line       line1  = Line.CreateBound(new XYZ(minX, maxY, 0), new XYZ(maxX, maxY, 0));
            Line       line2  = Line.CreateBound(new XYZ(maxX, maxY, 0), new XYZ(maxX, minY, 0));
            Line       line3  = Line.CreateBound(new XYZ(maxX, minY, 0), new XYZ(minX, minY, 0));
            Line       line4  = Line.CreateBound(new XYZ(minX, minY, 0), new XYZ(minX, maxY, 0));
            curves.Append(line1);
            curves.Append(line2);
            curves.Append(line3);
            curves.Append(line4);
#endif // BEFORE_USING_BOUNDING_BOX
            #endregion // Obsolete code using wall location line instad of bounding box

            BoundingBoxXYZ bb = GetBoundingBoxAroundAllWalls(
                doc, view);

            XYZ voffset = offset * (XYZ.BasisX + XYZ.BasisY);
            bb.Min -= voffset;
            bb.Max += voffset;

            XYZ[] bottom_corners = Util.GetBottomCorners(
                bb, 0);

            CurveArray curves = new CurveArray();
            for (int i = 0; i < 4; ++i)
            {
                int j = i < 3 ? i + 1 : 0;
                curves.Append(Line.CreateBound(
                                  bottom_corners[i], bottom_corners[j]));
            }

            using (TransactionGroup group
                       = new TransactionGroup(doc))
            {
                Room newRoom = null;

                group.Start("Find Outermost Walls");

                using (Transaction transaction
                           = new Transaction(doc))
                {
                    transaction.Start(
                        "Create New Room Boundary Lines");

                    SketchPlane sketchPlane = SketchPlane.Create(
                        doc, view.GenLevel.Id);

                    ModelCurveArray modelCaRoomBoundaryLines
                        = doc.Create.NewRoomBoundaryLines(
                              sketchPlane, curves, view);

                    // 创建房间的坐标点 -- Create room coordinates

                    double d     = Util.MmToFoot(600);
                    UV     point = new UV(bb.Min.X + d, bb.Min.Y + d);

                    // 根据选中点,创建房间 当前视图的楼层 doc.ActiveView.GenLevel
                    // Create room at selected point on the current view level

                    newRoom = doc.Create.NewRoom(view.GenLevel, point);

                    if (newRoom == null)
                    {
                        string msg = "创建房间失败。";
                        TaskDialog.Show("xx", msg);
                        transaction.RollBack();
                        return(null);
                    }

                    RoomTag tag = doc.Create.NewRoomTag(
                        new LinkElementId(newRoom.Id),
                        point, view.Id);

                    transaction.Commit();
                }

                //获取房间的墙体 -- Get the room walls

                List <ElementId> ids
                    = RetrieveWallsGeneratingRoomBoundaries(
                          doc, newRoom);

                group.RollBack(); // 撤销

                return(ids);
            }
        }