Ejemplo n.º 1
0
        public void CreateHyparModel(DesignAutomationData data)
        {
            #if !DEBUG
            var model = ParseExecution("execution.json");
            #else
            var model = ParseExecution(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "execution.json"));
            #endif

            var beamSymbol   = GetStructuralSymbol(data.RevitDoc, BuiltInCategory.OST_StructuralFraming, "200UB25.4");
            var columnSymbol = GetStructuralSymbol(data.RevitDoc, BuiltInCategory.OST_StructuralColumns, "450 x 450mm");
            var floorType    = GetFloorType(data.RevitDoc, "Insitu Concrete");
            var fec          = new FilteredElementCollector(data.RevitDoc);
            var levels       = fec.OfClass(typeof(Level)).Cast <Level>().ToList();

            Transaction trans = new Transaction(data.RevitDoc);
            trans.Start("Hypar");

            CreateBeams(model, beamSymbol, levels, data.RevitDoc, data.RevitApp);
            CreateWalls(model, levels, data.RevitDoc, data.RevitApp);
            CreateColumns(model, columnSymbol, levels, data.RevitDoc, data.RevitApp);
            CreateFloors(model, floorType, levels, data.RevitDoc, data.RevitApp);

            trans.Commit();

            #if !DEBUG
            var path = ModelPathUtils.ConvertUserVisiblePathToModelPath($"result.rvt");
            data.RevitDoc.SaveAs(path, new SaveAsOptions());
            #else
            data.RevitDoc.SaveAs(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), $"result.rvt"));
            #endif
        }
Ejemplo n.º 2
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 }
            });
        }
Ejemplo n.º 3
0
        public void SaveDetachworksets()
        {
            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.DetachAndPreserveWorksets;
                mpathOnlyFilename           = filePath.Name;
                Document                 openedDoc = app.OpenDocumentFile(mp, opt);
                SaveAsOptions            options   = new SaveAsOptions();
                WorksharingSaveAsOptions wokrshar  = new WorksharingSaveAsOptions();
                wokrshar.SaveAsCentral = true;
                options.SetWorksharingOptions(wokrshar);
                ModelPath modelPathout = ModelPathUtils.ConvertUserVisiblePathToModelPath(mpath + "\\" + "Detached" + "_" + datetimesave + "_" + mpathOnlyFilename);
                openedDoc.SaveAs(modelPathout, options);
                openedDoc.Close(true);
            }
        }
Ejemplo n.º 4
0
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            View view = commandData.View;

            if (null == view)
            {
                message = "Please run this command in an active document.";
                return(Result.Failed);
            }
            else
            {
                Document doc = view.Document;

                ModelPath modelPath = ModelPathUtils
                                      .ConvertUserVisiblePathToModelPath(
                    doc.PathName);

                ListLinks(modelPath);

                return(Result.Succeeded);
            }
        }
        /// <summary>
        /// Loads a specified Revit link external resource.
        /// </summary>
        /// <param name="resourceReference">An ExternalResourceReference identifying which particular resource to load.</param>
        /// <param name="loadContent">An ExternalResourceLoadContent object that will be populated with load data by the
        /// server.  There are different subclasses of ExternalResourceLoadContent for different ExternalResourceTypes.</param>
        private void LoadRevitLink(ExternalResourceReference resourceReference, ExternalResourceLoadContent loadContent)
        {
            LinkLoadContent linkLoadContent = (LinkLoadContent)loadContent;

            if (linkLoadContent == null)
            {
                throw new ArgumentException("Wrong type of ExternalResourceLoadContent (expecting a LinkLoadContent) for Revit links.", "loadContent");
            }

            try
            {
                // Copy the file from the path under the server "root" folder to a secret "cache" folder on the users machine
                String fullCachedPath = GetFullLinkCachedFilePath(resourceReference);
                String cacheFolder    = System.IO.Path.GetDirectoryName(fullCachedPath);
                if (!System.IO.Directory.Exists(cacheFolder))
                {
                    System.IO.Directory.CreateDirectory(cacheFolder);
                }
                String serverLinkPath = GetFullServerLinkFilePath(resourceReference);
                System.IO.File.Copy(serverLinkPath, fullCachedPath, true); // Overwrite

                ModelPath linksPath = ModelPathUtils.ConvertUserVisiblePathToModelPath(fullCachedPath);
                linkLoadContent.SetLinkDataPath(linksPath);
                loadContent.LoadStatus = ExternalResourceLoadStatus.Success;
            }
            catch (System.Exception)
            {
            }
        }
