/// <summary> /// Sets the central file. /// </summary> /// <param name="doc"></param> /// <param name="centralPath"></param> /// <returns></returns> public static void SetCentralFile(this Document doc, string centralPath) { if (doc is null) { throw new ArgumentNullException(nameof(doc)); } if (centralPath is null) { throw new ArgumentNullException(nameof(centralPath)); } var saveOption = new SaveAsOptions { OverwriteExistingFile = true }; var sharingOption = new WorksharingSaveAsOptions { SaveAsCentral = true, OpenWorksetsDefault = SimpleWorksetConfiguration.LastViewed }; saveOption.SetWorksharingOptions(sharingOption); doc.SaveAs(centralPath, saveOption); }
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { //【通过APP打开族文件】 Application app = commandData.Application.Application; string rftPath = @"C:\ProgramData\Autodesk\RVT 2020\Family Templates\Chinese\公制柱.rft"; Document docRfa = app.NewFamilyDocument(rftPath); //【开始创建】 Transaction trans = new Transaction(docRfa, "创建常规模型"); trans.Start(); CreateExtrusion(docRfa); CreateBlend(docRfa); CreateRevolution(docRfa); CreateSweep(docRfa, app); CreateSweptBlend(docRfa, app); trans.Commit(); //【保存出来】 SaveAsOptions saveAsOptions = new SaveAsOptions(); saveAsOptions.MaximumBackups = 1; saveAsOptions.OverwriteExistingFile = true; docRfa.SaveAs(@"E:\编程创建的柱子.rfa", saveAsOptions); docRfa.Close(false); return(Result.Succeeded); }
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); } }
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); }
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); }
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); }
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { var uiApp = commandData.Application; var doc = uiApp.ActiveUIDocument.Document; var saveFileDialog = new SaveFileDialog { Filter = "Revit file (*.rvt)|*.rvt", FileName = doc.Title }; if (saveFileDialog.ShowDialog() != true) { return(Result.Cancelled); } File.WriteAllText(saveFileDialog.FileName, string.Empty); using (var namedPipeServer = new NamedPipeServerStream("PilotRevitAddinPipe", PipeDirection.InOut, 1, PipeTransmissionMode.Message)) { namedPipeServer.WaitForConnection(); var messageBuilder = new StringBuilder(); var messageBuffer = new byte[983]; do { namedPipeServer.Read(messageBuffer, 0, messageBuffer.Length); var messageChunk = Encoding.UTF8.GetString(messageBuffer).TrimEnd((char)0); messageBuilder.Append(messageChunk); messageBuffer = new byte[messageBuffer.Length]; } while (!namedPipeServer.IsMessageComplete); var revitProject = JsonConvert.DeserializeObject <RevitProject>(messageBuilder.ToString()); var shareFilePathDirectory = Path.GetDirectoryName(revitProject.CentralModelPath); if (shareFilePathDirectory == null) { return(Result.Failed); } Directory.CreateDirectory(shareFilePathDirectory); var iniPath = Path.Combine(shareFilePathDirectory, saveFileDialog.SafeFileName + ".ini"); File.WriteAllText(iniPath, revitProject.PilotObjectId); var savingSettings = new SaveAsOptions() { OverwriteExistingFile = true }; savingSettings.SetWorksharingOptions(new WorksharingSaveAsOptions() { SaveAsCentral = true }); UpdateProjectSettingsCommand.UpdateProjectInfo(doc, revitProject); doc.SaveAs(Path.Combine(revitProject.CentralModelPath), savingSettings); } return(Result.Succeeded); }
/// <summary> /// Saves model by back end. /// </summary> /// <param name="doc"></param> /// <param name="centralPath"></param> public static void SaveRevit(this Document doc, string centralPath) { var saveOption = new SaveAsOptions { OverwriteExistingFile = true }; var modelPath = new FilePath(centralPath); doc.SaveAs(modelPath, saveOption); doc.Close(true); }
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); }
public AllCatCFFE2Request(UIApplication uiApp, String text) { MainUI uiForm = BARevitTools.Application.thisApp.newMainUi; uiForm.multiCatCFFEFamiliesProgressBar.Value = 0; string saveDirectory = uiForm.multiCatCFFEFamilySaveLocation; DataGridView dgv = uiForm.multiCatCFFEFamiliesDGV; RVTDocument doc = uiApp.ActiveUIDocument.Document; SaveAsOptions saveAsOptions = new SaveAsOptions(); saveAsOptions.Compact = true; saveAsOptions.MaximumBackups = 1; saveAsOptions.OverwriteExistingFile = true; //From the Comments section of the Excel template properties, get the family path for the family that was used to make the template string familyFileToUse = uiForm.multiCatCFFEFamilyFileToUse; if (!File.Exists(familyFileToUse)) { //If the family does not exist at that path, prompt the user to find it MessageBox.Show(String.Format("Could not find the family file '{0}'. Please navigate to it in the following window", familyFileToUse)); string file = GeneralOperations.GetFile(); if (file != "") { //If the family was selected, set the selection to the family to use familyFileToUse = file; } else { familyFileToUse = ""; } } //Assuming the family file to use exists, the user has set the save location, and they have set the creation method, continue if (familyFileToUse != "" && uiForm.multiCatCFFEFamilySaveLocation != "" && uiForm.multiCatCFFEFamiliesDGV.Rows.Count != 0 && uiForm.multiCatCFFEFamilyCreationComboBox.Text != "<Select Creation Method>") { //Call the AllCatCFFE2Request.CreateFamilyTypesFromTable method CreateFamilyTypesFromTable(uiApp, uiForm, saveDirectory, dgv, saveAsOptions, familyFileToUse); } //Otherwise, tell the user else if (uiForm.multiCatCFFEFamilySaveLocation == "") { MessageBox.Show("No save directory selected"); } else if (uiForm.multiCatCFFEFamilyCreationComboBox.Text == "<Select Creation Method>") { MessageBox.Show("Please select a creation method"); } else { MessageBox.Show("No families can be made because a family to use was not identified"); } }
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); }
/// <summary> /// Sets the central file. /// </summary> /// <param name="doc"></param> /// <param name="centralPath"></param> /// <returns></returns> public static void SetCentralFile(this Document doc, string centralPath) { var saveOption = new SaveAsOptions { OverwriteExistingFile = true }; var sharingOption = new WorksharingSaveAsOptions { SaveAsCentral = true, OpenWorksetsDefault = SimpleWorksetConfiguration.LastViewed }; saveOption.SetWorksharingOptions(sharingOption); doc.SaveAs(centralPath, saveOption); }
/// <summary> /// Executes the specified Revit command <see cref="ExternalCommand"/>. /// The main Execute method (inherited from IExternalCommand) must be public. /// </summary> /// <param name="commandData">The command data / context.</param> /// <param name="message">The message.</param> /// <param name="elements">The elements.</param> /// <returns>The result of command execution.</returns> public Result Execute( ExternalCommandData commandData, ref string message, ElementSet elements) { if (commandData is null) { throw new System.ArgumentNullException(nameof(commandData)); } var uiapp = commandData.Application; var exporter = new FamilyExporter(); using (var asd = new OpenFileDialog { Multiselect = true, CheckFileExists = true, Filter = "Revit Family Files|*.rfa" }) { if (asd.ShowDialog() != DialogResult.OK) { return(Result.Cancelled); } var projPath = Path.ChangeExtension(Path.GetTempFileName(), ".rvt"); var docWrapper = uiapp.Application.NewProjectDocument(UnitSystem.Metric); using (var saveAsOptions = new SaveAsOptions { OverwriteExistingFile = true }) { docWrapper.SaveAs(projPath, saveAsOptions); docWrapper.Close(false); } docWrapper = uiapp.OpenAndActivateDocument(projPath).Document; var viewType3D = docWrapper.CreateTweakedView3D(); uiapp.ActiveUIDocument.ActiveView = viewType3D; foreach (var rfaPath in asd.FileNames) { if (!File.Exists(rfaPath)) { continue; } exporter.ExportFile(docWrapper, viewType3D, rfaPath); } } return(Result.Succeeded); }
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); }
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); } } } } }
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); }
private void SaveAs_Loaded(object sender, RoutedEventArgs e) { //set the code execution that occurs when a particular dropdown option is selected in the SaveAs dropdown SaveAs.ItemsSource = new [] { new DropdownOption( "Event Frame", () => { FileOutput.IsEnabled = false; FileOutputButton.IsEnabled = false; AFServer.IsEnabled = true; AFDatabase.IsEnabled = true; MinSeconds.IsEnabled = true; SaveAsOption = SaveAsOptions.EventFrame; } ), new DropdownOption( "Text File", () => { FileOutput.IsEnabled = true; FileOutputButton.IsEnabled = true; AFServer.IsEnabled = false; AFDatabase.IsEnabled = false; MinSeconds.IsEnabled = true; SaveAsOption = SaveAsOptions.Text; } ), new DropdownOption( "Console Only", () => { FileOutput.IsEnabled = false; FileOutputButton.IsEnabled = false; AFServer.IsEnabled = false; AFDatabase.IsEnabled = false; MinSeconds.IsEnabled = true; SaveAsOption = SaveAsOptions.Console; } ), }; }
private bool upgradeOneFile(string sourceFolder, string targetFolder, string file) { string fileName = file.Substring(sourceFolder.Length).TrimStart('\\'); try { Document doc = _revitApp.OpenDocumentFile(file); string targetFile = System.IO.Path.Combine(targetFolder, fileName); string folder = System.IO.Path.GetDirectoryName(targetFile); if (Directory.Exists(folder) == false) { Directory.CreateDirectory(folder); } SaveAsOptions option = new SaveAsOptions(); option.Compact = true; option.OverwriteExistingFile = true; // set preview view id var setting = doc.GetDocumentPreviewSettings(); if (setting.PreviewViewId != ElementId.InvalidElementId) { option.PreviewViewId = setting.PreviewViewId; } else { // Find a candidate 3D view ElementId idView = findPreviewId <View3D>(doc, setting); if (idView == ElementId.InvalidElementId) { // no 3d view, try a plan view idView = findPreviewId <ViewPlan>(doc, setting); } if (idView != ElementId.InvalidElementId) { option.PreviewViewId = idView; } } doc.SaveAs(targetFile, option); doc.Close(); return(true); } catch (Exception ex) { // write error message into log file logError(targetFolder, fileName, ex.Message); return(false); } }
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { //Get application and document objects UIApplication uiapp = commandData.Application; Document doc = uiapp.ActiveUIDocument.Document; string fileName = doc.Title; string filePath = doc.PathName; SaveAsOptions options = new SaveAsOptions(); options.OverwriteExistingFile = true; options.Compact = true; doc.SaveAs(filePath, options); return(Result.Succeeded); }
public void EditandloadFamily(Document doc, List <FamilySymbol> listsymbol) { string path = System.IO.Path.GetTempPath(); string fordelsave = path + "\\" + "AFamilyrevit"; if (!System.IO.Directory.Exists(fordelsave)) { System.IO.Directory.CreateDirectory(fordelsave); } foreach (FamilySymbol symbol in listsymbol) { Family family = symbol.Family; Document familydoc = doc.EditFamily(family); SaveAsOptions saveop = new SaveAsOptions(); saveop.OverwriteExistingFile = true; } }
public static bool ProjectAsCentral(string path, bool compact = false, int maximumBackups = 10, string WorksetConfiguration = "AskUserToSpecify") { Autodesk.Revit.DB.Document doc = DocumentManager.Instance.CurrentDBDocument; SaveAsOptions saveAs = new SaveAsOptions { Compact = compact, MaximumBackups = maximumBackups }; SimpleWorksetConfiguration simple = new SimpleWorksetConfiguration(); WorksharingSaveAsOptions worksharing = new WorksharingSaveAsOptions(); if (WorksetConfiguration == "AskUserToSpecify") { simple = SimpleWorksetConfiguration.AskUserToSpecify; } else if (WorksetConfiguration == "AllEditable") { simple = SimpleWorksetConfiguration.AllEditable; } else if (WorksetConfiguration == "AllWorksets") { simple = SimpleWorksetConfiguration.AllWorksets; } else if (WorksetConfiguration == "LastViewed") { simple = SimpleWorksetConfiguration.LastViewed; } else { throw new NotSupportedException("Workset Configuration may only be one of four types: AskUserToSpecify, AllEditable, AllWorksets, or LastViewed. Use WorksetConfiguration node in Lightning package for seamless execution."); } worksharing.OpenWorksetsDefault = simple; worksharing.SaveAsCentral = true; saveAs.SetWorksharingOptions(worksharing); try { doc.SaveAs(path, saveAs); return(true); } catch (Exception ex) { throw ex; } }
private string CreateMassFamily(string famPath, Geometry.Surface surface, string name) { var famDoc = Doc.Application.NewFamilyDocument(famPath); using (Transaction t = new Transaction(famDoc, "Create Mass")) { t.Start(); try { var pointLists = surface.GetControlPoints(); var curveArray = new ReferenceArrayArray(); foreach (var list in pointLists) { var arr = new ReferencePointArray(); foreach (var point in list) { var refPt = famDoc.FamilyCreate.NewReferencePoint(PointToNative(point)); arr.Append(refPt); } var curve = famDoc.FamilyCreate.NewCurveByPoints(arr); var referenceArray = new ReferenceArray(); referenceArray.Append(curve.GeometryCurve.Reference); curveArray.Append(referenceArray); } var loft = famDoc.FamilyCreate.NewLoftForm(true, curveArray); } catch (Exception e) { } t.Commit(); } var famName = "SpeckleMass_" + name; string tempFamilyPath = Path.Combine(Path.GetTempPath(), famName + ".rfa"); SaveAsOptions so = new SaveAsOptions(); so.OverwriteExistingFile = true; famDoc.SaveAs(tempFamilyPath, so); famDoc.Close(); return(tempFamilyPath); }
public void HandleDesignAutomationReadyEvent(object sender, DesignAutomationReadyEventArgs e) { e.Succeeded = true; Document doc = e.DesignAutomationData.RevitDoc; if (doc.IsFamilyDocument) { FamilyManager fm = doc.FamilyManager; //Save the updated file by overwriting the existing file ModelPath ProjectModelPath = ModelPathUtils.ConvertUserVisiblePathToModelPath(doc.PathName); SaveAsOptions SAO = new SaveAsOptions(); SAO.OverwriteExistingFile = true; //Save the project file with updated window's parameters LogTrace("Saving file..."); doc.SaveAs(ProjectModelPath, SAO); } }
public static bool ProjectAsLocal(string path, bool compact = false, int maximumBackups = 10) { Autodesk.Revit.DB.Document doc = DocumentManager.Instance.CurrentDBDocument; SaveAsOptions saveAs = new SaveAsOptions { Compact = compact, MaximumBackups = maximumBackups }; try { doc.SaveAs(path, saveAs); return(true); } catch (Exception ex) { throw ex; } }
/// <summary> /// Metodo che salva il file modificato in un certo percorso /// </summary> private void SaveChanges(UIApplication uiapp) { if (_pathName == "") { _pathName = "ToDestroy"; } _filepath = _dirpath + "\\" + _pathName + ".rfa"; // Salva le modifiche al file Document doc = uiapp.ActiveUIDocument.Document; SaveAsOptions opt = new SaveAsOptions { OverwriteExistingFile = true }; doc.SaveAs(_filepath, opt); }
/// <summary> /// Saves model by back end. /// </summary> /// <param name="doc"></param> /// <param name="centralPath"></param> public static void SaveRevit(this Document doc, string centralPath) { if (doc == null) { throw new ArgumentNullException(nameof(doc)); } if (centralPath == null) { throw new ArgumentNullException(nameof(centralPath)); } var saveOption = new SaveAsOptions { OverwriteExistingFile = true }; var modelPath = new FilePath(centralPath); doc.SaveAs(modelPath, saveOption); doc.Close(true); }
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { //【通过APP打开族文件】 Application app = commandData.Application.Application; string rftPath = @"C:\ProgramData\Autodesk\RVT 2020\Family Templates\Chinese\公制柱.rft"; Document docRfa = app.NewFamilyDocument(rftPath); //【创建几何】 double width = 2.5 / 0.3048; double height = 10 / 0.3048; XYZ point1 = new XYZ(width, width, 0); XYZ point2 = new XYZ(-width, width, 0); XYZ point3 = new XYZ(-width, -width, 0); XYZ point4 = new XYZ(width, -width, 0); CurveArray curveArray = new CurveArray(); curveArray.Append(Line.CreateBound(point1, point2)); curveArray.Append(Line.CreateBound(point2, point3)); curveArray.Append(Line.CreateBound(point3, point4)); curveArray.Append(Line.CreateBound(point4, point1)); CurveArrArray curveArrArray = new CurveArrArray(); curveArrArray.Append(curveArray); //【创建草图平面】 SketchPlane sketchPlane = new FilteredElementCollector(docRfa).OfClass(typeof(SketchPlane)).First(x => x.Name == "低于参照标高") as SketchPlane; //【开始创建】 Transaction trans = new Transaction(docRfa, "创建柱族"); trans.Start(); Extrusion extrusion = docRfa.FamilyCreate.NewExtrusion(true, curveArrArray, sketchPlane, height); trans.Commit(); //【保存出来】 SaveAsOptions saveAsOptions = new SaveAsOptions(); saveAsOptions.MaximumBackups = 1; saveAsOptions.OverwriteExistingFile = true; docRfa.SaveAs(@"E:\编程创建的柱子.rfa", saveAsOptions); docRfa.Close(false); return(Result.Succeeded); }
private void EditWindowParametersMethod(Document doc) { //InputParams inputParameters = JsonConvert.DeserializeObject<InputParams>(File.ReadAllText("params.json")); ////Modifying the window parameters ////Open transaction //using (Transaction trans = new Transaction(doc)) //{ // trans.Start("Update window parameters"); // //Filter for windows // FilteredElementCollector WindowCollector = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Windows).WhereElementIsNotElementType(); // IList<ElementId> windowIds = WindowCollector.ToElementIds() as IList<ElementId>; // foreach (ElementId windowId in windowIds) // { // Element Window = doc.GetElement(windowId); // FamilyInstance FamInst = Window as FamilyInstance; // FamilySymbol FamSym = FamInst.Symbol; // SetElementParameter(FamSym, BuiltInParameter.WINDOW_HEIGHT, inputParameters.Height); // SetElementParameter(FamSym, BuiltInParameter.WINDOW_WIDTH, inputParameters.Width); // } // //To save all the changes commit the transaction // trans.Commit(); //} //Save the updated file by overwriting the existing file 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..."); doc.SaveAs(ProjectModelPath, SAO); }
private void EditWindowParametersMethod(Application app, string projectPath) { // Get the data of the project file(i.e)the project in which families are present DesignAutomationData data = new DesignAutomationData(app, projectPath); //get the revit project document Document doc = data.RevitDoc; //Modifying the window parameters //Open transaction using (Transaction windowTransaction = new Transaction(doc)) { windowTransaction.Start("Update window parameters"); //Filter for windows FilteredElementCollector WindowCollector = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Windows).WhereElementIsNotElementType(); IList <ElementId> windowIds = WindowCollector.ToElementIds() as IList <ElementId>; foreach (ElementId windowId in windowIds) { Element Window = doc.GetElement(windowId); FamilyInstance FamInst = Window as FamilyInstance; FamilySymbol FamSym = FamInst.Symbol; SetElementParameter(FamSym, BuiltInParameter.WINDOW_HEIGHT, windowHeight); SetElementParameter(FamSym, BuiltInParameter.WINDOW_WIDTH, windowWidth); } //To save all the changes commit the transaction windowTransaction.Commit(); } //Save the updated file by overwriting the existing file ModelPath ProjectModelPath = ModelPathUtils.ConvertUserVisiblePathToModelPath(projectPath); SaveAsOptions SAO = new SaveAsOptions(); SAO.OverwriteExistingFile = true; //Save the project file with updated window's parameters doc.SaveAs(ProjectModelPath, SAO); }
public void SaveDetach(Document doc) { System.Windows.Forms.OpenFileDialog theDialogRevit = new System.Windows.Forms.OpenFileDialog(); theDialogRevit.Title = "Select Revit Project Files"; theDialogRevit.Filter = "RVT files|*.rvt"; theDialogRevit.FilterIndex = 1; theDialogRevit.InitialDirectory = @"C:\"; theDialogRevit.Multiselect = true; if (theDialogRevit.ShowDialog() == DialogResult.OK) { string mpath = ""; string mpathOnlyFilename = ""; System.Windows.Forms.FolderBrowserDialog folderBrowserDialog1 = new System.Windows.Forms.FolderBrowserDialog(); folderBrowserDialog1.Description = "Select Folder Where Revit Projects to be Saved in Local"; folderBrowserDialog1.RootFolder = Environment.SpecialFolder.MyComputer; if (folderBrowserDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK) { mpath = folderBrowserDialog1.SelectedPath; foreach (string projectPath in theDialogRevit.FileNames) { FileInfo filePath = new FileInfo(projectPath); ModelPath mp = ModelPathUtils.ConvertUserVisiblePathToModelPath(filePath.FullName); OpenOptions opt = new OpenOptions(); opt.DetachFromCentralOption = DetachFromCentralOption.DetachAndDiscardWorksets; mpathOnlyFilename = filePath.Name; Document openedDoc = app.OpenDocumentFile(mp, opt); SaveAsOptions options = new SaveAsOptions(); options.OverwriteExistingFile = true; ModelPath modelPathout = ModelPathUtils.ConvertUserVisiblePathToModelPath(mpath + "\\" + mpathOnlyFilename); openedDoc.SaveAs(modelPathout, options); openedDoc.Close(false); } } } }
public Result Execute( ExternalCommandData commandData, ref string message, ElementSet elements) { UIApplication uiapp = commandData.Application; UIDocument uidoc = uiapp.ActiveUIDocument; Application app = uiapp.Application; Document doc = uidoc.Document; Selection sel = uidoc.Selection; // Retrieve all floors from the model var floors = new FilteredElementCollector( doc ) .OfClass( typeof( Floor ) ) .ToElements() .Cast<Floor>() .ToList(); if( 2 != floors.Count ) { message = "Please create two intersected floors"; return Result.Failed; } // Retrieve the floor solids Options opt = new Options(); var geometry1 = floors[0].get_Geometry( opt ); var geometry2 = floors[1].get_Geometry( opt ); var solid1 = geometry1.FirstOrDefault() as Solid; var solid2 = geometry2.FirstOrDefault() as Solid; // Calculate the intersection solid var intersectedSolid = BooleanOperationsUtils .ExecuteBooleanOperation( solid1, solid2, BooleanOperationsType.Intersect ); // Search for the metric mass family template file string template_path = DirSearch( app.FamilyTemplatePath, "Metric Mass.rft" ); // Create a new temporary family var family_doc = app.NewFamilyDocument( template_path ); // Create a free form element // from the intersection solid using( var t = new Transaction( family_doc ) ) { t.Start( "Add Free Form Element" ); var freeFormElement = FreeFormElement.Create( family_doc, intersectedSolid ); t.Commit(); } string dir = Path.GetTempPath(); string filepath = Path.Combine( dir, "floor_intersection_family.rfa" ); SaveAsOptions sao = new SaveAsOptions() { OverwriteExistingFile = true }; family_doc.SaveAs( filepath, sao ); // Create 3D View var viewFamilyType = new FilteredElementCollector( family_doc ) .OfClass( typeof( ViewFamilyType ) ) .OfType<ViewFamilyType>() .FirstOrDefault( x => x.ViewFamily == ViewFamily.ThreeDimensional ); View3D threeDView; using( var t = new Transaction( family_doc ) ) { t.Start( "Create 3D View" ); threeDView = View3D.CreateIsometric( family_doc, viewFamilyType.Id ); t.Commit(); } // Export to SAT var viewSet = new List<ElementId>() { threeDView.Id }; SATExportOptions exportOptions = new SATExportOptions(); var res = family_doc.Export( dir, "SolidFile.sat", viewSet, exportOptions ); return Result.Succeeded; }
/// <summary> /// Link in the new created document to parent document. /// </summary> /// <param name="baseFileName">The full path to the IFC file.</param> /// <param name="ifcDocument">The newly imported IFC file document.</param> /// <param name="originalDocument">The document to contain the IFC link.</param> /// <param name="useExistingType">True if the RevitLinkType already exists.</param> /// <param name="doSave">True if we should save the document. This should only be false if we are reusing a cached document.</param> public static void LinkInFile(string baseFileName, Document ifcDocument, Document originalDocument, bool useExistingType, bool doSave) { bool saveSucceded = true; string fileName = GenerateRevitFileName(baseFileName); if (doSave) { SaveAsOptions saveAsOptions = new SaveAsOptions(); saveAsOptions.OverwriteExistingFile = true; try { ifcDocument.SaveAs(fileName, saveAsOptions); } catch (Exception ex) { // We still want to close the document to prevent having a corrupt model in memory. IFCImportFile.TheLog.LogError(-1, ex.Message, false); saveSucceded = false; } } if (!ifcDocument.IsLinked) ifcDocument.Close(false); if (!saveSucceded) return; bool doReloadFrom = useExistingType && !Importer.TheOptions.CreateLinkInstanceOnly; ElementId revitLinkTypeId = ElementId.InvalidElementId; if (Importer.TheOptions.RevitLinkFileName != null) { FilePath originalRevitFilePath = new FilePath(Importer.TheOptions.RevitLinkFileName); revitLinkTypeId = RevitLinkType.GetTopLevelLink(originalDocument, originalRevitFilePath); } if (!doReloadFrom) { Transaction linkTransaction = new Transaction(originalDocument); linkTransaction.Start(Resources.IFCLinkFile); try { if (revitLinkTypeId == ElementId.InvalidElementId) { RevitLinkOptions options = new RevitLinkOptions(true); RevitLinkLoadResult loadResult = RevitLinkType.CreateFromIFC(originalDocument, baseFileName, fileName, false, options); if ((loadResult != null) && (loadResult.ElementId != ElementId.InvalidElementId)) revitLinkTypeId = loadResult.ElementId; } if (revitLinkTypeId != ElementId.InvalidElementId) RevitLinkInstance.Create(originalDocument, revitLinkTypeId); Importer.PostDelayedLinkErrors(originalDocument); linkTransaction.Commit(); } catch (Exception ex) { linkTransaction.RollBack(); throw ex; } } else // reload from { // For the reload from case, we expect the transaction to have been created in the UI. if (revitLinkTypeId != ElementId.InvalidElementId) { RevitLinkType existingRevitLinkType = originalDocument.GetElement(revitLinkTypeId) as RevitLinkType; if (existingRevitLinkType != null) existingRevitLinkType.UpdateFromIFC(originalDocument, baseFileName, fileName, false); } } }
/// <summary> /// Create Extrusion /// </summary> /// <param name="extrusion"></param> /// <returns></returns> public static Element Create(this Grevit.Types.SimpleExtrusion extrusion) { // Get the Massing template file string templateFile = GrevitBuildModel.RevitTemplateFolder + @"\Conceptual Mass\Metric Mass.rft"; // If the file doesnt exist ask the user for a new template if (!File.Exists(templateFile)) { System.Windows.Forms.OpenFileDialog ofd = new System.Windows.Forms.OpenFileDialog(); ofd.Multiselect = false; ofd.Title = templateFile + " not found."; System.Windows.Forms.DialogResult dr = ofd.ShowDialog(); if (dr != System.Windows.Forms.DialogResult.OK) return null; templateFile = ofd.FileName; } // Create a new family Document Document familyDocument = GrevitBuildModel.document.Application.NewFamilyDocument(templateFile); // Create a new family transaction Transaction familyTransaction = new Transaction(familyDocument, "Transaction in Family"); familyTransaction.Start(); // get family categories Categories categories = familyDocument.Settings.Categories; // Get the mass category Category catMassing = categories.get_Item("Mass"); // Create a new subcategory in Mass Category subcategory = familyDocument.Settings.Categories.NewSubcategory(catMassing, "GrevitExtrusion"); // Create a reference Array for the Profile ReferenceArray referenceArrayProfile = new ReferenceArray(); // Translate all Points to the reference Array for (int i = 0; i < extrusion.polyline.points.Count - 1; i++) { Grevit.Types.Point pkt1 = extrusion.polyline.points[i]; Grevit.Types.Point pkt2 = extrusion.polyline.points[i + 1]; referenceArrayProfile.Append(Utilities.CurveFromXYZ(familyDocument, pkt1.ToXYZ(), pkt2.ToXYZ())); } // Create a new Extrusion Form extrudedMass = familyDocument.FamilyCreate.NewExtrusionForm(true, referenceArrayProfile, new XYZ(extrusion.vector.x, extrusion.vector.y, extrusion.vector.z)); // Apply the subcategory extrudedMass.Subcategory = subcategory; // Commit the Family Transaction familyTransaction.Commit(); // Assemble a filename to save the family to string filename = Path.Combine(Path.GetTempPath(), "GrevitMass-" + extrusion.GID + ".rfa"); // Save Family to Temp path and close it SaveAsOptions opt = new SaveAsOptions(); opt.OverwriteExistingFile = true; familyDocument.SaveAs(filename, opt); familyDocument.Close(false); // Load the created family to the document Family family = null; GrevitBuildModel.document.LoadFamily(filename, out family); // Get the first family symbol FamilySymbol symbol = null; foreach (ElementId s in family.GetFamilySymbolIds()) { symbol = (FamilySymbol)GrevitBuildModel.document.GetElement(s); break; } if (!symbol.IsActive) symbol.Activate(); // Create a new Family Instance origin based FamilyInstance familyInstance = GrevitBuildModel.document.Create.NewFamilyInstance(new XYZ(0, 0, 0), symbol, Autodesk.Revit.DB.Structure.StructuralType.NonStructural); // Activate Mass visibility GrevitBuildModel.document.SetMassVisibilityOn(); return familyInstance; }
public Autodesk.Revit.UI.Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { try { string tmpPath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + @"\ifcComponentImporter"; string filePath = ""; string rvtPath = ""; OpenFileDialog openFileDialog1 = new OpenFileDialog(); openFileDialog1.Filter = "IFC Files|*.ifc"; openFileDialog1.Title = "Select a ifc File"; if(!Directory.Exists(tmpPath)) { Directory.CreateDirectory(tmpPath); } if (openFileDialog1.ShowDialog() == DialogResult.OK) { filePath = openFileDialog1.FileName; var ifcops = new IFCImportOptions(); Document document = commandData.Application.Application.OpenIFCDocument(filePath, ifcops); DocumentPreviewSettings settings = document.GetDocumentPreviewSettings(); FilteredElementCollector collector = new FilteredElementCollector(document); collector.OfClass(typeof(ViewPlan)); FilteredElementCollector uicollector = new FilteredElementCollector(commandData.Application.ActiveUIDocument.Document); uicollector.OfClass(typeof(ViewPlan)); Func<ViewPlan, bool> isValidForPreview = v => settings.IsViewIdValidForPreview(v.Id); ViewPlan viewForPreview = collector.OfType<ViewPlan>().First<ViewPlan>(isValidForPreview); using (Transaction tx = new Transaction(document)) { tx.Start("tr"); viewForPreview.SetWorksetVisibility(viewForPreview.WorksetId, WorksetVisibility.Visible); tx.Commit(); } SaveAsOptions options = new SaveAsOptions(); options.PreviewViewId = viewForPreview.Id; rvtPath = tmpPath + @"\" + Path.ChangeExtension(Path.GetFileName(filePath), "rvt"); if (File.Exists(rvtPath)) { File.Delete(rvtPath); } document.SaveAs(rvtPath, options); commandData.Application.PostCommand(RevitCommandId.LookupCommandId("ID_LOAD_GROUP")); Process process = new Process(); process.StartInfo.FileName = "PostAction.exe"; process.StartInfo.Arguments = "\""+rvtPath+"\""; process.Start(); } return 0; } catch (Exception ex) { message = ex.Message; return Autodesk.Revit.UI.Result.Failed; } }
public Result Execute( ExternalCommandData commandData, ref string message, ElementSet elements) { Application app = commandData.Application.Application; string filename = Path.Combine( _folder, _template ); Document familyDoc = app.NewFamilyDocument( filename ); Family family = familyDoc.OwnerFamily; Autodesk.Revit.Creation.FamilyItemFactory factory = familyDoc.FamilyCreate; Extrusion extrusion = null; using( Transaction trans = new Transaction( familyDoc ) ) { trans.Start( "Create Extrusion" ); XYZ arcCenter = new XYZ( 0.0, 3.0, -2.0 ); // Get the "left" view View view = GetView( ViewType.Elevation, XYZ.BasisY.Negate(), XYZ.BasisZ, familyDoc ); // 2D offsets from view 'left' XYZ xOffset = new XYZ( 0.0, 10.0, 0.0 ); XYZ yOffset = new XYZ( 0.0, 0.0, -10.0 ); //################## Reference planes ################################ // Origin's reference planes ReferencePlane referencePlaneOriginX = factory.NewReferencePlane( XYZ.BasisX, XYZ.Zero, XYZ.BasisY, view ); referencePlaneOriginX.Name = "ReferencePlane_OriginX"; referencePlaneOriginX.Pinned = true; ReferencePlane referencePlaneOriginY = factory.NewReferencePlane( XYZ.BasisZ, XYZ.Zero, -XYZ.BasisX, view ); referencePlaneOriginY.Name = "ReferencePlane_OriginY"; referencePlaneOriginY.Pinned = true; // Reference planes the extruded arc should stick to ReferencePlane referencePlaneX = factory.NewReferencePlane( XYZ.BasisX + yOffset, XYZ.Zero + yOffset, XYZ.BasisY, view ); referencePlaneX.Name = "ReferencePlane_X"; ReferencePlane referencePlaneY = factory.NewReferencePlane( XYZ.BasisZ + xOffset, XYZ.Zero + xOffset, -XYZ.BasisX, view ); referencePlaneY.Name = "ReferencePlane_Y"; familyDoc.Regenerate(); //################## Create dimensions ############################### // Dimension x ReferenceArray refArrayX = new ReferenceArray(); refArrayX.Append( referencePlaneX.GetReference() ); refArrayX.Append( referencePlaneOriginX.GetReference() ); Line lineX = Line.CreateUnbound( arcCenter, XYZ.BasisZ ); Dimension dimensionX = factory.NewDimension( view, lineX, refArrayX ); // Dimension y ReferenceArray refArrayY = new ReferenceArray(); refArrayY.Append( referencePlaneY.GetReference() ); refArrayY.Append( referencePlaneOriginY.GetReference() ); Line lineY = Line.CreateUnbound( arcCenter, XYZ.BasisY ); Dimension dimensionY = factory.NewDimension( view, lineY, refArrayY ); familyDoc.Regenerate(); //################## Create arc ###################################### double arcRadius = 1.0; Arc arc = Arc.Create( XYZ.Zero + xOffset + yOffset, arcRadius, 0.0, 2 * Math.PI, XYZ.BasisZ, XYZ.BasisY.Negate() ); CurveArray curves = new CurveArray(); curves.Append( arc ); CurveArrArray profile = new CurveArrArray(); profile.Append( curves ); Plane plane = new Plane( XYZ.BasisX.Negate(), arcCenter ); SketchPlane sketchPlane = SketchPlane.Create( familyDoc, plane ); Debug.WriteLine( "Origin: " + sketchPlane.GetPlane().Origin ); Debug.WriteLine( "Normal: " + sketchPlane.GetPlane().Normal ); Debug.WriteLine( "XVec: " + sketchPlane.GetPlane().XVec ); Debug.WriteLine( "YVec: " + sketchPlane.GetPlane().YVec ); extrusion = factory.NewExtrusion( true, profile, sketchPlane, 10 ); familyDoc.Regenerate(); //################## Add family parameters ########################### FamilyManager fmgr = familyDoc.FamilyManager; FamilyParameter paramX = fmgr.AddParameter( "X", BuiltInParameterGroup.PG_GEOMETRY, ParameterType.Length, true ); dimensionX.FamilyLabel = paramX; FamilyParameter paramY = fmgr.AddParameter( "Y", BuiltInParameterGroup.PG_GEOMETRY, ParameterType.Length, true ); dimensionY.FamilyLabel = paramY; // Set their values FamilyType familyType = fmgr.NewType( "Standard" ); fmgr.Set( paramX, 10 ); fmgr.Set( paramY, 10 ); trans.Commit(); } // Save it to inspect SaveAsOptions opt = new SaveAsOptions(); opt.OverwriteExistingFile = true; filename = Path.Combine( Path.GetTempPath(), "test.rfa" ); familyDoc.SaveAs( filename, opt ); return Result.Succeeded; }
public Result Execute( ExternalCommandData commandData, ref string message, ElementSet elements) { UIApplication uiapp = commandData.Application; UIDocument uidoc = uiapp.ActiveUIDocument; Application app = uiapp.Application; Document doc = uidoc.Document; _doc = doc; //Prompt for Input contents Document fdocX = app.NewFamilyDocument("C:\\ProgramData\\Autodesk\\RVT 2013\\Family Templates\\English_I\\Annotations\\Generic Annotation.rft"); //Document fdocX = app.NewFamilyDocument("C:\\ProgramData\\Autodesk\\RVT 2013\\Family Templates\\English_I\\Generic Model.rft"); //New Qrencoder using the family document QREncoder qrcode = new QREncoder(fdocX, uidoc, app); string contents = Microsoft.VisualBasic.Interaction.InputBox("Enter and text to QR encode.", "QR Encode Prompt", "", -1, -1); if (contents != "") { if (null == fdocX) { return Result.Failed; } // Modify document within a transaction using (Transaction tx = new Transaction(fdocX)) { tx.Start("Generate QR Code"); //GenerateQR(fdoc, qrcode, contents); GenerateQR(fdocX, qrcode, contents); tx.Commit(); } //save background family doc string dir = Path.GetDirectoryName(Environment.GetFolderPath(Environment.SpecialFolder.Desktop)); //Clean invalid filename characters string fileNameClean = CleanChars(contents); _familyName += fileNameClean; string filename = Path.Combine(dir, _familyName + ".rfa"); SaveAsOptions opt = new SaveAsOptions(); opt.OverwriteExistingFile = true; fdocX.SaveAs(filename, opt); fdocX.Close(false); //Insert new family into document using (Transaction tx2 = new Transaction(doc)) { tx2.Start("Insert QRCode"); Family fam = null; FilteredElementCollector fec = new FilteredElementCollector(doc) .OfClass(typeof(Family)); foreach (Family f in fec) { if (f.Name.Equals(_familyName)) { fam = f; } else { doc.LoadFamily(filename, out fam); } } FamilySymbol fs = null; foreach (FamilySymbol symbol in fam.Symbols) { fs = symbol; break; } XYZ p = uidoc.Selection.PickPoint("Please pick point to place QR code"); AnnotationSymbolTypeSet annoset = _doc.AnnotationSymbolTypes; AnnotationSymbolType annoSymbolType = null; foreach (AnnotationSymbolType type in annoset) { if (type.Name.Equals(_familyName)) { annoSymbolType = type; } } //Deprecated in 2013, but too lazy to implement new doc.Create.NewAnnotationSymbol(p, annoSymbolType, uidoc.ActiveView); //doc.Create.NewFamilyInstance(p, fs, Autodesk.Revit.DB.Structure.StructuralType.NonStructural); tx2.Commit(); } return Result.Succeeded; } else { return Result.Cancelled; } }
static void CreateFaceWalls( Document doc) { Application app = doc.Application; Document massDoc = app.NewFamilyDocument( _conceptual_mass_template_path ); CreateMassExtrusion( massDoc ); //if( File.Exists( _family_path ) ) // File.Delete( _family_path ); SaveAsOptions opt = new SaveAsOptions(); opt.OverwriteExistingFile = true; massDoc.SaveAs( _family_path, opt ); using( Transaction tx = new Transaction( doc ) ) { tx.Start( "Create FaceWall" ); if( !doc.LoadFamily( _family_path ) ) throw new Exception( "DID NOT LOAD FAMILY" ); Family family = new FilteredElementCollector( doc ) .OfClass( typeof( Family ) ) .Where<Element>( x => x.Name.Equals( _family_name ) ) .Cast<Family>() .FirstOrDefault(); FamilySymbol fs = doc.GetElement( family.GetFamilySymbolIds().First<ElementId>() ) as FamilySymbol; // Create a family instance Level level = doc.ActiveView.GenLevel; FamilyInstance fi = doc.Create.NewFamilyInstance( XYZ.Zero, fs, level, StructuralType.NonStructural ); doc.Regenerate(); // required to generate the geometry! // Determine wall type. WallType wallType = new FilteredElementCollector( doc ) .OfClass( typeof( WallType ) ) .Cast<WallType>() .Where<WallType>( x => FaceWall.IsWallTypeValidForFaceWall( doc, x.Id ) ) .FirstOrDefault(); // Retrieve mass element geometry. Options options = app.Create.NewGeometryOptions(); options.ComputeReferences = true; //options.View = doc.ActiveView; // conceptual mass is not visible in default view GeometryElement geo = fi.get_Geometry( options ); // Create a sloped wall from the geometry. foreach( GeometryObject obj in geo ) { Solid solid = obj as Solid; if( null != solid ) { foreach( Face f in solid.Faces ) { Debug.Assert( null != f.Reference, "we asked for references, didn't we?" ); PlanarFace pf = f as PlanarFace; if( null != pf ) { XYZ v = pf.FaceNormal; // Errors: // // Could not create a face wall. // // Caused by using ActiveView.Level // instead of ActiveView.GenLevel. // // This reference cannot be applied to a face wall. // // Caused by using this on a horizontal face. if( !Util.IsVertical( v ) ) { FaceWall.Create( doc, wallType.Id, WallLocationLine.CoreCenterline, f.Reference ); } } } } } tx.Commit(); } }
/// <summary> /// Link in the new created document to parent document. /// </summary> /// <param name="baseFileName">The full path to the IFC file.</param> /// <param name="ifcDocument">The newly imported IFC file document.</param> /// <param name="originalDocument">The document to contain the IFC link.</param> /// <param name="useExistingType">True if the RevitLinkType already exists.</param> /// <param name="doSave">True if we should save the document. This should only be false if we are reusing a cached document.</param> /// <returns>The element id of the RevitLinkType for this link operation.</returns> public static ElementId LinkInFile(string baseFileName, Document ifcDocument, Document originalDocument, bool useExistingType, bool doSave) { bool saveSucceded = true; string fileName = GenerateRevitFileName(baseFileName); if (doSave) { SaveAsOptions saveAsOptions = new SaveAsOptions(); saveAsOptions.OverwriteExistingFile = true; try { ifcDocument.SaveAs(fileName, saveAsOptions); } catch (Exception ex) { // We still want to close the document to prevent having a corrupt model in memory. Importer.TheLog.LogError(-1, ex.Message, false); saveSucceded = false; } } if (!ifcDocument.IsLinked) { ifcDocument.Close(false); } ElementId revitLinkTypeId = ElementId.InvalidElementId; if (!saveSucceded) { return(revitLinkTypeId); } bool doReloadFrom = useExistingType && !Importer.TheOptions.CreateLinkInstanceOnly; if (Importer.TheOptions.RevitLinkFileName != null) { FilePath originalRevitFilePath = new FilePath(Importer.TheOptions.RevitLinkFileName); revitLinkTypeId = RevitLinkType.GetTopLevelLink(originalDocument, originalRevitFilePath); } if (!doReloadFrom) { Transaction linkTransaction = new Transaction(originalDocument); linkTransaction.Start(Resources.IFCLinkFile); try { if (revitLinkTypeId == ElementId.InvalidElementId) { RevitLinkOptions options = new RevitLinkOptions(true); RevitLinkLoadResult loadResult = RevitLinkType.CreateFromIFC(originalDocument, baseFileName, fileName, false, options); if ((loadResult != null) && (loadResult.ElementId != ElementId.InvalidElementId)) { revitLinkTypeId = loadResult.ElementId; } } if (revitLinkTypeId != ElementId.InvalidElementId) { RevitLinkInstance.Create(originalDocument, revitLinkTypeId); } Importer.PostDelayedLinkErrors(originalDocument); linkTransaction.Commit(); } catch (Exception ex) { linkTransaction.RollBack(); throw ex; } } else // reload from { // For the reload from case, we expect the transaction to have been created in the UI. if (revitLinkTypeId != ElementId.InvalidElementId) { RevitLinkType existingRevitLinkType = originalDocument.GetElement(revitLinkTypeId) as RevitLinkType; if (existingRevitLinkType != null) { existingRevitLinkType.UpdateFromIFC(originalDocument, baseFileName, fileName, false); } } } return(revitLinkTypeId); }
public Result Execute( ExternalCommandData commandData, ref string message, ElementSet elements) { UIApplication uiapp = commandData.Application; UIDocument uidoc = uiapp.ActiveUIDocument; Application app = uiapp.Application; Document doc = uidoc.Document; Document fdoc = null; Transaction t = null; if( null == doc ) { message = "Please run this command in an open document."; return Result.Failed; } #region Create a new structural stiffener family // Check whether the family has already // been created or loaded previously. Family family = new FilteredElementCollector( doc ) .OfClass( typeof( Family ) ) .Cast<Family>() .FirstOrDefault<Family>( e => e.Name.Equals( _family_name ) ); if( null != family ) { fdoc = family.Document; } else { string templateFileName = Path.Combine( _path, _family_template_name + _family_template_ext ); fdoc = app.NewFamilyDocument( templateFileName ); if( null == fdoc ) { message = "Cannot create family document."; return Result.Failed; } using( t = new Transaction( fdoc ) ) { t.Start( "Create structural stiffener family" ); CreateExtrusion( fdoc, _countour, _thicknessMm ); t.Commit(); } //fdoc.Title = _family_name; // read-only property bool needToSaveBeforeLoad = false; if( needToSaveBeforeLoad ) { // Save our new family background document // and reopen it in the Revit user interface. string filename = Path.Combine( Path.GetTempPath(), _family_name + _rfa_ext ); SaveAsOptions opt = new SaveAsOptions(); opt.OverwriteExistingFile = true; fdoc.SaveAs( filename, opt ); bool closeAndOpen = true; if( closeAndOpen ) { // Cannot close the newly generated family file // if it is the only open document; that throws // an exception saying "The active document may // not be closed from the API." fdoc.Close( false ); // This obviously invalidates the uidoc // instance on the previously open document. //uiapp.OpenAndActivateDocument( filename ); } } } #endregion // Create a new structural stiffener family #region Load the structural stiffener family // Must be outside transaction; otherwise Revit // throws InvalidOperationException: The document // must not be modifiable before calling LoadFamily. // Any open transaction must be closed prior the call. // Calling this without a prior call to SaveAs // caused a "serious error" in Revit 2012: family = fdoc.LoadFamily( doc ); // Workaround for Revit 2012, // no longer needed in Revit 2014: //doc.LoadFamily( filename, out family ); // Setting the name requires an open // transaction, of course. //family.Name = _family_name; FamilySymbol symbol = null; foreach( ElementId id in family.GetFamilySymbolIds() ) { // Our family only contains one // symbol, so pick it and leave. symbol = doc.GetElement( id ) as FamilySymbol; break; } #endregion // Load the structural stiffener family #region Insert stiffener family instance using( t = new Transaction( doc ) ) { t.Start( "Insert structural stiffener family instance" ); // Setting the name requires an open // transaction, of course. family.Name = _family_name; symbol.Name = _family_name; // Need to activate symbol before // using it in Revit 2016. symbol.Activate(); bool useSimpleInsertionPoint = true; if( useSimpleInsertionPoint ) { //Plane plane = app.Create.NewPlane( new XYZ( 1, 2, 3 ), XYZ.Zero ); //SketchPlane sketch = doc.Create.NewSketchPlane( plane ); //commandData.View.SketchPlane = sketch; XYZ p = uidoc.Selection.PickPoint( "Please pick a point for family instance insertion" ); StructuralType st = StructuralType.UnknownFraming; doc.Create.NewFamilyInstance( p, symbol, st ); } bool useFaceReference = false; if( useFaceReference ) { Reference r = uidoc.Selection.PickObject( ObjectType.Face, "Please pick a point on a face for family instance insertion" ); Element e = doc.GetElement( r.ElementId ); GeometryObject obj = e.GetGeometryObjectFromReference( r ); PlanarFace face = obj as PlanarFace; if( null == face ) { message = "Please select a point on a planar face."; t.RollBack(); return Result.Failed; } else { XYZ p = r.GlobalPoint; //XYZ v = face.Normal.CrossProduct( XYZ.BasisZ ); // 2015 XYZ v = face.FaceNormal.CrossProduct( XYZ.BasisZ ); // 2016 if( v.IsZeroLength() ) { v = face.FaceNormal.CrossProduct( XYZ.BasisX ); } doc.Create.NewFamilyInstance( r, p, v, symbol ); // This throws an exception saying that the face has no reference on it: //doc.Create.NewFamilyInstance( face, p, v, symbol ); } } t.Commit(); } #endregion // Insert stiffener family instance return Result.Succeeded; }