Example #1
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);
        }
        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();
        }
        /// <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);
        }
        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);
        }
Example #5
0
        private static bool DuplicateReferenceCallouts(View fromView, View toView)
        {
            bool result = false;

            try
            {
                Document fromDoc = fromView.Document;
                Document toDoc   = toView.Document;

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

                ICollection <ElementId> referenceCalloutIds = fromView.GetReferenceCallouts();
                if (referenceCalloutIds.Count > 0)
                {
                    foreach (ElementId eId in referenceCalloutIds)
                    {
                        XYZ  firstPoint  = null;
                        XYZ  secondPoint = null;
                        bool cornerFound = GetCalloutCornerPoints(fromDoc, eId, out firstPoint, out secondPoint);

                        Element callout = fromDoc.GetElement(eId);
                        if (null != callout)
                        {
                            using (Transaction trans = new Transaction(toDoc, "Duplicate Reference Callout"))
                            {
                                try
                                {
                                    trans.Start();

                                    toDoc.Regenerate();
                                    FilteredElementCollector collector = new FilteredElementCollector(toDoc);
                                    List <ViewDrafting>      views     = collector.OfClass(typeof(ViewDrafting)).ToElements().Cast <ViewDrafting>().ToList();
                                    var viewFound = from view in views where view.Name == callout.Name select view;
                                    if (viewFound.Count() > 0)
                                    {
                                        ViewDrafting referenceView = viewFound.First();
                                        ViewSection.CreateReferenceCallout(toDoc, toView.Id, referenceView.Id, firstPoint, secondPoint);
                                    }

                                    trans.Commit();
                                }
                                catch (Exception ex)
                                {
                                    string message = ex.Message;
                                    trans.RollBack();
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                string message = ex.Message;
                //MessageBox.Show("Failed to duplicate reference callouts.\n"+ex.Message, "Duplicate Reference Callouts", MessageBoxButton.OK, MessageBoxImage.Warning);
                errorMessage.AppendLine(toView.Name + ": errors in duplicating reference callouts");
            }
            return(result);
        }
Example #6
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);
        }
Example #7
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);
            }
        }
Example #8
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);
        }
Example #9
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);
        }
Example #10
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();
            }
        }
Example #11
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");
        }
        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);
            }
        }
 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);
     }
 }
Example #15
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);
        }
Example #16
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();
        }
        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);
        }
Example #19
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();
            }
        }
        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();
        }
