Esempio n. 1
0
        public UIDocument DoOpenNewLocalFromModelPath(ModelPath centralPath, ModelPath localPath)
        {
            List <WorksetId> worksetsToOpen = new List <WorksetId>();
            // First set to close all worksets
            WorksetConfiguration worksetConfig  = new WorksetConfiguration(WorksetConfigurationOption.CloseAllWorksets);
            OpenOptions          theOpenOptions = new OpenOptions();

            try {
                // Create the new local at the given path
                WorksharingUtils.CreateNewLocal(centralPath, localPath);
                // Select specific worksets to open
                // Get a list of worksets from the unopened document
                IList <WorksetPreview> worksets = WorksharingUtils.GetUserWorksetInfo(localPath);
                foreach (WorksetPreview preview in worksets)
                {
                    bool Include = true;
                    ////// The inverse list is the inverse of the worksets checked. In other
                    ////// words an exclusion list.
                    //////foreach (string ws in InverseWorksetList) {
                    //////    if (ws == "") { continue; }
                    //////    if (preview.Name.StartsWith(ws)) {
                    //////        Include = false;
                    //////        continue;
                    //////    } else {
                    //////    }
                    //////}
                    if (Include)
                    {
                        worksetsToOpen.Add(preview.Id);
                    }
                    else
                    {
                        //System.Windows.MessageBox.Show("Excluding " + preview.Name);
                    }
                }
                // Setup option to open the target worksets
                // then set specific ones to open
                worksetConfig.Open(worksetsToOpen);
                theOpenOptions.SetOpenWorksetsConfiguration(worksetConfig);
                // Now open the new local
                UIDocument openedDoc = _uiApp.OpenAndActivateDocument(localPath, theOpenOptions, false);
                return(openedDoc);
            } catch (Exception ex) {
                System.Windows.MessageBox.Show("Opening the file from its location.\n\n" + ex.Message, "This Is Not A Workshared File");
            }
            // If here then not a workshared file.
            string     fname      = ModelPathUtils.ConvertModelPathToUserVisiblePath(centralPath);
            UIDocument openedDocN = _uiApp.OpenAndActivateDocument(fname);

            return(openedDocN);
        }
Esempio n. 2
0
        private static string ExportViewsProcessLoopNew(UIApplication uiapp, string source_path)
        {
            Application app = uiapp.Application;
            //  Tuple<string, bool> export_task =
            //       ReviFileManager.base_name_for_Export(uiapp, source_path);
            //   string final_hashed_base_name = export_task.Item1;
            string final_hashed_base_name = source_path;

            string        target_folder = FileManager.export_location + final_hashed_base_name + "\\";
            string        target_rvt    = FileManager.model_path + final_hashed_base_name + ".rvt";
            StringBuilder sb            = new StringBuilder();
            //TaskDialog.Show("r", target_folder + " " + target_rvt);

            // if (export_task.Item2 == true)
            //{
            UIDocument uidoc = uiapp.OpenAndActivateDocument(target_rvt);
            Document   doc   = uidoc.Document;

            doc.Save();

            //Actions - Export Bases, Export Mask, Export Shell, CSV DEfs.
            if (!File.Exists(target_folder + "sheet_data.csv"))
            {
                SheetsToCsv(doc, target_folder);
            }

            //if (!File.Exists(target_folder + "sheet_data.csv"))
            //{
            //   var category_colors = FileManager.ReadDefCsv(FileManager.export_location);
            // sb.AppendLine("sheet csv");
            //   JpegsFromSheets(doc, target_folder, category_colors);
            //}

            if (!File.Exists(target_folder + "shell"))
            {
                var shell_ovrs = FileManager.ReadDefCsv(FileManager.shell_data);
                sb.AppendLine("creating shell exports");
                string target_folder2 = FileManager.mkdir(target_folder + "shell\\");
                JpegsFromSheetsRs(doc, target_folder2, shell_ovrs);
            }

            File.AppendAllText(target_folder + "log.txt", sb.ToString());
            UIDocument uidoc2 = uiapp.OpenAndActivateDocument(init_path);

            doc.Close(false);
            // }
            return(final_hashed_base_name);
        }
Esempio n. 3
0
        /// <summary>
        /// Metodo che cancella il file in un certo percorso
        /// </summary>
        private void DeleteFile(UIApplication uiapp, string dirPath)
        {
            if (Directory.Exists(dirPath))
            {
                var files = Directory.EnumerateFiles(dirPath, "*.rfa");

                if (files.Count() > 0)
                {
                    List <string> backUpFiles = new List <string>();

                    foreach (string file in files)
                    {
                        backUpFiles.Add(file);
                    }

                    foreach (string file in backUpFiles)
                    {
                        try
                        {
                            File.Delete(file);
                        }
                        catch (Exception)
                        {
                            string     placeholderFile = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + @"\Bold Software\GetImages\Utilities\Example.rvt";
                            Document   doc             = uiapp.ActiveUIDocument.Document;
                            UIDocument docPlaceholder  = uiapp.OpenAndActivateDocument(placeholderFile);
                            doc.Close(false);
                            File.Delete(file);
                            //var uidoc = uiapp.OpenAndActivateDocument(file);
                            docPlaceholder.Document.Close(false);
                        }
                    }
                }
            }
        }
Esempio n. 4
0
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIApplication uiapp = commandData.Application;
            UIDocument    uidoc = uiapp.ActiveUIDocument;
            Application   app   = uiapp.Application;

            if (StoreExp.quickViews[5] != null)
            {
                try { uidoc.ActiveView = StoreExp.quickViews[5]; }
                catch (Autodesk.Revit.Exceptions.ArgumentException)
                {
                    uiapp.OpenAndActivateDocument(StoreExp.quickViews[5].Document.PathName);
                    uidoc            = uiapp.ActiveUIDocument;
                    uidoc.ActiveView = StoreExp.quickViews[5];
                }
            }
            else
            {
                TaskDialog.Show("Error", "Quick key has not been assigned");
            }
            return(Result.Succeeded);
        }
Esempio n. 5
0
        public static string saveCentralProd(
            UIApplication uiapp, string temp_file_path, string final_hashed_base_name)
        {
            Application app      = uiapp.Application;
            FileInfo    filePath = new FileInfo(temp_file_path);
            ModelPath   mp       =
                ModelPathUtils.ConvertUserVisiblePathToModelPath(
                    filePath.FullName);

            OpenOptions opt = new OpenOptions();

            opt.DetachFromCentralOption =
                DetachFromCentralOption.DetachAndDiscardWorksets;
            opt.AllowOpeningLocalByWrongUser = true;

            string new_path = FileManager.model_path + final_hashed_base_name + ".rvt";


            if (!File.Exists(new_path))
            {
                Document doc = app.OpenDocumentFile(mp, opt);

                SaveAsOptions options = new SaveAsOptions();
                options.OverwriteExistingFile = true;

                ModelPath modelPathout
                    = ModelPathUtils.ConvertUserVisiblePathToModelPath(new_path);
                doc.SaveAs(new_path, options);
                UIDocument uidoc2 = uiapp.OpenAndActivateDocument(FileManager.init_path);
                doc.Close(true);
            }

            return(new_path);
        }