Ejemplo n.º 6
0
        public static string saveNewCentral(
            Application app, string source_path, string temp_file_path)
        {
            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 = newpathName(source_path, temp_file_path);


            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);
                doc.Close(true);
            }

            return(new_path);
        }
Ejemplo n.º 7
0
        public void Load_Form(UIApplication uiapp, Document doc)
        {
            try
            {
                data_revit_link item = (data_revit_link)link_file.SelectedItem;
                doc.Delete(item.type.Id);

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

                List <Document> docs = new List <Document>();
                foreach (Document d in uiapp.Application.Documents)
                {
                    docs.Add(d);
                }
                item.document = docs.First(y => y.Title + ".rvt" == item.name);
                item.type     = doc.GetElement(linkType.ElementId) as RevitLinkType;
                link_file.Items.Refresh();
                MessageBox.Show(item.document.PathName);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                link_file.SelectedItem = null;
            }
        }
Ejemplo n.º 8
0
        /// <summary>
        /// This node will open the given file in the background.
        /// </summary>
        /// <param name="filePath">The file to obtain document from.</param>
        /// <param name="audit">Choose whether or not to audit the file upon opening. (Will run slower with this)</param>
        /// <param name="detachFromCentral">Choose whether or not to detach from central upon opening. Only for RVT files. </param>
        /// <returns name="document">The document object. Primarily for use with other Rhythm nodes.</returns>
        /// <search>
        /// Application.OpenDocumentFile, rhythm
        /// </search>
        public static string OpenDocumentFile(string filePath, bool audit = false, bool detachFromCentral = false)
        {
            var      uiapp = DocumentManager.Instance.CurrentUIApplication;
            var      app   = uiapp.Application;
            Document doc;
            string   docTitle = string.Empty;
            //instantiate open options for user to pick to audit or not
            OpenOptions openOpts = new OpenOptions();

            openOpts.Audit = audit;
            TransmittedModelOptions tOpt = TransmittedModelOptions.SaveAsNewCentral;

            if (detachFromCentral == false)
            {
                openOpts.DetachFromCentralOption = DetachFromCentralOption.DoNotDetach;
            }
            else
            {
                openOpts.DetachFromCentralOption = DetachFromCentralOption.DetachAndPreserveWorksets;
            }

            //convert string to model path for open
            ModelPath modelPath = ModelPathUtils.ConvertUserVisiblePathToModelPath(filePath);

            try
            {
                docTitle = DocumentUtils.OpenDocument(modelPath, openOpts);
            }
            catch (Exception)
            {
                //nothing
            }

            return(docTitle);
        }
Ejemplo n.º 9
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);
        }
Ejemplo n.º 10
0
        private void UpdateRFAinProject(Document doc)
        {
            //Load and update the family symbol instances present in the project
            //make changes to the documnet by modifying the family file
            //Open transaction
            using (Transaction updating_transaction = new Transaction(doc))
            {
                //Start the transaction
                updating_transaction.Start("UPDATE THE PROJECT");

                //FailureHandlingOptions will collect those warnings which occurs while importing the family file into the project and deletes those warning
                FailureHandlingOptions FH_options = updating_transaction.GetFailureHandlingOptions();
                FH_options.SetFailuresPreprocessor(new Warning_Swallower());
                updating_transaction.SetFailureHandlingOptions(FH_options);

                //Loads the new familysymbol
                FamilyLoadOptions FLO    = new FamilyLoadOptions();
                FamilySymbol      new_FS = null;
                doc.LoadFamilySymbol(RFA_TEMP, "Chair", FLO, out new_FS);

                //project gets updated after loading the family file
                //Commit the transaction to save the changes
                updating_transaction.Commit();
            }

            //save the project file in the same path after updating the project file
            //If the project file(.rvt) with same name  already exists in the project path ,overwrite the already existing project file
            ModelPath     Project_model_path = ModelPathUtils.ConvertUserVisiblePathToModelPath(RVT_OUTPUT);
            SaveAsOptions SAO = new SaveAsOptions();

            SAO.OverwriteExistingFile = true;

            //Save the project file
            doc.SaveAs(Project_model_path, SAO);
        }