Example #21
0
        public void CopyMaterial(ObservableCollection <DocModel> DocumentList, ObservableCollection <MaterialModel> curentMaterialList)
        {
            CopyPasteOptions copyPasteOptions = new CopyPasteOptions();

            foreach (var docModel in DocumentList)
            {
                if (docModel.ChangeMaterial)
                {
                    using (Transaction t = new Transaction(docModel.doc, "Копирование материалов"))
                    {
                        t.Start();

                        foreach (var KeyValuePair in GetElementIdCollection(curentMaterialList))
                        {
                            try
                            {
                                if (KeyValuePair.Value.Count > 0)
                                {
                                    ElementTransformUtils.CopyElements(KeyValuePair.Key, KeyValuePair.Value, docModel.doc, Transform.Identity, copyPasteOptions);
                                    foreach (var el in KeyValuePair.Value)
                                    {
                                        loger.AddLog("Скопирован материал " + KeyValuePair.Key.GetElement(el).Name + " из файла " + KeyValuePair.Key.Title + " в " + docModel.doc.Title);
                                    }
                                }
                            }
                            catch
                            {
                                loger.AddLog("Не удалось скопировать материалы из документа ", KeyValuePair.Key.Title);
                            }
                        }

                        t.Commit();
                    }
                }
            }
            loger.ShowTxtLog();
        }
        public void CopyElementsConnFlangeDtee(Document doc, FamilyInstance familyInstance, List <FamilyInstance> listinstance, ICollection <ElementId> elementIds, bool valuekey)
        {
            ICollection <ElementId> newlist  = new List <ElementId>();
            Parameter        pa1             = familyInstance.LookupParameter("Flange_Edge_Offset_Right");
            double           Flange_Right1   = pa1.AsDouble();
            Parameter        pa2             = familyInstance.LookupParameter("Flange_Edge_Offset_Left");
            double           Flange_Left1    = pa2.AsDouble();
            Parameter        pal             = familyInstance.LookupParameter("DIM_LENGTH");
            double           dim_length      = pal.AsDouble();
            var              f1              = elementIds.First();
            double           kl              = Nut(doc, familyInstance, f1);
            CopyPasteOptions option          = new CopyPasteOptions();
            ProgressBarform  progressBarform = new ProgressBarform(listinstance.Count, "Loading...");

            progressBarform.Show();
            foreach (FamilyInstance source in listinstance)
            {
                if (source.Id != familyInstance.Id)
                {
                    using (Transaction tran = new Transaction(doc, "Copy"))
                    {
                        tran.Start();
                        Transform transform1   = source.GetTransform();
                        Parameter pa3          = source.LookupParameter("Flange_Edge_Offset_Right");
                        double    Flange_Right = pa3.AsDouble();
                        ElementId sourceid     = source.GetTypeId();
                        Element   sourcetype   = doc.GetElement(sourceid);
                        Parameter sourcepa     = sourcetype.LookupParameter("DT_Stem_Spacing_Form");
                        Parameter pa4          = source.LookupParameter("Flange_Edge_Offset_Left");
                        double    Flange_Left  = pa4.AsDouble();
                        double    val1         = Flange_Right1 - Flange_Right;
                        double    val2         = Flange_Left1 - Flange_Left;
                        progressBarform.giatri();
                        if (progressBarform.iscontinue == false)
                        {
                            break;
                        }
                        Transform transform                  = TransformToCopy(source, familyInstance);
                        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)
                        {
                        }
                        if (valuekey == true)
                        {
                            if (sourcepa == null)
                            {
                                if (val1 != 0 || val2 != 0)
                                {
                                    FamilyInstance    flatsource        = GetFlat(doc, familyInstance);
                                    FamilyInstance    flattarget        = GetFlat(doc, source);
                                    List <PlanarFace> planarFacessource = FlFaces(flatsource);
                                    List <PlanarFace> planarFacetarget  = FlFaces(flattarget);
                                    Element           elesource         = doc.GetElement(elementIds.First());
                                    double            spatarget         = 0;
                                    foreach (ElementId i in newlist)
                                    {
                                        Element       eletarget      = doc.GetElement(i);
                                        LocationPoint locationPoint2 = eletarget.Location as LocationPoint;
                                        XYZ           pointtarget    = locationPoint2.Point;
                                        spatarget = DistanceToMin(doc, source, planarFacetarget, pointtarget, kl);
                                        if (spatarget != 0)
                                        {
                                            break;
                                        }
                                    }
                                    if (spatarget != 0)
                                    {
                                        foreach (ElementId i in newlist)
                                        {
                                            XYZ point1 = new XYZ(0, 0, 0);
                                            point1 = point1 + transform1.BasisX * -spatarget;
                                            ElementTransformUtils.MoveElement(doc, i, point1);
                                        }
                                    }
                                }
                            }
                            else
                            {
                                if (val2 > 0)
                                {
                                    foreach (ElementId i in newlist)
                                    {
                                        XYZ point1 = new XYZ(0, 0, 0);
                                        point1 = point1 + transform1.BasisX * -val2;
                                        ElementTransformUtils.MoveElement(doc, i, point1);
                                    }
                                }
                                else
                                {
                                    foreach (ElementId i in newlist)
                                    {
                                        XYZ point1 = new XYZ(0, 0, 0);
                                        point1 = point1 + transform1.BasisX * -val2;
                                        ElementTransformUtils.MoveElement(doc, i, point1);
                                    }
                                }
                            }
                        }
                        if (valuekey == false)
                        {
                            if (sourcepa == null)
                            {
                                if (val1 != 0 || val2 != 0)
                                {
                                    FamilyInstance    flatsource        = GetFlat(doc, familyInstance);
                                    FamilyInstance    flattarget        = GetFlat(doc, source);
                                    List <PlanarFace> planarFacessource = FlFaces(flatsource);
                                    List <PlanarFace> planarFacetarget  = FlFaces(flattarget);
                                    Element           elesource         = doc.GetElement(elementIds.First());
                                    double            spatarget         = 0;
                                    foreach (ElementId i in newlist)
                                    {
                                        Element       eletarget      = doc.GetElement(i);
                                        LocationPoint locationPoint2 = eletarget.Location as LocationPoint;
                                        XYZ           pointtarget    = locationPoint2.Point;
                                        spatarget = DistanceToMin(doc, source, planarFacetarget, pointtarget, kl);
                                        if (spatarget != 0)
                                        {
                                            break;
                                        }
                                    }
                                    if (spatarget != 0)
                                    {
                                        foreach (ElementId i in newlist)
                                        {
                                            XYZ point1 = new XYZ(0, 0, 0);
                                            point1 = point1 + transform1.BasisX * spatarget;
                                            ElementTransformUtils.MoveElement(doc, i, point1);
                                        }
                                    }
                                }
                            }
                            else
                            {
                                if (val1 > 0)
                                {
                                    foreach (ElementId i in newlist)
                                    {
                                        XYZ point1 = new XYZ(0, 0, 0);
                                        point1 = point1 + transform1.BasisX * (val1);
                                        ElementTransformUtils.MoveElement(doc, i, point1);
                                    }
                                }
                                else
                                {
                                    foreach (ElementId i in newlist)
                                    {
                                        XYZ point1 = new XYZ(0, 0, 0);
                                        point1 = point1 + transform1.BasisX * (-val1);
                                        ElementTransformUtils.MoveElement(doc, i, point1);
                                    }
                                }
                            }
                        }
                        tran.Commit();
                    }
                }
            }
            progressBarform.Close();
        }
        public void CopyElementsFlatToWarped(Document doc, FamilyInstance familyInstance, ICollection <ElementId> elementIds, Selection sel)
        {
            ICollection <ElementId> newlist = new List <ElementId>();
            CopyPasteOptions        option  = new CopyPasteOptions();
            ElementtransformToCopy  tr      = new ElementtransformToCopy();
            FamilyInstance          flat    = tr.GetFlat(doc, familyInstance);
            List <PlanarFace>       list1   = FlFaces(flat);
            FamilyInstance          warped  = tr.GetWarped(doc, familyInstance);
            PlanarFace    face1             = Facemax(list1);
            Element       element1          = doc.GetElement(elementIds.First());
            LocationPoint loc      = element1.Location as LocationPoint;
            XYZ           pointorg = loc.Point;
            //double minspace = MinSpacePlanarFace(doc, familyInstance, face1, pointorg);
            Transform transform = TransformFlatWapred(doc, flat, warped);

            //Solid solid1 = Solidhelper.AllSolids(flat).First();
            //Solid solid2 = Solidhelper.AllSolids(warped).First();
            //Transform transform1 = solid1.GetBoundingBox().Transform;
            //Transform transform2 = solid2.GetBoundingBox().Transform;
            //Transform transform = transform1.Inverse.Multiply(transform2);
            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)
                {
                }
                foreach (ElementId eleid in newlist)
                {
                    Element            ele      = doc.GetElement(eleid);
                    LocationPoint      locele   = ele.Location as LocationPoint;
                    XYZ                pointcon = locele.Point;
                    List <HermiteFace> list2    = WarpedFace(warped);
                    if (list2.Count != 0)
                    {
                        HermiteFace face2 = FacemaxWraped(list2);
                        //double distanceloc = kcpointtoHemiteFace(face2, pointcon);

                        double distanceloc = MinSpaceHermiteFace(doc, familyInstance, face2, pointcon);
                        var    xv1         = FIndpointonwraped(pointcon, new XYZ(0, 0, 1), distanceloc);
                        XYZ    point1      = pointcon - xv1;
                        ElementTransformUtils.MoveElement(doc, eleid, point1);
                    }
                    else
                    {
                        List <RevolvedFace> revolvedFaces = WarpedFaceRevolFace(warped);
                        RevolvedFace        face2         = FacemaxWrapedRevolFace(revolvedFaces);
                        //double distanceloc = kcpointtoHemiteFace(face2, pointcon);

                        double distanceloc = MinSpaceRevolFace(doc, familyInstance, face2, pointcon);
                        var    xv1         = FIndpointonwraped(pointcon, new XYZ(0, 0, 1), distanceloc);
                        XYZ    point1      = pointcon - xv1;
                        ElementTransformUtils.MoveElement(doc, eleid, point1);
                    }
                    //if (minspace > 0)
                    //{
                    //    var xv1 = FIndpointonwraped(pointcon,doc.ActiveView.UpDirection, distanceloc);
                    //    XYZ point1 = pointcon - xv1;
                    //    ElementTransformUtils.MoveElement(doc, eleid, point1);
                    //}
                    //else
                    //{
                    //    var xv1 = FIndpointonwraped(pointcon, doc.ActiveView.UpDirection, distanceloc);
                    //    XYZ point1 = xv1 - pointcon;
                    //    ElementTransformUtils.MoveElement(doc, eleid, point1);
                    //}
                }
                tran.Commit();
            }
        }