Esempio n. 6
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            if (FilesOption())
            {
                foreach (var file in files)
                {
                    string     codeBase        = Assembly.GetExecutingAssembly().CodeBase;
                    UriBuilder uri             = new UriBuilder(codeBase);
                    string     path            = Uri.UnescapeDataString(uri.Path);
                    var        placeholderFile = Path.GetDirectoryName(path) + @"\placeholderFile.rte";

                    UIApplication uiapp = commandData.Application;
                    UIDocument    uidoc = uiapp.OpenAndActivateDocument(file);
                    Autodesk.Revit.ApplicationServices.Application app = uiapp.Application;
                    Document doc             = uidoc.Document;
                    AssetSet objlibraryAsset = app.get_Assets(AssetType.Appearance);

                    #region///判断是否为空视图,若为空视图,切换为3d视图
                    View3D view = doc.ActiveView as View3D;
                    if (null == view)
                    {
                        IEnumerable <ViewFamilyType> viewFamilyTypes = from elem in new FilteredElementCollector(doc).OfClass(typeof(ViewFamilyType))
                                                                       let type = elem as ViewFamilyType
                                                                                  where type.ViewFamily == ViewFamily.ThreeDimensional
                                                                                  select type;
                        Transaction ts = new Transaction(doc, "Change3D");
                        try
                        {
                            ts.Start();
                            XYZ    direction = new XYZ(-1, 1, -1);
                            View3D view3D    = View3D.CreateIsometric(doc, viewFamilyTypes.First().Id);
                            //View3D view3D = uiDoc.Document.Create.NewView3D(new XYZ(-1, 1, -1));//斜视45度
                            ts.Commit();
                            //切换视图必须在事务结束后,否则会提示错误:
                            //Cannot change the active view of a modifiable document
                            uidoc.ActiveView = view3D;
                        }
                        catch (Exception ex)
                        {
                            TaskDialog.Show("ex", ex.ToString());
                            ts.RollBack();
                        }
                        //Util.ErrorMsg("You must be in a 3D view to export.");
                    }
                    #endregion

                    ExportView3D(doc.ActiveView as View3D, CreatFilePath(doc), objlibraryAsset);

                    //通过占位文件关闭当前文件
                    var docPlaceholder = commandData.Application.OpenAndActivateDocument(placeholderFile);
                    doc.Close(false);
                }
                MessageBox.Show("导出成功!", "通知");
            }
            return(Result.Succeeded);
        }
        /// <summary>
        /// Creates a project based a on a template chosen by the user
        /// </summary>
        /// <param name="uiApp">Current UIApplication</param>
        /// <returns>The document chosen by the user</returns>
        public static Document CreateFromTemplate(this UIApplication uiApp)
        {
            _uiApplication = uiApp;
            // prompt user to pick the template
            TaskDialogResult tdr = Choose();

            SetDocumentOpenOptions();

            UIDocument uidoc = null;

            // Based on the selection in the task dialog, choose the appropiate template
            #region Possible Disciplines (still need one for tech)
            switch (tdr)
            {
            case (TaskDialogResult.CommandLink1):
                return(uiApp.OpenAndActivateDocument(
                           ModelPathUtils.ConvertUserVisiblePathToModelPath(TemplateDiscipline.Electrical.GetStringValue()),
                           _openOptions,
                           false).Document);

            case (TaskDialogResult.CommandLink2):
                return(uiApp.OpenAndActivateDocument(
                           ModelPathUtils.ConvertUserVisiblePathToModelPath(TemplateDiscipline.Mechanical.GetStringValue()),
                           _openOptions,
                           false).Document);

            case (TaskDialogResult.CommandLink3):
                return(uiApp.OpenAndActivateDocument(
                           ModelPathUtils.ConvertUserVisiblePathToModelPath(TemplateDiscipline.PlumbingFireProtection.GetStringValue()),
                           _openOptions,
                           false).Document);

            case (TaskDialogResult.CommandLink4):
                return(uiApp.OpenAndActivateDocument(
                           ModelPathUtils.ConvertUserVisiblePathToModelPath(TemplateDiscipline.All.GetStringValue()),
                           _openOptions,
                           false).Document);

            default:
                return(null);
            }
            #endregion
        }
Esempio n. 8
0
        public static void ExportViewsProcessLoopNew(
            UIApplication uiapp, string source_path,
            List <List <string> > category_colors, string target_folder)
        {
            Application app = uiapp.Application;

            //copy from server
            string moved_path = FileManager.MoveAndRecord(source_path);

            moved_path = ReviFileManager.saveNewCentral(app, source_path, moved_path);

            //open and activate
            UIDocument uidoc = uiapp.OpenAndActivateDocument(moved_path);
            Document   doc   = uidoc.Document;

            JpegsFromSheets(doc, target_folder, category_colors);
            UIDocument uidoc2 = uiapp.OpenAndActivateDocument(init_path);

            doc.Close(false);
        }
Esempio n. 9
0
        public void RunBeforeTest(UIApplication uiApplication)
        {
            string versionName = uiApplication.Application.VersionName.Replace("Autodesk Revit ", "");

            string     path       = $"G:\\My Drive\\05 - Travail\\Revit Dev\\AlignTag\\Test Models\\AlignTestModel_{versionName}.rvt";
            UIDocument uIDocument = uiApplication.OpenAndActivateDocument(path);

            document = uIDocument.Document;
            Console.WriteLine($"Run 'SetUp' in {GetType().Name}");
            Console.WriteLine($"Open the AlignTestModel_{versionName} model.");
        }
Esempio n. 10
0
        /// <summary>
        /// Saves front model by front end.
        /// </summary>
        /// <param name="uiapp"></param>
        /// <param name="blankPath"></param>
        public static void SaveRevit(this UIApplication uiapp, string blankPath)
        {
            var doc        = uiapp.ActiveUIDocument.Document;
            var saveOption = new SaveOptions {
                Compact = true
            };

            doc.Save(saveOption);
            uiapp.OpenAndActivateDocument(blankPath);
            doc.Close(true);
        }
Esempio n. 11
0
 /// <summary>
 ///   Metodo che apre il file selezionato
 /// </summary>
 /// <remarks>
 /// </remarks>
 /// <param name="uiapp">L'oggetto Applicazione di Revit</param>m>
 ///
 private void OpenFile(UIApplication uiapp, string fullPath)
 {
     if (!File.Exists(fullPath))
     {
         TaskDialog.Show("Carica il file .rfa", "Non trovo il file " + fullPath);
     }
     else
     {
         if (uiapp.ActiveUIDocument == null)
         {
             uiapp.OpenAndActivateDocument(fullPath);
         }
         if (File.Exists(_pathOld) && _pathOld == fullPath && uiapp.ActiveUIDocument.Document.PathName.Contains(".rfa"))   // Se il file è lo stesso ed e .rfa, lo salva con un nuovo percorso, lo chiude e apre il nuovo
         {
             // Cattura il vecchio documento, salva con nome il vecchio, apre il nuovo, chiude quello vecchio
             string newFile = fullPath;
             // Cattura il vecchio
             Document doc = uiapp.ActiveUIDocument.Document;
             // Salva il vecchio
             string pathName = Path.GetFileName(_pathOld);
             string tempPath = _dirpath + "\\" + pathName;
             doc.SaveAs(tempPath);
             // Apre il nuovo
             uiapp.OpenAndActivateDocument(newFile);
             // chiude il vecchio
             doc.Close(false);
         }
         else if (File.Exists(_pathOld) && uiapp.ActiveUIDocument.Document.PathName.Contains(".rfa"))   // Chiude il file aperto precedentemente, se ha un percorso terminante con .rfa
         {
             // Apre il nuovo documento e chiude quello vecchio
             string   newFile = fullPath;
             Document doc     = uiapp.ActiveUIDocument.Document;
             uiapp.OpenAndActivateDocument(newFile);
             doc.Close(false);
         }
         else
         {
             uiapp.OpenAndActivateDocument(fullPath);
         }
     }
 }
