Ejemplo n.º 1
0
        //指定字段视图首次复制为目标视图
        public void copyPlotToFieldView(Document doc, IList <string> selectedPlotView, ICollection <ElementId> PlotViewIds, string origin_str, string target_str, CMD.myDelegate _myDelegate, string str_view_content_para, string str_view_content)
        {
            using (Transaction copyViewPlot = new Transaction(doc, "copyPLOTto"))
            {
                copyViewPlot.Start("copyPLOTto");
                foreach (string selectedstr in selectedPlotView)
                {
                    foreach (ElementId sourceViewId in PlotViewIds)
                    {
                        Autodesk.Revit.DB.View sourceView = doc.GetElement(sourceViewId) as Autodesk.Revit.DB.View;
                        string vieName = sourceView.Name;
                        if (selectedstr == vieName)
                        {
                            Autodesk.Revit.DB.View destinationView = CreateDependentCopy(doc, sourceViewId); //复制PLOT视图为指定字段视图

                            destinationView.Name = vieName.Replace(origin_str, target_str);                  //设置目标视图变量//更改视图名字,更元素属性,不能使用中间过渡变量进行处理
                            destinationView.LookupParameter(str_view_content_para).Set(str_view_content);;   //设置目标视图变量//更改共享参数
                            ICollection <ElementId> selectedEleIds = _myDelegate(doc, sourceViewId);         //设置目标函数变量//获取需要从PLOT视图复制的2D图元
                            if (selectedEleIds != null && selectedEleIds.Count() != 0)
                            {
                                ElementTransformUtils.CopyElements(sourceView, selectedEleIds, destinationView, null, null);//复制图元
                            }
                        }
                    }
                }
                copyViewPlot.Commit();
            }
            showSuccess(target_str);
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Copy detailed structural connection.
        /// </summary>
        /// <param name="activeDoc">The active document.</param>
        /// <param name="message">Set message on failure.</param>
        /// <returns>Returns the status of the operation.</returns>
        public static Result CopyDetailedStructuralConnection(UIDocument activeDoc, ref string message)
        {
            Result ret = Result.Succeeded;

            // Select a connection and the connected elements.
            List <ElementId> ids = activeDoc.Selection.GetElementIds().ToList();

            if (ids.Count() > 0)
            {
                // Create transform
                Transform transform = Transform.CreateTranslation(new XYZ(0, 20, 0));

                // Copy selection
                using (Transaction tran = new Transaction(activeDoc.Document, "Copy elements"))
                {
                    tran.Start();
                    ICollection <ElementId> copyResult = ElementTransformUtils.CopyElements(activeDoc.Document, ids, activeDoc.Document, transform, null);
                    TransactionStatus       ts         = tran.Commit();
                    if (ts != TransactionStatus.Committed)
                    {
                        message = "Failed to commit the current transaction !";
                        ret     = Result.Failed;
                    }
                }
            }
            else
            {
                message = "There is no element selected!";
                ret     = Result.Failed;
            }

            return(ret);
        }
Ejemplo n.º 3
0
        public static Dictionary <string, object> CopyElements(List <Revit.Elements.Element> element,
                                                               Autodesk.DesignScript.Geometry.Point translation)
        {
            //declare an elementId collection and add the ids to it.
            List <Autodesk.Revit.DB.ElementId> idCollection = new List <Autodesk.Revit.DB.ElementId>();

            foreach (var item in element)
            {
                var internalElement = (Autodesk.Revit.DB.Element)item.InternalElement;
                idCollection.Add(internalElement.Id);
            }
            //start the transaction to copy elements
            Document doc        = DocumentManager.Instance.CurrentDBDocument;
            var      revitPoint = translation.ToRevitType();

            TransactionManager.Instance.EnsureInTransaction(doc);
            var newElementIds = ElementTransformUtils.CopyElements(doc, idCollection, revitPoint);

            TransactionManager.Instance.TransactionTaskDone();
            //declare new list to append the new elements to it
            List <Revit.Elements.Element> newElements = new List <Revit.Elements.Element>();

            foreach (var item in newElementIds)
            {
                newElements.Add(doc.GetElement(item).ToDSType(true));
            }

            //returns the outputs
            var outInfo = new Dictionary <string, object>
            {
                { "element", newElements }
            };

            return(outInfo);
        }
        bool CopyLineElement(Document sourceDocument, Document destinationDocument)
        {
            string tagViewName = "Viewr_LineStyle";

            View view = GetViewByName(sourceDocument, tagViewName);

            if (view == null)
            {
                return(false);
            }

            IList <ElementId>        copyElemIdList = new List <ElementId>();
            FilteredElementCollector elems          = new FilteredElementCollector(sourceDocument, view.Id);

            foreach (Element elem in elems.OfCategory(BuiltInCategory.OST_Lines))
            {
                DetailLine detailLine = elem as DetailLine;
                if (detailLine != null)
                {
                    copyElemIdList.Add(detailLine.LineStyle.Id);
                }
            }

            //copyElemIdList.GroupBy(a => a.IntegerValue).Select(b => b.First());
            copyElemIdList.Distinct(new ElementIdComparer());

            CopyPasteOptions options = new CopyPasteOptions();

            options.SetDuplicateTypeNamesHandler(new ElementCopyCoverHandler());
            ElementTransformUtils.CopyElements(sourceDocument, copyElemIdList, destinationDocument, null, options);

            return(true);
        }
Ejemplo n.º 5
0
        private static void DuplicateSheetAnnotations(Sheet oldSheet, Sheet newSheet)
        {
            List <BuiltInCategory> Filters = new List <BuiltInCategory>
            {
                BuiltInCategory.OST_IOSDetailGroups,
                BuiltInCategory.OST_Dimensions,
                BuiltInCategory.OST_GenericAnnotation,
                BuiltInCategory.OST_Lines,
                BuiltInCategory.OST_TextNotes
            };
            List <ElementId> list        = new List <ElementId>();
            List <ElementId> currentList = new List <ElementId>();

            foreach (var category in Filters)
            {
                list.AddRange(new FilteredElementCollector(Document, oldSheet.InternalElementId).OfCategory(category).ToElementIds());
                currentList.AddRange(new FilteredElementCollector(Document, newSheet.InternalElementId).OfCategory(category).ToElementIds());
            }
            if (list.Any <ElementId>())
            {
                if (currentList.Any <ElementId>() && currentList.Count == list.Count)
                {
                    return;
                }
                else if (currentList.Any <ElementId>() && currentList.Count != list.Count)
                {
                    DeleteSheetAnnotations(newSheet);
                }
                ElementTransformUtils.CopyElements(oldSheet.InternalViewSheet, list, newSheet.InternalViewSheet, null, null);
            }
        }
Ejemplo n.º 6
0
        public static List <global::Revit.Elements.Element> CopyElementsFromDocument(Autodesk.Revit.DB.Document sourceDocument, List <global::Revit.Elements.Element> elements)
        {
            Autodesk.Revit.DB.Document doc = DocumentManager.Instance.CurrentDBDocument;
            //converts elements to ids in a collection
            ICollection <ElementId> idCollection = new List <ElementId>();

            foreach (global::Revit.Elements.Element element in elements)
            {
                idCollection.Add(element.InternalElement.Id);
            }
            //creates blank copy paste options
            CopyPasteOptions copyOpts = new CopyPasteOptions();
            //creates blank transform.
            Transform transform = Transform.CreateTranslation(Vector.XAxis().ToRevitType());

            //commits the transaction
            TransactionManager.Instance.EnsureInTransaction(doc);
            ICollection <ElementId> newElementIds = ElementTransformUtils.CopyElements(sourceDocument, idCollection, doc, transform, copyOpts);

            TransactionManager.Instance.TransactionTaskDone();
            //create a new list for the new elements
            List <global::Revit.Elements.Element> newElements = new List <global::Revit.Elements.Element>();

            //gets the new elements
            foreach (ElementId id in newElementIds)
            {
                newElements.Add(doc.GetElement(id).ToDSType(true));
            }

            return(newElements);
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Copies all view-specific elements from a source view to a target view.
        /// </summary>
        /// <remarks>
        /// The source and target views do not have to be in the same document.
        /// </remarks>
        /// <param name="fromView">The source view.</param>
        /// <param name="toView">The target view.</param>
        /// <returns>The number of new elements created during the copy operation.</returns>
        private static int DuplicateDetailingAcrossViews(View fromView,
                                                         View toView)
        {
            // Collect view-specific elements in source view
            FilteredElementCollector collector = new FilteredElementCollector(fromView.Document, fromView.Id);

            // Skip elements which don't have a category.  In testing, this was
            // the revision table and the extents element, which should not be copied as they will
            // be automatically created for the copied view.
            collector.WherePasses(new ElementCategoryFilter(ElementId.InvalidElementId, true))
            .WherePasses(new ElementCategoryFilter(BuiltInCategory.OST_Viewers, true));


            // Get collection of elements to copy for CopyElements()
            ICollection <ElementId> toCopy = collector.ToElementIds();

            // Collect view-specific elements in source view
            FilteredElementCollector sectionsCollector = new FilteredElementCollector(fromView.Document, fromView.Id);

            // Skip elements which don't have a category.  In testing, this was
            // the revision table and the extents element, which should not be copied as they will
            // be automatically created for the copied view.
            sectionsCollector.WherePasses(new ElementCategoryFilter(ElementId.InvalidElementId, true))
            .WherePasses(new ElementCategoryFilter(BuiltInCategory.OST_Viewers));


            // Get collection of elements to copy for CopyElements()
            ICollection <Element>   sectionsToCopy    = sectionsCollector.ToElements();
            ICollection <ElementId> sectionsToCopyIds = sectionsCollector.ToElementIds();

            // Return value
            int numberOfCopiedElements = 0;

            if (toCopy.Count > 0)
            {
                try
                {
                    using (Transaction t2 = new Transaction(toView.Document, "Duplicate view detailing"))
                    {
                        t2.Start();
                        // Set handler to skip the duplicate types dialog
                        CopyPasteOptions options = new CopyPasteOptions();
                        options.SetDuplicateTypeNamesHandler(new HideAndAcceptDuplicateTypeNamesHandler());

                        // Copy the elements using no transformation
                        ICollection <ElementId> copiedElements =
                            ElementTransformUtils.CopyElements(fromView, toCopy, toView, Transform.Identity, options);
                        numberOfCopiedElements = copiedElements.Count;

                        // Set failure handler to skip any duplicate types warnings that are posted.
                        FailureHandlingOptions failureOptions = t2.GetFailureHandlingOptions();
                        failureOptions.SetFailuresPreprocessor(new HidePasteDuplicateTypesPreprocessor());
                        t2.Commit(failureOptions);
                    }
                }
                catch { }
            }

            return(numberOfCopiedElements);
        }
        public static void TransferWallTypeToCurrentDoc(string SourceFilename, Revit.Elements.Element WallElementFromSource)
        {
            Autodesk.Revit.DB.Document      doc   = DocumentManager.Instance.CurrentDBDocument;
            Autodesk.Revit.UI.UIApplication uiapp = DocumentManager.Instance.CurrentUIApplication;
            //TransactionManager.Instance.EnsureInTransaction(doc);



            //Document WallDoc = uiapp.Application.OpenDocumentFile(SourceFilename);

            Autodesk.Revit.DB.Element RevEle = ((Revit.Elements.Element)WallElementFromSource).InternalElement;

            Document WallDoc = RevEle.Document;

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

            SourceElements.Add(RevEle.Id);
            //SourceElements.Add(RevEle.GetTypeId());

            TransactionManager.Instance.EnsureInTransaction(doc);

            CopyPasteOptions cpOpt = new CopyPasteOptions();

            try
            {
                ElementTransformUtils.CopyElements(WallDoc, SourceElements, doc, Transform.Identity, cpOpt);
            }
            catch (Exception ex)
            {
                throw;
            }

            //Close the transaction
            TransactionManager.Instance.TransactionTaskDone();
        }
        public void CopyText(Document doc, List <ElementId> ids, View source, List <View> Taggets)
        {
            ProgressbarWPF progressbarWPF = new ProgressbarWPF(Taggets.Count, "Copy Text");

            progressbarWPF.Show();
            foreach (var Tagget in Taggets)
            {
                if (progressbarWPF.iscontinue == false)
                {
                    break;
                }
                using (Transaction t = new Transaction(doc, "Copy Text"))
                {
                    t.Start();
                    FailureHandlingOptions options       = t.GetFailureHandlingOptions();
                    MyPreProcessor         ignoreProcess = new MyPreProcessor();
                    options.SetClearAfterRollback(true);
                    options.SetFailuresPreprocessor(ignoreProcess);
                    t.SetFailureHandlingOptions(options);
                    try
                    {
                        ElementTransformUtils.CopyElements(source, ids, Tagget, Transform.Identity, new CopyPasteOptions());
                    }
                    catch
                    {
                    }
                    t.Commit();
                }
            }
            progressbarWPF.Close();
        }
Ejemplo n.º 10
0
        private static ViewDrafting DuplicateDraftingViews(PreviewMap previewMap)
        {
            ViewDrafting viewDrafting = null;

            try
            {
                Document fromDoc = previewMap.SourceModelInfo.Doc;
                Document toDoc   = previewMap.RecipientModelInfo.Doc;

                ViewDrafting            sourceView          = previewMap.SourceViewProperties.ViewDraftingObj;
                ICollection <ElementId> referenceCalloutIds = sourceView.GetReferenceCallouts();

                CopyPasteOptions options = new CopyPasteOptions();
                options.SetDuplicateTypeNamesHandler(new HideAndAcceptDuplicateTypeNamesHandler());

                ICollection <ElementId> copiedIds = null;
                using (Transaction transaction = new Transaction(toDoc, "Duplicate Draftingviews"))
                {
                    transaction.Start();
                    try
                    {
                        List <ElementId> viewIds = new List <ElementId>();
                        viewIds.Add(sourceView.Id);

                        //view-specific item
                        copiedIds = ElementTransformUtils.CopyElements(fromDoc, viewIds, toDoc, Transform.Identity, options);

                        FailureHandlingOptions failureOptions = transaction.GetFailureHandlingOptions();
                        failureOptions.SetFailuresPreprocessor(new HidePasteDuplicateTypesPreprocessor());
                        transaction.Commit(failureOptions);
                    }
                    catch (Exception ex)
                    {
                        string message = ex.Message;
                        transaction.RollBack();
                    }
                }

                if (null != copiedIds)
                {
                    ElementId    viewId     = copiedIds.First();
                    ViewDrafting copiedView = toDoc.GetElement(viewId) as ViewDrafting;
                    if (null != copiedView)
                    {
                        int numOfCopied = DuplicateDetailingAcrossViews(sourceView, copiedView);
                    }
                    if (referenceCalloutIds.Count > 0)
                    {
                        bool placedCallout = DuplicateReferenceCallouts(sourceView, copiedView);
                    }
                    viewDrafting = copiedView;
                }
            }
            catch (Exception ex)
            {
                errorMessage.AppendLine(previewMap.SourceViewProperties.ViewName + ": errors in duplicating drafting views.\n" + ex.Message);
                //MessageBox.Show("Failed to duplicate drafintg views.\n" + ex.Message, "Duplicate DraftingViews", MessageBoxButton.OK, MessageBoxImage.Warning);
            }
            return(viewDrafting);
        }
Ejemplo n.º 11
0
        public static ICollection <ElementId> CopyPaste(List <Revit.Elements.Element> Element, Revit.Elements.Views.View SourceView, Revit.Elements.Views.View DestinationView)
        {
            var doc = DocumentManager.Instance.CurrentDBDocument;
            ICollection <ElementId> elem = new System.Collections.ObjectModel.Collection <ElementId>() as ICollection <ElementId>;
            ElementId sourceViewId       = UnwrapElement(SourceView);
            View      sourcefinalView    = doc.GetElement(sourceViewId) as View;
            ElementId destViewId         = UnwrapElement(DestinationView);
            View      destfinalView      = doc.GetElement(destViewId) as View;

            foreach (var k in Element)
            {
                Autodesk.Revit.DB.ElementId ElementID = UnwrapElement(k);
                elem.Add(ElementID);
            }
            ;

            try
            {
                TransactionManager.Instance.EnsureInTransaction(doc);
                ElementTransformUtils.CopyElements(sourcefinalView, elem, destfinalView, null, null);
                TransactionManager.Instance.TransactionTaskDone();
                return(elem);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Ejemplo n.º 12
0
        //指定字段视图更新二维图元函数-updateFieldView
        public void upadteFieldView(Document doc, IList <string> selectedFieldView, ICollection <ElementId> FieldViewId, ICollection <ElementId> PlotViewIds, string origin_str, string target_str, CMD.myDelegate _myDelegate)
        {
            ICollection <ElementId> selectedfieldViewIds = selNameToEleIds(doc, selectedFieldView, FieldViewId);//将选择目标字段视图转化为元素id

            using (Transaction UpdateEles = new Transaction(doc, "UpdateEles"))
            {
                UpdateEles.Start("UpdateEles");
                foreach (ElementId eId in selectedfieldViewIds)//遍历每一个选择的INTF视图
                {
                    Autodesk.Revit.DB.View destinationView = doc.GetElement(eId) as Autodesk.Revit.DB.View;
                    string destinationViewName             = destinationView.Name.Replace(target_str, origin_str);//设置目标视图变量//
                    foreach (ElementId sourceViewId in PlotViewIds)
                    {
                        string sourceName = doc.GetElement(sourceViewId).Name;
                        if (destinationViewName == sourceName)
                        {
                            ICollection <ElementId> all2DEleIds = getAllCopyEleIds(doc, eId);//删除INTF视图的二维图元
                            doc.Delete(all2DEleIds);
                            Autodesk.Revit.DB.View  sourceView     = doc.GetElement(sourceViewId) as Autodesk.Revit.DB.View;
                            ICollection <ElementId> selectedEleIds = _myDelegate(doc, sourceViewId);//设置目标函数变量//获取需要从PLOT视图复制的2D图元
                            if (selectedEleIds != null && selectedEleIds.Count() != 0)
                            {
                                ElementTransformUtils.CopyElements(sourceView, selectedEleIds, destinationView, null, null);//复制图元
                            }
                        }
                    }
                }
                UpdateEles.Commit();
            }
            showSuccess(target_str);
        }
Ejemplo n.º 13
0
        /// <summary>
        /// Копируем материалы из файла ресурса
        /// </summary>
        /// <param name="Doc"></param>
        /// <param name="ResurseDoc"></param>
        /// <param name="elementIds"></param>
        private void CopyProjectStandart(Document Doc, Document ResurseDoc, ICollection <ElementId> elementIds)
        {
            CopyPasteOptions copyPasteOptions = new CopyPasteOptions();

            if (elementIds.Count > 0)
            {
                ElementTransformUtils.CopyElements(ResurseDoc, elementIds, Doc, Transform.Identity, copyPasteOptions);
            }
        }
Ejemplo n.º 14
0
        public bool CopyRooms(Level toLevel)
        {
            var succeed = false;

            try
            {
                var destinationView = FindViewPlan(toLevel);
                var transform       = Transform.Identity;
                var opt             = new CopyPasteOptions();
                var boundaryIds     = new List <ElementId>();

                foreach (var roomId in RoomDictionary.Keys)
                {
                    var rp         = RoomDictionary[roomId];
                    var sourceView = rp.SourceView;

                    if (rp.RoomSeparationLinesIds.Count > 0)
                    {
                        var boundariesToCopy = new List <ElementId>();
                        foreach (var eId in rp.RoomSeparationLinesIds)
                        {
                            if (!boundaryIds.Contains(eId))
                            {
                                boundariesToCopy.Add(eId);
                                boundaryIds.Add(eId);
                            }
                        }
                        if (boundariesToCopy.Count > 0)
                        {
                            IList <ElementId> copiedBoundaries = ElementTransformUtils.CopyElements(sourceView, boundariesToCopy, destinationView, transform, opt).ToList();
                        }
                    }

                    var elementsToCopy = new List <ElementId>();
                    elementsToCopy.Add(rp.RoomObject.Id);
                    var copiedRooms = ElementTransformUtils.CopyElements(sourceView, elementsToCopy, destinationView, transform, opt).ToList();
                    NewRooms.AddRange(copiedRooms);
                    var element = m_doc.GetElement(copiedRooms.First());
                    if (null != element)
                    {
                        var newRoom = element as Room;
                        newRoom.Number = rp.RoomNumber;
                    }
                }
                if (NewRooms.Count > 0)
                {
                    succeed = true;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Failed to recreate rooms.\n" + ex.Message, "Recreate Rooms", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                succeed = false;
            }
            return(succeed);
        }
Ejemplo n.º 15
0
        private static int DuplicateDetailingAcrossViews(View fromView, View toView)
        {
            int numberOfCopiedElements = 0;

            try
            {
                List <ElementId> elementIdsToExclude = new List <ElementId>();

                ICollection <ElementId> referenceCalloutIds = fromView.GetReferenceCallouts();
                elementIdsToExclude.AddRange(referenceCalloutIds);
                ICollection <ElementId> referenceElevationIds = fromView.GetReferenceElevations();
                elementIdsToExclude.AddRange(referenceElevationIds);
                ICollection <ElementId> referenceSectionIds = fromView.GetReferenceSections();
                elementIdsToExclude.AddRange(referenceSectionIds);

                FilteredElementCollector collector = new FilteredElementCollector(fromView.Document, fromView.Id);
                if (elementIdsToExclude.Count > 0)
                {
                    collector.Excluding(elementIdsToExclude);
                }
                collector.WherePasses(new ElementCategoryFilter(ElementId.InvalidElementId, true));

                ICollection <ElementId> toCopy = collector.ToElementIds();

                CopyPasteOptions options = new CopyPasteOptions();
                options.SetDuplicateTypeNamesHandler(new HideAndAcceptDuplicateTypeNamesHandler());
                if (toCopy.Count > 0)
                {
                    using (Transaction t2 = new Transaction(toView.Document, "Duplicate view detailing"))
                    {
                        t2.Start();
                        try
                        {
                            ICollection <ElementId> copiedElements = ElementTransformUtils.CopyElements(fromView, toCopy, toView, Transform.Identity, options);
                            numberOfCopiedElements = copiedElements.Count;

                            FailureHandlingOptions failureOptions = t2.GetFailureHandlingOptions();
                            failureOptions.SetFailuresPreprocessor(new HidePasteDuplicateTypesPreprocessor());
                            t2.Commit(failureOptions);
                        }
                        catch (Exception ex)
                        {
                            string message = ex.Message;
                            t2.RollBack();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                //MessageBox.Show("Failed to duplicate detialing across views.\n"+ex.Message, "Duplicate Detailing Across Views", MessageBoxButton.OK, MessageBoxImage.Warning);
                errorMessage.AppendLine(toView.Name + ": errors in duplicating detailing across views.\n" + ex.Message);
            }
            return(numberOfCopiedElements);
        }
Ejemplo n.º 16
0
        private void BtnCopyViews_Click(object sender, RoutedEventArgs e)
        {
            //Use a Try block to keep any errors from crashing Revit
            try
            {
                //Integer variable to count the number of Legends transferred
                int count = 0;
                //Get the Link Document by casting the Selected Value of the Combo Box to a Document
                Document linkDoc = (Document)ComboBoxLinks.SelectedValue;
                //Use CopyPasteOptions to control the behavior of like elements on copy "Use Current Project or Import Types"
                CopyPasteOptions options = new CopyPasteOptions();
                //Set the Copy Paste Optiosn by useing a Copy Handler class in the Functions Class
                options.SetDuplicateTypeNamesHandler(new Helpers.CopyHandler());

                //Use a Transaction for the Document you are pasting INTO to copy the Legends into
                using (Transaction trans = new Transaction(doc))
                {
                    //Start the transaction and give it a name for the Undo / Redo list
                    trans.Start("Copy Linked Legends");
                    //Loop through each of the Checked Items (views) in the List view to copy
                    foreach (ElementIdName Legend in LinkedLegends)
                    {
                        if (Legend.Check)
                        {
                            //Cast the View from the List View Item Tag property set previously
                            View view = (View)linkDoc.GetElement(Legend.ElemId);
                            //Use a Element Collector to get ALL element Ids in the Legend using the Linked view.Id modifier and put them into a list
                            ICollection <ElementId> elemIds = new FilteredElementCollector(linkDoc, view.Id).ToElementIds();
                            //Use the Trsnform Utilities Class with the CopyElements method to copy the Legend View and elements into a new legend in the current document
                            //Although we supply the "TempLegend" view for this method to copy the elements into, the Linnked View ElemExt element is also copied and actually
                            //creates an entirely new Legend WITHOUT copying any elements into the "TempLegend" view.
                            ElementTransformUtils.CopyElements(view, elemIds, TempLegend, Transform.Identity, options);
                            //Add 1 to the counte integer we will use to tell the user how many legends were copied
                            count++;
                        }
                    }
                    //Commit the transaction to save the changed to the document
                    trans.Commit();
                }
                //Tell the user how many legends were copied
                TaskDialog.Show("Copy Legends", "Copied " + count + " Legends");
                //Set the Dialog Result so that the calling Method resturns the correct result and the changes stick
                DialogResult = true;
                //Close the form
                Close();
            }
            //Display a message that an error occured when trying to copy the legend, set the Dialog Result, and close the form.
            catch (Exception ex)
            {
                TaskDialog.Show("Copy Legends Error", ex.ToString());
                DialogResult = false;
                Close();
            }
        }
Ejemplo n.º 17
0
        public static Dictionary <string, object> BakeElements(List <Revit.Elements.Element> element,
                                                               Boolean bakeElementsToggle = false, Boolean pinElementsToggle = false)
        {
            //declare an elementId collection and add the ids to it.
            List <Autodesk.Revit.DB.ElementId> idCollection = new List <Autodesk.Revit.DB.ElementId>();

            //get the element ids
            foreach (var item in element)
            {
                var internalElement = (Autodesk.Revit.DB.Element)item.InternalElement;
                idCollection.Add(internalElement.Id);
            }
            //declare new list to append the new elements to it
            List <Revit.Elements.Element> newElements = new List <Revit.Elements.Element>();
            var wasRan = (string)"Set Toggle to true";

            if (bakeElementsToggle == true)
            {
                //start the transaction to copy elements
                Document doc        = DocumentManager.Instance.CurrentDBDocument;
                var      revitPoint = new XYZ(0, 0, 0);
                TransactionManager.Instance.EnsureInTransaction(doc);
                var newElementIds = ElementTransformUtils.CopyElements(doc, idCollection, revitPoint);
                TransactionManager.Instance.TransactionTaskDone();
                foreach (var id in idCollection)
                {
                    TransactionManager.Instance.EnsureInTransaction(doc);
                    var deletedElements = doc.Delete(id);
                    TransactionManager.Instance.TransactionTaskDone();
                }
                foreach (var item in newElementIds)
                {
                    newElements.Add(doc.GetElement(item).ToDSType(true));
                }
                foreach (Revit.Elements.Element ele in newElements)
                {
                    ele.InternalElement.Pinned = pinElementsToggle;
                }
                wasRan = (string)"Success!";
            }
            else
            {
                wasRan = (string)"Set Toggle to true";
            }

            //returns the outputs
            var outInfo = new Dictionary <string, object>
            {
                { "element", newElements },
                { "wasRan?", wasRan }
            };

            return(outInfo);
        }
Ejemplo n.º 18
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;

            IList <Reference> linkModelRefs = uidoc.Selection.PickObjects(ObjectType.LinkedElement, "Select Elements");

            //group selected elements by rvt link
            var refGroupByLinkModel = linkModelRefs.GroupBy(item => doc.GetElement(item).Id).Select(refs => refs.ToList());

            using (Transaction t = new Transaction(doc, "Copy Linked Elements"))
            {
                t.Start();

                try
                {
                    CopyPasteOptions copyPasteOption = new CopyPasteOptions();
                    copyPasteOption.SetDuplicateTypeNamesHandler(new CustomCopyHandler());

                    foreach (List <Reference> linkedModelRef in refGroupByLinkModel)
                    {
                        ICollection <ElementId> eleToCopy = new List <ElementId>();

                        Element           e             = doc.GetElement(linkedModelRef.First().ElementId);
                        RevitLinkInstance revitLinkInst = e as RevitLinkInstance;
                        Document          linkRvtDoc    = (e as RevitLinkInstance).GetLinkDocument();
                        Transform         transf        = revitLinkInst.GetTransform();

                        foreach (Reference elementRef in linkedModelRef)
                        {
                            Element eLinked = linkRvtDoc.GetElement(elementRef.LinkedElementId);
                            eleToCopy.Add(eLinked.Id);
                        }

                        ElementTransformUtils.CopyElements(linkRvtDoc, eleToCopy, doc, transf, copyPasteOption);

                        TaskDialog.Show("elements to copy", String.Format("{0} elements have been copied from model {1}", eleToCopy.Count, revitLinkInst.Name));
                    }
                }
                catch (Exception ex)
                {
                    TaskDialog.Show("e", ex.Message);
                }

                t.Commit();
            }

            return(Result.Succeeded);
        }//close Execute
        private void AllDetailsImports(int id)
        {
            CopyPasteOptions options = new CopyPasteOptions();

            options.SetDuplicateTypeNamesHandler(new HideAndAcceptDuplicateTypeNamesHandler());

            List <View> fromAllViews = GetAllViews(fromDocument);
            Dictionary <ElementId, List <ElementId> > selectedElemsIdsByViews = elementsIdsByViews(fromDocument, fromSelectedViews);

            foreach (KeyValuePair <ElementId, List <ElementId> > selectedKeyValuePairs in selectedElemsIdsByViews)
            {
                List <View> toAllViews = GetAllViews(toDocument);

                ElementId        fromSelectedViewId      = selectedKeyValuePairs.Key;
                List <ElementId> fromSelectedElementsIds = selectedKeyValuePairs.Value;

                List <ElementId> fromSelectedViewIdCol = new List <ElementId>();
                fromSelectedViewIdCol.Add(fromSelectedViewId);

                ICollection <ElementId> toSelectedViewIdCol = null;
                View toSelectedView = null;
                try
                {
                    toSelectedViewIdCol = ElementTransformUtils.CopyElements(fromDocument, fromSelectedViewIdCol, toDocument, Transform.Identity, options);
                    if (toSelectedViewIdCol.Count > 0)
                    {
                        toSelectedView = toDocument.GetElement(toSelectedViewIdCol.First()) as View;
                    }
                }
                catch (Exception ex)
                {
                    toSelectedViewIdCol = null;
                    toSelectedView      = null;
                }


                View fromSelectedView = fromDocument.GetElement(fromSelectedViewId) as View;
                if ((fromSelectedView != null) && (toSelectedView != null))
                {
                    ICollection <ElementId> toSelectedElementsIdsCol = null;
                    try
                    {
                        toSelectedElementsIdsCol = ElementTransformUtils.CopyElements(fromSelectedView, fromSelectedElementsIds, toSelectedView, Transform.Identity, options);
                    }
                    catch (Exception ex)
                    {
                        toSelectedElementsIdsCol = null;
                    }
                }
            }

            TaskDialog.Show("Info", "Were imported " + selectedElemsIdsByViews.Count.ToString() + " views");
        }
Ejemplo n.º 20
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);
            }
        }
Ejemplo n.º 21
0
        private static void DuplicateScheduleSheetInstance(Sheet oldSheet, Sheet newSheet)
        {
            List <ElementId> list = new List <ElementId>();

            foreach (var schedule in oldSheet.Schedules)
            {
                if (!schedule.InternalScheduleOnSheet.IsTitleblockRevisionSchedule)
                {
                    list.Add(schedule.InternalElement.Id);
                }
            }
            if (list.Any <ElementId>())
            {
                ElementTransformUtils.CopyElements(oldSheet.InternalViewSheet, list, newSheet.InternalViewSheet, null, null);
            }
        }
 public void Transferviewtemplate(Document source, Document target, List <ElementId> elementIds)
 {
     using (Transaction tran = new Transaction(target, "Ivention EXT: Transfer view template"))
     {
         tran.Start();
         FailureHandlingOptions options       = tran.GetFailureHandlingOptions();
         IgnoreProcess          ignoreProcess = new IgnoreProcess();
         options.SetClearAfterRollback(true);
         options.SetFailuresPreprocessor(ignoreProcess);
         tran.SetFailureHandlingOptions(options);
         CopyPasteOptions coptions = new CopyPasteOptions();
         coptions.SetDuplicateTypeNamesHandler(new CopyHandler());
         ICollection <ElementId> litstrans = ElementTransformUtils.CopyElements(source, elementIds, target, null, coptions);
         tran.Commit(options);
     }
 }
Ejemplo n.º 23
0
        public static IEnumerable <ElementId> CopyElements(this Document document, string path, Func <Document, FilteredElementCollector> function, CopyPasteOptions copyPasteOptions = null)
        {
            if (document == null || string.IsNullOrWhiteSpace(path) || !System.IO.File.Exists(path) || function == null)
            {
                return(null);
            }

            Document document_source = null;

            try
            {
                document_source = new Autodesk.Revit.UI.UIDocument(document).Application.Application.OpenDocumentFile(path);
            }
            catch (Exception exception)
            {
                if (document_source != null)
                {
                    document_source.Close(false);
                }

                return(null);
            }

            IEnumerable <ElementId> result = null;

            if (document_source != null)
            {
                FilteredElementCollector filteredElementCollector = function.Invoke(document_source);
                List <ElementId>         elementIds = filteredElementCollector?.ToElementIds()?.ToList();
                if (elementIds != null && elementIds.Count != 0)
                {
                    if (copyPasteOptions == null)
                    {
                        copyPasteOptions = new CopyPasteOptions();
                        copyPasteOptions.SetDuplicateTypeNamesHandler(new DestinationDuplicateTypeNamesHandler());
                    }

                    result = ElementTransformUtils.CopyElements(document_source, elementIds, document, null, copyPasteOptions);
                }
            }

            document_source.Close(false);

            return(result);
        }
Ejemplo n.º 24
0
        private void duplicateSheets(Document detailLibrary, Document templateFile, ViewSheet sheet)
        {
            ICollection <ElementId> sheetToCopy = new Collection <ElementId>();

            sheetToCopy.Add(sheet.Id);

            ICollection <ElementId> copyIdsViewSpecific = new Collection <ElementId>();

            foreach (Element e in new FilteredElementCollector(detailLibrary).OwnedByView(sheet.Id))
            {
                // do not put viewports into this collection because they cannot be copied
                if (!(e is Viewport))
                {
                    copyIdsViewSpecific.Add(e.Id);
                }
            }

            ElementId newsheet;

            using (Transaction tDelete = new Transaction(detailLibrary, "Clear Sheet"))
            {
                tDelete.Start();

                IList <Viewport> viewports = new FilteredElementCollector(detailLibrary).OfClass(typeof(Viewport)).Cast <Viewport>()
                                             .Where(q => q.SheetId == sheet.Id).ToList();

                foreach (Viewport vp in viewports)
                {
                    detailLibrary.Delete(vp.Id);
                }

                using (Transaction t = new Transaction(templateFile, "Duplicate Sheet"))
                {
                    t.Start();
                    ViewSheet newSheet = templateFile.GetElement(ElementTransformUtils.CopyElements(detailLibrary, sheetToCopy, templateFile, Transform.Identity, new CopyPasteOptions()).First()) as ViewSheet;
                    newsheet = newSheet.Id;
                    ElementTransformUtils.CopyElements(sheet, copyIdsViewSpecific, newSheet, Transform.Identity, new CopyPasteOptions());
                    t.Commit();
                }
                tDelete.RollBack();
            }

            this.sheetIDMap.Add(sheet.Id, newsheet);
        }
Ejemplo n.º 25
0
        /// <summary>
        /// need OPEN TRANSACTION
        /// </summary>
        public override void Execute()
        {
            var doc = this.fs.Document;

            if (this.sType != StructuralType.Footing)
            {
                //create new on level
                var locLine = getLocLine();
                base.Elem = doc.Create.NewFamilyInstance(locLine, this.fs, this.hostLevel, this.sType);
            }
            else
            {
                //find face on temp geom
                PlanarFace pf = this.tempDS.GetAllSolids()
                                .SelectMany(s => s.Faces.Cast <PlanarFace>())
                                .Where(f => f != null)
                                .FirstOrDefault(f => f.FaceNormal.IsAlmostEqualToByDifference(XYZ.BasisZ, 0.0001));

                var tempFi = doc.Create.NewFamilyInstance(pf, this.offsetLocLine, fs);
                //copy to level
                var cpo       = new CopyPasteOptions();
                var newCopies = ElementTransformUtils.CopyElements
                                    (this.viewPlan,
                                    new ElementId[1] {
                    tempFi.Id
                },
                                    this.viewPlan, null, cpo);
                base.Elem = doc.GetElement(newCopies.First()) as FamilyInstance;
                //delete temp elems
                doc.Delete(tempFi.Id);
                if (this.tempDS != null)
                {
                    doc.Delete(this.tempDS.Id);
                }
            }

            if (this.NewFI == null)
            {
                return;
            }
            FamilyEditor.SetParams(this.NewFI, this.paramValues);

            calcOffset();
        }
Ejemplo n.º 26
0
 public void Copyelement(Document Source, Document Target, ICollection <ElementId> elementIds)
 {
     using (Transaction t = new Transaction(Target, "Copy Model"))
     {
         t.Start();
         FailureHandlingOptions options       = t.GetFailureHandlingOptions();
         MyPreProcessor         ignoreProcess = new MyPreProcessor();
         options.SetClearAfterRollback(true);
         options.SetFailuresPreprocessor(ignoreProcess);
         t.SetFailureHandlingOptions(options);
         try
         {
             ElementTransformUtils.CopyElements(Source, elementIds, Target, Transform.Identity, new CopyPasteOptions());
         }
         catch
         {
         }
         t.Commit();
     }
 }
        bool CopyViewTemplate(Document sourceDocument, Document destinationDocument)
        {
            IList <ElementId>        copyElemIdList = new List <ElementId>();
            FilteredElementCollector elems          = new FilteredElementCollector(sourceDocument);

            foreach (View view in elems.OfClass(typeof(View)))
            {
                if (view.IsTemplate)
                {
                    copyElemIdList.Add(view.Id);
                }
            }

            CopyPasteOptions options = new CopyPasteOptions();

            options.SetDuplicateTypeNamesHandler(new ElementCopyCoverHandler());
            ElementTransformUtils.CopyElements(sourceDocument, copyElemIdList, destinationDocument, null, options);

            return(true);
        }
        bool CreateGeneralDrawing(Document sourceDocument, Document destinationDocument, ElementId titleBlockTypeId, ViewSheet viewSheet)
        {
            try
            {
                ViewSheet destiationView = ViewSheet.Create(destinationDocument, titleBlockTypeId);
                destiationView.SheetNumber = viewSheet.SheetNumber.Replace("D1_", "").Replace("D2_", "");
                destiationView.Name        = viewSheet.Name;

                IList <ElementId>          copyElemIdList = new List <ElementId>();
                ElementMulticategoryFilter categoryFilter = new ElementMulticategoryFilter(new List <BuiltInCategory> {
                    BuiltInCategory.OST_LegendComponents,
                    BuiltInCategory.OST_TextNotes,
                    BuiltInCategory.OST_Lines,
                    BuiltInCategory.OST_GenericAnnotation,
                    BuiltInCategory.OST_InsulationLines,
                    BuiltInCategory.OST_Dimensions,
                    BuiltInCategory.OST_IOSDetailGroups,
                    BuiltInCategory.OST_RevisionClouds,
                    BuiltInCategory.OST_RevisionCloudTags,
                    BuiltInCategory.OST_DetailComponents,
                    BuiltInCategory.OST_DetailComponentTags
                });
                FilteredElementCollector elems = new FilteredElementCollector(sourceDocument, viewSheet.Id);
                foreach (Element elem in elems.WherePasses(categoryFilter))
                {
                    if (elem.GroupId.IntegerValue == -1)
                    {
                        copyElemIdList.Add(elem.Id);
                    }
                }

                CopyPasteOptions options = new CopyPasteOptions();
                options.SetDuplicateTypeNamesHandler(new ElementCopyCoverHandler());
                ElementTransformUtils.CopyElements(viewSheet, copyElemIdList, destiationView, Transform.CreateTranslation(new XYZ(0, 0, 0)), options);
            }
            catch
            {
                return(false);
            }
            return(true);
        }
Ejemplo n.º 29
0
        public void CopyElementsBetweenSheets(SheetCopierViewHost sheet)
        {
            IList <ElementId> list = new List <ElementId>();

            using (var collector = new FilteredElementCollector(doc))
            {
                collector.OwnedByView(sheet.SourceSheet.Id);
                foreach (Element e in collector)
                {
                    if (!(e is Viewport))
                    {
                        if (e is CurveElement)
                        {
                            continue;
                        }
                        if (e.IsValidObject && e.ViewSpecific)
                        {
                            list.Add(e.Id);
                        }
                    }
                }
            }
            if (list.Count > 0)
            {
                Transform        transform;
                CopyPasteOptions options;
                ElementTransformUtils.CopyElements(
                    sheet.SourceSheet,
                    list,
                    sheet.DestinationSheet,
                    transform = new Transform(ElementTransformUtils.GetTransformFromViewToView(sheet.SourceSheet, sheet.DestinationSheet)),
                    options   = new CopyPasteOptions());
                if (Settings.Default.DeleteRevisionClouds)
                {
                    DeleteRevisionClouds(sheet.DestinationSheet.Id, doc);
                }
                options.Dispose();
                transform.Dispose();
            }
        }
Ejemplo n.º 30
0
        public void CopyElements(Document doc, FamilyInstance familyInstance, List <FamilyInstance> listinstance, ICollection <ElementId> elementIds)
        {
            ICollection <ElementId> newlist         = new List <ElementId>();
            CopyPasteOptions        option          = new CopyPasteOptions();
            ProgressBarform         progressBarform = new ProgressBarform(listinstance.Count, "Loading...");

            progressBarform.Show();
            foreach (FamilyInstance source in listinstance)
            {
                progressBarform.giatri();
                if (progressBarform.iscontinue == false)
                {
                    break;
                }
                Transform transform  = TransformToCopy(source, familyInstance);
                Transform transform1 = Transform.CreateTranslation(transform.Origin);
                using (Transaction tran = new Transaction(doc, "copy"))
                {
                    tran.Start();
                    FailureHandlingOptions options       = tran.GetFailureHandlingOptions();
                    IgnoreProcess          ignoreProcess = new IgnoreProcess();
                    options.SetClearAfterRollback(true);
                    options.SetFailuresPreprocessor(ignoreProcess);
                    tran.SetFailureHandlingOptions(options);
                    try
                    {
                        newlist = ElementTransformUtils.CopyElements(doc, elementIds, doc, transform, option);
                        Remove_product(doc, newlist);
                    }
                    catch (Exception)
                    {
                    }
                    tran.Commit();
                }
            }
            progressBarform.Close();
        }