/// <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 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); } }
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); }
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); }
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; } }
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); } RevitProject revitProject; using (var namedPipeClient = new NamedPipeClientStream(".", "PilotRevitAddinPrepareProjectPipe")) { try { namedPipeClient.Connect(10000); } catch (TimeoutException) { return(Result.Failed); } var pipeStream = new StreamString(namedPipeClient); pipeStream.SendCommand(saveFileDialog.FileName); var answer = pipeStream.ReadAnswer(); revitProject = JsonConvert.DeserializeObject <RevitProject>(answer); } var shareFilePathDirectory = Path.GetDirectoryName(revitProject.CentralModelPath); if (shareFilePathDirectory == null) { return(Result.Failed); } if (!Directory.Exists(shareFilePathDirectory)) { Directory.CreateDirectory(shareFilePathDirectory); } var savingSettings = new SaveAsOptions() { OverwriteExistingFile = true }; savingSettings.SetWorksharingOptions(new WorksharingSaveAsOptions() { SaveAsCentral = true }); UpdateProjectSettingsCommand.UpdateProjectInfo(doc, revitProject); doc.SaveAs(revitProject.CentralModelPath, savingSettings); File.Copy(revitProject.CentralModelPath, saveFileDialog.FileName, true); return(Result.Succeeded); }
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { UIApplication uiapp = commandData.Application; WorksetConfiguration openConfig = new WorksetConfiguration(WorksetConfigurationOption.CloseAllWorksets); OpenOptions openOptions = new OpenOptions(); openOptions.SetOpenWorksetsConfiguration(openConfig); openOptions.DetachFromCentralOption = DetachFromCentralOption.DetachAndPreserveWorksets; SaveAsOptions wsaveAs = new SaveAsOptions(); WorksharingSaveAsOptions saveConfig = new WorksharingSaveAsOptions(); saveConfig.SaveAsCentral = true; wsaveAs.SetWorksharingOptions(saveConfig); wsaveAs.OverwriteExistingFile = true; SaveAsOptions saveAs = new SaveAsOptions(); saveAs.OverwriteExistingFile = true; destinationpath = ""; documents.Clear(); string date = DateTime.Now.ToString("dd/MM/yyyy"); int completed = 0; int failed = 0; var exportdialog = new RevitBatchExporter.Dialogs.ExportDialog(); var dialog = exportdialog.ShowDialog(); if (dialog != DialogResult.OK) { return(Result.Cancelled); } bool purge = exportdialog.PurgeCheckBox.Checked; bool removeCADlinks = exportdialog.RemoveCADLinksCheckBox.Checked; bool removeCADImports = exportdialog.RemoveCADImportsCheckBox.Checked; bool removeRVTlinks = exportdialog.RemoveRVTLinksCheckBox.Checked; bool removeSchedules = exportdialog.SchedulesCheckBox.Checked; bool ungroup = exportdialog.UngroupCheckBox.Checked; bool removesheets = exportdialog.SheetsCheckBox.Checked; bool removeviewsON = exportdialog.ViewsONSheetsCheckBox.Checked; bool removeviewsNOT = exportdialog.ViewsNotSheetsCheckBox.Checked; bool exportnwc = exportdialog.NWCCheckBox.Checked; bool exportifc = exportdialog.IFCCheckBox.Checked; bool removeallsheetsviews = false; if (removesheets && removeviewsON && removeviewsNOT) { removeallsheetsviews = true; removesheets = false; removeviewsON = false; removeviewsNOT = false; } string reason = exportdialog.IssueReasonTextBox.Text.TrimEnd().TrimStart(); string customdate = exportdialog.DateTextBox.Text.TrimEnd().TrimStart(); string nameprefix = exportdialog.PrefixTextBox.Text.TrimEnd().TrimStart(); string namesuffix = exportdialog.SuffixTextBox.Text.TrimEnd().TrimStart(); string debugmessage = ""; bool samepath = false; List <string[]> results = new List <string[]>(); foreach (string path in documents) { string destdoc = nameprefix + Path.GetFileName(path.Replace(".rvt", "")) + namesuffix + ".rvt"; if (File.Exists(destinationpath + destdoc)) { samepath = true; break; } string pathOnly = Path.GetDirectoryName(path) + "\\"; if (pathOnly == destinationpath) { samepath = true; break; } } if (samepath) { TaskDialog td = new TaskDialog("XPORT"); td.MainInstruction = "Some documents already exist in the destination path."; td.MainContent = "The files will be overritten, do you wish to continue?"; td.AddCommandLink(TaskDialogCommandLinkId.CommandLink1, "Continue"); td.AddCommandLink(TaskDialogCommandLinkId.CommandLink2, "Cancel"); switch (td.Show()) { case TaskDialogResult.CommandLink1: break; case TaskDialogResult.CommandLink2: return(Result.Cancelled); default: return(Result.Cancelled); } } uiapp.DialogBoxShowing += new EventHandler <DialogBoxShowingEventArgs>(OnDialogBoxShowing); uiapp.Application.FailuresProcessing += FailureProcessor; DateTime start = DateTime.Now; foreach (string path in documents) { string[] result = new string[5]; if (!File.Exists(path)) { result[0] = Path.GetFileName(path.Replace(".rvt", "")); result[1] = "false"; result[2] = "false"; result[3] = "File Not Found"; result[4] = ""; results.Add(result); failed++; continue; } try { DateTime s1 = DateTime.Now; Document doc = uiapp.Application.OpenDocumentFile(ModelPathUtils.ConvertUserVisiblePathToModelPath(path), openOptions); Transaction t1 = new Transaction(doc, "XP"); t1.Start(); if (customdate != "") { date = customdate; } try { doc.ProjectInformation.LookupParameter("Model Issue Date").Set(date); } catch { }; try { doc.ProjectInformation.IssueDate = date; } catch { }; if (reason != "") { try { doc.ProjectInformation.LookupParameter("Model Issue Reason").Set(reason); } catch { } } if (removeCADlinks) { DeleteCADLinks(doc); } if (removeCADImports) { DeleteCADImports(doc); } if (removeRVTlinks) { DeleteRVTLinks(doc); } if (removeviewsNOT) { DeleteViewsNotOnSheets(doc); } if (removeviewsON) { DeleteViewsONSheets(doc); } if (removesheets) { DeleteSheets(doc); } if (removeallsheetsviews) { DeleteAllViewsSheets(doc); } if (removeSchedules) { DeleteSchedules(doc); } if (ungroup) { UngroupGroups(doc); } if (purge) { PurgeDocument(doc); } t1.Commit(); string docname = doc.Title; docname = docname.Replace("_detached", ""); if (docname.EndsWith(".rvt")) { docname = docname.Replace(".rvt", ""); } if (nameprefix != "") { docname = nameprefix + docname; } if (namesuffix != "") { docname = docname + namesuffix; } bool nwcexported = false; bool ifcexported = false; if (exportnwc) { nwcexported = ExportNWC(doc, destinationpath, docname); } if (exportifc) { ifcexported = ExportIFC(doc, destinationpath, docname); } try { if (doc.IsWorkshared) { doc.SaveAs(destinationpath + docname + ".rvt", wsaveAs); doc.Close(false); } else { doc.SaveAs(destinationpath + docname + ".rvt", saveAs); doc.Close(false); } } catch { doc.Close(false); } try { Directory.Delete(destinationpath + docname + "_backup", true); } catch { } try { Directory.Delete(destinationpath + "Revit_temp", true); } catch { } doc.Dispose(); completed++; DateTime e1 = DateTime.Now; int h = (e1 - s1).Hours; int m = (e1 - s1).Minutes; int s = (e1 - s1).Seconds; result[0] = Path.GetFileName(path.Replace(".rvt", "")); result[1] = nwcexported.ToString(); result[2] = ifcexported.ToString(); result[3] = "Completed"; result[4] = h.ToString() + ":" + m.ToString() + ":" + s.ToString(); results.Add(result); } catch (Exception e) { debugmessage = "\n" + "\n" + e.Message; result[0] = Path.GetFileName(path.Replace(".rvt", "")); result[1] = "false"; result[2] = "false"; result[3] = "Failed"; result[4] = ""; results.Add(result); failed++; } } uiapp.DialogBoxShowing -= OnDialogBoxShowing; uiapp.Application.FailuresProcessing -= FailureProcessor; DateTime end = DateTime.Now; int hours = (end - start).Hours; int minutes = (end - start).Minutes; int seconds = (end - start).Seconds; //TaskDialog.Show("Results", "Completed: " + completed.ToString() + "\nFailed: " + failed.ToString() + "\nTotal Time: " + hours.ToString() + " h " + minutes.ToString() + " m " + seconds.ToString() + " s" + debugmessage); TaskDialog rd = new TaskDialog("XPORT"); rd.MainInstruction = "Results"; rd.MainContent = "Exported to: " + destinationpath + "\n" + "Completed: " + completed.ToString() + "\nFailed: " + failed.ToString() + "\nTotal Time: " + hours.ToString() + " h " + minutes.ToString() + " m " + seconds.ToString() + " s"; rd.AddCommandLink(TaskDialogCommandLinkId.CommandLink1, "Close"); rd.AddCommandLink(TaskDialogCommandLinkId.CommandLink2, "Show Details"); documents.Clear(); destinationpath = ""; switch (rd.Show()) { case TaskDialogResult.CommandLink1: return(Result.Succeeded); case TaskDialogResult.CommandLink2: var resultsdialog = new RevitBatchExporter.Dialogs.ResultsDialog(); foreach (string[] r in results) { var item = new ListViewItem(r); resultsdialog.ResultsView.Items.Add(item); } var rdialog = resultsdialog.ShowDialog(); return(Result.Succeeded); default: return(Result.Succeeded); } }
public Result Execute( ExternalCommandData commandData, ref string message, ElementSet elements) { UIApplication uiapp = commandData.Application; Application app = uiapp.Application; int check = 0; int sheetsNumber = 0; int viewsNumber = 0; int schedulesNumber = 0; int furnitureElements = 0; using (var formOpen = new FormOpenFile()) { formOpen.ShowDialog(); string fileName = formOpen.filePath; ModelPath modelP = ModelPathUtils.ConvertUserVisiblePathToModelPath(fileName); if (formOpen.DialogResult == winForms.DialogResult.OK) { OpenOptions optionDetach = new OpenOptions(); optionDetach.DetachFromCentralOption = DetachFromCentralOption.DetachAndPreserveWorksets; optionDetach.Audit = true; openDoc = app.OpenDocumentFile(modelP, optionDetach); IEnumerable <ViewFamilyType> viewFamilyTypes = from elem in new FilteredElementCollector(openDoc).OfClass(typeof(ViewFamilyType)) let type = elem as ViewFamilyType where type.ViewFamily == ViewFamily.ThreeDimensional select type; IEnumerable <ElementId> sheetIds = from elem in new FilteredElementCollector(openDoc).OfCategory(BuiltInCategory.OST_Sheets) select elem.Id; IEnumerable <ElementId> viewsIds = from elem in new FilteredElementCollector(openDoc).OfCategory(BuiltInCategory.OST_Views) where elem.Name != "Clarity_IFC _3D" select elem.Id; #if REVIT2019 IEnumerable <ElementId> schedulesIds = from elem in new FilteredElementCollector(openDoc).OfCategory(BuiltInCategory.OST_Schedules) select elem.Id; #elif REVIT2017 #endif List <BuiltInCategory> builtInCats = new List <BuiltInCategory>(); builtInCats.Add(BuiltInCategory.OST_Furniture); builtInCats.Add(BuiltInCategory.OST_Casework); builtInCats.Add(BuiltInCategory.OST_Planting); builtInCats.Add(BuiltInCategory.OST_Entourage); builtInCats.Add(BuiltInCategory.OST_Railings); builtInCats.Add(BuiltInCategory.OST_StairsRailing); ElementMulticategoryFilter filter1 = new ElementMulticategoryFilter(builtInCats); View3D view3d = null; using (Transaction tran = new Transaction(openDoc)) { tran.Start("Clarity Setup"); FilteredWorksetCollector worksetCollector = new FilteredWorksetCollector(openDoc).OfKind(WorksetKind.UserWorkset); try { view3d = View3D.CreateIsometric(openDoc, viewFamilyTypes.First().Id); view3d.Name = "Clarity_IFC _3D"; //uiapp.ActiveUIDocument.ActiveView = view3d; foreach (Workset e in worksetCollector) { view3d.SetWorksetVisibility(e.Id, WorksetVisibility.Visible); } } catch (Exception ex) { TaskDialog.Show("Error", "Name already taken" + "\n" + ex.Message); } try { sheetsNumber += sheetIds.Count(); if (sheetIds.Count() > 0) { openDoc.Delete(sheetIds.ToList()); } } catch (Exception ex) { TaskDialog.Show("Sheets Error", ex.Message); } try { viewsNumber += viewsIds.Count(); if (viewsIds.Count() > 0) { openDoc.Delete(viewsIds.ToList()); } } catch (Exception ex) { TaskDialog.Show("Views Error", ex.Message); } #if REVIT2019 try { if (schedulesIds.Count() > 0) { openDoc.Delete(schedulesIds.ToList()); schedulesNumber += schedulesIds.Count(); } } catch (Exception ex) { TaskDialog.Show("Schedule Error", ex.Message); } #elif REVIT2017 #endif if (formOpen.cleanArchModel) { int furnitureError = 0; ICollection <ElementId> toDelete = new FilteredElementCollector(openDoc).WherePasses(filter1).ToElementIds(); if (toDelete.Count() > 0) { string lastEx = ""; foreach (ElementId id in toDelete) { try { openDoc.Delete(id); furnitureElements += 1; } catch (Exception ex) { lastEx = $"{ex.Message}\n"; } } //Debug.WriteLine(lastEx.Message); TaskDialog.Show("Error", $"{furnitureElements} elements deleted. {furnitureError} cannot be deleted. Errors:\n{lastEx}"); } } if (formOpen.purgeModel) { ICollection <ElementId> purgeableElements = null; PurgeTool.GetPurgeableElements(openDoc, ref purgeableElements); try { while (purgeableElements.Count > 0) { //TaskDialog.Show("Purge Count", purgeableElements.Count().ToString()); PurgeTool.GetPurgeableElements(openDoc, ref purgeableElements); openDoc.Delete(purgeableElements); } } catch (Exception ex) { TaskDialog.Show("Purge Error", ex.Message); } } tran.Commit(); } SaveAsOptions saveOpt = new SaveAsOptions(); WorksharingSaveAsOptions wos = new WorksharingSaveAsOptions(); wos.SaveAsCentral = true; saveOpt.Compact = true; saveOpt.SetWorksharingOptions(wos); saveOpt.OverwriteExistingFile = true; openDoc.SaveAs(modelP, saveOpt); check += 1; } else { TaskDialog.Show("Result", "Command aborted."); } if (check > 0) { ICollection <ElementId> viewsId = new FilteredElementCollector(openDoc).OfCategory(BuiltInCategory.OST_Views).ToElementIds(); string viewsNames = ""; foreach (ElementId eid in viewsId) { viewsNames += openDoc.GetElement(eid).Name + Environment.NewLine; } TaskDialog.Show("Result", String.Format("Sheets deleted {0} \nViews deleted {1} \nSchedules deleted {2} \nViews in the model {3}", sheetsNumber, viewsNumber, furnitureElements, viewsNames)); } //PurgeMaterials(openDoc); too slooooooow }//close using return(Result.Succeeded); }
/// <summary> /// delete elements depends on the input params.json file /// </summary> /// <param name="data"></param> public static void DeleteAllElements(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)); } // If the input revit model passed is a workshared revit file then by default the Design Automation // bridge will open the model detached from central, opting DetachAndPreserveWorsets option. // Non-worshared revit file will be load as is. Document doc = data.RevitDoc; if (doc == null) { throw new InvalidOperationException("Could not open document."); } // For CountIt workItem: If RvtParameters is null, count all types DeleteElementsParams deleteElementsParams = DeleteElementsParams.Parse("params.json"); using (Transaction transaction = new Transaction(doc)) { transaction.Start("Delete Elements"); if (deleteElementsParams.walls) { FilteredElementCollector col = new FilteredElementCollector(doc).OfClass(typeof(Wall)); doc.Delete(col.ToElementIds()); } if (deleteElementsParams.floors) { FilteredElementCollector col = new FilteredElementCollector(doc).OfClass(typeof(Floor)); doc.Delete(col.ToElementIds()); } if (deleteElementsParams.doors) { FilteredElementCollector collector = new FilteredElementCollector(doc); ICollection <ElementId> collection = collector.OfClass(typeof(FamilyInstance)) .OfCategory(BuiltInCategory.OST_Doors) .ToElementIds(); doc.Delete(collection); } if (deleteElementsParams.windows) { FilteredElementCollector collector = new FilteredElementCollector(doc); ICollection <ElementId> collection = collector.OfClass(typeof(FamilyInstance)) .OfCategory(BuiltInCategory.OST_Windows) .ToElementIds(); doc.Delete(collection); } transaction.Commit(); } ModelPath path = ModelPathUtils.ConvertUserVisiblePathToModelPath("result.rvt"); // If a worshared file is opened as a part of this addin then the new file will be // saved as central. SaveAsOptions opts = new SaveAsOptions(); if (doc.IsWorkshared) { opts.SetWorksharingOptions(new WorksharingSaveAsOptions { SaveAsCentral = true }); WorksharingUtils.RelinquishOwnership(doc, new RelinquishOptions(true), new TransactWithCentralOptions()); } doc.SaveAs(path, new SaveAsOptions()); }
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { UIApplication uiapp = commandData.Application; DestinationPath = string.Empty; Documents = new List <string>(); Splash = string.Empty; Errors = new List <string[]>(); string date = DateTime.Now.ToString("dd/MM/yyyy"); int completed = 0; int failed = 0; ExportDialog exportdialog = new ExportDialog(); System.Windows.Forms.DialogResult dialog = exportdialog.ShowDialog(); if (dialog != System.Windows.Forms.DialogResult.OK) { return(Result.Cancelled); } WorksetConfiguration openconfig = new WorksetConfiguration(WorksetConfigurationOption.CloseAllWorksets); OpenOptions openoptions = new OpenOptions(); openoptions.SetOpenWorksetsConfiguration(openconfig); if (exportdialog.DiscardRadioButton.Checked) { openoptions.DetachFromCentralOption = DetachFromCentralOption.DetachAndDiscardWorksets; } else { openoptions.DetachFromCentralOption = DetachFromCentralOption.DetachAndPreserveWorksets; } SaveAsOptions worksharedsaveas = new SaveAsOptions(); WorksharingSaveAsOptions saveConfig = new WorksharingSaveAsOptions { SaveAsCentral = true }; worksharedsaveas.SetWorksharingOptions(saveConfig); worksharedsaveas.OverwriteExistingFile = true; SaveAsOptions regularsaveas = new SaveAsOptions { OverwriteExistingFile = true }; if (exportdialog.AuditCheckBox.Checked) { openoptions.Audit = true; } if (exportdialog.SafeNameTextbox.Text.Trim() != string.Empty) { Splash = exportdialog.SafeNameTextbox.Text.Trim(); } string customdate = exportdialog.DateTimePickerIssue.Value.ToString("yyyy/MM/dd"); string nameprefix = exportdialog.PrefixTextBox.Text.Trim(); string namesuffix = exportdialog.SuffixTextBox.Text.Trim(); bool samepath = false; List <string[]> results = new List <string[]>(); foreach (string path in Documents) { string destdoc = nameprefix + Path.GetFileNameWithoutExtension(path) + namesuffix + ".rvt"; if (File.Exists(DestinationPath + destdoc)) { samepath = true; break; } string pathonly = Path.GetDirectoryName(path) + "\\"; if (pathonly == DestinationPath) { samepath = true; break; } } if (samepath) { TaskDialog td = new TaskDialog("Export") { MainInstruction = "Some documents already exist in the destination path.", MainContent = "The files will be overritten, do you wish to continue?" }; td.AddCommandLink(TaskDialogCommandLinkId.CommandLink1, "Continue"); td.AddCommandLink(TaskDialogCommandLinkId.CommandLink2, "Cancel"); switch (td.Show()) { case TaskDialogResult.CommandLink1: break; case TaskDialogResult.CommandLink2: return(Result.Cancelled); default: return(Result.Cancelled); } } uiapp.DialogBoxShowing += new EventHandler <DialogBoxShowingEventArgs>(OnDialogBoxShowing); uiapp.Application.FailuresProcessing += FailureProcessor; DateTime start = DateTime.Now; foreach (string path in Documents) { string[] result = new string[6]; string resultmessage = string.Empty; if (!File.Exists(path)) { result[0] = Path.GetFileName(path); result[1] = "File Not Found"; result[2] = string.Empty; results.Add(result); failed++; continue; } DateTime s1 = DateTime.Now; Document doc = null; //try //{ doc = uiapp.Application.OpenDocumentFile(ModelPathUtils.ConvertUserVisiblePathToModelPath(path), openoptions); string docname = nameprefix + Path.GetFileNameWithoutExtension(path) + namesuffix; using (Transaction t = new Transaction(doc, "Export")) { t.Start(); if (exportdialog.AutoCheckBox.Checked) { doc.ProjectInformation.IssueDate = date; } else { doc.ProjectInformation.IssueDate = customdate; } if (exportdialog.RemoveCADLinksCheckBox.Checked) { DeleteCADLinks(doc); } if (exportdialog.RemoveCADImportsCheckBox.Checked) { DeleteCADImports(doc); } if (exportdialog.RemoveRVTLinksCheckBox.Checked) { DeleteRVTLinks(doc); } DeleteViewsAndSheets(doc, exportdialog.ViewsONSheetsCheckBox.Checked, exportdialog.ViewsNOTSheetsCheckBox.Checked, exportdialog.SheetsCheckBox.Checked, exportdialog.TemplatesCheckBox.Checked); if (exportdialog.RemoveSchedulesCheckBox.Checked) { DeleteSchedules(doc); } if (exportdialog.UngroupCheckBox.Checked) { UngroupGroups(doc); } if (exportdialog.PurgeCheckBox.Checked) { PurgeDocument(doc); } t.Commit(); } if (doc.IsWorkshared) { doc.SaveAs(DestinationPath + docname + ".rvt", worksharedsaveas); } else { doc.SaveAs(DestinationPath + docname + ".rvt", regularsaveas); } doc.Close(false); string backupfolder = DestinationPath + docname + "_backup"; string tempfolder = DestinationPath + "Revit_temp"; if (Directory.Exists(backupfolder)) { Directory.Delete(backupfolder, true); } if (Directory.Exists(tempfolder)) { Directory.Delete(tempfolder, true); } resultmessage = "Completed"; completed++; //} // catch (Exception e) //{ // try // { // doc.Close(false); // } // catch { } // resultmessage = e.Message; // failed++; //} DateTime e1 = DateTime.Now; int h = (e1 - s1).Hours; int m = (e1 - s1).Minutes; int s = (e1 - s1).Seconds; result[0] = Path.GetFileName(path); result[1] = resultmessage; result[2] = h.ToString() + ":" + m.ToString() + ":" + s.ToString(); results.Add(result); } uiapp.DialogBoxShowing -= OnDialogBoxShowing; uiapp.Application.FailuresProcessing -= FailureProcessor; DateTime end = DateTime.Now; int hours = (end - start).Hours; int minutes = (end - start).Minutes; int seconds = (end - start).Seconds; TaskDialog rd = new TaskDialog("Export") { MainInstruction = "Results", MainContent = "Exported to: " + DestinationPath + "\n" + "Completed: " + completed.ToString() + "\nFailed: " + failed.ToString() + "\nTotal Time: " + hours.ToString() + " h " + minutes.ToString() + " m " + seconds.ToString() + " s" }; rd.AddCommandLink(TaskDialogCommandLinkId.CommandLink1, "Close"); rd.AddCommandLink(TaskDialogCommandLinkId.CommandLink2, "Show Details"); switch (rd.Show()) { case TaskDialogResult.CommandLink1: return(Result.Succeeded); case TaskDialogResult.CommandLink2: ResultsDialog resultsdialog = new ResultsDialog(); foreach (string[] r in results) { var item = new System.Windows.Forms.ListViewItem(r); resultsdialog.ResultsView.Items.Add(item); } var rdialog = resultsdialog.ShowDialog(); return(Result.Succeeded); default: return(Result.Succeeded); } }
public bool UpgradeRevitProject(Document document, string revitFileName) { bool upgraded = false; try { BasicFileInfo basicFileInfo = BasicFileInfo.Extract(revitFileName); FileSaveAsOptions fileSaveAsOptions = projectSettings.UpgradeOptions.UpgradeVersionSaveAsOptions; LogFileManager.AppendLog("Upgrade Revit Project: " + revitFileName); LogFileManager.AppendLog("The Original Revit file was saved in " + basicFileInfo.SavedInVersion); SaveAsOptions saveAsOptions = new SaveAsOptions(); saveAsOptions.OverwriteExistingFile = true; if (basicFileInfo.IsWorkshared) { WorksharingSaveAsOptions worksharingSaveAsOptions = new WorksharingSaveAsOptions(); worksharingSaveAsOptions.OpenWorksetsDefault = FindWorksetOption(fileSaveAsOptions.WorksetConfiguration); worksharingSaveAsOptions.SaveAsCentral = fileSaveAsOptions.MakeCentral; saveAsOptions.MaximumBackups = fileSaveAsOptions.NumOfBackups; saveAsOptions.SetWorksharingOptions(worksharingSaveAsOptions); } bool isFinalUpgrade = projectSettings.UpgradeOptions.IsFinalUpgrade; if (isFinalUpgrade) { string backupDirectory = FindBackupDirectory(revitFileName); if (!string.IsNullOrEmpty(backupDirectory)) { string fileName = Path.GetFileName(revitFileName); string newFilePath = Path.Combine(backupDirectory, fileName); File.Copy(revitFileName, newFilePath, true); if (File.Exists(newFilePath)) { document.SaveAs(revitFileName, saveAsOptions); LogFileManager.AppendLog("Backup Saved: " + newFilePath); if (fileSaveAsOptions.Relinquish) { RelinquishOptions roptions = new RelinquishOptions(false); roptions.UserWorksets = true; TransactWithCentralOptions coptions = new TransactWithCentralOptions(); WorksharingUtils.RelinquishOwnership(document, roptions, coptions); LogFileManager.AppendLog("Relinquish all worksets created by the current user."); } upgraded = true; } } else { LogFileManager.AppendLog("File Not Saved", "The backup directory cannot be found."); upgraded = false; } } else { string reviewDirectory = FindReviewDirectory(revitFileName); if (string.IsNullOrEmpty(reviewDirectory)) { reviewDirectory = fileSaveAsOptions.ReviewLocation; } string fileName = Path.GetFileName(revitFileName); if (!string.IsNullOrEmpty(reviewDirectory)) { revitFileName = Path.Combine(reviewDirectory, fileName); document.SaveAs(revitFileName, saveAsOptions); LogFileManager.AppendLog("File Saved: " + revitFileName); if (fileSaveAsOptions.Relinquish) { RelinquishOptions roptions = new RelinquishOptions(false); roptions.UserWorksets = true; TransactWithCentralOptions coptions = new TransactWithCentralOptions(); WorksharingUtils.RelinquishOwnership(document, roptions, coptions); LogFileManager.AppendLog("Relinquish all worksets created by the current user."); } upgraded = true; } else { LogFileManager.AppendLog("File Not Saved", "The review directory cannot be found."); upgraded = false; } } } catch (Exception ex) { string message = ex.Message; LogFileManager.AppendLog("[Error] Upgrade Revit Project", message); } return(upgraded); }
public SetupCWSRequest(UIApplication uiApp, String text) { MainUI uiForm = BARevitTools.Application.thisApp.newMainUi; RVTDocument doc = uiApp.ActiveUIDocument.Document; //Make the transaction options TransactWithCentralOptions TWCOptions = new TransactWithCentralOptions(); //Make the relinquish options RelinquishOptions relinquishOptions = new RelinquishOptions(true); //Make the synchronization options SynchronizeWithCentralOptions SWCOptions = new SynchronizeWithCentralOptions(); SWCOptions.Compact = true; SWCOptions.SetRelinquishOptions(relinquishOptions); //Make the worksharing SaveAs options WorksharingSaveAsOptions worksharingSaveOptions = new WorksharingSaveAsOptions(); worksharingSaveOptions.SaveAsCentral = true; worksharingSaveOptions.OpenWorksetsDefault = SimpleWorksetConfiguration.AllWorksets; //Make the save options SaveOptions projectSaveOptions = new SaveOptions(); projectSaveOptions.Compact = true; //Finally, make the SaveAs options SaveAsOptions projectSaveAsOptions = new SaveAsOptions(); projectSaveAsOptions.Compact = true; projectSaveAsOptions.OverwriteExistingFile = true; projectSaveAsOptions.SetWorksharingOptions(worksharingSaveOptions); //The worksetsToAdd list will the names of the worksets to create List <string> worksetsToAdd = new List <string>(); //Collect the names of the worksets from the defaults foreach (string item in uiForm.setupCWSDefaultListBox.Items) { worksetsToAdd.Add(item); } //Collect any names selected in the extended list foreach (string item in uiForm.setupCWSExtendedListBox.CheckedItems) { worksetsToAdd.Add(item); } //Collect the names of any user defined worksets foreach (DataGridViewRow row in uiForm.setupCWSUserDataGridView.Rows) { try { if (row.Cells[0].Value.ToString() != "") { worksetsToAdd.Add(row.Cells[0].Value.ToString()); } } catch { continue; } } //Collect all worksets in the current project List <Workset> worksets = new FilteredWorksetCollector(doc).Cast <Workset>().ToList(); List <string> worksetNames = new List <string>(); //Cycle through the worksets in the project if (worksets.Count > 0) { foreach (Workset workset in worksets) { //If Workset1 exists, rename it Arch if (workset.Name == "Workset1") { try { WorksetTable.RenameWorkset(doc, workset.Id, "Arch"); worksetNames.Add("Arch"); break; } catch { continue; } } else { worksetNames.Add(workset.Name); } } } //If the file has been saved and is workshared, continue if (doc.IsWorkshared && doc.PathName != "") { //Start a transaction Transaction t1 = new Transaction(doc, "CreateWorksets"); t1.Start(); //For each workset name in the list of worksets to add, continue foreach (string worksetName in worksetsToAdd) { //If the list of existing worksets does not contain the workset to make, continue if (!worksetNames.Contains(worksetName)) { //Create the new workset Workset.Create(doc, worksetName); } } t1.Commit(); try { //Save the project with the save options, then synchronize doc.Save(projectSaveOptions); doc.SynchronizeWithCentral(TWCOptions, SWCOptions); } catch { //Else, try using the SaveAs method, then synchronize doc.SaveAs(doc.PathName, projectSaveAsOptions); doc.SynchronizeWithCentral(TWCOptions, SWCOptions); } } //If the project has been saved and the document is not workshared, continue else if (!doc.IsWorkshared && doc.PathName != "") { //Make the document workshared and set the default worksets doc.EnableWorksharing("Shared Levels and Grids", "Arch"); //Add the default worksets to the list of pre-existing worksets worksetNames.Add("Shared Levels and Grids"); worksetNames.Add("Arch"); //Start the transaction Transaction t1 = new Transaction(doc, "MakeWorksets"); t1.Start(); foreach (string worksetName in worksetsToAdd) { //Create the workset if it does not exist in the list of pre-existing worksets if (!worksetNames.Contains(worksetName)) { Workset.Create(doc, worksetName); } } t1.Commit(); //Use the SaveAs method for saving the file, then synchronize doc.SaveAs(doc.PathName, projectSaveAsOptions); doc.SynchronizeWithCentral(TWCOptions, SWCOptions); } else { //If the project has not been saved, let the user know to save it first somewhere MessageBox.Show("Project file needs to be saved somewhere before it can be made a central model"); } }
// public void ReadAllFiles(string directory) // { // var fileNames = Directory.GetFiles(directory); // List<string> datedNames = new List<string>; // } // public string ReadDate(string filename) // { // if (filename.Length > 8) // { // var dateTest = filename.Substring(0,8); // } // if (int.TryParse(dateTest, out fileDate)) // { // return DateTime.ParseExact(dateStub, "yyyyMMdd", null); // } // else { return DateTime.Today;} // } public Result Execute( ExternalCommandData commandData, ref string message, ElementSet elements) { Autodesk.Revit.UI.UIApplication m_app; m_app = commandData.Application; Autodesk.Revit.ApplicationServices.Application app = m_app.Application; // Check worksharing mode of each document // Open Revit projects OpenFileDialog theDialogRevit = new OpenFileDialog(); theDialogRevit.Title = "Select Revit Project Files"; theDialogRevit.Filter = "RVT files|*.rvt"; theDialogRevit.FilterIndex = 1; theDialogRevit.InitialDirectory = @"D:\"; theDialogRevit.Multiselect = true; if (theDialogRevit.ShowDialog() == DialogResult.OK) { DateTime todaysDate = DateTime.Today; string dateStamp = string.Format("{0}", todaysDate.ToString("yyyyMMdd")); string mpath = ""; string mpathOnlyFilename = ""; FolderBrowserDialog folderBrowserDialog1 = new FolderBrowserDialog(); string currentFolder = Path.GetDirectoryName(theDialogRevit.FileName); folderBrowserDialog1.Description = "Select Folder Where Revit Projects to be Saved in Local"; //folderBrowserDialog1.RootFolder = Environment.SpecialFolder.MyComputer; folderBrowserDialog1.SelectedPath = currentFolder; if (folderBrowserDialog1.ShowDialog() == DialogResult.OK) { mpath = folderBrowserDialog1.SelectedPath; foreach (String projectPath in theDialogRevit.FileNames) { // convert input string to directory info. FileInfo filePath = new FileInfo(projectPath); ModelPath mp = ModelPathUtils.ConvertUserVisiblePathToModelPath(filePath.FullName); OpenOptions opt = new OpenOptions(); opt.DetachFromCentralOption = DetachFromCentralOption.DetachAndPreserveWorksets; mpathOnlyFilename = string.Format("{0}_{1}", dateStamp, filePath.Name); Document openedDoc = app.OpenDocumentFile(mp, opt); SaveAsOptions options = new SaveAsOptions(); WorksharingSaveAsOptions wsOptions = new WorksharingSaveAsOptions(); options.OverwriteExistingFile = true; wsOptions.SaveAsCentral = true; options.SetWorksharingOptions(wsOptions); ModelPath modelPathout = ModelPathUtils.ConvertUserVisiblePathToModelPath(mpath + "\\" + mpathOnlyFilename); openedDoc.SaveAs(modelPathout, options); openedDoc.Close(false); } } // Scan backup folder and retrieve date prefixes //List<string> filesToDelete = ReadAllFiles(mpath); } return(Result.Succeeded); }