Ejemplo n.º 11
0
        public static object OpenDocumentFile(string filePath, bool audit = false, bool detachFromCentral = false, bool preserveWorksets = true, bool closeAllWorksets = false)
        {
            var uiapp = DocumentManager.Instance.CurrentUIApplication;
            var app   = uiapp.Application;
            //instantiate open options for user to pick to audit or not
            OpenOptions openOpts = new OpenOptions
            {
                Audit = audit,
                DetachFromCentralOption = detachFromCentral == false ? DetachFromCentralOption.DoNotDetach :
                                          preserveWorksets == true ? DetachFromCentralOption.DetachAndPreserveWorksets :
                                          DetachFromCentralOption.DetachAndDiscardWorksets
            };
            //TransmittedModelOptions tOpt = TransmittedModelOptions.SaveAsNewCentral;
            //option to close all worksets
            WorksetConfiguration worksetConfiguration = new WorksetConfiguration(WorksetConfigurationOption.OpenAllWorksets);

            if (closeAllWorksets)
            {
                worksetConfiguration = new WorksetConfiguration(WorksetConfigurationOption.CloseAllWorksets);
            }
            openOpts.SetOpenWorksetsConfiguration(worksetConfiguration);

            //convert string to model path for open
            ModelPath modelPath = ModelPathUtils.ConvertUserVisiblePathToModelPath(filePath);

            var document = app.OpenDocumentFile(modelPath, openOpts);

            return(document);
        }
Ejemplo n.º 12
0
        // bug683 fix: functie toegevoegd zodat IFC exporter selectief kan rapporteren welke files missen
        /// <summary>
        ///    Geef alle gelinkte files die niet langer gevonden kunnen worden
        /// </summary>
        /// <param name="app"></param>
        /// <param name="addProj"></param>
        /// <returns></returns>
        // ReSharper disable once UnusedMember.Global
        public static List <string> GetMissingLinkedFiles(UIApplication app, bool addProj)
        {
            List <string> linkedProjects = new List <string>();

            if (linkedProjects.Count == 0)
            {
                // er zijn waarschijnlijk worksets gebruikt
                ModelPath        mdlPath   = ModelPathUtils.ConvertUserVisiblePathToModelPath(app.ActiveUIDocument.Document.PathName);
                TransmissionData transData = TransmissionData.ReadTransmissionData(mdlPath);
                if (transData != null)
                {
                    ICollection <ElementId> externalReferences = transData.GetAllExternalFileReferenceIds();
                    foreach (ElementId refId in externalReferences)
                    {
                        ExternalFileReference curRef = transData.GetLastSavedReferenceData(refId);
                        string refType = curRef.ExternalFileReferenceType.ToString();
                        string refPath = ModelPathUtils.ConvertModelPathToUserVisiblePath(curRef.GetAbsolutePath());
                        if (refType == "RevitLink")
                        {
                            linkedProjects.Add(refPath);
                        }
                    }
                }
            }

            if (addProj)
            {
                linkedProjects.Add(app.ActiveUIDocument.Document.PathName);
            }

            //laatste check om te kijken of de links ook gevonden worden
            return(linkedProjects.Where(p => (false == File.Exists(p))).ToList());
        }
Ejemplo n.º 13
0
        void GetKeynotesAssemblyCodesSharedParamAndLinks(IList <Document> targetDocumentsList, IList <string> targetList, Document activeDoc)
        {
            foreach (Document currentDoc in targetDocumentsList)
            {
                ModelPath        targetLocation = ModelPathUtils.ConvertUserVisiblePathToModelPath(currentDoc.PathName);
                TransmissionData targetData     = TransmissionData.ReadTransmissionData(targetLocation);

                if (targetData != null)
                {
                    ICollection <ElementId> externalReferences = targetData.GetAllExternalFileReferenceIds();

                    foreach (ElementId currentFileId in externalReferences)
                    {
                        if (currentFileId != ElementId.InvalidElementId)
                        {
                            ExternalFileReference extRef = targetData.GetLastSavedReferenceData(currentFileId);
                            //TODO CORRECT PROBLEMATIC IF STATEMENT HERE!!!!!!!!!!!!!!!!!!
                            if (extRef.GetLinkedFileStatus() != LinkedFileStatus.Invalid)
                            {
                                ModelPath currenFileLink = extRef.GetAbsolutePath();
                                if (!currenFileLink.Empty)
                                {
                                    string currentFileLinkString = ModelPathUtils.ConvertModelPathToUserVisiblePath(currenFileLink);
                                    CheckStringAValidLinkPathCorrectItAndAddToList(currentFileLinkString, targetList, activeDoc);
                                }
                            }
                        }
                    }
                }
            }
        }
