//DataSet import is from here: //http://stackoverflow.com/a/18006593/6073998 public static DataSet ImportExcelToDataSet(string fileName, string dataHasHeaders) { //On connection strings http://www.connectionstrings.com/excel/#p84 string connectionString = string.Format( "provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0;HDR={1};IMEX=1\"", fileName, dataHasHeaders); DataSet data = new DataSet(); foreach (string sheetName in GetExcelSheetNames(connectionString)) { using (OleDbConnection con = new OleDbConnection(connectionString)) { var dataTable = new DataTable(); string query = string.Format("SELECT * FROM [{0}]", sheetName); try { con.Open(); } catch (Exception e) { throw new Exception($"OleDb threw an Exception AGAIN!!!\n{e.Message}"); } OleDbDataAdapter adapter = new OleDbDataAdapter(query, con); adapter.Fill(dataTable); //Remove ' and $ from sheetName Regex rgx = new Regex("[^a-zA-Z0-9 _-]"); string tableName = rgx.Replace(sheetName, ""); dataTable.TableName = tableName; data.Tables.Add(dataTable); } } if (data == null) { BuildingCoderUtilities.ErrorMsg("Data set is null"); } if (data.Tables.Count < 1) { BuildingCoderUtilities.ErrorMsg("Table count in DataSet is 0"); } return(data); }
internal Result PopulatePipelineData(UIApplication uiApp, ref string msg, DataTable dataTable) { List <string> ParameterNames = (from dc in dataTable.Columns.Cast <DataColumn>() select dc.ColumnName).ToList(); //ParameterNames.RemoveAt(0); //ParameterNames.RemoveAt(0); //Test to see if the list of parameter names is defined at all, if not -- break. if (ParameterNames.IsNullOrEmpty()) { BuildingCoderUtilities.ErrorMsg("Parameter names are incorrectly defined. Please reselect the EXCEL workbook."); return(Result.Failed); } ; Document doc = uiApp.ActiveUIDocument.Document; StringBuilder sbFeedback = new StringBuilder(); //Get the systems of things and get the SystemTypes //Collector for PipingSystems FilteredElementCollector collector = new FilteredElementCollector(doc); IList <Element> elementList = collector.OfClass(typeof(PipingSystem)).ToElements(); //Collector returns Element, cast to PipingSystem IList <PipingSystem> systemList = elementList.Cast <PipingSystem>().ToList(); //Get the PipingSystemType Id from the PipingSystem elements IList <ElementId> systemTypeIdList = systemList.Select(sys => sys.GetTypeId()).ToList(); //Retrieve PipingSystemType from doc IEnumerable <Element> systemTypeList = from id in systemTypeIdList select doc.GetElement(id); //Group PipingSystemType by Name and retrieve first element of group -> equals to filtering a list to contain only unique elements List <Element> sQuery = (from st in systemTypeList group st by new { st.Name } //http://stackoverflow.com/a/9589705/6073998 {st.Name, st.Attribute1, st.Attribute2} into stGroup select stGroup.First()).ToList(); //prepare input variables which are initialized when looping the elements string sysAbbr = null; string columnName = null; //query is using the variables in the loop to query the dataset EnumerableRowCollection <string> query = from value in dataTable.AsEnumerable() where value.Field <string>(0) == iv.PCF_PROJECT_IDENTIFIER && value.Field <string>(1) == sysAbbr select value.Field <string>(columnName); //Get a query for pipeline parameters var pQuery = from p in new plst().LPAll where p.Domain == "PIPL" && p.ExportingTo != "LDT" //<- LDT parameters are read directly from EXCEL to PCF file. select p; //Debugging //StringBuilder sbParameters = new StringBuilder(); using (Transaction trans = new Transaction(doc, "Initialize Pipeline PCF parameters")) { trans.Start(); //Loop all elements pipes and fittings and accessories, setting parameters as defined in the dataset try { //Reporting the number of different elements initialized int sNumber = 0; foreach (Element pipeSystemType in sQuery) { //reporting sNumber++; sysAbbr = pipeSystemType.get_Parameter(BuiltInParameter.RBS_SYSTEM_ABBREVIATION_PARAM).AsString(); foreach (string parameterName in ParameterNames) // <-- ParameterNames must be correctly initialized!!! { columnName = parameterName; //This is needed to execute query correctly by deferred execution string parameterValue = query.FirstOrDefault(); if (string.IsNullOrEmpty(parameterValue)) { continue; } Guid parGuid = (from d in pQuery.ToList() where d.Name == parameterName select d.Guid).FirstOrDefault(); //Check if parGuid returns a match if (parGuid == null) { continue; } Parameter par = pipeSystemType.get_Parameter(parGuid); if (par == null) { continue; } par.Set(parameterValue); } //sbParameters.Append(eFamilyType); //sbParameters.AppendLine(); } //sbParameters.Append(eFamilyType); //sbParameters.AppendLine(); //} sbFeedback.Append(sNumber + " Pipe Systems (Pipelines) initialized.\n"); BuildingCoderUtilities.InfoMsg(sbFeedback.ToString()); //excelReader.Close(); //// Debugging //// Clear the output file //File.WriteAllBytes(InputVars.OutputDirectoryFilePath + "Parameters.pcf", new byte[0]); //// Write to output file //using (StreamWriter w = File.AppendText(InputVars.OutputDirectoryFilePath + "Parameters.pcf")) //{ // w.Write(sbParameters); // w.Close(); //} } catch (Autodesk.Revit.Exceptions.OperationCanceledException) { return(Result.Cancelled); } catch (Exception ex) { msg = ex.Message; BuildingCoderUtilities.ErrorMsg("Population of parameters failed with the following exception: \n" + msg); trans.RollBack(); return(Result.Failed); } trans.Commit(); } return(Result.Succeeded); }
internal Result PopulateElementData(UIApplication uiApp, ref string msg, DataTable dataTable) { List <string> ParameterNames = (from dc in dataTable.Columns.Cast <DataColumn>() select dc.ColumnName).ToList(); ParameterNames.RemoveAt(0); //Test to see if the list of parameter names is defined at all, if not -- break. if (ParameterNames.IsNullOrEmpty()) { BuildingCoderUtilities.ErrorMsg("Parameter names are incorrectly defined. Please reselect the EXCEL workbook."); return(Result.Failed); } ; Document doc = uiApp.ActiveUIDocument.Document; //string filename = path; StringBuilder sbFeedback = new StringBuilder(); //Failure feedback Element elementRefForFeedback = null; FilteredElementCollector collector = Shared.Filter.GetElementsWithConnectors(doc); //prepare input variables which are initialized when looping the elements string eFamilyType = null; string columnName = null; //query is using the variables in the loop to query the dataset EnumerableRowCollection <string> query = from value in dataTable.AsEnumerable() where value.Field <string>(0) == eFamilyType select value.Field <string>(columnName); var pQuery = from p in new plst().LPAll where p.Domain == "ELEM" select p; //Debugging //StringBuilder sbParameters = new StringBuilder(); using (Transaction trans = new Transaction(doc, "Initialize PCF parameters")) { trans.Start(); //Loop all elements pipes and fittings and accessories, setting parameters as defined in the dataset try { //Reporting the number of different elements initialized int pNumber = 0, fNumber = 0, aNumber = 0; foreach (Element element in collector) { //Feedback elementRefForFeedback = element; //Filter out elements in ARGD (Rigids) system type Cons cons = new Cons(element); if (cons.Primary.MEPSystemAbbreviation(doc) == "ARGD") { continue; } //reporting if (string.Equals(element.Category.Name.ToString(), "Pipes")) { pNumber++; } else if (string.Equals(element.Category.Name.ToString(), "Pipe Fittings")) { fNumber++; } else if (string.Equals(element.Category.Name.ToString(), "Pipe Accessories")) { aNumber++; } eFamilyType = element.get_Parameter(BuiltInParameter.ELEM_FAMILY_AND_TYPE_PARAM).AsValueString(); foreach (string parameterName in ParameterNames) // <-- ParameterNames must be correctly initialized!!! { columnName = parameterName; //This is needed to execute query correctly by deferred execution string parameterValue = query.FirstOrDefault(); if (string.IsNullOrEmpty(parameterValue)) { continue; } Guid parGuid = (from d in pQuery where d.Name == parameterName select d.Guid).First(); //Check if parGuid returns a match if (parGuid == null) { BuildingCoderUtilities.ErrorMsg("Wrong parameter set. Select ELEMENT parameters."); return(Result.Failed); } //Writing the parameter data //Implementing Overwrite or Append here if (iv.Overwrite) { element.get_Parameter(parGuid).Set(parameterValue); } else { Parameter par = element.get_Parameter(parGuid); if (string.IsNullOrEmpty(par.ToValueString())) { par.Set(parameterValue); } else { continue; } } } //sbParameters.Append(eFamilyType); //sbParameters.AppendLine(); } //sbParameters.Append(eFamilyType); //sbParameters.AppendLine(); sbFeedback.Append(pNumber + " Pipes initialized.\n" + fNumber + " Pipe fittings initialized.\n" + aNumber + " Pipe accessories initialized."); BuildingCoderUtilities.InfoMsg(sbFeedback.ToString()); //excelReader.Close(); //// Debugging //// Clear the output file //File.WriteAllBytes(InputVars.OutputDirectoryFilePath + "Parameters.pcf", new byte[0]); //// Write to output file //using (StreamWriter w = File.AppendText(InputVars.OutputDirectoryFilePath + "Parameters.pcf")) //{ // w.Write(sbParameters); // w.Close(); //} } catch (Autodesk.Revit.Exceptions.OperationCanceledException) { return(Result.Cancelled); } catch (Exception ex) { msg = ex.Message; BuildingCoderUtilities.ErrorMsg($"Population of parameters failed with the following exception: \n" + msg + $"\n For element {elementRefForFeedback.Id.IntegerValue}."); trans.RollBack(); return(Result.Failed); } trans.Commit(); } return(Result.Succeeded); }
internal Result ExecuteMyCommand(UIApplication uiApp) { Document doc = uiApp.ActiveUIDocument.Document; FilteredElementCollector collector = new FilteredElementCollector(doc); #region Pipeline schedule export //Collect piping systems collector.OfClass(typeof(PipingSystem)); //Group all elements by their Family and Type IOrderedEnumerable <Element> orderedCollector = collector.OrderBy(e => e.get_Parameter(BuiltInParameter.ELEM_FAMILY_AND_TYPE_PARAM).AsValueString()); IEnumerable <IGrouping <string, Element> > elementGroups = from e in orderedCollector group e by e.get_Parameter(BuiltInParameter.ELEM_FAMILY_AND_TYPE_PARAM).AsValueString(); xel.Application excel = new xel.Application(); if (null == excel) { BuildingCoderUtilities.ErrorMsg("Failed to get or start Excel."); return(Result.Failed); } excel.Visible = true; xel.Workbook workbook = excel.Workbooks.Add(Missing.Value); xel.Worksheet worksheet; worksheet = excel.ActiveSheet as xel.Worksheet; worksheet.Name = "PCF Export - pipelines"; worksheet.Columns.ColumnWidth = 20; worksheet.Cells[1, 1] = "Family and Type"; //Change domain for query string curDomain = "PIPL", curUsage = "U"; var query = from p in new plst().LPAll where p.Domain == curDomain && p.Usage == curUsage select p; worksheet.Range["A1", BuildingCoderUtilities.GetColumnName(query.Count()) + "1"].Font.Bold = true; //Export family and type names to first column and parameter values int row = 2, col = 2; foreach (IGrouping <string, Element> gp in elementGroups) { worksheet.Cells[row, 1] = gp.Key; foreach (var p in query.ToList()) { if (row == 2) { worksheet.Cells[1, col] = p.Name; //Fill out top row only in the first iteration } ElementId id = gp.First().GetTypeId(); PipingSystemType ps = (PipingSystemType)doc.GetElement(id); //SystemType parameters can only be read from type elements worksheet.Cells[row, col] = ps.get_Parameter(p.Guid).AsString(); col++; //Increment column } row++; col = 2; //Increment row and reset column } #endregion #region Element schedule export //Define a collector (Pipe OR FamInst) AND (Fitting OR Accessory OR Pipe). //This is to eliminate FamilySymbols from collector which would throw an exception later on. collector = Shared.Filter.GetElementsWithConnectors(doc); //Group all elements by their Family and Type orderedCollector = collector.OrderBy(e => e.get_Parameter(BuiltInParameter.ELEM_FAMILY_AND_TYPE_PARAM).AsValueString()); elementGroups = from e in orderedCollector group e by e.get_Parameter(BuiltInParameter.ELEM_FAMILY_AND_TYPE_PARAM).AsValueString(); excel.Sheets.Add(Missing.Value, Missing.Value, Missing.Value, Missing.Value); worksheet = excel.ActiveSheet as xel.Worksheet; worksheet.Name = "PCF Export - elements"; worksheet.Columns.ColumnWidth = 20; worksheet.Cells[1, 1] = "Family and Type"; //Query parameters curDomain = "ELEM"; //Formatting must occur here, because it depends on query worksheet.Range["A1", BuildingCoderUtilities.GetColumnName(query.Count()) + "1"].Font.Bold = true; //Export family and type names to first column and parameter values row = 2; col = 2; foreach (IGrouping <string, Element> gp in elementGroups) { worksheet.Cells[row, 1] = gp.Key; foreach (var p in query) { if (row == 2) { worksheet.Cells[1, col] = p.Name; //Fill out top row only in the first iteration } worksheet.Cells[row, col] = gp.First().get_Parameter(p.Guid).AsString(); col++; //Increment column } row++; col = 2; //Increment row and reset column } #endregion collector.Dispose(); return(Result.Succeeded); }
public StringBuilder Export(string key, Document doc) { StringBuilder sbPipeline = new StringBuilder(); try { //Instantiate collector FilteredElementCollector collector = new FilteredElementCollector(doc); //Get the elements collector.OfClass(typeof(PipingSystemType)); //Select correct systemType PipingSystemType pipingSystemType = (from PipingSystemType st in collector where string.Equals(st.Abbreviation, key) select st).FirstOrDefault(); IEnumerable <pdef> query = from p in Plst.LPAll where string.Equals(p.Domain, "PIPL") && !string.Equals(p.ExportingTo, "CII") && !string.Equals(p.ExportingTo, "LDT") select p; sbPipeline.Append("PIPELINE-REFERENCE "); sbPipeline.Append(key); sbPipeline.AppendLine(); if (PCF_Functions.InputVars.ExportToIsogen) { ////Facilitate export to Isogen ////This is where PipeSystemAbbreviation is stored //sbPipeline.Append(" "); //sbPipeline.Append("Attribute10"); //sbPipeline.Append(" "); //sbPipeline.Append(key); //sbPipeline.AppendLine(); string LDTPath = mySettings.Default.LDTPath; if (!string.IsNullOrEmpty(LDTPath) && File.Exists(LDTPath)) { var dataSet = Shared.DataHandler.ImportExcelToDataSet(LDTPath, "YES"); var data = Shared.DataHandler.ReadDataTable(dataSet.Tables, "Pipelines"); string sysAbbr = pipingSystemType.get_Parameter(BuiltInParameter.RBS_SYSTEM_ABBREVIATION_PARAM).AsString(); string parName = ""; string projId = iv.PCF_PROJECT_IDENTIFIER; //EnumerableRowCollection<string> ldtQuery = from row in data.AsEnumerable() // where row.Field<string>("PCF_PROJID") == projId && // row.Field<string>("LINE_NAME") == sysAbbr // select row.Field<string>(parName); //var lineId = pipingSystemType.get_Parameter(Plst.PCF_PIPL_LINEID.Guid).AsString(); var LdtPars = Plst.LPAll.Where(x => x.ExportingTo == "LDT"); foreach (pdef par in LdtPars) { parName = par.Name; int rowIndex = data.Rows.IndexOf(data.Select( $"PCF_PROJID = '{projId}' AND LINE_NAME = '{sysAbbr}'")[0]); string value = Convert.ToString(data.Rows[rowIndex][parName]); //string value = ldtQuery.FirstOrDefault(); if (!string.IsNullOrEmpty(value)) { sbPipeline.Append(" "); sbPipeline.Append(par.Keyword); sbPipeline.Append(" "); sbPipeline.Append(value); sbPipeline.AppendLine(); } } } } foreach (pdef p in query) { if (string.IsNullOrEmpty(pipingSystemType.get_Parameter(p.Guid).AsString())) { continue; } sbPipeline.Append(" "); sbPipeline.Append(p.Keyword); sbPipeline.Append(" "); sbPipeline.Append(pipingSystemType.get_Parameter(p.Guid).AsString()); sbPipeline.AppendLine(); } } catch (Exception e) { BuildingCoderUtilities.ErrorMsg(e.Message); } return(sbPipeline); //Debug //// Clear the output file //System.IO.File.WriteAllBytes(InputVars.OutputDirectoryFilePath + "Pipes.pcf", new byte[0]); //// Write to output file //using (StreamWriter w = File.AppendText(InputVars.OutputDirectoryFilePath + "Pipes.pcf")) //{ // w.Write(sbPipes); // w.Close(); //} }
public Result defineTapConnection(ExternalCommandData commandData, ref string msg, ElementSet elements) { UIApplication uiApp = commandData.Application; Document doc = uiApp.ActiveUIDocument.Document; Application app = doc.Application; UIDocument uidoc = uiApp.ActiveUIDocument; Transaction trans = new Transaction(doc, "Define tap"); trans.Start(); try { //Select tapped element Element tappedElement = BuildingCoderUtilities.SelectSingleElement(uidoc, "Select tapped element."); if (!(tappedElement != null)) { throw new Exception("Tap Connection cancelled!"); } //Pipe type to restrict selection of tapping element Type t = typeof(Pipe); //Select tap element Element tappingElement = BuildingCoderUtilities.SelectSingleElementOfType(uidoc, t, "Select tapping element (must be a pipe).", false); if (!(tappingElement != null)) { throw new Exception("Tap Connection cancelled!"); } ////Debugging //StringBuilder sbTaps = new StringBuilder(); if (string.IsNullOrEmpty(tappedElement.LookupParameter("PCF_ELEM_TAP1").AsString())) { tappedElement.LookupParameter("PCF_ELEM_TAP1").Set(tappingElement.UniqueId.ToString()); } else if (string.IsNullOrEmpty(tappedElement.LookupParameter("PCF_ELEM_TAP2").AsString())) { tappedElement.LookupParameter("PCF_ELEM_TAP2").Set(tappingElement.UniqueId.ToString()); } else if (string.IsNullOrEmpty(tappedElement.LookupParameter("PCF_ELEM_TAP3").AsString())) { tappedElement.LookupParameter("PCF_ELEM_TAP3").Set(tappingElement.UniqueId.ToString()); } else { BuildingCoderUtilities.ErrorMsg("All tapping slots are taken. Manually delete unwanted values og increase number of tapping slots."); } trans.Commit(); //Debug //sbTaps.Append(tappedElement.LookupParameter(InputVars.PCF_ELEM_TAP1).AsString() == ""); //sbTaps.AppendLine(); //sbTaps.Append(tappedElement.LookupParameter(InputVars.PCF_ELEM_TAP2).AsString() + " " + tappedElement.LookupParameter(InputVars.PCF_ELEM_TAP2).AsString() == null); //sbTaps.AppendLine(); //sbTaps.Append(tappedElement.LookupParameter(InputVars.PCF_ELEM_TAP3).AsString() + " " + tappedElement.LookupParameter(InputVars.PCF_ELEM_TAP3).AsString() == null); //sbTaps.AppendLine(); //// Debugging //// Clear the output file //File.WriteAllBytes(InputVars.OutputDirectoryFilePath + "Taps.pcf", new byte[0]); //// Write to output file //using (StreamWriter w = File.AppendText(InputVars.OutputDirectoryFilePath + "Taps.pcf")) //{ // w.Write(sbTaps); // w.Close(); //} } catch (Autodesk.Revit.Exceptions.OperationCanceledException) { trans.RollBack(); return(Result.Cancelled); } catch (Exception ex) { trans.RollBack(); msg = ex.Message; return(Result.Failed); } return(Result.Succeeded); }
internal Result ExecuteMyCommand(UIApplication uiApp, ref string msg) { // UIApplication uiApp = commandData.Application; //Test comment Document doc = uiApp.ActiveUIDocument.Document; UIDocument uidoc = uiApp.ActiveUIDocument; try { #region Declaration of variables // Instance a collector FilteredElementCollector collector = new FilteredElementCollector(doc); //FilteredElementCollector pipeTypeCollector = new FilteredElementCollector(doc); //Obsolete??? // Define a Filter instance to filter by System Abbreviation ElementParameterFilter sysAbbr = Shared.Filter.ParameterValueGenericFilter(doc, InputVars.SysAbbr, InputVars.SysAbbrParam); // Declare pipeline grouping object IEnumerable <IGrouping <string, Element> > pipelineGroups; //Declare an object to hold collected elements from collector HashSet <Element> colElements = new HashSet <Element>(); // Instance a collecting stringbuilder StringBuilder sbCollect = new StringBuilder(); #endregion #region Compose preamble //Compose preamble Composer composer = new Composer(); StringBuilder sbPreamble = composer.PreambleComposer(); //Append preamble sbCollect.Append(sbPreamble); #endregion #region Element collectors //If user chooses to export a single pipeline get only elements in that pipeline and create grouping. //Grouping is necessary even tho theres only one group to be able to process by the same code as the all pipelines case //If user chooses to export all pipelines get all elements and create grouping if (InputVars.ExportAllOneFile) { //Define a collector (Pipe OR FamInst) AND (Fitting OR Accessory OR Pipe). //This is to eliminate FamilySymbols from collector which would throw an exception later on. collector.WherePasses(new LogicalAndFilter(new List <ElementFilter> { new LogicalOrFilter(new List <ElementFilter> { new ElementCategoryFilter(BuiltInCategory.OST_PipeFitting), new ElementCategoryFilter(BuiltInCategory.OST_PipeAccessory), new ElementClassFilter(typeof(Pipe)) }), new LogicalOrFilter(new List <ElementFilter> { new ElementClassFilter(typeof(Pipe)), new ElementClassFilter(typeof(FamilyInstance)) }) })); colElements = collector.ToElements().ToHashSet(); } else if (InputVars.ExportAllSepFiles || InputVars.ExportSpecificPipeLine) { //Define a collector with multiple filters to collect PipeFittings OR PipeAccessories OR Pipes + filter by System Abbreviation //System Abbreviation filter also filters FamilySymbols out. collector.WherePasses( new LogicalOrFilter( new List <ElementFilter> { new ElementCategoryFilter(BuiltInCategory.OST_PipeFitting), new ElementCategoryFilter(BuiltInCategory.OST_PipeAccessory), new ElementClassFilter(typeof(Pipe)) })).WherePasses(sysAbbr); colElements = collector.ToElements().ToHashSet(); } else if (InputVars.ExportSelection) { ICollection <ElementId> selection = uiApp.ActiveUIDocument.Selection.GetElementIds(); colElements = selection.Select(s => doc.GetElement(s)).ToHashSet(); } #region Sub: Filtering HashSet <Element> elements; try { //DiameterLimit filter applied to ALL elements. var filtering = from element in colElements where Filters.FilterDL(element) select element; //Filter out EXCLUDED elements -> 0 means no checkmark filtering = from element in filtering where element.get_Parameter(new plst().PCF_ELEM_EXCL.Guid).AsInteger() == 0 select element; //Filter out EXCLUDED pipelines -> 0 means no checkmark filtering = filtering.Where(x => x.PipingSystemAllowed(doc) == true); //Remove instrument pipes filtering = filtering.ExceptWhere(x => x.get_Parameter(BuiltInParameter.RBS_DUCT_PIPE_SYSTEM_ABBREVIATION_PARAM) .AsString() == "INSTR"); //Filter out elements with specified PCF_ELEM_SPEC string if (InputVars.PCF_ELEM_SPEC_FILTER.IsNullOrEmpty() == false) { filtering = filtering.ExceptWhere(x => x.get_Parameter(new plst().PCF_ELEM_SPEC.Guid).AsString() == InputVars.PCF_ELEM_SPEC_FILTER); } //If exporting to ISO, remove some not needed elements if (InputVars.ExportToIsogen) { //When exporting to Plant3D ISO creation, remove the group with the Piping System: Analysis Rigids (ARGD) filtering = filtering .Where(x => !(x.get_Parameter(BuiltInParameter.RBS_DUCT_PIPE_SYSTEM_ABBREVIATION_PARAM).AsString() == "ARGD")); ////Also remove anchor symbols -> not needed for ISO ////Currently not removed -> used for floor symbols //filtering = filtering.ExceptWhere(x => x // .get_Parameter(BuiltInParameter.ELEM_FAMILY_AND_TYPE_PARAM) // .AsValueString() == "Support Symbolic: ANC"); } //Create a grouping of elements based on the Pipeline identifier (System Abbreviation) pipelineGroups = from e in filtering group e by e.get_Parameter(BuiltInParameter.RBS_DUCT_PIPE_SYSTEM_ABBREVIATION_PARAM).AsString(); elements = filtering.ToHashSet(); } catch (Exception ex) { throw new Exception("Filtering in Main threw an exception:\n" + ex.Message + "\nTo fix:\n" + "1. See if parameter PCF_ELEM_EXCL exists, if not, rerun parameter import."); } #endregion #endregion #region Initialize Material Data //TEST: Do not write material data to elements with EXISTING-INCLUDE spec //HashSet<Element> existInclElements = elements.Where(x => // x.get_Parameter(new plst().PCF_ELEM_SPEC.Guid).AsString() == "EXISTING-INCLUDE").ToHashSet(); ////Remember the clearing of previous run data in transaction below //elements = elements.ExceptWhere(x => // x.get_Parameter(new plst().PCF_ELEM_SPEC.Guid).AsString() == "EXISTING-INCLUDE").ToHashSet(); //Set the start number to count the COMPID instances and MAT groups. int elementIdentificationNumber = 0; int materialGroupIdentifier = 0; //Make sure that every element has PCF_MAT_DESCR filled out. foreach (Element e in elements) { if (string.IsNullOrEmpty(e.get_Parameter(new plst().PCF_MAT_DESCR.Guid).AsString())) { uidoc.Selection.SetElementIds(new List <ElementId>(1) { e.Id }); BuildingCoderUtilities.ErrorMsg("PCF_MAT_DESCR is empty for element " + e.Id + "! Please, correct this issue before exporting again."); throw new Exception("PCF_MAT_DESCR is empty for element " + e.Id + "! Please, correct this issue before exporting again."); } } //Initialize material group numbers on the elements IEnumerable <IGrouping <string, Element> > materialGroups = from e in elements group e by e.get_Parameter(new plst().PCF_MAT_DESCR.Guid).AsString(); using (Transaction trans = new Transaction(doc, "Set PCF_ELEM_COMPID and PCF_MAT_ID")) { trans.Start(); //Clear MTL data from previous runs for elements with EXISTING-INCLUDE spec //foreach (Element e in existInclElements) //{ // e.get_Parameter(new plst().PCF_ELEM_COMPID.Guid).Set(""); // e.get_Parameter(new plst().PCF_MAT_ID.Guid).Set(""); //} //Access groups foreach (IEnumerable <Element> group in materialGroups) { materialGroupIdentifier++; //Access parameters foreach (Element element in group) { elementIdentificationNumber++; element.get_Parameter(new plst().PCF_ELEM_COMPID.Guid).Set(elementIdentificationNumber.ToString()); element.get_Parameter(new plst().PCF_MAT_ID.Guid).Set(materialGroupIdentifier.ToString()); } } trans.Commit(); } //If turned on, write wall thickness of all components if (InputVars.WriteWallThickness) { //Assign correct wall thickness to elements. using (Transaction trans1 = new Transaction(doc)) { trans1.Start("Set wall thickness for pipes!"); ParameterDataWriter.SetWallThicknessPipes(elements); trans1.Commit(); } } #endregion using (TransactionGroup txGp = new TransactionGroup(doc)) { txGp.Start("Bogus transactionGroup for the break in hangers"); #region Pipeline management foreach (IGrouping <string, Element> gp in pipelineGroups) { HashSet <Element> pipeList = (from element in gp where element.Category.Id.IntegerValue == (int)BuiltInCategory.OST_PipeCurves select element).ToHashSet(); HashSet <Element> fittingList = (from element in gp where element.Category.Id.IntegerValue == (int)BuiltInCategory.OST_PipeFitting select element).ToHashSet(); HashSet <Element> accessoryList = (from element in gp where element.Category.Id.IntegerValue == (int)BuiltInCategory.OST_PipeAccessory select element).ToHashSet(); StringBuilder sbPipeline = new PCF_Pipeline.PCF_Pipeline_Export().Export(gp.Key, doc); StringBuilder sbFilename = PCF_Pipeline.Filename.BuildAndWriteFilename(doc); StringBuilder sbEndsAndConnections = PCF_Pipeline.EndsAndConnections .DetectAndWriteEndsAndConnections(gp.Key, pipeList, fittingList, accessoryList, doc); #region BrokenPipes //Here be code to handle break in accessories that act as supports //Find the supports in current acessoryList and add to supportList //Instantiate a brokenPipesGroup class //Collect all Connectors from brokenPipesList and find the longest distance //Create a temporary pipe from the Connectors with longest distance //Copy PCF_ELEM parameter values to the temporary pipe //Add the temporary pipe to the pipeList //Roll back the TransactionGroup after the elements are sent to Export class' Export methods. List <BrokenPipesGroup> bpgList = new List <BrokenPipesGroup>(); List <Element> supportsList = accessoryList.Where(x => x.ComponentClass1(doc) == "Pipe Support").ToList(); while (supportsList.Count > 0) { //Get an element to start traversing Element seedElement = supportsList.FirstOrDefault(); if (seedElement == null) { throw new Exception("BrokenPipes: Seed element returned null! supportsList.Count is " + supportsList.Count); } //Instantiate the BrokenPipesGroup BrokenPipesGroup bpg = new BrokenPipesGroup(seedElement, gp.Key); //Traverse system bpg.Traverse(doc); //Remove the support Elements from the collection to keep track of the while loop foreach (Element support in bpg.SupportsOnPipe) { supportsList = supportsList.ExceptWhere(x => x.Id.IntegerValue == support.Id.IntegerValue).ToList(); } bpgList.Add(bpg); } using (Transaction tx = new Transaction(doc)) { tx.Start("Create healed pipes"); foreach (BrokenPipesGroup bpg in bpgList) { //Remove the broken pipes from the pipeList //If there's only one broken pipe, then there's no need to do anything //If there's no broken pipes, then there's no need to do anything either if (bpg.BrokenPipes.Count != 0 && bpg.BrokenPipes.Count != 1) { foreach (Element pipe in bpg.BrokenPipes) { pipeList = pipeList.ExceptWhere(x => x.Id.IntegerValue == pipe.Id.IntegerValue).ToHashSet(); } //Using the new IEqualityComparer for Connectors to get distinct connectors in the collection var brokenCons = MepUtils.GetALLConnectorsFromElements(bpg.BrokenPipes.ToHashSet(), new ConnectorXyzComparer(2.0.MmToFt())); //Create distinct pair combinations with distance from all broken connectors //https://stackoverflow.com/a/47003122/6073998 List <(Connector c1, Connector c2, double dist)> pairs = brokenCons .SelectMany ( (fst, i) => brokenCons.Skip(i + 1).Select(snd => (fst, snd, fst.Origin.DistanceTo(snd.Origin))) ) .ToList(); var longest = pairs.MaxBy(x => x.dist).FirstOrDefault(); Pipe dPipe = (Pipe)longest.c1.Owner; bpg.HealedPipe = Pipe.Create(doc, dPipe.MEPSystem.GetTypeId(), dPipe.GetTypeId(), dPipe.ReferenceLevel.Id, longest.c1.Origin, longest.c2.Origin); Pipe donorPipe = (Pipe)bpg.BrokenPipes.FirstOrDefault(); bpg.HealedPipe.get_Parameter(BuiltInParameter.RBS_PIPE_DIAMETER_PARAM).Set(donorPipe.Diameter); //Add the healed pipe to the pipeList for processing pipeList.Add(bpg.HealedPipe); } } tx.Commit(); } //Now the healed pipe must be populated by the parameters from a donorPipe using (Transaction tx = new Transaction(doc)) { //Gather all relevant parameter definitions List <pdef> plist = new plst().LPAll.Where(x => x.Domain == "ELEM" && x.Usage == "U").ToList(); plist.Add(new plst().PCF_MAT_ID); tx.Start("Populate the HealedPipe parameters!"); foreach (BrokenPipesGroup bpg in bpgList) { //Skip iteration if there's only 1 or no broken pipes if (bpg.BrokenPipes.Count == 0 || bpg.BrokenPipes.Count == 1) { continue; } Element donorPipe = bpg.BrokenPipes.FirstOrDefault(); foreach (pdef p in plist) { Parameter donorParameter = donorPipe.get_Parameter(p.Guid); if (donorParameter == null) { continue; } switch (donorParameter.StorageType) { case StorageType.None: continue; case StorageType.Integer: int donorInt = donorParameter.AsInteger(); if (donorInt == 0) { continue; } Parameter targetParInt = bpg.HealedPipe.get_Parameter(p.Guid); targetParInt.Set(donorInt); break; case StorageType.Double: continue; case StorageType.String: string donorStr = donorParameter.AsString(); if (donorStr.IsNullOrEmpty()) { continue; } Parameter targetParStr = bpg.HealedPipe.get_Parameter(p.Guid); targetParStr.Set(donorStr); break; case StorageType.ElementId: continue; default: continue; } } } tx.Commit(); } #endregion StringBuilder sbPipes = new PCF_Pipes.PCF_Pipes_Export().Export(gp.Key, pipeList, doc); StringBuilder sbFittings = new PCF_Fittings.PCF_Fittings_Export().Export(gp.Key, fittingList, doc); StringBuilder sbAccessories = new PCF_Accessories.PCF_Accessories_Export().Export(gp.Key, accessoryList, doc); sbCollect.Append(sbPipeline); sbCollect.Append(sbFilename); sbCollect.Append(sbEndsAndConnections); sbCollect.Append(sbPipes); sbCollect.Append(sbFittings); sbCollect.Append(sbAccessories); } #endregion txGp.RollBack(); //RollBack the temporary created elements } #region Materials StringBuilder sbMaterials = composer.MaterialsSection(materialGroups); sbCollect.Append(sbMaterials); #endregion #region Output // Output the processed data PCF_Output.Output output = new PCF_Output.Output(); output.OutputWriter(sbCollect); #endregion } catch (Autodesk.Revit.Exceptions.OperationCanceledException) { return(Result.Cancelled); } catch (Exception ex) { throw new Exception(ex.Message); } return(Result.Succeeded); }