public IReadOnlyCollection <Document> LoadDocs()
        {
            var logs      = new List <LogMessage>();
            var documents = new List <Document>();
            var fileNames = GetFilesNames();

            fileNames = CheckIsReadOnly(fileNames);
            foreach (var fileName in fileNames)
            {
                try
                {
                    var doc = _app.OpenDocumentFile(fileName);
                    documents.Add(doc);
                }
                catch (Exception exception)
                {
                    // Не удалось загрузить документ
                    logs.Add(new LogMessage(Language.GetItem(_langItem, "err2"), $"{fileName} - {exception.Message}", true));
                }
            }

            if (logs.Count > 0)
            {
                LogWindow.ShowLogs(logs);
            }

            return(documents);
        }
Esempio n. 2
0
        public IReadOnlyCollection <Document> LoadDocs()
        {
            var logs      = new List <LogMessage>();
            var documents = new List <Document>();
            var fileNames = GetFilesNames();

            foreach (var fileName in fileNames)
            {
                try
                {
                    var doc = _app.OpenDocumentFile(fileName);
                    documents.Add(doc);
                }
                catch
                {
                    logs.Add(new LogMessage("Не удалось загрузить документ", fileName, true));
                }
            }

            if (logs.Count > 0)
            {
                LogWindow.ShowLogs(logs);
            }

            return(documents);
        }
Esempio n. 3
0
        /// <summary>
        /// 读取文件测试.
        /// </summary>
        private void readFile_Click(object sender, RoutedEventArgs e)
        {
            if (m_App == null)
            {
                MessageBox.Show("Revit NET 初始化失败,请检查电脑是否已安装Revit 相应版本!!");
                return;
            }

            var openFile = new OpenFileDialog();

            openFile.Filter = "Revit Project|*.rvt|Revit Family|*.rfa";

            if (openFile.ShowDialog() == true)
            {
                var file = openFile.FileName;

                if (!File.Exists(file))
                {
                    return;
                }

                var doc = m_App.OpenDocumentFile(file);
                if (doc == null)
                {
                    return;
                }

                var elems = new FilteredElementCollector(doc).OfClass(typeof(FamilyInstance));
                MessageBox.Show(string.Format("Docment : {0}, Element: {1} 个", doc.PathName, elems.Count()));
            }
        }
Esempio n. 4
0
        public static Dictionary <string, object> openDocumentBackground(string filePath = null, OpenOptions openOption = null)
        {
            string        message   = "";
            Document      doc       = DocumentManager.Instance.CurrentDBDocument;
            Document      openedDoc = null;
            UIApplication uiapp     = DocumentManager.Instance.CurrentUIApplication;

            Autodesk.Revit.ApplicationServices.Application app = uiapp.Application;
            UIDocument uidoc = DocumentManager.Instance.CurrentUIApplication.ActiveUIDocument;

            ModelPath path = ModelPathUtils.ConvertUserVisiblePathToModelPath(filePath);

            try
            {
                openedDoc = app.OpenDocumentFile(path, openOption);
                message   = "Opened";
            }
            catch (Exception ex)
            {
                message = ex.Message;
            }
            return(new Dictionary <string, object>
            {
                { "document", openedDoc },
                { "message", message }
            });
        }
Esempio n. 5
0
        public static RevitDoc Open(string modelPath, [DefaultArgument("true")] bool reset)
        {
            Autodesk.Revit.UI.UIApplication uiapp = DocumentManager.Instance.CurrentUIApplication;
            Autodesk.Revit.ApplicationServices.Application app = uiapp.Application;

            RevitDoc doc = app.OpenDocumentFile(modelPath);

            return(doc);
        }
Esempio n. 6
0
        public void SaveDetachDisworksets()
        {
            string mpath             = "";
            string mpathOnlyFilename = "";
            FolderBrowserDialog folderBrowserDialog1 = new FolderBrowserDialog();

            folderBrowserDialog1.Description = "Select Folder Where Revit Projects to be Saved in Local";
            folderBrowserDialog1.RootFolder  = Environment.SpecialFolder.MyComputer;
            if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
            {
                mpath = folderBrowserDialog1.SelectedPath;
                FileInfo    filePath = new FileInfo(projectPath);
                ModelPath   mp       = ModelPathUtils.ConvertUserVisiblePathToModelPath(filePath.FullName);
                OpenOptions opt      = new OpenOptions();
                opt.DetachFromCentralOption = DetachFromCentralOption.DetachAndDiscardWorksets;
                mpathOnlyFilename           = filePath.Name;
                Document      openedDoc = app.OpenDocumentFile(mp, opt);
                SaveAsOptions options   = new SaveAsOptions();
                options.OverwriteExistingFile = true;
                ModelPath modelPathout = ModelPathUtils.ConvertUserVisiblePathToModelPath(mpath + "\\" + "Detached" + "_" + datetimesave + "_" + mpathOnlyFilename);
                openedDoc.SaveAs(modelPathout, options);
                openedDoc.Close(true);
            }
        }
