Exemplo n.º 1
0
        private void IsolateElements_click(object sender, RoutedEventArgs e)
        {
            UIApplication uiApp = p_commanddata.Application;
            UIDocument    uiDoc = uiApp.ActiveUIDocument;

            if (ElementListView.Items.Count > 0)
            {
                try
                {
                    List <ElementId> vIds = new List <ElementId>();
                    foreach (Element vData in ElementListView.Items)
                    {
                        vIds.Add(vData.Id);
                    }

                    _Doc.ActiveView.IsolateElementsTemporary(vIds);
                    uiDoc.RefreshActiveView();
                    //this.Hide();
                    //this.Show();
                }
                catch (Exception vEx)
                {
                }
            }
            else
            {
                WrngMain vInsWrngMain = new WrngMain("No elements found");
                vInsWrngMain.Show();
            }
        }
Exemplo n.º 2
0
 public void RefreshView(UIDocument uiDocument)
 {
     RequiresRedraw = true;
     HyparLogger.Debug("Requires redraw has been set.");
     uiDocument.RefreshActiveView();
     HyparLogger.Debug("Refresh complete.");
 }
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIApplication uiapp = commandData.Application;

            uidoc = uiapp.ActiveUIDocument;
            Application app = uiapp.Application;

            doc = uidoc.Document;
            sel = uidoc.Selection;
            Reference      rf        = sel.PickObject(ObjectType.Face, "Select Face");
            Element        ele       = doc.GetElement(rf);
            GeometryObject geoobject = ele.GetGeometryObjectFromReference(rf);
            PlanarFace     face      = geoobject as PlanarFace;
            Plane          plane     = face.Faceby3pointPlane();
            XYZ            direction = face.ComputeNormal(UV.Zero);

            using (Transaction tran = new Transaction(doc, "Set view by face"))
            {
                tran.Start();
                SketchPlane skt    = SketchPlane.Create(doc, plane);
                View3D      view3d = doc.ActiveView as View3D;
                view3d.OrientTo(plane.Normal);
                doc.ActiveView.SketchPlane = skt;
                uidoc.RefreshActiveView();
                uidoc.ShowElements(ele.Id);
                tran.Commit();
            }
            return(Result.Succeeded);
        }
        public void SelectElement(Document doc, UIDocument uidoc, List <ElementId> elementIds)
        {
            View3D     view      = Get3Dview(doc).First();
            List <XYZ> pointsmax = new List <XYZ>();
            List <XYZ> pointsmin = new List <XYZ>();

            foreach (var i in elementIds)
            {
                Element        element = doc.GetElement(i);
                BoundingBoxXYZ boxXYZ  = element.get_BoundingBox(view);
                XYZ            max     = boxXYZ.Max;
                XYZ            min     = boxXYZ.Min;
                pointsmax.Add(max);
                pointsmin.Add(min);
            }
            var            Bpoint         = new Maxpoint(pointsmax);
            var            Vpoint         = new Minpoint(pointsmin);
            XYZ            Maxpoint       = new XYZ(Bpoint.Xmax, Bpoint.Ymax, Bpoint.Zmax);
            XYZ            Minpoint       = new XYZ(Vpoint.Xmin, Vpoint.Ymin, Vpoint.Zmin);
            BoundingBoxXYZ viewSectionBox = new BoundingBoxXYZ();

            viewSectionBox.Max = Maxpoint;
            viewSectionBox.Min = Minpoint;
            using (Transaction tx = new Transaction(doc))
            {
                tx.Start("Move And Resize Section Box");
                view.SetSectionBox(viewSectionBox);
                tx.Commit();
            }
            uidoc.ActiveView = view;
            uidoc.Selection.SetElementIds(elementIds);
            uidoc.RefreshActiveView();
            uidoc.ShowElements(elementIds);
        }
Exemplo n.º 5
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            UIApplication            uiapp     = commandData.Application;
            UIDocument               uidoc     = uiapp.ActiveUIDocument;
            Application              app       = uiapp.Application;
            Document                 doc       = uidoc.Document;
            ReadWriteSettingsCommand readWrite = new ReadWriteSettingsCommand();

            FindTemplateType(uiapp);

            string path;
            string searchString = "A0.70";

            thisCommand = this;

            RetrieveTitleBlockHeight(uiapp, searchString);
            path = ShowForm(uiapp);

            if (path != "")
            {
                string imagePath = Path.GetDirectoryName(path);
                readWrite.WriteFilePath(doc, path);
            }

            uidoc.RefreshActiveView();
            return(Result.Succeeded);
        }
