/// <summary> /// syncs the central file. /// </summary> /// <param name="uiapp"></param> /// <param name="comment"></param> public static void SyncCentralFile(this UIApplication uiapp, string comment) { if (uiapp == null) { throw new ArgumentNullException(nameof(uiapp)); } if (comment == null) { throw new ArgumentNullException(nameof(comment)); } var doc = uiapp.ActiveUIDocument.Document; var syncOption = new SynchronizeWithCentralOptions(); var relinqOption = new RelinquishOptions(false) { CheckedOutElements = true, StandardWorksets = false }; syncOption.SetRelinquishOptions(relinqOption); var transOption = new TransactWithCentralOptions(); uiapp.Application.WriteJournalComment(comment, true); doc.SynchronizeWithCentral(transOption, syncOption); }
public static bool SynchronizeWithCentralGeneral(bool Compact = true, bool SaveLocalBefore = true, bool SaveLocalAfter = true, string Comment = "", bool Transact = false) { Autodesk.Revit.DB.Document doc = DocumentManager.Instance.CurrentDBDocument; TransactWithCentralOptions transactOptions = new TransactWithCentralOptions(); RelinquishOptions rOptions = new RelinquishOptions(true); SynchronizeWithCentralOptions sOptions = new SynchronizeWithCentralOptions(); sOptions.SetRelinquishOptions(rOptions); sOptions.Compact = Compact; sOptions.Comment = Comment; sOptions.SaveLocalBefore = SaveLocalBefore; sOptions.SaveLocalAfter = SaveLocalAfter; if (Transact == true) { try { doc.SynchronizeWithCentral(transactOptions, sOptions); return(true); } catch (Exception e) { throw e; }; } else { return(false); }; }
void OnDocumentOpened(object sender, DocumentOpenedEventArgs e) { try { Document doc = e.Document; //string title = doc.Title; doc.SaveAsCloudModel(current["folder_id"].AsString, current["file_name"].AsString); Console.Write("cualquier cosa"); if (doc.CanEnableCloudWorksharing()) { doc.EnableCloudWorksharing(); TransactWithCentralOptions transact = new TransactWithCentralOptions(); SynchronizeWithCentralOptions synch = new SynchronizeWithCentralOptions(); synch.Comment = "Autosaved by the API at " + DateTime.Now; RelinquishOptions relinquishOptions = new RelinquishOptions(true); relinquishOptions.CheckedOutElements = true; synch.SetRelinquishOptions(relinquishOptions); doc.SynchronizeWithCentral(transact, synch); } } catch (Exception err) { Console.Write(err.ToString()); } }
private void Sync() { TransactWithCentralOptions transact = new TransactWithCentralOptions(); SynchLockCallback transCallBack = new SynchLockCallback(); transact.SetLockCallback(transCallBack); SynchronizeWithCentralOptions syncset = new SynchronizeWithCentralOptions(); RelinquishOptions relinquishoptions = new RelinquishOptions(true) { CheckedOutElements = true }; syncset.SetRelinquishOptions(relinquishoptions); OpenDocument.SynchronizeWithCentral(transact, syncset); }
//与中心模型同步操作代码展示 #region public void SyncWithRelinquishing(Document doc) { TransactWithCentralOptions transOpts = new TransactWithCentralOptions(); SynchLockCallback transCallBack = new SynchLockCallback(); transOpts.SetLockCallback(transCallBack); SynchronizeWithCentralOptions syncOpts = new SynchronizeWithCentralOptions(); RelinquishOptions relinquishOpts = new RelinquishOptions(true); syncOpts.SetRelinquishOptions(relinquishOpts); syncOpts.SaveLocalAfter = false; syncOpts.Comment = "User has already done something"; try { doc.SynchronizeWithCentral(transOpts, syncOpts); } catch (Exception e) { TaskDialog.Show("Synchronize Failed", e.Message); } }
public static bool SynchronizeWithCentralSpecific( bool StandardWorksets = true, bool ViewWorksets = true, bool FamilyWorksets = true, bool UserWorksets = true, bool CheckedOutElements = true, bool Compact = true, bool SaveLocalBefore = true, bool SaveLocalAfter = true, string Comment = "", bool Transact = false) { Autodesk.Revit.DB.Document doc = DocumentManager.Instance.CurrentDBDocument; TransactWithCentralOptions transactOptions = new TransactWithCentralOptions(); RelinquishOptions rOptions = new RelinquishOptions(false); rOptions.StandardWorksets = StandardWorksets; rOptions.ViewWorksets = ViewWorksets; rOptions.FamilyWorksets = FamilyWorksets; rOptions.UserWorksets = UserWorksets; rOptions.CheckedOutElements = CheckedOutElements; SynchronizeWithCentralOptions sOptions = new SynchronizeWithCentralOptions(); sOptions.SetRelinquishOptions(rOptions); sOptions.Compact = Compact; sOptions.Comment = Comment; sOptions.SaveLocalBefore = SaveLocalBefore; sOptions.SaveLocalAfter = SaveLocalAfter; if (Transact == true) { try { doc.SynchronizeWithCentral(transactOptions, sOptions); return(true); } catch (Exception e) { throw e; }; } else { return(false); } }
public void SyncWithCentral(Document doc) { // set options for accessing central model var transOpts = new TransactWithCentralOptions(); // var transCallBack = new SyncLockCallback(); // override default behavioor of waiting to try sync if central model is locked // transOpts.SetLockCallback(transCallBack); // set options for sync with central var syncOpts = new SynchronizeWithCentralOptions(); var relinquishOpts = new RelinquishOptions(true); syncOpts.SetRelinquishOptions(relinquishOpts); // do not autosave local model syncOpts.SaveLocalAfter = false; syncOpts.Comment = "ќсвобождено"; try { doc.SynchronizeWithCentral(transOpts, syncOpts); } catch (Exception ex) { TaskDialog.Show($"Sync with model {doc.Title}", ex.Message); } }
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { Document mainDoc = commandData.Application.ActiveUIDocument.Document; Application revitApp = commandData.Application.Application; //открываю окно выбора параметров, которые буду заполняться FormSelectParams formSelectParams = new FormSelectParams(); formSelectParams.ShowDialog(); if (formSelectParams.DialogResult != System.Windows.Forms.DialogResult.OK) { return(Result.Cancelled); } RebarDocumentWorker mainWorker = new RebarDocumentWorker(); List <Element> mainDocConcreteElements = new List <Element>(); string mainWorkerMessage = mainWorker.Start(mainDoc, revitApp, Transform.Identity, out mainDocConcreteElements); if (!string.IsNullOrEmpty(mainWorkerMessage)) { message = mainWorkerMessage + ". Документ " + mainDoc.Title; return(Result.Failed); } if (Settings.LinkFilesSetting == Settings.ProcessedLinkFiles.NoLinks) { return(Result.Succeeded); } List <RevitLinkInstance> linksAll = new FilteredElementCollector(mainDoc) .OfClass(typeof(RevitLinkInstance)) .Cast <RevitLinkInstance>() .ToList(); List <RevitLinkInstance> linksLib = linksAll .Where(i => i.Name.Contains(".lib")) .ToList(); // имя ссылки lib и список конструкций, которые она пересекает Dictionary <string, List <Element> > hostElemsForLibLinks = new Dictionary <string, List <Element> >(); foreach (RevitLinkInstance rli in linksLib) { string linkInstanceTitle = LinksSupport.GetDocumentTitleFromLinkInstance(rli); Element hostElem = LinksSupport.GetConcreteElementIsHostForLibLinkFile(mainDoc, ViewSupport.GetDefaultView(mainDoc), mainDocConcreteElements, rli); if (hostElem == null) { continue; } if (hostElemsForLibLinks.ContainsKey(linkInstanceTitle)) { hostElemsForLibLinks[linkInstanceTitle].Add(hostElem); } else { hostElemsForLibLinks.Add(linkInstanceTitle, new List <Element> { hostElem }); } } List <RevitLinkInstance> linksWithoutDuplicates = LinksSupport.DeleteDuplicates(linksAll); foreach (RevitLinkInstance rli in linksWithoutDuplicates) { RevitLinkType rlt = mainDoc.GetElement(rli.GetTypeId()) as RevitLinkType; Document linkDoc = rli.GetLinkDocument(); if (linkDoc == null) { continue; } string linkDocTitle = LinksSupport.GetDocumentTitleFromLinkInstance(rli); if (!linkDocTitle.Contains("-КР-")) { continue; } if (!linkDocTitle.Contains("lib") && Settings.LinkFilesSetting == Settings.ProcessedLinkFiles.OnlyLibs) { continue; } ModelPath mPath = linkDoc.GetWorksharingCentralModelPath(); rlt.Unload(new SaveCoordinates()); OpenOptions oo = new OpenOptions(); linkDoc = revitApp.OpenDocumentFile(mPath, oo); RebarDocumentWorker linkWorker = new RebarDocumentWorker(); if (linkDocTitle.Contains("lib")) { if (hostElemsForLibLinks.ContainsKey(linkDocTitle)) { List <Element> mainElemsForLib = hostElemsForLibLinks[linkDocTitle]; if (mainElemsForLib.Count > 0) { linkWorker.MainElementsForLibFile = mainElemsForLib; } } } Transform linkTransform = rli.GetTransform(); List <Element> linkConcreteElements = new List <Element>(); string linkWorkerMessage = linkWorker.Start(linkDoc, revitApp, linkTransform, out linkConcreteElements); if (!string.IsNullOrEmpty(linkWorkerMessage)) { message = linkWorkerMessage + ". Связь " + linkDoc.Title; return(Result.Failed); } TransactWithCentralOptions transOpt = new TransactWithCentralOptions(); SynchronizeWithCentralOptions syncOpt = new SynchronizeWithCentralOptions(); RelinquishOptions relOpt = new RelinquishOptions(true); syncOpt.SetRelinquishOptions(relOpt); linkDoc.SynchronizeWithCentral(transOpt, syncOpt); linkDoc.Close(); #if R2017 RevitLinkLoadResult rllr = rlt.Reload(); #else LinkLoadResult llr = rlt.Reload(); #endif } return(Result.Succeeded); }
public void Execute(UIApplication app) { if (App.docdict.Keys.Count == 0) { return; } TransactWithCentralOptions transact = new TransactWithCentralOptions(); SynchLockCallback transCallBack = new SynchLockCallback(); transact.SetLockCallback(transCallBack); SynchronizeWithCentralOptions syncset = new SynchronizeWithCentralOptions(); RelinquishOptions relinquishoptions = new RelinquishOptions(true) { CheckedOutElements = true }; syncset.SetRelinquishOptions(relinquishoptions); App.running = true; if (relinquish) { foreach (Document doc in App.docdict.Keys) { try { WorksharingUtils.RelinquishOwnership(doc, relinquishoptions, transact); } catch { } } relinquish = false; } if (sync) { if (App.Dismiss()) { sync = false; App.running = false; return; } app.Application.FailuresProcessing += FailureProcessor; bool syncfailed = false; foreach (Document doc in App.docdict.Keys) { try { if (docdict[doc]) { doc.SynchronizeWithCentral(transact, syncset); app.Application.WriteJournalComment("AutoSync", true); } } catch { syncfailed = true; } } app.Application.FailuresProcessing -= FailureProcessor; if (syncfailed) { countdown -= retrysync; } sync = false; } if (close) { if (App.Dismiss()) { App.running = false; close = false; return; } bool closelast = false; string activepathname = app.ActiveUIDocument.Document.PathName; List <Document> docsdeletelist = new List <Document>(); foreach (Document doc in App.docdict.Keys) { if (activepathname == doc.PathName) { closelast = true; } else { docsdeletelist.Add(doc); } } foreach (Document doc in docsdeletelist) { try { doc.Close(false); } catch { } } if (closelast) { RevitCommandId closeDoc = RevitCommandId.LookupPostableCommandId(PostableCommand.Close); app.PostCommand(closeDoc); } close = false; countdown = 0; } App.running = false; transact.Dispose(); syncset.Dispose(); relinquishoptions.Dispose(); }
/// <summary> /// Try to open each cloud model and reload if they have links, /// making that point to cloud path. /// </summary> /// <param name="directory">Transit directory where cloud models exist</param> /// <param name="projectId">not used</param> /// <returns></returns> public IEnumerator ReloadLinks(string directory, Guid projectId) { var view = (ViewMigrationToBim360)View; if (!Directory.Exists(directory)) { view.UpdateReloadingProgress("Directory doesn't exist.", 0); yield break; } view.UpdateReloadingProgress("Ready to start.", 2); var ops = new OpenOptions(); var transOp = new TransactWithCentralOptions(); var swcOptions = new SynchronizeWithCentralOptions(); var count = 0; // Read mapping info var jsonString = File.ReadAllText(FLinksInfo); JavaScriptSerializer serializer = new JavaScriptSerializer(); var mapLocalModelPathToLinksName = serializer.Deserialize <Dictionary <string, List <string> > >(jsonString); jsonString = File.ReadAllText(FModelsGuid); var mapModelsNameToGuid = serializer.Deserialize <Dictionary <string, string> >(jsonString); // Try to open each cloud model and reload if they have links, making that point to cloud path. foreach (var kvp in mapLocalModelPathToLinksName) { var localPath = kvp.Key; var name = Path.GetFileName(localPath); var guids = mapModelsNameToGuid[name].Split(','); var hostModelPath = ModelPathUtils.ConvertCloudGUIDsToCloudPath("US", Guid.Parse(guids[0]), Guid.Parse(guids[1])); var progress = count++ *100 / mapLocalModelPathToLinksName.Count(); view.UpdateReloadingProgress($"Reloading {name}", progress); yield return(null); try { var doc = Application.Application.OpenDocumentFile(hostModelPath, ops, new DefaultOpenFromCloudCallback()); foreach (var linkInstance in GetLinkInstances(doc)) { if (mapModelsNameToGuid.TryGetValue(linkInstance.Name, out var sLinkedGuids)) { guids = mapModelsNameToGuid[linkInstance.Name].Split(','); var linkModelPath = ModelPathUtils.ConvertCloudGUIDsToCloudPath("US", Guid.Parse(guids[0]), Guid.Parse(guids[1])); linkInstance.LoadFrom(linkModelPath, new WorksetConfiguration()); } } doc.SynchronizeWithCentral(transOp, swcOptions); doc.Close(false); } catch (Exception e) { var msg = $"Failed to reload {name} - {e.Message}"; view.UpdateUploadingProgress(msg, progress); MessageBox.Show(msg); yield break; } } view.UpdateReloadingProgress("Reloading finished", 100); }
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"); } }