Esempio n. 7
0
        private bool upgradeOneFile(string sourceFolder, string targetFolder, string file)
        {
            string fileName = file.Substring(sourceFolder.Length).TrimStart('\\');

            try
            {
                Document doc        = _revitApp.OpenDocumentFile(file);
                string   targetFile = System.IO.Path.Combine(targetFolder, fileName);
                string   folder     = System.IO.Path.GetDirectoryName(targetFile);
                if (Directory.Exists(folder) == false)
                {
                    Directory.CreateDirectory(folder);
                }
                SaveAsOptions option = new SaveAsOptions();
                option.Compact = true;
                option.OverwriteExistingFile = true;
                // set preview view id
                var setting = doc.GetDocumentPreviewSettings();
                if (setting.PreviewViewId != ElementId.InvalidElementId)
                {
                    option.PreviewViewId = setting.PreviewViewId;
                }
                else
                {
                    // Find a candidate 3D view
                    ElementId idView = findPreviewId <View3D>(doc, setting);
                    if (idView == ElementId.InvalidElementId)
                    {
                        // no 3d view, try a plan view
                        idView = findPreviewId <ViewPlan>(doc, setting);
                    }
                    if (idView != ElementId.InvalidElementId)
                    {
                        option.PreviewViewId = idView;
                    }
                }
                doc.SaveAs(targetFile, option);
                doc.Close();

                return(true);
            }
            catch (Exception ex)
            {
                // write error message into log file
                logError(targetFolder, fileName, ex.Message);
                return(false);
            }
        }
Esempio n. 8
0
        public static RevitDoc OpenWithOptions(string modelPath, [DefaultArgument("Synthetic.Revit.WorksetConfigurationOpenAll()")] RevitDB.WorksetConfiguration worksetConfiguration, [DefaultArgument("false")] bool audit, [DefaultArgument("true")] bool reset)
        {
            Autodesk.Revit.UI.UIApplication uiapp = DocumentManager.Instance.CurrentUIApplication;
            Autodesk.Revit.ApplicationServices.Application app = uiapp.Application;
            RevitDoc doc = null;

            RevitDB.ModelPath path = RevitDB.ModelPathUtils.ConvertUserVisiblePathToModelPath(modelPath);

            RevitDB.OpenOptions openOptions = new RevitDB.OpenOptions();
            openOptions.Audit = audit;
            openOptions.SetOpenWorksetsConfiguration(worksetConfiguration);

            doc = app.OpenDocumentFile(path, openOptions);

            return(doc);
        }
Esempio n. 9
0
        /// <summary>
        /// Get all families and theit nested families from a library folder
        /// </summary>
        /// <param name="app"></param>
        /// <param name="folder"></param>
        /// <returns>Key - parent family name, Value - list of nested families in this family</returns>
        public static Dictionary <string, List <string> > GetFamiliesLibrary(
            Autodesk.Revit.ApplicationServices.Application app, string folder)
        {
            string[] files = Directory.GetFiles(folder, "*.rfa", System.IO.SearchOption.AllDirectories);
            Dictionary <string, List <string> > library = new Dictionary <string, List <string> >();

            foreach (string file in files)
            {
                Document famdoc = app.OpenDocumentFile(file);
                //string title = System.IO.Path.GetFileNameWithoutExtension(file);

                //if (library.ContainsKey(title)) throw new Exception("ДУБЛИРОВАНИЕ СЕМЕЙСТВА " + title);


                List <Family> nestedFams = new FilteredElementCollector(famdoc)
                                           .OfClass(typeof(Family))
                                           .Cast <Family>()
                                           .ToList();
                List <string> nestedFamsTitles = new List <string>();
                foreach (Family fam in nestedFams)
                {
                    Parameter sharedFamParam = fam.get_Parameter(BuiltInParameter.FAMILY_SHARED);
                    if (sharedFamParam == null)
                    {
                        continue;
                    }
                    if (!sharedFamParam.HasValue)
                    {
                        continue;
                    }
                    int isShared = sharedFamParam.AsInteger();
                    if (isShared == 1)
                    {
                        nestedFamsTitles.Add(fam.Name);
                    }
                }
                library.Add(file, nestedFamsTitles);
                famdoc.Close(false);
            }
            return(library);
        }
