Exemple #1
0
        /// <summary>
        /// Recursively retrieve entire linked document
        /// hierarchy and return the resulting TreeNode
        /// structure.
        /// </summary>
        void GetChildren(
            Document mainDoc,
            ICollection <ElementId> ids,
            TreeNode parentNode)
        {
            int level = parentNode.Level;

            foreach (ElementId id in ids)
            {
                // Get the child information.

                RevitLinkType type = mainDoc.GetElement(id)
                                     as RevitLinkType;

                string label = LinkLabel(type, level);

                TreeNode subNode = new TreeNode(label);

                Debug.Print("{0}{1}", Indent(2 * level),
                            label);

                parentNode.Nodes.Add(subNode);

                // Go to the next level.

                GetChildren(mainDoc, type.GetChildIds(),
                            subNode);
            }
        }
Exemple #2
0
        public void Load_Form(UIApplication uiapp, Document doc)
        {
            try
            {
                data_revit_link item = (data_revit_link)link_file.SelectedItem;
                doc.Delete(item.type.Id);

                ModelPath        mp  = ModelPathUtils.ConvertUserVisiblePathToModelPath(path);
                RevitLinkOptions rlo = new RevitLinkOptions(false);
                var linkType         = RevitLinkType.Create(doc, mp, rlo);
                var instance         = RevitLinkInstance.Create(doc, linkType.ElementId);

                List <Document> docs = new List <Document>();
                foreach (Document d in uiapp.Application.Documents)
                {
                    docs.Add(d);
                }
                item.document = docs.First(y => y.Title + ".rvt" == item.name);
                item.type     = doc.GetElement(linkType.ElementId) as RevitLinkType;
                link_file.Items.Refresh();
                MessageBox.Show(item.document.PathName);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                link_file.SelectedItem = null;
            }
        }
Exemple #3
0
        public RenderNodeAction OnLinkBegin(LinkNode node)
        {
            ElementId     symbolId      = node.GetSymbolId();
            RevitLinkType revitLinkType = this.m_document.GetElement(symbolId) as RevitLinkType;
            string        name          = revitLinkType.Name;

            foreach (object obj in this.m_document.Application.Documents)
            {
                Document document = (Document)obj;
                bool     flag     = document.Title.Equals(name);
                if (flag)
                {
                    this.ZeLinkDoc = document;
                }
            }
            bool flag2 = name != null;

            if (flag2)
            {
                this.isLink = true;
            }
            bool flag3 = symbolId != null;

            if (flag3)
            {
                bool flag4 = !this.ListLINKID01.Contains(symbolId.IntegerValue.ToString());
                if (flag4)
                {
                    this.ListLINKID01.Add(symbolId.IntegerValue.ToString());
                }
            }
            this.m_TransformationStack.Push(this.m_TransformationStack.Peek().Multiply(node.GetTransform()));
            return(0);
        }
Exemple #4
0
        /// <summary>
        /// Creates an instance for the Revit file selected
        /// </summary>
        /// <param name="doc">Document to which the link should be added</param>
        /// <param name="revitFilePath">the full path of the Revit link to be added</param>
        private static void InstanceMaker(Document doc, string revitFilePath)
        {
            try
            {
                using (Transaction tr = new Transaction(doc))
                {
                    tr.Start("Revit files are being linked...");

                    // Cycle through the list
                    // Set the standard options and behavior for the links
                    FilePath         fp  = new FilePath(revitFilePath);
                    RevitLinkOptions rlo = new RevitLinkOptions(false);

                    // Create new revit link and store the path to the file as either absolute or relative
                    RevitLinkLoadResult result = RevitLinkType.Create(doc, fp, rlo);
                    ElementId           linkId = result.ElementId;

                    // Create the Revit Link Instance (this also automatically sets the link Origin-to-Origin)
                    // Pin the Revit link as well
                    RevitLinkInstance linkInstance = RevitLinkInstance.Create(doc, linkId);
                    linkInstance.Pinned = true;

                    tr.Commit();
                }
            }

            catch (Exception)
            {
                // not sure what exceptions may occur
                // make sure that whatever happens is logged for future troubleshooting
            }
        }