Esempio n. 12
0
        public void saveWorksharedFile(UIApplication uiapp, Document NewDoc, string savedProject)
        {
            SaveAsOptions            options   = new SaveAsOptions();
            WorksharingSaveAsOptions wsOptions = new WorksharingSaveAsOptions();

            wsOptions.SaveAsCentral = true;
            options.SetWorksharingOptions(wsOptions);
            options.OverwriteExistingFile = true;
            NewDoc.SaveAs(savedProject, options);
            //NewDoc.Close();
            uiapp.OpenAndActivateDocument(savedProject);
        }
Esempio n. 13
0
 //--------------------------------------------------------------------------------------------------------------------------------------------------------------
 private void Open_File(object sender, MouseButtonEventArgs e)
 {
     try
     {
         data_file item = (data_file)thong_tin_file.SelectedItem;
         if (item != null)
         {
             uiapp.OpenAndActivateDocument(item.path);
         }
     }
     catch (Exception)
     {
     }
 }
Esempio n. 14
0
        void binding_Executed(object sender, Autodesk.Revit.UI.Events.ExecutedEventArgs e)
        {
            UIApplication uiApp = sender as UIApplication;

            if (uiApp == null)
            {
                return;
            }

            String famTemplatePath            = uiApp.Application.FamilyTemplatePath;
            String conceptualmassTemplatePath = famTemplatePath + @"\Conceptual Mass\Mass.rft";

            if (System.IO.File.Exists(conceptualmassTemplatePath))
            {
                //uiApp.OpenAndActivateDocument(conceptualmassTemplatePath);
                Document familyDocument = uiApp.Application.NewFamilyDocument(conceptualmassTemplatePath);
                if (null == familyDocument)
                {
                    throw new Exception("Cannot open family document");
                }

                String fileName = Guid.NewGuid().ToString() + ".rfa";
                familyDocument.SaveAs(fileName);
                familyDocument.Close();

                uiApp.OpenAndActivateDocument(fileName);

                FilteredElementCollector collector = new FilteredElementCollector(uiApp.ActiveUIDocument.Document);
                collector = collector.OfClass(typeof(View3D));

                var query = from element in collector

                            where element.Name == "{3D}"

                            select element; // Linq query

                List <Autodesk.Revit.DB.Element> views = query.ToList <Autodesk.Revit.DB.Element>();

                View3D view3D = views[0] as View3D;
                if (view3D != null)
                {
                    uiApp.ActiveUIDocument.ActiveView = view3D;
                }
            }
        }
Esempio n. 15
0
        public static void OpenDocument(string docPath)
        {
            UIApplication uiapp  = Helper.UIApplication;
            Application   app    = Helper.Application;
            Document      oldDoc = uiapp.ActiveUIDocument.Document;

            //if (docPath.EndsWith("rte"))
            //{
            //Document doc = app.NewProjectTemplateDocument(docPath);
            //}
            //else
            //{
            uiapp.OpenAndActivateDocument(docPath);
            //}
            if (oldDoc != null)
            {
                oldDoc.Close(false);
            }
        }
Esempio n. 16
0
        /// <summary>
        ///     Closes the document safely.
        /// </summary>
        /// <param name="doc"></param>
        /// <param name="uiapp"></param>
        /// <param name="tmpRvt"></param>
        /// <param name="saveModified"></param>
        public static void SafelyClose(this Document doc, UIApplication uiapp, string tmpRvt, bool saveModified = true)
        {
            if (doc is null)
            {
                throw new ArgumentNullException(nameof(doc));
            }

            if (uiapp is null)
            {
                throw new ArgumentNullException(nameof(uiapp));
            }

            if (tmpRvt is null)
            {
                throw new ArgumentNullException(nameof(tmpRvt));
            }

            if (Equals(uiapp.ActiveUIDocument.Document, doc))
            {
                var modelPath = new FilePath(tmpRvt);

                var opt = new OpenOptions();

                uiapp.OpenAndActivateDocument(modelPath, opt, false);
            }

            // Before closing active document, must open another a document and active it.
            if (saveModified)
            {
                if (string.IsNullOrWhiteSpace(doc.PathName))
                {
                    throw new Exception("The document file doesn't exist, please save it!");
                }

                doc.Close(true);
            }

            else
            {
                doc.Close(false);
            }
        }
Esempio n. 17
0
        /// <summary>
        /// Method to open family for editing.
        /// </summary>
        /// <param name="app">Current UI Application.</param>
        public void EditFamily(UIApplication app)
        {
            var doc = app.ActiveUIDocument.Document;

            if (doc == null || doc.IsFamilyDocument)
            {
                return;
            }

            var family = new FilteredElementCollector(doc).OfClass(typeof(Family)).FirstOrDefault(x => x.Id.IntegerValue == FamilyItem.ElementId);

            if (family == null)
            {
                return;
            }

            var    famDoc = doc.EditFamily((Family)family);
            string filePath;
            var    storedPath = famDoc.PathName;

            if (File.Exists(storedPath))
            {
                filePath = storedPath;
            }
            else
            {
                var myDocPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
                filePath = Path.Combine(myDocPath, famDoc.Title);
                if (File.Exists(filePath))
                {
                    File.Delete(filePath);
                }
                famDoc.SaveAs(filePath);
            }

            famDoc.Close(false);
            app.OpenAndActivateDocument(
                ModelPathUtils.ConvertUserVisiblePathToModelPath(filePath),
                new OpenOptions(),
                false);
        }
Esempio n. 18
0
        /// <summary>
        ///     Saves front model by front end.
        /// </summary>
        /// <param name="uiapp"></param>
        /// <param name="blankPath"></param>
        public static void SaveRevit(this UIApplication uiapp, string blankPath)
        {
            if (uiapp == null)
            {
                throw new ArgumentNullException(nameof(uiapp));
            }

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

            var doc        = uiapp.ActiveUIDocument.Document;
            var saveOption = new SaveOptions {
                Compact = true
            };

            doc.Save(saveOption);
            uiapp.OpenAndActivateDocument(blankPath);
            doc.Close(true);
        }