Ejemplo n.º 14
0
        private void ExtractInfo(DesignAutomationData _data)
        {
            var doc = _data.RevitDoc;

            LogTrace("Rvt File opened...");
            var inputParameters = JsonConvert.DeserializeObject <InputParams>(File.ReadAllText("params.json"));

            LogTrace($"HubId: {inputParameters.HubId}");
            LogTrace($"ProjectId: {inputParameters.ProjectId}");
            LogTrace($"Filename: {inputParameters.Filename}");

            GoodPracticeDocument data;

            using (Transaction trans = new Transaction(doc))
            {
                trans.Start("Extract Good practices info");

                data = new GoodPracticeDocument(inputParameters.HubId, inputParameters.ProjectId, inputParameters.Filename, inputParameters.Version, doc);
                LogTrace("Data get ok...");

                trans.RollBack();
            }

            //Save the updated file by overwriting the existing file
            ModelPath ProjectModelPath = ModelPathUtils.ConvertUserVisiblePathToModelPath(OUTPUT_FILE);
            var       _path            = ModelPathUtils.ConvertModelPathToUserVisiblePath(ProjectModelPath);

            //Save the project file with updated window's parameters
            LogTrace("Saving file...");
            var json = JsonConvert.SerializeObject(data);

            File.WriteAllText(_path, json);
        }
Ejemplo n.º 15
0
        internal static void RevitFileProcessor(ObservableCollection <RevitFile> filenames)
        {
            var openOptions = new OpenOptions();

            openOptions.Audit = false;
            openOptions.DetachFromCentralOption = DetachFromCentralOption.DoNotDetach;
            var num     = 2;
            var strList = new List <string> {
                "File Name", "Volume of Column", "Volume of Beam", "Volume of Floor", "Area of Floor", "Length of Beam"
            };

            Excel excel = new Excel();

            excel.initNew();
            excel.open(@"C:\Users\Raja\Desktop\hackathon test files\datawriter.xlsx");
            excel.writeRow("Tabelle1", 1, strList);

            foreach (var file in filenames)
            {
                var       fullPath  = file.FullPath;
                var       excelFile = file.Directory;
                ModelPath modelPath = ModelPathUtils.ConvertUserVisiblePathToModelPath(fullPath);
                var       openedDoc = CachedApp.OpenDocumentFile(modelPath, openOptions);

                double volColumn = 0.0, volBeam = 0.0, volFloor = 0.0, areaFloor = 0.0, lenBeam = 0.0;

                var fecColumn = new FilteredElementCollector(openedDoc)
                                .OfCategory(BuiltInCategory.OST_StructuralColumns)
                                .WhereElementIsNotElementType();

                var fecBeam = new FilteredElementCollector(openedDoc)
                              .OfCategory(BuiltInCategory.OST_StructuralFraming)
                              .WhereElementIsNotElementType();

                var fecFloor = new FilteredElementCollector(openedDoc)
                               .OfCategory(BuiltInCategory.OST_Floors)
                               .WhereElementIsNotElementType();

                volColumn = fecColumn.Select(x => x.LookupParameter("Volume").AsDouble()).ToList().Sum();
                volBeam   = fecBeam.Select(x => x.LookupParameter("Volume").AsDouble()).ToList().Sum();
                volFloor  = fecFloor.Select(x => x.LookupParameter("Volume").AsDouble()).ToList().Sum();
                areaFloor = fecFloor.Select(x => x.LookupParameter("Area").AsDouble()).ToList().Sum();
                lenBeam   = fecBeam.Select(x => x.LookupParameter("Length").AsDouble()).ToList().Sum();

                var valList = new List <string> {
                    file.Filename, volColumn.ToString(), volBeam.ToString(), volFloor.ToString(), areaFloor.ToString(), lenBeam.ToString()
                };

                excel.writeRow("Tabelle1", num, valList);

                num += 1;

                openedDoc.Close(false);
                //TaskDialog.Show("Wishbox", $"The Total volume of column is: {volColumn.ToString()} \n The Total volume of beam is: {lenBeam.ToString()}");
            }
        }