Exemple #5
0
        /// <summary>
        /// Scans and returns the documents linked to the current model.
        /// </summary>
        /// <returns>List of linked documents.</returns>
        private List <Document> GetLinkedModels()
        {
            List <Document> linkedDocs = new List <Document>();

            try
            {
                // scan the current model looking for Revit links
                List <Element> linkedElements = FindLinkedModelElements();

                foreach (Element linkedElem in linkedElements)
                {
                    RevitLinkType linkType = linkedElem as RevitLinkType;

                    if (linkType != null)
                    {
                        // now look that up in the open documents
                        foreach (Document openedDoc in m_RevitApp.Documents)
                        {
                            if (Path.GetFileNameWithoutExtension(openedDoc.Title).ToUpper() == Path.GetFileNameWithoutExtension(linkType.Name).ToUpper())
                            {
                                linkedDocs.Add(openedDoc);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                STLDialogManager.ShowDebug(ex.Message);
            }

            return(linkedDocs);
        }
Exemple #6
0
        /// <summary>
        ///     Creates a revit link.
        /// </summary>
        /// <param name="doc"></param>
        /// <param name="linkPath"></param>
        /// <returns></returns>
        public static void AddRevitLink(this Document doc, string linkPath)
        {
            if (doc == null)
            {
                throw new ArgumentNullException(nameof(doc));
            }

            if (linkPath == null)
            {
                throw new ArgumentNullException(nameof(linkPath));
            }

            var filePathl  = new FilePath(linkPath);
            var linkOption = new RevitLinkOptions(false);

            doc.AutoTransaction(() =>
            {
                var result   = RevitLinkType.Create(doc, filePathl, linkOption);
                var instance = RevitLinkInstance.Create(doc, result.ElementId);

                if (!(doc.GetElement(instance.GetTypeId()) is RevitLinkType type))
                {
                    return;
                }

                type.AttachmentType = AttachmentType.Attachment;
                type.PathType       = PathType.Relative;
            });
        }
        public ElementId CreateRevitLink(Document doc, string pathName)
        {
            FilePath         path    = new FilePath(pathName);
            RevitLinkOptions options = new RevitLinkOptions(false);
            // Create new revit link storing absolute path to file
            LinkLoadResult result = RevitLinkType.Create(doc, path, options);

            return(result.ElementId);
        }
Exemple #8
0
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            //Create a DataTable to hold the Revit Link information
            DataTable dtLinkedDocuments = new DataTable();

            dtLinkedDocuments.Columns.Add(new DataColumn("Name", typeof(string)));
            dtLinkedDocuments.Columns.Add(new DataColumn("Document", typeof(Document)));
            //Add a row inthe DataTable for when no Link is Selected and give it a null value

            //Get all of the Link Instances in the Current Document
            using (FilteredElementCollector LinkInstancesCollector = new FilteredElementCollector(doc).OfClass(typeof(RevitLinkInstance)))
            {
                //Check to make sure there is at least one Link Instance
                if (LinkInstancesCollector.ToElements().Count > 0)
                {
                    //Get each Revit Link Instance since here may be more than one
                    foreach (RevitLinkInstance LinkedInstance in LinkInstancesCollector.ToElements())
                    {
                        //Get the Revit Link Type from the instance to check and see if it is loaded, which it should be if there is an instance
                        RevitLinkType linkType = doc.GetElement(LinkedInstance.GetTypeId()) as RevitLinkType;

                        //We only want to check Links that are currently Loaded
                        if (linkType.GetLinkedFileStatus() == LinkedFileStatus.Loaded && !linkType.IsNestedLink)
                        {
                            //Iterate through the Link Instances in the Document and match the first one with the Link Type. This is because you need the Link Instance to get the Link Document, not the Link Type
                            //RevitLinkInstance LinkedDocumentInstance = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_RvtLinks).OfClass(typeof(RevitLinkInstance)).Where(x => x.GetTypeId() == LinkedInstance.Id).First() as RevitLinkInstance;
                            //Add the Link Name and Link Instance to the Dictionary if it doesn't already exist
                            if (!linkInstances.ContainsKey(linkType.Name + " - " + LinkedInstance.Name))
                            {
                                linkInstances.Add(linkType.Name + " - " + LinkedInstance.Name, LinkedInstance);
                            }
                            else
                            {
                                //Tell the User that the Link Type Name and Instance Name combination already exist
                                TaskDialog.Show("Duplicate Link Instance Name", "More than one Link Instance has the same name. Only one instance has been added.");
                                //Continue through the for loop
                                continue;
                            }
                        }
                    }
                }
                //Tell the user when there aren't any linked document and close the form
                else
                {
                    TaskDialog.Show("No Revit Link", "Document does not contain any Revit Links.");
                    DialogResult = false;
                    Close();
                }
            }

            //Use the Dictionary as the items source of the Combobox and set the Display and value Path
            ComboBoxLinks.ItemsSource       = linkInstances.ToList();
            ComboBoxLinks.SelectedValuePath = "Value";
            ComboBoxLinks.DisplayMemberPath = "Key";
        }
 internal RemoteLink(Document doc, RevitLinkInstance linkinstance)
 {
     Document     = linkinstance.GetLinkDocument();
     Type         = doc.GetElement(linkinstance.GetTypeId()) as RevitLinkType;
     Title        = Document.Title;
     DocumentPath = Document.PathName;
     IsWorkShared = Document.IsWorkshared;
     IsLoaded     = RevitLinkType.IsLoaded(doc, Type.Id);
     TempPath     = Path.GetTempPath() + "RemoteParameters\\";
     OpenDocument = null;
 }
Exemple #10
0
        /// <summary>
        /// Links in a Revit File or files
        /// using a Dialog box within the active document;
        /// pins the instance of the Revit Link Origin-to-Origin automatically.
        /// Returns the name of the main file which should be used for Copy-Monitoriing etc
        /// </summary>
        /// <param name="doc">Active Document</param>
        public static ElementId CreateLinkRevit(this Document doc)
        {
            // Ask the user which links they would like to add to the project
            // Call the ShowDialog method to show the dialog box filtered to show only Revit Projects
            // Choose the main link to base the document on for Copy-Monitoring
            TaskDialog td_mainrvtlnk = TaskDialogUtil.Create("Main Revit Link",
                                                             "Select the link which should be used to set up Grids and Levels for Copy Monitoring",
                                                             TaskDialogIcon.TaskDialogIconNone);
            OpenFileDialog ofd = new OpenFileDialog();

            ofd.Multiselect = false;
            ofd.Filter      = "Revit Documents|*.rvt";

            TaskDialog td_addtlrvtlnk = TaskDialogUtil.Create("Additional Revit Links",
                                                              "Select any additional links which should be added to the project",
                                                              TaskDialogIcon.TaskDialogIconNone);
            OpenFileDialog ofd2 = new OpenFileDialog();

            ofd2.Multiselect = true;
            ofd2.Filter      = "Revit Documents|*.rvt";
            td_mainrvtlnk.Show();

            DialogResult dr = ofd.ShowDialog();

            //If the user clicks ok - record the name of main RVT Link
            if (dr == System.Windows.Forms.DialogResult.OK || dr == DialogResult.Cancel)
            {
                //Add the link selected to a list for later
                string lnk_cm = ofd.FileName;

                td_addtlrvtlnk.Show();
                DialogResult dr2 = ofd2.ShowDialog();
                //If the user clicks ok - continue
                if (dr2 == System.Windows.Forms.DialogResult.OK || dr2 == DialogResult.Cancel)
                {
                    //Link in the revit files
                    //Add the links selected to a list
                    List <string> rvtfiles = new List <string>();
                    rvtfiles.Add(ofd.FileName);
                    foreach (string x in ofd2.FileNames)
                    {
                        rvtfiles.Add(x);
                    }
                    InstanceMaker(doc, rvtfiles);
                }
            }

            // Gets the elementID of the link you want for copy-monitoring
            ElementId cm_linkid = RevitLinkType.GetTopLevelLink(doc,
                                                                ModelPathUtils.ConvertUserVisiblePathToModelPath(ofd.FileName));

            return(cm_linkid);
        }
Exemple #11
0
 public void Link_File(Document doc)
 {
     try
     {
         ModelPath        mp  = ModelPathUtils.ConvertUserVisiblePathToModelPath(path);
         RevitLinkOptions rlo = new RevitLinkOptions(false);
         var linkType         = RevitLinkType.Create(doc, mp, rlo);
         var instance         = RevitLinkInstance.Create(doc, linkType.ElementId);
     }
     catch (Exception ex)
     {
         MessageBox.Show(ex.Message);
     }
 }
Exemple #12
0
    /// <summary>
    /// Return a label to display for a link type.
    /// Nested links are always attachments.
    /// </summary>
    static string LinkLabel( 
      RevitLinkType type, 
      int level )
    {
      AttachmentType a = type.AttachmentType;
      AttachmentType b = 0 < level
        ? AttachmentType.Attachment
        : a;

      Debug.Print(
        "AttachmentType {0} at level {1} -> {2}", 
        a, level, b );

      return type.Name + "->" + b.ToString();
    }
Exemple #13
0
        /// <summary>
        /// Return a label to display for a link type.
        /// Nested links are always attachments.
        /// </summary>
        static string LinkLabel(
            RevitLinkType type,
            int level)
        {
            AttachmentType a = type.AttachmentType;
            AttachmentType b = 0 < level
        ? AttachmentType.Attachment
        : a;

            Debug.Print(
                "AttachmentType {0} at level {1} -> {2}",
                a, level, b);

            return(type.Name + "->" + b.ToString());
        }
Exemple #14
0
        public ItemInfo(object obj, ViewBy type)
        {
            itemObj  = obj;
            itemType = type;
            switch (type)
            {
            case ViewBy.Workset:
                Workset workset = obj as Workset;
                if (null != workset)
                {
                    itemName = workset.Name;
                    itemId   = workset.Id.IntegerValue;
                }
                break;

            case ViewBy.Phase:
                Phase phase = obj as Phase;
                if (null != phase)
                {
                    itemName = phase.Name;
                    itemId   = phase.Id.IntegerValue;
                }
                break;

            case ViewBy.DesignOption:
                DesignOption designOption = obj as DesignOption;
                if (null != designOption)
                {
                    itemName = designOption.Name;
                    itemId   = designOption.Id.IntegerValue;
                }
                break;

            case ViewBy.Link:
                RevitLinkType linktype = obj as RevitLinkType;
                if (null != linktype)
                {
                    itemName = linktype.Name;
                    itemId   = linktype.Id.IntegerValue;
                }
                break;
            }
        }
Exemple #15
0
 private void ComboBoxRevitLinks_SelectionChanged(object sender, SelectionChangedEventArgs e)
 {
     //Check to make sure the Selected value is not null, which is the Value for the row we added
     if (ComboBoxLinks.SelectedValue != null)
     {
         //Get the Link Document by casting the Selected Value of the Combo Box to a Document
         RevitLinkInstance rvtLinkInstance = (RevitLinkInstance)ComboBoxLinks.SelectedValue;
         //Get the Revit Link Type to check Type Parameter
         RevitLinkType rvtLinkType = doc.GetElement(rvtLinkInstance.GetTypeId()) as RevitLinkType;
         //Check to see if the Link Type is Room Bounding
         if (rvtLinkType.LookupParameter("Room Bounding").AsInteger() == 0)
         {
             //If it is not room bounding, ask the user if they want to proceed or not
             if (TaskDialog.Show("Linked Model Room Bounding", "The Revit Link " + rvtLinkType.Name + " is not Room Bounding.\n\nWould you like to make it Room Bounding and proceed with creating Spaces?", TaskDialogCommonButtons.Yes | TaskDialogCommonButtons.No, TaskDialogResult.No) == TaskDialogResult.Yes)
             {
                 //Use a transaction and set the Link Type parameter to be room bounding
                 using (Transaction trans = new Transaction(doc))
                 {
                     trans.Start("Change Link Room Bounding");
                     rvtLinkType.LookupParameter("Room Bounding").Set(1);
                     trans.Commit();
                 }
                 //If you user says yes, get all rooms in the linked model via GetLinkedRoom method by passing the Linked Document
                 GetLinkedRooms(rvtLinkInstance.GetLinkDocument());
             }
             else
             {
                 //If the user says no, close the form
                 DialogResult = false;
                 Close();
             }
         }
         else
         {
             //If the link is already room bounding, get all rooms in the linked model via GetLinkedRoom method by passing the Linked Document
             GetLinkedRooms(rvtLinkInstance.GetLinkDocument());
         }
     }
 }
Exemple #16
0
        /// <summary>
        /// Получает листы из всех открытых документов
        /// </summary>
        /// <param name="commandData"></param>
        /// <returns></returns>
        public static Dictionary <string, List <MySheet> > GetAllSheets(ExternalCommandData commandData, YayPrintSettings printSets)
        {
            Dictionary <string, List <MySheet> > data = new Dictionary <string, List <MySheet> >();
            Document mainDoc      = commandData.Application.ActiveUIDocument.Document;
            string   mainDocTitle = GetDocTitleWithoutRvt(mainDoc.Title);

            List <RevitLinkInstance> links = new FilteredElementCollector(mainDoc)
                                             .OfClass(typeof(RevitLinkInstance))
                                             .Cast <RevitLinkInstance>()
                                             .ToList();

            List <MySheet> mainSheets = GetSheetsFromDocument(mainDoc, printSets);

            data.Add(mainDocTitle, mainSheets);

            foreach (RevitLinkInstance rli in links)
            {
                Document linkDoc = rli.GetLinkDocument();
                if (linkDoc == null)
                {
                    continue;
                }
                string linkDocTitle = GetDocTitleWithoutRvt(linkDoc.Title);
                if (data.ContainsKey(linkDocTitle))
                {
                    continue;
                }

                RevitLinkType  rlt       = mainDoc.GetElement(rli.GetTypeId()) as RevitLinkType;
                List <MySheet> curSheets = GetSheetsFromDocument(linkDoc, printSets);

                data.Add(linkDocTitle, curSheets);
            }

            return(data);
        }
Exemple #17
0
        public List <Element> getLinkedDocFurniture(Document doc)
        {
            List <Element>  linkedFurniture = new List <Element>();
            IList <Element> linkedElemList  = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_RvtLinks).OfClass(typeof(RevitLinkType)).ToElements();

            foreach (Element e in linkedElemList)
            {
                RevitLinkType linkType = e as RevitLinkType;
                foreach (Document linkedDoc in doc.Application.Documents)
                {
                    if ((linkedDoc.Title + ".rvt").Equals(linkType.Name))
                    {
                        ElementCategoryFilter furnitureFilter = new ElementCategoryFilter(BuiltInCategory.OST_Furniture);
                        foreach (Element linkedEl in new FilteredElementCollector(linkedDoc)
                                 .OfClass(typeof(FamilyInstance))
                                 .WherePasses(furnitureFilter))
                        {
                            linkedFurniture.Add(linkedEl);
                        }
                    }
                }
            }
            return(linkedFurniture);
        }
        //method to return the inverse of transform from one linked file to another
        public static Transform GetInverseTransform(Document doc, Autodesk.Revit.ApplicationServices.Application app)
        {
            try
            {
                FilteredElementCollector collector = new FilteredElementCollector(doc);
                collector.OfClass(typeof(RevitLinkInstance));

                Transform transform = null;

                IEnumerator enumerate = collector.GetEnumerator();

                enumerate.Reset();

                while (enumerate.MoveNext())
                {
                    RevitLinkInstance instance = enumerate.Current as RevitLinkInstance;

                    RevitLinkType linkType = (RevitLinkType)doc.GetElement(instance.GetTypeId());

                    foreach (Document docu in app.Documents)
                    {
                        if (docu.PathName.Contains(linkType.Name))
                        {
                            transform = instance.GetTotalTransform().Inverse;
                            return(transform);
                        }
                    }
                }

                return(null);
            }
            catch
            {
                return(null);
            }
        }
Exemple #19
0
        //
        //This class is associated with the Upgrade Projects tool
        public SetupUPRequest(UIApplication uiApp, String text)
        {
            MainUI       uiForm = BARevitTools.Application.thisApp.newMainUi;
            DataGridView dgv    = uiForm.setupUPDataGridView;

            dgv.EndEdit();

            RVTDocument doc = uiApp.ActiveUIDocument.Document;
            string      hostFilePathToUpgrade  = uiForm.setupUPOriginalFilePathTextBox.Text;
            string      hostFilePathForUpgrade = uiForm.setupUPUpgradedFilePathSetTextBox.Text + "\\" + uiForm.setupUPUpgradedFilePathUserTextBox.Text + ".rvt";

            //Reset the progress bar
            uiForm.setupUPProgressBar.Value   = 0;
            uiForm.setupUPProgressBar.Minimum = 0;
            uiForm.setupUPProgressBar.Step    = 1;

            //Determine the number of steps for the progress bar based on the number of links checked for upgrading plus 1 for the host
            int progressBarSteps = 1;

            foreach (DataGridViewRow row in dgv.Rows)
            {
                if (row.Cells["Upgrade"].Value != null)
                {
                    if (row.Cells["Upgrade"].Value.ToString() == "True")
                    {
                        progressBarSteps++;
                    }
                }
            }
            uiForm.setupUPProgressBar.Maximum = progressBarSteps;

            //Let the user know if they are trying to save over a file that already exists
            if (File.Exists(hostFilePathForUpgrade))
            {
                MessageBox.Show("A file already exists with the name and location specified for the upgrade of the host Revit project file");
            }
            //If they didn't set a save location for the file, let them know
            else if (uiForm.setupUPUpgradedFilePathUserTextBox.Text == "")
            {
                MessageBox.Show("No location for the upgrade of the host Revit project file is set");
            }
            else
            {
                //Otherwise, show the progress bar and step through the rows of the DataGridView links
                uiForm.setupUPProgressBar.Visible = true;
                for (int i = 0; i < dgv.Rows.Count; i++)
                {
                    try
                    {
                        if (dgv.Rows[i].Cells["Upgrade"].Value != null)
                        {
                            //If the link is allowed to be upgraded, and its checkbox is checked, continue
                            if (dgv.Rows[i].Cells["Allow Upgrade"].Value.ToString() == "True" && dgv.Rows[i].Cells["Upgrade"].Value.ToString() == "True")
                            {
                                //Grab the orignial path for the link and the path for where it will be saved
                                string linkFilePathToUpgrade  = dgv.Rows[i].Cells["Original Path"].Value.ToString();
                                string linkFilePathForUpgrade = dgv.Rows[i].Cells["New Path"].Value.ToString();
                                //Perform the upgrade operations on the file and report if it was successful
                                bool linkResult = RVTOperations.UpgradeRevitFile(uiApp, linkFilePathToUpgrade, linkFilePathForUpgrade, false);

                                if (linkResult == true)
                                {
                                    //If the upgrade was successful, set the Upgrade Result column to true and set the row's background color to GreenYellow
                                    dgv.Rows[i].Cells["Upgrade Result"].Value = true;
                                    dgv.Rows[i].DefaultCellStyle.BackColor    = System.Drawing.Color.GreenYellow;
                                }
                                else
                                {
                                    //If the upgrade failed, set the Upgrade Result column to false and set the background color to red
                                    dgv.Rows[i].Cells["Upgrade Result"].Value = false;
                                    dgv.Rows[i].DefaultCellStyle.BackColor    = System.Drawing.Color.Red;
                                }
                                //Step forward the progress bar
                                uiForm.setupUPProgressBar.PerformStep();
                                uiForm.Update();
                            }
                        }
                        else
                        {
                            continue;
                        }
                    }
                    catch (Exception e)
                    {
                        MessageBox.Show(e.Message);
                    }
                }

                //Once the links are done upgrading, upgrade the host
                bool hostResult = RVTOperations.UpgradeRevitFile(uiApp, hostFilePathToUpgrade, hostFilePathForUpgrade, false);
                //Determine how many links were able to be upgraded
                int countOfUpgradeLinks = 0;
                foreach (DataGridViewRow row in dgv.Rows)
                {
                    try
                    {
                        if (row.Cells["Upgrade"].Value != null)
                        {
                            if (row.Cells["Upgrade"].Value.ToString() == "True")
                            {
                                countOfUpgradeLinks++;
                            }
                        }
                    }
                    catch
                    {
                        continue;
                    }
                    finally
                    {
                        uiForm.setupUPProgressBar.PerformStep();
                        uiForm.Update();
                    }
                }

                //If the host was able to be upgraded, continue
                if (hostResult == true)
                {
                    //Set the background color of the text box to GreenYellow
                    uiForm.setupUPOriginalFilePathTextBox.BackColor = System.Drawing.Color.GreenYellow;
                    if (countOfUpgradeLinks > 0)
                    {
                        try
                        {
                            //Open the upgraded host and get the links
                            RVTDocument hostDoc = RVTOperations.OpenRevitFile(uiApp, hostFilePathForUpgrade);
                            Dictionary <string, RevitLinkType> linkNames = new Dictionary <string, RevitLinkType>();
                            var linkTypes = new FilteredElementCollector(hostDoc).OfClass(typeof(RevitLinkType)).ToElements();
                            foreach (RevitLinkType linkType in linkTypes)
                            {
                                //Add each link to a dictionary with their file name and indexed link type
                                linkNames.Add(linkType.Name.Replace(".rvt", ""), linkType);
                            }

                            //Cycle through the links
                            foreach (DataGridViewRow row in dgv.Rows)
                            {
                                try
                                {
                                    //If the link's row was checked for upgrading, it was able to be upgraded, the upgraded file exists at the New Path location, and the dictionary of links contains the original name of the link, continue
                                    if (row.Cells["Upgrade"].Value.ToString() == "True" &&
                                        row.Cells["Upgrade Result"].Value.ToString() == "True" &&
                                        File.Exists(row.Cells["New Path"].Value.ToString()) &&
                                        linkNames.Keys.Contains(row.Cells["Original Name"].Value.ToString()))
                                    {
                                        try
                                        {
                                            //Get the link to reload via the name from the dictionary
                                            RevitLinkType linkToReload = linkNames[row.Cells["Original Name"].Value.ToString().Replace(".rvt", "")];
                                            //Convert the link's user path to a model path, then reload it
                                            ModelPath modelPathToLoadFrom = ModelPathUtils.ConvertUserVisiblePathToModelPath(row.Cells["New Path"].Value.ToString());
                                            linkToReload.LoadFrom(modelPathToLoadFrom, new WorksetConfiguration());
                                        }
                                        catch (Exception e)
                                        {
                                            //If the link was upgraded but could not be reloaded, set the background color to orange and let the user know it could not be reloaded
                                            row.DefaultCellStyle.BackColor = System.Drawing.Color.Orange;
                                            MessageBox.Show(String.Format("Could not remap the link named {0} in the host file", row.Cells["Original Name"].Value.ToString()));
                                            MessageBox.Show(e.ToString());
                                        }
                                    }
                                }
                                catch { continue; }
                            }
                            //Save the upgraded host file
                            RVTOperations.SaveRevitFile(uiApp, hostDoc, true);
                        }
                        catch (Exception e) { MessageBox.Show(e.ToString()); }
                    }
                }
                else
                {
                    //If the host file failed to upgrade, set its text box background color to red
                    uiForm.setupUPOriginalFilePathTextBox.BackColor = System.Drawing.Color.Red;
                }
                uiForm.Update();
                uiForm.Refresh();
            }
        }
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            Document    mainDoc  = commandData.Application.ActiveUIDocument.Document;
            Application revitApp = commandData.Application.Application;

            //открываю окно выбора параметров, которые буду заполняться
            FormSelectParams formSelectParams = new FormSelectParams();

            formSelectParams.ShowDialog();
            if (formSelectParams.DialogResult != System.Windows.Forms.DialogResult.OK)
            {
                return(Result.Cancelled);
            }


            RebarDocumentWorker mainWorker = new RebarDocumentWorker();
            List <Element>      mainDocConcreteElements = new List <Element>();



            string mainWorkerMessage = mainWorker.Start(mainDoc, revitApp, Transform.Identity, out mainDocConcreteElements);

            if (!string.IsNullOrEmpty(mainWorkerMessage))
            {
                message = mainWorkerMessage + ". Документ " + mainDoc.Title;
                return(Result.Failed);
            }

            if (Settings.LinkFilesSetting == Settings.ProcessedLinkFiles.NoLinks)
            {
                return(Result.Succeeded);
            }

            List <RevitLinkInstance> linksAll = new FilteredElementCollector(mainDoc)
                                                .OfClass(typeof(RevitLinkInstance))
                                                .Cast <RevitLinkInstance>()
                                                .ToList();

            List <RevitLinkInstance> linksLib = linksAll
                                                .Where(i => i.Name.Contains(".lib"))
                                                .ToList();

            // имя ссылки lib и список конструкций, которые она пересекает
            Dictionary <string, List <Element> > hostElemsForLibLinks = new Dictionary <string, List <Element> >();

            foreach (RevitLinkInstance rli in linksLib)
            {
                string  linkInstanceTitle = LinksSupport.GetDocumentTitleFromLinkInstance(rli);
                Element hostElem          = LinksSupport.GetConcreteElementIsHostForLibLinkFile(mainDoc, ViewSupport.GetDefaultView(mainDoc), mainDocConcreteElements, rli);
                if (hostElem == null)
                {
                    continue;
                }
                if (hostElemsForLibLinks.ContainsKey(linkInstanceTitle))
                {
                    hostElemsForLibLinks[linkInstanceTitle].Add(hostElem);
                }
                else
                {
                    hostElemsForLibLinks.Add(linkInstanceTitle, new List <Element> {
                        hostElem
                    });
                }
            }
            List <RevitLinkInstance> linksWithoutDuplicates = LinksSupport.DeleteDuplicates(linksAll);

            foreach (RevitLinkInstance rli in linksWithoutDuplicates)
            {
                RevitLinkType rlt     = mainDoc.GetElement(rli.GetTypeId()) as RevitLinkType;
                Document      linkDoc = rli.GetLinkDocument();
                if (linkDoc == null)
                {
                    continue;
                }

                string linkDocTitle = LinksSupport.GetDocumentTitleFromLinkInstance(rli);
                if (!linkDocTitle.Contains("-КР-"))
                {
                    continue;
                }
                if (!linkDocTitle.Contains("lib") && Settings.LinkFilesSetting == Settings.ProcessedLinkFiles.OnlyLibs)
                {
                    continue;
                }



                ModelPath mPath = linkDoc.GetWorksharingCentralModelPath();

                rlt.Unload(new SaveCoordinates());

                OpenOptions oo = new OpenOptions();

                linkDoc = revitApp.OpenDocumentFile(mPath, oo);


                RebarDocumentWorker linkWorker = new RebarDocumentWorker();
                if (linkDocTitle.Contains("lib"))
                {
                    if (hostElemsForLibLinks.ContainsKey(linkDocTitle))
                    {
                        List <Element> mainElemsForLib = hostElemsForLibLinks[linkDocTitle];
                        if (mainElemsForLib.Count > 0)
                        {
                            linkWorker.MainElementsForLibFile = mainElemsForLib;
                        }
                    }
                }
                Transform      linkTransform        = rli.GetTransform();
                List <Element> linkConcreteElements = new List <Element>();
                string         linkWorkerMessage    = linkWorker.Start(linkDoc, revitApp, linkTransform, out linkConcreteElements);
                if (!string.IsNullOrEmpty(linkWorkerMessage))
                {
                    message = linkWorkerMessage + ". Связь " + linkDoc.Title;
                    return(Result.Failed);
                }



                TransactWithCentralOptions    transOpt = new TransactWithCentralOptions();
                SynchronizeWithCentralOptions syncOpt  = new SynchronizeWithCentralOptions();

                RelinquishOptions relOpt = new RelinquishOptions(true);
                syncOpt.SetRelinquishOptions(relOpt);

                linkDoc.SynchronizeWithCentral(transOpt, syncOpt);

                linkDoc.Close();
#if R2017
                RevitLinkLoadResult rllr = rlt.Reload();
#else
                LinkLoadResult llr = rlt.Reload();
#endif
            }

            return(Result.Succeeded);
        }
 public SaveModifiedLinksOptions GetSaveModifiedLinksOption(RevitLinkType link)
 {
     return(SaveModifiedLinksOptions.DoNotSaveLinks);
 }
        public bool GetRoomLimitP(RevitLinkType type)
        {
            bool room_limit = true;

            return(room_limit);
        }
        /// <summary>
        /// Link in the new created document to parent document.
        /// </summary>
        /// <param name="originalIFCFileName">The full path to the original IFC file.  Same as baseLocalFileName if the IFC file is not on a server.</param>
        /// <param name="baseLocalFileName">The full path to the IFC file on disk.</param>
        /// <param name="ifcDocument">The newly imported IFC file document.</param>
        /// <param name="originalDocument">The document to contain the IFC link.</param>
        /// <param name="useExistingType">True if the RevitLinkType already exists.</param>
        /// <param name="doSave">True if we should save the document.  This should only be false if we are reusing a cached document.</param>
        /// <returns>The element id of the RevitLinkType for this link operation.</returns>
        public static ElementId LinkInFile(string originalIFCFileName, string baseLocalFileName, Document ifcDocument, Document originalDocument, bool useExistingType, bool doSave)
        {
            bool   saveSucceded = true;
            string fileName     = GenerateRevitFileName(baseLocalFileName);

            if (doSave)
            {
                SaveAsOptions saveAsOptions = new SaveAsOptions();
                saveAsOptions.OverwriteExistingFile = true;

                try
                {
                    ifcDocument.SaveAs(fileName, saveAsOptions);
                }
                catch
                {
                    saveSucceded = false;
                }

                if (!saveSucceded)
                {
                    try
                    {
                        string tempPathDir          = Path.GetTempPath();
                        string fileNameOnly         = Path.GetFileName(fileName);
                        string intermediateFileName = tempPathDir + fileNameOnly;
                        ifcDocument.SaveAs(tempPathDir + fileNameOnly, saveAsOptions);

                        File.Copy(intermediateFileName, fileName);
                        Application application = ifcDocument.Application;
                        ifcDocument.Close(false);

                        ifcDocument = application.OpenDocumentFile(fileName);
                        File.Delete(intermediateFileName);
                        saveSucceded = true;
                    }
                    catch (Exception ex)
                    {
                        // We still want to close the document to prevent having a corrupt model in memory.
                        saveSucceded = false;
                        Importer.TheLog.LogError(-1, ex.Message, false);
                    }
                }
            }

            if (!ifcDocument.IsLinked)
            {
                ifcDocument.Close(false);
            }

            ElementId revitLinkTypeId = ElementId.InvalidElementId;

            if (!saveSucceded)
            {
                return(revitLinkTypeId);
            }

            bool doReloadFrom = useExistingType && !Importer.TheOptions.CreateLinkInstanceOnly;

            if (Importer.TheOptions.RevitLinkFileName != null)
            {
                FilePath originalRevitFilePath = new FilePath(Importer.TheOptions.RevitLinkFileName);
                revitLinkTypeId = RevitLinkType.GetTopLevelLink(originalDocument, originalRevitFilePath);
            }

            ModelPath path = ModelPathUtils.ConvertUserVisiblePathToModelPath(originalIFCFileName);

            // Relative path type only works if the model isn't in the cloud.  As such, we'll try again if the
            // routine returns an exception.
            ExternalResourceReference ifcResource = null;

            for (int ii = 0; ii < 2; ii++)
            {
                PathType pathType = (ii == 0) ? PathType.Relative : PathType.Absolute;
                try
                {
                    ifcResource = ExternalResourceReference.CreateLocalResource(originalDocument,
                                                                                ExternalResourceTypes.BuiltInExternalResourceTypes.IFCLink, path, pathType);
                    break;
                }
                catch
                {
                    ifcResource = null;
                }
            }

            if (ifcResource == null)
            {
                Importer.TheLog.LogError(-1, "Couldn't create local IFC cached file.  Aborting import.", true);
            }


            if (!doReloadFrom)
            {
                Transaction linkTransaction = new Transaction(originalDocument);
                linkTransaction.Start(Resources.IFCLinkFile);

                try
                {
                    if (revitLinkTypeId == ElementId.InvalidElementId)
                    {
                        RevitLinkOptions options    = new RevitLinkOptions(true);
                        LinkLoadResult   loadResult = RevitLinkType.CreateFromIFC(originalDocument, ifcResource, fileName, false, options);
                        if ((loadResult != null) && (loadResult.ElementId != ElementId.InvalidElementId))
                        {
                            revitLinkTypeId = loadResult.ElementId;
                        }
                    }

                    if (revitLinkTypeId != ElementId.InvalidElementId)
                    {
                        RevitLinkInstance.Create(originalDocument, revitLinkTypeId);
                    }

                    Importer.PostDelayedLinkErrors(originalDocument);
                    linkTransaction.Commit();
                }
                catch (Exception ex)
                {
                    linkTransaction.RollBack();
                    throw ex;
                }
            }
            else // reload from
            {
                // For the reload from case, we expect the transaction to have been created in the UI.
                if (revitLinkTypeId != ElementId.InvalidElementId)
                {
                    RevitLinkType existingRevitLinkType = originalDocument.GetElement(revitLinkTypeId) as RevitLinkType;
                    if (existingRevitLinkType != null)
                    {
                        existingRevitLinkType.UpdateFromIFC(originalDocument, ifcResource, fileName, false);
                    }
                }
            }

            return(revitLinkTypeId);
        }
Exemple #24
0
        // https://forums.autodesk.com/t5/revit-api-forum/reload-revit-links-from/m-p/7722248
        public Result Execute1(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            // Get application and document objects

            UIApplication uiapp = commandData.Application;
            UIDocument    uidoc = uiapp.ActiveUIDocument;

            Autodesk.Revit.ApplicationServices.Application app = uiapp.Application;
            Document doc = uidoc.Document;

            // NO TRANSACTION NEEDS TO BE OPENED

            try
            {
                using (Transaction tx = new Transaction(doc))
                {
                    // Collect files linked in current project

                    FilteredElementCollector collector     = new FilteredElementCollector(doc);
                    ICollection <Element>    linkInstances = collector.OfClass(typeof(RevitLinkType)).ToElements();

                    // Check which elements are loaded > to be used as filter

                    List <bool> loaded = new List <bool>();
                    foreach (RevitLinkType i in linkInstances)
                    {
                        loaded.Add(RevitLinkType.IsLoaded(doc, i.Id));
                    }

                    // Convert ICollection into a list of RevitLinkTypes
                    int i1 = 0;

                    List <RevitLinkType> revLinkType = new List <RevitLinkType>();
                    foreach (RevitLinkType rli in linkInstances)
                    {
                        if (!loaded[i1++])
                        {
                            revLinkType.Add(rli);
                        }
                    }

                    // Put names of linked files into a list of strings
                    int i2 = 0;

                    List <string> linkNames = new List <string>();
                    foreach (Element eli in linkInstances)
                    {
                        if (!loaded[i2++])
                        {
                            linkNames.Add(eli.Name.Split(' ')[0]);
                        }
                    }

                    // Prompt user with files selection dialog

                    //Start:
                    OpenFileDialog openFileDialog1 = new OpenFileDialog();
                    openFileDialog1.InitialDirectory = (@"P:\");
                    openFileDialog1.Filter           = "RVT|*.rvt";
                    openFileDialog1.Multiselect      = true;
                    openFileDialog1.RestoreDirectory = true;

                    // If you select the files and hit OK (in the file browser)

                    if (openFileDialog1.ShowDialog() == DialogResult.OK)
                    {
                        // Show which files (path + version) has been selected before linking them

                        StringBuilder userSelectionWVersion = new StringBuilder();
                        foreach (string fp in openFileDialog1.FileNames)
                        {
                            userSelectionWVersion.AppendLine(
                                fp.ToString()
                                + " which was created with " +
                                BasicFileInfo.Extract(fp).SavedInVersion.ToString().ToUpper());
                        }

                        // Recap the user with his selection + Revit version of the file

                        DialogResult linkCorrect = MessageBox.Show(
                            userSelectionWVersion.ToString(),
                            "You selected the files:",
                            MessageBoxButtons.OKCancel);

                        // Put paths of files selected by user into a list

                        if (linkCorrect == DialogResult.OK)
                        {
                            List <string> userSelectionNames = new List <string>();
                            foreach (string fp in openFileDialog1.FileNames)
                            {
                                userSelectionNames.Add(fp.ToString());
                            }

                            // Check which of the files that the user selected have the same name of the files linked in the project

                            IEnumerable <string> elementsToReload = userSelectionNames.Where(a => linkNames.Exists(b => a.Contains(b)));

                            // Show which files need to be reloaded

                            StringBuilder intersection = new StringBuilder();
                            foreach (string fp in elementsToReload)
                            {
                                intersection.AppendLine(fp.ToString());
                            }
                            DialogResult promptToLoad = MessageBox.Show(intersection.ToString(), "The following files need to be roloaded");

                            // Initialize + populate list of ModelPaths > path from where to reload

                            List <ModelPath> modPaths = new List <ModelPath>();

                            foreach (string fp in elementsToReload)
                            {
                                FileInfo  filePath = new FileInfo(fp);
                                ModelPath linkpath = ModelPathUtils.ConvertUserVisiblePathToModelPath(filePath.ToString());
                                modPaths.Add(linkpath);
                            }

                            // Zip together file (as RevitLinkType) and the corresponding path to be reloaded from > Reload

                            foreach (var ab in revLinkType.Zip(modPaths, Tuple.Create))
                            {
                                ab.Item1.LoadFrom(ab.Item2, new WorksetConfiguration());
                            }
                        }
                        return(Result.Succeeded);
                    }
                }
            }
            catch (Exception ex)
            {
                // If something went wrong return Result.Failed

                DialogResult genericException = MessageBox.Show(ex.Message, "Oops there was problem!");

                return(Result.Failed);
            }
            return(Result.Succeeded);
        }
Exemple #25
0
        /// <summary>
        /// Get linked model and select all the doors.
        /// </summary>
        /// <param name="doc"></param>
        /// <param name="uiApp"></param>
        /// <returns>Object of doors</returns>
        public List <ObjDoors> LinkedModelDoors(Document doc, UIApplication uiApp)
        {
            FilteredElementCollector collector = new FilteredElementCollector(doc);

            IList <Element> elems = collector
                                    .OfCategory(BuiltInCategory.OST_RvtLinks)
                                    .OfClass(typeof(RevitLinkType))
                                    .ToElements();

            List <ObjDoors> LinkedModelDoors = new List <ObjDoors>();

            foreach (Element e in elems)
            {
                RevitLinkType linkType = e as RevitLinkType;
                String        s        = String.Empty;

                foreach (Document linkedDoc in uiApp.Application.Documents)
                {
                    if (linkedDoc.Title.Equals(linkType.Name))
                    {
                        LibraryGetItems library = new LibraryGetItems();
                        List <Element>  doors   = library.GetFamilyElement(linkedDoc, BuiltInCategory.OST_Doors);
                        foreach (Element door in doors)
                        {
                            try
                            {
                                LocationPoint location = door.Location as LocationPoint;
                                // Get level id parameter
                                Parameter levelId = door.get_Parameter(BuiltInParameter.FAMILY_LEVEL_PARAM);
                                // Get level value of id parameter
                                string parmLevel_Id = library.GetParameterValue(levelId);
                                // get all levels in linked model
                                List <Level> levels = library.GetLevels(linkedDoc);
                                // find and match of door level and linked model level to get level
                                Level levelName = levels.Find(x => Convert.ToString(x.Id.IntegerValue) == parmLevel_Id);

                                FamilySymbol familySymbol = library.GetFamilySymbol(linkedDoc, door.Name, BuiltInCategory.OST_Doors);
                                // find unique identification of door\
                                ObjDoors ObjectDoor = new ObjDoors();
                                ObjectDoor.doorElement = door;
                                ObjectDoor.doorName    = door.Name;
                                ObjectDoor.doorId      = door.Id.ToString();

                                ObjectDoor.doorWidth = door.get_Parameter(BuiltInParameter.DOOR_WIDTH).AsDouble();
                                try
                                {
                                    if (ObjectDoor.doorWidth == 0.0)
                                    {
                                        ObjectDoor.doorWidth = familySymbol.get_Parameter(BuiltInParameter.DOOR_WIDTH).AsDouble();
                                    }
                                }
                                catch { }

                                ObjectDoor.doorHeight = door.get_Parameter(BuiltInParameter.DOOR_HEIGHT).AsDouble();
                                try
                                {
                                    if (ObjectDoor.doorHeight == 0.0)
                                    {
                                        ObjectDoor.doorHeight = familySymbol.get_Parameter(BuiltInParameter.DOOR_HEIGHT).AsDouble();
                                    }
                                }
                                catch { }

                                ObjectDoor.doorSillHeight = door.get_Parameter(BuiltInParameter.INSTANCE_SILL_HEIGHT_PARAM).AsDouble();

                                ObjectDoor.X     = location.Point.X;
                                ObjectDoor.Y     = location.Point.Y;
                                ObjectDoor.Z     = location.Point.Z;
                                ObjectDoor.level = levelName;

                                FamilyInstance familyInstance = door as FamilyInstance;
                                ObjectDoor.HostObj = familyInstance.Host.Id.IntegerValue;
                                ObjectDoor.wall    = linkedDoc.GetElement(familyInstance.Host.Id) as Wall;
                                LinkedModelDoors.Add(ObjectDoor);
                            }
                            catch (Exception er)
                            {
                                string error = er.Message;
                            }
                        }
                    }
                }
            }
            return(LinkedModelDoors);
        }
Exemple #26
0
        public void Execute(UIApplication app)
        {
            GetLogs.SetNewLog(null, "--", ProjectDto.Id);
            var stp_watch = new Stopwatch();

            stp_watch.Start();

            Document doc = app.ActiveUIDocument.Document;

            foreach (ModelDto model in ModelList)
            {
                using (Transaction loadDoc = new Transaction(doc, "Load Link Documents"))
                {
                    loadDoc.Start();
                    RevitLinkOptions rvtLinkOptions = new RevitLinkOptions(false);


                    ModelPath         modelPath      = ModelPathUtils.ConvertUserVisiblePathToModelPath(model.ModelPath);
                    LinkLoadResult    linkType       = RevitLinkType.Create(doc, modelPath, rvtLinkOptions);
                    RevitLinkInstance openedDocument = RevitLinkInstance.Create(doc, linkType.ElementId);


                    Document docLink = openedDocument.GetLinkDocument();
                    stp_watch.Stop();
                    GetLogs.SetNewLog(stp_watch.Elapsed.ToString(), "Добавление модели: " + model.ModelName, ProjectDto.Id);
                    stp_watch.Restart();
                    stp_watch.Start();
                    /* Получить все экземплярый и записать их в бд */
                    List <Element> instances = FindElements(docLink, GetCategoryFilter(), true).Where(x => x != null).ToList();
                    dataBaseFamilies.AddFamilies(instances.Select(x => new FamilyDto()
                    {
                        Categoty     = x.Category.Name,
                        FamilyInstId = x.Id.IntegerValue,
                        FamilyTypeId = x.GetTypeId().IntegerValue,
                        ModelId      = model.Id
                    }).ToList());

                    stp_watch.Stop();
                    GetLogs.SetNewLog(stp_watch.Elapsed.ToString(), "Создание нового списка семейств и запись в БД. Количество семейств: " + instances.Count, ProjectDto.Id);

                    stp_watch.Restart();
                    stp_watch.Start();
                    var FamlistFroDb = dataBaseFamilies.GetFamilyInstances(model);
                    List <ParameterInstanceDto> ParamsInstList = new List <ParameterInstanceDto>();
                    List <ParameterTypeDto>     ParamsTypeList = new List <ParameterTypeDto>();
                    foreach (Element elem in instances)
                    {
                        var famId = FamlistFroDb.Where(x => x.FamilyInstId == elem.Id.IntegerValue).FirstOrDefault().Id;

                        ParamsInstList.AddRange(elem.Parameters.ToList().Select(x => new ParameterInstanceDto()
                        {
                            Name     = x.Definition.Name,
                            FamilyId = famId
                        }).ToList());
                    }
                    stp_watch.Stop();
                    GetLogs.SetNewLog(stp_watch.Elapsed.ToString(), "Создание списка параметров экземпляров. Количество параметров: " + ParamsInstList.Count, ProjectDto.Id);
                    stp_watch.Restart();
                    stp_watch.Start();

                    foreach (Element elem in instances)
                    {
                        var famId = FamlistFroDb.Where(x => x.FamilyInstId == elem.Id.IntegerValue).FirstOrDefault().Id;

                        var elemType = docLink.GetElement(elem.GetTypeId());

                        if (elemType != null)
                        {
                            ParamsTypeList.AddRange((elemType.Parameters.ToList().Select(x => new ParameterTypeDto()
                            {
                                Name = x.Definition.Name,
                                FamilyId = famId
                            }).ToList()));
                        }
                    }

                    stp_watch.Stop();
                    GetLogs.SetNewLog(stp_watch.Elapsed.ToString(), "Создание списка параметров типов. Количество параметров: " + ParamsTypeList.Count, ProjectDto.Id);
                    stp_watch.Restart();
                    stp_watch.Start();

                    dataBaseParameters.AddParameterInstances(ParamsInstList);

                    stp_watch.Stop();
                    GetLogs.SetNewLog(stp_watch.Elapsed.ToString(), "Выгрузка параметров экземпляров в БД", ProjectDto.Id);
                    stp_watch.Restart();
                    stp_watch.Start();

                    dataBaseParameters.AddParameterTypes(ParamsTypeList);
                    stp_watch.Stop();
                    GetLogs.SetNewLog(stp_watch.Elapsed.ToString(), "Выгрузка параметров типов в БД", ProjectDto.Id);


                    loadDoc.RollBack();
                }
            }
            stp_watch.Stop();

            //GetLogs.SetNewLog(stp_watch.Elapsed.TotalMinutes.ToString(), "Выгрузка параметров", ProjectDto.Id);
            //TaskDialog.Show("Время выгрузки", upload_link_model.ToString());
        }
        /// <summary>
        /// Tag all walls in all linked documents
        /// </summary>
        void TagAllLinkedWalls(Document doc)
        {
            // Point near my wall
            XYZ xyz = new XYZ(-20, 20, 0);

            // At first need to find our links
            FilteredElementCollector collector
                = new FilteredElementCollector(doc)
                  .OfClass(typeof(RevitLinkInstance));

            foreach (Element elem in collector)
            {
                // Get linkInstance
                RevitLinkInstance instance = elem
                                             as RevitLinkInstance;

                // Get linkDocument
                Document linkDoc = instance.GetLinkDocument();

                // Get linkType
                RevitLinkType type = doc.GetElement(
                    instance.GetTypeId()) as RevitLinkType;

                // Check if link is loaded
                if (RevitLinkType.IsLoaded(doc, type.Id))
                {
                    // Find walls for tagging
                    FilteredElementCollector walls
                        = new FilteredElementCollector(linkDoc)
                          .OfCategory(BuiltInCategory.OST_Walls)
                          .OfClass(typeof(Wall));

                    // Create reference
                    foreach (Wall wall in walls)
                    {
                        Reference newRef = new Reference(wall)
                                           .CreateLinkReference(instance);

                        // Create transaction
                        using (Transaction tx = new Transaction(doc))
                        {
                            tx.Start("Create tags");

                            IndependentTag newTag = IndependentTag.Create(
                                doc, doc.ActiveView.Id, newRef, true,
                                TagMode.TM_ADDBY_MATERIAL,
                                TagOrientation.Horizontal, xyz);

                            // Use TaggedElementId.LinkInstanceId and
                            // TaggedElementId.LinkInstanceId to retrieve
                            // the id of the tagged link and element:

                            LinkElementId linkId          = newTag.TaggedElementId;
                            ElementId     linkInstanceId  = linkId.LinkInstanceId;
                            ElementId     linkedElementId = linkId.LinkedElementId;

                            tx.Commit();
                        }
                    }
                }
            }
        }
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            Debug.Listeners.Clear();
            Debug.Listeners.Add(new RbsLogger.Logger("BatchPrint"));
            Debug.WriteLine("Print started");

            App.assemblyPath = System.Reflection.Assembly.GetExecutingAssembly().Location;

            Selection sel     = commandData.Application.ActiveUIDocument.Selection;
            Document  mainDoc = commandData.Application.ActiveUIDocument.Document;

            string mainDocTitle = SheetSupport.GetDocTitleWithoutRvt(mainDoc.Title);

            YayPrintSettings printSettings = YayPrintSettings.GetSavedPrintSettings();

            printSettings.dwgProfiles = DwgSupport.GetAllDwgExportSettingsNames(mainDoc);


            //листы из всех открытых файлов, ключ - имя файла, значение - список листов
            Dictionary <string, List <MySheet> > allSheets = SheetSupport.GetAllSheets(commandData, printSettings);

            //получаю выбранные листы в диспетчере проекта
            List <ElementId> selIds = sel.GetElementIds().ToList();
            //List<MySheet> mSheets0 = new List<MySheet>();
            bool sheetsIsChecked = false;

            foreach (ElementId id in selIds)
            {
                Element   elem  = mainDoc.GetElement(id);
                ViewSheet sheet = elem as ViewSheet;
                if (sheet == null)
                {
                    continue;
                }
                sheetsIsChecked = true;

                MySheet sheetInBase = allSheets[mainDocTitle].Where(i => i.sheet.Id.IntegerValue == sheet.Id.IntegerValue).First();
                sheetInBase.IsPrintable = true;

                //mSheets0.Add(new MySheet(sheet));
            }
            if (!sheetsIsChecked)
            {
                message = "Не выбраны листы. Выберите листы в Диспетчере проекта через Shift.";
                Debug.WriteLine("Печать остановлена, не выбраны листы");
                return(Result.Failed);
            }


            //запись статистики по файлу
            //ProjectRating.Worker.Execute(commandData);

            //очистка старых Schema при необходимости

            /*try
             * {
             *  Autodesk.Revit.DB.ExtensibleStorage.Schema sch =
             *       Autodesk.Revit.DB.ExtensibleStorage.Schema.Lookup(new Guid("414447EA-4228-4B87-A97C-612462722AD4"));
             *  Autodesk.Revit.DB.ExtensibleStorage.Schema.EraseSchemaAndAllEntities(sch, true);
             *
             *  Autodesk.Revit.DB.ExtensibleStorage.Schema sch2 =
             *       Autodesk.Revit.DB.ExtensibleStorage.Schema.Lookup(new Guid("414447EA-4228-4B87-A97C-612462722AD5"));
             *  Autodesk.Revit.DB.ExtensibleStorage.Schema.EraseSchemaAndAllEntities(sch2, true);
             *  Debug.WriteLine("Schema очищены");
             * }
             * catch
             * {
             *  Debug.WriteLine("Не удалось очистить Schema");
             * }
             */

            FormPrint form = new FormPrint(allSheets, printSettings);

            form.ShowDialog();

            if (form.DialogResult != System.Windows.Forms.DialogResult.OK)
            {
                return(Result.Cancelled);
            }
            Debug.WriteLine("В окне печати нажат ОК, переход к печати");
            printSettings = form.printSettings;

            string printerName = printSettings.printerName;

            allSheets = form.sheetsSelected;
            Debug.WriteLine("Выбранные для печати листы");
            foreach (var kvp in allSheets)
            {
                Debug.WriteLine(" Файл " + kvp.Key);
                foreach (MySheet ms in kvp.Value)
                {
                    Debug.WriteLine("  Лист " + ms.sheet.Name);
                }
            }

            string outputFolderCommon = printSettings.outputFolder;

            YayPrintSettings.SaveSettings(printSettings);
            Debug.WriteLine("Настройки печати сохранены");

            //Дополнительные возможности работают только с PDFCreator
            if (printerName != "PDFCreator")
            {
                if (printSettings.colorsType == ColorType.MonochromeWithExcludes || printSettings.mergePdfs || printSettings.useOrientation)
                {
                    string errmsg = "Объединение PDF и печать \"Штампа\" в цвете поддерживаются только  для PDFCreator.";
                    errmsg += "\nВо избежание ошибок эти настройки будут отключены.";
                    TaskDialog.Show("Предупреждение", errmsg);
                    printSettings.mergePdfs      = false;
                    printSettings.excludeColors  = new List <PdfColor>();
                    printSettings.useOrientation = false;
                    Debug.WriteLine("Выбранные настройки несовместимы с принтером " + printerName);
                }
            }
            else
            {
                if (!printSettings.useOrientation)
                {
                    SupportRegistry.SetOrientationForPdfCreator(OrientationType.Automatic);
                    Debug.WriteLine("Установлена ориентация листа Automatic");
                }
            }
            bool   printToFile  = form.printToFile;
            string outputFolder = "";

            if (printToFile)
            {
                outputFolder = PrintSupport.CreateFolderToPrint(mainDoc, printerName, outputFolderCommon);
                Debug.WriteLine("Создана папка для печати: " + outputFolder);
            }
            //List<string> pfdFileNames = new List<string>();

            //печатаю листы из каждого выбранного revit-файла
            List <MySheet> printedSheets = new List <MySheet>();

            foreach (string docTitle in allSheets.Keys)
            {
                Document openedDoc = null;
                Debug.WriteLine("Печать листов из файла " + docTitle);

                RevitLinkType rlt = null;

                //проверяю, текущий это документ или полученный через ссылку
                if (docTitle == mainDocTitle)
                {
                    openedDoc = mainDoc;
                    Debug.WriteLine("Это не ссылочный документ");
                }
                else
                {
                    List <RevitLinkType> linkTypes = new FilteredElementCollector(mainDoc)
                                                     .OfClass(typeof(RevitLinkType))
                                                     .Cast <RevitLinkType>()
                                                     .Where(i => SheetSupport.GetDocTitleWithoutRvt(i.Name) == docTitle)
                                                     .ToList();
                    if (linkTypes.Count == 0)
                    {
                        throw new Exception("Cant find opened link file " + docTitle);
                    }
                    rlt = linkTypes.First();

                    //проверю, не открыт ли уже документ, который пытаемся печатать
                    foreach (Document testOpenedDoc in commandData.Application.Application.Documents)
                    {
                        if (testOpenedDoc.IsLinked)
                        {
                            continue;
                        }
                        if (testOpenedDoc.Title == docTitle || testOpenedDoc.Title.StartsWith(docTitle) || docTitle.StartsWith(testOpenedDoc.Title))
                        {
                            openedDoc = testOpenedDoc;
                            Debug.WriteLine("Это открытый ссылочный документ");
                        }
                    }

                    //иначе придется открывать документ через ссылку
                    if (openedDoc == null)
                    {
                        Debug.WriteLine("Это закрытый ссылочный документ, пытаюсь его открыть");
                        List <Document> linkDocs = new FilteredElementCollector(mainDoc)
                                                   .OfClass(typeof(RevitLinkInstance))
                                                   .Cast <RevitLinkInstance>()
                                                   .Select(i => i.GetLinkDocument())
                                                   .Where(i => i != null)
                                                   .Where(i => SheetSupport.GetDocTitleWithoutRvt(i.Title) == docTitle)
                                                   .ToList();
                        if (linkDocs.Count == 0)
                        {
                            throw new Exception("Cant find link file " + docTitle);
                        }
                        Document linkDoc = linkDocs.First();

                        if (linkDoc.IsWorkshared)
                        {
                            Debug.WriteLine("Это файл совместной работы, открываю с отсоединением");
                            ModelPath   mpath = linkDoc.GetWorksharingCentralModelPath();
                            OpenOptions oo    = new OpenOptions();
                            oo.DetachFromCentralOption = DetachFromCentralOption.DetachAndPreserveWorksets;
                            WorksetConfiguration wc = new WorksetConfiguration(WorksetConfigurationOption.OpenAllWorksets);
                            oo.SetOpenWorksetsConfiguration(wc);
                            rlt.Unload(new SaveCoordinates());
                            openedDoc = commandData.Application.Application.OpenDocumentFile(mpath, oo);
                        }
                        else
                        {
                            Debug.WriteLine("Это однопользательский файл");
                            string docPath = linkDoc.PathName;
                            rlt.Unload(new SaveCoordinates());
                            openedDoc = commandData.Application.Application.OpenDocumentFile(docPath);
                        }
                    }
                    Debug.WriteLine("Файл-ссылка успешно открыт");
                } //


                List <MySheet> mSheets = allSheets[docTitle];

                if (docTitle != mainDocTitle)
                {
                    List <ViewSheet> linkSheets = new FilteredElementCollector(openedDoc)
                                                  .OfClass(typeof(ViewSheet))
                                                  .Cast <ViewSheet>()
                                                  .ToList();
                    List <MySheet> tempSheets = new List <MySheet>();
                    foreach (MySheet ms in mSheets)
                    {
                        foreach (ViewSheet vs in linkSheets)
                        {
                            if (ms.SheetId == vs.Id.IntegerValue)
                            {
                                MySheet newMs = new MySheet(vs, printSettings.alwaysColorParamName);
                                tempSheets.Add(newMs);
                            }
                        }
                    }
                    mSheets = tempSheets;
                }
                Debug.WriteLine("Листов для печати найдено в данном файле: " + mSheets.Count.ToString());

                Debug.WriteLine(": " + mSheets.Count.ToString());
                PrintManager pManager = openedDoc.PrintManager;
                Debug.WriteLine("Текущий выбранный принтер: " + pManager.PrinterName);
                Debug.WriteLine("Попытка назначить принтер: " + printerName);
                pManager.SelectNewPrintDriver(printerName);
                pManager            = openedDoc.PrintManager;
                pManager.PrintRange = PrintRange.Current;
                pManager.Apply();
                Debug.WriteLine("Настройки менеджера печати успешно применены");


                //список основных надписей нужен потому, что размеры листа хранятся в них
                //могут быть примечания, сделанные Основной надписью, надо их отфильровать, поэтому >0.6
                List <FamilyInstance> titleBlocks = new FilteredElementCollector(openedDoc)
                                                    .WhereElementIsNotElementType()
                                                    .OfCategory(BuiltInCategory.OST_TitleBlocks)
                                                    .Cast <FamilyInstance>()
                                                    .Where(t => t.get_Parameter(BuiltInParameter.SHEET_HEIGHT).AsDouble() > 0.6)
                                                    .ToList();
                Debug.WriteLine("Найдено основных надписей: " + titleBlocks.Count.ToString());


                //получаю имя формата и проверяю, настроены ли размеры бумаги в Сервере печати
                string formatsCheckinMessage = PrintSupport.PrintFormatsCheckIn(openedDoc, printerName, titleBlocks, ref mSheets);
                if (formatsCheckinMessage != "")
                {
                    message = formatsCheckinMessage;
                    Debug.WriteLine("Проверка форматов листов неудачна: " + message);
                    return(Result.Failed);
                }
                Debug.WriteLine("Проверка форматов листов выполнена успешно, переход к печати");

                //если включен экспорт dwg - нахожу параметры экспорта по имени
                DWGExportOptions dwgOptions = null;
                if (printSettings.exportToDwg)
                {
                    List <ExportDWGSettings> curDwgSettings = DwgSupport.GetAllDwgExportSettingsNames(openedDoc)
                                                              .Where(i => i.Name == printSettings.selectedDwgExportProfileName)
                                                              .ToList();
                    if (curDwgSettings.Count == 0)
                    {
                        TaskDialog.Show("Ошибка", "В файле " + openedDoc.Title + " не найден dwg профиль " + printSettings.selectedDwgExportProfileName);
                        dwgOptions = DwgSupport.GetAllDwgExportSettingsNames(openedDoc).First().GetDWGExportOptions();
                    }
                    else
                    {
                        dwgOptions = curDwgSettings.First().GetDWGExportOptions();
                    }
                }

                //печатаю каждый лист
                foreach (MySheet msheet in mSheets)
                {
                    Debug.WriteLine(" ");
                    Debug.WriteLine("Печатается лист: " + msheet.sheet.Name);
                    if (printSettings.refreshSchedules)
                    {
                        SchedulesRefresh.Start(openedDoc, msheet.sheet);
                        Debug.WriteLine("Спецификации обновлены успешно");
                    }


                    using (Transaction t = new Transaction(openedDoc))
                    {
                        t.Start("Профили печати");

                        string fileName0 = "";
                        if (printSettings.mergePdfs)
                        {
                            string guid = Guid.NewGuid().ToString();
                            fileName0 = msheet.sheet.SheetNumber + "_" + guid + ".pdf";
                        }
                        else
                        {
                            fileName0 = msheet.NameByConstructor(printSettings.nameConstructor);
                        }
                        string fileName = SheetSupport.ClearIllegalCharacters(fileName0);
                        if (fileName.Length > 128)
                        {
                            Debug.WriteLine("Имя листа длиннее 128 символов, будет урезано");
                            string cutname = fileName.Substring(0, 63);
                            cutname += fileName.Substring(fileName.Length - 64);
                            fileName = cutname;
                        }

                        if (printerName == "PDFCreator" && printSettings.useOrientation)
                        {
                            if (msheet.IsVertical)
                            {
                                SupportRegistry.SetOrientationForPdfCreator(OrientationType.Portrait);
                                Debug.WriteLine("Принудительно установлена Portrait ориентация");
                            }
                            if (!msheet.IsVertical)
                            {
                                SupportRegistry.SetOrientationForPdfCreator(OrientationType.Landscape);
                                Debug.WriteLine("Принудительно установлена Landscape ориентация");
                            }
                        }

                        for (int i = 0; i < msheet.titleBlocks.Count; i++)
                        {
                            string tempFilename = "";
                            if (msheet.titleBlocks.Count > 1)
                            {
                                Debug.WriteLine("На листе более 1 основной надписи! Печать части №" + i.ToString());
                                tempFilename = fileName.Replace(".pdf", "_" + i.ToString() + ".pdf");
                            }
                            else
                            {
                                Debug.WriteLine("На листе 1 основная надпись Id " + msheet.titleBlocks.First().Id.IntegerValue.ToString());
                                tempFilename = fileName;
                            }

                            string fullFilename = System.IO.Path.Combine(outputFolder, tempFilename);
                            Debug.WriteLine("Полное имя файла: " + fullFilename);

                            if (fullFilename.Length > 256)
                            {
                                throw new Exception("Слишком длинное имя файла " + fullFilename);
                            }

                            //смещаю область для печати многолистовых спецификаций
                            double offsetX = -i * msheet.widthMm / 25.4; //смещение задается в дюймах!
                            Debug.WriteLine("Смещение печати по X: " + offsetX.ToString("F3"));

                            PrintSetting ps = PrintSupport.CreatePrintSetting(openedDoc, pManager, msheet, printSettings, offsetX, 0);

                            pManager.PrintSetup.CurrentPrintSetting = ps;
                            Debug.WriteLine("Настройки печати применены, " + ps.Name);


                            PrintSupport.PrintView(msheet.sheet, pManager, ps, tempFilename);
                            Debug.WriteLine("Лист успешно отправлен на принтер");
                            msheet.PdfFileName = fullFilename;
                            printedSheets.Add(new MySheet(msheet));
                        }

                        if (printerName == "PDFCreator" && printSettings.useOrientation)
                        {
                            System.Threading.Thread.Sleep(5000);
                        }

                        t.RollBack();
                    }

                    //если включен dwg - то ещё экспортирую этот лист
                    if (printSettings.exportToDwg)
                    {
                        List <ElementId> sheetsIds = new List <ElementId> {
                            msheet.sheet.Id
                        };
                        string sheetname = msheet.NameByConstructor(printSettings.dwgNameConstructor);
                        openedDoc.Export(outputFolder, sheetname, sheetsIds, dwgOptions);
                    }
                }

                if (rlt != null)
                {
                    openedDoc.Close(false);
#if R2017
                    RevitLinkLoadResult LoadResult = rlt.Reload();
#else
                    LinkLoadResult loadResult = rlt.Reload();
#endif
                    Debug.WriteLine("Ссылочный документ закрыт");
                }
            }
            int printedSheetsCount = printedSheets.Count;
            printedSheets.Sort();

            //если требуется постобработка файлов - ждем, пока они напечатаются
            if (printSettings.colorsType == ColorType.MonochromeWithExcludes || printSettings.mergePdfs)
            {
                Debug.WriteLine("Включена постобработка файлов; ожидание окончания печати. Требуемое число файлов " + printedSheetsCount.ToString());
                int watchTimer = 0;
                while (printToFile)
                {
                    int filescount = System.IO.Directory.GetFiles(outputFolder, "*.pdf").Length;
                    Debug.WriteLine("Итерация №" + watchTimer + ", файлов напечатано " + filescount);
                    if (filescount >= printedSheetsCount)
                    {
                        break;
                    }
                    System.Threading.Thread.Sleep(500);
                    watchTimer++;


                    if (watchTimer > 100)
                    {
                        BalloonTip.Show("Обнаружены неполадки", "Печать PDF заняла продолжительное время или произошел сбой. Дождитесь окончания печати.");
                        Debug.WriteLine("Не удалось дождаться окончания печати");
                        return(Result.Failed);
                    }
                }
            }


            List <string> pdfFileNames = printedSheets.Select(i => i.PdfFileName).ToList();
            Debug.WriteLine("PDF файлы которые должны быть напечатаны:");
            foreach (string pdfname in pdfFileNames)
            {
                Debug.WriteLine("  " + pdfname);
            }
            Debug.WriteLine("PDF файлы напечатанные по факту:");
            foreach (string pdfnameOut in System.IO.Directory.GetFiles(outputFolder, "*.pdf"))
            {
                Debug.WriteLine("  " + pdfnameOut);
            }

            //преобразую файл в черно-белый при необходимости
            if (printSettings.colorsType == ColorType.MonochromeWithExcludes)
            {
                Debug.WriteLine("Преобразование PDF файла в черно-белый");
                foreach (MySheet msheet in printedSheets)
                {
                    if (msheet.ForceColored)
                    {
                        Debug.WriteLine("Лист не преобразовывается в черно-белый: " + msheet.sheet.Name);
                        continue;
                    }

                    string file    = msheet.PdfFileName;
                    string outFile = file.Replace(".pdf", "_OUT.pdf");
                    Debug.WriteLine("Файл будет преобразован из " + file + " в " + outFile);

                    pdf.PdfWorker.SetExcludeColors(printSettings.excludeColors);
                    pdf.PdfWorker.ConvertToGrayScale(file, outFile);

                    //GrayscaleConvertTools.ConvertPdf(file, outFile, ColorType.Grayscale, new List<ExcludeRectangle> { rect, rect2 });

                    System.IO.File.Delete(file);
                    System.IO.File.Move(outFile, file);
                    Debug.WriteLine("Лист успешно преобразован");
                }
            }



            //объединяю файлы при необходимости
            if (printSettings.mergePdfs)
            {
                Debug.WriteLine(" ");
                Debug.WriteLine("\nОбъединение PDF файлов");
                System.Threading.Thread.Sleep(500);
                string combinedFile = System.IO.Path.Combine(outputFolder, mainDoc.Title + ".pdf");

                BatchPrintYay.pdf.PdfWorker.CombineMultiplyPDFs(pdfFileNames, combinedFile);

                foreach (string file in pdfFileNames)
                {
                    System.IO.File.Delete(file);
                    Debug.WriteLine("Удален файл " + file);
                }
                Debug.WriteLine("Объединено успешно");
            }

            if (printToFile)
            {
                System.Diagnostics.Process.Start(outputFolder);
                Debug.WriteLine("Открыта папка " + outputFolder);
            }

            //восстанавливаю настройки PDFCreator
            //if(printerName == "PDFCreator")
            //{
            //    SupportRegistry.RestoreSettingsForPDFCreator();
            //}


            string msg = "Напечатано листов: " + printedSheetsCount;
            BalloonTip.Show("Печать завершена!", msg);
            Debug.WriteLine("Печать успешно завершена, напечатано листов " + printedSheetsCount);
            return(Result.Succeeded);
        }
Exemple #29
0
        private List <Element> FindElementsInLInkedFiles(Element massInstance, GeometryElement geomElement)
        {
            List <Element> foundElements = new List <Element>();

            try
            {
                Options opt = m_app.Application.Create.NewGeometryOptions();
                opt.ComputeReferences = true;
                opt.DetailLevel       = Autodesk.Revit.DB.ViewDetailLevel.Fine;

                FilteredElementCollector collector = new FilteredElementCollector(m_doc);
                collector.OfCategory(BuiltInCategory.OST_RvtLinks).WhereElementIsNotElementType();
                List <RevitLinkInstance> revitLinkInstances = collector.ToElements().Cast <RevitLinkInstance>().ToList();

                foreach (RevitLinkInstance linkInstance in revitLinkInstances)
                {
                    ElementId     typeId      = linkInstance.GetTypeId();
                    RevitLinkType linkType    = m_doc.GetElement(typeId) as RevitLinkType;
                    string        linkDocName = linkType.Name;

                    Document linkedDoc = null;
                    foreach (Document document in m_app.Application.Documents)
                    {
                        if (linkDocName.Contains(document.Title))
                        {
                            linkedDoc = document; break;
                        }
                    }

                    Transform transformValue = linkInstance.GetTotalTransform();

                    if (null != linkedDoc && null != transformValue)
                    {
                        GeometryElement transformedElement = geomElement.GetTransformed(transformValue.Inverse);
                        Solid           originalSolid      = GetSolid(geomElement);
                        Solid           transformedSolid   = GetSolid(transformedElement);

                        if (null != transformedSolid)
                        {
                            FilteredElementCollector elementCollector = new FilteredElementCollector(linkedDoc);
                            elementCollector.WherePasses(new ElementIntersectsSolidFilter(transformedSolid)).WhereElementIsNotElementType();
                            List <Element> elementList = elementCollector.ToElements().ToList();

                            foreach (Element element in elementList)
                            {
                                int elementId = element.Id.IntegerValue;
                                if (!elementDictionary.ContainsKey(elementId))
                                {
                                    ElementProperties ep = new ElementProperties(element);
                                    ep.Doc            = linkedDoc;
                                    ep.TransformValue = transformValue;
                                    ep.LinkedElement  = true;

                                    CollectParameterValues(element);

                                    FamilyInstance fi = element as FamilyInstance;
                                    if (null != fi)
                                    {
                                        if (null != fi.Host)
                                        {
                                            ep.HostElementId = fi.Host.Id.IntegerValue;
                                        }
                                    }

                                    Dictionary <int, Solid> massContainers = new Dictionary <int, Solid>();
                                    massContainers.Add(massInstance.Id.IntegerValue, originalSolid); //adjusted to the host coordinate system
                                    ep.MassContainers = massContainers;
                                    elementDictionary.Add(ep.ElementId, ep);

                                    if (!categoryIds.Contains(element.Category.Id.IntegerValue) && null != element.Category.Name)
                                    {
                                        elementCategories.Add(element.Category, false);
                                        categoryIds.Add(element.Category.Id.IntegerValue);
                                    }
                                }
                                else
                                {
                                    ElementProperties ep = elementDictionary[elementId];
                                    if (!ep.MassContainers.ContainsKey(massInstance.Id.IntegerValue))
                                    {
                                        ep.MassContainers.Add(massInstance.Id.IntegerValue, originalSolid);
                                        elementDictionary.Remove(elementId);
                                        elementDictionary.Add(elementId, ep);
                                    }
                                }
                            }
                            foundElements.AddRange(elementList);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Failed to find elements in mass.\n" + ex.Message, "FindElementsInMass", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            return(foundElements);
        }
Exemple #30
0
        /// <summary>
        /// Link in the new created document to parent document.
        /// </summary>
        /// <param name="baseFileName">The full path to the IFC file.</param>
        /// <param name="ifcDocument">The newly imported IFC file document.</param>
        /// <param name="originalDocument">The document to contain the IFC link.</param>
        /// <param name="useExistingType">True if the RevitLinkType already exists.</param>
        /// <param name="doSave">True if we should save the document.  This should only be false if we are reusing a cached document.</param>
        /// <returns>The element id of the RevitLinkType for this link operation.</returns>
        public static ElementId LinkInFile(string baseFileName, Document ifcDocument, Document originalDocument, bool useExistingType, bool doSave)
        {
            bool   saveSucceded = true;
            string fileName     = GenerateRevitFileName(baseFileName);

            if (doSave)
            {
                SaveAsOptions saveAsOptions = new SaveAsOptions();
                saveAsOptions.OverwriteExistingFile = true;

                try
                {
                    ifcDocument.SaveAs(fileName, saveAsOptions);
                }
                catch (Exception ex)
                {
                    // We still want to close the document to prevent having a corrupt model in memory.
                    Importer.TheLog.LogError(-1, ex.Message, false);
                    saveSucceded = false;
                }
            }

            if (!ifcDocument.IsLinked)
            {
                ifcDocument.Close(false);
            }

            ElementId revitLinkTypeId = ElementId.InvalidElementId;

            if (!saveSucceded)
            {
                return(revitLinkTypeId);
            }

            bool doReloadFrom = useExistingType && !Importer.TheOptions.CreateLinkInstanceOnly;

            if (Importer.TheOptions.RevitLinkFileName != null)
            {
                FilePath originalRevitFilePath = new FilePath(Importer.TheOptions.RevitLinkFileName);
                revitLinkTypeId = RevitLinkType.GetTopLevelLink(originalDocument, originalRevitFilePath);
            }

            if (!doReloadFrom)
            {
                Transaction linkTransaction = new Transaction(originalDocument);
                linkTransaction.Start(Resources.IFCLinkFile);

                try
                {
                    if (revitLinkTypeId == ElementId.InvalidElementId)
                    {
                        RevitLinkOptions    options    = new RevitLinkOptions(true);
                        RevitLinkLoadResult loadResult = RevitLinkType.CreateFromIFC(originalDocument, baseFileName, fileName, false, options);
                        if ((loadResult != null) && (loadResult.ElementId != ElementId.InvalidElementId))
                        {
                            revitLinkTypeId = loadResult.ElementId;
                        }
                    }

                    if (revitLinkTypeId != ElementId.InvalidElementId)
                    {
                        RevitLinkInstance.Create(originalDocument, revitLinkTypeId);
                    }

                    Importer.PostDelayedLinkErrors(originalDocument);
                    linkTransaction.Commit();
                }
                catch (Exception ex)
                {
                    linkTransaction.RollBack();
                    throw ex;
                }
            }
            else // reload from
            {
                // For the reload from case, we expect the transaction to have been created in the UI.
                if (revitLinkTypeId != ElementId.InvalidElementId)
                {
                    RevitLinkType existingRevitLinkType = originalDocument.GetElement(revitLinkTypeId) as RevitLinkType;
                    if (existingRevitLinkType != null)
                    {
                        existingRevitLinkType.UpdateFromIFC(originalDocument, baseFileName, fileName, false);
                    }
                }
            }

            return(revitLinkTypeId);
        }
Exemple #31
0
        private void DisplayRvtLinkTypes()
        {
            try
            {
                FilteredElementCollector collector = new FilteredElementCollector(m_doc);
                collector.OfCategory(BuiltInCategory.OST_RvtLinks).WhereElementIsNotElementType();
                List <RevitLinkInstance> revitLinkInstances = collector.ToElements().Cast <RevitLinkInstance>().ToList();

                Dictionary <int /*typeId*/, RevitLinkType> linkTypes = new Dictionary <int, RevitLinkType>();
                foreach (RevitLinkInstance instance in revitLinkInstances)
                {
                    LinkedInstanceProperties lip = new LinkedInstanceProperties(instance);
                    ElementId typeId             = instance.GetTypeId();

                    RevitLinkType linkType = m_doc.GetElement(typeId) as RevitLinkType;
                    lip.FileName = linkType.Name;
                    lip.TypeId   = linkType.Id.IntegerValue;

                    if (!linkTypes.ContainsKey(linkType.Id.IntegerValue))
                    {
                        linkTypes.Add(linkType.Id.IntegerValue, linkType);
                    }

                    Parameter nameParam = instance.get_Parameter(BuiltInParameter.RVT_LINK_INSTANCE_NAME);
                    if (null != nameParam)
                    {
                        lip.InstanceName = nameParam.AsString();
                    }

                    foreach (Document document in m_app.Application.Documents)
                    {
                        if (lip.FileName.Contains(document.Title))
                        {
                            lip.LinkedDocument = document;
                            FilteredElementCollector linkedCollector = new FilteredElementCollector(document);
                            List <Element>           massElements    = linkedCollector.OfCategory(BuiltInCategory.OST_Mass).WhereElementIsNotElementType().ToElements().ToList();

                            lip.MassElements = massElements;
                            linkedMassDictionary.Add(lip.InstanceId, lip);
                            break;
                        }
                    }
                }

                foreach (int typeId in linkTypes.Keys)
                {
                    RevitLinkType linkType = linkTypes[typeId];
                    TreeNode      typeNode = new TreeNode(linkType.Name);
                    typeNode.Name = typeId.ToString();
                    typeNode.Tag  = linkType.Id;

                    foreach (int instanceId in linkedMassDictionary.Keys)
                    {
                        LinkedInstanceProperties lip = linkedMassDictionary[instanceId];
                        if (lip.TypeId == typeId)
                        {
                            TreeNode instanceNode = new TreeNode(lip.FileName + " : " + lip.InstanceName);
                            instanceNode.Name = lip.InstanceId.ToString();
                            instanceNode.Tag  = lip.InstanceId;

                            foreach (Element massElement in lip.MassElements)
                            {
                                TreeNode massNode = new TreeNode(massElement.Name);
                                massNode.Name = massElement.Id.ToString();
                                massNode.Tag  = massElement.Id;

                                instanceNode.Nodes.Add(massNode);
                            }
                            typeNode.Nodes.Add(instanceNode);
                        }
                    }
                    treeViewLinkedFile.Nodes.Add(typeNode);
                }
                treeViewLinkedFile.Sort();

                if (treeViewLinkedFile.Nodes.Count > 0)
                {
                    radioButtonLink.Enabled = true;
                    radioButtonAll.Enabled  = true;
                    radioButtonAll.Checked  = true;

                    foreach (TreeNode typeNode in treeViewLinkedFile.Nodes)
                    {
                        typeNode.Checked = true;
                        foreach (TreeNode instanceNode in typeNode.Nodes)
                        {
                            instanceNode.Checked = true;
                            foreach (TreeNode massNode in instanceNode.Nodes)
                            {
                                massNode.Checked = true;
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Log.AppendLog(LogMessageType.EXCEPTION, ex.Message);
            }
        }