public AdminFamiliesSRCPRequest(UIApplication uiApp, String text) { MainUI uiForm = BARevitTools.Application.thisApp.newMainUi; RVTDocument doc = uiApp.ActiveUIDocument.Document; //Clear out the backup families from the directory List <string> backupFamilies = GeneralOperations.GetAllRvtBackupFamilies(uiForm.adminFamiliesSRCPDirectoryTextBox.Text, true); GeneralOperations.CleanRfaBackups(backupFamilies); //Get the family files from the directory. If the option to use the date since last modified was checked, use the first method, else use the second method List <string> familyFiles = new List <string>(); if (uiForm.adminFamiliesSRCPUseDateCheckBox.Checked) { familyFiles = GeneralOperations.GetAllRvtFamilies(uiForm.adminFamiliesSRCPDirectoryTextBox.Text, uiForm.adminFamiliesSRCPDatePicker.Value, true); } else { familyFiles = GeneralOperations.GetAllRvtFamilies(uiForm.adminFamiliesSRCPDirectoryTextBox.Text, false); } //Verify the number of families collected is more than 0 if (familyFiles.Count > 0) { foreach (string familyFile in familyFiles) { RVTDocument famDoc = RVTOperations.OpenRevitFile(uiApp, familyFile); Family family = famDoc.OwnerFamily; Parameter rcp = family.get_Parameter(BuiltInParameter.ROOM_CALCULATION_POINT); if (rcp.AsInteger() == 0) { try { using (Transaction t1 = new Transaction(famDoc, "SetRoomCalculationPoint")) { t1.Start(); rcp.Set(1); t1.Commit(); } uiForm.adminFamiliesSRCPListBox.Items.Add(famDoc.Title.Replace(".rfa", "") + ": Updated"); } catch (Exception e) { uiForm.adminFamiliesSRCPListBox.Items.Add(famDoc.Title.Replace(".rfa", "") + ": FAILED"); } } else { uiForm.adminFamiliesSRCPListBox.Items.Add(famDoc.Title.Replace(".rfa", "") + ": Ignored"); } RVTOperations.SaveRevitFile(uiApp, famDoc, true); } } GeneralOperations.CleanRfaBackups(uiForm.adminFamiliesSRCPDirectoryTextBox.Text); }
public WallsDPRequest(UIApplication uiApp, String text) { RVTDocument doc = uiApp.ActiveUIDocument.Document; //Encapsulating in a transaction for tidiness using (Transaction t1 = new Transaction(doc, "RemoveWallParts")) { t1.Start(); //Get the ElementId of the wall to remove parts from ElementId elementId = RVTOperations.SelectElement(uiApp); if (elementId != null) { //Verify the element is a wall if (doc.GetElement(elementId).Category.Name.ToString() == "Walls") { try { //Delete the parts associated with the wall RVTOperations.DeleteParts(uiApp, doc, elementId); } catch { //If the parts could not be deleted, report it MessageBox.Show("Could not delete any parts from the wall." + " If the element you selected has parts, ensure you are selecting the original wall and not the parts." + " Set the view's Parts Visibility property to Show Original to assist with selecting the wall."); } } else { //If the element was not a wall element, let the user know to select a wall element MessageBox.Show("The element selected was not a wall. Please select a wall element."); } } else { //If the user didn't select an element, MessageBox.Show("No element was selected"); } t1.Commit(); } }
public MaterialsCMSLoadFamilyRequest(UIApplication uiApp, String text) { RVTDocument doc = uiApp.ActiveUIDocument.Document; //Get version of the family file used for the ID Material Schedule symbol that matches the version of Revit running string familyFile = Properties.Settings.Default.RevitFamilyMaterialsCMSSymbIdMaterialSchedule; string versionedFamilyFile = ""; try { versionedFamilyFile = RVTOperations.GetVersionedFamilyFilePath(uiApp, familyFile); } catch { //But if that fails, just take the original version and upgrade it versionedFamilyFile = familyFile; } using (Transaction t1 = new Transaction(doc, "LoadFamily")) { t1.Start(); uiApp.ActiveUIDocument.Document.LoadFamily(versionedFamilyFile, out Family loadedFamily); Application.thisApp.newMainUi.materialsCMSFamilyToUse = loadedFamily; t1.Commit(); } }
// //This class is associated with the Upgrade Projects tool public SetupUPRequest(UIApplication uiApp, String text) { MainUI uiForm = BARevitTools.Application.thisApp.newMainUi; DataGridView dgv = uiForm.setupUPDataGridView; dgv.EndEdit(); RVTDocument doc = uiApp.ActiveUIDocument.Document; string hostFilePathToUpgrade = uiForm.setupUPOriginalFilePathTextBox.Text; string hostFilePathForUpgrade = uiForm.setupUPUpgradedFilePathSetTextBox.Text + "\\" + uiForm.setupUPUpgradedFilePathUserTextBox.Text + ".rvt"; //Reset the progress bar uiForm.setupUPProgressBar.Value = 0; uiForm.setupUPProgressBar.Minimum = 0; uiForm.setupUPProgressBar.Step = 1; //Determine the number of steps for the progress bar based on the number of links checked for upgrading plus 1 for the host int progressBarSteps = 1; foreach (DataGridViewRow row in dgv.Rows) { if (row.Cells["Upgrade"].Value != null) { if (row.Cells["Upgrade"].Value.ToString() == "True") { progressBarSteps++; } } } uiForm.setupUPProgressBar.Maximum = progressBarSteps; //Let the user know if they are trying to save over a file that already exists if (File.Exists(hostFilePathForUpgrade)) { MessageBox.Show("A file already exists with the name and location specified for the upgrade of the host Revit project file"); } //If they didn't set a save location for the file, let them know else if (uiForm.setupUPUpgradedFilePathUserTextBox.Text == "") { MessageBox.Show("No location for the upgrade of the host Revit project file is set"); } else { //Otherwise, show the progress bar and step through the rows of the DataGridView links uiForm.setupUPProgressBar.Visible = true; for (int i = 0; i < dgv.Rows.Count; i++) { try { if (dgv.Rows[i].Cells["Upgrade"].Value != null) { //If the link is allowed to be upgraded, and its checkbox is checked, continue if (dgv.Rows[i].Cells["Allow Upgrade"].Value.ToString() == "True" && dgv.Rows[i].Cells["Upgrade"].Value.ToString() == "True") { //Grab the orignial path for the link and the path for where it will be saved string linkFilePathToUpgrade = dgv.Rows[i].Cells["Original Path"].Value.ToString(); string linkFilePathForUpgrade = dgv.Rows[i].Cells["New Path"].Value.ToString(); //Perform the upgrade operations on the file and report if it was successful bool linkResult = RVTOperations.UpgradeRevitFile(uiApp, linkFilePathToUpgrade, linkFilePathForUpgrade, false); if (linkResult == true) { //If the upgrade was successful, set the Upgrade Result column to true and set the row's background color to GreenYellow dgv.Rows[i].Cells["Upgrade Result"].Value = true; dgv.Rows[i].DefaultCellStyle.BackColor = System.Drawing.Color.GreenYellow; } else { //If the upgrade failed, set the Upgrade Result column to false and set the background color to red dgv.Rows[i].Cells["Upgrade Result"].Value = false; dgv.Rows[i].DefaultCellStyle.BackColor = System.Drawing.Color.Red; } //Step forward the progress bar uiForm.setupUPProgressBar.PerformStep(); uiForm.Update(); } } else { continue; } } catch (Exception e) { MessageBox.Show(e.Message); } } //Once the links are done upgrading, upgrade the host bool hostResult = RVTOperations.UpgradeRevitFile(uiApp, hostFilePathToUpgrade, hostFilePathForUpgrade, false); //Determine how many links were able to be upgraded int countOfUpgradeLinks = 0; foreach (DataGridViewRow row in dgv.Rows) { try { if (row.Cells["Upgrade"].Value != null) { if (row.Cells["Upgrade"].Value.ToString() == "True") { countOfUpgradeLinks++; } } } catch { continue; } finally { uiForm.setupUPProgressBar.PerformStep(); uiForm.Update(); } } //If the host was able to be upgraded, continue if (hostResult == true) { //Set the background color of the text box to GreenYellow uiForm.setupUPOriginalFilePathTextBox.BackColor = System.Drawing.Color.GreenYellow; if (countOfUpgradeLinks > 0) { try { //Open the upgraded host and get the links RVTDocument hostDoc = RVTOperations.OpenRevitFile(uiApp, hostFilePathForUpgrade); Dictionary <string, RevitLinkType> linkNames = new Dictionary <string, RevitLinkType>(); var linkTypes = new FilteredElementCollector(hostDoc).OfClass(typeof(RevitLinkType)).ToElements(); foreach (RevitLinkType linkType in linkTypes) { //Add each link to a dictionary with their file name and indexed link type linkNames.Add(linkType.Name.Replace(".rvt", ""), linkType); } //Cycle through the links foreach (DataGridViewRow row in dgv.Rows) { try { //If the link's row was checked for upgrading, it was able to be upgraded, the upgraded file exists at the New Path location, and the dictionary of links contains the original name of the link, continue if (row.Cells["Upgrade"].Value.ToString() == "True" && row.Cells["Upgrade Result"].Value.ToString() == "True" && File.Exists(row.Cells["New Path"].Value.ToString()) && linkNames.Keys.Contains(row.Cells["Original Name"].Value.ToString())) { try { //Get the link to reload via the name from the dictionary RevitLinkType linkToReload = linkNames[row.Cells["Original Name"].Value.ToString().Replace(".rvt", "")]; //Convert the link's user path to a model path, then reload it ModelPath modelPathToLoadFrom = ModelPathUtils.ConvertUserVisiblePathToModelPath(row.Cells["New Path"].Value.ToString()); linkToReload.LoadFrom(modelPathToLoadFrom, new WorksetConfiguration()); } catch (Exception e) { //If the link was upgraded but could not be reloaded, set the background color to orange and let the user know it could not be reloaded row.DefaultCellStyle.BackColor = System.Drawing.Color.Orange; MessageBox.Show(String.Format("Could not remap the link named {0} in the host file", row.Cells["Original Name"].Value.ToString())); MessageBox.Show(e.ToString()); } } } catch { continue; } } //Save the upgraded host file RVTOperations.SaveRevitFile(uiApp, hostDoc, true); } catch (Exception e) { MessageBox.Show(e.ToString()); } } } else { //If the host file failed to upgrade, set its text box background color to red uiForm.setupUPOriginalFilePathTextBox.BackColor = System.Drawing.Color.Red; } uiForm.Update(); uiForm.Refresh(); } }
public MaterialsAMLPaletteRequest(UIApplication uiApp, String text) { RVTDocument doc = uiApp.ActiveUIDocument.Document; MaterialsAMLPalette materialsPalette = BARevitTools.Application.thisApp.newMainUi.materialsAMLPalette; //Get the versioned symbol family FamilySymbol familySymbol = null; string versionedFamily = RVTOperations.GetVersionedFamilyFilePath(uiApp, Properties.Settings.Default.RevitIDAccentMatTag); //Try loading the family symbol Transaction loadSymbolTransaction = new Transaction(doc, "LoadFamilySymbol"); loadSymbolTransaction.Start(); try { try { IFamilyLoadOptions loadOptions = new RVTFamilyLoadOptions(); doc.LoadFamilySymbol(versionedFamily, "Legend Tag (Fake)", loadOptions, out FamilySymbol symb); familySymbol = symb; } catch { MessageBox.Show(String.Format("Could not get the 'Legend Tag (Fake)' type from {0}", versionedFamily), "Family Symbol Load Error"); } loadSymbolTransaction.Commit(); } catch (Exception transactionException) { loadSymbolTransaction.RollBack(); MessageBox.Show(transactionException.ToString()); } //Get the line style to use, or create the default Element lineStyle = null; if (materialsPalette.paletteMaterialComboBox.Text == "Default") { try { lineStyle = doc.Settings.Categories.get_Item(BuiltInCategory.OST_Lines).SubCategories.get_Item("6 BA ID ACCENT").GetGraphicsStyle(GraphicsStyleType.Projection); } catch { try { Category linesCategory = doc.Settings.Categories.get_Item(BuiltInCategory.OST_Lines); Category newLineStyleCategory = doc.Settings.Categories.NewSubcategory(linesCategory, "6 BA ID ACCENT"); newLineStyleCategory.LineColor = new Color(0, 0, 0); newLineStyleCategory.SetLineWeight(6, GraphicsStyleType.Projection); newLineStyleCategory.SetLinePatternId(LinePatternElement.GetSolidPatternId(), GraphicsStyleType.Projection); doc.Regenerate(); lineStyle = newLineStyleCategory.GetGraphicsStyle(GraphicsStyleType.Projection); } catch (Exception e) { MessageBox.Show(e.ToString()); } } } else { lineStyle = doc.Settings.Categories.get_Item(BuiltInCategory.OST_Lines).SubCategories.get_Item("ID " + materialsPalette.paletteMaterialComboBox.Text).GetGraphicsStyle(GraphicsStyleType.Projection); } //Assure the view being used is a floor plan if (doc.ActiveView.ViewType != ViewType.FloorPlan) { MessageBox.Show("This tool should be used ina a Floor Plan or Area Plan view"); } else { //Create a loop for picking points. Change the palette background color based on the number of points picked List <XYZ> pickedPoints = new List <XYZ>(); bool breakLoop = false; int pickCount = 0; while (breakLoop == false) { try { //Have the user begin picking points. The number of clicks to start the UI color change is 1 because the first click is usually to activate the window. XYZ point = uiApp.ActiveUIDocument.Selection.PickPoint(Autodesk.Revit.UI.Selection.ObjectSnapTypes.Endpoints, "Click points for the line to follow. Then click once to the side where the lines should be drawn. Hit ESC to finish"); pickedPoints.Add(point); if (pickCount == 1) { materialsPalette.BackColor = System.Drawing.Color.Firebrick; } else if (pickCount == 2) { materialsPalette.BackColor = System.Drawing.Color.Orange; } else if (pickCount > 2) { //After three clicks in the window, the user has made the minimum point selection to generate the lines from the start, end, and positive side points. materialsPalette.BackColor = System.Drawing.Color.GreenYellow; } else { ; } pickCount++; } catch { materialsPalette.BackColor = MaterialsAMLPalette.DefaultBackColor; breakLoop = true; } } //Get rid of the first point from clicking into the Revit view. This point is not needed. pickedPoints.RemoveAt(0); if (pickedPoints.Count > 2) { Transaction createLinesTransaction = new Transaction(doc, "CreateAccentLines"); createLinesTransaction.Start(); try { //These points will be used in determining the start, end, and room points XYZ firstPoint = pickedPoints[0]; XYZ roomPoint = pickedPoints[pickedPoints.Count - 1]; XYZ lastPoint = pickedPoints[pickedPoints.Count - 2]; //Create a list of points for the polyline that excludes the room point List <XYZ> polyLinePoints = new List <XYZ>(); for (int i = 0; i < pickedPoints.Count - 1; i++) { polyLinePoints.Add(pickedPoints[i]); } //Create a polyline from the list of picked points and then get make lines from the points on the poly line PolyLine guidePolyLine = PolyLine.Create(polyLinePoints); IList <XYZ> polyPoints = guidePolyLine.GetCoordinates(); List <Line> guideLines = new List <Line>(); for (int i = 0; i < polyLinePoints.Count - 1; i++) { guideLines.Add(Line.CreateBound(polyLinePoints[i], polyLinePoints[i + 1])); } //Get the direction of the line offset by measuring the first offset for positive and negative values and comparing their distances with the room point bool positiveZ = false; List <Line> offsetLines = new List <Line>(); Line positiveOffsetLine = guideLines.Last().CreateOffset(0.6666666667d, XYZ.BasisZ) as Line; Line negativeOffsetLine = guideLines.Last().CreateOffset(-0.6666666667d, XYZ.BasisZ) as Line; XYZ positiveOffsetMidPoint = positiveOffsetLine.Evaluate(0.5d, true); XYZ negativeOffsetMidPoint = negativeOffsetLine.Evaluate(0.5d, true); Double positiveOffsetDistance = positiveOffsetMidPoint.DistanceTo(roomPoint); Double negativeOffsetDistance = negativeOffsetMidPoint.DistanceTo(roomPoint); //If the positive offset side resulted in a shorter distance to the point inside the room, then the offset should have a positive Z normal. if (positiveOffsetDistance < negativeOffsetDistance) { positiveZ = true; } //Knowing whether or not to use a positive or negative offset, begin creating offset lines for each guide line foreach (Line guideLine in guideLines) { if (positiveZ) { offsetLines.Add(guideLine.CreateOffset(0.6666666667d, XYZ.BasisZ) as Line); } else { offsetLines.Add(guideLine.CreateOffset(-0.6666666667d, XYZ.BasisZ) as Line); } } //Determine if the number of line segments is 1 or more Line firstLine = offsetLines.First(); Line lastLine = null; if (offsetLines.Count > 1) { lastLine = offsetLines.Last(); } //If there is only one line segment, both end operations must be performed on it if (lastLine == null) { double lineLength = firstLine.Length; double fractionOfLength = 0.6666666667d / lineLength; //Checking fractions to ensure they are not greater than 1 for the normalization if (fractionOfLength > 1) { fractionOfLength = 0.25d; } //Re-evaluating where to place the start and end point of the line XYZ shiftedStartPoint = firstLine.Evaluate(fractionOfLength, true); XYZ shiftedEndPoint = firstLine.Evaluate(1 - fractionOfLength, true); firstLine = Line.CreateBound(shiftedStartPoint, shiftedEndPoint); //Creating the angled corner lines Line firstCornerLine = Line.CreateBound(firstPoint, firstLine.GetEndPoint(0)); Line lastCornerLine = Line.CreateBound(lastPoint, firstLine.GetEndPoint(1)); //Create the detail lines from the lines DetailCurve newAccentLine1 = doc.Create.NewDetailCurve(doc.ActiveView, firstCornerLine); DetailCurve newAccentLine2 = doc.Create.NewDetailCurve(doc.ActiveView, firstLine); DetailCurve newAccentLine3 = doc.Create.NewDetailCurve(doc.ActiveView, lastCornerLine); //Assign a line style to the newly created detail lines newAccentLine1.LineStyle = lineStyle; newAccentLine2.LineStyle = lineStyle; newAccentLine3.LineStyle = lineStyle; XYZ tagPlacementPoint = firstLine.Evaluate(0.5d, true); XYZ direction = firstLine.Direction; Line axisLine = Line.CreateUnbound(tagPlacementPoint, XYZ.BasisZ); double rotationAngle = direction.AngleTo(XYZ.BasisX); //Get the midpoint of the line, its direction, and create the rotation and axis if (familySymbol != null) { //Create the tag instance FamilyInstance newTag = doc.Create.NewFamilyInstance(tagPlacementPoint, familySymbol, doc.ActiveView); //Rotate the new tag instance ElementTransformUtils.RotateElement(doc, newTag.Id, axisLine, rotationAngle); } createLinesTransaction.Commit(); } //If there is more than one line segment, an operation must be performed on the start and end of the start and end lines, respectively else { List <Line> linesToDraw = new List <Line>(); // Get the normalized value for 8" relative to the lengths of the start and end lines double firstLineLength = firstLine.Length; double fractionOfFirstLine = 0.6666666667 / firstLineLength; double lastLineLength = lastLine.Length; double fractionOfLastLine = 0.666666667 / lastLineLength; //Checking fractions to ensure they are not greater than 1 for the normalization if (fractionOfFirstLine > 1) { fractionOfFirstLine = 0.25d; } if (fractionOfLastLine > 1) { fractionOfLastLine = 0.25d; } //Shift the ends of the start and end lines by finding the point along the line relative to the normalized 8" value XYZ shiftedStartPoint = firstLine.Evaluate(fractionOfFirstLine, true); XYZ shiftedEndPoint = lastLine.Evaluate(1 - fractionOfLastLine, true); //Reset the start and end lines with the new shifted points firstLine = Line.CreateBound(shiftedStartPoint, firstLine.GetEndPoint(1)); lastLine = Line.CreateBound(lastLine.GetEndPoint(0), shiftedEndPoint); linesToDraw.Add(firstLine); //If there are only 3 offset lines, there will be just one middle segment if (offsetLines.Count == 3) { linesToDraw.Add(offsetLines[1]); } //If there are more than three offset lines, there will be more than one middle line segment else { List <Line> middleLines = offsetLines.GetRange(1, offsetLines.Count - 2); foreach (Line middleLine in middleLines) { linesToDraw.Add(middleLine); } } linesToDraw.Add(lastLine); //For the lines to draw, intersect them with the next line in the list and reset their start and end points to be the intersection for (int i = 0; i < linesToDraw.Count - 1; i++) { Line line1 = linesToDraw[i]; Line scaledLine1 = Line.CreateUnbound(line1.GetEndPoint(1), line1.Direction); Line line2 = linesToDraw[i + 1]; Line scaledLine2 = Line.CreateUnbound(line2.GetEndPoint(0), line2.Direction.Negate()); SetComparisonResult intersectionResult = scaledLine1.Intersect(scaledLine2, out IntersectionResultArray results); if (intersectionResult == SetComparisonResult.Overlap) { IntersectionResult result = results.get_Item(0); Line newLine1 = Line.CreateBound(line1.GetEndPoint(0), result.XYZPoint); Line newLine2 = Line.CreateBound(result.XYZPoint, line2.GetEndPoint(1)); linesToDraw[i] = newLine1; linesToDraw[i + 1] = newLine2; } } //Create the angled corner lines at the start and end of the line chain Line firstCornerLine = Line.CreateBound(firstPoint, firstLine.GetEndPoint(0)); Line lastCornerLine = Line.CreateBound(lastPoint, lastLine.GetEndPoint(1)); linesToDraw.Add(firstCornerLine); linesToDraw.Add(lastCornerLine); //Create each line as a detail line foreach (Line apiLine in linesToDraw) { DetailCurve newAccentLine = doc.Create.NewDetailCurve(doc.ActiveView, apiLine); newAccentLine.LineStyle = lineStyle; } //Declare some stuff for use in the symbol placement Line firstMiddleLine = linesToDraw[0]; Line lastMiddleLine = linesToDraw[linesToDraw.Count - 3]; XYZ firstTagPoint = firstMiddleLine.Evaluate(0.5d, true); XYZ lastTagPoint = lastMiddleLine.Evaluate(0.5d, true); XYZ firstDirection = firstMiddleLine.Direction; XYZ lastDirection = lastMiddleLine.Direction; Line firstAxisLine = Line.CreateUnbound(firstTagPoint, XYZ.BasisZ); Line lastAxisLine = Line.CreateUnbound(lastTagPoint, XYZ.BasisZ); double firstRotation = firstDirection.AngleTo(XYZ.BasisX); double lastRotation = lastDirection.AngleTo(XYZ.BasisX); if (familySymbol != null) { //Create tag at the beginning of the middle lines FamilyInstance firstTag = doc.Create.NewFamilyInstance(firstTagPoint, familySymbol, doc.ActiveView); ElementTransformUtils.RotateElement(doc, firstTag.Id, firstAxisLine, firstRotation); //Create a tag at the end of the middle lines if there are more than 2 middle lines if (linesToDraw.Count > 4) { FamilyInstance lastTag = doc.Create.NewFamilyInstance(lastTagPoint, familySymbol, doc.ActiveView); ElementTransformUtils.RotateElement(doc, lastTag.Id, lastAxisLine, lastRotation); } } createLinesTransaction.Commit(); } } catch (Exception e) { //Suppose the user closed the palette too soon. This will remind them to keep it open. if (BARevitTools.Application.thisApp.newMainUi.materialsAMLPalette == null) { MessageBox.Show("AML Picker was closed prematurely. Please keep the picker open until the lines are drawn."); } else { //Otherwise, if some other error occurred, show the exception MessageBox.Show(e.ToString()); } createLinesTransaction.RollBack(); } } else { ; } } }
public AdminFamiliesBRPRequest(UIApplication uiApp, String text) { MainUI uiForm = BARevitTools.Application.thisApp.newMainUi; RVTDocument doc = uiApp.ActiveUIDocument.Document; SaveAsOptions saveAsOptions = new SaveAsOptions(); saveAsOptions.Compact = true; saveAsOptions.MaximumBackups = 3; saveAsOptions.OverwriteExistingFile = true; //Get how many families to evaluate for the progress bar steps and resetting the progress bar int filesToProcess = 0; foreach (DataGridViewRow rowCount in uiForm.adminFamiliesBRPFamiliesDGV.Rows) { if (rowCount.Cells[0].Value.ToString() == "True") { filesToProcess++; } } uiForm.adminFamiliesBRPProgressBar.Value = 0; uiForm.adminFamiliesBRPProgressBar.Minimum = 0; uiForm.adminFamiliesBRPProgressBar.Maximum = filesToProcess; uiForm.adminFamiliesBRPProgressBar.Step = 1; uiForm.adminFamiliesBRPProgressBar.Visible = true; //Stop all edits to the DataGridView table uiForm.adminFamiliesBAPParametersDGV.EndEdit(); foreach (DataGridViewRow row in uiForm.adminFamiliesBRPFamiliesDGV.Rows) { //If the checkbox to select the family is not in a null state, continue if (row.Cells["Family Select"].Value != null) { //If the checkbox to select the family is checked, continue if (row.Cells["Family Select"].Value.ToString() == "True") { //Get the family path for the selected row and make a dictionary to store the parameters by name string filePath = row.Cells["Family Path"].Value.ToString(); Dictionary <string, FamilyParameter> famParams = new Dictionary <string, FamilyParameter>(); try { //Open the file and verify it is a family document RVTDocument famDoc = RVTOperations.OpenRevitFile(uiApp, filePath); if (famDoc.IsFamilyDocument) { //saveFamily will be used to determine if the family needs saved or just closed. No need to save the family if nothing was modified bool saveFamily = false; //Get the Family Manager to retrieve the parameters, then add each parameter to the dictionary by name FamilyManager familyManager = famDoc.FamilyManager; foreach (FamilyParameter famParam in familyManager.Parameters) { if (!famParams.Keys.Contains(famParam.Definition.Name)) { famParams.Add(famParam.Definition.Name, famParam); } else { continue; } } //Cycle through the rows of parameter to remove foreach (DataGridViewRow paramRow in uiForm.adminFamiliesBRPParametersDGV.Rows) { //If the cell for the parameter name is not null, continue if (paramRow.Cells["Parameter Name"].Value != null) { //Get the name of the parameter to attempt removal, and see if it exists in the dictionary string name = paramRow.Cells["Parameter Name"].Value.ToString(); if (famParams.Keys.Contains(name)) { try { //Attempt to remove the parameter. This may not be possible if a built-in parameter was specified by name, so the Catch will throw the message stating the name of the parameter that could not be removed and which family it was attempted on using (Transaction t = new Transaction(famDoc, "Remove Parameter")) { t.Start(); familyManager.RemoveParameter(famParams[name]); t.Commit(); saveFamily = true; } } catch { MessageBox.Show(String.Format("Could not remove parameter '{0}' for family {1}", name, famDoc.Title)); } } } } //If there were any changes, save the family. If not, continue on to close the family if (saveFamily == true) { ModelPath modelPath = ModelPathUtils.ConvertUserVisiblePathToModelPath(filePath); famDoc.SaveAs(filePath, saveAsOptions); } } //Close the family document famDoc.Close(false); } catch { MessageBox.Show("The family could not be opened, likely due to being a newer version of Revit"); } finally { //No matter what, step forward the progress bar uiForm.adminFamiliesBRPProgressBar.PerformStep(); } } else { continue; } } } GeneralOperations.CleanRfaBackups(uiForm.adminFamiliesBRPFamilyDirectory); uiForm.adminFamiliesBRPProgressBar.Visible = false; }
//Here, the families or types will be made private static void CreateFamilyTypesFromTable(UIApplication uiApp, MainUI uiForm, string saveDirectory, DataGridView dgv, SaveAsOptions saveAsOptions, string familyFileToUse) { //First thing to do is open the family document and access the FamilyManager RVTDocument famDoc = RVTOperations.OpenRevitFile(uiApp, familyFileToUse); FamilyManager famMan = famDoc.FamilyManager; string tempFamilyPath = ""; //Next, delete all of the family types except one from the family and save the file off for temporary use try { //This is in a Try/Catch becuse there is a possibility for failure RVTOperations.DeleteFamilyTypes(famDoc, famMan); tempFamilyPath = saveDirectory + "\\" + String.Format(famDoc.Title).Replace(".rfa", "") + "_temp.rfa"; famDoc.SaveAs(tempFamilyPath, saveAsOptions); } catch { MessageBox.Show("Could not save out a temporary family file to the location where the families are to be saved. Verify the location is not read-only."); } //Ensure the open family gets closed finally { famDoc.Close(); } //Then, reopen the temporary family if it exists if (tempFamilyPath != "") { //Get all of the parameters in the family and add them to a dictionary indexed by the parameter name RVTDocument newFamDoc = RVTOperations.OpenRevitFile(uiApp, tempFamilyPath); FamilyManager newFamMan = newFamDoc.FamilyManager; FamilyParameterSet parameters = newFamMan.Parameters; Dictionary <string, FamilyParameter> famParamDict = new Dictionary <string, FamilyParameter>(); foreach (FamilyParameter param in parameters) { famParamDict.Add(param.Definition.Name, param); } //These integer values will be used to increment loops int rowsCount = dgv.Rows.Count; int columnsCount = dgv.Columns.Count; //Keep track of what family types were made so the script can later delete out the one that pre-existed in the family but is not needed. List <string> familyTypesMade = new List <string>(); //If the user decide to make types per row instead of families per row... if (uiForm.multiCatCFFEFamilyCreationComboBox.SelectedItem.ToString() == "Combine Types (1 File)") { //The progress bar should be prepared using the number of rows multipled by the number of columns for the number of steps to perform. This gives a better indication of progress than doing it based on the number of rows uiForm.multiCatCFFEFamiliesProgressBar.Minimum = 0; uiForm.multiCatCFFEFamiliesProgressBar.Maximum = (rowsCount - 1) * (columnsCount - 1); uiForm.multiCatCFFEFamiliesProgressBar.Step = 1; uiForm.multiCatCFFEFamiliesProgressBar.Visible = true; //Open the transaction Transaction t2 = new Transaction(newFamDoc, "MakeNewTypes"); t2.Start(); //The maximum of rows is greater than the maximum index value by 1, so this uses < to stop before an index out of range exception occurs. Also, the index starts at 1 instead of 0 because the top row is the info about the data type for (int i = 1; i < rowsCount; i++) { //The type name is in the first column. string newTypeName = dgv.Rows[i].Cells[0].Value.ToString(); //This operation will get the existing type names in the family as new ones are added to avoide duplication Dictionary <string, FamilyType> existingTypeNames = RVTOperations.GetFamilyTypeNames(newFamMan); //If the type does not exist in the dictionary... if (!existingTypeNames.Keys.Contains(newTypeName)) { //Create a new type and add it to the list of types made FamilyType newType = newFamMan.NewType(newTypeName); newFamMan.CurrentType = newType; familyTypesMade.Add(newType.Name); } else { //Otherwise set the current type in the family manager to the pre-existing one with the name of the one to be created newFamMan.CurrentType = existingTypeNames[newTypeName]; //Add that one to the list of types made, though it wasn't actually made familyTypesMade.Add(newFamMan.CurrentType.Name); } //Next, cycle through the columns, again starting with the column at index 1 and incrementing the columns to one less than the number of columns for (int j = 1; j < columnsCount; j++) { //Get the parameter name from the first column's header text string paramName = dgv.Columns[j].HeaderText; //Get the storage type from the first row string paramStorageTypeString = dgv.Rows[0].Cells[j].Value.ToString(); var paramValue = dgv.Rows[i].Cells[j].Value; //Assuming the parameter value is set... if (paramValue.ToString() != "") { //Set the parameter given the information about the FamilyManager, parameter definition, parameter type, parameter data type, value to set, and whether or not to convert inches to feet. Because this script relies on inch input, this needs done to convert to feet used by the Revit API FamilyParameter param = famParamDict[paramName]; ParameterType paramType = param.Definition.ParameterType; RVTOperations.SetFamilyParameterValue(newFamMan, param, paramType, paramStorageTypeString, paramValue, true); } //Step forward the progress bar for this parameter uiForm.multiCatCFFEFamiliesProgressBar.PerformStep(); } } t2.Commit(); //In another transaction, delete the pre-existing type used to generate the other types Transaction t3 = new Transaction(newFamDoc, "DeleteOldTypes"); t3.Start(); foreach (FamilyType type in newFamMan.Types) { //Set the current type to the one with the pre-existing type name and delete it if (!familyTypesMade.Contains(type.Name)) { newFamMan.CurrentType = type; newFamMan.DeleteCurrentType(); } } t3.Commit(); //Save out the family to the directory and remove the _temp from the name newFamDoc.SaveAs(saveDirectory + "\\" + String.Format(newFamDoc.Title).Replace("_temp", "") + ".rfa", saveAsOptions); newFamDoc.Close(); } //If the user chose to make a family file per row, the family will be saved out multiple times else if (uiForm.multiCatCFFEFamilyCreationComboBox.SelectedItem.ToString() == "1 Family Per Type (Multiple Files)") { //Set the number of steps for the progress bar to the number of rows with families to make uiForm.multiCatCFFEFamiliesProgressBar.Minimum = 0; uiForm.multiCatCFFEFamiliesProgressBar.Maximum = rowsCount - 1; uiForm.multiCatCFFEFamiliesProgressBar.Step = 1; uiForm.multiCatCFFEFamiliesProgressBar.Visible = true; //Again, starting at row index 1 because the first is the information about the data types. This loop will produce a family per row. One familly will be opened and saved off multiple times, performing the process of deleting types, adding a default type, and setting parameters before each save for (int i = 1; i < rowsCount; i++) { Transaction t2 = new Transaction(newFamDoc, "MakeNewTypes"); t2.Start(); //Create a new type using the name of the type in the first column FamilyType newType = newFamMan.NewType(dgv.Rows[i].Cells[0].Value.ToString()); //Clean up the family file name by leaving everything that does not pass the regular expression in CleanFileName string saveName = GeneralOperations.CleanFileName(newType.Name); if (saveName != "") { //Assuming nothing went wrong modifying the family name... newFamMan.CurrentType = newType; //Cycle through the columns to set the parameter values this performs the same operations as those above for making 1 family with multiple types for (int j = 1; j < columnsCount; j++) { string paramName = dgv.Columns[j].HeaderText; string paramStorageTypeString = dgv.Rows[0].Cells[j].Value.ToString(); var paramValue = dgv.Rows[i].Cells[j].Value; if (paramValue.ToString() != "") { FamilyParameter param = famParamDict[paramName]; ParameterType paramType = param.Definition.ParameterType; RVTOperations.SetFamilyParameterValue(newFamMan, param, paramType, paramStorageTypeString, paramValue, true); } } t2.Commit(); //Again, do another transaction to delete the pre-existing type Transaction t3 = new Transaction(newFamDoc, "DeleteOldTypes"); t3.Start(); foreach (FamilyType type in newFamMan.Types) { newFamMan.CurrentType = type; if (newFamMan.CurrentType.Name != newType.Name) { newFamMan.DeleteCurrentType(); } } t3.Commit(); //Save out the family and continue the loop newFamDoc.SaveAs(saveDirectory + "\\" + saveName + ".rfa", saveAsOptions); uiForm.multiCatCFFEFamiliesProgressBar.PerformStep(); } } // The family document is finally closed after saving off itself for each row newFamDoc.Close(); } else { MessageBox.Show("No Creation Method was selected"); } //Delete the _temp file File.Delete(tempFamilyPath); //Clean up the backup files too List <string> backupFiles = GeneralOperations.GetAllRvtBackupFamilies(uiForm.multiCatCFFEFamilySaveLocation, false); GeneralOperations.CleanRfaBackups(backupFiles); } }
public WallsMPWRequest(UIApplication uiApp, String text) { MainUI uiForm = BARevitTools.Application.thisApp.newMainUi; RVTDocument doc = uiApp.ActiveUIDocument.Document; //Collect all the levels FilteredElementCollector levelsCollector = new FilteredElementCollector(doc); ICollection <Element> existingLevels = levelsCollector.OfCategory(BuiltInCategory.OST_Levels).WhereElementIsNotElementType().ToElements(); //Collect the wall types FilteredElementCollector wallTypesCollector = new FilteredElementCollector(doc); ICollection <Element> existingWallTypes = wallTypesCollector.OfCategory(BuiltInCategory.OST_Walls).WhereElementIsElementType().ToElements(); List <Line> wallLines = new List <Line>(); List <Wall> newWalls = new List <Wall>(); List <Element> selectedElements = new List <Element>(); //Get the wall type name from the MainUI combobox string selectedWallTypeName = uiForm.wallsMPWComboBoxWall.Text.ToString(); WallType wallTypeInput = null; double wallHeightInput = 0; //Ensure the active view is a plan view if (doc.ActiveView.GetType().ToString() != "Autodesk.Revit.DB.ViewPlan") { MessageBox.Show("Please run from a plan view"); } else { try { //Get the height of the walls to create from the MainUI, converted to a Double value in decimal feet wallHeightInput = (Convert.ToDouble(uiForm.wallsMPWNumericUpDownWallHeightFt.Value + (uiForm.wallsMPWNumericUpDownWallHeightIn.Value / 12))); } catch { //If the wall height input is invalid, let the user know throw new System.ArgumentException("Invalid wall height"); } double offsetDistance = 0; try { //To get the distance to offset the wall, get the wall type's thickness, then divide it in half because walls are placed along the centerline foreach (WallType wallType in existingWallTypes) { if (wallType.Name == selectedWallTypeName) { wallTypeInput = wallType; offsetDistance = (wallTypeInput.Width) / 2; break; } } } catch { new System.ArgumentException("No wall type was selected"); } //Get the active view and its associated level ViewPlan activeView = doc.ActiveView as ViewPlan; Level levelInput = activeView.GenLevel; //If the user selected a wall type, the level was obtained from the view, and the wall height is valid, continue if (wallTypeInput != null && levelInput != null && wallHeightInput != 0) { //Invoke selection of the rooms and get them from either the rooms or room tags selected List <Room> selectedRoomElements = RVTOperations.SelectRoomElements(uiApp); //Cycle through the room elements foreach (Room roomElem in selectedRoomElements) { try { //Get the location of the room as a point Location roomLocation = roomElem.Location; LocationPoint rlp = roomLocation as LocationPoint; //Get the room geometry Options geomOptions = new Options(); geomOptions.IncludeNonVisibleObjects = true; GeometryElement geomElements = roomElem.get_Geometry(geomOptions); foreach (GeometryObject geomObject in geomElements) { if (geomObject.GetType().ToString() == "Autodesk.Revit.DB.Solid") { //Grab the solid form of the room geometry Solid roomSolid = geomObject as Solid; FaceArray roomSolidFaces = roomSolid.Faces; foreach (PlanarFace roomSolidFace in roomSolidFaces) { //Get the bottom face of the room which is the face that has a -Z vector XYZ faceNormal = roomSolidFace.FaceNormal; if (faceNormal.Z == -1) { //Get the CurveLoops for the bottom face IList <CurveLoop> faceCurveLoops = roomSolidFace.GetEdgesAsCurveLoops(); foreach (CurveLoop curveLoop in faceCurveLoops) { //Offset the CurveLoop by the half thickness of the wall CurveLoop offsetCurveLoops = CurveLoop.CreateViaOffset(curveLoop, offsetDistance, XYZ.BasisZ); foreach (Line line in offsetCurveLoops) { //Collect the lines to draw walls along wallLines.Add(line); } } } } } } } catch { continue; } } //Start a transaction using (Transaction t1 = new Transaction(doc, "MakeWalls")) { t1.Start(); foreach (Line wallLine in wallLines) { //Draw a line along each of the lines and add them to a list of walls created Wall newWall = Wall.Create(doc, wallLine, wallTypeInput.Id, levelInput.Id, wallHeightInput, 0, true, false); newWalls.Add(newWall); } t1.Commit(); } //Start a new transaction to join the walls to adjacent walls using (Transaction t2 = new Transaction(doc, "JoinWalls")) { t2.Start(); foreach (Wall newWall in newWalls) { //Collect the walls in the project FilteredElementCollector existingWallsCollector = new FilteredElementCollector(doc, doc.ActiveView.Id); existingWallsCollector.OfCategory(BuiltInCategory.OST_Walls).WhereElementIsNotElementType().ToElements(); //Get the bounding box of each wall BoundingBoxXYZ wallBBox = newWall.get_BoundingBox(doc.ActiveView); //Get the outline of the bounding box using the minimum and maximum points Outline wallBBoxOutline = new Outline(wallBBox.Min, wallBBox.Max); //Generate a new BoundingBoxIntersectsFilter to find the other bounding boxes that intersect the outline BoundingBoxIntersectsFilter bBoxFilter = new BoundingBoxIntersectsFilter(wallBBoxOutline); //Get all walls that pass the filter (they intersect the evaluated new wall's outline) existingWallsCollector.WherePasses(bBoxFilter); foreach (Wall existingWall in existingWallsCollector) { try { //Try to joing the new wall to the existing walls so they are cut by the hosted elements JoinGeometryUtils.JoinGeometry(doc, newWall, existingWall); } catch { continue; } } } t2.Commit(); } } else if (levelInput == null) { //Let the user know if the level could not be obtained MessageBox.Show("No level set"); } else if (wallTypeInput == null) { //Let the user know if they didn't select a wall type MessageBox.Show("No wall type set"); } else if (wallHeightInput <= 0) { //Let the user know if they specified a 0 or negative wall height MessageBox.Show("Wall height must be set to greater than 0'"); } else { //If for some reason the script fails, report that one of the following settings could not be used. This is highly unlikely though MessageBox.Show(String.Format("One of the following settings could not be used: Wall Type = '{0}'; " + "Level = '{1}'; " + "Wall Height = '{2}'", ((Wall)doc.GetElement(wallTypeInput.Id)).WallType.Name.ToString(), ((Level)doc.GetElement(levelInput.Id)).Name.ToString(), (wallHeightInput / 12d).ToString())); } } }
public ViewsCEPRRequest(UIApplication uiApp, String text) { MainUI uiForm = BARevitTools.Application.thisApp.newMainUi; UIDocument uidoc = uiApp.ActiveUIDocument; //Collect the ViewTypes in the project FilteredElementCollector viewTypesCollector = new FilteredElementCollector(uidoc.Document); ICollection <Element> viewTypes = viewTypesCollector.OfClass(typeof(ViewFamilyType)).ToElements(); ElementId viewTypeId = null; //Cycle through the ViewType elements to find the one with a type name equal to the one selected in the MainUI's combobox foreach (ViewFamilyType viewType in viewTypes) { if (viewType.get_Parameter(BuiltInParameter.ALL_MODEL_TYPE_NAME).AsString() == uiForm.viewsCEPRElevationComboBox.Text) { viewTypeId = viewType.Id; } } //If the ViewType was found, and the active view is a plan view, continue if (viewTypeId != null && uidoc.ActiveView.GetType().ToString() == "Autodesk.Revit.DB.ViewPlan") { //Invoke a room selection List <Room> selectedRoomElements = RVTOperations.SelectRoomElements(uiApp); //If the user selected rooms, continue if (selectedRoomElements != null) { try { //Cycle through each selected room foreach (Room room in selectedRoomElements) { //First, get the room number for use in generating the elevation view names string roomNumber = room.Number; string roomName = room.get_Parameter(BuiltInParameter.ROOM_NAME).AsString().ToUpper(); //Get the geometry of the room Options geomOptions = new Options(); geomOptions.IncludeNonVisibleObjects = true; GeometryElement geomElements = room.get_Geometry(geomOptions); //Get the location point of the room as a point for where to place the elevation marker LocationPoint roomLocation = room.Location as LocationPoint; XYZ point = roomLocation.Point; //Start a transaction Transaction t1 = new Transaction(uidoc.Document, "Create Elevations Per Room"); t1.Start(); try { //Make a new ElevationMarker that uses the ViewType earlier, the location point of the room, and has a view scale of 1/8" ElevationMarker newMarker = ElevationMarker.CreateElevationMarker(uidoc.Document, viewTypeId, point, 96); //Start making views going around the elevation marker where the indexes start on the west side and go clockwise ViewSection view0 = newMarker.CreateElevation(uidoc.Document, uidoc.ActiveView.Id, 0); //Set the view name equal to the room number + room name + plus orientation view0.Name = roomNumber + " " + roomName + " WEST"; view0.CropBoxActive = true; //Repeat for the other view directions at their appropriate index ViewSection view1 = newMarker.CreateElevation(uidoc.Document, uidoc.ActiveView.Id, 1); view1.Name = roomNumber + " " + roomName + " NORTH"; view1.CropBoxActive = true; ViewSection view2 = newMarker.CreateElevation(uidoc.Document, uidoc.ActiveView.Id, 2); view2.Name = roomNumber + " " + roomName + " EAST"; view2.CropBoxActive = true; ViewSection view3 = newMarker.CreateElevation(uidoc.Document, uidoc.ActiveView.Id, 3); view3.Name = roomNumber + " " + roomName + " SOUTH"; view3.CropBoxActive = true; //Make a Solid object for assignment Solid roomSolid = null; //The following section is dedicated to cropping the elevation views to the cross-section of the room geometry if (uiForm.viewsCEPRCropCheckBox.Checked == true) { //Cycle through the geometry elements associated with the room geometry until the solid is found foreach (GeometryObject geom in geomElements) { if (geom.GetType().ToString() == "Autodesk.Revit.DB.Solid") { roomSolid = geom as Solid; break; } } //Generate 4 planes at the room point that will correspond to each elevation view's cross section of the room geometry // Each plane's normal vector is in the direction their view is facing Plane westPlane = Plane.CreateByNormalAndOrigin(new XYZ(-1, 0, 0), point); //-X vector for West Plane northPlane = Plane.CreateByNormalAndOrigin(new XYZ(0, 1, 0), point); //+Y vector for North Plane eastPlane = Plane.CreateByNormalAndOrigin(new XYZ(1, 0, 0), point); //+X vector for East Plane southPlane = Plane.CreateByNormalAndOrigin(new XYZ(0, -1, 0), point); //-Y vector for South //Use the room section's perimeter as the crop boundary if the first index of the MainUI combobox is selected if (uiForm.viewsCEPRCropMethodComboBox.SelectedIndex == 0) { try { //Generate some CurveLoop lists for use later IList <CurveLoop> westCurveLoopsFitted = null; IList <CurveLoop> northCurveLoopsFitted = null; IList <CurveLoop> southCurveLoopsFitted = null; IList <CurveLoop> eastCurveLoopsFitted = null; //Slice the room solid with the westPlane object made earlier. This will result in a solid boolean result to the west of the plane because the positive side of the plane faces west Solid westBooleanSolid = BooleanOperationsUtils.CutWithHalfSpace(roomSolid, westPlane); //Grab the faces of the solid that resulted from the boolean FaceArray westBoolSolidFaces = westBooleanSolid.Faces; //Cycle through each face and get the normal vector foreach (PlanarFace westFace in westBoolSolidFaces) { //For the west elevation face to use as the crop boundary, we need the face that has a vector going east, or the +X vector XYZ westFaceNormal = westFace.FaceNormal; if (westFaceNormal.X == 1) { //Get the edges as a CurveLoops once the face is found, then jump out of the loop thorugh the faces westCurveLoopsFitted = westFace.GetEdgesAsCurveLoops(); break; } } //Repeat for the north elevation Solid northBooleanSolid = BooleanOperationsUtils.CutWithHalfSpace(roomSolid, northPlane); FaceArray northBoolSolidFaces = northBooleanSolid.Faces; foreach (PlanarFace northFace in northBoolSolidFaces) { XYZ northFaceNormal = northFace.FaceNormal; if (northFaceNormal.Y == -1) { northCurveLoopsFitted = northFace.GetEdgesAsCurveLoops(); break; } } //Repeat for the east elevation Solid eastBooleanSolid = BooleanOperationsUtils.CutWithHalfSpace(roomSolid, eastPlane); FaceArray eastBoolSolidFaces = eastBooleanSolid.Faces; foreach (PlanarFace eastFace in eastBoolSolidFaces) { XYZ eastFaceNormal = eastFace.FaceNormal; if (eastFaceNormal.X == -1) { eastCurveLoopsFitted = eastFace.GetEdgesAsCurveLoops(); break; } } //Repeat for the south elevation Solid southBooleanSolid = BooleanOperationsUtils.CutWithHalfSpace(roomSolid, southPlane); FaceArray southBoolSolidFaces = southBooleanSolid.Faces; foreach (PlanarFace southFace in southBoolSolidFaces) { XYZ southFaceNormal = southFace.FaceNormal; if (southFaceNormal.Y == 1) { southCurveLoopsFitted = southFace.GetEdgesAsCurveLoops(); break; } } //To get the CurveLoop fitted 0.5" offset to the boundary of the face retrieved, create a CurveLoop via an offset //Now, the original curve loop was drawn on a plane with a +X axis vector normal, so the offset must be made in the positive X axis plane as well CurveLoop offsetWestCurveLoopFitted = CurveLoop.CreateViaOffset(westCurveLoopsFitted[0], (0.5d / 12), XYZ.BasisX); ViewCropRegionShapeManager westCropRegionShapeManager = view0.GetCropRegionShapeManager(); westCropRegionShapeManager.SetCropShape(offsetWestCurveLoopFitted); //Repeat for the north CurveLoop //Note that because the plane has a -Y vector, the offset needs to be negative too CurveLoop offsetNorthCurveLoopFitted = CurveLoop.CreateViaOffset(northCurveLoopsFitted[0], -(0.5d / 12), XYZ.BasisY);; ViewCropRegionShapeManager northCropRegionShapeManager = view1.GetCropRegionShapeManager(); northCropRegionShapeManager.SetCropShape(offsetNorthCurveLoopFitted); //Repeat for the east CurveLoop CurveLoop offsetEastCurveLoopFitted = CurveLoop.CreateViaOffset(eastCurveLoopsFitted[0], -(0.5d / 12), XYZ.BasisX);; ViewCropRegionShapeManager eastCropRegionShapeManager = view2.GetCropRegionShapeManager(); eastCropRegionShapeManager.SetCropShape(offsetEastCurveLoopFitted); //Repeat for the south CurveLoop CurveLoop offsetSouthCurveLoopFitted = CurveLoop.CreateViaOffset(southCurveLoopsFitted[0], (0.5d / 12), XYZ.BasisY);; ViewCropRegionShapeManager southCropRegionShapeManager = view3.GetCropRegionShapeManager(); southCropRegionShapeManager.SetCropShape(offsetSouthCurveLoopFitted); } catch (Exception e) { MessageBox.Show(e.ToString()); } } //Use the room section's rectangular extents as the crop boundary if the second index was selected for the MainUI combobox if (uiForm.viewsCEPRCropMethodComboBox.SelectedIndex == 1) { try { //Create some CurveLoop lists to use later IList <CurveLoop> westCurveLoopsRectangular = null; IList <CurveLoop> northCurveLoopsRectangular = null; IList <CurveLoop> southCurveLoopsRectangular = null; IList <CurveLoop> eastCurveLoopsRectangular = null; //To get a rectangular cross section of a non-rectangular room cross section, we need to generate a bounding box for the room, then make a solid from the bounding box //Get the bounding box of the room BoundingBoxXYZ roomBBox = roomSolid.GetBoundingBox(); //Use the minimum and maximum points of the bounding box to get the 4 points along the bottom of the bounding box XYZ pt0 = new XYZ(roomBBox.Min.X, roomBBox.Min.Y, roomBBox.Min.Z); XYZ pt1 = new XYZ(roomBBox.Max.X, roomBBox.Min.Y, roomBBox.Min.Z); XYZ pt2 = new XYZ(roomBBox.Max.X, roomBBox.Max.Y, roomBBox.Min.Z); XYZ pt3 = new XYZ(roomBBox.Min.X, roomBBox.Max.Y, roomBBox.Min.Z); //Generate perimeter lines for the bottom of the bounding box points Line edge0 = Line.CreateBound(pt0, pt1); Line edge1 = Line.CreateBound(pt1, pt2); Line edge2 = Line.CreateBound(pt2, pt3); Line edge3 = Line.CreateBound(pt3, pt0); //Make a list of curves out of the edges List <Curve> edges = new List <Curve>(); edges.Add(edge0); edges.Add(edge1); edges.Add(edge2); edges.Add(edge3); //Use the curves to make a CurveLoop list List <CurveLoop> loops = new List <CurveLoop>(); loops.Add(CurveLoop.Create(edges)); //Generate a solid from an extrusion that uses the CurveLoops extruded upward a height equal to the the height of the bounding box Solid initialSolidBBox = GeometryCreationUtilities.CreateExtrusionGeometry(loops, XYZ.BasisZ, (roomBBox.Max.Z - roomBBox.Min.Z)); //Create a transformed solid box from the previously created box moved to where the room bounding box is located Solid roomSolidBBox = SolidUtils.CreateTransformed(initialSolidBBox, roomBBox.Transform); //Cut the solid box with the west plane created earlier and get the faces Solid westBooleanSolidBBox = BooleanOperationsUtils.CutWithHalfSpace(roomSolidBBox, westPlane); FaceArray westBoolSolidFacesBBox = westBooleanSolidBBox.Faces; foreach (PlanarFace westFace in westBoolSolidFacesBBox) { //As with the earlier code for a fitted crop, get the face with a positive X normal XYZ westFaceNormal = westFace.FaceNormal; if (westFaceNormal.X == 1) { //Obtain the edges of the face westCurveLoopsRectangular = westFace.GetEdgesAsCurveLoops(); break; } } //Repeat for the north face Solid northBooleanSolidBBox = BooleanOperationsUtils.CutWithHalfSpace(roomSolidBBox, northPlane); FaceArray northBoolSolidFacesBBox = northBooleanSolidBBox.Faces; foreach (PlanarFace northFace in northBoolSolidFacesBBox) { XYZ northFaceNormal = northFace.FaceNormal; if (northFaceNormal.Y == -1) { northCurveLoopsRectangular = northFace.GetEdgesAsCurveLoops(); break; } } //Repeat for the east face Solid eastBooleanSolidBBox = BooleanOperationsUtils.CutWithHalfSpace(roomSolidBBox, eastPlane); FaceArray eastBoolSolidFacesBBox = eastBooleanSolidBBox.Faces; foreach (PlanarFace eastFace in eastBoolSolidFacesBBox) { XYZ eastFaceNormal = eastFace.FaceNormal; if (eastFaceNormal.X == -1) { eastCurveLoopsRectangular = eastFace.GetEdgesAsCurveLoops(); break; } } //Repeat for the south face Solid southBooleanSolidBBox = BooleanOperationsUtils.CutWithHalfSpace(roomSolidBBox, southPlane); FaceArray southBoolSolidFacesBBox = southBooleanSolidBBox.Faces; foreach (PlanarFace southFace in southBoolSolidFacesBBox) { XYZ southFaceNormal = southFace.FaceNormal; if (southFaceNormal.Y == 1) { southCurveLoopsRectangular = southFace.GetEdgesAsCurveLoops(); break; } } //As before, get the offset curve from the original curve, but offset by 1' CurveLoop offsetWestCurveLoopRectangular = CurveLoop.CreateViaOffset(westCurveLoopsRectangular[0], 1, XYZ.BasisX); ViewCropRegionShapeManager westCropRegionShapeManager = view0.GetCropRegionShapeManager(); westCropRegionShapeManager.SetCropShape(offsetWestCurveLoopRectangular); //As with the fitted offset curve, the offset for a curve in a plane with a negative vector must also be negative CurveLoop offsetNorthCurveLoopRectangular = CurveLoop.CreateViaOffset(northCurveLoopsRectangular[0], -1, XYZ.BasisY); ViewCropRegionShapeManager northCropRegionShapeManager = view1.GetCropRegionShapeManager(); northCropRegionShapeManager.SetCropShape(offsetNorthCurveLoopRectangular); CurveLoop offsetEastCurveLoopRectangular = CurveLoop.CreateViaOffset(eastCurveLoopsRectangular[0], -1, XYZ.BasisX); ViewCropRegionShapeManager eastCropRegionShapeManager = view2.GetCropRegionShapeManager(); eastCropRegionShapeManager.SetCropShape(offsetEastCurveLoopRectangular); CurveLoop offsetSouthCurveLoopRectangular = CurveLoop.CreateViaOffset(southCurveLoopsRectangular[0], 1, XYZ.BasisY); ViewCropRegionShapeManager southCropRegionShapeManager = view3.GetCropRegionShapeManager(); southCropRegionShapeManager.SetCropShape(offsetSouthCurveLoopRectangular); } catch (Exception e) { MessageBox.Show(e.ToString()); } } //If the user opted to override the crop boundary of the elevations, continue as follows if (uiForm.viewsCEPROverrideCheckBox.Checked == true) { //Make a new OverrideGraphicsSetting to use in the boundary override OverrideGraphicSettings orgs = new OverrideGraphicSettings(); //Use the solid line pattern orgs.SetProjectionLinePatternId(LinePatternElement.GetSolidPatternId()); //Set the line weight to the properties value orgs.SetProjectionLineWeight(Properties.Settings.Default.RevitOverrideInteriorCropWeight); //Grab all of the viewers, which are the viewport windows, and cycle through them var viewers = new FilteredElementCollector(uidoc.Document).OfCategory(BuiltInCategory.OST_Viewers); foreach (Element viewer in viewers) { //Get the parameters for the viewer ParameterSet parameters = viewer.Parameters; foreach (Parameter parameter in parameters) { //Get the View Name parameter if (parameter.Definition.Name.ToString() == "View Name") { string viewName = parameter.AsString(); //If the view's view name is the same as the west elvation, continue if (viewName == view0.Name) { //Set the view's override setting using the viewer and the OverrideGraphicsSettings Autodesk.Revit.DB.View viewtouse = view0 as Autodesk.Revit.DB.View; viewtouse.SetElementOverrides(viewer.Id, orgs); } //Continue to evaluate for the other view names else if (viewName == view1.Name) { Autodesk.Revit.DB.View viewtouse = view1 as Autodesk.Revit.DB.View; viewtouse.SetElementOverrides(viewer.Id, orgs); } else if (viewName == view2.Name) { Autodesk.Revit.DB.View viewtouse = view2 as Autodesk.Revit.DB.View; viewtouse.SetElementOverrides(viewer.Id, orgs); } else if (viewName == view3.Name) { Autodesk.Revit.DB.View viewtouse = view3 as Autodesk.Revit.DB.View; viewtouse.SetElementOverrides(viewer.Id, orgs); } else { //If the view's name is not one of the create elevation views, skip it continue; } } } } } } t1.Commit(); } catch (Exception e) { MessageBox.Show(e.ToString()); t1.RollBack(); } t1.Dispose(); } } catch { //If the user did not select any room tags or room elements, then report that MessageBox.Show("No rooms were selected"); } } } else if (uidoc.ActiveView.GetType().ToString() != "Autodesk.Revit.DB.ViewPlan") { //If the user tried to run this outside a plan view, report it MessageBox.Show("Please run from a plan view"); } else { //If the user did not select an elevation type, report it MessageBox.Show("No elevation type selected"); } }
public AdminFamiliesBAPRequest(UIApplication uiApp, String text) { MainUI uiForm = BARevitTools.Application.thisApp.newMainUi; uiForm.adminFamiliesBAPDoneLabel.Visible = false; RVTDocument doc = uiApp.ActiveUIDocument.Document; SaveAsOptions saveAsOptions = new SaveAsOptions(); saveAsOptions.Compact = true; saveAsOptions.MaximumBackups = 3; saveAsOptions.OverwriteExistingFile = true; Dictionary <string, ExternalDefinition> sharedParameterDefinitions = new Dictionary <string, ExternalDefinition>(); //Determine if the shared parameters file is accessible and try to get the shared parameters so their definition names and definitions could be added to a dictionary bool sharedParametersIsAccessible = true; try { DefinitionGroups sharedParameterGroups = uiApp.Application.OpenSharedParameterFile().Groups; foreach (DefinitionGroup group in sharedParameterGroups) { foreach (ExternalDefinition definition in group.Definitions) { if (!sharedParameterDefinitions.Keys.Contains(definition.Name)) { sharedParameterDefinitions.Add(definition.Name, definition); } } } } //If the access fails, then the shared parameters file was not accessible. catch { sharedParametersIsAccessible = false; } //Get the number of families to process from the DataGridView int filesToProcess = 0; foreach (DataGridViewRow rowCount in uiForm.adminFamiliesBAPFamiliesDGV.Rows) { if (rowCount.Cells["Family Select"].Value.ToString() == "True") { filesToProcess++; } } //Prepare the progress bar uiForm.adminFamiliesBAPProgressBar.Value = 0; uiForm.adminFamiliesBAPProgressBar.Minimum = 0; uiForm.adminFamiliesBAPProgressBar.Maximum = filesToProcess; uiForm.adminFamiliesBAPProgressBar.Step = 1; uiForm.adminFamiliesBAPProgressBar.Visible = true; //Stop any edits to the DataGridView of parameters to add uiForm.adminFamiliesBAPParametersDGV.EndEdit(); try { foreach (DataGridViewRow row in uiForm.adminFamiliesBAPFamiliesDGV.Rows) { try { //If the checkbox for including the family in the process is not null, continue if (row.Cells["Family Select"].Value != null) { //Grab the file path for the family string filePath = row.Cells["Family Path"].Value.ToString(); List <string> famParamNames = new List <string>(); //If the checkbox is checked to select the family if (row.Cells["Family Select"].Value.ToString() == "True") { //Open the family document RVTDocument famDoc = RVTOperations.OpenRevitFile(uiApp, filePath); if (famDoc.IsFamilyDocument) { //Grab the family manager and make a list of parameter names already in the family FamilyManager familyManager = famDoc.FamilyManager; foreach (FamilyParameter famParam in familyManager.Parameters) { if (!famParamNames.Contains(famParam.Definition.Name)) { famParamNames.Add(famParam.Definition.Name); } else { continue; } } foreach (DataGridViewRow newParamRow in uiForm.adminFamiliesBAPParametersDGV.Rows) { try { //Get the name of the parameter, group, and type of parameter to add string name = newParamRow.Cells["Parameter Name"].Value.ToString(); BuiltInParameterGroup group = RVTOperations.GetBuiltInParameterGroupFromString(newParamRow.Cells["Parameter Group"].Value.ToString()); ParameterType type = RVTOperations.GetParameterTypeFromString(newParamRow.Cells["Parameter Type"].Value.ToString()); //Determine if the checkbox for making the parameter an instance parameter is checked bool isInstance = false; try { isInstance = Convert.ToBoolean(newParamRow.Cells["Parameter Is Instance"].Value.ToString()); } catch { isInstance = false; } //Determine if the read-only checkbox for the parameter being a shared parameter is checked. bool isShared = false; try { isShared = Convert.ToBoolean(newParamRow.Cells["Parameter Is Shared"].Value.ToString()); } catch { isShared = false; } //If the parameter is shared, and the parameter file is still accessible, and the family does not already contain a parameter with that name, continue if (isShared == true && sharedParametersIsAccessible == true && !famParamNames.Contains(name)) { using (Transaction t = new Transaction(famDoc, "Add Parameter")) { t.Start(); //Get the parameter definition from the dictionary of shared parameters, then add it to the family ExternalDefinition definition = sharedParameterDefinitions[newParamRow.Cells["Parameter Name"].Value.ToString()]; FamilyParameter newParam = familyManager.AddParameter(definition, group, isInstance); try { //Try to assign the parameter value if one is to be assigned if (newParamRow.Cells["Parameter Value"].Value != null) { //If the number of types is greater than 0, cycle through them if (familyManager.Types.Size > 0) { foreach (FamilyType familyType in familyManager.Types) { //For each type, make a subtransaction SubTransaction s1 = new SubTransaction(famDoc); s1.Start(); try { //Then set the family type as current familyManager.CurrentType = familyType; //Attempt to set the parameter value RVTOperations.SetFamilyParameterValue(familyManager, newParam, RVTOperations.SetParameterValueFromString(newParamRow.Cells["Parameter Type"].Value.ToString(), newParamRow.Cells["Parameter Value"].Value)); s1.Commit(); } catch { //If that fails, let the user know and break out of the loop MessageBox.Show(String.Format("Could not assign value {0} to parameter {1} for type {2} in family {3}.", newParamRow.Cells["Parameter Value"], newParamRow.Cells["Parameter Name"], familyType.Name, row.Cells["Family Name"])); break; } } } else { //If there was was no family types in the family, just set it for the default one RVTOperations.SetFamilyParameterValue(familyManager, newParam, RVTOperations.SetParameterValueFromString(newParamRow.Cells["Parameter Type"].Value.ToString(), newParamRow.Cells["Parameter Value"].Value)); } } } catch { //If assignment fails, let the user know the parameter value, parameter name, and the family where the failure occured. MessageBox.Show(String.Format("Could not assign value {0} to parameter {1} for family {2}", newParamRow.Cells["Parameter Value"], newParamRow.Cells["Parameter Name"], row.Cells["Family Name"])); } t.Commit(); } } else if (isShared == true && sharedParametersIsAccessible == false && !famParamNames.Contains(name)) { //If the shared parameter file could not be accessed, let the user know MessageBox.Show(String.Format("Could not set the shared parameter {0} because the shared parameters file for this project could not be found. " + "Verify the shared parameters file is mapped correctly.", name)); } else if (isShared != true && !famParamNames.Contains(name)) { //Otherwise, just make a standard parameter using (Transaction t = new Transaction(famDoc, "Add Parameter")) { t.Start(); FamilyParameter newParam = familyManager.AddParameter(name, group, type, isInstance); try { if (newParamRow.Cells["Parameter Value"].Value != null) { RVTOperations.SetFamilyParameterValue(familyManager, newParam, RVTOperations.SetParameterValueFromString(newParamRow.Cells["Parameter Type"].Value.ToString(), newParamRow.Cells["Parameter Value"].Value)); } } catch { continue; } t.Commit(); } } else { //If all other conditions were not met, then the parameter already exists. MessageBox.Show(String.Format("Could not make parameter '{0}' for {1} because it already exists.", name, famDoc.Title)); } } catch { continue; } finally { //Save the family ModelPath modelPath = ModelPathUtils.ConvertUserVisiblePathToModelPath(filePath); famDoc.SaveAs(filePath, saveAsOptions); } } } //Close the family famDoc.Close(false); } else { continue; } //Step forward the progress bar uiForm.adminFamiliesBAPProgressBar.PerformStep(); } } catch { MessageBox.Show("The family could not be opened, likely due to being saved in a newer version of Revit"); } } } catch (Exception e) { MessageBox.Show(e.ToString()); } finally { //Clean up the backups when done GeneralOperations.CleanRfaBackups(uiForm.adminFamiliesBAPFamilyDirectory); } uiForm.adminFamiliesBAPProgressBar.Visible = false; uiForm.adminFamiliesBAPDoneLabel.Visible = true; uiForm.Update(); }
public QaqcRFSPRequest(UIApplication uiApp, String text) { MainUI uiForm = BARevitTools.Application.thisApp.newMainUi; List <string> familyFiles = uiForm.qaqcRFSPFamilyFiles; foreach (string familyFile in familyFiles) { //Open the family file and get its Family Manager. Then, get the list of family parameters RVTDocument familyDoc = uiApp.Application.OpenDocumentFile(familyFile); FamilyManager famMan = familyDoc.FamilyManager; IList <FamilyParameter> famParams = famMan.GetParameters(); string famName = familyDoc.Title.Replace(".rfa", ""); //Start a transaction using (Transaction t1 = new Transaction(familyDoc, "ChangeSharedParameters")) { t1.Start(); try { //Cycle through the family parameters foreach (FamilyParameter param in famParams) { string paramName = param.Definition.Name; try { //If the parameter is shared, and the name does not contain BA or BAS, continue if (param.IsShared && !paramName.ToUpper().Contains("BA ") && !paramName.ToUpper().Contains("BAS ")) { //A temporary parameter needs to be made in the place of the one to be removed, so get the group of the parameter to be replaced BuiltInParameterGroup paramGroup = param.Definition.ParameterGroup; string paramTempName = "tempName"; //Determine if the parameter to replaced is an instance parameter bool paramInstance = param.IsInstance; //Make replace the parameter with the temporary one, giving it the same group and instance settings FamilyParameter newParam = famMan.ReplaceParameter(param, paramTempName, paramGroup, paramInstance); //Then, rename the new parameter famMan.RenameParameter(newParam, paramName); //Add to the ListBox the outcome of the shared parameter replacement uiForm.qaqcRFSPParametersListBox.Items.Add(famName + " : " + paramName + ": SUCCESS"); } } catch { //If the replacement fails, report that too uiForm.qaqcRFSPParametersListBox.Items.Add(famName + " : " + paramName + ": FAILED"); } } t1.Commit(); //Update the MainUI uiForm.qaqcRFSPParametersListBox.Update(); uiForm.qaqcRFSPParametersListBox.Refresh(); } catch { t1.RollBack(); } } //Save the family and remove the backups RVTOperations.SaveRevitFile(uiApp, familyDoc, true); GeneralOperations.CleanRfaBackups(Path.GetDirectoryName(familyFile)); } }
public AdminDataGBDVRequest(UIApplication uiApp, String text) { MainUI uiForm = BARevitTools.Application.thisApp.newMainUi; DataTable dt = new DataTable(); uiForm.adminDataGBDVWaitLabel.Text = "Please Wait..."; uiForm.adminDataGBDVWaitLabel.Visible = true; //Begin by getting the Revit version of the BA Details file in the BART properties. This should be lowest supported BART version string detailVersion = RVTOperations.GetRevitNumber(BARevitTools.Properties.Settings.Default.RevitProjectBADetails).ToString(); //Get the last two digits for the year of the BA Details Revit version string detailSubVersion = detailVersion.Substring(detailVersion.Length - 2); //Get the version of Revit running and then get the last two digits string activeSubVersion = uiApp.Application.VersionNumber.Substring(uiApp.Application.VersionNumber.Length - 2); //Get the appropriate BA Details file by version number. This only works if the files are named with the A## suffix string detailsFile = BARevitTools.Properties.Settings.Default.RevitProjectBADetails.Replace(detailSubVersion, activeSubVersion); //Create a new DataTable to collect data. dt = new DataTable(); DataColumn categoryColumn = dt.Columns.Add("Category", typeof(String)); //View type DataColumn divisionSortColumn = dt.Columns.Add("Division", typeof(String)); //BA View Sort 1 Division DataColumn typeSortColumn = dt.Columns.Add("Type", typeof(String)); //BA View Sort 2 Type DataColumn nameColumn = dt.Columns.Add("Name", typeof(String)); //View name //Try to open the details file saved in the running version of Revit. RVTDocument detailsDoc = null; try { //Open the BA Details file detailsDoc = RVTOperations.OpenRevitFile(uiApp, detailsFile); } catch { //Assuming the file could not be opened because it does not exist at the expected location, prompt the user to select it. MessageBox.Show(String.Format("Could not load the {0} file. Please select the BA Details file to use in the following dialog.", detailsFile)); try { //Generate the file selection dialog string filePath = GeneralOperations.GetFile(); detailsDoc = RVTOperations.OpenRevitFile(uiApp, filePath); } catch {; } } //Assuming the BA Details was opened, continue if (detailsDoc != null) { List <ViewDrafting> viewsCollection = new FilteredElementCollector(detailsDoc).OfClass(typeof(ViewDrafting)).WhereElementIsNotElementType().Cast <ViewDrafting>().ToList(); List <ViewSheet> sheetsCollection = new FilteredElementCollector(detailsDoc).OfClass(typeof(ViewSheet)).WhereElementIsNotElementType().Cast <ViewSheet>().ToList(); //Order the views by division, type, and name var viewsGroupedQuery = from viewElem in viewsCollection orderby viewElem.GetParameters("BA View Sort 1 Division").First().ToString(), viewElem.GetParameters("BA View Sort 2 Type").First().ToString(), viewElem.Name select viewElem; //Fill out the DataTable foreach (ViewDrafting viewDrafting in viewsGroupedQuery) { DataRow row = dt.NewRow(); row["Category"] = "View"; row["Division"] = viewDrafting.GetParameters("BA View Sort 1 Division").First().AsString(); row["Type"] = viewDrafting.GetParameters("BA View Sort 2 Type").First().AsString(); row["Name"] = viewDrafting.Name; dt.Rows.Add(row); } //Order the sheets by discipline, division, and name var sheetsGroupedQuery = from sheetElem in sheetsCollection orderby sheetElem.GetParameters("BA Sheet Discipline").First().AsString(), sheetElem.GetParameters("BA Sheet Division").First().AsString(), sheetElem.Name select sheetElem; //Add the sheets to the DataTable foreach (ViewSheet viewSheet in sheetsGroupedQuery) { DataRow row = dt.NewRow(); row["Category"] = "Sheet"; row["Division"] = viewSheet.GetParameters("BA Sheet Discipline").First().AsString(); row["Type"] = viewSheet.GetParameters("BA Sheet Division").First().AsString(); row["Name"] = viewSheet.Name; dt.Rows.Add(row); } uiForm.adminDataGBDVWaitLabel.Text = "Done!"; detailsDoc.Close(false); uiForm.adminDataGBDVDataTable = dt; } }
private void SetParameters(UIApplication uiApp, string familyFile, ExternalDefinition externalDefinition) { try { //Get the FileInfo of the family file and then get the LastWriteTime value as a date string in MM/DD/YYYY format FileInfo fileInfo = new FileInfo(familyFile); string lastModified = fileInfo.LastWriteTime.ToShortDateString(); //Open the family file RVTDocument famDoc = RVTOperations.OpenRevitFile(uiApp, familyFile); if (famDoc != null) { //Get the family manager for the family file FamilyManager famMan = famDoc.FamilyManager; //Get the family parameters and add them to a dictionary indexed by parameter name FamilyParameter famParameter = null; Dictionary <string, FamilyParameter> famParamDict = new Dictionary <string, FamilyParameter>(); foreach (FamilyParameter famParam in famMan.Parameters) { famParamDict.Add(famParam.Definition.Name, famParam); } //Get the number of family types because there must be at least one family type to make this work FamilyTypeSet types = famMan.Types; int numberOfTypes = types.Size; Transaction t1 = new Transaction(famDoc, "SetParameters"); t1.Start(); if (numberOfTypes == 0) { //If the number of family types was 0, then one must be made. Thus Default is a family type created try { famMan.NewType("Default"); } catch { MessageBox.Show(String.Format("Could not make a default type or find any type for {0}", familyFile)); } } //Once the existence of a family type is confirmed, move on with determining if the version parameter already exists. If it doesn't add the parameter to the family and regenerate the document if (!famParamDict.Keys.Contains(BARevitTools.Properties.Settings.Default.RevitUFVPParameter)) { famParameter = famMan.AddParameter(externalDefinition, BuiltInParameterGroup.PG_IDENTITY_DATA, false); famDoc.Regenerate(); } else { famParameter = famParamDict[BARevitTools.Properties.Settings.Default.RevitUFVPParameter]; } //Check to see if the value for the parameter is equal to the date last modified if (famMan.CurrentType.AsString(famParameter) == lastModified) { //If so, roll back the transaction and just close the file. t1.RollBack(); famDoc.Close(false); } else { //Otherwise set the formula of the version parameter to the quote encapsulated date, just like it would appear in Revit, commit it, then save. famMan.SetFormula(famParameter, "\"" + lastModified + "\""); t1.Commit(); RVTOperations.SaveRevitFile(uiApp, famDoc, true); } } else { //If the family could not be opened for any reason, let the user know MessageBox.Show(String.Format("{0} could not be opened.", familyFile)); } } catch (Exception e) { MessageBox.Show(e.ToString()); } }
public AllCatCFFE1Request(UIApplication uiApp, String text) { MainUI uiForm = BARevitTools.Application.thisApp.newMainUi; RVTDocument doc = uiApp.ActiveUIDocument.Document; DataTable dt = new DataTable(); DataGridView dgv = uiForm.multiCatCFFEExcelDGV; RVTDocument famDoc = RVTOperations.OpenRevitFile(uiApp, Application.thisApp.newMainUi.multiCatSelectedFamilyFile); FamilyManager famMan = famDoc.FamilyManager; FamilyParameterSet famParamSet = famMan.Parameters; //The following columns are being added to the DataTable for use in the Excel template creation DataColumn paramSelectColumn = dt.Columns.Add("Parameter Select", typeof(Boolean)); DataColumn parameterNameColumn = dt.Columns.Add("Parameter Name", typeof(String)); DataColumn parameterGroupColumn = dt.Columns.Add("Parameter Group", typeof(String)); DataColumn parameterTypeColumn = dt.Columns.Add("Parameter Type", typeof(String)); DataColumn parameterStorageTypeColumn = dt.Columns.Add("Parameter Storage Type", typeof(String)); //For each family parameter, get data associated with it for the DataTable foreach (FamilyParameter famParam in famParamSet) { string paramName = famParam.Definition.Name; string paramGroup = RVTOperations.GetNameFromBuiltInParameterGroup(famParam.Definition.ParameterGroup); string paramType = famParam.Definition.ParameterType.ToString(); string paramStorageType = famParam.StorageType.ToString(); //Verify the parameter being evaluated is not one where the value is an element because that will not be useful without knowing the element ID ahead of time. Also, ensure the parameter is not locked by a formula, and ensure the ParameterType is valid if (paramStorageType.ToString() != "ElementId" && famParam.IsDeterminedByFormula == false && famParam.Definition.ParameterType != ParameterType.Invalid) { //Pending the pass of the checks, fill out the DataTable with the parameter name, group, type, and data type DataRow row = dt.NewRow(); row["Parameter Select"] = false; row["Parameter Name"] = paramName; row["Parameter Group"] = paramGroup; row["Parameter Type"] = paramType; row["Parameter Storage Type"] = paramStorageType; dt.Rows.Add(row); } } //Bind the DataTable to the DataGridView BindingSource bs = new BindingSource(); bs.DataSource = dt; dgv.DataSource = bs; //Format the DataGridView and set the names for its columns so the row values can be retrieved by column name dgv.RowHeadersVisible = false; dgv.SelectionMode = DataGridViewSelectionMode.FullRowSelect; dgv.Columns["Parameter Select"].Width = 45; dgv.Columns["Parameter Select"].HeaderText = "Select"; dgv.Columns["Parameter Select"].Name = "Parameter Select"; dgv.Columns["Parameter Name"].Width = 125; dgv.Columns["Parameter Name"].ReadOnly = true; dgv.Columns["Parameter Name"].HeaderText = "Name"; dgv.Columns["Parameter Name"].Name = "Parameter Name"; dgv.Columns["Parameter Group"].Width = 75; dgv.Columns["Parameter Group"].ReadOnly = true; dgv.Columns["Parameter Group"].HeaderText = "Group"; dgv.Columns["Parameter Group"].Name = "Parameter Group"; dgv.Columns["Parameter Type"].Width = 100; dgv.Columns["Parameter Type"].ReadOnly = true; dgv.Columns["Parameter Type"].HeaderText = "Param Type"; dgv.Columns["Parameter Type"].Name = "Parameter Type"; dgv.Columns["Parameter Storage Type"].Width = 100; dgv.Columns["Parameter Storage Type"].ReadOnly = true; dgv.Columns["Parameter Storage Type"].HeaderText = "Data Format"; dgv.Columns["Parameter Storage Type"].Name = "Parameter Storage Type"; //Sort by the Parameter Name column dgv.Sort(dgv.Columns["Parameter Name"], ListSortDirection.Ascending); foreach (DataGridViewColumn column in dgv.Columns) { column.SortMode = DataGridViewColumnSortMode.NotSortable; } //Close the family famDoc.Close(false); }
public RoomsCDRTRequest(UIApplication uiApp, String text) { RVTDocument doc = uiApp.ActiveUIDocument.Document; Autodesk.Revit.DB.View activeView = doc.ActiveView; //Verify the active view is a floor plan view if (activeView.ViewType != ViewType.FloorPlan) { MessageBox.Show("Please run from a demo floor plan view."); } else { //Get the current phase of the active view Phase currentPhase = doc.GetElement(activeView.get_Parameter(BuiltInParameter.VIEW_PHASE).AsElementId()) as Phase; ElementId currentPhaseId = currentPhase.Id; ElementId previousPhaseId = null; //Collect the phases of the document PhaseArray phaseArray = doc.Phases; //Cycle through the phases in the project to get the previous phase for (int i = 0; i < phaseArray.Size; i++) { //By finding the index of the current phase, which must not be the first phase, the phase in the previous index can be obtained if (phaseArray.get_Item(i).ToString() == currentPhase.ToString() && i != 0) { previousPhaseId = phaseArray.get_Item(i - 1).Id; } i++; } //Collect the rooms in the current view where their phase is equal to the active view's phase List <Room> currentVisibleRooms = new FilteredElementCollector(doc, activeView.Id).OfCategory(BuiltInCategory.OST_Rooms).WhereElementIsNotElementType().ToElements().Cast <Room>().Where(r => r.get_Parameter(BuiltInParameter.ROOM_PHASE).AsElementId() == currentPhaseId).ToList(); List <string> currentVisibleRoomNumbers = new List <string>(); //Get the list of currently visible rooms' numbers foreach (Room room in currentVisibleRooms) { currentVisibleRoomNumbers.Add(room.Number); } //Only continue if the previous phase was found if (previousPhaseId != null) { List <Room> previousRoomsToTag = new List <Room>(); Outline outline = null; try { //This portion will require a new outline from the view's bounding box BoundingBoxXYZ viewBBox = activeView.get_BoundingBox(activeView); //Get the active view as a plan view so the view range can be obtained for the height of the outline ViewPlan viewPlan = activeView as ViewPlan; PlanViewRange planViewRange = viewPlan.GetViewRange(); double minX = viewBBox.Min.X; double minY = viewBBox.Min.Y; //The bottom Z point of the outline will be the elevation of the view's level plus the bottom offset double minZ = activeView.GenLevel.Elevation + planViewRange.GetOffset(PlanViewPlane.BottomClipPlane); double maxX = viewBBox.Max.X; double maxY = viewBBox.Max.Y; //The top Z point of the outline will be the elevation of the view's level plust the top offset double maxZ = activeView.GenLevel.Elevation + planViewRange.GetOffset(PlanViewPlane.TopClipPlane); //Generate the minimum and maximum points XYZ minPoint = new XYZ(minX, minY, minZ); XYZ maxPoint = new XYZ(maxX, maxY, maxZ); //Make a new outline from the points outline = new Outline(minPoint, maxPoint); //Establish a new bounding box filter using the outline BoundingBoxIntersectsFilter bboxFilter = new BoundingBoxIntersectsFilter(outline); //The previous rooms will be those that pass the bounding box intersects filter (their bounding boxes intersect the view bounding box) and they belong to the previous phase var previousNonVisibleRooms = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Rooms).WhereElementIsNotElementType().WherePasses(bboxFilter).ToElements().Where(r => r.get_Parameter(BuiltInParameter.ROOM_PHASE).AsElementId() == previousPhaseId); foreach (Element elem in previousNonVisibleRooms) { //Get the rooms and their numbers Room room = elem as Room; string roomNumber = room.Number; //Verify the room number is not in the current view's list of visible room numbers if (!currentVisibleRoomNumbers.Contains(roomNumber)) { previousRoomsToTag.Add(room); } } } catch (Exception e) { //If something went wrong in getting the demoed rooms, report an error MessageBox.Show(e.ToString(), "Getting Demo Rooms Error"); } //Start a transaction to make the new tags Transaction t = new Transaction(doc, "Create Demo Room Tags"); t.Start(); FamilySymbol symbol = null; //Create a new instance of the load options IFamilyLoadOptions loadOptions = new RVTFamilyLoadOptions(); try { //Get the versioned symbol family to use as a "tag" string roomTagSymbolPath = RVTOperations.GetVersionedFamilyFilePath(uiApp, Properties.Settings.Default.RevitRoomTagSymbol); try { //Load only the particular type of tag doc.LoadFamilySymbol(roomTagSymbolPath, Properties.Settings.Default.RevitRoomTagSymbolType, loadOptions, out FamilySymbol symb); symbol = symb; } catch { //If it could not be loaded, let the user know it needs added to the family for the script to work MessageBox.Show(String.Format("The family type {0} could not be found in {1}. Please add it for this tool to work.", Properties.Settings.Default.RevitRoomTagSymbolType, Properties.Settings.Default.RevitRoomTagSymbol)); } } catch { //If the family itself could not be loaded, let the user know where the family was expected to be found. MessageBox.Show(String.Format("The {0} family could not be found at {1}. Please place the {0} family in the {1} folder for this tool to work.", Path.GetFileNameWithoutExtension(Properties.Settings.Default.RevitRoomTagSymbol), Path.GetDirectoryName(Properties.Settings.Default.RevitRoomTagSymbol))); } try { //Verify there are rooms to tag and the family symbol to use is not null if (previousRoomsToTag.Count > 0 && symbol != null) { //Cycle through the demoed rooms foreach (Room demoRoom in previousRoomsToTag) { //Get the location point of the demo room as a point LocationPoint roomLocationPoint = demoRoom.Location as LocationPoint; //Make a new symbol at the locatoin FamilyInstance newSymbol = doc.Create.NewFamilyInstance(roomLocationPoint.Point, symbol, activeView); //Update the parameter values for room Name and Number in the symbol newSymbol.GetParameters("Name").First().Set(demoRoom.get_Parameter(BuiltInParameter.ROOM_NAME).AsString()); newSymbol.GetParameters("Number").First().Set(demoRoom.get_Parameter(BuiltInParameter.ROOM_NUMBER).AsString()); } } t.Commit(); } catch (Exception f) { //Well, crap, the symbol didn't place in the view MessageBox.Show(f.ToString(), "Placement Error"); t.RollBack(); } } else { //If the previous phase was null, then the current phase of the view is the first phase, so let the user know MessageBox.Show("The currently viewed phase is the earliest phase in the project. Please verify you are viewing a new construction phase, but showing previous and demoed elements."); } } }
public AdminFamiliesUFRequest(UIApplication uiApp, String text) { try { MainUI uiForm = BARevitTools.Application.thisApp.newMainUi; RVTDocument doc = uiApp.ActiveUIDocument.Document; bool fullSync = uiForm.adminFamiliesUFFullSyncCheckbox.Checked; string currentVersion = Properties.Settings.Default.BARTRevitFamilyCurrentYear; string upgradedVersion = uiApp.Application.VersionNumber; //The current library path is needed to make the new library path by swapping the year of the current development library with the year of the Revit version running. string currentLibraryPath = Properties.Settings.Default.RevitBAFamilyLibraryPath; string upgradedLibraryPath = currentLibraryPath.Replace(currentVersion, upgradedVersion); //If the new library does not yet exist, make it. This will likely be used only once when a new version of Revit is released. if (!Directory.Exists(upgradedLibraryPath)) { Directory.CreateDirectory(upgradedLibraryPath); } //Do some cleanup in the current library and the new library if backups exist GeneralOperations.CleanRfaBackups(currentLibraryPath); GeneralOperations.CleanRfaBackups(upgradedLibraryPath); //Create a list of family paths in the current library, and a list of family paths in the new library. List <string> familiesInCurrentLibrary = GeneralOperations.GetAllRvtFamilies(currentLibraryPath, false); //Also, make a dictionary because while the family paths will be evaluated, the paths themselves will need to be retrieved later by family name. Dictionary <string, string> currentLibraryDict = new Dictionary <string, string>(); List <string> familiesInUpgradedLibrary = GeneralOperations.GetAllRvtFamilies(upgradedLibraryPath, false); Dictionary <string, string> upgradedLibraryDict = new Dictionary <string, string>(); List <string> familiesToUpgrade = new List <string>(); List <string> familiesToDelete = new List <string>(); List <string> upgradedFamilies = new List <string>(); List <string> deletedFamilies = new List <string>(); //Just a variable for storing which family name is currently being evaluated string currentEvaluation = ""; //If there are families in the new library... if (familiesInUpgradedLibrary.Count > 0) { foreach (string upgradedFamilyPath in familiesInUpgradedLibrary) { try { //Get the name of the family and add it as a key in the dictionary, along with the family path currentEvaluation = Path.GetFileNameWithoutExtension(upgradedFamilyPath); upgradedLibraryDict.Add(Path.GetFileNameWithoutExtension(upgradedFamilyPath), upgradedFamilyPath); } catch { continue; } } } //Next, evaluate what families are in the current library foreach (string currentFamilyPath in familiesInCurrentLibrary) { //Skip any path that contains "Archive" or "Backup" if (!currentFamilyPath.Contains("Archive") && !currentFamilyPath.Contains("Backup")) { try { //Add the name off the family to dictionary as a key assigned the path currentEvaluation = Path.GetFileNameWithoutExtension(currentFamilyPath); currentLibraryDict.Add(Path.GetFileNameWithoutExtension(currentFamilyPath), currentFamilyPath); } catch { continue; } } } //Going back to the families in the new library if (familiesInUpgradedLibrary.Count > 0) { //Evaluate each family name serving as a key in the dictionary for the new library foreach (string upgradedFamily in upgradedLibraryDict.Keys) { //If the current library dictionary has a key with the same family name... if (currentLibraryDict.Keys.Contains(upgradedFamily)) { //Compare the dates when the families were last modified to determine if the one in the new library is older than the one in the current library DateTime currentFamilyWriteTime = File.GetLastWriteTime(currentLibraryDict[upgradedFamily]); DateTime upgradedFamilyWriteTime = File.GetLastWriteTime(upgradedLibraryDict[upgradedFamily]); //If the familly in the current library is more recently modified, add it to the list of families that will need upgraded and saved to the new library, thus replacing the one in the new library with the updated one if (currentFamilyWriteTime > upgradedFamilyWriteTime) { familiesToUpgrade.Add(currentLibraryDict[upgradedFamily]); } } else { //Otherwise, if the family in the new library does not exist in the current library, add it to a list of families to delete if a full sync is performed familiesToDelete.Add(upgradedLibraryDict[upgradedFamily]); } } //If the new library does not contain the family in the current library, add it to the list of families to upgrade and save to the new library. foreach (string originalFamily in currentLibraryDict.Keys) { if (!upgradedLibraryDict.Keys.Contains(originalFamily)) { familiesToUpgrade.Add(currentLibraryDict[originalFamily]); } } } else { //If there are no families in the new library, such as one that was just created for a new version of Revit, then all families from the current library will need upgraded and saved in the new library familiesToUpgrade = familiesInCurrentLibrary; } //Cycle through all of the families that will need to be upgraded and saved to the new library foreach (string familyToUpgrade in familiesToUpgrade) { try { //First, determine if the family can be opened and is not a newer version of Revit if (RVTOperations.RevitVersionUpgradeCheck(uiApp, familyToUpgrade, true)) { //If it can be opened, upgrade it and add its name to the list of families that were upgraded bool result = RVTOperations.UpgradeRevitFile(uiApp, familyToUpgrade, familyToUpgrade.Replace(currentVersion, upgradedVersion), true); if (result == true) { upgradedFamilies.Add(Path.GetFileNameWithoutExtension(familyToUpgrade)); } } else { //If the family could not be opened because it was saved in a newer version of Revit, let the user know and skip over the family MessageBox.Show(String.Format("{0} was saved in a new version of Revit", Path.GetFileNameWithoutExtension(familyToUpgrade))); } } catch (Exception f) { MessageBox.Show(f.ToString()); } } //If the user checked the box to do a full sync, delete the families that were added to the list of families to delete. This will ensure the new library and current library match regarding what families they contain if (fullSync) { foreach (string familyToDelete in familiesToDelete) { try { File.Delete(familyToDelete); deletedFamilies.Add(Path.GetFileNameWithoutExtension(familyToDelete)); } catch (Exception e) { MessageBox.Show(e.ToString()); } } } //Update the listboxes of the UI showing what families were upgraded and what were deleted uiForm.adminFamiliesUFUpgradedFamiliesListBox.DataSource = upgradedFamilies; uiForm.adminFamiliesUFDeletedFamiliesListBox.DataSource = deletedFamilies; //Cleanup the family backups in the new library if they exist GeneralOperations.CleanRfaBackups(upgradedLibraryPath); } catch (Exception g) { MessageBox.Show(g.ToString()); } }
public AdminDataGFFRequest(UIApplication uiApp, String text) { //Items pertaining to the open UI MainUI uiForm = BARevitTools.Application.thisApp.newMainUi; List <string> itemsToCollect = uiForm.adminDataGFFItemsToCollect; //UI settings related to the proggress bar int filesToProcess = uiForm.adminDataGFFFiles.Count; uiForm.adminDataGFFDataProgressBar.Value = 0; uiForm.adminDataGFFDataProgressBar.Minimum = 0; uiForm.adminDataGFFDataProgressBar.Maximum = filesToProcess; uiForm.adminDataGFFDataProgressBar.Step = 1; uiForm.adminDataGFFDataProgressBar.Visible = true; //New objects DataTable dt = new DataTable(); int selectionGroup = -2; //Getting the items from the list obtained from checked listbox items to determine what datatable columns are needed //The items below are able to be obtained without API calls. Statementselect remains -1 to indicate no API request will be needed, saving time. if (itemsToCollect.Contains("Family Name")) { DataColumn familyNameColumn = dt.Columns.Add("FamilyName", typeof(String)); selectionGroup = -1; } if (itemsToCollect.Contains("Family Size")) { DataColumn familySizeColumn = dt.Columns.Add("FamilySize", typeof(Double)); selectionGroup = -1; } if (itemsToCollect.Contains("Date Last Modified")) { DataColumn dateLastModifiedColumn = dt.Columns.Add("DateLastModified", typeof(String)); selectionGroup = -1; } //Here is where items must be obtained via API calls. Statementselect changes from -1 to 0 to later indicate that API usage will be needed. if (itemsToCollect.Contains("Revit Version")) { DataColumn revitVersionColumn = dt.Columns.Add("RevitVersion", typeof(String)); selectionGroup = 0; } if (itemsToCollect.Contains("Family Category")) { DataColumn familyCategoryColumn = dt.Columns.Add("FamilyCategory", typeof(String)); selectionGroup = 0; } //From here, the IF statments indicate the files will need to be opened and API calls will be used, resulting in a slow data collection. Statementselect becomes 1 if (itemsToCollect.Contains("Family Types")) { DataColumn familyTypeColumn = dt.Columns.Add("FamilyType", typeof(String)); selectionGroup = 1; } if (itemsToCollect.Contains("Parameter Name")) { DataColumn parameterNameColumn = dt.Columns.Add("ParameterName", typeof(String)); selectionGroup = 1; } if (itemsToCollect.Contains("Parameter Group")) { DataColumn parameterGroupColumn = dt.Columns.Add("ParameterGroup", typeof(String)); selectionGroup = 1; } if (itemsToCollect.Contains("Parameter Type")) { DataColumn parameterTypeColumn = dt.Columns.Add("ParameterType", typeof(String)); selectionGroup = 1; } if (itemsToCollect.Contains("Parameter Value")) { //If the parameter value is to be collected, it could be either an integer, double, or string, so create all three columns anyways DataColumn parameterValueIntegerColumn = dt.Columns.Add("ParameterValueInteger", typeof(Int32)); parameterValueIntegerColumn.AllowDBNull = true; DataColumn parameterValueDoubleColumn = dt.Columns.Add("ParameterValueDouble", typeof(Double)); parameterValueDoubleColumn.AllowDBNull = true; DataColumn parameterValueStringColumn = dt.Columns.Add("ParameterValueString", typeof(String)); parameterValueStringColumn.AllowDBNull = true; selectionGroup = 1; } if (itemsToCollect.Contains("Parameter Is Instance")) { DataColumn parameterIsInstanceColumn = dt.Columns.Add("ParameterIsInstance", typeof(Boolean)); selectionGroup = 1; } if (itemsToCollect.Contains("Parameter Is Shared")) { DataColumn parameterIsSharedColumn = dt.Columns.Add("ParameterIsShared", typeof(Boolean)); selectionGroup = 1; } if (itemsToCollect.Contains("Parameter GUID")) { DataColumn parameterGUIDColumn = dt.Columns.Add("ParameterGUID", typeof(String)); selectionGroup = 1; } //Cycle through the file paths obtained from the open UI foreach (string filePath in uiForm.adminDataGFFFiles) { //Increment the progress bar of the open UI uiForm.adminDataGFFDataProgressBar.PerformStep(); // If selectionGroup is -1, no use of the API will be used if (selectionGroup == -1) { DataRow row = dt.NewRow(); if (dt.Columns.Contains("FamilyName")) { row["FamilyName"] = GeneralOperations.GetFileName(filePath); } if (dt.Columns.Contains("FamilySize")) { row["FamilySize"] = GeneralOperations.GetFileSize(filePath); } if (dt.Columns.Contains("DateLastModified")) { row["DateLastModified"] = GeneralOperations.GetFileLastModifiedDate(filePath); } dt.Rows.Add(row); } //If selectionGroup is 0, then the API will be used, resulting in slower processing else if (selectionGroup == 0) { //Get the Revit version year of the file int rvtNumber = RVTOperations.GetRevitNumber(filePath); //Check to see if the GetRevitNumber did not return 0 (could not be determined), and that the saved in version is not newer that the one running. if (rvtNumber != 0 && Convert.ToInt32(uiApp.Application.VersionNumber) >= rvtNumber) { DataRow row = dt.NewRow(); if (dt.Columns.Contains("FamilyName")) { row["FamilyName"] = GeneralOperations.GetFileName(filePath); } if (dt.Columns.Contains("FamilySize")) { row["FamilySize"] = GeneralOperations.GetFileSize(filePath); } if (dt.Columns.Contains("DateLastModified")) { row["DateLastModified"] = GeneralOperations.GetFileLastModifiedDate(filePath); } if (dt.Columns.Contains("RevitVersion")) { row["RevitVersion"] = RVTOperations.GetRevitVersion(filePath); } RVTDocument doc = RVTOperations.OpenRevitFile(uiApp, filePath); if (dt.Columns.Contains("FamilyCategory") && doc.IsFamilyDocument) { row["FamilyCategory"] = RVTOperations.GetRevitFamilyCategory(doc); } doc.Close(false); dt.Rows.Add(row); } } //If selectionGroup is 1, then the API will be used, and the file must be opened to obtain the information else if (selectionGroup == 1) { //Verifying Revit version year int rvtNumber = RVTOperations.GetRevitNumber(filePath); if (rvtNumber != 0 && Convert.ToInt32(uiApp.Application.VersionNumber) >= rvtNumber) { //Open the Revit file RVTDocument doc = RVTOperations.OpenRevitFile(uiApp, filePath); //Ensure it is a family document if (doc.IsFamilyDocument) { //Get the family manager of the family file FamilyManager famMan = doc.FamilyManager; //Get the set of family types from the family file FamilyTypeSet familyTypes = famMan.Types; Transaction t1 = new Transaction(doc, "CycleFamilyTypes"); t1.Start(); FailureHandlingOptions failureHandlingOptions = t1.GetFailureHandlingOptions(); failureHandlingOptions.SetFailuresPreprocessor(new RVTFailuresPreprocessor()); t1.SetFailureHandlingOptions(failureHandlingOptions); //For each family type... foreach (FamilyType famType in familyTypes) { //Create a subtransaction to change the current family type in the family manager SubTransaction s1 = new SubTransaction(doc); s1.Start(); famMan.CurrentType = famType; s1.Commit(); //Get each parameter from the current family type, and create a row for each parameter foreach (FamilyParameter param in famMan.GetParameters()) { DataRow row = dt.NewRow(); if (dt.Columns.Contains("FamilyName")) { try { row["FamilyName"] = GeneralOperations.GetFileName(filePath); } catch { row["FamilyName"] = ""; } } if (dt.Columns.Contains("FamilySize")) { try { row["FamilySize"] = GeneralOperations.GetFileSize(filePath); } catch { row["FamilySize"] = 0; } } if (dt.Columns.Contains("DateLastModified")) { try { row["DateLastModified"] = GeneralOperations.GetFileLastModifiedDate(filePath); } catch { row["DateLastModified"] = ""; } } if (dt.Columns.Contains("RevitVersion")) { try { row["RevitVersion"] = RVTOperations.GetRevitVersion(filePath); } catch { row["RevitVersion"] = ""; } } if (dt.Columns.Contains("FamilyCategory")) { try { row["FamilyCategory"] = RVTOperations.GetRevitFamilyCategory(doc); } catch { row["FamilyCategory"] = ""; } } if (dt.Columns.Contains("FamilyType")) { try { row["FamilyType"] = famType.Name.ToString(); } catch { row["FamilyType"] = ""; } } if (dt.Columns.Contains("ParameterName")) { try { row["ParameterName"] = param.Definition.Name; } catch { row["ParameterName"] = ""; } } if (dt.Columns.Contains("ParameterGroup")) { try { row["ParameterGroup"] = param.Definition.ParameterGroup.ToString(); } catch { row["ParameterGroup"] = ""; } } if (dt.Columns.Contains("ParameterType")) { try { row["ParameterType"] = param.Definition.ParameterType.ToString(); } catch { row["ParameterType"] = ""; } } //Here is where the attempts to get the parameter values begins. Get the StorageType of the parameter, then determine which column the data goes in if (dt.Columns.Contains("ParameterValueInteger") && param.StorageType == StorageType.Integer) { try { row["ParameterValueInteger"] = famType.AsInteger(param); } catch { row["ParameterValueInteger"] = 0; } } if (dt.Columns.Contains("ParameterValueDouble") && param.StorageType == StorageType.Double) { try { row["ParameterValueDouble"] = famType.AsDouble(param); } catch { row["ParameterValueDouble"] = 0; } } if (dt.Columns.Contains("ParameterValueString") && param.StorageType == StorageType.ElementId) { //Instead of getting the ElementID, which is limited in value to someone reading the data, get the element name instead try { row["ParameterValueString"] = doc.GetElement(famType.AsElementId(param)).Name; } catch { row["ParameterValueString"] = ""; } } if (dt.Columns.Contains("ParameterValueString") && param.StorageType == StorageType.String) { //First, try getting the parameter string as a string. If that fails, try getting it as a ValueString try { string paramValue = famType.AsString(param); row["ParameterValueString"] = paramValue; } catch { try { string paramValue = famType.AsValueString(param).ToString(); row["ParameterValueString"] = paramValue; } catch { row["ParameterValueString"] = ""; } } } if (dt.Columns.Contains("ParameterIsInstance")) { try { row["ParameterIsInstance"] = param.IsInstance; } catch { row["ParameterIsInstance"] = false; } } if (dt.Columns.Contains("ParameterIsShared")) { try { row["ParameterIsShared"] = param.IsShared; } catch { row["ParameterIsShared"] = false; } } if (dt.Columns.Contains("ParameterGUID")) { try { row["ParameterGUID"] = param.GUID.ToString(); } catch { row["ParameterGUID"] = ""; } } //Add the datatable row to the datatable dt.Rows.Add(row); } } //Commit the primary transaction t1.Commit(); } //Close the document, do not save doc.Close(false); } } else { //selectionGroup is still -2, and thus nothing was selected. Do nothing. continue; } } //Set the datatable of the open UI to the one with the obtained data uiForm.adminDataGFFDataTable = dt; //Indicate the collection is done with the label uiForm.adminDataGFFCollectDataWaitLabel.Text = "Done!"; //Hide the progress bar when done, and clear out the list of data items to collect uiForm.adminDataGFFDataProgressBar.Visible = false; uiForm.adminDataGFFItemsToCollect.Clear(); }
public MaterialsCMSRequest(UIApplication uiApp, String text) { MainUI uiForm = BARevitTools.Application.thisApp.newMainUi; ProgressBar progressBar = uiForm.materialsCMSExcelCreateSymbolsProgressBar; DataGridView dgv = uiForm.materialsCMSExcelDataGridView; int rowsCount = dgv.Rows.Count; int columnsCount = dgv.Columns.Count; List <string> familyTypesMade = new List <string>(); //Prepare the progress bar. The column count is one less because the first column is the column for family type names progressBar.Minimum = 0; progressBar.Maximum = (rowsCount) * (columnsCount - 1); progressBar.Step = 1; progressBar.Visible = true; RVTDocument doc = uiApp.ActiveUIDocument.Document; //Reset the progress bar uiForm.materialsCMSExcelCreateSymbolsProgressBar.Value = 0; //First, try to use the family from the project. If that fails, use the family file Family familyToUse = RVTGetElementsByCollection.FamilyByFamilyName(uiApp, Path.GetFileNameWithoutExtension(Properties.Settings.Default.RevitFamilyMaterialsCMSSymbIdMaterialSchedule)); //Assuming nothing went to hell in the process of loading one famiy... if (familyToUse != null) { //Save out the family to use RVTDocument tempFamDoc = doc.EditFamily(familyToUse); RVTOperations.SaveRevitFile(uiApp, tempFamDoc, @"C:\Temp\" + tempFamDoc.Title, true); //Open the family to use and get its FamilyManager RVTDocument famDoc = RVTOperations.OpenRevitFile(uiApp, @"C:\Temp\" + Path.GetFileName(Properties.Settings.Default.RevitFamilyMaterialsCMSSymbIdMaterialSchedule)); FamilyManager famMan = famDoc.FamilyManager; //Get the parameters from the Family Manager and add them to a dictionary FamilyParameterSet parameters = famMan.Parameters; Dictionary <string, FamilyParameter> famParamDict = new Dictionary <string, FamilyParameter>(); foreach (FamilyParameter param in parameters) { famParamDict.Add(param.Definition.Name, param); } //Start a new transaction to make the new family types in the family to use using (Transaction t1 = new Transaction(famDoc, "MakeNewTypes")) { t1.Start(); //Cycle through the rows in the dgv for (int i = 0; i < rowsCount; i++) { //The first column cell will be the type name string newTypeName = dgv.Rows[i].Cells[0].Value.ToString(); //Get the family type names in the family Dictionary <string, FamilyType> existingTypeNames = RVTOperations.GetFamilyTypeNames(famMan); //If the family to make from the DGV does not exist in the dictionary keys... if (!existingTypeNames.Keys.Contains(newTypeName)) { //Make the family type and add it to the list of types made FamilyType newType = famMan.NewType(newTypeName); famMan.CurrentType = newType; familyTypesMade.Add(newType.Name); } else { //If the type exists, set the current type it from the dictionary and add it to the list of types made famMan.CurrentType = existingTypeNames[newTypeName]; familyTypesMade.Add(famMan.CurrentType.Name); } //Next, evaluate the columns that contain parameters for (int j = 1; j < columnsCount; j++) { //The parameter names will be retrieved from the column HeaderText property string paramName = dgv.Columns[j].HeaderText; //Meanwhile the parameter value will come from the DGV cells var paramValue = dgv.Rows[i].Cells[j].Value; try { //If the parameter dictionary contains the parameter and the value to assign it is not empty, continue. if (paramValue.ToString() != "" && famParamDict.Keys.Contains(paramName)) { //Get the family parameter and check if it is locked by a formula FamilyParameter param = famParamDict[paramName]; if (!param.IsDeterminedByFormula) { //If it is not locked by a formula, set the parameter ParameterType paramType = param.Definition.ParameterType; RVTOperations.SetFamilyParameterValue(famMan, param, paramValue); } } } catch {; } finally { //Always perform the step to indicate the progress. progressBar.PerformStep(); } } } t1.Commit(); } //Use another transaction to delete the types that were not needed using (Transaction t2 = new Transaction(famDoc, "DeleteOldTypes")) { t2.Start(); //Cycle through the family types and determine if it is in the list of types made foreach (FamilyType type in famMan.Types) { if (!familyTypesMade.Contains(type.Name)) { //If the type is not in the list of types made, delete it from the family file famMan.CurrentType = type; famMan.DeleteCurrentType(); } } t2.Commit(); } //Save the family document at this point as all of the types and their parameters have been set famDoc.Close(true); using (Transaction t3 = new Transaction(doc, "LoadFamily")) { t3.Start(); doc.LoadFamily(@"C:\Temp\" + Path.GetFileName(Properties.Settings.Default.RevitFamilyMaterialsCMSSymbIdMaterialSchedule), new RVTFamilyLoadOptions(), out Family loadedFamily); t3.Commit(); } //Get the drafting view type in the project for BA Drafting View, else just get the first drafting view type ViewDrafting placementView = null; var draftingViews = new FilteredElementCollector(doc).OfClass(typeof(ViewDrafting)).WhereElementIsNotElementType().ToElements(); ViewFamilyType draftingViewType = null; try { //From the view family types collection, get the first one where its name is BA Drafting View draftingViewType = new FilteredElementCollector(doc).OfClass(typeof(ViewFamilyType)).WhereElementIsElementType().ToElements().Where(elem => elem.Name == "BA Drafting View").First() as ViewFamilyType; } catch { //Well, crap. It doesn't exist. Just get the first type then and call it good. draftingViewType = new FilteredElementCollector(doc).OfClass(typeof(ViewFamilyType)).WhereElementIsElementType().ToElements().First() as ViewFamilyType; } //Start a transaction for making the ID Material View and placing the family symbol types using (Transaction t4 = new Transaction(doc, "MakeIDMaterialView")) { t4.Start(); foreach (ViewDrafting view in draftingViews) { //Find the view named ID Material View, or whatever jibberish someone typed in the CMS text box for the name to use. in the drafting views if (view.Name == "ID Material View" || view.Name == uiForm.materialsCMSSetViewNameTextBox.Text) { //Delete the drafting view doc.Delete(view.Id); doc.Regenerate(); break; } else { continue; } } //Make a new view placementView = ViewDrafting.Create(doc, draftingViewType.Id); placementView.Scale = 1; if (uiForm.materialsCMSSetViewNameTextBox.Text != "") { //If someone defined a custom view name, use that and strip out brackets if they exist placementView.Name = uiForm.materialsCMSSetViewNameTextBox.Text.Replace("{", "").Replace("}", ""); } else { //Otherwise, this will be the new ID Material View placementView.Name = "ID Material View"; } try { //Set the view sort parameters if they exist placementView.GetParameters(Properties.Settings.Default.BAViewSort1).First().Set("2 Plans"); placementView.GetParameters(Properties.Settings.Default.BAViewSort2).First().Set("230 Finish Plans"); } catch (Exception e) { MessageBox.Show(e.ToString()); } doc.Regenerate(); t4.Commit(); } //Do magic to place each symbol in its view by calling the method below in this class PlaceSymbolsInView(uiApp, "ID Use", "Mark", placementView); //Clean up the files from the operations GeneralOperations.CleanRfaBackups(GeneralOperations.GetAllRvtBackupFamilies(@"C:\Temp\", false)); File.Delete(@"C:\Temp\" + Path.GetFileName(Properties.Settings.Default.RevitFamilyMaterialsCMSSymbIdMaterialSchedule)); Application.thisApp.newMainUi.materialsCMSFamilyToUse = RVTGetElementsByCollection.FamilyByFamilyName(uiApp, Path.GetFileNameWithoutExtension(Properties.Settings.Default.RevitFamilyMaterialsCMSSymbIdMaterialSchedule)); } else { //If the family could not be found, well, let the user know of this. MessageBox.Show(String.Format("The {0} family could not be found in the project.", Path.GetFileNameWithoutExtension(Properties.Settings.Default.RevitFamilyMaterialsCMSSymbIdMaterialSchedule))); } }