Exemplo n.º 6
0
        //--------------------------------------------------------------
        #endregion

        #region event handlers
        //--------------------------------------------------------------

        private void On_ElementSelected(object sender, MainWindow.ElementSelectedEventArgs e)
        {
            UIDocument uiDoc = commandData.Application.ActiveUIDocument;

            uiDoc.Selection.Elements.Clear();
            uiDoc.Selection.Elements.Add(e.SelectedElement);
            uiDoc.RefreshActiveView();
        }
Exemplo n.º 7
0
        private void HighlightElements_click(object sender, RoutedEventArgs e)
        {
            UIApplication uiApp = p_commanddata.Application;
            UIDocument    uiDoc = uiApp.ActiveUIDocument;



            if (ElementListView.Items.Count > 0)
            {
                try
                {
                    OverrideGraphicSettings ogs = new OverrideGraphicSettings();
                    Autodesk.Revit.DB.Color red = new Autodesk.Revit.DB.Color(255, 0, 0);
                    Element solidFill           = new FilteredElementCollector(_Doc).OfClass(typeof(FillPatternElement)).Where(q => q.Name.Contains("Solid")).First();

                    ogs.SetProjectionLineColor(red);
                    ogs.SetProjectionLineWeight(8);

                    try
                    {
                        List <ElementId> vIds = new List <ElementId>();
                        foreach (Element vData in ElementListView.Items)
                        {
                            vIds.Add(vData.Id);
                            using (Transaction t = new Transaction(_Doc, "Highlight element"))
                            {
                                try
                                {
                                    _Doc.ActiveView.SetElementOverrides(vData.Id, ogs);
                                }
                                catch (Exception ex)
                                {
                                    TaskDialog.Show("Exception", ex.ToString());
                                }


                                t.Commit();
                            }
                        }
                        _Doc.ActiveView.IsolateElementsTemporary(vIds);
                        _Doc.ActiveView.DisableTemporaryViewMode(TemporaryViewMode.TemporaryHideIsolate);
                    }
                    catch (Exception ex)
                    {
                        TaskDialog.Show("Exception", ex.ToString());
                    }
                }
                catch (Exception vEx)
                {
                }
                uiDoc.RefreshActiveView();
            }
            else
            {
                WrngMain vInsWrngMain = new WrngMain("No elements found");
                vInsWrngMain.Show();
            }
        }
Exemplo n.º 8
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);
        }
        /// <summary>
        /// Executes on type to instance change
        /// </summary>
        /// <param name="uiapp"></param>
        /// <param name="text"></param>
        /// <param name="values"></param>
        private void ExecuteParameterChange(UIApplication uiapp, String text, List <string> values, string type)
        {
            UIDocument uidoc = uiapp.ActiveUIDocument;
            Document   doc   = uidoc.Document;

            if (!doc.IsFamilyDocument)
            {
                Command.global_message =
                    "Please run this command in a family document.";
                TaskDialog.Show("Message", Command.global_message);
            }

            if ((uidoc != null))
            {
                using (TransactionGroup tg = new TransactionGroup(doc, "Parameter Type To Instance"))
                {
                    tg.Start();
                    using (Transaction trans = new Transaction(uidoc.Document))
                    {
                        FailureHandlingOptions failureHandlingOptions = trans.GetFailureHandlingOptions();
                        FailureHandler         failureHandler         = new FailureHandler();
                        failureHandlingOptions.SetFailuresPreprocessor(failureHandler);
                        failureHandlingOptions.SetClearAfterRollback(true);
                        trans.SetFailureHandlingOptions(failureHandlingOptions);
                        // Since we'll modify the document, we need a transaction
                        // It's best if a transaction is scoped by a 'using' block
                        // The name of the transaction was given as an argument
                        if (trans.Start(text) == TransactionStatus.Started)
                        {
                            FamilyManager mgr = doc.FamilyManager;
                            foreach (var value in values)
                            {
                                FamilyParameter fp = mgr.get_Parameter(value);
                                if (fp.IsInstance)
                                {
                                    mgr.MakeType(fp);
                                }
                                else
                                {
                                    mgr.MakeInstance(fp);
                                };
                            }
                        }
                        doc.Regenerate();
                        trans.Commit();
                        uidoc.RefreshActiveView();
                        if (failureHandler.ErrorMessage != "")
                        {
                            if (EncounteredError != null)
                            {
                                EncounteredError(this, null);
                            }
                        }
                    }
                    tg.Assimilate();
                }
            }
        }