Esempio n. 10
0
        private bool exportOneFile(string file, string targetFolder)
        {
            string fileName = Path.GetFileNameWithoutExtension(file);

            try
            {
                Document doc  = _revitApp.OpenDocumentFile(file);
                View3D   view = ViewCreator.Create3DView(doc);
                if (view != null)
                {
                    FBXExporter.Export(doc, view, targetFolder, fileName);
                }
                doc.Close(false);

                return(true);
            }
            catch (Exception ex)
            {
                // write error message into log file
                logError(targetFolder, fileName, ex.Message);
                return(false);
            }
        }
Esempio n. 11
0
        public void SaveDetach(Document doc)
        {
            System.Windows.Forms.OpenFileDialog theDialogRevit = new System.Windows.Forms.OpenFileDialog();
            theDialogRevit.Title            = "Select Revit Project Files";
            theDialogRevit.Filter           = "RVT files|*.rvt";
            theDialogRevit.FilterIndex      = 1;
            theDialogRevit.InitialDirectory = @"C:\";
            theDialogRevit.Multiselect      = true;
            if (theDialogRevit.ShowDialog() == DialogResult.OK)

            {
                string mpath             = "";
                string mpathOnlyFilename = "";
                System.Windows.Forms.FolderBrowserDialog folderBrowserDialog1 = new System.Windows.Forms.FolderBrowserDialog();
                folderBrowserDialog1.Description = "Select Folder Where Revit Projects to be Saved in Local";
                folderBrowserDialog1.RootFolder  = Environment.SpecialFolder.MyComputer;
                if (folderBrowserDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    mpath = folderBrowserDialog1.SelectedPath;
                    foreach (string projectPath in theDialogRevit.FileNames)
                    {
                        FileInfo    filePath = new FileInfo(projectPath);
                        ModelPath   mp       = ModelPathUtils.ConvertUserVisiblePathToModelPath(filePath.FullName);
                        OpenOptions opt      = new OpenOptions();
                        opt.DetachFromCentralOption = DetachFromCentralOption.DetachAndDiscardWorksets;
                        mpathOnlyFilename           = filePath.Name;
                        Document      openedDoc = app.OpenDocumentFile(mp, opt);
                        SaveAsOptions options   = new SaveAsOptions();
                        options.OverwriteExistingFile = true;
                        ModelPath modelPathout = ModelPathUtils.ConvertUserVisiblePathToModelPath(mpath + "\\" + mpathOnlyFilename);
                        openedDoc.SaveAs(modelPathout, options);
                        openedDoc.Close(false);
                    }
                }
            }
        }