Ejemplo n.º 16
0
        public void OpenDoc(string SourcePath, out Document doc)
        {
            ModelPath mp = ModelPathUtils.ConvertUserVisiblePathToModelPath(SourcePath);

            OpenOptions options1 = new OpenOptions
            {
                //DetachFromCentralOption = DetachFromCentralOption.DetachAndDiscardWorksets
            };

            doc = App.Application.OpenDocumentFile(mp, options1);
        }
Ejemplo n.º 17
0
        /// <summary>
        /// Links in a Revit File or files
        /// using a Dialog box within the active document;
        /// pins the instance of the Revit Link Origin-to-Origin automatically.
        /// Returns the name of the main file which should be used for Copy-Monitoriing etc
        /// </summary>
        /// <param name="doc">Active Document</param>
        public static ElementId CreateLinkRevit(this Document doc)
        {
            // Ask the user which links they would like to add to the project
            // Call the ShowDialog method to show the dialog box filtered to show only Revit Projects
            // Choose the main link to base the document on for Copy-Monitoring
            TaskDialog td_mainrvtlnk = TaskDialogUtil.Create("Main Revit Link",
                                                             "Select the link which should be used to set up Grids and Levels for Copy Monitoring",
                                                             TaskDialogIcon.TaskDialogIconNone);
            OpenFileDialog ofd = new OpenFileDialog();

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

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

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

            DialogResult dr = ofd.ShowDialog();

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

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

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

            return(cm_linkid);
        }
Ejemplo n.º 18
0
        private static void Process(DesignAutomationData data)
        {
            if (data == null)
            {
                throw new InvalidDataException(nameof(data));
            }

            Application rvtApp = data.RevitApp;

            if (rvtApp == null)
            {
                throw new InvalidDataException(nameof(rvtApp));
            }

            System.Console.WriteLine("Start application...");

            System.Console.WriteLine("File Path" + data.FilePath);


            string modelPath = data.FilePath;

            if (String.IsNullOrWhiteSpace(modelPath))
            {
                System.Console.WriteLine("No File Path");
            }

            if (String.IsNullOrWhiteSpace(modelPath))
            {
                throw new InvalidDataException(nameof(modelPath));
            }

            Document doc = data.RevitDoc;

            if (doc == null)
            {
                throw new InvalidOperationException("Could not open document.");
            }

            // SetUnits(doc);

            string          filepathJson     = "WoodProjectInput.json";
            WoodProjectItem jsonDeserialized = WoodProjectParams.Parse(filepathJson);

            CreateWalls(jsonDeserialized, doc);

            var saveAsOptions = new SaveAsOptions();

            saveAsOptions.OverwriteExistingFile = true;

            ModelPath path = ModelPathUtils.ConvertUserVisiblePathToModelPath("woodproject_result.rvt");

            doc.SaveAs(path, saveAsOptions);
        }
Ejemplo n.º 19
0
        private static ModelPath GetWSAPIModelPath(string fileName, string locRevitRoot = "")
        {
            // Utility to get a local path for a target model file
            if (locRevitRoot == "")
            {
                locRevitRoot = "C:\\Documents\\Revit Projects";
            }
            //FileInfo filePath = new FileInfo(Path.Combine(@"C:\Documents\Revit Projects", fileName));
            FileInfo  filePath = new FileInfo(Path.Combine(@locRevitRoot, fileName));
            ModelPath mp       = ModelPathUtils.ConvertUserVisiblePathToModelPath(filePath.FullName);

            return(mp);
        }
Ejemplo n.º 20
0
        private List <ModelPath> ParseModelPaths(DirectoryInfo path)
        {
            var revitFiles = path.GetDirectories("*.rvt", System.IO.SearchOption.AllDirectories);
            var modelPaths = new List <ModelPath>();

            // Parse filepath to RSN path
            foreach (var filePathInfo in revitFiles)
            {
                var filePath = filePathInfo.FullName;
                var rsnPath  = Regex.Replace(@"RSN:\\" + filePath.Remove(0, 2), @"(?<=.ru\b).*?(?<=Prj|Projects|Prg)", "");
                modelPaths.Add(ModelPathUtils.ConvertUserVisiblePathToModelPath(rsnPath));
            }
            return(modelPaths);
        }