Exemplo n.º 10
0
        public void PutRemarkToElement()
        {
            Document   doc   = ActiveUIDocument.Document;
            UIDocument uidoc = ActiveUIDocument;

            ICollection <ElementId> selection = uidoc.Selection.GetElementIds();

            foreach (ElementId e in selection)
            {
                //Element obj = doc.GetElement(e);
                HiLighted(e, uidoc, doc);
                uidoc.ShowElements(e);
                uidoc.RefreshActiveView();
                try {
                    Reference Pick2 = uidoc.Selection.PickObject(ObjectType.Element, "選取標示文字:");
                } catch  {
                    break;
                }

                UnHiLighted(e, uidoc, doc);
                uidoc.RefreshActiveView();
            }

//			Reference PickOnce = uidoc.Selection.PickObject(ObjectType.Element, "選取元件:");
//			Element ref_object=doc.GetElement(PickOnce.ElementId);
//			//IList<Parameter> paras = ref_object.GetAllParameters();
//			Parameter Remark = ref_object.get_Parameter(BuiltInParameter.ALL_MODEL_MARK);
//			//String str=Remark.AsString(); //取出標註值。


            //Get the Mark Text to be put into object Mark
            //TextNote ref_object2=doc.GetElement(Pick2.ElementId) as TextNote;

            //FormattedText formatText = ref_object2.GetFormattedText();

//			using (Transaction tx = new Transaction(doc))
//            {
//			    tx.Start("Change Object Mark");
//				Remark.Set("Hello");
//				tx.Commit();
//			}
        }
        private void PlaceAndRotateFamily(UIDocument uidoc, FamilySymbol myFamilySymbol, XYZ myXYZ_Location, double myDouble_Rotation, Element myLevel)
        {
            Document doc = uidoc.Document;

            myFamilySymbol.Activate();
            FamilyInstance myFamilyInstance = doc.Create.NewFamilyInstance(myXYZ_Location, myFamilySymbol, myLevel, Autodesk.Revit.DB.Structure.StructuralType.NonStructural);
            Line           myLine           = Line.CreateUnbound(myXYZ_Location, XYZ.BasisZ);

            ElementTransformUtils.RotateElement(doc, myFamilyInstance.Id, myLine, myDouble_Rotation);
            myFamilyInstance.get_Parameter(BuiltInParameter.ALL_MODEL_INSTANCE_COMMENTS).Set("Room Setup Entities");
            uidoc.RefreshActiveView();
        }
Exemplo n.º 12
0
        void Createdrafting(Document doc, Selection sel, UIDocument uidoc, List <ElementId> list)
        {
            var list1 = HideIsolate(doc, list);

            uidoc.RefreshActiveView();
            string file  = null;
            string file2 = null;

            try
            {
                using (Transaction tr = new Transaction(doc, "Delete"))
                {
                    tr.Start();
                    bool             exported   = false;
                    ElementId        outid      = ElementId.InvalidElementId;
                    DWGExportOptions dwgOptions = new DWGExportOptions();
                    dwgOptions.FileVersion = ACADVersion.R2007;
                    View v      = null;
                    var  option = new CopyPasteOptions();
                    option.SetDuplicateTypeNamesHandler(new CopyHandler());
                    ICollection <ElementId> views = new List <ElementId>();
                    views.Add(doc.ActiveView.Id);
                    var fd = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
                    exported = doc.Export(fd, "234567", views, dwgOptions);
                    file     = Path.Combine(fd, "234567" + ".dwg");
                    file2    = Path.Combine(fd, "234567" + ".PCP");
                    var dwgimport = new DWGImportOptions();
                    dwgimport.ColorMode = ImportColorMode.BlackAndWhite;
                    if (exported)
                    {
                        v = CreateDrafting(doc);
                        doc.Import(file, dwgimport, v, out outid);
                        File.Delete(file);
                        File.Delete(file2);
                    }
                    if (doc.GetElement(outid).Pinned)
                    {
                        doc.GetElement(outid).Pinned = false;
                    }
                    ElementTransformUtils.CopyElements(v, new List <ElementId> {
                        outid
                    }, doc.ActiveView, Transform.Identity, option);
                    doc.ActiveView.UnhideElements(list1);
                    doc.Delete(v.Id);
                    tr.Commit();
                }
            }
            catch
            {
                File.Delete(file);
                File.Delete(file2);
            }
        }