Esempio n. 12
0
        /// <summary>
        /// search for the family files and the corresponding parameter records
        /// load each family file, add parameters and then save and close.
        /// </summary>
        /// <returns>
        /// if succeeded, return true; otherwise false
        /// </returns>
        private bool LoadFamiliesAndAddParameters()
        {
            bool succeeded = true;

            List <string> famFilePaths = new List <string>();

            Environment.SpecialFolder myDocumentsFolder = Environment.SpecialFolder.MyComputer;
            string myDocs = Environment.GetFolderPath(myDocumentsFolder);

            FolderBrowserDialog folderBrowserDialog1 = new FolderBrowserDialog();

            folderBrowserDialog1.RootFolder          = myDocumentsFolder;
            folderBrowserDialog1.ShowNewFolderButton = false;
            folderBrowserDialog1.Description         = "Select the Folder containing the families to be processed:";

            if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
            {
                string families = folderBrowserDialog1.SelectedPath;
                //string families = myDocs + "\\AutoParameter_Families";
                // if (!Directory.Exists(families))
                //{
                //   MessageManager.MessageBuff.Append("The folder [AutoParameter_Families] doesn't exist in [MyDocuments] folder.\n");
                //}
                DirectoryInfo familiesDir = new DirectoryInfo(families);
                FileInfo[]    files       = familiesDir.GetFiles("*.rfa");
                if (0 == files.Length)
                {
                    MessageManager.MessageBuff.Append("No family file exists in [AutoParameter_Families] folder.\n");
                }
                foreach (FileInfo info in files)
                {
                    if (info.IsReadOnly)
                    {
                        MessageManager.MessageBuff.Append("Family file: \"" + info.FullName + "\" is read only. Can not add parameters to it.\n");
                        continue;
                    }

                    string   famFilePath = info.FullName;
                    Document doc         = m_app.OpenDocumentFile(famFilePath);

                    if (!doc.IsFamilyDocument)
                    {
                        succeeded = false;
                        MessageManager.MessageBuff.Append("Document: \"" + famFilePath + "\" is not a family document.\n");
                        continue;
                    }

                    // return and report the errors
                    if (!succeeded)
                    {
                        return(false);
                    }

                    FamilyParameterAssigner assigner = new FamilyParameterAssigner(m_app, doc);
                    // the parameters to be added are defined and recorded in a text file, read them from that file and load to memory
                    succeeded = assigner.LoadParametersFromFile();
                    if (!succeeded)
                    {
                        MessageManager.MessageBuff.Append("Failed to load parameters from parameter files.\n");
                        return(false);
                    }
                    Transaction t = new Transaction(doc, Guid.NewGuid().GetHashCode().ToString());
                    t.Start();
                    succeeded = assigner.AddParameters();
                    if (succeeded)
                    {
                        t.Commit();
                        doc.Save();
                        doc.Close();
                    }
                    else
                    {
                        t.RollBack();
                        doc.Close();
                        MessageManager.MessageBuff.Append("Failed to add parameters to " + famFilePath + ".\n");
                        return(false);
                    }
                }
                return(true);
            }
            return(false);
        }
