public Result Execute( ExternalCommandData revit, ref string message, ElementSet elements) { UIApplication uiapp = revit.Application; UIDocument uidoc = uiapp.ActiveUIDocument; Document doc = uidoc.Document; string path = doc.PathName; BasicFileInfo info = BasicFileInfo.Extract( path); DocumentVersion v = info.GetDocumentVersion(); int n = v.NumberOfSaves; Util.InfoMsg(string.Format( "Document '{0}' has GUID {1} and {2} save{3}.", path, v.VersionGUID, n, Util.PluralSuffix(n))); return(Result.Succeeded); }
private void DeleteFile(UIDocument UIdoc, Transaction t) { Document _doc = UIdoc.Document; string _filePath = BasicFileInfo.Extract(_doc.PathName).CentralPath; string _filename = Path.GetFileNameWithoutExtension(_filePath); string _filedir = Path.GetDirectoryName(_filePath); string _backupDir = _filename + "_backup"; string _corruptFileName = "corrupt"; string fullPath = Path.Combine(_filedir, _backupDir, _corruptFileName); if (File.Exists(fullPath)) { MessageBoxResult question = MessageBox.Show($"Удалить файл {fullPath} ?", "Удалить коррупцию", MessageBoxButton.OKCancel, MessageBoxImage.Warning); if (question == MessageBoxResult.OK) { t.Start("Удалить файл Corrupt"); try { File.Delete(fullPath); } catch (IOException exception) { MessageBox.Show("Ошибка", exception.Message); } TaskDialog.Show("Удалить файл", "Файл " + _corruptFileName + " удален."); t.Commit(); } } else { MessageBox.Show($"Файл {_corruptFileName} не найден по пути {fullPath}", "Ошибка"); } }
public static void DocClosed(object sender, DocumentClosingEventArgs args) { Document currentDoc = args.Document; Autodesk.Revit.ApplicationServices.Application uiApp = currentDoc.Application; if (!currentDoc.IsFamilyDocument) { EventData ptdata = new EventData("ProjectTime"); ptdata.DirSetup(); string fp = currentDoc.PathName; BasicFileInfo bfi = BasicFileInfo.Extract(fp); string fpath = bfi.CentralPath.Split('\\').Last().Split('.').First(); string pnum = currentDoc.ProjectInformation.Number.ToString(); EventData odata = new EventData(pnum); string[] Open = File.ReadAllLines(odata.FileName); DateTime dtin = DateTime.MinValue; DateTime.TryParse(Open.Last().Split(',')[3], out dtin); if (dtin != DateTime.MinValue) { long timedif = ptdata.Time.Ticks - dtin.Ticks; double hours = TimeSpan.FromTicks(timedif).TotalHours; string[] lines = new string[1]; lines[0] = ptdata.User + "," + pnum + "," + fpath + "," + ptdata.Time + "," + hours.ToString() + "," + Open.Last().Split(',')[4]; File.AppendAllLines(ptdata.FileName, lines); File.Delete(odata.FileName); } } }
private void OnDocumentSynchronizingWithCentral(object sender, DocumentSynchronizingWithCentralEventArgs e) { tempPath = Path.GetDirectoryName(BasicFileInfo.Extract(e.Document.PathName).CentralPath) + @"\tracker\"; try{ var path = tempPath + documentName + "_" + username; if (!File.Exists(path)) { var di = Directory.CreateDirectory(Path.GetDirectoryName(path)); di.Attributes = FileAttributes.Directory | FileAttributes.Hidden; } if (deletedList.Count > 0) { using (var tw = new StreamWriter(path, true, System.Text.Encoding.GetEncoding(1251))) { deletedList.ForEach((item) => { tw.WriteLine(item.ToString()); }); } } deletedList.Clear(); addedList.Clear(); } catch { } }
/// <summary> /// Retrieve the project identification information /// to store in the external database and return it /// as a dictionary in a JSON formatted string. /// </summary> string GetProjectDataJson( //string project_id, Document doc) { string path = doc.PathName.Replace('\\', '/'); BasicFileInfo file_info = BasicFileInfo.Extract(path); DocumentVersion doc_version = file_info.GetDocumentVersion(); ModelPath model_path = doc.GetWorksharingCentralModelPath(); string central_server_path = null != model_path ? model_path.CentralServerPath : string.Empty; // Hand-written JSON formatting. string s = string.Format( //"\"_id\": \"{0}\"," "\"projectinfo_uid\": \"{0}\"," + "\"versionguid\": \"{1}\"," + "\"numberofsaves\": {2}," + "\"title\": \"{3}\"," + "\"centralserverpath\": \"{4}\"," + "\"path\": \"{5}\"," + "\"computername\": \"{6}\"," + "\"jid\": \"{7}\"", //project_id, doc.ProjectInformation.UniqueId, doc_version.VersionGUID, doc_version.NumberOfSaves, doc.Title, central_server_path, path, System.Environment.MachineName, Util.GetProjectIdentifier(doc)); return("{" + s + "}"); #region Use JavaScriptSerializer #if USE_JavaScriptSerializer // Use JavaScriptSerializer to format JSON data. ProjectData project_data = new ProjectData() { projectinfo_uid = doc.ProjectInformation.UniqueId, versionguid = doc_version.VersionGUID.ToString(), numberofsaves = doc_version.NumberOfSaves, title = doc.Title, centralserverpath = central_server_path, path = path, computername = System.Environment.MachineName }; return(new JavaScriptSerializer().Serialize( project_data)); #endif // USE_JavaScriptSerializer #endregion // Use JavaScriptSerializer }
public static void UpdateSplashPage(Document currentDoc) { string fp = currentDoc.PathName; BasicFileInfo bfi = BasicFileInfo.Extract(fp); string proj = bfi.CentralPath.Split('\\').Last().Split('.').First(); string pdir = DBIdentifiers.Database + "ProjectData\\" + proj + "\\"; if (Directory.Exists(pdir)) { string[] files = Directory.GetFiles(pdir); PData data = PDataFromRevit(currentDoc); PDataParamUpdates(currentDoc, data); } }
public static void ViewChangeTime(object sender, ViewActivatedEventArgs args) { View closingView = args.PreviousActiveView; View openedView = args.CurrentActiveView; Document closingDoc = closingView.Document; Document openedDoc = openedView.Document; if (closingView != openedView) { EventData rdata = new EventData("ProjectTime"); rdata.DirSetup(); string fp = closingDoc.PathName; BasicFileInfo bfi = BasicFileInfo.Extract(fp); string fpath = bfi.CentralPath.Split('\\').Last().Split('.').First(); string pnum = closingDoc.ProjectInformation.Number.ToString(); EventData cdata = new EventData(pnum); string[] Open = File.ReadAllLines(cdata.FileName); DateTime dtin = DateTime.MinValue; DateTime.TryParse(Open.Last().Split(',')[3], out dtin); if (dtin != DateTime.MinValue) { long timedif = rdata.Time.Ticks - dtin.Ticks; double hours = TimeSpan.FromTicks(timedif).TotalHours; string[] clines = new string[1]; clines[0] = rdata.User + "," + pnum + "," + fpath + "," + rdata.Time + "," + hours.ToString() + "," + Open.Last().Split(',')[4]; File.AppendAllLines(rdata.FileName, clines); File.Delete(cdata.FileName); } if (!openedDoc.IsFamilyDocument) { string ofp = openedDoc.PathName; BasicFileInfo obfi = BasicFileInfo.Extract(fp); string ofpath = obfi.CentralPath.Split('\\').Last().Split('.').First(); string opnum = openedDoc.ProjectInformation.Number.ToString(); EventData odata = new EventData(opnum); string[] olines = new string[1]; olines[0] = odata.User + "," + opnum + "," + ofpath + "," + odata.Time + "," + openedView.Name; File.AppendAllLines(odata.FileName, olines); } } }
private static void OnDocumentOpening(object source, DocumentOpeningEventArgs args) { try { var pathName = args.PathName; if (string.IsNullOrEmpty(pathName) || args.DocumentType != DocumentType.Project) { return; } var fileInfo = BasicFileInfo.Extract(pathName); var centralPath = fileInfo.CentralPath; Log.Initialize("HOK_Tools", string.IsNullOrEmpty(centralPath) ? string.Empty : centralPath); } catch (Exception ex) { Log.AppendLog(LogMessageType.EXCEPTION, ex.Message); } }
//This runs the events on startup public static void starttime(object sender, DocumentOpenedEventArgs args) { Document currentDoc = args.Document; Autodesk.Revit.ApplicationServices.Application uiApp = currentDoc.Application; if (!currentDoc.IsFamilyDocument) { string fp = currentDoc.PathName; BasicFileInfo bfi = BasicFileInfo.Extract(fp); string fpath = bfi.CentralPath.Split('\\').Last().Split('.').First(); string pnum = currentDoc.ProjectInformation.Number.ToString(); EventData edata = new EventData(pnum); edata.DirSetup(); string[] lines = new string[1]; string line = edata.User + "," + pnum + "," + fpath + "," + edata.Time + ",Open"; lines[0] = line; File.AppendAllLines(edata.FileName, lines); } }
protected void UpgradeFile(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."); } BasicFileInfo fileInfo = BasicFileInfo.Extract(modelPath); if (fileInfo.Format.Equals("2019")) { return; } string pathName = doc.PathName; string[] pathParts = pathName.Split('\\'); string[] nameParts = pathParts[pathParts.Length - 1].Split('.'); string extension = nameParts[nameParts.Length - 1]; string filePath = "revitupgrade." + extension; ModelPath path = ModelPathUtils.ConvertUserVisiblePathToModelPath(filePath); SaveAsOptions saveOpts = new SaveAsOptions(); // Check for permanent preview view if (doc .GetDocumentPreviewSettings() .PreviewViewId .Equals(ElementId.InvalidElementId)) { // use 3D view as preview View view = new FilteredElementCollector(doc) .OfClass(typeof(View)) .Cast <View>() .Where(vw => vw.ViewType == ViewType.ThreeD && !vw.IsTemplate ) .FirstOrDefault(); if (view != null) { saveOpts.PreviewViewId = view.Id; } } doc.SaveAs(path, saveOpts); }
// https://forums.autodesk.com/t5/revit-api-forum/reload-revit-links-from/m-p/7722248 public Result Execute1( ExternalCommandData commandData, ref string message, ElementSet elements) { // Get application and document objects UIApplication uiapp = commandData.Application; UIDocument uidoc = uiapp.ActiveUIDocument; Autodesk.Revit.ApplicationServices.Application app = uiapp.Application; Document doc = uidoc.Document; // NO TRANSACTION NEEDS TO BE OPENED try { using (Transaction tx = new Transaction(doc)) { // Collect files linked in current project FilteredElementCollector collector = new FilteredElementCollector(doc); ICollection <Element> linkInstances = collector.OfClass(typeof(RevitLinkType)).ToElements(); // Check which elements are loaded > to be used as filter List <bool> loaded = new List <bool>(); foreach (RevitLinkType i in linkInstances) { loaded.Add(RevitLinkType.IsLoaded(doc, i.Id)); } // Convert ICollection into a list of RevitLinkTypes int i1 = 0; List <RevitLinkType> revLinkType = new List <RevitLinkType>(); foreach (RevitLinkType rli in linkInstances) { if (!loaded[i1++]) { revLinkType.Add(rli); } } // Put names of linked files into a list of strings int i2 = 0; List <string> linkNames = new List <string>(); foreach (Element eli in linkInstances) { if (!loaded[i2++]) { linkNames.Add(eli.Name.Split(' ')[0]); } } // Prompt user with files selection dialog //Start: OpenFileDialog openFileDialog1 = new OpenFileDialog(); openFileDialog1.InitialDirectory = (@"P:\"); openFileDialog1.Filter = "RVT|*.rvt"; openFileDialog1.Multiselect = true; openFileDialog1.RestoreDirectory = true; // If you select the files and hit OK (in the file browser) if (openFileDialog1.ShowDialog() == DialogResult.OK) { // Show which files (path + version) has been selected before linking them StringBuilder userSelectionWVersion = new StringBuilder(); foreach (string fp in openFileDialog1.FileNames) { userSelectionWVersion.AppendLine( fp.ToString() + " which was created with " + BasicFileInfo.Extract(fp).SavedInVersion.ToString().ToUpper()); } // Recap the user with his selection + Revit version of the file DialogResult linkCorrect = MessageBox.Show( userSelectionWVersion.ToString(), "You selected the files:", MessageBoxButtons.OKCancel); // Put paths of files selected by user into a list if (linkCorrect == DialogResult.OK) { List <string> userSelectionNames = new List <string>(); foreach (string fp in openFileDialog1.FileNames) { userSelectionNames.Add(fp.ToString()); } // Check which of the files that the user selected have the same name of the files linked in the project IEnumerable <string> elementsToReload = userSelectionNames.Where(a => linkNames.Exists(b => a.Contains(b))); // Show which files need to be reloaded StringBuilder intersection = new StringBuilder(); foreach (string fp in elementsToReload) { intersection.AppendLine(fp.ToString()); } DialogResult promptToLoad = MessageBox.Show(intersection.ToString(), "The following files need to be roloaded"); // Initialize + populate list of ModelPaths > path from where to reload List <ModelPath> modPaths = new List <ModelPath>(); foreach (string fp in elementsToReload) { FileInfo filePath = new FileInfo(fp); ModelPath linkpath = ModelPathUtils.ConvertUserVisiblePathToModelPath(filePath.ToString()); modPaths.Add(linkpath); } // Zip together file (as RevitLinkType) and the corresponding path to be reloaded from > Reload foreach (var ab in revLinkType.Zip(modPaths, Tuple.Create)) { ab.Item1.LoadFrom(ab.Item2, new WorksetConfiguration()); } } return(Result.Succeeded); } } } catch (Exception ex) { // If something went wrong return Result.Failed DialogResult genericException = MessageBox.Show(ex.Message, "Oops there was problem!"); return(Result.Failed); } return(Result.Succeeded); }
private void CollectConfigurationOnOpening(object source, DocumentOpeningEventArgs args) { try { string pathName = args.PathName; if (!string.IsNullOrEmpty(pathName) && args.DocumentType == DocumentType.Project) { BasicFileInfo fileInfo = BasicFileInfo.Extract(pathName); if (fileInfo.IsWorkshared) { if (!socketOn) { ConnectSocket(); } string centralPath = fileInfo.CentralPath; if (!string.IsNullOrEmpty(centralPath)) { //serch for config LogUtil.AppendLog(centralPath + " Opening."); Configuration configFound = ServerUtil.GetConfigurationByCentralPath(centralPath); if (null != configFound) { //check if the single session should be activated if (SingleSessionMonitor.CancelOpening(centralPath, configFound)) { if (args.Cancellable) { SingleSessionWindow ssWindow = new SingleSessionWindow(centralPath); if ((bool)ssWindow.ShowDialog()) { args.Cancel(); return; } } } if (configDictionary.ContainsKey(centralPath)) { configDictionary.Remove(centralPath); } configDictionary.Add(centralPath, configFound); Project projectFound = ServerUtil.GetProjectByConfigurationId(configFound._id); if (null != projectFound) { if (projectDictionary.ContainsKey(centralPath)) { projectDictionary.Remove(centralPath); } projectDictionary.Add(centralPath, projectFound); } LogUtil.AppendLog("Configuration Found: " + configFound._id); } else { //not a seed file, just check if the single session is activated if (SingleSessionMonitor.SingleSessionActivated) { SingleSessionWindow ssWindow = new SingleSessionWindow(centralPath); if ((bool)ssWindow.ShowDialog()) { args.Cancel(); return; } } } } } } } catch (Exception ex) { string message = ex.Message; LogUtil.AppendLog("CollectConfigurationOnOpening:" + ex.Message); } }
private void appDocOpened(object sender, Autodesk.Revit.DB.Events.DocumentOpenedEventArgs e) { Variables.logOpenEnd = DateTime.Now; Variables.logOpenDuration = Variables.logOpenEnd - Variables.logOpenStart; Autodesk.Revit.ApplicationServices.Application app = sender as Autodesk.Revit.ApplicationServices.Application; Document doc = e.Document; #region Variables: Document & Application Variables string path = GetUNCPath(doc.PathName); BasicFileInfo fileInfo = BasicFileInfo.Extract(path); FileInfo f = new FileInfo(path); Variables.logComputerName = Environment.MachineName; Variables.logChangesSaved = fileInfo.AllLocalChangesSavedToCentral; Variables.logFileCentral = GetUNCPath(fileInfo.CentralPath); Variables.logFileCentralName = Path.GetFileName(Variables.logFileCentral); Variables.logIsCentral = fileInfo.IsCentral; Variables.logIsWorkshared = fileInfo.IsWorkshared; Variables.logCreatedLocal = fileInfo.IsCreatedLocal; Variables.logFileName = doc.Title; Variables.logFilePath = GetUNCPath(doc.PathName); Variables.logFileSize = Convert.ToInt32(f.Length / 1000000); Variables.logUsername = app.Username; Variables.logVersionBuild = app.VersionBuild; Variables.logVersionName = app.VersionName; Variables.logVersionNumber = app.VersionNumber; #endregion #region Tracking: Start Logging Pinned Elements IEnumerable <Element> a = TrackChanges.Command.GetTrackedElements(doc); _start_state = TrackChanges.Command.GetSnapshot(a); #endregion #region Settings: Load settings if they exist (Extensible Storage) ParameterCommands.Load(doc); #endregion #region Post: Worksharing Warning-Opened Central Model bool patheq = string.Equals(Variables.logFileCentral, Variables.logFilePath); if (Variables.slackOn && Variables.slackWSWarn) { if (patheq && Variables.logIsWorkshared) { string gif_lg_url = null; string gif_sm_url = null; if (Variables.giphySet > 0) { var giphyClient = new GiphyClient(); string gif_msg = giphyClient.GetRandomGif("Alarm").Content; var gif_resp = JsonConvert.DeserializeObject <Giphy.Response>(gif_msg); if (Variables.giphySet == 1) { gif_sm_url = gif_resp.data.fixed_height_small_url; } if (Variables.giphySet == 2) { gif_lg_url = gif_resp.data.image_url; } } var slackClient = new SlackClient(Variables.slackToken); string text = ""; string channel = Variables.slackChId; string botname = "Worksharing Warning"; string icon_url = Variables.icon_revit; var attachments = new Attachments { fallback = Variables.logUsername + "has opened the central model", color = "danger", fields = new Fields[] { new Fields { title = "Description", value = "The user has opened the central model. Close the central model and create a new local file> to work from.", @short = false }, new Fields { title = "User", value = Variables.logUsername, @short = true }, new Fields { title = "File", value = Variables.logFileCentralName, @short = true } }, image_url = gif_lg_url, thumb_url = gif_sm_url }; string msg_response = slackClient.PostMessage(text, channel: channel, botName: botname, attachments: attachments, icon_url: icon_url).Content; var resp = JsonConvert.DeserializeObject <ChatPostMessageResponse>(msg_response); msgts_ws.Add(resp.ts); } } #endregion #region Post: Model Warning-File Size > 300MB if (Variables.slackOn && Variables.slackModelWarn) { string gif_lg_url = null; string gif_sm_url = null; if (Variables.logFileSize > 300) { if (Variables.giphySet > 0) { var giphyClient = new GiphyClient(); string gif_msg = giphyClient.GetRandomGif("Gasp").Content; var gif_resp = JsonConvert.DeserializeObject <Giphy.Response>(gif_msg); if (Variables.giphySet == 1) { gif_sm_url = gif_resp.data.fixed_height_small_url; } if (Variables.giphySet == 2) { gif_lg_url = gif_resp.data.image_url; } var slackClient = new SlackClient(Variables.slackToken); string text = ""; string channel = Variables.slackChId; string botname = "Model Warning"; string icon_url = Variables.icon_revit; var attachments = new Attachments { fallback = "The file size has gone above 300MB, time to do some model file size management.", color = "danger", fields = new Fields[] { new Fields { title = "Description", value = "The file size is above 300MB, time to do some model maintenance", @short = false }, new Fields { title = "File Size", value = Variables.logFileSize.ToString() + "MB", @short = true }, new Fields { title = "File", value = Variables.logFileCentralName, @short = true } }, image_url = gif_lg_url, thumb_url = gif_sm_url }; string msg_response = slackClient.PostMessage(text, channel: channel, botName: botname, attachments: attachments, icon_url: icon_url).Content; var resp = JsonConvert.DeserializeObject <ChatPostMessageResponse>(msg_response); msgts_model.Add(resp.ts); } } #endregion #region Post: Tracking-Pinned Element-Started if (Variables.slackOn && Variables.slackExtraTrackPin) { var slackClient = new SlackClient(Variables.slackToken); //Post pinned elements message string text = ""; string channel = Variables.slackChId; string botname = "Pinning Info"; string icon_url = Variables.icon_revit; var attachments = new Attachments { fallback = Variables.logUsername + "has started tracking pinned elements.", color = "good", fields = new Fields[] { new Fields { title = "Status", value = Variables.logUsername + " has started tracking pinned elements.\n[" + Variables.logFileCentralName + "]", @short = true } } }; string msg_response = slackClient.PostMessage(text, channel: channel, botName: botname, attachments: attachments, icon_url: icon_url).Content; var resp = JsonConvert.DeserializeObject <ChatPostMessageResponse>(msg_response); msgts_extra.Add(resp.ts); } #endregion } }
private void appDocClosing(object sender, Autodesk.Revit.DB.Events.DocumentClosingEventArgs e) { BasicFileInfo fileInfo = BasicFileInfo.Extract(Variables.logFilePath); #region Post: Worksharing Warning-Close without saving if (Variables.slackOn && Variables.slackWSWarn) { if (fileInfo.AllLocalChangesSavedToCentral == false) { string gif_lg_url = null; string gif_sm_url = null; if (Variables.giphySet > 0) { var giphyClient = new GiphyClient(); string gif_msg = giphyClient.GetRandomGif("Disappointed").Content; var gif_resp = JsonConvert.DeserializeObject <Giphy.Response>(gif_msg); if (Variables.giphySet == 1) { gif_sm_url = gif_resp.data.fixed_height_small_url; } if (Variables.giphySet == 2) { gif_lg_url = gif_resp.data.image_url; } } var slackClient = new SlackClient(Variables.slackToken); string text = ""; string channel = Variables.slackChId; string botname = "Worksharing Warning"; string icon_url = Variables.icon_revit; var attachments = new Attachments { fallback = Variables.logUsername + "did not save to central before closing", color = "danger", fields = new Fields[] { new Fields { title = "Description", value = "The user has closed the model without saving their changes back to the central model. Open the model and save changes back to the central model.", @short = false }, new Fields { title = "User", value = Variables.logUsername, @short = true }, new Fields { title = "File", value = Variables.logFileCentralName, @short = true } }, image_url = gif_lg_url, thumb_url = gif_sm_url }; string msg_response = slackClient.PostMessage(text, channel: channel, botName: botname, attachments: attachments, icon_url: icon_url).Content; var resp = JsonConvert.DeserializeObject <ChatPostMessageResponse>(msg_response); msgts_ws.Add(resp.ts); } } #endregion }
public Document OpenRevitDocument(string revitFileName) { Document doc = null; try { LogFileManager.AppendLog("Open Revit Document: " + revitFileName); BasicFileInfo basicFileInfo = BasicFileInfo.Extract(revitFileName); FileOpenOptions fileOpenOptions = projectSettings.UpgradeOptions.UpgradeVersionOpenOptions; if (basicFileInfo.IsWorkshared) { ModelPath modelPath = ModelPathUtils.ConvertUserVisiblePathToModelPath(revitFileName); OpenOptions openOptions = new OpenOptions(); openOptions.Audit = fileOpenOptions.Audit; if (fileOpenOptions.DetachAndPreserveWorksets) { openOptions.DetachFromCentralOption = DetachFromCentralOption.DetachAndPreserveWorksets; } IList <WorksetPreview> wsPreviews = new List <WorksetPreview>(); IList <WorksetId> worksetIds = new List <WorksetId>(); WorksetConfiguration wsConfiguration = new WorksetConfiguration(); try { wsPreviews = WorksharingUtils.GetUserWorksetInfo(modelPath); if (wsPreviews.Count > 0) { foreach (WorksetPreview wsPreview in wsPreviews) { worksetIds.Add(wsPreview.Id); } if (fileOpenOptions.OpenAllWorkset) { wsConfiguration.Open(worksetIds); } else { wsConfiguration.Close(worksetIds); } openOptions.SetOpenWorksetsConfiguration(wsConfiguration); } } catch (Exception ex) { LogFileManager.AppendLog("[Warning] Open Worksets", ex.Message); } doc = uiApp.Application.OpenDocumentFile(modelPath, openOptions); } else { doc = uiApp.Application.OpenDocumentFile(revitFileName); } } catch (Exception ex) { string message = ex.Message; LogFileManager.AppendLog("[Error] Open Revit Document", message); } return(doc); }
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); }