Exemplo n.º 13
0
        //--------------------------------------------------------------

        public Autodesk.Revit.UI.Result Execute(Autodesk.Revit.UI.ExternalCommandData commandData, ref string message, Autodesk.Revit.DB.ElementSet elements)
        {
            this.commandData = commandData;
            List <Autodesk.Revit.DB.Element>          revitElements   = new List <Autodesk.Revit.DB.Element>();
            ICollection <Autodesk.Revit.DB.ElementId> revitElementIds = commandData.Application.ActiveUIDocument.Selection.GetElementIds();

            foreach (Autodesk.Revit.DB.ElementId elId in revitElementIds)
            {
                Autodesk.Revit.DB.Element el = commandData.Application.ActiveUIDocument.Document.GetElement(elId);

                Autodesk.Revit.DB.BuiltInCategory cat = (Autodesk.Revit.DB.BuiltInCategory)el.Category.Id.IntegerValue;

                switch (cat)
                {
                case Autodesk.Revit.DB.BuiltInCategory.OST_StructuralColumns:
                case Autodesk.Revit.DB.BuiltInCategory.OST_StructuralFraming:
                case Autodesk.Revit.DB.BuiltInCategory.OST_Floors:
                case Autodesk.Revit.DB.BuiltInCategory.OST_StructuralFoundation:
                case Autodesk.Revit.DB.BuiltInCategory.OST_Walls:
                case Autodesk.Revit.DB.BuiltInCategory.OST_WallAnalytical:
                    revitElements.Add(el);
                    break;

                default:
                    break;
                }
            }

            if (revitElements.Count < 1)
            {
                MessageBox.Show("No structural columns, structural framings, slabs or no walls are selected.");
                return(Autodesk.Revit.UI.Result.Cancelled);
            }

            UIDocument uiDoc = commandData.Application.ActiveUIDocument;

            uiDoc.Selection.GetElementIds().Clear();

            MainWindow mainWindow = new MainWindow(revitElements, On_ElementSelected);

            mainWindow.ShowDialog();

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

            foreach (Autodesk.Revit.DB.Element el in revitElements)
            {
                elIds.Add(el.Id);
            }
            uiDoc.Selection.SetElementIds(elIds);
            uiDoc.RefreshActiveView();

            return(Autodesk.Revit.UI.Result.Succeeded);
        }
Exemplo n.º 14
0
        //--------------------------------------------------------------
        #endregion

        #region event handlers
        //--------------------------------------------------------------

        private void On_ElementSelected(object sender, MainWindow.ElementSelectedEventArgs e)
        {
            UIDocument uiDoc = commandData.Application.ActiveUIDocument;

            uiDoc.Selection.GetElementIds().Clear();
            List <ElementId> elIds = new List <ElementId>();

            elIds.Add(e.SelectedElement.Id);
            uiDoc.Selection.SetElementIds(elIds);

            uiDoc.RefreshActiveView();
        }
Exemplo n.º 15
0
        public override void comboVisuals_SelectionChanged(object sender, SelectionChangedEventArgs e, AddComment addCommentWindow)
        {
            try
            {
                System.Windows.Controls.ComboBox comboVisuals = sender as System.Windows.Controls.ComboBox;
                if (doc.ActiveView.DisplayStyle.ToString() != comboVisuals.SelectedValue.ToString())
                {
                    switch (comboVisuals.SelectedIndex)
                    {
                    case 0:
                        doc.ActiveView.DisplayStyle = DisplayStyle.FlatColors;
                        break;

                    case 1:
                        doc.ActiveView.DisplayStyle = DisplayStyle.HLR;
                        break;

                    case 2:
                        doc.ActiveView.DisplayStyle = DisplayStyle.Realistic;
                        break;

                    case 3:
                        doc.ActiveView.DisplayStyle = DisplayStyle.RealisticWithEdges;
                        break;

                    case 4:
                        doc.ActiveView.DisplayStyle = DisplayStyle.Rendering;
                        break;

                    case 5:
                        doc.ActiveView.DisplayStyle = DisplayStyle.Shading;
                        break;

                    case 6:
                        doc.ActiveView.DisplayStyle = DisplayStyle.ShadingWithEdges;
                        break;

                    case 7:
                        doc.ActiveView.DisplayStyle = DisplayStyle.Wireframe;
                        break;

                    default:
                        break;
                    }
                }
                uidoc.RefreshActiveView();
                addCommentWindow.captureModelViewpointButton_Click(null, null);
            }
            catch (System.Exception ex1)
            {
                TaskDialog.Show("Error!", "exception: " + ex1);
            }
        }
        /// <summary>
        /// Restore all values
        /// </summary>
        /// <param name="uiapp"></param>
        /// <param name="text"></param>
        /// <param name="values"></param>
        public static void ExecuteParameterChange(UIApplication uiapp, String text, List <Tuple <string, string, double> > values)
        {
            UIDocument uidoc = uiapp.ActiveUIDocument;
            Document   doc   = uidoc.Document;

            if (!doc.IsFamilyDocument)
            {
                Command.global_message = "Please run this command in a family document.";
                TaskDialog.Show("Message", Command.global_message);
            }

            if ((uidoc != null))
            {
                using (TransactionGroup tg = new TransactionGroup(doc, "Parameter Change"))
                {
                    tg.Start();
                    foreach (var value in values)
                    {
                        using (Transaction trans = new Transaction(uidoc.Document))
                        {
                            FailureHandlingOptions failureHandlingOptions = trans.GetFailureHandlingOptions();
                            FailureHandler         failureHandler         = new FailureHandler();
                            failureHandlingOptions.SetFailuresPreprocessor(failureHandler);
                            failureHandlingOptions.SetClearAfterRollback(true);
                            trans.SetFailureHandlingOptions(failureHandlingOptions);

                            FamilyManager   mgr = doc.FamilyManager;
                            FamilyParameter fp  = mgr.get_Parameter(value.Item1);
                            // Since we'll modify the document, we need a transaction
                            // It's best if a transaction is scoped by a 'using' block
                            // The name of the transaction was given as an argument
                            if (trans.Start(text) == TransactionStatus.Started)
                            {
                                mgr.Set(fp, value.Item3);
                                //operation(mgr, fp);
                                doc.Regenerate();
                                if (!value.Item1.Equals(value.Item2))
                                {
                                    mgr.RenameParameter(fp, value.Item2);
                                }
                                trans.Commit();
                                uidoc.RefreshActiveView();
                            }
                            if (failureHandler.ErrorMessage != "")
                            {
                                RequestError.ErrorLog.Add(new Message(fp.Definition.Name, failureHandler.ErrorMessage));
                            }
                        }
                    }
                    tg.Assimilate();
                }
            }
        }