Esempio n. 13
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            UIApplication uiapp = commandData.Application;
            UIDocument    uidoc = uiapp.ActiveUIDocument;
            Application   app   = uiapp.Application;

            form     fm  = new form();
            Document doc = app.OpenDocumentFile(TextPath);

            //决定导出的元素
            FilteredElementCollector collector = null;

            collector = new FilteredElementCollector(doc);

            collector.WhereElementIsNotElementType().WhereElementIsViewIndependent();

            ObjExporter exporter = new ObjExporter();
            Options     opt      = app.Create.NewGeometryOptions();

            ExportElements(exporter, collector, opt);



            Directory.CreateDirectory(@"D:\to_obj\" + TextName.ToString());
            exporter.ExportTo(@"D:\to_obj\" + TextName.ToString() + @"\" + TextName.ToString() + ".obj".ToString());

            Directory.CreateDirectory(@"D:\to_obj\" + TextName.ToString() + @"\" + "Texture");
            //var objlibraryAsset = app.get_Assets(AssetType.Appearance);
            //foreach (Element elem in collector)
            //{
            //    string theValue = null;
            //    ICollection<ElementId> ids = elem.GetMaterialIds(false);
            //    foreach (ElementId id in ids)
            //    {
            //        Material mat = doc.GetElement(id) as Material;
            //        AssetPropertyString bitmapProperty = null;
            //        AssetProperty property;

            //        ElementId appearanceId = mat.AppearanceAssetId;
            //        AppearanceAssetElement appearanceElem = doc.GetElement(appearanceId) as AppearanceAssetElement;
            //        Asset asset = appearanceElem.GetRenderingAsset();
            //        if (0 != asset.Size)
            //        {
            //            for (var j = 0; j < asset.Size; j++)
            //            {
            //                property = asset[j];
            //                if (property.Name == BitmapPropertyName)
            //                {
            //                    bitmapProperty = property as AssetPropertyString;
            //                    if (bitmapProperty != null)
            //                    {
            //                        theValue = bitmapProperty.Value;
            //                        break;
            //                    }
            //                }
            //            }
            //        }
            //        else
            //        {
            //            foreach (Asset objCurrentAsset in objlibraryAsset)
            //            {
            //                if (objCurrentAsset.Name == asset.Name &&
            //                    objCurrentAsset.LibraryName == asset.LibraryName)
            //                {
            //                    theValue = objCurrentAsset.Type.ToString();
            //                }
            //            }
            //        }

            //    }
            //    if (theValue != null)
            //    {
            //        TaskDialog.Show("lalala", theValue);
            //    }


            //}
            return(Result.Succeeded);
        }
Esempio n. 14
0
        private void cbDocs_SelIdxChanged(object sender, EventArgs e)
        {
            DBDocumentItem documentItem = _cbDocuments.SelectedItem as DBDocumentItem;

            if (documentItem.Document == _dbDocument)
            {
                return;
            }

            if (documentItem.IsNull)
            {
                OpenFileDialog ofd = new OpenFileDialog();
                ofd.DefaultExt = "rvt";
                ofd.Filter     = "Revit project files (*.rvt)|*.rvt|Revit family files (*.rfa)|*.rfa|Revit family template files (*.rft)|*.rft";
                if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    try
                    {
                        _dbDocument = _application.OpenDocumentFile(ofd.FileName);
                    }
                    catch (System.Exception)
                    {
                    }
                    if (_dbDocument != null)
                    {
                        updateDocumentList(_dbDocument);
                        updateViewsList(null);
                    }
                }
                else
                {
                    // the combobox should show the current document item.
                    String documentName;
                    String projName = _dbDocument.ProjectInformation.Name;
                    if (String.IsNullOrEmpty(projName) || projName.ToLower().CompareTo("project name") == 0)
                    {
                        if (String.IsNullOrEmpty(_dbDocument.PathName))
                        {
                            documentName = projName;
                        }
                        else
                        {
                            documentName = new System.IO.FileInfo(_dbDocument.PathName).Name;
                        }
                    }
                    else
                    {
                        documentName = projName;
                    }

                    foreach (DBDocumentItem dbItem in _cbDocuments.Items)
                    {
                        if (dbItem.Name.ToLower().CompareTo(documentName.ToLower()) == 0)
                        {
                            _cbDocuments.SelectedItem = dbItem;
                            break;
                        }
                    }
                }
            }
            else
            {
                _dbDocument = documentItem.Document;
                updateViewsList(null);
            }
        }
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            Autodesk.Revit.ApplicationServices.Application app =
                commandData.Application.Application;

            string familyPath  = "";
            string libraryPath = "";

            using (FormCheckNestedFamily form = new FormCheckNestedFamily())
            {
                if (form.ShowDialog() != System.Windows.Forms.DialogResult.OK)
                {
                    return(Result.Cancelled);
                }
                familyPath  = form.FamilyPath;
                libraryPath = form.LibraryPath;
            }

            Document myFamDoc = app.OpenDocumentFile(familyPath);
            //int myFamDocOwnerFamilyId = myFamDoc.OwnerFamily.Id.IntegerValue; ;
            FamilyInfo fi1  = new FamilyInfo(myFamDoc);
            string     xml1 = fi1.SerializeToXml();

            myFamDoc.Close(false);

            string familyTitle = System.IO.Path.GetFileNameWithoutExtension(familyPath);

            Dictionary <string, List <string> > library = FilesWorker.GetFamiliesLibrary(app, libraryPath);

            //search parent families that includes my family
            List <string> parentFams = new List <string>();

            foreach (KeyValuePair <string, List <string> > kvp in library)
            {
                foreach (string fam in kvp.Value)
                {
                    if (fam.Equals(familyTitle))
                    {
                        parentFams.Add(kvp.Key);
                    }
                }
            }

            //open that parent families and check version of family as nested
            Dictionary <string, string> log = new Dictionary <string, string>();

            foreach (string parentFamFile in parentFams)
            {
                Document      parentfamDoc = app.OpenDocumentFile(parentFamFile);
                List <Family> nestedFams   = new FilteredElementCollector(parentfamDoc)
                                             .OfClass(typeof(Family))
                                             .Cast <Family>()
                                             .Where(i => i.Name == familyTitle)
                                             .ToList();
                if (nestedFams.Count == 0)
                {
                    throw new Exception("Не удалось найти " + familyTitle + " в семействе " + parentFamFile);
                }

                Document nestedFamForChecking = parentfamDoc.EditFamily(nestedFams.First());


                FamilyInfo fi2 = new FamilyInfo(nestedFamForChecking);
                //int idOffset = nestedFamForChecking.OwnerFamily.Id.IntegerValue - myFamDocOwnerFamilyId;
                fi2.ApplyIdOffset(fi1);

                string xml2 = fi2.SerializeToXml();
                nestedFamForChecking.Close(false);
                parentfamDoc.Close(false);

                string compareResult = XmlComparer.Comparer.CompareXmls(xml1, xml2);
                if (string.IsNullOrEmpty(compareResult))
                {
                    compareResult = "IDENTITY!";
                }
                log.Add(parentFamFile, compareResult);
            }

            using (FormResultNestedFamily formResult = new FormResultNestedFamily(familyTitle, log))
            {
                formResult.ShowDialog();
            }



            return(Result.Succeeded);
        }