Esempio n. 19
0
        void OnApplicationInitialized(
            object sender,
            ApplicationInitializedEventArgs e)
        {
            // This does not work, because the sender is
            // an Application instance, not UIApplication.

            //UIApplication uiapp = sender as UIApplication;

            // Sender is an Application instance:

            Application app = sender as Application;

            // However, UIApplication can be
            // instantiated from Application.

            UIApplication uiapp = new UIApplication(app);

            uiapp.OpenAndActivateDocument(
                _test_project_filepath);
        }
        void needsCollaboration(Object sender)
        {
            if (current != null)
            {
                Autodesk.Revit.ApplicationServices.Application app = sender as Autodesk.Revit.ApplicationServices.Application;
                UIApplication uiapp = new UIApplication(app);

                var filter = Builders <BsonDocument> .Filter.Eq("_id", current["_id"]);

                var update = Builders <BsonDocument> .Update.Set("is_running", true);

                collection.UpdateOne(filter, update);

                uiapp.OpenAndActivateDocument(_test_project_filepath);

                RevitCommandId closeDoc = RevitCommandId.LookupPostableCommandId(PostableCommand.Close);
                uiapp.PostCommand(closeDoc);
            }
            else
            {
                closeRevit();
            }
        }
Esempio n. 21
0
        public static ExternalEvent LibraryAction(UIApplication revit)
        {
            // get the UIApplication object, which opens the Revit API for you...
            UIDocument  uidoc = revit.ActiveUIDocument;
            Document    doc   = revit.ActiveUIDocument.Document;
            Transaction trans = new Transaction(revit.ActiveUIDocument.Document, "Part Library");

            if (MessageHandler.LibraryToAppActions.Count > 0)
            {
                string action = MessageHandler.LibraryToAppActions.Dequeue();
                //MessageBox.Show(action);
                Dictionary <string, string> actionD = JsonConvert.DeserializeObject <Dictionary <string, string> >(action);

                //####################################################
                //#"Start" the transaction
                //trans.Start();
                if (actionD["option"] == "OPEN")
                {
                    try
                    {
                        ElementId     pElementId;
                        List <string> files = Directory.GetFiles(actionD["hyperlink"]).ToList();
                        string        rfa   = "";
                        string        dwg   = "";
                        foreach (string file in files)
                        {
                            if (file.Contains(".rfa"))
                            {
                                rfa = file;
                            }
                            else if (file.Contains(".dwg"))
                            {
                                dwg = file;
                            }
                            else
                            {
                            }
                        }
                        if (rfa != "")
                        {
                            try
                            {
                                revit.OpenAndActivateDocument(rfa);
                            }
                            catch (Exception ex)
                            {
                                MessageBox.Show(ex.Message);
                            }
                        }
                        else if (dwg != "")
                        {
                            Document                 famDoc          = revit.Application.NewFamilyDocument(doc.Application.FamilyTemplatePath + "\\Detail Item.rft");
                            DWGImportOptions         dwgImportOption = new DWGImportOptions();
                            FilteredElementCollector col             = new FilteredElementCollector(famDoc).OfCategory(BuiltInCategory.OST_Views);
                            Autodesk.Revit.DB.View   view            = col.First() as Autodesk.Revit.DB.View;
                            Transaction              famTrans        = new Transaction(famDoc, "Import CAD");
                            famTrans.Start();
                            famDoc.Import(dwg, dwgImportOption, view, out pElementId);
                            famTrans.Commit();

                            SaveAsOptions saveOpt        = new SaveAsOptions();
                            string        familyfilename = dwg.Remove(dwg.Length - 4, 4) + ".rfa";
                            famDoc.SaveAs(familyfilename, saveOpt);
                            famDoc.Close();
                            revit.Application.OpenDocumentFile(familyfilename);
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                    }
                }
                else if (actionD["option"] == "LOAD")
                {
                    try
                    {
                        ElementId     pElementId;
                        List <string> files = Directory.GetFiles(actionD["hyperlink"]).ToList();
                        string        rfa   = "";
                        string        dwg   = "";
                        foreach (string file in files)
                        {
                            if (file.Contains(".rfa"))
                            {
                                rfa = file;
                            }
                            else if (file.Contains(".dwg"))
                            {
                                dwg = file;
                            }
                            else
                            {
                            }
                        }
                        if (rfa != "")
                        {
                            Transaction famLoad = new Transaction(doc, "Load Family");
                            famLoad.Start();
                            doc.LoadFamily(rfa);
                            famLoad.Commit();
                        }
                        else if (dwg != "")
                        {
                            Document                 famDoc          = revit.Application.NewFamilyDocument(doc.Application.FamilyTemplatePath + "\\Detail Item.rft");
                            DWGImportOptions         dwgImportOption = new DWGImportOptions();
                            FilteredElementCollector col             = new FilteredElementCollector(famDoc).OfCategory(BuiltInCategory.OST_Views);
                            Autodesk.Revit.DB.View   view            = col.First() as Autodesk.Revit.DB.View;
                            Transaction              famTrans        = new Transaction(famDoc, "Import CAD");
                            famTrans.Start();
                            famDoc.Import(dwg, dwgImportOption, view, out pElementId);
                            famTrans.Commit();

                            SaveAsOptions saveOpt        = new SaveAsOptions();
                            string        familyfilename = dwg.Remove(dwg.Length - 4, 4) + ".rfa";
                            famDoc.SaveAs(familyfilename, saveOpt);
                            famDoc.Close();

                            Transaction famLoad = new Transaction(doc, "Load Family");
                            famLoad.Start();
                            doc.LoadFamily(familyfilename);
                            famLoad.Commit();
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                    }
                }
                else if (actionD["option"] == "VIEW")
                {
                    try
                    {
                        ElementId     pElementId;
                        List <string> files = Directory.GetFiles(actionD["hyperlink"]).ToList();
                        string        rfa   = "";
                        string        dwg   = "";
                        foreach (string file in files)
                        {
                            if (file.Contains(".dwg"))
                            {
                                dwg = file;
                            }
                            else
                            {
                            }
                        }
                        if (dwg != "")
                        {
                            string  progId = "AutoCAD.Application";
                            dynamic cadApp = null;


                            try
                            {
                                cadApp = Marshal.GetActiveObject(progId);
                            }
                            catch
                            {
                                try
                                {
                                    Type t = Type.GetTypeFromProgID(progId);
                                    cadApp = Activator.CreateInstance(t);
                                }
                                catch
                                {
                                }
                            }

                            if (cadApp != null)
                            {
                                dynamic cadFile = cadApp.Documents.Open(dwg, false);
                                cadApp.Visible = true;
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                    }
                }

                //# "End" the transaction
                //trans.Commit();
                //####################################################

                // do your Revit tasks here
                //MessageBox.Show("Text received from the Library window: " + actionD);

                // reply something back
                MessageHandler.AppToLibraryActions.Enqueue("A message from the Revit plugin - " + DateTime.Now.ToString());
            }

            return(m_ExEvent);
        }
Esempio n. 22
0
        /// <summary>
        /// Method designed to directly load a family into a project using only a family symbol
        /// </summary>
        /// <param name="curdoc"></param>
        /// <param name="famsym"></param>
        /// <param name="cmd">External Command Data from the current command</param>
        /// <param name="doctoloadfrom">Document the family symbol should be loaded from</param>
        public static FamilySymbol LoadFamilyDirect(this Document curdoc, FamilySymbol famsym, Document doctoloadfrom, ExternalCommandData cmd)
        {
            Family newfamily = null;

            // grab the application and change the active document
            using (UIApplication uiapp = cmd.Application)
            {
                OpenOptions oop = new OpenOptions();

                oop.AllowOpeningLocalByWrongUser = true;
                oop.DetachFromCentralOption      = DetachFromCentralOption.DetachAndPreserveWorksets;

                // open "doctoloadfrom" (linked doc) and make it the active document
                if (uiapp.ActiveUIDocument.Document != doctoloadfrom)
                {
                    // try opening the document from memory only
                    try
                    {
                        Document newcurdoc = curdoc.Application.OpenDocumentFile(ModelPathUtils.ConvertUserVisiblePathToModelPath(doctoloadfrom.PathName), oop);
                    }

                    // was unable to open the document for some reason
                    catch
                    {
                        uiapp.OpenAndActivateDocument(ModelPathUtils.ConvertUserVisiblePathToModelPath(doctoloadfrom.PathName), oop, false);
                        throw new Exception("Failed in attempt to open file. File name is:" + doctoloadfrom.PathName);
                    }
                }

                // open the family document
                newfamily = famsym.Family;
                using (Document doc_family = doctoloadfrom.EditFamily(newfamily))
                {
                    // load it into the original document
                    doc_family.LoadFamily(curdoc);

                    // close the family once done
                    doc_family.Close(false);
                    //doctoloadfrom.Close(true);
                }

                // return control to the original active document
                // could create possible bug - write a method to both
                // move to another current document
                // close all but current document
                if (uiapp.ActiveUIDocument.Document != curdoc)
                {
                    while (uiapp.ActiveUIDocument.Document != curdoc)
                    {
                        uiapp.ActiveUIDocument.Document.Close(false);
                    }
                }

                using (Transaction tr_regen = new Transaction(curdoc, "Regenerating the document..."))
                {
                    tr_regen.Start();

                    // regenerate that document
                    curdoc.Regenerate();
                    tr_regen.Commit();
                }
            }

            return(famsym);
        }
        public static void BUYLStartNewProject(UIApplication app, BUYLTools.Utils.Countries country)
        {
            if (BUYLTools.ContentLoader.GitContentLoader.CheckForContentRepositoryDirectory())
            {
                if (app != null)
                {
                    Document doc = null;

                    switch (country)
                    {
                        case BUYLTools.Utils.Countries.DECH:
                            if (File.Exists(BUYLTools.ContentLoader.GitContentLoader.GetDECHTemplateFile(app.Application.VersionNumber)))
                                doc = app.Application.NewProjectDocument(BUYLTools.ContentLoader.GitContentLoader.GetDECHTemplateFile(app.Application.VersionNumber));
                            else
                                MessageBox.Show("Templatefile {0} not found!", BUYLTools.ContentLoader.GitContentLoader.GetDECHTemplateFile(app.Application.VersionNumber));
                            break;
                        case BUYLTools.Utils.Countries.DEDE:
                            if (File.Exists(BUYLTools.ContentLoader.GitContentLoader.GetDEDETemplateFile(app.Application.VersionNumber)))
                                doc = app.Application.NewProjectDocument(BUYLTools.ContentLoader.GitContentLoader.GetDEDETemplateFile(app.Application.VersionNumber));
                            else
                                MessageBox.Show("Templatefile {0} not found!", BUYLTools.ContentLoader.GitContentLoader.GetDEDETemplateFile(app.Application.VersionNumber));
                            break;
                        default:
                            doc = null;
                            break;
                    }

                    if (doc != null)
                    {
                        SaveFileDialog dlg = new SaveFileDialog();
                        dlg.Filter = "Revit project files (*.rvt)|*.rvt";
                        if (dlg.ShowDialog() == DialogResult.OK)
                        {
                            SaveAsOptions op = new SaveAsOptions() { OverwriteExistingFile = false };
                            if (File.Exists(dlg.FileName))
                            {
                                if (MessageBox.Show("The model alreaddy exists and will be overriden!", "Model Creation", MessageBoxButtons.YesNo) == DialogResult.Yes)
                                    op.OverwriteExistingFile = true;
                                else
                                    op.OverwriteExistingFile = false;
                            }

                            doc.SaveAs(dlg.FileName, op);
                            app.OpenAndActivateDocument(dlg.FileName);
                        }
                    }
                }
            }
        }
Esempio n. 24
0
        /// <summary>
        /// Toggle back and forth between two different documents
        /// </summary>
        void ToggleViews(
            View view1,
            string filepath2)
        {
            Document      doc   = view1.Document;
            UIDocument    uidoc = new UIDocument(doc);
            Application   app   = doc.Application;
            UIApplication uiapp = new UIApplication(app);

            // Select some elements in the first document

            ICollection <ElementId> idsView1
                = new FilteredElementCollector(doc, view1.Id)
                  .WhereElementIsNotElementType()
                  .ToElementIds();

            // Open the second file

            UIDocument uidoc2 = uiapp
                                .OpenAndActivateDocument(filepath2);

            Document doc2 = uidoc2.Document;

            // Do something in second file

            using (Transaction tx = new Transaction(doc2))
            {
                tx.Start("Change Scale");
                doc2.ActiveView.get_Parameter(
                    BuiltInParameter.VIEW_SCALE_PULLDOWN_METRIC)
                .Set(20);
                tx.Commit();
            }

            // Save modified second file

            SaveAsOptions opt = new SaveAsOptions
            {
                OverwriteExistingFile = true
            };

            doc2.SaveAs(filepath2, opt);

            // Switch back to original file;
            // in a new file, doc.PathName is empty

            if (!string.IsNullOrEmpty(doc.PathName))
            {
                uiapp.OpenAndActivateDocument(
                    doc.PathName);

                doc2.Close(false); // no problem here, says Remy
            }
            else
            {
                // Avoid using OpenAndActivateDocument

                uidoc.ShowElements(idsView1);
                uidoc.RefreshActiveView();

                //doc2.Close( false ); // Remy says: Revit throws the exception and doesn't close the file
            }
        }
Esempio n. 25
0
        private static void ViewToDxf(UIApplication uiapp, string source_path,
                                      string target_folder)
        {
            Application app = uiapp.Application;
            //copy from server
            string moved_path = FileManager.MoveAndRecord(source_path);

            moved_path = ReviFileManager.saveNewCentral(app, source_path, moved_path);

            //open and activate
            UIDocument uidoc = uiapp.OpenAndActivateDocument(moved_path);

            Document doc = uidoc.Document;
            //uiapp.DialogBoxShowing += new EventHandler<DialogBoxShowingEventArgs>(OnDialogBoxShowing);

            DXFExportOptions opt  = new DXFExportOptions();
            var dwgSettingsFilter = new ElementClassFilter(typeof(ExportDWGSettings));

            var fc = new FilteredElementCollector(doc)
                     .WherePasses(dwgSettingsFilter);

            foreach (ExportDWGSettings element in fc)
            {
                var options    = element.GetDWGExportOptions();
                var layerTable = options.GetExportLayerTable();
                foreach (var layerItem in layerTable)
                {
                    var layerInfo = layerItem.Value;
                    //layerItem.
                    if (layerInfo.CategoryType == LayerCategoryType.Model)
                    {
                        layerInfo.ClearCutLayerModifiers();
                        // layerInfo.LayerName =

                        var modifiers = layerInfo.GetLayerModifiers();
                        foreach (var modifier in modifiers)
                        {
                            // get modifier type
                            var modifierType = modifier.ModifierType;
                            // get separator
                            var separater = modifier.Separator;
                        }
                    }
                }
            }
            //string filename;

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

                // foreach (ElementId id in ids)
                // {
                //  Element e = doc.GetElement(id);

                // . . .

                // view.IsolateElementTemporary(partId);

                // doc.Export(target_folder, filename, viewIds, opt);
                // }

                // We do not commit the transaction, because
                // we do not want any modifications saved.
                // The transaction is only created and started
                // because it is required by the
                // IsolateElementTemporary method.
                // Since the transaction is not committed,
                // the changes are automatically discarded.

                tx.Commit();
            }
        }
Esempio n. 26
0
        public static Tuple <string, bool> base_name_for_Export(UIApplication uiapp,
                                                                string source_path)
        {
            StringBuilder sb  = new StringBuilder();
            Application   app = uiapp.Application;
            string        final_hashed_base_name = "";
            bool          continueproc           = true;
            //create base hash and folder name
            string target_hashed_folder = Helper.AndHash(source_path)
                                          + Path.GetFileNameWithoutExtension(source_path);

            //string target_hashed_folder = Path.GetDirectoryName(tmp);

            // TaskDialog.Show("x", target_hashed_folder + " ");

            string rvt_base_name     = Path.GetFileNameWithoutExtension(source_path);
            string moved_rvt_path    = FileManager.model_path + target_hashed_folder + ".rvt";
            string moved_folder_path = FileManager.export_location + target_hashed_folder;

            bool rvt_exists_at_start    = File.Exists(moved_rvt_path);
            bool folder_exists_at_start = File.Exists(moved_folder_path);

            if (rvt_exists_at_start == false)
            {
                sb.AppendLine("RVT already exists " + rvt_exists_at_start.ToString());
                //check if exists by existing folder
                var mathing_DirsByBaseName = Directory.EnumerateDirectories(FileManager.export_location, "*" + rvt_base_name);
                //if the folder exists, does ---shell exsist?

                if (mathing_DirsByBaseName.Count() > 1)
                {
                    string temp_file_path = FileManager.MoveAndRecord(source_path);
                    sb.AppendLine("copying temp file and checking for sheet matches: " + temp_file_path);
                    OpenOptions op = new OpenOptions();
                    op.DetachFromCentralOption = DetachFromCentralOption.DetachAndDiscardWorksets;
                    ModelPath mp =
                        ModelPathUtils.ConvertUserVisiblePathToModelPath(
                            temp_file_path);
                    UIDocument uidoc = uiapp.OpenAndActivateDocument(mp, op, false);
                    Document   doc   = uidoc.Document;
                    //doc.Save();
                    SaveAsOptions options = new SaveAsOptions();


                    options.OverwriteExistingFile = true;
                    options.MaximumBackups        = 1;

                    doc.SaveAs(temp_file_path, options);

                    List <ViewSheet> AllSheets = Helper.GetAllSheets(doc);
                    if (AllSheets.Count() > 0)
                    {
                        sb.AppendLine("POssible matches exist : " + mathing_DirsByBaseName.Count().ToString());
                        bool found_match_in_possible_dirs = false;

                        foreach (var possible_dir in mathing_DirsByBaseName)
                        {
                            var sheet_strings = AllSheets.Select(x => x.ViewName + " - Sheet - " + x.SheetNumber);
                            var sheet_files   = Directory.GetFiles(possible_dir);

                            bool all_sheets_present = true;
                            foreach (string sheet_string in sheet_strings)
                            {
                                var cl = sheet_strings.Where(x => x.Contains(sheet_string)).Count();
                                if (cl == 0)
                                {
                                    all_sheets_present = false;
                                    break;
                                }
                            }
                            if (all_sheets_present == true)
                            {
                                final_hashed_base_name       = Path.GetFileName(possible_dir);
                                found_match_in_possible_dirs = true;
                            }
                        }
                        if (found_match_in_possible_dirs == false)
                        {
                            sb.AppendLine("Matches do did not have same sheets");
                            final_hashed_base_name = Helper.ConsHash(source_path) + rvt_base_name;
                            continueproc           = true;


                            UIDocument uidoc2 = uiapp.OpenAndActivateDocument(FileManager.init_path);
                            doc.Close();

                            saveCentralProd(uiapp, temp_file_path, final_hashed_base_name);
                        }
                        else
                        {
                            sb.AppendLine("Match found with same sheets");
                            // final_hashed_base_name = Helper.ConsHash(source_path) + rvt_base_name;

                            UIDocument uidoc2 = uiapp.OpenAndActivateDocument(FileManager.init_path);
                            doc.Close();
                        }
                    }
                    else
                    {
                        final_hashed_base_name = Helper.ConsHash(source_path) + rvt_base_name;
                        sb.AppendLine("No Sheets found...");
                        saveCentralProd(uiapp, temp_file_path, final_hashed_base_name);
                        continueproc = false;
                    }
                }
                else if (mathing_DirsByBaseName.Count() == 1)
                {
                    final_hashed_base_name = Path.GetFileName(mathing_DirsByBaseName.First());
                }
                else
                {
                    //if no directory is found with the base_name - this was never exported...
                    // use good hash,
                    sb.AppendLine("No Directory found creating new...");
                    final_hashed_base_name = Helper.ConsHash(source_path) + rvt_base_name;
                }
            }
            else
            {
                //if folder is present, then it is base folder
                sb.AppendLine("Directory Exists " + final_hashed_base_name);
                final_hashed_base_name = Path.GetFileName(moved_folder_path);
            }

            sb.AppendLine();
            //TaskDialog.Show("d", FileManager.export_location + final_hashed_base_name);
            string final_dir_path = FileManager.mkdir(FileManager.export_location + final_hashed_base_name);

            File.AppendAllText(final_dir_path + "\\log.txt", sb.ToString());


            return(new Tuple <string, bool>(final_hashed_base_name, continueproc));
        }
Esempio n. 27
0
    public Result Execute(
        ExternalCommandData commandData,
        ref string message,
        ElementSet elements)
    {
        UIApplication uiApp = commandData.Application;

        string      keystr    = @"Software\FamilyToDWG";
        string      revityear = "2017";
        string      subkeystr = "TemplateLocation" + revityear;
        RegistryKey key       = Registry.CurrentUser.OpenSubKey(keystr, true);

        if (key == null)
        {
            key = Registry.CurrentUser.CreateSubKey(keystr);
            key.SetValue(subkeystr, "");
        }

        if (key.GetValue(subkeystr, null).ToString() == "" || File.Exists(key.GetValue(subkeystr).ToString()) == false)
        {
            var templateFD = new OpenFileDialog();
            templateFD.Filter = "rte files (*.rte)|*.rte";
            templateFD.Title  = "Choose a Template";
            templateFD.ShowDialog();
            string docdir = templateFD.FileName;
            key.SetValue(subkeystr, @docdir);
        }

        if (key.GetValue(subkeystr, null).ToString() == null)
        {
            return(Result.Failed);
        }

        Autodesk.Revit.DB.Document uiDoc;

        try
        {
            uiDoc = uiApp.Application.NewProjectDocument(key.GetValue(subkeystr).ToString());
        }
        catch
        {
            return(Result.Failed);
        }

        if (uiDoc == null)
        {
            return(Result.Failed);
        }

        if (!Directory.Exists(@"C:\temp\"))
        {
            Directory.CreateDirectory(@"C:\temp\");
        }

        if (File.Exists(@"C:\temp\new_project.rvt"))
        {
            File.Delete(@"C:\temp\new_project.rvt");
        }

        SaveAsOptions options1 = new SaveAsOptions();

        options1.OverwriteExistingFile = true;
        uiDoc.SaveAs(@"C:/temp/new_project.rvt", options1);

        uiApp.OpenAndActivateDocument(@"C:/temp/new_project.rvt");

        var FD = new OpenFileDialog();

        FD.Filter = "rfa files (*.rfa)|*.rfa";
        FD.Title  = "Choose A RevitRFA Family file";
        FD.ShowDialog();

        string filename = FD.SafeFileName;
        string filedir  = FD.FileName.Replace(filename, "");

        if (File.Exists(FD.FileName))
        {
            using (Transaction tx = new Transaction(uiDoc))
            {
                tx.Start("Load Family");
                Autodesk.Revit.DB.Family family = null;
                uiDoc.LoadFamily(FD.FileName, out family);
                tx.Commit();

                string name = family.Name;
                foreach (ElementId id in family.GetFamilySymbolIds())
                {
                    FamilySymbol famsymbol = family.Document.GetElement(id) as FamilySymbol;
                    XYZ          origin    = new XYZ(0, 0, 0);
                    tx.Start("Load Family Member");
                    famsymbol.Activate();
                    FamilyInstance instance = uiDoc.Create.NewFamilyInstance(origin, famsymbol, StructuralType.NonStructural);
                    tx.Commit();

                    DWGExportOptions options = new DWGExportOptions();
                    options.FileVersion             = ACADVersion.R2007;
                    options.ExportOfSolids          = SolidGeometry.ACIS;
                    options.HideUnreferenceViewTags = true;
                    //options.FileVersion = (ACADVersion)(3);

                    var collector = new FilteredElementCollector(uiDoc);

                    var viewFamilyType = collector
                                         .OfClass(typeof(ViewFamilyType))
                                         .OfType <ViewFamilyType>()
                                         .FirstOrDefault(x => x.ViewFamily == ViewFamily.ThreeDimensional);

                    // Export the active view
                    ICollection <ElementId> views = new List <ElementId>();
                    tx.Start("ChangeView");
                    View3D view = View3D.CreateIsometric(uiDoc, viewFamilyType.Id);
                    view.DisplayStyle = DisplayStyle.Shading;
                    tx.Commit();
                    views.Add(view.Id);
                    string dwgfilename     = famsymbol.Name + ".dwg";
                    string dwgfullfilename = filedir + dwgfilename;
                    if (File.Exists(dwgfullfilename))
                    {
                        File.Delete(dwgfullfilename);
                    }
                    uiDoc.Export(@filedir, @dwgfilename, views, options);

                    tx.Start("Delete Family Member");
                    uiDoc.Delete(instance.Id);
                    tx.Commit();
                }
            }
        }
        else
        {
            Console.WriteLine("Please Create Export Directory For the chosen CAPS file.");
        }

        return(Result.Succeeded);
    }
Esempio n. 28
0
        public void jViewsFixer(UIApplication uiapp, string sFileName)
        {
            if (uiapp.ActiveUIDocument == null)
            {
                TaskDialog.Show("Revit", "Please open a file, any file, for this Addin work.");
                return;
            }
            Document origDoc         = uiapp.ActiveUIDocument.Document;
            var      origDocPathName = origDoc.PathName;

            uiapp.OpenAndActivateDocument(sFileName);

            using (Transaction t = new Transaction(origDoc))
            {
                t.Start("Deleting Views");
                uiapp.OpenAndActivateDocument(sFileName);
                t.Commit();
            }

            Document doc = uiapp.ActiveUIDocument.Document;

            Autodesk.Revit.DB.View currentView = doc.ActiveView;
            var vname = currentView.Name;
            var len   = vname.Length;

            if (len > 4)
            {
                if (vname.StartsWith(prefix))
                {
                    TaskDialog.Show("Revit", "The active view contains \"" + prefix + "\", cannot continue.");
                }
            }

            FilteredElementCollector viewCollector = new FilteredElementCollector(doc);

            viewCollector.OfClass(typeof(Autodesk.Revit.DB.View));
            List <ElementId> eleIds = new List <ElementId>();

            foreach (Element viewElement in viewCollector)
            {
                Autodesk.Revit.DB.View view = (Autodesk.Revit.DB.View)viewElement;
                vname = view.Name;
                len   = vname.Length;
                if (len > 4)
                {
                    if (vname.StartsWith(prefix))
                    {
                        eleIds.Add(view.Id);
                    }
                }
            }

            using (Transaction t = new Transaction(doc))
            {
                t.Start("Deleting Views");
                doc.Delete(eleIds);
                t.Commit();
            }

            FileInfo f       = new FileInfo(doc.PathName);
            var      newFile = @"C:\Temp\Revit\loopsamples_output\" + f.Name;

            if (File.Exists(newFile))
            {
                File.Delete(newFile);
            }
            doc.SaveAs(newFile);
            uiapp.OpenAndActivateDocument(origDocPathName);
            doc.Close(false); //Revit doesn't allow you to close the active document, either activate another or sendkeys //SendKeys.SendWait( "^{F4}" );
        }
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            //载入FourPlugin.dll


            UIApplication uiapp = commandData.Application;
            Document      doc   = uiapp.ActiveUIDocument.Document;

            string copyFilePath;         //储存文件夹路径
            string temFilePath;          //临时文件路径
            bool   isWorkshared;         //当前文档是否开启工作共享
            bool   enoughRAM;            //内存是否足够
            bool   enoughDiskSpace;      //储存空间是否足够
            bool   purgeUnused;          //是否清除未使用项
            bool   packageLinkingModels; //是否打包链接模型
            bool   clearLinkingModels;   //是否清除链接

            string fileFullName;

            #region 环境判断及初始化

            copyFilePath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\" + doc.Title + ".rvt";

            temFilePath     = Constants.TemFolder + @"\\temFile.rvt";
            isWorkshared    = doc.IsWorkshared;
            enoughRAM       = true;
            enoughDiskSpace = GetHardDiskFreeSpace("C") > 1.5;

            #endregion

            #region 警告
            if (!enoughRAM)
            {
                message += "内存不足,请关闭一些软件释放运行内存\r\n";
            }
            if (!enoughDiskSpace)
            {
                message += "C盘临时空间不足,请关闭一些程序释放空间\r\n";
            }

            if (string.IsNullOrEmpty(message))
            {
                return(Result.Cancelled);
            }
            #endregion

            #region 模型打包

            //分离中心文件
            if (isWorkshared)
            {
                //同步
                doc.SynchronizeWithCentral(new TransactWithCentralOptions(), new SynchronizeWithCentralOptions());
                //创建临时文件
                Document temDoc = uiapp.Application.NewProjectDocument(@"C:\ProgramData\Autodesk\RVT 2019\Templates\China\Construction-DefaultCHSCHS.rte");
                temDoc.SaveAs(temFilePath);
                temDoc.Close(false);
                uiapp.OpenAndActivateDocument(temFilePath);
                temDoc = uiapp.ActiveUIDocument.Document;
                //关闭本地文件
                string    docPathName = doc.PathName;
                ModelPath modelPath   = doc.GetWorksharingCentralModelPath();
                doc.Close(false);
                //分离模型
                OpenOptions openOptions = new OpenOptions
                {
                    DetachFromCentralOption = DetachFromCentralOption.DetachAndDiscardWorksets
                };
                Document detachDoc = uiapp.Application.OpenDocumentFile(modelPath, openOptions);
                detachDoc.SaveAs(copyFilePath);
                detachDoc.Close(true);
                //重新打开本地文件
                uiapp.OpenAndActivateDocument(docPathName);
                //清理临时文件
                temDoc.Close(false);
                File.Delete(temFilePath);
            }
            else
            {
                doc.Save();
                File.Copy(doc.PathName, copyFilePath);
            }

            #endregion

            return(Result.Succeeded);
        }
        // Method which upgrades each file
        private void Upgrade(FileInfo file, String destPath)
        {
            addInfo = false;

            // Check if file type is what is expected to be upgraded
            // or is a text file which is for files which contain
            // type information for certain family files

            if (fileTypes.Contains(file.Extension) ||
                file.Extension.Equals(".txt"))
            {
                try
                {
                    // If it is a text file

                    if (file.Extension.Equals(".txt"))
                    {
                        if (fileTypes.Contains(".rfa"))
                        {
                            bool copy = false;

                            // Check each file from the list to see
                            // if the text file has the same name as
                            // any of the family files or if it is
                            // just a standalone text file. In case
                            // of standalone text file, ignore.

                            foreach (FileInfo rft in files)
                            {
                                if (
                                    rft.Name.Remove(rft.Name.Length - 4, 4).Equals(
                                        file.Name.Remove(file.Name.Length - 4, 4)) &&
                                    !(rft.Extension.Equals(file.Extension))
                                    )
                                {
                                    copy = true; break;
                                }
                            }
                            if (copy)
                            {
                                // Copy the text file into target
                                // destination

                                File.Copy(file.DirectoryName +
                                          "\\" + file.Name, destPath +
                                          "\\" + file.Name, true);
                                addInfo = true;
                            }
                        }
                    }

                    // For other file types other than text file

                    else
                    {
                        // This is the main function that opens and save
                        // a given file.

                        // Check if the file is RFT file
                        // Since we have to use OpenDocumentFile for RFT files
                        if (file.Extension.Equals(".rft"))
                        {
                            Document doc =
                                cmdData.Application.Application.OpenDocumentFile(
                                    file.FullName);

                            String destinationFile = destPath + "\\" + file.Name;

                            Transaction trans = new Transaction(doc, "T1");
                            trans.Start();
                            doc.Regenerate();
                            trans.Commit();

                            doc.SaveAs(destinationFile);
                            doc.Close();

                            addInfo = true;
                        }
                        else
                        {
                            // Open a Revit file as an active document.

                            UIApplication UIApp = cmdData.Application;
                            UIDocument    UIDoc = UIApp.OpenAndActivateDocument(file.FullName);

                            Document doc = UIDoc.Document;

                            // Try closing the previously opened document after
                            // another one is opened. We are doing this because we
                            // cannot explicitely close an active document
                            //  at a moment.

                            if (previousDocument != null)
                            {
                                previousDocument.SaveAndClose();
                            }

                            // Save the Revit file to the target destination.
                            // Since we are opening a file as an active document,
                            // it takes care of preview.

                            String destinationFile = destPath + "\\" + file.Name;
                            doc.SaveAs(destinationFile);

                            // Saving the current document to close it later.
                            // If we had a method to close an active document,
                            // we want to close it here. However, since we opened
                            // it as an active document, we cannot do so.
                            // We'll close it after the next file is opened.

                            previousDocument = UIDoc;

                            // Set variable to know if upgrade
                            // was successful - for status updates

                            addInfo = true;
                        }
                    }

                    if (addInfo)
                    {
                        String msg = " has been upgraded";

                        // Log file and user interface updates

                        lstBxUpdates.Items.Add("\n" + file.Name + msg);
                        lstBxUpdates.TopIndex = lstBxUpdates.Items.Count - 1;
                        writer.WriteLine(file.FullName + msg);
                        writer.Flush();
                        bar.PerformStep();
                        ++success;
                    }
                }
                catch (Exception ex)
                {
                    failures.Add(file.FullName
                                 + " could not be upgraded: "
                                 + ex.Message);

                    bar.PerformStep();

                    ++failed;
                }
            }
        }
Esempio n. 31
0
        public static void BUYLStartNewProject(UIApplication app, BUYLTools.Utils.Countries country)
        {
            if (BUYLTools.ContentLoader.GitContentLoader.CheckForContentRepositoryDirectory())
            {
                if (app != null)
                {
                    Document doc = null;

                    switch (country)
                    {
                    case BUYLTools.Utils.Countries.DECH:
                        if (File.Exists(BUYLTools.ContentLoader.GitContentLoader.GetDECHTemplateFile(app.Application.VersionNumber)))
                        {
                            doc = app.Application.NewProjectDocument(BUYLTools.ContentLoader.GitContentLoader.GetDECHTemplateFile(app.Application.VersionNumber));
                        }
                        else
                        {
                            MessageBox.Show("Templatefile {0} not found!", BUYLTools.ContentLoader.GitContentLoader.GetDECHTemplateFile(app.Application.VersionNumber));
                        }
                        break;

                    case BUYLTools.Utils.Countries.DEDE:
                        if (File.Exists(BUYLTools.ContentLoader.GitContentLoader.GetDEDETemplateFile(app.Application.VersionNumber)))
                        {
                            doc = app.Application.NewProjectDocument(BUYLTools.ContentLoader.GitContentLoader.GetDEDETemplateFile(app.Application.VersionNumber));
                        }
                        else
                        {
                            MessageBox.Show("Templatefile {0} not found!", BUYLTools.ContentLoader.GitContentLoader.GetDEDETemplateFile(app.Application.VersionNumber));
                        }
                        break;

                    default:
                        doc = null;
                        break;
                    }

                    if (doc != null)
                    {
                        SaveFileDialog dlg = new SaveFileDialog();
                        dlg.Filter = "Revit project files (*.rvt)|*.rvt";
                        if (dlg.ShowDialog() == DialogResult.OK)
                        {
                            SaveAsOptions op = new SaveAsOptions()
                            {
                                OverwriteExistingFile = false
                            };
                            if (File.Exists(dlg.FileName))
                            {
                                if (MessageBox.Show("The model alreaddy exists and will be overriden!", "Model Creation", MessageBoxButtons.YesNo) == DialogResult.Yes)
                                {
                                    op.OverwriteExistingFile = true;
                                }
                                else
                                {
                                    op.OverwriteExistingFile = false;
                                }
                            }

                            doc.SaveAs(dlg.FileName, op);
                            app.OpenAndActivateDocument(dlg.FileName);
                        }
                    }
                }
            }
        }