Example #24
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            Document doc = commandData.Application.ActiveUIDocument.Document;

            // Variables to store user input
            View       selectedView;
            bool       copyDims;
            List <int> selectedIntIds;

            // Prompt window to collect user input
            using (MatchGridsWPF customWindow = new MatchGridsWPF(commandData))
            {
                customWindow.ShowDialog();
                copyDims       = customWindow.copyDim;
                selectedView   = customWindow.SelectedComboItem.Tag as View;
                selectedIntIds = customWindow.IntegerIds;
            }

            // Check that elements have been selected
            if (selectedIntIds == null)
            {
                return(Result.Cancelled);
            }
            else if (selectedIntIds.Count == 0)
            {
                TaskDialog.Show("Warning", "No views have been selected");
                return(Result.Cancelled);
            }
            else if (selectedIntIds.Count != 0)
            {
                // Collect grids visible in view
                FilteredElementCollector gridsCollector = new FilteredElementCollector(doc, selectedView.Id)
                                                          .OfCategory(BuiltInCategory.OST_Grids)
                                                          .WhereElementIsNotElementType();

                // Grid Ids
                ICollection <ElementId> gridIds = gridsCollector.ToElementIds();

                // Template for grids display
                var gridsTemplate = new Dictionary <ElementId, bool[]>();

                // Check each grid
                foreach (Grid g in gridsCollector)
                {
                    bool end0 = g.IsBubbleVisibleInView(DatumEnds.End0, selectedView);
                    bool end1 = g.IsBubbleVisibleInView(DatumEnds.End1, selectedView);

                    bool[] endSettings = { end0, end1 };

                    gridsTemplate[g.Id] = endSettings;
                }

                // Retrieve views to be matched
                List <View> viewsToMatch = new List <View>();

                foreach (int intId in selectedIntIds)
                {
                    ElementId eId  = new ElementId(intId);
                    View      view = doc.GetElement(eId) as View;

                    viewsToMatch.Add(view);
                }

                // Transaction
                using (Transaction gridTransacation = new Transaction(doc, "Match grids"))
                {
                    gridTransacation.Start();

                    foreach (View vMatch in viewsToMatch)
                    {
                        // Collect grids visible in view
                        FilteredElementCollector gridsMatchCollector = new FilteredElementCollector(doc, vMatch.Id)
                                                                       .OfCategory(BuiltInCategory.OST_Grids)
                                                                       .WhereElementIsNotElementType();

                        // Match each visible grid in view
                        foreach (Grid gMatch in gridsMatchCollector)
                        {
                            ElementId gId = gMatch.Id;

                            if (gridIds.Contains(gId))
                            {
                                bool end0GridMatch = gMatch.IsBubbleVisibleInView(DatumEnds.End0, vMatch);
                                bool end1GridMatch = gMatch.IsBubbleVisibleInView(DatumEnds.End1, vMatch);

                                bool end0Temp = gridsTemplate[gId][0];
                                bool end1Temp = gridsTemplate[gId][1];

                                // Match End0
                                if (end0Temp == true && end0GridMatch == false)
                                {
                                    gMatch.ShowBubbleInView(DatumEnds.End0, vMatch);
                                }
                                else if (end0Temp == false && end0GridMatch)
                                {
                                    gMatch.HideBubbleInView(DatumEnds.End0, vMatch);
                                }

                                // Match End1
                                if (end1Temp == true && end1GridMatch == false)
                                {
                                    gMatch.ShowBubbleInView(DatumEnds.End1, vMatch);
                                }
                                else if (end1Temp == false && end1GridMatch)
                                {
                                    gMatch.HideBubbleInView(DatumEnds.End1, vMatch);
                                }
                            }
                        }
                    }

                    // Copy grid dimensions
                    if (copyDims)
                    {
                        // Collect dimensions in selected view
                        FilteredElementCollector dimensionsCollector = new FilteredElementCollector(doc, selectedView.Id)
                                                                       .OfCategory(BuiltInCategory.OST_Dimensions)
                                                                       .WhereElementIsNotElementType();

                        // Dimensions to copy
                        List <ElementId> dimsToCopy = new List <ElementId>();

                        // Check dimensions only take grids as references
                        foreach (Dimension d in dimensionsCollector)
                        {
                            ReferenceArray dReferences = d.References;
                            bool           gridDim     = true;

                            foreach (Reference dRef in dReferences)
                            {
                                ElementId dRefId = dRef.ElementId;

                                if (!gridIds.Contains(dRefId))
                                {
                                    gridDim = false;
                                    break;
                                }
                            }

                            if (gridDim)
                            {
                                dimsToCopy.Add(d.Id);
                            }
                        }

                        // Copy dimensions
                        if (dimsToCopy.Count > 0)
                        {
                            CopyPasteOptions cp = new CopyPasteOptions();

                            foreach (View v in viewsToMatch)
                            {
                                ElementTransformUtils.CopyElements(selectedView, dimsToCopy, v, null, cp);
                            }
                        }
                    }

                    gridTransacation.Commit();
                }
            }

            return(Result.Succeeded);
        }
        /// <summary>
        /// Duplicates a set of elements across documents.
        /// </summary>
        /// <param name="fromDocument">The source document.</param>
        /// <param name="elementIds">Collection of view ids.</param>
        /// <param name="toDocument">The target document.</param>
        /// <param name="findMatchingElements">True to return a map of matching elements
        /// (matched by Name).  False to skip creation of this map.</param>
        /// <returns>The map of matching elements, if findMatchingElements was true.</returns>
        private static Dictionary <ElementId, ElementId> DuplicateElementsAcrossDocuments(Document fromDocument,
                                                                                          ICollection <ElementId> elementIds,
                                                                                          Document toDocument,
                                                                                          bool findMatchingElements)
        {
            // Return value
            Dictionary <ElementId, ElementId> elementMap = new Dictionary <ElementId, ElementId>();

            ICollection <ElementId> copiedIds;

            using (Transaction t1 = new Transaction(toDocument, "Duplicate elements"))
            {
                t1.Start();

                // Set options for copy-paste to hide the duplicate types dialog
                CopyPasteOptions options = new CopyPasteOptions();
                options.SetDuplicateTypeNamesHandler(new HideAndAcceptDuplicateTypeNamesHandler());

                // Copy the input elements.
                copiedIds =
                    ElementTransformUtils.CopyElements(fromDocument, elementIds, toDocument, Transform.Identity, options);

                // Set failure handler to hide duplicate types warnings which may be posted.
                FailureHandlingOptions failureOptions = t1.GetFailureHandlingOptions();
                failureOptions.SetFailuresPreprocessor(new HidePasteDuplicateTypesPreprocessor());
                t1.Commit(failureOptions);
            }

            // Find matching elements if required
            if (findMatchingElements)
            {
                // Build a map from name -> source element
                Dictionary <String, ElementId> nameToFromElementsMap = new Dictionary <string, ElementId>();

                foreach (ElementId id in elementIds)
                {
                    Element e    = fromDocument.GetElement(id);
                    String  name = e.Name;
                    if (!String.IsNullOrEmpty(name))
                    {
                        nameToFromElementsMap.Add(name, id);
                    }
                }

                // Build a map from name -> target element
                Dictionary <String, ElementId> nameToToElementsMap = new Dictionary <string, ElementId>();

                foreach (ElementId id in copiedIds)
                {
                    Element e    = toDocument.GetElement(id);
                    String  name = e.Name;
                    if (!String.IsNullOrEmpty(name))
                    {
                        nameToToElementsMap.Add(name, id);
                    }
                }

                // Merge to make source element -> target element map
                foreach (String name in nameToFromElementsMap.Keys)
                {
                    ElementId copiedId;
                    if (nameToToElementsMap.TryGetValue(name, out copiedId))
                    {
                        elementMap.Add(nameToFromElementsMap[name], copiedId);
                    }
                }
            }

            return(elementMap);
        }