Exemplo n.º 17
0
        //execute or cancel
        private void HighlightElement(bool execute, Document doc)
        {
            try
            {
                UIDocument uidoc = new UIDocument(doc);
                using (Transaction trans = new Transaction(doc))
                {
                    trans.Start("Highlight");
                    try
                    {
                        Element element = m_doc.GetElement(new ElementId(currentElement.ElementId));
                        if (null != element)
                        {
                            if (execute)
                            {
#if RELEASE2013 || RELEASE2014
                                SelElementSet selElements = SelElementSet.Create();
                                selElements.Add(element);
                                uidoc.Selection.Elements = selElements;
                                uidoc.ShowElements(element);
#elif RELEASE2015 || RELEASE2016
                                List <ElementId> selectedIds = new List <ElementId>();
                                selectedIds.Add(element.Id);
                                uidoc.Selection.SetElementIds(selectedIds);
                                uidoc.ShowElements(element.Id);
#endif
                            }
                            else
                            {
#if RELEASE2013 || RELEASE2014
                                SelElementSet selElementSet = SelElementSet.Create();
                                uidoc.Selection.Elements = selElementSet;
#elif RELEASE2015 || RELEASE2016
                                uidoc.Selection.SetElementIds(new List <ElementId>());
#endif
                            }
                            uidoc.RefreshActiveView();
                        }
                        trans.Commit();
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(currentElement.ElementName + ": Failed to highlight elements.\n" + ex.Message, "Highlight Element", MessageBoxButton.OK, MessageBoxImage.Warning);
                        trans.RollBack();
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Failed to highlight elements.\n" + ex.Message, "Highlight Elements", MessageBoxButton.OK, MessageBoxImage.Warning);
            }
        }
        /// <summary>
        /// Delete parameter
        /// </summary>
        /// <param name="uiapp"></param>
        /// <param name="text"></param>
        /// <param name="values"></param>
        public static void ExecuteParameterChange(UIApplication uiapp, String text, List <string> values)
        {
            UIDocument uidoc = uiapp.ActiveUIDocument;
            Document   doc   = uidoc.Document;

            if (!doc.IsFamilyDocument)
            {
                Command.global_message =
                    "Please run this command in a family document.";
                TaskDialog.Show("Message", Command.global_message);
            }

            if ((uidoc != null))
            {
                using (TransactionGroup tg = new TransactionGroup(doc, "Parameter Delete"))
                {
                    tg.Start();
                    using (Transaction trans = new Transaction(uidoc.Document))
                    {
                        FailureHandlingOptions failureHandlingOptions = trans.GetFailureHandlingOptions();
                        FailureHandler         failureHandler         = new FailureHandler();
                        failureHandlingOptions.SetFailuresPreprocessor(failureHandler);
                        failureHandlingOptions.SetClearAfterRollback(true);
                        trans.SetFailureHandlingOptions(failureHandlingOptions);
                        // Since we'll modify the document, we need a transaction
                        // It's best if a transaction is scoped by a 'using' block
                        // The name of the transaction was given as an argument
                        if (trans.Start(text) == TransactionStatus.Started)
                        {
                            FamilyManager mgr = doc.FamilyManager;
                            foreach (var value in values)
                            {
                                FamilyParameter fp = mgr.get_Parameter(value);
                                mgr.RemoveParameter(fp);
                            }
                        }
                        doc.Regenerate();
                        trans.Commit();
                        uidoc.RefreshActiveView();
                        if (failureHandler.ErrorMessage != "")
                        {
                            RequestError.ErrorLog.Add(new Message("", failureHandler.ErrorMessage));
                        }
                        else
                        {
                            RequestError.NotifyLog += $"Successfully purged {values.Count.ToString()} unused parameters.";
                        }
                    }
                    tg.Assimilate();
                }
            }
        }
Exemplo n.º 19
0
        private void comboVisuals_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                if (doc.ActiveView.DisplayStyle.ToString() != comboVisuals.SelectedValue.ToString())
                {
                    switch (comboVisuals.SelectedIndex)
                    {
                    case 0:
                        doc.ActiveView.DisplayStyle = DisplayStyle.FlatColors;
                        break;

                    case 1:
                        doc.ActiveView.DisplayStyle = DisplayStyle.HLR;
                        break;

                    case 2:
                        doc.ActiveView.DisplayStyle = DisplayStyle.Realistic;
                        break;

                    case 3:
                        doc.ActiveView.DisplayStyle = DisplayStyle.RealisticWithEdges;
                        break;

                    case 4:
                        doc.ActiveView.DisplayStyle = DisplayStyle.Rendering;
                        break;

                    case 5:
                        doc.ActiveView.DisplayStyle = DisplayStyle.Shading;
                        break;

                    case 6:
                        doc.ActiveView.DisplayStyle = DisplayStyle.ShadingWithEdges;
                        break;

                    case 7:
                        doc.ActiveView.DisplayStyle = DisplayStyle.Wireframe;
                        break;

                    default:
                        break;
                    }
                }
                uidoc.RefreshActiveView();
                updateImage();
            }
            catch (System.Exception ex1)
            {
                TaskDialog.Show("Error!", "exception: " + ex1);
            }
        }