Ejemplo n.º 21
0
        public void NWC_Export(UIApplication uiapp, string FileName, string NWCFileName)
        {
            ModelPath mp = ModelPathUtils.ConvertUserVisiblePathToModelPath(FileName);

            OpenOptions options1 = new OpenOptions
            {
                DetachFromCentralOption = DetachFromCentralOption.DetachAndDiscardWorksets
            };

            Document doc = uiapp.Application.OpenDocumentFile(mp, options1);

            //Empty models exclusion
            DS_IsEmptyModel dS_IsEmptyModel = new DS_IsEmptyModel();

            if (dS_IsEmptyModel.IsEmptyModel(doc))
            {
                EmptyModels.Add(FileName);
                doc.Close(false);
                return;
            }

            //Linkes models exclusion
            if (doc.IsLinked)
            {
                LinkedDocs.Add(FileName);
                doc.Close(false);
                return;
            }

            string dirName = GetDirNWC(NWCFileName);

            // Get a reference to each file in that directory.
            string OutputPath = DestinationPath + "\\" + dirName + "\\";

            //Options for Navisworks export
            NavisworksExportOptions nweo = new NavisworksExportOptions
            {
                ExportScope          = NavisworksExportScope.View,
                ViewId               = NW_View(doc).Id,
                ExportRoomGeometry   = false,
                DivideFileIntoLevels = false,
                ExportParts          = true
            };

            doc.Export(OutputPath, NWCFileName, nweo);

            FileFiltered.Add(OutputPath + NWCFileName + ".nwc");

            doc.Close(false);
        }
Ejemplo n.º 22
0
        public static void DeleteAllDoors(DesignAutomationData data)
        {
            if (data == null)
            {
                throw new ArgumentNullException(nameof(data));
            }

            Application rvtApp = data.RevitApp;

            if (rvtApp == null)
            {
                throw new InvalidDataException(nameof(rvtApp));
            }

            string modelPath = data.FilePath;

            if (String.IsNullOrWhiteSpace(modelPath))
            {
                throw new InvalidDataException(nameof(modelPath));
            }

            Document doc = data.RevitDoc;

            if (doc == null)
            {
                throw new InvalidOperationException("Could not open document.");
            }

            IList <Element> listOfDoors = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Doors).WhereElementIsNotElementType().ToElements();
            int             taille      = listOfDoors.Count;

            using (Transaction tr = new Transaction(doc))
            {
                tr.Start("do");
                for (int i = 0; i < taille; i++)
                {
                    DeleteElement(doc, listOfDoors[i]);
                }

                tr.Commit();
            }
            ModelPath     path = ModelPathUtils.ConvertUserVisiblePathToModelPath("DeleteDoorsProjectResult.rvt");
            SaveAsOptions SAO  = new SaveAsOptions();

            SAO.OverwriteExistingFile = false;

            //Save the project file with updated window's parameters
            LogTrace("Saving file...");
            doc.SaveAs(path, SAO);
        }
Ejemplo n.º 23
0
 public void Link_File(Document doc)
 {
     try
     {
         ModelPath        mp  = ModelPathUtils.ConvertUserVisiblePathToModelPath(path);
         RevitLinkOptions rlo = new RevitLinkOptions(false);
         var linkType         = RevitLinkType.Create(doc, mp, rlo);
         var instance         = RevitLinkInstance.Create(doc, linkType.ElementId);
     }
     catch (Exception ex)
     {
         MessageBox.Show(ex.Message);
     }
 }
Ejemplo n.º 24
0
        public static string ReloadFrom(global::Revit.Elements.Element revitLinkType, string path)
        {
            Autodesk.Revit.DB.RevitLinkType internalLinkType =
                revitLinkType.InternalElement as Autodesk.Revit.DB.RevitLinkType;

            ModelPath mPath = ModelPathUtils.ConvertUserVisiblePathToModelPath(path.Replace(Char.Parse("//"), '/'));

            TransactionManager.Instance.ForceCloseTransaction();

            LinkLoadResult loadResult = internalLinkType.LoadFrom(mPath, new WorksetConfiguration());

            return(string.Format(
                       "Result = {0}", loadResult.LoadResult));
        }
