/// <summary> /// Implement this method as an external command for Revit. /// </summary> /// <param name="commandData">An object that is passed to the external application /// which contains data related to the command, /// such as the application object and active view.</param> /// <param name="message">A message that can be set by the external application /// which will be displayed if a failure or cancellation is returned by /// the external command.</param> /// <param name="elements">A set of elements to which the external application /// can add elements that are to be highlighted in case of failure or cancellation.</param> /// <returns>Return the status of the external command. /// A result of Succeeded means that the API external method functioned as expected. /// Cancelled can be used to signify that the user cancelled the external operation /// at some point. Failure should be returned if the application is unable to proceed with /// the operation.</returns> public virtual Result Execute(ExternalCommandData commandData , ref string message, ElementSet elements) { try { Document doc = commandData.Application.ActiveUIDocument.Document; // get the user selection UIDocument uidoc = commandData.Application.ActiveUIDocument; ICollection <ElementId> collection = uidoc.Selection.GetElementIds(); if (collection.Count > 0) { // DesignToFabrication needs an ISet<ElementId> ISet <ElementId> selIds = new HashSet <ElementId>(); foreach (ElementId id in collection) { selIds.Add(id); } using (Transaction tr = new Transaction(doc, "Convert To Fabrication Parts")) { tr.Start(); FabricationConfiguration config = FabricationConfiguration.GetFabricationConfiguration(doc); // get all loaded fabrication services and attempt to convert the design elements // to the first loaded service IList <FabricationService> allLoadedServices = config.GetAllLoadedServices(); DesignToFabricationConverter converter = new DesignToFabricationConverter(doc); DesignToFabricationConverterResult result = converter.Convert(selIds, allLoadedServices[0].ServiceId); if (result != DesignToFabricationConverterResult.Success) { message = "There was a problem with the conversion."; return(Result.Failed); } doc.Regenerate(); tr.Commit(); } return(Result.Succeeded); } else { // inform user they need to select at least one element message = "Please select at least one element."; } return(Result.Failed); } catch (Exception ex) { message = ex.Message; return(Result.Failed); } }
public List <QLFabricationService> GetFabServices(IResolveFieldContext context, string[] nameFilter = null) { Document _doc = ResolverEntry.Doc; var stuff = ResolverEntry.aRevitTask.Run <List <QLFabricationService> >(app => { var fabricationConfiguration = FabricationConfiguration.GetFabricationConfiguration(_doc); var objectList = fabricationConfiguration.GetAllServices(); var nameFilterStrings = nameFilter != null ? nameFilter.ToList() : new List <string>(); //var qlFabricationPartsField = GraphQlHelpers.GetFieldFromContext(context, "qlFabricationParts"); var returnObject = new ConcurrentBag <QLFabricationService>(); //Parallel.ForEach(stringList, aFamilyCategoryName => foreach (var aFabricationService in objectList) { if (nameFilterStrings.Count == 0 || nameFilterStrings.Contains(aFabricationService.Name)) { var qlFabricationService = new QLFabricationServiceResolve(aFabricationService, context); returnObject.Add(qlFabricationService); } } return(returnObject.OrderBy(x => x.name).ToList()); }).Result; return(stuff); }
/// <summary> /// Implement this method as an external command for Revit. /// </summary> /// <param name="commandData">An object that is passed to the external application /// which contains data related to the command, /// such as the application object and active view.</param> /// <param name="message">A message that can be set by the external application /// which will be displayed if a failure or cancellation is returned by /// the external command.</param> /// <param name="elements">A set of elements to which the external application /// can add elements that are to be highlighted in case of failure or cancellation.</param> /// <returns>Return the status of the external command. /// A result of Succeeded means that the API external method functioned as expected. /// Cancelled can be used to signify that the user cancelled the external operation /// at some point. Failure should be returned if the application is unable to proceed with /// the operation.</returns> public virtual Result Execute(ExternalCommandData commandData , ref string message, ElementSet elements) { try { Document doc = commandData.Application.ActiveUIDocument.Document; using (Transaction tr = new Transaction(doc, "Set button and group exclusions")) { tr.Start(); FabricationConfiguration config = FabricationConfiguration.GetFabricationConfiguration(doc); if (config == null) { message = "No fabrication configuration loaded."; return(Result.Failed); } // get all loaded fabrication services IList <FabricationService> allLoadedServices = config.GetAllLoadedServices(); // get the "ADSK - HVAC:Supply Air" service string serviceName = "ADSK - HVAC: Supply Air"; FabricationService selectedService = allLoadedServices.FirstOrDefault(x => x.Name == serviceName); if (selectedService == null) { message = $"Could not find fabrication service {serviceName}"; return(Result.Failed); } string rectangularGroupName = "Rectangular"; string roundGroupName = "Round Bought Out"; string excludeButtonName = "Square Bend"; int rectangularGroupIndex = -1; int roundGroupIndex = -1; // find Rectangular and Round groups in service for (int i = 0; i < selectedService.GroupCount; i++) { if (selectedService.GetGroupName(i) == rectangularGroupName) { rectangularGroupIndex = i; } if (selectedService.GetGroupName(i) == roundGroupName) { roundGroupIndex = i; } if (rectangularGroupIndex > -1 && roundGroupIndex > -1) { break; } } if (rectangularGroupIndex > -1) { // exclude square bend in Rectangular group for (int i = 0; i < selectedService.GetButtonCount(rectangularGroupIndex); i++) { if (selectedService.GetButton(rectangularGroupIndex, i).Name == excludeButtonName) { selectedService.OverrideServiceButtonExclusion(rectangularGroupIndex, i, true); break; } } } else { message = $"Unable to locate {excludeButtonName} button to exclude."; return(Result.Failed); } // exclude entire Round Bought Out service group if (roundGroupIndex > -1) { selectedService.SetServiceGroupExclusions(new List <int>() { roundGroupIndex }); } else { message = $"Unable to locate {roundGroupName} service group to exclude."; return(Result.Failed); } tr.Commit(); TaskDialog td = new TaskDialog("Button and Group Exclsuions") { MainIcon = TaskDialogIcon.TaskDialogIconInformation, TitleAutoPrefix = false, MainInstruction = "Operation Successful", MainContent = $"Excluded {excludeButtonName} button from {serviceName} {rectangularGroupName} Group {Environment.NewLine}" + $"Excluded {roundGroupName} Group from {serviceName}" }; td.Show(); } return(Result.Succeeded); } catch (Exception ex) { message = ex.Message; return(Result.Failed); } }
/// <summary> /// Implement this method as an external command for Revit. /// </summary> /// <param name="commandData">An object that is passed to the external application /// which contains data related to the command, /// such as the application object and active view.</param> /// <param name="message">A message that can be set by the external application /// which will be displayed if a failure or cancellation is returned by /// the external command.</param> /// <param name="elements">A set of elements to which the external application /// can add elements that are to be highlighted in case of failure or cancellation.</param> /// <returns>Return the status of the external command. /// A result of Succeeded means that the API external method functioned as expected. /// Cancelled can be used to signify that the user cancelled the external operation /// at some point. Failure should be returned if the application is unable to proceed with /// the operation.</returns> public virtual Result Execute(ExternalCommandData commandData , ref string message, ElementSet elements) { try { var uiDoc = commandData.Application.ActiveUIDocument; var doc = uiDoc.Document; FilteredElementCollector cl = new FilteredElementCollector(doc); cl.OfClass(typeof(Level)); IList <Element> levels = cl.ToElements(); Level levelOne = null; foreach (Level level in levels) { if (level != null && level.Name.Equals("Level 1")) { levelOne = level; break; } } if (levelOne == null) { return(Result.Failed); } using (var config = FabricationConfiguration.GetFabricationConfiguration(doc)) { if (config == null) { message = "No fabrication configuration in use"; return(Result.Failed); } using (var configInfo = config.GetFabricationConfigurationInfo()) { using (var source = FabricationConfigurationInfo.FindSourceFabricationConfiguration(configInfo)) { if (source == null) { message = "Source fabrication configuration not found"; return(Result.Failed); } using (var trans = new Autodesk.Revit.DB.Transaction(doc, "Load And Place Next Item File")) { trans.Start(); // reload the configuration config.ReloadConfiguration(); // get the item folders var itemFolders = config.GetItemFolders(); // get the next unloaded item file from the item folders structure var nextFile = GetNextUnloadedItemFile(itemFolders); if (nextFile == null) { message = "Could not locate the next unloaded item file"; return(Result.Failed); } var itemFilesToLoad = new List <FabricationItemFile>(); itemFilesToLoad.Add(nextFile); // load the item file into the config var failedItems = config.LoadItemFiles(itemFilesToLoad); if (failedItems != null && failedItems.Count > 0) { message = "Could not load the item file: " + nextFile.Identifier; return(Result.Failed); } // create a part from the item file using (var part = FabricationPart.Create(doc, nextFile, levelOne.Id)) { doc.Regenerate(); var selectedElements = new List <ElementId>() { part.Id }; uiDoc.Selection.SetElementIds(selectedElements); uiDoc.ShowElements(selectedElements); trans.Commit(); } } } } } return(Result.Succeeded); } catch (Exception ex) { message = ex.Message; return(Result.Failed); } }
/// <summary> /// Implement this method as an external command for Revit. /// </summary> /// <param name="commandData">An object that is passed to the external application /// which contains data related to the command, /// such as the application object and active view.</param> /// <param name="message">A message that can be set by the external application /// which will be displayed if a failure or cancellation is returned by /// the external command.</param> /// <param name="elements">A set of elements to which the external application /// can add elements that are to be highlighted in case of failure or cancellation.</param> /// <returns>Return the status of the external command. /// A result of Succeeded means that the API external method functioned as expected. /// Cancelled can be used to signify that the user cancelled the external operation /// at some point. Failure should be returned if the application is unable to proceed with /// the operation.</returns> public virtual Result Execute(ExternalCommandData commandData , ref string message, ElementSet elements) { try { var uiDoc = commandData.Application.ActiveUIDocument; var doc = uiDoc.Document; using (var config = FabricationConfiguration.GetFabricationConfiguration(doc)) { if (config == null) { message = "No fabrication configuration in use"; return(Result.Failed); } using (var trans = new Transaction(doc, "Unload unused item files")) { trans.Start(); config.ReloadConfiguration(); var loadedFiles = config.GetAllLoadedItemFiles(); var unusedFiles = loadedFiles.Where(x => x.IsUsed == false).ToList(); if (unusedFiles.Count == 0) { message = "No unuseed item files found"; return(Result.Failed); } if (config.CanUnloadItemFiles(unusedFiles) == false) { message = "Cannot unload item files"; return(Result.Failed); } config.UnloadItemFiles(unusedFiles); trans.Commit(); var builder = new StringBuilder(); unusedFiles.ForEach(x => builder.AppendLine(System.IO.Path.GetFileNameWithoutExtension(x.Identifier))); TaskDialog td = new TaskDialog("Unload Unused Item Files") { MainIcon = TaskDialogIcon.TaskDialogIconInformation, TitleAutoPrefix = false, MainInstruction = "The following item files were unloaded:", MainContent = builder.ToString() }; td.Show(); } } return(Result.Succeeded); } catch (Exception ex) { message = ex.Message; return(Result.Failed); } }
/// <summary> /// Implement this method as an external command for Revit. /// </summary> /// <param name="commandData">An object that is passed to the external application /// which contains data related to the command, /// such as the application object and active view.</param> /// <param name="message">A message that can be set by the external application /// which will be displayed if a failure or cancellation is returned by /// the external command.</param> /// <param name="elements">A set of elements to which the external application /// can add elements that are to be highlighted in case of failure or cancellation.</param> /// <returns>Return the status of the external command. /// A result of Succeeded means that the API external method functioned as expected. /// Cancelled can be used to signify that the user cancelled the external operation /// at some point. Failure should be returned if the application is unable to proceed with /// the operation.</returns> public virtual Result Execute(ExternalCommandData commandData , ref string message, ElementSet elements) { Document doc = commandData.Application.ActiveUIDocument.Document; UIDocument uidoc = commandData.Application.ActiveUIDocument; FabricationPart fabPart = null; FabricationConfiguration config = null; try { // check for a load fabrication config config = FabricationConfiguration.GetFabricationConfiguration(doc); if (config == null) { message = "No fabrication configuration loaded."; return(Result.Failed); } // pick a fabrication part Reference refObj = uidoc.Selection.PickObject(ObjectType.Element, "Pick a fabrication part to start."); fabPart = doc.GetElement(refObj) as FabricationPart; } catch (Autodesk.Revit.Exceptions.OperationCanceledException) { return(Result.Cancelled); } if (fabPart == null) { message = "The selected element is not a fabrication part."; return(Result.Failed); } else { // get ancillary data from selected part and report to user IList <FabricationAncillaryUsage> ancillaries = fabPart.GetPartAncillaryUsage(); List <string> ancillaryDescriptions = new List <string>(); // create list of ancillary descriptions using the Ancillary UseageType and Name foreach (var ancillaryUsage in ancillaries) { FabricationAncillaryType ancilType = ancillaryUsage.Type; FabricationAncillaryUsageType usageType = ancillaryUsage.UsageType; ancillaryDescriptions.Add($"{ancilType.ToString()}: {usageType.ToString()} - " + $"{config.GetAncillaryName(ancillaryUsage.AncillaryId)}"); } string results = string.Empty; // group and quantify if (ancillaryDescriptions.Count > 0) { ancillaryDescriptions.Sort(); StringBuilder resultsBuilder = new StringBuilder(); string currentAncillary = string.Empty; foreach (var ancillaryName in ancillaryDescriptions) { if (ancillaryName != currentAncillary) { resultsBuilder.AppendLine($"{ancillaryName} x {ancillaryDescriptions.Count(x => x == ancillaryName)}"); currentAncillary = ancillaryName; } } results = resultsBuilder.ToString(); } TaskDialog td = new TaskDialog("Ancillaries") { MainIcon = TaskDialogIcon.TaskDialogIconInformation, TitleAutoPrefix = false, MainInstruction = ancillaryDescriptions.Count > 0 ? $"{ancillaryDescriptions.Count} ancillaries found on selected part" : $"No ancillaries found on selected part", MainContent = results }; td.Show(); } return(Result.Succeeded); }
private void extract_mep_data(Document rvtDoc) { try { FabricationConfiguration config = FabricationConfiguration.GetFabricationConfiguration(rvtDoc); if (config == null) { LogTrace("GetFabricationConfiguration failed"); return; } GetFabricationConnectors(config); FilteredElementCollector m_Collector = new FilteredElementCollector(rvtDoc); m_Collector.OfClass(typeof(FabricationPart)); IList <Element> fps = m_Collector.ToElements(); string outputFullPath = System.IO.Directory.GetCurrentDirectory() + "\\" + OUTPUT_FILE; FileStream fs = new FileStream(outputFullPath, System.IO.FileMode.Create, System.IO.FileAccess.Write); StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.UTF8); foreach (Element el in fps) { FabricationPart fp = el as FabricationPart; LogTrace("Reading data of one FabricationPart: " + fp.Name); sw.WriteLine("Name: " + fp.Name); foreach (Parameter para in el.Parameters) { sw.WriteLine(" " + GetParameterInformation(para, rvtDoc)); } sw.WriteLine(" ProductName: " + fp.ProductName); sw.WriteLine(" ServiceName: " + fp.ServiceName); sw.WriteLine(" Service Type: " + config.GetServiceTypeName(fp.ServiceType)); sw.WriteLine(" SpoolName: " + fp.SpoolName); sw.WriteLine(" Alias: " + fp.Alias); sw.WriteLine(" CID: " + fp.ItemCustomId.ToString()); sw.WriteLine(" Domain Type: " + fp.DomainType.ToString()); if (fp.IsAHanger()) { string rodKitName = " None"; var rodKit = fp.HangerRodKit; if (rodKit > 0) { rodKitName = config.GetAncillaryGroupName(fp.HangerRodKit) + ": " + config.GetAncillaryName(fp.HangerRodKit); } sw.WriteLine(" Hanger Rod Kit: " + rodKitName); } var insSpec = config.GetInsulationSpecificationGroup(fp.InsulationSpecification) + ": " + config.GetInsulationSpecificationName(fp.InsulationSpecification); sw.WriteLine(" Insulation Specification: " + insSpec); sw.WriteLine(" Has No Connections: " + fp.HasNoConnections().ToString()); sw.WriteLine(" Item Number: " + fp.ItemNumber); var material = config.GetMaterialGroup(fp.Material) + ": " + config.GetMaterialName(fp.Material); sw.WriteLine(" Material: " + material); sw.WriteLine(" Part Guid: " + fp.PartGuid.ToString()); sw.WriteLine(" Part Status: " + config.GetPartStatusDescription(fp.PartStatus)); sw.WriteLine(" Product Code: " + fp.ProductCode); var spec = config.GetSpecificationGroup(fp.Specification) + ": " + config.GetSpecificationName(fp.Specification); sw.WriteLine(" Specification: " + spec); sw.WriteLine(" Dimensions from Fabrication Dimension Definition:"); foreach (FabricationDimensionDefinition dmdef in fp.GetDimensions()) { sw.WriteLine(" " + dmdef.Name + ":" + fp.GetDimensionValue(dmdef).ToString()); } int index = 1; sw.WriteLine(" Connectors:"); foreach (Connector con in fp.ConnectorManager.Connectors) { sw.WriteLine(" C" + index.ToString()); FabricationConnectorInfo fci = con.GetFabricationConnectorInfo(); sw.WriteLine(" Connector Info:" + m_connGroups[fci.BodyConnectorId] + " " + m_connNames[fci.BodyConnectorId]); sw.WriteLine(" IsBodyConnectorLocked:" + fci.IsBodyConnectorLocked.ToString()); sw.WriteLine(" Shape:" + con.Shape.ToString()); try { sw.WriteLine(" Radius:" + con.Radius.ToString()); } catch (Exception ex) { } try { sw.WriteLine(" PressureDrop:" + con.PressureDrop.ToString()); } catch (Exception ex) { } try { sw.WriteLine(" Width:" + con.Width.ToString()); } catch (Exception ex) { } try { sw.WriteLine(" Height:" + con.Height.ToString()); } catch (Exception ex) { } try { sw.WriteLine(" PipeSystemType:" + con.PipeSystemType.ToString()); } catch (Exception ex) { } try { sw.WriteLine(" VelocityPressure:" + con.VelocityPressure.ToString()); } catch (Exception ex) { } try { sw.WriteLine(" DuctSystemType:" + con.DuctSystemType.ToString()); } catch (Exception ex) { } index++; } } LogTrace("Saving file..."); sw.Close(); fs.Close(); } catch (Exception ex) { LogTrace("Unexpected Exception..." + ex.ToString()); } }
/// <summary> /// Report the custom data. /// </summary> /// <param name="doc"></param> /// <param name="uiDoc"></param> /// <param name="setNewValues"></param> /// <param name="message"></param> /// <returns></returns> public static Result ReportCustomData(Document doc, UIDocument uiDoc, bool setNewValues, ref string message) { FabricationPart fabPart = null; FabricationConfiguration config = null; try { // check for a load fabrication config config = FabricationConfiguration.GetFabricationConfiguration(doc); if (config == null) { message = "No fabrication configuration loaded."; return(Result.Failed); } // pick a fabrication part Reference refObj = uiDoc.Selection.PickObject(ObjectType.Element, "Pick a fabrication part to start."); fabPart = doc.GetElement(refObj) as FabricationPart; } catch (Autodesk.Revit.Exceptions.OperationCanceledException) { return(Result.Cancelled); } if (fabPart == null) { message = "The selected element is not a fabrication part."; return(Result.Failed); } else { // get custom data from loaded fabrication config IList <int> customDataIds = config.GetAllPartCustomData(); int customDataCount = customDataIds.Count; string results = string.Empty; // report custom data info if (customDataCount > 0) { StringBuilder resultsBuilder = new StringBuilder(); resultsBuilder.AppendLine($"Fabrication config contains {customDataCount} custom data entries {Environment.NewLine}"); foreach (var customDataId in customDataIds) { FabricationCustomDataType customDataType = config.GetPartCustomDataType(customDataId); string customDataName = config.GetPartCustomDataName(customDataId); resultsBuilder.AppendLine($"Type: {customDataType.ToString()} Name: {customDataName}"); // check custom data exists on selected part if (fabPart.HasCustomData(customDataId)) { string fabPartCurrentValue = string.Empty; string fabPartNewValue = string.Empty; switch (customDataType) { case FabricationCustomDataType.Text: fabPartCurrentValue = $"\"{fabPart.GetPartCustomDataText(customDataId)}\""; if (setNewValues) { string installDateTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm"); fabPart.SetPartCustomDataText(customDataId, installDateTime); fabPartNewValue = installDateTime; } break; case FabricationCustomDataType.Integer: fabPartCurrentValue = fabPart.GetPartCustomDataInteger(customDataId).ToString(); if (setNewValues) { int installHours = new Random().Next(1, 10); fabPart.SetPartCustomDataInteger(customDataId, installHours); fabPartNewValue = installHours.ToString(); } break; case FabricationCustomDataType.Real: fabPartCurrentValue = $"{fabPart.GetPartCustomDataReal(customDataId):0.##}"; if (setNewValues) { double installCost = new Random().NextDouble() * new Random().Next(100, 1000); fabPart.SetPartCustomDataReal(customDataId, installCost); fabPartNewValue = $"{installCost:0.##}"; } break; } resultsBuilder.AppendLine("Current custom data entry value = " + $"{fabPartCurrentValue} {Environment.NewLine}"); if (setNewValues) { resultsBuilder.AppendLine("New custom data entry value = " + $"{fabPartNewValue} {Environment.NewLine}"); } } else { resultsBuilder.AppendLine($"Custom data entry is not set on the part {Environment.NewLine}"); } } results = resultsBuilder.ToString(); } TaskDialog td = new TaskDialog("Custom Data") { MainIcon = TaskDialogIcon.TaskDialogIconInformation, TitleAutoPrefix = false, MainInstruction = $"{customDataCount} custom data entries found in the loaded fabrication config", MainContent = results }; td.Show(); } return(Result.Succeeded); }
/// <summary> /// Implement this method as an external command for Revit. /// </summary> /// <param name="commandData">An object that is passed to the external application /// which contains data related to the command, /// such as the application object and active view.</param> /// <param name="message">A message that can be set by the external application /// which will be displayed if a failure or cancellation is returned by /// the external command.</param> /// <param name="elements">A set of elements to which the external application /// can add elements that are to be highlighted in case of failure or cancellation.</param> /// <returns>Return the status of the external command. /// A result of Succeeded means that the API external method functioned as expected. /// Cancelled can be used to signify that the user cancelled the external operation /// at some point. Failure should be returned if the application is unable to proceed with /// the operation.</returns> public virtual Result Execute(ExternalCommandData commandData , ref string message, ElementSet elements) { try { // check user selection var uiDoc = commandData.Application.ActiveUIDocument; var doc = uiDoc.Document; Reference refObj = uiDoc.Selection.PickObject(ObjectType.Element, "Pick a fabrication part to start."); var part = doc.GetElement(refObj) as FabricationPart; if (part == null) { message = "The selected element is not a fabrication part."; return(Result.Failed); } var config = FabricationConfiguration.GetFabricationConfiguration(doc); if (config == null) { message = "no valid fabrication configuration"; return(Result.Failed); } var builder = new StringBuilder(); // alias builder.AppendLine("Alias: " + part.Alias); // cid builder.AppendLine("CID: " + part.ItemCustomId.ToString()); // domain type builder.AppendLine("Domain Type: " + part.DomainType.ToString()); // hanger rod kit if (part.IsAHanger()) { string rodKitName = "None"; var rodKit = part.HangerRodKit; if (rodKit > 0) { rodKitName = config.GetAncillaryGroupName(part.HangerRodKit) + ": " + config.GetAncillaryName(part.HangerRodKit); } builder.AppendLine("Hanger Rod Kit: " + rodKitName); } // insulation specification var insSpec = config.GetInsulationSpecificationGroup(part.InsulationSpecification) + ": " + config.GetInsulationSpecificationName(part.InsulationSpecification); builder.AppendLine("Insulation Specification: " + insSpec); // has no connections builder.AppendLine("Has No Connections: " + part.HasNoConnections().ToString()); // item number builder.AppendLine("Item Number: " + part.ItemNumber); // material var material = config.GetMaterialGroup(part.Material) + ": " + config.GetMaterialName(part.Material); builder.AppendLine("Material: " + material); // part guid builder.AppendLine("Part Guid: " + part.PartGuid.ToString()); // part status builder.AppendLine("Part Status: " + config.GetPartStatusDescription(part.PartStatus)); // product code builder.AppendLine("Product Code: " + part.ProductCode); // service builder.AppendLine("Service Name: " + part.ServiceName); // get the service type name builder.AppendLine("Service Type: " + config.GetServiceTypeName(part.ServiceType)); // specification var spec = config.GetSpecificationGroup(part.Specification) + ": " + config.GetSpecificationName(part.Specification); builder.AppendLine("Specification: " + spec); // centerline length builder.AppendLine("Centerline Length: " + GetStringFromNumber(doc, part.CenterlineLength, UnitType.UT_Length)); TaskDialog.Show("Fabrication Part [" + part.Id.IntegerValue + "]", builder.ToString()); return(Result.Succeeded); } catch (Exception ex) { message = ex.Message; return(Result.Failed); } }
/// <summary> /// Implement this method as an external command for Revit. /// </summary> /// <param name="commandData">An object that is passed to the external application /// which contains data related to the command, /// such as the application object and active view.</param> /// <param name="message">A message that can be set by the external application /// which will be displayed if a failure or cancellation is returned by /// the external command.</param> /// <param name="elements">A set of elements to which the external application /// can add elements that are to be highlighted in case of failure or cancellation.</param> /// <returns>Return the status of the external command. /// A result of Succeeded means that the API external method functioned as expected. /// Cancelled can be used to signify that the user cancelled the external operation /// at some point. Failure should be returned if the application is unable to proceed with /// the operation.</returns> public virtual Result Execute(ExternalCommandData commandData , ref string message, ElementSet elements) { try { Document doc = commandData.Application.ActiveUIDocument.Document; // get the user selection UIDocument uidoc = commandData.Application.ActiveUIDocument; ICollection <ElementId> collection = uidoc.Selection.GetElementIds(); if (collection.Count > 0) { // DesignToFabrication needs an ISet<ElementId> ISet <ElementId> selIds = new HashSet <ElementId>(); foreach (ElementId id in collection) { selIds.Add(id); } // Set the in-line element type identiers to be swapped during the conversion replacing the family with a similar fabrication part IDictionary <ElementId, ElementId> convertInLineIds = new Dictionary <ElementId, ElementId>(); // Get all family symbols FilteredElementCollector familyFinder = new FilteredElementCollector(doc); var families = familyFinder.OfClass(typeof(FamilySymbol)).ToElements().ToList(); // Get the family symbol for the damper we are going to convert String fsName = "Fire Damper - Rectangular - Simple"; // The found family symbol FamilySymbol fsDamper = null; foreach (FamilySymbol family in families) { if (family.FamilyName == fsName) { fsDamper = family; break; } } // If the damper was found try to find the matching fabrication part type if (fsDamper != null) { // Get the element type identifier for the family symbol var elemFamSymId = fsDamper.Id; // Get all fabrication part types FilteredElementCollector fabPartTypeFinder = new FilteredElementCollector(doc); var fabPartTypes = fabPartTypeFinder.OfClass(typeof(FabricationPartType)).ToElements().ToList(); // Get the fabrication part type for the damper we are going to convert to String fptName = "Rect FD - Flange"; // The found fabrication part type FabricationPartType fptDamper = null; foreach (FabricationPartType partType in fabPartTypes) { if (partType.FamilyName == fptName) { fptDamper = partType; break; } } // The damper was found create the mapping in between the family symbol and the matching fabrication part type if (fptDamper != null) { // Get the element type identifier for the fabricaion part type var elemFabPartTypeId = fptDamper.Id; // Create the mapping for the family to the fabrication part convertInLineIds.Add(elemFamSymId, elemFabPartTypeId); } } using (Transaction tr = new Transaction(doc, "Convert To Fabrication Parts")) { tr.Start(); FabricationConfiguration config = FabricationConfiguration.GetFabricationConfiguration(doc); // get all loaded fabrication services and attempt to convert the design elements // to the first loaded service IList <FabricationService> allLoadedServices = config.GetAllLoadedServices(); DesignToFabricationConverter converter = new DesignToFabricationConverter(doc); // If there is a mapping defined attempt to add it to the converter if (convertInLineIds.Count() > 0) { // Set the mappings DesignToFabricationMappingResult mappingResult = converter.SetMapForFamilySymbolToFabricationPartType(convertInLineIds); if (mappingResult != DesignToFabricationMappingResult.Success) { if (mappingResult != DesignToFabricationMappingResult.Undefined) { message = "There was a problem with the conversion. The map contained no entries."; } else if (mappingResult != DesignToFabricationMappingResult.InvalidFamilySymbol) { message = "There was a problem with the conversion. There was an invalid Family symbol identifier or an identifier that did not exist in the mappings."; } else if (mappingResult != DesignToFabricationMappingResult.InvalidFabricationPartType) { message = "There was a problem with the conversion. There was an invalid Fabrication part type identifier or an identifier that did not exist in the mappings."; } else if (mappingResult != DesignToFabricationMappingResult.UnsupportedFamilySymbol) { message = "There was a problem with the conversion. Unsupported Family symbol it is expected to be either valve, strainer, damper, smoke detector, end cap, or other in line component."; } else if (mappingResult != DesignToFabricationMappingResult.UnsupportedFabricationPartType) { message = "There was a problem with the conversion. Unsupported Fabrication part type. It is expected to be either valve, strainer, damper, smoke detector, end cap, or other in line component."; } return(Result.Failed); } } DesignToFabricationConverterResult result = converter.Convert(selIds, allLoadedServices[0].ServiceId); if (result != DesignToFabricationConverterResult.Success) { message = "There was a problem with the conversion."; return(Result.Failed); } doc.Regenerate(); tr.Commit(); } return(Result.Succeeded); } else { // inform user they need to select at least one element message = "Please select at least one element."; } return(Result.Failed); } catch (Exception ex) { message = ex.Message; return(Result.Failed); } }
/// <summary> /// Implement this method as an external command for Revit. /// </summary> /// <param name="commandData">An object that is passed to the external application /// which contains data related to the command, /// such as the application object and active view.</param> /// <param name="message">A message that can be set by the external application /// which will be displayed if a failure or cancellation is returned by /// the external command.</param> /// <param name="elements">A set of elements to which the external application /// can add elements that are to be highlighted in case of failure or cancellation.</param> /// <returns>Return the status of the external command. /// A result of Succeeded means that the API external method functioned as expected. /// Cancelled can be used to signify that the user cancelled the external operation /// at some point. Failure should be returned if the application is unable to proceed with /// the operation.</returns> public virtual Result Execute(ExternalCommandData commandData , ref string message, ElementSet elements) { try { Document doc = commandData.Application.ActiveUIDocument.Document; // get the user selection UIDocument uidoc = commandData.Application.ActiveUIDocument; ICollection <ElementId> collection = uidoc.Selection.GetElementIds(); if (collection.Count > 0) { // FabricationNetworkChangeService needs an ISet<ElementId> ISet <ElementId> selIds = new HashSet <ElementId>(); foreach (ElementId id in collection) { selIds.Add(id); } using (Transaction tr = new Transaction(doc, "Appply Change Service and Size of Fabrication Parts")) { tr.Start(); FabricationConfiguration config = FabricationConfiguration.GetFabricationConfiguration(doc); // Get all loaded fabrication services IList <FabricationService> allLoadedServices = config.GetAllLoadedServices(); FabricationNetworkChangeService applychange = new FabricationNetworkChangeService(doc); // Set the selection of element identifiers to be changed applychange.SetSelection(selIds); // Set the service to the second service in the list (ductwork exhaust service) applychange.SetServiceId(allLoadedServices[1].ServiceId); // Set the group to the second in the list (round) applychange.SetGroupId(1); // Get the sizes of all the straights that was in the selection of elements that was added to FabricationNetworkChangeService ISet <Autodesk.Revit.DB.Fabrication.FabricationPartSizeMap> sizeMappings = applychange.GetMapOfAllSizesForStraights(); foreach (Autodesk.Revit.DB.Fabrication.FabricationPartSizeMap sizemapping in sizeMappings) { if (sizemapping != null) { // Testing round so ignoring the depth and adding 6" to the current size so all straights will be updated to a new size var widthDia = sizemapping.WidthDiameter + 0.5; sizemapping.MappedWidthDiameter = widthDia; } } applychange.SetMapOfSizesForStraights(sizeMappings); // Get the in-line element type identiers var inlineRevIds = new HashSet <Autodesk.Revit.DB.ElementId>(); ISet <Autodesk.Revit.DB.ElementId> inlineIds = applychange.GetInLinePartTypes(); for (var ii = inlineIds.Count() - 1; ii > -1; ii--) { var elemId = inlineIds.ElementAt(ii); if (elemId != null) { inlineRevIds.Add(elemId); } } // Set the in-line element type identiers by swapping them out by reversing the order to keep it simple but still exercise the code IDictionary <ElementId, ElementId> swapinlineIds = new Dictionary <ElementId, ElementId>(); for (var ii = inlineIds.Count() - 1; ii > -1; ii--) { var elemId = inlineIds.ElementAt(ii); var elemIdother = inlineRevIds.ElementAt(ii); if ((elemId != null) && (elemId != null)) { swapinlineIds.Add(elemId, elemIdother); } } applychange.SetMapOfInLinePartTypes(swapinlineIds); // Apply the changes FabricationNetworkChangeServiceResult result = applychange.ApplyChange(); if (result != FabricationNetworkChangeServiceResult.Success) { message = "There was a problem with the apply change."; return(Result.Failed); } doc.Regenerate(); tr.Commit(); } return(Result.Succeeded); } else { // inform user they need to select at least one element message = "Please select at least one element."; } return(Result.Failed); } catch (Exception ex) { message = ex.Message; return(Result.Failed); } }
/// <summary> /// Implement this method as an external command for Revit. /// </summary> /// <param name="commandData">An object that is passed to the external application /// which contains data related to the command, /// such as the application object and active view.</param> /// <param name="message">A message that can be set by the external application /// which will be displayed if a failure or cancellation is returned by /// the external command.</param> /// <param name="elements">A set of elements to which the external application /// can add elements that are to be highlighted in case of failure or cancellation.</param> /// <returns>Return the status of the external command. /// A result of Succeeded means that the API external method functioned as expected. /// Cancelled can be used to signify that the user cancelled the external operation /// at some point. Failure should be returned if the application is unable to proceed with /// the operation.</returns> public virtual Result Execute(ExternalCommandData commandData , ref string message, ElementSet elements) { try { Document doc = commandData.Application.ActiveUIDocument.Document; // get the user selection UIDocument uidoc = commandData.Application.ActiveUIDocument; ICollection <ElementId> collection = uidoc.Selection.GetElementIds(); if (collection.Count > 0) { // FabricationNetworkChangeService needs an ISet<ElementId> ISet <ElementId> selIds = new HashSet <ElementId>(); foreach (ElementId id in collection) { selIds.Add(id); } using (Transaction tr = new Transaction(doc, "Change Size of Fabrication Parts")) { tr.Start(); FabricationConfiguration config = FabricationConfiguration.GetFabricationConfiguration(doc); // Get all loaded fabrication services IList <FabricationService> allLoadedServices = config.GetAllLoadedServices(); // Create a map of sizes to swap the current sizes to a new size var sizeMappings = new HashSet <Autodesk.Revit.DB.Fabrication.FabricationPartSizeMap>(); var mapping = new Autodesk.Revit.DB.Fabrication.FabricationPartSizeMap("12x12", 1.0, 1.0, false, ConnectorProfileType.Rectangular, allLoadedServices[0].ServiceId, 0); mapping.MappedWidthDiameter = 1.5; mapping.MappedDepth = 1.5; sizeMappings.Add(mapping); var mapping1 = new Autodesk.Revit.DB.Fabrication.FabricationPartSizeMap("18x18", 1.5, 1.5, false, ConnectorProfileType.Rectangular, allLoadedServices[0].ServiceId, 0); mapping1.MappedWidthDiameter = 2.0; mapping1.MappedDepth = 2.0; sizeMappings.Add(mapping1); FabricationNetworkChangeService changesize = new FabricationNetworkChangeService(doc); // Change the size of the fabrication parts in the selection to the new sizes FabricationNetworkChangeServiceResult result = changesize.ChangeSize(selIds, sizeMappings); if (result != FabricationNetworkChangeServiceResult.Success) { // Get the collection of element identifiers for parts that had errors posted against them ICollection <ElementId> errorIds = changesize.GetElementsThatFailed(); if (errorIds.Count > 0) { message = "There was a problem with the change size."; return(Result.Failed); } } doc.Regenerate(); tr.Commit(); } return(Result.Succeeded); } else { // inform user they need to select at least one element message = "Please select at least one element."; } return(Result.Failed); } catch (Exception ex) { message = ex.Message; return(Result.Failed); } }