Exemplo n.º 20
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            UIDocument uIDocument = commandData.Application.ActiveUIDocument;
            Document   DOC        = commandData.Application.ActiveUIDocument.Document;

            // Отобранные кривые в проекте.
            var selectedCurves = new FilteredElementCollector(DOC)
                                 .OfCategory(BuiltInCategory.OST_DuctCurves)
                                 .Where(w => w is MEPCurve)
                                 .Cast <MEPCurve>();

            // Отобранные коннекторы в проекте. (вершины)
            FilteredElementCollector selectedVertex = new FilteredElementCollector(DOC)
                                                      .WhereElementIsNotElementType()
                                                      .OfCategory(BuiltInCategory.OST_DuctFitting);

            List <Vertex>    Vertexes = GetListVertexAndEdges(selectedVertex);
            List <EdgeGraph> Edges    = GetEdges(Vertexes, selectedCurves);

            Reference reference1 = uIDocument.Selection.PickObject(ObjectType.Element);
            Reference reference2 = uIDocument.Selection.PickObject(ObjectType.Element);

            Element el1 = DOC.GetElement(reference1);
            Element el2 = DOC.GetElement(reference2);

            Graph graph = new Graph();

            foreach (Vertex item in Vertexes)
            {
                graph.AddVertex(item.IdVertex.ToString());
            }

            foreach (EdgeGraph item in Edges)
            {
                graph.AddEdge(item.VertexA.ToString(), item.VertexB.ToString(), item.EdgeWidth);
            }

            Dijkstra deijkstra = new Dijkstra(graph);

            List <ElementId> vertex     = deijkstra.FindShortestPath(el1.Id.ToString(), el2.Id.ToString());
            List <ElementId> elementIds = GetConnectedEdgesId(Vertexes, vertex);

            elementIds.InsertRange(0, vertex);

            uIDocument.Selection.SetElementIds(elementIds);
            uIDocument.RefreshActiveView();


            return(Result.Succeeded);
        }
Exemplo n.º 21
0
        public override void selectElements(List <string> elementIds)
        {
            SelElementSet elementsToBeSelected = SelElementSet.Create();

            elementIds.ForEach(eId => {
                Element e = doc.GetElement(new ElementId(int.Parse(eId)));
                if (e != null)
                {
                    elementsToBeSelected.Add(e);
                }
            });
            uidoc.Selection.Elements = elementsToBeSelected;
            uidoc.RefreshActiveView();
        }