Ejemplo n.º 25
0
        public void LoadResource(Guid loadRequestId, ExternalResourceType resourceType,
                                 ExternalResourceReference resourceReference, ExternalResourceLoadContext loadContext,
                                 ExternalResourceLoadContent content)
        {
            LinkLoadContent linkLoadContent = (LinkLoadContent)content;

            string file = resourceReference.GetReferenceInformation()["File"];

            DBUtils.DBItem dbItem    = DBUtils.FindDBItem(file);
            ModelPath      linksPath = ModelPathUtils.ConvertUserVisiblePathToModelPath(dbItem.Path);

            linkLoadContent.SetLinkDataPath(linksPath);
            content.LoadStatus = ExternalResourceLoadStatus.Success;
            return;
        }
        private void HandleDesignAutomationReadyEvent(object sender, DesignAutomationReadyEventArgs e)
        {
            LogTrace("Design Automation Ready event triggered...");
            e.Succeeded = true;
            //EditWindowParametersMethod(e.DesignAutomationData.RevitDoc);
            DoJob(e.DesignAutomationData);
            ModelPath     ProjectModelPath = ModelPathUtils.ConvertUserVisiblePathToModelPath(OUTPUT_FILE);
            SaveAsOptions SAO = new SaveAsOptions();

            SAO.OverwriteExistingFile = true;

            //Save the project file with updated window's parameters
            LogTrace("Saving file...");
            e.DesignAutomationData.RevitDoc.SaveAs(ProjectModelPath, SAO);
        }
Ejemplo n.º 27
0
        /// <summary>
        ///    Geef alle gelinkte files
        /// </summary>
        /// <param name="app"></param>
        /// <param name="addProj"></param>
        /// <returns></returns>
        public static List <string> GetLinkedFiles(UIApplication app, bool addProj)
        {
            List <string>            linkedProjects = new List <string>();
            List <RevitLinkInstance> instantiekes   =
                GetAllProjectElements(app.ActiveUIDocument.Document)
                .OfType <RevitLinkInstance>()
                .Where(c => c.Name.ToLower().Contains(".rvt"))
                .ToList();

            foreach (RevitLinkInstance rli in instantiekes)
            {
                if (rli.GetLinkDocument() == null)
                {
                    continue;
                }
                string linknaam = rli.GetLinkDocument().PathName;
                if (!linkedProjects.Contains(linknaam))
                {
                    linkedProjects.Add(linknaam);
                }
            }
            if (linkedProjects.Count == 0)
            {
                // er zijn waarschijnlijk worksets gebruikt
                ModelPath        mdlPath   = ModelPathUtils.ConvertUserVisiblePathToModelPath(app.ActiveUIDocument.Document.PathName);
                TransmissionData transData = TransmissionData.ReadTransmissionData(mdlPath);
                if (transData != null)
                {
                    ICollection <ElementId> externalReferences = transData.GetAllExternalFileReferenceIds();
                    foreach (ElementId refId in externalReferences)
                    {
                        ExternalFileReference curRef = transData.GetLastSavedReferenceData(refId);
                        string refType = curRef.ExternalFileReferenceType.ToString();
                        string refPath = ModelPathUtils.ConvertModelPathToUserVisiblePath(curRef.GetAbsolutePath());
                        if (refType == "RevitLink")
                        {
                            linkedProjects.Add(refPath);
                        }
                    }
                }
            }
            if (addProj)
            {
                linkedProjects.Add(app.ActiveUIDocument.Document.PathName);
            }
            //laatste check om te kijken of de links ook gevonden worden
            return(linkedProjects.Where(File.Exists).ToList());
        }