Example #26
0
        public static IEnumerable <ElementId> CopyMaterials(this Document document, string path, IEnumerable <string> materialNames, CopyPasteOptions copyPasteOptions = null)
        {
            Func <Document, FilteredElementCollector> function = new Func <Document, FilteredElementCollector>((Document document_Temp) =>
            {
                if (document_Temp == null)
                {
                    return(null);
                }

                FilteredElementCollector filteredElementCollector = new FilteredElementCollector(document_Temp).OfCategory(BuiltInCategory.OST_Materials);

                IEnumerable <Element> elements = filteredElementCollector.ToElements();
                if (elements == null)
                {
                    return(null);
                }

                List <ElementId> elementIds = new List <ElementId>();
                foreach (Element element in elements)
                {
                    Autodesk.Revit.DB.Material material = element as Autodesk.Revit.DB.Material;
                    if (!materialNames.Contains(material.Name))
                    {
                        continue;
                    }

                    elementIds.Add(element.Id);
                }

                if (elementIds == null || elementIds.Count == 0)
                {
                    return(null);
                }

                return(new FilteredElementCollector(document_Temp, elementIds).OfCategory(BuiltInCategory.OST_Materials));
            });

            return(CopyElements(document, path, function, copyPasteOptions));
        }
        private static Element CopyByFamilyMaps(Document recipientDoc, LinkedInstanceProperties lip, Element sourceElement, CopyPasteOptions options)
        {
            Element copiedElement = null;

            try
            {
                var foundTypes = from sType in lip.LinkedFamilies.Values
                                 where sType.SourceLinkInstanceId == lip.InstanceId && sType.SourceTypeId == sourceElement.GetTypeId()
                                 select sType;
                if (foundTypes.Count() > 0)
                {
                    var familyInfo = foundTypes.First();
                    var targetType = recipientDoc.GetElement(familyInfo.TargetTypeId) as ElementType;
                    if (null != targetType)
                    {
                        if (sourceElement is FamilyInstance && targetType is FamilySymbol)
                        {
                            var sourceInstance = sourceElement as FamilyInstance;
                            var targetSymbol   = targetType as FamilySymbol;
                            if (!targetSymbol.IsActive)
                            {
                                targetSymbol.Activate();
                            }

                            var location = sourceInstance.Location;
                            if (null != location)
                            {
                                Element hostElement = null;
                                if (null != sourceInstance.Host)
                                {
                                    var hostFound = from host in lip.LinkedElements.Values
                                                    where host.SourceLinkInstanceId == lip.InstanceId && host.SourceElementId == sourceInstance.Host.Id
                                                    select host;

                                    if (hostFound.Count() > 0)
                                    {
                                        var linkedElementInfo = hostFound.First();
                                        hostElement = recipientDoc.GetElement(linkedElementInfo.LinkedElementId);
                                    }
                                }
                                Level hostLevel = null;
                                if (null != sourceInstance.LevelId)
                                {
                                    var levelFound = from level in lip.LinkedElements.Values
                                                     where level.SourceLinkInstanceId == lip.InstanceId && level.SourceElementId == sourceInstance.LevelId
                                                     select level;
                                    if (levelFound.Count() > 0)
                                    {
                                        var linkedElementInfo = levelFound.First();
                                        hostLevel = recipientDoc.GetElement(linkedElementInfo.LinkedElementId) as Level;
                                    }
                                }

                                if (location is LocationPoint)
                                {
                                    var locationPt = location as LocationPoint;
                                    var point      = locationPt.Point;
                                    point = lip.TransformValue.OfPoint(point);

                                    if (null != hostElement && null != hostLevel)
                                    {
                                        copiedElement = recipientDoc.Create.NewFamilyInstance(point, targetSymbol, hostElement, hostLevel, sourceInstance.StructuralType);
                                    }
                                    else if (null != hostElement)
                                    {
                                        copiedElement = recipientDoc.Create.NewFamilyInstance(point, targetSymbol, hostElement, sourceInstance.StructuralType);
                                    }
                                    else if (null != hostLevel)
                                    {
                                        copiedElement = recipientDoc.Create.NewFamilyInstance(point, targetSymbol, hostLevel, sourceInstance.StructuralType);
                                    }
                                    else
                                    {
                                        copiedElement = recipientDoc.Create.NewFamilyInstance(point, targetSymbol, sourceInstance.StructuralType);
                                    }
                                }
                                else if (location is LocationCurve)
                                {
                                    var locationCv = location as LocationCurve;
                                    var curve      = locationCv.Curve;
                                    curve = curve.CreateTransformed(lip.TransformValue);
                                    //check existing level mapping
                                    if (null != hostLevel)
                                    {
                                        copiedElement = recipientDoc.Create.NewFamilyInstance(curve, targetSymbol, hostLevel, sourceInstance.StructuralType);
                                    }
                                }
                            }
                        }
                        else
                        {
                            //System Families : Copy Element and change type
                            var elementIds = new List <ElementId>();
                            elementIds.Add(sourceElement.Id);
                            var copiedElementIds = ElementTransformUtils.CopyElements(lip.LinkedDocument, elementIds, recipientDoc, lip.TransformValue, options);
                            if (copiedElementIds.Count > 0)
                            {
                                var copiedElementId = copiedElementIds.First();
                                copiedElement = recipientDoc.GetElement(copiedElementId);
                                if (copiedElement.CanHaveTypeAssigned())
                                {
                                    copiedElement.ChangeTypeId(familyInfo.TargetTypeId);
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Failed to place elements by family maps.\n" + ex.Message, "Place Family Maps", MessageBoxButton.OK, MessageBoxImage.Warning);
            }
            return(copiedElement);
        }
        private static LinkedInstanceProperties DuplicateElements(Document recipientDoc, LinkedInstanceProperties lip, CategoryProperties cp, UpdateMode updateMode)
        {
            var updatedLIP = lip;

            try
            {
                var collector      = new FilteredElementCollector(updatedLIP.LinkedDocument);
                var elementsToCopy = collector.OfCategoryId(cp.CategoryId).WhereElementIsNotElementType().ToElements().ToList();

                var updatePbDelegate = new UpdateProgressBarDelegate(progressBar.SetValue);
                progressBar.Value   = 0;
                progressBar.Maximum = elementsToCopy.Count;

                var duplicated = 0;
                using (var tGroup = new TransactionGroup(recipientDoc))
                {
                    tGroup.Start("Duplicate Elements");
                    tGroup.IsFailureHandlingForcedModal = false;
                    var failureHanlder = new FailureHandler();

                    try
                    {
                        var options = new CopyPasteOptions();
                        options.SetDuplicateTypeNamesHandler(new HideAndAcceptDuplicateTypeNamesHandler());

                        double value = 0;
                        foreach (var sourceElement in elementsToCopy) //elements from link
                        {
                            value++;
                            System.Windows.Threading.Dispatcher.CurrentDispatcher.Invoke(updatePbDelegate, System.Windows.Threading.DispatcherPriority.Background, new object[] { ProgressBar.ValueProperty, value });

                            var foundElements = from element in updatedLIP.LinkedElements.Values where element.SourceUniqueId == sourceElement.UniqueId && element.SourceLinkInstanceId == updatedLIP.InstanceId select element;
                            if (foundElements.Count() > 0)
                            {
                                var linkInfo      = foundElements.First();
                                var linkedElement = recipientDoc.GetElement(linkInfo.LinkedElementId);
                                if (null != linkedElement)
                                {
                                    if (linkInfo.LinkElementType == LinkType.ByMap || updateMode == UpdateMode.UpdateLocationOnly)
                                    {
                                        if (!linkInfo.Matched)
                                        {
                                            using (var trans = new Transaction(recipientDoc))
                                            {
                                                trans.Start("Move Element");
                                                var failureOption = trans.GetFailureHandlingOptions();
                                                failureOption.SetForcedModalHandling(false);
                                                failureOption.SetFailuresPreprocessor(failureHanlder);
                                                failureOption.SetClearAfterRollback(true);
                                                trans.SetFailureHandlingOptions(failureOption);

                                                try
                                                {
                                                    var moved = LinkedElementInfo.MoveLocation(sourceElement, linkedElement, updatedLIP.TransformValue);
                                                    linkInfo.Matched = moved;
                                                    if (updatedLIP.LinkedElements.ContainsKey(linkedElement.Id))
                                                    {
                                                        updatedLIP.LinkedElements.Remove(linkedElement.Id);
                                                        updatedLIP.LinkedElements.Add(linkedElement.Id, linkInfo);
                                                    }
                                                    trans.Commit();
                                                    duplicated++;
                                                }
                                                catch (Exception ex)
                                                {
                                                    trans.RollBack();
                                                    var message = ex.Message;
                                                }
                                            }
                                        }
                                        continue;
                                    }
                                    else if (updateMode == UpdateMode.ReplaceElements)
                                    {
                                        using (var trans = new Transaction(recipientDoc))
                                        {
                                            trans.Start("Delete Element");
                                            var failureOption = trans.GetFailureHandlingOptions();
                                            failureOption.SetForcedModalHandling(false);
                                            failureOption.SetFailuresPreprocessor(failureHanlder);
                                            failureOption.SetClearAfterRollback(true);
                                            trans.SetFailureHandlingOptions(failureOption);

                                            try
                                            {
                                                var deletedIds = recipientDoc.Delete(linkInfo.LinkedElementId);
                                                if (updatedLIP.LinkedElements.ContainsKey(linkInfo.LinkedElementId))
                                                {
                                                    updatedLIP.LinkedElements.Remove(linkInfo.LinkedElementId);
                                                }
                                                trans.Commit();
                                            }
                                            catch (Exception ex)
                                            {
                                                var message = ex.Message;
                                                trans.RollBack();
                                            }
                                        }
                                    }
                                }
                            }

                            var elementIds = new List <ElementId>();
                            elementIds.Add(sourceElement.Id);
                            try
                            {
                                Element copiedElement = null;
                                var     linkType      = LinkType.None;
                                using (var trans = new Transaction(recipientDoc))
                                {
                                    trans.Start("Copy Element");
                                    var failureOption = trans.GetFailureHandlingOptions();
                                    failureOption.SetForcedModalHandling(false);
                                    failureOption.SetFailuresPreprocessor(failureHanlder);
                                    failureOption.SetClearAfterRollback(true);
                                    trans.SetFailureHandlingOptions(failureOption);

                                    try
                                    {
                                        copiedElement = CopyByFamilyMaps(recipientDoc, updatedLIP, sourceElement, options);
                                        if (null != copiedElement)
                                        {
                                            linkType = LinkType.ByMap;
                                        }
                                        else
                                        {
                                            linkType = LinkType.ByCopy;
                                            var copiedElementIds = ElementTransformUtils.CopyElements(updatedLIP.LinkedDocument, elementIds, recipientDoc, updatedLIP.TransformValue, options);
                                            if (copiedElementIds.Count > 0)
                                            {
                                                var copiedElementId = copiedElementIds.First();
                                                copiedElement = recipientDoc.GetElement(copiedElementId);
                                            }
                                        }
                                        trans.Commit();
                                    }
                                    catch (Exception ex)
                                    {
                                        trans.RollBack();
                                        var message = ex.Message;
                                    }
                                }

                                if (null != copiedElement)
                                {
                                    using (var trans = new Transaction(recipientDoc))
                                    {
                                        trans.Start("Update Link Info");
                                        var failureOption = trans.GetFailureHandlingOptions();
                                        failureOption.SetForcedModalHandling(false);
                                        failureOption.SetFailuresPreprocessor(failureHanlder);
                                        failureOption.SetClearAfterRollback(true);
                                        trans.SetFailureHandlingOptions(failureOption);

                                        try
                                        {
                                            var linkInfo = new LinkedElementInfo(linkType, sourceElement, copiedElement, updatedLIP.InstanceId, updatedLIP.TransformValue);
                                            if (!linkInfo.Matched)
                                            {
                                                var moved = LinkedElementInfo.MoveLocation(sourceElement, copiedElement, updatedLIP.TransformValue);
                                                linkInfo.Matched = moved;
                                            }
                                            var updated = MoverDataStorageUtil.UpdateLinkedElementInfo(linkInfo, copiedElement);
                                            if (!updatedLIP.LinkedElements.ContainsKey(linkInfo.LinkedElementId))
                                            {
                                                updatedLIP.LinkedElements.Add(linkInfo.LinkedElementId, linkInfo);
                                            }
                                            duplicated++;
                                            trans.Commit();
                                        }
                                        catch (Exception ex)
                                        {
                                            trans.RollBack();
                                            var message = ex.Message;
                                        }
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                var message = ex.Message;
                            }
                        }


                        if (updatedLIP.Categories.ContainsKey(cp.CategoryId))
                        {
                            cp.Selected = false;
                            updatedLIP.Categories.Remove(cp.CategoryId);
                            updatedLIP.Categories.Add(cp.CategoryId, cp);
                        }

                        tGroup.Assimilate();
                    }
                    catch (Exception ex)
                    {
                        tGroup.RollBack();
                        MessageBox.Show("Failed to duplicate elements in the category " + cp.CategoryName + "\n" + ex.Message, "Duplicate Elements", MessageBoxButton.OK, MessageBoxImage.Warning);
                    }
                }

                messageBuilder.AppendLine(duplicated.ToString() + " of " + elementsToCopy.Count.ToString() + " elements in " + cp.CategoryName + " has been successfully copied or updated.");
            }
            catch (Exception ex)
            {
                MessageBox.Show("Failed to duplicate elements.\n" + ex.Message, "Duplicate Elements", MessageBoxButton.OK, MessageBoxImage.Warning);
            }
            return(updatedLIP);
        }
Example #29
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            Debug.Listeners.Clear();
            Debug.Listeners.Add(new RbsLogger.Logger("CopyTemplates"));

            Application app     = commandData.Application.Application;
            Document    mainDoc = commandData.Application.ActiveUIDocument.Document;

            DocumentSet       docSet  = app.Documents;
            List <MyDocument> allDocs = new List <MyDocument>();

            foreach (Document doc in app.Documents)
            {
                if (doc.Title == mainDoc.Title)
                {
                    continue;
                }
                if (doc.IsValidObject)
                {
                    MyDocument myDoc = new MyDocument(doc);
                    allDocs.Add(myDoc);
                }
            }
            Debug.Write("Docs count: " + allDocs.Count);
            if (allDocs.Count == 0)
            {
                message = "Нет открытых документов для копирования!";
                return(Result.Failed);
            }

            FormSelectDocument form1 = new FormSelectDocument(allDocs);

            form1.ShowDialog();
            if (form1.DialogResult != System.Windows.Forms.DialogResult.OK)
            {
                Debug.WriteLine("Cancelled by user");
                return(Result.Cancelled);
            }

            Document selectedDoc = form1.selectedDocument.doc;

            Debug.WriteLine("Selected doc: " + selectedDoc.Title);

            List <View> templates = new FilteredElementCollector(selectedDoc)
                                    .OfClass(typeof(View))
                                    .Cast <View>()
                                    .Where(v => v.IsTemplate == true)
                                    .ToList();

            Debug.WriteLine("Templates found: " + templates.Count);
            List <MyView> myViews = templates
                                    .OrderBy(i => i.Name)
                                    .Select(i => new MyView(i))
                                    .ToList();

            FormSelectTemplates form2 = new FormSelectTemplates(myViews);

            form2.ShowDialog();
            if (form2.DialogResult != System.Windows.Forms.DialogResult.OK)
            {
                Debug.WriteLine("Cancelled by user");
                return(Result.Cancelled);
            }

            List <ElementId> templateIds = form2.selectedTemplates.Select(i => i.view.Id).ToList();

            Debug.WriteLine("Selected templates: " + templateIds.Count);
            CopyPasteOptions cpo = new CopyPasteOptions();

            cpo.SetDuplicateTypeNamesHandler(new DuplicateNamesHandler());

            using (Transaction t = new Transaction(mainDoc))
            {
                t.Start("Копирование шаблонов видов");

                ElementTransformUtils.CopyElements(selectedDoc, templateIds, mainDoc, Transform.Identity, cpo);

                t.Commit();
            }

            string msg = "Успешно скопировано шаблонов: " + templateIds.Count.ToString();

            if (DuplicateTypes.types.Count > 0)
            {
                msg += "\nПродублированы: " + DuplicateTypes.ReturnAsString();
            }

            Debug.WriteLine(msg);
            TaskDialog.Show("Отчет", msg);

            return(Result.Succeeded);
        }
Example #30
0
        private void ButtonCopy_Click(object sender, EventArgs 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());
                //Create List of Schedule Element Ids to Copy
                List <ElementId> ScheduleIds = new List <ElementId>();

                foreach (ListViewItem item in ListViewSchedules.CheckedItems)
                {
                    //Cast the Schedule from the List View Item Tag property set previously
                    ElementId scheduleId = (ElementId)item.Tag;
                    //Use a helper method to see if a Schedule with the same name already exists
                    if (Helpers.Collectors.CheckSchedule(Doc, item.Text))
                    {
                        //Add the Schedule Element Id to the List of items to copy
                        ScheduleIds.Add(scheduleId);
                        //Add 1 to the counte integer we will use to tell the user how many legends were copied
                        count++;
                    }
                    else
                    {
                        //If a Schedule with the same name does exist, ask the user what they want to do
                        if (TaskDialog.Show("Schedule Exists", "Schedule " + item.Text + " already exits in the current Document.\n\nWould you like to copy the Schedule?", TaskDialogCommonButtons.Yes | TaskDialogCommonButtons.No, TaskDialogResult.No) == TaskDialogResult.Yes)
                        {
                            //If the User wants to copy it anyway, add the Id to the list
                            ScheduleIds.Add(scheduleId);
                            //Add 1 to the counte integer we will use to tell the user how many legends were copied
                            count++;
                        }
                    }
                }

                //Check to make sure there is a least one Schedule to be copied
                if (count > 0)
                {
                    //Use a Transaction for the Document you are pasting INTO to copy the Schedules into
                    using (Transaction trans = new Transaction(Doc))
                    {
                        //Start the transaction and give it a name for the Undo / Redo list
                        trans.Start("Copy Schedules");
                        //Use the Transform Utilties Class with the CopyElemens method to copy the Schedules from the Linked Document
                        //to the Current Document. This can be done one time with ALL Schedule Ids and doesn't need to be part of a loop
                        ElementTransformUtils.CopyElements(linkDoc, ScheduleIds, Doc, Transform.Identity, options);
                        //Commit the transaction to save the changed to the document
                        trans.Commit();
                    }
                    //Tell the user how many Schedules were copied
                    TaskDialog.Show("Copy Schedules", "Copied " + count + " Schedules");
                    //Set the Dialog Result so that the calling Method resturns the correct result and the changes stick
                    DialogResult = DialogResult.OK;
                    //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 Schedules Error", ex.ToString());
                DialogResult = DialogResult.Cancel;
                Close();
            }
        }