Exemplo n.º 22
0
        private static void ApplyMaterialChanges()
        {
            foreach (KeyValuePair <ElementId, Material> change in materialChanges)
            {
                var element = _doc.GetElement(change.Key) as Autodesk.Revit.DB.Material;
                int value   = change.Value.color;
                var blue    = Convert.ToByte((value >> 0) & 255);
                var green   = Convert.ToByte((value >> 8) & 255);
                var red     = Convert.ToByte((value >> 16) & 255);


                element.Color = new Color(red, green, blue);
            }
            materialChanges.Clear();
            _uidoc.RefreshActiveView();
        }
        /// <summary>
        /// Change Parameter
        /// </summary>
        /// <param name="uiapp"></param>
        /// <param name="text"></param>
        /// <param name="values"></param>
        public static void ExecuteParameterChange(UIApplication uiapp, String text, Tuple <string, double> value)
        {
            UIDocument uidoc = uiapp.ActiveUIDocument;
            Document   doc   = uidoc.Document;

            if (!doc.IsFamilyDocument)
            {
                Command.global_message = "Please run this command in a family document.";
                TaskDialog.Show("Message", Command.global_message);
            }

            if ((uidoc != null))
            {
                using (Transaction trans = new Transaction(uidoc.Document, "Change Parameter Value"))
                {
                    FailureHandlingOptions failureHandlingOptions = trans.GetFailureHandlingOptions();
                    FailureHandler         failureHandler         = new FailureHandler();
                    failureHandlingOptions.SetFailuresPreprocessor(failureHandler);
                    failureHandlingOptions.SetClearAfterRollback(true);
                    trans.SetFailureHandlingOptions(failureHandlingOptions);

                    FamilyManager   mgr = doc.FamilyManager;
                    FamilyParameter fp  = mgr.get_Parameter(value.Item1);
                    // Since we'll modify the document, we need a transaction
                    // It's best if a transaction is scoped by a 'using' block
                    // The name of the transaction was given as an argument
                    if (trans.Start(text) == TransactionStatus.Started)
                    {
                        if (fp.IsDeterminedByFormula || fp.IsReporting)
                        {
                            trans.RollBack();  //Cannot change parameters driven by formulas, cannot change reporting parameters
                            return;
                        }

                        mgr.Set(fp, value.Item2);
                        doc.Regenerate();
                        trans.Commit();
                        uidoc.RefreshActiveView();
                        if (failureHandler.ErrorMessage != "")
                        {
                            RequestError.ErrorLog.Add(new Message(fp.Definition.Name, failureHandler.ErrorMessage));
                        }
                    }
                }
            }
        }
    public Result Execute(
        ExternalCommandData commandData,
        ref string message,
        ElementSet elements)
    {
        UIApplication uiapp = commandData.Application;
        UIDocument    uidoc = uiapp.ActiveUIDocument;
        Application   app   = uiapp.Application;
        Document      doc   = uidoc.Document;

        Selection  sel1    = uidoc.Selection;
        List <XYZ> tempXYZ = new List <XYZ>(1);
        XYZ        p1      = sel1.PickPoint();
        XYZ        p2      = null;


        //tempXYZ.Add(p3);

        ModelCurve visualLine = null;

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

Redraw:
            using (Transaction t = new Transaction(doc))
            {
                t.Start("Step 1");

                Line line = Line.CreateBound(p1, getP3(uidoc));

                Plane       geomPlane = Plane.CreateByNormalAndOrigin(doc.ActiveView.ViewDirection, doc.ActiveView.Origin);
                SketchPlane sketch    = SketchPlane.Create(doc, geomPlane);
                visualLine = doc.Create.NewModelCurve(line, sketch) as ModelCurve;
                doc.Regenerate();
                uidoc.RefreshActiveView();
                goto Redraw;

                t.Commit();
            }
            tGroup.Commit();
        }
        return(Result.Succeeded);
    }
Exemplo n.º 25
0
        public Message Execute(Document doc, Message msg)
        {
            _log("EXECUTE SET");

            JObject dto = JObject.Parse(msg.Data);

            _log("GOT DTO");
            _log(JsonConvert.SerializeObject(dto));

            _log("GETTING ELEMENT");

            Element dbValue = doc.GetElement(new ElementId(Int32.Parse(dto["Id"].ToString())));

            using (Transaction tx = new Transaction(doc))
            {
                tx.Start("Set Element");

                // Ensure warnings are suppressed and failures roll-back
                var failureOptions = tx.GetFailureHandlingOptions();
                failureOptions.SetFailuresPreprocessor(new WarningSupressor());
                tx.SetFailureHandlingOptions(failureOptions);
                _log($"GOT FAMILY INSTANCE {dbValue?.Id.ToString()}");

                // Map dto values to DB
                _converter.MapFromDTO(dto, dbValue);

                tx.Commit();
            }

            _log($"MAPPED FAMILY INSTANCE");

            dto = _converter.ConvertToDTO(dbValue);

            _log("NEW VALUE");
            _log(JsonConvert.SerializeObject(dto));

            _uiDocument.RefreshActiveView();

            return(new Message
            {
                Type = "VALUE",
                Data = JsonConvert.SerializeObject(dto)
            });
        }
