public Workset GetActiveWorkset(Document doc) { // Get the workset table from the document WorksetTable worksetTable = doc.GetWorksetTable(); // Get the Id of the active workset WorksetId activeId = worksetTable.GetActiveWorksetId(); // Find the workset with that Id Workset workset = worksetTable.GetWorkset(activeId); return workset; }
publicvoidGetWorksetsInfo(Document doc) { String message = String.Empty; // Enumerating worksets in a document and getting basic information for each FilteredWorksetCollector collector = new FilteredWorksetCollector(doc);
// find all user worksets collector.OfKind(WorksetKind.UserWorkset); IList worksets = collector.ToWorksets();
// get information for each workset int count = 3; // show info for 3 worksets only foreach (Workset workset in worksets) { message += "Workset : " + workset.Name; message += "\nUnique Id : " + workset.UniqueId; message += "\nOwner : " + workset.Owner; message += "\nKind : " + workset.Kind; message += "\nIs default : " + workset.IsDefaultWorkset; message += "\nIs editable : " + workset.IsEditable; message += "\nIs open : " + workset.IsOpen; message += "\nIs visible by default : " + workset.IsVisibleByDefault;
public Workset CreateWorkset(Document document) { Workset newWorkset = null; // Worksets can only be created in a document with worksharing enabled if (document.IsWorkshared) { string worksetName = "New Workset"; // Workset name must not be in use by another workset if (WorksetTable.IsWorksetNameUnique(document, worksetName)) { using (Transaction worksetTransaction = new Transaction(document, "Set preview view id")) { worksetTransaction.Start(); newWorkset = Workset.Create(document, worksetName); worksetTransaction.Commit(); } } }
publicvoidWorksetElements(Document doc, Workset workset) { // filter all elements that belong to the given workset FilteredElementCollector elementCollector = new FilteredElementCollector(doc); ElementWorksetFilter elementWorksetFilter = new ElementWorksetFilter(workset.Id, false); ICollection worksetElemsfounds = elementCollector.WherePasses(elementWorksetFilter).ToElements();
// how many elements were found? int elementsCount = worksetElemsfounds.Count; String message = "Element count : " + elementsCount;
// Get name and/or Id of the elements that pass the given filter and show a few of them int count = 5; // show info for 5 elements only foreach (Element ele in worksetElemsfounds) { if (null != ele) { message += "\nElementId : " + ele.Id; message += ", Element Name : " + ele.Name;
// Workset not found, abort if (workset == null) { TaskDialog dialog = new TaskDialog("Error"); dialog.MainInstruction = String.Format("There is no workset named {0} in the document. Aborting this operation.", targetWorksetName); dialog.MainIcon = TaskDialogIcon.TaskDialogIconWarning; dialog.Show(); return Result.Cancelled; }
// Find "Level 1" for the new wall FilteredElementCollector collector = new FilteredElementCollector(doc); collector.OfClass(typeof(Level)); Level level = collector.Cast().First(lvl => lvl.Name == "Level 1");
using (Transaction t = new Transaction(doc, "Add elements by API")) { t.Start();
// Create the wall Wall wall = Wall.Create(doc, Line.CreateBound(new XYZ(25, 0, 0), new XYZ(25, 15, 0)), level.Id, false);
// Get the parameter that stores the workset id Parameter p = wall.get_Parameter(BuiltInParameter.ELEM_PARTITION_PARAM);
// This parameter storage type is Integer p.Set(workset.Id.IntegerValue);
Element elem = doc.GetElement(elemId); if(null == elem) { message += "Element does not exist"; return; }
// The workset the element belongs to WorksetId worksetId = elem.WorksetId; message += ("\nWorkset Id : " + worksetId.ToString());
// Model Updates Status of the element ModelUpdatesStatus updateStatus = WorksharingUtils.GetModelUpdatesStatus(doc, elemId); message += ("\nUpdate status : " + updateStatus.ToString());
// Checkout Status of the element CheckoutStatus checkoutStatus = WorksharingUtils.GetCheckoutStatus(doc, elemId); message += ("\nCheckout status : " + checkoutStatus.ToString());
// Getting WorksharingTooltipInfo of a given element Id WorksharingTooltipInfo tooltipInfo = WorksharingUtils.GetWorksharingTooltipInfo(doc, elemId); message += ("\nCreator : " + tooltipInfo.Creator); message += ("\nCurrent Owner : " + tooltipInfo.Owner); message += ("\nLast Changed by : " + tooltipInfo.LastChangedBy);
if (!checkedOutSuccessfully) { TaskDialog.Show("Element is not checked out", "Cannot edit the " + categoryName + " element - " + "it was not checked out successfully and may be checked out to another."); returnfalse; }
// If element is updated in central or deleted in central, it is not editable ModelUpdatesStatus updatesStatus = WorksharingUtils.GetModelUpdatesStatus(doc, element.Id); if (updatesStatus == ModelUpdatesStatus.DeletedInCentral || updatesStatus == ModelUpdatesStatus.UpdatedInCentral) { TaskDialog.Show("Element is not up to date", "Cannot edit the " + categoryName + " element - " + "it is not up to date with central, but it is checked out."); returnfalse; }
returntrue; }
下一个示例演示如何检出所有视图工作集。
1 2 3 4 5 6 7 8 9 10
voidCheckoutAllViewWorksets(Document doc) { FilteredWorksetCollector collector = new FilteredWorksetCollector(doc);
// find all view worksets collector.OfKind(WorksetKind.ViewWorkset); ICollection viewworksets = collector.ToWorksetIds(); ICollection checkoutworksets = WorksharingUtils.CheckoutWorksets(doc, viewworksets); TaskDialog.Show("Checked out worksets", "Number of worksets checked out: " + checkoutworksets.Count); }
Document OpenDocumentWithWorksets(Application app, ModelPath projectPath) { Document doc = null; try { // Get info on all the user worksets in the project prior to opening IList worksets = WorksharingUtils.GetUserWorksetInfo(projectPath); IList worksetIds = new List(); // Find two predetermined worksets foreach (WorksetPreview worksetPrev in worksets) { if (worksetPrev.Name.CompareTo("Workset1") == 0 || worksetPrev.Name.CompareTo("Workset2") == 0) { worksetIds.Add(worksetPrev.Id); } }
OpenOptions openOptions = new OpenOptions(); // Setup config to close all worksets by default WorksetConfiguration openConfig = new WorksetConfiguration(WorksetConfigurationOption.CloseAllWorksets); // Set list of worksets for opening openConfig.Open(worksetIds); openOptions.SetOpenWorksetsConfiguration(openConfig); doc = app.OpenDocumentFile(projectPath, openOptions); } catch (Exception e) { TaskDialog.Show("Open File Failed", e.Message); }
// Setup options OpenOptions options1 = new OpenOptions();
// Default config opens all. Close all first, then open last viewed to get the correct settings. WorksetConfiguration worksetConfig = new WorksetConfiguration(WorksetConfigurationOption.OpenLastViewed); options1.SetOpenWorksetsConfiguration(worksetConfig);
// Open the document Document openedDoc = application.OpenDocumentFile(GetWSAPIModelPath("WorkaredFileSample.rvt"), options1);
return openedDoc; }
privatestatic ModelPath GetWSAPIModelPath(string fileName) { // Utility to get a local path for a target model file FileInfo filePath = new FileInfo(Path.Combine(@"C:\Documents\Revit Projects", fileName)); ModelPath mp = ModelPathUtils.ConvertUserVisiblePathToModelPath(filePath.FullName);
publicstatic Document OpenNewLocalFromDisk(UIApplication uiApplication) { // Create new local from a disk location ModelPath newLocalPath = GetWSAPIModelPath("LocalWorksharing.rvt"); return (OpenNewLocalFromModelPath(uiApplication.Application, GetWSAPIModelPath("NewLocalWorksharing.rvt"), newLocalPath)); }
privatestatic Document OpenNewLocalFromModelPath(Application app, ModelPath centralPath, ModelPath localPath) { // Create the new local at the given path WorksharingUtils.CreateNewLocal(centralPath, localPath);
// Select specific worksets to open // First get a list of worksets from the unopened document IList worksets = WorksharingUtils.GetUserWorksetInfo(localPath); List worksetsToOpen = new List();
foreach (WorksetPreview preview in worksets) { // Match worksets to open with criteria if (preview.Name.StartsWith("O")) worksetsToOpen.Add(preview.Id); }
// Setup option to open the target worksets // First close all, then set specific ones to open WorksetConfiguration worksetConfig = new WorksetConfiguration(WorksetConfigurationOption.CloseAllWorksets); worksetConfig.Open(worksetsToOpen);
// Open the new local OpenOptions options1 = new OpenOptions(); options1.SetOpenWorksetsConfiguration(worksetConfig); Document openedDoc = app.OpenDocumentFile(localPath, options1);
/// /// Get the server path for a particular model and open a new local copy /// publicstatic Document OpenNewLocalFromServer(UIApplication uiApp) { // Create new local from a server location Application app = uiApp.Application;
// Get the host id/IP of the server String hostId = app.GetRevitServerNetworkHosts().First();
// try to get the server path for the particular model on the server String rootFolder = "|"; ModelPath serverPath = FindWSAPIModelPathOnServer(app, hostId, rootFolder, "WorksharingOnServer.rvt");
/// /// Uses the Revit Server REST API to recursively search the folders of the Revit Server for a particular model. /// privatestatic ModelPath FindWSAPIModelPathOnServer(Application app, string hostId, string folderName, string fileName) { // Connect to host to find list of available models (the "/contents" flag) XmlDictionaryReader reader = GetResponse(app, hostId, folderName + "/contents"); bool found = false;
// Look for the target model name in top level folder List folders = new List(); while (reader.Read()) { // Save a list of subfolders, if found if (reader.NodeType == XmlNodeType.Element && reader.Name == "Folders") { while (reader.Read()) { if (reader.NodeType == XmlNodeType.EndElement && reader.Name == "Folders") break;
if (reader.NodeType == XmlNodeType.Element && reader.Name == "Name") { reader.Read(); folders.Add(reader.Value); } } } // Check for a matching model at this folder level if (reader.NodeType == XmlNodeType.Element && reader.Name == "Models") { found = FindModelInServerResponseJson(reader, fileName); if (found) break; } }
reader.Close();
// Build the model path to match the found model on the server if (found) { // Server URLs use "|" for folder separation, Revit API uses "/" String folderNameFragment = folderName.Replace('|', '/');
// Add trailing "/" if not present if (!folderNameFragment.EndsWith("/")) folderNameFragment += "/";
// This string is different for each RevitServer version privatestaticstring s_revitServerVersion = "/RevitServerAdminRESTService2014/AdminRESTService.svc/";
/// /// Connect to server to get list of available models and return server response /// privatestatic XmlDictionaryReader GetResponse(Application app, string hostId, string info) { // Create request WebRequest request = WebRequest.Create("http://" + hostId + s_revitServerVersion + info); request.Method = "GET";
// Read the response XmlDictionaryReaderQuotas quotas = new XmlDictionaryReaderQuotas(); XmlDictionaryReader jsonReader = JsonReaderWriterFactory.CreateJsonReader(request.GetResponse().GetResponseStream(), quotas);
return jsonReader; }
/// /// Read through server response to find particular model /// privatestaticboolFindModelInServerResponseJson(XmlDictionaryReader reader, string fileName) { // Read through entries in this section while (reader.Read()) { if (reader.NodeType == XmlNodeType.EndElement && reader.Name == "Models") break;
if (reader.NodeType == XmlNodeType.Element && reader.Name == "Name") { reader.Read(); String modelName = reader.Value; if (modelName.Equals(fileName)) { // Match found, stop looping and return returntrue; } } }
publicstatic Document CopyAndOpenDetached(UIApplication uiApp) { // Copy a server model locally and open detached Application application = uiApp.Application; String hostId = application.GetRevitServerNetworkHosts().First();
// Try to get the server path for the particular model on the server String rootFolder = "|"; ModelPath serverPath = FindWSAPIModelPathOnServer(application, hostId, rootFolder, "ServerModel.rvt");
// For debugging String sourcePath = ModelPathUtils.ConvertModelPathToUserVisiblePath(serverPath);
// Setup the target location for the copy ModelPath localPath = GetWSAPIModelPath("CopiedModel.rvt");
publicvoidHideWorkset(Document doc, View view, WorksetId worksetId) { // get the current visibility WorksetVisibility visibility = view.GetWorksetVisibility(worksetId);
// and set it to 'Hidden' if it is not hidden yet if (visibility != WorksetVisibility.Hidden) { view.SetWorksetVisibility(worksetId, WorksetVisibility.Hidden); }
// Get the workset’s default visibility WorksetDefaultVisibilitySettings defaultVisibility = WorksetDefaultVisibilitySettings.GetWorksetDefaultVisibilitySettings(doc);
// and making sure it is set to 'false' if (true == defaultVisibility.IsWorksetVisible(worksetId)) { defaultVisibility.SetWorksetVisibility(worksetId, false); } }
public Result Execute(ExternalCommandData commandData, refstring message, ElementSet elements) { View activeView = commandData.View; Document doc = activeView.Document;
// Prepare settings Color red = new Color(0xFF, 0x00, 0x00); WorksharingDisplayGraphicSettings settingsToApply = new WorksharingDisplayGraphicSettings(true, red);
// Toggle mode based on the current mode using (Transaction t = new Transaction(doc, "Toggle display mode")) { t.Start();
// get or create a WorksharingDisplaySettings current active document WorksharingDisplaySettings displaySettings = WorksharingDisplaySettings.GetOrCreateWorksharingDisplaySettings(doc);
// get graphic settings for a user, if specified if (!String.IsNullOrEmpty(userName)) graphicSettings = displaySettings.GetGraphicOverrides(userName);
// get graphicSettings for a workset, if specified elseif (worksetId != WorksetId.InvalidWorksetId) graphicSettings = displaySettings.GetGraphicOverrides(worksetId);
// get graphic settings for the OwnedByCurrentUser status elseif (ownedbyCurrentUser) graphicSettings = displaySettings.GetGraphicOverrides(CheckoutStatus.OwnedByCurrentUser);
// otherwise get graphic settings for the CurrentWithCentral status else graphicSettings = displaySettings.GetGraphicOverrides(ModelUpdatesStatus.CurrentWithCentral);
// get or create a WorksharingDisplaySettings current active document WorksharingDisplaySettings displaySettings = WorksharingDisplaySettings.GetOrCreateWorksharingDisplaySettings(doc);
// set a new graphicSettings for CheckoutStatus - NotOwned WorksharingDisplayGraphicSettings graphicSettings = new WorksharingDisplayGraphicSettings(true, new Color(255, 0, 0)); displaySettings.SetGraphicOverrides(CheckoutStatus.NotOwned, graphicSettings);
// set a new graphicSettings for ModelUpdatesStatus - CurrentWithCentral graphicSettings = new WorksharingDisplayGraphicSettings(true, new Color(128, 128, 0)); displaySettings.SetGraphicOverrides(ModelUpdatesStatus.CurrentWithCentral, graphicSettings);
// set a new graphicSettings by a given userName graphicSettings = new WorksharingDisplayGraphicSettings(true, new Color(0, 255, 0)); displaySettings.SetGraphicOverrides(userName, graphicSettings);
// set a new graphicSettings by a given workset Id graphicSettings = new WorksharingDisplayGraphicSettings(true, new Color(0, 0, 255)); displaySettings.SetGraphicOverrides(worksetId, graphicSettings); }
publicvoidRemoveAndRestoreUsers(Document doc) { // get or create a WorksharingDisplaySettings current active document WorksharingDisplaySettings displaySettings = WorksharingDisplaySettings.GetOrCreateWorksharingDisplaySettings(doc);
// get all users with GraphicOverrides ICollection users = displaySettings.GetAllUsersWithGraphicOverrides();
// remove the users from the display settings (they will not have graphic overrides anymore) ICollection outUserList; displaySettings.RemoveUsers(doc, users, out outUserList);
// show the current list of removed users ICollection removedUsers = displaySettings.GetRemovedUsers();
String message = "Current list of removed users: "; if (removedUsers.Count > 0 ) { foreach (String user in removedUsers) { message += "\n" + user; } } else { message = "[Empty]"; }
TaskDialog.Show("Users Removed", message);
// restore the previously removed users int number = displaySettings.RestoreUsers(outUserList);
// again, show the current list of removed users // it should not contain the users that were restored removedUsers = displaySettings.GetRemovedUsers();
message = "Current list of removed users: "; if (removedUsers.Count > 0 ) { foreach (String user in removedUsers) { message += "\n" + user; } } else { message = "[Empty]"; }
publicstaticvoidReloadLatestWithMessage(Document doc) { // Tell user what we're doing TaskDialog td = new TaskDialog("Alert"); td.MainInstruction = "Application 'Automatic element creator' needs to reload changes from central in order to proceed."; td.MainContent = "This will update your local with all changes currently in the central model. This operation " + "may take some time depending on the number of changes available on the central."; td.CommonButtons = TaskDialogCommonButtons.Ok | TaskDialogCommonButtons.Cancel;
TaskDialogResult result = td.Show();
if (result == TaskDialogResult.Ok) { // There are no currently customizable user options for ReloadLatest. doc.ReloadLatest(new ReloadLatestOptions()); TaskDialog.Show("Proceeding...", "Reload operation completed, proceeding with updates."); } else { TaskDialog.Show("Canceled.", "Reload operation canceled, so changes will not be made. Return to this command later when ready to reload."); } }
publicvoidSyncWithoutRelinquishing(Document doc) { // Set options for accessing central model TransactWithCentralOptions transOpts = new TransactWithCentralOptions(); SynchLockCallback transCallBack = new SynchLockCallback(); // Override default behavior of waiting to try again if the central model is locked transOpts.SetLockCallback(transCallBack);
// Set options for synchronizing with central SynchronizeWithCentralOptions syncOpts = new SynchronizeWithCentralOptions(); // Sync without relinquishing any checked out elements or worksets RelinquishOptions relinquishOpts = new RelinquishOptions(false); syncOpts.SetRelinquishOptions(relinquishOpts); // Do not automatically save local model after sync syncOpts.SaveLocalAfter = false; syncOpts.Comment = "Changes to Workset1";
classSynchLockCallback : ICentralLockedCallback { // If unable to lock central, give up rather than waiting publicboolShouldWaitForLockAvailability() { returnfalse; }
publicstaticvoidSynchWithCentralWithMessage(Document doc) { // Checkout workset (for use with "keep checked out worksets" option later) FilteredWorksetCollector fwc = new FilteredWorksetCollector(doc); fwc.OfKind(WorksetKind.UserWorkset); Workset workset1 = fwc.First(ws => ws.Name == "Workset1");
WorksharingUtils.CheckoutWorksets(doc, new WorksetId[] { workset1.Id });
// Make a change using (Transaction t = new Transaction(doc, "Add Level")) { t.Start(); Level.Create(doc, 100); t.Commit(); }
// Tell user what we're doing TaskDialog td = new TaskDialog("Alert"); td.MainInstruction = "Application 'Automatic element creator' has made changes and is prepared to synchronize with central."; td.MainContent = "This will update central with all changes currently made in the project by the application or by the user. This operation " + "may take some time depending on the number of changes made by the app and by the user.";
td.AddCommandLink(TaskDialogCommandLinkId.CommandLink1, "Do not synchronize at this time."); td.AddCommandLink(TaskDialogCommandLinkId.CommandLink2, "Synchronize and relinquish all elements."); td.AddCommandLink(TaskDialogCommandLinkId.CommandLink3, "Synchronize but keep checked out worksets."); td.DefaultButton = TaskDialogResult.CommandLink1;
TaskDialogResult result = td.Show();
switch (result) { case TaskDialogResult.CommandLink1: default: { // Do not synch. Nothing to do. break; } case TaskDialogResult.CommandLink2: case TaskDialogResult.CommandLink3: { // Prepare to synch // TransactWithCentralOptions has to do with the behavior related to locked or busy central models. // We'll use the default behavior. TransactWithCentralOptions twcOpts = new TransactWithCentralOptions();
// Setup synch-with-central options (add a comment about our change) SynchronizeWithCentralOptions swcOpts = new SynchronizeWithCentralOptions(); swcOpts.Comment = "Synchronized by 'Automatic element creator' with user acceptance.";
if (result == TaskDialogResult.CommandLink3) { // Setup relinquish options to keep user worksets checked out RelinquishOptions rOptions = new RelinquishOptions(true); rOptions.UserWorksets = false; swcOpts.SetRelinquishOptions(rOptions); }