Ejemplo n.º 28
0
        /// <inheritdoc/>
        internal override int Execute(string args = null)
        {
            var filepath = _doc.PathName;

            if (filepath != null)
            {
                IList <Element> xRefLinks    = new List <Element>();
                var             modelPath    = ModelPathUtils.ConvertUserVisiblePathToModelPath(filepath);
                var             wasException = false;
                try
                {
                    var transData          = TransmissionData.ReadTransmissionData(modelPath);
                    var externalReferences = transData.GetAllExternalFileReferenceIds();
                    foreach (var xRefId in externalReferences)
                    {
                        var externalReference = _doc.GetElement(xRefId);
                        if (ConfirmRemoval(externalReference))
                        {
                            xRefLinks.Add(externalReference);
                        }
                    }

                    HelperMethods.RemoveElements(Name, _doc, xRefLinks);
                }
                catch
                {
                    wasException = true;
                }

                try
                {
                    var linkTypesIds = new FilteredElementCollector(_doc).OfClass(typeof(RevitLinkType)).Select(l => l.Id).ToList();

                    HelperMethods.RemoveElements(Name, _doc, linkTypesIds);
                }
                catch
                {
                    wasException = true;
                }

                return(wasException ? 0 : 1);
            }

            // Модель должна быть сохранена для удаления внешних ссылок
            MessageBox.Show(Language.GetItem(RevitCommand.LangItem, "m1"), MessageBoxIcon.Alert);

            return(0);
        }
Ejemplo n.º 29
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            using (OpenFileDialog oFD = new OpenFileDialog {
                Multiselect = true, Filter = "Revit Project/ Family|*.rvt;*.rte;*.rfa;*.rft"
            })
            {
                if (oFD.ShowDialog() == DialogResult.OK && oFD.FileNames.Length > 0)
                {
                    DialogResult dialogResult = oFD.FileNames.Any(path => Path.GetExtension(path) == ".rvt") ? MessageBox.Show("Do you wanna open like a detached document?", "Opening document mode", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1) : DialogResult.None;
                    if (dialogResult == DialogResult.Cancel)
                    {
                        return(Result.Cancelled);
                    }
                    DialogResult discartWorksetDialogResult = dialogResult == DialogResult.Yes ? MessageBox.Show("Do you wanna preserve the document worksets", "Workset preservation", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1) : DialogResult.None;
                    if (discartWorksetDialogResult == DialogResult.Cancel)
                    {
                        return(Result.Cancelled);
                    }

                    EventHandler <DialogBoxShowingEventArgs> eventHandler = SetPopUpEvent(commandData);
                    foreach (string path in oFD.FileNames)
                    {
                        try
                        {
                            DetachFromCentralOption detachFromCentral = (dialogResult == DialogResult.Yes && Path.GetExtension(path) == ".rvt") ?
                                                                        (discartWorksetDialogResult == DialogResult.Yes) ?
                                                                        DetachFromCentralOption.DetachAndPreserveWorksets :
                                                                        DetachFromCentralOption.DetachAndDiscardWorksets :
                                                                        DetachFromCentralOption.DoNotDetach;
                            commandData.Application.OpenAndActivateDocument(ModelPathUtils.ConvertUserVisiblePathToModelPath(path),
                                                                            new OpenOptions
                            {
                                AllowOpeningLocalByWrongUser = true,
                                DetachFromCentralOption      = detachFromCentral
                            },
                                                                            true);
                        }
                        catch (Exception error)
                        {
                            MessageBox.Show($"Error: {error.Message}\nTime: {DateTime.Now.ToString()}");
                        }
                    }
                    RemovePopUpEvent(commandData, eventHandler);
                }
            }
            return(Result.Succeeded);
        }
Ejemplo n.º 30
0
        public void ReloadNotes()
        {
            KeynoteTable                   knTable        = KeynoteTable.GetKeynoteTable(this.docu);
            KeyBasedTreeEntries            kntableEntries = knTable.GetKeyBasedTreeEntries();
            ModelPath                      p           = ModelPathUtils.ConvertUserVisiblePathToModelPath(dialog.tempFilePath);
            KeyBasedTreeEntriesLoadResults loadResults = new KeyBasedTreeEntriesLoadResults();

            ExternalResourceReference s = ExternalResourceReference.CreateLocalResource(this.docu, ExternalResourceTypes.BuiltInExternalResourceTypes.KeynoteTable, p, PathType.Absolute);
            Transaction t = new Transaction(this.docu, "Reload");

            t.Start();
            knTable.LoadFrom(s, loadResults);
            t.Commit();
            //ExternalResourceReference exRef = new ExternalResourceReference(
            //Transaction tr = new Transaction(this.docu, "Reload");
            //tr.Start();
        }