Exemplo n.º 26
0
        /// <summary>
        /// Event handler that provides context to execute actions over the Active UI Document and performs cleaning of the highlited elements
        /// </summary>
        /// <param name="app">Injected UIApplication from revit API</param>
        public void Execute(UIApplication app)
        {
            UIDocument uiDoc = app.ActiveUIDocument;

            using (Transaction tx = new Transaction(app.ActiveUIDocument.Document, "CleanViewTransaction"))
            {
                try
                {
                    tx.Start();
                    RevitTools.ResetView();
                    uiDoc.RefreshActiveView();
                    tx.Commit();
                }
                catch
                {
                    TaskDialog.Show("Clasher Detection: Error", "An error has occured. Cannot clean view");
                }
            }
        }
Exemplo n.º 27
0
        ////[SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")]
        private bool RotateView(View view)
        {
            if (view.ViewType == ViewType.ThreeD)
            {
                var forward = GetSunDirectionalVector(view, position, out var azimuth);
                var up      = forward.CrossProduct(new XYZ(Math.Cos(azimuth), -Math.Sin(azimuth), 0));

                var v3d = (View3D)view;
                if (v3d.IsLocked)
                {
                    SCaddinsApp.WindowManager.ShowMessageBox("ERROR", "View is locked, please unlock before rotating");
                    return(false);
                }

                using (var t = new Transaction(doc))
                {
                    t.Start("Rotate View");
                    v3d.SetOrientation(new ViewOrientation3D(GetEyeLocation(view), up, forward));
                    if (v3d.CanBeLocked() && !v3d.Name.StartsWith("{", StringComparison.OrdinalIgnoreCase))
                    {
                        try
                        {
                            v3d.SaveOrientationAndLock();
                        }
                        catch (InvalidOperationException e)
                        {
                            Debug.WriteLine(e.Message);
                            return(false);
                        }
                    }

                    udoc.RefreshActiveView();
                    t.Commit();
                }
            }
            else
            {
                SCaddinsApp.WindowManager.ShowMessageBox("ERROR", "Not a 3d view");
                return(false);
            }
            return(true);
        }
Exemplo n.º 28
0
        public void selectElements(List <Component> components)
        {
#if REVIT2014
            SelElementSet elementsToBeSelected = SelElementSet.Create();
            components.ForEach(component =>
            {
                Element e = doc.GetElement(new ElementId(int.Parse(component.AuthoringToolId)));
                if (e != null)
                {
                    elementsToBeSelected.Add(e);
                }
            });
            uidoc.Selection.Elements = elementsToBeSelected;
            uidoc.RefreshActiveView();
#else
            List <ElementId> elementsToBeSelected = new List <ElementId>();
            components.ForEach(component => elementsToBeSelected.Add(new ElementId(int.Parse(component.AuthoringToolId))));
            uidoc.Selection.SetElementIds(elementsToBeSelected);
#endif
        }
        /// <summary>
        /// Selects the search hit elements in the view
        /// </summary>
        /// <param name="activeUIDoc"></param>
        private void SelectElements(UIDocument activeUIDoc)
        {
            ICollection <ElementId> newCollection = new List <ElementId>();

            _liSelection.Clear();
            _liUniqueIds.Clear();
            foreach (string sUniqueId in _liUniqueIdsToSel)
            {
                Element elem = activeUIDoc.Document.GetElement(sUniqueId);
                if (null != elem)
                {
                    newCollection.Add(elem.Id);
                    _liSelection.Add(elem);
                    _liUniqueIds.Add(sUniqueId);
                }
            }
            activeUIDoc.Selection.SetElementIds(newCollection);
            //uiApp.ActiveUIDocument.Document.Regenerate();
            activeUIDoc.ShowElements(newCollection);
            activeUIDoc.RefreshActiveView();
        }
Exemplo n.º 30
0
        /// <summary>
        /// Executes on restore all values
        /// </summary>
        /// <param name="uiapp"></param>
        /// <param name="text"></param>
        /// <param name="values"></param>
        private void ExecuteMakeSelection(UIApplication uiapp, String text, List <ICollection <ElementId> > ids)
        {
            UIDocument uidoc = uiapp.ActiveUIDocument;
            Document   doc   = uidoc.Document;

            if (doc.IsFamilyDocument)
            {
                CommandWarningChart.global_message =
                    "Please run this command in a normal document.";
                TaskDialog.Show("Message", CommandWarningChart.global_message);
            }

            if ((uidoc != null))
            {
                List <ElementId> idsToSelect = new List <ElementId>();

                foreach (var warning in ids)
                {
                    foreach (var id in warning)
                    {
                        idsToSelect.Add(id);
                    }
                }

                try
                {
                    using (Transaction trans = new Transaction(uidoc.Document))
                    {
                        if (trans.Start(text) == TransactionStatus.Started)
                        {
                            uidoc.Selection.SetElementIds(idsToSelect);
                            doc.Regenerate();
                            trans.Commit();
                            uidoc.RefreshActiveView();
                        }
                    }
                }
                catch (Exception) { }
            }
        }